code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _assert_if_none_match(request: web.Request, etag: T.Union[None, bool, str], allow_weak: bool) -> bool: <NEW_LINE> <INDENT> etags = _parse_if_header(request, _IF_NONE_MATCH) <NEW_LINE> if etags is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if etag is False or etag is None: <NEW_LINE> <... | Todo:
Evert lammerts schreef: Documenteren. Ik vind _assert_if_none_match niet
makkelijk te lezen zonder docs voor de parameters. Bv: etag heeft als
type None, bool, of str. En if etag is True: PreconditionFailed. Die
semantiek is vast logisch in context maar niet op zichzelf.
The If-None-Match: header... | 625941ea5fdd1c0f98dc06f4 |
def send(self, data, force=False): <NEW_LINE> <INDENT> if self._registered or force: <NEW_LINE> <INDENT> self._sock.send('%s\r\n' % data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._out_buffer.append(data) | Send raw data over the wire if connection is registered. Otherewise,
save the data to an output buffer for transmission later on.
If the force flag is true, always send data, regardless of
registration status. | 625941eaad47b63b2c50a43d |
def __init__(self, configuration): <NEW_LINE> <INDENT> self.configuration = configuration <NEW_LINE> self.raw_benford_output = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0} <NEW_LINE> self.item_count = 0 | :param configuration: is a dictionary with the configuration values. It looks like:
{
'file_name': '',
'numeric_column': ''
} | 625941ea50485f2cf553d25a |
def processEvent(self, sgEvent): <NEW_LINE> <INDENT> self.writeMessage(self.formatMessage(sgEvent)) | Processes the event and writes a formatted string to the handlers stream.
Args:
* (SgEvent) sgEvent:
Event to process. | 625941ea66656f66f7cbc66b |
def genpxd(template, header=None, ts=None): <NEW_LINE> <INDENT> ts = ts or TypeSystem() <NEW_LINE> pxdfuncs = dict([(k[7:], v) for k, v in globals().items() if k.startswith('genpxd_') and callable(v)]) <NEW_LINE> pxd = _pxdheader if header is None else header <NEW_LINE> with ts.swap_stlcontainers(Non... | Returns a string of a pxd file representing the given template. | 625941eaa4f1c619b28b04ec |
def degree(spline): <NEW_LINE> <INDENT> return [p-1 for p in spline.order()] | Returns polynomial degree (splipy order - 1) for all parametric directions | 625941eacc0a2c11143dd350 |
def test_1_EigenFaceTrain(self): <NEW_LINE> <INDENT> ilog = None <NEW_LINE> if 'ilog' in globals().keys(): <NEW_LINE> <INDENT> ilog = globals()['ilog'] <NEW_LINE> <DEDENT> ef = self.trainScraps(ilog=ilog) <NEW_LINE> self.assertEqual(ef.eigenvalues.shape[0],53) <NEW_LINE> self.assertEqual(ef.eigenbasis.shape[0],53) <NEW... | Eigenfaces: Training Checks...................................... | 625941eafff4ab517eb2f8fe |
def prepare_labels(self): <NEW_LINE> <INDENT> assert 'Id' in self.df.columns <NEW_LINE> values = np.array(self.df['Id']) <NEW_LINE> label_encoder = LabelEncoder() <NEW_LINE> integer_encoded = label_encoder.fit_transform(values) <NEW_LINE> onehot_encoder = OneHotEncoder(sparse=False) <NEW_LINE> integer_encoded = integer... | Returns a vectorized np.array that contains the class for each picture
The self.df should have a column named 'Id'
Returns
-------
one_hot_encoded_labels : np.array in a vectorized form (n_images, n_classes)
label_encoder : to be used in case we need to find the original class name | 625941eaf548e778e58cda3e |
def climbStairs(self, n): <NEW_LINE> <INDENT> if n == 1: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> dp = [0 for col in range(n)] <NEW_LINE> dp[0] = 1 <NEW_LINE> dp[1] = 2 <NEW_LINE> for i in range(2, n): <NEW_LINE> <INDENT> dp[i] = dp[i-1] + dp[i-2] <NEW_LINE> <DEDENT> return dp[n-1] | :type n: int
:rtype: int | 625941ea851cf427c661a9c9 |
def _get_log(): <NEW_LINE> <INDENT> logger = logging.getLogger('PyWebStatMon') <NEW_LINE> logger.setLevel(logging.CRITICAL) <NEW_LINE> ch = logging.StreamHandler() <NEW_LINE> ch.setLevel(logging.DEBUG) <NEW_LINE> ch.setFormatter(_get_formatter()) <NEW_LINE> logger.addHandler(ch) <NEW_LINE> return logger | Set up a basic logger | 625941ea9b70327d1c4e1296 |
def sample_batch(X_train,y_train,batch_size): <NEW_LINE> <INDENT> N = X_train.shape[0] <NEW_LINE> ind_N = np.random.choice(N,batch_size,replace=False) <NEW_LINE> X_batch = X_train[ind_N] <NEW_LINE> y_batch = y_train[ind_N] <NEW_LINE> return X_batch,y_batch | Function to sample a batch for training | 625941ea63b5f9789fde75a5 |
def _log_request(self): <NEW_LINE> <INDENT> self.log('method={0}, path={1}, client={2}, user={3}, group={4}, key={5}, token={6}, data={7}'.format( self.method, self.path, self.client, self.USER.name, self.USER.group, self.key, self.token, truncate(str(self.data)) ), level='debug', method='_log_request') | Log incoming requests to the request log. | 625941ea7b180e01f3dc4cb2 |
def test_multi_dim_train_weights_wrong_inner_dim(self): <NEW_LINE> <INDENT> head = head_lib._binary_logistic_head_with_sigmoid_cross_entropy_loss( weight_column='weights') <NEW_LINE> logits = np.array([[[10], [-10]], [[12], [-12]]], dtype=np.float32) <NEW_LINE> labels = np.array([[[0], [0]], [[1], [1]]], dtype=np.float... | Logits and labels of shape [2, 2, 1], weights [2, 1]. | 625941ea4f88993c3716c521 |
def _do_read(self, selector, deadline): <NEW_LINE> <INDENT> selector.modify(self._socket, selectors.EVENT_READ) <NEW_LINE> results = selector.select(deadline.remaining_time()) <NEW_LINE> if not results: <NEW_LINE> <INDENT> raise BlockingIOError() <NEW_LINE> <DEDENT> assert len(results) == 1 <NEW_LINE> assert results[0]... | A helper method that performs a read from the network and passes the
data into the receive buffer. | 625941ea3c8af77a43ae3c65 |
def test_successful_subscriptions_notifies_pm(self): <NEW_LINE> <INDENT> invitee = self.example_email("iago") <NEW_LINE> current_stream = self.get_streams(invitee)[0] <NEW_LINE> invite_streams = self.make_random_stream_names([current_stream])[:1] <NEW_LINE> result = self.common_subscribe_to_streams( invitee, invite_str... | Calling POST /json/users/me/subscriptions should notify when a new stream is created. | 625941ea16aa5153ce362937 |
def __init__(self, logger): <NEW_LINE> <INDENT> self._logger = logger <NEW_LINE> self._task = misc.utility.create_task(logger=logger) <NEW_LINE> self._solution = misc.utility.create_solution() <NEW_LINE> self._communication_helper = misc.communication.CommunicationHelper( logger=logger) | Initialization. | 625941eae1aae11d1e74a17b |
def __init__(self, session, user_input, view): <NEW_LINE> <INDENT> self.session = session <NEW_LINE> self.user_input = user_input <NEW_LINE> self.view = view | Instance initializer
| 625941eaa05bb46b383eccdc |
def collate_python(witnesses, algorithm): <NEW_LINE> <INDENT> dekcol = collatex.Collation() <NEW_LINE> input_d = dict(witnesses=witnesses, algorithm=algorithm) <NEW_LINE> if FUZZY_EDIT_DISTANCE: <NEW_LINE> <INDENT> input_d['tokenComparator'] = {"type": "levenshtein", "distance": FUZZY_EDIT_DISTANCE} <NEW_LINE> <DEDENT>... | Collate using collatex-python | 625941ea30bbd722463cc288 |
def test_exceptionsRaisedFromReceiver(self): <NEW_LINE> <INDENT> transport = FakeTransport() <NEW_LINE> self.protocol.makeConnection(transport) <NEW_LINE> self.protocol.dataReceived('e') <NEW_LINE> self.failIfEqual(self.protocol.receiver.lossReason, None) <NEW_LINE> self.assertTrue( isinstance(self.protocol.receiver.lo... | Raising an exception from receiver methods called from the grammar
propagate to finishParsing. | 625941ead18da76e2353299b |
def test_align_help(): <NEW_LINE> <INDENT> pytest.debug_func() <NEW_LINE> cmd = pexpect.which("align") <NEW_LINE> result = pexpect.run("%s --help" % cmd) <NEW_LINE> nexp = "Traceback" <NEW_LINE> assert nexp not in result <NEW_LINE> exp = "Align columns from input" <NEW_LINE> assert exp in result | Verify that 'align --help' does the right thing | 625941eaff9c53063f47c6b0 |
def testZDeletePlacement(self): <NEW_LINE> <INDENT> delete_placement.main(client, self.__class__.ad_group_id, self.__class__.placement_id) | Tests whether we can delete a placement. | 625941eacad5886f8bd27497 |
def parse(self, data): <NEW_LINE> <INDENT> print(data) | Dummy method to be replaced | 625941ea6e29344779a62acf |
def aw(self, _pinNum, _val): <NEW_LINE> <INDENT> if 0 <= _pinNum <= (ArduinoSim._numAnalogs - 1): <NEW_LINE> <INDENT> self._analogPins[_pinNum].write(_val) | Writes the value to the corresponding analog pin instance only if the pin number is in the correct range. | 625941ea10dbd63aa1bd3061 |
def get_device(name='auto'): <NEW_LINE> <INDENT> if name == 'auto': <NEW_LINE> <INDENT> return torch.device('cuda' if torch.cuda.is_available() else 'cpu') <NEW_LINE> <DEDENT> return torch.device(name) | choose device
Returns:
the device specified by name, if name is None, proper device will be returned | 625941ead268445f265b532e |
def test_not_digits(self): <NEW_LINE> <INDENT> digits = ['1', '2', 'd', '%' ] <NEW_LINE> for digit in digits: <NEW_LINE> <INDENT> result = is_leap_year(digit) <NEW_LINE> self.assertEqual(result, False) | Validate not using digits | 625941ead58c6744b425811d |
def __init__(self, type=None, url=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._type = None <NEW_LINE> self._url =... | PushNotificationSoundSchemaUrl - a model defined in OpenAPI | 625941eaaad79263cf390f07 |
def metrics(self): <NEW_LINE> <INDENT> from prometheus_client.parser import text_string_to_metric_families <NEW_LINE> return text_string_to_metric_families(self.metrics_raw()) | get the modelized metrics parsed by prometheus_client | 625941ea7d847024c06be77f |
def make1DHist(data, name, title, caption, xTitle, yTitle, outputDir, nbins, xmax, xmin=0): <NEW_LINE> <INDENT> hist = ROOT.TH1I(name, title, nbins, xmin, xmax) <NEW_LINE> hist.SetXTitle(xTitle) <NEW_LINE> hist.SetYTitle(yTitle) <NEW_LINE> import array <NEW_LINE> hist.FillN(len(data), array.array('d',data), array.array... | Create 1D ROOT Histogram plot, save to file.
args:
data - 1-D sequence of data
name - should be valid as part of a filename
title - short title (can contain spaces)
caption - can be longer & can contain any characters.
xTitle - x axis title
yTitle - y axis title
outputDir - output directory for image file.
nbins - num... | 625941ea3346ee7daa2b322f |
def subscribeEvent(self, symbol): <NEW_LINE> <INDENT> contract = self.mainEngine.getContract(symbol) <NEW_LINE> if not contract: <NEW_LINE> <INDENT> self.writeLog(u'行情订阅失败,找不到合约:%s' %symbol) <NEW_LINE> return <NEW_LINE> <DEDENT> vtSymbol = contract.vtSymbol <NEW_LINE> req = VtSubscribeReq() <NEW_LINE> req.symbol = cont... | 订阅对应合约的事件 | 625941eab5575c28eb68e4c4 |
def create_team(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> name = self.get_argument('team_name', '') <NEW_LINE> motto = self.get_argument('motto', '') <NEW_LINE> if Team.by_name(name) is not None: <NEW_LINE> <INDENT> raise ValidationError("Team already exists") <NEW_LINE> <DEDENT> team = Team() <NEW_LINE> team... | Admins can create teams manually | 625941eafbf16365ca6f668d |
def _GetEthernet(self): <NEW_LINE> <INDENT> result = sub.Popen('ifconfig | cut -d\' \' -f 1 | grep eth', stdout=sub.PIPE, shell=True).communicate() <NEW_LINE> self.assertNotEqual(result[0], '', msg='Not connected to Ethernet.') <NEW_LINE> self._ethernet = result[0].rstrip() | Get the ethernet to which the device is connected. | 625941ea7047854f462a18c3 |
def extractParsedTweet(parsedTweet): <NEW_LINE> <INDENT> hashtags = [tweet['text'] for tweet in parsedTweet['entities']['hashtags']] <NEW_LINE> timeStamp = int(time.mktime( time.strptime(parsedTweet['created_at'][0:20] + parsedTweet['created_at'][26:], '%a %b %d %H:%M:%S %Y'))) <NEW_LINE> return timeStamp, hashtags | This function reads a tweet parsed from input file and extract hastags and created_at field from the tweet.
:param parsedTweet: tweet parsed from input file.
:return:
hashtags - list of hashtags from parsed tweet.
timestamp - convert extracted created_at field to seconds. | 625941eae5267d203edce156 |
def set_up(entrypoint_service_name: str, entrypoint_service_namespace: str, archive_url: str) -> None: <NEW_LINE> <INDENT> with tempfile.TemporaryDirectory() as tmp_dir_path: <NEW_LINE> <INDENT> archive_path = os.path.join(tmp_dir_path, 'istio.tar.gz') <NEW_LINE> _download(archive_url, archive_path) <NEW_LINE> extracte... | Installs Istio from the archive URL.
Requires Helm client to be present.
This downloads and extracts the archive in a temporary directory, then
installs the resources via `helm template` and `kubectl apply`. | 625941eaeab8aa0e5d26e019 |
def is_fresh(self, access_mode): <NEW_LINE> <INDENT> log.debug("[#0000] C: <ROUTING> Checking table freshness for %r", access_mode) <NEW_LINE> expired = self.last_updated_time + self.ttl <= self.timer() <NEW_LINE> has_server_for_mode = bool(access_mode == READ_ACCESS and self.readers) or bool(access_mode == WRITE_ACCE... | Indicator for whether routing information is still usable.
| 625941ea67a9b606de4a8376 |
def getNeighborsPos(pos): <NEW_LINE> <INDENT> global neighborsObj <NEW_LINE> neighbors = [] <NEW_LINE> for t in [[0,0,1],[0,1,0],[1,0,0],[0,0,-1],[0,-1,0],[-1,0,0]]: <NEW_LINE> <INDENT> test = [pos[0]+t[0],pos[1] + t[1],pos[2]+t[2]] <NEW_LINE> if max(test) <= 2 and min(test) >= 0: <NEW_LINE> <INDENT> neighbors.append(t... | get all neighbors of a position | 625941ead6c5a1020814450e |
def select_source_dir(self, *args, **kwargs): <NEW_LINE> <INDENT> fpath = str(QtWidgets.QFileDialog.getExistingDirectory( self, "Séléctionner le chemin de la clé USB")) <NEW_LINE> self.source_dir = "/".join((fpath, 'Dossiers')) if fpath and 'Dossiers' in os.listdir(fpath) else None <NEW_LINE> self.action_but... | show folder picker and update `source_dir` and select_feedback | 625941eabe8e80087fb210fb |
def gen_positions(array): <NEW_LINE> <INDENT> posiciones = [] <NEW_LINE> r, c = array.shape <NEW_LINE> for row in range(r): <NEW_LINE> <INDENT> for column in range(c): <NEW_LINE> <INDENT> if array[row, column] == 1: <NEW_LINE> <INDENT> posiciones.append((column, row)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass ... | Generates a list with the positions of live cells | 625941eae64d504609d74cff |
def testCaptureWithExposureZero(self): <NEW_LINE> <INDENT> self._switchToBurstFast() <NEW_LINE> self._setExposureStatus('0') <NEW_LINE> self._captureAndCheck() | Summary:testCaptureWithExposureZero: Take burst piture with exposure 0
Steps: 1.Launch burst activity
2.Check exposure setting icon ,set to 0
3.Touch shutter button to capture burst picture
4.Exit activity | 625941eaf8510a7c17cf9bbf |
@contextmanager <NEW_LINE> def bake_in_temp_dir(cookies, *args, **kwargs): <NEW_LINE> <INDENT> result = cookies.bake(*args, **kwargs) <NEW_LINE> try: <NEW_LINE> <INDENT> yield result <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> rmtree(str(result.project)) | Bakes cookies in a temporary directory. Cleans up after itself (I think) | 625941ea82261d6c526ab966 |
def versioned_minter(pid_type='recid', object_type='rec', parent_minter=None): <NEW_LINE> <INDENT> parent_minter = parent_minter or default_parent_minter <NEW_LINE> def decorator(child_minter): <NEW_LINE> <INDENT> @wraps(child_minter) <NEW_LINE> def wrapper(record_uuid=None, data=None): <NEW_LINE> <INDENT> parent = (da... | Parameterized minter decorator for automatic versioning.
This decorator can be applied to any minter function. in order to introduce
record versioning through the `relations` metadata key. | 625941ea60cbc95b062c6a03 |
def child_edges(self, term): <NEW_LINE> <INDENT> self._cache_validate() <NEW_LINE> term = self.term(term) <NEW_LINE> return self._related_to.get(term, []) | Return a list of (rel_type, source_term) tuples. | 625941ea5fcc89381b1e1b82 |
def transform(self, x): <NEW_LINE> <INDENT> if self._scaler is not None: <NEW_LINE> <INDENT> x = self._scaler.transform(x) <NEW_LINE> <DEDENT> return self._encoder.predict(x) | :param x:
:return: | 625941ea5e10d32532c5f3e5 |
def showSuccess(self,pos,newpos,showState=True): <NEW_LINE> <INDENT> trace = False and not g.unitTesting <NEW_LINE> c = self.c ; p = self.p.copy() <NEW_LINE> if not p: <NEW_LINE> <INDENT> return g.trace('can not happen: self.p is None') <NEW_LINE> <DEDENT> insert = g.choose(self.reverse,min(pos,newpos),max(pos,newpos))... | Display the result of a successful find operation. | 625941ea6e29344779a62ad0 |
def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.key_order = ['title', 'id', 'icon', 'panel', 'theme', '...', 'cards'] <NEW_LINE> super().__init__(**kwargs) | Init view. | 625941ea4a966d76dd5514d4 |
@task() <NEW_LINE> @skip_if_no_change("sonar", expect_files="sonar.json") <NEW_LINE> @timed() <NEW_LINE> def sonar() -> None: <NEW_LINE> <INDENT> do_sonar() | Lint using remote sonar service | 625941ea21bff66bcd684e0d |
def get_employees_names(self): <NEW_LINE> <INDENT> list_of_employees = [employee._first_name + ' ' + employee._surname for employee in self._employees] <NEW_LINE> for sub_dept_id in self._sub_depts: <NEW_LINE> <INDENT> list_of_employees.extend(self._organization._departments[sub_dept_id].get_employees_names()) <NEW_LIN... | :return: a list of employees' names | 625941ea7c178a314d6ef927 |
def send_file_old(self, target, client_soc): <NEW_LINE> <INDENT> if not os.access(target, os.R_OK): <NEW_LINE> <INDENT> raise OSError('Unable to access file: %s' % target) <NEW_LINE> <DEDENT> file = open(target, 'r') <NEW_LINE> chunk = '' <NEW_LINE> count = 0 <NEW_LINE> packet_no = 0 <NEW_LINE> for line in file: <NEW_L... | This will open a file and put it into a list
each element will be a string with the maximum size
that was specified in the variable self.packet_len | 625941ea379a373c97cfb006 |
def save_environ(path='c:/Prog'): <NEW_LINE> <INDENT> suffixe = time.strftime('%Hh%Mm%Ss_%d_%B_20%y') <NEW_LINE> path = os.path.join(path, 'path_' + suffixe + '.json') <NEW_LINE> file = open(path, 'w') <NEW_LINE> file.write('{\n\t' + str(os.environ)[9:-2].replace('\'', '"') .replace('",', '",\n\t').replac... | Export environment variables in JSON
:param path: path where the json file wil be created
:return: full path to created file | 625941ea76e4537e8c351b36 |
def filter(self, result): <NEW_LINE> <INDENT> if result is None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> reject = ( result in self.history ) <NEW_LINE> if reject: <NEW_LINE> <INDENT> log.debug('result %s, rejected by\n%s', Repr(result), self) <NEW_LINE> <DEDENT> return reject | Filter the specified result based on query criteria.
@param result: A potential result.
@type result: L{sxbase.SchemaObject}
@return: True if result should be excluded.
@rtype: boolean | 625941ea3cc13d1c6d3c7838 |
def _google_highlight_diffs(old, new): <NEW_LINE> <INDENT> textdiff = u"" <NEW_LINE> removed = u"" <NEW_LINE> diff = differencer.diff_main(old, new) <NEW_LINE> differencer.diff_cleanupSemantic(diff) <NEW_LINE> for op, text in diff: <NEW_LINE> <INDENT> if op == 0: <NEW_LINE> <INDENT> if removed: <NEW_LINE> <INDENT> text... | Highlights the differences between old and new. | 625941ea99fddb7c1c9de84e |
def word_count(df, column, sort='ascending', **kwargs): <NEW_LINE> <INDENT> assert isinstance(df, pd.DataFrame), "Pass a DataFrame" <NEW_LINE> assert column in df, "The column is not present in the DataFrame, pass a valid column name" <NEW_LINE> if 'stopwords' in kwargs.keys(): <NEW_LINE> <INDENT> assert (isinstance(kw... | Take the count of unique words
Parameters
----------
df : DataFrame
The df to perform case operation on.
column : string, int
The column selected should be present in the Dataframe passed
sort : string, default ascending
Options: ascending, descending
If sorted, it will sort values by the count
stopwor... | 625941ea377c676e91272667 |
def disable_frame_rendered_callback(self): <NEW_LINE> <INDENT> self.check_validity() <NEW_LINE> self.ipcon.send_request(self, BrickletLEDStrip.FUNCTION_DISABLE_FRAME_RENDERED_CALLBACK, (), '', 0, '') | Disables the :cb:`Frame Rendered` callback.
By default the callback is enabled.
.. versionadded:: 2.0.6$nbsp;(Plugin) | 625941ea6fece00bbac2dc05 |
def _create_349_refund_records(self, refunds): <NEW_LINE> <INDENT> if not refunds: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.ensure_one() <NEW_LINE> partner_detail_obj = self.env[ 'l10n.es.aeat.mod349.partner_record_detail'] <NEW_LINE> obj = self.env['l10n.es.aeat.mod349.partner_refund'] <NEW_LINE> obj_... | Creates restitution records in 349. All refunds must be for the
same partner and operation key. | 625941ea5fdd1c0f98dc06f5 |
def query_users_from_emails(self, emails): <NEW_LINE> <INDENT> return phlcon_user.query_users_from_emails(self._conduit, emails) | Return a list of username strings based on the provided emails.
If an email does not correspond to a username then None is inserted in
its place.
:emails: a list of strings corresponding to user email addresses
:returns: a list of strings corresponding to Phabricator usernames | 625941ea38b623060ff0b2ad |
def _changed_packages_activity_query(): <NEW_LINE> <INDENT> import ckan.model as model <NEW_LINE> q = model.Session.query(model.Activity) <NEW_LINE> q = q.filter(model.Activity.activity_type.endswith('package')) <NEW_LINE> return q | Return an SQLAlchemyu query for all changed package activities.
Return a query for all activities with activity_type '*package', e.g.
'new_package', 'changed_package', 'deleted_package'. | 625941ead268445f265b532f |
def update(self, disease): <NEW_LINE> <INDENT> d = self.index(disease) <NEW_LINE> if self.c[d] <= 0: <NEW_LINE> <INDENT> return(False) <NEW_LINE> <DEDENT> elif self.c[d] == 1: <NEW_LINE> <INDENT> if not rolldie(disease.r): <NEW_LINE> <INDENT> self.c[d] = -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.c[d] = 0 <N... | Daily status update. | 625941ea293b9510aa2c3751 |
def transform(self): <NEW_LINE> <INDENT> instances, features = CocoNgrams.transform(self) <NEW_LINE> return(instances, features) | Model transformer
=====
Function to featurize instances based on the fitted features | 625941ea26068e7796caf1a7 |
def _load_usernames(self, users=None): <NEW_LINE> <INDENT> status_query = Q(status__in=CertificateStatuses.PASSED_STATUSES) <NEW_LINE> course_run_query = reduce( lambda x, y: x | y, [Q(course_id=course_run.key, mode=course_run.type) for course_run in self.course_runs] ) <NEW_LINE> for course_run in self.course_runs: <N... | Identify a subset of users who may be eligible for a program certificate.
This is done by finding users who have earned a qualifying certificate in
at least one program course's course run. | 625941ea4e696a04525c990e |
def bubble_pressure(box, elements, out_fmt, header, dr, time, container, debug=False): <NEW_LINE> <INDENT> for eles in elements: <NEW_LINE> <INDENT> e = ''.join(eles) <NEW_LINE> print("Bubble pressure stats for {e}\n".format(e=e)) <NEW_LINE> bubble_pressure = box.pressure_stats(eles, dr) <NEW_LINE> outname = out_fmt.fo... | Calculate bubble pressure and write results to disk. | 625941eaf7d966606f6aa4ca |
def test_effect_of_strategy_with_history_CC(self): <NEW_LINE> <INDENT> P1 = axelrod.GradualKiller() <NEW_LINE> P2 = axelrod.Player() <NEW_LINE> P1.history = [D, D, D, D, D, C, C] <NEW_LINE> P2.history = [C, C, C, C, C, D, D] <NEW_LINE> self.assertEqual(P1.strategy(P2), 'D') <NEW_LINE> P1.history = [D, D, D, D, D, C, C,... | Continues with D if opponent played DD on 6 and 7. | 625941ea004d5f362079a7f0 |
def num_channels(framefile): <NEW_LINE> <INDENT> return len(get_channel_names(framefile)) | Find the total number of channels in this framefile
**Requires:** |LDAStools.frameCPP|_
Parameters
----------
framefile : `str`
path to GWF-format file on disk
Returns
-------
n : `int`
the total number of channels found in the table of contents for this
file | 625941ea66673b3332b92551 |
def shortest_path(source, target): <NEW_LINE> <INDENT> debut = Node(state=source, parent=None, action=None) <NEW_LINE> frontier = QueueFrontier() <NEW_LINE> frontier.add(debut) <NEW_LINE> explored = set() <NEW_LINE> explored_count = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> if frontier.empty(): <NEW_LINE> <INDENT> r... | Returns the shortest list of (movie_id, person_id) pairs
that connect the source to the target.
If no possible path, returns None. | 625941ea283ffb24f3c55dbd |
def test_ordinal(self): <NEW_LINE> <INDENT> tests = [ (1, '1st'), (2, '2nd'), (3, '3rd'), (4, '4th'), (5, '5th'), ] <NEW_LINE> for value, expected in tests: <NEW_LINE> <INDENT> self.assertEqual( expected, template.Template( '{{ %s | ordinal }}' % value, self.hass).render()) | Test the ordinal filter. | 625941eaa05bb46b383eccdd |
def eliminate(values): <NEW_LINE> <INDENT> solved_values = [box for box in values.keys() if len(values[box]) == 1] <NEW_LINE> for box in solved_values: <NEW_LINE> <INDENT> digit = values[box] <NEW_LINE> for peer in peers[box]: <NEW_LINE> <INDENT> values[peer] = values[peer].replace(digit,'') <NEW_LINE> <DEDENT> <DEDENT... | ----------------------------------------------------------------------
This section was taken from the previous lesson "Applying AI to Sudoku"
-----------------------------------------------------------------------
Eliminate values from peers of each box with a single value.
Go through all the boxes, and whenever ther... | 625941eae5267d203edce157 |
def select_cumulative(self, metric): <NEW_LINE> <INDENT> p = "PARTITION BY {}".format(self.id_col) <NEW_LINE> if not self.group_by_id: <NEW_LINE> <INDENT> p = "" <NEW_LINE> <DEDENT> s = "sum({name}) OVER ({p} ORDER BY {date_col} ASC) AS {name}" <NEW_LINE> return s.format(p=p, **self.add_kw(**metric)) | A select statement to make a count metric cumulative. | 625941ea8c3a873295158881 |
def interrupt_thread(thread): <NEW_LINE> <INDENT> for thread_id, frame in sys._current_frames().items(): <NEW_LINE> <INDENT> if thread_id == thread.ident: <NEW_LINE> <INDENT> set_trace_for_frame_and_parents(frame, throw_signal_function) <NEW_LINE> while thread in [t for t in threading.enumerate()]: <NEW_LINE> <INDENT> ... | Interrupt a thread using :py:func:`throw_signal_function`. | 625941ea7cff6e4e81117e46 |
def db_for_read(self, model, **hints): <NEW_LINE> <INDENT> if model._meta.db_table not in self.default_database_tables: <NEW_LINE> <INDENT> return self.data_database <NEW_LINE> <DEDENT> return None | @param model:
@param hints:
@return: | 625941ea3346ee7daa2b3230 |
def delete_account_receive_table(): <NEW_LINE> <INDENT> return db_instance.delete_table(AccountReceive) | 清空表
:return: | 625941eabaa26c4b54cb15db |
def setup_platform(hass, config, add_entities, discovery_info=None): <NEW_LINE> <INDENT> if discovery_info is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> data = hass.data[SENSE_DATA] <NEW_LINE> sense_devices = data.get_discovered_device_data() <NEW_LINE> devices = [SenseDevice(data, device) for device in sense... | Set up the Sense sensor. | 625941ea956e5f7376d7132c |
def crimes(self): <NEW_LINE> <INDENT> results = self.crimes_base.list() <NEW_LINE> return { 'results': results } | Crimes list | 625941ea55399d3f05588b78 |
def coefficients(self, potential) -> T.Optional[T.Dict[str, T.Any]]: <NEW_LINE> <INDENT> coeffs = None <NEW_LINE> if isinstance(potential, gpot.SCFPotential): <NEW_LINE> <INDENT> coeffs = dict( type="SCF", Acos=potential._Acos, Asin=potential._Asin, ) <NEW_LINE> <DEDENT> elif isinstance(potential, gpot.DiskSCFPotential... | Coefficients of the potential.
Parameters
----------
potential : :class:`~galpy.potential.Potential`
The potential.
Returns
-------
None or dict
None if there aren't coefficients, a dict of the coefficients
if there are. | 625941eacdde0d52a9e534f7 |
def add_volume_to_storage_group( self, serial_number, device_id, storagegroup_name, volume_name, extra_specs, force=False): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> @coordination.synchronized("emc-sg-{sg_name}-{serial_number}") <NEW_LINE> def do_add_volume_to_sg(sg_name, serial_number): <NEW_LINE> <INDEN... | Add a volume to a storage group.
:param serial_number: array serial number
:param device_id: volume device id
:param storagegroup_name: storage group name
:param volume_name: volume name
:param extra_specs: extra specifications
:param force: add force argument to call | 625941ea66673b3332b92552 |
def __call__(self): <NEW_LINE> <INDENT> CMPFUNC = CFUNCTYPE(None, c_int, c_int, POINTER(c_double), POINTER(c_double)) <NEW_LINE> callback = CMPFUNC(self._callback) <NEW_LINE> solutions = numpy.zeros([self.mu*self.n_var]) <NEW_LINE> if self.bounds[0] is None: <NEW_LINE> <INDENT> lbound = None <NEW_LINE> <DEDENT> else: <... | Method to start the optimizer. During the optimization process a file
called pareto.dat is written.
Returns:
numpy.ndarray holding the solutions found by the optimizer | 625941ea596a897236089f7a |
def GetPointer(self): <NEW_LINE> <INDENT> return _itkMattesMutualInformationImageToImageMetricPython.itkMattesMutualInformationImageToImageMetricIUL2IUL2_GetPointer(self) | GetPointer(self) -> itkMattesMutualInformationImageToImageMetricIUL2IUL2 | 625941ea30c21e258bdfa963 |
def convertXMLElement( geometryOutput, xmlElement, xmlProcessor ): <NEW_LINE> <INDENT> xmlProcessor.createChildren( geometryOutput, xmlElement ) | Convert the xml element to a group xml element. | 625941ea96565a6dacc8fb8a |
def change_ownership(self, crawl_run_id, owner_id): <NEW_LINE> <INDENT> result = None <NEW_LINE> try: <NEW_LINE> <INDENT> response = apicore.object_store_change_ownership( api_key=self._api_key, object_type='crawlrun', object_id=crawl_run_id, owner_id=owner_id) <NEW_LINE> if response.status_code == requests.codes.ok: <... | Changes the ownership of a crawl run
:param crawl_run_id: Object id of the crawl run
:param owner_id: User id to change ownership
:return: response | 625941ea1f037a2d8b9466bd |
def export_curves_data_as_csv(cds: List[mmodels.CurveData]) -> io.StringIO: <NEW_LINE> <INDENT> cdict = {} <NEW_LINE> explen = len(cds) <NEW_LINE> for i, cd in enumerate(cds): <NEW_LINE> <INDENT> for x, y in zip(cd.xVector, cd.yVector): <NEW_LINE> <INDENT> tmp = cdict.get(x, [None] * explen) <NEW_LINE> tmp[i] = y <NEW_... | Turn a list of CurveData instances into CSV file. | 625941ea66656f66f7cbc66d |
def calc_check_digit(number): <NEW_LINE> <INDENT> alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' <NEW_LINE> cutoff = lambda x: x - 9 if x > 9 else x <NEW_LINE> s = sum( cutoff(alphabet.index(n) * 2) if i % 2 == 0 else alphabet.index(n) for i, n in enumerate(number[::-1])) <NEW_LINE> return str((10 - s) % 10) | Calculate the check digit for the number. | 625941eabd1bec0571d90aef |
def set_xticklabels(self, labels, fontdict=None, minor=False, **kwargs): <NEW_LINE> <INDENT> if fontdict is not None: <NEW_LINE> <INDENT> kwargs.update(fontdict) <NEW_LINE> <DEDENT> ret = self.xaxis.set_ticklabels(labels, minor=minor, **kwargs) <NEW_LINE> self.stale = True <NEW_LINE> return ret | Set the xtick labels with list of string labels
Parameters
----------
labels : list of str
list of string labels
Returns
-------
A list of `~matplotlib.text.Text` instances
Other Parameters
-----------------
**kwargs : `~matplotlib.text.Text` properties. | 625941ea45492302aab5e789 |
def get_negative_object_property_values(self, ontology): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for ax in ontology.get_negative_object_property_assertion_axioms(self): <NEW_LINE> <INDENT> inds = result.get(ax.property) <NEW_LINE> if inds is None: <NEW_LINE> <INDENT> inds = set() <NEW_LINE> result[ax.property] = ind... | Gets the object property values that are explicitly asserted NOT to
hold for this individual
:param ontology: The owlapy.model.OWLOntology that should be examined
for axioms
:return: A dictionary containing the negative object property values | 625941ea6aa9bd52df037268 |
def with_tracking(transformer: tp.Type[cst.CSTTransformer]) -> tp.Type[cst.CSTTransformer]: <NEW_LINE> <INDENT> return type(transformer.__name__, (_NodeTrackerMixin, transformer), {}) | Helper function than adds tracking to a transformer type | 625941eab830903b967e9dc6 |
def get_produto(self, ncm, ncm_ex): <NEW_LINE> <INDENT> raise NotImplementedError() | Obtém as alíquotas para um produto conforme seu NCM/SH e exceção.
As implementações de provisionamento deverão sobrescrever este método
para obter os dados do provisionamento ou do web services do IBPT,
quando não houver um provisionamento disponível.
:param str ncm: O código NCM/SH do produto.
:param int ncm_ex: A ex... | 625941ea596a897236089f7b |
def _find_stdev_threshold_sal(dwords, stdevs): <NEW_LINE> <INDENT> allsal = [] <NEW_LINE> for obj in dwords: <NEW_LINE> <INDENT> allsal.append(obj['sal']) <NEW_LINE> <DEDENT> stdev = statistics.stdev(allsal) <NEW_LINE> outlier_thr = (stdev*stdevs)+sum(allsal)/len(allsal) <NEW_LINE> return outlier_thr | dword is an object like {'word':w, 'bias':bias, 'biasW':biasW, 'freq':freq, 'freqW':freqW, 'sal':val, 'wv':wv, 'sent':sent }
stdevs : minimum stdevs for which we want to compute the threshold
returns
outlier_thr : the threshold correpsonding to stdevs considering salience values from the dwrods object list | 625941ea8e05c05ec3eea839 |
def __init__(self): <NEW_LINE> <INDENT> logger.debug('Constructing GeneratorBase.') | Constructor. | 625941eaa219f33f34628e23 |
def check_df(self, df): <NEW_LINE> <INDENT> if len(df) == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if df.index.freqstr != 'D': <NEW_LINE> <INDENT> if df.index.freqstr is not None: <NEW_LINE> <INDENT> print("Wrong frequency of the index: '{}' (instead of 'D')".format(df.index.freqstr)) <NEW_LINE> return F... | Verify that the dataframe is acceptable as a daily aggregation variable
Arguments
---------
df : pandas DataFrame
Returns
--------
True/False
Return False when the dataframe is empty or when the index does not have a daily frequency | 625941ea16aa5153ce362939 |
def devices_from_config(domain_config, hass=None): <NEW_LINE> <INDENT> devices = [] <NEW_LINE> for device_id, config in domain_config[CONF_DEVICES].items(): <NEW_LINE> <INDENT> if CONF_TYPE in config: <NEW_LINE> <INDENT> entity_type = config.pop(CONF_TYPE) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> entity_type = ent... | Parse configuration and add Rflink light devices. | 625941eabd1bec0571d90af0 |
def cvt_pt_Q_to_V(Q): <NEW_LINE> <INDENT> return rot.Vector(Q.q1,Q.q2,Q.q3) | Converts a pure (pointing) Q to a unit position Vector | 625941ea8e05c05ec3eea83a |
def create_bucket( self, Bucket=None): <NEW_LINE> <INDENT> log.info( f'mock - MockBotoS3.create_bucket(Bucket={Bucket})') <NEW_LINE> return self.buckets.add( bucket_name=Bucket) | create_bucket
:param bucket_name: name of the new bucket | 625941ea442bda511e8be8d2 |
def get_exe_location(self): <NEW_LINE> <INDENT> return self.__binary_location | @summary: Returns the location of the Crypter exe that was built | 625941ea94891a1f4081bf6c |
def _check_previous_process(self): <NEW_LINE> <INDENT> if not self.pid_file or not os.path.exists(self.pid_file): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> pid_file = os.path.abspath(self.pid_file) <NEW_LINE> self.log.warning("Found proxy pid file: %s", pid_file) <NEW_LINE> try: <NEW_LINE> <INDENT> with open(pid_f... | Check if there's a process leftover and shut it down if so | 625941ea2eb69b55b151cd77 |
def __init__(self, pool_idx_array): <NEW_LINE> <INDENT> super(GraphUnpooling, self).__init__() <NEW_LINE> self.pool_x1 = pool_idx_array[:, 0] <NEW_LINE> self.pool_x2 = pool_idx_array[:, 1] | Initialisation
Args:
pool_idx_array (tensor): vertex IDs that should be comined to new
vertices | 625941eaa219f33f34628e24 |
def doneTurn(): <NEW_LINE> <INDENT> return None | C++ signature:
void doneTurn()
:rtype None | 625941eacdde0d52a9e534f8 |
def fancy_rename(oldname, newname): <NEW_LINE> <INDENT> if not os.path.exists(newname): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.rename(oldname, newname) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> (fd, tmpfile) = tempfile.... | Rename file with temporary backup file to rollback if rename fails | 625941ea796e427e537b0a8b |
def shift_rows(self, b): <NEW_LINE> <INDENT> b[1], b[5], b[ 9], b[13] = b[ 5], b[ 9], b[13], b[ 1] <NEW_LINE> b[2], b[6], b[10], b[14] = b[10], b[14], b[ 2], b[ 6] <NEW_LINE> b[3], b[7], b[11], b[15] = b[15], b[ 3], b[ 7], b[11] | ShiftRows step. Shifts 2nd row to left by 1, 3rd row by 2, 4th row by 3
Since we're performing this on a transposed matrix, cells are numbered
from top to bottom first::
0 4 8 12 -> 0 4 8 12 -- 1st row doesn't change
1 5 9 13 -> 5 9 13 1 -- row shifted to left by 1 (wraps around)
2 6 10... | 625941ea15baa723493c443a |
def get_autotb_parameters(file: str) -> List[str]: <NEW_LINE> <INDENT> assert os.path.isfile(file) <NEW_LINE> assert file.endswith(".autotb.v") <NEW_LINE> with open(file, "r") as f: <NEW_LINE> <INDENT> lines = f.readlines() <NEW_LINE> <DEDENT> lines = [line.strip() for line in lines] <NEW_LINE> start_line = next( i for... | Read interface from autotb files. | 625941ea0fa83653e4657479 |
def test_index_page_renders_index_template(self): <NEW_LINE> <INDENT> response = self.client.get('/') <NEW_LINE> self.assertEqual(response.status_code,200) <NEW_LINE> self.assertTemplateUsed(response,'index.html') | 测试index视图 | 625941eabe7bc26dc91cdab8 |
def getNextPmapColor(self): <NEW_LINE> <INDENT> return None | Return a QColor to use for the next crop. | 625941ea293b9510aa2c3752 |
def set_level(self, level, name=None): <NEW_LINE> <INDENT> if name is not None: <NEW_LINE> <INDENT> name = self._get_log_name(name) <NEW_LINE> logger = self._loggers.get(name) <NEW_LINE> if logger is not None: <NEW_LINE> <INDENT> logger.setLevel(level) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._defaul... | Change the log level of the logging
:param level: the level of the logging to be setLevel
:param name: the name of the logging to set, in case it is not set,
all the loggers will be affected | 625941eab5575c28eb68e4c6 |
def md5_sum(path): <NEW_LINE> <INDENT> with open(path, mode="rb") as bfile: <NEW_LINE> <INDENT> return hashlib.md5(bfile.read()).hexdigest() | Computes the MD5 sum of the specified file. | 625941ead58c6744b425811f |
def format_line(address, data): <NEW_LINE> <INDENT> data += padding(16 - len(data)) <NEW_LINE> hexdata = [] <NEW_LINE> for byte in data: <NEW_LINE> <INDENT> if byte is not None: <NEW_LINE> <INDENT> elem = f'{byte:02x}' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> elem = ' ' <NEW_LINE> <DEDENT> hexdata.append(elem) <N... | `data` is a list of integers and None for unused elements.
| 625941eaa79ad161976cc607 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.