code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def extract_tgz(self): <NEW_LINE> <INDENT> if self.verbosity > 2: <NEW_LINE> <INDENT> print('DEBUG: Extracting %s to %s.' % (self.local_archive, self.tempdir)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> tar = tarfile.open(self.local_archive, 'r:gz') <NEW_LINE> <DEDENT> except tarfile.TarError: <NEW_LINE> <INDENT> pri... | Extract NEWS.tgz archive into temporary directory. | 625941c3a8ecb033257d309f |
def convert_unixdate(day, month, year, escape=True): <NEW_LINE> <INDENT> if escape: <NEW_LINE> <INDENT> day, month, year = (get_int(i) for i in [day, month, year]) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> ret = int(time.mktime(datetime.date(year, month, day).timetuple())) <NEW_LINE> <DEDENT> except: <NEW_LINE> <IND... | Returns the unixtime corresponding to the beginning of the specified date; if
the date is not valid, None is returned. | 625941c3d7e4931a7ee9deef |
def start(self): <NEW_LINE> <INDENT> QtCore.QThreadPool.globalInstance().start(self) | Start the Asynchronous task by passing this class to global thread
pool instance
| 625941c3167d2b6e31218b68 |
def create(self, **kwargs): <NEW_LINE> <INDENT> raise self.AdapterMethodNotImplementedError( 'The `create` method is not implemented by this adapter.' ) | Creates a new statement matching the keyword arguments specified.
Returns the created statement. | 625941c32c8b7c6e89b35793 |
def fix_logo_padding(self): <NEW_LINE> <INDENT> header_base = 53 <NEW_LINE> portal = getToolByName(self.context, 'portal_url').getPortalObject() <NEW_LINE> view = portal.restrictedTraverse('customlogo', None) <NEW_LINE> if view: <NEW_LINE> <INDENT> blob = view.get_logo(headers=False) <NEW_LINE> if blob: <NEW_LINE> <IND... | Get the images height to fix the padding in the header.
Checks if the header is big and uses another height to calculate
padding. | 625941c3442bda511e8be3ec |
def _get_loss( self, logits: torch.Tensor, targets: torch.Tensor, target_mask: torch.Tensor ) -> torch.Tensor: <NEW_LINE> <INDENT> target_lengths = torch.sum(target_mask, dim=-1).float() <NEW_LINE> return target_lengths * sequence_cross_entropy_with_logits( logits, targets, target_mask, average=None ) | Compute cross entropy loss of predicted caption (logits) w.r.t. target caption. The cross
entropy loss of caption is cross entropy loss at each time-step, summed.
Parameters
----------
logits: torch.Tensor
A tensor of shape ``(batch_size, max_caption_length - 1, vocab_size)`` containing
unnormalized log-probab... | 625941c315fb5d323cde0adf |
def __sub__(self, vector): <NEW_LINE> <INDENT> if(len(self)!=len(vector)): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> subtracted_vector=[] <NEW_LINE> for i in range(0,len(self)): <NEW_LINE> <INDENT> subtracted_vector.append(self[i]-vector[i]) <NEW_LINE> <DEDENT> return subtracted_vector | Return the difference of this vector with another 'vector' (allows use of - operator between vectors)
Use the make_vector function to instantiate the appropriate subclass of Vector
Assumes that the elements of the vectors have a - operator defined between them (if they are not numbers)
If the lengths of this and 'vecto... | 625941c31d351010ab855aee |
def __init__(self, H0, Om0, Ode0, Tcmb0=2.725, Neff=3.04, name='LambdaCDM'): <NEW_LINE> <INDENT> FLRW.__init__(self, H0, Om0, Ode0, Tcmb0, Neff, name=name) | Initializer.
Parameters
----------
H0 : float
Hubble constant in [km/sec/Mpc] at z=0
Om0 : float
Omega matter: density of non-relativistic matter in units
of the critical density at z=0.
Ode0 : float
Omega dark energy: density of the cosmological constant in units
of the critical density at z=0.
Tcmb0 : f... | 625941c3e8904600ed9f1efd |
def is_module_name(spec) : <NEW_LINE> <INDENT> return spec is not None and spec != "" | Anything can be a module name | 625941c33617ad0b5ed67ecb |
def random_spd(p, eig_min, cond, random_state=0): <NEW_LINE> <INDENT> random_state = check_random_state(random_state) <NEW_LINE> mat = random_state.randn(p, p) <NEW_LINE> unitary, _ = linalg.qr(mat) <NEW_LINE> diag = random_diagonal(p, v_min=eig_min, v_max=cond * eig_min, random_state=random_state) <NEW_LINE> return un... | Generate a random symmetric positive definite matrix.
Parameters
----------
p : int
The first dimension of the array.
eig_min : float
Minimal eigenvalue.
cond : float
Condition number, defined as the ratio of the maximum eigenvalue to the
minimum one.
random_state : int or numpy.random.RandomState i... | 625941c3e5267d203edcdc71 |
def zeropoint(self,filterset,band): <NEW_LINE> <INDENT> return self._filtersets[filterset][band].zp() | Return all the zero point of a given Band and FilterSet, as astropy Quantity | 625941c3be7bc26dc91cd5d5 |
def resample(df, intervals='1H'): <NEW_LINE> <INDENT> df = df.resample(intervals).mean() <NEW_LINE> return df | Resamples the data frame to a given interval | 625941c34e4d5625662d43ac |
def sigmoid(x_value): <NEW_LINE> <INDENT> return 1.0 / (1 + math.exp(-x_value)) | Compute sigmoid. | 625941c321bff66bcd684926 |
def waitForReadyRead(self, msecs = 30000): <NEW_LINE> <INDENT> return bool() | bool QSslSocket.waitForReadyRead(int msecs = 30000) | 625941c392d797404e30415b |
def get_bibid(docid, lookup=BIBID_LOOKUP_PATH): <NEW_LINE> <INDENT> with open(lookup, "rb") as f: <NEW_LINE> <INDENT> lookup_data = json.load(f) <NEW_LINE> <DEDENT> return next((item['bibid'] for item in lookup_data if item["docid"] == str(docid)), None) | Look up bibid based on lookup table.
Args:
docid (int): Proquest docid
lookup (uri, optional): Local path to lookup table. Defaults to BIBID_LOOKUP_PATH JSON file.
Returns:
int: BIBID | 625941c310dbd63aa1bd2b76 |
def validate(self): <NEW_LINE> <INDENT> success = True <NEW_LINE> msg = "" <NEW_LINE> acked = self.producer.acked <NEW_LINE> consumed = self.consumer.messages_consumed[1] <NEW_LINE> missing = set(acked) - set(consumed) <NEW_LINE> self.logger.info("num consumed: %d" % len(consumed)) <NEW_LINE> if len(missing) > 0: <NEW... | Check that each acked message was consumed. | 625941c3b5575c28eb68dfd1 |
def qdii(self, min_volume=0): <NEW_LINE> <INDENT> self.__qdii_url = self.__qdii_url.format(ctime=int(time.time())) <NEW_LINE> rep = requests.get(self.__qdii_url) <NEW_LINE> fundjson = json.loads(rep.text) <NEW_LINE> data = self.formatjisilujson(fundjson) <NEW_LINE> data = {x: y for x, y in data.items() if y["notes"] !=... | 以字典形式返回QDII数据
:param min_volume:最小交易量,单位万元 | 625941c30a366e3fb873e7eb |
def generate_username(): <NEW_LINE> <INDENT> username = uuid.uuid4().hex[:30] <NEW_LINE> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> User.objects.get(username=username) <NEW_LINE> username = uuid.uuid4().hex[:30] <NEW_LINE> <DEDENT> <DEDENT> except User.DoesNotExist: <NEW_LINE> <INDENT> pass <NEW_LINE> <DE... | Generate a random and unique username using the uuid library
Also consider uniqueness by comparing with existing user names in db. | 625941c3d486a94d0b98e117 |
def setup_grid(self): <NEW_LINE> <INDENT> self.g=self.hydro.grid() <NEW_LINE> self.gd=self.g.create_dual(center='centroid') <NEW_LINE> self.N=self.gd.Nnodes() | Initialize spatial information | 625941c3be383301e01b545b |
def updateLink(self): <NEW_LINE> <INDENT> number = self.selectedLinkA or self.selectedLinkB or self.selectedResidueA or self.selectedResidueB <NEW_LINE> if not number: <NEW_LINE> <INDENT> self.emptyPeakTable() <NEW_LINE> return <NEW_LINE> <DEDENT> dataModel = self.dataModel <NEW_LINE> resNumber = self.resultsResidueNum... | Checks for any selected link (self.selectedLinkA or self.selectedLinkB) and calls
updatePeakTable with the correct residue Object and spinsystem Objects. | 625941c3de87d2750b85fd63 |
def bandwidth(self, channel): <NEW_LINE> <INDENT> channel = str(channel) <NEW_LINE> try: <NEW_LINE> <INDENT> return self.channel_to_bandwidth[channel] <NEW_LINE> <DEDENT> except KeyError as error: <NEW_LINE> <INDENT> self.logger.debug(error) <NEW_LINE> raise ArgumentError("Invalid Channel: {0}".format(channel)) <NEW_LI... | Gets a mode appropriate for the channel, based on T/H's defaults
:param:
- `channel`: integer (or string) WiFi channel (e.g. 11)
:return: string of form 'HT(20|40)[MINUS|PLUS]
:raise: ArgumentError if invalid (DFS channels not allowed) | 625941c3cdde0d52a9e53003 |
def md5(self): <NEW_LINE> <INDENT> if self._modified_m or not hasattr(self, '_hashed_md5'): <NEW_LINE> <INDENT> if self.flags['C_CONTIGUOUS']: <NEW_LINE> <INDENT> self._hashed_md5 = md5(self).hexdigest() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._hashed_md5 = md5( np.ascontiguousarray(self)).hexdigest() <NEW_L... | Return an MD5 hash of the current array.
Returns
-----------
md5 : str
Hexadecimal MD5 of the array | 625941c355399d3f05588685 |
def modular_exponent(a, d, n): <NEW_LINE> <INDENT> a = a % n <NEW_LINE> i = 0 <NEW_LINE> tmp = 1 <NEW_LINE> for i in range(len(bin(d)) - 2): <NEW_LINE> <INDENT> tmp *= a ** (d & (2**i)) <NEW_LINE> tmp %= n <NEW_LINE> <DEDENT> return tmp | Returns a to the power of d modulo n
Parameters
----------
a : The exponential's base.
d : The exponential's exponent.
n : The exponential's modulus.
Returns
-------
b: such that b == (a**d) % n | 625941c3097d151d1a222e2d |
def updatePositionAndClean(self): <NEW_LINE> <INDENT> self.pos <NEW_LINE> cleanTileAtPosition(self.pos) | Simulate the raise passage of a single time-step.
Move the robot to a new position and mark the tile it is on as having
been cleaned. | 625941c3fb3f5b602dac3664 |
def isinstance(x, A_tuple): <NEW_LINE> <INDENT> pass | Return whether an object is an instance of a class or of a subclass thereof.
A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
or ...`` etc. | 625941c36aa9bd52df036d75 |
def __len__(self): <NEW_LINE> <INDENT> return _OWL.stl_vector_owlrigid___len__(self) | __len__(self) -> size_type | 625941c357b8e32f5248346c |
def test_graph_link_dirs_at_node(): <NEW_LINE> <INDENT> graph = Graph((NODE_Y, NODE_X), links=NODES_AT_LINK, sort=True) <NEW_LINE> assert_array_equal( graph.link_dirs_at_node, [[-1, -1, 0], [-1, -1, 1], [-1, 1, 0], [-1, 1, 0], [-1, 1, 1], [1, 1, 0]], ) | Test links directions at nodes without rotational sorting. | 625941c38a349b6b435e8145 |
def set_number(self): <NEW_LINE> <INDENT> pool = Pool() <NEW_LINE> Period = pool.get('account.period') <NEW_LINE> Sequence = pool.get('ir.sequence.strict') <NEW_LINE> Date = pool.get('ir.date') <NEW_LINE> if self.number: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> test_state = True <NEW_LINE> if self.type == 'in': <... | Set number to the invoice | 625941c3b7558d58953c4ee9 |
def get_wildcard_filter(pattern): <NEW_LINE> <INDENT> regex = _get_regex(pattern) <NEW_LINE> def _filter(path, stat_info): <NEW_LINE> <INDENT> return regex.match(os.path.basename(path)) is not None <NEW_LINE> <DEDENT> return _filter | Return a filter for "walk" based on a wildcard pattern a la fnmatch. | 625941c330bbd722463cbd96 |
def my_random_string(string_length=10): <NEW_LINE> <INDENT> random = str(uuid.uuid4()) <NEW_LINE> random = random.upper() <NEW_LINE> random = random.replace("-", "") <NEW_LINE> return random[0:string_length] | Returns a random string of length string_length. | 625941c3f548e778e58cd54f |
def fileno(self): <NEW_LINE> <INDENT> return self._socket.fileno() | Return the fileno of the socket.
| 625941c34527f215b584c42b |
def configure_connector(): <NEW_LINE> <INDENT> logging.debug("creating or updating kafka connect connector...") <NEW_LINE> resp = requests.get(f"{KAFKA_CONNECT_URL}/{CONNECTOR_NAME}") <NEW_LINE> if resp.status_code == 200: <NEW_LINE> <INDENT> logging.debug("connector already created skipping recreation") <NEW_LINE> ret... | Starts and configures the Kafka Connect connector | 625941c3009cb60464c63385 |
def choi_matrix(gate, mxBasis): <NEW_LINE> <INDENT> return _tools.jamiolkowski_iso(gate, mxBasis, mxBasis) | Choi matrix | 625941c33d592f4c4ed1d044 |
def do_file_hide(self, line): <NEW_LINE> <INDENT> done = False <NEW_LINE> for index, f in enumerate(self.files): <NEW_LINE> <INDENT> if f.file_name_short == line: <NEW_LINE> <INDENT> if not f.active: <NEW_LINE> <INDENT> print("File %s is already hidden" % line) <NEW_LINE> return <NEW_LINE> <DEDENT> f.active = False <NE... | Hide a specific file | 625941c3cdde0d52a9e53004 |
def __iter__(self): <NEW_LINE> <INDENT> countries = self.countries <NEW_LINE> for code in self.countries_first: <NEW_LINE> <INDENT> yield (code, force_text(countries[code])) <NEW_LINE> <DEDENT> if (self.countries_first and settings.COUNTRIES_FIRST_BREAK): <NEW_LINE> <INDENT> yield ('', force_text(settings.COUNTRIES_FIR... | Iterate through countries, sorted by name.
Each country record consists of a tuple of the two letter ISO3166-1
country code and short name.
The sorting happens based on the thread's current translation.
Countries that are in ``settings.COUNTRIES_FIRST`` will be displayed
before any sorted countries (in the order pro... | 625941c3eab8aa0e5d26db2a |
def update(self, instance, validated_data): <NEW_LINE> <INDENT> instance.title = validated_data.get('title', instance.title) <NEW_LINE> instance.code = validated_data.get('code', instance.code) <NEW_LINE> instance.linenos = validated_data.get('linenos', instance.linenos) <NEW_LINE> instance.language = validated_data.ge... | 更新并返回存在的‘Snippet’实例,提供validated数据
:param instance:
:param validated_data:
:return: | 625941c38a349b6b435e8146 |
def test_task_detail(self): <NEW_LINE> <INDENT> url = reverse('task_retrieve', kwargs={'pk': self.task.id}) <NEW_LINE> response = self.client.get(url, format='json') <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_200_OK) | Ensure we can detail task. | 625941c3fff4ab517eb2f40d |
@_create_slack.register(str) <NEW_LINE> def _create_slack_with_string(string: str) -> NoReturn: <NEW_LINE> <INDENT> raise TypeError("Use layabout.Token or layabout.EnvVar instead of str") | Direct users to prefer :obj:`Token` and :obj:`EnvVar` over strings. | 625941c3e64d504609d74812 |
def start(self): <NEW_LINE> <INDENT> self.socket.bind(self.addr) <NEW_LINE> self.socket.listen() <NEW_LINE> print(f'[[LISTENING]] server is listening on {self.host}') <NEW_LINE> while 1: <NEW_LINE> <INDENT> conn, addr = self.socket.accept() <NEW_LINE> threading.Thread(target = self.handle_client, args = (conn, addr)).s... | Start running the server | 625941c38a43f66fc4b54039 |
@main.route('/news-and-updates/news', methods=['GET']) <NEW_LINE> def news(): <NEW_LINE> <INDENT> posts = Posts.query.filter_by(post_type='news', deleted=False).all() <NEW_LINE> tags_counter = {} <NEW_LINE> for tag in choices.TAGS: <NEW_LINE> <INDENT> tags_counter[tag] = 0 <NEW_LINE> <DEDENT> for post in posts: <NEW_LI... | View function to handle the news landing page
Renders the page as empty then uses ajax to fill in the post rows
:return: HTML template for news landing page | 625941c3379a373c97cfab16 |
def _do_layout(self, data): <NEW_LINE> <INDENT> c = data['output'] <NEW_LINE> word_space = c.text_width( ' ', font_name=self.font_name, font_size=self.font_size) <NEW_LINE> self._layout = [[]] <NEW_LINE> x = self.font_size if self.paragraph_indent else 0 <NEW_LINE> for word in self.text.split(): <NEW_LINE> <INDENT> ww ... | Lays the text out into separate lines and calculates their
total height. | 625941c315baa723493c3f46 |
def reviews(self, params): <NEW_LINE> <INDENT> return self.request('/reviews', params) | :see http://developer.jamendo.com/v3.0/reviews
:param {Object} params.A query string object
:param {Function} callback The request callback(error, response_body)
:return {Object} The JSON response | 625941c3a934411ee3751666 |
def Associate(self, ftype, ext): <NEW_LINE> <INDENT> assoc = self.get(ftype, None) <NEW_LINE> exts = ext.strip().split() <NEW_LINE> if assoc: <NEW_LINE> <INDENT> for x in exts: <NEW_LINE> <INDENT> if x not in assoc: <NEW_LINE> <INDENT> assoc.append(x) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> asso... | Associate a given file type with the given file extension(s).
The ext parameter can be a string of space separated extensions
to allow for multiple associations at once.
@param ftype: file type description string
@param ext: file extension to associate | 625941c3fbf16365ca6f6193 |
def predict(self, X): <NEW_LINE> <INDENT> num_test = len(X) <NEW_LINE> Ypred = [0 * num_test] <NEW_LINE> for i in range(num_test): <NEW_LINE> <INDENT> p1 = picture.Picture(self.X_train[i]) <NEW_LINE> distances = distance.Manhattan() | :param X: X is an N x D array where each row i in N is an example. Each example (image) consists of D / 3
pixels. Each pixel contains an R, G, and B value where each is between 0 and 255.
:param y: A 1 dimensional array of size N.
:return: None | 625941c3cc40096d61595923 |
def __init__(self, cmd, jobtype='generic', shorttag=None, checkfiles=[], checkfilesstart=[], ncores=1, queue=None): <NEW_LINE> <INDENT> self.cmd = cmd <NEW_LINE> self.jobtype = jobtype <NEW_LINE> self.verbose = 1 <NEW_LINE> self.ncores = ncores <NEW_LINE> self.queue = queue <NEW_LINE> self.shorttag = shorttag <NEW_LINE... | Create an object for job definitions
Arguments:
cmd (str): command to be executed
jobtype (str)
checkfiles (list, optional): the job is complete when all files are present
checkfilesstart (list, optional): the job is can be executed if each of the files in the list is present
ncores (int): number o... | 625941c3379a373c97cfab17 |
def likelihood(self, x, collapsed_format=False, **kwargs): <NEW_LINE> <INDENT> latents = x <NEW_LINE> if collapsed_format is False: <NEW_LINE> <INDENT> N, C, H, W = latents.size() <NEW_LINE> latents = latents.permute(1,0,2,3) <NEW_LINE> shape = latents.shape <NEW_LINE> latents = torch.reshape(latents, (shape[0],1,-1)) ... | Expected input: (N,C,H,W) | 625941c3ec188e330fd5a775 |
def detect_inline_hooks(self): <NEW_LINE> <INDENT> pe = pe_vtypes.PE(image_base=self.plugin_args.image_base, address_space=self.session.GetParameter( "default_address_space"), session=self.session) <NEW_LINE> pfn_db = self.session.profile.get_constant_object("MmPfnDatabase") <NEW_LINE> heuristic = HookHeuristic(session... | A Generator of hooked exported functions from this PE file.
Yields:
A tuple of (function, name, jump_destination) | 625941c3925a0f43d2549e48 |
def greet(request): <NEW_LINE> <INDENT> random_record = get_random_motif() <NEW_LINE> template_dict = dict(TF_name = random_record.TF_name, TF_accession = random_record.TF_accession, organism = random_record.species_name, genome_accession = random_record.genome_accession, aligned_sites = random_record.align_sites(), cu... | Handler for the main page!
It grabs a random motif from the database to display on the main page. | 625941c3e1aae11d1e749c88 |
def set_table(self, table_number): <NEW_LINE> <INDENT> lists.table = ('Table ' + str(table_number) + '\n') <NEW_LINE> lists.table_set = True <NEW_LINE> self.table_window.delete(1.0, 'end') <NEW_LINE> self.display_table_info() | Sets table based on button selected and displays in GUI | 625941c3d486a94d0b98e118 |
@pytest.fixture(scope="session") <NEW_LINE> def client(): <NEW_LINE> <INDENT> client = sc.AuthClient(*ah.get_auth_client_params()) <NEW_LINE> yield client | Set up a Smartcar Auth Client with test parameters.
Default test parameters include default scope of permissions,
which matches that of Chevrolet. Default test brand for this
client will be Chevrolet.
Yields:
client(smartcar.AuthClient)
A smartcar auth client that can be used across all tests. | 625941c363b5f9789fde70b8 |
def _do_search(self, sqp, query, search_restriction, dbcache, book_ids=None): <NEW_LINE> <INDENT> if isinstance(search_restriction, bytes): <NEW_LINE> <INDENT> search_restriction = search_restriction.decode('utf-8') <NEW_LINE> <DEDENT> if isinstance(query, bytes): <NEW_LINE> <INDENT> query = query.decode('utf-8') <NEW_... | Do the search, caching the results. Results are cached only if the
search is on the full library and no virtual field is searched on | 625941c371ff763f4b54965b |
def _load_urllib(self, filename, kwargs): <NEW_LINE> <INDENT> print ('original filename: {0}'.format(filename)) <NEW_LINE> if PY2: <NEW_LINE> <INDENT> import urllib2 as urllib_request <NEW_LINE> def gettype(info): <NEW_LINE> <INDENT> the_info = info.gettype() <NEW_LINE> print ('gettype info: {0}'.format(the_info)) <NEW... | (internal) Loading a network file. First download it, save it to a
temporary file, and pass it to _load_local(). | 625941c30a50d4780f666e64 |
def test_mask_to_parent(self): <NEW_LINE> <INDENT> K = 3 <NEW_LINE> Z = Categorical(np.ones(K)/K, plates=(4,5)) <NEW_LINE> Mu = GaussianARD(0, 1, shape=(2,), plates=(4,K,5)) <NEW_LINE> Alpha = Gamma(1, 1, plates=(4,K,5,2)) <NEW_LINE> X = Mixture(Z, GaussianARD, Mu, Alpha, cluster_plate=-2) <NEW_LINE> Y = GaussianARD(X,... | Test the mask handling in Mixture node | 625941c32ae34c7f2600d104 |
def power_basis_ancestor(self): <NEW_LINE> <INDENT> if isinstance(self, PowerBasis): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> c = self.parent <NEW_LINE> if c is not None: <NEW_LINE> <INDENT> return c.power_basis_ancestor() <NEW_LINE> <DEDENT> return None | Return the :py:class:`~.PowerBasis` that is an ancestor of this module.
See Also
========
Module | 625941c33317a56b86939c2f |
def _receive_reply(self, reply_pkg, timeout): <NEW_LINE> <INDENT> sig_handler = scarab.SignalHandler() <NEW_LINE> sig_handler.add_cancelable(self._receiver) <NEW_LINE> result = self._receiver.wait_for_reply(reply_pkg, timeout) <NEW_LINE> sig_handler.remove_cancelable(self._receiver) <NEW_LINE> return result | internal helper method to standardize receiving reply messages | 625941c39b70327d1c4e0da7 |
def __repr__(self): <NEW_LINE> <INDENT> return 'Path('+repr(self._s)+')' | Representation of Path object. | 625941c382261d6c526ab470 |
def testEzsigndocumentGetWordsPositionsV1Request(self): <NEW_LINE> <INDENT> pass | Test EzsigndocumentGetWordsPositionsV1Request | 625941c316aa5153ce36244c |
def test_is_correct(self): <NEW_LINE> <INDENT> correct = run.is_correct(3,3) <NEW_LINE> self.assertTrue(correct) | Test to see if the guessed answer is correct or not | 625941c332920d7e50b281a2 |
def load_pub_key(self, path): <NEW_LINE> <INDENT> with open(path, "r") as key_file: <NEW_LINE> <INDENT> self.pub_key = key_file.read() | Loads public key from a public key SSH file. | 625941c394891a1f4081ba7b |
def generate_embeddings(outputs, speakers_inputs, vector_size): <NEW_LINE> <INDENT> logger = get_logger('clustering', logging.INFO) <NEW_LINE> logger.info('Generate embeddings') <NEW_LINE> num_speakers = len(set(speakers_inputs[0])) <NEW_LINE> number_embeddings = len(outputs) * num_speakers <NEW_LINE> embeddings = [] <... | Combines the utterances of the speakers in the train- and testing-set and combines them into embeddings.
:param train_output: The training output (8 sentences)
:param test_output: The testing output (2 sentences)
:param train_speakers: The speakers used in training
:param test_speakers: The speakers used in testing
:p... | 625941c3004d5f362079a307 |
def __set_guifeedback_text_item(self): <NEW_LINE> <INDENT> self.__text_item.setDefaultTextColor(self.__text_color) <NEW_LINE> self.__text_item.setFont(self.__text_font) <NEW_LINE> self.__text_item.setPos(self.__text_horizontal_padding, 0) <NEW_LINE> self.__text_item.setTextWidth( self.__width - (2 * self.__text_horizon... | Rather than convolute the __init__, set the popup text here.
| 625941c3c4546d3d9de72a05 |
def build_rel_times(player): <NEW_LINE> <INDENT> date_strings=[] <NEW_LINE> for date in player.dates: <NEW_LINE> <INDENT> date_strings.append(convert_time(date)) <NEW_LINE> <DEDENT> return date_strings | convert UTC time stamps to time elapsed since data collection | 625941c3c432627299f04c18 |
def gen_pnext0(p): <NEW_LINE> <INDENT> i, k, m = 0, -1, len(p) <NEW_LINE> pnext = [-1] * m <NEW_LINE> while i < m-1: <NEW_LINE> <INDENT> if k == -1 or p[i] == p[k]: <NEW_LINE> <INDENT> i, k = i+1, k+1 <NEW_LINE> pnext[i] = k <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> k = pnext[k] <NEW_LINE> <DEDENT> <DEDENT> return ... | 生成针对p中各位置i的下一检查位置表,用于KMP算法 | 625941c3596a897236089a96 |
def exec_calls(ins): <NEW_LINE> <INDENT> exec_call(ins) | CALLS: call an external procedure. Not implemented. | 625941c3dd821e528d63b17d |
def keys(self): <NEW_LINE> <INDENT> all_keys = [] <NEW_LINE> for bucket in self.buckets: <NEW_LINE> <INDENT> for key, value in bucket.items(): <NEW_LINE> <INDENT> all_keys.append(key) <NEW_LINE> <DEDENT> <DEDENT> return all_keys | Return a list of all keys in this hash table.
Best and worst case running time: O(n) worst, where n is number of buckets
O(1) best, if there is only a single bucket | 625941c4b57a9660fec33856 |
def saveState(self, element): <NEW_LINE> <INDENT> for key, value in self._stateDic.items(): <NEW_LINE> <INDENT> state_history = self._all_states[key] <NEW_LINE> state_derivative_history = self._all_state_derivatives[key] <NEW_LINE> if value.getMultiplicity() == 1: <NEW_LINE> <INDENT> state_history[element] = value.getS... | Once the state history is created, this method saves a state at a given time in a certain position of the state history.
:param element:
:return: | 625941c3187af65679ca50f1 |
def evaluationFunction(self, currentGameState, action): <NEW_LINE> <INDENT> successorGameState = currentGameState.generatePacmanSuccessor(action) <NEW_LINE> newPos = successorGameState.getPacmanPosition() <NEW_LINE> newFood = successorGameState.getFood() <NEW_LINE> newGhostStates = successorGameState.getGhostStates() <... | Design a better evaluation function here.
The evaluation function takes in the current and proposed successor
GameStates (pacman.py) and returns a number, where higher numbers are better.
The code below extracts some useful information from the state, like the
remaining food (newFood) and Pacman position after moving... | 625941c4ff9c53063f47c1c7 |
def blocks_subtasks(streets): <NEW_LINE> <INDENT> polygons = list(ops.polygonize(list(streets.geometry))) <NEW_LINE> blocks = gpd.GeoDataFrame(geometry=polygons) <NEW_LINE> blocks.crs = streets.crs <NEW_LINE> blocks['poly_id'] = blocks.index <NEW_LINE> return blocks | Given a street network as the input, generated polygons that roughly
correspond to street blocks.
Returns a GeoDataFrame of those blocks, numbered from 0 to n - 1. | 625941c450812a4eaa59c2f7 |
def counting_sort(sort_list): <NEW_LINE> <INDENT> k = max(sort_list) <NEW_LINE> k_list = [0] * (k + 1) <NEW_LINE> for i in sort_list: <NEW_LINE> <INDENT> k_list[i] += 1 <NEW_LINE> <DEDENT> for i in range(1, k + 1): <NEW_LINE> <INDENT> k_list[i] += k_list[i - 1] <NEW_LINE> <DEDENT> result = [0] * len(sort_list) <NEW_LIN... | \This is func implementing counting sort.
First count #number for every element
Second count #number not lager than each element
Finally place element into right space.
k is the range of the number
T(n)=O(n+k)
S(n)=O(n+k)
Args:
sort_list (list) : The list to be sorted, where element number is no less than 0
... | 625941c4287bf620b61d3a38 |
def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> is_owner = bool(obj.owner == request.user) <NEW_LINE> is_superuser = bool(request.user.is_superuser) <NEW_LINE> return bool(is_superuser or is_owner) | Does the object has permission | 625941c48a43f66fc4b5403a |
def reconnect(self): <NEW_LINE> <INDENT> if not self._closing: <NEW_LINE> <INDENT> self._connection = self.connect() | 重连 | 625941c4e1aae11d1e749c89 |
def understands_money(model, func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> args = _expand_money_args(model, args) <NEW_LINE> kwargs = kwargs.copy() <NEW_LINE> kwargs = _expand_money_kwargs(model, kwargs) <NEW_LINE> return func(*args, **kwargs) <NEW_LINE> <DEDENT> r... | Used to wrap a queryset method with logic to expand
a query from something like:
mymodel.objects.filter(money=Money(100,"USD"))
To something equivalent to:
mymodel.objects.filter(money=Decimal("100.0), money_currency="USD") | 625941c491af0d3eaac9b9ea |
def lambda_handler(event, context): <NEW_LINE> <INDENT> feedback = event['feedback'] <NEW_LINE> sentiment=client.detect_sentiment(Text=feedback,LanguageCode='en')['Sentiment'] <NEW_LINE> return { 'sentiment': sentiment, 'reviewType': event['reviewType'], 'reviewID': event['reviewID'], 'customerID': event['customerID'],... | perform sentiment analysis on the input feedback | 625941c48e7ae83300e4af9f |
@app.route("/remove", methods=["POST", "GET"]) <NEW_LINE> def remove(): <NEW_LINE> <INDENT> if request.method == "POST": <NEW_LINE> <INDENT> person_id = request.form.get("person_id_remove") <NEW_LINE> db.execute("DELETE FROM friends WHERE username1=:user1 AND username2=:user2;", user1=session["user_id"], user2=person_i... | remove friends | 625941c4bf627c535bc131a2 |
def set_range(self): <NEW_LINE> <INDENT> self.mapper.SetScalarRange(self.min_data, self.max_data) | Sets the scalar range in z | 625941c4283ffb24f3c558d6 |
def _test_python(self): <NEW_LINE> <INDENT> irf = cscripts.csobs2caldb() <NEW_LINE> irf['inobs'] = self._inobs <NEW_LINE> irf['caldb'] = 'cta' <NEW_LINE> irf['irf'] = 'Py1' <NEW_LINE> irf['rootdir'] = 'caldb' <NEW_LINE> irf['logfile'] = 'csobs2caldb_py1.log' <NEW_LINE> irf['chatter'] = 2 <NEW_LINE> irf.logFileO... | Test csobs2caldb from Python | 625941c4f548e778e58cd550 |
def freq_check(time, flag ,freq,data_f_pmu , num_of_pmu): <NEW_LINE> <INDENT> if(flag == 0): <NEW_LINE> <INDENT> if((freq - data_f_pmu[2]) > (freq * 0.01) or (freq - data_f_pmu[2]) < (freq * 0.01)): <NEW_LINE> <INDENT> return [int(data_f_pmu[0]), 1, data_f_pmu[1]] <NEW_LINE> <DEDENT> <DEDENT> if(flag == 1 and num_of_pm... | freq function checking the frequency of each PMU station.
If received flag equal to 0 it means that PMU station don't have any anomaly before,
if flag equal to 1 it's mean anomaly received and extra check if anomaly are required,
after 50ms it's mean CYBER ATACK | 625941c4a17c0f6771cbe025 |
def compute_angle_2vec_V2(p1: list, p2: list, p3: list, p1p2_dist: float, p2p3_dist: float): <NEW_LINE> <INDENT> v1 = compute_cuboid_diag(p2, p1, p1p2_dist, True) <NEW_LINE> v2 = compute_cuboid_diag(p2, p3, p2p3_dist, False) <NEW_LINE> prod = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2) + 1e-6) <NEW_LINE> ... | Computes angle between vectors p2-p1 and p2-p3.
Parameters
----------
p1 : list
[x, y, z]
p2 : list
[x, y, z]
p3 : list
[x, y, z]
p1p2_dist : float
Distance between points p1 and p2 in 3D space.
p2p3_dist : float
Distance between points p2 and p3 in 3D space.
Returns
-------
float
Angle betwee... | 625941c44d74a7450ccd4197 |
def save_calibration(device_type): <NEW_LINE> <INDENT> if are_calibration_tools_available(): <NEW_LINE> <INDENT> if not device_type in [ JOYSTICK, DIGITAL_JOYSTICK ]: <NEW_LINE> <INDENT> raise Exception("Cannot calibrate this device type (%s)" % device_type) <NEW_LINE> <DEDENT> device_file = get_device(device_type) <NE... | Run external joystick calibration utility
Keyword arguments:
device_type -- device type | 625941c491f36d47f21ac4c4 |
@pytest.fixture(scope='session') <NEW_LINE> def app(): <NEW_LINE> <INDENT> app = create_app() <NEW_LINE> app.config.from_object('config.TestConfig') <NEW_LINE> return app | Instance of the Flask application available for testing | 625941c4baa26c4b54cb10f4 |
def item_index(arr, item): <NEW_LINE> <INDENT> for i, value in enumerate(arr): <NEW_LINE> <INDENT> if value == item: <NEW_LINE> <INDENT> return i <NEW_LINE> <DEDENT> <DEDENT> return | 获取元素在列表中的索引
:param arr:
:param item:
:return: | 625941c45e10d32532c5eefb |
def build_toplevel_group(variables): <NEW_LINE> <INDENT> return Group(*[url for url in sorted(HANDLERS)]) | Bulids a listing of all the different plugin groups | 625941c40c0af96317bb81bc |
def get_product_class(self): <NEW_LINE> <INDENT> return self.product_class | :return: a hook's item class. | 625941c4e8904600ed9f1eff |
def SVM_build_chars(self, svm, data, chars): <NEW_LINE> <INDENT> res_data = self.SVM_predict(svm, data, chars) <NEW_LINE> lines = [val for val in chars if chr(val.result) == '1'] <NEW_LINE> dots = [res for res in chars if chr(res.result) == '.'] <NEW_LINE> dashes = [obj for obj in chars if chr(obj.result) == '-'] <NEW_... | DOCSTRING:
Given SVM and data from which to build prediction, edits chars
to reflect the current SVM & data set | 625941c47cff6e4e81117959 |
def _kcs_sensor_set(self, sensor): <NEW_LINE> <INDENT> if self._debug_mode: <NEW_LINE> <INDENT> self.logger.info('SENSOR_DEBUG: sensor-status ' + str(time.time()) + ' ' + sensor.name + ' ' + str(sensor.STATUSES[sensor.status()]) + ' ' + str(sensor.value())) <NEW_LINE> return <NEW_LINE> <DEDENT> assert self.kcs_sensors ... | Generate #sensor-status informs to update sensors"
#sensor-status timestamp 1 sensor-name status value
:param sensor: A katcp.Sensor object
:return: | 625941c4ac7a0e7691ed40a3 |
def in_annulus(v, r, dr): <NEW_LINE> <INDENT> rvec = r*np.ones_like(v) <NEW_LINE> mask = (rvec <= v) <NEW_LINE> mask2 = (v < rvec+dr) <NEW_LINE> my_mask = mask & mask2 <NEW_LINE> indices = np.where(my_mask) <NEW_LINE> return indices | Takes a vector of all distances to a single particle
Returns a tuple of indices of all particles within the annulus | 625941c47cff6e4e8111795a |
def _print_comma(self): <NEW_LINE> <INDENT> number_zones = max(1, int(self._output.width // 14)) <NEW_LINE> next_zone = int((self._output.col-1) // 14) + 1 <NEW_LINE> if next_zone >= number_zones and self._output.width >= 14 and self._output.width != 255: <NEW_LINE> <INDENT> self._output.write_line() <NEW_LINE> <DEDENT... | Skip to next output zone. | 625941c421a7993f00bc7cc0 |
def forecastSearchCount(self, value=0): <NEW_LINE> <INDENT> self.query.update({"forecastSearchCount": value}) | Parameters
----------
value = int
forecast search count (default = 0) | 625941c492d797404e30415d |
def __create_gbx_config(self): <NEW_LINE> <INDENT> l_font = QtGui.QFont() <NEW_LINE> assert l_font <NEW_LINE> l_font.setFamily("Courier") <NEW_LINE> l_font.setPointSize(12) <NEW_LINE> self.__pte_editor = QtGui.QPlainTextEdit() <NEW_LINE> assert self.__pte_editor <NEW_LINE> self.__pte_editor.setFont(l_font) <NEW_LINE> s... | create configuration groupBox | 625941c43cc13d1c6d3c734f |
def __init__(self, client_id, client_secret, grant_type="client_credentials"): <NEW_LINE> <INDENT> self.parameter = { "grant_type": grant_type } <NEW_LINE> user_info_bytes = base64.b64encode( (client_id + ":" + client_secret).encode()) <NEW_LINE> self.user_info_base64 = user_info_bytes.decode() | Args:
client_id (str): Provided by Spotify when register app.
cleint_secret (str): Provided by Spotify when register app.
grant_type (str, optional): Grant type, set it to
"client_credentials". | 625941c40a366e3fb873e7ed |
def __init__(self, parameter_name): <NEW_LINE> <INDENT> self.parameter_name = parameter_name | Create a new optimization parameter with `parameter_name` as name
The names of parameters have to be unique, as they get identified
by the name.
:param parameter_name: The name of the parameter to create.
:type parameter_name: str | 625941c44f6381625f114a0f |
def compute_grad(y, X, w): <NEW_LINE> <INDENT> return (-2 * X.T.dot(y) + 2 * X.T.dot(X).dot(w)) | Compute grad of J(w) = ||y - Xw||_2^2:
\grad_w(J) = y^Ty - 2y^T (Xw) + (w^T X^ X w)
= 0 - 2y^TX + 2X^TXw
y: numpy vector of dim n x 1
X: numpy matrix of dim n x d
w: numpy vector of dim d x 1
Returns numpy vector of dim (shape w)
d x n x n x 1 + d x n x n x d x d x 1 => d x 1 | 625941c473bcbd0ca4b2c04a |
def __str__(self): <NEW_LINE> <INDENT> return '{}({})'.format( self.__class__.__name__, ','.join([str(v) for v in self.__dict__.values()]) ) | クラス名とフィールド値を持つ文字列へ変換する
:return: クラスの文字列へ変換した結果 | 625941c430dc7b766590193c |
def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.bricks = [] <NEW_LINE> self.states = [] <NEW_LINE> self.modes = [] <NEW_LINE> self.brickPrinter = None | Constructor.
:param name: String, name of the app
:return: | 625941c4711fe17d82542343 |
def diff(self, time, system, pos, minimap, minimatrix, infecteds=None): <NEW_LINE> <INDENT> if infecteds is None: <NEW_LINE> <INDENT> infecteds = [] <NEW_LINE> <DEDENT> output = np.zeros(system.shape) <NEW_LINE> R_0 = self.R_0 <NEW_LINE> gamma = self.gamma <NEW_LINE> N = self.N <NEW_LINE> if callable(R_0): <NEW_LINE> <... | Calculate the derivative of the compartment with respect to
time.
## **Parameters**
`time`: Time to take the derivative at. Similar to `time`
parameter in `epispot.models.Model.diff`.
`system`: A list containing the system of compartment values.
Should be of the same shape as the `starting_state`... | 625941c4287bf620b61d3a39 |
def is_empty(board, pos): <NEW_LINE> <INDENT> return square_state(board, pos) == Sq.empty | make sure square is empty | 625941c456b00c62f0f1462d |
def get_reg_importers(self): <NEW_LINE> <INDENT> return self.__pgr.import_plugins() | Return list of registered importers
| 625941c48c0ade5d55d3e98d |
def guessPublishedSourcePackageName(pkgname): <NEW_LINE> <INDENT> pass | Return the "published" SourcePackageName related to pkgname.
If pkgname corresponds to a source package that was published in
any of the distribution series, that's the SourcePackageName that is
returned.
If there is any official source package branch linked, then that
source package name is returned.
Otherwise, try... | 625941c48a349b6b435e8147 |
def make_cmd(self, s): <NEW_LINE> <INDENT> script_file = s.getMappedReadFolder()+s.getAccession()+".sh" <NEW_LINE> bwa_cmd = ' bwa mem -v 1 -t %s %s "%s" "%s" ' % (self.threads(), self._genome, s.getTrimmedRead1(), s.getTrimmedRead2()) <NEW_LINE> commands = [] <NEW_LINE> commands.append(bwa_cmd) <NEW_LINE> commands.ap... | get the run command for the given sample
The verbosity is set to 0 - no output. Excess verbosity (default 3) causes /tmp/slurmd.log overflow
Setting -v from 0-2 has no effect on the logging to console - as documentation says, 'This option has not been fully supported throughout BWA' | 625941c457b8e32f5248346e |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_struct_3I.pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) <NEW_LINE> _x = self.header.frame_id <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <INDENT> _x = _x.... | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941c430bbd722463cbd99 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.