code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def add_account(self, account): <NEW_LINE> <INDENT> serialized = account.serialize() <NEW_LINE> section_items = flatten_dict(serialized) <NEW_LINE> section_id = section_items['local_id'] <NEW_LINE> if not self.parser.has_section(section_id): <NEW_LINE> <INDENT> self.parser.add_section(section_id) <NEW_LINE> <DEDENT> fo... | Add Account to config (does not save) | 625941c4adb09d7d5db6c76f |
def do_replacements(self): <NEW_LINE> <INDENT> self.replace_substring("127.0.0.1", "localhost") <NEW_LINE> self.replace_result("| audit.log", "| audit.log [...] \n") <NEW_LINE> self.replace_result("+------------+--------+--------------------------" "-+---------------------------+\n", "+------------+-------+------------... | Apply masks in the result.
| 625941c48e71fb1e9831d789 |
def get_featuredim(self): <NEW_LINE> <INDENT> return self.feature_dim | get feature dimension | 625941c467a9b606de4a7e9a |
def lr_schedule(fun, var, halfLife, start): <NEW_LINE> <INDENT> def Trapz(t): <NEW_LINE> <INDENT> t1 = 1./2 <NEW_LINE> t2 = 1./4 <NEW_LINE> t3 = 1.-(t1+t2) <NEW_LINE> if t < t1:return t/t1 <NEW_LINE> elif t < (t2+t1): return 1. <NEW_LINE> else: return (1. - (t-(1.-t3)) / t3) <NEW_LINE> <DEDENT> def ZeroTrapz(t): <NEW_L... | Implementation of various learning rate schedules.
Arguments:
fun - which learning rate schedule
var - current position in the total training, var = current update / total updates
halfLife - halfLife parameter for exponential function
start - parameter for functions which a... | 625941c401c39578d7e74e1a |
def dir_clashes_with_python_module(path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> mod = load_module(os.path.basename(path)) <NEW_LINE> <DEDENT> except ModuleNotFoundError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if path not in mod.__path__: <NEW_LINE> <INDENT> return True <NE... | Returns a boolean | 625941c424f1403a92600b47 |
def p_blocks(p): <NEW_LINE> <INDENT> if p[1]: <NEW_LINE> <INDENT> p[0] = [p[1]]+p[2] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p[0] = p[2] | blocks : block blocks | 625941c43317a56b86939c3b |
def featureNormalize(X): <NEW_LINE> <INDENT> mu = np.mean(X, 0) <NEW_LINE> sigma = np.std(X, 0, ddof=1) <NEW_LINE> X_norm = (X-mu)/sigma <NEW_LINE> return X_norm, mu, sigma | Normalize features. | 625941c4d164cc6175782d2d |
def __init__(self, id_, description, door=None, code=None, free_access=True, delay=DEFAULT_DELAY_BEFORE_OPEN, **kwargs): <NEW_LINE> <INDENT> super(DoorTerminal, self).__init__( id_=id_, description=description) <NEW_LINE> self._actions_list = [ACTION_BAD, ACTION_USE] <NEW_LINE> self._door = door <NEW_LINE> self._is_acc... | Init.
id_: Class ID in configuration files.
description: Index of description string in locale
text files.
door: Number of a door object, terminal connected
with (int).
free_access: Is free mode enabled (boolean). In free
... | 625941c445492302aab5e2a1 |
def linear_path(path): <NEW_LINE> <INDENT> assert isinstance(path, str) <NEW_LINE> s = path.replace("\\", "/") <NEW_LINE> return s | Linear path is designated as a path without back-slashes, but rather, possibly, slashes.
:param self:
:param path: string, filename (or a path)
:return: string | 625941c4627d3e7fe0d68e2e |
def update(self): <NEW_LINE> <INDENT> if self.connect() != True: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.readTemperatures() <NEW_LINE> self.close() <NEW_LINE> return True | Update controller by reading all parameters from lakeshore | 625941c4656771135c3eb84c |
def timeseries(inputs,period=None,extent=None,**kwds): <NEW_LINE> <INDENT> inputs = _sanitize_inputs(inputs) <NEW_LINE> if period is None: <NEW_LINE> <INDENT> period = inputs.source.period <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> period = _sanitize_period(period, inputs.source.period.freq) <NEW_LINE> <DEDENT> if e... | Inputs is a variable or group of variables
If extent is larger than a single cell, variables
will be aggregated using their default method | 625941c4a8370b771705287f |
def jnxexvlantag(self): <NEW_LINE> <INDENT> data_dict = defaultdict(dict) <NEW_LINE> oid = '.1.3.6.1.4.1.2636.3.40.1.5.1.7.1.3' <NEW_LINE> results = self.snmp_object.walk(oid, normalized=False) <NEW_LINE> for key in sorted(results.keys()): <NEW_LINE> <INDENT> nodes = key.split('.') <NEW_LINE> vlan_id = nodes[-2] <NEW_L... | Return dict of JUNIPER-VLAN-MIB jnxExVlanTag per port.
Args:
None
Returns:
data_dict: Dict of jnxExVlanTag using ifIndex as key | 625941c43c8af77a43ae377e |
def _populate_transitive_metadata(bazel_rules: Any, public_dep_names: Iterable[str]) -> None: <NEW_LINE> <INDENT> bazel_label_to_dep_name = {} <NEW_LINE> for dep_name in public_dep_names: <NEW_LINE> <INDENT> bazel_label_to_dep_name[_get_bazel_label(dep_name)] = dep_name <NEW_LINE> <DEDENT> for rule_name in bazel_rules:... | Add 'transitive_deps' field for each of the rules | 625941c4dc8b845886cb5513 |
def __enter__(self): <NEW_LINE> <INDENT> self._id = 0 <NEW_LINE> self._stack = [ ] <NEW_LINE> self._element_tags = Counter() <NEW_LINE> self._element_ancestors = defaultdict(set) <NEW_LINE> self._start_callbacks = [ ] <NEW_LINE> self._end_callbacks = [ ] <NEW_LINE> self._children = { } <NEW_LINE> return self | Context manager entry point. | 625941c491af0d3eaac9b9f6 |
def _build_json_payload(self, domain, covariance, historical_data, num_to_sample, lie_value=None, lie_method=None): <NEW_LINE> <INDENT> dict_to_dump = { 'num_to_sample': num_to_sample, 'mc_iterations': TEST_EXPECTED_IMPROVEMENT_MC_ITERATIONS, 'gp_historical_info': historical_data.json_payload(), 'covariance_info': cova... | Create a json_payload to POST to the /gp/next_points/* endpoint with all needed info. | 625941c4187af65679ca50fd |
def decode_str(string): <NEW_LINE> <INDENT> if not len(string) >= 2: <NEW_LINE> <INDENT> raise SyntaxError(f"Expected the string {string!r} to be longer than two characters so it can begin and end with a quotation") <NEW_LINE> <DEDENT> if not string.startswith('"'): <NEW_LINE> <INDENT> raise SyntaxError(f"Expected the ... | Examples:
>>> decode_str(r'"hello"')
'hello'
>>> decode_str(r'""')
''
>>> decode_str(r'"\x89\t"')
'\x89\t'
>>> decode_str(r'')
Traceback (most recent call last):
...
SyntaxError: Expected the string '' to be longer than two characters so it can begin and end with a quotation... | 625941c47c178a314d6ef43c |
def bprop_conv(self, out, weights, deltas, ofmshape, ofmsize, ofmlocs, ifmshape, links, padding, stride, nifm, ngroups, bpropbuf, local=False): <NEW_LINE> <INDENT> self.ng.bprop_conv(layer=bpropbuf, F=weights, E=deltas, grad_I=out, alpha=1.0, repeat=1) | Backward propagate the error through a convolutional network layer.
Arguments:
out (GPUTensor): Where to store the backward propagated errors.
weights (GPUTensor): The weight coefficient values for this layer.
deltas (GPUTensor): The error values for this layer
ofmshape (tuple): Dimensions of each outp... | 625941c4f9cc0f698b1405dc |
def __init__(self, val=None): <NEW_LINE> <INDENT> self.val = val <NEW_LINE> self.next = None <NEW_LINE> self.prev = None | Create a node for the list. | 625941c4ad47b63b2c509f5f |
def mark_as_run(self, imported_module): <NEW_LINE> <INDENT> flat_imports = util.flatten_imports(imported_module, self.import_tree) <NEW_LINE> self.modules_to_run |= flat_imports | Mark a module as causing a test run
This also implicitly marks any modules that import the
"imported_module" as needing to run.
:param imported_module: The module that should cause a test run
:type imported_module: str | 625941c497e22403b379cf79 |
def add(self, product, quantity=1, action=None): <NEW_LINE> <INDENT> id = product.id <NEW_LINE> newItem = True <NEW_LINE> if str(product.id) not in self.cart.keys(): <NEW_LINE> <INDENT> self.cart[product.id] = { 'userid': self.request.user.id, 'product_id': id, 'name': product.name, 'quantity': 1, 'price': str(product.... | Add a product to the cart or update its quantity. | 625941c4cb5e8a47e48b7a8b |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gestao_clientes_final.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django... | Run administrative tasks. | 625941c499fddb7c1c9de371 |
def message(driver): <NEW_LINE> <INDENT> driver.find_element_by_xpath( '//UIAApplication[1]/UIAWindow[1]/UIATableView[1]/UIATableCell[1]/UIAButton[1]').click() <NEW_LINE> random_click(driver, '//UIAApplication[1]/UIAWindow[1]/UIATableView[1]/')[1].click() <NEW_LINE> driver.find_element_by_xpath( '//UIAApplication[1]/UI... | 到我的关注页面随机给一个人发送一个私信 | 625941c4be383301e01b5468 |
@iterate_jit(nopython=True) <NEW_LINE> def StdDed(DSI, earned, STD, age_head, age_spouse, STD_Aged, STD_Dep, MARS, MIDR, blind_head, blind_spouse, standard, c19700, STD_allow_charity_ded_nonitemizers, STD_charity_ded_nonitemizers_max): <NEW_LINE> <INDENT> if DSI == 1: <NEW_LINE> <INDENT> c15100 = max(350. + earned, STD... | Calculates standard deduction, including standard deduction for
dependents, aged and bind.
Parameters
-----
DSI: int
1 if claimed as dependent on another return; otherwise 0
earned: float
Earned income for filing unit
STD: list
Standard deduction amount
age_head: int
Age in years of taxpayer
age_spouse... | 625941c48e7ae83300e4afab |
def maxSubArray(self, nums): <NEW_LINE> <INDENT> currentSum = 0 <NEW_LINE> maxSum = -2**31 <NEW_LINE> for i in range(len(nums)): <NEW_LINE> <INDENT> if currentSum < 0: <NEW_LINE> <INDENT> currentSum = 0 <NEW_LINE> <DEDENT> currentSum += nums[i] <NEW_LINE> maxSum = max(maxSum, currentSum) <NEW_LINE> <DEDENT> return maxS... | :type nums: List[int]
:rtype: int | 625941c4d58c6744b4257c40 |
def get_battery_power_plugged(self) -> namedtuple: <NEW_LINE> <INDENT> output = self.netcat.query("get battery_power_plugged") <NEW_LINE> return self._nt(output) | Returns whether the charging usb is plugged (new model only) | 625941c44c3428357757c308 |
def Vbnunit(self, name): <NEW_LINE> <INDENT> scenario = Scenarios.Vbnunit() <NEW_LINE> scenario.GivenAFeatureFileCalled(name) <NEW_LINE> scenario.WhenTheGeneratorIsNunit() <NEW_LINE> scenario.ThenTheGeneratedTestIsTheSameAsTheSaved() | Gherkin DSL scenario | 625941c4a17c0f6771cbe031 |
def EditObject(dbstate, uistate, track, obj_class, prop, value): <NEW_LINE> <INDENT> import logging <NEW_LINE> LOG = logging.getLogger(".Edit") <NEW_LINE> if obj_class in dbstate.db.get_table_names(): <NEW_LINE> <INDENT> if prop in ("gramps_id", "handle"): <NEW_LINE> <INDENT> obj = dbstate.db.get_table_metadata(obj_cla... | Generic Object Editor.
obj_class is Person, Source, Repository, etc.
prop is 'handle' or 'gramps_id'
value is string handle or string gramps_id | 625941c47b25080760e39439 |
def __verify(self, target): <NEW_LINE> <INDENT> if not set(SUPPORTED_HASH_ALGORITHMS).intersection(self): <NEW_LINE> <INDENT> logger.debug("Artifact '{}' lacks any checksum definition.".format(self.name)) <NEW_LINE> return False <NEW_LINE> <DEDENT> if not Resource.CHECK_INTEGRITY: <NEW_LINE> <INDENT> logger.info("Integ... | Checks all defined check_sums for an artifact | 625941c4bde94217f3682dd2 |
def drawLabels(self, labels=None, display="deferToFrame", frame=None): <NEW_LINE> <INDENT> if not labels: <NEW_LINE> <INDENT> labels = self.labels <NEW_LINE> <DEDENT> if not labels: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if len(labels) != self.nImage: <NEW_LINE> <INDENT> raise RuntimeError(f"You provided {len(l... | Draw the list labels at the corners of each panel.
Notes
-----
If labels is None, use the ones specified by ``Mosaic.append()`` | 625941c423e79379d52ee545 |
def split(src, join=False): <NEW_LINE> <INDENT> src = src.lstrip('\n').rstrip() <NEW_LINE> match = re.match('\s+', src) <NEW_LINE> length = len(match.group(0)) if match else 0 <NEW_LINE> result = [line[length:] for line in src.split('\n')] <NEW_LINE> if join: <NEW_LINE> <INDENT> result = '\n'.join(result) <NEW_LINE> <D... | Splits a (possibly multiline) string of Python input into
a list, adjusting for common indents.
PARAMETERS:
src -- str; (possibly) multiline string of Python input
join -- bool; if True, join output into one string
DESCRIPTION:
Indentation adjustment is determined by the first nonempty
line. The characters of indenta... | 625941c4a8ecb033257d30ad |
def get_create_sql(self, curs, new_table_name = None): <NEW_LINE> <INDENT> if not new_table_name: <NEW_LINE> <INDENT> return self.defn <NEW_LINE> <DEDENT> rx = r"\bTO[ ][a-z0-9._]+[ ]DO[ ]" <NEW_LINE> pnew = "TO %s DO " % new_table_name <NEW_LINE> return rx_replace(rx, self.defn, pnew) | Generate creation SQL. | 625941c42c8b7c6e89b357a1 |
def _get_checkout_args(self, patched_create_order): <NEW_LINE> <INDENT> return dict(zip(('request', 'user', 'course_key', 'course_mode', 'amount'), patched_create_order.call_args[0])) | Assuming patched_create_order was called, return a mapping containing the call arguments. | 625941c4d18da76e235324b4 |
def add_oxidation_state_by_guess(self, **kwargs): <NEW_LINE> <INDENT> oxid_guess = self.composition.oxi_state_guesses(**kwargs) <NEW_LINE> oxid_guess = oxid_guess or [{e.symbol: 0 for e in self.composition}] <NEW_LINE> self.add_oxidation_state_by_element(oxid_guess[0]) | Decorates the structure with oxidation state, guessing
using Composition.oxi_state_guesses()
Args:
**kwargs: parameters to pass into oxi_state_guesses() | 625941c4de87d2750b85fd71 |
def setZeroes(self, matrix): <NEW_LINE> <INDENT> index_i = [] <NEW_LINE> index_j = [] <NEW_LINE> for i in range(len(matrix)): <NEW_LINE> <INDENT> for j in range(len(matrix[i])): <NEW_LINE> <INDENT> if matrix[i][j] == 0: <NEW_LINE> <INDENT> index_i.append(i) <NEW_LINE> index_j.append(j) <NEW_LINE> <DEDENT> <DEDENT> <DED... | :type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead. | 625941c4dc8b845886cb5514 |
def __init__(self, keytype, size, privatekey, publickey, encryption_algorithm): <NEW_LINE> <INDENT> self.__size = size <NEW_LINE> self.__keytype = keytype <NEW_LINE> self.__privatekey = privatekey <NEW_LINE> self.__publickey = publickey <NEW_LINE> self.__encryption_algorithm = encryption_algorithm <NEW_LINE> try: <NEW_... | :keytype: One of rsa, dsa, ecdsa, ed25519
:size: The key length for the private key of this key pair
:privatekey: Private key object of this key pair
:publickey: Public key object of this key pair
:encryption_algorithm: Hashed secret used to encrypt the private key of this key pair | 625941c44f88993c3716c048 |
def wamp_publish(message): <NEW_LINE> <INDENT> payload = { 'topic': 'question.update', 'args': [message] } <NEW_LINE> try: <NEW_LINE> <INDENT> response = requests.post(settings.MY_WAMP_HTTP_GATEWAY, json=payload) <NEW_LINE> <DEDENT> except requests.ConnectionError as exc: <NEW_LINE> <INDENT> response = exc <NEW_LINE> <... | Making a WAMP PUB throug the http bridge.
http://crossbar.io/docs/HTTP-Bridge-Publisher/ | 625941c4b5575c28eb68dfdf |
def segment_rule_match(rules, playlist, segment): <NEW_LINE> <INDENT> non_cdn_bandwidth_key = "{0}k".format(int(playlist["bandwidth"]) / 1000) <NEW_LINE> cdn_bandwidth_key = "{0}.{1}".format(playlist["cdn"], non_cdn_bandwidth_key) <NEW_LINE> cdn_wildcard_key = "{0}.*".format(playlist["cdn"]) <NEW_LINE> wildcard_key = "... | Check if any rule matches the current segment. Generate the playlist/segment possible
rule permutation and test for rule hit. Work from more specific rules to more generic rules.
If a rule is hit, no further checks will be made. | 625941c44f6381625f114a1b |
def __init__(self, channel): <NEW_LINE> <INDENT> self.checkEventAvailability = channel.unary_unary( '/soboto.items.ItemsService/checkEventAvailability', request_serializer=CheckEventAvailabilityRequest.SerializeToString, response_deserializer=CheckEventAvailabilityResponse.FromString, ) <NEW_LINE> self.duplicateItemEve... | Constructor.
Args:
channel: A grpc.Channel. | 625941c44f6381625f114a1c |
def _handle_picks(info, picks): <NEW_LINE> <INDENT> if picks is None: <NEW_LINE> <INDENT> out = mne.pick_types(info, meg=True, eeg=True, ref_meg=False, fnirs=True, exclude='bads') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out = _picks_to_idx(info, picks, exclude='bads') <NEW_LINE> <DEDENT> return out | Pick the data channls or return picks. | 625941c473bcbd0ca4b2c056 |
def __str__(self) -> str: <NEW_LINE> <INDENT> return f"IGD Device: {self.name}/{self.udn}::{self.device_type}" | Get string representation. | 625941c4d486a94d0b98e125 |
def __extract_seq_len(self): <NEW_LINE> <INDENT> return np.array([s.shape[0] for s in self.samples], dtype=np.int32) | Returns (np.array):
List of lengths of each sequence sample in the dataset. | 625941c49c8ee82313fbb754 |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941c46aa9bd52df036d83 |
def do_EOF(self, line): <NEW_LINE> <INDENT> return True | EOF command to exit the program | 625941c46fb2d068a760f07b |
def get_day_measurements(self, day): <NEW_LINE> <INDENT> request_url = self.url + self.DAY_MEASUREMENT_URL_SUFFIX <NEW_LINE> request_url = request_url.replace('{index}', day) <NEW_LINE> try: <NEW_LINE> <INDENT> fve_response = HttpClient.get_request(request_url) <NEW_LINE> <DEDENT> except FveHttpError as error: <NEW_LIN... | Get Day Results -> 'http://192.168.2.51:8003/stat_day.xml?day={index}'
{index} - 1: yesterday
2: day before yesterday
...
List of Elements:
-> <SDD{index}> : measured day
-> <SDS4> : surplus (not consumed) by all phases L1 + L2 + L3
-> <SDH4> : consumed by... | 625941c463f4b57ef00010fd |
@timer <NEW_LINE> def part_1(program: List[int], grid_size: int = 1_0-1) -> int: <NEW_LINE> <INDENT> painting_robot = initialize_painting_robot(program, grid_size) <NEW_LINE> counter = 0 <NEW_LINE> while not painting_robot.computer.stop: <NEW_LINE> <INDENT> painting_robot.move() <NEW_LINE> counter += 1 <NEW_LINE> print... | Part 1 | 625941c4e64d504609d74820 |
def parse_url(self, url): <NEW_LINE> <INDENT> o = urlparse(url) <NEW_LINE> query = parse_qs(o.query) <NEW_LINE> stid = query['Stations'][0] <NEW_LINE> sens_num = int(query['SensorNums'][0]) <NEW_LINE> sens_name = None <NEW_LINE> for v in self.sensor_metadata.values(): <NEW_LINE> <INDENT> if sens_num == v['num']: <NEW_L... | Parse the url that was passed to CDEC. Pull out the station
id and the sensor name
Args:
url: url string with parameters
Returns:
station id and sensor name from sensor_metadata, None if not found | 625941c4711fe17d8254234f |
def on_test_batch_start(self): <NEW_LINE> <INDENT> for callback in self.callbacks: <NEW_LINE> <INDENT> callback.on_test_batch_start(self, self.get_model()) | Called when the test batch begins. | 625941c4d8ef3951e324351d |
def inside(mayor, menor): <NEW_LINE> <INDENT> return (mayor[0]<=menor[0]) and (mayor[1]>=menor[1]) | Comprueba que intervalo2 está dentro de
intervalo 1 o bien son iguales | 625941c4eab8aa0e5d26db38 |
def generate_s3_prefix_for_manifest_input_files(base_prefix, manifests_source): <NEW_LINE> <INDENT> if manifests_source.lower() == "streaming_main": <NEW_LINE> <INDENT> qualified_source = "streaming/main" <NEW_LINE> <DEDENT> elif manifests_source.lower() == "streaming_equality": <NEW_LINE> <INDENT> qualified_source = "... | Returns the qualified s3 path to the manifest input files.
Arguments:
base_prefix (string): The base prefix of all the manifest files
manifests_source (string): "streaming_main", "streaming_equality", "historic", "full or "incremental" | 625941c48a349b6b435e8153 |
def add_loss_op(self, pred): <NEW_LINE> <INDENT> out1 = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.labels_placeholder, logits=pred) <NEW_LINE> loss = tf.reduce_mean(out1) <NEW_LINE> return loss | Adds Ops for the loss function to the computational graph.
In this case we are using cross entropy loss.
The loss should be averaged over all examples in the current minibatch.
Remember that you can use tf.nn.sparse_softmax_cross_entropy_with_logits to simplify your
implementation. You might find tf.reduce_mean useful... | 625941c41b99ca400220aa91 |
def error(self, msg): <NEW_LINE> <INDENT> self.cli.print_tokens([ (Token.Pdb.Error, ' %s \n' % msg) ]) | Override default error handler from PDB. | 625941c4a4f1c619b28b001d |
def parse_date( text: Optional[str], formats: Iterable[str], default: Optional[str] = None ) -> Iterable[str]: <NEW_LINE> <INDENT> if text is None: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> parsed = parse_formats(text, formats) <NEW_LINE> if parsed.text is not None: <NEW_LINE> <INDENT> return [parsed.text] <NEW... | Parse a date two ways: first, try and apply a set of structured formats and
return a partial date if any of them parse correctly. Otherwise, apply `extract_years`
on the remaining string. | 625941c4cdde0d52a9e53012 |
def test_add_image_bad_store(self): <NEW_LINE> <INDENT> fixture_headers = {'x-image-meta-store': 'bad', 'x-image-meta-name': 'fake image #3'} <NEW_LINE> req = webob.Request.blank("/images") <NEW_LINE> req.method = 'POST' <NEW_LINE> for k, v in fixture_headers.iteritems(): <NEW_LINE> <INDENT> req.headers[k] = v <NEW_LIN... | Tests raises BadRequest for invalid store header | 625941c46fece00bbac2d71d |
def maxIncreaseKeepingSkyline(self, grid): <NEW_LINE> <INDENT> row_maxes = [0 for _ in grid] <NEW_LINE> col_maxes = [0 for _ in grid[0]] <NEW_LINE> result = 0 <NEW_LINE> for i, row in enumerate(grid): <NEW_LINE> <INDENT> for j, value in enumerate(row): <NEW_LINE> <INDENT> row_maxes[i] = max(row_maxes[i], value) <NEW_LI... | :type grid: List[List[int]]
:rtype: int | 625941c45fc7496912cc395e |
def test_delete_works_if_authorized(self): <NEW_LINE> <INDENT> aRun = Run(user=self.user, date="2011-7-22", hours=0, minutes=19, seconds=59, distance=4) <NEW_LINE> aRun.save() <NEW_LINE> self.c.login(username='user', password='pass') <NEW_LINE> status = self.c.post('/delete/1').status_code <NEW_LINE> self.assertEquals(... | Make sure the delete view returns 200 status code. | 625941c423849d37ff7b3070 |
def test_discovery_dev_type(dev): <NEW_LINE> <INDENT> dev[1].request("SET sec_device_type 1-0050F204-2") <NEW_LINE> dev[1].p2p_listen() <NEW_LINE> dev[0].p2p_find(social=True, dev_type="5-0050F204-1") <NEW_LINE> ev = dev[0].wait_event(['P2P-DEVICE-FOUND'], timeout=1) <NEW_LINE> if ev: <NEW_LINE> <INDENT> raise Exceptio... | P2P device discovery with Device Type filter | 625941c407f4c71912b11462 |
def __alt_chgat_single(self, y, x, beg, end, offset): <NEW_LINE> <INDENT> pos = self.get_cell_width(beg - offset) <NEW_LINE> siz = self.get_cell_edge(end - beg + 1) <NEW_LINE> end = pos + siz <NEW_LINE> buf = self.fileops.read(offset, self.bufmap.x) <NEW_LINE> s = self.get_form_line(buf) <NEW_LINE> d = end - len(s) <NE... | Alternative for Python 2.5 | 625941c4851cf427c661a4f1 |
def test_cannot_delete_provider_filter_more_than_once(advanced_search_view): <NEW_LINE> <INDENT> filter_name = fauxfactory.gen_alphanumeric() <NEW_LINE> assert advanced_search_view.entities.search.save_filter( "fill_count(Infrastructure Provider.VMs, >, 0)", filter_name) <NEW_LINE> assert advanced_search_view.entities.... | When Delete button appars, it does not want to go away
Polarion:
assignee: gtalreja
casecomponent: WebUI
caseimportance: medium
initialEstimate: 1/10h | 625941c4bde94217f3682dd3 |
def test_chmod_command_007(self): <NEW_LINE> <INDENT> self.proto.lineReceived(b"chmod abcd efgh") <NEW_LINE> self.assertEquals( self.tr.value(), b"chmod: invalid mode: \xe2\x80\x98abcd\xe2\x80\x99\n" + TRY_CHMOD_HELP_MSG + PROMPT ) | Invalid mode | 625941c4442bda511e8be3fb |
def directory_should_exist(self, path, msg=None): <NEW_LINE> <INDENT> path = self._absnorm(path) <NEW_LINE> matches = [p for p in glob.glob(path) if os.path.isdir(p)] <NEW_LINE> if not matches: <NEW_LINE> <INDENT> self._fail(msg, "Path '%s' does not match any directory" % path) <NEW_LINE> <DEDENT> self._link("Directory... | Fails unless the given path points to an existing directory.
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
The default error message can be overridden with the `msg` argument. | 625941c41b99ca400220aa92 |
def __get_normalization_method__(self, normalization_method: str = None): <NEW_LINE> <INDENT> if not normalization_method: <NEW_LINE> <INDENT> return self.DEFAULT_NORMALIZATION_METHOD <NEW_LINE> <DEDENT> if normalization_method != self.LEMMATIZATION and normalization_method != self.STEMMING: <NEW_LINE> <INDENT> raise V... | Returns the normalization method
:param normalization_method: Normalization method to check
:return: Normalization method | 625941c4925a0f43d2549e56 |
def compile_to_c(self, filename, list_of_Argument, fn_name=""): <NEW_LINE> <INDENT> pass | Statically compile this function to C source code. This is
useful for providing fallback code paths that will compile on
many platforms. Vectorization will fail, and parallelization
will produce serial code. | 625941c4379a373c97cfab25 |
def log(obj): <NEW_LINE> <INDENT> pp.pprint(obj) | Print out obj
:param obj: object to be printed
:return: | 625941c463b5f9789fde70c6 |
def SetIgnoreExisting(self, b: bool): <NEW_LINE> <INDENT> return _lldb.SBAttachInfo_SetIgnoreExisting(self, b) | SetIgnoreExisting(SBAttachInfo self, bool b) | 625941c43d592f4c4ed1d052 |
def test_update_user_no_data(self): <NEW_LINE> <INDENT> user = User(name="Michael", email="[email protected]") <NEW_LINE> with get_session() as DB: <NEW_LINE> <INDENT> DB.add(user) <NEW_LINE> <DEDENT> rv = self.client.put("/api/user/{0}".format(user.id)) <NEW_LINE> self.assertEqual(rv.status_code, 400) <NEW_LINE> self.a... | Test the endpoint for updating a user if no data is provided. | 625941c499cbb53fe6792bc7 |
def buildPairPosGlyphs(pairs, glyphMap): <NEW_LINE> <INDENT> p = {} <NEW_LINE> for (glyphA, glyphB), (valA, valB) in pairs.items(): <NEW_LINE> <INDENT> formatA = valA.getFormat() if valA is not None else 0 <NEW_LINE> formatB = valB.getFormat() if valB is not None else 0 <NEW_LINE> pos = p.setdefault((formatA, formatB),... | Builds a list of glyph-based pair adjustment (GPOS2 format 1) subtables.
This organises a list of pair positioning adjustments into subtables based
on common value record formats.
Note that if you are implementing a layout compiler, you may find it more
flexible to use
:py:class:`fontTools.otlLib.lookupBuilders.PairP... | 625941c4ab23a570cc250162 |
def put(self, jobinstance_id): <NEW_LINE> <INDENT> request_data = JobInstance.parser.parse_args() <NEW_LINE> try: <NEW_LINE> <INDENT> with mongo.cx.start_session() as session: <NEW_LINE> <INDENT> with session.start_transaction(): <NEW_LINE> <INDENT> job_instance = JobInstanceModel.find_by_id(jobinstance_id) <NEW_LINE> ... | Edit the participants in a job instance | 625941c482261d6c526ab47d |
def elemwise(op, *args, **kwargs): <NEW_LINE> <INDENT> meta = kwargs.pop('meta', no_default) <NEW_LINE> _name = funcname(op) + '-' + tokenize(op, kwargs, *args) <NEW_LINE> args = _maybe_from_pandas(args) <NEW_LINE> from .multi import _maybe_align_partitions <NEW_LINE> args = _maybe_align_partitions(args) <NEW_LINE> das... | Elementwise operation for dask.Dataframes | 625941c4b545ff76a8913df7 |
def filterdata(Z, filterinds, radius=1): <NEW_LINE> <INDENT> m = shape(Z)[0] <NEW_LINE> n = shape(Z)[1] <NEW_LINE> for ind in filterinds: <NEW_LINE> <INDENT> i = ind[0] <NEW_LINE> j = ind[1] <NEW_LINE> r = radius <NEW_LINE> irange = list(range(max(0, i - r), min(i + r + 1, m))) <NEW_LINE> jrange = list(range(max(0, j -... | filter data in array z, at indice tuples in list filterinds
by averaging surrounding data, ball with radius=radius in inf-norm
acts as a low-band pass filter and removes oscillatory data | 625941c45fc7496912cc395f |
def __init__( self, uri: Optional[str], protocol_info: Optional[str], import_uri: Optional[str] = None, size: Optional[str] = None, duration: Optional[str] = None, bitrate: Optional[str] = None, sample_frequency: Optional[str] = None, bits_per_sample: Optional[str] = None, nr_audio_channels: Optional[str] = None, resol... | Initialize. | 625941c42ae34c7f2600d112 |
def _show_report(self, report, action): <NEW_LINE> <INDENT> assert action is not None <NEW_LINE> if len(report): <NEW_LINE> <INDENT> total = sum( len(located_questions.qs) for located_questions in report ) <NEW_LINE> self.stdouthelper.print_blue( '\n{}了 {} 个问题:\n'.format(action, total)) <NEW_LINE> for located_questions... | Args:
report: 一个LocatedQuestions列表
action: | 625941c4d18da76e235324b5 |
def add_log(): <NEW_LINE> <INDENT> handler.emit(log_record) <NEW_LINE> handler.close() | Emit a mock log. | 625941c48da39b475bd64f53 |
def _add_transaction(self, transaction): <NEW_LINE> <INDENT> if self._share_balance == 0: <NEW_LINE> <INDENT> old_acb_per_share = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> old_acb_per_share = self._total_acb / self._share_balance <NEW_LINE> <DEDENT> proceeds = (transaction.qty * transaction.price) * transaction.e... | Adds a transaction and updates the calculated values. | 625941c4046cf37aa974cd2a |
def test_03_flow_query(self): <NEW_LINE> <INDENT> logging.info("*** test_03_flow_query ***") <NEW_LINE> if AnalyticsTest._check_skip_test() is True: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> vizd_obj = self.useFixture( AnalyticsFixture(logging, builddir, self.__class__.redis_port, self.__class__.cassandra_por... | This test starts redis,vizd,opserver and qed
It uses the test class' cassandra instance
Then it sends flow stats to the collector
and checks if flow stats can be accessed from
QE. | 625941c44527f215b584c43a |
def lista_estadocivil(request): <NEW_LINE> <INDENT> if request.user.id is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> nropag = PerzonalizacionVisual.objects.values('valor').filter(usuario= request.user.id, tipo="paginacion") <NEW_LINE> <DEDENT> except PerzonalizacionVisual.DoesNotExist: <NEW_LINE> <INDENT> n... | docstring | 625941c4656771135c3eb84d |
def save_data(df, database_filename, table_name='Table_Clean'): <NEW_LINE> <INDENT> engine = create_engine('sqlite:///' + database_filename) <NEW_LINE> df.to_sql(table_name, engine, index=False, if_exists='replace', chunksize=600) | Save data into database.
Args:
df: pandas.DataFrame. It contains disaster messages and categories that are cleaned.
database_filename: String. Dataframe is saved into this database file.
table_name: String. Dataframe is saved into this table on database. | 625941c41f5feb6acb0c4b33 |
def create_promotion(self, name, job_name, config_xml): <NEW_LINE> <INDENT> if self.promotion_exists(name, job_name): <NEW_LINE> <INDENT> raise JenkinsException('promotion[%s] already exists at job[%s]' % (name, job_name)) <NEW_LINE> <DEDENT> folder_url, short_name = self._get_job_folder(job_name) <NEW_LINE> self.jenki... | Create a new Jenkins promotion
:param name: Name of Jenkins promotion, ``str``
:param job_name: Job name, ``str``
:param config_xml: config file text, ``str`` | 625941c401c39578d7e74e1c |
def annotate_group(name, xspan, ax=None): <NEW_LINE> <INDENT> def annotate(ax, name, left, right, y, pad): <NEW_LINE> <INDENT> arrow = ax.annotate(name, xy=(left, y), xycoords='data', xytext=(right, y-pad), textcoords='data', annotation_clip=False, verticalalignment='top', horizontalalignment='center', linespacing=2.0,... | Annotates a span of the x-axis | 625941c4fff4ab517eb2f41c |
def check_post_auth(auth_user, auth_pw): <NEW_LINE> <INDENT> return auth_user == config['HTTP Auth POST']['user'] and auth_pw == config['HTTP Auth POST']['password'] | Check the HTTP basic auth credentials for a POST request adding a quote. | 625941c416aa5153ce362459 |
def clean(text_blob): <NEW_LINE> <INDENT> text_blob = text_blob.lower() <NEW_LINE> strip_emoji = wide_build_emoji(text_blob) <NEW_LINE> filter_surplus_white = re.sub(r'/s{2,}', ' ',strip_emoji) <NEW_LINE> replace_at_symbol = re.sub(r'(?<=\s)@(?=\s)','at', filter_surplus_white) <NEW_LINE> multi_seq_char_ex = r"\b.?(a{3,... | Naive implementation of sequential same-alpha chars | 625941c4d164cc6175782d2f |
def send_doumail(self, id, content='Linsir, this doumail from https://github.com/linsir/doubanrobot'): <NEW_LINE> <INDENT> if not self.auth.ck: <NEW_LINE> <INDENT> logger.error('ck is invalid!') <NEW_LINE> return False <NEW_LINE> <DEDENT> post_data = { "ck": self.auth.ck, "m_text": content, "to": id, "m_submit": "好了,寄出... | send a doumail to other. | 625941c445492302aab5e2a3 |
def setUp(self): <NEW_LINE> <INDENT> self.app = create_app(config_name="testing") <NEW_LINE> self.client = self.app.test_client <NEW_LINE> self.bucketlist = {'name': 'Go to Borabora for vacation'} <NEW_LINE> self.bucketlist_item = {'name': 'See the Hills There'} <NEW_LINE> self.bucketlist_item1 = {'name': 'Propose to H... | Define test variables and initialize app. | 625941c43317a56b86939c3d |
def __init__(self, name: 'str'): <NEW_LINE> <INDENT> self.name = name | For internal use; do not instantiate.
Use ActionType.Move, ActionType.Push, and ActionType.Pull instead. | 625941c415fb5d323cde0aee |
def add_initiators(self): <NEW_LINE> <INDENT> if self.parameters.get('initiators') == [''] or self.parameters.get('initiators') is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for initiator in self.parameters['initiators']: <NEW_LINE> <INDENT> self.modify_initiator(initiator, 'igroup-add') | Add the list of initiators to igroup
:return: None | 625941c43346ee7daa2b2d4c |
def idle_text(): <NEW_LINE> <INDENT> berlin_time = datetime.now(timezone('Europe/Berlin')) <NEW_LINE> formatted_time = berlin_time.strftime("%H:%M:%S on a %A") <NEW_LINE> text = "It is " + formatted_time + "!" <NEW_LINE> return text | Return text that is tweeted when not replying | 625941c450812a4eaa59c304 |
def _get_embed_html( self, trans, item_class, item_id ): <NEW_LINE> <INDENT> item_class = self.get_class( item_class ) <NEW_LINE> if item_class == model.History: <NEW_LINE> <INDENT> return self._get_embedded_history_html( trans, item_id ) <NEW_LINE> <DEDENT> elif item_class == model.HistoryDatasetAssociation: <NEW_LINE... | Returns HTML for embedding an item in a page. | 625941c4004d5f362079a315 |
@numba.jit(nopython=True, nogil=True) <NEW_LINE> def zoom_numbaThread(data, chunkIndices, zoomArray): <NEW_LINE> <INDENT> for i in range(chunkIndices[0], chunkIndices[1]): <NEW_LINE> <INDENT> x = i*numba.float32(data.shape[0]-1)/(zoomArray.shape[0]-0.99999999) <NEW_LINE> x1 = numba.int32(x) <NEW_LINE> for j in range(z... | 2-D zoom interpolation using purely python - fast if compiled with numba.
Both the array to zoom and the output array are required as arguments, the
zoom level is calculated from the size of the new array.
Parameters:
array (ndarray): The 2-D array to zoom
zoomArray (ndarray): The array to place the calculatio... | 625941c4377c676e9127218a |
def __init__(self, last_update_timestamp=None, rx=None, tx=None, logical_router_port_id=None, *args, **kwargs): <NEW_LINE> <INDENT> self._last_update_timestamp = None <NEW_LINE> self._rx = None <NEW_LINE> self._tx = None <NEW_LINE> self._logical_router_port_id = None <NEW_LINE> self.discriminator = None <NEW_LINE> if l... | LogicalRouterPortStatisticsSummary - a model defined in Swagger | 625941c4d58c6744b4257c41 |
def principal_order_ideal(self, x): <NEW_LINE> <INDENT> return self.order_ideal([x]) | Return the order ideal generated by an element ``x``.
This is also called the lower set generated by this element.
EXAMPLES::
sage: B = Posets.BooleanLattice(4)
sage: B.principal_order_ideal(6)
[0, 2, 4, 6] | 625941c491af0d3eaac9b9f8 |
@before.each_scenario <NEW_LINE> def before_each_scenario(scenario): <NEW_LINE> <INDENT> world.product_list_with_attributes = list() <NEW_LINE> world.paas_product_list_with_attributes = list() | Lettuce Hook. Will be executed before each scenario. Init global scenario vars. | 625941c430c21e258bdfa47d |
def test_repr(self, new_dimension_conflict): <NEW_LINE> <INDENT> assert repr(new_dimension_conflict) == "New new" | Verify the representation of conflict for user interface | 625941c4498bea3a759b9a91 |
def main(): <NEW_LINE> <INDENT> app = QtGui.QApplication(sys.argv) <NEW_LINE> window = gui.MainWindow.MainWindow() <NEW_LINE> window.show() <NEW_LINE> sys.exit(app.exec_()) | main application loop | 625941c4566aa707497f454d |
def premier_indice_exh_rec(lst, elem): <NEW_LINE> <INDENT> if not lst: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if lst[0] == elem: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> indice = premier_indice_exh_rec(lst[1:], elem) <NEW_LINE> return 1 + indice if indice is not None else ... | Parcours la liste et retourne le plus indice de l'élement ou
None si celui-ci n'est pas trouvé.
:param lst: Liste à parcourir.
:param elem: Élément à rechercher.
:return: Indice de l'élément ou None.
>>> premier_indice_exh_rec([2, 2, 3, 4, 5], 3)
2 | 625941c4711fe17d82542350 |
def calculate_weights(r_sample): <NEW_LINE> <INDENT> n_sample = len(r_sample) <NEW_LINE> weights = np.zeros(n_sample) <NEW_LINE> for i in range(n_sample): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> r_outer = r_sample[0] <NEW_LINE> r_inner = 0.5*(r_sample[1] + r_sample[0]) <NEW_LINE> <DEDENT> elif i == (n_sample... | Calculates weights proportional to volume of spherical shell closest to
each sample. | 625941c4fbf16365ca6f61a2 |
def update_many(self, instances: list[SQLModel], session: Session) -> list[SQLModel]: <NEW_LINE> <INDENT> return self.create_many(instances, session, refresh=True) | Update `instances` in db | 625941c499fddb7c1c9de373 |
def findFileInDir(folder, namekeys): <NEW_LINE> <INDENT> for filename in os.listdir(folder): <NEW_LINE> <INDENT> status = True <NEW_LINE> for key in namekeys: <NEW_LINE> <INDENT> if key not in filename: <NEW_LINE> <INDENT> status = False <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if status: <NEW_LINE> <INDENT> retur... | find a file with keys in filename under dir, It will not go into subfolders.
:param folder:
:param namekeys:
:return: | 625941c4091ae35668666f42 |
def get_transition_matrix(user_interest_set): <NEW_LINE> <INDENT> transition_matrix = np.zeros((num_clusters, num_clusters)) <NEW_LINE> for src_state in range(num_clusters): <NEW_LINE> <INDENT> transition_matrix[src_state] = get_transition_probability( user_interest_set, src_state) <NEW_LINE> <DEDENT> return transition... | Returns the transition matrix of a user given user_interest_set. | 625941c41f037a2d8b9461e0 |
def setup_app(command, conf, vars): <NEW_LINE> <INDENT> if not pylons.test.pylonsapp: <NEW_LINE> <INDENT> load_environment(conf.global_conf, conf.local_conf) | Place any commands to setup webui here | 625941c4eab8aa0e5d26db39 |
def range( start, stop, step=None ): <NEW_LINE> <INDENT> if step is None: <NEW_LINE> <INDENT> step = UnitDbl( 1, start._units ) <NEW_LINE> <DEDENT> elems = [] <NEW_LINE> i = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> d = start + i * step <NEW_LINE> if d >= stop: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> elems.app... | Generate a range of UnitDbl objects.
Similar to the Python range() method. Returns the range [
start, stop ) at the requested step. Each element will be a
UnitDbl object.
= INPUT VARIABLES
- start The starting value of the range.
- stop The stop value of the range.
- step Optional step to use. If se... | 625941c4a17c0f6771cbe033 |
def set_calibration_constant(self, coeff, value): <NEW_LINE> <INDENT> pass | Syntax: WC <Coeff> <Value>
Function: Change the calibration constant indicated by "Coeff" with "Value"
Input: Coeff = 0-13 (0-5 are accelerometer constant, 6-B are magnetometer constant) Value = 0-FFFF (C-D Temp Constant)
E.G.: WC 0 1111 --> change the first constant (Gxmean) value to "1111" | 625941c4a05bb46b383ec805 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.