code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def total_reward(self): <NEW_LINE> <INDENT> return np.sum(self.rewards)
float: Returns the total reward.
625941dde5267d203edcdfb7
def _get_hash(document): <NEW_LINE> <INDENT> hash_dict = {key: document.get(key) for key in HASH_FIELDS} <NEW_LINE> hash_str = json.dumps(hash_dict, sort_keys=True, ensure_ascii=True).encode('ascii') <NEW_LINE> m = hashlib.sha224() <NEW_LINE> m.update(hash_str) <NEW_LINE> return m.hexdigest()
Get the hash for a document
625941dd9b70327d1c4e10f4
def Trunc(self, *args): <NEW_LINE> <INDENT> return _snap.TStrV_Trunc(self, *args)
Trunc(TStrV self, int const & _Vals=-1) Parameters: _Vals: int const & Trunc(TStrV self) Parameters: self: TVec< TStr,int > *
625941ddadb09d7d5db6caac
def addItemToCards(self, item): <NEW_LINE> <INDENT> note = ForeignNote() <NEW_LINE> note.fields.append(self._fudgeText(self._decode_htmlescapes(item.Question))) <NEW_LINE> note.fields.append(self._fudgeText(self._decode_htmlescapes(item.Answer))) <NEW_LINE> note.tags = [] <NEW_LINE> if ( not self.META.resetLearningData...
This method actually do conversion
625941dd4f6381625f114d5a
def update_group_by_session_id(self, group_data): <NEW_LINE> <INDENT> group = [group for group in self.group_store if str(group.session_id) == str(group_data['session_id'])] <NEW_LINE> if group != []: <NEW_LINE> <INDENT> group[0].update_properties(group_data) <NEW_LINE> if self.settings.LOG_VERBOSE: <NEW_LINE> <INDENT>...
accepts a dictionary of group data and creates/updates a group
625941dd7cff6e4e81117ca4
def convert_downloaded_files_to_tab_delimited(program_input_path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> file_hndl = open(program_input_path + "filenames.txt", 'w') <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> print(Bcolors.FAIL + "Cannot open file " + program_input_path + " filenames.txt" + Bcolors...
let's open each new downloaded file and search for filename
625941dd91f36d47f21ac814
def cert_list_permission(subject, reg=r'LOCAL_MACHINE\My'): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> cmd_ret = __salt__['cmd.run_all']('"{0}" -l -c "{1}" -s "{2}"'.format( WinHttpCertCfg, reg, subject )) <NEW_LINE> if cmd_ret['retcode'] != 0: <NEW_LINE> <INDENT> log.error('could not find certificate for "{0}" in "{1}"'....
List users with permission to the supplied certificate
625941ddfbf16365ca6f64e7
def update_policy(self): <NEW_LINE> <INDENT> states=np.vstack(self.states) <NEW_LINE> gradients=np.vstack(self.gradients) <NEW_LINE> rewards=np.vstack(self.rewards) <NEW_LINE> discounted_rewards=self.get_discounted_rewards(rewards) <NEW_LINE> gradients*=discounted_rewards <NEW_LINE> gradients=self.alpha*np.vstack([grad...
Updates the policy network using the NN model. This function is used after the MC sampling is done - following \delta heta = lpha * gradient + log pi
625941dd6aa9bd52df0370c4
def get_main_menu_model_string(): <NEW_LINE> <INDENT> from wagtailmenus.conf import settings <NEW_LINE> return settings.MAIN_MENU_MODEL
Get the dotted ``app.Model`` name for the main menu model as a string. Useful for developers extending wagtailmenus, that need to refer to the main menu model (such as in foreign keys), but the model itself is not required.
625941dd01c39578d7e7515a
def choose_move_01(self, game_state): <NEW_LINE> <INDENT> x = reduce(xor, game_state) <NEW_LINE> if x == 0: <NEW_LINE> <INDENT> return next((i, pile) for i, pile in enumerate(game_state) if pile > 0) <NEW_LINE> <DEDENT> for i, pile in enumerate(game_state): <NEW_LINE> <INDENT> if xor(x, pile) < pile: <NEW_LINE> <INDENT...
simplified
625941dd76e4537e8c351994
def open(self, number=0, name="Control XL", template=0): <NEW_LINE> <INDENT> self.user_template = template <NEW_LINE> retval = super(LaunchControlXL, self).open(number=number, name=name) <NEW_LINE> if retval: <NEW_LINE> <INDENT> self.template_set(self.user_template) <NEW_LINE> <DEDENT> return retval
Opens one of the attached Control XL MIDI devices. Uses search string "Control XL", by default.
625941dd4a966d76dd551330
def transposeRelative(p, lastPitch): <NEW_LINE> <INDENT> p.makeAbsolute(lastPitch) <NEW_LINE> if not in_selection(p): <NEW_LINE> <INDENT> return p <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> last = lastPitch.transposed <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> last = lastPitch <NEW_LINE> <DEDENT> ...
Transposes a relative pitch; returns the pitch in absolute form.
625941dd3cc13d1c6d3c7698
def test_delete_recipe(self): <NEW_LINE> <INDENT> self.category_one.add_item(self.recipe_two) <NEW_LINE> result = self.category_one.delete_item('Beef stew', self.category_one.item_name) <NEW_LINE> self.assertEqual(result, [{'name': 'Vegetable salad', 'ingredients': 'corriander, vegetables', 'preparation': 'boil ...
Test if recipe deleted successfully
625941dd07f4c71912b117a3
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <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> <...
Returns the model properties as a dict
625941dde64d504609d74b5e
def run(): <NEW_LINE> <INDENT> sys.exit(main(sys.argv[1:]))
Entry point for the runnable script.
625941dd4a966d76dd551331
def time(self) -> float: <NEW_LINE> <INDENT> return self._time
Get the number of seconds into the track we have played :return: The number of seconds played as a float
625941dd1f037a2d8b94651c
def verify_password_masked(liteserv_platform, log_file, password, test_cbllog): <NEW_LINE> <INDENT> delimiter = "/" <NEW_LINE> if "-msft" in liteserv_platform or liteserv_platform == "uwp": <NEW_LINE> <INDENT> delimiter = "\\" <NEW_LINE> <DEDENT> log_info("\n Collecting logs from the log file.. {}".format(log_file)) <N...
@note: Porting logs for Android, xamarin-android, net-core and net-uwp platform, as the logs reside outside runner's file directory
625941ddd268445f265b518d
def flatten(lst): <NEW_LINE> <INDENT> return [i for subl in lst for i in subl]
Flatten a nested list lst
625941dd379a373c97cfae65
def get_port_table_name(interface_name): <NEW_LINE> <INDENT> if interface_name.startswith(front_panel_prefix()): <NEW_LINE> <INDENT> if VLAN_SUB_INTERFACE_SEPARATOR in interface_name: <NEW_LINE> <INDENT> return "VLAN_SUB_INTERFACE" <NEW_LINE> <DEDENT> return "PORT" <NEW_LINE> <DEDENT> elif interface_name.startswith(por...
Get table name by port_name prefix
625941ddb5575c28eb68e321
def lookup(symbol): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = requests.get(f"https://cloud.iexapis.com/stable/stock/{urllib.parse.quote_plus(symbol)}/quote?token=pk_84ef81ab768847e9b2a827e9054405fd") <NEW_LINE> response.raise_for_status() <NEW_LINE> <DEDENT> except requests.RequestException: <NEW_LINE> <I...
Look up quote for symbol.
625941dd9b70327d1c4e10f5
def __init__(self, after_date: datetime=None, amount: float=None): <NEW_LINE> <INDENT> self.openapi_types = { 'after_date': datetime, 'amount': float } <NEW_LINE> self.attribute_map = { 'after_date': 'afterDate', 'amount': 'amount' } <NEW_LINE> self._after_date = after_date <NEW_LINE> self._amount = amount
CancellationCost - a model defined in OpenAPI :param after_date: The after_date of this CancellationCost. :param amount: The amount of this CancellationCost.
625941dd099cdd3c635f0f79
def OrganizeUsers(self, customer_id, org_unit_path, pattern): <NEW_LINE> <INDENT> users = self.user_client.RetrieveAllUsers() <NEW_LINE> matched_users = [] <NEW_LINE> for user in users.entry: <NEW_LINE> <INDENT> if (pattern.search(user.login.user_name) or pattern.search(user.name.given_name) or pattern.search(user.name...
Find users with given pattern and move to an organization in batches. Args: customer_id: [string] customer_id to make calls to Organization API. org_unit_path: [string] path of organization unit where users are moved pattern: [regex object] regex to match with users
625941dd187af65679ca543e
def find_residual_peaks( model, num_residuals=100, threshold=4.0, buffer=2, wl_range=(0, np.inf) ): <NEW_LINE> <INDENT> residual = np.mean(list(model.residuals)[-num_residuals:], axis=0) <NEW_LINE> sigma = residual.std() <NEW_LINE> if "global_cov" in model.params: <NEW_LINE> <INDENT> ag = np.exp(model.params["global_co...
Find the peaks of the most recent residual and return their properties to aid in setting up local kernels Parameters ---------- model : Model The model to determine peaks from. Need only have a residuals array. num_residuals : int, optional The number of residuals to average together for determining peaks. By ...
625941dd16aa5153ce362797
def create_matrix(n): <NEW_LINE> <INDENT> return [[1 for column in range(n)] for row in range(n)]
Create the initial matrix nxn, with all the places with "1".
625941ddfff4ab517eb2f75c
def get_templates(self, filters=None): <NEW_LINE> <INDENT> url = "%s/projectTemplates" % MEMSOURCE_ENDPOINT_V1_URL <NEW_LINE> try: <NEW_LINE> <INDENT> templates = self.handle_rest_call(url, "GET").json()["content"] <NEW_LINE> return templates if not filters else [item for item in templates if filters.items() <= item.it...
List all Memsource templates
625941dd23e79379d52ee87f
def stopService(self): <NEW_LINE> <INDENT> ret = None <NEW_LINE> if self.running and self._streamDone is not None: <NEW_LINE> <INDENT> self._streamDone.cancel() <NEW_LINE> ret = self._streamDone <NEW_LINE> <DEDENT> Service.startService(self) <NEW_LINE> return ret
Stop reading from the stream.
625941ddde87d2750b8600b4
def P2Sig(pval): <NEW_LINE> <INDENT> return -norm.ppf(pval/2)
convert pval to sigma
625941ddcad5886f8bd272f8
def _remoteServerToggledSlot(self, checked): <NEW_LINE> <INDENT> if checked: <NEW_LINE> <INDENT> self.uiRemoteServersGroupBox.setEnabled(True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.uiRemoteServersGroupBox.setEnabled(False)
Slot for when the remote server radio button is toggled. :param checked: either the button is checked or not
625941ddd6c5a1020814436c
def point(self, lut, mode=None): <NEW_LINE> <INDENT> self.load() <NEW_LINE> if isinstance(lut, ImagePointHandler): <NEW_LINE> <INDENT> return lut.point(self) <NEW_LINE> <DEDENT> if callable(lut): <NEW_LINE> <INDENT> if self.mode in ("I", "I;16", "F"): <NEW_LINE> <INDENT> scale, offset = _getscaleoffset(lut) <NEW_LINE> ...
Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65336 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the res...
625941dd1f5feb6acb0c4e6a
def _check_payload_schemas(self, from_module, fields): <NEW_LINE> <INDENT> resource = from_module.__name__.split('.')[-1] <NEW_LINE> payloads = get_payloads_with_schemas(from_module) <NEW_LINE> for payload in payloads: <NEW_LINE> <INDENT> for schema_key in payload.SCHEMA: <NEW_LINE> <INDENT> self.assertIn(schema_key, p...
Assert that the Payload SCHEMAs have the expected properties. A payload's SCHEMA should: 1. Have each of its keys in the payload's fields 2. Have each member of the schema match with a corresponding field in the object
625941ddbde94217f368310d
def test_prob_double_simple_three_exists(self): <NEW_LINE> <INDENT> card_strs = ['3s', '4d', '4h', '4s', '5s', '5d', '6h', '6d', '7c'] <NEW_LINE> cards = Card.strs_to_cards(card_strs) <NEW_LINE> n_cards1 = 5 <NEW_LINE> TestProbability._run_test_prob_of_occurance(cards, 2, n_cards1)
100% chance of a person having a double since there is a triple
625941ddac7a0e7691ed43e6
def test_receive_create_bad_notifier(self): <NEW_LINE> <INDENT> payload = "8dfd70000001000000000000076578616d706c6503636f6d00ff02ff00" <NEW_LINE> expected_response = ("8dfdf0050001000000000000076578616d706c6503636f6d" "00ff02ff00") <NEW_LINE> request = dns.message.from_wire(binascii.a2b_hex(payload)) <NEW_LINE> request...
Get a NOTIFY from a bad master and refuse it
625941dda79ad161976cc465
def get_city_weather(city_name): <NEW_LINE> <INDENT> my_api_thinkpage_key = os.getenv("API_THINKPAGE_KEY", default=None) <NEW_LINE> if my_api_thinkpage_key == 'None': <NEW_LINE> <INDENT> print("获取密钥失败,请检查相关系统环境变量。") <NEW_LINE> exit() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> weather_params ...
查询城市天气 通过“心知天气API”实现。 详情查询相关文档(https://www.seniverse.com/doc)
625941dde64d504609d74b5f
def deletePlayers(): <NEW_LINE> <INDENT> dbcursor = connect() <NEW_LINE> dbcursor.execute("TRUNCATE players") <NEW_LINE> return 1
Remove all the player records from the database.
625941dd7c178a314d6ef783
def get_sensors(self, timeout: int = DEFAULT_TIMEOUT) -> List[Dict[str, Any]]: <NEW_LINE> <INDENT> r = self._session.get(f"{self._url}/sensors", timeout=timeout) <NEW_LINE> if r.status_code == 200: <NEW_LINE> <INDENT> data = r.json() <NEW_LINE> return data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeErro...
Get all sensors
625941ddf9cc0f698b140918
def __init__(self, is_training, box_code_size, kernel_size, use_depthwise=False, box_encodings_clip_range=None): <NEW_LINE> <INDENT> super(ConvolutionalBoxHead, self).__init__() <NEW_LINE> self._is_training = is_training <NEW_LINE> self._box_code_size = box_code_size <NEW_LINE> self._kernel_size = kernel_size <NEW_LINE...
Constructor. Args: is_training: Indicates whether the BoxPredictor is in training mode. box_code_size: Size of encoding for each box. kernel_size: Size of final convolution kernel. If the spatial resolution of the feature map is smaller than the kernel size, then the kernel size is automatically set to ...
625941dd67a9b606de4a81d6
def roll_dice(num_rolls, dice=six_sided): <NEW_LINE> <INDENT> assert type(num_rolls) == int, 'num_rolls must be an integer.' <NEW_LINE> assert num_rolls > 0, 'Must roll at least once.' <NEW_LINE> "*** REPLACE THIS LINE ***"
Simulate rolling the DICE exactly NUM_ROLLS>0 times. Return the sum of the outcomes unless any of the outcomes is 1. In that case, return the number of 1's rolled.
625941dd097d151d1a223177
def iterable_sort(list): <NEW_LINE> <INDENT> pass
Optional: As a challenge, write a version of merge sort that works for iterables. That is, it can't use `length` or `split` and must look at the list one (head, tail) pair at a time.
625941dda8ecb033257d33eb
def enum(*sequential, **named): <NEW_LINE> <INDENT> enum_dict = dict(list(zip([str(value) for value in sequential], list(range(len(sequential))))), **named) <NEW_LINE> reverse = dict((value, key) for key, value in list(enum_dict.items())) <NEW_LINE> enums = IterableUserDict(reverse) <NEW_LINE> enums.mapping = enum_dict...
Define an enumeration type helper, since the operation of this codebase depends heavily on enumeration types. Usage: new_enum = enum('value1', 'value2') This code is base on code by StackOverflow user Alec Thomas http://stackoverflow.com/users/7980/alec-thomas From: http://stackoverflow.com/questions/36932/how-can-i...
625941dd85dfad0860c3b17b
def compute_cov_pushforward(lambda0, F, cells_coords, device=None, n_chunks=200, n_flush=50): <NEW_LINE> <INDENT> start = timer() <NEW_LINE> if device is None: <NEW_LINE> <INDENT> device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') <NEW_LINE> <DEDENT> lambda0 = torch.tensor(lambda0, requires_grad=Fals...
Compute the covariance pushforward. The covariance pushforward is just KF^T, where K is the model covariance matrix. Note that the sigam0^2 is not included, and one has to manually add it when using the covariance pushforward computed here. Parameters ---------- lambda0: float Lenght-scale parameter F: tensor ...
625941ddb545ff76a8914135
def ud_add_motif(self, *args, **kwargs) -> "void": <NEW_LINE> <INDENT> return _RNA.fold_compound_ud_add_motif(self, *args, **kwargs)
ud_add_motif(fold_compound self, std::string motif, double motif_en, std::string name="", unsigned int options=)
625941ddd53ae8145f87a58a
def get_all_hypernyms(word): <NEW_LINE> <INDENT> result = set() <NEW_LINE> for x in wn.synsets(word): <NEW_LINE> <INDENT> for y in get_all_hypernyms_from_sense(x): <NEW_LINE> <INDENT> result.add(y) <NEW_LINE> <DEDENT> <DEDENT> return result
e.g. get_all_hypernyms('dog')
625941dd3c8af77a43ae3ac2
def __init__(self, size=0, position=(0, 0)): <NEW_LINE> <INDENT> self.size = size <NEW_LINE> self.position = position
initializes instance attribute size and position
625941ddcc0a2c11143dd1b0
@app.route("/test") <NEW_LINE> def test(): <NEW_LINE> <INDENT> return render_template("z_test.html")
to test charts :return:
625941dd8a43f66fc4b54381
def get_edgelist_with_atts(self): <NEW_LINE> <INDENT> output = [] <NEW_LINE> attributes = sorted(self.es[0].attribute_names()) <NEW_LINE> for e in self.es: <NEW_LINE> <INDENT> output.append([self.vs[e.source]['name'], self.vs[e.target]['name']] + [e.attributes()[x] for x in attributes]) <NEW_LINE> <DEDENT> return {'hea...
Writes out an edgelist, followed by edge attributes
625941dd7047854f462a1726
def boundingRect(self): <NEW_LINE> <INDENT> return QRectF(-50, -50, self._width + 400, self._height + 400)
QGraphicsItem.boundingRect() -> QRectF
625941dd29b78933be1e59c7
def standard_deviation_of_slope(self, i, output, zfactor=None, filterx=11, filtery=11, callback=None): <NEW_LINE> <INDENT> args = [] <NEW_LINE> args.append("--input='{}'".format(i)) <NEW_LINE> args.append("--output='{}'".format(output)) <NEW_LINE> if zfactor is not None: args.append("--zfactor='{}'".format(zfactor)) <N...
Calculates the standard deviation of slope from an input DEM. Keyword arguments: i -- Input raster DEM file. output -- Output raster DEM file. zfactor -- Optional multiplier for when the vertical and horizontal units are not the same. filterx -- Size of the filter kernel in the x-direction. filtery -- Size of the...
625941dd7d43ff24873a2fc1
def make_it_html(raml, output_html): <NEW_LINE> <INDENT> raml2html.raml2html(raml, output_html) <NEW_LINE> return output_html
Takes in the RAML and gives out HTML
625941dd5f7d997b87174dba
def update_eyes(self, up_down_part, left_right_part): <NEW_LINE> <INDENT> if up_down_part and abs(up_down_part) > 5: <NEW_LINE> <INDENT> y = up_down_part/abs(up_down_part) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> y = 0 <NEW_LINE> <DEDENT> if left_right_part and abs(left_right_part) > 5: <NEW_LINE> <INDENT> x = lef...
Set self.looking value based on position of Pinky w/r/t Pacman
625941ddd268445f265b518e
def delete_ml_model(ml_model_id): <NEW_LINE> <INDENT> filters = {MLModel.id: ml_model_id} <NEW_LINE> MLModel.query.filter(*filters).delete() <NEW_LINE> db.session.commit()
删除 ml_model :param ml_model_id: :return:
625941dd94891a1f4081bdca
def parseCommand(self, cmdId=[], cmdData=[]): <NEW_LINE> <INDENT> if cmdId and cmdData and CmdDict[cmdId].messageFormat: <NEW_LINE> <INDENT> cmdBody = dict() <NEW_LINE> for i in range(len(CmdDict[cmdId].messageFormat)): <NEW_LINE> <INDENT> cmdBody[CmdDict[cmdId].messageFormat[i]] = cmdData[i] <NEW_LINE> <DEDENT> return...
Parses command data based on message format of command ID.
625941dd63d6d428bbe4480f
def setValue(self, value): <NEW_LINE> <INDENT> self.__value = value
Setter to set the value in our DataPair object.
625941dd6fb2d068a760f3c1
def parse_message(message): <NEW_LINE> <INDENT> if 'result' in message: <NEW_LINE> <INDENT> return __handle_subscription(message['result']) <NEW_LINE> <DEDENT> elif 'error' in message: <NEW_LINE> <INDENT> return message <NEW_LINE> <DEDENT> elif 'event' in message: <NEW_LINE> <INDENT> channel = '.'.join(message['event']...
Parses messages from resgate websocket and converts them to a more readable format subscription confirmation messages may contain multiple subscriptions and will be of the format: [[channel, 'subscribed', model-schema], [channel, 'subscribed', model-schema]] For example [['news.today', 'subscribed', {'message': 'Hello...
625941dd1d351010ab855e3b
def empty_datastore(): <NEW_LINE> <INDENT> return datastore.Client().get(datastore.Client().key("Data", 1)) is None
Verifies that the Cloud Datastore is empty
625941dd50485f2cf553d0bb
def test_get_contact_dist(self): <NEW_LINE> <INDENT> from allosmod.get_contacts import get_contact_dist <NEW_LINE> class Residue(object): <NEW_LINE> <INDENT> def __init__(self, av): <NEW_LINE> <INDENT> self.average = av <NEW_LINE> <DEDENT> <DEDENT> self.assertEqual(get_contact_dist(Residue(((0, 0, 0),)), Residue(((0, 5...
Test get_contact_dist()
625941dd8c3a8732951586dd
def __mul__(self, other): <NEW_LINE> <INDENT> return self.multiply(other)
Multiply two Gaussian distributions, or multiply a gaussian distribution with a matrix (as done during an affine transformation). Args: other (Gaussian, array_like of float[D,D]): Gaussian, or square matrix (to rotate or scale) Returns: Gaussian: resulting Gaussian distribution
625941dd7d43ff24873a2fc2
def __init__(self, armor=2): <NEW_LINE> <INDENT> Insect.__init__(self, armor)
Create a WallAnt with an ARMOR quantity.
625941dd8e05c05ec3eea697
def test_max_point_arc(self): <NEW_LINE> <INDENT> arc = Arc(2, 3, 0, 0.5, 5) <NEW_LINE> self.assertEqual(arc.max_point().x, 7) <NEW_LINE> self.assertEqual(arc.max_point().y, 8)
max_point() of an arc tracing bottom-right quarter
625941dd32920d7e50b284f2
def download(self, url, destination): <NEW_LINE> <INDENT> args = {"url": url, "destination": destination} <NEW_LINE> self._download_chk.check(args) <NEW_LINE> return self._client.raw("web.download", args)
download a file from the url and write it to the destination parent directory of destination MUST exists for this method to work
625941dd283ffb24f3c55c1e
def request( self, method, endpoint, params=None, data=None, files=None, response_type="json", ): <NEW_LINE> <INDENT> url = self._endpoint_to_url(endpoint) <NEW_LINE> if files is None: <NEW_LINE> <INDENT> headers = { "Accept": "application/json", "Content-Type": "application/json;charset=UTF-8", } <NEW_LINE> headers.up...
Make a request to the ICE server. This is a generic method used by all the subsequent methods, and wraps the ``requests.request`` method Examples -------- >>> ice = IceClient(...) >>> ice.request("GET", "GET", "folders/12/entries", params=dict(limit=20)) Parameters ---------- method One of "GET"...
625941dd99cbb53fe6792f06
def get_nrotor(x): <NEW_LINE> <INDENT> if isinstance(x, str): <NEW_LINE> <INDENT> mol = get_mol(x, make3D=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mol = get_mol(x) <NEW_LINE> <DEDENT> return mol.OBMol.NumRotors()
Return number of rotors.
625941ddd8ef3951e324385e
def test_conditional_switch_autocontinue_ci_not_active(self) -> None: <NEW_LINE> <INDENT> given = copy.deepcopy(self.our_config) <NEW_LINE> given["cli_testing"]["ci"]["active"] = False <NEW_LINE> given["cli_testing"]["autocontinue"] = False <NEW_LINE> expected = copy.deepcopy(given) <NEW_LINE> actual = self.config_load...
Tests the method which let us switch some of our values based on some assumption. In this test, we check the the autocontinue is getting activated if we are under CI.
625941ddcdde0d52a9e53354
def test_psi(): <NEW_LINE> <INDENT> sfreq = 50. <NEW_LINE> n_signals = 3 <NEW_LINE> n_epochs = 10 <NEW_LINE> n_times = 500 <NEW_LINE> rng = np.random.RandomState(42) <NEW_LINE> data = rng.randn(n_epochs, n_signals, n_times) <NEW_LINE> for i in range(n_epochs): <NEW_LINE> <INDENT> data[i, 1, 10:] = data[i, 0, :-10] <NEW...
Test Phase Slope Index (PSI) estimation
625941dd4f88993c3716c385
def process_sky(data, skycs, skyls): <NEW_LINE> <INDENT> mtr = "" <NEW_LINE> for i, (skyc, skyl) in enumerate(zip(skycs, skyls)): <NEW_LINE> <INDENT> if skyc == "": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> data[f"skyc{i + 1}"] = skyc <NEW_LINE> if skyc != "CLR": <NEW_LINE> <INDENT> data[f"skyl{i + 1}"] = float(...
Process the sky cover
625941dd442bda511e8be734
def ensure_dir(path, create=True): <NEW_LINE> <INDENT> if not Path(path).exists(): <NEW_LINE> <INDENT> if create: <NEW_LINE> <INDENT> logging.info(f'Creating new path {path}') <NEW_LINE> os.makedirs(path) <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.info(f'Path {path} does not exist, and...
Check that the given path exists, optionally creating it if not :param path: path to check :param create: create directories if not present :return: False if the path didn't exist and we didn't create it, or it existed already and was a file
625941dd30c21e258bdfa7bf
def oyuncuBıraktı(self): <NEW_LINE> <INDENT> pass
Oyuncu bu nesneyi bıraktığında çalıştırılacak betik
625941dd3d592f4c4ed1d387
def __init__(self): <NEW_LINE> <INDENT> super(USCitiesHTMLParser, self).__init__() <NEW_LINE> self.states = None <NEW_LINE> self._open_state = False <NEW_LINE> self._reading_cities = False
Initialize parser state that keeps track of the document tree and the collected results.
625941dd32920d7e50b284f3
def optibubbulesort(numList): <NEW_LINE> <INDENT> for i in range (len(numList) -1): <NEW_LINE> <INDENT> bbalance = False <NEW_LINE> for j in range(i,len(numList)-1): <NEW_LINE> <INDENT> if numList[j] > numList [j+1]: <NEW_LINE> <INDENT> numList[j],numList[j+1] = numList[j+1],numList[j] <NEW_LINE> bbalance = True <NEW_L...
优化后 :param numList: :return:
625941dddd821e528d63b4c7
def matrix_translate_2d(x, y): <NEW_LINE> <INDENT> return ((1.0, 0, x), (0, 1.0, y))
Create a transform matrix to translate (move). :param x: translation along X axis :param y: translation along Y axis
625941dd167d2b6e31218eb5
def link(text=None, structure=False, title=None, css_class=None, icon=0, preview=0, **args): <NEW_LINE> <INDENT> pass
Returns an HTML link tag for the file or image.
625941dd56ac1b37e62644ea
def copy(self, dc_id=None): <NEW_LINE> <INDENT> new_obj = DrawingCommand(self.action, dc_id=dc_id) <NEW_LINE> new_obj.prev_select = self.prev_select <NEW_LINE> new_obj.new_select = self.new_select <NEW_LINE> new_obj.prev_markers = DmMarker.copy_markers(self.prev_markers) <NEW_LINE> new_obj.new_markers = DmMarker.copy_m...
Make copy - new unique object unless dc_id passed in
625941dd1f037a2d8b94651d
def __init__(self, access_key=None, secret=None): <NEW_LINE> <INDENT> access_key = access_key or os.getenv('VEN_S3_ACCESS_KEY') <NEW_LINE> secret = secret or os.getenv('VEN_S3_SECRET') <NEW_LINE> self.connection = boto.dynamodb2.connect_to_region(region_name='eu-west-1', aws_access_key_id=access_key, aws_secret_access_...
If access_key and/or secret are not passed in, assumes we are accessing erenev's aws account and that the access info is stored as environment variables on the current server. Connection and Table are available to clients via self properties, in case clients wish to use those objects directly.
625941dd15baa723493c4297
def diagonalize(self, eigenvectors, eigenvalues): <NEW_LINE> <INDENT> O_diag = self.diag_descr.empty(dtype=float) <NEW_LINE> if self.matrix_descr.blacsgrid.is_active(): <NEW_LINE> <INDENT> O_orig = eigenvectors <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> O_orig = np.empty((0,0), dtype=float) <NEW_LINE> <DEDENT> self....
Diagonalize symmetric distributed Casida matrix using Scalapack. Parameters: eigenvectors distributed Casida matrix on input, distributed eigenvectors on output eigenvalues zero array on input, eigenvalues on output
625941dd3346ee7daa2b308e
@app.route("/resources/<int:resource_numerical_id>/edit", methods=["GET"]) <NEW_LINE> def show_edit_resource_form(resource_numerical_id): <NEW_LINE> <INDENT> resource = Resource.query.get(resource_numerical_id) <NEW_LINE> user = User.query.get(resource.user_id) <NEW_LINE> if "id" not in session or user.id != session['i...
Show resource edit form
625941dd711fe17d82542685
def test_dbt(self): <NEW_LINE> <INDENT> engine = create_engine('postgresql://peiyan:peiyan@localhost:8000/peiyan') <NEW_LINE> db_points = pd.read_sql_query("select price from restaurant where id='tacorea-san-francisco';",con=engine) <NEW_LINE> result = db_points['price'].iloc[0] <NEW_LINE> self.assertIn("$", result)
Test read from db
625941dda8ecb033257d33ec
def test_add_a_customer(self): <NEW_LINE> <INDENT> customers = Customer.all() <NEW_LINE> self.assertEqual(customers, []) <NEW_LINE> customer = Customer( name="Alex", address="Washington Square Park", phone_number="555-555-1234", email="alex@jr.com", credit_card="VISA", active = True ) <NEW_LINE> self.assertTrue(custome...
Create a customer and add it to the database
625941ddd99f1b3c44c678aa
def info(self): <NEW_LINE> <INDENT> return str({'Test Plan': self.synapsert.get_issue_key(self.test_plan), 'Test Case': self.synapsert.get_issue_key(self.subtest), 'Platform': self.platform, 'Option append_tcs': self.append_tcs, 'Option force_update': self.force_update, })
Return report settings.
625941ddd53ae8145f87a58b
def pageSize(self): <NEW_LINE> <INDENT> return QSizeF(self.pageWidth, self.pageHeight)
Return our natural page size (QSizeF). This value is only used in the computeSize() method, to get the size in pixels of the page. By the default implementation of computeSize(), the page size is assumed to be in points, 1/72 of an inch.
625941ddc432627299f04f68
def _py2_and_3_joiner(sep, joinable): <NEW_LINE> <INDENT> if IS_PY3: <NEW_LINE> <INDENT> sep = bytes(sep, DEFAULT_ENCODING) <NEW_LINE> <DEDENT> joined = sep.join(joinable) <NEW_LINE> return joined.decode(DEFAULT_ENCODING) if IS_PY3 else joined
Allow ' '.join(...) statements to work in Py2 and Py3. :param sep: :param joinable: :return:
625941dd57b8e32f524837bd
def tail_call_optimized(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def _wrapped(*args, **kwargs): <NEW_LINE> <INDENT> frame = sys._getframe() <NEW_LINE> if frame.f_back and frame.f_back.f_back and frame.f_back.f_back.f_code == frame.f_code: <NEW_LINE> <INDENT> raise TailRecurseException(args, kwargs) <NEW_LINE>...
This function decorates a function with tail call optimization. It does this by throwing an exception if it is it's own grandparent, and catching such exceptions to fake the tail call optimization. This function fails if the decorated function recurses in a non-tail context.
625941dd63b5f9789fde7406
def _get_job_counts(query_params): <NEW_LINE> <INDENT> queries = [] <NEW_LINE> query_params["job_id"] = query_params["_id"]["$oid"] <NEW_LINE> query_str = "status=%(status)s&job=%(job)s&kernel=%(kernel)s" <NEW_LINE> total_query_str = "job=%(job)s&kernel=%(kernel)s" % query_params <NEW_LINE> queries.append({ "method": "...
Retrieve the builds and boots count. :param query_params: The result from the previous query to be used as parameter. :type query_params: dict :return: A dictionary with the buils and boots count.
625941dde8904600ed9f2251
def get_groups(self, *args): <NEW_LINE> <INDENT> if len(args) == 0: <NEW_LINE> <INDENT> args = self._options_dict.keys() <NEW_LINE> <DEDENT> options = {} <NEW_LINE> for group in args: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for option, value in self._options_dict[group].items(): <NEW_LINE> <INDENT> if option not i...
Returns options as a dictionary. Returns options from all the groups specified as arguments, returns the options from all groups if no argument provided. Options are overridden when they are found in the next group. *args[in] Each group to be returned can be requested by providing its name as an argum...
625941ddac7a0e7691ed43e7
@app.route('/currentFolderSize', methods=['GET']) <NEW_LINE> def get_current_folder_size(): <NEW_LINE> <INDENT> return str(file_system[request.args['side']].get_current_folder_size())
brief: Get a string, representing the size (with units) of the current folder. handled methods: - GET: get the size of the current folder for the selected size.
625941dd0a50d4780f6671b5
def test_maui_data_source_name(init): <NEW_LINE> <INDENT> with expected_protocol(ik.teledyne.MAUI, [init], [], sep="\n") as osc: <NEW_LINE> <INDENT> assert osc.math[0].name == "F1" <NEW_LINE> assert osc.channel[1].name == "C2"
Return the name of the channel in the data source.
625941dd71ff763f4b5499b1
def fitgaussian(pixels, params, fixed=None, maxfev=0): <NEW_LINE> <INDENT> fixed = fixed or {} <NEW_LINE> initial = [] <NEW_LINE> for param in FIT_PARAMS: <NEW_LINE> <INDENT> if param not in fixed: <NEW_LINE> <INDENT> if hasattr(params[param], "value"): <NEW_LINE> <INDENT> initial.append(params[param].value) <NEW_LINE>...
Calculate source positional values by fitting a 2D Gaussian Args: pixels (numpy.ma.MaskedArray): Pixel values (with bad pixels masked) params (dict): initial fit parameters (possibly estimated using the moments() function, above) Kwargs: fixed (dict): parameters & their values to be kept frozen (...
625941dd498bea3a759b9dcf
def allow_syncdb(self, db, model): <NEW_LINE> <INDENT> if model._meta.app_label in ['south']: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if db == 'case': <NEW_LINE> <INDENT> return model._meta.app_label == 'case' <NEW_LINE> <DEDENT> elif model._meta.app_label == 'case': <NEW_LINE> <INDENT> return False <NEW_LI...
Make sure the case app only appears on the 'case' db
625941dd097d151d1a223178
def get_presence(self): <NEW_LINE> <INDENT> return self._fan_list[0].get_presence()
Retrieves the presence of the FAN Returns: bool: True if FAN is present, False if not
625941dd7cff6e4e81117ca6
def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.id = kwargs.get('id') <NEW_LINE> VapiStruct.__init__(self, {})
Initialize StrataQueryId @type id: C{str} @kwarg id: ID value
625941dd23849d37ff7b33ad
def runner(): <NEW_LINE> <INDENT> petrov = Person("Petrov", "Peter", "1979-11-30") <NEW_LINE> petrov.get_fullname() <NEW_LINE> petrov.get_age() <NEW_LINE> sidorov = Person("Sidorov", "Sid", "1977-01-17", "Sider") <NEW_LINE> sidorov.get_fullname() <NEW_LINE> sidorov.get_age()
Запускает выполнение всех задач
625941dd8e71fb1e9831dac8
def _construct_url_1(self, obj, config_only=True): <NEW_LINE> <INDENT> obj_class = obj.get('aci_class') <NEW_LINE> obj_rn = obj.get('aci_rn') <NEW_LINE> obj_filter = obj.get('target_filter') <NEW_LINE> mo = obj.get('module_object') <NEW_LINE> if self.module.params.get('state') in ('absent', 'present'): <NEW_LINE> <INDE...
This method is used by construct_url when the object is the top-level class.
625941dd5510c4643540f6fd
def plot_soil_param(ax, plt): <NEW_LINE> <INDENT> simple_axis(ax) <NEW_LINE> ax.set_ylabel('') <NEW_LINE> ax.set_xlabel('')
Plot soil temperature for different sites, depths input: plt: matplotlib object leg_labels: Name of legend entries file_name: output file name for image
625941dde5267d203edcdfba
def _next_internal(self): <NEW_LINE> <INDENT> with context.execution_mode(context.SYNC): <NEW_LINE> <INDENT> with ops.device(self._device): <NEW_LINE> <INDENT> ret = gen_dataset_ops.iterator_get_next_sync( self._iterator_resource, output_types=self._flat_output_types, output_shapes=self._flat_output_shapes) <NEW_LINE> ...
Returns a nested structure of `tf.Tensor`s containing the next element.
625941dd94891a1f4081bdcb
def test_checkDiskForFile_DBTrue_FileFalse_FixTrue(self): <NEW_LINE> <INDENT> os.remove(self.td + '/L0/testDB_001_001.raw') <NEW_LINE> self.assertTrue(self.dbu.checkDiskForFile(1, True))
Check consistency between FS and DB, correct DB
625941dd91f36d47f21ac816
def reset_pass(headers, user): <NEW_LINE> <INDENT> url = str(public_baseurl) + '/_synapse/admin/v2/users/' + user <NEW_LINE> passw = getpass.getpass('Please enter new password for ' + user + ': ') <NEW_LINE> json = {'password': passw, 'logout_devices': True} <NEW_LINE> put(headers, url, json)
Resets a Synapse user's password
625941dd6aa9bd52df0370c6
def merge(self, method=0, fill_value=None, interpolation_samples=0, **kwargs): <NEW_LINE> <INDENT> def listsort(order, current): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return order.index(current) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> <DEDENT> self._cleanup(**kwar...
Merge ObsPy Trace objects with same IDs. :type method: int, optional :param method: Methodology to handle overlaps/gaps of traces. Defaults to ``0``. See :meth:`obspy.core.trace.Trace.__add__` for details on methods ``0`` and ``1``, see :meth:`obspy.core.stream.Stream._cleanup` for details on metho...
625941dd4527f215b584c774
def callback_output_decorator(func): <NEW_LINE> <INDENT> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> print("\033[33mSignal: %s" % (func.__name__.replace("_", " ")[:-9]).title()) <NEW_LINE> print("Parameters Passed in:") <NEW_LINE> print(*("%s--->%s" % i for i in kwargs.items()), sep="\n") <NEW_LINE> func(*args, *...
print all the parameters passed to a receiver(callbacks) by sender
625941dd16aa5153ce362798
@cli.command() <NEW_LINE> @click.argument("title",type=str) <NEW_LINE> @click.option("--content",type=str,default="") <NEW_LINE> @click.option("--id",type=int,default=-1) <NEW_LINE> def add(title,content,id): <NEW_LINE> <INDENT> addOneIssueData(title,content,id) <NEW_LINE> click.echo("success! {title}".format(title=tit...
issue情報を追加
625941dd82261d6c526ab7c4
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, StataView): return False <NEW_LINE> if (not len(self._rownums) == len(other._rownums) or not len(self._colnums) == len(other._colnums)): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> rows1, cols1 = self._rownums, self._colnums <NEW_LINE> rows2...
determine if self is equal to other
625941ddbe7bc26dc91cd91b
def connect_rule(): <NEW_LINE> <INDENT> conn = pymysql.connect(host="192.168.2.137", port=3306, user="root", passwd="123456", db="taobao", charset="utf8") <NEW_LINE> return conn
定义需要链接的数据库 :return:
625941ddbd1bec0571d9094f
def decode(self,g): <NEW_LINE> <INDENT> output = u"" <NEW_LINE> for line in g: <NEW_LINE> <INDENT> if line: <NEW_LINE> <INDENT> fields = line.split(u"\t") <NEW_LINE> if fields[-1] == '1': <NEW_LINE> <INDENT> output += u"-" <NEW_LINE> output += fields[0] <NEW_LINE> <DEDENT> elif fields[-1] == '0': <NEW_LINE> <INDENT> ou...
Decodes a labelled hyphenation sequence for printing.
625941ddf548e778e58cd8a0