code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _insert_between(self, e, predecessor, successor): <NEW_LINE> <INDENT> node = super()._insert_between(e, predecessor, successor) <NEW_LINE> return self._make_position(node) | add element between existing nodes and return new Position | 625941e46aa9bd52df03719d |
def move(self, tx: float, ty: float, before=True) -> Transform2D: <NEW_LINE> <INDENT> t_matrix = np.array([ [1, 0, tx], [0, 1, ty], [0, 0, 1] ], dtype=np.float64) <NEW_LINE> transform = Transform2D.identity() <NEW_LINE> transform.matrix = np.dot(t_matrix, self.matrix) if before else np.dot(self.matrix, t_matrix) <NEW_L... | Apply a translation to the transform.
:param tx: The movement to apply to the transform in the X axis.
:param ty: The movement to apply to the transform in the Y axis.
:param before: If true, the movement will be applied before current transform. Otherwise will be applied after.
:return: The resulting transform. | 625941e4d10714528d6000de |
@entry_exit(exclude_index=[], exclude_name=[]) <NEW_LINE> def update_rack(session): <NEW_LINE> <INDENT> session.commit() | Updates racks in data store
args:
session: Active database session
returns:
nothing | 625941e47b25080760e3984e |
def upload_feed(self, config): <NEW_LINE> <INDENT> self.logger.info("Upload feeds updates") <NEW_LINE> act = action.UploadAction(conf_filename=config) <NEW_LINE> act.process([self.feed.feed_filename, self.feed.rss2_filename]) | Upload Feed file
:param config: Configuration used to upload feed on a server | 625941e4851cf427c661a903 |
def get_user_password(self): <NEW_LINE> <INDENT> if self._userPassword is None: <NEW_LINE> <INDENT> self._userPassword = os.getenv('MCP_PASSWORD') <NEW_LINE> if self._userPassword is None or len(self._userPassword) < 3: <NEW_LINE> <INDENT> raise PlumberyException( "Error: missing credentials in environment MCP_PASSWORD... | Retrieves user password to authenticate to the API
:return: the user password to be used with the driver
:rtype: ``str``
:raises: :class:`plumbery.PlumberyException`
- if no user password can be found
The user password is not put in the fittings plan, but is normally
taken from the environment variable ``MCP_PAS... | 625941e4dc8b845886cb592e |
def main(): <NEW_LINE> <INDENT> ee = EventEngine2() <NEW_LINE> me = MainEngine(ee) <NEW_LINE> me.addApp(riskManager) <NEW_LINE> me.addApp(ctaStrategy) <NEW_LINE> mw = MainWindow(me, ee) <NEW_LINE> mw.showMaximized() <NEW_LINE> sys.exit(qApp.exec_()) | 主程序入口 | 625941e48c3a8732951587b6 |
def test_clear_markers_copy(self): <NEW_LINE> <INDENT> cpy = self.dat.copy() <NEW_LINE> clear_markers(self.dat) <NEW_LINE> self.assertEqual(self.dat, cpy) | clear_markers must not modify argument. | 625941e44527f215b584c84a |
def user_market(request, typeid, cid, sid): <NEW_LINE> <INDENT> if request.method == 'GET': <NEW_LINE> <INDENT> ticket = request.COOKIES.get('ticket') <NEW_LINE> user_ticket = UserTicketModel.objects.filter(ticket=ticket).first() <NEW_LINE> if user_ticket: <NEW_LINE> <INDENT> user = user_ticket.user <NEW_LINE> <DEDENT>... | :param typeid: 分类id
:param cid: 子分类id
:param sid: 排序id | 625941e4a4f1c619b28b0427 |
def testMax(self): <NEW_LINE> <INDENT> print(self.typeStr, "... ", end=' ', file=sys.stderr) <NEW_LINE> max = Matrix.__dict__[self.typeStr + "Max"] <NEW_LINE> matrix = [[6, 5, 4], [3, 2, 1]] <NEW_LINE> self.assertEqual(max(matrix), 6) | Test max function | 625941e4187af65679ca5517 |
def get_response(prompt, choices, winners=[]): <NEW_LINE> <INDENT> if len(winners) == 0: <NEW_LINE> <INDENT> response = POLL_HEADER + "\n" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = "" <NEW_LINE> <DEDENT> response += prompt + "\n```" <NEW_LINE> for number, choice in enumerate(choices, 1): <NEW_LINE> <INDE... | Get a formatted poll string, with all choices enumerated. | 625941e44a966d76dd55140a |
def whoIsNext(names, bottle_num): <NEW_LINE> <INDENT> people = len(names) <NEW_LINE> while people < bottle_num: <NEW_LINE> <INDENT> bottle_num -= people <NEW_LINE> people *= 2 <NEW_LINE> <DEDENT> return names[int(len(names)*(bottle_num - 1) / people)] | Find out who drinks given bottle of cola. | 625941e4b830903b967e9cfe |
def __init__(self, nodes=None, replicas=3, distribution_points=3): <NEW_LINE> <INDENT> self.distribution_points = distribution_points <NEW_LINE> self.replicas = replicas <NEW_LINE> self.ring = dict() <NEW_LINE> self._sorted_keys = [] <NEW_LINE> if nodes: <NEW_LINE> <INDENT> for node in nodes: <NEW_LINE> <INDENT> self.a... | Manages a hash ring.
`nodes` is a list of objects that have a proper __str__ representation.
`distribution_points` indicates how many virtual points should be used pr. node,
distribution_points are required to improve the distribution.
I, Johan, Borrowed this code from:
http://amix.dk/blog/post/19367
and changed it t... | 625941e4a17c0f6771cbe446 |
def get_alignment(self, col_id): <NEW_LINE> <INDENT> return self.alignment[col_id] | Returns the alignment of the specified col_id
| 625941e4099cdd3c635f1050 |
def dK_dtheta(self,X,X2,target): <NEW_LINE> <INDENT> if X2 is None: X2 = X <NEW_LINE> FX = np.column_stack([f(X) for f in self.F]) <NEW_LINE> FX2 = np.column_stack([f(X2) for f in self.F]) <NEW_LINE> DER = np.zeros((self.n,self.n,self.n)) <NEW_LINE> for i in range(self.n): <NEW_LINE> <INDENT> DER[i,i,i] = np.sqrt(self.... | Return shape is NxMx(Ntheta) | 625941e49f2886367277ac81 |
@app.route('/project/running/list', methods=['GET', 'POST']) <NEW_LINE> def project_running_list(): <NEW_LINE> <INDENT> project_form = ProjectRunningListForm(request.form, csrf_enabled=False) <NEW_LINE> if 'list_type' in request.form or 'list_type' in request.args: <NEW_LINE> <INDENT> projects = _list() <NEW_LINE> if n... | プロジェクト進行中一覧 | 625941e47cff6e4e81117d7d |
def read(self, callback): <NEW_LINE> <INDENT> def foo(): <NEW_LINE> <INDENT> while 1: <NEW_LINE> <INDENT> l = self.stdout.read1(Process.bufsize) <NEW_LINE> if not l and not self.alive(): <NEW_LINE> <INDENT> self._quit() <NEW_LINE> break <NEW_LINE> <DEDENT> callback(self, l.decode(encoding=encoding, errors='replace')) <... | 启动一个线程循环读取输出,并传递给回调函数 | 625941e47d847024c06be6b7 |
def send(obj, way, number, **kwargs): <NEW_LINE> <INDENT> is_satisfied = func(obj, number) <NEW_LINE> if is_satisfied: <NEW_LINE> <INDENT> response_code_func = getattr(response_code, is_satisfied) <NEW_LINE> return Response(response_code_func) <NEW_LINE> <DEDENT> code = set_verification_code() <NEW_LINE> try: <NEW_LINE... | 选择手机号还是邮箱进行验证码发送 | 625941e416aa5153ce36286f |
def has_changes(self, xblock): <NEW_LINE> <INDENT> def get_course(branch_name): <NEW_LINE> <INDENT> return self._lookup_course(xblock.location.course_key.for_branch(branch_name)).structure <NEW_LINE> <DEDENT> def get_block(course_structure, block_key): <NEW_LINE> <INDENT> return self._get_block_from_structure(course_st... | Checks if the given block has unpublished changes
:param xblock: the block to check
:return: True if the draft and published versions differ | 625941e45fcc89381b1e1ab8 |
def __init__(self): <NEW_LINE> <INDENT> QWidget.__init__(self) <NEW_LINE> self.menuSetup = False <NEW_LINE> self.layout = QVBoxLayout() <NEW_LINE> self.layout.setSpacing(0) <NEW_LINE> self.tabs = QTabWidget() <NEW_LINE> self.layout.addWidget(self.tabs) <NEW_LINE> for group in ["Pickups", "Enemies", "Bosses", "Stage", "... | Initialises the widget. Remember to call setTileset() on it
whenever the layer changes. | 625941e4adb09d7d5db6cb84 |
def test_nginx_x_accel_redirect_middleware(self): <NEW_LINE> <INDENT> with override_settings( MIDDLEWARE_CLASSES=["django_downloadview.nginx.XAccelRedirectMiddleware"], MIDDLEWARE=["django_downloadview.nginx.XAccelRedirectMiddleware"], ): <NEW_LINE> <INDENT> with self.assertRaises(ImproperlyConfigured): <NEW_LINE> <IND... | XAccelRedirectMiddleware in settings triggers ImproperlyConfigured. | 625941e45510c4643540f7d1 |
def onResidual (pokemon): <NEW_LINE> <INDENT> pass | function (pokemon) {
if (pokemon.status && ['raindance', 'primordialsea'].includes(pokemon.effectiveWeather())) {
this.debug('hydration');
this.add('-activate', pokemon, 'ability: Hydration');
pokemon.cureStatus();
}
} | 625941e463d6d428bbe448e8 |
def Report(self, readptr): <NEW_LINE> <INDENT> readptr = readptr + self.start <NEW_LINE> now = self.now() <NEW_LINE> if now > self.last_time + old_div(1000000,4): <NEW_LINE> <INDENT> rate = ((readptr - self.last_offset) / (now - self.last_time) * 1000000 / 1024/1024) <NEW_LINE> sys.stdout.write(" Reading %sMiB / %sMiB ... | This will be called periodically to report the progress.
Note that readptr is specified relative to the start of the range
operation (WriteStream and CopyToStream) | 625941e44c3428357757c71d |
def ulog_list(self): <NEW_LINE> <INDENT> return _kyototycoon.DB_ulog_list(self) | ulog_list(self) -> FileStatusList | 625941e4e64d504609d74c37 |
def _create_athena_s3_bucket_if_not_exist(self): <NEW_LINE> <INDENT> account = self.boto_session.client("sts").get_caller_identity()["Account"] <NEW_LINE> region = self.boto_session.region_name <NEW_LINE> s3_bucket_name = "sagemaker-{}-{}".format(region, account) <NEW_LINE> s3 = self.boto_session.resource("s3") <NEW_LI... | Create s3 bucket for athena data if not exists
Use sagemaker-{region}-{account_id} bucket to store data
Returns:
str: s3 bucket name for athena | 625941e4de87d2750b86018e |
def inst_predicate(self): <NEW_LINE> <INDENT> pred = None <NEW_LINE> iform = self.inst.format <NEW_LINE> for ffield, opnum in zip(iform.imm_fields, self.inst.imm_opnums): <NEW_LINE> <INDENT> arg = self.args[opnum] <NEW_LINE> if isinstance(arg, Var): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> pred = And.combine(pr... | Construct an instruction predicate that verifies the immediate operands
on this instruction.
Immediate operands in a source pattern can be either free variables or
constants like `ConstantInt` and `Enumerator`. We don't currently
support constraints on free variables, but we may in the future. | 625941e4ad47b63b2c50a376 |
def range(self): <NEW_LINE> <INDENT> content_range = self.header("range") <NEW_LINE> if content_range: <NEW_LINE> <INDENT> range_end = range_start = 0 <NEW_LINE> content_range = content_range.split("=") <NEW_LINE> if len(content_range) > 1: <NEW_LINE> <INDENT> content_range = content_range[1].split("-") <NEW_LINE> rang... | Returns the range header information as a couple (start, end) or None if
there is no range. | 625941e42ae34c7f2600d528 |
def _compute_magnitude(ctx, C): <NEW_LINE> <INDENT> return C['c1'] + (C['c2'] * ctx.mag) + (C['c3'] * (ctx.mag ** 2)) | Compute the first term of the equation described on p. 1866:
"c1 + (c2 * M) + (c3 * M**2) " | 625941e482261d6c526ab89d |
def generate_verifier(length=8): <NEW_LINE> <INDENT> s = ''.join([str(random.randint(0, 9)) for i in range(length)]) <NEW_LINE> return _utf8_str(s) | Generate pseudorandom number. | 625941e47d43ff24873a309b |
def zero(item): <NEW_LINE> <INDENT> return 0 | item -> 0 used for unknown fields | 625941e4b5575c28eb68e3fb |
def __init__(self): <NEW_LINE> <INDENT> self.hit_q = collections.deque() <NEW_LINE> self.hit_count = 0 | Initialize your data structure here. | 625941e4d7e4931a7ee9e316 |
def __getitem__(self, key): <NEW_LINE> <INDENT> normal_key = self._normalize_key(key) <NEW_LINE> if normal_key not in self.ALL_HEADERS: <NEW_LINE> <INDENT> raise ValueError('Header name must be one of %s.' % self.ALL_HEADERS) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return collections.defaultdict.__getitem__(self,... | Get a header value, normalizing the key case.
Args:
key: str, the header key.
Returns:
String header value.
Raises:
KeyError if the key is not one of the accepted headers. | 625941e4d10714528d6000df |
def allow_relation(self, obj1, obj2, **hints): <NEW_LINE> <INDENT> if self._is_node_model(obj1) != self._is_node_model(obj2): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return None | Checks if a relation between `obj1` and `obj2` should be allowed. This
is done by checking that both objects are either NodeModels or regular
django models | 625941e49b70327d1c4e11ce |
def select_chapters(chapters: 'List[Chapter]', selectors_str: str) -> 'List[Chapter]': <NEW_LINE> <INDENT> if not selectors_str: <NEW_LINE> <INDENT> return chapters <NEW_LINE> <DEDENT> selectors = selectors_str.split(',') <NEW_LINE> chaps = set() <NEW_LINE> ignored_chaps = set() <NEW_LINE> for selector in selectors: <N... | Selects the chapters specified in the given selectors.
:param chapters: a list of chapters.
:param selectors: a string of comma-separated selectors.
:return: a list of selected chapters. | 625941e45fc7496912cc3d75 |
def update_pytrees_QP(self, params, state, epoch, data, *args, **kwargs): <NEW_LINE> <INDENT> del epoch, args, kwargs <NEW_LINE> def losses(params): <NEW_LINE> <INDENT> return self.fun(params, data)[0] <NEW_LINE> <DEDENT> aux = self.fun(params, data)[1] <NEW_LINE> def matvec_Q(params_Q, u): <NEW_LINE> <INDENT> del para... | Performs one iteration of the system Polyak solver.
Args:
params: pytree containing the parameters.
state: named tuple containing the solver state.
epoch: int, epoch number.
data: a batch of data.
*args: additional positional arguments to be passed to ``fun``.
**kwargs: additional keyword arguments to be p... | 625941e430bbd722463cc1bf |
def value_to_sint(n): <NEW_LINE> <INDENT> if n > 0xffff: <NEW_LINE> <INDENT> raise error.RunError(6) <NEW_LINE> <DEDENT> if n < 0: <NEW_LINE> <INDENT> n = 0x10000 + n <NEW_LINE> <DEDENT> return bytearray((n&0xff, n >> 8)) | Convert Python integer to two's complement little-endian token. | 625941e43617ad0b5ed682ee |
def readPlist(pathOrFile): <NEW_LINE> <INDENT> didOpen = 0 <NEW_LINE> if isinstance(pathOrFile, (bytes, str)): <NEW_LINE> <INDENT> pathOrFile = open(pathOrFile, "rb") <NEW_LINE> didOpen = 1 <NEW_LINE> <DEDENT> p = PlistParser() <NEW_LINE> rootObject = p.parse(pathOrFile) <NEW_LINE> if didOpen: <NEW_LINE> <INDENT> pathO... | Read a .plist file. 'pathOrFile' may either be a file name or a
(readable) file object. Return the unpacked root object (which
usually is a dictionary). | 625941e4d486a94d0b98e53e |
def __autoconnect_signals(self): <NEW_LINE> <INDENT> dic = {} <NEW_LINE> for name in dir(self): <NEW_LINE> <INDENT> method = getattr(self, name) <NEW_LINE> if (not callable(method)): continue <NEW_LINE> assert(not dic.has_key(name)) <NEW_LINE> dic[name] = method <NEW_LINE> pass <NEW_LINE> <DEDENT> for xml in self.view.... | This is called during view registration, to autoconnect
signals in glade file with methods within the controller | 625941e4a8ecb033257d34c3 |
def lines(*args): <NEW_LINE> <INDENT> return os.linesep.join(args) | Make multi-line string. | 625941e4d58c6744b4258056 |
def onRspQryFill( self, session: int, error: int, last: str, data: dict ) -> None: <NEW_LINE> <INDENT> if error != ERROR_VT2TAP["TAPIERROR_SUCCEED"]: <NEW_LINE> <INDENT> self.gateway.write_log(f"查询成交信息失败") <NEW_LINE> return <NEW_LINE> <DEDENT> if data: <NEW_LINE> <INDENT> self.update_trade(data) <NEW_LINE> <DEDENT> if ... | Callback of today's order fill (trade) query. | 625941e4cdde0d52a9e5342d |
def _median_absolute_deviation(self): <NEW_LINE> <INDENT> noise_median = np.median(self.noise_heights, axis=0) <NEW_LINE> deviations = np.abs(self.noise_heights - noise_median) <NEW_LINE> return np.median(deviations, axis=0) | Calculate Median Average Deviation for noise in each spectra.
https://en.wikipedia.org/wiki/Median_absolute_deviation
Return numpy array `len(spectrum_list)` x 1 | 625941e415fb5d323cde0f0c |
def update_fine_tune_checkpoint_type(train_config): <NEW_LINE> <INDENT> if not train_config.fine_tune_checkpoint_type: <NEW_LINE> <INDENT> if train_config.from_detection_checkpoint: <NEW_LINE> <INDENT> train_config.fine_tune_checkpoint_type = "detection" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> train_config.fine_t... | Set `fine_tune_checkpoint_type` using `from_detection_checkpoint`.
`train_config.from_detection_checkpoint` field is deprecated. For backward
compatibility, this function sets `train_config.fine_tune_checkpoint_type`
based on `train_config.from_detection_checkpoint`.
Args:
train_config: train_pb2.TrainConfig proto ... | 625941e4aad79263cf390e3f |
def __iter__(self): <NEW_LINE> <INDENT> assert self._iter_list is not None <NEW_LINE> return iter(self._iter_list) | Iterates through self._iter_list, that must have been set by
self.set_iter before. | 625941e4090684286d50f0e3 |
def open(self): <NEW_LINE> <INDENT> logger.debug("Popping Open browser") <NEW_LINE> return filedialog.askopenfile(**self.kwargs) | Open a file | 625941e45fc7496912cc3d76 |
def hook_ready(fm): <NEW_LINE> <INDENT> pass | A hook that is called after the ranger UI is initialized.
Parameters:
fm = the file manager instance
Return Value:
ignored
This hook is executed after the user interface is initialized. You should
NOT print anything to stdout anymore from here on. Use fm.notify instead. | 625941e48c3a8732951587b7 |
def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkConstrainedValueAdditionImageFilterIUS2IUS2IUS2.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj | New() -> itkConstrainedValueAdditionImageFilterIUS2IUS2IUS2
Create a new object of the class itkConstrainedValueAdditionImageFilterIUS2IUS2IUS2 and set the input and the parameters if some
named or non-named arguments are passed to that method.
New() tries to assign all the non named parameters to the input of the ne... | 625941e499fddb7c1c9de787 |
def list_stacks(conn, name_filter='*', verbose=False): <NEW_LINE> <INDENT> states = FAILED_STACK_STATES + COMPLETE_STACK_STATES + IN_PROGRESS_STACK_STATES + ROLLBACK_STACK_STATES <NEW_LINE> s = conn.list_stacks(states) <NEW_LINE> stacks = [] <NEW_LINE> for n in s: <NEW_LINE> <INDENT> if name_filter and fnmatch(n.stack_... | List active stacks | 625941e407f4c71912b1187d |
def p_statement_list_1(p): <NEW_LINE> <INDENT> p[0] = [p[1]] | statement_list : statement | 625941e4adb09d7d5db6cb85 |
def init_weights(self): <NEW_LINE> <INDENT> r = np.sqrt(6.) / np.sqrt(self.fc.in_features + self.fc.out_features) <NEW_LINE> self.fc.weight.data.uniform_(-r, r) <NEW_LINE> self.fc.bias.data.fill_(0) | Xavier initialization for the fully connected layer | 625941e4d268445f265b5266 |
def get_monitor(**kwargs): <NEW_LINE> <INDENT> from utils.logger import get_logger <NEW_LINE> pattern = get(kwargs, 'pattern', str2list, None) <NEW_LINE> interval = get(kwargs, 'interval', int, 100) <NEW_LINE> prefix = get(kwargs, 'prefix', str, kwargs['console_arg'].symbol_name + '.') <NEW_LINE> check(kwargs, 'monitor... | return a TensorBoardMonitor instance (with custom callback)
:param pattern: "a,b,c" like string, where a,b,c are regex pattern str
:type pattern: str
:param interval: monitor interval
:type interval: int
:param prefix: tensorboard name prefix
:type prefix: str
:return: mxnet.tensorboard.TensorBoardMonitor | 625941e47c178a314d6ef85e |
def __init__( self, slaveFunction ): <NEW_LINE> <INDENT> self.function = slaveFunction <NEW_LINE> if hasattr( slaveFunction, '__len__' ): <NEW_LINE> <INDENT> assert( len( slaveFunction ) == 1 ) <NEW_LINE> self.function = slaveFunction[0] <NEW_LINE> <DEDENT> self.queue = [] | Creates a new SerializedThreadPool that will call the
specified function. | 625941e450485f2cf553d193 |
def mousePressEvent(self, gsMouseEvt): <NEW_LINE> <INDENT> shiftmod = (gsMouseEvt.modifiers() & QtCore.Qt.ShiftModifier) <NEW_LINE> if shiftmod: <NEW_LINE> <INDENT> mpos = gsMouseEvt.scenePos() <NEW_LINE> for it in reversed(self.childItems()): <NEW_LINE> <INDENT> if it.contains(it.mapFromScene(mpos)): <NEW_LINE> <INDEN... | The user clicked on a tile that either:
* was not selected:
- and just became the only tile in the selection and should be ready to now drag
- or was just added to the existing selection (using the modifer key)
and should not be dragged
* was already selected:
- and should now be dragged
- or should now b... | 625941e4bf627c535bc135c8 |
def eth_estimateGas( self, sender='', to='', value=0, data='', startgas=GAS_PRICE, gasprice=GAS_PRICE): <NEW_LINE> <INDENT> json_data = format_data_for_call( sender, to, value, data, startgas, gasprice, ) <NEW_LINE> res = self.call('eth_estimateGas', json_data) <NEW_LINE> return quantity_decoder(res) | Makes a call or transaction, which won't be added to the blockchain
and returns the used gas, which can be used for estimating the used
gas.
Args:
from: The address the transaction is sent from.
to: The address the transaction is directed to.
gas (int): Gas provided for the transaction execution. eth_call
... | 625941e4d486a94d0b98e53f |
def append_formula(self, formula, no_return=True): <NEW_LINE> <INDENT> if self.maplesat: <NEW_LINE> <INDENT> res = None <NEW_LINE> if type(formula) == CNFPlus and formula.atmosts: <NEW_LINE> <INDENT> raise NotImplementedError('Atmost constraints are not supported by MapleChrono') <NEW_LINE> <DEDENT> for clause in formu... | Appends list of clauses to solver's internal formula. | 625941e4bd1bec0571d90a27 |
def cmd_users_add_bots(bot, update, args): <NEW_LINE> <INDENT> chat_id = update.message.chat_id <NEW_LINE> user_id = update.message.from_user.id <NEW_LINE> chat_type = update.message.chat.type <NEW_LINE> lang = get_chat_config(chat_id, 'Language') <NEW_LINE> allow_users_to_add_bots = get_chat_config(chat_id, 'Allow_use... | Command /users_add_bots message handler | 625941e4d4950a0f3b08c741 |
def copy_astylewx_top(dist_top, to_dos=False): <NEW_LINE> <INDENT> print("copying top") <NEW_LINE> deleted = 0 <NEW_LINE> docfiles = glob.glob(__astylewx_dir + "/*") <NEW_LINE> for filepath in docfiles: <NEW_LINE> <INDENT> sep = filepath.rfind(os.sep) <NEW_LINE> filename = filepath[sep + 1:] <NEW_LINE> if filename in (... | Copy astylewx top directory to a distribution directory.
| 625941e4f9cc0f698b1409f0 |
def compute_ngrams(toks, n=2): <NEW_LINE> <INDENT> gramDict={} <NEW_LINE> for i in range(len(toks)-(n-1)): <NEW_LINE> <INDENT> if toks[i] in gramDict: <NEW_LINE> <INDENT> if i + n - 1 < len(toks): <NEW_LINE> <INDENT> tempListA = [] <NEW_LINE> for k in range(n): <NEW_LINE> <INDENT> if k >= 1: <NEW_LINE> <INDENT> tempLis... | Returns an n-gram dictionary based on the provided list of tokens. | 625941e4dd821e528d63b59e |
def breakdown_constraints(table, constraint): <NEW_LINE> <INDENT> if("=" in constraint): <NEW_LINE> <INDENT> listConditions = constraint.split("=") <NEW_LINE> col1 = listConditions[0] <NEW_LINE> col2 = listConditions[1] <NEW_LINE> try: <NEW_LINE> <INDENT> col2 = col2.strip("'") <NEW_LINE> col2 = float(col2) <NEW_LINE> ... | (Table, str) -> Table
REQ: Table has a dict with more than 0 rows
REQ: constraint is a str with valid column names and operator
Given a table and a constraint, modify to table so that it satisfies
the condition of the constraint. | 625941e4eab8aa0e5d26df52 |
def validationDataset(self,path): <NEW_LINE> <INDENT> dataSet = pd.read_csv(path) <NEW_LINE> dataSet = dataSet.fillna(0) <NEW_LINE> labelSet = dataSet.label.astype(np.int32).as_matrix() <NEW_LINE> appid = dataSet.subappid.astype(np.int32).astype(str).as_matrix() <NEW_LINE> appidVec = [self.w[self.dictApp[i]] for i in a... | create the validation dataset for RNN
:param path: the data path
:return: (data,label) | 625941e4a934411ee3751a8d |
def testSortNoDbAscending(self): <NEW_LINE> <INDENT> self.request.GET['sort'] = "custom" <NEW_LINE> self.datagrid.load_state() <NEW_LINE> self.assertEqual(self.datagrid.sort_list, ["custom"]) <NEW_LINE> self.assertEqual(len(self.datagrid.rows), self.datagrid.paginate_by) <NEW_LINE> self.assertEqual(self.datagrid.rows[0... | Testing datagrids with ascending sort | 625941e499cbb53fe6792fdd |
def command_getval(self, **kwargs): <NEW_LINE> <INDENT> wc = self.wallet.wallet_config <NEW_LINE> for name in kwargs['key'].split('.'): <NEW_LINE> <INDENT> wc = wc[name] <NEW_LINE> <DEDENT> print (json.dumps(wc, indent=4)) | Returns the value for a given key in the config.
Key is expressed like so: key.subkey.subsubkey | 625941e466673b3332b92489 |
def door_position_input(people_waiting, bearing_condition): <NEW_LINE> <INDENT> time_constant = range_transform((0, 100), (2, 30))(float(bearing_condition)) <NEW_LINE> gain = 10 <NEW_LINE> if people_waiting: <NEW_LINE> <INDENT> return gain, time_constant, 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return gain, tim... | It should take from 2 to 30 seconds for the doors to almost close. Remaining
error could be treated as sensor tolerance. | 625941e46e29344779a62a08 |
def get_comment_header(line): <NEW_LINE> <INDENT> m = re.match(r"^([ \t]*#*)", line) <NEW_LINE> if m is None: return "" <NEW_LINE> return m.group(1) | Return string with leading whitespace and '#' from line or ''.
A null return indicates that the line is not a comment line. A non-
null return, such as ' #', will be used to find the other lines of
a comment block with the same indent. | 625941e466673b3332b9248a |
def read_from_EEPROM(self, offset, length): <NEW_LINE> <INDENT> if length > maximum_payload_length - 1: <NEW_LINE> <INDENT> raise EEPROMLengthError(length) <NEW_LINE> <DEDENT> payload = struct.pack( '<BHb', host_query_command_dict['READ_FROM_EEPROM'], offset, length ) <NEW_LINE> response = self.writer.send_query_payloa... | Read some data from the machine. The data structure is implementation specific.
@param byte offset: EEPROM location to begin reading from
@param int length: Number of bytes to read from the EEPROM (max 31)
@return byte array of data read from EEPROM | 625941e44e4d5625662d47cb |
def wif_public(self): <NEW_LINE> <INDENT> return self.wif(public=True) | Get Extended WIF public key
:return str: Base58 encoded WIF key | 625941e432920d7e50b285cc |
def parse_date(date): <NEW_LINE> <INDENT> month, day, year = [int(part) for part in date.split('/')] <NEW_LINE> return datetime.date(year, month, day) | Parse data from dd/mm/yyyy format to Python datetime object. | 625941e4c432627299f05041 |
def downsample_using_sox(self, fpath, sample_rate): <NEW_LINE> <INDENT> fpath = os.path.abspath(fpath) <NEW_LINE> fpath_ds = self.new_path(fpath) <NEW_LINE> dpath_ds = os.path.dirname(fpath_ds) <NEW_LINE> if not os.path.exists(dpath_ds): <NEW_LINE> <INDENT> os.makedirs(dpath_ds) <NEW_LINE> <DEDENT> if os.path.exists(fp... | Change sample to the given sample rate and return the new
(temporary) file. | 625941e463d6d428bbe448e9 |
def _set_drag_flag(self, flag=True): <NEW_LINE> <INDENT> if self._drag_flag == flag: <NEW_LINE> <INDENT> self._has_changed = False <NEW_LINE> return <NEW_LINE> <DEDENT> self._has_changed = True <NEW_LINE> self._drag_flag = flag <NEW_LINE> if self._manager is not None and self._manager.parent is not None: <NEW_LINE> <IN... | The derivative class sets the drag flag value to indicate that
dragging motion is possible | 625941e4046cf37aa974d13c |
def db_init(db, conn_name): <NEW_LINE> <INDENT> global db_ready <NEW_LINE> if db_ready.count(conn_name) < 1: <NEW_LINE> <INDENT> db.execute("create table if not exists seen_user(name, time, quote, chan, host, primary key(name, chan))") <NEW_LINE> db.commit() <NEW_LINE> db_ready.append(conn_name) | check to see that our db has the the seen table (connection name is for caching the result per connection)
:type db: sqlalchemy.orm.Session | 625941e41f5feb6acb0c4f42 |
def activiate_derivative_fun(self,z): <NEW_LINE> <INDENT> return self.activiate_fun(z) * (1 - self.activiate_fun(z)) | the derivative value of activate function at z | 625941e46fb2d068a760f49c |
def lda_on_corpus(corpus): <NEW_LINE> <INDENT> id2word = corpora.Dictionary(corpus) <NEW_LINE> texts = corpus <NEW_LINE> corpus = [id2word.doc2bow(text) for text in texts] <NEW_LINE> lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus, id2word=id2word, num_topics=1, random_state=100, update_every=1, chunksize=100... | lda sur le corpus de texte
:param corpus: liste contenant les listes de mots des lyrics
:return: gensim.models.ldamodel.LdaModel | 625941e45166f23b2e1a5551 |
def remove_StockEOD(): <NEW_LINE> <INDENT> for fpath in glob.glob(f"{baseDir().path}/StockEOD/*/**/***"): <NEW_LINE> <INDENT> os.remove(fpath) <NEW_LINE> print(fpath) | Remove all files in StockEOD directory. | 625941e4fff4ab517eb2f837 |
def avoidArea(self, widget, area, screen = None): <NEW_LINE> <INDENT> return bool() | static bool KDialog.avoidArea(QWidget widget, QRect area, int screen = -1) | 625941e471ff763f4b549a8b |
def test_write_projection(): <NEW_LINE> <INDENT> tmpdir = tempfile.mkdtemp() <NEW_LINE> curdir = os.getcwd() <NEW_LINE> os.chdir(tmpdir) <NEW_LINE> test_ds = fake_random_ds(64) <NEW_LINE> c = [0.5, 0.5, 0.5] <NEW_LINE> norm = [0.5, 0.5, 0.5] <NEW_LINE> W = [0.5,0.5,1.0] <NEW_LINE> N = 64 <NEW_LINE> field = "density" <N... | Tests functionality of off_axis_projection and write_projection. | 625941e48e05c05ec3eea770 |
@remote_compatible <NEW_LINE> def test_hapd_ctrl_unknown(dev, apdev): <NEW_LINE> <INDENT> ssid = "hapd-ctrl" <NEW_LINE> params = {"ssid": ssid} <NEW_LINE> hapd = hostapd.add_ap(apdev[0], params) <NEW_LINE> if "UNKNOWN COMMAND" not in hapd.request("FOO"): <NEW_LINE> <INDENT> raise Exception("Unexpected response") | hostapd and unknown ctrl_iface command | 625941e4a05bb46b383ecc16 |
def __init__(self, ped, qtl_file, allele_file, pos_file, num_alleles=1): <NEW_LINE> <INDENT> self.ped = ped <NEW_LINE> self.len = num_alleles <NEW_LINE> self.build_allele_assignments(qtl_file, self.len) <NEW_LINE> self.get_allele_info(allele_file, self.len) <NEW_LINE> self.get_allele_positions(pos_file, self.len) <NEW_... | Constructor for QTL class. The QTL class relates QTL (quantitative
trait loci) data to pedigree data: this class relates allele assigments
to the individuals specified in a pedigree. The QTL class ultimately
builds a segregation network from the pedigree in 'ped'.
Parameters
----------
ped : Pedigree object
A Pedi... | 625941e476e4537e8c351a6e |
def is_chinese(uchar): <NEW_LINE> <INDENT> if (uchar >= u'\u2E80' and uchar <= u'\uFE4F') or(uchar >= u'\uFF00' and uchar <= u'\uFFEF')or(uchar >= u'\u2160' and uchar <= u'\u2168'): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | 判断一个unicode是否是汉字,全角字符,罗马数字1-9 | 625941e4097d151d1a223250 |
def to_xml(self, element_name=None): <NEW_LINE> <INDENT> E = self.client.E <NEW_LINE> if element_name: <NEW_LINE> <INDENT> element_name += '-contact-info' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> element_name = 'contact-info' <NEW_LINE> <DEDENT> return getattr(E, element_name)( getattr(E, 'first-name')(self.first_... | Converts WebInfo object to XML object:
<{element_name-}contact-info>
<first-name>John</first-name>
<last-name>Doe</last-name>
<email>dev@justyoyo.com</email>
<address1>Address 1</address1>
<city>City</city>
<zip>SW5</zip>
<country>gb</country>
<phone>07777777777</phone>
</{element_name-... | 625941e4091ae3566866734f |
def get_region_of_interest(workspace, radius=None, roi_files=None, mask_files=None): <NEW_LINE> <INDENT> trans_roi = [] <NEW_LINE> if radius is not None: <NEW_LINE> <INDENT> clone_name = "CloneWorkspace" <NEW_LINE> clone_options = {"InputWorkspace": workspace, "OutputWorkspace": EMPTY_NAME} <NEW_LINE> clone_alg = creat... | Calculate the various contributions to the "region of interest", used in the
transmission calculation.
The region of interest can be made up of a circle of detectors (with a given radius)
around the beam centre, and/or one or more mask files, and/or the main detector bank.
Note that the mask files wont actually be use... | 625941e497e22403b379d394 |
def loss(self, X, y=None): <NEW_LINE> <INDENT> X = X.astype(self.dtype) <NEW_LINE> mode = 'test' if y is None else 'train' <NEW_LINE> if self.use_dropout: <NEW_LINE> <INDENT> self.dropout_param['mode'] = mode <NEW_LINE> <DEDENT> if self.use_batchnorm: <NEW_LINE> <INDENT> for bn_param in self.bn_params: <NEW_LINE> <INDE... | Compute loss and gradient for the fully-connected net.
Input / output: Same as TwoLayerNet above. | 625941e450485f2cf553d194 |
def tasujKarty(Talia,ile = 200,iloscKart = 24): <NEW_LINE> <INDENT> for i in range(ile): <NEW_LINE> <INDENT> x = randint(0,iloscKart-1) <NEW_LINE> y = randint(0,iloscKart-1) <NEW_LINE> Talia[x], Talia[y] = Talia[y],Talia[x] | Losujemy dwie karty i zamieniamy je ze sobą | 625941e4460517430c394573 |
def __init__(self, id=None, name=None): <NEW_LINE> <INDENT> self.openapi_types = { 'id': long, 'name': str } <NEW_LINE> self.attribute_map = { 'id': 'id', 'name': 'name' } <NEW_LINE> self._id = id <NEW_LINE> self._name = name | Category - a model defined in OpenAPI
:param id: The id of this Category. # noqa: E501
:type id: long
:param name: The name of this Category. # noqa: E501
:type name: str | 625941e43cc13d1c6d3c7771 |
def test_access_item_instance_from_instance(registrymixin_models): <NEW_LINE> <INDENT> r1 = registrymixin_models.RegistryTest1() <NEW_LINE> r2 = registrymixin_models.RegistryTest2() <NEW_LINE> i1 = r1.views.test() <NEW_LINE> i2 = r2.views.test() <NEW_LINE> assert isinstance(i1, registrymixin_models.RegisteredItem1) <NE... | Registered items can be instantiated from the model instance. | 625941e421bff66bcd684d47 |
def vectf2(function): <NEW_LINE> <INDENT> vectorized = lambda rows: [function(*x) for x in rows] <NEW_LINE> vectorized.__doc__ = function.__doc__ <NEW_LINE> return vectorized | :param function:
:return:
>>> from m2py.misc import vectorize as m >>> from math import *
>>> def f(x, y, z):
... return sqrt(x**2+y**2+z**2)
...
>>>
>>> fv = m.vectf2(f)
>>>
>>> fv([[1,23,5], [23, 49,5], [12,4,6]])
[23.558437978779494, 54.35991169970753, 14.0] | 625941e494891a1f4081bea4 |
def _update_posts_rating(self): <NEW_LINE> <INDENT> common_posts_rating = 0 <NEW_LINE> posts = Post.objects.filter(author__user=self.user) <NEW_LINE> if posts.exists(): <NEW_LINE> <INDENT> for individual_post_rating in posts.values("rating"): <NEW_LINE> <INDENT> common_posts_rating += individual_post_rating["rating"] *... | Возвращает суммарный рейтинг каждой статьи автора умноженный на 3. | 625941e43317a56b8693a047 |
@memoize <NEW_LINE> def check(text): <NEW_LINE> <INDENT> err = "misc.annotations" <NEW_LINE> msg = u"Annotation left in text." <NEW_LINE> annotations = [ "FIXME", "FIX ME", "TODO", "todo", "ERASE THIS", "FIX THIS", ] <NEW_LINE> return existence_check( text, annotations, err, msg, ignore_case=False, join=True) | Check the text. | 625941e41b99ca400220aeac |
def SetDstIPAddr(self,stream,dstaddr): <NEW_LINE> <INDENT> if (stream != 0) and (stream != 1): <NEW_LINE> <INDENT> raise ValueError("Stream should be 1 or 0") <NEW_LINE> <DEDENT> config_key = "DestinationIPAddress{}".format(stream) <NEW_LINE> self.config['Streaming'][config_key] = dstaddr | Set the Destination IP address for a stream | 625941e43617ad0b5ed682ef |
def __init__(self, count=0): <NEW_LINE> <INDENT> aeidon.Observable.__init__(self) <NEW_LINE> self.edit_mode = gaupol.conf.editor.mode <NEW_LINE> self.project = None <NEW_LINE> self.tab_label = None <NEW_LINE> self.tab_widget = None <NEW_LINE> self.untitle = _("Untitled {:d}").format(count) <NEW_LINE> self.view = gaupol... | Initialize a :class:`Page` object. | 625941e467a9b606de4a82b0 |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> _simuPOP_laop.PyPenetrance_swiginit(self, _simuPOP_laop.new_PyPenetrance(*args, **kwargs)) | Usage:
PyPenetrance(func, loci=[], ancGens=UNSPECIFIED, begin=0,
end=-1, step=1, at=[], reps=ALL_AVAIL, subPops=ALL_AVAIL,
infoFields=[])
Details:
Create a Python hybrid penetrance operator that passes genotype at
specified loci, values at specified information fields (if
requested), and ... | 625941e445492302aab5e6c0 |
def yeojohnson_llf(lmb, data): <NEW_LINE> <INDENT> data = np.asarray(data) <NEW_LINE> n_samples = data.shape[0] <NEW_LINE> if n_samples == 0: <NEW_LINE> <INDENT> return np.nan <NEW_LINE> <DEDENT> trans = _yeojohnson_transform(data, lmb) <NEW_LINE> loglike = -n_samples / 2 * np.log(trans.var(axis=0)) <NEW_LINE> loglike ... | The yeojohnson log-likelihood function.
Parameters
----------
lmb : scalar
Parameter for Yeo-Johnson transformation. See `yeojohnson` for
details.
data : array_like
Data to calculate Yeo-Johnson log-likelihood for. If `data` is
multi-dimensional, the log-likelihood is calculated along the first
axi... | 625941e485dfad0860c3b254 |
def process_input(self, batch): <NEW_LINE> <INDENT> batch["feed"] = (batch["image"] - 127.5) / 127.5 <NEW_LINE> return batch | Compile the detection image(s) for prediction | 625941e450812a4eaa59c716 |
def publish(key, shard, message): <NEW_LINE> <INDENT> pass | Send message.
@param key: Will be passed to the exchange as the routing key.
@param shard: Identifier of the exchange we are sending message to.
@param message: Message body.
@type message: subclass of L{feat.agents.message.BaseMessage} | 625941e45166f23b2e1a5552 |
def make_state(state_name: str) -> Type: <NEW_LINE> <INDENT> return _StateClassCreater(state_name, (), {}) | make state as a class.
Args:
state_name (str): the state name.
Returns:
A state relative class | 625941e44527f215b584c84b |
def field_extension(self, names): <NEW_LINE> <INDENT> R = self.parent() <NEW_LINE> x = R.gen() <NEW_LINE> F = R.modulus().root_field(names) <NEW_LINE> alpha = F.gen() <NEW_LINE> f = R.hom([alpha], F, check=False) <NEW_LINE> if number_field_rel.is_RelativeNumberField(F): <NEW_LINE> <INDENT> base_map = F.base_field().hom... | Given a polynomial with base ring a quotient ring, return a
3-tuple: a number field defined by the same polynomial, a
homomorphism from its parent to the number field sending the
generators to one another, and the inverse isomorphism.
INPUT:
- ``names`` - name of generator of output field
OUTPUT:
- field
- homo... | 625941e48c3a8732951587b8 |
def create_socket(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) <NEW_LINE> sock.bind((self.host,self.port)) <NEW_LINE> sock.listen(5) <NEW_LINE> print ('Serving HTTP on port %s ...' % self.port) <NEW_LINE> self.logger.info('Serving HTTP on port %s ...' %self.p... | To create a socket | 625941e4046cf37aa974d13d |
def test_initiallySchedulesOneDataCall(self): <NEW_LINE> <INDENT> reactor = task.Clock() <NEW_LINE> a = H2Connection(reactor) <NEW_LINE> calls = reactor.getDelayedCalls() <NEW_LINE> self.assertEqual(len(calls), 1) <NEW_LINE> call = calls[0] <NEW_LINE> self.assertTrue(call.active()) <NEW_LINE> self.assertEqual(call.time... | When a H2Connection is established it schedules one call to be run as
soon as the reactor has time. | 625941e47d847024c06be6b8 |
def filelist(self, timerange): <NEW_LINE> <INDENT> directories = self.range(timerange) <NEW_LINE> filesurls = [] <NEW_LINE> if directories[0][0:3] == "ftp": <NEW_LINE> <INDENT> return self._ftpfileslist(timerange) <NEW_LINE> <DEDENT> for directory in directories: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> opn = urlop... | Returns the list of existent files in the archive for the given time
range.
Parameters
----------
timerange : `~sunpy.time.TimeRange`
Time interval where to find the directories for a given pattern.
Returns
-------
filesurls : `list` of `str`
List of all the files found between the time range given.
Examples... | 625941e4187af65679ca5519 |
def get_transactions(self): <NEW_LINE> <INDENT> request = ln.GetTransactionsRequest() <NEW_LINE> response = self.lightning_stub.GetTransactions(request) <NEW_LINE> return response | Describe all the known transactions relevant to the wallet
:returns: TransactionDetails with 1 attribute: 'transactions', containing a list
of all transactions | 625941e42c8b7c6e89b35bb7 |
def _VerifyValues(self, image, ksizes, strides, padding, patches): <NEW_LINE> <INDENT> ksizes = [1] + ksizes + [1] <NEW_LINE> strides = [1] + strides + [1] <NEW_LINE> with self.cached_session(use_gpu=True): <NEW_LINE> <INDENT> out_tensor = array_ops.extract_volume_patches( constant_op.constant(image), ksizes=ksizes, st... | Tests input-output pairs for the ExtractVolumePatches op.
Args:
image: Input tensor with shape:
[batch, in_planes, in_rows, in_cols, depth].
ksizes: Patch size specified as: [ksize_planes, ksize_rows, ksize_cols].
strides: Output strides, specified as:
[stride_planes, stride_rows, stride_cols... | 625941e4f548e778e58cd978 |
def makeFormTemplate(self, entity_class, html=None): <NEW_LINE> <INDENT> json_template = dict() <NEW_LINE> json_template['name'] = entity_class.__name__ <NEW_LINE> json_template['html'] = html if html else self.show_dictionary( entity_class.__dict__) <NEW_LINE> return json_template | Utility method to create a json template from a `class` definition.
:param entity_class: Class to build the template
:param html: Already defined html
:return: `dict` with the json form template. | 625941e4ff9c53063f47c5eb |
def expand_all(self) -> None: <NEW_LINE> <INDENT> if not self._subtrees: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.expand() <NEW_LINE> for tree in self._subtrees: <NEW_LINE> <INDENT> tree.expand_all() | If the user selects a rectangle, and then presses a, the tree
corresponding to that rectangle, as well as all of its subtrees,
are expanded in the displayed-tree. If the tree is a leaf,
nothing happens.
:return: | 625941e49f2886367277ac83 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.