code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def ignored_dct(): <NEW_LINE> <INDENT> consts = gen_consts() <NEW_LINE> consts = [c for c in consts if c.weight() in [18, 20]] <NEW_LINE> return {c: [6] for c in consts} | Return value will be passed to GivenWtBase._basis_const_base.
| 625941e65510c4643540f828 |
def _get_covariance_matrix(self, name=None): <NEW_LINE> <INDENT> if name: <NEW_LINE> <INDENT> index = self.ml.parameters.loc[ self.ml.parameters.loc[:, "name"] == name].index <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> index = self.ml.parameters.index <NEW_LINE> <DEDENT> pcov = self.pcov.reindex(index=index, columns=... | Internal method to obtain the covariance matrix from the model.
Parameters
----------
name: str, optional
Name of the stressmodel or model component to obtain the
parameters for.
Returns
-------
pcov: pandas.DataFrame
Pandas DataFrame with the covariances for the parameters. | 625941e6bde94217f368323c |
def add_layer(self,name): <NEW_LINE> <INDENT> if "eth" in name: <NEW_LINE> <INDENT> self.data["eth"] = EthPacket() <NEW_LINE> <DEDENT> elif "ip" in name: <NEW_LINE> <INDENT> self.data["ip"] = IPPacket() <NEW_LINE> <DEDENT> elif "udp" in name: <NEW_LINE> <INDENT> self.data["udp"] = UDPPacket() <NEW_LINE> <DEDENT> elif "... | Add a new network layer to the dictionary. | 625941e6377c676e912725f6 |
def silverman_covariance(xdata, model=None): <NEW_LINE> <INDENT> xdata = np.atleast_2d(xdata) <NEW_LINE> d, n = xdata.shape <NEW_LINE> return variance_bandwidth(np.power(n * (d + 2.) / 4., -1. / (d + 4.)), xdata) | The Silverman bandwidth is defined as a variance bandwidth with factor:
.. math::
\tau = \left( n \frac{d+2}{4} \right)^\frac{-1}{d+4} | 625941e699fddb7c1c9de7de |
def dispose(self): <NEW_LINE> <INDENT> log.debug('Disposing') <NEW_LINE> self.stop_all(wait=True) <NEW_LINE> self._stop() <NEW_LINE> log.debug('Removed jobs.') <NEW_LINE> self._output = None <NEW_LINE> log.debug('Removed output.') <NEW_LINE> self._q_completed.clear() <NEW_LINE> log.debug('Removed completed.') <NEW_LINE... | Clears all output and stops the queue system pulse. | 625941e68da39b475bd653c8 |
def get_current_theme(): <NEW_LINE> <INDENT> style_dict = sys.modules["thorpy.miscgui.style"].__dict__ <NEW_LINE> painterstyle_dict = sys.modules["thorpy.miscgui.painterstyle"].__dict__ <NEW_LINE> style_dict_clean = {} <NEW_LINE> painterstyle_dict_clean = {} <NEW_LINE> for key, value in iter(style_dict.items()): <NEW_L... | Returns style and painterstyle variables into dictionnaries. | 625941e6be8e80087fb2108b |
def __init__(self, root=None): <NEW_LINE> <INDENT> if root is None: <NEW_LINE> <INDENT> self.root = self._get_git_root() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.root = root <NEW_LINE> <DEDENT> super().__init__(self) | Initialize a few necessary parameters. | 625941e6236d856c2ad44c2f |
def process(self, conversations): <NEW_LINE> <INDENT> self.network = NetworkStat() <NEW_LINE> for channel in conversations: <NEW_LINE> <INDENT> self.channel = self.network.channels[channel] <NEW_LINE> for date, conversation in conversations[channel].items(): <NEW_LINE> <INDENT> self.day = self.channel.days[date] <NEW_L... | Process a list of conversations and return a NetworkStat object. | 625941e6009cb60464c637fd |
def get_current_user(): <NEW_LINE> <INDENT> identity = get_jwt_identity() <NEW_LINE> usuario_id = int(identity.split('-')[0]) <NEW_LINE> facebook_id = int(identity.split('-')[1]) <NEW_LINE> return {'id': usuario_id, 'facebook_id': facebook_id} | Gets the current used based on get_jwt_identify
Returns:
(dict): Containing the usuario_id and the facebook_id | 625941e62eb69b55b151cd05 |
def test_book_order_by_non_existent_field(self): <NEW_LINE> <INDENT> return self._order_by_field('another_non_existent_field', self.books_url, check_ordering=False) | Order by non-existent field. | 625941e60a50d4780f6672e5 |
def wheelEvent(self, event: QWheelEvent): <NEW_LINE> <INDENT> delta = event.angleDelta() <NEW_LINE> if delta.y() == 0: <NEW_LINE> <INDENT> event.ignore() <NEW_LINE> return <NEW_LINE> <DEDENT> d = delta.y() / abs(delta.y()) <NEW_LINE> if d > 0.0: <NEW_LINE> <INDENT> self.scale_up() <NEW_LINE> <DEDENT> else: <NEW_LINE> <... | wheelEvent
Parameters
----------
event : QWheelEvent | 625941e63539df3088e2e79b |
def is_selection_key(self, key): <NEW_LINE> <INDENT> if key == 'C n' or key == 'C f' or key == 'down': <NEW_LINE> <INDENT> self.cand_index += 1 <NEW_LINE> return True <NEW_LINE> <DEDENT> elif key == 'C p' or key == 'C b' or key == 'up': <NEW_LINE> <INDENT> self.cand_index -= 1 <NEW_LINE> return True <NEW_LINE> <DEDENT>... | Handle selection keys | 625941e692d797404e3045db |
def _do_quickxplain(core): <NEW_LINE> <INDENT> wset = core[:] <NEW_LINE> filt_sz = len(wset) / 2.0 <NEW_LINE> while filt_sz >= 1: <NEW_LINE> <INDENT> i = 0 <NEW_LINE> while i < len(wset): <NEW_LINE> <INDENT> to_test = wset[:i] + wset[(i + int(filt_sz)):] <NEW_LINE> self.calls += 1 <NEW_LINE> if to_test and not self.ora... | Do QuickXplain-like search. | 625941e629b78933be1e5af6 |
def get_page_sourcecode(self): <NEW_LINE> <INDENT> return self.driver.page_source | Returns page source code | 625941e6de87d2750b8601e6 |
def __str__(self): <NEW_LINE> <INDENT> return self.name | Text representation of ProgressOutcome object.
Returns:
String describing ProgressOutcome. | 625941e66e29344779a62a5f |
def findPairs(self, nums, k): <NEW_LINE> <INDENT> from collections import Counter <NEW_LINE> counter=Counter(nums) <NEW_LINE> res=0 <NEW_LINE> for i in counter: <NEW_LINE> <INDENT> if k>0 and i+k in counter or (k==0 and counter[i]>1): <NEW_LINE> <INDENT> res+=1 <NEW_LINE> <DEDENT> <DEDENT> return res | :type nums: List[int]
:type k: int
:rtype: int | 625941e6167d2b6e31218fe4 |
def conf_read_file(self, path=None): <NEW_LINE> <INDENT> self.require_state("configuring", "connected") <NEW_LINE> if path is not None and not isinstance(path, str): <NEW_LINE> <INDENT> raise TypeError('path must be a string') <NEW_LINE> <DEDENT> ret = run_in_thread(self.librados.rados_conf_read_file, (self.cluster, c_... | Configure the cluster handle using a Ceph config file.
:param path: path to the config file
:type path: str | 625941e6460517430c3945c9 |
def createrepos(self): <NEW_LINE> <INDENT> logger.info('') <NEW_LINE> logger.info('Updating metadata') <NEW_LINE> procs = [] <NEW_LINE> for distro in self.distros: <NEW_LINE> <INDENT> logger.info(' Creating metadata for %s', distro) <NEW_LINE> for path in self.realized_paths: <NEW_LINE> <INDENT> dst_dir = os.path.join... | Generate the yum repositories metadata | 625941e6442bda511e8be861 |
def update_w(self): <NEW_LINE> <INDENT> if self.flagged: <NEW_LINE> <INDENT> self._w.attr = 'flagged' <NEW_LINE> self._w.focus_attr = 'flagged focus' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._w.attr = 'body' <NEW_LINE> self._w.focus_attr = 'focus' | Update the attributes of self.widget based on self.flagged.
| 625941e65fcc89381b1e1b11 |
def scale_data(data, header, channel_names, data_shape): <NEW_LINE> <INDENT> MAX = 65536.0 <NEW_LINE> data = data/MAX <NEW_LINE> row, col = data_shape[0] <NEW_LINE> chan_scale = [] <NEW_LINE> for i, head in enumerate(header): <NEW_LINE> <INDENT> if 'Scan size' in head[0]: <NEW_LINE> <INDENT> m = re.search('(\d+) nm', h... | use header data to scale data to proper units
all lengths are in um, heights in nm | 625941e6b830903b967e9d56 |
def cmd_pkg_check(package, options): <NEW_LINE> <INDENT> packages = source_package.source_package_iterator() <NEW_LINE> if cmd_pkg_check.all_pkg_names is None: <NEW_LINE> <INDENT> cmd_pkg_check.all_pkg_names = [os.path.basename(p.root) for p in packages] <NEW_LINE> <DEDENT> util.log("Checking deps for %s .." % package.... | Verify dependency information for given package(s) | 625941e6fff4ab517eb2f88e |
def _validate_recaptcha(self, challenge, response, remote_addr): <NEW_LINE> <INDENT> if current_app.testing: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> private_key = current_app.config['RECAPTCHA_PRIVATE_KEY'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise RuntimeError(... | Performs the actual validation. | 625941e696565a6dacc8fb1a |
def minSwaps(self, data): <NEW_LINE> <INDENT> ones = sum(data) <NEW_LINE> window_sum = sum(data[:ones]) <NEW_LINE> result = ones - window_sum <NEW_LINE> for i in range(len(data) - ones): <NEW_LINE> <INDENT> window_sum -= data[i] <NEW_LINE> window_sum += data[i + ones] <NEW_LINE> result = min(result, ones - window_sum) ... | :type data: List[int]
:rtype: int | 625941e630c21e258bdfa8f1 |
def _callback(self, port, buf): <NEW_LINE> <INDENT> if self.stopped: <NEW_LINE> <INDENT> mmal.mmal_buffer_header_release(buf) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stop = False <NEW_LINE> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> mmal_check( mmal.mmal_buffer_header_mem_lock(buf), prefix="Unable to lock ... | The encoder's main callback function.
When the encoder is active, this method is periodically called in a
background thread. The *port* parameter specifies the MMAL port
providing the output (typically this is the encoder's output port, but
in the case of unencoded captures may simply be a camera port), while
the *buf... | 625941e6aad79263cf390e97 |
def calc_vticks(first, last) : <NEW_LINE> <INDENT> first_hour = time.localtime(first).tm_hour <NEW_LINE> delta_hours = ((last - first) // 3600) <NEW_LINE> return [ str((h + first_hour) % 24) for h in range(delta_hours + 1) ] | Make a list of hour strings from the first job starting to the
last job ending.
Imputs:
first is time in seconds since epoch, of the first job starting
last is time in seconds since epoch of the last job ending. | 625941e68da39b475bd653c9 |
def test_big_task_create_chain(celery_app, mocker, monkeypatch): <NEW_LINE> <INDENT> mocked_task_a = mocker.patch('foo.tasks.task_a') <NEW_LINE> mocked_task_b = mocker.patch('foo.tasks.task_b') <NEW_LINE> is_failed = False <NEW_LINE> @celery_app.task <NEW_LINE> def normal(*args): <NEW_LINE> <INDENT> print("normal %s" %... | Check big_task create the correct signatures.
Here we are going to use the celery_app fixture to define our own tasks to
be called as callback. | 625941e67d43ff24873a30f3 |
def make_error_block(self): <NEW_LINE> <INDENT> B = self.HTMLPage.B <NEW_LINE> fieldset = self.HTMLPage.fieldset("Errors") <NEW_LINE> fieldset.set("class", "errors") <NEW_LINE> ul = B.UL() <NEW_LINE> for error in self.errors: <NEW_LINE> <INDENT> ul.append(B.LI(error, B.CLASS("errors"))) <NEW_LINE> <DEDENT> fieldset.app... | Create a box showing the errors preventing the save request. | 625941e6097d151d1a2232a7 |
def elevation(self, point): <NEW_LINE> <INDENT> point = np.asarray(point) <NEW_LINE> s = self.find_simplices(point) <NEW_LINE> if s == -1: <NEW_LINE> <INDENT> return np.nan <NEW_LINE> <DEDENT> p = self.points <NEW_LINE> n = self.normal(s) <NEW_LINE> s = self.tri.simplices[s] <NEW_LINE> if n[2] != 0: <NEW_LINE> <INDENT>... | Returns the elevation of the TIN surface at the input point. Returns
NaN if the TIN surface does not exist at that point.
Parameters
----------
point : array
A point for which the elevation will be calculated. The point
must be of shape (2,) or (3,). | 625941e60c0af96317bb8637 |
def build_node_set(node, s=None): <NEW_LINE> <INDENT> if s is None: <NEW_LINE> <INDENT> s = set() <NEW_LINE> <DEDENT> if node is None or ( node in s and all(n in s for n in node.upstreams) and all(n in s for n in node.downstreams) ): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> new_nodes = {n for n in node.downstream... | Build a set of all the nodes in a streamz graph
Parameters
----------
node : Stream
The node to use as a starting point for building the set
s : set or None
The set to put the nodes into. If None return a new set full of nodes
Returns
-------
s : set
The set of nodes in the graph | 625941e624f1403a92600fb2 |
def ptb_producer(raw_data, batch_size, num_steps, L, name=None): <NEW_LINE> <INDENT> with tf.name_scope(name, "PTBProducer", [raw_data, batch_size, num_steps]): <NEW_LINE> <INDENT> raw_data = tf.convert_to_tensor(raw_data, name="raw_data", dtype=tf.int32) <NEW_LINE> data_len = tf.size(raw_data) <NEW_LINE> batch_len = d... | Iterate on the raw PTB data.
This chunks up raw_data into batches of examples and returns Tensors that
are drawn from these batches.
Args:
raw_data: one of the raw data outputs from ptb_raw_data.
batch_size: int, the batch size.
num_steps: int, the number of unrolls.
L: extra data on input for context.
name... | 625941e6fb3f5b602dac3ae7 |
def get_tiezi(self): <NEW_LINE> <INDENT> doc = self.get_parse_page() <NEW_LINE> pageIndex = doc('#thread_theme_5 .red').text() <NEW_LINE> items = doc('#pb_content .left_section .p_postlist .l_post.l_post_bright.j_l_post.clearfix ').items() <NEW_LINE> title = self.get_title() <NEW_LINE> author_image = doc('#j_p_postlis... | 抓取帖子内容
:return: | 625941e6f7d966606f6aa459 |
def max_radius(bottom_left_corner, dimensions): <NEW_LINE> <INDENT> b_x, b_y = bottom_left_corner[0], bottom_left_corner[1] <NEW_LINE> w, h = dimensions[0], dimensions[1] <NEW_LINE> lengths = [((b_x+a*w)**2+(b_y-b*h)**2)**0.5 for (a, b) in [(0, 0), (0, 1), (1, 0), (1, 1)]] <NEW_LINE> return max(lengths) | given the bottom left corner and width and height, returns the
min radius needed to completely enclose the rectangle. | 625941e69b70327d1c4e1227 |
def firstRule(self, cube: Pos) -> bool: <NEW_LINE> <INDENT> assert self.isActive(cube) <NEW_LINE> return self.neighboursActiveInRange(cube, min=2, max=3) | Return True if the cube shall be activated by the first rule:
The cube must be active.
If exactly 2 or 3 neighbors are active, the cube remains active.
Otherwise, the cube becomes inactive. | 625941e6fb3f5b602dac3ae8 |
def is_sro(value, stix_version=stix2.version.DEFAULT_VERSION): <NEW_LINE> <INDENT> result = True <NEW_LINE> if isinstance(value, collections.abc.Mapping): <NEW_LINE> <INDENT> value_stix_version = detect_spec_version(value) <NEW_LINE> if value_stix_version != stix_version: <NEW_LINE> <INDENT> result = False <NEW_LINE> <... | Determine whether the given object, type, or ID is/is for an SRO of the
given STIX version. If value is a type or ID, this just checks whether
the type is "sighting" or "relationship". If a mapping, *simple* STIX
version inference is additionally done on the value, and the result is
checked against stix_version. It ... | 625941e6925a0f43d254a2cb |
def ReadPkscLightCone(i): <NEW_LINE> <INDENT> halos = HaloLightCone() <NEW_LINE> filename = params.folder+params.inputfile <NEW_LINE> Nreads = params.Nreads <NEW_LINE> pkfile = open(filename,"rb") <NEW_LINE> halos.Non = np.fromfile(pkfile, dtype=np.int32, count=1).astype('int')[0] <NEW_LINE> halos.RTHmax ... | @brief Reads peakpatch output in binary format into an object. | 625941e621a7993f00bc8147 |
def media_seek(self, position): <NEW_LINE> <INDENT> self.cmus.seek(position) | Send seek command. | 625941e64a966d76dd551463 |
def check_spider_all_len_value_stat(json_list, write_file_path): <NEW_LINE> <INDENT> all_keys_dict = dict() <NEW_LINE> count = 0 <NEW_LINE> all_count = len(json_list) <NEW_LINE> for item_dict in json_list: <NEW_LINE> <INDENT> for key, value in dict(item_dict).items(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> len_va... | 检查并收集各个字段长度的统计
:return: | 625941e60c0af96317bb8638 |
def find(dict, item, beta=True): <NEW_LINE> <INDENT> if item in dict: <NEW_LINE> <INDENT> return dict[item], item <NEW_LINE> <DEDENT> for key, value in sorted(dict.iteritems(), key=lambda k_v: (k_v[1], k_v[0])): <NEW_LINE> <INDENT> if re.match(key, item, re.I): <NEW_LINE> <INDENT> return dict[key], key <NEW_LINE> <DEDE... | Find value in dictionary.
| 625941e621bff66bcd684d9e |
def step_average(self): <NEW_LINE> <INDENT> return self.step_sum / (self.step or 1) | Computes average reward per step. | 625941e6d486a94d0b98e597 |
def get_guesses(self): <NEW_LINE> <INDENT> if self.guesses is not None: <NEW_LINE> <INDENT> return self.guesses <NEW_LINE> <DEDENT> print("RECALCULATING GUESSES") <NEW_LINE> self.guesses = get_all(Animal) <NEW_LINE> for animal in self.guesses: <NEW_LINE> <INDENT> animal.prob = 1 <NEW_LINE> <DEDENT> self.guesses = norma... | Get a weighted list of animals that 'best' fit our information | 625941e6a934411ee3751ae5 |
def train(self,X_train,y_train): <NEW_LINE> <INDENT> self.X_train = X_train <NEW_LINE> self.y_train = y_train <NEW_LINE> tree = self.TreeGenerate(X_train,y_train) <NEW_LINE> self.Tree = self.pruning(tree) | 对于类别属性来说,有两种处理方法:
1. 按属性中所有的值来分类来生成树(C3.0等早期分类树就是这种方式)
2. 将类别属性One-hot 编码来这样就只有0-1变量了。(Xgboost,CART 是这种)
3. 其实如果按照最好的离散属性分割方式,应该穷举所有的组合,找到一个最好的分割方式。H20好像有这种实践。
对于连续属性来说,就很好办了,直接二分分类。
属性中的值来说,一般来说,如果是(0,1)变量,那么每次分类后就可以去掉这个特征了,对于连续变量就不是了,要继续保留参与分割。
本算法采用方法2处理离散变量。即不再区分特征是离散变量还是连续变量,这样做能降低代码复杂度,而且做到了分类和回归任务的统一处理。
本算法仅仅生... | 625941e6bd1bec0571d90a7f |
def parse_sane_cookie_date(self): <NEW_LINE> <INDENT> savepos = self.pos <NEW_LINE> date_str = self.parse_until(b'GMT') <NEW_LINE> date_str = date_str + self.parse(b'GMT') <NEW_LINE> try: <NEW_LINE> <INDENT> return params.FullDate.from_http_str(date_str) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.s... | Parses the sane-cookie-date production.
This is the stricter syntax defined in section 4. The returns
result is a :class:`~params.FullDate` instance. | 625941e68a43f66fc4b544b1 |
def createNewJobs(self, wmbsJobs): <NEW_LINE> <INDENT> existingTransaction = self.beginTransaction() <NEW_LINE> jobsToCreate = [] <NEW_LINE> for wmbsJob in wmbsJobs: <NEW_LINE> <INDENT> runJob = RunJob() <NEW_LINE> runJob.buildFromJob(job=wmbsJob) <NEW_LINE> if runJob.get('status') not in self.states: <NEW_LINE> <INDEN... | _createNewJobs_
Create new jobs in the BossAir database
Accepts WMBS Jobs | 625941e615fb5d323cde0f66 |
def menu_output(user_id, menu_option): <NEW_LINE> <INDENT> if menu_option is 1: <NEW_LINE> <INDENT> print('The balance is', format(account_list[user_id].get_balance(), '0.2f')) <NEW_LINE> <DEDENT> elif menu_option is 2: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> withdraw_amount = float... | :param user_id: account_id
:param menu_option: User's chosen menu option
Performs one of 4 actions to specified account, depending on
the chosen menu option. | 625941e61f5feb6acb0c4f9a |
def getUnicodeEncoding(self): <NEW_LINE> <INDENT> return self.__unicodeEncoding | return the unicode encoding used for the class | 625941e6283ffb24f3c55d4d |
def has_previous_records(self): <NEW_LINE> <INDENT> return False | Check whether there are records which can be used to continue the simulation
:return has_previous_records: | 625941e63346ee7daa2b31bf |
def viewRangeChanged(self): <NEW_LINE> <INDENT> px_h = self.pixelHeight() <NEW_LINE> px_w = self.pixelWidth() <NEW_LINE> if self._px_h != px_h or self._px_w != px_w: <NEW_LINE> <INDENT> self._px_h = px_h <NEW_LINE> self._px_w = px_w <NEW_LINE> self.generatePicture() | Called whenever the view coordinates of the ViewBox containing this item have changed. | 625941e6d18da76e2353292c |
def message(prompt): <NEW_LINE> <INDENT> pass | message(prompt) -> None
Show an info dialog box. Pops up an info box (with a 'i' and the text message) and waits for the user to hit the OK button.
@param prompt: Present user with this message.
@return: None | 625941e6796e427e537b0a1a |
def rob(self, nums): <NEW_LINE> <INDENT> if not nums: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if len(nums) == 1: <NEW_LINE> <INDENT> return nums[0] <NEW_LINE> <DEDENT> if len(nums) == 2: <NEW_LINE> <INDENT> return max(nums) <NEW_LINE> <DEDENT> last = [nums[0], nums[1], nums[2] + nums[0]] <NEW_LINE> for i in ra... | :type nums: List[int]
:rtype: int | 625941e6566aa707497f49b3 |
def join_room(self, room, username=None, password=None): <NEW_LINE> <INDENT> join_pres = self.build_room_presence(room, username, password) <NEW_LINE> return self.send_stanza(join_pres) | Send join presence. This function doesn't touch self.rooms variable at all.
Instead, when server responses with "ok" presence, we add that room to self.rooms | 625941e6b545ff76a8914266 |
def _crow_int_to_python(data, num_of_rows, nbytes=None, micro=False): <NEW_LINE> <INDENT> if num_of_rows > 0: <NEW_LINE> <INDENT> return [ None if ele == FieldType.C_INT_NULL else ele for ele in ctypes.cast(data, ctypes.POINTER(ctypes.c_int))[:abs(num_of_rows)][::-1] ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret... | Function to convert C int row to python row
| 625941e6fbf16365ca6f661d |
def change(self, state, amount): <NEW_LINE> <INDENT> pass | Method to be overwritten.
Changes the object in some way if the interval has passed. | 625941e60383005118ecfa32 |
def right_insert(unorder): <NEW_LINE> <INDENT> if not isinstance(unorder, list): <NEW_LINE> <INDENT> print("Type error,need LIST !") <NEW_LINE> <DEDENT> length = len(unorder) <NEW_LINE> if length <= 1: <NEW_LINE> <INDENT> return unorder <NEW_LINE> <DEDENT> for index in range(1, length): <NEW_LINE> <INDENT> insert_num =... | unorder: 待排列表 | 625941e6adb09d7d5db6cbdd |
def _i_suffix(i: int) -> str: <NEW_LINE> <INDENT> i_str = str(i) <NEW_LINE> suff_123 = {1: 'st', 2: 'nd', 3: 'rd'} <NEW_LINE> suff_th = 'th' <NEW_LINE> i_last_num = int(i_str[-1]) <NEW_LINE> return suff_123[i_last_num] if i_last_num in suff_123 else suff_th | Checks the number and returns the appropriate suffix for it. | 625941e6e64d504609d74c90 |
def probOcurrence(count): <NEW_LINE> <INDENT> nEvents = sum(count) <NEW_LINE> prob = [1.0*x/nEvents for x in count] <NEW_LINE> density = [] <NEW_LINE> total = 0 <NEW_LINE> for p in prob: <NEW_LINE> <INDENT> total += p <NEW_LINE> density.append(total) <NEW_LINE> <DEDENT> return density | Calculates the accumulated probability of an event
:param count: a list with event's count
:return: a list with probabilities | 625941e6ac7a0e7691ed4515 |
def test_create(self): <NEW_LINE> <INDENT> for solver in ['newton']: <NEW_LINE> <INDENT> self._test_create(self.sf, self.target, self.features, solver, self.def_kwargs, True) <NEW_LINE> self._test_create(self.sf, self.target, self.features, solver, self.def_kwargs, False) | Driver for testing create function under various inputs. | 625941e6596a897236089f0b |
def entropy(examples): <NEW_LINE> <INDENT> classes_distinct = [] <NEW_LINE> classes_all = [] <NEW_LINE> for e in range(len(examples)): <NEW_LINE> <INDENT> classes_all.append(examples[e]['Class']) <NEW_LINE> if examples[e]['Class'] not in classes_distinct: <NEW_LINE> <INDENT> classes_distinct.append(examples[e]['Class']... | takes dictionary of examples and target attribute, returns entropy | 625941e6aad79263cf390e98 |
def find_next_valid_lat(abs_lat, current, max_lat): <NEW_LINE> <INDENT> l = len(abs_lat) <NEW_LINE> i = current <NEW_LINE> while (i < l) and (abs_lat[i] >= max_lat): <NEW_LINE> <INDENT> i = i + 1 <NEW_LINE> <DEDENT> return i | Return the index of the next absolute latitude which is below threshold.
| 625941e67c178a314d6ef8b7 |
def get(self, user_id): <NEW_LINE> <INDENT> with self.connection: <NEW_LINE> <INDENT> admin = self.cursor.execute(f"SELECT * FROM {AdminsWorker.TABLE} WHERE id=?", (user_id,)).fetchone() <NEW_LINE> <DEDENT> return Admin(*admin) | Врнуть одного админа из таблицы по его user_id
возвращает экземпляр класса Admin,
который обладает всеми сопутствующими свойствами | 625941e62c8b7c6e89b35c0e |
def interpolate(self, x, y, z): <NEW_LINE> <INDENT> return self._lib.interpolate3D(ct.pointer(self._ip), ct.c_double(x), ct.c_double(y), ct.c_double(z)) | Interpolate at point (`x`, `y`, `z`). | 625941e623e79379d52ee9af |
def hasMember(self, user): <NEW_LINE> <INDENT> return(user.id in self.members.value) | Checks if a user belongs is in this group.
@param user: the user object
@type user: L{GenericUser}
@rtype: bool | 625941e64428ac0f6e5bac46 |
def parse_mhd(header): <NEW_LINE> <INDENT> file_format = "mhd" <NEW_LINE> dim_order = get_condensed_dim_order(header) <NEW_LINE> data_type = DataType.name_from_metaio(header["ElementType"]) <NEW_LINE> image_size = header["DimSize"] <NEW_LINE> msb = header["BinaryDataByteOrderMSB"] <NEW_LINE> compression = None <NEW_LIN... | Read a metaheader and returns a FileImageDescriptor | 625941e63317a56b8693a09e |
def index(request): <NEW_LINE> <INDENT> status = get_status(request) <NEW_LINE> if request.method == 'POST': <NEW_LINE> <INDENT> form = ConfigurationForm(request.POST, initial=status, prefix='configuration') <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> _apply_changes(request, status, form.cleaned_data) <NEW_LINE>... | Serve the configuration form | 625941e6f7d966606f6aa45a |
def goToPreviousColumn(self): <NEW_LINE> <INDENT> if self.selectedModelColumn > 1: <NEW_LINE> <INDENT> self.selectedModelColumn-=1 <NEW_LINE> self.updateSelectedData() | Select previous column from model
| 625941e6090684286d50f13c |
def get_fixtures(self, type: Type = None, plugin_id: str = '', instance_id: str = '') -> 'Fixtures': <NEW_LINE> <INDENT> matches = Fixtures() <NEW_LINE> [matches.add_fixture(match) for match in self._filter_instances( type=type, plugin_id=plugin_id, instance_id=instance_id)] <NEW_LINE> return matches | Retrieve an ordered filtered list of Fixtures
Parameters:
-----------
Filtering parameters:
type (.plugin.Type|str) : Type of plugin
plugin_id (str) : registry plugin_id
instance_id (str) : plugin instance identifier
Returns:
--------
A List of Fixture structs that matched the arguments,
possibly empty.
If you wan... | 625941e6fbf16365ca6f661e |
def resnet101(pretrained=False, **kwargs): <NEW_LINE> <INDENT> model = ResNet('Bottleneck', [3, 4, 23, 3], **kwargs) <NEW_LINE> if pretrained: <NEW_LINE> <INDENT> model.load_state_dict(model_zoo.load_url(model_urls['resnet101'], model_dir='.'), strict=False) <NEW_LINE> <DEDENT> return model | Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet | 625941e645492302aab5e718 |
def asymmetric_exponential_peak(x, center, amplitude, left_decay, right_decay, c, cap): <NEW_LINE> <INDENT> ix_cen = bisect_right(x, center) <NEW_LINE> xl = center - x[:ix_cen] <NEW_LINE> yl = c + amplitude * np.exp(-xl / left_decay) <NEW_LINE> xr = x[ix_cen:] - center <NEW_LINE> yr = c + amplitude * np.exp(-xr / right... | Asymmetric exponential decay peak function.
Parameters
----------
x : ndarray
Independent variable.
center : int or float
The center of the peak.
amplitude : float
Amplitude parameter.
left_decay : float
Decay for left-hand flank.
right_decay : float
Decay for right-hand flank.
c : float
Consta... | 625941e64e696a04525c989e |
def _getLocalPart(self): <NEW_LINE> <INDENT> return self.__localPart | @return: NS local name
@rtype: basestring | 625941e67cff6e4e81117dd6 |
def addCombinedPerfResult(self, fNames, metricName, value, units, startTime, endTime, pr_ids, label=None): <NEW_LINE> <INDENT> if self.debug >= self.NO_WRITE: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> metric_id = self.findResourceByName(metricName) <NEW_LINE> if metric_id == 0: <NEW_LINE> <INDENT> return 0 <NEW_... | Adds a new combined performance result to the database
Returns 0 if metricName is not already defined in DB
Returns perfResultID if new record added, or 0 if nothing changed in the DB | 625941e6be7bc26dc91cda49 |
def lbtcBalance(lbtcKey, lbtcSecret): <NEW_LINE> <INDENT> hmac_key = lbtcKey <NEW_LINE> hmac_secret = lbtcSecret <NEW_LINE> conn = api.hmac(hmac_key, hmac_secret) <NEW_LINE> lbcBal = conn.call('GET', '/api/wallet-balance/').json() <NEW_LINE> ts = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S... | usage: from lbcapi import api
lbcBalance(key, secret)
returns balance as float | 625941e69b70327d1c4e1228 |
def __init__(self, pod=None, node=None, name=None, role=None, parent=None): <NEW_LINE> <INDENT> if name: <NEW_LINE> <INDENT> if not isinstance(name, str): <NEW_LINE> <INDENT> raise TypeError("Name must be a string") <NEW_LINE> <DEDENT> <DEDENT> if isinstance(parent, str): <NEW_LINE> <INDENT> raise TypeError("Parent obj... | :param pod: String representation of the pod number
:param node: String representation of the node number
:param name: Name of the node
:param role: Role of the node. Valid roles are None, 'spine', 'leaf', 'controller', 'loosenode'
:param parent: Parent pod object of the node. | 625941e6627d3e7fe0d692a2 |
def _isQObjectAlive(obj): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if hasattr(obj, 'parent'): <NEW_LINE> <INDENT> obj.parent() <NEW_LINE> <DEDENT> elif hasattr(obj, 'parentItem'): <NEW_LINE> <INDENT> obj.parentItem() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Cannot determine whether Qt object %... | An approximation of PyQt's isQObjectAlive().
| 625941e6a219f33f34628db4 |
def configure_control_network(module, network): <NEW_LINE> <INDENT> cli = pn_cli(module) <NEW_LINE> cli += ' fabric-info format control-network ' <NEW_LINE> current_control_network = run_cli(module, cli).split() <NEW_LINE> if len(current_control_network) == 1: <NEW_LINE> <INDENT> cli = pn_cli(module) <NEW_LINE> cli += ... | Method to configure the fabric control network.
:param module: The Ansible module to fetch input parameters.
:param network: It can be in-band or management.
:return: The output of run_cli() method. | 625941e6956e5f7376d712bd |
def _set_attr(self, **kwargs): <NEW_LINE> <INDENT> keys = c_str_array(kwargs.keys()) <NEW_LINE> vals = c_str_array([str(s) for s in kwargs.values()]) <NEW_LINE> num_args = mx_uint(len(kwargs)) <NEW_LINE> check_call(_LIB.MXSymbolSetAttrs( self.handle, num_args, keys, vals)) | Set the attribute of the symbol.
Parameters
----------
**kwargs
The attributes to set | 625941e69c8ee82313fbbbc7 |
def svn_fs_print_modules(*args): <NEW_LINE> <INDENT> return _fs.svn_fs_print_modules(*args) | svn_fs_print_modules(svn_stringbuf_t * output, apr_pool_t pool) -> svn_error_t | 625941e6004d5f362079a781 |
def fileExt(repo): <NEW_LINE> <INDENT> for file in sorted( REPOS_DIR.joinpath("apertium-{0}".format(repo)).glob( "apertium-{0}.{0}.*".format(repo) ) ): <NEW_LINE> <INDENT> if file.suffix in (".lexc", ".dix", ".metadix"): <NEW_LINE> <INDENT> return file.suffix.replace(".", "") <NEW_LINE> <DEDENT> <DEDENT> return "unknow... | Returns the extension of the dictionary.
Useful for monolinguals, that can have a .lexc, .dix or .metadix extension | 625941e65fc7496912cc3dce |
def getlistint(self, section, option): <NEW_LINE> <INDENT> return [int(x) for x in self.getlist(section, option)] | Helper function for ConfigParser objects which allows converts values to
a list of integers.
@param section: Section of config parser to read
@param option: Option in section to retrieve
@returns: List of integers built from value stored in CP for section/option. | 625941e63cc13d1c6d3c77c9 |
def _divide_heigths(self, cli, write_position): <NEW_LINE> <INDENT> if not self.children: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> given_dimensions = self.get_dimensions(cli) if self.get_dimensions else None <NEW_LINE> def get_dimension_for_child(c, index): <NEW_LINE> <INDENT> if given_dimensions and given_dim... | Return the heights for all rows.
Or None when there is not enough space. | 625941e6eab8aa0e5d26dfaa |
def create(self, request, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> choice = Choice.objects.select_related('question').get(id=int(request.data['choice_id'])) <NEW_LINE> question = choice.question <NEW_LINE> survey = question.survey <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return Response(sta... | Create answer if same answer is not exist | 625941e6435de62698dfe09e |
def handle_event(self, event, connector_name): <NEW_LINE> <INDENT> return event | Called to process an event message (
:class:`vumi.message.TransportEvent`).
See :meth:`handle_inbound`. | 625941e6d268445f265b52c0 |
def _clause_sat(self, cls): <NEW_LINE> <INDENT> for lit in self.clauses[cls]: <NEW_LINE> <INDENT> if lit in self.var_settings: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | Check if a clause is satisfied by the current variable setting.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([set([1]), set([-1])], set([1]), set([]))
>>> try:
... next(l._find_model())
... except StopIteration:
... pass
>>> l._clause_sat(0)
False
>>> l._clause_sa... | 625941e63539df3088e2e79c |
def _get_subnets_from_network(self, context, network, vif, instance_host=None): <NEW_LINE> <INDENT> ipam_subnets = self.ipam.get_subnets_by_net_id(context, network['project_id'], network['uuid'], vif['uuid']) <NEW_LINE> subnets = [] <NEW_LINE> for subnet in ipam_subnets: <NEW_LINE> <INDENT> subnet_dict = {'cidr': subne... | Returns the 1 or 2 possible subnets for a nova network | 625941e6bde94217f368323e |
def info(self, s): <NEW_LINE> <INDENT> self.__print__(string=s, stream=self.__stderr__, add_newline=True, flush=False) | displays an informative message unicode string to stderr
this appends a newline to that message | 625941e6d6c5a1020814449f |
def destroy_planet(self): <NEW_LINE> <INDENT> self.gravity = None <NEW_LINE> self.kind = 'asteroids' <NEW_LINE> self.size = None <NEW_LINE> self.organic = None <NEW_LINE> self.mineral = None <NEW_LINE> self.colony = None <NEW_LINE> self.special = None <NEW_LINE> self.homeworld = False <NEW_LINE> self.environment = None | Set planet as asteroid field and sets all planet attributes to None/False. | 625941e6a79ad161976cc596 |
def filter_regular(sols, tol, oper): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for sol in sols: <NEW_LINE> <INDENT> rco = diagnostics(sol)[1] <NEW_LINE> if oper == 'select': <NEW_LINE> <INDENT> if rco > tol: <NEW_LINE> <INDENT> result.append(sol) <NEW_LINE> <DEDENT> <DEDENT> if oper == 'remove': <NEW_LINE> <INDENT> if... | Filters solutions in *sols* for the estimate of
the inverse of the condition number.
The input parameters are
1. *sols* is a list of solution strings in PHCpack format,
2. *tol* is the tolerance on the value for the estimate rco
for the inverse of the condition number to decide whether
a solution is singular (i... | 625941e66fece00bbac2db95 |
def _generate_instance_info( self, instance: designspaceLib.InstanceDescriptor, location_normalized: Location, location: Location, font: ufoLib2.Font, ) -> None: <NEW_LINE> <INDENT> info_instance = self.info_mutator.instance_at(location_normalized) <NEW_LINE> if self.round_geometry: <NEW_LINE> <INDENT> info_instance = ... | Generate fontinfo related attributes.
Separate, as fontinfo treatment is more extensive than the rest. | 625941e6099cdd3c635f10aa |
def LocalMax(self, data, kwidth, scaling, out = None): <NEW_LINE> <INDENT> assert len(data.shape) == 3, "Unsupported shape for input data: %s" % (data.shape,) <NEW_LINE> kshape = (kwidth, kwidth) <NEW_LINE> output = np.empty_like(data) <NEW_LINE> for d, o in zip(data, output): <NEW_LINE> <INDENT> maximum_filter(... | Convolve maps with local 2-D max filter.
data -- (3-D) array of input data
kwidth -- (positive int) kernel width
scaling -- (positive int) subsampling factor
out -- (2-D) array in which to store result | 625941e63d592f4c4ed1d4b3 |
def info(self): <NEW_LINE> <INDENT> raise NotImplementedError() | Returns bacs.xsd.problem.InfoType instance. | 625941e6cb5e8a47e48b7ef5 |
def build(self): <NEW_LINE> <INDENT> if self.is_built: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> assert self.ntimes > 0, 'ntimes=%s' % self.ntimes <NEW_LINE> assert self.nelements > 0, 'nelements=%s' % self.nelements <NEW_LINE> assert self.ntotal > 0, 'ntotal=%s' % self.ntotal <NEW_LINE> self.nelements //= self.nt... | sizes the vectorized attributes of the RealNonlinearSpringStressArray | 625941e6236d856c2ad44c31 |
def testValidNames(self): <NEW_LINE> <INDENT> self.init_connection() <NEW_LINE> try: <NEW_LINE> <INDENT> (accepted_names, rejected_names) = self.try_file_names(0) <NEW_LINE> <DEDENT> except SkipException as e: <NEW_LINE> <INDENT> self.skip(e) <NEW_LINE> <DEDENT> lookup_dir_ops = self.ncl.lookup_path(self.tmp_dir) <NEW_... | LOOKUP should succeed on all legal names
Extra test
Comments: This test tries LOOKUP on all names returned from try_file_names() | 625941e650485f2cf553d1ed |
def authentication(): <NEW_LINE> <INDENT> creds = None <NEW_LINE> if os.path.exists('token.pickle'): <NEW_LINE> <INDENT> with open('token.pickle', 'rb') as token: <NEW_LINE> <INDENT> creds = pickle.load(token) <NEW_LINE> <DEDENT> <DEDENT> if not creds or not creds.valid: <NEW_LINE> <INDENT> if creds and creds.expired a... | Authenticate to Google API | 625941e6f548e778e58cd9d1 |
def _setSchedule(self): <NEW_LINE> <INDENT> schedule.every().day.at(self._taskStartTimeStr).do(self._startWatcher) <NEW_LINE> schedule.every().day.at(self._taskStopTimeStr).do(self._stopWatcher) <NEW_LINE> schedule.every().day.at(self._rushTaskStartTimeStr).do(self._startRushWatcher) <NEW_LINE> schedule.every().day.at(... | 1 normal 2 rush 3 normal 4
[----------[========]----------]
1 - inicia o watcher normal: _startWatcher
2 - para o watcher normal e inicia o watcher rush: _startRushWatcher
3 - para o watcher rush e inicia o watcher normal: _stopRushWatcher
4 - para o watcher normal: _stopWatcher | 625941e6293b9510aa2c36e3 |
def _do_cluster_routing(self, cluster_routing: curator.ClusterRouting) -> None: <NEW_LINE> <INDENT> if self._dry_run: <NEW_LINE> <INDENT> cluster_routing.do_dry_run() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cluster_routing.do_action() | Performs cluster routing of shards.
Arguments:
cluster_routing (curator.ClusterRouting): Curator's cluster routing object. | 625941e607d97122c4178ce6 |
def pensynth_weights(X0, X1, pen=0.0, V=None): <NEW_LINE> <INDENT> if V is None: <NEW_LINE> <INDENT> V = np.identity(X0.shape[1]) <NEW_LINE> <DEDENT> n0 = len(X0) <NEW_LINE> delta = np.diag((X0-X1) @ V @ np.transpose(X0-X1)) <NEW_LINE> P = matrix(X0 @ V @ np.transpose(X0)) <NEW_LINE> q = matrix(-X0 @ V @ X1 + (pen/2)*d... | pensynth_weights:
computes penalized synthetic control weights with penalty pen
See "A Penalized Synthetic Control Estimator for Disaggregated Data"
@param X0 (np.array): n x p matrix of untreated units
@param X1 (np.array): 1 x p matrix of the treated unit
@param pen (float): lambda, positive tuning parameter
@p... | 625941e64e696a04525c989f |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self.type <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <INDENT> _x = _x.encode('utf-8') <NEW_LINE> length = len(_x) <NEW_LINE> <DEDENT> buff.write(struct.pack('<I%ss'%length, length, _x)) <NEW_LINE> _x =... | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941e6bd1bec0571d90a80 |
@periodic_task(run_every=(crontab(hour="*", minute="*", day_of_week="*"))) <NEW_LINE> def scraper_url(): <NEW_LINE> <INDENT> category = Category.objects.filter(status=1).order_by('id').first() <NEW_LINE> if category: <NEW_LINE> <INDENT> monitoring = Monitoring.objects.get(id=category.monitoring_id) <NEW_LINE> if catego... | :Flow
- Scrap object based on given url
- Write the result to Item table url
import monitoree.tasks as tasks
category = Category.objects.filter(status=1).order_by('id').first()
from monitoree.models import Monitoring, Category, Item, Url | 625941e6cad5886f8bd2742a |
def mutate(self, txt): <NEW_LINE> <INDENT> return txt | Operate on specified text and return new text.
Method designed to be overridden by subclasses to provide the
text operation desired by the subclass.
@param txt: input text
@returns: text resulting from the desired processing | 625941e656ac1b37e6264618 |
def get_data_kdj(self,min_clf,k,dd,j=None): <NEW_LINE> <INDENT> if j is None: <NEW_LINE> <INDENT> data = np.vstack(self.data)[:,dd] <NEW_LINE> clf = np.vstack(self.classif_freq)[:,k]/sum(self.classif_freq[0][0,:]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = self.data[j][:,dd] <NEW_LINE> clf = self.classif_freq... | Get data points belonging to a certain cluster
min_clf - min classification frequency for the point into the given cluster
k - cluster number
dd - dimonsion for which data should be returned
j - sample nbr | 625941e66e29344779a62a61 |
def soma_avaliacoes(self): <NEW_LINE> <INDENT> soma = 0 <NEW_LINE> for individuo in self.populacao: <NEW_LINE> <INDENT> soma += individuo.nota_avaliacao <NEW_LINE> <DEDENT> return soma | Calcula a soma das avaliações para utilizá-la no cálculo da proporção em que cada indivíduo
tem sobre este total.
:return: | 625941e6167d2b6e31218fe6 |
def __init__(self, key, item_type, default_value=None): <NEW_LINE> <INDENT> if isinstance(item_type, type): <NEW_LINE> <INDENT> raise ValueError('item_type needs to be an instance of a SessionVar and not a class') <NEW_LINE> <DEDENT> super().__init__(key, default_value=default_value) <NEW_LINE> self.item_type = item_ty... | :param item_type: SessionVar defining the type of each item in the list. The key attribute
of item_type will be ignored - you can just pass in None | 625941e6287bf620b61d3eb2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.