code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def export_bucket(self, bucket_name, outfile, exclude_mounts=[], img_repo=None, img_tag=None): <NEW_LINE> <INDENT> name, ext = os.path.splitext(outfile) <NEW_LINE> if not ext == '.tar': <NEW_LINE> <INDENT> outfile = name + '.tar' <NEW_LINE> <DEDENT> bucket = self.get_bucket(bucket_name) <NEW_LINE> print('Exporting buck...
Export a bucket
625941ec96565a6dacc8fbe4
@csrf_protect <NEW_LINE> @require_POST <NEW_LINE> def post_ajax_contact_form( request, template_preview="django_contactme/preview_ajax.html", template_discarded="django_contactme/discarded_ajax.html", template_post="django_contactme/confirmation_sent_ajax.html", template_field_errors="django_contactme/field_errors.html...
Post a contact message via AJAX. HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are errors a preview template, ``django_contactme/preview_ajax.html``, will be rendered.
625941ec7cff6e4e81117ea0
def setup_signals(signals, handler): <NEW_LINE> <INDENT> def install_glib_handler(sig): <NEW_LINE> <INDENT> GLib.unix_signal_add( GLib.PRIORITY_HIGH, sig, handler, sig ) <NEW_LINE> <DEDENT> for sig in signals: <NEW_LINE> <INDENT> GLib.idle_add( install_glib_handler, sig, priority = GLib.PRIORITY_HIGH )
This is a workaround to signal.signal(signal, handler) which does not work with a GLib.MainLoop() for some reason. Thanks to: http://stackoverflow.com/a/26457317/5433146 args: signals (list of signal.SIG... signals): the signals to connect to handler (function): function to be executed on these signals
625941ec5166f23b2e1a5673
def libvlc_renderer_discoverer_stop(p_rd): <NEW_LINE> <INDENT> f = _Cfunctions.get('libvlc_renderer_discoverer_stop', None) or _Cfunction('libvlc_renderer_discoverer_stop', ((1,),), None, None, RendererDiscoverer) <NEW_LINE> return f(p_rd)
Stop renderer discovery. See L{libvlc_renderer_discoverer_start}(). @param p_rd: renderer discoverer object. @version: LibVLC 3.0.0 or later.
625941ecf548e778e58cda9a
def test_shib_login(self): <NEW_LINE> <INDENT> response = self.client.get(reverse('huntserver:new_shib_account')) <NEW_LINE> self.assertTemplateUsed(response, 'attribute_error.html') <NEW_LINE> META = {"Shib-Identity-Provider": 'https://login.cmu.edu/idp/shibboleth', "eppn": "", "givenName": "Test", "sn": "User"} <NEW_...
Test the shib login view
625941ec3617ad0b5ed68411
def population_based_train(agent, result, args): <NEW_LINE> <INDENT> all_weights = agent.get_weights() <NEW_LINE> agents = [f'agent_{id}' for id in range(args.num_agents)] <NEW_LINE> policy_reward_mean = result['policy_reward_mean'] <NEW_LINE> if policy_reward_mean: <NEW_LINE> <INDENT> sorted_rewards = sorted(policy_re...
Helper function to implement population based training
625941eca8370b7717052db8
def r(self, inverted=False): <NEW_LINE> <INDENT> if not inverted: <NEW_LINE> <INDENT> self.right.clockwise() <NEW_LINE> temp = self.front.right <NEW_LINE> self.front.right = self.down.right <NEW_LINE> self.down.right = self.back.left[::-1] <NEW_LINE> self.back.left = self.top.right[::-1] <NEW_LINE> self.top.right = tem...
Spins the right face, clockwise if inverted is passed, counter-clockwise otherwise
625941eccc40096d61595e69
def test_stock_price_summary_big_negative_numbers(self): <NEW_LINE> <INDENT> negative_given = -0.184357 <NEW_LINE> (positive_calc, negative_calc) = a1.stock_price_summary([0.010126, 0.03894, -0.02, -0.144827, 0, 0, 0.10, -0.01953]) <NEW_LINE> self.assertAlmostEqual(negative_calc, negative_given, places=7, msg=None, del...
Test with big floating point numbers (precise calculation)
625941ec851cf427c661aa25
def parse_port_data(data): <NEW_LINE> <INDENT> interface = {} <NEW_LINE> for line in data: <NEW_LINE> <INDENT> bits = line.split(",") <NEW_LINE> port_num = bits[0].split("=")[1] <NEW_LINE> port = {} <NEW_LINE> for bit in bits[1:]: <NEW_LINE> <INDENT> key, value = bit.split("=") <NEW_LINE> port[key] = value <NEW_LINE> <...
Parse the raw csv data we got from the switch Returns dict of data
625941ecbde94217f3683307
def handleOk(self): <NEW_LINE> <INDENT> pt = self.tfPath.GetValue() <NEW_LINE> self.app.getGlobalConfig().set("main", "plugin_ical_export_dir", pt)
This is called if checkOk() returned True for all panels. Transfer here all values from text fields, checkboxes, ... into the configuration file.
625941ec15baa723493c4494
def view_tool_config(request): <NEW_LINE> <INDENT> lti_tool_config = ToolConfig( title="Tutor-web", launch_url=request.application_url, secure_launch_url=request.application_url.replace('http://', 'https://'), description="Responsive drilling platform", icon='%s/images/apple-touch-icon-ipad-retina-152x152.png' % reques...
Generate tool config and return
625941ec29b78933be1e5bc0
def constraint_set(self, **kwargs): <NEW_LINE> <INDENT> return FitConstraintSet(self, **kwargs)
Returns constraint set
625941ec4527f215b584c96d
def load(self, module, filename=None, **kwargs): <NEW_LINE> <INDENT> if filename or (not getattr(self, 'filename', None)): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> <DEDENT> if not self.filename: <NEW_LINE> <INDENT> raise ValueError('`filename` must be set.') <NEW_LINE> <DEDENT> extra_args = self.load_kwa...
Load this dict from a file using `module`.load(f, **args). Raises the same errors as open() and `module`.load().
625941ec99fddb7c1c9de8a9
def get_sort_on(request, allowed_indexes=None): <NEW_LINE> <INDENT> sort_on = request.form.get("sort_on") <NEW_LINE> if allowed_indexes and sort_on not in allowed_indexes: <NEW_LINE> <INDENT> _.fail("Usage of index '%s' is not allowed." % sort_on) <NEW_LINE> <DEDENT> return sort_on
returns the 'sort_on' from the request
625941ecb5575c28eb68e520
def fetch_ua_url_content(url, user_agent_category): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> logger.info("Attempting to fetch user agent data for %s...", user_agent_category) <NEW_LINE> resp = urlopen(url, timeout=HTTP_TIMEOUT) <NEW_LINE> <DEDENT> except HTTPError as err: <NEW_LINE> <INDENT> logger.error("Data fetc...
Fetch url, catching exceptions along the way
625941ec293b9510aa2c37ac
@profile <NEW_LINE> def hash_data(data, hashlen=None, alphabet=None): <NEW_LINE> <INDENT> if alphabet is None: <NEW_LINE> <INDENT> alphabet = ALPHABET_27 <NEW_LINE> <DEDENT> if hashlen is None: <NEW_LINE> <INDENT> hashlen = HASH_LEN2 <NEW_LINE> <DEDENT> if isinstance(data, stringlike) and len(data) == 0: <NEW_LINE> <IN...
Get a unique hash depending on the state of the data. Args: data (object): any sort of loosely organized data hashlen (None): (default = None) alphabet (None): (default = None) Returns: str: text - hash string CommandLine: python -m utool.util_hash hash_data Ignore: >>> # ENABLE_DOCTEST ...
625941ec4f6381625f114f56
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, SmartContractInformation): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict()
Returns true if both objects are equal
625941ec8a43f66fc4b5457b
def postStartup(self): <NEW_LINE> <INDENT> pass
Required to implement the ICollectorPreferences interface.
625941ec21bff66bcd684e69
def forward(self, data_batch, is_train=None): <NEW_LINE> <INDENT> self._scores = data_batch.data[0] <NEW_LINE> if is_train is None: <NEW_LINE> <INDENT> is_train = self.for_training <NEW_LINE> <DEDENT> if is_train: <NEW_LINE> <INDENT> self._labels = data_batch.label[0]
Forward computation. Here we do nothing but to keep a reference to the scores and the labels so that we can do backward computation. Parameters ---------- data_batch : DataBatch Could be anything with similar API implemented. is_train : bool Default is ``None``, which means `is_train` takes the value of ``self...
625941ec07d97122c4178db3
def get_reward(self, game_state_before, game_state_after): <NEW_LINE> <INDENT> reward = 0.0 <NEW_LINE> reward -= (game_state_after.count_holes() - game_state_before.count_holes()) * 5 <NEW_LINE> reward -= (game_state_after.get_max_height() - game_state_before.get_max_height()) * 4 <NEW_LINE> reward -= -20 if (game_stat...
Calculate rewards comparing some metrics of the state of the game before and after the action.
625941ec9f2886367277ada4
def get_user_metadata( self, bucket: str, object_name: str ) -> typing.Dict[str, str]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = self.get_all_metadata(bucket, object_name) <NEW_LINE> metadata = response['Metadata'].copy() <NEW_LINE> response = self.s3_client.get_object_tagging( Bucket=bucket, Key=object_n...
Retrieves the user metadata for a given object in a given bucket. If the platform has any mandatory prefixes or suffixes for the metadata keys, they should be stripped before being returned. :param bucket: the bucket the object resides in. :param object_name: the name of the object for which metadata is being retrieve...
625941ec3c8af77a43ae3cc2
def referenced_sale(order_number, pnref, amt): <NEW_LINE> <INDENT> txn = gateway.reference_transaction( order_number, pnref, amt) <NEW_LINE> if not txn.is_approved: <NEW_LINE> <INDENT> raise exceptions.UnableToTakePayment(txn.respmsg) <NEW_LINE> <DEDENT> return txn
Capture funds using the bank/address details of a previous transaction This is equivalent to a *sale* transaction but without the user having to enter their payment details. There are two main uses for this: 1. This allows customers to checkout without having to re-enter their payment details. 2. It allows an in...
625941ec8e05c05ec3eea894
def objects_ids_and_slot_variables(self): <NEW_LINE> <INDENT> checkpointable_objects, path_to_root = self._breadth_first_traversal() <NEW_LINE> object_names = object_identity.ObjectIdentityDictionary() <NEW_LINE> for obj, path in path_to_root.items(): <NEW_LINE> <INDENT> object_names[obj] = _object_prefix_from_path(pat...
Traverse the object graph and list all accessible objects. Looks for `Checkpointable` objects which are dependencies of `root_checkpointable`. Includes slot variables only if the variable they are slotting for and the optimizer are dependencies of `root_checkpointable` (i.e. if they would be saved with a checkpoint). ...
625941eccb5e8a47e48b7fbd
def base_rev_for_display(self): <NEW_LINE> <INDENT> if self.parent_revs is None: <NEW_LINE> <INDENT> self.parent_revs = commit_parents(self.rev) <NEW_LINE> <DEDENT> if self.parent_revs: <NEW_LINE> <INDENT> return self.parent_revs[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
The rev as reference to determine what changed in this commit. RETURN VALUE The reference commit's SHA1, or None if this commit does not have a parent (root commit).
625941ec7b25080760e39971
def ChunkTable(table: rdf_osquery.OsqueryTable, max_chunk_size: int) -> Iterator[rdf_osquery.OsqueryTable]: <NEW_LINE> <INDENT> def ByteLength(string: Text) -> int: <NEW_LINE> <INDENT> return len(string.encode("utf-8")) <NEW_LINE> <DEDENT> def Chunk() -> rdf_osquery.OsqueryTable: <NEW_LINE> <INDENT> result = rdf_osquer...
Chunks given table into multiple smaller ones. Tables that osquery yields can be arbitrarily large. Because GRR's messages cannot be arbitrarily large, it might happen that the table has to be split into multiple smaller ones. Note that that serialized response protos are going to be slightly bigger than the specifie...
625941ecaad79263cf390f64
@cli.command() <NEW_LINE> @click.argument('deployment_id', metavar='UUID', type=click.UUID) <NEW_LINE> @click.pass_obj <NEW_LINE> def terminate(api, deployment_id): <NEW_LINE> <INDENT> api.terminate(deployment_id) <NEW_LINE> logger.info("Deployment successfully terminated.")
Terminate the given deployment.
625941ecbe7bc26dc91cdb11
def get_current_time(): <NEW_LINE> <INDENT> now = dt.datetime.now() <NEW_LINE> return ''.join(map(lambda x: '{0:02d}'.format(x),[now.year, now.month, now.day, now.hour, now.minute, now.second]))
-------------------------------------------------- Returns an integer in the format YYYYMMDDHHmmSS representing the current time
625941ecfb3f5b602dac3bb4
def lab2praat(file_name, praat_align_file,state_number=5): <NEW_LINE> <INDENT> fid = open(file_name) <NEW_LINE> utt_labels = fid.readlines() <NEW_LINE> fid.close() <NEW_LINE> current_index = 0 <NEW_LINE> label_number = len(utt_labels) <NEW_LINE> duration_phone_list=[] <NEW_LINE> for line in utt_labels: <NEW_LINE> <INDE...
convert state alignment lab file to praat alignment file file_name should be state alignment file end with *.lab praat_align_file should be praat Textgrid file for visualization and state number are state number of one senone
625941ec96565a6dacc8fbe5
def get_simulation_by_date(model, date_string): <NEW_LINE> <INDENT> if request.method == 'GET': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> session = entityDB.create_session() <NEW_LINE> date = datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S") <NEW_LINE> date = date.replace(hour=0, minute=0, second=0) <NEW_LINE> dat...
Answers a http request for a given model and date with all values for this day.
625941ec91af0d3eaac9bf39
def test_dag_depth2(self): <NEW_LINE> <INDENT> q = QuantumRegister(5, 'q') <NEW_LINE> c = ClassicalRegister(1, 'c') <NEW_LINE> qc = QuantumCircuit(q, c) <NEW_LINE> qc.h(q[0]) <NEW_LINE> qc.cx(q[0], q[4]) <NEW_LINE> qc.x(q[2]) <NEW_LINE> qc.x(q[2]) <NEW_LINE> qc.x(q[2]) <NEW_LINE> qc.x(q[4]) <NEW_LINE> qc.cx(q[4], q[1])...
Test barrier increases DAG depth
625941ec3d592f4c4ed1d57b
def getMaptool(self, canvas): <NEW_LINE> <INDENT> def _getEditTool(): <NEW_LINE> <INDENT> radius = 10 <NEW_LINE> tool = EditTool(canvas = canvas, layers = [self.QGISLayer]) <NEW_LINE> tool.searchRadius = radius <NEW_LINE> return tool <NEW_LINE> <DEDENT> def _getInsectionTool(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDE...
Returns the map tool configured for this layer.
625941ec07f4c71912b119a0
def __set_timebase(self): <NEW_LINE> <INDENT> time_series = np.arange(self._output_frame_len, dtype=np.float64) / self.sample_rate <NEW_LINE> self.time_base = np.tile(time_series, (self.nr_of_chan, 1))
Updates <ndarray> of time base values in seconds spanning the length of the frame in steps according to sample rate. time_base has to have the dimensions according to nr_of_chan because it casts these dimensions on all subsequent calculations. time_base can also be used as horizontal values for signal plotting.
625941ec66673b3332b925ad
def unitless(self): <NEW_LINE> <INDENT> return not (self.uvec * Quantity.basePersistant).any()
Returns True if the unit vector is zero, or if all non vanishing components' bases are marked as 'unitless'. Otherwise it returns False. For example Meter is not unitless, but Radian is unitless. The unitlessness of Radian is required because functions such as sin require a unitless argument, which is usually a multi...
625941ecdd821e528d63b6c0
def get_points_index(self): <NEW_LINE> <INDENT> return (self.__cp_start.index, self.__cp_end.index)
Returns point indexes
625941ec0383005118ecfafc
def add_files(self, prefix, folder='', preserve_paths=False): <NEW_LINE> <INDENT> def resp_to_filelist(resp): <NEW_LINE> <INDENT> file_list = [] <NEW_LINE> for x in resp['Contents']: <NEW_LINE> <INDENT> key = x['Key'] <NEW_LINE> if key == prefix: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if preserve_paths is Tru...
Add s3 files from a directory inside the source bucket self.all_keys gets added to directly Args: prefix (str): Folder path inside the source bucket folder (str, optional): Folders to place the file inside the tar file. Defaults to ''. preserve_paths (bool, optional): Starting from the prefix, use...
625941ec73bcbd0ca4b2c591
def find(self, mongo_collection, query, find_one=False, mongo_db=None, **kwargs): <NEW_LINE> <INDENT> collection = self.get_collection(mongo_collection, mongo_db=mongo_db) <NEW_LINE> if find_one: <NEW_LINE> <INDENT> return collection.find_one(query, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return collect...
Runs a mongo find query and returns the results https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find
625941ecb5575c28eb68e521
def GrammarProductionRole(typ, rawtext, text, lineno, inliner, options={}, content=[]): <NEW_LINE> <INDENT> env = inliner.document.settings.env <NEW_LINE> targetid = 'grammar-token-{}'.format(text) <NEW_LINE> target = nodes.target('', '', ids=[targetid]) <NEW_LINE> inliner.document.note_explicit_target(target) <NEW_LIN...
An inline role to declare grammar productions that are not in fact included in a `productionlist` directive. Useful to informally introduce a production, as part of running text
625941eca4f1c619b28b0548
def associate_team_member(projectId=None, clientRequestToken=None, userArn=None, projectRole=None, remoteAccessAllowed=None): <NEW_LINE> <INDENT> pass
Adds an IAM user to the team for an AWS CodeStar project. See also: AWS API Documentation :example: response = client.associate_team_member( projectId='string', clientRequestToken='string', userArn='string', projectRole='string', remoteAccessAllowed=True|False ) :type projectId: string :param pr...
625941ec4c3428357757c840
def connect_to(self, fn): <NEW_LINE> <INDENT> self.connections.append(fn) <NEW_LINE> return self
Whenever this client receives a call from its own end, it will check the conditions at connections, and if True, calls the fn. fn(cmd, replyf) The fn must call the replyf only if it processes the request, and return True. replyf({id, result|error}) None means that the answer can not be given right now, will be give...
625941ec379a373c97cfb063
def AcceptsFocusFromKeyboard(self): <NEW_LINE> <INDENT> return False
Can this window be given focus by keyboard navigation? If not, the only way to give it focus (provided it accepts it at all) is to click it. :note: This method always returns ``False`` as we do not accept focus from the keyboard. :note: Overridden from :class:`Panel`.
625941ec4f88993c3716c57d
def __read(self): <NEW_LINE> <INDENT> status, tag_type = self.__tag_reader.MFRC522_Request( self.__tag_reader.PICC_REQIDL) <NEW_LINE> if not self.__read_succeeded(status): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> status, uid = self.__tag_reader.MFRC522_Anticoll() <NEW_LINE> if not status == self.__tag_reader.MI_O...
Reads any tag and updates the current configuration if a tag was detected. :return:
625941ec8c3a8732951588dd
def _respond(self, text: str, session_id: str) -> str: <NEW_LINE> <INDENT> if not text: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> input_stack = self.get_input_stack(session_id) <NEW_LINE> if len(input_stack) > self._max_recursion_depth: <NEW_LINE> <INDENT> if self._verbose_mode: <NEW_LINE> <INDENT> err = "WARNI...
Private version of respond(), does the real work.
625941ec0a366e3fb873ed3b
def get_translation(instance, language_code=None): <NEW_LINE> <INDENT> accessor = getattr(instance, instance._meta.translations_accessor) <NEW_LINE> language_code = language_code or get_language() <NEW_LINE> qs = accessor.all() <NEW_LINE> if qs._result_cache is not None: <NEW_LINE> <INDENT> for obj in qs: <NEW_LINE> <I...
Get translation by language. Fresh copy is loaded from DB. Can leverage prefetched data, like in .prefetch_related('translations')
625941ec7cff6e4e81117ea1
def edit(self): <NEW_LINE> <INDENT> if not self._render_edit: <NEW_LINE> <INDENT> self._render_edit = ModeWrapValueRenderer( "edit", TemplateWrapValueRenderer( edit_value_wrapper_template, self._edit_renderer ) ) <NEW_LINE> <DEDENT> return self._render_edit
Returns a renderer object to display just an editable field value.
625941ec4f88993c3716c57e
def on_background_change(self, event): <NEW_LINE> <INDENT> text = self.m_background_textbox.GetValue() <NEW_LINE> try: <NEW_LINE> <INDENT> if text == "": <NEW_LINE> <INDENT> cl = RGBA("#FFFFFF") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cl = RGBA(text) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> event....
On background change event.
625941ec5fc7496912cc3e99
def dotarray(self,axis,array): <NEW_LINE> <INDENT> if isinstance(axis,Label): axis=self.axis(axis) <NEW_LINE> od=self.labels[axis].qns.toordereddict() <NEW_LINE> data={key:block*array[[od[key[axis]] if i==axis else np.newaxis for i in range(self.ndim)]] for key,block in self.data.items()} <NEW_LINE> return STensor(data...
Multiply a certain axis of a tensor with an array. Parameters ---------- axis : int The axis of the tensor to be multiplied. array : 1d ndarray The multiplication array. Returns ------- STensor The new tensor.
625941ec2c8b7c6e89b35cd8
@run_in_thread <NEW_LINE> def create_alarm_for_healthcheck(request, region_name=None, **kwargs): <NEW_LINE> <INDENT> healthcheck_id = kwargs.get('healthcheck_id') <NEW_LINE> notification_arns = [] <NEW_LINE> notification = kwargs.get('notification', None) <NEW_LINE> if notification: <NEW_LINE> <INDENT> notification_arn...
Method to return all the alarms for healthchecks, in the given region
625941ec5fdd1c0f98dc0751
def writeoffset(self,offset,value): <NEW_LINE> <INDENT> self.fp.seek(offset,0) <NEW_LINE> s = struct.pack(self.ounpack,value) <NEW_LINE> self.fp.write(s) <NEW_LINE> self.ateof=0
Write an OFFSET to the file at the given location
625941ec67a9b606de4a83d3
def _get_topology_dict(self): <NEW_LINE> <INDENT> return {'topology': {**self._get_switches_dict(), **self._get_links_dict()}}
Return a dictionary with the known topology.
625941ec91f36d47f21aca14
def run_executable(repo, args, includes): <NEW_LINE> <INDENT> mgr = plugins_get_mgr() <NEW_LINE> repomgr = mgr.get(what='instrumentation', name='platform') <NEW_LINE> platform_metadata = repomgr.get_metadata() <NEW_LINE> print("Obtaining Commit Information") <NEW_LINE> (executable, commiturl) = find_executab...
Run the executable and capture the input and output...
625941ec76d4e153a657f04f
def get_labels(df, cutoff_day): <NEW_LINE> <INDENT> df["transaction_date"] = pd.to_datetime(df["transaction_date"], format='%Y%m%d') <NEW_LINE> df["membership_expire_date"] = pd.to_datetime(df["membership_expire_date"], format='%Y%m%d') <NEW_LINE> cutoff_day = pd.to_datetime(cutoff_day, format='%Y%m%d') <NEW_LINE> end ...
Calculates lables for the month before cutoff_day. Parameters: df (pandas.DataFrame): Transactions table cutoff_daye (str): First day of the month in format %Y%m%d e.g. 20170301 Returns: pandas.DataFrame: Two columns data frame; columns: "msno", "is_churn"
625941ecf7d966606f6aa526
def recvMessage(self, data, nodeStruct): <NEW_LINE> <INDENT> if len(data) > 1: <NEW_LINE> <INDENT> i_status = self.OK <NEW_LINE> parse_str = re.split("[b';\r\n\s]", data) <NEW_LINE> i_data = len(data) <NEW_LINE> nodeStruct = self.readData(parse_str, nodeStruct) <NEW_LINE> nodeStruct.s_message = "{0}:{1:d}:{2}".format(o...
Метод принимает строку байт от клиента и проверяет на целостность данных :param: * data: байтовая строка * nodeStruct: объект nodeStruct :return: * i_status: код ошибки * NodeInfo(): обработанный объект nodeStruct
625941ec5e10d32532c5f441
def request_seasons(key = None): <NEW_LINE> <INDENT> if key is None: <NEW_LINE> <INDENT> key = api_key <NEW_LINE> <DEDENT> text = requests.get(base_url + 'seasons?api_key=' + key).text <NEW_LINE> return json.loads(text)
make request of seasons, returns json object this is static, so should be cached see https://docs.crowdscores.com/#page:seasons
625941ec24f1403a9260107e
def _get_height(self): <NEW_LINE> <INDENT> return int(self._tr.get('h'))
Return height of row in EMU
625941ec091ae35668667471
def patch_001_paramiko_deprecation(): <NEW_LINE> <INDENT> import warnings <NEW_LINE> warnings.filterwarnings( category=DeprecationWarning, message='This application uses RandomPool,', action='ignore', )
Silence an an unhelpful DeprecationWarning triggered by Paramiko. Not strictly a monkeypatch.
625941ec7d847024c06be7dd
def __init__(self, status, remote_message, remote_stack_trace): <NEW_LINE> <INDENT> super(CoreHttpError, self).__init__(status, '%s%s' % (remote_message, remote_stack_trace)) <NEW_LINE> self.remote_message = remote_message <NEW_LINE> self.remote_stack_trace = remote_stack_trace
:type status: int :type remote_message: str :type remote_stack_trace: str
625941ec0383005118ecfafd
def get_feeds(self): <NEW_LINE> <INDENT> result = [] <NEW_LINE> if self.es_feed_result["hits"]["total"]["value"] > 0: <NEW_LINE> <INDENT> for activity_type in self.es_feed_result["aggregations"]["types"][ "buckets" ]: <NEW_LINE> <INDENT> _dict = {"type": activity_type["key"]} <NEW_LINE> hit_array = [] <NEW_LINE> for hi...
Construct an array of activity feeds grouped by type and ordered by published datetime. Each activity type has the following keys type: Activity type activities: An array of the activity feeds ordered by published datetime. Each activity has the following keys: published type ...
625941eccc40096d61595e6a
def outcome_list(num_rolls, outcomes, dice=six_sided): <NEW_LINE> <INDENT> if num_rolls == 0: <NEW_LINE> <INDENT> return outcomes <NEW_LINE> <DEDENT> print(type(outcomes)) <NEW_LINE> outcomes.append(dice()) <NEW_LINE> return outcome_list(num_rolls-1, outcomes, dice=six_sided)
Returns a list containing all outcomes in a turn of a player
625941ec1b99ca400220afd0
def _setLiveCache(self, key, value): <NEW_LINE> <INDENT> self._live_cacher.set(self._getLiveCacheKey() + key, value)
Save a new key -> value pair to the in-memory cache.
625941ec091ae35668667472
def create_hub(host, port): <NEW_LINE> <INDENT> method = 'create_hub' <NEW_LINE> params = { 'my_ip': host } <NEW_LINE> return _check(https.client.jsonrpc_post(host, port, '/', method, params=params))
POST (my_ip) create_hub
625941ecf7d966606f6aa527
def plot_mz_diffs(self, knots_no = 1000, plt_style = 'dark_background', all_diffs = True, cluster_diffs = True, trend = True, show = True): <NEW_LINE> <INDENT> plt.style.use(plt_style) <NEW_LINE> if all_diffs: <NEW_LINE> <INDENT> plt.scatter(self.mz[:-1], np.diff(self.mz), c = 'blue', s = ...
Plot the clustering on the mass spectrum. Parameters ---------- plt_style : str The type of the matplotlib style used in the plot. all_diffs : logical Plot all the differences, or only the ones in clusters? cluster_diffs : logical Plot the differences that belong to the cluster. ...
625941ec4d74a7450ccd46e1
def update(isamAppliance, connection, description='', locked=False, connectionManager=None, servers=None, name=None, new_name=None, check_mode=False, force=False): <NEW_LINE> <INDENT> if check_mode is True: <NEW_LINE> <INDENT> return isamAppliance.create_return_object(changed=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> ...
Modifying an LDAP server connection Use new_name to rename the connection, cannot compare password so update will take place everytime
625941ec38b623060ff0b309
def natural_selection(population): <NEW_LINE> <INDENT> population_size = len(population.generation) <NEW_LINE> next_population_size = math.floor(population_size / 2) <NEW_LINE> new_generation = sorted(population.generation, key=lambda x: x.rate, reverse=True)[0:next_population_size] <NEW_LINE> population.generation = n...
Defines the new generation of a population of teas as that half of the generation that has higher fitness values, i.e. higher rankings from the user.
625941ec167d2b6e312190b1
def copy_template(self, template, dest, mode=0o644): <NEW_LINE> <INDENT> path = os.path.join(self.workflowdir, dest) <NEW_LINE> t = self.jinja.get_template(template) <NEW_LINE> t.stream(**self.__dict__).dump(path) <NEW_LINE> os.chmod(path, mode)
Copy template to dest in workflowdir with mode
625941ec4428ac0f6e5bad13
def write(self): <NEW_LINE> <INDENT> new_summary = pd.DataFrame([self._summ.values()], index=[self._date_str], columns=self._summ.keys()) <NEW_LINE> try: <NEW_LINE> <INDENT> current = pd.read_csv(self._output_path, index_col=0) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> new_summary.to_csv(self._output_path...
Write summary to csv file If date_str already exists, overwrite it
625941ec2eb69b55b151cdd3
def update_editor(self): <NEW_LINE> <INDENT> self.fit_list = [] <NEW_LINE> self.search_choices = [] <NEW_LINE> for specimen in self.specimens_list: <NEW_LINE> <INDENT> if specimen not in self.parent.pmag_results_data['specimens']: continue <NEW_LINE> self.fit_list += [(fit,specimen) for fit in self.parent.pmag_results_...
updates the logger and plot on the interpretation editor window
625941ec5166f23b2e1a5675
def test_get_user_locked(self): <NEW_LINE> <INDENT> user = self.factory.make_user(locked=True) <NEW_LINE> self.assertRaises( errors.LockedUserError, self.gw.get_user, user.id, session_id='QWERTY')
Test get_user with a locked user.
625941ece76e3b2f99f3ad1f
def fix_policy_float(policy): <NEW_LINE> <INDENT> return collections.OrderedDict((k, float(v)) for k, v in policy.items())
Numpy to normal python float, for json dumps
625941ec627d3e7fe0d6936e
def authenticate(self, username=None, password=None): <NEW_LINE> <INDENT> if username is None or password is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> user_profile = get_user_profile_by_email(username) <NEW_LINE> if not password_auth_enabled(user_profile.realm): <NEW_LINE> <INDE...
Authenticate a user based on email address as the user name.
625941ec009cb60464c638ca
def check_input_data(input_file): <NEW_LINE> <INDENT> import logging as log <NEW_LINE> log.debug("Determining input data file type.\n") <NEW_LINE> try: <NEW_LINE> <INDENT> from scipy.io import loadmat <NEW_LINE> f = loadmat(input_file) <NEW_LINE> ftype = ".mat" <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT>...
This function determines what the input file type is: It accommodates binary, HDF5, and MATLAB formatted data files. :param str input_file: name of the input file :return str ftype: the determined file type of input_file
625941ec3617ad0b5ed68413
def _find_empty(self, x, y, area=None, count=None): <NEW_LINE> <INDENT> if area is None: <NEW_LINE> <INDENT> area = list() <NEW_LINE> <DEDENT> if count is None: <NEW_LINE> <INDENT> count = [0, 0] <NEW_LINE> <DEDENT> if self.board[y][x] is not None or (x, y) in area: <NEW_LINE> <INDENT> return area, count <NEW_LINE> <DE...
Finds the connected empty fields starting at (x, y) and counts the adjacent stones of each color. Returns: area (list): empty fields [Black, White] count (list): number of adjacents stones to [Black, White]
625941ec9c8ee82313fbbc94
@app.route("/") <NEW_LINE> def index(): <NEW_LINE> <INDENT> dbReply = getInfo() <NEW_LINE> return render_template('index.html', marsData = dbReply)
Generate html page
625941ec21a7993f00bc8216
def move(state, position): <NEW_LINE> <INDENT> new_state = state[:] <NEW_LINE> index = new_state.index(0) <NEW_LINE> if position == 1: <NEW_LINE> <INDENT> if index not in range(0, board_side): <NEW_LINE> <INDENT> temp = new_state[index - board_side] <NEW_LINE> new_state[index - board_side] = new_state[index] <NEW_LINE>...
ეს ფუნქცია აკეთებს სვლას :param state: მიმდინარე მდგომარეობა :param position: სვლა :return:
625941ec435de62698dfe16a
def command(self, dbname, spec, slave_ok=False, read_preference=ReadPreference.PRIMARY, codec_options=DEFAULT_CODEC_OPTIONS, check=True, allowable_errors=None, check_keys=False, read_concern=None, write_concern=None, parse_write_concern_error=False, collation=None, session=None, client=None, retryable_write=False, publ...
Execute a command or raise an error. :Parameters: - `dbname`: name of the database on which to run the command - `spec`: a command document as a dict, SON, or mapping object - `slave_ok`: whether to set the SlaveOkay wire protocol bit - `read_preference`: a read preference - `codec_options`: a CodecOptions i...
625941ec090684286d50f20b
def numberOfArithmeticSlices(self, A): <NEW_LINE> <INDENT> l=len(A) <NEW_LINE> count=1 <NEW_LINE> sum_1=0 <NEW_LINE> for i in range(0,l-2): <NEW_LINE> <INDENT> if A[i]+A[i+2]==2*A[i+1]: <NEW_LINE> <INDENT> sum_1+=count <NEW_LINE> count+=1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> count=1 <NEW_LINE> <DEDENT> <DEDENT...
:type A: List[int] :rtype: int 32MS
625941ec7047854f462a1920
def test_is_recent_on_future(self): <NEW_LINE> <INDENT> q = create_question(days=3) <NEW_LINE> self.assertIs(q.is_recent(), False)
`question.is_recent()` should return False when `question.pub_date` is future
625941ecad47b63b2c50a49c
def testFTISetup(self): <NEW_LINE> <INDENT> self.failUnless(self.portal.portal_types['FSDClassification'].Title() != "AT Content Type")
Make sure the FTI is pulling info from the GS types profile
625941ec099cdd3c635f1175
def go(self, direction): <NEW_LINE> <INDENT> return self.paths.get(direction, None)
Function for getting directions in the game
625941ec7047854f462a1921
def test_get_authors(self): <NEW_LINE> <INDENT> forum = self._Forum() <NEW_LINE> author_count = forum.get_author_count() <NEW_LINE> authors = forum.get_authors() <NEW_LINE> self.assertIsInstance(authors, list) <NEW_LINE> self.assertEqual(len(authors), author_count)
should return a list of length author_count
625941ec63b5f9789fde7603
def download_single(self, component): <NEW_LINE> <INDENT> if '.' not in component: <NEW_LINE> <INDENT> componentpath = self.conf_dir + '/custom_components/' + component + '.py' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> domain = component.split('.')[0] <NEW_LINE> platform = component.split('.')[1] <NEW_LINE> compone...
Helper for download_single service
625941ec99fddb7c1c9de8ab
@nodeHandle <NEW_LINE> def getNobility_3304(dynamicId,request_proto): <NEW_LINE> <INDENT> arguments = GetShangJiaoInfo3304_pb2.GetShangJiaoInfoRequest() <NEW_LINE> arguments.ParseFromString(request_proto) <NEW_LINE> response = GetShangJiaoInfo3304_pb2.GetShangJiaoInfoResponse() <NEW_LINE> pid=arguments.id <NEW_LINE> wy...
上交物品换取威望
625941ec15baa723493c4497
def print_category_node_and_all_features(node, level): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = True <NEW_LINE> node_category = PySpin.CCategoryPtr(node) <NEW_LINE> display_name = node_category.GetDisplayName() <NEW_LINE> print_with_indent(level, display_name) <NEW_LINE> for node_feature in node_category.G...
This function retrieves and prints out the display name of a category node before printing all child nodes. Child nodes that are also category nodes are printed recursively. :param node: Category node to get information from. :type node: INode :param level: Depth to indent output. :type level: int :return: True if suc...
625941ecab23a570cc2506a4
def read_data_file(datafile, token): <NEW_LINE> <INDENT> dataset = [] <NEW_LINE> with open(datafile, 'r') as file: <NEW_LINE> <INDENT> for line in file: <NEW_LINE> <INDENT> data = line[:-1].split(token) <NEW_LINE> tmp = [] <NEW_LINE> for x in data: <NEW_LINE> <INDENT> if x != "": <NEW_LINE> <INDENT> x = float(x) <NEW_L...
:param datafile: :return: 2d array
625941ec8e71fb1e9831dcc4
def search(self, query: MetadataMovie) -> Iterator[MetadataMovie]: <NEW_LINE> <INDENT> assert query <NEW_LINE> if query.id_imdb: <NEW_LINE> <INDENT> results = self._lookup_movie(query.id_imdb) <NEW_LINE> <DEDENT> elif query.name: <NEW_LINE> <INDENT> results = self._search_movie(query.name, query.year) <NEW_LINE> <DEDEN...
Searches OMDb for movie metadata.
625941ec50812a4eaa59c839
def sync_groups(self, group_names): <NEW_LINE> <INDENT> current_groups = {g.name for g in self.orm_user.groups} <NEW_LINE> new_groups = set(group_names) <NEW_LINE> if current_groups == new_groups: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> new_groups = set(group_names).difference(current_groups) <NEW_LINE> removed_...
Synchronize groups with database
625941ec23e79379d52eea7a
def test_empty_message(self): <NEW_LINE> <INDENT> response = self.client.post(reverse('jqchat_ajax', kwargs={'id': 1}), {'time': 0, 'action': 'postmsg', 'message': ' '}) <NEW_LINE> self.assert_(response.status_code == 200, response.status_code) <NEW_LINE> payload = simplejson.loads(response.content) <NEW_LINE> message...
Post an empty message to the server - it will be ignored.
625941ecff9c53063f47c70e
def test_user_option_parser(self): <NEW_LINE> <INDENT> print("default options testing") <NEW_LINE> user_options = ["-i", "everywhere"] <NEW_LINE> options = self.ins.user_option_parser(user_options=user_options) <NEW_LINE> print(self.tool.pprint(options)) <NEW_LINE> self.assertTrue(options["ipaddr"] == "everywhere") <NE...
test user option parser
625941ec167d2b6e312190b2
def item(self): <NEW_LINE> <INDENT> return Akonadi.Item()
Akonadi.Item Akonadi.PartFetcher.item()
625941ec0c0af96317bb8705
def plot_log_var_mean(one_option, layer_solver, ax1, ax2): <NEW_LINE> <INDENT> M = int(layer_solver.level_scaling_factor) <NEW_LINE> print("...start pricing option using mlmc...") <NEW_LINE> (option_price, means, variances, counts) = layer_solver.solve_option_price(one_option, True) <NEW_LINE> L = len(variances) <NEW_L...
This is the upper left and upper right plot
625941ec1f037a2d8b94671a
def slope(x1, y1, x2, y2): <NEW_LINE> <INDENT> delta_y = y2-y1 <NEW_LINE> delta_x = x2-x1 <NEW_LINE> return delta_y / delta_x
Returns the slope of a line through two points
625941ec5510c4643540f8f4
def render(self, *args, **kwargs): <NEW_LINE> <INDENT> user_name = kwargs.get('user_name', args[0]) <NEW_LINE> kind = kwargs.get('kind', args[1]) <NEW_LINE> num = kwargs.get('num', args[2] if len(args) > 2 else 6) <NEW_LINE> with_tag = kwargs.get('with_tag', False) <NEW_LINE> glyph = kwargs.get('glyph', '') <NEW_LINE> ...
fun(user_name, kind) fun(user_name, kind, num) fun(user_name, kind, num, with_tag = val1, glyph = val2) fun(user_name = vala, kind = valb, num = valc, with_tag = val1, glyph = val2)
625941ec6aa9bd52df0372c5
def make_comp_list(instance_dict): <NEW_LINE> <INDENT> comp_list = dict() <NEW_LINE> for component, connections in instance_dict.items(): <NEW_LINE> <INDENT> label, cid = clean_id(component) <NEW_LINE> label = label.split('/')[1] <NEW_LINE> if label in comp_list.keys(): <NEW_LINE> <INDENT> comp_list[label].append(cid) ...
make_comp_list() creates a dict used for replacing the random 4 or 5 char id associated with each instance of a component with a shorter integer in name_with_new_id() Parameters ---------- instance_dict : dict Component names with random id's paired with dict of it's 'in' and 'out' ports Returns ------- comp_...
625941ec8a43f66fc4b5457d
def getCommand(self): <NEW_LINE> <INDENT> return input("UCI move: ")
:return: Chess-formatted string of the most recent command recieved from the microphone :rtype: None|Move
625941ec26068e7796caf205
def ok(self): <NEW_LINE> <INDENT> return self.go("ok")
Click <Ok> Goes to SCR_0182
625941ec16aa5153ce362996
@app.route('/predict',methods=["Get"]) <NEW_LINE> def predict_note_authentication(): <NEW_LINE> <INDENT> variance=request.args.get("variance") <NEW_LINE> skewness=request.args.get("skewness") <NEW_LINE> curtosis=request.args.get("curtosis") <NEW_LINE> entropy=request.args.get("entropy") <NEW_LINE> prediction=classifier...
Let's Authenticate the Banks Note This is using docstrings for specifications. --- parameters: - name: variance in: query type: number required: true - name: skewness in: query type: number required: true - name: curtosis in: query type: number required: true - name: entro...
625941ec8e05c05ec3eea896
def render(self, context): <NEW_LINE> <INDENT> resolved_args, resolved_kwargs = self.get_resolved_arguments(context) <NEW_LINE> if resolved_kwargs: <NEW_LINE> <INDENT> raise ValueError("Due to ArgCache limitations, " "cache_inclusion_tag does not support " "passing keyword arguments.") <NEW_LINE> <DEDENT> self._context...
Renders the specified template and context. Caches the template object in render_context to avoid reparsing and loading when used in a for loop.
625941ec460517430c394694
def buildT(post_o, in_o): <NEW_LINE> <INDENT> if in_o: <NEW_LINE> <INDENT> mid = in_o.index(post_o.pop()) <NEW_LINE> n = BTNode(in_o[mid]) <NEW_LINE> n.right = buildT(post_o, in_o[mid+1:]) <NEW_LINE> n.left = buildT(post_o, in_o[:mid]) <NEW_LINE> return n
68% percentile in leetcode
625941ecbd1bec0571d90b4c
def delete_post_2(self, post): <NEW_LINE> <INDENT> zid = post.zid <NEW_LINE> fid = post.fid <NEW_LINE> pid = post.pid <NEW_LINE> tbs = self.__get_tbs(post.url) <NEW_LINE> operator_url = "http://tieba.baidu.com/mo/m?" <NEW_LINE> payload = {'expand': '0', 'fid': fid, 'nlm': '11', 'ntn': 'bdKSW', 'pinf': '1_2_0', 'pn': '0...
Delete post by generate a url :param post: :return:
625941ecdc8b845886cb5a54
def get_itemcategory_by_name(self, name): <NEW_LINE> <INDENT> cat = self.db_session.query(ItemCategory) .filter(ItemCategory.name == name).first() <NEW_LINE> return cat
Return ItemCategory object or None.
625941eceab8aa0e5d26e077
def data_clone_source(soup): <NEW_LINE> <INDENT> result = soup.findAll("div", attrs={"class":"complex-type-contents data-contract-clone-source"}) <NEW_LINE> for item in result: <NEW_LINE> <INDENT> level = item.find("div").attrs["class"][1][-1:] <NEW_LINE> DATA_SOURCE[item.attrs['data-clone-id']] = get_body(item, int(le...
Retrieve data contract clone sources
625941ecd268445f265b538c