code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def findActorByName(self, name): <NEW_LINE> <INDENT> for a in self.getAll(): <NEW_LINE> <INDENT> if a.getName() == name: <NEW_LINE> <INDENT> return a <NEW_LINE> <DEDENT> <DEDENT> raise ValueError("Actor does not exist!") | returns the actor with the given name
raises error if it doesn't exist | 625941f3b57a9660fec33e7a |
def get_cached_input_variables_and_parameters(column): <NEW_LINE> <INDENT> assert input_variables_extractor is not None <NEW_LINE> global input_variables_and_parameters_by_column_name_cache <NEW_LINE> input_variables_and_parameters = input_variables_and_parameters_by_column_name_cache.get(column.name) <NEW_LINE> if inp... | This function uses input_variables_extractor and expects the caller to check it is not None. | 625941f315fb5d323cde1106 |
def rmr(hdfs_path, project=None): <NEW_LINE> <INDENT> if project == None: <NEW_LINE> <INDENT> project = project_name() <NEW_LINE> <DEDENT> hdfs_path = _expand_path(hdfs_path, project) <NEW_LINE> return hdfs.rmr(hdfs_path) | Recursively remove files and directories.
Args:
:hdfs_path: You can specify either a full hdfs pathname or a relative one (relative to project_name in HDFS).
:project: If the supplied hdfs_path is a relative path, it will look for that file in this project's subdir in HDFS. | 625941f3d164cc617578333c |
def calc_message_mean_and_std(m_store): <NEW_LINE> <INDENT> for k in m_store: <NEW_LINE> <INDENT> msgs = m_store[k]["message"] <NEW_LINE> msgs = torch.stack(msgs, dim=0) <NEW_LINE> debuglogger.debug(f'Key: {k}, Count: {m_store[k]["count"]}, Messages: {msgs.size()}') <NEW_LINE> mean = torch.mean(msgs, dim=0).cpu() <NEW_... | Calculate the mean and std deviation of messages per agent per shape, color and shape-color combination | 625941f3fb3f5b602dac3c87 |
def synced_listboxes(self): <NEW_LINE> <INDENT> def synced_select(e): <NEW_LINE> <INDENT> index = e.widget.curselection()[0] <NEW_LINE> for lb in lbs: <NEW_LINE> <INDENT> lb.select_clear(0, END) <NEW_LINE> lb.select_set(index) <NEW_LINE> <DEDENT> <DEDENT> wrapper = Frame(self) <NEW_LINE> wrapper.pack(fill=BOTH, expand=... | Create two Listboxes whose selected items are synced. | 625941f315baa723493c4567 |
def end_event(self): <NEW_LINE> <INDENT> self.running = False <NEW_LINE> messagebox.showinfo('ゲーム終了', 'GAME OVER') <NEW_LINE> self.master.bind("<Left>", self.left_key_event) <NEW_LINE> self.master.bind("<Right>", self.right_key_event) <NEW_LINE> self.master.bind("<Down>", self.down_key_event) <NEW_LINE> self.master.bin... | ゲーム終了時の処理 | 625941f34e4d5625662d49bc |
def fit_posteirors(self): <NEW_LINE> <INDENT> z = [] <NEW_LINE> for t in self.points[:,0]: <NEW_LINE> <INDENT> if len(z) == 0: <NEW_LINE> <INDENT> temp_z = 5. <NEW_LINE> <DEDENT> z.append(optimize.fmin(self.redshift_finder, temp_z, args=(t,))) <NEW_LINE> temp_z = z[-1] <NEW_LINE> <DEDENT> z = np.concatenate(z) <NEW_LIN... | fits with full posteriors | 625941f3c4546d3d9de73027 |
def __init__(self, **features): <NEW_LINE> <INDENT> self._features = {} <NEW_LINE> for name in features: <NEW_LINE> <INDENT> self.addFeatureSpec(name, features[name]) | Initialize a FeatureCollection object.
:param features: A dictionary of specifications for feature
conversions. Each key represents a named
specification that maps to a dictionary of
the form {'type': featureType, ...}.
Additional values in this dicti... | 625941f3c432627299f05237 |
@decorator.decorator <NEW_LINE> def correction(func, *args, **kwargs): <NEW_LINE> <INDENT> self = args[0] <NEW_LINE> if func.__name__ in self.correction: <NEW_LINE> <INDENT> self.log.warning('CORRECTION {} has already been applied'.format(func.__name__)) <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s... | automatically adds the called correction_function to self._correct | 625941f3377c676e91272793 |
def auto( cls: Optional[T] = None, *, angular: Optional[bool] = None ) -> Union[T, Callable[[T], T]]: <NEW_LINE> <INDENT> def do_replace(cls: Type[T], angular: Optional[bool] = None) -> Type[T]: <NEW_LINE> <INDENT> def auto_repr(self: Type[T]) -> str: <NEW_LINE> <INDENT> repr_str: List[str] = [] <NEW_LINE> append = rep... | Class decorator to create __repr__ from __rich_repr__ | 625941f3cb5e8a47e48b808c |
def in_hold_range(self, position: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]]) -> bool: <NEW_LINE> <INDENT> if self.drawable_shape.collide_point(position): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.hold_range[0] > 0 or self.hold_range[1] > 0: <NEW_LINE> <INDENT> hold_rect = pyga... | Imagines a potentially larger rectangle around our button in which range we still grip
hold of our button when moving the mouse. Makes it easier to use scrollbars.
:param position: The position we are testing.
:return bool: Returns True if our position is inside the hold range. | 625941f323849d37ff7b3677 |
def create_rows_admission(cause, reason): <NEW_LINE> <INDENT> concept_cause = ':'.join(['P21:ADMC', str.upper(cause)]) <NEW_LINE> concept_reason = ':'.join(['P21:ADMR', str.upper(reason)]) <NEW_LINE> return [{'concept_cd': concept_cause, 'modifier_cd': '@', 'valtype_cd': '@', 'valueflag_cd': '@'}, {'concept_cd': concep... | Creates observation_fact rows for encounter admission. Cause and reason
are both added as seperate rows with seperate concept_cd.
Parameters
----------
cause : str
Value of 'Aufnahmeanlass' in FALL.csv
reason : str
Value of 'Aufnahmegrund' in FALL.csv
Returns
-------
list
List with dicts (observation_fact... | 625941f33d592f4c4ed1d64a |
@typ.typ(items=[int]) <NEW_LINE> def teleportinggnome_sort(items): <NEW_LINE> <INDENT> i = j = 0 <NEW_LINE> n = len(items) <NEW_LINE> while i < n: <NEW_LINE> <INDENT> if i and items[i] < items[i-1]: <NEW_LINE> <INDENT> items[i], items[i-1] = items[i-1], items[i] <NEW_LINE> i -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <I... | >>> teleportinggnome_sort([])
[]
>>> teleportinggnome_sort([1])
[1]
>>> teleportinggnome_sort([2,1])
[1, 2]
>>> teleportinggnome_sort([1,2])
[1, 2]
>>> teleportinggnome_sort([1,2,2])
[1, 2, 2] | 625941f32c8b7c6e89b35da8 |
def URL_Isolate(x): <NEW_LINE> <INDENT> l=x.split('"') <NEW_LINE> newX=l[1] <NEW_LINE> return newX | URL_Isolate(string) --> string
returnd a substring of x from the first index in which tha char
'"' appears to the last index in which tha char '"' appears. | 625941f396565a6dacc8fcb6 |
def _get_prefix(self): <NEW_LINE> <INDENT> return self.__prefix | Getter method for prefix, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/global/dynamic_neighbor_prefixes/dynamic_neighbor_prefix/config/prefix (oc-inet:ip-prefix)
YANG Description: The IP prefix within which the source address of the remote
BGP speaker must fall to be con... | 625941f357b8e32f52483a8c |
def check_answer(answer, id, game): <NEW_LINE> <INDENT> if game["answer"] == answer: <NEW_LINE> <INDENT> game["score"] += 1 <NEW_LINE> r.set(id, json.dumps(game)) <NEW_LINE> return True, game["answer"], game['review'] <NEW_LINE> <DEDENT> return False, game["answer"], game['review'] | Check if the user answer is correct and updates the user score in the db
:param answer: the user answer
:param id: this game id
:param game: this game session
:return: True if is correct,false if incorrect and | 625941f30a366e3fb873ee0d |
def eprint(*args, **kwargs) -> None: <NEW_LINE> <INDENT> sys.stdout.flush() <NEW_LINE> print(*args, file=sys.stderr, **kwargs) <NEW_LINE> sys.stderr.flush() | Error printing | 625941f35fc7496912cc3f6a |
def get_matrix_copy(self): <NEW_LINE> <INDENT> return self._matrix.copy() | Returns a copy of the internal matrix. | 625941f3dc8b845886cb5b24 |
def _to_dict(self): <NEW_LINE> <INDENT> _dict = {} <NEW_LINE> if hasattr(self, 'used_bytes') and self.used_bytes is not None: <NEW_LINE> <INDENT> _dict['used_bytes'] = self.used_bytes <NEW_LINE> <DEDENT> if hasattr(self, 'maximum_allowed_bytes' ) and self.maximum_allowed_bytes is not None: <NEW_LINE> <INDENT> _dict['ma... | Return a json dictionary representing this model. | 625941f330bbd722463cc3b7 |
def diff(x, y, z): <NEW_LINE> <INDENT> return any([x - y == z, z - x == y, y - x == z]) | Return whether one argument is the difference between the other two.
x, y, and z are all integers.
>>> diff(5, 3, 2) # 5 - 3 is 2
True
>>> diff(2, 3, 5) # 5 - 3 is 2
True
>>> diff(2, 5, 3) # 5 - 3 is 2
True
>>> diff(-2, 3, 5) # 3 - 5 is -2
True
>>> diff(-5, -3, -2) # -5 - -2 is -3
True
>>> diff(-2, 3, -5) # -2 - 3 is... | 625941f3379a373c97cfb134 |
def handle_response(self, response): <NEW_LINE> <INDENT> view = self.view <NEW_LINE> req, res, err = response <NEW_LINE> if err: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> content, point = get_response_view_content(response) <NEW_LINE> view.run_command('requester_replace_view_text', {'text': content, 'point': point... | Overwrites content in current view.
| 625941f3dd821e528d63b791 |
def gen_numero(): <NEW_LINE> <INDENT> numero = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> numero += 1 <NEW_LINE> yield numero | Esta funcion es un generador de numeros para los eventos.
A cada evento solo se le debe asignar un numero en el momento en el que se realiza dicho evento.
Este numero esta pensado para que las properties puedan verificar si su valor se encuentra actualizado.
También se usa para que cada evaluacion y cada tipo de evento... | 625941f345492302aab5e8b7 |
def test_cleanup_after_install_from_pypi(): <NEW_LINE> <INDENT> env = reset_env() <NEW_LINE> result = run_pip('install', 'INITools==0.2', expect_error=True) <NEW_LINE> build = env.scratch_path/"build" <NEW_LINE> src = env.scratch_path/"src" <NEW_LINE> assert not exists(build), "build/ dir still exists: %s" % build <NEW... | Test clean up after installing a package from PyPI. | 625941f3e1aae11d1e74a2ab |
def get_data_extraction_conf(self, properties): <NEW_LINE> <INDENT> return self.conf.get("data_extraction").get(properties) | 获取data_extraction下的配置
Parameters
----------
properties : str
字段
Returns
-------
dict | 625941f35fc7496912cc3f6b |
def test_add_context_activity_as_user_no_subscription(self): <NEW_LINE> <INDENT> from max.tests.mockers import create_context <NEW_LINE> from max.tests.mockers import user_status_context <NEW_LINE> username = 'sheldon' <NEW_LINE> self.create_user(username) <NEW_LINE> self.create_context(create_context, permissions={'wr... | Given i'm a regular user
When i try to post a activity to a context
And i'm not subscribed to that context
I get a Forbidden Exception | 625941f3956e5f7376d71458 |
def _analyses_data(self, ws): <NEW_LINE> <INDENT> ans = ws.getAnalyses() <NEW_LINE> layout = ws.getLayout() <NEW_LINE> pos_count = 0 <NEW_LINE> prev_pos = 0 <NEW_LINE> ars = {} <NEW_LINE> uid_to_pos_mapping = dict( map(lambda row: (row["analysis_uid"], row["position"]), layout)) <NEW_LINE> for an in ans: <NEW_LINE> <IN... | Returns a list of dicts. Each dict represents an analysis
assigned to the worksheet | 625941f350812a4eaa59c908 |
def interest_over_time(self): <NEW_LINE> <INDENT> over_time_payload = { 'req': json.dumps(self.interest_over_time_widget['request']), 'token': self.interest_over_time_widget['token'], 'tz': self.tz } <NEW_LINE> req_json = self._get_data( url=TrendReq.INTEREST_OVER_TIME_URL, method=TrendReq.GET_METHOD, trim_chars=5, par... | Request data from Google's Interest Over Time section and return a dataframe | 625941f30383005118ecfbcd |
def as_variable_name(x): <NEW_LINE> <INDENT> allowed = string.letters + string.digits + '_' <NEW_LINE> result = [letter if letter in allowed else '_' for letter in x or 'x'] <NEW_LINE> if result[0] in string.digits: <NEW_LINE> <INDENT> result.insert(0, '_') <NEW_LINE> <DEDENT> return ''.join(result) | Convert a string to a legal python variable name
:param x: A string to (possibly) rename
:returns: A legal python variable name | 625941f33346ee7daa2b335f |
def testGETEmailHistoryVOsType(self): <NEW_LINE> <INDENT> pass | Test GETEmailHistoryVOsType | 625941f3796e427e537b0bb8 |
def get_text(filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> f = open(filename, "r") <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> print("Not found file \"{0}\"".format(filename)) <NEW_LINE> return "" <NEW_LINE> <DEDENT> text = f.read() <NEW_LINE> f.close() <NEW_LINE> rx = re.compile(NON_PRI... | Getting a text from a file | 625941f38e71fb1e9831dd94 |
def limit_bandwidth_by_mbps(self, amount): <NEW_LINE> <INDENT> self.bandwidth = "%sM" % (amount,) | Cap the bandwidth used by the Zmap scanner to the specified amount in mbps.
:param amount: The amount in mbps to limit the scanner's bandwidth to.
:return: None | 625941f3be8e80087fb21225 |
def fit(self, X, y, sample_weight=None): <NEW_LINE> <INDENT> random_state = check_random_state(self.random_state) <NEW_LINE> X, = check_arrays(X, dtype=DTYPE, sparse_format="dense", check_ccontiguous=True) <NEW_LINE> n_samples, self.n_features_ = X.shape <NEW_LINE> y = np.atleast_1d(y) <NEW_LINE> if y.ndim == 2 and y.s... | Build a forest of trees from the training set (X, y).
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The training input samples.
y : array-like, shape = [n_samples] or [n_samples, n_outputs]
The target values (integers that correspond to classes in
classification, real numbers in ... | 625941f394891a1f4081c09a |
def test_list_index(): <NEW_LINE> <INDENT> my_list = ['Hello', 'world', '!'] <NEW_LINE> assert my_list[2] == '!' | Можно обращаться к отдельным элементам списка
Отсчет элементов в списке начинается с 0
Например, в списке your_city = ['Moscow', 'Kiev', 'London']
обращаемся к первому элементу your_city[0] = 'Moscow' | 625941f391af0d3eaac9c00b |
def forward(self, x): <NEW_LINE> <INDENT> xl = list(map(len, x)) <NEW_LINE> x = pad_sequence(x, True) <NEW_LINE> xm = key_padding_mask(xl).to(x.device) <NEW_LINE> xm = xm.unsqueeze(dim=1) <NEW_LINE> for layer in self.layers: <NEW_LINE> <INDENT> x = layer(x, xm) <NEW_LINE> <DEDENT> x = self.norm(x) <NEW_LINE> return unp... | Args:
x: [(t d)]
Returns:
x: [(t d)] | 625941f3796e427e537b0bb9 |
def click(self, btn): <NEW_LINE> <INDENT> bi, ci = self.el_btns_lst_index[btn] <NEW_LINE> if self.current_index + bi >= len(self.examples): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> class_id = self.class_ids[ci] <NEW_LINE> self.update_examples([(self.current_index + bi, class_id)], toggle=True) | A button is clicked, we need to figure out the class of that example | 625941f3627d3e7fe0d6943f |
def __init__(self, reparse, access_key, secret_key, profile, iam_role_arn, bucket, only_logs_after, skip_on_error, account_alias, max_queue_buffer, prefix, delete_file): <NEW_LINE> <INDENT> self.wazuh_path = open('/etc/ossec-init.conf').readline().split('"')[1] <NEW_LINE> self.wazuh_queue = '{0}/queue/ossec/queue'.form... | AWS Bucket constructor.
:param reparse: Wether to parse already parsed logs or not
:param access_key: AWS access key id
:param secret_key: AWS secret access key
:param profile: AWS profile
:param iam_role_arn: IAM Role
:param bucket: Bucket name to extract logs from
:param only_logs_after: Date after which obtain logs... | 625941f36aa9bd52df037395 |
def preprocess_descriptors(rule, base_url, descriptors): <NEW_LINE> <INDENT> for descriptor in descriptors: <NEW_LINE> <INDENT> if descriptor.type != 'declaration' or descriptor.important: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> tokens = remove_whitespace(descriptor.value) <NEW_LINE> try: <NEW_LINE> <INDENT> i... | Filter unsupported names and values for descriptors.
Log a warning for every ignored descriptor.
Return a iterable of ``(name, value)`` tuples. | 625941f3187af65679ca570e |
def breadthFirstSearch(problem): <NEW_LINE> <INDENT> explorados = [] <NEW_LINE> expandidos = [] <NEW_LINE> frontera = util.Queue() <NEW_LINE> frontera.push((problem.getStartState(), [])) <NEW_LINE> while not frontera.isEmpty(): <NEW_LINE> <INDENT> nodo = frontera.pop() <NEW_LINE> if problem.isGoalState(nodo[0]): <NEW_L... | Search the shallowest nodes in the search tree first. | 625941f3566aa707497f4b4d |
def get_class_from_string(self, classname, module): <NEW_LINE> <INDENT> myclass = None <NEW_LINE> try: <NEW_LINE> <INDENT> myclass = getattr(module, classname) <NEW_LINE> <DEDENT> except AttributeError as e: <NEW_LINE> <INDENT> logger.warning("Failed to load resource: " + str(e)) <NEW_LINE> <DEDENT> return myclass | Get a specific class from a module using a string variable | 625941f3ab23a570cc250775 |
def __init__(self, name, description=None, related_type=None, related_is_a=None, graph=None, entity_map=None, icon=None, md_icon=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.description = description <NEW_LINE> self.related_type = related_type <NEW_LINE> self.related_is_a = related_is_a <NEW_LINE> self.g... | :type name: str
:type description: str
:type related_type: str
:type related_is_a: str
:type graph: dart.model.graph.Graph
:type entity_map: dict[str, dart.model.base.BaseModel]
:type icon: str
:type md_icon: str | 625941f35f7d997b8717508b |
def integral(self, t_min, t_max): <NEW_LINE> <INDENT> pars = self.parameters <NEW_LINE> decindex = pars["decindex"].quantity <NEW_LINE> t_ref = Time(pars["t_ref"].quantity, format="mjd") <NEW_LINE> dec1 = decindex+1.0 <NEW_LINE> value = self.evaluate(t_max, dec1, t_ref) - self.evaluate(t_min, dec1, t_ref) <NEW_LINE> re... | Evaluate the integrated flux within the given time intervals
Parameters
----------
t_min: `~astropy.time.Time`
Start times of observation
t_max: `~astropy.time.Time`
Stop times of observation
Returns
-------
norm : float
Integrated flux norm on the given time intervals | 625941f3507cdc57c63072d7 |
def get_model(self): <NEW_LINE> <INDENT> return self.model | Retrieves model for the given disk device
Returns:
A string holding disk model as provided by the manufacturer | 625941f3b545ff76a8914403 |
def on_pluginsButton_Configure_clicked(self, button, pluginClass): <NEW_LINE> <INDENT> name,description,status = self.plugins.getPluginInfo(pluginClass) <NEW_LINE> prefs = self.plugins.getPluginConfParams(pluginClass) <NEW_LINE> self.prefwindow = Gtk.Window() <NEW_LINE> self.prefwindow.set_border_width(20) <NEW_LINE> s... | Handler for plugin Buttons | 625941f3956e5f7376d71459 |
def execute_controlfile(self, name): <NEW_LINE> <INDENT> if not name in imports: <NEW_LINE> <INDENT> agenda = Agenda.parse(name) <NEW_LINE> imports[name] = agenda <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> agenda = imports[name] <NEW_LINE> <DEDENT> self.execute_agenda(agenda) <NEW_LINE> return agenda | Execute controlfile or agenda on workspace.
This method looks recursively for a controlfile with the given name in the current
directory and the arts include path. If such a file has been found it will be parsed
and executed on the workspace.
Args:
name(str): Name of the controlfile
Raises:
Exception: If p... | 625941f3f8510a7c17cf9cef |
def cmd(cmd_name, source, args: list = [], version={}, params={}): <NEW_LINE> <INDENT> in_json = json.dumps({ "source": source, "version": version, "params": params, }) <NEW_LINE> command = ['/opt/resource/' + cmd_name] + args <NEW_LINE> output = subprocess.check_output(command, stderr=sys.stderr, input=bytes(in_json, ... | Wrap command interaction for easier use with python objects. | 625941f3e8904600ed9f2525 |
def make_workspace(image, labels=None, dimensions=2): <NEW_LINE> <INDENT> m = cellprofiler_core.measurement.Measurements() <NEW_LINE> object_set = cellprofiler_core.object.ObjectSet() <NEW_LINE> module = cellprofiler.modules.overlayoutlines.OverlayOutlines() <NEW_LINE> module.blank_image.value = False <NEW_LINE> module... | Make a workspace for testing Threshold | 625941f3b7558d58953c54f5 |
def rotate(curve, degs, origin=None): <NEW_LINE> <INDENT> def transform(z): <NEW_LINE> <INDENT> return exp(1j*radians(degs))*(z - origin) + origin <NEW_LINE> <DEDENT> if origin == None: <NEW_LINE> <INDENT> if isinstance(curve, Arc): <NEW_LINE> <INDENT> origin = curve.center <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>... | Returns curve rotated by `degs` degrees (CCW) around the point `origin`
(a complex number). By default origin is either `curve.point(0.5)`, or in
the case that curve is an Arc object, `origin` defaults to `curve.center`. | 625941f31b99ca400220b0a2 |
def to_postfix(pattern): <NEW_LINE> <INDENT> pattern = add_anchors(pattern) <NEW_LINE> return _to_postfix(pattern) | Transform a regular expression to the postfix form.
:param pattern: A regular expression.
:type pattern: str
:returns: A list of postfix form tokens for the given regular expression.
:rtype: list
:raises: :py:class:`~MalformedRegex` if the regular expression
is malformed. | 625941f38a349b6b435e8760 |
def to_data(pm, names, data, td, dim, file_name=None, timestep=0): <NEW_LINE> <INDENT> if len(data) > 1: <NEW_LINE> <INDENT> raise IOError('cannot save multiple quantities to data file') <NEW_LINE> <DEDENT> data = data[0] <NEW_LINE> names = names[0] <NEW_LINE> file_name = names <NEW_LINE> if td == False: <NEW_LINE> <IN... | Outputs data to a .dat file in (/data)
parameters
----------
pm: parameters object
parameters object
names: list of string
names of the data to be saved (e.g 'gs_ext_den')
data: list of array_like
list of arrays to be plotted
td: bool
True: Time-dependent data, False: ground-state data
dim: int
number of di... | 625941f37d847024c06be8af |
def memoize(self, obj): <NEW_LINE> <INDENT> if self.fast: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> assert id(obj) not in self.memo <NEW_LINE> idx = len(self.memo) <NEW_LINE> self.write(self.put(idx)) <NEW_LINE> self.memo[id(obj)] = idx, obj | Store an object in the memo. | 625941f363f4b57ef00016f5 |
def fully_conn(x_tensor, num_outputs): <NEW_LINE> <INDENT> fc_layer = tf.contrib.layers.fully_connected(x_tensor, num_outputs, activation_fn=tf.nn.relu) <NEW_LINE> return fc_layer | Apply a fully connected layer to x_tensor using weight and bias
: x_tensor: A 2-D tensor where the first dimension is batch size.
: num_outputs: The number of output that the new tensor should be.
: return: A 2-D tensor where the second dimension is num_outputs. | 625941f3379a373c97cfb135 |
def _get_32bit_data_segment(): <NEW_LINE> <INDENT> s = KVMSegment() <NEW_LINE> s.base = 0 <NEW_LINE> s.limit = 0xffffffff <NEW_LINE> s.selector = 0 <NEW_LINE> s.type = 0x2 <NEW_LINE> s.present = 1 <NEW_LINE> s.dpl = 0 <NEW_LINE> s.db = 1 <NEW_LINE> s.s = 1 <NEW_LINE> s.l = 0 <NEW_LINE> s.g = 1 <NEW_LINE> return s | Refer to the Intel System Developer Manual (Vol 3) for details
about the meaning of these fields.
:return: A data segment suitable for executing 32-bit binaries | 625941f37c178a314d6efa58 |
def get_stack(name=None): <NEW_LINE> <INDENT> __args__ = dict() <NEW_LINE> __args__['name'] = name <NEW_LINE> __ret__ = pulumi.runtime.invoke('aws:cloudformation/getStack:getStack', __args__) <NEW_LINE> return GetStackResult( capabilities=__ret__.get('capabilities'), description=__ret__.get('description'), disable_roll... | The CloudFormation Stack data source allows access to stack
outputs and other useful data including the template body. | 625941f3ec188e330fd5ad80 |
def user_private_ssh_key_download(request, user_id): <NEW_LINE> <INDENT> user = get_object_or_404(User, pk=user_id) <NEW_LINE> try: <NEW_LINE> <INDENT> user_profile = UserProfile.get_or_create_profile(request.user) <NEW_LINE> user_priv_ssh_key = user_profile.private_ssh_key <NEW_LINE> user_profile.private_ssh_key = '' ... | Download a public SSH key. | 625941f391f36d47f21acae7 |
def search_users(self, username: str = None) -> list: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return json.loads( self.api_req('post', 'users/search', data={'q': username}).text ).get('users') <NEW_LINE> <DEDENT> except UnexpectedApiResponse as e: <NEW_LINE> <INDENT> self.logger.warning(f'No response from query for... | Searches for a user in SonarQube, returns results as a list | 625941f3ac7a0e7691ed46ae |
def reset(self): <NEW_LINE> <INDENT> self.epsilon_greedy_policy.epsilon = self.start | Start the decay over at the start value. | 625941f37047854f462a19f1 |
def name_temp_file(): <NEW_LINE> <INDENT> global filename <NEW_LINE> filename = input("Give your temporary file a name (default is temp.txt): ") <NEW_LINE> if filename == '': <NEW_LINE> <INDENT> filename = 'temp.txt' | Prompts user to name the file, or sets the default name | 625941f3b545ff76a8914404 |
def validate_pawn_move( self, pawn: models.Piece, rank: int, file: int, promotion: models.PieceType = None, validate_promotion: bool = True) -> bool: <NEW_LINE> <INDENT> absolute_file_delta = abs(file - pawn.file) <NEW_LINE> relative_rank_delta = pawn.side.forwards * (rank - pawn.rank) <NEW_LINE> if relative_rank_delta... | Validate a pawn's move. | 625941f36fece00bbac2dd34 |
def model_fn(features, labels, mode, params): <NEW_LINE> <INDENT> inputs = features['inputs'] <NEW_LINE> seq_steps = features['seq_len'] <NEW_LINE> is_training = (mode == tf.estimator.ModeKeys.TRAIN) <NEW_LINE> try: <NEW_LINE> <INDENT> batch_size, length = get_shape_list(inputs, expected_rank=2) <NEW_LINE> <DEDENT> exc... | define how to train, evaluate and predict from the transfomer model.
Args:
mode:
params:
Returns: | 625941f3004d5f362079a91d |
def __init__(self, name, method='post', action=None, detect_multipart=True, session=None, **kwargs): <NEW_LINE> <INDENT> if not session: <NEW_LINE> <INDENT> raise ValueError( 'A session must be assigned to the form for validation.') <NEW_LINE> <DEDENT> super( CsrfProtectedForm, self).__init__( name, method, action, det... | Inititalize the form and set some default attributes.
Args:
name (string): the name of the form
method (string): the http method to use
action (string): the url to submit the form to
detect_multipart (boolean): automatically set multipart/form-data
session (watson.http.session.StorageMixin): the se... | 625941f39f2886367277ae76 |
def test_prep_seven_zip_which(self): <NEW_LINE> <INDENT> with mock.patch('platform.system', mock.MagicMock(return_value="Wandows")): <NEW_LINE> <INDENT> with mock.patch("bbarchivist.compat.where_which", mock.MagicMock(side_effect=ImportError)): <NEW_LINE> <INDENT> assert not bu.prep_seven_zip(True) | Test availability of 7z, no which. | 625941f34428ac0f6e5bade6 |
def enum(*sequential, **named): <NEW_LINE> <INDENT> enums = dict(zip(sequential, range(len(sequential))), **named) <NEW_LINE> return type('Enum', (), enums) | Custom enumerator creator -
example:
Numbers = enum('ZERO', 'ONE', 'TWO')
>>> Numbers.ZERO
0
>>> Numbers.ONE
1 | 625941f376e4537e8c351c66 |
def equal(u, v): <NEW_LINE> <INDENT> assert v.size == u.size <NEW_LINE> if u.store == v.store: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Return true iff u is equal to v.
>>> Vec([1,2,3]) == Vec([1,2,3])
True
>>> Vec([0,0,0]) == Vec([0,0,0])
True | 625941f38a43f66fc4b5464c |
def __setattr__(self, item, value): <NEW_LINE> <INDENT> if item in ['schedule', 'replica_flags', 'transport_guid', 'source_dsa_obj_guid', 'source_dsa_invocation_id', 'consecutive_sync_failures', 'last_success', 'last_attempt']: <NEW_LINE> <INDENT> if item in ['replica_flags']: <NEW_LINE> <INDENT> self.__dict__['update_... | Set an attribute and chyange update flag.
Be aware that setting any RepsFromTo attribute will set the
drsuapi.DRSUAPI_DRS_UPDATE_ADDRESS update flag. | 625941f35fcc89381b1e1cb2 |
def get_all_game_scores(args, game_id, teams=None, schedule=None, save=False): <NEW_LINE> <INDENT> if not teams: <NEW_LINE> <INDENT> teams = load_teams(args.data_file) <NEW_LINE> <DEDENT> if not schedule: <NEW_LINE> <INDENT> schedule = load_schedule(args.schedule_file) <NEW_LINE> <DEDENT> desired_game = 'Game %d' % gam... | Retrieve the scores for all the matches of a particular game | 625941f3a79ad161976cc734 |
def put(self, buf): <NEW_LINE> <INDENT> assert(self.pointer) <NEW_LINE> ach_py.put_buf( self.pointer, buf ) | Put a buffer into the channel.
buf -- an object providing the buffer interface | 625941f3cc40096d61595f3c |
def get_answers(self, lower=115, upper=208, full=False): <NEW_LINE> <INDENT> answers = [] <NEW_LINE> errors = {} <NEW_LINE> for i, (q, boxes) in enumerate(zip(self.questions, self.boxes)): <NEW_LINE> <INDENT> ans, error = q.get_answers(boxes, lower, upper, full) <NEW_LINE> answers.append(ans) <NEW_LINE> if error: <NEW_... | Find all answers to the questions.
Parameters
----------
lower, upper : int, optional
The treshold for the mean of the pixels of the box. If the mean is
between the upper and lower bound the box should be checked
otherwise not.
full : boolean, optional
If true, the status of every box of the question i... | 625941f3be7bc26dc91cdbe3 |
def csv_feats( comment, bngl ): <NEW_LINE> <INDENT> if bngl: <NEW_LINE> <INDENT> cols = [3, 4, 5] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cols = [2, 5, 8] <NEW_LINE> <DEDENT> tokens = re.sub(r"(\S+)\/\S+", r"\1", comment).split() <NEW_LINE> token_feats = [] <NEW_LINE> for token in tokens: <NEW_LINE> <INDENT> if r... | This function extracts the average and standard deviation of the
columns of interest in the csv files.
Parameters:
comment : string, the comment to be examining
bngl : bool, true if the csv file is BristolNorms+GilhoolyLogie,
false if it's Ratings_Warriner_et_al
Returns:
vals : Tuple[L... | 625941f366656f66f7cbc79b |
def InitInterFaceSettings_ForDefinition(self,*,uDefinitionName:str) -> None: <NEW_LINE> <INDENT> Globals.oDefinitions.InitInterFaceSettings(uDefinitionName=uDefinitionName,fSplashScreenPercentageStartValue=self.oProgessBar.value) <NEW_LINE> return None | Initializes the inerface settings for the definitions | 625941f376e4537e8c351c67 |
def iter_files(self): <NEW_LINE> <INDENT> filesdir = os.path.join(self.path, 'files') <NEW_LINE> if os.path.exists(filesdir): <NEW_LINE> <INDENT> for hsh in sorted(os.listdir(filesdir)): <NEW_LINE> <INDENT> f = UnknownFile(self, hsh) <NEW_LINE> yield f | Get all files with a stored configuration. | 625941f356b00c62f0f14c4c |
def open_file(self, fname, length=None, offset=None, swap=None, block=None, peek=None): <NEW_LINE> <INDENT> if length is None: <NEW_LINE> <INDENT> length = self.length <NEW_LINE> <DEDENT> if offset is None: <NEW_LINE> <INDENT> offset = self.offset <NEW_LINE> <DEDENT> if swap is None: <NEW_LINE> <INDENT> swap = self.swa... | Opens the specified file with all pertinent configuration settings. | 625941f34a966d76dd551605 |
def list_info(args: Any) -> int: <NEW_LINE> <INDENT> filename = args.filename <NEW_LINE> account = args.account <NEW_LINE> account_str = '' <NEW_LINE> with PassFile(filename) as passfile: <NEW_LINE> <INDENT> if account == 'ALL': <NEW_LINE> <INDENT> for account_dict in passfile.accounts(): <NEW_LINE> <INDENT> account_st... | List the info in the account or file. | 625941f3b57a9660fec33e7c |
def write_file(filename="", text=""): <NEW_LINE> <INDENT> n_characters = 0 <NEW_LINE> with open(filename, mode='w', encoding='UTF-8') as f: <NEW_LINE> <INDENT> n_characters = f.write(text) <NEW_LINE> <DEDENT> return n_characters | write a text and return the number of characters | 625941f3f7d966606f6aa5fa |
def std_decode(text, encoding='utf-8', errors='strict'): <NEW_LINE> <INDENT> return tlz.pipe(text, verify_bytestring, lambda txt: txt.decode(encoding=encoding, errors=errors)) | Standardized interface to standard python string decode method.
Only accepts byte string. | 625941f3596a89723608a0a7 |
def num_achieved_goals(): <NEW_LINE> <INDENT> goals = Goal.objects.filter(user__is_staff=False, user__is_active=True) <NEW_LINE> num_achieved_goals = 0 <NEW_LINE> for goal in goals: <NEW_LINE> <INDENT> if goal.progress >= 100: <NEW_LINE> <INDENT> num_achieved_goals += 1 <NEW_LINE> <DEDENT> <DEDENT> return num_achieved_... | Number of achieved goals | 625941f31f037a2d8b9467eb |
@pytest.mark.parametrize( ["color", "ansi"], [ ["cursor_line", "\x1b[37;46m"], ["top_statusbar", "\x1b[30;43m"], ["bottom_statusbar", "\x1b[30;43m"], ["search_label", "\x1b[34;40m"], ["search_query", "\x1b[31;40m"], ["popup_help", "\x1b[37;42m"], ["popup_stdout", "\x1b[37;44m"], ["popup_stderr", "\x1b[37;41m"], ["selec... | Test default ANSI color code generation.
Args:
setup: a local pytest fixture.
color: the name of the color.
ansi: the expected ANSI code. | 625941f307f4c71912b11a74 |
def __q2tProcessBlk(self, psl, blk, qRngNext, qRngEnd): <NEW_LINE> <INDENT> if qRngNext >= blk.qEnd: <NEW_LINE> <INDENT> return qRngNext <NEW_LINE> <DEDENT> assert(qRngNext >= blk.qStart) <NEW_LINE> tRngNext = blk.tStart + (qRngNext - blk.qStart) <NEW_LINE> if qRngEnd < blk.qEnd: <NEW_LINE> <INDENT> tRngNextNext = tRng... | Analyze next block overlapping range. Return updated qRngNext | 625941f3d268445f265b545e |
def fit_transform(self, X, y=None, **fit_params): <NEW_LINE> <INDENT> X_ = to_time_series_dataset(X) <NEW_LINE> return self.fit(X_)._transform(X_) | Fit a 1d-SAX representation and transform the data accordingly.
Parameters
----------
X : array-like of shape (n_ts, sz, d)
Time series dataset
Returns
-------
numpy.ndarray of integers with shape (n_ts, n_segments, 2 * d)
1d-SAX-Transformed dataset. The order of the last dimension is:
first d elements re... | 625941f323849d37ff7b3679 |
def read_openapi_schema( path: Path, *, loader: SchemaLoader = None ) -> DictStrAny: <NEW_LINE> <INDENT> if loader is None: <NEW_LINE> <INDENT> if path.suffix == ".json": <NEW_LINE> <INDENT> loader = json.loads <NEW_LINE> <DEDENT> elif path.suffix in {".yml", ".yaml"}: <NEW_LINE> <INDENT> loader = partial(yaml.load, Lo... | Read OpenAPI Schema from given path.
By default, when ``loader`` is not explicitly passed, attempt to guess
schema loader function from path extension.
``loader`` should be a callable, which receives ``bytes`` and returns
``Dict[str, Any]`` of OpenAPI Schema.
By default, next schema loader used,
- :func:`json.loads... | 625941f3460517430c394763 |
def MakeRequest( url, source_url, start_time=None, headers_time=None, end_time=None, magic_content_type=False, initiator_type='other'): <NEW_LINE> <INDENT> assert ((start_time is None and headers_time is None and end_time is None) or (start_time is not None and headers_time is not None and end_time is not None)), ... | Make a dependent request.
Args:
url: a url, or number which will be used as a url.
source_url: a url or number which will be used as the source (initiating)
url. If the source url is not present, then url will be a root. The
convention in tests is to use a source_url of 'null' in this case.
start_time: T... | 625941f3e1aae11d1e74a2ac |
def setUp(self): <NEW_LINE> <INDENT> self.cred = Credential( name='cred1', cred_type=Credential.SATELLITE_CRED_TYPE, username='username', password='password', become_password=None, become_method=None, become_user=None, ssh_keyfile=None) <NEW_LINE> self.cred.save() <NEW_LINE> self.source = Source( name='source1', port=4... | Create test case setup. | 625941f30c0af96317bb87d6 |
def min_value(self, game_state, index, depth, alpha, beta): <NEW_LINE> <INDENT> legalMoves = game_state.getLegalActions(index) <NEW_LINE> min_value = float("inf") <NEW_LINE> min_action = "" <NEW_LINE> for action in legalMoves: <NEW_LINE> <INDENT> successor = game_state.generateSuccessor(index, action) <NEW_LINE> succes... | Returns the min utility action-score for min-agent with alpha-beta pruning | 625941f32c8b7c6e89b35dab |
def matrix4_to_array(mat): <NEW_LINE> <INDENT> return tuple(f for v in mat.transposed() for f in v) | Concatenate matrix's columns into a single, flat tuple | 625941f3a4f1c619b28b0619 |
@AUTH.route("/login", methods=["GET", "POST"]) <NEW_LINE> def login(): <NEW_LINE> <INDENT> form = LoginForm() <NEW_LINE> if form.validate_on_submit(): <NEW_LINE> <INDENT> _user = User.get_by_username(form.username.data) <NEW_LINE> if _user is not None and _user.check_password(form.password.data): <NEW_LINE> <INDENT> lo... | Processes user login
:return: renders template | 625941f3236d856c2ad44dd2 |
def datetime_to_timestamp(date): <NEW_LINE> <INDENT> if isinstance(date, datetime): <NEW_LINE> <INDENT> timestamp = mktime(date.timetuple()) <NEW_LINE> json_timestamp = int(timestamp) * 1000 <NEW_LINE> return '{0}'.format(json_timestamp) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "" | Converts datetime to timestamp
with json fix | 625941f3d7e4931a7ee9e50f |
def retrieve(self, resource_id, **kwargs): <NEW_LINE> <INDENT> return Transfer(self, **self.get('/v2/transfers/' + resource_id, query=kwargs)) | Returns an array of Transfer objects for the given search criteria. | 625941f3c432627299f0523a |
def parse_ui__universe_count(user_input): <NEW_LINE> <INDENT> start_index = user_input.find(':') <NEW_LINE> if start_index > -1: <NEW_LINE> <INDENT> universe_count_new = user_input[start_index + 1:] <NEW_LINE> try: <NEW_LINE> <INDENT> universe_count_new = int(universe_count_new) <NEW_LINE> <DE... | Parse universe count. | 625941f3956e5f7376d7145a |
def show_actions(self, _widget=None, _uri=None): <NEW_LINE> <INDENT> dialog = message_dialogs.ShowActionsDialog(self.main_window, self.list_actions.actions_list) <NEW_LINE> self.run_dialog(dialog) <NEW_LINE> return True | Show scheduled actions
| 625941f3283ffb24f3c55eea |
def __init__(self, filenames, transform=None): <NEW_LINE> <INDENT> self.filenames = filenames <NEW_LINE> self.transform = transform | Initialization | 625941f33eb6a72ae02ecade |
def validate_email(self, email): <NEW_LINE> <INDENT> if User.objects.filter(email=email).exists(): <NEW_LINE> <INDENT> raise serializers.ValidationError("중복되는 이메일이 존재합니다.") <NEW_LINE> <DEDENT> return email | 중복되는 이메일이 있는지 검사합니다. | 625941f360cbc95b062c6b33 |
def test_non_crf_modelform_mixin_not_ok(self): <NEW_LINE> <INDENT> SubjectOffstudy.objects.create( offstudy_datetime=get_utcnow() - relativedelta(days=1), subject_identifier=self.subject_identifier) <NEW_LINE> data = dict( subject_identifier=self.subject_identifier, report_datetime=get_utcnow()) <NEW_LINE> form = NonCr... | Asserts that Offstudy class is called.
Other tests above apply. | 625941f367a9b606de4a84a5 |
def insertControl(trk, ln): <NEW_LINE> <INDENT> if len(ln) != 3: <NEW_LINE> <INDENT> error("MidiNote: Controller expecting 3 arguments.") <NEW_LINE> <DEDENT> offset = getoffset(trk, ln[0]) <NEW_LINE> v = MMA.midiC.ctrlToValue(ln[1]) <NEW_LINE> if v < 0: <NEW_LINE> <INDENT> v = stoi(ln[1]) <NEW_LINE> if v < 0 or v > 0x7... | Insert a controller event. | 625941f3462c4b4f79d1dcbf |
def simulate(self, partition, outdir, jobhandler=default_jobhandler, batchsize=1, **kwargs): <NEW_LINE> <INDENT> results = self.get_partition_results(partition) <NEW_LINE> DEFAULT_DNA_MODEL = 'GTR' <NEW_LINE> DEFAULT_PROTEIN_MODEL = 'LG08' <NEW_LINE> args = [None] * len(self.collection) <NEW_LINE> for result in results... | Simulate a set of alignments from the parameters inferred on a partition
:param partition:
:return: | 625941f3de87d2750b860389 |
def find_security_group_by_name(conn, sg_name): <NEW_LINE> <INDENT> sgs = conn.describe_security_groups(Filters=[{'Name': 'group-name', 'Values': [sg_name]}]) <NEW_LINE> return sgs | Finds and returns a security group by name | 625941f30fa83653e46575a6 |
def notify_success(context): <NEW_LINE> <INDENT> attachments = [ { "fallback": "{0} success".format(context['task']), "color": "#36a64f", "title": "{0} successfully end!".format(context['dag'], context['task']), "title_link": settings.AIRFLOW_SERVER_URL, "text": ":ok_woman:" } ] <NEW_LINE> notify_base(attachments) | notify_success
Notification of success of the task.
Pass this function through the argument,
`on_success_callback` to an operator.
:param context:
:return: None | 625941f363b5f9789fde76d5 |
def complete_flag_based(self, text, line, begidx, endidx) -> List[str]: <NEW_LINE> <INDENT> flag_dict = { '-f': food_item_strs, '--food': food_item_strs, '-s': sport_item_strs, '--sport': sport_item_strs, '-p': self.path_complete, '--path': self.path_complete, } <NEW_LINE> return self.flag_based_complete(text, line, be... | Completion function for do_flag_based | 625941f30383005118ecfbd0 |
def schedule_host(self, tenant_id, instance_id, instance_desc): <NEW_LINE> <INDENT> LOG.debug(_("schedule_host() called")) <NEW_LINE> host_list = self._invoke_device_plugins(self._func_name(), [tenant_id, instance_id, instance_desc]) <NEW_LINE> return host_list | Provides the hostname on which a dynamic vnic is reserved | 625941f3be8e80087fb21227 |
def gcd(a: int, b: int) -> int: <NEW_LINE> <INDENT> while a != 0 and b != 0: <NEW_LINE> <INDENT> if a > b: <NEW_LINE> <INDENT> a = a % b <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> b = b % a <NEW_LINE> <DEDENT> <DEDENT> return a + b | Euclid's algorithm for determining the greatest common divisor.
>>> gcd(12, 15)
3
>>> gcd(3, 7)
1 | 625941f324f1403a92601150 |
def _set_var(self, controller, var, value): <NEW_LINE> <INDENT> self.env[controller][var] = value | Set controller environment variable to value | 625941f397e22403b379d58b |
@user_passes_test(check_user_is_hiccup_staff) <NEW_LINE> def device_stats(request): <NEW_LINE> <INDENT> template = loader.get_template("crashreport_stats/device.html") <NEW_LINE> uuid = request.GET.get("uuid", "NO_UUID") <NEW_LINE> if not Device.objects.filter(uuid=uuid).exists(): <NEW_LINE> <INDENT> raise Http404("Dev... | Respond with statistics for a specific device. | 625941f38e7ae83300e4b5be |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.