code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _construct_angles(self): <NEW_LINE> <INDENT> if not hasattr(self, "_angles"): <NEW_LINE> <INDENT> self._construct_bonded_atoms_list() <NEW_LINE> self._angles = set() <NEW_LINE> for atom1 in self._atoms: <NEW_LINE> <INDENT> for atom2 in self._bondedAtoms[atom1]: <NEW_LINE> <INDENT> for atom3 in self._bondedAtoms[ato... | Get an iterator over all i-j-k angles. | 625941b794891a1f4081b8d8 |
def player_title(player_name: str) -> None: <NEW_LINE> <INDENT> player_name += ' cards' <NEW_LINE> len_title_line: int = ( (int(term_width / 2) - int((len(player_name) / 2) + 1)) + (int(term_width / 2) - int((len(player_name) / 2) + 1)) + len(player_name) ) + 2 <NEW_LINE> end_sep_count: int = 2 if (len_title_line > ter... | Function print separator with player name | 625941b730bbd722463cbbf2 |
@login_required <NEW_LINE> def admin(request): <NEW_LINE> <INDENT> all_tags = Tag.objects.all().values_list("name", flat=True) <NEW_LINE> if request.method == "POST" and request.user.is_superuser: <NEW_LINE> <INDENT> image_list = request.FILES.getlist("imagedata") <NEW_LINE> tags = filter(lambda s:s!="", request.POST[... | 管理画面 | 625941b7fb3f5b602dac34be |
def remainder_(self, divisor): <NEW_LINE> <INDENT> return self.arithmetic_operation(divisor, "remainder", 'FloatTensor') | Computes the element-wise remainder of division, inplace.
Parameters
----------
Returns
-------
FloatTensor
Caller with values inplace | 625941b7b57a9660fec336b0 |
def show_virtual_network(self, uuid): <NEW_LINE> <INDENT> url = '/virtual-network/%s' % uuid <NEW_LINE> return self.get(url) | :param uuid:
:return: | 625941b74e4d5625662d420d |
def load_number_around_mines(self): <NEW_LINE> <INDENT> for row in range(self.HEIGHT): <NEW_LINE> <INDENT> for col in range(self.WIDTH): <NEW_LINE> <INDENT> self.set_number(row, col) | load amount of mines around cell with a mine | 625941b78e05c05ec3eea1a1 |
def getChunk( aList, chunkSize ): <NEW_LINE> <INDENT> for i in range( 0, len( aList ), chunkSize ): <NEW_LINE> <INDENT> yield aList[i:i + chunkSize] | Generator yielding chunk from a list of a size chunkSize.
:param list aList: list to be splitted
:param integer chunkSize: lenght of one chunk
:raise: StopIteration
Usage:
>>> for chunk in getChunk( aList, chunkSize=10):
process( chunk ) | 625941b7f548e778e58cd3ac |
@nox.session(python=DEFAULT_PYTHON_VERSION) <NEW_LINE> def mypy_samples(session): <NEW_LINE> <INDENT> session.install("-e", ".[all]") <NEW_LINE> session.install("ipython", "pytest") <NEW_LINE> session.install(MYPY_VERSION) <NEW_LINE> session.install("types-mock", "types-pytz") <NEW_LINE> session.install("typing-extensi... | Run type checks with mypy. | 625941b7091ae35668666d96 |
def isValidMask(mask): <NEW_LINE> <INDENT> p = re.compile(IRC_HOSTMASK_REGEX) <NEW_LINE> return p.match(mask) != None | Returns True if "/xaop add" supplied "mask" is a valid hostmask | 625941b750485f2cf553cbc9 |
def __init__(self, source=None, preserve=1): <NEW_LINE> <INDENT> self.data = {} <NEW_LINE> self.preserve=preserve <NEW_LINE> if source : <NEW_LINE> <INDENT> self.update(source) | Create an empty dictionary, or update from 'dict'. | 625941b797e22403b379cdc9 |
def updateUserProfile(self, authzToken, userProfile): <NEW_LINE> <INDENT> self.send_updateUserProfile(authzToken, userProfile) <NEW_LINE> return self.recv_updateUserProfile() | Parameters:
- authzToken
- userProfile | 625941b7a79ad161976cbf76 |
def reload_allocations(self): <NEW_LINE> <INDENT> if not self._enable_dhcp(): <NEW_LINE> <INDENT> self.disable() <NEW_LINE> LOG.debug('Killing dnsmasq for network since all subnets have ' 'turned off DHCP: %s', self.network.id) <NEW_LINE> return <NEW_LINE> <DEDENT> self._release_unused_leases() <NEW_LINE> self._spawn_o... | Rebuild the dnsmasq config and signal the dnsmasq to reload. | 625941b7de87d2750b85fbbe |
def wait_for_job(cook_url, job_id, status, max_wait_ms=DEFAULT_TIMEOUT_MS): <NEW_LINE> <INDENT> return wait_for_jobs(cook_url, [job_id], status, max_wait_ms)[0] | Wait for the given job's status to change to the specified value. | 625941b745492302aab5e0f0 |
def validate_response_contains_expected_response(self, json_actual_response, expected_response_dict, ignored_keys=None, full_list_validation=False, identity_key="", sort_lists=False, **kwargs): <NEW_LINE> <INDENT> if not json_actual_response: <NEW_LINE> <INDENT> zoomba.fail("The Actual Response is Empty.") <NEW_LINE> r... | This is the most used method for validating Request responses from an API against a supplied
expected response. It performs an object to object comparison between two json objects, and if that fails,
a more in depth method is called to find the exact discrepancies between the values of the provided objects.
Additionall... | 625941b766656f66f7cbbfda |
def isWordGuessed(secretWord, lettersGuessed): <NEW_LINE> <INDENT> charB = " " <NEW_LINE> n=0 <NEW_LINE> n2=0 <NEW_LINE> result =0 <NEW_LINE> charA = lettersGuessed[n2] <NEW_LINE> charB = secretWord[n] <NEW_LINE> while True: <NEW_LINE> <INDENT> if result == len(secretWord): <NEW_LINE> <INDENT> return True <NEW_LINE> <... | secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise | 625941b76aa9bd52df036bd2 |
def __len__(self): <NEW_LINE> <INDENT> return self.npoints | Return length of result set | 625941b7236d856c2ad4460f |
def __trunc__(a): <NEW_LINE> <INDENT> if a._numerator < 0: <NEW_LINE> <INDENT> return -(-a._numerator // a._denominator) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return a._numerator // a._denominator | math.trunc(a) | 625941b732920d7e50b27ffc |
def _json(self): <NEW_LINE> <INDENT> d = {} <NEW_LINE> for k, v in self.items(): <NEW_LINE> <INDENT> if isinstance(v, InsensitiveDict): <NEW_LINE> <INDENT> d[k] = v._json() <NEW_LINE> <DEDENT> elif type(v) in (list, tuple): <NEW_LINE> <INDENT> l = [] <NEW_LINE> for i in v: <NEW_LINE> <INDENT> if isinstance(i, Insensiti... | converts an InsensitiveDict to a dictionary | 625941b7090684286d50eb10 |
def _exclude_items(self, section, items): <NEW_LINE> <INDENT> save_groups = [] <NEW_LINE> for item in items: <NEW_LINE> <INDENT> group = self._get_group(item) <NEW_LINE> if group is not None: <NEW_LINE> <INDENT> add_group = False <NEW_LINE> perms = getattr(group, self.group_perms_key) <NEW_LINE> for i in range(len(perm... | Remove groups from a permission.
:param section: The name of the permission to remove groups from.
:param items: A list containing names of groups to remove from the permission. | 625941b767a9b606de4a7ced |
@contextmanager <NEW_LINE> def chmod(path, mode): <NEW_LINE> <INDENT> orig_mode = stat.S_IMODE(os.stat(path).st_mode) <NEW_LINE> os.chmod(path, mode) <NEW_LINE> try: <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.chmod(path, orig_mode) <NEW_LINE> <DEDENT> except E... | Changes path permissions.
Change the permissions of path to the numeric mode before entering the
context, and restore the original value when exiting from the context.
Arguments:
path (str): file/directory path
mode (int): new mode | 625941b7f8510a7c17cf9535 |
def __init__(self): <NEW_LINE> <INDENT> self.host = '10.0.0.247' <NEW_LINE> self.port = 3306 <NEW_LINE> self.user = 'pamodata' <NEW_LINE> self.passwd = 'pamodata' <NEW_LINE> self.db = 'db_pamodata' <NEW_LINE> self.charset = 'utf8mb4' | 初始化 | 625941b773bcbd0ca4b2beae |
def add_basic_contact_brick(self, varname_u, multname_n, multname_t=None, *args): <NEW_LINE> <INDENT> return self.set("add_basic_contact_brick", varname_u, multname_n, multname_t, *args) | Synopsis: ind = Model.add_basic_contact_brick(self, string varname_u, string multname_n[, string multname_t], string dataname_r, Spmat BN[, Spmat BT, string dataname_friction_coeff][, string dataname_gap[, string dataname_alpha[, int augmented_version[, string dataname_gamma, string dataname_wt]]])
Add a contact with ... | 625941b7d486a94d0b98df7f |
def on_motion(event): <NEW_LINE> <INDENT> global _clock_window <NEW_LINE> delta_x = event.x - _clock_window.x <NEW_LINE> delta_y = event.y - _clock_window.y <NEW_LINE> res_x = _clock_window.winfo_x() + delta_x <NEW_LINE> res_y = _clock_window.winfo_y() + delta_y <NEW_LINE> _clock_window.geometry("+"+str(res_x)+"+"+str(... | on_motion docs | 625941b7d4950a0f3b08c18b |
def create_from_uri(uri): <NEW_LINE> <INDENT> result = None <NEW_LINE> root, ext = os.path.splitext(uri) <NEW_LINE> if ext.lower() == '.shelve' or ext.lower() == '.shelf': <NEW_LINE> <INDENT> result = ShelveReader(uri) <NEW_LINE> <DEDENT> return result | A shelve file is a .shelve
| 625941b73539df3088e2e17c |
def __setup__(self, experiment): <NEW_LINE> <INDENT> mid = experiment.mid <NEW_LINE> name = experiment.name <NEW_LINE> composition = info_table.get_composition(conn, mid) <NEW_LINE> notes = info_table.get_notes(conn, mid) <NEW_LINE> units = info_table.get_units(conn, mid) <NEW_LINE> type = info_table.get_type(conn, mid... | :param experiment:
:return: | 625941b78e7ae83300e4adfc |
def post(self): <NEW_LINE> <INDENT> request_json = request.get_json(silent=True) <NEW_LINE> username: str = request_json['username'] <NEW_LINE> avatar_url: str = request_json.get('avatar_url', '') <NEW_LINE> try: <NEW_LINE> <INDENT> user = UserRepository.create(username, avatar_url) <NEW_LINE> return user, 200 <NEW_LIN... | Create user | 625941b7d18da76e23532302 |
def star_helper(r, s): <NEW_LINE> <INDENT> temp = star_index(r, s) <NEW_LINE> if temp is False: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return regex_match(r, s[temp + 1:]) | (RegexTree, str) -> bool
This function takes the index where the part of the string matches the
regex tree, and call star case with everything after the string to see
if the rest of it matches, false if it does not match at all
>>> star_helper(StarTree(BarTree(Leaf('1'), Leaf('2'))), '12')
True
>>> star_helper(StarTree... | 625941b716aa5153ce3622a9 |
def test_issue3830_with_subtok(): <NEW_LINE> <INDENT> parser = DependencyParser(Vocab(), learn_tokens=True) <NEW_LINE> parser.add_label("nsubj") <NEW_LINE> assert "subtok" not in parser.labels <NEW_LINE> parser.begin_training(lambda: []) <NEW_LINE> assert "subtok" in parser.labels | Test that the parser does have subtok label if learn_tokens=True. | 625941b7aad79263cf39086c |
def SetPROJSearchPath(*args): <NEW_LINE> <INDENT> return _osr.SetPROJSearchPath(*args) | SetPROJSearchPath(char const * utf8_path) | 625941b738b623060ff0ac20 |
def print_text(text, *args, **kwargs): <NEW_LINE> <INDENT> print('text:' + text) | Print just the text value | 625941b7566aa707497f43ab |
def settings(): <NEW_LINE> <INDENT> return Settings(keypirinha_api.app_settings()) | Return the :py:class:`Settings` object associated with the application.
Note:
* Settings might change at any time if the end-user decides to edit the
configuration file. In thise case, the application will notify every
loaded plugins by calling :py:meth:`Plugin.on_events` with the
:py:const:`Even... | 625941b7627d3e7fe0d68c7f |
def volume_update_status_based_on_attachment(context, volume_id): <NEW_LINE> <INDENT> return IMPL.volume_update_status_based_on_attachment(context, volume_id) | Update volume status according to attached instance id | 625941b71d351010ab85594e |
def p_not_condition(p): <NEW_LINE> <INDENT> p[0] = (p[1], p[2], p[3]) | not_condition : NAME NOTEQUAL nis | 625941b75fc7496912cc37b7 |
def __match_trace(self, input_reader): <NEW_LINE> <INDENT> if (input_reader.trace): <NEW_LINE> <INDENT> print("Try: %s"%str(self)) <NEW_LINE> try: <NEW_LINE> <INDENT> m = self.__match(input_reader) <NEW_LINE> print('Match of rule type %s'%type(self)) <NEW_LINE> print(type(m)) <NEW_LINE> print("Done %s. Matched %s"%(str... | output a trace string indicating which rule is currently tried | 625941b707f4c71912b112b8 |
def neighboring_non_walls(self, pos): <NEW_LINE> <INDENT> for neighbor in util.iterate_neighbors(pos): <NEW_LINE> <INDENT> if not self.is_wall(neighbor): <NEW_LINE> <INDENT> yield neighbor | Find the non-walls neighboring the given position. | 625941b7a4f1c619b28afe73 |
def _add_commit_rtag(self, rtag_type, who): <NEW_LINE> <INDENT> self.commit.AddRtag(rtag_type, who) | Add a response tag to the current commit
Args:
rtag_type (str): rtag type (e.g. 'Reviewed-by')
who (str): Person who gave that rtag, e.g.
'Fred Bloggs <fred@bloggs.org>' | 625941b7e64d504609d74671 |
def send_alert(self, name: str, monitor: Monitor) -> None: <NEW_LINE> <INDENT> alert_type = self.should_alert(monitor) <NEW_LINE> command = None <NEW_LINE> downtime = monitor.get_downtime() <NEW_LINE> if monitor.is_remote(): <NEW_LINE> <INDENT> host = monitor.running_on <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hos... | Execute the command | 625941b7be7bc26dc91cd436 |
def save_target_urls(self, target_urls: List[str]): <NEW_LINE> <INDENT> for url in target_urls: <NEW_LINE> <INDENT> if url not in self.db_target_pages: <NEW_LINE> <INDENT> data, errs = TargetPage(strict=True).load({'page_url': url, 'status': False, 'note': '', 'extracted_at': ''}) <NEW_LINE> self.db_target_pages[url] =... | Save target URL into DB. | 625941b726068e7796caeb09 |
def fdmobilenet_w3d4(**kwargs): <NEW_LINE> <INDENT> return get_mobilenet(version="fd", width_scale=0.75, model_name="fdmobilenet_w3d4", **kwargs) | FD-MobileNet 0.75x model from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.tensorflow/models'
Location for keeping the mod... | 625941b7adb09d7d5db6c5c4 |
@add_method(Case) <NEW_LINE> def nnc_connections_static_values_async(self, property_name): <NEW_LINE> <INDENT> return self.__nnc_connections_values_async( property_name, NNCProperties_pb2.NNC_STATIC, 0 ) | Get the static NNC values. Async, so returns an iterator.
Returns:
An iterator to a chunk object containing an list of doubles.
Loop through the chunks and then the values within the chunk to get values
for all the connections. The order of the list matches the list from
nnc_connections, i.e. the nth o... | 625941b7097d151d1a222c8d |
def setDefaultColormap(self, colormap=None): <NEW_LINE> <INDENT> self._plot.setDefaultColormap(colormap) | Sets the colormap that will be applied by the backend to an image
if no colormap is applied to it.
A colormap is a dictionary with the keys:
:type name: string
:type normalization: string (linear, log)
:type autoscale: boolean
:type vmin: float, minimum value
:type vmax: float, maximum value
:type colors: integer (typi... | 625941b726068e7796caeb0a |
def GetNext(self, prev): <NEW_LINE> <INDENT> next = [] <NEW_LINE> prev_pos = self._cities[prev.Value] <NEW_LINE> for name, position in self._cities.items(): <NEW_LINE> <INDENT> if name != prev.Value: <NEW_LINE> <INDENT> next.append(SearchNode(name, self._distance(prev_pos, position))) <NEW_LINE> <DEDENT> <DEDENT> retur... | Return children nodes
:param prev: previous node
:return: Children | 625941b796565a6dacc8f506 |
def __init__(self, method, host, port): <NEW_LINE> <INDENT> self.port = port <NEW_LINE> self.method = method <NEW_LINE> self.host = host <NEW_LINE> self.token = None <NEW_LINE> self.default_port = None <NEW_LINE> self._remote = None <NEW_LINE> self._callback = None | Initialize Bridge. | 625941b7379a373c97cfa97c |
def get( self, location_name, name, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = "2018-09-15" <NEW_LINE> acce... | Get operation.
:param location_name: The name of the location.
:type location_name: str
:param name: The name of the operation.
:type name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: OperationResult, or the result of cls(response)
:rtype: ~azure.mgmt.devtestla... | 625941b7fbf16365ca6f5fed |
def signal_rshift(shift: int) -> Callable[[int], int]: <NEW_LINE> <INDENT> return lambda x: limit_signal(x >> shift) | A circuit element performing a fixed RSHIFT on a signal. | 625941b77c178a314d6ef28a |
def test_authority_ids_none(self): <NEW_LINE> <INDENT> from querying import get_authority_ids <NEW_LINE> authors = [ ([('0', 'CERN12345')], ' ', ' ', '', 1), ([('i', 'inspire')], ' ', ' ', '', 1), ([('u', 'INSPIRE-123')], ' ', ' ', '', 1), ([('0', 'INSPIRE-')], ' ', ' ', '', 1), ([('0', 'CERN-')], ' ', ' ', '', 1), ([(... | Test `author` objects by expecting empty dictionary. | 625941b7d99f1b3c44c673c9 |
def get_embed(input_data, vocab_size, embed_dim): <NEW_LINE> <INDENT> embedding = tf.Variable(tf.truncated_normal((vocab_size,embed_dim),mean = 0,stddev= 0.1)) <NEW_LINE> embed = tf.nn.embedding_lookup(embedding,input_data) <NEW_LINE> return embed | Create embedding for <input_data>.
:param input_data: TF placeholder for text input.
:param vocab_size: Number of words in vocabulary.
:param embed_dim: Number of embedding dimensions
:return: Embedded input. | 625941b7004d5f362079a168 |
def restoreTabs(self): <NEW_LINE> <INDENT> fileList = self.configuration.setting("ListOfOpenFilesAndPanels") <NEW_LINE> for i in range(0, len(fileList), 2): <NEW_LINE> <INDENT> panel = int(fileList[i + 1]) <NEW_LINE> self.loadFile(fileList[i], True, panel) <NEW_LINE> <DEDENT> self.splitter.restoreState(self.configurati... | restores tabs based on the last saved session | 625941b7e8904600ed9f1d5a |
def xkcd_palette(colors): <NEW_LINE> <INDENT> palette = [xkcd_rgb[name] for name in colors] <NEW_LINE> return color_palette(palette, len(palette)) | Make a palette with color names from the xkcd color survey.
This is just a simple wrapper around the seaborn.xkcd_rbg dictionary.
See xkcd for the full list of colors: http://xkcd.com/color/rgb/ | 625941b7bde94217f3682c2e |
def delta(self, enemy_position, target_position): <NEW_LINE> <INDENT> coordinates = [x - y for x, y in zip(enemy_position, target_position)] <NEW_LINE> return sum(int(math.fabs(x)) for x in coordinates) | Find the distance in tiles to the target | 625941b78a43f66fc4b53e9b |
def sale_records_info(sale, features): <NEW_LINE> <INDENT> invoice = sale.invoice <NEW_LINE> sale_features = [x for x in SALE_FEATURES if x in features] <NEW_LINE> course_reg_features = [x for x in COURSE_REGISTRATION_FEATURES if x in features] <NEW_LINE> sale_dict = dict((feature, getattr(invoice, feature)) for featur... | Convert sales records to dictionary | 625941b73d592f4c4ed1ceb2 |
def fbank(signal,samplerate=16000,winlen=0.025,winstep=0.01, nfilt=26,nfft=512,lowfreq=0,highfreq=None,preemph=0.97): <NEW_LINE> <INDENT> highfreq= highfreq or samplerate/2 <NEW_LINE> signal = sigproc.preemphasis(signal,preemph) <NEW_LINE> frames = sigproc.framesig(signal, winlen*samplerate, winstep*samplerate) <NEW_LI... | Compute Mel-filterbank energy features from an audio signal.
:param signal: the audio signal from which to compute features. Should be an N*1 array
:param samplerate: the samplerate of the signal we are working with.
:param winlen: the length of the analysis window in seconds. Default is 0.025s (25 milliseconds)
:param... | 625941b7d6c5a10208143e79 |
def __init__( self, location_map={}, minified=False, asset_version=None, default_location=None): <NEW_LINE> <INDENT> self.location_map = location_map <NEW_LINE> self.minified = minified <NEW_LINE> self.asset_version = asset_version <NEW_LINE> self.default_location = default_location <NEW_LINE> if self.default_location ... | Constructor
Args:
location_map (dict): An hash with the default AssetLocation instances available
minified (bool): If true, the minified version of the resources are returned
asset_version (str): The default version of the assets to be returned
default_location (str): The default location used, when is asked for the i... | 625941b7796e427e537b03f4 |
def data_entry(): <NEW_LINE> <INDENT> with open('/home/jaremciuc/data_analysis_test/assignment_data.csv') as fin: <NEW_LINE> <INDENT> c = db.cursor() <NEW_LINE> dr = csv.DictReader(fin) <NEW_LINE> to_db = [(i['id'], i['title'], i['features'], i['living_area'], i['total_area'], i['plot_area'], i['price']) for i in dr] <... | Inserts the data into the database | 625941b723e79379d52ee39a |
def cmd_unmaximize(ensoapi): <NEW_LINE> <INDENT> cmd_restore(ensoapi) | Unmaximize window if it is maximized | 625941b77b25080760e3928c |
def get_detector_for_component(move_info, component): <NEW_LINE> <INDENT> detectors = move_info.detectors <NEW_LINE> selected_detector = None <NEW_LINE> if component == "HAB": <NEW_LINE> <INDENT> selected_detector = detectors[DetectorType.to_string(DetectorType.HAB)] <NEW_LINE> <DEDENT> elif component == "LAB": <NEW_LI... | Get the detector for the selected component.
The detector can be either an actual component name or a HAB, LAB abbreviation
:param move_info: a SANSStateMove object
:param component: the selected component
:return: an equivalent detector to teh selected component or None | 625941b7d10714528d5ffb11 |
def want_to_rest(self): <NEW_LINE> <INDENT> if self.resting_time > 0: <NEW_LINE> <INDENT> self.resting_time -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.random.random() <= 0.5: <NEW_LINE> <INDENT> self.resting_status = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.resting_status = 0 <NEW_LINE> <DED... | Returns if the agent wants to rest.
| 625941b730dc7b766590179c |
def from_api_response(self, file_version_dict, force_action=None): <NEW_LINE> <INDENT> assert file_version_dict.get('action') is None or force_action is None, 'action was provided by both info_dict and function argument' <NEW_LINE> action = file_version_dict.get('action') or force_action <NEW_LINE> file_name... | Turn this:
.. code-block:: python
{
"action": "hide",
"fileId": "4_zBucketName_f103b7ca31313c69c_d20151230_m030117_c001_v0001015_t0000",
"fileName": "randomdata",
"size": 0,
"uploadTimestamp": 1451444477000
}
or this:
.. code-block:: python
{
"accountId": "4aa9865... | 625941b7097d151d1a222c8e |
def _is_in_range(self, creep): <NEW_LINE> <INDENT> if not creep or not creep.active or creep.dead: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self._get_distance_to_creep(creep) <= self.bounding_radius | checks whether the creep is in range | 625941b7d18da76e23532303 |
def __init__(self, spec): <NEW_LINE> <INDENT> super(AcsKubernetesCluster, self).__init__(spec) <NEW_LINE> self.resource_group = azure_network.GetResourceGroup(self.zone) <NEW_LINE> self.name = 'pkbcluster%s' % FLAGS.run_uri <NEW_LINE> self._deleted = False | Initializes the cluster. | 625941b7b57a9660fec336b1 |
def test_vectorial_operation(): <NEW_LINE> <INDENT> lha = 123 * u.degree <NEW_LINE> dec = 42.3213 * u.degree <NEW_LINE> rotation = xyz_to_uvw_rotation_matrix(lha, dec) <NEW_LINE> xyz_vec_tuple = (e_x, e_x, e_y, e_z, e_y, e_z) <NEW_LINE> uvw_expected_results = [] <NEW_LINE> for vec in xyz_vec_tuple: <NEW_LINE> <INDENT> ... | It's desirable to make use of Numpy's vector optimizations and transform
many XYZ positions in one go, so let's see if that works correctly: | 625941b7eab8aa0e5d26d990 |
def __init__(self, target, payload_provider, timeout, socket_options=(), seed_id=None, verbose=False, output=sys.stdout): <NEW_LINE> <INDENT> self.socket = network.Socket(target, 'icmp', source=None, options=socket_options) <NEW_LINE> self.provider = payload_provider <NEW_LINE> self.timeout = timeout <NEW_LINE> self.re... | Creates an instance that can handle communication with the target device
:param target: IP or hostname of the remote device
:type target: str
:param payload_provider: An iterable list of payloads to send
:type payload_provider: PayloadProvider
:param timeout: Timeout that will apply to all ping messages, in seconds
:t... | 625941b78e7ae83300e4adfd |
def test_get_info(self): <NEW_LINE> <INDENT> ddoc = DesignDocument(self.db, '_design/ddoc001') <NEW_LINE> ddoc.save() <NEW_LINE> ddoc_remote = DesignDocument(self.db, '_design/ddoc001') <NEW_LINE> ddoc_remote.fetch() <NEW_LINE> info = ddoc_remote.info() <NEW_LINE> info['view_index'].pop('signature') <NEW_LINE> if 'disk... | Test retrieval of info endpoint from the DesignDocument. | 625941b7d53ae8145f87a0a8 |
def _set_up(self): <NEW_LINE> <INDENT> pass | Subclasses my decorate this as a coroutine | 625941b70a50d4780f666cc1 |
def __init__(self): <NEW_LINE> <INDENT> self.screen_width = 1200 <NEW_LINE> self.screen_height = 800 <NEW_LINE> self.bg_color = (230, 230, 230) <NEW_LINE> self.ship_speed_factor = 1.5 <NEW_LINE> self.ship_limit = 3 <NEW_LINE> self.bullet_speed_factor = 3 <NEW_LINE> self.bullet_width = 3 <NEW_LINE> self.bullet_height = ... | 初始化屏幕设置 | 625941b72c8b7c6e89b355f5 |
def roles_dict(path, repo_prefix=""): <NEW_LINE> <INDENT> exit_if_path_not_found(path) <NEW_LINE> aggregated_roles = {} <NEW_LINE> roles = os.walk(path).next()[1] <NEW_LINE> for role in roles: <NEW_LINE> <INDENT> if is_role(os.path.join(path, role)): <NEW_LINE> <INDENT> if isinstance(role, basestring): <NEW_LINE> <INDE... | Return a dict of role names and repo paths. | 625941b7d58c6744b4257a92 |
def job_failed( self, job_wrapper, message, exception=False ): <NEW_LINE> <INDENT> pass | Called when a job has failed | 625941b721bff66bcd684787 |
def stemWord(word): <NEW_LINE> <INDENT> global porter <NEW_LINE> return porter.stem(word) | Stems the given word using the Porter Stemmer library
Parameters
----------
word : String type
A word to be stemmed
Returns
-------
stemmedWord : String type
The stemmed version of the given word | 625941b71b99ca400220a8e2 |
def set_file_log(self): <NEW_LINE> <INDENT> logging.basicConfig(filename=self.FILE_LOG_DEBUG, datefmt="[%Y-%m-%d %H:%M]", format="%(asctime)s - %(name)-2s %(levelname)-2s %(message)s", filemode='a', level=logging.DEBUG) <NEW_LINE> self.log = logging.getLogger(CondeConstants().LOGGER_NAME) <NEW_LINE> formatter = logging... | Set log file.
Args:
None
Returns:
None | 625941b797e22403b379cdca |
def initialize_tree(BST): <NEW_LINE> <INDENT> if isinstance(BST,tuple): <NEW_LINE> <INDENT> return (initialize_tree(BST[0]),initialize_tree(BST[1])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return BST[0] | that takes a BST and returns a copy of that tree with all the leaves replaced by their first characters
BST -> str | 625941b763b5f9789fde6f17 |
def enter_selection_set( self, node: SelectionSetNode, key: Any, parent: Any, path: List[Any], ancestors: List[Any] ) -> None: <NEW_LINE> <INDENT> selections = node.selections <NEW_LINE> if len(selections) == 1 and isinstance(selections[0], InlineFragmentNode): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_... | Check selections are valid.
If selections contains an InlineFragment, check that it is the only inline fragment in
scope. Otherwise, check that property fields occur before vertex fields.
Args:
node: selection set
key: The index or key to this node from the parent node or Array.
parent: the parent immedia... | 625941b750812a4eaa59c158 |
def get_cost_updates(self, lr=0.1, persistent=None, k=1): <NEW_LINE> <INDENT> n_vis = self.n_visible <NEW_LINE> n_hid = self.n_hidden <NEW_LINE> pre_sigmoid_ph, ph_mean, ph_sample = self.sample_h_given_v(self.input) <NEW_LINE> tf.assert_rank(ph_sample, 2) <NEW_LINE> _, pv_mean, _ = self.sample_v_given_h(ph_sample) <NEW... | This functions implements one step of CD-k (PCD-k)
args.:
lr : learning rate used to train the RBM
persistent: None for CD. For PCD, shared variable
containing old state of Gibbs chain. This must be a shared
variable of size (batch size, number of hidden units).
k : number of Gibbs steps t... | 625941b70a366e3fb873e649 |
def make_pastmaclist(): <NEW_LINE> <INDENT> db.pastdata.aggregate([ {"$group": {"_id": {"mac":"$mac"}, }, }, {"$out": "pastmaclist"}, ], allowDiskUse=True, ) | pastdataコレクションから過去データ(1min)に含まれるmacアドレスを抽出した
pastmaclistコレクションを作成する | 625941b7462c4b4f79d1d502 |
def score(self, emit, target, mask): <NEW_LINE> <INDENT> sen_len, batch_size, labels_num = emit.shape <NEW_LINE> assert (labels_num==self.labels_num) <NEW_LINE> scores = torch.zeros_like(target, dtype=torch.float) <NEW_LINE> scores[1:] += self.transitions[target[:-1], target[1:]] <NEW_LINE> scores += emit.gather(dim=2,... | author: zhangyu
return: sum(score) | 625941b799cbb53fe6792a19 |
def validate(data, required_fields): <NEW_LINE> <INDENT> if all(field in data for field in required_fields): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Validate if all required_fields are in the given data dictionary | 625941b7a17c0f6771cbde86 |
def event_attach(self, eventtype, callback, *args, **kwds): <NEW_LINE> <INDENT> if not isinstance(eventtype, EventType): <NEW_LINE> <INDENT> raise VLCException("%s required: %r" % ('EventType', eventtype)) <NEW_LINE> <DEDENT> if not hasattr(callback, '__call__'): <NEW_LINE> <INDENT> raise VLCException("%s required: %r"... | Register an event notification.
@param eventtype: the desired event type to be notified about.
@param callback: the function to call when the event occurs.
@param args: optional positional arguments for the callback.
@param kwds: optional keyword arguments for the callback.
@return: 0 on success, ENOMEM on error.
@note... | 625941b7b5575c28eb68de2f |
def test02_distributionZSHY(self): <NEW_LINE> <INDENT> self.zo = Page_ZSHY_distribution(self.driver) <NEW_LINE> self.username = Config().get('HZ_NAME') <NEW_LINE> distribution = getData(2, "HZ_ZSHY") <NEW_LINE> self.A.IntoModule("帐号2直属会员4") <NEW_LINE> i = self.driver.find_element_by_id("mainIframe") <NEW_LINE> self.dri... | 对直属会员发放 | 625941b79f2886367277a6c3 |
def frequency_list_sorting_with_counter(elements: list): <NEW_LINE> <INDENT> frequency = Counter(elements) <NEW_LINE> sorted_frequency = frequency.most_common() <NEW_LINE> result = [] <NEW_LINE> for key, value in sorted_frequency: <NEW_LINE> <INDENT> result.append(key) <NEW_LINE> <DEDENT> return result | Reduce the list to unique elements and sort them by frequency
>>> frequency_list_sorting_with_counter([1, 2, 1, 3, 3, 3, 3])
[3, 1, 2]
>>> frequency_list_sorting_with_counter([1, 2, 1, 2, 3, 3])
[1, 2, 3]
>>> frequency_list_sorting_with_counter(['c', 'c', 'b', 'b', 'b', 'a'])
['b', 'c', 'a'] | 625941b791af0d3eaac9b846 |
def take_snapshot(snapmeta): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> logging.warn("Taking snapshot of " + str(snapmeta)) <NEW_LINE> ec2 = boto3.client('ec2') <NEW_LINE> response = ec2.create_snapshot( Description='Automated snap of {} at {} from instance {} named {}'.format(snapmeta['volume'], snapmeta['DeviceName... | Takes a snapshot, tagging it with the meta data of the instance the volume is attached to | 625941b74527f215b584c28d |
def launchBenchCast(num_cpus, app_list, outfile, config, bench_cast_seconds, event_file): <NEW_LINE> <INDENT> printColor("Launching bench_cast with apps: %s" % app_list, "blue") <NEW_LINE> exec_cmd = "./bench_cast -c %s -v %s -s %d -l 2 -p %d -e %s %s" % ( config, outfile, bench_cast_seconds, num_cpus, event_file, app_... | Launch BENCHCAST | 625941b71b99ca400220a8e3 |
def test_wrong_data_raise(): <NEW_LINE> <INDENT> signal_interpreter_app.testing = True <NEW_LINE> signal_interpreter_app_instance = signal_interpreter_app.test_client() <NEW_LINE> with patch.object( LoadAndParseJson, "return_signal_by_title", return_value="Service not suported!"): <NEW_LINE> <INDENT> with signal_interp... | Action : Test mocking server answer.
Expected Results : No difference from normal application usage.
Returns: N/A. | 625941b7dd821e528d63afde |
def _create_sequence(in_q, out_q): <NEW_LINE> <INDENT> for args in iter(in_q.get, THREAD_STOP): <NEW_LINE> <INDENT> out_q.put(Sequence(args[0], args[1])) | Create sequence worker process
Input:
in_q: multiprocessing.Queue; work queue
out_q; multiprocessing.Queue; sequence queue | 625941b76aa9bd52df036bd4 |
def set_max_speed(self, max_sp, board_ind=0): <NEW_LINE> <INDENT> board_ind = ctypes.c_int16(board_ind) <NEW_LINE> max_sp = ctypes.c_int16(max_sp) <NEW_LINE> self.cmd.send_command(4, (board_ind, max_sp)) | sets the max speed to integer value specified | 625941b7f9cc0f698b140438 |
def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> if (self.name in self.__class__.dataMap_.keys()): <NEW_LINE> <INDENT> self.mentions_ = self.__class__.dataMap_[self.name].mentions_ + 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.mentions_ = 1 <NEW_LINE> <DEDENT> super(Character, self).__... | Initializes a character.
Args:
name: A string containing the character's name. | 625941b7d53ae8145f87a0a9 |
def createDependencies(self, product, version, flavor=None, tag=None, recursive=False): <NEW_LINE> <INDENT> self.unimplemented("createDependencies") | create a list of product dependencies based on what is known from
the system.
This implementation will look up the product in the EUPS database and
analyze its table file.
A typical full implementation of this function in a sub-class would
call _createDeps() to get the initial list of dependencies, but then
ite... | 625941b7cb5e8a47e48b78e2 |
def start_game(stdscr): <NEW_LINE> <INDENT> black_player, white_player = select_players(stdscr) <NEW_LINE> play_game(stdscr, black_player, white_player) | Asks the user to select players for the white and black side and then
starts a new game of brandubh with the selected players. | 625941b724f1403a9260099c |
def has_network_field(value, key="name"): <NEW_LINE> <INDENT> def find(net): <NEW_LINE> <INDENT> return net[key] == value <NEW_LINE> <DEDENT> return find | Returns a function usable as a filter to list_neutron_nets
Usage::
active_pred = has_network_field("ACTIVE", key="status")
nets = list_neutron_nets(net_cl, filter_fn=active_pred)
:param value: The value (of key) to match against
:param key: the key in the network object to look up
:return: a predicate function t... | 625941b77cff6e4e811177b9 |
def user_details(request, stu_id=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user_dada = MyUser.objects.get(id=stu_id) <NEW_LINE> <DEDENT> except MyUser.DoesNotExist: <NEW_LINE> <INDENT> messages.error(request, "User Does not exist") <NEW_LINE> return HttpResponseRedirect("/") <NEW_LINE> <DEDENT> else: <NEW_LIN... | get user details
:param request: student_id
:return: | 625941b73c8af77a43ae35d1 |
def create_user(self, email, password=None): <NEW_LINE> <INDENT> if not email: <NEW_LINE> <INDENT> raise ValueError('Users must have an email address') <NEW_LINE> <DEDENT> user = self.model( email=self.normalize_email(email), ) <NEW_LINE> user.set_password(password) <NEW_LINE> user.save(using=self._db) <NEW_LINE> retur... | Creates and saves a User | 625941b744b2445a33931ed2 |
def fibsfun(num): <NEW_LINE> <INDENT> fibs = [0, 1] <NEW_LINE> for i in range(num): <NEW_LINE> <INDENT> fibs.append(fibs[-2] + fibs[-1]) <NEW_LINE> <DEDENT> return fibs | hahahahhah | 625941b7f8510a7c17cf9537 |
def run(): <NEW_LINE> <INDENT> logger = logging.getLogger("rc") <NEW_LINE> logger.setLevel(logging.INFO) <NEW_LINE> formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') <NEW_LINE> if args.log_path: <NEW_LINE> <INDENT> file_handler = logging.FileHandler(args.log_path) <NEW_LINE> file_han... | Prepares and runs the whole system. | 625941b7ab23a570cc24ffb2 |
def test_letter_count_single(): <NEW_LINE> <INDENT> copied_character_string = copies.mcopies_ofc("10") <NEW_LINE> assert len(copied_character_string) == 10 <NEW_LINE> assert copied_character_string.count("C") == 10 | Returns output with correct number of copies | 625941b73346ee7daa2b2b9c |
def showModalDialog(self): <NEW_LINE> <INDENT> if nukescripts.panels.PythonPanel.showModalDialog(self): <NEW_LINE> <INDENT> self.submit() | Shows the Zync Submit dialog and does the work to submit it. | 625941b7d8ef3951e3243370 |
def clean(params): <NEW_LINE> <INDENT> if os.path.isfile(params.vocab_file): <NEW_LINE> <INDENT> os.remove(params.vocab_file) <NEW_LINE> <DEDENT> if os.path.isfile(params.map_file): <NEW_LINE> <INDENT> os.remove(params.map_file) <NEW_LINE> <DEDENT> if os.path.isdir(params.ckpt_path): <NEW_LINE> <INDENT> shutil.rmtree(p... | 重新训练前清除函数
Clean current folder
remove saved model and training log | 625941b799cbb53fe6792a1a |
def allow(self, access_type, access): <NEW_LINE> <INDENT> self._validate_access(access_type, access) <NEW_LINE> return self.manager.allow(self, access_type, access) | Allow access to a share. | 625941b73539df3088e2e17e |
def get_open_orders(self): <NEW_LINE> <INDENT> orders = [] <NEW_LINE> for o in self.api.list_orders(): <NEW_LINE> <INDENT> orders.append([o.symbol, o.side, o.qty, o.filled_qty, o.submitted_at]) <NEW_LINE> <DEDENT> time.sleep(60/200) <NEW_LINE> return orders | Gets the users open orders from the Alpaca API as Python Lists | 625941b72ae34c7f2600cf64 |
def _playsoundWin(sound, block = True): <NEW_LINE> <INDENT> sound = '"' + _canonicalizePath(sound) + '"' <NEW_LINE> from ctypes import create_unicode_buffer, windll, wintypes <NEW_LINE> from time import sleep <NEW_LINE> windll.winmm.mciSendStringW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.UINT, wintypes... | Utilizes windll.winmm. Tested and known to work with MP3 and WAVE on
Windows 7 with Python 2.7. Probably works with more file formats.
Probably works on Windows XP thru Windows 10. Probably works with all
versions of Python.
Inspired by (but not copied from) Michael Gundlach <gundlach@gmail.com>'s mp3play:
https://git... | 625941b73cc13d1c6d3c71b7 |
def step(self): <NEW_LINE> <INDENT> self.get_info() <NEW_LINE> self.datacollector.collect(self) <NEW_LINE> self.schedule.step() | advance model by one step | 625941b7baa26c4b54cb0f56 |
def test_reordering_non_sequential(sorted_entries_gaps): <NEW_LINE> <INDENT> qs = SortedModel.objects <NEW_LINE> nodes = sorted_entries_gaps <NEW_LINE> operations = {nodes[5].pk: -1, nodes[2].pk: +3} <NEW_LINE> expected = _sorted_by_order( [ (nodes[0].pk, 0), (nodes[1].pk, 2), (nodes[2].pk, 4 + (3 * 2) - 1), (nodes[3].... | Ensures that reordering non-sequential sort order values is properly
handled. This case happens when an item gets deleted, creating gaps between values. | 625941b760cbc95b062c637c |
def set_timeout_async(f, timeout_ms = 0): <NEW_LINE> <INDENT> sublime_api.set_timeout_async(f, timeout_ms) | Schedules a function to be called in the future. The function will be
called in a worker thread, and Sublime Text will not block while the function is running | 625941b785dfad0860c3ac8b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.