code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def check_status(self, agent_positions): <NEW_LINE> <INDENT> if not self.dead and (self.sugar <= 0 or self.spice <= 0 or self.age == self.dying_age): <NEW_LINE> <INDENT> self.die(agent_positions) <NEW_LINE> <DEDENT> self.age += 1 | Check whether I'm still healthy and stuff | 625941c7d99f1b3c44c675d5 |
def split(s): <NEW_LINE> <INDENT> s = tuple(s) <NEW_LINE> size = len(s) <NEW_LINE> return s[:size//2], s[size//2:] | Split s into two roughly equal parts | 625941c75fdd1c0f98dc0278 |
def _cpshnext(self, args=None): <NEW_LINE> <INDENT> self.cpinfo['shtime'] = args['time'] <NEW_LINE> self.savestate() | handle cpshnext | 625941c710dbd63aa1bd2be9 |
def _add_self_references(namespace, autograph_module): <NEW_LINE> <INDENT> global ag_internal <NEW_LINE> if ag_internal is None: <NEW_LINE> <INDENT> ag_internal = imp.new_module('autograph') <NEW_LINE> ag_internal.__dict__.update(autograph_module.__dict__) <NEW_LINE> ag_internal.ConversionOptions = converter.Conversion... | Adds namespace references to the module that exposes the api itself. | 625941c7187af65679ca5163 |
def set_sticker_position_in_set(self, sticker, position): <NEW_LINE> <INDENT> return apihelper.set_sticker_position_in_set(self.token, sticker, position) | Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success.
:param sticker:
:param position:
:return: | 625941c72eb69b55b151c8f3 |
def __init__(self, width=640, height=400, fps=30): <NEW_LINE> <INDENT> pygame.init() <NEW_LINE> pygame.display.set_caption("Press ESC to quit") <NEW_LINE> self.width = width <NEW_LINE> self.height = height <NEW_LINE> self.screen = pygame.display.set_mode((self.width, self.height), pygame.DOUBLEBUF) <NEW_LINE> self.back... | Initialize pygame, window, background, font,...
default arguments | 625941c7d164cc6175782d92 |
@docfiller <NEW_LINE> def gaussian_filter1d(input, sigma, axis=-1, order=0, output=None, mode="reflect", cval=0.0, truncate=4.0): <NEW_LINE> <INDENT> if order not in range(4): <NEW_LINE> <INDENT> raise ValueError('Order outside 0..3 not implemented') <NEW_LINE> <DEDENT> sd = float(sigma) <NEW_LINE> lw = int(truncate * ... | One-dimensional Gaussian filter.
Parameters
----------
%(input)s
sigma : scalar
standard deviation for Gaussian kernel
%(axis)s
order : {0, 1, 2, 3}, optional
An order of 0 corresponds to convolution with a Gaussian
kernel. An order of 1, 2, or 3 corresponds to convolution with
the first, second or thi... | 625941c7e8904600ed9f1f70 |
def get_rcmd_users(user): <NEW_LINE> <INDENT> sex = user.profile.dating_sex <NEW_LINE> location = user.profile.location <NEW_LINE> min_age = user.profile.min_dating_age <NEW_LINE> max_age = user.profile.max_dating_age <NEW_LINE> current_year = datetime.date.today().year <NEW_LINE> min_year = current_year - min_age <NEW... | 获取用户列表
:param user:
:return:
max_year min_year current_year
----|-----------------|----------------|--------------|-------->
2018 2019 | 625941c7956e5f7376d70eb3 |
def play_theme(self): <NEW_LINE> <INDENT> songs = ['james_bond','glad_you_came'] <NEW_LINE> try: <NEW_LINE> <INDENT> pg.mixer.music.stop() <NEW_LINE> play_theme_song(songs[random.randint(0,1)],1) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> play_theme_song(songs[random.randint(0,1)],1) | Selects a random theme for the game | 625941c75e10d32532c5ef6c |
def test_iter(self): <NEW_LINE> <INDENT> self.__add_movies() <NEW_LINE> imdbList = list(self.movie_data) <NEW_LINE> self.assertListEqual( imdbList, ['tt0110912', 'tt0090605', 'tt0268978'], ) | Load movies and make sure the iterator returns the movies in the correct order | 625941c77047854f462a1450 |
def getModel(self, model, data, stringresponse=False): <NEW_LINE> <INDENT> apiurl = urljoin(self.api.scheme + '://', COGNIOUS_API_BASEURL, 'v1.0', model) <NEW_LINE> headers = self.api.headers <NEW_LINE> res = requests.post(apiurl, headers=headers, data=data) <NEW_LINE> if res.status_code == 200: <NEW_LINE> <INDENT> sel... | **DEPRICATED**
scheme = 'https' if parsed.scheme == '' else parsed.scheme
base_url = parsed.path if not parsed.netloc else parsed.netloc
self.base_url = base_url
self.scheme = scheme | 625941c750812a4eaa59c368 |
def _log_info(self, message, level=0, offset=0): <NEW_LINE> <INDENT> if level == 0 or (self._debug and self._debug_level >= level): <NEW_LINE> <INDENT> tf.logging.info("[LMS][{}] ".format(level) + ' '*offset + "{}".format(message)) | Log debug information.
Args:
message: a formatted string.
level: an `integer`. | 625941c7d4950a0f3b08c395 |
def test_user_cannot_retrieve_unregistered_person(self): <NEW_LINE> <INDENT> logger = logging.getLogger('django.request') <NEW_LINE> previous_level = logger.getEffectiveLevel() <NEW_LINE> logger.setLevel(logging.ERROR) <NEW_LINE> url = reverse( 'person-detail', kwargs={'person_guid': self.unregistered_driller.person_gu... | unauthorized request to person detail view. Note: now always returns 401 if not staff. | 625941c73c8af77a43ae37e4 |
def __len__(self): <NEW_LINE> <INDENT> return len(self.Serialize()) | Return a length of serialized packet . | 625941c797e22403b379cfdf |
def slot_style(self, style): <NEW_LINE> <INDENT> selection = self.editor.selection <NEW_LINE> if selection.isSelection(): <NEW_LINE> <INDENT> sm1, sm2 = selection.order() <NEW_LINE> tl = sm1[0].tline <NEW_LINE> self.rsubject.restyle(tl, sm2[0].tline.para, style) <NEW_LINE> selection.markSelection() <NEW_LINE> <DEDENT> ... | Handler for 'style' action - change style:
u"n"/normal, u"l"/special, u"r"/special/right-aligned | 625941c7c432627299f04c8a |
def check_solution(self, potential_solution): <NEW_LINE> <INDENT> old_k = self.K <NEW_LINE> new_k = potential_solution.set_K(self.len_connections) <NEW_LINE> delta = new_k - old_k <NEW_LINE> if delta >= 0: <NEW_LINE> <INDENT> probability = 1 <NEW_LINE> <DEDENT> probability = np.exp(delta / self.T) <NEW_LINE> if random.... | Calculates new and old K. Checks and accepts better solutions than the current solution.
Also sometimes accepts solutions that are worse, depending on the current temperature. | 625941c776d4e153a657eb76 |
def load_repos_info(channel_lookup): <NEW_LINE> <INDENT> with open(os.path.join(SCRIPT_DIR, "repos_info.json"), "r", encoding="utf-8") as f: <NEW_LINE> <INDENT> repos_info = json.load(f) <NEW_LINE> <DEDENT> infos = [ RepoInfo( name=repo_info["name"], repo_url=repo_info["repo_url"], ci_hash_url=( repo_info["ci_hash_url"... | Load repo information from JSON and looks up channel ids for each repo
Args:
channel_lookup (dict): Map of channel names to channel ids
Returns:
list of RepoInfo: Information about the repositories | 625941c7de87d2750b85fdd7 |
def remove(self, child): <NEW_LINE> <INDENT> if isinstance(child, JSONableDict): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del(self[child.name]) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> warnings.warn('{0} not found in dict when attempting removal'.format(child.name)) <NEW_LINE> <DEDENT> <DEDENT> else... | Remove a child node
Args:
child: An instance of JSONableDict
Raises:
AddRemoveError: :exc:`cfn_pyplates.exceptions.AddRemoveError` | 625941c7099cdd3c635f0ca1 |
def insert_object(self, index, obj): <NEW_LINE> <INDENT> self.__objects.insert(index, obj) | Insert an item before specific position.
:param index: The position.
:param obj: The object. | 625941c756ac1b37e6264217 |
def test_register(self): <NEW_LINE> <INDENT> def test_converter(session, value): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.translator.register('convert', test_converter) <NEW_LINE> assert_true(self.translator.converters.has_key('convert')) <NEW_LINE> assert_equals(len(self.translator.converters.keys()), 2) <NEW... | Test that the register method works as expected (i.e., registers the specified converter)
.. versionadded:: v00_03_00 | 625941c7cc40096d61595996 |
def _train_controller(self): <NEW_LINE> <INDENT> self._search_space.eval() <NEW_LINE> self._controller.train() <NEW_LINE> for _ in range(self._controller_max_steps): <NEW_LINE> <INDENT> dag, log_prob = self._controller() <NEW_LINE> self._search_space.dag = dag <NEW_LINE> batch = self._valid_iter.next() <NEW_LINE> input... | Training the controller parameters
Fix omega and update the policy parameters theta
the gradient is computed using REINFORCE, with a moving average baseline
to reduce variance. | 625941c7cc0a2c11143dced6 |
def minimum_x(x): <NEW_LINE> <INDENT> def decorator(fun): <NEW_LINE> <INDENT> def wrapper(y): <NEW_LINE> <INDENT> if y >= x: <NEW_LINE> <INDENT> fun(y) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> <DEDENT> return wrapper <NEW_LINE> <DEDENT> return decorator | Write a function decorator that takes an argument, and returns a decorator
that can be used to decorate a function, which verifies that the first
argument to a decorated function is at least the given value, raising a
ValueError on failure.
>>> @minimum_x(6)
... def test(arg):
... print arg
...
>>> test(6)
6
>>> tes... | 625941c75fc7496912cc39c3 |
def plusOne(self, digits): <NEW_LINE> <INDENT> for i in range(len(digits) - 1, -1, -1): <NEW_LINE> <INDENT> digits[i] += 1 <NEW_LINE> if digits[i] >= 10: <NEW_LINE> <INDENT> digits[i] = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return digits <NEW_LINE> <DEDENT> <DEDENT> digits.insert(0, 1) <NEW_LINE> return digit... | :type digits: List[int]
:rtype: List[int] | 625941c7bde94217f3682e37 |
def same(self): <NEW_LINE> <INDENT> return self.current_dict == self.past_dict | True if the two dicts are the same. | 625941c7bf627c535bc13214 |
def highlight_span(start=None, end=None, color='g', alpha=0.5, grapher=None): <NEW_LINE> <INDENT> if start is None and end is None: <NEW_LINE> <INDENT> raise Exception("strat and end cannot both be None") <NEW_LINE> <DEDENT> if grapher is None: <NEW_LINE> <INDENT> fig = charting.gcf() <NEW_LINE> grapher = fig.grapher <... | A quick shortcut way to highlight regions of a chart. Uses the Grapher.df.index
to translate non int-position arguments to int locations. | 625941c726068e7796caed23 |
def test_sensor_source(self): <NEW_LINE> <INDENT> assert setup_component( self.hass, "sensor", { "sensor": { "platform": "statistics", "name": "test", "entity_id": "sensor.test_monitored", } }, ) <NEW_LINE> self.hass.block_till_done() <NEW_LINE> self.hass.start() <NEW_LINE> self.hass.block_till_done() <NEW_LINE> for va... | Test if source is a sensor. | 625941c73317a56b86939ca0 |
def get_calendar_service(): <NEW_LINE> <INDENT> creds = None <NEW_LINE> if os.path.exists('token.pickle'): <NEW_LINE> <INDENT> with open('token.pickle', 'rb') as token: <NEW_LINE> <INDENT> creds = pickle.load(token) <NEW_LINE> <DEDENT> <DEDENT> if not creds or not creds.valid: <NEW_LINE> <INDENT> if creds and creds.exp... | Authenticates user with google, thene exports calendar service | 625941c7090684286d50ed2a |
def test_multpack4(self): <NEW_LINE> <INDENT> csv_file_as_str = ",123456,,123456,,123456\n" <NEW_LINE> pack_size = 8 <NEW_LINE> self.assertEqual(field_width.calculate_field_widths(csv_file_as_str, pack_size), [0, 6, 0, 6, 0, 6]) | Test with multi-pack aligned on pack boundaries. | 625941c750485f2cf553cddf |
def backupHotpatch(): <NEW_LINE> <INDENT> if os.path.samefile(g_gausshome, g_opts.newClusterAppPath): <NEW_LINE> <INDENT> g_logger.debug("Has switched to new version, no need to backup again.") <NEW_LINE> return <NEW_LINE> <DEDENT> for dbInstance in g_dbNode.cmservers: <NEW_LINE> <INDENT> backupInstanceHotpatchConfig(d... | function: if the upgrade process failed in check cluster status,
user can reenter upgrade process | 625941c7498bea3a759b9af5 |
def solve_manual(totals, ks_constants, params, log_kt_constants, ptargets=None): <NEW_LINE> <INDENT> if ptargets is None: <NEW_LINE> <INDENT> ptargets = stoichiometric.create_ptargets(totals, ks_constants) <NEW_LINE> <DEDENT> optresult_thermodynamic = thermodynamic.solve( totals, ks_constants, params, log_kt_constants,... | Solve for thermodynamic equilibrium to return solute molalities and stoichiometric
equilibrium constants, having manually evaluated the relevant constants. | 625941c76e29344779a62658 |
@_send <NEW_LINE> def update_farmware(package): <NEW_LINE> <INDENT> kind = 'update_farmware' <NEW_LINE> return _assemble(kind, {'package': package}) | Send command: update_farmware.
Args:
package (str): Name of the Farmware to update. | 625941c76aa9bd52df036de9 |
def __init__(self): <NEW_LINE> <INDENT> self.message = 'Invalid Task Parameters.' <NEW_LINE> self.code = 't-1' <NEW_LINE> self.status_code = 400 | Initial values. | 625941c755399d3f055886f9 |
def train_distributed(self, num_gpus) -> None: <NEW_LINE> <INDENT> logger.warning("train_distributed() not implemented in the base Trainer.") | Executes the training of the model in a distributed fashion.
:param num_gpus: The number of gpus to use for training.
:return: None | 625941c738b623060ff0ae34 |
def _get_mediatypes_from_qsa(self): <NEW_LINE> <INDENT> qsa_mediatypes = self.request.query_params.get('_format', self.request.query_params.get('_mediatype', None)) <NEW_LINE> if qsa_mediatypes is not None: <NEW_LINE> <INDENT> qsa_mediatypes = str(qsa_mediatypes).replace(' ', '+').split(',') <NEW_LINE> if qsa_mediatype... | Returns a list of Media Types from QSA
:return: list | 625941c73346ee7daa2b2db0 |
def default_classification_model(num_classes, num_anchors, pyramid_feature_size=256, prior_probability=0.01, classification_feature_size=256, name='classification_submodel'): <NEW_LINE> <INDENT> options = { 'kernel_size': 3, 'strides': 1, 'padding': 'same', } <NEW_LINE> inputs = keras.layers.Input(shape=(None, None, py... | Creates the default classification submodel.
Args
num_classes: Number of classes to predict a score for at each feature
level.
num_anchors: Number of anchors to predict classification scores for at
each feature level.
pyramid_feature_size: The number of filters to expect from the fe... | 625941c77d43ff24873a2ce6 |
def isPalindrome(self, s): <NEW_LINE> <INDENT> list1 = [] <NEW_LINE> for a in s: <NEW_LINE> <INDENT> if (a.isalnum()) == True: <NEW_LINE> <INDENT> list1.append(a.lower()) <NEW_LINE> <DEDENT> <DEDENT> list2 = list(reversed(list1)) <NEW_LINE> if list1 == list2: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <N... | :type s: str
:rtype: bool | 625941c7fbf16365ca6f6208 |
def saveVariantsLayer(self, origin, fileName=None): <NEW_LINE> <INDENT> fileName = self.getFileDialog( fileName, options=False, fileType="USD (*.usd *.usda)") <NEW_LINE> if not fileName: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> return pm.walterStandin(saveVariantsLayer=(origin, fileName)) | Save the shader assignment to external file. | 625941c78a349b6b435e81b9 |
def from_object(self, obj): <NEW_LINE> <INDENT> for key in dir(obj): <NEW_LINE> <INDENT> if key.isupper(): <NEW_LINE> <INDENT> val = getattr(obj, key) <NEW_LINE> setattr(self, key, val) <NEW_LINE> <DEDENT> <DEDENT> return self | Copy uppercase attributes from another object to this one | 625941c732920d7e50b28215 |
def Run(self, args): <NEW_LINE> <INDENT> holder = base_classes.ComputeApiHolder(self.ReleaseTrack()) <NEW_LINE> client = holder.client <NEW_LINE> peer_network_ref = resources.REGISTRY.Parse( args.peer_network, params={ 'project': args.peer_project or properties.VALUES.core.project.GetOrFail }, collection='compute.netwo... | Issues the request necessary for adding the peering. | 625941c75fcc89381b1e1704 |
def Clean_0_Jet(Train, Val, Test): <NEW_LINE> <INDENT> sets = [Train, Val, Test] <NEW_LINE> for df in sets: <NEW_LINE> <INDENT> df.drop('PRI_jet_leading_pt', axis=1, inplace=True) <NEW_LINE> df.drop('PRI_jet_leading_eta', axis=1, inplace=True) <NEW_LINE> df.drop('PRI_jet_leading_phi', axis=1, inplace=True) <NEW_LINE> d... | Removes variable columns that are meaningless for events with 0 jets.
Parameters
----------
Train : pandas.dataframe
dataset with also meaningless variables.
Val : pandas.dataframe
dataset with also meaningless variables.
Test : pandas.dataframe
dataset with also meaningless variables.
Returns
-------
Tra... | 625941c78e7ae83300e4b012 |
def test_past_questions(self): <NEW_LINE> <INDENT> past_question = create_question(question_text='Past Question.', days=-5) <NEW_LINE> url = reverse('polls:detail', args=(past_question.id,)) <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertContains(response, past_question.question_text) | The detail view of a question with a pub_date in the past displays the question's text. | 625941c78da39b475bd64fb8 |
def get_cltk_text_dir(lang, corpus='perseus'): <NEW_LINE> <INDENT> cltk_home = os.path.expanduser('~/cltk_data') <NEW_LINE> text_dir = os.path.join(cltk_home, lang.casefold(), 'text', lang.casefold() + '_text_' + corpus, 'json') <NEW_LINE> return text_dir | Take relative filepath, return absolute | 625941c791f36d47f21ac537 |
def _generate_outside_terrain(self, empty_outside_terrain_grid, number_of_generations): <NEW_LINE> <INDENT> grid = empty_outside_terrain_grid <NEW_LINE> number_of_generations = number_of_generations <NEW_LINE> for x in range(number_of_generations): <NEW_LINE> <INDENT> next_grid = [] <NEW_LINE> for column_index, column ... | creates a bubble effect with cellular automaton | 625941c78e71fb1e9831d7f0 |
def make_encoder(activation, latent_size, base_depth): <NEW_LINE> <INDENT> conv = functools.partial( tf.keras.layers.Conv2D, padding="SAME", activation=activation) <NEW_LINE> encoder_net = tf.keras.Sequential([ conv(base_depth, 5, 1), conv(base_depth, 5, 2), conv(2 * base_depth, 5, 1), conv(2 * base_depth, 5, 2), conv(... | Creates the encoder function.
Args:
activation: Activation function in hidden layers.
latent_size: The dimensionality of the encoding.
base_depth: The lowest depth for a layer.
Returns:
encoder: A `callable` mapping a `Tensor` of images to a
`tf.distributions.Distribution` instance over encodings. | 625941c75e10d32532c5ef6d |
def getyieldy(self, key): <NEW_LINE> <INDENT> if key in self.propmap: <NEW_LINE> <INDENT> funcval = self.propmap[key] <NEW_LINE> if isinstance(funcval, ScriptCallable): <NEW_LINE> <INDENT> if not funcval.yieldy: <NEW_LINE> <INDENT> return (funcval.func(), False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (fun... | Get an entry which may be an asychronous operation.
(This is terrible, but better than handling every single
nmsp.attr as a coroutine call? I think?)
Anyhow, you call this with the idiom:
(res, yieldy) = nmsp.getyieldy(key)
if yieldy:
res = yield res() | 625941c74c3428357757c36e |
def write(self, data): <NEW_LINE> <INDENT> self._processor.process(data) | Write directly to the C{MessageProcessor}. | 625941c792d797404e3041d0 |
def create_alien(ai_settings,screen,aliens,alien_number,row_number): <NEW_LINE> <INDENT> alien = Alien(ai_settings, screen) <NEW_LINE> alien_width=alien.rect.width <NEW_LINE> alien.x=alien_width+2*alien_width*alien_number <NEW_LINE> alien.rect.x=alien.x <NEW_LINE> alien.rect.y=alien.rect.height+2*alien.rect.height*row_... | 创建一个外星人并将其放入当前行 | 625941c75fc7496912cc39c4 |
def getLastUV( self ): <NEW_LINE> <INDENT> result = self.sendMessage( 'D3' ) <NEW_LINE> return result.split(',') | Fetches (from the device) the last CIE 1976 u,v coords
:returns:
list: status, units, Photometric brightness, u, v
:see also:
:func:`~PR655.measure` automatically populates pr655.lastUV with [u,v] | 625941c7460517430c3941ce |
def test_bytes(self): <NEW_LINE> <INDENT> self.check_hosts((['host'], [], [], [], [], [], []), ([0], [], [], [], [], [], []), from_bytes=True) | Test match against byte string | 625941c750812a4eaa59c369 |
def get_seed(self, rating, me=None): <NEW_LINE> <INDENT> seed = self.seed[rating] <NEW_LINE> if me: <NEW_LINE> <INDENT> seed -= self.elo_win_prob[rating - me.rating] <NEW_LINE> <DEDENT> return seed | Get seed given a rating and user. | 625941c73617ad0b5ed67f3e |
def __add__(self, other): <NEW_LINE> <INDENT> v = self.data + other.data <NEW_LINE> return MyNumber(v) | 此方法来用制定self + other的规则 | 625941c7a17c0f6771cbe098 |
def set_weights(self, new_weights): <NEW_LINE> <INDENT> self._check_sess() <NEW_LINE> self.sess.run(self.assignment_nodes, feed_dict={self.placeholders[name]: value for (name, value) in new_weights.items() if name in self.placeholders}) | Sets the weights to new_weights. | 625941c794891a1f4081baef |
def phi(dvw, width): <NEW_LINE> <INDENT> z = dvw/width <NEW_LINE> val = np.exp(-1.0*(z*z)/2.0) <NEW_LINE> return val | Given the sigma in velocity units, this routine computes
the relative Gaussian value of the instrumental profile
Called by routine instrument iteratively | 625941c7cc40096d61595997 |
def install(cwd=None): <NEW_LINE> <INDENT> directory = cwd <NEW_LINE> chromedriver_filepath = download_chromedriver(directory) <NEW_LINE> if not chromedriver_filepath: <NEW_LINE> <INDENT> logging.debug('Can not download chromedriver.') <NEW_LINE> return <NEW_LINE> <DEDENT> chromedriver_dir = os.path.dirname(chromedrive... | Appends the directory of the chromedriver binary file to PATH.
:param cwd: Flag indicating whether to download to current working directory
:return: The file path of chromedriver | 625941c7be383301e01b54ce |
@logic.validate(logic.schema.default_activity_list_schema) <NEW_LINE> def organization_activity_list(context, data_dict): <NEW_LINE> <INDENT> data_dict['include_data'] = False <NEW_LINE> include_hidden_activity = data_dict.get('include_hidden_activity', False) <NEW_LINE> _check_access('organization_activity_list', cont... | Return a organization's activity stream.
:param id: the id or name of the organization
:type id: string
:param offset: where to start getting activity items from
(optional, default: ``0``)
:type offset: int
:param limit: the maximum number of activities to return
(optional, default: ``31`` unless set in site's... | 625941c75166f23b2e1a519f |
def get(self, a, b, limit): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._get((a, b, limit)) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return self._get((b, a, limit)) | Return cost or raise KeyError | 625941c74f6381625f114a82 |
def print_server_info(ip, user, password): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> r = requests.get(f'https://{ip}:8443/api/v2/server', auth=(user, password), verify=False) <NEW_LINE> if r.status_code != 200: <NEW_LINE> <INDENT> raise Exception(f"Invalid response from plesk api. Response code: {r.status_code}") <N... | Fetch and print servers info
@params:
ip - Required : the ip of the server (Str)
user - Required : the administrator username (Str)
password - Required : The administrator password (Str) | 625941c7d18da76e2353251b |
def create_column(conn, schema, table, column_name, data_type): <NEW_LINE> <INDENT> full_table_name = create_full_table_name(schema, table) <NEW_LINE> query = "ALTER TABLE {0} ADD COLUMN \"{1}\" {2};".format( full_table_name, column_name, data_type) <NEW_LINE> with closing(conn.cursor()) as cursor: <NEW_LINE> <INDENT> ... | Create a new column with matching datatype for the specified trend. | 625941c7c4546d3d9de72a79 |
def test_xor(self): <NEW_LINE> <INDENT> def ggen(n): <NEW_LINE> <INDENT> i=0 <NEW_LINE> while i<n: <NEW_LINE> <INDENT> r1=random.normalvariate(0,0.01) <NEW_LINE> r2=random.normalvariate(0,0.01) <NEW_LINE> if i%4==0: <NEW_LINE> <INDENT> yield np.array([0,1]),[r1,r2] <NEW_LINE> <DEDENT> elif i%4==1: <NEW_LINE> <INDENT> y... | A test to verify training for XOR | 625941c7009cb60464c633f9 |
def counter_subtract_demo(self, now_iterable='abcdab', other_iterable='chci'): <NEW_LINE> <INDENT> now_counter_result = collections.Counter(now_iterable) <NEW_LINE> print(now_counter_result) <NEW_LINE> other_counter_result = collections.Counter(other_iterable) <NEW_LINE> print(other_counter_result) <NEW_LINE> now_count... | 求 now_iterable 与 other_iterable的差 | 625941c74e4d5625662d4420 |
def get_course_lang(course_url): <NEW_LINE> <INDENT> return constant.CRSLANG_EN if "cycle" in course_url else constant.CRSLANG_IT | Getter function to get a course's language without directly analyzing the URL | 625941c7bf627c535bc13215 |
def _ChangedIndexRows(composite_indexes, old_entity, new_entity): <NEW_LINE> <INDENT> unique_old_properties = collections.defaultdict(set) <NEW_LINE> unique_new_properties = collections.defaultdict(set) <NEW_LINE> if old_entity is not None: <NEW_LINE> <INDENT> for old_prop in old_entity.property_list(): <NEW_LINE> <IND... | Determine the number of index rows that need to change.
We assume that old_entity represents the current state of the Datastore.
Args:
composite_indexes: The composite_indexes for the kind of the entities.
old_entity: Entity representing the current state in the Datastore.
new_entity: Entity representing the de... | 625941c771ff763f4b5496d0 |
def _sim_one_sig(self, sig_param): <NEW_LINE> <INDENT> f0 = self._system_parameters['f0'] <NEW_LINE> incF = self._system_parameters['delta_f'] <NEW_LINE> Tm = self._system_parameters['Tm'] <NEW_LINE> fs = self._system_parameters['fs'] <NEW_LINE> N = self._system_parameters['length'] <NEW_LINE> delay = si... | Simulate one harmonic beat signal.
Parameters
-------------
* sig_param: dict
dictionary of signal parameters, whcih include
(a,delay,delta_delat,phi0,callback).
Returns
------------
* sig: 1d ndarray (complex),
simulated signal.
Notes
---------
* Parameters f0, Delta_f, fs and N are system paramet... | 625941c7f7d966606f6aa04a |
def testGetWithInvalidOperation(self): <NEW_LINE> <INDENT> user = createUser(u'name', u'password', u'Name', u'name@example.com') <NEW_LINE> namespace = createNamespace(user, u'name') <NEW_LINE> permission = createNamespacePermission(namespace) <NEW_LINE> self.assertRaises(RuntimeError, permission.get, Operation.WRITE_T... | L{NamespacePermission.get} raises a C{RuntimeError} if an invalid
L{Operation} is provided. | 625941c7adb09d7d5db6c7d7 |
def __init__(self, first_name, last_name, username, email, location): <NEW_LINE> <INDENT> super().__init__(first_name, last_name, username, email, location) <NEW_LINE> self.privileges = [] | Initializes Admin | 625941c75fdd1c0f98dc0279 |
def get_auxSignal(self): <NEW_LINE> <INDENT> if self._cacheExpiration <= YAPI.GetTickCount(): <NEW_LINE> <INDENT> if self.load(YAPI._yapiContext.GetCacheValidity()) != YAPI.SUCCESS: <NEW_LINE> <INDENT> return YStepperMotor.AUXSIGNAL_INVALID <NEW_LINE> <DEDENT> <DEDENT> res = self._auxSignal <NEW_LINE> return res | Returns the current value of the signal generated on the auxiliary output.
@return an integer corresponding to the current value of the signal generated on the auxiliary output
On failure, throws an exception or returns YStepperMotor.AUXSIGNAL_INVALID. | 625941c77b25080760e394a0 |
def test_small_pos(self): <NEW_LINE> <INDENT> d = 1 <NEW_LINE> arr = [1,3,5,7] <NEW_LINE> result = hackerrank_DS_4.rotateLeft(d, arr) <NEW_LINE> self.assertEqual(result, [3, 5, 7, 1]) | test to rotate a small array by only 1 position
:return: 3,5,7,1 | 625941c7ab23a570cc2501c8 |
def _uninstall(self): <NEW_LINE> <INDENT> return None | This method is called by *uninstall()* and should remove all
data or configuration generated by the plugin.
**Subclass:**
* You may completly override this method. | 625941c730bbd722463cbe0c |
def create_child_with_parents(node, address, privkeys, parents_tx, values, locking_scripts, fee=DEFAULT_FEE): <NEW_LINE> <INDENT> num_parents = len(parents_tx) <NEW_LINE> total_value = sum(values) <NEW_LINE> inputs = [{"txid": tx.rehash(), "vout": 0} for tx in parents_tx] <NEW_LINE> outputs = {address : total_value - f... | Creates a transaction that spends the first output of each parent in parents_tx. | 625941c730bbd722463cbe0b |
def query_from_elem(elem): <NEW_LINE> <INDENT> if elem is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> output = [] <NEW_LINE> for subelem in elem: <NEW_LINE> <INDENT> if subelem.tag == "constant": <NEW_LINE> <INDENT> name = subelem.attrib['name'] <NEW_LINE> value = subelem.text.strip() <NEW_LINE> try: <NEW... | Creates a Query object from the specified xml element | 625941c7507cdc57c6306d1f |
def draw_emoji(self, frame, emoji_bbs): <NEW_LINE> <INDENT> if emoji_bbs is None or len(emoji_bbs) == 0: <NEW_LINE> <INDENT> return frame <NEW_LINE> <DEDENT> frameDC = copy.deepcopy(frame) <NEW_LINE> frame_h, frame_w = frameDC.shape[:2] <NEW_LINE> for emoji_name, bb in emoji_bbs: <NEW_LINE> <INDENT> l,t,r,b = bb <NEW_L... | Draw emoji is non-trivial omg.
Params
-------
emoji_bbs : list of tuples
Each tuple consist of (emoji_name, bb) pairs
Returns
-------
Drawn frame ndarray | 625941c7046cf37aa974cd8f |
def get_url(endpoint): <NEW_LINE> <INDENT> if not isinstance(endpoint, str): <NEW_LINE> <INDENT> raise Exception('endpoint has to be a string') <NEW_LINE> <DEDENT> return base_url + endpoint | This utility function will return a url to be used in a request
:param endpoint:
:return: | 625941c79f2886367277a8d5 |
def cast(*args): <NEW_LINE> <INDENT> return _itkFlipImageFilterPython.itkFlipImageFilterIUL2_cast(*args) | cast(itkLightObject obj) -> itkFlipImageFilterIUL2 | 625941c750485f2cf553cde0 |
def retry_erroneous(self, name, properties_update=None): <NEW_LINE> <INDENT> with self.__instances_lock: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> stored_instance = self.__instances[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise ValueError( "Unknown component instance '{0}'".format(name)) <NEW_... | Removes the ERRONEOUS state of the given component, and retries a
validation
:param name: Name of the component to retry
:param properties_update: A dictionary to update component properties
:return: The new state of the component
:raise ValueError: Invalid component name | 625941c7a79ad161976cc18c |
def check_pages(language): <NEW_LINE> <INDENT> yaml_pat = re.compile(r'\A---\n.+\n---\n.+', flags=re.DOTALL + re.MULTILINE) <NEW_LINE> links_pat = re.compile(r'{%\s+include\s+links.md\s+%}\s*\Z', flags=re.DOTALL + re.MULTILINE) <NEW_LINE> content = get_all_docs(language) <NEW_LINE> result = set() <NEW_LINE> for (slug, ... | Check that Markdown pages are properly structured. | 625941c7462c4b4f79d1d717 |
def __init__(self, _conf_): <NEW_LINE> <INDENT> self.conf_ = _conf_ <NEW_LINE> self.PATH_LOG = set_.APPS[self.conf_]['PATH_LOG'] <NEW_LINE> self.log = set_.log_init('covid-l_pro.log', self.conf_) <NEW_LINE> self.PATH_DATA = set_.DATA[self.conf_]['PATH'] <NEW_LINE> self.DB_ = set_.MYSQL[self.conf_]['DB'] <NEW_LINE> pass | Is base of the root. | 625941c75fdd1c0f98dc027a |
def getData(self, label): <NEW_LINE> <INDENT> data = self._ensemble.getData(label) <NEW_LINE> if data is not None: <NEW_LINE> <INDENT> data = data[self._index] <NEW_LINE> <DEDENT> return data | Returns a copy of the data array associated with *label*, or **None**
if such data is not present. | 625941c7b7558d58953c4f5d |
def depthFirstSearch(problem): <NEW_LINE> <INDENT> currState = problem.getStartState() <NEW_LINE> visited = set() <NEW_LINE> visited.add(currState) <NEW_LINE> currPath = [] <NEW_LINE> result = dfsHelper(problem, visited, currPath, currState) <NEW_LINE> return result | Search the deepest nodes in the search tree first.
Your search algorithm needs to return a list of actions that reaches the
goal. Make sure to implement a graph search algorithm.
To get started, you might want to try some of these simple commands to
understand the search problem that is being passed in:
print "Start... | 625941c7d486a94d0b98e18c |
def check(self, request, mtype=None): <NEW_LINE> <INDENT> if not request: <NEW_LINE> <INDENT> raise LogDBError("Request name is empty") <NEW_LINE> <DEDENT> if mtype and mtype not in LOGDB_MSG_TYPES: <NEW_LINE> <INDENT> raise LogDBError("Unsupported message type: '%s', supported types %s" % (mtype, ... | Check that given request name is valid | 625941c707f4c71912b114c8 |
def build_sampling_funcs(self): <NEW_LINE> <INDENT> x_sym = tensor.matrix('x_sym') <NEW_LINE> y_sym = tensor.matrix('y_sym') <NEW_LINE> cs, nll, kl_q2ps, kl_p2qs = self.run_model_simul(x_sym, y_sym) <NEW_LINE> cs_as_ys = tensor.nnet.sigmoid(tanh_clip(cs, clip_val=15.0)) <NEW_LINE> nll_term = nll.mean() <NEW_LINE> kl_te... | Build functions for visualizing the behavior of this model. | 625941c7c4546d3d9de72a7a |
def TrainDNN(self,train_DF,test_DF,multi=False,nclass = 4,epochs=200,batch_size=1024,useDropOut = False,class_weights=None,loss=None): <NEW_LINE> <INDENT> NDIM = len(self.var_list) <NEW_LINE> DNN = Sequential() <NEW_LINE> DNN.add(Dense(64, input_dim=NDIM, kernel_initializer='uniform', activation='relu')) <NEW_LINE> if ... | With training and testing DataFrame, and a list of variables with which to train and evaluate, produce the
score series for both the training and testing sets | 625941c799cbb53fe6792c2d |
def get_user(self, request): <NEW_LINE> <INDENT> if hasattr(request, settings.MARKETPLACE_DOMAIN_NAME_KEY): <NEW_LINE> <INDENT> domain = getattr(request, settings.MARKETPLACE_DOMAIN_NAME_KEY) <NEW_LINE> user = get_gaema_user(domain) <NEW_LINE> if user: <NEW_LINE> <INDENT> user['_service'] = domain <NEW_LINE> key_name =... | check for gaema authenticated user and return the user
| 625941c776e4537e8c3516b8 |
def layer(self, layer_id): <NEW_LINE> <INDENT> buf = cStringIO.StringIO() <NEW_LINE> f = gzip.GzipFile(mode='wb', compresslevel=self._compresslevel, fileobj=buf) <NEW_LINE> try: <NEW_LINE> <INDENT> f.write(self._content(layer_id + '/layer.tar', memoize=False)) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> f.close() ... | Override. | 625941c723e79379d52ee5ac |
def calc_template_ranges(network): <NEW_LINE> <INDENT> network.update_network() <NEW_LINE> nbase = network.network.network <NEW_LINE> name_fragment = calc_name_fragment(network) <NEW_LINE> if network.ip_type == '4': <NEW_LINE> <INDENT> if network.prefixlen <= 24 and network.prefixlen >= 20: <NEW_LINE> <INDENT> template... | Given a network, return the range information for that network. These
ranges will be used by the user to decide where to request an IP address.
This function will not actually find that ip address, it will mearly
suggest which ranges a user might want to check in.
This function should contain allocation policy that ne... | 625941c75166f23b2e1a51a0 |
def d_input(self): <NEW_LINE> <INDENT> input_ = self.get_cache('input') <NEW_LINE> output = self.get_cache('output') <NEW_LINE> error = self.error() <NEW_LINE> result = np.zeros((error.shape[:1] + self.input_shape)) <NEW_LINE> stride_x, stride_y = self.stride <NEW_LINE> for i in range(self.input_shape[0]): <NEW_LINE> <... | Compute the gradient with respect to the inputs (which are also the activations of the
preceding layer). | 625941c7e8904600ed9f1f73 |
def apply( self, func: Callable[..., Styler], axis: Axis | None = 0, subset: Subset | None = None, **kwargs, ) -> Styler: <NEW_LINE> <INDENT> self._todo.append( (lambda instance: getattr(instance, "_apply"), (func, axis, subset), kwargs) ) <NEW_LINE> return self | Apply a CSS-styling function column-wise, row-wise, or table-wise.
Updates the HTML representation with the result.
Parameters
----------
func : function
``func`` should take a Series if ``axis`` in [0,1] and return an object
of same length, also with identical index if the object is a Series.
``func`` sh... | 625941c7e8904600ed9f1f72 |
def test_create(self): <NEW_LINE> <INDENT> pass | Test case for create
Create a new Participant for the given Study. | 625941c785dfad0860c3aea1 |
def __init__(self, FLAGS, split): <NEW_LINE> <INDENT> self.n_points = FLAGS.n_points <NEW_LINE> self.len = FLAGS.epoch_length <NEW_LINE> self.split = split <NEW_LINE> assert self.split in ["log", "train"] | Create a dataset of graphs. Each graph represents a set of points in 3D space, where each pair of points
interacts according to a randomly parameterised potential. The parameter(s) of this potential are stored in the
graph as edge information.
Node data has shape (num_points, num_channels, data_dimensionality)
Edge da... | 625941c7851cf427c661a557 |
def __get_product_seller(self, doc): <NEW_LINE> <INDENT> product_seller = doc.xpath(self.xpath.item_seller) <NEW_LINE> if product_seller: <NEW_LINE> <INDENT> product_seller = product_seller[0] <NEW_LINE> <DEDENT> return product_seller | Uses the lxml doc to fetch product seller | 625941c7377c676e912721f0 |
def test_mkdir_url_with_revprops(self): <NEW_LINE> <INDENT> directory = urljoin(self.repos_uri+b"/", b"some/deep/subdir") <NEW_LINE> commit_info = client.mkdir3((directory,), 1, {b'customprop':b'value'}, self.client_ctx) <NEW_LINE> self.assertEqual(commit_info.revision, 13) <NEW_LINE> self.assertEqual(self.log_message_... | Test svn_client_mkdir3 on a file:// URL, with added revprops | 625941c776e4537e8c3516b9 |
def test_check_inputs_1(): <NEW_LINE> <INDENT> Z = X.astype('float') <NEW_LINE> Z[0, 0] = np.inf <NEW_LINE> H, _ = np.testing.assert_warns(InputDataWarning, check_inputs, Z, y, 1) <NEW_LINE> assert id(H) == id(Z) <NEW_LINE> np.testing.assert_array_equal(Z, H) | [Utils] check_inputs: warnings level = 1. | 625941c750812a4eaa59c36a |
def is_remote(path): <NEW_LINE> <INDENT> return issubclass(path.__class__, RemotePath) | Return whether the given protocol path belongs to a remote protocol or not.
:param path: protocol path to process.
:type path: ProtocolPath
:returns: whether the protocol is local (True in this case).
:rtype: bool | 625941c71d351010ab855b63 |
def _valid_epoch(self): <NEW_LINE> <INDENT> self.model.eval() <NEW_LINE> total_val_loss = 0 <NEW_LINE> total_val_metrics = np.zeros(len(self.metrics)) <NEW_LINE> with torch.no_grad(): <NEW_LINE> <INDENT> for batch_idx, gt in enumerate(self.data_loader): <NEW_LINE> <INDENT> img, score_map, geo_map, training_mask, transc... | Validate after training an epoch
:return: A log that contains information about validation
Note:
The validation metrics in log must have the key 'val_metrics'. | 625941c7d4950a0f3b08c397 |
def test_user_can_only_list_where_he_has_journal_membership(self): <NEW_LINE> <INDENT> self.client.login(username=self.user.username, password='top_secret') <NEW_LINE> response = self.client.get( reverse('userspace:journal:editor:issues', args=(self.journal.pk, )), user=self.user) <NEW_LINE> journal_ids = [j.id for j i... | Test list of issue submissions
Make sure the list contains only issue submission link to a journal
with his membership | 625941c7e76e3b2f99f3a854 |
def test_hostgroups_patch_description_204_ok(self): <NEW_LINE> <INDENT> self.assert_patch(f'/hostgroups/{self.hostgroup_one.name}', {'description': 'new d€scription'}) <NEW_LINE> data = self.assert_get('/hostgroups/%s' % self.hostgroup_one.name).json() <NEW_LINE> self.assertEqual(data['description'], 'new d€scription') | Rename a group should return 204 ok | 625941c701c39578d7e74e82 |
def bin_data_log10(datax,datay,numbins,botedge=-99,topedge=-99): <NEW_LINE> <INDENT> tempx = np.log10(datax) <NEW_LINE> if botedge == -99: <NEW_LINE> <INDENT> botedge = np.min(tempx) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> botedge = np.log10(botedge) <NEW_LINE> <DEDENT> if topedge == -99: <NEW_LINE> <INDENT> tope... | Place data in bins spaced regularly in log10 space.
Calculates binned averages and standard deviations for
both the abscissa and ordinate data.
Returns arrays containing binned averages and standard
deviations of both x and y data as well as the number
of samples in each bin:
binmeanx, binstdx, binmeany, binstdy, ... | 625941c707d97122c41788d0 |
def rebuild(self, id, image, wait=False, poll=5, timeout=300): <NEW_LINE> <INDENT> uri = "%s/%s/actions" % (self.uri, id) <NEW_LINE> try: <NEW_LINE> <INDENT> image = int(image) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> attribs = {"type": "rebuild", "image": image} <NEW_LINE> re... | description: Rebuild a Droplet
A rebuild action functions just like a new create.
in:
- id - number - The id of the Droplet
- image - string if an image slug. number if an image ID. - An image slug or ID. This represents the image that the Droplet will use as a base.
- wait - boolean - Whether to wait... | 625941c767a9b606de4a7f02 |
def _updater_wrapper(updater): <NEW_LINE> <INDENT> def updater_handle(key, lhs_handle, rhs_handle): <NEW_LINE> <INDENT> lhs = NDArray(NDArrayHandle(lhs_handle)) <NEW_LINE> rhs = NDArray(NDArrayHandle(rhs_handle)) <NEW_LINE> updater(key, lhs, rhs) <NEW_LINE> <DEDENT> return updater_handle | a wrapper for the user-defined handle | 625941c71f037a2d8b946245 |
def getDataAge(self, filesByLumi): <NEW_LINE> <INDENT> maxInsertTime = 0 <NEW_LINE> for filesInfos in list(filesByLumi.values()): <NEW_LINE> <INDENT> for fileInfo in filesInfos: <NEW_LINE> <INDENT> if fileInfo['insert_time'] > maxInsertTime: <NEW_LINE> <INDENT> maxInsertTime = fileInfo['insert_time'] <NEW_LINE> <DEDENT... | _getDataAge_
Return age of youngest streamer in filesByLumi | 625941c79c8ee82313fbb7bc |
def calc_n_coarse_chan(self): <NEW_LINE> <INDENT> coarse_chan_bw = 2.9296875 <NEW_LINE> bandwidth = abs(self.header[b'nchans']*self.header[b'foff']) <NEW_LINE> n_coarse_chan = bandwidth / coarse_chan_bw <NEW_LINE> return n_coarse_chan | This makes an attempt to calculate the number of coarse channels in a given file.
It assumes for now that a single coarse channel is 2.9296875 MHz | 625941c7be7bc26dc91cd649 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.