code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_all_tags(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.get_all_tags_with_http_info(**kwargs)
Get all 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_all_tags(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param int o...
625941d27b180e01f3dc49b5
def test_version(self): <NEW_LINE> <INDENT> server = self.server <NEW_LINE> server.connect() <NEW_LINE> self.assertFalse(server.check_version_compat((7, 0, 0))) <NEW_LINE> self.assertFalse(server.check_version_compat((6, 0, 0)))
Check MySQLServer's version.
625941d2442bda511e8be5d1
def rpicamera_set_action(self, node_uuid, index, data): <NEW_LINE> <INDENT> params = {} <NEW_LINE> if data == "start_preview": <NEW_LINE> <INDENT> self.camera_start() <NEW_LINE> <DEDENT> elif data == "stop_preview": <NEW_LINE> <INDENT> self.camera_stop()
Act on the server
625941d2ac7a0e7691ed4283
def as_p(self): <NEW_LINE> <INDENT> return self._html_output( normal_row='<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>', error_row='%s', row_ender='</p>', help_text_html=' <span class="helptext">%s</span>', errors_on_separate_row=True)
Returns this form rendered as HTML <p>s.
625941d292d797404e304344
def test_locate_handler_for_call_when_no_respondents_of_low_rank_available(self): <NEW_LINE> <INDENT> self.call_handler.add_respondent(self.mock_respondent) <NEW_LINE> self.mock_respondent.rank = 1 <NEW_LINE> self.assertFalse(self.call_handler.locate_handler_for_call(0),msg='must be able to find respondent none availab...
increase the rank of the only available respondent, the locate_handler_for_call should not return an respondent
625941d2d58c6744b4257e19
def cdf(data_r, data_f, xlabel: str = 'Values', ylabel: str = 'Cumulative Sum', ax=None): <NEW_LINE> <INDENT> x1 = np.sort(data_r) <NEW_LINE> x2 = np.sort(data_f) <NEW_LINE> y = np.arange(1, len(data_r) + 1) / len(data_r) <NEW_LINE> ax = ax if ax else plt.subplots()[1] <NEW_LINE> axis_font = {'size': '14'} <NEW_LINE> a...
Plot continous density function on optionally given ax. If no ax, cdf is plotted and shown. :param data_r: Series with real data :param data_f: Series with fake data :param xlabel: Label to put on the x-axis :param ylabel: Label to put on the y-axis :param ax: The axis to plot on. If ax=None, a new figure is created.
625941d299fddb7c1c9de54a
def listdir(view, dir, base, ext, on_done): <NEW_LINE> <INDENT> if not os.path.isdir(dir): <NEW_LINE> <INDENT> sublime.status_message("Directory %s does not exist." % dir) <NEW_LINE> return <NEW_LINE> <DEDENT> ls = os.listdir(dir) <NEW_LINE> if ext: <NEW_LINE> <INDENT> fnames = [f for f in ls if os.path.splitext(f)[1]....
List a directory using quick panel
625941d2287bf620b61d3c1c
def read_htk(self, inputFileNmae, framePerSecond=100): <NEW_LINE> <INDENT> kinds=['WAVEFORM','LPC','LPREFC','LPCEPSTRA','LPDELCEP','IREFC','MFCC','FBANK','MELSPEC','USER','DISCRETE','PLP','ANON','???'] <NEW_LINE> with open(inputFileNmae, 'rb') as fid: <NEW_LINE> <INDENT> nf=struct.unpack(">l",fid.read(4))[0] <NEW_LINE>...
in: file name
625941d27cff6e4e81117b3f
def testSwishLiteHint(self): <NEW_LINE> <INDENT> image = array_ops.constant([1., 2., 3., 4.]) <NEW_LINE> swish_scale = array_ops.constant(1.0) <NEW_LINE> def _swish(input_tensor, scale): <NEW_LINE> <INDENT> custom = op_hint.OpHint("cool_activation") <NEW_LINE> input_tensor, scale = custom.add_inputs(input_tensor, scale...
Makes a custom op swish and makes sure it gets converted as a unit.
625941d263d6d428bbe446a9
def _getAndCacheApiData(tickers, api_key, cache_folder): <NEW_LINE> <INDENT> ticker_data = {} <NEW_LINE> for t, ticker in enumerate(tickers): <NEW_LINE> <INDENT> print('Getting ticker %s (%d/%d)' % (ticker, t + 1, len(tickers))) <NEW_LINE> data = _getAllApiData(ticker, api_key) <NEW_LINE> data_json = json.dumps(data) <...
Get API data for all tickers, cache it, and return it. Args: tickers: Iterable of ticker strings. api_key: String API key for authentication. cache_folder: Where to store cache files. Returns: ticker_data: See _getAllApiData for format.
625941d2004d5f362079a4ec
def get_settings(self) -> Dict[str, Any]: <NEW_LINE> <INDENT> return self.execute(Command.GET_SETTINGS, {})['value']
Returns the appium server Settings for the current session. Do not get Settings confused with Desired Capabilities, they are separate concepts. See https://github.com/appium/appium/blob/master/docs/en/advanced-concepts/settings.md Returns: Current settings
625941d2cc0a2c11143dd04a
def confidenceIntervals(self, alpha): <NEW_LINE> <INDENT> t = stats.t.ppf(1.0-alpha/2., self._linearModel.degreesOfFreedom()) <NEW_LINE> lowerBounds = self.regressionCoefficients() - t * self.errorBars() <NEW_LINE> upperBounds = self.regressionCoefficients() + t * self.errorBars() <NEW_LINE> return lowerBounds, upperBo...
Returns the symmetric (1-alpha) confidence interval around the fit coefficients E.g. if alpha = 0.05, the 95% symmetric confidence interval is returned. Remarks: - The formula used assumes that the noise on the observations is independently, identically and gaussian distributed. @...
625941d2c432627299f04e00
def message_from_oscsysexpayload(payload): <NEW_LINE> <INDENT> payload = payload.lower() <NEW_LINE> if len(payload) < 2: <NEW_LINE> <INDENT> raise ValueError("sysex too short") <NEW_LINE> <DEDENT> elif not payload.startswith('f0'): <NEW_LINE> <INDENT> raise ValueError("sysex doesn't start with F0") <NEW_LINE> <DEDENT> ...
Convert the OSC string into a mido sysex message.
625941d230dc7b7665901b20
def remote(self, key): <NEW_LINE> <INDENT> return self._run('remote {}'.format(key))
Send remote key press.
625941d2cb5e8a47e48b7c63
def process_song_file(cur, filepath): <NEW_LINE> <INDENT> df = pd.read_json(path_or_buf=filepath, lines=True) <NEW_LINE> song_cols = ["song_id", "title", "artist_id", "year", "duration"] <NEW_LINE> song_data = df[song_cols].values[0].tolist() <NEW_LINE> cur.execute(song_table_insert, song_data) <NEW_LINE> artist_cols =...
Function that reads a json song file, proccesses it and inserts it into a database into two tables. Parameters ---------- cur Cursor of the created database. filepath : str Filepath of the song json file.
625941d2e5267d203edcde56
def localMaxima(image): <NEW_LINE> <INDENT> if image.ndim != 2: <NEW_LINE> <INDENT> raise RuntimeError("localMaxima is currently only implemented for 2D images") <NEW_LINE> <DEDENT> return __peak_local_max(image, exclude_border=False, indices=False)
get the local maxima of an image Get the local maxima wrt a 4-neighborhood on an image. For a plateau, all pixels of this plateau are marked as maximum pixel. Args: image (numpy.ndarray): the input image Returns: (numpy.ndarray) : array which is 1 the maximum 0 elsewhere.
625941d266656f66f7cbc365
def next_indexes_time(lines, p_init, p_end, gap, section, cumulative, time_stamp): <NEW_LINE> <INDENT> time_elapsed = 0 <NEW_LINE> time, hrf = lines[p_init].split() <NEW_LINE> if cumulative: <NEW_LINE> <INDENT> time_stamp = float(time) <NEW_LINE> <DEDENT> while test_time_limit(cumulative, float(time), time_stamp, time_...
(int, int, int) -> (int, int) Take the last partitions initial and final indexes and return the next partition's indexes.
625941d26fece00bbac2d8f9
def predict_labels(self, dists, k=1): <NEW_LINE> <INDENT> num_test = dists.shape[0] <NEW_LINE> y_pred = np.zeros(num_test) <NEW_LINE> for i in range(num_test): <NEW_LINE> <INDENT> closest_y = [] <NEW_LINE> closet_y = self.y_train[np.argsort(dists[i,:])[:k]] <NEW_LINE> y_pred[i] = np.argmax(np.bincount(closet_y)) <NEW_L...
Given a matrix of distances between test points and training points, predict a label for each test point. Inputs: - dists: A numpy array of shape (num_test, num_train) where dists[i, j] gives the distance betwen the ith test point and the jth training point. Returns: - y: A numpy array of shape (num_test,) containi...
625941d22c8b7c6e89b3597a
def next_batch(self): <NEW_LINE> <INDENT> start = self._index_in_epoch <NEW_LINE> if self._epochs_completed == 0 and start == 0 and self.is_shuffle: <NEW_LINE> <INDENT> perm0 = np.arange(self._num_samples) <NEW_LINE> np.random.shuffle(perm0) <NEW_LINE> self._images = self._images[perm0] <NEW_LINE> self._labels = self._...
Return the next `batch_size` examples from this data set.
625941d257b8e32f52483656
def test_refmat(self): <NEW_LINE> <INDENT> v1 = Vector(0, 0, 1) <NEW_LINE> v2 = Vector(0, 1, 0) <NEW_LINE> ref = refmat(v1, v2) <NEW_LINE> self.assertTrue(numpy.allclose(ref[0], [1.0, 0.0, 0.0])) <NEW_LINE> self.assertTrue(numpy.allclose(ref[1], [0.0, 0.0, 1.0])) <NEW_LINE> self.assertTrue(numpy.allclose(ref[2], [0.0, ...
Test refmat can mirror one matrix to another.
625941d250812a4eaa59c4db
def _compare( left, right, left_label="left", right_label="right", drop_close=True, **kwargs ): <NEW_LINE> <INDENT> def as_series(s): <NEW_LINE> <INDENT> return s if isinstance(s, pd.Series) else s._data <NEW_LINE> <DEDENT> ret = pd.merge( left=as_series(left).rename(index=left_label), right=as_series(right).rename(ind...
Internal implementation of comparison of IamDataFrames or pd.Series
625941d2be8e80087fb20dfb
def Parse(self, inp): <NEW_LINE> <INDENT> if isinstance(inp, IntegerList): <NEW_LINE> <INDENT> return inp <NEW_LINE> <DEDENT> elif isinstance(inp, list): <NEW_LINE> <INDENT> return IntegerList(inp) <NEW_LINE> <DEDENT> elif isinstance(inp, int): <NEW_LINE> <INDENT> return IntegerList([inp]) <NEW_LINE> <DEDENT> def Handl...
Parse an integer list. Args: inp: a string, a list, or an IntegerList. Returns: An iterable of integers. Raises: ValueError if inp doesn't follow a format it recognizes.
625941d24f88993c3716c221
def unset_processor_affinity(self): <NEW_LINE> <INDENT> return _atsc_swig.atsc_bit_timing_loop_sptr_unset_processor_affinity(self)
unset_processor_affinity(atsc_bit_timing_loop_sptr self)
625941d29f2886367277aa47
def createKeyFile(): <NEW_LINE> <INDENT> randomDataGenerator = addon.getSetting(consts.randomNumberGenerator); <NEW_LINE> setting = getInformationFromUser(createKeyFile = True); <NEW_LINE> if setting == None: <NEW_LINE> <INDENT> return; <NEW_LINE> <DEDENT> success = tcitem.createKeyFile(setting[consts.keyFiles], random...
Method initializes creation of key file and gets path from user.
625941d2cad5886f8bd27193
def has_move(board: list, line: int, column: int) -> bool: <NEW_LINE> <INDENT> return len(get_adjacents(board, line, column)) > 0
Given a board with Black, White, and Empty Slot.Create function that calculates if starting from line and column defined as parameters there are empty slots that can be occupied. Imagine each player start with a position occupied.So the first can occupy any adjacent Empty slot.After that the second player can do the sa...
625941d29b70327d1c4e0f90
def log(message,loglevel=xbmc.LOGNOTICE): <NEW_LINE> <INDENT> xbmc.log(encode(__addon_id__ + u": " + message), level=loglevel)
"save message to xbmc.log. Args: message: has to be unicode, http://wiki.xbmc.org/index.php?title=Add-on_unicode_paths#Logging loglevel: xbmc.LOGDEBUG, xbmc.LOGINFO, xbmc.LOGNOTICE, xbmc.LOGWARNING, xbmc.LOGERROR, xbmc.LOGFATAL
625941d215fb5d323cde0ccb
def __init__(self, config = None): <NEW_LINE> <INDENT> self._config = config <NEW_LINE> Localization.setup() <NEW_LINE> Gtk.Dialog.__init__(self, _("Settings"), None, Gtk.DialogFlags.DESTROY_WITH_PARENT) <NEW_LINE> self.set_resizable(False) <NEW_LINE> close_button = self.add_button(Gtk.STOCK_CLOSE, Gtk.ResponseType.CLO...
Constructor.
625941d2b5575c28eb68e1bb
def Skeleton(image): <NEW_LINE> <INDENT> Image_Thinned = image.copy() <NEW_LINE> changing1 = changing2 = 1 <NEW_LINE> while changing1 or changing2: <NEW_LINE> <INDENT> changing1 = [] <NEW_LINE> rows, columns = Image_Thinned.shape <NEW_LINE> for x in range(1, rows - 1): <NEW_LINE> <INDENT> for y in range(1, columns - 1)...
the Zhang-Suen Thinning Algorithm
625941d2b545ff76a8913fd0
def __init__(self, cmd_string): <NEW_LINE> <INDENT> self.cmd_list = re.split("{{|}}", cmd_string) <NEW_LINE> if "add_item " not in self.cmd_list: <NEW_LINE> <INDENT> raise IOError("输入错误")
初始化cmd_list,如果没有“add_item”,判定输入错误 :param cmd_string:
625941d2498bea3a759b9c69
def __init__(self, nums): <NEW_LINE> <INDENT> if nums == []: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.nums_end = len(nums) - 1 <NEW_LINE> self.values = [0] * 4 * len(nums) <NEW_LINE> def build_segment_tree(pos, left, right): <NEW_LINE> <INDENT> if left == right: <NEW_LINE> <INDENT> self.values[pos] = nums[le...
建立分段树: 由于分段树最顶层的根节点存储的是[0,len(nums)]的区间和左子树存储的是[0,len(nums)/2]的区间和, 右子树存储[len(nums)/2+1,len(nums)]区间和,以此类推,所以可以用递归的方式建立 [0,len(nums)-1] / [0,len(nums)/2] [len(nums)/2+1,len(nums)] / ...
625941d226068e7796caee9b
def prime_colander(nums): <NEW_LINE> <INDENT> n = max(nums) <NEW_LINE> sieve = [True for _ in range(max(n + 1, 2))] <NEW_LINE> for i in range(2, int(pow(n, 0.5)) + 1): <NEW_LINE> <INDENT> if not sieve[i]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for j in range(i*i, n + 1, i): <NEW_LINE> <INDENT> sieve[j] = Fals...
Discart NO prime number
625941d23eb6a72ae02ec69a
def test_multiple_rules(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> lim = limits.Limiter.parse_limits( '(get, *, .*, 20, minute);' '(PUT, /foo*, /foo.*, 10, hour);' '(POST, /bar*, /bar.*, 5, second);' '(Say, /derp*, /derp.*, 1, day)') <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> assert False,...
Test that parse_limits() handles multiple rules correctly.
625941d20383005118ecf79c
def get_winner(self): <NEW_LINE> <INDENT> return self.__winner
Returns the winner of the raffle. :return:
625941d2596a897236089c7a
def send_sms(self, to: str, message: str) -> str: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = self.client.messages.create( to=to, from_=self.TWILIO_SEND_FROM, body=message) <NEW_LINE> return response.sid <NEW_LINE> <DEDENT> except TwilioException as error: <NEW_LINE> <INDENT> raise TwilioGatewayError(error)
Send SMS :param to: int :param message: int :return: str
625941d271ff763f4b549847
def fit_model(model, X, y): <NEW_LINE> <INDENT> n_folds = 3 <NEW_LINE> skf = StratifiedKFold(y, n_folds=n_folds) <NEW_LINE> models, measures = [], [] <NEW_LINE> for train_index, test_index in skf: <NEW_LINE> <INDENT> X_train, X_test = X[train_index], X[test_index] <NEW_LINE> y_train, y_test = y[train_index], y[test_ind...
Function to fit the model we want.
625941d2d486a94d0b98e300
def offending_op(self): <NEW_LINE> <INDENT> return type(self.r.owner.op)
Return the Op class whose c_code and perform implementations didn't match.
625941d2090684286d50eea1
def deactivate(self): <NEW_LINE> <INDENT> if not self._optional: <NEW_LINE> <INDENT> self._optional = True <NEW_LINE> <DEDENT> self._activated = False
Set the dependency as optional.
625941d2dd821e528d63b363
def test_create_tpu_estimator_and_inputs(self): <NEW_LINE> <INDENT> run_config = tpu_config.RunConfig() <NEW_LINE> hparams = model_hparams.create_hparams( hparams_overrides='load_pretrained=false') <NEW_LINE> pipeline_config_path = get_pipeline_config_path(MODEL_NAME_FOR_TEST) <NEW_LINE> train_steps = 20 <NEW_LINE> tra...
Tests that number of train/eval defaults to config values.
625941d232920d7e50b2838b
def handle_event(self, topic, properties): <NEW_LINE> <INDENT> self.last_event = topic <NEW_LINE> self.last_props = properties <NEW_LINE> self.__event.set()
Handles an event received from EventAdmin
625941d26e29344779a627cc
def get_asset_record(self, asset_record_type): <NEW_LINE> <INDENT> return
Gets the asset record corresponding to the given ``Asset`` record ``Type``. This method is used to retrieve an object implementing the requested record. The ``asset_record_type`` may be the ``Type`` returned in ``get_record_types()`` or any of its parents in a ``Type`` hierarchy where ``has_record_type(asset_record_ty...
625941d232920d7e50b2838c
def get_volume_histogram(objName, bins=64, range=None, _self=cmd): <NEW_LINE> <INDENT> r = DEFAULT_ERROR <NEW_LINE> try: <NEW_LINE> <INDENT> _self.lock(_self) <NEW_LINE> r = _self._cmd.get_volume_histogram(_self._COb,objName, int(bins), range or (0., 0.)) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> _self.unlock(r,...
DESCRIPTION API ONLY. Get min, max, mean, stdev and histogram of a map or volume object as a list of length bins + 4.
625941d291f36d47f21ac6ae
def _process_data_arg(self, arg): <NEW_LINE> <INDENT> string = None <NEW_LINE> try: <NEW_LINE> <INDENT> res_str = arg if not self._is_dict(arg) else self._json_handler(arg) <NEW_LINE> string = base64.b64encode(res_str.encode('utf-8')).decode('ascii') <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise ...
Given either a dict or str: - If str, b64 encode to string - If dict, convert to json and b64 encode to ascii string
625941d266673b3332b9224c
def getPosts(how_many): <NEW_LINE> <INDENT> pass
Retrieve 'how_many' posts from the database.
625941d221bff66bcd684b0c
def lexical_similarity(words_list): <NEW_LINE> <INDENT> total_similarity = 0 <NEW_LINE> for word1 in words_list: <NEW_LINE> <INDENT> word_similarity = 0 <NEW_LINE> for word2 in words_list: <NEW_LINE> <INDENT> if(word1 != word2): <NEW_LINE> <INDENT> synset1 = wn.synsets(word1) <NEW_LINE> synset2 = wn.synsets(word2) <NEW...
computes the lexical_similarity scores of each of the sentence comparing it's words :param words_list : list of the words of the current sentence :return : lexical_similarity score
625941d231939e2706e4d023
def manhattan_distance(vec1, vec2, weights=None): <NEW_LINE> <INDENT> utils.check_for_none(vec1, vec2) <NEW_LINE> utils.check_for_type(list, vec1, vec2) <NEW_LINE> if weights: <NEW_LINE> <INDENT> utils.check_for_type(list, weights) <NEW_LINE> <DEDENT> if len(vec1) != len(vec2): <NEW_LINE> <INDENT> raise ValueError('vec...
Manhattan distance. Args: vec1 (list): Vector 1. List of integer or float. vec2 (list): Vector 2. List of integer or float. It should have the same length to vec1. weights (list): Weights for each value in vectors. If it's None, all weights will be 1.0. Defaults to None. Returns: float: Manhattan dist...
625941d2566aa707497f4722
def flushall(self, async_op=False): <NEW_LINE> <INDENT> if async_op: <NEW_LINE> <INDENT> fut = self.execute(b'FLUSHALL', b'ASYNC') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fut = self.execute(b'FLUSHALL') <NEW_LINE> <DEDENT> return wait_ok(fut)
Remove all keys from all databases. :param async_op: lets the entire dataset to be freed asynchronously. Defaults to False
625941d25fcc89381b1e187a
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(GoalStatusArray, self).__init__(*args, **kwds) <NEW_LINE> if self.header is None: <NEW_LINE> <INDENT> self.header = std_msgs.msg.Header() <NEW_LINE> <DEDENT> if self.status_list is None: <NEW_LINE> <INDENT> self.status_lis...
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: header,status_list :param args: c...
625941d2cdde0d52a9e531ef
def search(uri=None, user=None, tags=None, text=None, sort='updated', order='desc', after=None, auth=None): <NEW_LINE> <INDENT> search_args = {} <NEW_LINE> if uri is not None: <NEW_LINE> <INDENT> if not isinstance(uri, six.string_types): <NEW_LINE> <INDENT> raise TypeError('uri must be a string') <NEW_LINE> <DEDENT> se...
Search for annotations. Returns a SearchResults object. Supported arguments: uri user tags text sort, order, and after (for search_after) are also supported.
625941d23eb6a72ae02ec69b
def get_preds(attributes, targets, model): <NEW_LINE> <INDENT> splits = cv.train_test_split(attributes, targets, test_size=0.2) <NEW_LINE> X_train, X_test, y_train, y_test = splits <NEW_LINE> model.fit(X_train, y_train) <NEW_LINE> y_true = y_test <NEW_LINE> y_pred = model.predict(X_test) <NEW_LINE> return (y_true,y_pre...
Executes classification or regression using the specified model and returns expected and predicted values. Useful for comparison plotting.
625941d2b830903b967e9ac5
def enter(self): <NEW_LINE> <INDENT> pass
Called by the commander when transitioning to this state.
625941d28c0ade5d55d3eb76
def __init__(__self__, *, api_id: Optional[pulumi.Input[str]] = None, arn: Optional[pulumi.Input[str]] = None, data_source: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, function_id: Optional[pulumi.Input[str]] = None, function_version: Optional[pulumi.Input[str]] = None, max_batc...
Input properties used for looking up and filtering Function resources. :param pulumi.Input[str] api_id: The ID of the associated AppSync API. :param pulumi.Input[str] arn: The ARN of the Function object. :param pulumi.Input[str] data_source: The Function DataSource name. :param pulumi.Input[str] description: The Functi...
625941d229b78933be1e5865
def repair(self): <NEW_LINE> <INDENT> if not self.usable: <NEW_LINE> <INDENT> self.usable = True <NEW_LINE> print("Your {0} has been repaired".format(self.name)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Your {0} does not need to be repaired".format(self.name))
Repair the Metal Key if damaged, and allow use.
625941d2f548e778e58cd739
def test_pk_hidden_fields(self): <NEW_LINE> <INDENT> story1 = Story.objects.create(title='The adventures of Guido', content='Once upon a time in Djangoland...') <NEW_LINE> story2 = Story.objects.create( title='Crouching Tiger, Hidden Python', content='The Python was sneaking into...', ) <NEW_LINE> response = self.clien...
hidden pk fields aren't displayed in the table body and their corresponding human-readable value is displayed instead. The hidden pk fields are displayed but separately (not in the table) and only once.
625941d276d4e153a657ecec
def test_escapes(self): <NEW_LINE> <INDENT> self.assertEqual( lexer.tokenize(r'"\"\\\n\\t"', ""), [Token(token_kinds.string, [ord('"'), ord("\\"), ord("\n"), ord("\\"), ord("t"), 0] )])
Test tokenizing strings with escapes. This is testing the string: " \" \\ \n \\t " without the spaces.
625941d263f4b57ef00012d2
def _fetch_info(self) -> DeviceInfo: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> info = super()._fetch_info() <NEW_LINE> return info <NEW_LINE> <DEDENT> except (TypeError, DeviceInfoUnavailableException): <NEW_LINE> <INDENT> def create_dummy_mac(addr): <NEW_LINE> <INDENT> from ipaddress import ip_address <NEW_LINE> ip...
Return info about the device. This is overrides the base class info to account for gen1 devices that do not respond to info query properly when not connected to the cloud.
625941d24f6381625f114bf6
def getAround(self, pos, withPonderation = False): <NEW_LINE> <INDENT> if withPonderation: <NEW_LINE> <INDENT> res = [] <NEW_LINE> for curPos, ponderation in self.mapTypeInst.getAround(pos, True): <NEW_LINE> <INDENT> if self.isValid(curPos): <NEW_LINE> <INDENT> res.append((curPos, ponderation)) <NEW_LINE> <DEDENT> <DED...
Return position around this one Begin the hexa part
625941d2283ffb24f3c55abb
def targets(self) -> List[PBXNativeTarget]: <NEW_LINE> <INDENT> return list(self.fetch_type(PBXNativeTarget).values())
Get the targets. :returns: A list of targets
625941d276e4537e8c35182e
def _valid_generated_by(self, table_json): <NEW_LINE> <INDENT> if not table_json['generated_by']: <NEW_LINE> <INDENT> return "'generated_by' is not populated" <NEW_LINE> <DEDENT> if not isinstance(table_json['generated_by'], unicode): <NEW_LINE> <INDENT> return "'generated_by' is not a string" <NEW_LINE> <DEDENT> retur...
Validate the generated_by field
625941d2aad79263cf390bfd
def __file(self, header): <NEW_LINE> <INDENT> parent = self.__parents[_int(self.__read((header >> 4 & 7) + 1))] <NEW_LINE> name = self.__read(_int(self.__read((header >> 3 & 1) + 1))) <NEW_LINE> destination = open(_os.path.join(parent, name), 'wb') <NEW_LINE> data_size = _int(self.__read((header & 7) + 1)) <NEW_LINE> t...
Private class method.
625941d201c39578d7e74ff6
def getId(self): <NEW_LINE> <INDENT> if (self.config['disk_id'] is None): <NEW_LINE> <INDENT> self.config['disk_id'] = self._getAvailableId() <NEW_LINE> <DEDENT> return self.config['disk_id']
Returns the disk ID of the current disk, generating a new one if there is not already one present
625941d223849d37ff7b324a
def to_string(self): <NEW_LINE> <INDENT> a = list() <NEW_LINE> for name in self._sections: <NEW_LINE> <INDENT> section = self.get_section(name) <NEW_LINE> a.append(section.to_string()) <NEW_LINE> <DEDENT> return "\n".join(a)
Get the config as a string. :rtype: str
625941d25e10d32532c5f0e2
def zapisz_s_polaczone_komorki(self, akt_wiersz, akt_kolumna, the_content, the_style, liczba_kolumn=1, liczba_wierszy=1): <NEW_LINE> <INDENT> m_coor = to_kw.MergedCoords(akt_wiersz, akt_kolumna, liczba_kolumn, liczba_wierszy) <NEW_LINE> self.write_unicode(m_coor, the_content, the_style)
WriterGateway:
625941d24c3428357757c4e2
def getTrimmedCurve(e): <NEW_LINE> <INDENT> edges = e.toNurbs().Edges <NEW_LINE> c = edges[0].Curve.copy() <NEW_LINE> if len(edges) > 1: <NEW_LINE> <INDENT> FreeCAD.Console.PrintWarning("Trimming input edge returns multiple edges !\n") <NEW_LINE> for edge in edges[1:]: <NEW_LINE> <INDENT> c.join(edge.Curve) <NEW_LINE> ...
Get a trimmed BSpline curve from an edge.
625941d291af0d3eaac9bbd5
def get_custom_objects(custom_objects=None): <NEW_LINE> <INDENT> tfl_custom_objects = { 'AggregateFunction': AggregateFunction, 'AggregateFunctionConfig': configs.AggregateFunctionConfig, 'Aggregation': aggregation_layer.Aggregation, 'BiasInitializer': kfll.BiasInitializer, 'CalibratedLatticeEnsemble': CalibratedLattic...
Creates and returns a dictionary mapping names to custom objects. Args: custom_objects: Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization. If provided, the returned mapping will be extended to contain this one. Returns: A dictionary mapping ...
625941d2e5267d203edcde57
def score_grad_variance_callback(my_model): <NEW_LINE> <INDENT> params = my_model.collect_params() <NEW_LINE> param_grads = collections.defaultdict(lambda: []) <NEW_LINE> for name, param in params.items(): <NEW_LINE> <INDENT> if param.grad_req != 'null': <NEW_LINE> <INDENT> grads = np.stack(param_grads[name]) <NEW_LINE...
Get score function gradient variance.
625941d221bff66bcd684b0d
def __contains__(self, key): <NEW_LINE> <INDENT> return key in self._data
Return ``True`` if the config section contains ``key``, else ``False``.
625941d2b5575c28eb68e1bc
def __init__(self, lon, lat): <NEW_LINE> <INDENT> epsg = 4326 <NEW_LINE> size = (len(lon), len(lat)) <NEW_LINE> dx = lon[1]-lon[0]; dy = lat[1]-lat[0] <NEW_LINE> ulx = lon[0]-dx/2.; uly = lat[0]-dy/2. <NEW_LINE> geotransform = (ulx, dx, 0., uly, 0., dy) <NEW_LINE> projection = osr.SpatialReference() <NEW_LINE> projecti...
initialize projection dataset based on (regular) lat/lon vectors
625941d2187af65679ca52da
def read_parquet_store(path, nthreads=5): <NEW_LINE> <INDENT> return(pq.read_table(path, nthreads=nthreads).to_pandas())
Description ----------- Read dataset at the given path into a pandas dataframe for analysis Parameters ---------- path : string path to parquet data store to read into memory for analysis nthreads : int, 5 number of threads to use for reading the parquet store into memory Returns ------- : pandas.Da...
625941d2d7e4931a7ee9e0d9
def test_invalid_table_fails(self): <NEW_LINE> <INDENT> rows = [['1', i, i+1, 0, 1] for i in range(100, 121)] + [['1', i, i+1, 10, 1] for i in range(150, 161)] <NEW_LINE> table = Table(header=['chrom', 'start', 'end', 'value', 'blah'], rows=rows) <NEW_LINE> self.assertRaises(AssertionError, table.tostrin...
assertion error if table has > 4 columns
625941d2d18da76e23532692
def monoid_generators(self): <NEW_LINE> <INDENT> G = self.group_generators() <NEW_LINE> from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets <NEW_LINE> if G not in FiniteEnumeratedSets(): <NEW_LINE> <INDENT> raise NotImplementedError("currently only implemented for finitely generated groups") <NEW_LI...
Return the generators of ``self`` as a monoid. Let `G` be a group with generating set `X`. In general, the generating set of `G` as a monoid is given by `X \cup X^{-1}`, where `X^{-1}` is the set of inverses of `X`. If `G` is a finite group, then the generating set as a monoid is `X`. EXAMPLES:: sage: A = Altern...
625941d28c3a873295158577
def test_user_exists(self, client): <NEW_LINE> <INDENT> response = client.post( "/api/v1/register", data=json.dumps(existing_user), content_type='application/json;charset=utf-8') <NEW_LINE> res_data = json.loads(response.get_data(as_text=True)) <NEW_LINE> assert response.status_code == 409 <NEW_LINE> assert 'User alrea...
This method tests for a valid registration
625941d276e4537e8c35182f
def show_dot(self, dpos, bit_value=None): <NEW_LINE> <INDENT> if dpos < self._ndigits and dpos >= 0: <NEW_LINE> <INDENT> self.pixel(self._ndigits-dpos-1, 7, bit_value)
The decimal point for a digit. :param int dpos: the digit to set the decimal point zero-based :param int value: value > zero lights the decimal point, else unlights the point
625941d29c8ee82313fbb931
@web.route("/book/search") <NEW_LINE> def search(): <NEW_LINE> <INDENT> form = SearchForm(request.args) <NEW_LINE> book_collection = BookCollection() <NEW_LINE> if form.validate(): <NEW_LINE> <INDENT> q = form.q.data <NEW_LINE> page = form.page.data <NEW_LINE> yushu = YushuBook() <NEW_LINE> key_or_isbn = is_isbn_or_key...
/book/search?q=金庸&page=1 :return:
625941d2a934411ee375184f
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Listing): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941d2a219f33f34628b24
@event.listens_for(Log.__table__, "after_create") <NEW_LINE> def create_inherited_tables( target: Table, connection: Connection, **kwargs: Any ) -> None: <NEW_LINE> <INDENT> naming = DatabaseModel.metadata.naming_convention <NEW_LINE> connection.execute( "CREATE TABLE log_topics (topic_id bigint not null) INHERITS (log...
Create all the tables that inherit from the base "log" one.
625941d292d797404e304346
def collectSermons(self): <NEW_LINE> <INDENT> urlBase = "http://www.ccgn.nl/boeken02/xbls/" <NEW_LINE> urlExt = ".htm" <NEW_LINE> fExt = ".txt" <NEW_LINE> fBase = "/storage/emulated/0/Documents/xbls_" <NEW_LINE> numLectures = 43+1 <NEW_LINE> lstUrls = ["24a", "24b", "24c", "25a", "25b", "25c"] <NEW_LINE> self.col...
1-23, 26-43 exceptions: 24a, 24b, 24c 25a, 25b, 25c
625941d244b2445a33932251
def __init__(self, source, line, column=None, endLine=None, endColumn=None, **kwargs): <NEW_LINE> <INDENT> if source is None: <NEW_LINE> <INDENT> self.source = Source() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.source = Source(**source) if source.__class__ != Source else source <NEW_LINE> <DEDENT> self.line =...
:param Source source: The source location of the breakpoints; either 'source.path' or 'source.reference' must be specified. :param integer line: Start line of range to search possible breakpoint locations in. If only the line is specified, the request returns all possible locations in that line. :param integer column: ...
625941d2d6c5a10208144207
def dump_poll(self): <NEW_LINE> <INDENT> if self.poll_answers is None: <NEW_LINE> <INDENT> self.poll_answers = {} <NEW_LINE> <DEDENT> answers_to_json = OrderedDict() <NEW_LINE> temp_poll_answers = self.poll_answers <NEW_LINE> for answer in self.answers: <NEW_LINE> <INDENT> if answer['id'] not in temp_poll_answers: <NEW...
Dump poll information. Returns: string - Serialize json.
625941d2d4950a0f3b08c509
def BinarySearch(self, *__args): <NEW_LINE> <INDENT> pass
BinarySearch(self: ArrayList, index: int, count: int, value: object, comparer: IComparer) -> int Searches a range of elements in the sorted System.Collections.ArrayList for an element using the specified comparer and returns the zero-based index of the element. index: The zero-based starting index of the ...
625941d24c3428357757c4e3
def test_getInitPos_fromSerialNo(self): <NEW_LINE> <INDENT> idx = loadData.getInitialPositions(self.serialData) <NEW_LINE> assert_almost_equal(idx, self.testIndex)
Test to ensure the function returns correct values based on serial number
625941d2796e427e537b0782
def _get_zhuanlan(html, jpgs, gifs): <NEW_LINE> <INDENT> print('专栏页面加载完成,正在解析图片源地址') <NEW_LINE> soup = BeautifulSoup(html, 'html.parser').find('div', class_='Post-RichTextContainer') <NEW_LINE> imgs = soup.find_all('img') <NEW_LINE> for img in imgs[::2]: <NEW_LINE> <INDENT> url = img['src'] <NEW_LINE> if '.gif' in url:...
如果是专栏就直接拿链接,前端源码里面就有
625941d2ad47b63b2c50a13b
def generateParenthesis(self, n): <NEW_LINE> <INDENT> result = [] <NEW_LINE> def backtracking(S, left, right): <NEW_LINE> <INDENT> if len(S) == 2 * n: <NEW_LINE> <INDENT> result.append(S) <NEW_LINE> return <NEW_LINE> <DEDENT> if left < n: <NEW_LINE> <INDENT> backtracking(S + '(', left + 1, right) <NEW_LINE> <DEDENT> if...
:type n: int :rtype: List[str]
625941d2097d151d1a223015
def plotVerticalSection(filename,varIdentifier,vertSection,coordVal,tIndex): <NEW_LINE> <INDENT> import netCDF4 <NEW_LINE> import netcdfUtils <NEW_LINE> import plotting <NEW_LINE> nc=netCDF4.Dataset(filename) <NEW_LINE> dataVar=nc.variables[varIdentifier] <NEW_LINE> lonVar = netcdfUtils.findLongitudeVar(nc, dataVar) <N...
Takes five aruguments i.e. a string representing location of NetCDF file, variable identifier, string indicating whether vertical section is North-South (NS) or East-West (EW), the value of latitude/longitude depending on EW or NS, and the index along the time axis for which to get the data. Uses the extractVerticalS...
625941d24d74a7450ccd437f
def getServiceStatus(self): <NEW_LINE> <INDENT> self._req_with() <NEW_LINE> status = SERVICE_STATUS() <NEW_LINE> if not advapi32.QueryServiceStatus(self.hSvc, ctypes.byref(status)): <NEW_LINE> <INDENT> raise ctypes.WinError() <NEW_LINE> <DEDENT> return status
Returns a SERVICE_STATUS structure for the service.
625941d226238365f5f0f02b
def modprod(xs: List[int], modulo: int) -> int: <NEW_LINE> <INDENT> return reduce(lambda x, y: mulmod(x, y, modulo), xs, 1)
Return the product modulo a value
625941d223849d37ff7b324b
def lookup(self, prodname): <NEW_LINE> <INDENT> return self.prod.get(prodname)
return the tag data for a given product or None if does not exist
625941d25fdd1c0f98dc03f0
def delete_property(request, property_id): <NEW_LINE> <INDENT> property_listing = get_object_or_404(Property, id=property_id) <NEW_LINE> seller = property_listing.seller.username <NEW_LINE> if request.user.is_authenticated and request.user.username == seller: <NEW_LINE> <INDENT> property_listing.delete() <NEW_LINE> mes...
deletes the property from the database with the passed in property_id. Only the authenticated seller who created the property can delete the property :param request: :param property_id: unique id to identify properties :return: HttpResponse renders back to dashboard with error or success message
625941d2de87d2750b85ff4f
def __init__(self, specification, note, measureIndex, measureOffset): <NEW_LINE> <INDENT> self._specification = specification <NEW_LINE> self._note = None <NEW_LINE> self._parameters = {} <NEW_LINE> self._isParsed = False <NEW_LINE> self._parseSpecification(self._specification) <NEW_LINE> self._note = note <NEW_LINE> s...
A specification must be created when access the Measure that the source note is found in. Storing the measure and index position provides significant performance optimization, as we do no have to search every note when generated the reduction. The `measureIndex` is the index of measure where this is found, not the ...
625941d2bf627c535bc1338b
def createAnnulus(n=256, r=32, w=4): <NEW_LINE> <INDENT> if np.isscalar(n): <NEW_LINE> <INDENT> v = np.arange(n) <NEW_LINE> v = v - np.floor(n/2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> v = n <NEW_LINE> <DEDENT> y,x = np.meshgrid(v,v) <NEW_LINE> q = np.hypot(x,y) <NEW_LINE> annulus = abs(q-r) < w <NEW_LINE> retur...
createAnnulus - create a ring-like structure INPUT n - size of square array or vector r - radius of the ring w - width of the ring OUTPUT an array n x n
625941d22eb69b55b151ca6c
def delete_temp(aip_id, deletion_log=False): <NEW_LINE> <INDENT> delete = ['.DS_Store', '._.DS_Store', 'Thumbs.db'] <NEW_LINE> deleted_files = [] <NEW_LINE> for root, directories, files in os.walk(aip_id): <NEW_LINE> <INDENT> for item in files: <NEW_LINE> <INDENT> if item in delete or item.endswith('.tmp') or item.star...
Deletes temporary files of various types from anywhere within the AIP folder because they cause errors later in the workflow, especially with bag validation.
625941d256b00c62f0f14816
def main_proc(n): <NEW_LINE> <INDENT> shapes = [] <NEW_LINE> for i in range(10): <NEW_LINE> <INDENT> if i % 2 == 0: <NEW_LINE> <INDENT> shapes.append(Circle(n+i)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> shapes.append(Square(n+i)) <NEW_LINE> <DEDENT> <DEDENT> for s in shapes: <NEW_LINE> <INDENT> print("形状面积: {:.2f...
主处理函数
625941d294891a1f4081bc66
def __init__(self, rest_unit_num, hidden_unit_num, **kwargs): <NEW_LINE> <INDENT> super(ResBlock, self).__init__(**kwargs) <NEW_LINE> with self.name_scope(): <NEW_LINE> <INDENT> self.nn2 = gluon.nn.Dense(hidden_unit_num, activation="relu") <NEW_LINE> self.nn3 = gluon.nn.Dense(rest_unit_num, activation="relu")
:type rest_unit_num: int :type hidden_unit_num: int :param rest_unit_num: int :param hidden_unit_num: int :param kwargs:
625941d2e5267d203edcde58
def p_array(self, p): <NEW_LINE> <INDENT> if len(p) == 3: <NEW_LINE> <INDENT> p[0] = stl.base.Value([]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p[0] = stl.base.Value(p[2])
array : '[' ']' | '[' array_elements ']' | '[' array_elements ',' ']'
625941d2167d2b6e31218d52
def _arg(*, artifacts: types.ArgArtifacts, name: str) -> str: <NEW_LINE> <INDENT> required_sources = map( lambda artifacts: _arg_single_required(artifacts, name), artifacts.required ) <NEW_LINE> not_required_sources = map( lambda artifacts: _arg_single_not_required(artifacts, name), artifacts.not_required, ) <NEW_LINE>...
Generate the arguments for a function signature of a model. Args: artifacts: The artifacts for the arguments. name: The attribute name to use for the type. Returns: The argument signature for the functions.
625941d24e4d5625662d4592
def executeSql(query): <NEW_LINE> <INDENT> db, cursor = connect() <NEW_LINE> cursor.execute(query) <NEW_LINE> db.commit() <NEW_LINE> db.close()
Function to run SQL queries.
625941d2c432627299f04e03
def wallunderground(idf, bsdobject, deletebsd=True, setto000=False): <NEW_LINE> <INDENT> if bsdobject.Surface_Type.upper() == "WALL": <NEW_LINE> <INDENT> if bsdobject.Outside_Boundary_Condition.upper().startswith( "GROUND" ): <NEW_LINE> <INDENT> simpleobject = idf.newidfobject("WALL:UNDERGROUND") <NEW_LINE> simpleobjec...
return a wall:underground if bsdobject (buildingsurface:detailed) is an underground wall
625941d2d10714528d5ffea1
def __init__(self, color, x, y, left, top, tree=False): <NEW_LINE> <INDENT> if color == "red": <NEW_LINE> <INDENT> super().__init__(all_sprites, piece_sprites, red_piece_sprites) <NEW_LINE> <DEDENT> elif color == "blue": <NEW_LINE> <INDENT> super().__init__(all_sprites, piece_sprites, blue_piece_sprites) <NEW_LINE> <DE...
Общая форма создания фигур, color - цвет, (x, y) - координаты фигуры на поле
625941d2a8ecb033257d3289
def test_template(self): <NEW_LINE> <INDENT> self.assertTemplateUsed(self.response, 'subscriptions/subscription_form.html')
GET must use 'subscriptions/subscription_form.html'
625941d250485f2cf553cf56
def configTurtles(): <NEW_LINE> <INDENT> mcLaren.shape("turtle") <NEW_LINE> mcLaren.color("Red") <NEW_LINE> ferrari.shape("turtle") <NEW_LINE> ferrari.color("Blue") <NEW_LINE> mcLaren.penup() <NEW_LINE> ferrari.penup()
Configure shape and colour of turtles
625941d2b545ff76a8913fd2
def my_schedule(request,username): <NEW_LINE> <INDENT> user = get_object_or_404(User, username=username) <NEW_LINE> user_profile = UserProfile.objects.get_or_create(user=user)[0] <NEW_LINE> weekly_schedule = WeeklySchedule.objects.filter(user_profile=user_profile) <NEW_LINE> userScheduleInlineFormSet = inlineformset_fa...
For editing and rendering weekly schedule
625941d2656771135c3eba2c