code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
@templatekeyword("file_adds") <NEW_LINE> def showfileadds(**args): <NEW_LINE> <INDENT> args = args <NEW_LINE> repo, ctx, revcache = args["repo"], args["ctx"], args["revcache"] <NEW_LINE> return showlist("file_add", getfiles(repo, ctx, revcache)[1], args, element="file") | List of strings. Files added by this changeset. | 625941e33539df3088e2e720 |
def setup(i2c_dev=None, i2c_address=0x74): <NEW_LINE> <INDENT> global display <NEW_LINE> if display is not None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> display = is31fl3731.IS31FL3731( i2c=i2c_dev, address=i2c_address) <NEW_LINE> enable_pattern = [ 0b01111111, 0b01111111, 0b01111111, 0b01111111, 0b01111111, 0b0... | Set up Scroll pHAT HD.
:param i2c_dev: smbus-compatible i2c object
:param i2c_address: 7-bit i2c address | 625941e34d74a7450ccd4599 |
def PUtilXPolDivide (inUV, outUV, err): <NEW_LINE> <INDENT> if inUV.myClass=='AIPSUVData': <NEW_LINE> <INDENT> raise TypeError("Function unavailable for "+inUV.myClass) <NEW_LINE> <DEDENT> if not inUV.UVIsA(): <NEW_LINE> <INDENT> raise TypeError("inUV MUST be a Python Obit UV") <NEW_LINE> <DEDENT> if not outUV.UVIsA():... | Divides cross hand visibilites Stokes I (avg. parallel hand)
outUV = Output Python UV object,
inUV = Input Python UV object,
outUV = Output python UV object
err = Python Obit Error/message stack | 625941e37d847024c06be695 |
def get_bip32_address(self, ecdh=False): <NEW_LINE> <INDENT> index = struct.pack('<L', self.identity_dict.get('index', 0)) <NEW_LINE> addr = index + identity_to_string(self.identity_dict).encode('ascii') <NEW_LINE> log.debug('bip32 address string: %r', addr) <NEW_LINE> digest = hashlib.sha256(addr).digest() <NEW_LINE> ... | Compute BIP32 derivation address according to SLIP-0013/0017. | 625941e360cbc95b062c6919 |
def _array_del(self, idx): <NEW_LINE> <INDENT> last = self.a_size - 1 <NEW_LINE> if idx != last: <NEW_LINE> <INDENT> self.array[idx] = self.array[last] <NEW_LINE> self.table[self.array[idx]] = idx <NEW_LINE> <DEDENT> self.a_size -= 1 | Remove specific index from table | 625941e30a366e3fb873ebf3 |
def filterByNbUsed(self, minsearch, maxsearch=9999): <NEW_LINE> <INDENT> result = Packages() <NEW_LINE> for o in self.mylist: <NEW_LINE> <INDENT> if o.nbused >= minsearch and o.nbused <= maxsearch: <NEW_LINE> <INDENT> result.append(o) <NEW_LINE> <DEDENT> <DEDENT> return result | Filter packages by nbused (range) | 625941e39b70327d1c4e11ac |
def get_changes(self, checkpoint='', include_purged=False) -> 'Generator[ChangeSet]': <NEW_LINE> <INDENT> logger.info('Getting changes with checkpoint "%s".' % checkpoint) <NEW_LINE> body = {} <NEW_LINE> if checkpoint: <NEW_LINE> <INDENT> body['checkpoint'] = checkpoint <NEW_LINE> <DEDENT> if include_purged: <NEW_LINE>... | Generates a ChangeSets for each checkpoint in changes response
https://developer.amazon.com/public/apis/experience/cloud-drive/content/changes | 625941e3aad79263cf390e1c |
def test_ankicoverter_donttouchmultiplemath(self): <NEW_LINE> <INDENT> expected = "te\_xt$$important_math^with*syntax$$te\*xt$important_math^with*syntax$te\^xt" <NEW_LINE> result = ankiToMarkDown("te_xt[$$]important_math^with*syntax[/$$]te*xt[$]important_math^with*syntax[/$]te^xt") <NEW_LINE> self.assertEquals(result,e... | Tests that multiple [$$] or [$] content does not get escaped or converted | 625941e323849d37ff7b3462 |
def _response_to_dataframe(response, request_url): <NEW_LINE> <INDENT> resp_dict = response.json() <NEW_LINE> if 'objects' in resp_dict: <NEW_LINE> <INDENT> rows = resp_dict['objects'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rows = [resp_dict] <NEW_LINE> <DEDENT> df = DataFrame(rows) <NEW_LINE> for col in df.colu... | Converts a ``requests`` json response to a ``pandas`` DataFrame | 625941e3656771135c3ebc48 |
def archetype_length_in_symbols(self) -> int: <NEW_LINE> <INDENT> return int(sum([g.totalsymbols() for g in self.clone_groups]) / len(self.clone_groups[0].instances)) | :return: Count of symbols in archetype, regardless to groups' power. | 625941e39c8ee82313fbbb4b |
def minDistance(self, word1, word2): <NEW_LINE> <INDENT> l1 = len(word1) <NEW_LINE> l2 = len(word2) <NEW_LINE> DP = [ [0] * (l1 + 1) for i in xrange(l2 + 1) ] <NEW_LINE> for i in xrange(1, l1 + 1): <NEW_LINE> <INDENT> DP[0][i] = i <NEW_LINE> <DEDENT> for j in xrange(1, l2 + 1): <NEW_LINE> <INDENT> DP[j][0] = j <NEW_LIN... | :type word1: str
:type word2: str
:rtype: int | 625941e34f88993c3716c439 |
def sutoggle(self, root_sudo): <NEW_LINE> <INDENT> root_entry.set_sensitive(True) | Choose sudo over pkexec | 625941e3ad47b63b2c50a354 |
def visitSelectExpressionElement(self, ctx: MySqlParser.SelectExpressionElementContext) -> SQLToken: <NEW_LINE> <INDENT> name = self.visit(ctx.expression()) <NEW_LINE> alis = ctx.ID() <NEW_LINE> return SQLToken(AS, (name, CONST(alis.getText()))) if alis else name | expression (AS? ID)? | 625941e3293b9510aa2c3667 |
def get_batch_size(name): <NEW_LINE> <INDENT> if FLAGS.batch_size is not None: <NEW_LINE> <INDENT> return FLAGS.batch_size <NEW_LINE> <DEDENT> elif 'upsampler' in name: <NEW_LINE> <INDENT> return 5 <NEW_LINE> <DEDENT> return 20 | Gets optimal batch-size based on model. | 625941e33617ad0b5ed682cc |
def _validateFilename(self, filePath): <NEW_LINE> <INDENT> raise NotImplementedError | Function that changes per file type for validating its filename
Expects an assertion error.
Args:
filePath: Path to file | 625941e3eab8aa0e5d26df2f |
def move(distance, fill='black', width=1.0): <NEW_LINE> <INDENT> global pen, xpos, ypos <NEW_LINE> rad = angle * 2 * 3.14 / 360 <NEW_LINE> x = xpos + distance * math.cos(rad) <NEW_LINE> y = ypos + distance * math.sin(rad) <NEW_LINE> if pen: <NEW_LINE> <INDENT> line_to(x, y, fill=fill, width=width) <NEW_LINE> <DEDENT> x... | Moves the turtle the specified distance forward.
If the pen is down, it will draw while it moves with the specified fill color and pen width. | 625941e3be383301e01b5854 |
def p_selector_group(self, p): <NEW_LINE> <INDENT> self.selectors.append(p[1]) <NEW_LINE> p[0] = reduce(lambda x, y: x+y, p[1:]) <NEW_LINE> logging.debug('FOUND SELECTOR GROUP: {0}'.format(p[0])) | selector_group : selector ',' selector_group
| selector | 625941e3bf627c535bc135a5 |
def __init__(self, n_nodes, C_pp, C_p, C, reduction_p, reduction): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.reduction = reduction <NEW_LINE> self.n_nodes = n_nodes <NEW_LINE> if reduction_p: <NEW_LINE> <INDENT> self.preproc0 = ops.FactorizedReduce(C_pp, C, affine=False) <NEW_LINE> <DEDENT> else: <NEW_LINE... | Args:
n_nodes: # of intermediate n_nodes
C_pp: C_out[k-2]
C_p : C_out[k-1]
C : C_in[k] (current)
reduction_p: flag for whether the previous cell is reduction cell or not
reduction: flag for whether the current cell is reduction cell or not | 625941e307f4c71912b1185a |
def LoadArray(self, path): <NEW_LINE> <INDENT> lines = [] <NEW_LINE> with open(path, 'r', encoding='utf-8') as ship: <NEW_LINE> <INDENT> for line in ship: <NEW_LINE> <INDENT> lines.append(line.rstrip('\n')) <NEW_LINE> <DEDENT> <DEDENT> self.lines = lines <NEW_LINE> ship_array = np.chararray((len(lines), len(lines[0])),... | Laods the ship file into both lines array and char array | 625941e3e76e3b2f99f3abdc |
def get_tosid(self): <NEW_LINE> <INDENT> return self.options['tosid'] | Use this parameter to specify the TOS ID of this vserver. Applicable only when the LB mode is TOS.
Default value: 0
Minimum value = 1
Maximum value = 63 | 625941e31f5feb6acb0c4f1f |
def set_cwd(self, cwd=None): <NEW_LINE> <INDENT> if cwd is not None: <NEW_LINE> <INDENT> self.cwd = cwd | Set our cwd | 625941e33cc13d1c6d3c774e |
def get_event(self, event_id): <NEW_LINE> <INDENT> return json.loads(self.__makeRequest('/api/v1/applications/me/events/' + repr(event_id), 'GET')) | Get Fomo Event
@:param event_id: Fomo Event ID
:return: :class:`FomoEvent <FomoEvent>` object
:rtype: FomoEvent | 625941e3d4950a0f3b08c71f |
def check_config(config, parameters, defaults): <NEW_LINE> <INDENT> return config_module.validate(config, parameters['required'], parameters['optional'], defaults) | Asserts that all of the types in config match the types in the description strings in parameters. In addition,
missing optional keys are added to the config from defaults.
Args:
config (dict): A dictionary to check. Should contain all keys from parameters['required']. Each key's value
must be of the same t... | 625941e3ac7a0e7691ed449b |
def send_file(self, channel: str, content: str, file: str, tts: bool = False): <NEW_LINE> <INDENT> raise NotImplemented | :param channel:
:param content:
:param file:
:param tts:
:return: | 625941e3851cf427c661a8e2 |
def get_samples(sentence, sample_count): <NEW_LINE> <INDENT> sampleMap = Counter() <NEW_LINE> samples = [] <NEW_LINE> initSample = generateInitSamples(sentence) <NEW_LINE> previousSample = initSample <NEW_LINE> for i in range(1, Constants.gibbs_max_iteration): <NEW_LINE> <INDENT> modifiedSample = previousSample <NEW_LI... | Gibbs sampler
1. Generate initial samples, i.e. Assign the sentence random Parts of Speech [uniform or random or EM, not sure]
1.1 Optional Burn-in or thinning?, throw away few samples. [TO-DO]
Repeat sample_count times
2. Pick the last sample, x[t] <- x[t-1]
3. Repeat the following steps for all unobserved/non... | 625941e37b180e01f3dc4bcc |
def check_parameter_presence(self): <NEW_LINE> <INDENT> return len(self._values) == len(self._details) | Check so the number of installed parameters are equal to
the number of available ones
:returns: ``True`` if they're up to date, ``False`` otherwise | 625941e3e5267d203edce06e |
def validate_boolean(var: Any) -> bool: <NEW_LINE> <INDENT> assert isinstance(var, bool), "Argument must be True/False" <NEW_LINE> return var | Evaluates whether an argument is boolean True/False
Args:
var: the input argument to validate
Returns:
var: the value if it passes validation
Raises:
AssertionError: `var` was not boolean | 625941e3507cdc57c63070b9 |
def weighted_jaccard_index(a, b): <NEW_LINE> <INDENT> min_ = pd.DataFrame({'a': a, 'b': b}).fillna(0).apply(min, axis=1) <NEW_LINE> numerator = min_.sum() <NEW_LINE> max_ = pd.DataFrame({'a': a, 'b': b}).fillna(0).apply(max, axis=1) <NEW_LINE> denominator = max_.sum() <NEW_LINE> return numerator / denominator | For each key k, we take min(a[k], b[k]), and sum those up. That's the numerator. The denominator is the same except is uses max instead of min. | 625941e3167d2b6e31218f6b |
def get_end_date(start_date)->datetime.date: <NEW_LINE> <INDENT> date_str = input("Enter end day of analysis(format- YYYY-MM-DD): ") <NEW_LINE> try: <NEW_LINE> <INDENT> date = datetime.datetime.strptime(date_str, "%Y-%m-%d").date() <NEW_LINE> if date > datetime.date.today(): <NEW_LINE> <INDENT> print('End date cannot b... | asks the user to enter end date | 625941e363f4b57ef00014e4 |
def p_statement(p): <NEW_LINE> <INDENT> p[0] = p[1] | statement : assignement
| printing | 625941e3e64d504609d74c16 |
def gaussian(omega, cent, delta): <NEW_LINE> <INDENT> return numpy.sqrt(numpy.log(2.0)/numpy.pi) *numpy.exp(-numpy.log(2.0)*((omega-cent)/delta)**2) /delta | Normalized Gaussian line shape
| 625941e3460517430c394552 |
def init_base_logger( self, logger_name = 'base_logger' ): <NEW_LINE> <INDENT> loglevel = logging.WARNING <NEW_LINE> logformat = '%(levelname)s: %(message)s' <NEW_LINE> if self.verbose == 1: <NEW_LINE> <INDENT> loglevel = logging.INFO <NEW_LINE> <DEDENT> elif self.verbose > 1: <NEW_LINE> <INDENT> loglevel = logging.DEB... | Initializes a logger object and returns it, maybe overwritten.
@param logger_name: The name of the logging object
@type logger_name: str
@return: logger object
@rtype: logging.Logger | 625941e3627d3e7fe0d69227 |
def sw_reset(self): <NEW_LINE> <INDENT> self.write8(_STATUS_BASE, _STATUS_SWRST, 0xFF) <NEW_LINE> time.sleep(.500) <NEW_LINE> chip_id = self.read8(_STATUS_BASE, _STATUS_HW_ID) <NEW_LINE> if chip_id != _HW_ID_CODE: <NEW_LINE> <INDENT> raise RuntimeError("Seesaw hardware ID returned (0x{:x}) is not " "correct! Expected 0... | Trigger a software reset of the SeeSaw chip | 625941e34428ac0f6e5babcb |
def layer_fn(long_input, global_input): <NEW_LINE> <INDENT> long_output = long_input <NEW_LINE> global_output = global_input <NEW_LINE> long_output, global_output = self.fused_att_layers[index]( [long_output, global_output], l2l_att_mask=l2l_att_mask, g2g_att_mask=g2g_att_mask, l2g_att_mask=l2g_att_mask, g2l_att_mask=g... | A function for an entire layer. | 625941e376e4537e8c351a4b |
@test_requirements.customer_stories <NEW_LINE> @pytest.mark.meta(automates=[1729341, 1743266]) <NEW_LINE> def test_generic_object_with_service_button(appliance, generic_object, button_with_dialog): <NEW_LINE> <INDENT> myservice = MyService(appliance, name=generic_object.associations.get("services")[0].name) <NEW_LINE> ... | Bugzilla:
1729341
1743266
Polarion:
assignee: jdupuy
initialEstimate: 1/6h
caseimportance: high
caseposneg: positive
testtype: functional
startsin: 5.10
casecomponent: GenericObjects | 625941e3b57a9660fec33c60 |
@grad_test((3, 4)) <NEW_LINE> def test_tuple(x, y): <NEW_LINE> <INDENT> return (x + y, x - y, x * y, x / y) | Test multiple outputs. | 625941e36e29344779a629e6 |
def getusername(prompt): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> value = input(prompt) <NEW_LINE> if(len(value)==0): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if(checkusername(value)): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Inv... | Gets a username. Returns the empty string if enter was pressed without any other input.
:param prompt:
:return: | 625941e332920d7e50b285aa |
def render( self, alt_template: str = "alt.html", additional_alt_template_context=None, alt_template_context_replace=False ): <NEW_LINE> <INDENT> if self.vf_error is not None: <NEW_LINE> <INDENT> return Response(self.vf_error, status=400, media_type='text/plain') <NEW_LINE> <DEDENT> elif self.profile == 'alt' or self.p... | Use the received profile and mediatype to create a response back to the client.
TODO: Ashley, are you able to update this description with your new changes please?
What is the method for rendering other profiles now? - Edmond
This is an abstract method.
.. note:: The :class:`pyldapi.Renderer.render` requires you to ... | 625941e38e05c05ec3eea74e |
def _FetchStoredAnomalies(test, revisions): <NEW_LINE> <INDENT> stored_anomalies, _, _ = anomaly.Anomaly.QueryAsync( test=test.key).get_result() <NEW_LINE> stored_anomaly_dicts = [] <NEW_LINE> for a in stored_anomalies: <NEW_LINE> <INDENT> if a.end_revision > revisions[0]: <NEW_LINE> <INDENT> stored_anomaly_dicts.appen... | Makes a list of data about Anomaly entities for a Test. | 625941e385dfad0860c3b232 |
def largest_prime_factor(number): <NEW_LINE> <INDENT> factors = prime_factors(number) <NEW_LINE> return factors[len(factors) - 1] | Finds the largest prime factor of a number. | 625941e35f7d997b87174e71 |
def __init__(self, *, pattern: Graph, replacement: Graph) -> None: <NEW_LINE> <INDENT> self.pattern = pattern <NEW_LINE> self.replacement = replacement | Constructor. | 625941e3507cdc57c63070ba |
def create_new_model(self, *args, **kwargs) -> Model: <NEW_LINE> <INDENT> kwargs['periodic_id'] = self.__periodic_id <NEW_LINE> kwargs['is_periodic'] = True <NEW_LINE> kwargs = self._add_periodic_state(**kwargs) <NEW_LINE> return super(BaseMeetingPeriodicCreateDecorator, self).create_new_model(*args, **kwargs) | Create periodic meeting. (Same with create meeting, just add an extra step by adding periodic_id to kwargs)
:param args: create meeting list data
:param kwargs: create meeting dict data
:return: New periodic meeting | 625941e3711fe17d82542739 |
def initializeModelParamsFromPrior(self): <NEW_LINE> <INDENT> self.initializeGpuMemory() <NEW_LINE> K = self.modelParams["proc_id_model","K"] <NEW_LINE> W0 = np.zeros((K,K), dtype=np.float32) <NEW_LINE> W0[np.diag_indices(K)] = np.random.gamma(self.params["a_w"], 1.0/self.params["b_w"], size=(K,)) <NEW_LINE> W0_lower =... | Initialize the background rate with a draw from the prior. | 625941e3046cf37aa974d11a |
def strip_mat_name(mat_name): <NEW_LINE> <INDENT> tmp1 = mat_name.split(':')[1] <NEW_LINE> special_char = [':', ',', ' ', ';', "'", '"'] <NEW_LINE> for char in special_char: <NEW_LINE> <INDENT> tmp2 = tmp1.split(char) <NEW_LINE> tmp1 = ''.join(tmp2) <NEW_LINE> <DEDENT> return tmp1 | Provide a material name (string) and receive a compacted name without
'mat:' or special characters.
Assumes PyNE naming convention (must start with 'mat:'). | 625941e35e10d32532c5f2fc |
def findShortPath(source, target) -> list: <NEW_LINE> <INDENT> node_dict = Map.NODE_DICT <NEW_LINE> Map.G = nx.DiGraph() <NEW_LINE> for node in node_dict.values(): <NEW_LINE> <INDENT> Map.G.add_node(node) <NEW_LINE> <DEDENT> for i in Map.EDGE_LIST: <NEW_LINE> <INDENT> i_list = list(i) <NEW_LINE> i_list.append(math.sqrt... | 利用networkx作路径规划
:param source:'A'
:param target:'F'
:return: | 625941e310dbd63aa1bd2f79 |
def list(self, detailed=False, search_opts=None): <NEW_LINE> <INDENT> if search_opts is None: <NEW_LINE> <INDENT> search_opts = {} <NEW_LINE> <DEDENT> qparams = {} <NEW_LINE> for opt, val in search_opts.iteritems(): <NEW_LINE> <INDENT> if val: <NEW_LINE> <INDENT> qparams[opt] = val <NEW_LINE> <DEDENT> <DEDENT> query_st... | Get a list of all pool usages.
:rtype: list of :class:`PoolUsage` | 625941e3e5267d203edce06f |
def split(self, X, y=None, groups=None, fixed_length=False, train_splits=1, test_splits=1): <NEW_LINE> <INDENT> X, y, groups = indexable(X, y, groups) <NEW_LINE> n_samples = _num_samples(X) <NEW_LINE> n_splits = self.n_splits <NEW_LINE> n_folds = n_splits + 1 <NEW_LINE> train_splits, test_splits = int(train_splits), in... | Generate indices to split data into training and test set.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data, where n_samples is the number of samples
and n_features is the number of features.
y : array-like, shape (n_samples,)
Always ignored, exists for compatibility.
groups... | 625941e345492302aab5e69e |
def get_blank(self): <NEW_LINE> <INDENT> return self.cell.value == '' | Note that cells might not exist at all.
Behaviour for spanned cells might be complicated: hence this function | 625941e321a7993f00bc80cd |
def tick(self) -> bool: <NEW_LINE> <INDENT> wait_time = self.max_frame_time - (time() - self.frame_start_time) <NEW_LINE> if wait_time > 0: <NEW_LINE> <INDENT> sleep(wait_time) <NEW_LINE> <DEDENT> self.frame_start_time = time() <NEW_LINE> return (self.frame_start_time - self.timeout_start_time) > self.timeout_time | Wait for a single frame roll to finish before returning and check to see if we have timed out
Returns
-------
bool: Whether or not we have timed out | 625941e366656f66f7cbc583 |
def test_BatchCreateSku(): <NEW_LINE> <INDENT> TestData=parentdir+'\Test_Data\SmallBear\BatchCreateSku.yaml' <NEW_LINE> f = open(TestData,'rb') <NEW_LINE> TestCase=XsxDriver() <NEW_LINE> headers=None <NEW_LINE> i=1 <NEW_LINE> for data in yaml.load_all(f): <NEW_LINE> <INDENT> Data=data <NEW_LINE> yaml.safe_dump(Data) <N... | ERP自动创建sku | 625941e34f6381625f114e12 |
def GPVariance(self, locations, current_location, cholesky): <NEW_LINE> <INDENT> assert cholesky is not None <NEW_LINE> k_star = self.CovarianceMesh(locations, current_location) <NEW_LINE> K_current = self.CovarianceMesh(current_location, current_location) <NEW_LINE> v = scipy.linalg.solve_triangular(cholesky, k_star, ... | if cholesky is None:
cholesky = self.Cholesky(locations) | 625941e3a8370b7717052c74 |
def get_queryset(self, request): <NEW_LINE> <INDENT> querys = self.model.all_objects.get_queryset() <NEW_LINE> ordering = self.get_ordering(request) <NEW_LINE> if ordering: <NEW_LINE> <INDENT> querys = querys.order_by(*ordering) <NEW_LINE> <DEDENT> return querys | Don't use the default manager. | 625941e3dc8b845886cb590e |
def choose_sex01(self): <NEW_LINE> <INDENT> self.click(self.sex_male_loc) <NEW_LINE> log.info("选择性别:{}".format(self.sex_male_loc)) | 选择性别 | 625941e32c8b7c6e89b35b95 |
def is_column(self): <NEW_LINE> <INDENT> if self.row1 != self.row2 and self.col1 == self.col2: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Returns ``True`` if the Range consists of a single Column otherwise ``False``. | 625941e3b545ff76a89141ec |
def compute_distance_field(self, entity_type): <NEW_LINE> <INDENT> boundary = poc_queue.Queue() <NEW_LINE> if entity_type == ZOMBIE: <NEW_LINE> <INDENT> for zombie in self._zombie_list: <NEW_LINE> <INDENT> boundary.enqueue(zombie) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for human in self._human_list: <NE... | Function computes and returns a 2D distance field
Distance at member of entity_list is zero
Shortest paths avoid obstacles and use four-way distances | 625941e329b78933be1e5a7e |
def list_destroy(lentry): <NEW_LINE> <INDENT> lentry.data = None <NEW_LINE> lentry._prev = None <NEW_LINE> lentry._next = None | Invalidate list entry ''lentry''. The result of this is that any
reference cycle will be broken | 625941e34f6381625f114e13 |
def _getLocked(self): <NEW_LINE> <INDENT> return self._locked | True if the item is locked | 625941e3d53ae8145f87a63f |
def setTimeWindow(self, *args): <NEW_LINE> <INDENT> return _IO.SLConnection_setTimeWindow(self, *args) | setTimeWindow(SLConnection self, Seiscomp::Core::TimeWindow const & w) -> bool | 625941e3498bea3a759b9e85 |
def dedup(aDict): <NEW_LINE> <INDENT> return {'removed':[]} | NO OP
Args:
Output: | 625941e330dc7b7665901d39 |
def getNewFileName(prompt): <NEW_LINE> <INDENT> while (True): <NEW_LINE> <INDENT> fname = raw_input('Please enter file name for ' + prompt + ' : ') <NEW_LINE> if os.path.exists(fname): <NEW_LINE> <INDENT> print ('Entered name already exists; please enter the name of a new file') <NEW_LINE> <DEDENT> else: <NEW_LINE> <IN... | Get the name of a new file, insuring that no file of that name already exists.
If a file of that name exists, the user will be prompted to re-enter the filename.
Returns a string | 625941e360cbc95b062c691a |
@APP.route('/remote/prior') <NEW_LINE> def prior(): <NEW_LINE> <INDENT> slides = APP.config['SLIDES'] <NEW_LINE> slides.index -= 1 <NEW_LINE> return "" | Decrement the current slide | 625941e37cff6e4e81117d5c |
def _test_fire_pending(self, is_scalar, time_to_wait): <NEW_LINE> <INDENT> if time_to_wait > 3: <NEW_LINE> <INDENT> time_to_wait = 3 <NEW_LINE> <DEDENT> l_val = time_to_wait * 1000000000 if is_scalar else 0 <NEW_LINE> h_val = 0 if is_scalar else time_to_wait <NEW_LINE> l_name = "exp-scalar-l" if is_scalar else "exp-nse... | It test that the trigger immediately fire when a pending trigger fire
while trigger was disabled | 625941e3a219f33f34628d3b |
def get_selected_text(self, vi_cmd_data): <NEW_LINE> <INDENT> fragments = [self.view.substr(r) for r in list(self.view.sel())] <NEW_LINE> if (vi_cmd_data._synthetize_new_line_at_eof and not vi_cmd_data._yanks_linewise): <NEW_LINE> <INDENT> if (not fragments[-1].endswith('\n') and self.view.sel()[-1].b >= self.view.size... | Inspect settings and populate registers as needed.
| 625941e307d97122c4178c6b |
def __init__(self, frame, text, font_size = 40): <NEW_LINE> <INDENT> self.frame = frame <NEW_LINE> self.text = text <NEW_LINE> self.font_size = font_size | Creates a new notification and display it on the canvas | 625941e38c3a873295158796 |
def attention(query, key, value, mask=None, dropout=None): <NEW_LINE> <INDENT> d_k = query.size(-1) <NEW_LINE> scores = torch.matmul(query, key.transpose(-2, -1))/math.sqrt(d_k) <NEW_LINE> if mask is not None: <NEW_LINE> <INDENT> scores = scores.masked_fill(mask == 0, -1e9) <NEW_LINE> <DEDENT> m = torch.max(scores,dim=... | Compute 'Scaled Dot Product Attention' | 625941e34c3428357757c6fd |
def _setStepProperty(self, propertyName, propertyDict, stepMap): <NEW_LINE> <INDENT> propMethodMap = {"AcquisitionEra": "setAcqEra", "ProcessingString": "setProcStr", "ProcessingVersion": "setProcStr"} <NEW_LINE> if self.taskType() not in ["Production", "Processing"]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for ... | For StepChain workloads, we also need to set AcqEra/ProcStr/ProcVer
at the WMStep level, such that we can properly map different cmsRun
steps - within the same task - to different meta data information.
:param propertyName: the name of the property to set at step level
:param propertyDict: a dictionary mapping StepName... | 625941e34a966d76dd5513ea |
def writeDependent(temp, inFile, myVariableName, myNumChoices, currentLine, saveChoicesFile, txtChoicesFile, outFile, myLabel, dictionaryRepeatSame, dictionaryRepeatNever, dictionaryMatchSame, dictionaryMatchDifferent, dictionaryMatchOnlyOneEver, dictionaryMaxSelectionsPerSubPoint, startString, endString, currentString... | Writes out a Dependend section, using recursiveGenerate. | 625941e3187af65679ca54f7 |
def get_name(): <NEW_LINE> <INDENT> letters = listdir('./letters/') <NEW_LINE> letters = [letter.split('.')[0] for letter in letters] <NEW_LINE> found = [] <NEW_LINE> screen = np.asarray(pyautogui.screenshot()) <NEW_LINE> screen = cv.cvtColor(screen, cv.COLOR_BGR2GRAY)[270:300, 920:1030] <NEW_LINE> for letter in letter... | get the name of the pokemon | 625941e34d74a7450ccd459b |
def readSongDB(): <NEW_LINE> <INDENT> csv_reader = csv.reader(open(wii_songdb)) <NEW_LINE> songdb = {} <NEW_LINE> headers = None <NEW_LINE> for row in csv_reader: <NEW_LINE> <INDENT> if not headers: <NEW_LINE> <INDENT> headers = row <NEW_LINE> <DEDENT> else: songdb[row[1]] = dict(zip(headers, row)) <NEW_LINE> <DEDENT>... | Read Wii's songdb.csv file into a dictionary. | 625941e33539df3088e2e722 |
def suite(): <NEW_LINE> <INDENT> test_suite = unittest.TestSuite() <NEW_LINE> test_suite.addTest(unittest.makeSuite(TestSuiteAdMonitor)) <NEW_LINE> return test_suite | Assemble tests. | 625941e3442bda511e8be7ea |
def settings(self, nodialog=False): <NEW_LINE> <INDENT> if 'Line' not in self.indata and 'Vector' not in self.indata: <NEW_LINE> <INDENT> self.showprocesslog('No vector data.') <NEW_LINE> return False <NEW_LINE> <DEDENT> if 'Vector' in self.indata: <NEW_LINE> <INDENT> firstkey = next(iter(self.indata['Vector'].keys()))... | Entry point into item.
Parameters
----------
nodialog : bool, optional
Run settings without a dialog. The default is False.
Returns
-------
bool
True if successful, False otherwise. | 625941e3f548e778e58cd956 |
def register_enhancer(enhancer): <NEW_LINE> <INDENT> if not issubclass(enhancer, ElementEnhancer): <NEW_LINE> <INDENT> raise TypeError( "Only subclasses of holmium.core.ElementEnhancer can be registered") <NEW_LINE> <DEDENT> if not hasattr(enhancer, "__TAG__") or not enhancer.__TAG__: <NEW_LINE> <INDENT> raise Attribut... | registers a :class:`ElementEnhancer` with the internal
lookup | 625941e3dd821e528d63b57d |
def format_dict(indict): <NEW_LINE> <INDENT> for key in indict: <NEW_LINE> <INDENT> indict[key] = format_str(indict[key]) <NEW_LINE> <DEDENT> return indict | :param indict:
:return: | 625941e3167d2b6e31218f6c |
def add_mock_s3_data(self, data, age=None, location=None): <NEW_LINE> <INDENT> add_mock_s3_data(self.mock_s3_fs, data, age, location) | Update self.mock_s3_fs with a map from bucket name
to key name to data. | 625941e344b2445a3393246b |
def update_wrapper(): <NEW_LINE> <INDENT> def do_nothing(): "Doing nothing." <NEW_LINE> def wrapper(): <NEW_LINE> <INDENT> return do_nothing() <NEW_LINE> <DEDENT> wrapper_alias = functools.update_wrapper(wrapper, do_nothing) <NEW_LINE> return wrapper_alias is wrapper and wrapper.__doc__.strip() | Copy wrapped function information. | 625941e363b5f9789fde74be |
def test_setup_instantiation(self): <NEW_LINE> <INDENT> with self.assertRaises(InstantiationError): <NEW_LINE> <INDENT> self.test_class(1, 2) <NEW_LINE> <DEDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> instance = self.test_class.setup() <NEW_LINE> <DEDENT> with self.assertRaises(TypeError): <NEW_LINE> <I... | Test instantiation with setup. | 625941e373bcbd0ca4b2c44d |
def detailUserProfileInfo(request, pk): <NEW_LINE> <INDENT> a = UserProfileInfo.objects.filter(id_id=request.user.id) <NEW_LINE> user_profile_info = None <NEW_LINE> if not a: <NEW_LINE> <INDENT> message = 'Profile not edited' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> user_profile_info = a[0] <NEW_LINE> message = 'P... | Shows detailView of User | 625941e3bde94217f36831c5 |
def convertTabbedString2Dictionary(tabstr) -> dict: <NEW_LINE> <INDENT> ele = tabstr.split() <NEW_LINE> if 0 < len(ele) < 4: <NEW_LINE> <INDENT> return {'suraface': ele[0], 'base': '', 'pos': '', 'pos1': ''} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return {'suraface': ele[0], 'base': ele[1], 'pos': ele[2], 'pos1':... | This function create the dictionary by reading .mecab file | 625941e307f4c71912b1185c |
def __init__(self, config): <NEW_LINE> <INDENT> log_format = '%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s' <NEW_LINE> log_date_format = None <NEW_LINE> self.formatter = logging.Formatter(log_format, log_date_format) | Creates a new plugin to capture log messges.
The formatter can be safely shared across all handlers so
create a single one for the entire test session here. | 625941e31f5feb6acb0c4f21 |
def cudnn_rnn_params_to_canonical_eager_fallback(num_layers, num_units, input_size, params, num_params, rnn_mode="lstm", input_mode="linear_input", direction="unidirectional", dropout=0, seed=0, seed2=0, name=None, ctx=None): <NEW_LINE> <INDENT> _ctx = ctx if ctx else _context.context() <NEW_LINE> num_params = _execute... | This is the slowpath function for Eager mode.
This is for function cudnn_rnn_params_to_canonical | 625941e34e4d5625662d47ab |
def choose_action(self, state): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> self.next_waypoint = self.planner.next_waypoint() <NEW_LINE> action = None <NEW_LINE> action = random.choice(self.valid_actions) <NEW_LINE> if self.learning == True: <NEW_LINE> <INDENT> if random.random() < self.epsilon: <NEW_LINE> <INDEN... | The choose_action function is called when the agent is asked to choose
which action to take, based on the 'state' the smartcab is in. | 625941e33c8af77a43ae3b7c |
def iterjson(text): <NEW_LINE> <INDENT> decoder = json.JSONDecoder() <NEW_LINE> while text: <NEW_LINE> <INDENT> obj, ndx = decoder.raw_decode(text) <NEW_LINE> if not isinstance(obj, dict): <NEW_LINE> <INDENT> raise ValueError() <NEW_LINE> <DEDENT> text = text[ndx:].lstrip("\r\n") <NEW_LINE> yield obj | Decode JSON stream. | 625941e3cc40096d61595d27 |
def record_backup(name, size, backup_lsn=None): <NEW_LINE> <INDENT> log.info("Saving information about backup:", log_params) <NEW_LINE> log.info("File name : %s" % name, log_params) <NEW_LINE> log.info("Volume id : %d" % int(job_order["params"]["volume_id"]), log_params) <NEW_LINE> log.info("Size : %d (%s)" % (int... | Saves details about backup copy in TwinDB dispatcher
:param name: name of backup
:param size: size of the backup in bytes
:param backup_lsn: last LSN if it was incremental backup
:return: JSON string with status of the request i.e. { "success": True } or None if error happened | 625941e3ac7a0e7691ed449d |
def get_nodes_checked_stable(self): <NEW_LINE> <INDENT> test_elements_attr_list = [] <NEW_LINE> nodes = self.find_elems('.weui-check') <NEW_LINE> for node in nodes: <NEW_LINE> <INDENT> if node.is_selected() == True: <NEW_LINE> <INDENT> test_elements_attr_list.append(True) <NEW_LINE> <DEDENT> elif node.is_selected() == ... | 获取所有流程节点的单选框状态 | 625941e3435de62698dfe025 |
def test_template_string(self): <NEW_LINE> <INDENT> str_path = "Nuke Script Name, v02" <NEW_LINE> template = self.tk.template_from_path(str_path) <NEW_LINE> self.assertIsNotNone(template) <NEW_LINE> self.assertIsInstance(template, TemplateString) | Resolve 'path' which is a resolved TemplateString. | 625941e3090684286d50f0c2 |
def buildFeatureVector(self, messages): <NEW_LINE> <INDENT> words = {} <NEW_LINE> for message in messages: <NEW_LINE> <INDENT> messageWordCount = Counter(nltk.word_tokenize(message.lower())) <NEW_LINE> for word,count in messageWordCount.items(): <NEW_LINE> <INDENT> if not hasPunct(word): <NEW_LINE> <INDENT> if word not... | Define a feature vector for the given messages.
Builds feature vectors of the 30 words with highest corpus-wide TF-IDF scores | 625941e357b8e32f52483876 |
def __init__(self): <NEW_LINE> <INDENT> self.clients = {'1': ("User", Player())} <NEW_LINE> self.new_friends = {} <NEW_LINE> self.dispatch_prefixes = {'be': self.process_bet, 'ng': self.new_round} <NEW_LINE> self.new_game = False <NEW_LINE> self.game_time = False <NEW_LINE> self.task_queue = queue.Queue() | Initialises a Dealer Object! | 625941e345492302aab5e69f |
def to_eigenbasis(self, op): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.ek <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.compute_frequencies() <NEW_LINE> <DEDENT> if is_vector(op): <NEW_LINE> <INDENT> return np.dot(dag(self.ek), op)[:self.nstates,:] <NEW_LINE> <DEDENT> elif is_matrix(op): <NEW_LINE> <INDE... | Transforms vector or operator to energy eigenbasis. | 625941e39c8ee82313fbbb4e |
def truncate_segment_tokens(segment_tokens, max_tokens): <NEW_LINE> <INDENT> mask = tf.ones_like(segment_tokens, dtype=tf.int32).to_tensor() <NEW_LINE> mask.set_shape([None, None]) <NEW_LINE> max_tokens = tf.cast(max_tokens, dtype=tf.int32) <NEW_LINE> transposed_mask = tf.transpose(mask) <NEW_LINE> visit_order_flat = t... | Truncates segment tokens.
Suppose we arrange our segment tokens in a matrix, e.g.:
this is query one <pad> <-- first segment
this is query two <pad> <-- second segment
more text <pad> <pad> <pad> <-- third segment
If we visit the tokens in column-major order, we get this orderin... | 625941e3498bea3a759b9e86 |
def __init__(self, local_address, remote_addres, socks_chain = [], udp = False, version = V_SOCKS5, user = None, pwd = None): <NEW_LINE> <INDENT> if version not in _VERSIONS: <NEW_LINE> <INDENT> raise ValueError("Invalid SOCKS version") <NEW_LINE> <DEDENT> self.remote_addres = remote_addres <NEW_LINE> self.local_addres... | Initialize SocksClient properties.
local_address is where the client listen and from there forward the
traffic to tunnle and remote_address is to where sending the traffic
after forwarded in the tunnle (Both in (address, port) format).
socks_chain is a list of SOCKS server addresses and... | 625941e33539df3088e2e723 |
def __init__(self, baseName = 'fk',side = 'm',size = 1.5,fkCcType = 'shape',type = 'fk',pointCnst = 1): <NEW_LINE> <INDENT> self.baseName = baseName <NEW_LINE> self.side = side <NEW_LINE> self.size = size <NEW_LINE> self.fkType = type <NEW_LINE> self.fkCcType = fkCcType <NEW_LINE> self.controlsArray = [] <NEW_LINE> sel... | Constructor | 625941e310dbd63aa1bd2f7a |
def numerical_stats(feature, column, num_nonblank, feature_list): <NEW_LINE> <INDENT> sigma = 3 <NEW_LINE> stats = column.describe() <NEW_LINE> if ("number_of_numeric_values" in feature_list): <NEW_LINE> <INDENT> feature["number_of_numeric_values"] = int(stats["count"]) <NEW_LINE> <DEDENT> if ("ratio_of_numeric_values"... | calculates numerical statistics | 625941e371ff763f4b549a6a |
@pytest.mark.parametrize( 'selection_strategy, truncation_factor, deformation_factor', [ (selection_strategy, truncation_factor, deformation_factor) for selection_strategy in SELECTION_STRATEGY for truncation_factor in TRUNCATION_FACTORS for deformation_factor in DEFORMATION_FACTORS ], ) <NEW_LINE> def test_gsmote_fit_... | Test fit and sample for binary class case. | 625941e307d97122c4178c6c |
def feature_importances(model, df): <NEW_LINE> <INDENT> f = plt.figure(figsize=(10,8)) <NEW_LINE> plt.title('Feature importances') <NEW_LINE> plt.ylabel("Feature") <NEW_LINE> plt.xlabel("Relative Importance") <NEW_LINE> (pd.Series(model.best_estimator_.feature_importances_, index=df.columns) .nlargest(10) .plot(kind='b... | Plot feature importances of the model when you using gridsearch (model is the result of the gridSearch fit). | 625941e307f4c71912b1185d |
def _find_largest_divisible_subset(self, nums): <NEW_LINE> <INDENT> if len(nums) == 1: <NEW_LINE> <INDENT> return nums <NEW_LINE> <DEDENT> if len(nums) == 2: <NEW_LINE> <INDENT> if nums[1] % nums[0] == 0: <NEW_LINE> <INDENT> return nums <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [nums[0]] <NEW_LINE> <DEDENT> ... | helper function to work on a sorted nums array recursively.
starts from the minimal element,
divide all the other elements by this minimal element,
build a tmp_nums:
1. if len(tmp_nums) == 0, no other common elements
2. use _find_largest_divisible_subset on this subset,
the returned valid subset will be [elem] + [elem*... | 625941e31f037a2d8b9465d5 |
def index(request): <NEW_LINE> <INDENT> pizza = Pizza.objects.all().order_by('price') <NEW_LINE> return render(request, 'menu/index.html', {'pizzas': pizza}) | pizzas = Pizza.objects.all()
pizzas_names_and_price = [pizza.name + ' - ' + str(pizza.price) + ' $' for pizza in pizzas]
pizzas_names_and_price_str = ', '.join(pizzas_names_and_price)
return HttpResponse('Pizzas : ' + pizzas_names_and_price_str) | 625941e391f36d47f21ac8cf |
def _set_scan_params(self, device, start, stop, step, device2, start2, stop2, step2, scalers, dwell_time, timer, scan_dim='1D', detector=None, file_name=None, dir_path=None, scalers_raw='', **kwargs): <NEW_LINE> <INDENT> self.out_path = dir_path <NEW_LINE> self.out_name = file_name <NEW_LINE> self.device = device <NEW_... | Sets the parameters for the scan.
:param str device: The MX record name for motor 1.
:param float start: The absolute start position of the scan for motor 1.
:param float stop: The absolute stop position of the scan for motor 1.
:param float step: The step size of the scan for motor 1.
:param str device2: The MX recor... | 625941e36aa9bd52df03717e |
def p_compStmt(self, p): <NEW_LINE> <INDENT> p[0] = RustAST.Compound(p[2], self._token_coord(p, 1)) | compStmt : lbrace stmtList rbrace
| 625941e3ff9c53063f47c5ca |
def testBasicEditGet(self): <NEW_LINE> <INDENT> response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/episode/1/') <NEW_LINE> self.failUnlessEqual(response.status_code, 200) | A smoke test to ensure GET on the change_view works. | 625941e3a05bb46b383ecbf7 |
def loglike(self, params): <NEW_LINE> <INDENT> return np.sum(self.loglikeobs(params)) | Loglikelihood of Generalized Poisson model
Parameters
----------
params : array_like
The parameters of the model.
Returns
-------
loglike : float
The log-likelihood function of the model evaluated at `params`.
See notes.
Notes
-----
.. math:: \ln L=\sum_{i=1}^{n}\left[\mu_{i}+(y_{i}-1)*ln(\mu_{i}+
\a... | 625941e32ae34c7f2600d509 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.