code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def __init__( self, azure=None, nfs=None, s3=None, name=None, protocol=None, space=None, status=None, target_id=None, ): <NEW_LINE> <INDENT> if azure is not None: <NEW_LINE> <INDENT> self.azure = azure <NEW_LINE> <DEDENT> if nfs is not None: <NEW_LINE> <INDENT> self.nfs = nfs <NEW_LINE> <DEDENT> if s3 is not None: <NEW...
Keyword args: azure (OffloadAzure): The Microsoft Azure Blob storage settings. nfs (OffloadNfs): The NFS storage settings. s3 (OffloadS3): The Amazon S3 storage settings. name (str): A user-specified name. The name must be locally unique and can be changed. protocol (str): The type of offload. Valid...
625941d9b5575c28eb68e28c
def set_redirect_instance_id(self, instance_id): <NEW_LINE> <INDENT> self._set_container_cookies({ JBoxCookies.COOKIE_INSTANCEID: instance_id })
Sets a cookie COOKIE_INSTANCEID (instance_id) to mark a destination for the router to redirect the next request to. This is used to implement stickyness for dedicated sessions. But this can also be used to route requests for load balancing. :param instance_id: Host to redirect to (typically an internal IP address inacc...
625941d94428ac0f6e5baa7e
def content_processing(content_dict): <NEW_LINE> <INDENT> print_break("Performing preprocessing to content:") <NEW_LINE> df = pd.DataFrame(data=content_dict) <NEW_LINE> df["content"] = df.loc[:,"content"].apply(decode_utf) <NEW_LINE> df["content_clean"] = df.loc[:,"content"].apply(text_preprocess) <NEW_LINE> print("Pre...
Perform some basic preprocessing on conent from GitHub.
625941d994891a1f4081bd34
def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=1000, subtract_mean=True): <NEW_LINE> <INDENT> cifar10_dir = 'cse468/datasets/cifar-10-batches-py' <NEW_LINE> X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir) <NEW_LINE> mask = list(range(num_training, num_training + num_validation)) <NE...
Load the CIFAR-10 dataset from disk and perform preprocessing to prepare it for classifiers. These are the same steps as we used for the SVM, but condensed to a single function.
625941d92c8b7c6e89b35a4a
def getRow(self, rowIndex): <NEW_LINE> <INDENT> rows = [[1 for _ in range(rowIndex + 1)] for _ in range(2)] <NEW_LINE> for i in range(1, rowIndex + 1): <NEW_LINE> <INDENT> index = i % 2 <NEW_LINE> for j in range(1, i): <NEW_LINE> <INDENT> rows[index][j] = rows[index^1][j-1] + rows[index^1][j] <NEW_LINE> <DEDENT> <DEDEN...
:type rowIndex: int :rtype: List[int]
625941d98e71fb1e9831da33
def get_formatted_value(self, input_value): <NEW_LINE> <INDENT> return self.formatter.vformat(input_value, None, self)
Run token substitution on the input against context. If input_value is a formattable string or SpecialTagDirective, will return the formatted result. If input_value is an iterable, will iterate input recursively and format all formattable objects it finds. Mappings will format both key and value. If input_value is n...
625941d9b57a9660fec33b11
def lineno(): <NEW_LINE> <INDENT> return str(' - IamUserParser- line number: '+str(inspect.currentframe().f_back.f_lineno))
Returns the current line number in our program.
625941d9498bea3a759b9d39
def fromxml(tree): <NEW_LINE> <INDENT> f = Firecrest() <NEW_LINE> f.set_elements(tree) <NEW_LINE> return f
Initialize a Firecrest object from an element tree node
625941d97d847024c06be549
def json_body(self): <NEW_LINE> <INDENT> json_body = [ { "measurement": "ping_rtt", "tags": { "host": self.target, "region": self.region}, "time": str(datetime.datetime.today()), "fields": { "transmitted": self.transmitted, "received": self.received, "loss": self.loss, "min": self.min, "avg": self.avg, "max": self.max}...
build json body for API call
625941d992d797404e304415
def __init__(self, name, age): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.age = age <NEW_LINE> self.recommended_food = 'kibble'
Initialize name and age attributes
625941d94f6381625f114cc6
def convex_hull_phases(phases, axes='CEV'): <NEW_LINE> <INDENT> A = [] <NEW_LINE> for phase_dict in phases: <NEW_LINE> <INDENT> if axes == 'CE': <NEW_LINE> <INDENT> A.append(phase_dict['phase_coord'][1:] + [phase_dict['energy_pa']]) <NEW_LINE> <DEDENT> elif axes == 'CV': <NEW_LINE> <INDENT> A.append(phase_dict['phase_c...
Calculate the phases that lie on the composition-volume-pressure convex hull of a given list of phases. :param phases: dictionary of thermodynamic data to be used to construct the convex hull e.g., {'Al2Si_13125': {'icsd_id': 1654, 'comp_str': 'Al2Si', 'energy_pa': -1.5, ...}, ...} :type phases: dict(st...
625941d9e8904600ed9f21ba
def main(self): <NEW_LINE> <INDENT> args = self._parse_command_line() <NEW_LINE> if args.show_progress: <NEW_LINE> <INDENT> self.show_progress = True <NEW_LINE> <DEDENT> self._get_config(args.config) <NEW_LINE> if args.show_parameters: <NEW_LINE> <INDENT> self._show_parameters() <NEW_LINE> return <NEW_LINE> <DEDENT> se...
Main entry point
625941d9bde94217f3683079
def find_combination(choices, total): <NEW_LINE> <INDENT> length = len(choices) <NEW_LINE> res = np.zeros(length, int) <NEW_LINE> bestres = [] <NEW_LINE> for i in range( 2**length): <NEW_LINE> <INDENT> binary = bin(i)[2:] <NEW_LINE> res = np.array(list(binary), dtype = int) <NEW_LINE> res = np.append(np.zeros(length-le...
choices: a non-empty list of ints total: a positive int Returns result, a numpy.array of length len(choices) such that * each element of result is 0 or 1 * sum(result*choices) == total * sum(result) is as small as possible In case of ties, returns any result that works. If there is no result that gives th...
625941d9d4950a0f3b08c5d7
def test_reg_cust_sms_with_name_only(self): <NEW_LINE> <INDENT> message = IncomingSMS('94770000000', util.current_time(), 'reg cust n:janaka') <NEW_LINE> parsed = message_parser.parse(message) <NEW_LINE> self.assertEqual(parsed.type, query.CUST_REGISTER) <NEW_LINE> self.assertEqual(parsed.params['phone'], '94770000000'...
test customer registration query with name only
625941d9ec188e330fd5aa26
def von_mises_log_likelihood_tf(y_true, mu_pred, kappa_pred, input_type='biternion'): <NEW_LINE> <INDENT> if input_type == 'degree': <NEW_LINE> <INDENT> scaler = 0.0174533 <NEW_LINE> cosin_dist = tf.cos(scaler * (y_true - mu_pred)) <NEW_LINE> <DEDENT> elif input_type == 'radian': <NEW_LINE> <INDENT> cosin_dist = tf.cos...
Compute log-likelihood given data samples and predicted Von-Mises model parameters :param y_true: true values of an angle in biternion (cos, sin) representation :param mu_pred: predicted mean values of an angle in biternion (cos, sin) representation :param kappa_pred: predicted kappa (inverse variance) values of an ang...
625941d9d7e4931a7ee9e1a8
def make_callback(name, *args): <NEW_LINE> <INDENT> prefix = "T" + name + CALLBACK_ARGUMENT_SEPARATOR <NEW_LINE> res = prefix + CALLBACK_ARGUMENT_SEPARATOR.join(args) <NEW_LINE> key = prefix + CALLBACK_ARGUMENT_SEPARATOR + hashlib.md5(res.encode("utf-8")).hexdigest() <NEW_LINE> CALLBACK_DATA_STORE[key] = res <NEW_LINE>...
Keep data between Telegram API calls by generating a key and placing the data in CALLBACK_DATA_STORE this is useful for answering inline queries, since only 64 byte can be cached on telegram side (which is enough for the generated key)
625941d9cad5886f8bd27263
def reset_focus(self) -> None: <NEW_LINE> <INDENT> self.focused = False
Resets the focus of the component.
625941d957b8e32f52483727
def add_notification(self, timestamp, subject, text): <NEW_LINE> <INDENT> self.notifications.append((timestamp, subject, text))
Store a new notification to send at the first opportunity (i.e., at the first request for db notifications). timestamp (datetime): the time of the notification. subject (string): subject of the notification. text (string): body of the notification.
625941d9a8370b7717052b29
def get_data(run_id, output_path, holdout_num=0, param_set=0): <NEW_LINE> <INDENT> data = hlp.model_load(run_id, 'prepped', output_path=output_path) <NEW_LINE> data_transform = hlp.model_load(run_id, 'parameters', param_set=None, output_path=output_path)[ 'data_transform'].iat[0] <NEW_LINE> ko_col = ['ko_{}'.format(hol...
Returns some useful data columns, stage1, st, and gpr. The modeling columns are in NORMAL space - ie backtransformed out of any log/logit space if the model ran in that space. Data and variance are provided in both transformed and non-transformed space.
625941d94f88993c3716c2f0
def extend(self, tps): <NEW_LINE> <INDENT> assert(self.cell_order == tps.cell_order) <NEW_LINE> self.points = np.vstack((self.points, tps.points)) <NEW_LINE> self.sign = np.hstack((self.sign, tps.sign))
Merges another TopologicalPointSet into this TopologicalPointSet :param tps: another TopologicalPointSet
625941d9711fe17d825425f1
def kmer_seq_to_filters(kmers): <NEW_LINE> <INDENT> return np.concatenate([dna_string_to_array(s) for s in kmers])
Transform kmer sequence data to an np array used in the first filtering stage of the convolutional neural net.
625941d94c3428357757c5b2
def count_lines(f): <NEW_LINE> <INDENT> lf = "\n".encode() <NEW_LINE> chunk_size = 1 << 20 <NEW_LINE> lines = 0 <NEW_LINE> chunk = f.read(chunk_size) <NEW_LINE> while chunk: <NEW_LINE> <INDENT> lines += chunk.count(lf) <NEW_LINE> chunk = f.read(chunk_size) <NEW_LINE> <DEDENT> return lines
Count lines in a byte iterable
625941d94a966d76dd55129c
def close(self): <NEW_LINE> <INDENT> if not hasattr(self, 'tiffs'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for tif in self._tiffs.values(): <NEW_LINE> <INDENT> if tif._fd: <NEW_LINE> <INDENT> tif._fd.close() <NEW_LINE> tif._fd = None
Close open file handle(s).
625941d991af0d3eaac9bca6
def __init__(self, base, side, theta): <NEW_LINE> <INDENT> self.base = base <NEW_LINE> self.side = side <NEW_LINE> self.theta = theta
(Parallelogram, int, int, int) -> NoneType Create a new parallelogram with base, side and theta. REQ: base >= 0 REQ: side >= 0 REQ: theta >= 0, <= 360
625941d91d351010ab855da6
def AND(x1, x2): <NEW_LINE> <INDENT> x = np.array([x1, x2]) <NEW_LINE> w = np.array([0.5, 0.5]) <NEW_LINE> b = -0.7 <NEW_LINE> tmp = np.sum(w * x) + b <NEW_LINE> if tmp < 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 1
Calculate AND.
625941d9b7558d58953c519b
def backup_file(f): <NEW_LINE> <INDENT> if os.path.exists(f): <NEW_LINE> <INDENT> dirname = os.path.dirname(f) <NEW_LINE> basename = os.path.basename(f) <NEW_LINE> count = 1 <NEW_LINE> rn_to = os.path.join( dirname, '#' + basename + '.{0}#'.format(count)) <NEW_LINE> while os.path.exists(rn_to): <NEW_LINE> <INDENT> coun...
Back up a file, old_file will be renamed to #old_file.n#, where n is a number incremented each time a backup takes place
625941d921bff66bcd684bdc
def smtp_serialize(self, filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> smtp_entity_dump = {} <NEW_LINE> smtp_entity = self.__smtp_entity.get_all() <NEW_LINE> for entity in smtp_entity: <NEW_LINE> <INDENT> smtp_entity_item = copy.copy(smtp_entity.get(entity)) <NEW_LINE> smtp_entity_dump[entity] = {} <NEW_LINE>...
serialize smtp object save it as pickle object
625941d9167d2b6e31218e20
def select_all(self): <NEW_LINE> <INDENT> for i in range(0, self.rowCount()): <NEW_LINE> <INDENT> selected_checkbox = QTableWidgetItem() <NEW_LINE> selected_checkbox.setCheckState(True) <NEW_LINE> self.setItem(i, 0, selected_checkbox) <NEW_LINE> <DEDENT> return True
Selects every checkboxes return True if the operation is successful
625941d98da39b475bd65201
def upload_from_stream(self, filename, data, properties = {}): <NEW_LINE> <INDENT> logger.debug("-> uploading from stream: " + filename) <NEW_LINE> key = self._basename + filename <NEW_LINE> try: <NEW_LINE> <INDENT> if len(properties) > 0: <NEW_LINE> <INDENT> self._s3.put_object(Bucket=self._bucket, Key=key, Body=data,...
Upload from a stream Puts the stream information in data to an object at basename/filename. Data can be the output of json.dumps() or similar.
625941d926238365f5f0f0fc
def vdst_factory(): <NEW_LINE> <INDENT> vdst = VolumeDescriptorSetTerminator() <NEW_LINE> vdst.new() <NEW_LINE> return vdst
An internal function to create a new Volume Descriptor Set Terminator. Parameters: None. Returns: The newly created Volume Descriptor Set Terminator.
625941d94e4d5625662d4660
def attributes(self, *args): <NEW_LINE> <INDENT> return _gnsdk.GnPlaylistCollection_attributes(self, *args)
attributes(GnPlaylistCollection self, GnUser user, GnPlaylistIdentifier mediaIdentifier) -> GnPlaylistAttributes attributes(GnPlaylistCollection self, GnUser user, gnsdk_cstr_t mediaIdentifier, gnsdk_cstr_t joinedCollectionName) -> GnPlaylistAttributes
625941d94e696a04525c96d7
def is_completed(self, sid): <NEW_LINE> <INDENT> return self._connection.get(api_path_by_module(self, sid))
Check if the submission with the given sid is completed. Required: sid : Submission ID. (string) Returns True/False. Throws a Client exception if the submission does not exist.
625941d9be383301e01b570e
def __init__(self, architecture, input_var=None, learning_rate=None, equal_weights=False, noise=DEF_NOISE, batch_size=DEF_BATCH, data_format=DEF_DATA_FORMAT, cost_function=DEF_COST_FUNC, training_scope=None, **kwargs): <NEW_LINE> <INDENT> self.batch_size = batch_size <NEW_LINE> self.learning_rate=learning_rate <NEW_LIN...
Initialize and construct the Auto-encoder architecture. :param architecture: The architectue as returned from `nn_utils.nn_parse_architecture`. :param input_var: If provided, this will be the data used for training. :param learning_rate: The learning rate to be used with the AdamOptimizer. :param equal_weights: Whether...
625941d9925a0f43d254a104
def get_lacp(self): <NEW_LINE> <INDENT> self.logger.debug('Entering get_lacp_trunk_detail method') <NEW_LINE> lacp_trunk_detail = self.clideploy(['show lacp trunk detail']) <NEW_LINE> self.logger.info(lacp_trunk_detail) <NEW_LINE> self.logger.debug('Exiting get_lacp_info method') <NEW_LINE> return lacp_trunk_detail
show lacp trunk detail
625941d9507cdc57c6306f6b
def const_return(func): <NEW_LINE> <INDENT> result = _undef <NEW_LINE> def ret_call(*args, **kwargs): <NEW_LINE> <INDENT> nonlocal result <NEW_LINE> if result is _undef: <NEW_LINE> <INDENT> result = func(*args, **kwargs) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> return ret_call
>>> from Redy.Magic.Classic import const_return >>> @const_return >>> def f(x): >>> return x >>> r1 = f(1) >>> assert r1 is 1 and r1 is f(2)
625941d9fbf16365ca6f6452
def mpl_weight2qt(weight): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> weight = weights_mpl2qt[weight] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> weight = float(weight) / 10 <NEW_LINE> <DEDENT> except (ValueError, TypeError): <NEW_LINE> <INDENT> weight = QtGui.QFont.Normal <NEW_L...
Convert a weight from matplotlib definition to a Qt weight Parameters ---------- weight: int or string Either an integer between 1 and 1000 or a string out of :attr:`weights_mpl2qt` Returns ------- int One type of the PyQt5.QtGui.QFont.Weight
625941d94f88993c3716c2f1
def set_output_tnsrs(self): <NEW_LINE> <INDENT> if self.mode in ['train_noval', 'train_with_val']: <NEW_LINE> <INDENT> self.y_hat_train_tnsr = [self.loss_op, self.metric_op, self.optim_op] <NEW_LINE> <DEDENT> if self.mode == 'train_with_val': <NEW_LINE> <INDENT> self.y_hat_val_tnsr = [self.loss_op, self.metric_op] <NEW...
Initialize output tensors
625941d9d53ae8145f87a4f7
def fixDiscontinuityPolys(verts, colors): <NEW_LINE> <INDENT> length = np.abs(verts[:,3,1] - verts[:,0,1]) <NEW_LINE> polysWithDiscont = verts[length>180] <NEW_LINE> print(polysWithDiscont) <NEW_LINE> return verts, colors
Splits polygons which cross the 180deg discontinuity into two parts. NOTE: The vertices must lie on a regular lat/lon grid! Currently not used, see comment on _drawPolygons. :param verts: (n,4,2) in degrees (:,:,0 = lat) :param colors: (n,3)
625941d9e76e3b2f99f3aa93
@default_parameter_change('0.17', dict(baz='monde')) <NEW_LINE> @default_parameter_change('0.16', dict(bar='bonjour')) <NEW_LINE> def foo_two_params_redux(bar='hello', baz='world'): <NEW_LINE> <INDENT> return bar + ' ' + baz
Joins two strings with a space between them. **This function has a no deprecation decorator.** Parameters ---------- bar : str The first word to join. baz : str The second word to join.
625941d98c3a873295158648
def magToMass(magnitude,set='mann2019',mag_e = 0,nsamples=100): <NEW_LINE> <INDENT> pass
:Purpose: Computes the mass based on a given absolute magnitude and magnitude/mass relation TO BE COMPLETED :Required Inputs: :param mag: magnitude to use in computation; should be in the filter defined by the relation :Optional Inputs: :param set='douglas2014': reference for parameters to use f...
625941d956b00c62f0f148e6
def count_objects(filters: List[Dict[str, Any]], compartment_id: str = None, configuration: Configuration = None, secrets: Secrets = None) -> int: <NEW_LINE> <INDENT> compartment_id = compartment_id or from_file().get('compartment') <NEW_LINE> if compartment_id is None: <NEW_LINE> <INDENT> raise ActivityFailed('We have...
Return the number of objects in accordance with the given filters. Please refer to: https://oracle-cloud-infrastructure-python-sdk.readthedocs.io/en/latest/api/core/models/oci.core.models.InstancePool.html#oci.core.models.Instance for details on the available filters under the 'parameters' section.
625941d945492302aab5e551
def format(self, msg, exporter_context): <NEW_LINE> <INDENT> name, _, content, re_id, _, _, _ = common.extract_message_data(msg) <NEW_LINE> msg_dump_str = '[{}-{:02d}-{:02d} {:02d}:{:02d}] ID={} {}{}: {}'.format( msg.date.year, msg.date.month, msg.date.day, msg.date.hour, msg.date.minute, msg.id, "RE_ID=%s " % re_id if...
Formatter method. Takes raw msg and converts it to a *one-line* string. :param msg: Raw message object :class:`telethon.tl.types.Message` and derivatives. https://core.telegram.org/type/Message :returns: *one-line* string containing one message data.
625941d931939e2706e4d0f2
def itkMaskNegatedImageFilterICF2IUS2ICF2_cast(*args): <NEW_LINE> <INDENT> return _itkMaskNegatedImageFilterPython.itkMaskNegatedImageFilterICF2IUS2ICF2_cast(*args)
itkMaskNegatedImageFilterICF2IUS2ICF2_cast(itkLightObject obj) -> itkMaskNegatedImageFilterICF2IUS2ICF2
625941d967a9b606de4a8143
def test_zeros(): <NEW_LINE> <INDENT> mod = tvm.IRModule() <NEW_LINE> shape = (10, 10) <NEW_LINE> dtype = 'float32' <NEW_LINE> t = relay.TensorType(shape, dtype) <NEW_LINE> x = relay.var("x", t) <NEW_LINE> y = relay.Function([x], x + relay.zeros(shape, dtype)) <NEW_LINE> mod["main"] = y <NEW_LINE> mod = transform.LazyG...
Simple test using "zeros" op
625941d966656f66f7cbc437
def linear_deform(template, displacement, out=None): <NEW_LINE> <INDENT> image_pts = template.space.points() <NEW_LINE> for i, vi in enumerate(displacement): <NEW_LINE> <INDENT> image_pts[:, i] += vi.asarray().ravel() <NEW_LINE> <DEDENT> values = template.interpolation(image_pts.T, out=out, bounds_check=False) <NEW_LIN...
Linearized deformation of a template with a displacement field. The function maps a given template ``I`` and a given displacement field ``v`` to the new function ``x --> I(x + v(x))``. Parameters ---------- template : `DiscreteLpElement` Template to be deformed by a displacement field. displacement : element of p...
625941d9ab23a570cc25040f
def setStorageForType(portal_type, id): <NEW_LINE> <INDENT> pass
Set the storage to be used for objects of 'portal_type' If ID is None, set to default storage Raises KeyError if there is no storage registered with the provided ID
625941d96fece00bbac2d9cc
def export_from_export_domain(self, export_name, timeout=300): <NEW_LINE> <INDENT> end_time = time.time() + timeout <NEW_LINE> storage_domains = self.connection.storagedomains.get(export_name) <NEW_LINE> logging.info('Export VM %s' % self.name) <NEW_LINE> self.instance.export(types.Action(storage_domain=storage_domains...
Export a VM from storage domain to export domain. :param export_name: Export domain name.
625941d921a7993f00bc7f7f
def load_mongo_col(col: Collection) -> dict: <NEW_LINE> <INDENT> return { doc['_id']: doc for doc in col.find({}) }
Load the pymongo collection to a dictionary. In the dictionary. The key will be the '_id' and in each value which is a dictionary there will also be a key '_id' so that the structure will be the same as the filesystem collection. Parameters ---------- col : Collection The mongodb collection. Returns ------- dct ...
625941d90c0af96317bb8473
def report_online_inference_sdk_error(sdk_error): <NEW_LINE> <INDENT> logging.exception(sdk_error.private_failure_message())
Report SDK error occurred during batch inference or online inference. Write private error message along with stack trace to the public stream (stdout). :param sdk_error: BaseSdkError instance
625941d9a219f33f34628bf2
def get_tags_with_http_info(self, **kwargs): <NEW_LINE> <INDENT> all_params = ['name', 'type', 'page', 'size', 'sort'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_L...
Tags # noqa: E501 Returns all tags. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_tags_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool :param str name: name :param str type: t...
625941d9ff9c53063f47c47e
def euclidian_recursion(a, b): <NEW_LINE> <INDENT> if b == 0: <NEW_LINE> <INDENT> return a <NEW_LINE> <DEDENT> return euclidian_recursion(b, a % b)
Алгоритм Евклида поиска наибольшего общего делителя рекурсией
625941d9956e5f7376d710f7
def trip_duration(city_file, time_period): <NEW_LINE> <INDENT> city_file = get_city() <NEW_LINE> time_period = get_time_period() <NEW_LINE> '''DicReader reads the file to the function and maps the first row as the fieldname, similar to Excel/csv''' <NEW_LINE> with open(city_file,'r') as table: <NEW_LINE> <INDENT> j = c...
TODO: fill out docstring with description, arguments, and return values. Question: What is the total trip duration and average trip duration?
625941d997e22403b379d226
def enumerate(s, start=0): <NEW_LINE> <INDENT> return zip([start, (start + (len(s) - 2))], s)
Returns a list of lists, where the i-th list contains i+start and the i-th element of the sequence. >>> enumerate([6, 1, 'a']) [[0, 6], [1, 1], [2, 'a']] >>> enumerate('five', 5) [[5, 'f'], [6, 'i'], [7, 'v'], [8, 'e']]
625941d96e29344779a6289c
def quatrieme(self, isbn): <NEW_LINE> <INDENT> return self.fetch_back_cover(isbn)
;
625941d95fdd1c0f98dc04bf
def _createSessionObject(self, request): <NEW_LINE> <INDENT> c_key = ndb.Key(urlsafe=request.websafeConferenceKey) <NEW_LINE> conference = c_key.get() <NEW_LINE> if not conference: <NEW_LINE> <INDENT> raise endpoints.NotFoundException( 'No conference found with key: %s' % request.websafeConferenceKey) <NEW_LINE> <DEDEN...
Create or update Session object.
625941d9566aa707497f47f1
def get_setpoint_for_current_mode(self): <NEW_LINE> <INDENT> cache = {} <NEW_LINE> if self._op_mode.is_manual: <NEW_LINE> <INDENT> return self._setpoints_temp.get(self._op_mode.current_mode, {}).get( MODE, -1 ) <NEW_LINE> <DEDENT> if not self._schedule_found: <NEW_LINE> <INDENT> return ACTIVE_PROGRAM <NEW_LINE> <DEDENT...
Get setpoints for mode.
625941d926238365f5f0f0fd
def insert_mass(self, table_name, data, ignore=False): <NEW_LINE> <INDENT> fields = [] <NEW_LINE> to_insert = [] <NEW_LINE> for row in data: <NEW_LINE> <INDENT> if fields == []: <NEW_LINE> <INDENT> fields = map((lambda s: "`" + str(s) + "`"), row.keys()) <NEW_LINE> <DEDENT> values = map(self.quote, row.values()) <NEW_L...
Insert data into table with many VALUES sections :param table_name: target table :param data: list of dicts with data {col_name: value} :param ignore: Its INSERT IGNORE request or no? :return:
625941d916aa5153ce362703
def GetAmount(self,StartDate,EndDate): <NEW_LINE> <INDENT> trading_dates = GetTradeDates(StartDate,EndDate) <NEW_LINE> data = pd.concat([pd.read_pickle(self.path+date+".pkl") for date in trading_dates],axis=0) <NEW_LINE> data.sort_values(["TRADE_DT","S_INFO_WINDCODE"],inplace=True) <NEW_LINE> final = data.pivot(index =...
获取成交金额,千元 StartDate : [str] 开始日期,如 "20100101" EndDate : [str] 截止日期,如 "20100131"
625941d92eb69b55b151cb3d
def from_vector_to_diagonal_matrix(vector, num_diag=0): <NEW_LINE> <INDENT> num_columns = gs.shape(vector)[-1] <NEW_LINE> identity = gs.eye(num_columns) <NEW_LINE> identity = gs.cast(identity, vector.dtype) <NEW_LINE> diagonals = gs.einsum("...i,ij->...ij", vector, identity) <NEW_LINE> diagonals = gs.to_ndarray(diagona...
Create diagonal matrices from rows of a matrix. Parameters ---------- vector : array-like, shape=[m, n] num_diag : int number of diagonal in result matrix. If 0, the result matrix is a diagonal matrix; if positive, the result matrix has an upper-right non-zero diagonal; if negative, the result matrix has a...
625941d90383005118ecf86d
def create_folder(self, folder_name='Unnamed Folder', parent_folder_id=None): <NEW_LINE> <INDENT> if not self.drive_service: <NEW_LINE> <INDENT> raise ConnectionError("Drive service has not been turned on or not yet authenticated. " "Please run the `authenticate()` function before attempting to manage files.") <NEW_LI...
Creates a folder of the name passed in. If no parent folder ID is given, the folder will appear at the root of your Google Drive space. :param folder_name: Name of the folder you want to create. If none is given, it will be called "Unnamed Folder" :param parent_folder_id: Optional parent folder ID. :return: Folder JS...
625941d9656771135c3ebafd
def deserialize_numpy(self, str, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> end = 0 <NEW_LINE> _x = self <NEW_LINE> start = end <NEW_LINE> end += 20 <NEW_LINE> (_x.steering_angle, _x.steering_angle_velocity, _x.speed, _x.acceleration, _x.jerk,) = _get_struct_5f().unpack(str[start:end]) <NEW_LINE> return self ...
unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module
625941d907f4c71912b1170f
def has_page_change_permission(request): <NEW_LINE> <INDENT> from cms.utils.helpers import current_site <NEW_LINE> user = request.user <NEW_LINE> site = current_site(request) <NEW_LINE> global_change_perm = GlobalPagePermission.objects.user_has_change_permission( user, site).exists() <NEW_LINE> return user.is_superuser...
Return true if the current user has permission to change this page. To be granted this permission, you need the cms.change_page permission. In addition, if CMS_PERMISSION is enabled you also need to either have global can_change permission or just on this page.
625941d95510c4643540f66b
def dump(self): <NEW_LINE> <INDENT> values_binary = b"".join([value.dump() for value in self.values]) <NEW_LINE> return bytes(values_binary)
dump binary representation of the contained values
625941d9956e5f7376d710f8
def iter_read_objects(ioclass, filenames, directory=None, target=None, return_path=False, return_ioobj=False, return_reader=False, clean=False, readall=False, cascade=True, lazy=False): <NEW_LINE> <INDENT> for obj_reader, path, ioobj in iter_generic_readers(ioclass, filenames, directory=directory, target=target, return...
Iterate over objects read from a list of filenames. If target is None, use the first supported_objects from ioobj If target is False, use the 'read' method. If target is the Block or Segment class, use read_block or read_segment, respectively. If target is a string, use 'read_'+target. If directory is not None and pa...
625941d973bcbd0ca4b2c302
def get_user(self, username): <NEW_LINE> <INDENT> session = self._get_session() <NEW_LINE> for user in session.query(User).filter_by(user_name=username): <NEW_LINE> <INDENT> return user
Get a user by username
625941d91b99ca400220ad3e
def set_css_filename(self, css_filename): <NEW_LINE> <INDENT> self.css_filename = css_filename
set the CSS filename
625941d94527f215b584c6e0
def verify(self, item, *args, **kw): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if item is None: <NEW_LINE> <INDENT> raise AssertionError("Didn't pass in the Item to evaluate") <NEW_LINE> <DEDENT> logger.info("Attempting to verify {}".format(item)) <NEW_LINE> item = self.sanitize(item) <NEW_LINE> logger.debug("Using ...
Calls the underlying verify sub verbs @param item (string) - The item to verify @param args (Variable positions arguments) - holds any position arguments @param kw (Variable Dictionary) - A variable dictionary that holds optional parameters @par EXAMPLE self.assertTrue(ts.verify(item='Subject Report', name=td.assessmen...
625941d93617ad0b5ed68182
def get_instance(self, payload): <NEW_LINE> <INDENT> return DeviceInstance(self._version, payload, account_id=self._solution['account_id'], )
Build an instance of DeviceInstance :param dict payload: Payload response from the API :returns: connio.rest.api.v3.account.device.DeviceInstance :rtype: connio.rest.api.v3.account.device.DeviceInstance
625941d97047854f462a1693
def get_accept_languages(accept): <NEW_LINE> <INDENT> return map(lang_in_gettext_format, parse_http_accept_header(accept))
Returns a list of languages, by order of preference, based on an HTTP Accept-Language string.See W3C RFC 2616 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) for specification.
625941d9f9cc0f698b140885
def __len__(self): <NEW_LINE> <INDENT> return len(self._type_keys)
Return mapping length.
625941d966673b3332b9231d
def draw_checkbox(self): <NEW_LINE> <INDENT> val = self.env.preview_analysis <NEW_LINE> self.prev_cb.SetValue(val)
Update the state of the checkbox
625941d9c4546d3d9de72cc1
def Handle(self, args, token=None): <NEW_LINE> <INDENT> user_record = aff4.FACTORY.Create( aff4.ROOT_URN.Add("users").Add(token.username), aff4_type=aff4_users.GRRUser, mode="r", token=token) <NEW_LINE> notifications = user_record.Get(user_record.Schema.PENDING_NOTIFICATIONS) <NEW_LINE> return ApiGetPendingUserNotifica...
Fetches the pending notification count.
625941d9460517430c39440c
def save_df_as_csv(self, df, file_name, separator=";"): <NEW_LINE> <INDENT> df.to_csv( os.path.join(self.config.get("path", "final_data"), file_name+".csv"), sep=separator, index=False )
:param df: DataFrame. DF to save. :param file_name: String. File name without .csv
625941d955399d3f05588941
def decodingreturnhandler(status, rheaders, rcontent): <NEW_LINE> <INDENT> if (status < 200) or (status >= 300): <NEW_LINE> <INDENT> raise exceptions.WrongStatusCode(u"%s: Fehler: %r" % (status, rcontent)) <NEW_LINE> <DEDENT> if not rheaders.get('Content-Type', '').startswith('application/json'): <NEW_LINE> <INDENT> lo...
Closure to do the json decoding and then call the provided returnhandler
625941d930c21e258bdfa72a
def classifiction_metric(preds, labels, label_list): <NEW_LINE> <INDENT> acc = metrics.accuracy_score(labels, preds) <NEW_LINE> labels_list = [i for i in range(len(label_list))] <NEW_LINE> report = metrics.classification_report( labels, preds, labels=labels_list, target_names=label_list, digits=5, output_dict=True) <NE...
分类任务的评价指标, 传入的数据需要是 numpy 类型的
625941d94d74a7450ccd4450
def torrent_add(self, torrent): <NEW_LINE> <INDENT> config = util.get_config() <NEW_LINE> if config.TRANSMISSION_WATCH_DIR and torrent.filename: <NEW_LINE> <INDENT> filename = torrent.filename <NEW_LINE> log.debug('get file: %s', filename) <NEW_LINE> full_name = os.path.join( config.TRANSMISSION_WATCH_DIR, filename) <N...
:type torrent: util.Torrent
625941d96fece00bbac2d9cd
def __init__(self, store_filename, **kwargs): <NEW_LINE> <INDENT> super(ModifiedHamiltonianExchange, self).__init__(store_filename, **kwargs) <NEW_LINE> self._fully_interacting_expanded_context = None <NEW_LINE> self.fully_interacting_expanded_state = None <NEW_LINE> self._noninteracting_expanded_context = None <NEW_LI...
Constructor. See ReplicaExchange.__init__ for details on keyword arguments. Parameters ---------- store_filename : string Name of file to bind simulation to use as storage for checkpointing and storage of results.
625941d9f548e778e58cd80b
def clean_county(self): <NEW_LINE> <INDENT> county = escape(self.cleaned_data["county"]) <NEW_LINE> if county != "": <NEW_LINE> <INDENT> if re.match(settings.REGEX["COUNTY"], county) is None: <NEW_LINE> <INDENT> raise forms.ValidationError( "Please spell out the name of the county using letters" ) <NEW_LINE> <DEDENT> i...
County validation :return: string
625941d950812a4eaa59c5ac
def __init__(self, user_id, name, mail, password): <NEW_LINE> <INDENT> self.id = user_id <NEW_LINE> self.name = name <NEW_LINE> self.mail = mail <NEW_LINE> self.password = password
Attributes for all users - id, name, e-mail, password
625941d956ac1b37e6264458
def set_del_button(self, pre): <NEW_LINE> <INDENT> pre['url'] = url_for('domain.domain_delete', domain_id=self.id) <NEW_LINE> return pre
Check for del button in Pager. :param pre: Flask-LwAdmin action dictionary :return: Flask-LwAdmin action dictionary
625941d95fdd1c0f98dc04c0
def set_RestorableBy(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'RestorableBy', value)
Set the value of the RestorableBy input for this Choreo. ((optional, string) AWS accounts ID that can create volumes from the snapshot.)
625941d976d4e153a657edbe
def connection_config_tunneling(self): <NEW_LINE> <INDENT> gateway_ip = self.config[DOMAIN][CONF_KNX_TUNNELING].get(CONF_HOST) <NEW_LINE> gateway_port = self.config[DOMAIN][CONF_KNX_TUNNELING].get(CONF_PORT) <NEW_LINE> local_ip = self.config[DOMAIN][CONF_KNX_TUNNELING].get(CONF_KNX_LOCAL_IP) <NEW_LINE> if gateway_port ...
Return the connection_config if tunneling is configured.
625941d9fbf16365ca6f6453
def get_input_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument('--dir', type = str, default = 'pet_images/', help = 'Path to the pet image files') <NEW_LINE> parser.add_argument('--arch', type = str, default = 'resnet', help = 'CNN model architecture to use for image classif...
Retrieves and parses the command line arguments created and defined using the argparse module. This function returns these arguments as an ArgumentParser object. 3 command line arguments are created: dir - Path to the pet image files(default- 'pet_images/') arch - CNN model architecture to use for image classif...
625941d90fa83653e4657246
def testJSONParamsButNoHits(self): <NEW_LINE> <INDENT> mockOpener = mockOpen(read_data=dumps(PARAMS) + '\n') <NEW_LINE> with patch.object(builtins, 'open', mockOpener): <NEW_LINE> <INDENT> reads = Reads() <NEW_LINE> readsAlignments = DiamondReadsAlignments( reads, 'file.json', databaseFilename='database.fasta') <NEW_LI...
When DIAMOND parameters are present in the input but there are no records, the __iter__ method of a L{DiamondReadsAlignments} instance must not yield anything.
625941d9a17c0f6771cbe2dc
def return_overlay(tfile): <NEW_LINE> <INDENT> metadata = tfile.imagej_metadata <NEW_LINE> img_stk = tfile.asarray() <NEW_LINE> img_shape = img_stk.shape <NEW_LINE> if img_shape.__len__()>3: <NEW_LINE> <INDENT> img_shape = [img_shape[0],img_shape[2],img_shape[3]] <NEW_LINE> <DEDENT> roi_array = [] <NEW_LINE> if 'Overla...
Get existing metadata
625941d99c8ee82313fbba02
def on_done(self, text): <NEW_LINE> <INDENT> if not text: self.restore_selection() <NEW_LINE> else: <NEW_LINE> <INDENT> self.update_selection(text, draw_borders=False) <NEW_LINE> SelectByRegexCommand.history.append(text) <NEW_LINE> SelectByRegexCommand.history_index = 0
Event handler for input, called when user presses return or submits the field :param text: The current text of the input field
625941d992d797404e304417
def get_output_for(self, inputs, **kwargs): <NEW_LINE> <INDENT> tmp_mask = T.where(T.eq(inputs[0],0), np.float32(0.0), np.float32(1.0)) <NEW_LINE> exps = tmp_mask * T.exp(inputs[1]) <NEW_LINE> nums = tmp_mask.sum(axis=1) <NEW_LINE> return ( exps / (exps.sum(axis=1).dimshuffle((0, 'x')) + 1e-6) )*nums.dimshuffle((0, 'x'...
Take the exp() of all inputs, and divide by the total.
625941d9e5267d203edcdf26
def delete_obj(self, obj): <NEW_LINE> <INDENT> node_id = self.node_id(obj) <NEW_LINE> self.delete_node(node_id)
Delete a Drupal node corresponding to the given model instance. Arguments: obj (django.db.models.Model): Model instance to be deleted.
625941d9e5267d203edcdf27
@app.route('/update_anime', methods=['POST']) <NEW_LINE> @login_required <NEW_LINE> def update_anime(): <NEW_LINE> <INDENT> info = MALB.get_anime_info(request.form.get('malId'), ['episodes'])[0] <NEW_LINE> utoa = UserToAnime(g.user.get_id(), request.form['malId']) <NEW_LINE> utoa.episodes = info.episodes <NEW_LINE> for...
Process AJAX calls for updating existing anime in MAL with new metrics
625941d950485f2cf553d027
@pytest.mark.django_db <NEW_LINE> def test_calls_actions(test_scheduler): <NEW_LINE> <INDENT> test_actions = dict(create_action() for _ in range(3)) <NEW_LINE> for i, cb in enumerate(test_actions): <NEW_LINE> <INDENT> create_entry("test" + str(i), 1, 0, 3, 1, cb.__name__) <NEW_LINE> <DEDENT> s = test_scheduler <NEW_LIN...
The scheduler should call task's action function at the right time.
625941d996565a6dacc8f957
def setTimeFrameSize(self, timeFrameSize): <NEW_LINE> <INDENT> self.timeLayerManager.setTimeFrameSize(timeFrameSize) <NEW_LINE> self.guiControl.refreshMapCanvas('setTimeFrameSize')
Set timeLayerManager's time frame size
625941d94c3428357757c5b3
def registerViews(self): <NEW_LINE> <INDENT> self.views.append(connection.LIST_CONNECTION_FOR_ORG_ADMIN) <NEW_LINE> self.views.append(connection.LIST_CONNECTION_FOR_USER) <NEW_LINE> self.views.append(connection.MANAGE_CONNECTION_AS_ORG) <NEW_LINE> self.views.append(connection.MANAGE_CONNECTION_AS_USER) <NEW_LINE> self....
Instantiates all view objects.
625941d9d8ef3951e32437ca
def activationSkill(self,skillGroup): <NEW_LINE> <INDENT> characterId = self._owner.baseInfo.id <NEW_LINE> reason = dbSkill.LearnSkill(characterId, skillGroup) <NEW_LINE> if not reason: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> LearnedSkillInfo = {'skillId':skillGroup,'skillLevel':1} <NEW_LINE> self.learned_...
学习技能 @skillGroup 技能组的ID
625941d9099cdd3c635f0ee6
def load_plugin(plugin_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> plugin = importlib.import_module(plugin_name) <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> raise ValueError('Failed to load plugin %s.' % plugin_name) <NEW_LINE> <DEDENT> return plugin
Loads plugin given by plugin_name.
625941d93c8af77a43ae3a2e
def validUTF8(data): <NEW_LINE> <INDENT> number = 0 <NEW_LINE> higer = 1 << 7 <NEW_LINE> lower = 1 << 6 <NEW_LINE> for num in data: <NEW_LINE> <INDENT> mask = 1 << 7 <NEW_LINE> if number == 0: <NEW_LINE> <INDENT> while mask & num: <NEW_LINE> <INDENT> number += 1 <NEW_LINE> mask = mask >> 1 <NEW_LINE> <DEDENT> if number...
checks data and returns true if data is a valid UTF-8 encoding
625941d9442bda511e8be6a2
def download_genome_contigs(patric_id, outdir=".", throttle=False): <NEW_LINE> <INDENT> if throttle: <NEW_LINE> <INDENT> sleep(2) <NEW_LINE> <DEDENT> file_name = urljoin(PATRIC_FTP_GENOMES_URL, patric_id + "/" + patric_id + ".fna") <NEW_LINE> logging.debug("Downloading contigs for genome {0!s} ({1!s})".format(patric_id...
Downloads the contigs for a given genome Parameters: ----------- patric_id: str The PATRIC identifier of the genome outdir: str The output directory in which to store the contig file throttle: bool Whether or not to throttle the download by sleeping for a short period of time Returns: -------- exception: ...
625941d907d97122c4178b1c
def test_unmount_target_not_found_exception(self): <NEW_LINE> <INDENT> self.args.target = "catch-me-if-you-can" <NEW_LINE> self.assertRaises(FileMissingError, unmount.unmount_main, self.args)
Check target path not found raises FileNotFoundError exception
625941d9be383301e01b570f
def extract_phones(html): <NEW_LINE> <INDENT> return [match.group() for match in re.finditer('(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}', html)]
Extract phone numbers from this HTML >>> extract_phones('Phone: (123) 456-7890 <br>') ['(123) 456-7890'] >>> extract_phones('Phone 123.456.7890 ') ['123.456.7890'] >>> extract_phones('+1-123-456-7890<br />123 456 7890n') ['123-456-7890', '123 456 7890'] >>> extract_phones('456-7890') []
625941d98da39b475bd65202
def read_config() -> Dict[str, Any]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(CONFIG, "rt") as config: <NEW_LINE> <INDENT> conf = json.load(config) <NEW_LINE> <DEDENT> <DEDENT> except (FileNotFoundError, IsADirectoryError): <NEW_LINE> <INDENT> print(f"Could not find configuration file {CONFIG}.", file=sys...
Read JSON configuration file CONFIG. Returns: A dictionary containing the addresses of Elasticsearch node, index names and field names in case of success. Will return an empty dictionary when the file could not be found.
625941d9d58c6744b4257eeb
def specDiff_Adj(f, grid, order=1): <NEW_LINE> <INDENT> if not isinstance(grid, PeriodicGrid): <NEW_LINE> <INDENT> raise TypeError("grid <PeriodicGrid>") <NEW_LINE> <DEDENT> if not isinstance(f, np.ndarray): <NEW_LINE> <INDENT> raise TypeError("f <numpy.ndarray>") <NEW_LINE> <DEDENT> if not (f.ndim==1 and len(f)==grid....
Spectral differentiation adjoint specDiff_Adj(f,grid, order=1) f : input <numpy.ndarray> grid : <PeriodicGrid> order : order of differentiation <int>
625941d982261d6c526ab72f