code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __init__(self, cnx): <NEW_LINE> <INDENT> self._cnx = cnx <NEW_LINE> self._tnx = False <NEW_LINE> self.type_cache = TypeCache(cnx) <NEW_LINE> self.cursor_type = Cursor <NEW_LINE> try: <NEW_LINE> <INDENT> self._cnx.source() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise _op_error("Invalid connection"... | Create a database connection object. | 625941f3a8ecb033257d36cc |
def authenticate(self, code=None, group=None, openid=None, provider=None, request=None): <NEW_LINE> <INDENT> keystone = KeystoneBackend() <NEW_LINE> self.keystone = keystone <NEW_LINE> try: <NEW_LINE> <INDENT> profile_handle = getattr(self, '_get_%s_profile' % provider) <NEW_LINE> <DEDENT> except AttributeError: <NEW_L... | Reads in a code and asks Provider if it's valid and
what user it points to. | 625941f3adb09d7d5db6cd8d |
def signalAllProcesses(self, signal): <NEW_LINE> <INDENT> processes = self._getAllProcesses() <NEW_LINE> signalall = make_allfunc(processes, isRunning, self.signalProcess, signal=signal) <NEW_LINE> result = signalall() <NEW_LINE> self._update('signalAllProcesses') <NEW_LINE> return result | Send a signal to all processes in the process list
@param string signal Signal to send, as name ('HUP') or number ('1')
@return array An array of process status info structs | 625941f323e79379d52eeb5d |
def connect(self): <NEW_LINE> <INDENT> with self.microphone as source: <NEW_LINE> <INDENT> self.recognizer.adjust_for_ambient_noise(source) <NEW_LINE> <DEDENT> stop_listening = self.recognizer.listen_in_background( self.microphone, self.callback ) | Prepare the system to begin listening. | 625941f33c8af77a43ae3da9 |
def dq(self, message=None, origin=None): <NEW_LINE> <INDENT> password, quote_id = message.split(' ') <NEW_LINE> if password == self.password: <NEW_LINE> <INDENT> quote_id = str(int(quote_id)) <NEW_LINE> self.bucket.Object(quote_id).delete() <NEW_LINE> if quote_id in self.cache: <NEW_LINE> <INDENT> del self.cache[quote_... | Delete a quote. Password required. Usage: "dq PASSWORD QUOTE_ID" | 625941f330dc7b7665901f61 |
def set_voltage(self, channel, value): <NEW_LINE> <INDENT> if self.bipolar: <NEW_LINE> <INDENT> fraction = float(value) / (2 * self.max_voltage) + 0.5 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fraction = float(value) / self.max_voltage <NEW_LINE> <DEDENT> assert isinstance(channel, int) <NEW_LINE> self.comm(self.se... | Set the voltage of a channel | 625941f37c178a314d6efa6c |
def closehelp(self): <NEW_LINE> <INDENT> if not self.hw is None: <NEW_LINE> <INDENT> self.hw.destroy() <NEW_LINE> self.hw=None | time to close the tooltip | 625941f382261d6c526abaab |
def deletePlayers(): <NEW_LINE> <INDENT> conn = connect() <NEW_LINE> cursor = conn.cursor() <NEW_LINE> cursor.execute("DELETE * FROM players;") <NEW_LINE> conn.close() | Remove all the player records from the database. | 625941f3cc0a2c11143dd493 |
def reload_config(self, new_dp): <NEW_LINE> <INDENT> raise NotImplementedError | Reload the config from new_dp
KW Arguments:
new_dp -- A new DP object containing the updated config. | 625941f3f9cc0f698b140bf7 |
def run_test(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.compile: <NEW_LINE> <INDENT> self.get_model() <NEW_LINE> self.wrap_project() <NEW_LINE> self.get_bash_files() <NEW_LINE> self.remove_bitcode() <NEW_LINE> <DEDENT> if self.test: <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> print("source=... | Runs the test | 625941f367a9b606de4a84b8 |
def handle_db_request(self, queue): <NEW_LINE> <INDENT> address, empty, msg = queue.recv_multipart() <NEW_LINE> msg, *args = pickle.loads(msg) <NEW_LINE> try: <NEW_LINE> <INDENT> handler = { 'ALLPKGS': self.do_allpkgs, 'ALLVERS': self.do_allvers, 'NEWPKG': self.do_newpkg, 'NEWVER': self.do_newver, 'SKIPPKG': self.do_sk... | Handle incoming requests from :class:`DbClient` instances. | 625941f385dfad0860c3b45f |
def _initialize_glove(self) -> torch.Tensor: <NEW_LINE> <INDENT> glove = GloVe(name="42B", dim=300) <NEW_LINE> glove_vectors = torch.zeros(self._vocabulary.get_vocab_size(), 300) <NEW_LINE> for word, i in self._vocabulary.get_token_to_index_vocabulary().items(): <NEW_LINE> <INDENT> if word in glove.stoi: <NEW_LINE> <IN... | Initialize embeddings of all the tokens in a given
:class:`~allennlp.data.vocabulary.Vocabulary` by their GloVe vectors.
Extended Summary
----------------
It is recommended to train an :class:`~updown.models.updown_captioner.UpDownCaptioner` with
frozen word embeddings when one wishes to perform Constrained Beam Searc... | 625941f39b70327d1c4e13da |
def setupIndexes(context, event): <NEW_LINE> <INDENT> if isinstance(context, RelationRegistry): <NEW_LINE> <INDENT> context.setupIndexes() | Handles IObjectAdded event for the RelationRegistry utility
and creates the indexes needed. | 625941f323849d37ff7b368c |
def test_draw_anchors(self): <NEW_LINE> <INDENT> gpu = self.gpu <NEW_LINE> filename = self.filename <NEW_LINE> img_width = 1024 <NEW_LINE> img_height = 1024 <NEW_LINE> img = imgutils.draw_empty(img_width, img_height) <NEW_LINE> anchors = anchorutils.generate_anchors(gpu=gpu) <NEW_LINE> for anchor in anchors: <NEW_LINE>... | Generate the basic 9 anchors and draw and then save them to a
file. | 625941f3379a373c97cfb149 |
def project_impl(K, Rt, points): <NEW_LINE> <INDENT> raise NotImplementedError() | Project 3D points into a calibrated camera.
Input:
K -- camera intrinsics calibration matrix
Rt -- 3 x 4 camera extrinsics calibration matrix
points -- height x width x 3 array of 3D points
Output:
projections -- height x width x 2 array of 2D projections | 625941f391f36d47f21acafb |
def to_undirected_class(self): <NEW_LINE> <INDENT> return nx.Graph | Returns the class to use for undirected copies.
See :func:`networkx.DiGraph.to_undirected()`. | 625941f332920d7e50b287d7 |
def __init__(self, n_heads, n_units, dropout=0.1): <NEW_LINE> <INDENT> super(MultiHeadedAttention, self).__init__() <NEW_LINE> assert n_units % n_heads == 0 <NEW_LINE> self.n_units = n_units <NEW_LINE> self.d_k = n_units // n_heads <NEW_LINE> self.h = n_heads <NEW_LINE> self.q_linear = nn.Linear(n_units, n_units) <NEW_... | n_heads: the number of attention heads
n_units: the number of output units
dropout: probability of DROPPING units | 625941f391f36d47f21acafc |
def find_ops(self, prefix=None, op_type=None, exactly_one=False): <NEW_LINE> <INDENT> found_ops = [] <NEW_LINE> for f_name, f in self.functions.items(): <NEW_LINE> <INDENT> found_ops.extend(f.find_ops(prefix=prefix, op_type=op_type)) <NEW_LINE> <DEDENT> if exactly_one and len(found_ops) != 1: <NEW_LINE> <INDENT> msg = ... | Return list of ops with name matching `prefix` if specified, and
op_type, if specified. At least one of {prefix, op_type} must be
specified.
If `exactly_one` == True, raise ValueError if we find <1 or >1 ops satisfying
the criteria.
prefix: str
Return list[Operation]. Empty list if no op satisfies. | 625941f329b78933be1e5ca7 |
def testCancelWork(self): <NEW_LINE> <INDENT> self.queue.queueWork(self.processingSpec.specUrl()) <NEW_LINE> elements = len(self.queue) <NEW_LINE> self.queue.updateLocationInfo() <NEW_LINE> work = self.queue.getWork({'T2_XX_SiteA' : 1000, 'T2_XX_SiteB' : 1000}, {}) <NEW_LINE> self.assertEqual(len(self.queue), 0) <NEW_L... | Cancel work | 625941f38e7ae83300e4b5d1 |
def _get_current_output(self): <NEW_LINE> <INDENT> output = [] <NEW_LINE> for item in self.items: <NEW_LINE> <INDENT> out = self.py3.get_output(item) <NEW_LINE> if out and 'separator' not in out[-1]: <NEW_LINE> <INDENT> out[-1]['separator'] = True <NEW_LINE> <DEDENT> output += out <NEW_LINE> <DEDENT> return output | Get child modules output. | 625941f35510c4643540f9d6 |
def create_widget(self): <NEW_LINE> <INDENT> item = QEdgeItem(self) <NEW_LINE> self.widget = item | Create the QComboBox widget.
| 625941f33c8af77a43ae3daa |
def prev(self): <NEW_LINE> <INDENT> if self.limit and self.limit == self.count: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> since_id = self.max_id <NEW_LINE> data = self.method(since_id = since_id, *self.args, **self.kargs) <NEW_LINE> if len(data) == 0: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE>... | Fetch a set of items with IDs greater than current set. | 625941f34428ac0f6e5badfa |
def extract_mapping(conf, strings_to_ignore): <NEW_LINE> <INDENT> reference_mapping = StringMapping() <NEW_LINE> extensions_by_parser = _get_extensions_by_parser(conf) <NEW_LINE> logger = logging.getLogger(logger_name) <NEW_LINE> logger.info("Extracting string mapping") <NEW_LINE> for parser_name in extensions_by_parse... | Extracts a mapping of strings to native-language translations | 625941f344b2445a33932693 |
def output(dataframe, output_dir, filename): <NEW_LINE> <INDENT> dataframe.to_csv(os.path.join(output_dir, filename), sep='\t', header=True, index=False) | Arguments:
dataframe (dataframe): the result of the analysis we want to write out as a csv.
output_dir (str): the fullpath of a directory we will write our output to. | 625941f3851cf427c661ab0b |
def __amend_order(self, ord_id, side, ord_qty, limit=0, stop=0, post_only=False): <NEW_LINE> <INDENT> if limit > 0 and stop > 0: <NEW_LINE> <INDENT> ord_type = "StopLimit" <NEW_LINE> retry(lambda: self.private_client.Order.Order_amend(origClOrdID=ord_id, orderQty=ord_qty, price=limit, stopPx=stop).result()) <NEW_LINE> ... | 注文を更新する | 625941f36fece00bbac2dd48 |
def from_absolute(absx, absy, width, height): <NEW_LINE> <INDENT> return Coordinate(None, None, absx, absy, width, height) | Builds a Coordinate given absolute x and y coordinates, along with
the width and height of the absolute coordinate area (necessary for
conversion to fractional). | 625941f399fddb7c1c9de98f |
def test_md5sum(): <NEW_LINE> <INDENT> tempdir = _TempDir() <NEW_LINE> fname1 = op.join(tempdir, 'foo') <NEW_LINE> fname2 = op.join(tempdir, 'bar') <NEW_LINE> with open(fname1, 'wb') as fid: <NEW_LINE> <INDENT> fid.write(b'abcd') <NEW_LINE> <DEDENT> with open(fname2, 'wb') as fid: <NEW_LINE> <INDENT> fid.write(b'efgh')... | Test md5sum calculation. | 625941f376d4e153a657f134 |
def is_history_enabled(self): <NEW_LINE> <INDENT> a = ATTR_JobHistoryEnable <NEW_LINE> attrs = self.status(SERVER, level=logging.DEBUG)[0] <NEW_LINE> if ((a in attrs.keys()) and attrs[a] == 'True'): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Short-hand method to return the value of job_history_enable | 625941f38da39b475bd6557e |
def ensure_required_folders_exist(sync_dir): <NEW_LINE> <INDENT> sync_dir_abs = os.path.abspath(sync_dir) <NEW_LINE> if not os.path.isdir(sync_dir_abs): <NEW_LINE> <INDENT> print('Creating', sync_dir_abs) <NEW_LINE> os.mkdir(sync_dir_abs) <NEW_LINE> <DEDENT> required_subfolders = ['projects', 'datasets', 'instructions'... | 1. If the sync dir doesn't exist then create it.
2. If the required sync dir subfolders don't exist then create them. | 625941f392d797404e30478f |
def pre_run(self) -> None: <NEW_LINE> <INDENT> self._messages_logged.clear() <NEW_LINE> self._packages_filtered.clear() <NEW_LINE> super().pre_run() | Initialize this pipeline unit before each run. | 625941f3dd821e528d63b7a6 |
def test_user_blog_slugify(self, mock_config): <NEW_LINE> <INDENT> mock_config.site = MagicMock(slugify=None) <NEW_LINE> mock_config.blog = MagicMock(slugify=lambda s: 'deprecated') <NEW_LINE> slug = self._call_fut('Foo Bar!') <NEW_LINE> self.assertEqual(slug, 'deprecated') | create_slug uses user-defined config.blog.slugify function
| 625941f3a8370b7717052e9f |
def copy_resolv_conf_to_root(root=""): <NEW_LINE> <INDENT> src = "/etc/resolv.conf" <NEW_LINE> dst = os.path.join(root, src.lstrip('/')) <NEW_LINE> if not os.path.isfile(src): <NEW_LINE> <INDENT> log.debug("%s does not exist", src) <NEW_LINE> return <NEW_LINE> <DEDENT> if os.path.isfile(dst): <NEW_LINE> <INDENT> log.de... | Copy resolv.conf to a system root. | 625941f38a43f66fc4b54660 |
def is_subtype_helper(left: mypy.types.Type, right: mypy.types.Type) -> bool: <NEW_LINE> <INDENT> left = mypy.types.get_proper_type(left) <NEW_LINE> right = mypy.types.get_proper_type(right) <NEW_LINE> if ( isinstance(left, mypy.types.LiteralType) and isinstance(left.value, int) and left.value in (0, 1) and isinstance(... | Checks whether ``left`` is a subtype of ``right``. | 625941f37b25080760e39a57 |
def stoptopology(topologyName): <NEW_LINE> <INDENT> queryData = {'from': '/', 'nodes': [{'node': 'topology', 'properties': ['name'], 'where': [{'property': 'name', 'regex': topologyName}]}] } <NEW_LINE> queryResponse = middleware.ixn.query(data=queryData) <NEW_LINE> try: <NEW_LINE> <INDENT> topologyObj = queryRespon... | Stop a running Topology Group and all of its protocol stacks.
param: topologyName: (int): The Topology Group name. | 625941f3a4f1c619b28b062c |
def full_runscript(self): <NEW_LINE> <INDENT> ret = self.settings.runscript.shebang +'\n\n' <NEW_LINE> if 'pre' in self.settings.runscript: <NEW_LINE> <INDENT> ret += self.settings.runscript.pre+'\n\n' <NEW_LINE> <DEDENT> ret += self.get_runscript() <NEW_LINE> if 'post' in self.settings.runscript: <NEW_LINE> <INDENT> r... | Generate the full runscript, including shebang line and contents of ``pre`` and ``post``, if any. In practice this method is just a simple wrapper around |get_runscript|.
| 625941f30a50d4780f667499 |
def convert(aerosol_path, out_h5: h5py.Group, compression, filter_opts): <NEW_LINE> <INDENT> func = {"pix": read_pix, "cmp": read_cmp} <NEW_LINE> dataset_names = [] <NEW_LINE> metadata = [] <NEW_LINE> pattern = ["*.pix", "*.cmp"] <NEW_LINE> for p in pattern: <NEW_LINE> <INDENT> for search_path in aerosol_path.glob(p): ... | Converts all the .pix and .cmp files found in `aerosol_path`
to a HDF5 file. | 625941f39f2886367277ae8a |
def rename_yearly_avg_rate_column( self, df ): <NEW_LINE> <INDENT> if not WvmFxRatesTransformFunctions.static_year_in_data_file: <NEW_LINE> <INDENT> raise InvalidValueFoundError( f"Seems like extracting year information from the " f"first few lines of the FX rate data file did not " f"return anything. Please inspect th... | Rename the name of the original column which stores
average FX rates of the year to the value of the year
found in the file. | 625941f366673b3332b92693 |
def check_stops(it): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> val = next(it) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> assert False, "expected exhausted iterator; got {}".format(str(val)) | Verify that an exhausted iterator yields StopIteration. | 625941f3cc0a2c11143dd494 |
def classify(self, phrase_vector): <NEW_LINE> <INDENT> x = Variable(np.asarray([phrase_vector])) <NEW_LINE> return self.model.predictor(x).data[0] | Run this over an input vector and see the result | 625941f399cbb53fe67931e7 |
def match_stars_calvstrue(stardat, starcal, sorted=True): <NEW_LINE> <INDENT> stardat['magcal'] = n.zeros(len(stardat['id']), dtype='float') - 99 <NEW_LINE> if sorted: <NEW_LINE> <INDENT> j = 0 <NEW_LINE> for i in range(len(starcal['id'])): <NEW_LINE> <INDENT> while (starcal['id'][i] != stardat['id'][j]) & (j<len(stard... | Match up true information to calibration information, return extended starcal.
Note that stardat and starcal do not have to be the same length; in fact, starcal
will usually be slightly shorter than stardat. | 625941f3adb09d7d5db6cd8e |
def __init__(self, owner, starting_loc, ending_loc, speed, size=(50, 50), img=None, collision_func=None, ending_func=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.owner = owner <NEW_LINE> self.board = owner.board <NEW_LINE> self.ending_loc = ending_loc <NEW_LINE> self.speed = speed <NEW_LINE> try: <NEW_... | @starting_loc, ending_loc: Euclidean coords for display | 625941f324f1403a92601163 |
def init_state(self): <NEW_LINE> <INDENT> balls = [self.random_new_ball()] <NEW_LINE> state = State(self.screen_x, self.screen_y, balls, self.end_line) <NEW_LINE> self.current_state = state <NEW_LINE> self.current_reward = 0 <NEW_LINE> self.is_finish = False <NEW_LINE> return state | Initialize the state with one ball at the middle top of the canvas | 625941f38c0ade5d55d3efc3 |
def main(): <NEW_LINE> <INDENT> import argparse <NEW_LINE> parser = argparse.ArgumentParser( description="Generate a Witchytwigs site (version %s)" % __VERSION__ ) <NEW_LINE> parser.add_argument( '--site', help='path to the site directory (default: .)' ) <NEW_LINE> parser.add_argument( '--out', help='path to write the ... | Run Witchytwigs as a CLI. | 625941f3091ae35668667556 |
def read_supercross_headers(self): <NEW_LINE> <INDENT> self.reader = csv.reader(self.f, delimiter=",") <NEW_LINE> for i in xrange(3): <NEW_LINE> <INDENT> next(self.reader) <NEW_LINE> <DEDENT> line = next(self.reader)[0].strip() <NEW_LINE> fields = line .replace("Geography by", "") .strip() ... | Return fields and tuples of categories for this supercross export.
Categories are defined by the permutations of values for each field.
For an export with fields [gender, race, age], categories will be a
list like [
('male', 'black', '0-5'),
('male', 'black', '6-10'),
...
('male'... | 625941f3ac7a0e7691ed46c2 |
@_add2docstring_common_params <NEW_LINE> def csd(darray, other_darray, fs=None, seglen=None, overlap_ratio=2, window='hann', nperseg=256, noverlap=None, nfft=None, detrend='constant', return_onesided=True, dim=None, scaling='density', mode='psd'): <NEW_LINE> <INDENT> Pxy = crossspectrogram(darray, other_darray, fs, seg... | Estimate the cross power spectral density, Pxy, using Welch's method.
Parameters
----------
darray : xarray
Series of measurement values
other_darray : xarray
Series of measurement values
{common_params}
{scaling_param}
{mode_param}
Returns
-------
Pxy : xarray.DataArray
Cross spectral density or cross po... | 625941f3442bda511e8bea12 |
def transform(self, X): <NEW_LINE> <INDENT> assert isinstance(X, pd.DataFrame) <NEW_LINE> X_full = X.drop(columns=self.drop_columns) <NEW_LINE> return X_full | Description
-----------
Drops columns with more missing values than the threshold.
Args
----
X: DataFrame, (examples, features)
Pandas DataFrame containing training/test example features
Returns
-------
X_full: DataFrame, (examples, features)
Pandas DataFrame containing example features without columns
in... | 625941f3a8ecb033257d36cd |
def get_current_user(): <NEW_LINE> <INDENT> import ctypes <NEW_LINE> MAX_PATH = 260 <NEW_LINE> name = ctypes.create_unicode_buffer(MAX_PATH) <NEW_LINE> namelen = ctypes.c_int(len(name)) <NEW_LINE> if not ctypes.windll.advapi32.GetUserNameW(name, ctypes.byref(namelen)): <NEW_LINE> <INDENT> raise ctypes.WinError() <NEW_L... | Get the login name for the current user.
>>> get_current_user()
u'htouvet' | 625941f3596a89723608a0ba |
def is_tile_cleaned(self, m, n): <NEW_LINE> <INDENT> if self.tiles[(m,n)] == 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Return True if the tile (m, n) has been cleaned.
Assumes that (m, n) represents a valid tile inside the room.
m: an integer
n: an integer
Returns: True if the tile (m, n) is cleaned, False otherwise
Note: The tile is considered clean only when the amount of dirt on this
tile is 0. | 625941f3293b9510aa2c3892 |
def __init__(self, **kwargs): <NEW_LINE> <INDENT> settings = kwargs["settings"] <NEW_LINE> self.settings = settings.get("pymdown_settings", {}) <NEW_LINE> self.page = settings.get("page", {}) <NEW_LINE> self.extra = settings.get("extra", {}) <NEW_LINE> self.preview = kwargs.get("preview", False) <NEW_LINE> self.encodin... | Initialize. | 625941f3287bf620b61d4062 |
def clean_up(): <NEW_LINE> <INDENT> ls = os.listdir(settings.TEMP_CSET_DIR) <NEW_LINE> delta = timedelta(days=1) <NEW_LINE> now = datetime.now() <NEW_LINE> for fname in ls: <NEW_LINE> <INDENT> file_path = os.path.join(settings.TEMP_CSET_DIR, fname) <NEW_LINE> mtime = datetime.fromtimestamp(os.path.getmtime(file_path)) ... | Removes outdated tmpcset files | 625941f3c4546d3d9de7303d |
def print_all_attribute_value_counts(instances, attribute_names): <NEW_LINE> <INDENT> num_instances = len(instances) <NEW_LINE> for attribute in attribute_names: <NEW_LINE> <INDENT> value_counts = attribute_value_counts(instances, attribute, attribute_names) <NEW_LINE> print('{}:'.format(attribute), end=' ') <NEW_LINE>... | Returns a list of defaultdicts containing the counts of occurrences of each value of each attribute in the list of instances.
attribute_names is a list of names of attributes. | 625941f33346ee7daa2b3374 |
def __init__( self, *, id: str, entities: List["LinkedEntity"], warnings: List["TextAnalyticsWarning"], statistics: Optional["DocumentStatistics"] = None, **kwargs ): <NEW_LINE> <INDENT> super(DocumentLinkedEntities, self).__init__(**kwargs) <NEW_LINE> self.id = id <NEW_LINE> self.entities = entities <NEW_LINE> self.wa... | :keyword id: Required. Unique, non-empty document identifier.
:paramtype id: str
:keyword entities: Required. Recognized well known entities in the document.
:paramtype entities: list[~azure.ai.textanalytics.v3_2_preview_2.models.LinkedEntity]
:keyword warnings: Required. Warnings encountered while processing document.... | 625941f3d164cc6175783351 |
def invalid_index_idxes(self, data: pd.Series) -> list: <NEW_LINE> <INDENT> return [i + 1 for i in range(len(data) - 1) if data[i + 1] - data[i] != 1] | Summary
Returns indexes where data value is not continuous | 625941f3435de62698dfe250 |
def to_matrix(self): <NEW_LINE> <INDENT> theta, phi, lam = self.params <NEW_LINE> theta, phi, lam = float(theta), float(phi), float(lam) <NEW_LINE> return numpy.array([ [ numpy.cos(theta / 2), -numpy.exp(1j * lam) * numpy.sin(theta / 2) ], [ numpy.exp(1j * phi) * numpy.sin(theta / 2), numpy.exp(1j * (phi + lam)) * nump... | Return a Numpy.array for the U3 gate. | 625941f3091ae35668667557 |
def _auto_discovery(self): <NEW_LINE> <INDENT> self.current_project = self._guess_current('PROJECT', self.all_projects) <NEW_LINE> if self.current_project: <NEW_LINE> <INDENT> self.project_instances = dict(self.current_project.instances()) <NEW_LINE> self.project_packages = dict(self.current_project.packages()) <NEW_LI... | Guess current project, package, instance and site. | 625941f356ac1b37e62647c5 |
def get_coord_type(coord): <NEW_LINE> <INDENT> coord_dict = {"^": "local", "~": "relative"} <NEW_LINE> return coord_dict.get(coord[0], "absolute") | This assumes the given coordinate is indeed a coord type
Args:
coord (str)
Returns:
str ("relative", "local", "absolute"): The coordinate type | 625941f3d8ef3951e3243b40 |
def _create_heat_stack_nodes(self, stack): <NEW_LINE> <INDENT> identity = IDEN_ATTR.copy() <NEW_LINE> state = STATE_ATTR.copy() <NEW_LINE> uuid = stack.id <NEW_LINE> state['stack_name'] = stack.stack_name <NEW_LINE> template = self.heat.stacks.template(uuid) <NEW_LINE> state['template'] = template <NEW_LINE> return ide... | Creates the identity and state nodes for a heat stack.
:param stack: Heat stack object.
:return: Identity and state node. | 625941f37d43ff24873a32a8 |
def ssd(self, other): <NEW_LINE> <INDENT> return libamino.aa_tf_qssd(self, Quat.ensure(other)) | Sum-square-differences of self and other. | 625941f37cff6e4e81117f88 |
def m_load_plugin(self, plugin): <NEW_LINE> <INDENT> if plugin not in list(self.plugins.keys()): <NEW_LINE> <INDENT> raise UserWarning("plugin is not available") <NEW_LINE> <DEDENT> if self.plugins[plugin].active: <NEW_LINE> <INDENT> raise UserWarning("plugin is already loaded") <NEW_LINE> <DEDENT> pid = imp.load_modul... | Load and activate plugin.
@param plugin plugin id | 625941f3be7bc26dc91cdbf7 |
def testrepo(repo): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> repourl = 'http://' + repo <NEW_LINE> request = requests.get("%s/ppdslist.json" % repourl, allow_redirects=False) <NEW_LINE> request.raise_for_status() <NEW_LINE> <DEDENT> except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError, request... | send http request to repolist on host | 625941f3bd1bec0571d90c32 |
def __init__(self, hass): <NEW_LINE> <INDENT> self._state = None <NEW_LINE> self.update() | Initialize the sensor. | 625941f373bcbd0ca4b2c678 |
def cancel(self): <NEW_LINE> <INDENT> self._log_traceback = False <NEW_LINE> if self.done(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self._fut_waiter is not None: <NEW_LINE> <INDENT> if self._fut_waiter.cancel(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> self._must_cancel = True <NEW_... | Request that this task cancel itself.
This arranges for a CancelledError to be thrown into the
wrapped coroutine on the next cycle through the event loop.
The coroutine then has a chance to clean up or even deny
the request using try/except/finally.
Unlike Future.cancel, this does not guarantee that the
task will be ... | 625941f33eb6a72ae02ecaf1 |
def _get_month_parameters(self, cr, uid, context): <NEW_LINE> <INDENT> param_pool = self.pool.get("ir.config_parameter") <NEW_LINE> config_min_months_id = param_pool.search(cr, uid, [('key', '=', 'min.months.last.purchase')], context=context) <NEW_LINE> config_max_months_id = param_pool.search(cr, uid, [('key', '=', 'm... | Devuelve los meses configurados en los parametros en una tupla. | 625941f323e79379d52eeb5e |
def test_distance_is_euclidean(self): <NEW_LINE> <INDENT> sources = np.array([1, 1]) <NEW_LINE> destinations = np.array([4, 5]) <NEW_LINE> distance_matrix = distances.euclidean_distance_matrix( sources, destinations ) <NEW_LINE> assert distance_matrix[0] == 5. | It must return an actual Euclidean distance
In this case, it is easy to see that the distance from [1, 1] to [4, 5]
is:
sqrt((4 - 1)**2 + (5 - 1)**2) = sqrt(3**2 + 4**2) = 5 | 625941f315baa723493c457d |
def symbol_name(self): <NEW_LINE> <INDENT> return _tutorial_swig.my_qpsk_demod_cb_sptr_symbol_name(self) | symbol_name(my_qpsk_demod_cb_sptr self) -> std::string | 625941f3d6c5a10208144652 |
def metade(numero, formatar=False): <NEW_LINE> <INDENT> if formatar: <NEW_LINE> <INDENT> return moeda(numero / 2) <NEW_LINE> <DEDENT> return numero / 2 | -> Recebe um valor e devolve a metade. Permite ainda informar se deve devolver já formatado ou não
:param numero: valor a ser trabalhado
:param formatar: booleano que indica se deve ou não retornar o valor com a formatação de moeda
:return: metade do valor recebido | 625941f35510c4643540f9d7 |
def relink_manifest(url, consumer, user, password, exp_subs_file, manifest_file=None): <NEW_LINE> <INDENT> manifest_file = manifest_file or download_manifest( url=url, consumer=consumer, user=user, password=password) <NEW_LINE> if not manifest_file: <NEW_LINE> <INDENT> print('manifest_file is not populated.') <NEW_LINE... | Links the latest downloaded manifest file to the manifest_latest.zip softlink.
:param url: Subscription Manager URL
:param consumer: A consumer hash to be used for getting the manifest
:param user: Red Hat Network username
:param password: Red Hat Network password
:param exp_subs_file: Expected subscription file
:para... | 625941f366673b3332b92694 |
def purgelog(*args): <NEW_LINE> <INDENT> if len(args) < 3: <NEW_LINE> <INDENT> raise NameError('Missing arguments') <NEW_LINE> <DEDENT> file_name = args[0] <NEW_LINE> limitize = int(args[1]) <NEW_LINE> logsNumber = int(args[2]) <NEW_LINE> if os.path.isfile(file_name): <NEW_LINE> <INDENT> logfile_size = os.stat(file_nam... | List of arguments in the function
<log-file name> <limit in KB> <logs-files>
:param args: arguments above
:return: nothing to return | 625941f34e4d5625662d49d1 |
def make_finite(X): <NEW_LINE> <INDENT> X = _check_floating(X) <NEW_LINE> return np.minimum(np.maximum(X, np.finfo(X.dtype).min), np.finfo(X.dtype).max) | Make the data matrix finite by replacing -infty and infty.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Data matrix.
Returns
-------
X : array, shape (n_samples, n_features)
Data matrix as numpy array after checking and possibly replacing
-infty and infty with min and max of floatin... | 625941f31f037a2d8b9467ff |
def opt_out(): <NEW_LINE> <INDENT> parser = get_or_create_config() <NEW_LINE> parser['user']['track'] = "False" <NEW_LINE> with open(popylar_path, 'w') as fhandle: <NEW_LINE> <INDENT> parser.write(fhandle) | Permanently opt-out of Popylar tracking.
To opt-in again, run ``popylar.reset_uid()`` | 625941f3b830903b967e9f07 |
def read_file(path): <NEW_LINE> <INDENT> with open(path) as json_file: <NEW_LINE> <INDENT> data = json.load(json_file) <NEW_LINE> <DEDENT> return data | This method will return the data saved in your file as a Python Object
Args:
path: path to the file from which you wish to read the data.
Example - './data/users'
Return:
data - the json data saved in the file as a python object.
Example - In our case, it will return a list of dictionary objects... | 625941f3009cb60464c639b0 |
def types(self): <NEW_LINE> <INDENT> if self.pbtype == 'BYTES' and self.allocation == 'STATIC': <NEW_LINE> <INDENT> result = 'typedef struct {\n' <NEW_LINE> result += ' size_t size;\n' <NEW_LINE> result += ' uint8_t bytes[%d];\n' % self.max_size <NEW_LINE> result += '} %s;\n' % self.ctype <NEW_LINE> <DEDENT> else... | Return definitions for any special types this field might need. | 625941f30c0af96317bb87ea |
def clean_command(sql_url, min_num_days, do_clean_unassociated_projects, do_soft_delete_expired_secrets, verbose, log_file): <NEW_LINE> <INDENT> if verbose: <NEW_LINE> <INDENT> CONF.set_override('debug', True) <NEW_LINE> <DEDENT> if log_file: <NEW_LINE> <INDENT> CONF.set_override('log_file', log_file) <NEW_LINE> <DEDEN... | Clean command to clean up the database.
:param sql_url: sql connection string to connect to a database
:param min_num_days: clean up soft deletions older than this date
:param do_clean_unassociated_projects: If True, clean up
unassociated projects
:param do_soft_delete_expired_se... | 625941f3925a0f43d254a480 |
def randomwalk(n): <NEW_LINE> <INDENT> walk=[] <NEW_LINE> w=0 <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> w+=random.gauss(0,1) <NEW_LINE> walk.append(w) <NEW_LINE> <DEDENT> return walk | Generate a gaussian random walk of length n | 625941f3236d856c2ad44de6 |
def page_factory(self): <NEW_LINE> <INDENT> name_list = ['add_obligations', 'without_add_obligations', 'service_type', 'invoice_amount', 'confirm', 'start_time', 'end_time', 'quantity_ceiling', 'type', 'lower_number', 'origin', 'tolerate', 'resource_discount', 'complete', 'continue_add', 'all_compulsory_items', 'swipe_... | 初始化页面控件 | 625941f3a05bb46b383ece1e |
def acosh(*args, **kwargs): <NEW_LINE> <INDENT> pass | acosh(x)
Return the hyperbolic arc cosine (measured in radians) of x.
This function has been overriden from math.acosh to work element-wise on iterables | 625941f3711fe17d82542960 |
def scamp_auto(files): <NEW_LINE> <INDENT> for f in files: <NEW_LINE> <INDENT> shutil.move(setup.fitsdir + '/' + f, setup.scampdir + '/' + f) <NEW_LINE> <DEDENT> os.chdir(setup.scampdir) <NEW_LINE> catalogs = open('catalogs.txt', 'w') <NEW_LINE> for i in files: <NEW_LINE> <INDENT> catalogs.write(i + '\n') <NEW_LINE> <D... | Run Scamp on list 'files' 'files' is a Python list consisting of .fits file names to be sextracted. | 625941f371ff763f4b549c9a |
def set_rlwaitforcmd_data(self, argparse_data): <NEW_LINE> <INDENT> importance = self.lowMedium <NEW_LINE> subject = ["cmd", argparse_data.command] <NEW_LINE> param_option = ["", ""] <NEW_LINE> if argparse_data.r: <NEW_LINE> <INDENT> param_option[0] = argparse_data.r <NEW_LINE> <DEDENT> if argparse_data.p: <NEW_LINE> <... | Sets DocumentationInformation object to specified BeakerLib command
:param argparse_data: argparse object | 625941f357b8e32f52483aa2 |
def _adapter_connect(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> addresses = socket.getaddrinfo(self.params.host, self.params.port) <NEW_LINE> <DEDENT> except socket.error as error: <NEW_LINE> <INDENT> LOGGER.critical('Could not get addresses to use: %s (%s)', error, self.params.host) <NEW_LINE> return False <N... | Connect to the RabbitMQ broker, returning True if connected
:rtype: bool | 625941f3e1aae11d1e74a2c1 |
def getLookupTabel(property): <NEW_LINE> <INDENT> result = {} <NEW_LINE> query = u'SELECT ?item ?id WHERE { ?item wdt:%s ?id }' % (property, ) <NEW_LINE> sq = pywikibot.data.sparql.SparqlQuery() <NEW_LINE> queryresult = sq.select(query) <NEW_LINE> for resultitem in queryresult: <NEW_LINE> <INDENT> qid = resultitem.get(... | Make a lookupt table "id" -> "qid" for the property
:param property: Property to make the lookup table for
:return: Dict with strings in it | 625941f3293b9510aa2c3893 |
def aapl(csv_line): <NEW_LINE> <INDENT> pass | csv_line: A line from data/NASDAQ_AAPL.csv, structured as
YYYY-MM-DD, open, high, low, close, volume
Returns an Aapl initialized with the contents of csv_line | 625941f3d268445f265b5472 |
def set_mac_background(image_path: str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> mac_script = ( f"""osascript -e 'tell application "Finder" """ f""" to set desktop picture to "{image_path}" as POSIX file'""" ) <NEW_LINE> subprocess.run(mac_script, shell=True) <NEW_LINE> <DEDENT> except subprocess.CalledProcessErro... | Sets given image path as background for Mac using osascript | 625941f3dc8b845886cb5b3a |
def write_to_stdout(sorted_requests): <NEW_LINE> <INDENT> writer = csv.writer(sys.stdout) <NEW_LINE> for item in sorted_requests: <NEW_LINE> <INDENT> writer.writerow(item) | Write generated report to standard output
:param list sorted_requests: sorted list of tuples in form: (URL, number of requests)
:return: None | 625941f3a934411ee3751c98 |
def node_task_finished(self, node_id, task_id, result): <NEW_LINE> <INDENT> if not self.nodes.has_key(node_id): <NEW_LINE> <INDENT> raise JSONRPCError(jsonrpc.INVALID_NODE_ID) <NEW_LINE> <DEDENT> if not self.tasks.has_key(task_id): <NEW_LINE> <INDENT> raise JSONRPCError(jsonrpc.INVALID_TASK_ID) <NEW_LINE> <DEDENT> task... | Run task finished process | 625941f3f7d966606f6aa60f |
def mToPitchClassSet(*args): <NEW_LINE> <INDENT> return _CsoundAC.Voicelead_mToPitchClassSet(*args) | mToPitchClassSet(double pcn, size_t divisionsPerOctave=12) -> DoubleVector
mToPitchClassSet(double pcn) -> DoubleVector | 625941f3d58c6744b4258260 |
def __init__(self, ranges=None, rule=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._ranges = None <NEW_LINE> self._... | ExtensionsV1beta1FSGroupStrategyOptions - a model defined in OpenAPI | 625941f363f4b57ef000170a |
@app.route('/', methods=['POST']) <NEW_LINE> def save(): <NEW_LINE> <INDENT> param = request.json <NEW_LINE> book = Book(name=param['name'], price=param['price']) <NEW_LINE> success = book.save() <NEW_LINE> if (success): <NEW_LINE> <INDENT> return jsonify({'success': True, 'data': model_to_dict(book)}) <NEW_LINE> <DEDE... | 创建一本书
---
parameters:
- in: body
name: body
schema:
id: Book
required:
- name
- price
properties:
name:
type: string
description: 书名
price:
type: number
description: 价格
responses:
200:
description: 'success' | 625941f33eb6a72ae02ecaf2 |
def _prepararCampo(self, campo: list) -> str: <NEW_LINE> <INDENT> raise NotImplementedError | Prepara el Campo como una cadena. | 625941f3460517430c394777 |
def to_json(self, raw_value): <NEW_LINE> <INDENT> return self.sequence_type.to_json(raw_value.values()) | Dict is saved as a sequence. | 625941f33539df3088e2e94f |
def describe_topics(mlModel): <NEW_LINE> <INDENT> vocab = mlModel.stages[0].vocabulary <NEW_LINE> ldaModel = mlModel.stages[2] <NEW_LINE> topics = ldaModel.describeTopics(15) <NEW_LINE> topics_rdd = topics.rdd <NEW_LINE> topic_words = topics_rdd .map(lambda row: row['termIndices']) .map(lambda idx_list: [... | Obtain topic words and weights from the LDA model.
Returns: topics -> List[Dict[str, float]]
A list of mappings between the top 15 topic words (str) and their weights
(float) for each topic. The length of the list equals the number of topics. | 625941f3187af65679ca5723 |
def get_dates(): <NEW_LINE> <INDENT> hasValidStart = False <NEW_LINE> hasValidEnd = False <NEW_LINE> start = None <NEW_LINE> end = None <NEW_LINE> while True: <NEW_LINE> <INDENT> if not hasValidStart: <NEW_LINE> <INDENT> start = raw_input("Enter start date (MM/DD/YYYY): ") <NEW_LINE> if not valid_date(start): <NEW_LINE... | Prompt the user for a start and end date.
This function will keep prompting until valid dates are entered.
Returns a tuple of start date and end date strings. | 625941f3462c4b4f79d1dcd2 |
def modsplit(module): <NEW_LINE> <INDENT> return tuple(module.split(".")) | Split module into submodules. | 625941f3c432627299f0524e |
def getAllMemberEmails(self): <NEW_LINE> <INDENT> mtool = getToolByName(self.context, 'portal_membership') <NEW_LINE> out = {} <NEW_LINE> for m in mtool.listMembers(): <NEW_LINE> <INDENT> email = m.getProperty('email').lower() <NEW_LINE> if email in out: <NEW_LINE> <INDENT> self.uploadLog("WARNING: %s used by both %s a... | Make lookup of member email addresses to ids | 625941f32c8b7c6e89b35dbf |
def test_help_constant_cannot_redefine(): <NEW_LINE> <INDENT> with pytest.raises(AttributeError): <NEW_LINE> <INDENT> constants.help.Checker_Dir = CANNOT_SET_CONSTANT_VARIABLE <NEW_LINE> <DEDENT> with pytest.raises(AttributeError): <NEW_LINE> <INDENT> constants.help.No_Welcome = CANNOT_SET_CONSTANT_VARIABLE <NEW_LINE> ... | Check cannot redefine the variables in the help constant. | 625941f3a4f1c619b28b062d |
def read(self): <NEW_LINE> <INDENT> if os.path.exists(self.path) and os.path.isfile(self.path): <NEW_LINE> <INDENT> with open(self.path, 'rb') as f: <NEW_LINE> <INDENT> lines = f.readall() <NEW_LINE> return lines | 读取. | 625941f3d7e4931a7ee9e523 |
def _addNoise(self): <NEW_LINE> <INDENT> self.dispNoise = self.dispRaw.copy() <NEW_LINE> self.dispNoise[:,0] += self.sigmaEast * numpy.random.randn(self.numStations) <NEW_LINE> self.dispNoise[:,1] += self.sigmaNorth * numpy.random.randn(self.numStations) <NEW_LINE> self.dispNoise[:,2] += self.sigmaUp * numpy.random.ran... | Function to add noise to computed displacements. | 625941f3167d2b6e31219198 |
def addDigits(self, num): <NEW_LINE> <INDENT> s = str(num) <NEW_LINE> if len(s)==1: <NEW_LINE> <INDENT> return int(s) <NEW_LINE> <DEDENT> while len(s)!=1: <NEW_LINE> <INDENT> parSum = 0 <NEW_LINE> for i in range(0,len(s)): <NEW_LINE> <INDENT> parSum = parSum + int(s[i]) <NEW_LINE> <DEDENT> s = str(parSum) <NEW_LINE> <D... | :type num: int
:rtype: int | 625941f32ae34c7f2600d733 |
def setFileTemplate(self, name): <NEW_LINE> <INDENT> pass | void QTemporaryFile.setFileTemplate(QString name) | 625941f35f7d997b871750a1 |
def _outp(s, text_to_normalise): <NEW_LINE> <INDENT> t = text_to_normalise <NEW_LINE> if len(t) != 14: return t <NEW_LINE> return "{}.{}.{}/{}-{}".format(t[0:2], t[2:5], t[5:8], t[8:12], t[12:14]) | format: 00.000.000/0001-00 | 625941f3f8510a7c17cf9d05 |
def extract_tables(self, file, *, file_content_type=None, model=None, **kwargs): <NEW_LINE> <INDENT> if file is None: <NEW_LINE> <INDENT> raise ValueError('file must be provided') <NEW_LINE> <DEDENT> headers = {} <NEW_LINE> if 'headers' in kwargs: <NEW_LINE> <INDENT> headers.update(kwargs.get('headers')) <NEW_LINE> <DE... | Extract a document's tables.
Analyzes the tables in a document.
:param file file: The document on which to run table extraction.
:param str file_content_type: (optional) The content type of file.
:param str model: (optional) The analysis model to be used by the service.
For the **Element classification** and *... | 625941f330dc7b7665901f62 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.