code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def set_tag_names(self, tag_names, user): <NEW_LINE> <INDENT> if "mine" not in tag_names: <NEW_LINE> <INDENT> self.tagging_set.filter(user=user, value='mine').update(archived=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tag, created = self.tagging_set.get_or_create( value='mine', user=user ) <NEW_LINE> if not cr... | 1. Special case mine
2. Archive dangling tags not in our current list.
3. Add new tags.
4. Ensure that we're setting the parents of child tags
5. There is no step 6. | 625941f1460517430c39471a |
def hinton(X, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> X = X._convert(GaussianMoments) <NEW_LINE> <DEDENT> except Moments.NoConverterError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return gaussian_hinton(X, **kwargs) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> X = X._conver... | Plot the Hinton diagram of a node
The keyword arguments depend on the node type. For some node types, the
diagram also shows uncertainty with non-filled rectangles. Currently,
beta-like, Gaussian-like and Dirichlet-like nodes are supported.
Parameters
----------
X : node | 625941f199fddb7c1c9de933 |
def display_transfer (listA, listB): <NEW_LINE> <INDENT> print ("Source:", listA, " -> ", "Destination:", listB) | This is to display '<listA> -> <listB>' | 625941f191af0d3eaac9bfc3 |
def get_structures(self, primitive=True): <NEW_LINE> <INDENT> structures = [] <NEW_LINE> for d in self._cif.data.values(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> s = self._get_structure(d, primitive) <NEW_LINE> if s: <NEW_LINE> <INDENT> structures.append(s) <NEW_LINE> <DEDENT> <DEDENT> except (KeyError, ValueErro... | Return list of structures in CIF file. primitive boolean sets whether a
conventional cell structure or primitive cell structure is returned.
Args:
primitive (bool): Set to False to return conventional unit cells.
Defaults to True.
Returns:
List of Structures. | 625941f1796e427e537b0b70 |
def euclidean_error(x, y): <NEW_LINE> <INDENT> return numpy.mean(((x - y) ** 2).sum(axis=1)) | Computes the mean squared euclidean distance between vectors in x and y
:param x: matrix of size MxD
:param y: matrix of size MxD
:return: average distance | 625941f1f9cc0f698b140b9b |
def get_processing_postags(vocab_pos_tags=None): <NEW_LINE> <INDENT> def f(pos_tag): <NEW_LINE> <INDENT> if vocab_pos_tags is not None: <NEW_LINE> <INDENT> if pos_tag in vocab_pos_tags: <NEW_LINE> <INDENT> pos_tag = vocab_pos_tags[pos_tag] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("POSTAG",pos_tag) <NEW_LINE>... | Return lambda function that transform a pos tag (string) into id
Args:
vocab: dict[pos_tags] = idx
Returns:
f("NN") = (1)
= (pos_tag id) | 625941f1bd1bec0571d90bd4 |
def get_ip_address(self, interface): <NEW_LINE> <INDENT> intf = self.__get_interface(interface) <NEW_LINE> if intf["ip_address"] != "": <NEW_LINE> <INDENT> return intf["ip_address"].strip() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "" | Get the IP address for the given interface. | 625941f1a17c0f6771cbe5f4 |
def save_full_page_screenshot(self, filename) -> bool: <NEW_LINE> <INDENT> return self.get_full_page_screenshot_as_file(filename) | Saves a full document screenshot of the current window to a PNG image file. Returns
False if there is any IOError, else returns True. Use full paths in
your filename.
:Args:
- filename: The full path you wish to save your screenshot to. This
should end with a `.png` extension.
:Usage:
::
driver... | 625941f1de87d2750b86033e |
def addPageInfos(page): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> ss = input("pageinfo输入:") <NEW_LINE> args = ss.split(" ") <NEW_LINE> if ss == "e": <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> elif len(args) == 2: <NEW_LINE> <INDENT> SavePageInfo(page,args[0],args[1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <I... | 循环直到收到e | 625941f1d4950a0f3b08c8ec |
def __init__(self, base_attr, bitmask): <NEW_LINE> <INDENT> self.base_attr = base_attr <NEW_LINE> self.bitmask = bitmask | Create the descriptor. `base_attr` is the name of an integer attribute
that represents binary flags. `bitmask` is the binary value to toggle
on `base_attr`. | 625941f1a79ad161976cc6eb |
def validate_mobile(self, mobile): <NEW_LINE> <INDENT> if User.objects.filter(mobile=mobile).count(): <NEW_LINE> <INDENT> raise serializers.ValidationError('用户已经存在') <NEW_LINE> <DEDENT> if not re.match(MOBILE_REGEX, mobile): <NEW_LINE> <INDENT> raise serializers.ValidationError('手机号码非法') <NEW_LINE> <DEDENT> one_minute_... | 验证手机号码
:param mobile:
:return: | 625941f1b830903b967e9eaa |
def get_parent_children(self) -> Tuple[Optional[str], List[str]]: <NEW_LINE> <INDENT> parent = self.parent_id <NEW_LINE> children = self.engine.run_sql( SQL("SELECT image_hash FROM {}.get_images(%s,%s) WHERE parent_id = %s").format( Identifier(SPLITGRAPH_API_SCHEMA) ), (self.repository.namespace, self.repository.reposi... | Gets the parent and a list of children of a given image. | 625941f16aa9bd52df03734d |
def reduce(self, N=0, **kwargs): <NEW_LINE> <INDENT> from spectral import status <NEW_LINE> num = kwargs.get('num', None) <NEW_LINE> eigs = kwargs.get('eigs', None) <NEW_LINE> fraction = kwargs.get('fraction', None) <NEW_LINE> if num is not None: <NEW_LINE> <INDENT> return PrincipalComponents(self.eigenvalues[:num], se... | Reduces the number or principal components.
Keyword Arguments (one of the following must be specified):
`num` (integer):
Number of eigenvalues/eigenvectors to retain. The top `num`
eigenvalues will be retained.
`eigs` (list):
A list of indices of eigenvalues/eigenvectors to be reta... | 625941f1dc8b845886cb5adc |
def get_permission_model(): <NEW_LINE> <INDENT> return get_swapped_model(constants.RBAC_PERMISSION_MODEL_SETTING) | Returns the currently configured permission model | 625941f1377c676e9127274c |
def do_current(self, city): <NEW_LINE> <INDENT> for backend, current in self.do('get_current', city): <NEW_LINE> <INDENT> self.format(current) <NEW_LINE> <DEDENT> self.flush() | current CITY
Get current weather. | 625941f13d592f4c4ed1d603 |
def create_bcm_socket(channel: str) -> socket.socket: <NEW_LINE> <INDENT> s = socket.socket(PF_CAN, socket.SOCK_DGRAM, CAN_BCM) <NEW_LINE> s.connect((channel,)) <NEW_LINE> return s | create a broadcast manager socket and connect to the given interface | 625941f14e696a04525c99f3 |
def find_l75(contig_lengths_dict, genome_length_dict): <NEW_LINE> <INDENT> l75_dict = dict() <NEW_LINE> for file_name, contig_lengths in contig_lengths_dict.items(): <NEW_LINE> <INDENT> currentlength = 0 <NEW_LINE> currentcontig = 0 <NEW_LINE> for contig_length in contig_lengths: <NEW_LINE> <INDENT> currentlength += co... | Calculate the L50 for each strain. L75 is defined as the number of contigs required to achieve the N75
:param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths
:param genome_length_dict: dictionary of strain name: total genome length
:return: l50_dict: dictionary of strain name: ... | 625941f1c432627299f051f0 |
def get_serializer(self, *args, **kwargs): <NEW_LINE> <INDENT> action = kwargs.pop('action', None) <NEW_LINE> serializer_class = self.get_serializer_class(action) <NEW_LINE> kwargs['context'] = self.get_serializer_context() <NEW_LINE> return serializer_class(*args, **kwargs) | Returns the serializer instance that should be used to the
given action.
If any action was given, returns the serializer_class | 625941f1f9cc0f698b140b9c |
def _test_support(): <NEW_LINE> <INDENT> fd, makefile = mkstemp() <NEW_LINE> os.write(fd, JOBSERVER_SUPPORT_MAKEFILE) <NEW_LINE> os.close(fd) <NEW_LINE> ret = subprocess.call(['make', '-f', makefile, '-j2'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) <NEW_LINE> os.unlink(makefile) <NEW_LINE> return (ret == 0) | Test if the system 'make' supports the job server implementation. | 625941f18e05c05ec3eea91f |
def coerce(self, value): <NEW_LINE> <INDENT> if isinstance(value, (compat.long, int)): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> return int(value) | Convert text values into integer values.
Args:
value (str or int): The value to coerce.
Raises:
TypeError: If the value is not an int or string.
ValueError: If the value is not int or an acceptable value.
Returns:
int: The integer value represented. | 625941f110dbd63aa1bd3148 |
def zip_cmd(com_base_len, source, zipf, prtl=[]): <NEW_LINE> <INDENT> for path in source: <NEW_LINE> <INDENT> if os.path.isfile(path): <NEW_LINE> <INDENT> prtl.append(path) <NEW_LINE> zipf.write(path, path[com_base_len:]) <NEW_LINE> source.remove(path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for bases, dirs, file... | Zip command using zipfile module.
| 625941f17d43ff24873a324b |
def containsDuplicate(nums): <NEW_LINE> <INDENT> unique = set(nums) <NEW_LINE> return len(unique) != len(nums) | :type nums: List[int]
:rtype: bool | 625941f156ac1b37e6264769 |
def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'credit': 'int', 'id_quality': 'int', 'name': 'str' } <NEW_LINE> self.attribute_map = { 'credit': 'Credit', 'id_quality': 'IdQuality', 'name': 'Name' } <NEW_LINE> self._credit = None <NEW_LINE> self._id_quality = None <NEW_LINE> self._name = None | QualityReaderServiceModel - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | 625941f1d99f1b3c44c67b2a |
def get_inventory(url=URL, owner='ndlambo', pagelength=500): <NEW_LINE> <INDENT> inventory = [] <NEW_LINE> params = { 'length': pagelength, 'start': 0, } <NEW_LINE> while True: <NEW_LINE> <INDENT> resp = requests.get(url.format(owner=owner), params=params) <NEW_LINE> try: <NEW_LINE> <INDENT> j = resp.json() <NEW_LINE> ... | simple inventory json getter | 625941f1b5575c28eb68e5ab |
def test_create_constraint(self): <NEW_LINE> <INDENT> pass | Test case for create_constraint
| 625941f1a934411ee3751c3b |
def variableize(self, x: str, max_length: int=64) -> str: <NEW_LINE> <INDENT> VALID_CHARS = ascii_letters + digits + '_' <NEW_LINE> chars = '_' <NEW_LINE> if x and x[0] not in digits: chars = '' <NEW_LINE> replaced_spaces = x.replace(' ','_') <NEW_LINE> chars += ''.join([char for char in replaced_spaces if char in VALI... | Converts a user defined string into a valid variable format. | 625941f16fb2d068a760f64d |
def actor_gcn_critic_gcn_mean(test_num=5, max_episodes=5000, test_name="test", log_file=None): <NEW_LINE> <INDENT> log_dir = "confirm/step5_prior/a_gcn_c_gcn_results/{}".format(test_name) <NEW_LINE> assert not os.path.exists(log_dir), "already folder exists" <NEW_LINE> os.makedirs(log_dir, exist_ok=True) <NEW_LINE> his... | Actor-Criticの5回実験したときの平均グラフを作成する関数 | 625941f10c0af96317bb878d |
@requires_user_role([UserRole.Browse, UserRole.Annotate]) <NEW_LINE> def connector_associated_edgetimes(request, project_id=None): <NEW_LINE> <INDENT> connector_ids = get_request_list(request.POST, 'connector_ids', map_fn=int) <NEW_LINE> def default(obj): <NEW_LINE> <INDENT> import calendar, datetime <NEW_LINE> if isin... | See _connector_associated_edgetimes | 625941f1be7bc26dc91cdb9b |
def __init__(self, info): <NEW_LINE> <INDENT> pass | Constructor: info will be an object having the
following attributes: name (the renderer name), package
(the package that was 'current' at the time the
renderer was registered), type (the renderer type
name), registry (the current application registry) and
settings (the deployment settings dictionary). | 625941f1711fe17d82542904 |
def get_divergences(gold, testname, itera, size, pct): <NEW_LINE> <INDENT> model1 = '../measuredivergence/modeloutput/' + gold + '.pkl' <NEW_LINE> meta1 = '../measuredivergence/modeloutput/' + gold + '.csv' <NEW_LINE> testpath = '../measuredivergence/modeloutput/' + testname <NEW_LINE> model2 = testpath + '.pkl' <NEW_L... | This function gets several possible measures of divergence
between two models. | 625941f199cbb53fe679318a |
def setPilotHints (self, hints): <NEW_LINE> <INDENT> self._pilotHints = hints | NOT FOR USE BY PILOT !!! | 625941f1a4f1c619b28b05d1 |
def _with_metaclass(meta, *bases): <NEW_LINE> <INDENT> class metaclass(meta): <NEW_LINE> <INDENT> def __new__(cls, name, this_bases, d): <NEW_LINE> <INDENT> return meta(name, bases, d) <NEW_LINE> <DEDENT> <DEDENT> return type.__new__(metaclass, 'temporary_class', (), {}) | Create a base class with a metaclass. | 625941f192d797404e304733 |
def create_shell_script_solid( shell_script_path, name="create_shell_script_solid", input_defs=None, **kwargs ): <NEW_LINE> <INDENT> return core_create_shell_script( dagster_decorator=solid, decorator_name="solid", shell_script_path=shell_script_path, name=name, input_defs=input_defs, **kwargs, ) | This function is a factory which constructs a solid that will execute a shell command read
from a script file.
Any kwargs passed to this function will be passed along to the underlying :func:`@solid
<dagster.solid>` decorator. However, note that overriding ``config`` or ``output_defs`` is not
supported.
You might con... | 625941f1ab23a570cc25072e |
def silence_psychopy(): <NEW_LINE> <INDENT> with _suppress_stdout_stderr() as quiet: <NEW_LINE> <INDENT> from psychopy import visual, core, logging <NEW_LINE> <DEDENT> logging.console = logging.LogFile("./error-log.txt", filemode='a') | Import psychopy but ignores all kinds of error messages from modules
psychopy imports. It is a good idea to turn this function off if
you encounter errors. | 625941f132920d7e50b2877b |
def sleep_window(self): <NEW_LINE> <INDENT> log.error('Maximum requests exceeded, sleeping for {sleep}'.format( sleep=self.pretty_time(self.request_window) )) <NEW_LINE> if self.request_window > 0: <NEW_LINE> <INDENT> time.sleep(self.request_window) | Sleep for window. | 625941f126068e7796caf28e |
def save_to_json_file(my_obj, filename): <NEW_LINE> <INDENT> with open(filename, mode='w', encoding='utf-8') as f: <NEW_LINE> <INDENT> json.dump(my_obj, f) | Args:
my_obj (object): The first parameter.
filename (file): The second parameter.
Returns:
string: JSON string | 625941f1a8370b7717052e43 |
def __init__(self, file: str, line: int, message: str) -> None: <NEW_LINE> <INDENT> self.file = file <NEW_LINE> self.line = line <NEW_LINE> self.message = message | Constructor.
Args:
file: File error originated on.
line: Line error originated on.
message: Error message. | 625941f16aa9bd52df03734e |
def test_AnalyzeColon1(self): <NEW_LINE> <INDENT> self.delayDisplay("Starting the test") <NEW_LINE> import urllib <NEW_LINE> downloads = ( ('http://slicer.kitware.com/midas3/download?items=5767', 'FA.nrrd', slicer.util.loadVolume), ) <NEW_LINE> for url,name,loader in downloads: <NEW_LINE> <INDENT> filePath = slicer.app... | Ideally you should have several levels of tests. At the lowest level
tests should exercise the functionality of the logic with different inputs
(both valid and invalid). At higher levels your tests should emulate the
way the user would interact with your code and confirm that it still works
the way you intended.
One ... | 625941f1956e5f7376d71411 |
def setcontroller( self, aIndex ): <NEW_LINE> <INDENT> if self.controllernum != aIndex or self._controller == None: <NEW_LINE> <INDENT> self.controllernum = aIndex <NEW_LINE> self._initcontroller() | Set controller index if it changed, and create a controller. | 625941f1e1aae11d1e74a263 |
def cal_base(t): <NEW_LINE> <INDENT> if t.diff == 0.0: <NEW_LINE> <INDENT> return t.diff <NEW_LINE> <DEDENT> e = 2.718281828 <NEW_LINE> b = 2.1 <NEW_LINE> l1 = 0 <NEW_LINE> l2 = 0 <NEW_LINE> while (l1 >= 0 and l2 == 0) or (l1 == 0 and l2 <= 0): <NEW_LINE> <INDENT> cal = round((e**b) / (2 * t.sem1), 2) <NEW_LINE> temp =... | Calculate the base value for each node. | 625941f1a05bb46b383ecdc2 |
def isBandEnabled(self, band, outputConfig): <NEW_LINE> <INDENT> result = None <NEW_LINE> if band == outputConfig.GPS.L1: <NEW_LINE> <INDENT> result = self.isL1CAEnabled() <NEW_LINE> <DEDENT> elif band == outputConfig.GPS.L2: <NEW_LINE> <INDENT> result = self.isL2CEnabled() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>... | Checks if particular band is supported and enabled.
Parameters
----------
band : Band
Band description object.
outputConfig : object
Output configuration
Returns:
bool
True, if the band is supported and enabled; False otherwise. | 625941f1d10714528d600290 |
def _retransmit(self, message, timeout, retransmission_counter): <NEW_LINE> <INDENT> key = (message.remote, message.mid) <NEW_LINE> exchange_monitor, next_retransmission = self._active_exchanges.pop(key) <NEW_LINE> next_retransmission.cancel() <NEW_LINE> if retransmission_counter < MAX_RETRANSMIT: <NEW_LINE> <INDENT> s... | Retransmit CON message that has not been ACKed or RSTed. | 625941f144b2445a33932638 |
def __iter__(self): <NEW_LINE> <INDENT> arg_cutoff = len(self.args) - len(self.defaults) <NEW_LINE> for (i, name) in enumerate(self.args): <NEW_LINE> <INDENT> if i < arg_cutoff: <NEW_LINE> <INDENT> yield (name, Signature.ARGUMENT, None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield (name, Signature.ARGUMENT_WITH_... | Iterates over the arguments in this function signature in the
order they were specefied.
Each element is a triple (name, tp, d) where
- name is a string giving the name of the argument,
- tp is the type of the argument and is one of Signature.ARGUMENT,
Signature.ARGUMENT_WITH_DEFAULT, Signature.VARARG,
... | 625941f12c8b7c6e89b35d62 |
def parse(fn): <NEW_LINE> <INDENT> renpy.game.exception_info = 'While parsing ' + fn + '.' <NEW_LINE> try: <NEW_LINE> <INDENT> lines = list_logical_lines(fn) <NEW_LINE> nested = group_logical_lines(lines) <NEW_LINE> <DEDENT> except ParseError as e: <NEW_LINE> <INDENT> parse_errors.append(e.message) <NEW_LINE> return No... | Parses a Ren'Py script contained within the file with the given
filename. Returns a list of AST objects representing the
statements that were found at the top level of the file. | 625941f1be8e80087fb211de |
def build(self, projectName, projectURL, sourceURL, packagePath, outputPath): <NEW_LINE> <INDENT> intersphinxes = [] <NEW_LINE> for intersphinx in intersphinxURLs: <NEW_LINE> <INDENT> intersphinxes.append("--intersphinx") <NEW_LINE> intersphinxes.append(intersphinx) <NEW_LINE> <DEDENT> from pydoctor.templatewriter impo... | Call pydoctor's entry point with options which will generate HTML
documentation for the specified package's API.
@type projectName: C{str}
@param projectName: The name of the package for which to generate
documentation.
@type projectURL: C{str}
@param projectURL: The location (probably an HTTP URL) of the project... | 625941f1236d856c2ad44d89 |
def digit_subdirs(path): <NEW_LINE> <INDENT> for name in os.listdir(path): <NEW_LINE> <INDENT> spath = os.path.join(path, name) <NEW_LINE> if os.path.isdir(spath) and name.isdigit(): <NEW_LINE> <INDENT> yield name, spath | Return subdirectories of path which names are composed of digits | 625941f1b545ff76a89143bc |
def update(self): <NEW_LINE> <INDENT> if self.on_update: <NEW_LINE> <INDENT> self.execute() <NEW_LINE> <DEDENT> return tuple() | updater | 625941f1be8e80087fb211df |
def _report_hook(count, block_size, total_size): <NEW_LINE> <INDENT> progress_size = int(count * block_size) <NEW_LINE> percent = min(100, int(count * block_size * 100 / total_size)) <NEW_LINE> sys.stdout.write(f"\rDownloading {progress_size / (1024 * 1024)}" f"/{total_size / (1024 * 1024)} MB ({percent}%)") <NEW_LINE>... | Display a progress bar for ``urlretrieve`` | 625941f1a8ecb033257d3671 |
def onehot_training(): <NEW_LINE> <INDENT> labels_onehot = torch.zeros(self.train_batch_size, self.labels) <NEW_LINE> for i in range(self.train_batch_size): <NEW_LINE> <INDENT> labels_onehot[i][target[i]] = 1 <NEW_LINE> <DEDENT> return labels_onehot | # USE THIS ONLY FOR MSE Loss
Local method: This method performs onehot encoding for training labels
:return: encoded labels for the whole batch of data | 625941f1d6c5a102081445f6 |
def get_today_all(retry_count=3): <NEW_LINE> <INDENT> ct._write_head() <NEW_LINE> df = _parsing_dayprice_json(1, retry_count=retry_count) <NEW_LINE> if df is not None: <NEW_LINE> <INDENT> for i in range(2, ct.PAGE_NUM[0]): <NEW_LINE> <INDENT> newdf = _parsing_dayprice_json(i, retry_count=retry_count) <NEW_LINE> df = df... | 一次性获取最近一个日交易日所有股票的交易数据
return
-------
DataFrame
属性:代码,名称,涨跌幅,现价,开盘价,最高价,最低价,最日收盘价,成交量,换手率,成交额,市盈率,市净率,总市值,流通市值 | 625941f1377c676e9127274d |
def action_opciones(self): <NEW_LINE> <INDENT> if(self.crear_venta): <NEW_LINE> <INDENT> self.agregarVenta() <NEW_LINE> self.crear_venta = False <NEW_LINE> <DEDENT> self.pagos = NumeroPagos(self.id_pedido,self) <NEW_LINE> self.pagos.show() | Método que se llama cuando el usuario apreta en el boton 'mas opciones'.
Crea una instancia de NumeroPagos(). | 625941f173bcbd0ca4b2c61c |
def create_signature(*args, what_signer): <NEW_LINE> <INDENT> hsh = SHA.new(pickle.dumps(args)) <NEW_LINE> signer = PKCS1_v1_5.new(RSA.importKey(what_signer)) <NEW_LINE> signature = signer.sign(hsh) <NEW_LINE> return hsh, signature | Create signature from hashing args and signing what_signer
:param args: tuple
:param what_signer: str
:return: tuple | 625941f11d351010ab8560c1 |
def __init__(self, name, species, food, amount, notes = None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.species = species <NEW_LINE> self.food = food <NEW_LINE> self.amount = amount <NEW_LINE> self.notes = notes | Amount is a float, the others are strings. food is the type of food the Animal eats,
amount is the amount in kilograms of one meal. | 625941f176d4e153a657f0d9 |
def getVoltage(self, port): <NEW_LINE> <INDENT> response = self.getSensor(port) <NEW_LINE> voltage_value = response *VOLTAGE_FACTOR <NEW_LINE> return voltage_value | Read the value of the dial attached to a certain port. | 625941f107f4c71912b11a2b |
def extrair_numeros_cnpj(cnpj): <NEW_LINE> <INDENT> cnpj_formatado = re.sub(r'[^0-9]', '', cnpj) <NEW_LINE> return cnpj_formatado | Extrai os demais caracteres do cnpj, retornando apenas o números
:param cnpj: cnpj original
:type cnpj: str
:return: números do cnpj
:rtype: str | 625941f1a79ad161976cc6ec |
def waterfallCoarse(data): <NEW_LINE> <INDENT> plt.figure() <NEW_LINE> plt.figure(figsize=(10,10)) <NEW_LINE> plt.subplot(2,1,1) <NEW_LINE> xpol = [row[0] for table in data.CCPWRS for row in table] <NEW_LINE> imgX = np.array(xpol) <NEW_LINE> imgX = imgX.reshape(len(ccpwrs),512) <NEW_LINE> plt.imshow(imgX.astype(int), o... | Plots CCPWRS over time. Color indicates Power. | 625941f1851cf427c661aab0 |
def commit_and_branch(self): <NEW_LINE> <INDENT> self.wt.commit('adding a,b', rev_id='r1') <NEW_LINE> dir2 = self.wt.branch.bzrdir.sprout('b2', revision_id='r1') <NEW_LINE> wt2 = dir2.open_workingtree() <NEW_LINE> self.assertEqual(['r1'], wt2.get_parent_ids()) <NEW_LINE> self.assertEqual('r1', wt2.branch.last_revision(... | Commit the current tree, and create a second tree | 625941f18c3a873295158968 |
def conv_dec(bina): <NEW_LINE> <INDENT> num = 0 <NEW_LINE> bina = bina[::-1] <NEW_LINE> for i in range(len(bina)): <NEW_LINE> <INDENT> num += (2**int(i))*int(bina[i]) <NEW_LINE> <DEDENT> return num | Return n(int): numero decimal
la funcion convierte a decimal un numero binario
Parametros:
bn(str): numero binario | 625941f176e4537e8c351c1e |
def transform( self, store: Mapping[ states.StateSegment, Optional[betterproto.Message] ], events_log: alarms.Manager ) -> None: <NEW_LINE> <INDENT> power_management = typing.cast( mcu_pb.MCUPowerStatus, store[states.StateSegment.MCU_POWER_STATUS] ) <NEW_LINE> if power_management.charging: <NEW_LINE> <INDENT> self._tra... | Update the parameters for power management service | 625941f14e4d5625662d4976 |
def clean_dataframe(df, month): <NEW_LINE> <INDENT> df = df[(df['tpep_pickup_datetime'].dt.year == 2018) & (df['tpep_pickup_datetime'].dt.month == month)] <NEW_LINE> df = df[(df['total_amount'] > 0)] <NEW_LINE> return df | Clean the dataframe, removing wrong dates and wrong taxy's trips
input:
- dataframe
- month which correspond the dataframe
output:from scipy.stats import chi2_contingency, ttest_ind ,chisquare, kruskal, pearsonr
- cleaned dataframe | 625941f1cb5e8a47e48b8047 |
def _bind_nics(): <NEW_LINE> <INDENT> if not _NICS_PCI: <NEW_LINE> <INDENT> _LOGGER.info('NICs are not configured - nothing to bind') <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> _driver = 'igb_uio' <NEW_LINE> if 'vfio-pci' in S.getValue('TOOLS')['dpdk_modules']: <NEW_LINE> <INDENT> _driver = 'vfio-pc... | Bind NICs using the bind tool specified in the configuration.
| 625941f18da39b475bd65522 |
@click.command() <NEW_LINE> @click.pass_context <NEW_LINE> def build(context): <NEW_LINE> <INDENT> build_distributions(context.obj) | Attempts to build the sdist and wheel. | 625941f1baa26c4b54cb16c0 |
def post_chroot(step, echo, run, shell): <NEW_LINE> <INDENT> step('Post-installation step (shell in chroot)') <NEW_LINE> import pty <NEW_LINE> pty.spawn('bash') | Post-installation steps (run in chroot) | 625941f1f8510a7c17cf9ca8 |
def get_set_clause(self): <NEW_LINE> <INDENT> command_list = ["{0} = %({1})s".format(k, k) for k in sorted(self.minimized_record())] <NEW_LINE> return ", ".join(command_list) | returns a string using the objects state of the form:
" key = %(key)s,"
usable as a partial input to psycopg2. We sort the keys prior to
building the string to aid in testing | 625941f138b623060ff0b394 |
def anagram(string1, string2): <NEW_LINE> <INDENT> string1 = string1.lower() <NEW_LINE> string2 = string2.lower() <NEW_LINE> string = string1+string2 <NEW_LINE> new_long_string = "" <NEW_LINE> for i in string: <NEW_LINE> <INDENT> if i.isalpha(): <NEW_LINE> <INDENT> new_long_string += i <NEW_LINE> <DEDENT> <DEDENT> mark... | ##Comment out print functions if you submit on gradescope.
@string1: The first string
@string2: The second string
@return True if string1 is anagram of string2
False otherwise | 625941f1be383301e01b5a21 |
def pointerToUnconstrainedPublic(maxPointeeSize=0x10000, cannotPointSecret=False): <NEW_LINE> <INDENT> return AbstractPointerToUnconstrainedPublic(maxPointeeSize=maxPointeeSize, cannotPointSecret=cannotPointSecret) | A (public) pointer to unconstrained public data, which could be a public value,
an array (of unconstrained size) of public values, or a public data structure
maxPointeeSize: upper bound on the size of the value/array/struct being pointed to
cannotPointSecret: if True, we assert that this pointer _cannot_ point (dir... | 625941f156b00c62f0f14c04 |
def t_INTEGER(self,t): <NEW_LINE> <INDENT> t.value = (t.value, "int") <NEW_LINE> return t | \d+ | 625941f115fb5d323cde10bf |
def map(self): <NEW_LINE> <INDENT> with Pool(self.cpu_count) as pool: <NEW_LINE> <INDENT> pool.map(self._func, self._iterable) <NEW_LINE> pool.close() <NEW_LINE> <DEDENT> return True | Perform a function on every item in an iterable. | 625941f1ff9c53063f47c797 |
def reconstruction(img2, flow, coef1=1, coef2=1, coef3=1, name=None): <NEW_LINE> <INDENT> if coef1 is None: <NEW_LINE> <INDENT> coef1 = 1 <NEW_LINE> <DEDENT> coef1 = _execute.make_float(coef1, "coef1") <NEW_LINE> if coef2 is None: <NEW_LINE> <INDENT> coef2 = 1 <NEW_LINE> <DEDENT> coef2 = _execute.make_float(coef2, "coe... | Reconstructs the first image from the second image and the flow (1 -> 2).
Args:
img2: A `Tensor`. Must be one of the following types: `float32`, `float64`.
flow: A `Tensor`. Must have the same type as `img2`.
coef1: An optional `float`. Defaults to `1`.
coef2: An optional `float`. Defaults to `1`.
coef3: An ... | 625941f130dc7b7665901f06 |
def _get_chains(self): <NEW_LINE> <INDENT> chain_dict = dict() <NEW_LINE> for line in self.cont: <NEW_LINE> <INDENT> if line.startswith(('ATOM', 'HETATM', 'TER')): <NEW_LINE> <INDENT> if line[21:22] not in chain_dict: <NEW_LINE> <INDENT> chain_dict[line[21:22]] = [] <NEW_LINE> <DEDENT> chain_dict[line[21:22]].append(li... | Splits a PDB file into individual chains.
Returns a dictionary with the respective chains, where
the Chain IDs are the keys, and the lines of the chain
are the dictionary values as lists:
{'A':[chain A lines], 'B':[...], ...} | 625941f1a219f33f34628f08 |
def construct_encoder_decoder(in_size, enc_size, latent_size, hidden_size = 512, channels = 32, n_layers = 6, n_mlp = 2, type_ae = 'ae', type_mod='gated_cnn', args=None): <NEW_LINE> <INDENT> if (type_mod in ['mlp', 'gated_mlp']): <NEW_LINE> <INDENT> type_ed = (type_mod == 'mlp') and 'normal' or 'gated' <NEW_LINE> encod... | Construct encoder and decoder layers for AE models | 625941f1167d2b6e3121913c |
def __repr__(self): <NEW_LINE> <INDENT> return "<UserPark user_id = {} park_id = {} date = {}>".format(self.user_id, self.park_id, self.date_searched) | Provide helpful representation when printed | 625941f1ad47b63b2c50a527 |
def terminate_proc(): <NEW_LINE> <INDENT> proc.kill() | Kill child process.
All signals should be forwarded to the child processes
automatically, however child processes are also free to ignore
some of them. With this we make sure the child processes get
killed once dotenv exits. | 625941f163f4b57ef00016af |
def setMetadata(self, event, context): <NEW_LINE> <INDENT> self.event = event <NEW_LINE> self.context = context <NEW_LINE> granules = _get_granule_ids(event) <NEW_LINE> self._msg = dict((k, v) for k, v in { "asyncOperationId": _get_async_operation_id(event), "executions": _get_execution_name(event), "granules": json.du... | Sets metadata to be logged via one of the logging methods.
Extracts the following metadata from various locations within the
``event`` and ``context`` parameters (indicated within parentheses):
+ ``asyncOperationId`` (``event``): asynchronous operation ID of the
execution
+ ``executions`` (``event``): singleton lis... | 625941f1091ae356686674fc |
def is_orcid(val): <NEW_LINE> <INDENT> val = val.replace("-", "").replace(" ", "") <NEW_LINE> if is_isni(val): <NEW_LINE> <INDENT> val = int(val[:-1], 10) <NEW_LINE> return val >= 15000000 and val <= 35000000 <NEW_LINE> <DEDENT> return False | Test if argument is an ORCID ID
See http://support.orcid.org/knowledgebase/articles/116780-structure-of-the-orcid-identifier | 625941f1e8904600ed9f24de |
def parse_header(self, buffer): <NEW_LINE> <INDENT> if len(buffer) < 2: <NEW_LINE> <INDENT> raise IncompleteFrame <NEW_LINE> <DEDENT> self.fin = True if buffer[0] & 0b10000000 else False <NEW_LINE> self.opcode = buffer[0] & 0b00001111 <NEW_LINE> self.masked = True if buffer[1] & 0b10000000 else False <NEW_LINE> self.rs... | byte 1 consists of
- fin (Last Frame)
- rsv1, rsv2, rsv3 (Reserved bits)
- Opcode (Operation code) | 625941f1460517430c39471c |
def bfs_solve(self, problem): <NEW_LINE> <INDENT> step = 0 <NEW_LINE> node = Node(None, problem.initial_state, None) <NEW_LINE> if problem.goal_test(node.state): <NEW_LINE> <INDENT> return self.solution(node) <NEW_LINE> <DEDENT> frontier = Queue() <NEW_LINE> frontier.appendleft(node) <NEW_LINE> explored = [] <NEW_LINE>... | Search for a goal with bfs algorithm | 625941f1a934411ee3751c3c |
def split_book(book,n): <NEW_LINE> <INDENT> print(book.get_chapter(n=1).title()) <NEW_LINE> print(book.tot_pages()) <NEW_LINE> print("Creating front matter") <NEW_LINE> book.sub_pdf(2,book.volume_first_page(1,n)-1,"front.pdf") <NEW_LINE> for v in range(1,n+1): <NEW_LINE> <INDENT> pI=book.volume_first_page(v,n) <NEW_LIN... | Split the book in 'v' volumes
@param book (type Book)
@param n (integer) the number of volumes
The 'book' parameter has to contain the pdf filename. | 625941f199fddb7c1c9de935 |
def get_logical_routers(self, tier=None): <NEW_LINE> <INDENT> lrouters = self.get_resource_by_type('LogicalRouter') <NEW_LINE> if tier: <NEW_LINE> <INDENT> lrouters = [router for router in lrouters if router['router_type'] == tier] <NEW_LINE> <DEDENT> return lrouters | Retrieve all the logical routers based on router type. If tier
is None, it will return all logical routers. | 625941f1b57a9660fec33e34 |
def personPhoto(self): <NEW_LINE> <INDENT> return QUrl() | static QUrl Soprano.Vocabulary.Xesam.personPhoto() | 625941f18a43f66fc4b54606 |
def var_max_pool(inputs, ksize, strides, padding, seq_length, is_clip_output_size=False): <NEW_LINE> <INDENT> h = tf.nn.max_pool(value=inputs, ksize=ksize, strides=strides, padding=padding) <NEW_LINE> s = strides[1] <NEW_LINE> seq_len1 = seq_length <NEW_LINE> if padding == 'VALID': <NEW_LINE> <INDENT> k = ksize[1] <NEW... | max pool for variable length sequence input,
if padding == 'SAME', please make sure all the element in inputs >= 0
:param inputs: A Tensor, [batch_size, max_time, dim, channel].
:param ksize: A 1-D int Tensor of 4 elements.
:param strides: A 1-D int Tensor of 4 elements.
:param padding: A string, either 'VALID' or 'SAM... | 625941f1f9cc0f698b140b9d |
def get_details_of_generation_levels(self, level_name): <NEW_LINE> <INDENT> list_details_level = [] <NEW_LINE> for level in self.root.findall("./Generation/Level/[@name='" + level_name + "']"): <NEW_LINE> <INDENT> bottom_limit = level.find('BottomLimit').text <NEW_LINE> top_limit = level.find('TopLimit').text <NEW_LINE... | Return list_details_level.
string level_name --> ('Easy') level name entry required to filter the XML file.
list list_details_level --> ['Easy',30,10,'Active'] details of specific level; name, bottom, top limit and status value of an especific level. | 625941f192d797404e304734 |
@log_call(namespace=__xmlrpc_namespace__) <NEW_LINE> @permission_required("testcases.delete_testcasetag", raise_exception=True) <NEW_LINE> def remove_tag(request, case_ids, tags): <NEW_LINE> <INDENT> cases = TestCase.objects.filter(case_id__in=pre_process_ids(value=case_ids)) <NEW_LINE> tags = TestTag.objects.filter(na... | Remove a tag from a case.
:param case_ids: give one or more case IDs. It could be an integer, a
string containing comma separated IDs, or a list of int each of them is
a case ID.
:type case_ids: int, str or list
:param tags: tag name or a list of tag names to remove.
:type tags: str or list
:return: a list whi... | 625941f115fb5d323cde10c0 |
def bags_of_words(file): <NEW_LINE> <INDENT> tweet_wakata = [] <NEW_LINE> f = open(file) <NEW_LINE> line = f.readline() <NEW_LINE> while line: <NEW_LINE> <INDENT> wakati = [] <NEW_LINE> parse_line = tagger.parse(line) <NEW_LINE> for nodes in parse_line.split('\n'): <NEW_LINE> <INDENT> node = nodes.split('\t') <NEW_LINE... | 各ツイートを品詞分解した2次元配列を返します
@param
file ... 1行が1ツイートの文章
@return
各ツイート文章の単語の2次元配列
[
["WBC", "バット", "甲子園"]
["WBC", "バット", "甲子園"]
["WBC", "バット", "甲子園"]
] | 625941f1de87d2750b860340 |
def LoginWithCustomID(request, callback, customData = None, extraHeaders = None): <NEW_LINE> <INDENT> request["TitleId"] = PlayFabSettings.TitleId or request.TitleId <NEW_LINE> if not request["TitleId"]: <NEW_LINE> <INDENT> raise PlayFabErrors.PlayFabException("Must be have TitleId set to call this method") <NEW_LINE> ... | Signs the user in using a custom unique identifier generated by the title, returning a session identifier that can
subsequently be used for API calls which require an authenticated user
https://docs.microsoft.com/rest/api/playfab/client/authentication/loginwithcustomid | 625941f150812a4eaa59c8c2 |
def __init__(self): <NEW_LINE> <INDENT> self.dictMessage = {} | Initialize your data structure here. | 625941f18da39b475bd65523 |
def fit_transform(self, X, y, weight=None): <NEW_LINE> <INDENT> X, y, weight = check_arrays(X, y, weight, sparse_format='dense') <NEW_LINE> y = as_float_array(y) <NEW_LINE> self._check_fit_data(X, y, weight) <NEW_LINE> order = np.lexsort((y, X)) <NEW_LINE> order_inv = np.argsort(order) <NEW_LINE> self.X_ = as_float_arr... | Fit model and transform y by linear interpolation.
Parameters
----------
X: array-like, shape=(n_samples,)
training data
y: array-like, shape=(n_samples,)
training target
weight: array-like, shape=(n_samples,), optional, default: None
weights. If set to None, all weights will be equal to 1 (equal
wei... | 625941f1a4f1c619b28b05d2 |
def __init__(self, dist_cls, name=None, dist_value_type=None, loss_fn=sge.score_function, **dist_args): <NEW_LINE> <INDENT> if not issubclass(dist_cls, distributions.Distribution): <NEW_LINE> <INDENT> raise TypeError("dist_cls must be a subclass of Distribution") <NEW_LINE> <DEDENT> self._dist_cls = dist_cls <NEW_LINE>... | Construct a `StochasticTensor`.
`StochasticTensor` will instantiate a distribution from `dist_cls` and
`dist_args` and its `value` method will return the same value each time
it is called. What `value` is returned is controlled by the
`dist_value_type` (defaults to `SampleAndReshapeValue`).
Some distributions' sample... | 625941f16e29344779a62bb8 |
def idCiudad(nombre): <NEW_LINE> <INDENT> cont = 0 <NEW_LINE> for i in piss.listMunicipios: <NEW_LINE> <INDENT> if i[0] == nombre: <NEW_LINE> <INDENT> return cont <NEW_LINE> <DEDENT> cont += 1 | Dado el nombre de una ciudad devuelve su id correspondiente en la lista. | 625941f1099cdd3c635f11ff |
def chunkTargetWriteSpecs(target, outDir, conf): <NEW_LINE> <INDENT> specDir = abspath(join(outDir, "chunks", basename(target))) <NEW_LINE> if not isdir(specDir): <NEW_LINE> <INDENT> os.makedirs(specDir) <NEW_LINE> <DEDENT> logging.info("Partitioning target %s to %s" % (target, specDir)) <NEW_LINE> twoBitFname, specFna... | create spec files for target,
returns twoBitFilename, oocFilename, sizeFname, list of spec filenames | 625941f194891a1f4081c053 |
def __init__(self, data_dir: str = None): <NEW_LINE> <INDENT> if data_dir is None: <NEW_LINE> <INDENT> data_dir = os.path.join(tempfile.gettempdir(), 'inferlo_experiments') <NEW_LINE> <DEDENT> self.data_dir = os.path.expanduser(data_dir) <NEW_LINE> if not os.path.exists(self.data_dir): <NEW_LINE> <INDENT> os.makedirs(s... | :param data_dir: Where to store cached results. | 625941f1236d856c2ad44d8a |
def normalize_ret(self, ret): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for item, descr in ret.items(): <NEW_LINE> <INDENT> result[item] = { "__run_num__": descr["__run_num__"], "comment": descr["comment"], "result": descr["result"], "changes": descr["changes"] != {}, } <NEW_LINE> <DEDENT> return result | Normalize the return to the format that we'll use for result checking | 625941f115baa723493c4522 |
def get_connected_hosts(): <NEW_LINE> <INDENT> hosts_info = get_env_hosts_info() <NEW_LINE> my_group = [] <NEW_LINE> for item in hosts_info: <NEW_LINE> <INDENT> ip = item.get('ip', '') <NEW_LINE> if is_out_server: <NEW_LINE> <INDENT> if ip == '176.122.147.85': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW... | 连接所有主机, 并返回连接结果list
:return: a list eg: [<连接对象>, ...] | 625941f160cbc95b062c6aeb |
def remove(self, indices): <NEW_LINE> <INDENT> indices = asarrayi(indices) <NEW_LINE> if self.shape[0] >= self.shape[1]: <NEW_LINE> <INDENT> rindices = delete(_a.arangei(self.shape[0]), indices) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rindices = delete(_a.arangei(self.shape[1]), indices) <NEW_LINE> <DEDENT> retur... | Return a new sparse CSR matrix with all the indices removed
Parameters
----------
indices : array_like
the indices of the rows *and* columns that are removed in the sparse pattern | 625941f1a79ad161976cc6ed |
def _check_file_length(self, file_object, trusted_file_length): <NEW_LINE> <INDENT> file_object.seek(0, 2) <NEW_LINE> observed_length = file_object.tell() <NEW_LINE> if observed_length != trusted_file_length: <NEW_LINE> <INDENT> raise tuf.exceptions.DownloadLengthMismatchError(trusted_file_length, observed_length) <NEW... | <Purpose>
Non-public method that ensures the length of 'file_object' is strictly
equal to 'trusted_file_length'. This is a deliberately redundant
implementation designed to complement
tuf.download._check_downloaded_length().
<Arguments>
file_object:
A file object.
trusted_file_length:
A non-negat... | 625941f1004d5f362079a8d6 |
def test_session_retry(): <NEW_LINE> <INDENT> concourse_sessions.Client = MockSession <NEW_LINE> LDAPTokenProvider.get_token = MagicMock(side_effect=mock_get_token) <NEW_LINE> token_provider = LDAPTokenProvider(DiskTokenCache("NEVER_USED")) <NEW_LINE> my_session = concourse_sessions.ConcourseSession( "NEVER_USED", toke... | Check that the session will attempt to get a new token if the first one fails | 625941f10383005118ecfb88 |
def __init__(self, interactive=False, select_first=False, debug=False, cache=True, episodes=True, banners=False, actors=False, custom_ui=None, language=None, search_all_languages=False, apikey=None, force_connect=False, use_zip=False, dvdorder=False, proxy=None, session=None, image_type=None): <NEW_LINE> <INDENT> self.... | Pass these arguments on as args from the subclass. | 625941f101c39578d7e753e3 |
def SetFixedImage(self, *args): <NEW_LINE> <INDENT> return _itkPDEDeformableRegistrationFunctionPython.itkPDEDeformableRegistrationFunctionIF2IF2IVF22_SetFixedImage(self, *args) | SetFixedImage(self, itkImageF2 ptr) | 625941f1c432627299f051f2 |
@pytest.mark.parametrize(["op", "state", "pairs", "probabilities"], [ pytest.param(sigmaz(), basis(2, 0), SIGMAZ, [0, 1], id="sigmaz_ket"), pytest.param(sigmaz(), ket2dm(basis(2, 0)), SIGMAZ, [0, 1], id="sigmaz_dm"), pytest.param(sigmax(), basis(2, 0), SIGMAX, [0.5, 0.5], id="sigmax_ket"), pytest.param(sigmax(), ket2dm... | measurement_statistics_observable: observables on basis states. | 625941f13d592f4c4ed1d605 |
def junk_mesh(): <NEW_LINE> <INDENT> junk_mesh = bpy.data.meshes.get("Bricker_junk_mesh") <NEW_LINE> if junk_mesh is None: <NEW_LINE> <INDENT> junk_mesh = bpy.data.meshes.new("Bricker_junk_mesh") <NEW_LINE> <DEDENT> return junk_mesh | returns junk mesh (only creates one if necessary) | 625941f17d43ff24873a324d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.