code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def unlock(self, lock): <NEW_LINE> <INDENT> del self.__locks[lock] | Removes the given lock
| 625941bd4c3428357757c231 |
def __init__(self, icon, parent=None): <NEW_LINE> <INDENT> QSystemTrayIcon.__init__(self, icon, parent) <NEW_LINE> self.menu = None <NEW_LINE> self._load_menu() | Constructor. | 625941bd30bbd722463cbcca |
def build_resource(properties): <NEW_LINE> <INDENT> resource = {} <NEW_LINE> for p in properties: <NEW_LINE> <INDENT> prop_array = p.split('.') <NEW_LINE> ref = resource <NEW_LINE> for pa in range(0, len(prop_array)): <NEW_LINE> <INDENT> is_array = False <NEW_LINE> key = prop_array[pa] <NEW_LINE> if key[-2:] == '[]': <NEW_LINE> <INDENT> key = key[0:len(key)-2:] <NEW_LINE> is_array = True <NEW_LINE> <DEDENT> if pa == (len(prop_array) - 1): <NEW_LINE> <INDENT> if properties[p]: <NEW_LINE> <INDENT> if is_array: <NEW_LINE> <INDENT> ref[key] = properties[p].split(',') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ref[key] = properties[p] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif key not in ref: <NEW_LINE> <INDENT> ref[key] = {} <NEW_LINE> ref = ref[key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ref = ref[key] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return resource | This builds the body listed by the properties which can further be
used to update the body of a playlist, playlistitem, etc. | 625941bd29b78933be1e55b7 |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.tags = kwargs.pop('tags', []) <NEW_LINE> super(Tags, self).__init__(*args, **kwargs) | Args:
**kwargs: If kwargs contains `tags`, assign them to the attribute. | 625941bd29b78933be1e55b8 |
def numDistinct(self, s, t): <NEW_LINE> <INDENT> cnt = [1] + [0] * (len(t)) <NEW_LINE> for ch in s: <NEW_LINE> <INDENT> for i in range(len(t)-1,-1,-1): <NEW_LINE> <INDENT> if ch == t[i]: <NEW_LINE> <INDENT> cnt[i+1] += cnt[i] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return cnt[-1] | :type s: str
:type t: str
:rtype: int | 625941bdbd1bec0571d9053d |
def __call__(self, *args: Any, **kwargs: Any): <NEW_LINE> <INDENT> sys_method = ("listMethods", "methodSignature", 'methodHelp', 'lenConnections', 'lenUndoneTasks', 'getresult') <NEW_LINE> if self.__name.startswith("system."): <NEW_LINE> <INDENT> if self.__name.split(".")[-1] not in sys_method: <NEW_LINE> <INDENT> raise UnsupportSysMethodError( "UnsupportSysMethod:{}".format(self.__name), self.__ID ) <NEW_LINE> <DEDENT> <DEDENT> return self.__send( self.__ID, self.__name, *args, **kwargs) | 执行发送任务.
Parameters:
args (Any): - 远端名字是<name>的函数的位置参数
kwargs (Any): - 远端名字是<name>的函数的关键字参数
Return:
(Any): - 发送函数send的返回值 | 625941bd1f5feb6acb0c4a5b |
def set_target(self, target_player): <NEW_LINE> <INDENT> if isinstance(target_player, PlayerInterface): <NEW_LINE> <INDENT> self.target_player = target_player <NEW_LINE> self.current_pattern.clone(self.target_player.get_color_pattern()) <NEW_LINE> self.current_pattern_counter = 0 <NEW_LINE> self.next_add_symbol_index = 0 <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Implemented UpdateHelper set_target
set target player | 625941bd26068e7796caebe1 |
def adverbs(input): <NEW_LINE> <INDENT> return count_tags(input, ['RB', 'RBR', 'RBS']) | valid = tagged as RB, RBR, RBS
:param input:
:return: | 625941bdab23a570cc250087 |
def weather_command(self, message): <NEW_LINE> <INDENT> location = message.arg <NEW_LINE> if len(location) == 0: <NEW_LINE> <INDENT> message.reply(self.__class__.error_msg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> weather_forecast(location, message) | /w: 天气预报 | 625941bdd7e4931a7ee9de24 |
def transform(self, node): <NEW_LINE> <INDENT> typemap = self.typemap <NEW_LINE> entries = [] <NEW_LINE> groupindices = {} <NEW_LINE> types = {} <NEW_LINE> for field in node: <NEW_LINE> <INDENT> fieldname, fieldbody = field <NEW_LINE> try: <NEW_LINE> <INDENT> fieldtype, fieldarg = fieldname.astext().split(None, 1) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> fieldtype, fieldarg = fieldname.astext(), '' <NEW_LINE> <DEDENT> typedesc, is_typefield = typemap.get(fieldtype, (None, None)) <NEW_LINE> if _is_single_paragraph(fieldbody): <NEW_LINE> <INDENT> content = fieldbody.children[0].children <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> content = fieldbody.children <NEW_LINE> <DEDENT> print('Field %s content is (%s) >%s<' % (fieldname, len(content), content)) <NEW_LINE> if not content: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if typedesc is None or typedesc.has_arg != bool(fieldarg): <NEW_LINE> <INDENT> print('Unknown field >%s<' % (field)) <NEW_LINE> new_fieldname = fieldtype[0:1].upper() + fieldtype[1:] <NEW_LINE> if fieldarg: <NEW_LINE> <INDENT> new_fieldname += ' ' + fieldarg <NEW_LINE> <DEDENT> fieldname[0] = nodes.Text(new_fieldname) <NEW_LINE> entries.append(field) <NEW_LINE> continue <NEW_LINE> <DEDENT> typename = typedesc.name <NEW_LINE> if is_typefield: <NEW_LINE> <INDENT> content = [n for n in content if isinstance(n, nodes.Inline) or isinstance(n, nodes.Text)] <NEW_LINE> if content: <NEW_LINE> <INDENT> types.setdefault(typename, {})[fieldarg] = content <NEW_LINE> <DEDENT> continue <NEW_LINE> <DEDENT> if typedesc.is_typed: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> argtype, argname = fieldarg.split(None, 1) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> types.setdefault(typename, {})[argname] = [nodes.Text(argtype)] <NEW_LINE> fieldarg = argname <NEW_LINE> <DEDENT> <DEDENT> translatable_content = nodes.inline(fieldbody.rawsource, translatable=True) <NEW_LINE> translatable_content.document = fieldbody.parent.document <NEW_LINE> translatable_content.source = fieldbody.parent.source <NEW_LINE> translatable_content.line = fieldbody.parent.line <NEW_LINE> translatable_content += content <NEW_LINE> if typedesc.is_grouped: <NEW_LINE> <INDENT> if typename in groupindices: <NEW_LINE> <INDENT> group = entries[groupindices[typename]] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> groupindices[typename] = len(entries) <NEW_LINE> group = [typedesc, []] <NEW_LINE> entries.append(group) <NEW_LINE> <DEDENT> entry = typedesc.make_entry(fieldarg, [translatable_content]) <NEW_LINE> group[1].append(entry) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> entry = typedesc.make_entry(fieldarg, [translatable_content]) <NEW_LINE> entries.append([typedesc, entry]) <NEW_LINE> <DEDENT> <DEDENT> new_list = nodes.field_list() <NEW_LINE> for entry in entries: <NEW_LINE> <INDENT> if isinstance(entry, nodes.field): <NEW_LINE> <INDENT> new_list += entry <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fieldtype, content = entry <NEW_LINE> fieldtypes = types.get(fieldtype.name, {}) <NEW_LINE> env = self.directive.state.document.settings.env <NEW_LINE> new_list += fieldtype.make_field(fieldtypes, self.directive.domain, content, env=env) <NEW_LINE> <DEDENT> <DEDENT> node.replace_self(new_list) | Transform a single field list *node*. | 625941bdf7d966606f6a9f08 |
def buildTriangle(self, x0, y0, n=6): <NEW_LINE> <INDENT> numcol = [(color.YELLOW, "1"), (color.BLUE, "2"), (color.RED, "3"), (color.PINK, "4"), (color.BLACK, "8"), (color.DARK_GREEN, "6"), (color.BROWN, "7"), (color.ORANGE, "5"), (color.YELLOW, "9"), (color.BLUE, "10"), (color.RED, "11"), (color.PINK, "12"), (color.ORANGE, "13"), (color.DARK_GREEN, "14"), (color.BROWN, "15")] <NEW_LINE> triangle = [1, 1, 0, 1, 8, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0] <NEW_LINE> tmp = [] <NEW_LINE> coords = self.triangleCoords(0.5, 0.5) <NEW_LINE> for i, pair in enumerate(numcol): <NEW_LINE> <INDENT> x, y = coords[i] <NEW_LINE> ball = kugel.Ball(pair[0], triangle[i], pair[1], x, y) <NEW_LINE> tmp.append(ball) <NEW_LINE> <DEDENT> return tmp | Initiates the balls required to play the game.
Associate colors with numbers and boolean values to
identify balls and initiates balls with these values and the
proper initial positions. Returns a list of ball objects. This
list is the one that is supposed to bo used throughout the game. | 625941bd38b623060ff0acf6 |
def gen_inputs(self, dir_path, out_len, out_overlap=0): <NEW_LINE> <INDENT> EMG = [] <NEW_LINE> for path in walk_through_dir(dir_path): <NEW_LINE> <INDENT> print('MUAPTs file path: ', path) <NEW_LINE> seq_data = np.load(path) <NEW_LINE> seq_data = np.squeeze(seq_data) <NEW_LINE> seq_data = self.filter(seq_data) <NEW_LINE> print(path, 'Seq Length: ', len(seq_data)) <NEW_LINE> EMG.append(self.cut_sequence_to_matrix(seq_data, out_len, out_overlap)) <NEW_LINE> <DEDENT> EMG = np.concatenate(EMG, axis=0) <NEW_LINE> EMG = self.del_emg_too_small(EMG) <NEW_LINE> self.x = EMG | dir_path: 采样率均为1kHz,读取目录下面的全部结尾为.npy的文件
out_len: 输出的iEMG长度 | 625941bdcc40096d61595859 |
def test_single_null(setup_teardown_file): <NEW_LINE> <INDENT> f = setup_teardown_file[3] <NEW_LINE> dset = f.create_dataset('x', (1,), dtype='i1') <NEW_LINE> out = dset[()] <NEW_LINE> assert isinstance(out, np.ndarray) <NEW_LINE> assert out.shape == (1,) | Single-element selection with [()] yields ndarray. | 625941bda79ad161976cc04c |
def arith_prover(a, b, A, B, C, rnd_bytes=os.urandom, RO=sha2): <NEW_LINE> <INDENT> assert a*G == A <NEW_LINE> assert b*G == B <NEW_LINE> assert (a*(b-3))*G == C | Params:
a and b are elements of Fp
A, B, C are Points
Returns:
prf, of the form (KA,KB,KC,sa,sb)
Must satisfy verify_proof2(A, B, C, prf)
Must be zero-knowledge | 625941bd097d151d1a222d63 |
def mostCompetitive(self, nums: List[int], k: int) -> List[int]: <NEW_LINE> <INDENT> N = len(nums) <NEW_LINE> stack = [] <NEW_LINE> skipped = 0 <NEW_LINE> for i,num in enumerate(nums): <NEW_LINE> <INDENT> while stack and num < stack[-1] and skipped < N - k: <NEW_LINE> <INDENT> pop = stack.pop() <NEW_LINE> skipped += 1 <NEW_LINE> <DEDENT> stack.append(num) <NEW_LINE> <DEDENT> return stack[:k] | stack solution | 625941bd287bf620b61d396d |
def move_config(config_file, model_dir): <NEW_LINE> <INDENT> tf.logging.info("Copying config file to model directory...") <NEW_LINE> tf.gfile.MakeDirs(os.path.join(model_dir, CONFIG_DIR)) <NEW_LINE> new_config_file = os.path.join(model_dir, CONFIG_DIR, os.path.basename(config_file)) <NEW_LINE> tf.gfile.Copy(config_file, new_config_file, overwrite=True) <NEW_LINE> return new_config_file | Move config file to model directory | 625941bd07d97122c417878d |
@parser.command <NEW_LINE> def echo(con, message): <NEW_LINE> <INDENT> con.message(message) | Send a message right back to a connected client. | 625941bd63d6d428bbe443f7 |
def __init__(self, limit=None, offset=None, global_only=None, include_inherited=None, owner_ids=None, resource_ids=None, role_ids=None, sort_field=None, sort_order=None): <NEW_LINE> <INDENT> self._limit = None <NEW_LINE> self._offset = None <NEW_LINE> self._global_only = None <NEW_LINE> self._include_inherited = None <NEW_LINE> self._owner_ids = None <NEW_LINE> self._resource_ids = None <NEW_LINE> self._role_ids = None <NEW_LINE> self._sort_field = None <NEW_LINE> self._sort_order = None <NEW_LINE> self.discriminator = None <NEW_LINE> if limit is not None: <NEW_LINE> <INDENT> self.limit = limit <NEW_LINE> <DEDENT> if offset is not None: <NEW_LINE> <INDENT> self.offset = offset <NEW_LINE> <DEDENT> if global_only is not None: <NEW_LINE> <INDENT> self.global_only = global_only <NEW_LINE> <DEDENT> if include_inherited is not None: <NEW_LINE> <INDENT> self.include_inherited = include_inherited <NEW_LINE> <DEDENT> if owner_ids is not None: <NEW_LINE> <INDENT> self.owner_ids = owner_ids <NEW_LINE> <DEDENT> if resource_ids is not None: <NEW_LINE> <INDENT> self.resource_ids = resource_ids <NEW_LINE> <DEDENT> if role_ids is not None: <NEW_LINE> <INDENT> self.role_ids = role_ids <NEW_LINE> <DEDENT> if sort_field is not None: <NEW_LINE> <INDENT> self.sort_field = sort_field <NEW_LINE> <DEDENT> if sort_order is not None: <NEW_LINE> <INDENT> self.sort_order = sort_order | XmlNs0FindResponsibilitiesRequest - a model defined in Swagger | 625941bdff9c53063f47c0fc |
@np.deprecate(message="scipy.special.sph_jnyn is deprecated in scipy 0.18.0. " "Use scipy.special.spherical_jn and " "scipy.special.spherical_yn instead. " "Note that the new function has a different signature.") <NEW_LINE> def sph_jnyn(n, z): <NEW_LINE> <INDENT> if not (isscalar(n) and isscalar(z)): <NEW_LINE> <INDENT> raise ValueError("arguments must be scalars.") <NEW_LINE> <DEDENT> if (n != floor(n)) or (n < 0): <NEW_LINE> <INDENT> raise ValueError("n must be a non-negative integer.") <NEW_LINE> <DEDENT> if (n < 1): <NEW_LINE> <INDENT> n1 = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> n1 = n <NEW_LINE> <DEDENT> if iscomplex(z) or less(z, 0): <NEW_LINE> <INDENT> nm, jn, jnp, yn, ynp = specfun.csphjy(n1, z) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nm, yn, ynp = specfun.sphy(n1, z) <NEW_LINE> nm, jn, jnp = specfun.sphj(n1, z) <NEW_LINE> <DEDENT> return jn[:(n+1)], jnp[:(n+1)], yn[:(n+1)], ynp[:(n+1)] | Compute spherical Bessel functions jn(z) and yn(z) and derivatives.
This function computes the value and first derivative of jn(z) and yn(z)
for all orders up to and including n.
Parameters
----------
n : int
Maximum order of jn and yn to compute
z : complex
Argument at which to evaluate
Returns
-------
jn : ndarray
Value of j0(z), ..., jn(z)
jnp : ndarray
First derivative j0'(z), ..., jn'(z)
yn : ndarray
Value of y0(z), ..., yn(z)
ynp : ndarray
First derivative y0'(z), ..., yn'(z)
See also
--------
spherical_jn
spherical_yn
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 8.
http://jin.ece.illinois.edu/specfunc.html | 625941bd009cb60464c632bb |
def create_dt_from_response(self): <NEW_LINE> <INDENT> self.httpinfo['headers'] = dict(self.httpresponse.headers) <NEW_LINE> self.httpinfo['rawpage'] = self.httpresponse.read().decode('utf-8') <NEW_LINE> self.httpinfo['msg'] = '%s %s' % (self.httpresponse.code, self.httpresponse.msg) | Set up appropriate datastructures in self.httpinfo. | 625941bd82261d6c526ab3a3 |
@pytest.mark.skip() <NEW_LINE> def test_misclassified_points_empty(): <NEW_LINE> <INDENT> pass | The list of mis | 625941bd5fdd1c0f98dc0139 |
def __getattr__(self, name): <NEW_LINE> <INDENT> def _pass_attr(*args, **kwargs): <NEW_LINE> <INDENT> self.initialise(self.descDict) <NEW_LINE> return getattr(self.internalDict, name)(*args, **kwargs) <NEW_LINE> <DEDENT> return _pass_attr | Deal with all names that are not defined explicitly by passing them to the internal dictionary (after initialising it). | 625941bda219f33f34628874 |
def __init__( self, address: int = 0, count: int = 0, data: bytes | None = None ) -> None: <NEW_LINE> <INDENT> if data is None: <NEW_LINE> <INDENT> data = bytearray() <NEW_LINE> <DEDENT> self.address = address <NEW_LINE> self.count = count <NEW_LINE> self.data = data | Initialize a new instance of MemoryResponse. | 625941bd7b25080760e39362 |
def single(self, query_data: Dict[str, Any]) -> Dict[str, Any]: <NEW_LINE> <INDENT> _key = query_data.pop(self.identifier) <NEW_LINE> query_data[self.id_key] = str(_key) <NEW_LINE> return query_data | :param query_data: Mongo Document
:return: | 625941bdcad5886f8bd26ee4 |
def sparse_read(self, indices, name=None): <NEW_LINE> <INDENT> with ops.name_scope("Gather" if name is None else name) as name: <NEW_LINE> <INDENT> if self.trainable: <NEW_LINE> <INDENT> tape.watch_variable(self) <NEW_LINE> <DEDENT> value = gen_resource_variable_ops.resource_gather( self._handle, indices, dtype=self._dtype, name=name) <NEW_LINE> <DEDENT> return array_ops.identity(value) | Reads the value of this variable sparsely, using `gather`. | 625941bd16aa5153ce362380 |
def add_outliers(self, config): <NEW_LINE> <INDENT> OUTLIER_GENERATORS = {'extreme': MultivariateExtremeOutlierGenerator, 'shift': MultivariateShiftOutlierGenerator, 'trend': MultivariateTrendOutlierGenerator, 'variance': MultivariateVarianceOutlierGenerator} <NEW_LINE> generator_keys = [] <NEW_LINE> for outlier_key, outlier_generator_config in config.items(): <NEW_LINE> <INDENT> assert outlier_key in OUTLIER_GENERATORS, 'outlier_key must be one of {} but was'.format(OUTLIER_GENERATORS, outlier_key) <NEW_LINE> generator_keys.append(outlier_key) <NEW_LINE> for outlier_timeseries_config in outlier_generator_config: <NEW_LINE> <INDENT> n, timestamps = outlier_timeseries_config['n'], outlier_timeseries_config['timestamps'] <NEW_LINE> assert n in range(self.N), 'n must be between 0 and {} but was {}'.format(self.N - 1, n) <NEW_LINE> for timestamp in list(sum(timestamps, ())): <NEW_LINE> <INDENT> assert timestamp in range( self.STREAM_LENGTH), 'timestamp must be between 0 and {} but was {}'.format(self.STREAM_LENGTH, timestamp) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> df = self.data <NEW_LINE> if self.data.shape == (0, 0): <NEW_LINE> <INDENT> raise Exception('You have to first compute a base line by invoking generate_baseline()') <NEW_LINE> <DEDENT> for generator_key in generator_keys: <NEW_LINE> <INDENT> for outlier_timeseries_config in config[generator_key]: <NEW_LINE> <INDENT> n, timestamps = outlier_timeseries_config['n'], outlier_timeseries_config['timestamps'] <NEW_LINE> generator_args = dict([(k, v) for k, v in outlier_timeseries_config.items() if k not in ['n', 'timestamps']]) <NEW_LINE> generator = OUTLIER_GENERATORS[generator_key](timestamps=timestamps, **generator_args) <NEW_LINE> df[df.columns[n]] += generator.add_outliers(self.data[self.data.columns[n]]) <NEW_LINE> <DEDENT> <DEDENT> assert not df.isnull().values.any(), 'There is at least one NaN in the generated DataFrame' <NEW_LINE> self.outlier_data = df <NEW_LINE> return df | Adds outliers based on the given configuration to the base line
:param config: Configuration file for the outlier addition e.g.
{'extreme': [{'n': 0, 'timestamps': [(3,)]}],
'shift': [{'n': 3, 'timestamps': [(4,10)]}]}
would add an extreme outlier to time series 0 at timestamp 3 and a base shift
to time series 3 between timestamps 4 and 10
:return: | 625941bd3317a56b86939b67 |
def adjust_results4_isadog(results_dic, dogfile): <NEW_LINE> <INDENT> dognames_dic = dict() <NEW_LINE> with open(dogfile, "r") as infile: <NEW_LINE> <INDENT> line = infile.readline() <NEW_LINE> while line != "": <NEW_LINE> <INDENT> if line not in dognames_dic: <NEW_LINE> <INDENT> dognames_dic[line.rstrip()] = 1 <NEW_LINE> <DEDENT> line = infile.readline() <NEW_LINE> <DEDENT> <DEDENT> for key in results_dic: <NEW_LINE> <INDENT> if results_dic[key][0] in dognames_dic: <NEW_LINE> <INDENT> if results_dic[key][1] in dognames_dic: <NEW_LINE> <INDENT> print('test1') <NEW_LINE> results_dic[key].extend((1, 1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('test2') <NEW_LINE> results_dic[key].extend((1, 0)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if results_dic[key][1] in dognames_dic: <NEW_LINE> <INDENT> print('test3') <NEW_LINE> results_dic[key].extend((0, 1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('test4') <NEW_LINE> results_dic[key].extend((0, 0)) | Adjusts the results dictionary to determine if classifier correctly
classified images 'as a dog' or 'not a dog' especially when not a match.
Demonstrates if model architecture correctly classifies dog images even if
it gets dog breed wrong (not a match).
Parameters:
results_dic - Dictionary with 'key' as image filename and 'value' as a
List. Where the list will contain the following items:
index 0 = pet image label (string)
index 1 = classifier label (string)
index 2 = 1/0 (int) where 1 = match between pet image
and classifer labels and 0 = no match between labels
------ where index 3 & index 4 are added by this function -----
NEW - index 3 = 1/0 (int) where 1 = pet image 'is-a' dog and
0 = pet Image 'is-NOT-a' dog.
NEW - index 4 = 1/0 (int) where 1 = Classifier classifies image
'as-a' dog and 0 = Classifier classifies image
'as-NOT-a' dog.
dogfile - A text file that contains names of all dogs from the classifier
function and dog names from the pet image files. This file has
one dog name per line dog names are all in lowercase with
spaces separating the distinct words of the dog name. Dog names
from the classifier function can be a string of dog names separated
by commas when a particular breed of dog has multiple dog names
associated with that breed (ex. maltese dog, maltese terrier,
maltese) (string - indicates text file's filename)
Returns:
None - results_dic is mutable data type so no return needed. | 625941bd8a43f66fc4b53f70 |
def remove_mask(image): <NEW_LINE> <INDENT> mask = ee.Image(1) <NEW_LINE> return image.updateMask(mask) | Removes the mask from an EE image.
Args:
image: The input EE image.
Returns:
The EE image without its mask. | 625941bd3346ee7daa2b2c71 |
def test_action_model(app): <NEW_LINE> <INDENT> assert Action.query.count() == 2 | Test number of records in Action table | 625941bde1aae11d1e749bbc |
def is_ordinary_singularity(self, P): <NEW_LINE> <INDENT> r = self.multiplicity(P) <NEW_LINE> if r < 2: <NEW_LINE> <INDENT> raise TypeError("(=%s) is not a singular point of (=%s)"%(P,self)) <NEW_LINE> <DEDENT> i = 0 <NEW_LINE> while P[i] == 0: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> <DEDENT> C = self.affine_patch(i) <NEW_LINE> return C.is_ordinary_singularity(C(P.dehomogenize(i))) | Return whether the singular point ``P`` of this projective plane curve is an ordinary singularity.
The point ``P`` is an ordinary singularity of this curve if it is a singular point, and
if the tangents of this curve at ``P`` are distinct.
INPUT:
- ``P`` -- a point on this curve.
OUTPUT:
- Boolean. True or False depending on whether ``P`` is or is not an ordinary singularity of this
curve, respectively. An error is raised if ``P`` is not a singular point of this curve.
EXAMPLES::
sage: P.<x,y,z> = ProjectiveSpace(QQ, 2)
sage: C = Curve([y^2*z^3 - x^5], P)
sage: Q = P([0,0,1])
sage: C.is_ordinary_singularity(Q)
False
::
sage: R.<a> = QQ[]
sage: K.<b> = NumberField(a^2 - 3)
sage: P.<x,y,z> = ProjectiveSpace(K, 2)
sage: C = P.curve([x^2*y^3*z^4 - y^6*z^3 - 4*x^2*y^4*z^3 - 4*x^4*y^2*z^3 + 3*y^7*z^2 + 10*x^2*y^5*z^2\
+ 9*x^4*y^3*z^2 + 5*x^6*y*z^2 - 3*y^8*z - 9*x^2*y^6*z - 11*x^4*y^4*z - 7*x^6*y^2*z - 2*x^8*z + y^9 +\
2*x^2*y^7 + 3*x^4*y^5 + 4*x^6*y^3 + 2*x^8*y])
sage: Q = P([0,1,1])
sage: C.is_ordinary_singularity(Q)
True
::
sage: P.<x,y,z> = ProjectiveSpace(QQ, 2)
sage: C = P.curve([z^5 - y^5 + x^5 + x*y^2*z^2])
sage: Q = P([0,1,1])
sage: C.is_ordinary_singularity(Q)
Traceback (most recent call last):
...
TypeError: (=(0 : 1 : 1)) is not a singular point of (=Projective Plane
Curve over Rational Field defined by x^5 - y^5 + x*y^2*z^2 + z^5) | 625941bdfb3f5b602dac3598 |
def put(self, item): <NEW_LINE> <INDENT> with self._cond_not_full: <NEW_LINE> <INDENT> if self._maxsize > 0: <NEW_LINE> <INDENT> while self._queue_size() == self._maxsize: <NEW_LINE> <INDENT> self._cond_not_full.wait() <NEW_LINE> <DEDENT> <DEDENT> self._put(item) <NEW_LINE> self._unfinished_tasks += 1 <NEW_LINE> self._cond_not_empty.notify() | Put an item into the queue. | 625941bdbe383301e01b5393 |
def grad(b, a, x): <NEW_LINE> <INDENT> m = len(b) <NEW_LINE> d = x.shape[0] <NEW_LINE> gr = np.zeros(d, dtype=float) <NEW_LINE> for j in range(d): <NEW_LINE> <INDENT> for k in range(m): <NEW_LINE> <INDENT> gr[j] += (innprod(x, a[k, :]) - b[k]) * a[k, j] <NEW_LINE> <DEDENT> <DEDENT> return gr | Compute the gradient of (y - <c,z>)^2, with respect to z,
evaluated at z=x. | 625941bdbf627c535bc130d6 |
def run_tsne_viz(dsname, cats): <NEW_LINE> <INDENT> report_fpath = "{}_{}_modified_sklearn".format(dsname, "_".join(sorted(cats))) <NEW_LINE> sos_fpath = "{}_{}_modified_sklearn_sos".format(dsname, "_".join(sorted(cats))) <NEW_LINE> report_fullpath = osp.join(REPORT_DIR, report_fpath+".html") <NEW_LINE> sos_fullpath = osp.join(REPORT_DIR, sos_fpath+".pkl") <NEW_LINE> print("cats = {}".format(cats)) <NEW_LINE> if not osp.exists(report_fullpath) or not osp.exists(sos_fullpath) : <NEW_LINE> <INDENT> run_command([ "python", "/mnt/ssd_01/khoa/python_scripts/detection_tsne.py", "-I", dsname, "-R", report_fpath, "-D", "/mnt/ssd_01/khoa/furniture_detection/data", "-C" ]+list(map(str, cats))) <NEW_LINE> <DEDENT> sosdata = pkl.load(open(sos_fullpath, "rb")) <NEW_LINE> postsos = defaultdict(list) <NEW_LINE> subcluster = defaultdict(lambda: defaultdict(list)) <NEW_LINE> print("type sosdata: {}".format(type(sosdata))) <NEW_LINE> print("len sosdata: {}".format(len(sosdata))) <NEW_LINE> for impath, sos, lblids, label in zip(*sosdata): <NEW_LINE> <INDENT> postsos[label].append([osp.join("http://hydra2.visenze.com:4567/", impath), sos]) <NEW_LINE> subcluster[label][int(lblids)].append([osp.join("http://hydra2.visenze.com:4567/", impath), lblids]) <NEW_LINE> <DEDENT> for lbl in postsos: <NEW_LINE> <INDENT> postsos[lbl] = sorted(postsos[lbl], key=lambda x: x[1], reverse=True)[:20] <NEW_LINE> <DEDENT> for lbl in subcluster: <NEW_LINE> <INDENT> for sublbl in subcluster[lbl]: <NEW_LINE> <INDENT> l = min(len(subcluster[lbl][sublbl]), 10) <NEW_LINE> subcluster[lbl][sublbl] = subcluster[lbl][sublbl][:l] <NEW_LINE> <DEDENT> <DEDENT> return report_fullpath, postsos, subcluster | run the script which generates the T-SNE for a detection dataset,
return the content of HTML page
Parameters:
:param dataset_name: (str) dataset name
:param cats: (list) categories | 625941bdbaa26c4b54cb102a |
def primitive_root(p): <NEW_LINE> <INDENT> if(p<1 or p!=int(p)): <NEW_LINE> <INDENT> raise ValueError( "n must be positive integer" ) <NEW_LINE> <DEDENT> fact = [] <NEW_LINE> phi = euler_function(p) <NEW_LINE> n = phi <NEW_LINE> i = 2 <NEW_LINE> while(i*i <= n): <NEW_LINE> <INDENT> if(n%i == 0): <NEW_LINE> <INDENT> fact.append(i) <NEW_LINE> while(n%i == 0): <NEW_LINE> <INDENT> n /= i <NEW_LINE> <DEDENT> <DEDENT> i = i + 1 <NEW_LINE> <DEDENT> if(n > 1): <NEW_LINE> <INDENT> fact.append(n) <NEW_LINE> <DEDENT> res = 2 <NEW_LINE> while(res<=p): <NEW_LINE> <INDENT> ok = True <NEW_LINE> size = len(fact) <NEW_LINE> i = 0 <NEW_LINE> while(i<size and ok): <NEW_LINE> <INDENT> r = pow(res, int(phi / fact[i]), p) <NEW_LINE> ok &= (r != 1) <NEW_LINE> i = i+1 <NEW_LINE> <DEDENT> if(ok): <NEW_LINE> <INDENT> return res <NEW_LINE> <DEDENT> res = res + 1 <NEW_LINE> <DEDENT> return -1 | Returns the smallest primitive root of positive integer p
Parameters
----------
p : int
denotes positive integer
return : int
returns integer primitive root if exist otherwise returns -1
| 625941bd96565a6dacc8f5d4 |
def image_summary(tag, tensor, max_images=3, collections=None, name=None): <NEW_LINE> <INDENT> with ops.name_scope(name, "ImageSummary", [tag, tensor]) as scope: <NEW_LINE> <INDENT> val = gen_logging_ops._image_summary( tag=tag, tensor=tensor, max_images=max_images, name=scope) <NEW_LINE> _Collect(val, collections, [ops.GraphKeys.SUMMARIES]) <NEW_LINE> <DEDENT> return val | Outputs a `Summary` protocol buffer with images.
The summary has up to `max_images` summary values containing images. The
images are built from `tensor` which must be 4-D with shape `[batch_size,
height, width, channels]` and where `channels` can be:
* 1: `tensor` is interpreted as Grayscale.
* 3: `tensor` is interpreted as RGB.
* 4: `tensor` is interpreted as RGBA.
The images have the same number of channels as the input tensor. For float
input, the values are normalized one image at a time to fit in the range
`[0, 255]`. `uint8` values are unchanged. The op uses two different
normalization algorithms:
* If the input values are all positive, they are rescaled so the largest one
is 255.
* If any input value is negative, the values are shifted so input value 0.0
is at 127. They are then rescaled so that either the smallest value is 0,
or the largest one is 255.
The `tag` argument is a scalar `Output` of type `string`. It is used to
build the `tag` of the summary values:
* If `max_images` is 1, the summary value tag is '*tag*/image'.
* If `max_images` is greater than 1, the summary value tags are
generated sequentially as '*tag*/image/0', '*tag*/image/1', etc.
Args:
tag: A scalar `Output` of type `string`. Used to build the `tag`
of the summary values.
tensor: A 4-D `uint8` or `float32` `Output` of shape `[batch_size, height,
width, channels]` where `channels` is 1, 3, or 4.
max_images: Max number of batch elements to generate images for.
collections: Optional list of ops.GraphKeys. The collections to add the
summary to. Defaults to [ops.GraphKeys.SUMMARIES]
name: A name for the operation (optional).
Returns:
A scalar `Output` of type `string`. The serialized `Summary` protocol
buffer. | 625941bd3eb6a72ae02ec3dd |
def test_redundant_rename(self): <NEW_LINE> <INDENT> col_count = len(self.frame.take(1)[0]) <NEW_LINE> self.frame.rename_columns({'str': 'str'}) <NEW_LINE> self.assertEqual(col_count, len(self.frame.take(1)[0])) <NEW_LINE> self.assertIn('str', self.frame.column_names) | Test renaming with the same name works | 625941bdbe8e80087fb20b4f |
def test_post_save_turned_on_by_default(self): <NEW_LINE> <INDENT> with patch('entity.signal_handlers.sync_entities') as mock_handler: <NEW_LINE> <INDENT> Account.objects.create() <NEW_LINE> self.assertTrue(mock_handler.called) | Tests that save signals are connected by default. | 625941bdc432627299f04b4c |
def status_update(self): <NEW_LINE> <INDENT> base = BASE_URL + '/status/all' <NEW_LINE> requestURL = base + API_ARG + self._key <NEW_LINE> contents = self._get(requestURL) <NEW_LINE> return contents | Get all translink status updates | 625941bd23849d37ff7b2f98 |
def _getRegion(self, region=None, binning=None): <NEW_LINE> <INDENT> if region is None: region = self.getParam('region') <NEW_LINE> if binning is None: binning = self.getParam('binning') <NEW_LINE> rgn = LIB.rgn_type(region[0], region[2]+region[0]-1, binning[0], region[1], region[3]+region[1]-1, binning[1]) <NEW_LINE> rgn.width = int(region[2] / binning[0]) <NEW_LINE> rgn.height = int(region[3] / binning[1]) <NEW_LINE> return rgn | Create a Region object based on current settings. | 625941bd73bcbd0ca4b2bf7e |
def escape_yaml_specials(string): <NEW_LINE> <INDENT> alpha_string = alphanumeric_lowercase(string) <NEW_LINE> if alpha_string == "yes" or alpha_string == "no": <NEW_LINE> <INDENT> return '"' + string + '"' <NEW_LINE> <DEDENT> elif bool(re.search('^"', string)): <NEW_LINE> <INDENT> return "'" + string + "'" <NEW_LINE> <DEDENT> elif bool( re.search(r"^'|^\? |: |^,|^&|^%|^@|^!|^\||^\*|^#|^- |^[|^]|^{|^}|^>", string) ): <NEW_LINE> <INDENT> return '"' + string + '"' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return string | Surrounds the given string with quotes if it is not conform to YAML syntax. | 625941bd507cdc57c6306bdc |
def _accFunPreCompute(self, f: File, acc: FileAccess): <NEW_LINE> <INDENT> return self._match(f) | Precompute a data structure about the file or access. | 625941bd0c0af96317bb80f0 |
def new_detector(dtype=0): <NEW_LINE> <INDENT> return hkl_module.Detector.factory_new(hkl_module.DetectorType(dtype)) | Create a new HKL-library detector | 625941bd56ac1b37e62640dc |
def status(): <NEW_LINE> <INDENT> ret = {} <NEW_LINE> res = __salt__["cmd.run"]("timedatectl status") <NEW_LINE> pairs = (l.split(": ") for l in res.splitlines()) <NEW_LINE> for k, v in pairs: <NEW_LINE> <INDENT> ret[k.strip().lower().replace(" ", "_")] = v.strip() <NEW_LINE> <DEDENT> return ret | Show current time settings. | 625941bde5267d203edcdba8 |
def genome(corpus, size=5000, nodes=5): <NEW_LINE> <INDENT> return Markov().markov_pitch(corpus, size, nodes) | Generate a genome
default parameters, can override when calling functions | 625941bdd10714528d5ffbe9 |
def get_last_started(self): <NEW_LINE> <INDENT> return self.song("~#laststarted") | Get the datetime the song was last started. | 625941bd0a366e3fb873e71f |
def timestep_weighted_resample(series0, tindex): <NEW_LINE> <INDENT> t0e = np.array(series0.index) <NEW_LINE> dt0 = np.diff(t0e) <NEW_LINE> dt0 = np.hstack((dt0[0], dt0)) <NEW_LINE> t0s = t0e - dt0 <NEW_LINE> v0 = series0.values <NEW_LINE> t1e = np.array(tindex) <NEW_LINE> dt1 = np.diff(t1e) <NEW_LINE> dt1 = np.hstack((dt1[0], dt1)) <NEW_LINE> t1s = t1e - dt1 <NEW_LINE> v1 = [] <NEW_LINE> for t1si, t1ei in zip(t1s, t1e): <NEW_LINE> <INDENT> mask = (t0e > t1si) & (t0s < t1ei) <NEW_LINE> if np.any(mask): <NEW_LINE> <INDENT> ts = t0s[mask] <NEW_LINE> te = t0e[mask] <NEW_LINE> ts[ts < t1si] = t1si <NEW_LINE> te[te > t1ei] = t1ei <NEW_LINE> dt = (te - ts).astype(float) <NEW_LINE> v1.append(np.sum(dt * v0[mask]) / np.sum(dt)) <NEW_LINE> <DEDENT> <DEDENT> series = Series(v1, index=tindex) <NEW_LINE> return series | Resample a timeseries to a new tindex, using an overlapping period
weighted average.
The original series and the new tindex do not have to be equidistant. Also,
the timestep-edges of the new tindex do not have to overlap with the
original series.
It is assumed the series consists of measurements that describe an
intensity at the end of the period for which they apply. Therefore, when
upsampling, the values are uniformly spread over the new timestep (like
bfill).
Compared to the reample methods in Pandas, this method is more accurate for
non-equidistanct series. It is much slower however.
Parameters
----------
series0 : pandas.Series
The original series to be resampled
tindex : pandas.index
The index to which to resample the series
Returns
-------
series : pandas.Series
The resampled series | 625941bdab23a570cc250088 |
def test_maxinconsts_one_cluster_linkage(self): <NEW_LINE> <INDENT> Z = np.asarray([[0, 1, 0.3, 4]], dtype=np.double) <NEW_LINE> R = np.asarray([[0, 0, 0, 0.3]], dtype=np.double) <NEW_LINE> MD = maxinconsts(Z, R) <NEW_LINE> eps = 1e-15 <NEW_LINE> expectedMD = calculate_maximum_inconsistencies(Z, R) <NEW_LINE> self.failUnless(within_tol(MD, expectedMD, eps)) | Tests maxinconsts(Z, R) on linkage with one cluster. | 625941bd26238365f5f0ed72 |
def __repr__(self): <NEW_LINE> <INDENT> return "<Attachment: %s>" % self.id | Obj to Str method. | 625941bd26238365f5f0ed73 |
def setSelected(self, selected): <NEW_LINE> <INDENT> pass | Sets the radio buttons's selected status.
selected : bool - True=selected (on) / False=not selected (off)
*Note, You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- self.radiobutton.setSelected(True) | 625941bd0a366e3fb873e720 |
def __init__(self, websocket: WebsocketType, channel_id: int, handler: 'Callable[[ChannelMessage], Awaitable[ChannelResponse]]' = None, logger: logging.Logger = None): <NEW_LINE> <INDENT> self._websocket = websocket <NEW_LINE> self._handler = handler <NEW_LINE> self._id = channel_id <NEW_LINE> self._logger = logger or logging.getLogger(__name__) <NEW_LINE> self._message_id_counter = 0 <NEW_LINE> self._subscribed_messages = defaultdict(EventItem) <NEW_LINE> self._subscribe_messages_lock = asyncio.Lock() | Creates a link between 2 peers on top of a websocket.
Websockets communication is bi-directional, each message is independent so we can't tell which message is a request and
which is a response. This creates a protocol on top of a websocket to solve this problem.
:param websocket: An established websocket between 2 servers. Channel is responsible for closing it
:param handler: an awaitable callable to handle ChannelMessages. If left as None, we won't handle incoming messages, but we'll still be able to send
:param channel_id: a unique id for that Channel.
:param logger: additional logger | 625941bd7047854f462a1314 |
def filter_by_units(record): <NEW_LINE> <INDENT> units = get_units(record=record) <NEW_LINE> if all(u == 'kWh' or u == 'kWh daily' for u in units): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True | Filter out records with units that are not 'kWh' or 'kWh' daily
True: filter out
False: keep
:param record:
:return: | 625941bd1f5feb6acb0c4a5c |
def extract(self) -> dict: <NEW_LINE> <INDENT> self.pre() <NEW_LINE> startline = -1 <NEW_LINE> endline = -1 <NEW_LINE> rpointer = 0 <NEW_LINE> temp = [] <NEW_LINE> match = self.pattern.finditer(self.target) <NEW_LINE> logger.debug("=======") <NEW_LINE> logger.debug("用正则提取关键字:") <NEW_LINE> for m in match: <NEW_LINE> <INDENT> logger.debug(m) <NEW_LINE> startline = m.start() <NEW_LINE> if startline == endline: <NEW_LINE> <INDENT> rpointer -= 1 <NEW_LINE> temp[rpointer] = temp[rpointer] + m.group() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> temp.append(m.group()) <NEW_LINE> <DEDENT> logger.debug(f"temp:{temp}") <NEW_LINE> endline = m.end() <NEW_LINE> rpointer += 1 <NEW_LINE> <DEDENT> logger.debug("=======") <NEW_LINE> try: <NEW_LINE> <INDENT> res: List[TimeUnit] = [] <NEW_LINE> contextTp = TimePoint() <NEW_LINE> logger.debug(f"基础时间: {self.baseTime}") <NEW_LINE> logger.debug(f"待处理的字段: {temp}") <NEW_LINE> logger.debug(f"待处理字段长度: {rpointer}") <NEW_LINE> for i in range(0, rpointer): <NEW_LINE> <INDENT> res.append(TimeUnit(temp[i], self, contextTp)) <NEW_LINE> contextTp = res[i].tp <NEW_LINE> <DEDENT> logger.debug(f"全部字段处理后的结果: {res}") <NEW_LINE> res = self.filter(res) <NEW_LINE> if self.isTimeDelta and self.timeDelta: <NEW_LINE> <INDENT> return Result.from_timedelta(self.timeDelta) <NEW_LINE> <DEDENT> if len(res) == 1: <NEW_LINE> <INDENT> return Result.from_timestamp(res) <NEW_LINE> <DEDENT> if len(res) == 2: <NEW_LINE> <INDENT> return Result.from_timespan(res) <NEW_LINE> <DEDENT> return Result.from_invalid() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.opt(exception=e).debug("解析时发生错误") <NEW_LINE> return Result.from_exception(e) | 返回 TimeUnit[] 时间表达式类型数组 | 625941bd82261d6c526ab3a4 |
def close_application(self, app): <NEW_LINE> <INDENT> name = self.config[app]['applicationName'] <NEW_LINE> for device in self.devices: <NEW_LINE> <INDENT> subprocess.check_call('adb -s {0} shell am force-stop {1}'.format(device, name), shell=True) | Each application has a name on Android. With this name, a force stop is possible
This method needs an application name as input,. | 625941bdb7558d58953c4e21 |
def datetime_diff(sdate, edate): <NEW_LINE> <INDENT> delta = edate - sdate <NEW_LINE> minutes, seconds = divmod(delta.total_seconds(), 60) <NEW_LINE> return [minutes, seconds] | Returns the difference in minutes and the
remaining in seconds between two dates.
Parameters
----------
sdate : datetime.datetime
Datetime module object corresponding to
the oldest date.
edate : datetime.datetime
Datetime module object corresponding to
the most recent date.
Returns
-------
A list with the following elements:
minutes : float
Time difference between the two dates
in minutes.
seconds : float
The remaining time difference in seconds. | 625941bd6aa9bd52df036cab |
@app.route("/add_student", methods=['POST']) <NEW_LINE> def student_add(): <NEW_LINE> <INDENT> first_name = request.form.get('first_name') <NEW_LINE> last_name = request.form.get('last_name') <NEW_LINE> github = request.form.get('github') <NEW_LINE> hackbright.make_new_student(first_name, last_name, github) <NEW_LINE> html = render_template("succesful_add.html", first_name=first_name, last_name=last_name, github=github) <NEW_LINE> return html | add student | 625941bda8ecb033257d2fd7 |
def t2d(twt, data, td_depth, td_twt, target_depth): <NEW_LINE> <INDENT> f1 = interp1d(td_twt, td_depth, kind='cubic', bounds_error=False, fill_value='extrapolate') <NEW_LINE> depth_timestep = f1(twt) <NEW_LINE> f2 = interp1d(depth_timestep, data, kind='cubic', bounds_error=False, fill_value='extrapolate') <NEW_LINE> data_depth = f2(target_depth) <NEW_LINE> return data_depth | Convenience function for converting a well log from depth to time given
time-depth pairs. This function both converts from time to depth and
resamples the log data to a regular sampling rate in depth. | 625941bd627d3e7fe0d68d56 |
def sort_args(args_or_types,types_or_args): <NEW_LINE> <INDENT> if ( (type(args_or_types[0]) is type) or ( isinstance(args_or_types[0],(list,tuple)) and (type(args_or_types[0][0]) is type) ) ): <NEW_LINE> <INDENT> types = args_or_types <NEW_LINE> args = types_or_args <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> types = types_or_args <NEW_LINE> args = args_or_types <NEW_LINE> <DEDENT> type_arg_tuples = [(type(a),a) for a in args] <NEW_LINE> res=[] <NEW_LINE> for t in types: <NEW_LINE> <INDENT> found = False <NEW_LINE> for type_arg in type_arg_tuples: <NEW_LINE> <INDENT> arg_type,arg_val = type_arg <NEW_LINE> if issubclass(arg_type,t): <NEW_LINE> <INDENT> found=True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if found: <NEW_LINE> <INDENT> res.append(arg_val) <NEW_LINE> type_arg_tuples.remove(type_arg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('One of the required argument is of type '+ t.__name__ + ', but none of the given arguments is of this type.') <NEW_LINE> <DEDENT> <DEDENT> return res | This is a very interesting function.
It is used to support __arbitrary-arguments-ordering__ in TorchFun.
Input:
The function takes a list of types, and a list of arguments.
Returns:
a list of arguments, with the same order as the types-list.
Of course, `sort_args` supports arbitrary-arguments-ordering by itself. | 625941bd8da39b475bd64e79 |
@api.route("/api/ascii-graphs", methods=['GET']) <NEW_LINE> def ascii_graph_index(): <NEW_LINE> <INDENT> return MandelbrotController.invoke(OUTPUT_DIRECTORY) | Download a ascii graph. | 625941bd7b180e01f3dc470c |
def test_empty_node_has_no_root(): <NEW_LINE> <INDENT> node = Node() <NEW_LINE> assert node.value is None <NEW_LINE> assert node.left_child is None <NEW_LINE> assert node.right_child is None | Test that initializing a root has empoty attriubutes. | 625941bd9f2886367277a798 |
def create(self, context: Context, data_dict: dict[str, Any]) -> Any: <NEW_LINE> <INDENT> raise NotImplementedError() | Create new resourct inside datastore.
Called by `datastore_create`.
:param data_dict: See `ckanext.datastore.logic.action.datastore_create`
:returns: The newly created data object
:rtype: dictonary | 625941bd94891a1f4081b9b0 |
def CreateBlob(self, blob_key, content): <NEW_LINE> <INDENT> entity = datastore.Entity(blobstore.BLOB_INFO_KIND, name=blob_key, namespace='') <NEW_LINE> entity['size'] = len(content) <NEW_LINE> datastore.Put(entity) <NEW_LINE> self.storage.StoreBlob(blob_key, StringIO.StringIO(content)) <NEW_LINE> return entity | Create new blob and put in storage and Datastore.
This is useful in testing where you have access to the stub.
Args:
blob_key: String blob-key of new blob.
content: Content of new blob as a string.
Returns:
New Datastore entity without blob meta-data fields. | 625941bd3d592f4c4ed1cf7d |
def register_bonus(self, bonus): <NEW_LINE> <INDENT> self.add(bonus.sprite) <NEW_LINE> self.bonuses.append(bonus) <NEW_LINE> CollisionManager.register(bonus) | Tracks single bonus dropped | 625941bd56b00c62f0f14560 |
def taskstailstopperform(request): <NEW_LINE> <INDENT> if request.method == "POST": <NEW_LINE> <INDENT> ret = {'status': True, 'error': None, } <NEW_LINE> name = request.user.username <NEW_LINE> os.environ["".format(name)] = "false" <NEW_LINE> return HttpResponse(json.dumps(ret)) | 执行 tail_log stop 命令 | 625941bd0c0af96317bb80f1 |
def get_projectors(self): <NEW_LINE> <INDENT> Pup = torch.zeros(self.nconfs, self.nmo, self.nup) <NEW_LINE> Pdown = torch.zeros(self.nconfs, self.nmo, self.ndown) <NEW_LINE> for ic, (cup, cdown) in enumerate( zip(self.configs[0], self.configs[1])): <NEW_LINE> <INDENT> for _id, imo in enumerate(cup): <NEW_LINE> <INDENT> Pup[ic][imo, _id] = 1. <NEW_LINE> <DEDENT> for _id, imo in enumerate(cdown): <NEW_LINE> <INDENT> Pdown[ic][imo, _id] = 1. <NEW_LINE> <DEDENT> <DEDENT> return Pup.unsqueeze(1), Pdown.unsqueeze(1) | Get the projectors of the conf in the CI expansion
Returns:
torch.tensor, torch.tensor : projectors | 625941bd4f6381625f114945 |
def update(self,e,wf): <NEW_LINE> <INDENT> self.calc.start_timing('update') <NEW_LINE> self.e=e <NEW_LINE> self.wf=wf <NEW_LINE> self.f=self.occu.occupy(e) <NEW_LINE> self.calc.start_timing('rho') <NEW_LINE> self.rho = compute_rho(self.wf,self.f) <NEW_LINE> self.calc.stop_timing('rho') <NEW_LINE> if self.SCC: <NEW_LINE> <INDENT> self.dq = self.mulliken() <NEW_LINE> self.es.set_dq(self.dq) <NEW_LINE> <DEDENT> self.calc.stop_timing('update') | Update all essential stuff from given wave functions. | 625941bd293b9510aa2c31a1 |
def test_HVP_RowOnly(self): <NEW_LINE> <INDENT> esccmd.HVP(Point(6, 3)) <NEW_LINE> position = GetCursorPosition() <NEW_LINE> AssertEQ(position.x(), 6) <NEW_LINE> AssertEQ(position.y(), 3) <NEW_LINE> esccmd.HVP(row=2) <NEW_LINE> position = GetCursorPosition() <NEW_LINE> AssertEQ(position.x(), 1) <NEW_LINE> AssertEQ(position.y(), 2) | Default column is 1. | 625941bd7d847024c06be1c1 |
def test_get(self): <NEW_LINE> <INDENT> url = reverse('user', args=[self.admin.id]) <NEW_LINE> r = self.admin_client.get(url) <NEW_LINE> self.assertEqual(r.status_code, 200, "Bad response code (%i)." % r.status_code) | Get a user. | 625941bd4f6381625f114946 |
def GetValue(self,*args): <NEW_LINE> <INDENT> pass | GetValue(self: DataGridViewImageCell,rowIndex: int) -> object
rowIndex: The index of the cell's parent row.
Returns: The value contained in the System.Windows.Forms.DataGridViewCell. | 625941bd67a9b606de4a7dc4 |
def process_raw(self, msg, payload): <NEW_LINE> <INDENT> nats_error = { 'error': '', 'message': 'inbound mastodon message process failed' } <NEW_LINE> nats_success = { 'message': 'OK : inbound mastodon message proceeded' } <NEW_LINE> try: <NEW_LINE> <INDENT> user = User.get(payload['user_id']) <NEW_LINE> identity = UserIdentity.get(user, payload['identity_id']) <NEW_LINE> deliver = UserMastodonDelivery(user, identity) <NEW_LINE> new_message = deliver.process_raw(payload['message_id']) <NEW_LINE> nats_success['message_id'] = str(new_message.message_id) <NEW_LINE> nats_success['discussion_id'] = str(new_message.discussion_id) <NEW_LINE> self.natsConn.publish(msg.reply, json.dumps(nats_success)) <NEW_LINE> <DEDENT> except DuplicateObject: <NEW_LINE> <INDENT> log.info("Message already imported : {}".format(payload)) <NEW_LINE> nats_success['message_id'] = str(payload['message_id']) <NEW_LINE> nats_success['discussion_id'] = "" <NEW_LINE> nats_success['message'] = 'raw message already imported' <NEW_LINE> self.natsConn.publish(msg.reply, json.dumps(nats_success)) <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> exc_info = sys.exc_info() <NEW_LINE> log.error("deliver process failed for raw {}: {}". format(payload, traceback.print_exception(*exc_info))) <NEW_LINE> nats_error['error'] = str(exc.message) <NEW_LINE> self.natsConn.publish(msg.reply, json.dumps(nats_error)) <NEW_LINE> return exc | Process an inbound raw message. | 625941bdbe7bc26dc91cd50d |
def __init__(self, data_root,vocab_root): <NEW_LINE> <INDENT> self.vocab = pickle.load(open(vocab_root,'rb')) <NEW_LINE> self.num_vocab = self.vocab['size'] <NEW_LINE> self.num_samples = [] <NEW_LINE> self.data = [] <NEW_LINE> self.targets = [] <NEW_LINE> for r in data_root: <NEW_LINE> <INDENT> print('载入数据集:', r) <NEW_LINE> with open(r) as file: <NEW_LINE> <INDENT> js = json.load(file) <NEW_LINE> self.num_samples += js['num_samples'] <NEW_LINE> for u in js['users']: <NEW_LINE> <INDENT> for d in js['user_data'][u]['x']: <NEW_LINE> <INDENT> for dd in d: <NEW_LINE> <INDENT> self.data.append([self.word_to_indices(dd)]) <NEW_LINE> <DEDENT> <DEDENT> for t in js['user_data'][u]['y']: <NEW_LINE> <INDENT> for tt in t['target_tokens']: <NEW_LINE> <INDENT> self.targets.append(self.letter_to_index(tt[9])) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> self.data = torch.tensor(self.data) | data_root: 数据集位置
vocab_root:词汇表位置 | 625941bd4f88993c3716bf73 |
def me(): <NEW_LINE> <INDENT> pass | 文档注释说明
:return: | 625941bdd268445f265b4d77 |
def get_all_private_template(self): <NEW_LINE> <INDENT> return self._get("cgi-bin/template/get_all_private_template") | 【模板消息】获取模板列表
详情请参考
https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html#3
:return: 返回的 JSON 数据包 | 625941bdcb5e8a47e48b79b6 |
def next_trash_day(date: str, holidays: list) -> dict: <NEW_LINE> <INDENT> next_regular = next_regular_trash_day(date) <NEW_LINE> weekdays = get_weekdays(next_regular) <NEW_LINE> default_trash_day = {'type': 'default', 'schedule': calendar.day_name[TRASH_DAY]} <NEW_LINE> if holiday.contains_holiday(weekdays): <NEW_LINE> <INDENT> holiday_name = holiday.get_holiday(weekdays) <NEW_LINE> find_holiday = list(filter(lambda holiday_delays: holiday_delays['name'] == holiday_name, holidays)) <NEW_LINE> if len(find_holiday) > 0: <NEW_LINE> <INDENT> trash_day = {'type': 'holiday', 'holiday': holiday_name, 'schedule': find_holiday[0]['routeDelays']} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> trash_day = default_trash_day <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> trash_day = default_trash_day <NEW_LINE> <DEDENT> return trash_day | gets the next trash day taking holidays into consideration
:param date: date to calculate next trash day for
:param holidays: list of holidays
:return: dict containing either the default trash day or route delay information based off holiday. | 625941bd10dbd63aa1bd2aaf |
def __init__(self, name, func, create_scope_now=False, unique_name=None): <NEW_LINE> <INDENT> self._func = func <NEW_LINE> self._stacktrace = traceback.format_stack()[:-2] <NEW_LINE> self._name = name <NEW_LINE> self._unique_name = unique_name <NEW_LINE> if name is None: <NEW_LINE> <INDENT> raise ValueError("name cannot be None.") <NEW_LINE> <DEDENT> if create_scope_now: <NEW_LINE> <INDENT> with variable_scope.variable_op_scope( [], self._unique_name, self._name) as vs: <NEW_LINE> <INDENT> self._var_scope = vs <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._var_scope = None <NEW_LINE> <DEDENT> self._variables_created = False | Creates a template for the given function.
Args:
name: A name for the scope created by this template. The
name will be made unique by appending `_N` to the it (see how
`tf.variable_op_scope` treats the `default_name` for details).
func: The function to apply each time.
create_scope_now: Whether to create the scope at Template construction
time, rather than first call. Defaults to false. Creating the scope at
construction time may be more convenient if the template is to passed
through much lower level code, and you want to be sure of the scope
name without knowing exactly where it will be first called. If set to
True, the scope will be created in the constructor, and all subsequent
times in __call__, leading to a trailing numeral being added to the
names of all created Tensors. If set to False, the scope will be created
at the first call location.
unique_name: When used, it overrides name_ and is not made unique. If a
template of the same scope/unique_name already exists and reuse is
false, an error is raised. Defaults to None.
Raises:
ValueError: if the name is None. | 625941bddc8b845886cb543c |
def testInstantiate(self): <NEW_LINE> <INDENT> self.model = SLS.SeparateLeadProcess( **self.SLSkwargs ) <NEW_LINE> pass | Testing instantiation of SeparateLeadStereo with STFT
| 625941bd4c3428357757c232 |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> if hasattr(self, attr): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if issubclass(HardwareConnectorGetResponse, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result | Returns the model properties as a dict | 625941bd8c0ade5d55d3e8c8 |
def get_long_desc(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return subprocess.check_output(['pandoc', '-f', 'markdown', '-t', 'rst', 'README.mdown']) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print("WARNING: The long readme wasn't converted properly") | Use Pandoc to convert the readme to ReST for the PyPI. | 625941bd9c8ee82313fbb67d |
def ForceAddOneTest(self, test, shell): <NEW_LINE> <INDENT> if shell.shell not in self.shells: <NEW_LINE> <INDENT> self.shells.add(shell.shell) <NEW_LINE> <DEDENT> self.needed_work -= test.duration <NEW_LINE> self.assigned_work += test.duration <NEW_LINE> shell.total_duration -= test.duration <NEW_LINE> self.tests.append(test) | Forcibly adds another test to this peer, disregarding needed_work. | 625941bdfbf16365ca6f60c7 |
def __init__(self, id=None, invalid_application_user_ids=None, invalid_user_uuids=None, status=None, started_at=None, users=None, links=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._id = None <NEW_LINE> self._invalid_application_user_ids = None <NEW_LINE> self._invalid_user_uuids = None <NEW_LINE> self._status = None <NEW_LINE> self._started_at = None <NEW_LINE> self._users = None <NEW_LINE> self._links = None <NEW_LINE> self.discriminator = None <NEW_LINE> if id is not None: <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <DEDENT> if invalid_application_user_ids is not None: <NEW_LINE> <INDENT> self.invalid_application_user_ids = invalid_application_user_ids <NEW_LINE> <DEDENT> if invalid_user_uuids is not None: <NEW_LINE> <INDENT> self.invalid_user_uuids = invalid_user_uuids <NEW_LINE> <DEDENT> if status is not None: <NEW_LINE> <INDENT> self.status = status <NEW_LINE> <DEDENT> if started_at is not None: <NEW_LINE> <INDENT> self.started_at = started_at <NEW_LINE> <DEDENT> if users is not None: <NEW_LINE> <INDENT> self.users = users <NEW_LINE> <DEDENT> if links is not None: <NEW_LINE> <INDENT> self.links = links | BulkUserDeleteDetails - a model defined in OpenAPI | 625941bd23e79379d52ee46f |
def get(lane, name): <NEW_LINE> <INDENT> URL = "https://na.op.gg/champion/" + name + "/statistics/" + lane <NEW_LINE> hdr = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'} <NEW_LINE> req = Request(URL,headers=hdr) <NEW_LINE> html = request.urlopen(req) <NEW_LINE> soup = BeautifulSoup(html, "html.parser") <NEW_LINE> skills = soup.find("table", {"class": "champion-skill-build__table"}) <NEW_LINE> tbody = skills.find("tbody") <NEW_LINE> tr = tbody.find_all("tr")[1] <NEW_LINE> skill_table = [] <NEW_LINE> for td in tr.find_all("td"): <NEW_LINE> <INDENT> if td.text.strip() == 'Q' or td.text.strip() == 'W' or td.text.strip() == 'R' or td.text.strip() == 'E': <NEW_LINE> <INDENT> skill_table.append(td.text.strip()) <NEW_LINE> <DEDENT> <DEDENT> return skill_table | Gets skill order of specific champion and lane | 625941bd01c39578d7e74d44 |
def current_git_hash(): <NEW_LINE> <INDENT> git_file = ".git/refs/heads/master" <NEW_LINE> git_path = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir, git_file)) <NEW_LINE> if not os.path.exists(git_path): <NEW_LINE> <INDENT> git_path = os.getcwd() + "/" + git_file <NEW_LINE> if not os.path.exists(git_path): <NEW_LINE> <INDENT> git_path = os.getcwd() + "/../" + git_file <NEW_LINE> if not os.path.exists(git_path): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> with open(git_path, "r") as git: <NEW_LINE> <INDENT> git_hash = git.read() <NEW_LINE> <DEDENT> return git_hash[0:5] | Return the current git hash | 625941bd283ffb24f3c5580d |
def testLogisticRegression_MatrixData(self): <NEW_LINE> <INDENT> classifier = debug.DebugClassifier( config=run_config.RunConfig(tf_random_seed=1)) <NEW_LINE> input_fn = test_data.iris_input_logistic_fn <NEW_LINE> classifier.fit(input_fn=input_fn, steps=5) <NEW_LINE> scores = classifier.evaluate(input_fn=input_fn, steps=1) <NEW_LINE> self._assertInRange(0.0, 1.0, scores['accuracy']) <NEW_LINE> self.assertIn('loss', scores) | Tests binary classification using matrix data as input. | 625941bd29b78933be1e55b9 |
def find_items_from_list_page(self, sel, item_urls): <NEW_LINE> <INDENT> base_url = '' <NEW_LINE> items_xpath = '//div[@class="category-products"]//a/@href' <NEW_LINE> return self._find_items_from_list_page( sel, base_url, items_xpath, item_urls) | parse items in category page | 625941bd76d4e153a657ea39 |
def get_fingerprint(contents: str) -> str: <NEW_LINE> <INDENT> md5 = hashlib.md5() <NEW_LINE> md5.update(repr(contents).encode()) <NEW_LINE> return md5.hexdigest() | Generate a fingerprint for the contents of a virtual relation.
This fingerprint is used by the server for caching purposes.
:param contents: The full contents of a tsv file
:returns: md5 sum representing the file contents | 625941bd21bff66bcd68485e |
def __contains__(self, value): <NEW_LINE> <INDENT> return (value in self.channel_types or BaseType.__contains__(self, value)) | Check if specific type is allowed | 625941bd0fa83653e4656ec5 |
def all_intents(self): <NEW_LINE> <INDENT> return self.results | Returns all intents found by the intent engine. | 625941bd63d6d428bbe443f8 |
def test_get_series_daily_agg_rain_sum(self): <NEW_LINE> <INDENT> with weewx.manager.open_manager_with_config(self.config_dict, 'wx_binding') as db_manager: <NEW_LINE> <INDENT> start_vec, stop_vec, data_vec = weewx.xtypes.DailySummaries.get_series('rain', TimeSpan(start_ts, stop_ts), db_manager, 'sum', 'day') <NEW_LINE> <DEDENT> self.assertEqual(len(start_vec[0]), 30 + 1) <NEW_LINE> self.assertEqual(len(stop_vec[0]), 30 + 1) <NEW_LINE> self.assertEqual((["%.2f" % d for d in data_vec[0]], data_vec[1], data_vec[2]), (["%.2f" % d for d in Common.expected_daily_rain_sum], 'inch', 'group_rain')) | Test a series of daily aggregated rain totals, run against the daily summaries | 625941bdbd1bec0571d9053f |
def test_violations(self): <NEW_LINE> <INDENT> obj = vv.Validator() <NEW_LINE> q = vv.MongoQuery() <NEW_LINE> q.add_clause(vv.MongoClause(vv.Constraint('foo', 'size>', 2))) <NEW_LINE> q.add_clause(vv.MongoClause(vv.Constraint('bar', '>', 1))) <NEW_LINE> rec = {'foo': [0], 'bar': 0} <NEW_LINE> reasons = obj._get_violations(q, rec) <NEW_LINE> self.failUnlessEqual(len(reasons), 2) <NEW_LINE> for r in reasons: <NEW_LINE> <INDENT> if r.field == 'bar': <NEW_LINE> <INDENT> self.failUnless(r.op == '>' and r.got_value == 0 and r.expected_value == 1) <NEW_LINE> <DEDENT> <DEDENT> q = vv.MongoQuery() <NEW_LINE> q.add_clause(vv.MongoClause(vv.Constraint('foo', 'size>', 2))) <NEW_LINE> q.add_clause(vv.MongoClause(vv.Constraint('bar', '>', 1))) <NEW_LINE> rec = {'foo': [0, 1, 2], 'bar': 9} <NEW_LINE> reasons = obj._get_violations(q, rec) <NEW_LINE> rtuples = [r.as_tuple() for r in reasons] <NEW_LINE> print('\n'.join(map(str, rtuples))) <NEW_LINE> self.failUnlessEqual(len(reasons), 0) | Test error determination in CollectionValidator.why_bad | 625941bd498bea3a759b99b9 |
def shared_directory(files, verbose=False): <NEW_LINE> <INDENT> for i in range(len(files[0])): <NEW_LINE> <INDENT> shared = files[0][:i + 1] <NEW_LINE> if verbose: <NEW_LINE> <INDENT> print('"{}"'.format(shared)) <NEW_LINE> <DEDENT> for f in files: <NEW_LINE> <INDENT> if f[:i + 1] != shared: <NEW_LINE> <INDENT> if verbose: <NEW_LINE> <INDENT> print('Huzzah! "{}" is shared across {} files.'.format( shared[:-1], len(files))) <NEW_LINE> <DEDENT> return shared[:-1] | Find the shared base directory amongst a list of files.
Parameters
----------
files : list
A list of filenames.
Returns
-------
shared : str
A filepath that is the shared across all the files. | 625941bd377c676e912720b2 |
def prod(): <NEW_LINE> <INDENT> env.hosts = ['45.55.169.49'] <NEW_LINE> env.user = "root" <NEW_LINE> env.password = "projetoq1w2e3r4" <NEW_LINE> env.key_filename = 'fabfile/deploy' <NEW_LINE> env.DJANGO_SETTINGS = 'curso_de_extensao.settings.production' | Define o ambiente das operações como sendo o de produção | 625941bd45492302aab5e1c9 |
@app.route("/") <NEW_LINE> def index(): <NEW_LINE> <INDENT> return render_template("home.html") | Return the homepage. | 625941bd44b2445a33931fa8 |
def get_abilities(self): <NEW_LINE> <INDENT> return self.db.strength, self.db.agility, self.db.magic | Simple access method to return ability
scores as a tuple (str,agi,mag) | 625941bd8a43f66fc4b53f71 |
def get_command(self, ctx, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> script = self.scripts[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> colorama.init() <NEW_LINE> self.logger.error( "{c.Fore.RED}{c.Style.BRIGHT}{c.Back.BLACK}" "Did you mean {0}?" "{c.Style.RESET_ALL}" .format( " or ".join( difflib.get_close_matches(name, self.scripts, n=2) ), c=colorama ) ) <NEW_LINE> return None <NEW_LINE> <DEDENT> if script['plugin']: <NEW_LINE> <INDENT> return script['plugin'] | Get the command to be run
>>> mc = MultiCommand()
>>> cmd = mc.get_command(None, 'add')
>>> cmd.name, cmd.help
('add', 'Add...')
>>> mc.get_command(None, 'this command does not exist') | 625941bd60cbc95b062c644d |
def updateModules(modules, pymodule): <NEW_LINE> <INDENT> checkStubPackage(module_package) <NEW_LINE> poamodules = [ skeletonModuleName(m) for m in modules ] <NEW_LINE> real_updateModules(modules, pymodule) <NEW_LINE> real_updateModules(poamodules, pymodule) | Create or update the Python modules corresponding to the IDL
module names | 625941bdb5575c28eb68df07 |
def test_getlist_defaults(self): <NEW_LINE> <INDENT> getter = getconf.ConfigGetter('TESTNS') <NEW_LINE> self.assertEqual([], getter.getlist('test')) <NEW_LINE> self.assertIsNone(getter.getlist('test', None)) | Test fetching the defaults in every possible way | 625941bd07f4c71912b1138b |
def reparent_resource_tags(req, resource, old_id, comment=u''): <NEW_LINE> <INDENT> pass | Move tags, typically when renaming an existing resource. | 625941bd45492302aab5e1ca |
def purple_request_field_int_new(*args): <NEW_LINE> <INDENT> return _purple.purple_request_field_int_new(*args) | purple_request_field_int_new(char id, char text, int default_value) -> PurpleRequestField | 625941bdd53ae8145f87a17d |
def serialize(self, queryset, **options): <NEW_LINE> <INDENT> self.options = options <NEW_LINE> self.stream = options.pop("stream", six.StringIO()) <NEW_LINE> self.selected_fields = options.pop("fields", None) <NEW_LINE> self.use_natural_keys = options.pop("use_natural_keys", False) <NEW_LINE> self.start_serialization() <NEW_LINE> self.first = True <NEW_LINE> for obj in queryset: <NEW_LINE> <INDENT> self.start_object(obj) <NEW_LINE> concrete_model = obj._meta.concrete_model <NEW_LINE> for field in concrete_model._meta.local_fields: <NEW_LINE> <INDENT> if field.serialize: <NEW_LINE> <INDENT> if field.rel is None: <NEW_LINE> <INDENT> if self.selected_fields is None or field.attname in self.selected_fields: <NEW_LINE> <INDENT> self.handle_field(obj, field) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.selected_fields is None or field.attname[:-3] in self.selected_fields: <NEW_LINE> <INDENT> self.handle_fk_field(obj, field) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> for field in concrete_model._meta.many_to_many: <NEW_LINE> <INDENT> if field.serialize: <NEW_LINE> <INDENT> if self.selected_fields is None or field.attname in self.selected_fields: <NEW_LINE> <INDENT> self.handle_m2m_field(obj, field) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.end_object(obj) <NEW_LINE> if self.first: <NEW_LINE> <INDENT> self.first = False <NEW_LINE> <DEDENT> <DEDENT> self.end_serialization() <NEW_LINE> return self.getvalue() | Serialize a queryset. | 625941bd07d97122c417878f |
def call_base_info(power_wall): <NEW_LINE> <INDENT> gateway_din = None <NEW_LINE> with contextlib.suppress((AssertionError, PowerwallError)): <NEW_LINE> <INDENT> gateway_din = power_wall.get_gateway_din().upper() <NEW_LINE> <DEDENT> return { POWERWALL_API_SITE_INFO: power_wall.get_site_info(), POWERWALL_API_STATUS: power_wall.get_status(), POWERWALL_API_DEVICE_TYPE: power_wall.get_device_type(), POWERWALL_API_SERIAL_NUMBERS: sorted(power_wall.get_serial_numbers()), POWERWALL_API_GATEWAY_DIN: gateway_din, } | Wrap powerwall properties to be a callable. | 625941bdd8ef3951e3243446 |
def plot_radar(self,utc,datadir,outdir=False,Nlim=False,Elim=False, Slim=False,Wlim=False,ncdir=False,nct=False, ncf=False,dom=1,composite=False,locations=False, fig=False,ax=False,cb=True,compthresh=False, drawcounties=False): <NEW_LINE> <INDENT> if not Nlim and isinstance(ncdir,str): <NEW_LINE> <INDENT> self.W = self.get_netcdf(ncdir,ncf=ncf,nct=nct,dom=dom) <NEW_LINE> Nlim, Elim, Slim, Wlim = self.W.get_limits() <NEW_LINE> <DEDENT> if composite: <NEW_LINE> <INDENT> radars = {} <NEW_LINE> for n,t in enumerate(utc): <NEW_LINE> <INDENT> radars[n] = Radar(t,datadir) <NEW_LINE> if compthresh: <NEW_LINE> <INDENT> dBZ = radars[n].get_dBZ(radars[n].data) <NEW_LINE> radars[n].data[dBZ<compthresh] = 0 <NEW_LINE> <DEDENT> if n == 0: <NEW_LINE> <INDENT> stack = radars[0].data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stack = N.dstack((stack,radars[n].data)) <NEW_LINE> <DEDENT> <DEDENT> max_pixel = N.max(stack,axis=2) <NEW_LINE> R = Radar(utc[-1],datadir) <NEW_LINE> R.data = max_pixel <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> R = Radar(utc,datadir) <NEW_LINE> <DEDENT> R.plot_radar(outdir,Nlim=Nlim,Elim=Elim,Slim=Slim,Wlim=Wlim, fig=fig,ax=ax,cb=cb,drawcounties=drawcounties) | Plot verification radar.
composite allows plotting max reflectivity for a number of times
over a given domain.
This can show the evolution of a system.
Need to rewrite so plotting is done in birdseye. | 625941bd167d2b6e31218aa0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.