code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def set_live(self, win): <NEW_LINE> <INDENT> if self.status == 'dead': <NEW_LINE> <INDENT> self.status = 'live' <NEW_LINE> self.draw(win) | Sets the block status to 'live' and draws it on the grid.
Be sure to do this on the canvas! | 625941e9a17c0f6771cbe4ec |
def relative_multi_level_risk_decomposition(self, portfolio, benchmark, percentile, functions=None, lookback_days=730, horizon=1, frequency=1, fields=None): <NEW_LINE> <INDENT> if functions is None: <NEW_LINE> <INDENT> functions = DECOMPOSABLE_RISK_FUNCTIONS <NEW_LINE> <DEDENT> params = dict(lookback_days=lookback_days... | Portfolio relative multi-level risk decomposition
Compute the multi-level risk decomposition of the given risk functions
on the given portfolio relative to the given benchmark using the attributes
lists from the portfolio holdings. It returns a hierarchy of risk figures
according to the assets attributes | 625941e97047854f462a18a1 |
def test__get_pwt_data(self): <NEW_LINE> <INDENT> io._get_pwt_data(self.base_url, self.version) <NEW_LINE> tmp_file = 'pwt' + str(self.version) + '.dta' <NEW_LINE> mesg = "Download of " + tmp_file + "file failed!" <NEW_LINE> assert os.path.isfile(tmp_file), mesg | Test download of PWT data. | 625941e90a366e3fb873ecbc |
def __init__(self, config, name="mrcnn_classifer_model", **kwargs): <NEW_LINE> <INDENT> super(Classifier, self).__init__(name=name, **kwargs) <NEW_LINE> self.config = config <NEW_LINE> self.roialign = PyramidROIAlign([config.POOL_SIZE, config.POOL_SIZE], config, name="roi_align_classifier") <NEW_LINE> self.tconv1 = KL.... | Structures:
-----------------------------------------------------------
rois+featuremap
|
RoiAlign
|
CBRCBR
|
Sequeeze
/ Dense Dense
| |
class box | 625941e9099cdd3c635f10f6 |
def is_connected_to(self, other_mesh): <NEW_LINE> <INDENT> assert other_mesh.is_mesh() <NEW_LINE> return self._is_connected_to(other_mesh) | Whether the one mesh is conencted to the other. | 625941e98e05c05ec3eea816 |
def handle_bank_switch_ids(self, switch_id): <NEW_LINE> <INDENT> self.main_script().log_message("self.__assignment_mode == C4M_CHANNEL_STRIP is <{0}>" .format(self.__assignment_mode == C4M_CHANNEL_STRIP)) <NEW_LINE> current_bank_nbr = self.__eah.get_current_track_device_parameter_bank_nbr() <NEW_LINE> update_self = Fal... | works in all modes | 625941e9a17c0f6771cbe4ed |
def group_by_clause(self, select, **kw): <NEW_LINE> <INDENT> group_by = self._generate_delimited_list( select._group_by_clauses, OPERATORS[operators.comma_op], **kw ) <NEW_LINE> if group_by: <NEW_LINE> <INDENT> return " GROUP BY " + group_by <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "" | allow dialects to customize how GROUP BY is rendered. | 625941e9046cf37aa974d1e0 |
def isMoreToRead(self): <NEW_LINE> <INDENT> if len(self.line) == self.offset: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | Returns False if we're at the end of the string, True otherwise. | 625941e944b2445a33932530 |
def write_packet(self, packet: Any) -> None: <NEW_LINE> <INDENT> if not hasattr(packet, '_is_packet') or not bool(getattr(packet, '_is_packet')): <NEW_LINE> <INDENT> raise ValueError("Invalid argument: Must be a packet!") <NEW_LINE> <DEDENT> packet._write(self) | Writes the given packet. | 625941e9e64d504609d74cdd |
def tokenise(string, colstart=None, linenum=0): <NEW_LINE> <INDENT> if colstart is None: <NEW_LINE> <INDENT> nested = False <NEW_LINE> colstart = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nested = True <NEW_LINE> <DEDENT> if not string: <NEW_LINE> <INDENT> if nested: <NEW_LINE> <INDENT> return colstart <NEW_LINE>... | Tokenise a string using pattern notation.
Arguments:
string -- the input string using pattern notation (str)
colstart -- the column to start token indexing at (int)
Yields Token objects | 625941e9be8e80087fb210d9 |
def interpolate_zeros(array, kernel = [1,1], epsilon = 1e-9): <NEW_LINE> <INDENT> sh = array.shape[1] <NEW_LINE> for ii in tqdm(range(sh), unit='images'): <NEW_LINE> <INDENT> mask = array[:, ii, :] > epsilon <NEW_LINE> mask_norm = ndimage.filters.gaussian_filter(numpy.float32(mask), sigma = kernel) <NEW_LINE> tmp = ndi... | Fill in zero volues, for instance, blank pixels.
Args:
kernel: Size of the interpolation kernel
epsilon: if less than epsilon -> interpolate | 625941e93c8af77a43ae3c43 |
def test_compare_to_01(self): <NEW_LINE> <INDENT> iri = IRI('http://ex.org/sth') <NEW_LINE> self.assertEqual(0, iri.compare_to(iri)) | same object --> 0 | 625941e9498bea3a759b9f4b |
def test_pending(self): <NEW_LINE> <INDENT> mkdir("./branch") <NEW_LINE> wt = self.make_branch_and_tree('branch') <NEW_LINE> b = wt.branch <NEW_LINE> wt.commit("Empty commit 1") <NEW_LINE> b_2_dir = b.bzrdir.sprout('./copy') <NEW_LINE> b_2 = b_2_dir.open_branch() <NEW_LINE> wt2 = b_2_dir.open_workingtree() <NEW_LINE> w... | Pending merges display works, including Unicode | 625941e9e76e3b2f99f3aca1 |
def forward(self, in_img, goal_img, p, apply_softmax=True): <NEW_LINE> <INDENT> assert in_img.shape == goal_img.shape, f'{in_img.shape}, {goal_img.shape}' <NEW_LINE> input_unproc = np.pad(in_img, self.padding, mode='constant') <NEW_LINE> input_data = self.preprocess(input_unproc.copy()) <NEW_LINE> input_shape = (1,) + ... | Forward pass of goal-conditioned Transporters.
Runs input through all three networks, to get output of the same
shape, except the last channel is 3 (output_dim). Then, the output
for one stream has the convolutional kernels for another. Call
tf.nn.convolution, and the operation is be differentiable, so that
gradients ... | 625941e92c8b7c6e89b35c5b |
def add_tools_registry(context): <NEW_LINE> <INDENT> api.portal.get_tool('portal_setup').runImportStepFromProfile( 'profile-oira.website:default', 'jsregistry') <NEW_LINE> api.portal.get_tool('portal_setup').runImportStepFromProfile( 'profile-oira.website:default', 'typeinfo') <NEW_LINE> site = api.portal.get() <NEW_LI... | Add and populate the OiRA Tools registry, which contains tools shown
on the OiRA Tools page. | 625941e9e76e3b2f99f3aca2 |
def string(length): <NEW_LINE> <INDENT> def _decorator(data): <NEW_LINE> <INDENT> if isinstance(data, unicode): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif isinstance(data, str): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = str(data) <NEW_LINE> <DEDENT> ex... | desc: 字符串类型
params: length 字符串长度
return: True 合法
False 非法 | 625941e97d847024c06be75d |
def __init__(self, buf, offset, parent): <NEW_LINE> <INDENT> super(SKRecord, self).__init__(buf, offset, parent) <NEW_LINE> _id = self.unpack_string(0x0, 2) <NEW_LINE> if _id != b"sk": <NEW_LINE> <INDENT> raise ParseException("Invalid SK Record ID") <NEW_LINE> <DEDENT> self._offset_prev_sk = self.unpack_dword(0x4) <NEW... | Constructor.
Arguments:
- `buf`: Byte string containing Windows Registry file.
- `offset`: The offset into the buffer at which the block starts.
- `parent`: The parent block, which links to this block. This should be an HBINCell. | 625941e97c178a314d6ef904 |
def uuid(size=16): <NEW_LINE> <INDENT> size = max(int(size), 16) <NEW_LINE> if sys.platform == 'win32': <NEW_LINE> <INDENT> front = "{0:0x}".format(int(time.clock() * 1000000)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> front = "{0:0x}".format(int(time.time() * 1000000)) <NEW_LINE> <DEDENT> extra = size - len(fron... | Generate universally unique id hex string with size characters
Timebased with random bytes
Minimum size is 16
Uses time.clock instead of time.time on windows.
Tests of rapid uuid generation fail to generate unique uuids
on Windows with time.time().
See http://www.pythoncentral.io/measure-time-in-python-time-time-vs-ti... | 625941e94e4d5625662d486f |
def groupAnagrams(self, strs): <NEW_LINE> <INDENT> sortedList = [] <NEW_LINE> for i, word in enumerate(strs): <NEW_LINE> <INDENT> sorted_strs = "".join(sorted(word)) <NEW_LINE> sortedList.append(sorted_strs) <NEW_LINE> del sorted_strs <NEW_LINE> <DEDENT> thisDict = {} <NEW_LINE> for i, word in enumerate(sortedList): <N... | :type strs: List[str]
:rtype: List[List[str]] | 625941e98e7ae83300e4b46c |
def send(event, **arguments): <NEW_LINE> <INDENT> log.debug(u'Sending event: {0}', event) <NEW_LINE> results = [] <NEW_LINE> for handler in event_handlers()[event]: <NEW_LINE> <INDENT> result = handler(**arguments) <NEW_LINE> if result is not None: <NEW_LINE> <INDENT> results.append(result) <NEW_LINE> <DEDENT> <DEDENT>... | Send an event to all assigned event listeners.
`event` is the name of the event to send, all other named arguments
are passed along to the handlers.
Return a list of non-None values returned from the handlers. | 625941e963d6d428bbe4498e |
def get_cashf_conceptshares_EM(bkname,day=''): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> df=pd.read_pickle('output/eastmsource/bk.pkl') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> df=pd.read_csv('output/eastmsource/bk.csv',encoding='gbk') <NEW_LINE> <DEDENT> idd=df[df['name']==bkname]['id'].tolist()[0] <NEW_LINE... | 获取同行业的股票涨跌信息
| 625941e9167d2b6e31219032 |
def getUsersByType(self, typeId, offset=None, limit=None, q=None): <NEW_LINE> <INDENT> return self._getAll(UserMapped.Type == typeId, q, offset, limit) | @see: IUserService.getUsersByType | 625941e95166f23b2e1a55f6 |
def _get_proj_array(self): <NEW_LINE> <INDENT> if self._proj_array is None: <NEW_LINE> <INDENT> if self.symmetric: <NEW_LINE> <INDENT> IP_array = self.vec_space.compute_symm_inner_product_array( self.basis_vecs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> IP_array = self.vec_space.compute_inner_product_array( self.ad... | Gets the projection array, i.e. inv(Psi^* Phi). | 625941e99f2886367277ad27 |
def __init__(self, D_IN, D_OUT, M=50): <NEW_LINE> <INDENT> self.sig_offset = 1e-5 <NEW_LINE> self.process_sig_offset = 1e-5 <NEW_LINE> self.lambda_offset = 1e-5 <NEW_LINE> self.D_IN = D_IN <NEW_LINE> self.D_OUT = D_OUT <NEW_LINE> self.M = M <NEW_LINE> self._init_mean_function(D_IN, D_OUT) <NEW_LINE> self.ARD_loglambda ... | Initialize GP layer
D_IN : dimension of input
D_OUT : dimension of output
M : the number of inducing points | 625941e96e29344779a62aae |
def getMeter(self): <NEW_LINE> <INDENT> return self.meter | return the meter of all of the words in the poem compared to the
poemFormObject. | 625941e99c8ee82313fbbc14 |
def ambiguity(memberships): <NEW_LINE> <INDENT> partition = -np.partition(-memberships, [0, 1], axis=1) <NEW_LINE> top1 = partition[:, 0] <NEW_LINE> top2 = partition[:, 1] <NEW_LINE> return top1 - top2 | Compute the ambiguity of a memberships matrix.
The ambiguity of a memberships matrix is defined as the vector containing for each sample the differences of the two
highest memberships he has. | 625941e9d6c5a102081444ec |
def array123(nums): <NEW_LINE> <INDENT> if nums is None or len(nums) == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> hlst = {1: 1, 2: 2, 3: 3} <NEW_LINE> for n in nums: <NEW_LINE> <INDENT> if n in hlst: <NEW_LINE> <INDENT> del hlst[n] <NEW_LINE> <DEDENT> if len(hlst) == 0: <NEW_LINE> <INDENT> return True <NE... | Given an array of ints,return True if .. 1, 2, 3, .. appears in the array somewhere. | 625941e992d797404e30462a |
def test_curso_nao_encontrado_get_all_klass_rs_get_course_by_id(self): <NEW_LINE> <INDENT> data = GetByCourseIdRQ( lms_course_id=15 ) <NEW_LINE> res = self.api.get_by_course_id(data) <NEW_LINE> if isinstance(res, ConnectionExceptionRS): <NEW_LINE> <INDENT> raise unittest.SkipTest(res.msg) <NEW_LINE> <DEDENT> self.asser... | Testa a resposta de erro caso o curso nao seja encontrado
na resposta do metodo get_course_by_id | 625941e93317a56b8693a0ea |
def create_time_window_graphs(self, window_size=1): <NEW_LINE> <INDENT> num_splits = len(self.time_splits_graph_list) <NEW_LINE> for i in range(window_size, num_splits): <NEW_LINE> <INDENT> long_train_G = nx.Graph() <NEW_LINE> long_train_set_list = self.time_splits_graph_list[:i] <NEW_LINE> for g in long_train_set_list... | Given the list of graphs splitted by time
return a list of tuple (long_train_set, short_train_set, test_set) with train dataset as the concatenation
of window_size time split graphs and the test set as the next time split graph | 625941e9d8ef3951e32439db |
def __init__(self, ads_hub, name, ads_var): <NEW_LINE> <INDENT> self._state_dict = {} <NEW_LINE> self._state_dict[STATE_KEY_STATE] = None <NEW_LINE> self._ads_hub = ads_hub <NEW_LINE> self._ads_var = ads_var <NEW_LINE> self._event = None <NEW_LINE> self._attr_unique_id = ads_var <NEW_LINE> self._attr_name = name | Initialize ADS binary sensor. | 625941e9925a0f43d254a319 |
def iriToURI(iri): <NEW_LINE> <INDENT> return _escapeme_re.sub(_percentEscapeUnicode, iri) | Transform an IRI to a URI by escaping unicode. | 625941e98a349b6b435e8610 |
def connect(self): <NEW_LINE> <INDENT> if self._mode_curl: <NEW_LINE> <INDENT> self._connected = True <NEW_LINE> return True <NEW_LINE> <DEDENT> url = urlparse(self._ctrl_host) <NEW_LINE> port = url.port if url.port else Linstor.REST_PORT <NEW_LINE> is_https = False <NEW_LINE> if url.scheme == "linstor+ssl" or url.sche... | Connects the internal linstor network client.
:return: True | 625941e991af0d3eaac9bebb |
def all_netcdfs(self): <NEW_LINE> <INDENT> return [f for f in glob.glob(self.archive_name("*")) if Path(f).is_file()] | Pattern matches potential paths where files could be stored to those that actually exist.
Warning: Files outside this directory aren't indexed and won't get ingested.
:return: | 625941e9379a373c97cfafe4 |
def test_autocomplete_diacritics_insensitive_query(self, *_): <NEW_LINE> <INDENT> all_organizations, response = self.execute_query(querystring="query=Üñî") <NEW_LINE> self.assertEqual( [all_organizations[i]["id"] for i in [0, 2]], [organization["id"] for organization in response], ) | Queries are diacritics insensitive. | 625941e9004d5f362079a7ce |
def add_anno(self, anno_id, lnum): <NEW_LINE> <INDENT> assert not anno_id in self.keys() <NEW_LINE> if anno_id == FRAME_ANNO_ID: <NEW_LINE> <INDENT> self[anno_id] = FrameAnnotation(self, lnum, self.nbsock) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self[anno_id] = Annotation(self, anno_id, lnum, self.nbsock) <NEW_LI... | Add an annotation. | 625941e9c432627299f050e7 |
@pytest.fixture(scope='session') <NEW_LINE> def session_mm_secondary_master_tcp_master_workers(): <NEW_LINE> <INDENT> return get_unused_localhost_port() | Returns an unused localhost port | 625941e9293b9510aa2c372f |
def __crawler(self, element) -> (str, str): <NEW_LINE> <INDENT> if self.browser == "google": <NEW_LINE> <INDENT> return element.find('h3').text, element.find('a')['href'] <NEW_LINE> <DEDENT> if self.browser == "duckduckgo": <NEW_LINE> <INDENT> return element.find( 'a', class_="result__a").getText() if element.find( 'a'... | Crawl the html page and get titles and links
Result
---
(str, str) | 625941e9baa26c4b54cb15b9 |
def __init__(__self__, *, active: Optional[pulumi.Input[bool]] = None, enabled: Optional[pulumi.Input[bool]] = None, name: Optional[pulumi.Input[str]] = None, priority: Optional[pulumi.Input[int]] = None, realm_id: Optional[pulumi.Input[str]] = None, secret_size: Optional[pulumi.Input[int]] = None): <NEW_LINE> <INDENT>... | Input properties used for looking up and filtering RealmKeystoreAesGenerated resources.
:param pulumi.Input[bool] active: When `false`, key in not used for signing. Defaults to `true`.
:param pulumi.Input[bool] enabled: When `false`, key is not accessible in this realm. Defaults to `true`.
:param pulumi.Input[str] name... | 625941e9566aa707497f4a00 |
def unpool_with_argmax(bottom, argmax, output_shape=None, name='max_unpool_with_argmax'): <NEW_LINE> <INDENT> with tf.name_scope(name): <NEW_LINE> <INDENT> ksize = [1, 2, 2, 1] <NEW_LINE> input_shape = bottom.get_shape().as_list() <NEW_LINE> if output_shape is None: <NEW_LINE> <INDENT> output_shape = (input_shape[0], i... | upsampling according argmax
:param bottom: the output feature maps needed to be upsampled
:param argmax: the indice made by tf.nn.max_pool_with_argmax()
:param output_shape:
:param name:
:return: | 625941e926238365f5f0f313 |
def crossSpecgram(x, y, NFFT=256, Fs=2, detrend=mlab.detrend_none, window=mlab.window_hanning, noverlap=0, pad_to=None, sides='default', scale_by_freq=None) : <NEW_LINE> <INDENT> assert(len(x)==len(y)) <NEW_LINE> Pxy, freqs, t = mlab._spectral_helper(x, y, NFFT, Fs, detrend, window, noverlap, pad_to, sides, scale_by_fr... | Use matplotlib.mlab function, _spectral_helper, to calculate cross power between x and y in short time bins.
USAGE:
Pxy,freqs,t=crossSpecgram(x,y,NFFT=256, Fs=2, detrend=mlab.detrend_none, window=window_hanning, noverlap=0, pad_to=None, sides='default', scale_by_freq=None)
NFFT=# data points in each time bin
Fs =... | 625941e95fc7496912cc3e1b |
def update_editor(self): <NEW_LINE> <INDENT> text = self.str_value <NEW_LINE> if self.factory.format_text: <NEW_LINE> <INDENT> text = self.factory.parse_text(text) <NEW_LINE> <DEDENT> if self.base_url: <NEW_LINE> <INDENT> url = self.base_url <NEW_LINE> if not url.endswith("/"): <NEW_LINE> <INDENT> url += "/" <NEW_LINE>... | Updates the editor when the object trait changes external to the
editor. | 625941e982261d6c526ab944 |
def create_environment_scripts_only( prefix_path, pkg, *, default_hooks=None, additional_hooks=None ): <NEW_LINE> <INDENT> logger.log(1, 'create_environment_scripts_only(%s)', pkg.name) <NEW_LINE> hooks = [] <NEW_LINE> if default_hooks is None: <NEW_LINE> <INDENT> default_hooks = create_environment_hooks(prefix_path, p... | Create the environment scripts for a package.
:param prefix_path: The prefix path
:param pkg: The package descriptor
:param list default_hooks: If none are parsed explicitly the hooks provided
by :function:`create_environment_hooks` are used
:param list additional_hooks: Any additional hooks which should be
refere... | 625941e923849d37ff7b3529 |
def __init__(self, type_id, command): <NEW_LINE> <INDENT> super().__init__( "Unknown ID value {0} for data type during command {1}".format( type_id, command)) | :param int type_id: The ID of the requested type
:param str command: The command being executed | 625941e9090684286d50f18b |
def paragraph(self, text): <NEW_LINE> <INDENT> text = _re_user.sub(userify, text) <NEW_LINE> return super(AppRender, self).paragraph(text) | Render paragraph tags, autolinking user handles. | 625941e9046cf37aa974d1e1 |
def match_sample_in_data_frame(df, regex, column): <NEW_LINE> <INDENT> if not df.shape[0]: <NEW_LINE> <INDENT> return df <NEW_LINE> <DEDENT> col_query = df.loc[:, column] <NEW_LINE> names = {} <NEW_LINE> for query in col_query: <NEW_LINE> <INDENT> m = re.match(regex, query) <NEW_LINE> if m: <NEW_LINE> <INDENT> for key ... | Use ``regex`` to parse out information from the ``"query"`` column of the ``df`` DataFrame.
Return an augmented DataFrame. | 625941e9187af65679ca55be |
def validate_values(self): <NEW_LINE> <INDENT> return len(self.choices_for_values()) == len(self.values) | Return True if all values where found in :py:attr:`choices`. | 625941e955399d3f05588b55 |
@pytest.mark.django_db <NEW_LINE> def test_remove_single(client): <NEW_LINE> <INDENT> link = LinkFactory() <NEW_LINE> content = TitleFactory(link=link) <NEW_LINE> user = UserFactory(is_staff=True) <NEW_LINE> assert content.link is not None <NEW_LINE> assert client.login(username=user.username, password=TEST_PASSWORD) i... | The multi test for removing is ````. | 625941e9d18da76e2353297a |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, AvscanServer): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941e9a934411ee3751b33 |
def add_file(name_data, filename): <NEW_LINE> <INDENT> year = '' <NEW_LINE> with open(filename, 'r') as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> token = line.split(',') <NEW_LINE> if len(token) > 1: <NEW_LINE> <INDENT> rank = token[0].strip() <NEW_LINE> name1 = token[1].strip() <NEW_LINE> name2 = token... | Reads the information from the specified file and populates the name_data
dict with the data found in the file.
Input:
name_data (dict): dict holding baby name data
filename (str): name of the file holding baby name data
Output:
This function modifies the name_data dict to store information from
the p... | 625941e9d7e4931a7ee9e3bd |
def selected(self, a): <NEW_LINE> <INDENT> return a[self.array] | Return the selected voxels of an array as a flat array. | 625941e96fece00bbac2dbe2 |
def reset(self): <NEW_LINE> <INDENT> self.scores = 0 <NEW_LINE> new_sprites = [] <NEW_LINE> for s in self.sprites: <NEW_LINE> <INDENT> if not isinstance(s, Ball): <NEW_LINE> <INDENT> new_sprites.append(s) <NEW_LINE> <DEDENT> <DEDENT> self.sprites = new_sprites <NEW_LINE> self.show_ball_time = 1000 <NEW_LINE> self.diffi... | Remet à zero le niveau
:return: | 625941e991f36d47f21ac995 |
def frequencySort(self, nums): <NEW_LINE> <INDENT> hashSet ={} <NEW_LINE> for i in nums: <NEW_LINE> <INDENT> if i in hashSet: <NEW_LINE> <INDENT> hashSet[i]+=1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hashSet[i] =1 <NEW_LINE> <DEDENT> <DEDENT> newHash={} <NEW_LINE> for i in hashSet: <NEW_LINE> <INDENT> tmpNum = ha... | :type nums: List[int]
:rtype: List[int] | 625941e96aa9bd52df037245 |
def messageQueue(self): <NEW_LINE> <INDENT> return self.store.findUnique(MessageQueue) | This is a temporary workaround; see ticket #2640 for details on the way
this method should be implemented in the future. | 625941e930dc7b7665901dff |
def fit(self, *, timeout: float = None, iterations: int = None) -> CallResult[None]: <NEW_LINE> <INDENT> if self._fitted: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self._df is None: <NEW_LINE> <INDENT> raise ValueError('Missing training(fitting) data.') <NEW_LINE> <DEDENT> self._column_names = list(self._df) if... | call both prefix and date method and return a combined list
:return: list of list of columns to fold | 625941e9a8ecb033257d3569 |
def __init__(self, X, Y, max_lv): <NEW_LINE> <INDENT> self.X = X <NEW_LINE> self.Y = Y <NEW_LINE> self.n = X.shape[0] <NEW_LINE> self.m = X.shape[1] <NEW_LINE> self.p = Y.shape[1] <NEW_LINE> self.max_lv = max_lv <NEW_LINE> self._nr_lv = max_lv <NEW_LINE> self._T = np.zeros((self.n, max_lv)) <NEW_LINE> self._P = np.zero... | Instantiate space for the model. | 625941e9a8ecb033257d356a |
def build_sink_factory(function: Callable[..., None] = None, *, unpack: bool = False): <NEW_LINE> <INDENT> def _build_sink(function: Callable[..., None]): <NEW_LINE> <INDENT> @wraps(function) <NEW_LINE> def _wrapper(*args, **kwargs) -> Sink: <NEW_LINE> <INDENT> if 'unpack' in kwargs: <NEW_LINE> <INDENT> raise TypeError... | Decorator to wrap a function to return a Sink subscriber factory.
:param function: function to be wrapped
:param unpack: value from emits will be unpacked (*value) | 625941e991f36d47f21ac996 |
def is_valid_dependency(self, dep): <NEW_LINE> <INDENT> return isinstance(dep, baseobject.PBXBaseObject) and dep.isa == u'PBXTargetDependency' | check if dep is valid dependency | 625941e98e71fb1e9831dc46 |
def register_datehandler(locales,parse_class,display_class): <NEW_LINE> <INDENT> for lang_str in locales: <NEW_LINE> <INDENT> LANG_TO_PARSER[lang_str] = parse_class <NEW_LINE> LANG_TO_DISPLAY[lang_str] = display_class | Registers the passed date parser class and date displayer
classes with the specified language locales.
@param locales: tuple of strings containing language codes.
The character encoding is not included, so the language
should be in the form of fr_FR, not fr_FR.utf8
@type locales: tuple
@param parse_class: Clas... | 625941e94e696a04525c98ec |
def add_input(self, accumulator: MinMax, batch: input_batch.InputBatch) -> MinMax: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> left_lengths = batch.list_lengths(self._left_path) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> left_lengths = np.full(batch.record_batch.num_rows, 0) <NEW_LINE> <DEDENT> try: <NEW... | Updates the min and max lengths from new batch. | 625941e93346ee7daa2b320e |
def command(self, name, *args): <NEW_LINE> <INDENT> args = [name.encode()] + [str(arg).encode() for arg in args if arg is not None] + [None] <NEW_LINE> _mpv_command(self.handle, (c_char_p*len(args))(*args)) | Execute a raw command | 625941e9d4950a0f3b08c7e7 |
def _put_part_image(self, pnum): <NEW_LINE> <INDENT> sparse_copy(self._partimages[pnum], self.imagepath, seek=self.partitions[pnum].start) | Put partition image into partitioned image. | 625941e9ad47b63b2c50a41d |
def clean_buckets(self): <NEW_LINE> <INDENT> for bucket in self.storage.buckets(): <NEW_LINE> <INDENT> if not self.queue.find_one({'bucket': bucket.id}): <NEW_LINE> <INDENT> print(f'Bucket {bucket.id} is unreferenced. Deleting.') <NEW_LINE> bucket.drop() | Deletes all buckets not associated to a task. | 625941e97cff6e4e81117e24 |
def __init__(self, this_generation: int, parent1=None, parent2=None) -> BeingType: <NEW_LINE> <INDENT> self.generation = this_generation <NEW_LINE> self.parent1 = parent1 <NEW_LINE> self.parent2 = parent2 <NEW_LINE> if None in (parent1, parent2): <NEW_LINE> <INDENT> self.dna = Being.random_dna() <NEW_LINE> <DEDENT> els... | Constructor -> generate being (from parents) | 625941e9cdde0d52a9e534d5 |
def findPairs(self, nums, k): <NEW_LINE> <INDENT> if k < 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> table = {} <NEW_LINE> for n in nums: <NEW_LINE> <INDENT> table[n] = table.get(n,0)+1 <NEW_LINE> <DEDENT> ans = 0 <NEW_LINE> for t in table: <NEW_LINE> <INDENT> if k == 0: <NEW_LINE> <INDENT> if table[t] > 1: <NE... | :type nums: List[int]
:type k: int
:rtype: int | 625941e963d6d428bbe4498f |
def __init__(self, config): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> try: <NEW_LINE> <INDENT> super(ProxyServer, self).__init__((config.host, config.port)) <NEW_LINE> <DEDENT> except socket.error as e: <NEW_LINE> <INDENT> six.reraise( ServerException, ServerException('Error starting proxy server: ' + repr(e)... | Raises ProxyServerError if there's a startup problem. | 625941e9dc8b845886cb59d5 |
def reset(self, wanted_relay_ops=None): <NEW_LINE> <INDENT> self.task_collection = [] <NEW_LINE> self.wanted_relay_ops = wanted_relay_ops | Reset task collections
Parameters
----------
wanted_relay_ops: List of tvm.ir.Op
The relay ops to be extracted | 625941e976e4537e8c351b15 |
def send_for_reprocessing(crash_ids, env, batch_size, auth_token): <NEW_LINE> <INDENT> url = '{}/api/Reprocessing/'.format(URLS[env]) <NEW_LINE> click.echo('Starting reprocessing') <NEW_LINE> for i in range(0, len(crash_ids), batch_size): <NEW_LINE> <INDENT> payload = { 'crash_ids': crash_ids[i:i + batch_size] } <NEW_L... | Send a list of crash IDs to be reprocessed.
| 625941e99f2886367277ad28 |
def get_entity(order_id): <NEW_LINE> <INDENT> client = datastore.Client(config.PROJECT_ID) <NEW_LINE> log('retrieve object for ID: %s' % order_id) <NEW_LINE> entity = load_order_entity(client, order_id) <NEW_LINE> return entity | Load a datastore entity using a particular client, and the ID. | 625941e9cc0a2c11143dd331 |
@bottle.route('/suites') <NEW_LINE> def suites(): <NEW_LINE> <INDENT> s = DBConn().session() <NEW_LINE> q = s.query(Suite) <NEW_LINE> q = q.order_by(Suite.suite_name) <NEW_LINE> ret = [] <NEW_LINE> for p in q: <NEW_LINE> <INDENT> ret.append({'name': p.release_suite_output, 'codename': p.codename, 'dakname': ... | Give information about all known suites.
@maps: name maps to Suite: in the release file
@maps: codename maps to Codename: in the release file.
@maps: dakname is an internal name and should not be relied upon.
@rtype: list of dictionaries
@return: Dictionaries made out of
- name
- codename
-... | 625941e94428ac0f6e5bac95 |
def autoload(interval=1): <NEW_LINE> <INDENT> if not os.environ.get('IMOUTO_APP'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> lockfile = None <NEW_LINE> fd, lockfile = tempfile.mkstemp( prefix='IMOUTO_APP', suffix='.lock') <NEW_LINE> os.close(fd) <NEW_LINE> while os.path.exists(lockfile): <NEW_LINE> <INDENT> args = [... | autoload the user code, work as the following control flow
----------- -----------
| | poll() | |
| main | ==> | sub | exec user code
| process | <== | process |
| | signal | |
----------- -----------
|| / \... | 625941e91f037a2d8b94669c |
def market(self): <NEW_LINE> <INDENT> return self._market | The market of the order event
:return: | 625941e98e05c05ec3eea817 |
@pytest.fixture <NEW_LINE> def supply_testSchema(): <NEW_LINE> <INDENT> return TestSchema | return TestSchema object | 625941e9851cf427c661a9aa |
def extract_label(path, label_dict, label_pos=-2): <NEW_LINE> <INDENT> label = path.split(os.path.sep)[label_pos] <NEW_LINE> if label in label_dict: <NEW_LINE> <INDENT> label = label_dict[label] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> label = 0 <NEW_LINE> <DEDENT> return label | extract the class label from the image path | 625941e95fcc89381b1e1b61 |
def save_page(self, page, job, text, banner): <NEW_LINE> <INDENT> if job.dry_run: <NEW_LINE> <INDENT> self.logger.debug("[DRY RUN] Banner: %s", banner) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> summary = job.summary.replace("$3", banner) <NEW_LINE> page.edit(text, self.make_summary(summary), minor=True) | Save a page with an updated banner. | 625941e9a05bb46b383eccbc |
def test_dashes_string(self): <NEW_LINE> <INDENT> text1 = Link.normalize_key('-') <NEW_LINE> text2 = Link.normalize_key('--') <NEW_LINE> text3 = Link.normalize_key('hello-there') <NEW_LINE> text4 = Link.normalize_key('hello--there') <NEW_LINE> text5 = Link.normalize_key('-hello-there-') <NEW_LINE> text6 = Link.normaliz... | Test strings with dashes. | 625941e915baa723493c4418 |
def doppler(freq_observed, voverc): <NEW_LINE> <INDENT> return freq_observed * (1.0 + voverc) | doppler(freq_observed, voverc):
This routine returns the frequency emitted by a pulsar
(in MHz) given that we observe the pulsar at frequency
freq_observed (MHz) while moving with radial velocity
(in units of v/c) of voverc wrt the pulsar. | 625941e9627d3e7fe0d692f1 |
def _colate_features_to_feeds_and_fetches(continue_from, signature, features, graph): <NEW_LINE> <INDENT> if _feature_keys.FilteringResults.STATE_TUPLE in continue_from: <NEW_LINE> <INDENT> state_values = _head.state_to_dictionary( continue_from[_feature_keys.FilteringResults.STATE_TUPLE]) <NEW_LINE> <DEDENT> else: <NE... | Uses a saved model signature to construct feed and fetch dictionaries. | 625941e9be7bc26dc91cda96 |
def test_configure_version(self): <NEW_LINE> <INDENT> with patch('argyle.postgres.confirm') as confirm: <NEW_LINE> <INDENT> with patch('argyle.postgres.detect_version') as version: <NEW_LINE> <INDENT> confirm.return_value = True <NEW_LINE> postgres.reset_cluster(pg_version='8.4') <NEW_LINE> self.assertSudoCommand('pg_d... | Use given version without detection if given. | 625941e9566aa707497f4a01 |
def set(self, value: float): <NEW_LINE> <INDENT> if value > self.max or value < self.min: <NEW_LINE> <INDENT> raise ValueError((f"Set value {value} is too {'low' if value < self.min else 'high'}. " f"The min value is {self.min}. The max value is {self.max}")) <NEW_LINE> <DEDENT> if self._setter(self.element_uid, value)... | Set the multilevel switch of the given element_uid to the given value.
:param value: Value to set | 625941e9a4f1c619b28b04cd |
def prc_curve(y_true, y_probas, pos_label=None, sample_weight=None): <NEW_LINE> <INDENT> from sklearn.metrics import precision_recall_curve <NEW_LINE> return precision_recall_curve(y_true, y_probas, pos_label, sample_weight) | Compute precision-recall pairs for different probability thresholds
Note: this implementation is restricted to the binary classification task.
The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of
true positives and ``fp`` the number of false positives. The precision is
intuitively the ability o... | 625941e92eb69b55b151cd55 |
def names(df: pd.DataFrame, regex: str = None, astype: str = 'list') -> Union[str, list, dict, pd.Series, pd.DataFrame]: <NEW_LINE> <INDENT> cols = df.columns.tolist() <NEW_LINE> if regex: <NEW_LINE> <INDENT> cols = list(filter(re.compile(regex).match, cols)) <NEW_LINE> <DEDENT> if astype == 'dict': <NEW_LINE> <INDENT>... | show dataframe column information
This function is useful reviewing or manipulating column(s)
The dictionary output is particularly useful when composing the rename of
multiple columns.
Examples
--------
.. code-block::
import numpy as np
import pandas as pd
id_list = ['A', 'B', 'C', 'D', 'E']
s1 ... | 625941e957b8e32f5248393d |
def usersmenu(): <NEW_LINE> <INDENT> ui.keymenu([ ("1", "Users", manageusers, None), ("2", "Tokens", managetokens, None), ("3", "Current user information", display_info, None), ], title="Manage Users") | Create and edit users and tokens
| 625941e907f4c71912b11924 |
def test___init__(self): <NEW_LINE> <INDENT> result = validate._CheckMainKeys('string') <NEW_LINE> self.assertEqual(result.valid(), False) | Testing function __init__. | 625941e97047854f462a18a3 |
def __generate_token(uid, client_type, authority=None, expiration=7200): <NEW_LINE> <INDENT> s = TimedJSONWebSignatureSerializer(current_app.config['SECRET_KEY'], expiration) <NEW_LINE> return s.dumps({'uid': uid, 'type': client_type, 'authority': authority}) | 生成令牌 | 625941e98e05c05ec3eea818 |
def set_style_sheet_text( styleSheetId: StyleSheetId, text: str ) -> Generator[dict, dict, Optional[str]]: <NEW_LINE> <INDENT> response = yield { "method": "CSS.setStyleSheetText", "params": {"styleSheetId": str(styleSheetId), "text": text}, } <NEW_LINE> return response.get("sourceMapURL") | Sets the new stylesheet text.
Parameters
----------
styleSheetId: StyleSheetId
text: str
Returns
-------
sourceMapURL: Optional[str]
URL of source map associated with script (if any). | 625941e98da39b475bd65419 |
def prepare_batch(self, features, texts): <NEW_LINE> <INDENT> assert len(features) == len(texts), "Inputs and outputs to the network must be of the same number" <NEW_LINE> input_lengths = [f.shape[0] for f in features] <NEW_LINE> max_length = max(input_lengths) <NEW_LINE> nr_channels = features[0].shape[1] <... | Featurize a minibatch of data, zero pad them and return a dictionary
Params:
features (list(np.array)): List of ECoG data
texts (list(str)): List of texts corresponding to the features
Returns:
dict: See below for contents | 625941e9377c676e91272646 |
def fit(self, X, y=None, **fit_params): <NEW_LINE> <INDENT> self.fit_transform(X, y, **fit_params) <NEW_LINE> return self | Fit estimator to X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples and
`n_features` is the number of features.
y : None, default=None
Not used in the fitting process but kept for compatibility.
fit_params : dict, optional
... | 625941e996565a6dacc8fb69 |
def D2_FinitDiff2Central_Coeff(N, dx): <NEW_LINE> <INDENT> DN = np.zeros([N, N]) <NEW_LINE> DN[0, 0] = -2. <NEW_LINE> DN[0, 1] = 1. <NEW_LINE> for ii in range(1, N - 1): <NEW_LINE> <INDENT> DN[ii, ii - 1] = 1. <NEW_LINE> DN[ii, ii] = -2. <NEW_LINE> DN[ii, ii + 1] = 1. <NEW_LINE> <DEDENT> DN[-1, -1] = 2. <NEW_LINE> DN[-... | Returns the coefficient of the derivative matrix as in FinitDiff2Central | 625941e93c8af77a43ae3c45 |
def _on_enter(self,**kwargs): <NEW_LINE> <INDENT> self._update_from_kwargs(**kwargs) <NEW_LINE> logger.info("Start: < {} > file name: {}".format(self.label,self._raw_fname)) <NEW_LINE> if self._debug: <NEW_LINE> <INDENT> logger.debug("config parameter:\n{}".format(self._cfg)) <NEW_LINE> <DEDENT> self._run = True <NEW_L... | :return:
raw_fname, raw obj | 625941e93cc13d1c6d3c7817 |
def rename_results(self): <NEW_LINE> <INDENT> logger.debug("Renaming analysis results") <NEW_LINE> for result in AnalysisResult.objects.filter(analysis_uuid=self.uuid): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> item = FileStoreItem.objects.get(uuid=result.file_store_uuid) <NEW_LINE> <DEDENT> except (FileStoreItem.Do... | Rename files in file_store after download | 625941e9796e427e537b0a69 |
def getCrashDumpForPools(self): <NEW_LINE> <INDENT> return sorted(x.id for x in self.crash_dump_for_pools.objectValuesGen()) | Return a sorted list of related Pool ids.
Used by modeling. | 625941e9b7558d58953c53aa |
def getEntitiesByUri(self, uri, sort=None): <NEW_LINE> <INDENT> return self.query( self._properties['uri'] >= uri, self._properties['uri'] < uri + u'\uFFFD' ).order(self._properties['uri']).fetch() | if sort:
sort = sort.lower()
if sort == 'uri':
pass
elif sort == 'type':
pass
elif sort == 'size':
pass
elif sort == 'ctime':
pass
elif sort == 'mtime':
pass
elif sort == 'atime':
pass
else:
pass | 625941e97047854f462a18a4 |
def collect_tweets(category): <NEW_LINE> <INDENT> result_directory = './result/'+category+'/' <NEW_LINE> if not os.path.isdir(result_directory): <NEW_LINE> <INDENT> os.mkdir(result_directory) <NEW_LINE> open(result_directory+'finished.txt', 'a').close() <NEW_LINE> user_data = pd.read_csv(category+'.txt', sep="\t") <NEW... | :param category: name of the userlist txt file.
:return: txt files for tweet messages, plus three txt files under the directory 'result'.
(user id).txt is the collection of 'pure' tweet messages made by the person with the user id.
tocollect.txt is the user ID's to be collected
finished.txt is t... | 625941e9be8e80087fb210db |
def make_z_scatter_plot(las, output_file): <NEW_LINE> <INDENT> print("Making scatter plot...") <NEW_LINE> start_time = time.time() <NEW_LINE> xArray, yArray, zArray = [las.x, las.y, las.z] <NEW_LINE> plt.scatter(xArray, yArray, c=zArray, cmap='RdYlGn_r', alpha=0.75, marker='.') <NEW_LINE> plt.axis('off') <NEW_LINE> plt... | make a scatter plot image of points with height as color | 625941e9e64d504609d74cdf |
def _parsedirstate(self, content): <NEW_LINE> <INDENT> f = util.stringio(content) <NEW_LINE> p1 = f.read(20) or node.nullid <NEW_LINE> p2 = f.read(20) or node.nullid <NEW_LINE> header = f.read(len(HEADER)) <NEW_LINE> if header and header != HEADER: <NEW_LINE> <INDENT> raise error.Abort(_("working directory state appear... | Parse given dirstate metadata file | 625941e91d351010ab855fba |
def glInitInstancedArraysARB(): <NEW_LINE> <INDENT> from OpenGL import extensions <NEW_LINE> return extensions.hasGLExtension( _EXTENSION_NAME ) | Return boolean indicating whether this extension is available | 625941e9498bea3a759b9f4d |
def ciclo_infinito(): <NEW_LINE> <INDENT> i = 1 <NEW_LINE> while i <= 10: <NEW_LINE> <INDENT> print(i, end=" ") | Imprime el número 1 infinitas veces | 625941e9187af65679ca55bf |
def setAutosharing( self, experiment_sharing=UNSPECIFIED, protocol_sharing=UNSPECIFIED, resource_sharing=UNSPECIFIED ): <NEW_LINE> <INDENT> self.update() <NEW_LINE> if self.security_policy is None: <NEW_LINE> <INDENT> import labstep.generic.entity.repository as entityRepository <NEW_LINE> policy = entityRepository.newE... | Parameters
----------
experiment_sharing (str)
Automatically share experiments
you create and own with this workspace. Set to True or False
protocol_sharing (str)
Automatically share protocols
you create and own with this workspace. Set to True or False
resource_sharing (str)
Automatically share r... | 625941e9009cb60464c6384d |
def sessionmaker(bind=None, class_=None, autoflush=True, autocommit=False, expire_on_commit=True, **kwargs): <NEW_LINE> <INDENT> kwargs['bind'] = bind <NEW_LINE> kwargs['autoflush'] = autoflush <NEW_LINE> kwargs['autocommit'] = autocommit <NEW_LINE> kwargs['expire_on_commit'] = expire_on_commit <NEW_LINE> if class_ is ... | Generate a custom-configured :class:`.Session` class.
The returned object is a subclass of :class:`.Session`, which, when instantiated
with no arguments, uses the keyword arguments configured here as its
constructor arguments.
It is intended that the :func:`.sessionmaker()` function be called within the
global scope ... | 625941e94e4d5625662d4871 |
def prep(self): <NEW_LINE> <INDENT> if self.short_message: <NEW_LINE> <INDENT> self.sm_length = len(self.short_message) <NEW_LINE> delattr(self, 'message_payload') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.sm_length = 0 | Prepare to generate binary data | 625941e997e22403b379d43b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.