code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __init__(self, hass, config_entry): <NEW_LINE> <INDENT> self.config_entry = config_entry <NEW_LINE> self.hass = hass <NEW_LINE> self.available = True <NEW_LINE> self.authorized = False <NEW_LINE> self.api = None <NEW_LINE> self.parallel_updates_semaphore = None <NEW_LINE> self.reset_jobs = [] <NEW_LINE> self.sensor... | Initialize the system. | 625941e097e22403b379d316 |
def before_execute(self): <NEW_LINE> <INDENT> pass | Called before each call to `execute()`. | 625941e0a17c0f6771cbe3cb |
def top_five(request): <NEW_LINE> <INDENT> posts = Post.objects.filter(published_date__lte=timezone.now() ).order_by('-views')[:5] <NEW_LINE> return render(request, "blogposts.html", {'posts': posts}) | Create a view that displays the top 5 most
popular posts | 625941e057b8e32f52483819 |
def checkout_revision(repo, commit): <NEW_LINE> <INDENT> if isinstance(repo, basestring): <NEW_LINE> <INDENT> cmd = [ 'git', '-C', repo, 'checkout', '-q', commit, ] <NEW_LINE> subprocess.call(cmd) <NEW_LINE> <DEDENT> elif isinstance(repo, git.repo.base.Repo): <NEW_LINE> <INDENT> repo.git.checkout(commit) <NEW_LINE> <DE... | Check out given commit in a given repository
This would usually (and for some cases always) result in 'detached
HEAD' situation, that is HEAD reference pointing directly to a
commit, and not to a branch.
This function is called for its effects and does return nothing.
Parameters
----------
repo : str | git.Repo | py... | 625941e01f5feb6acb0c4ec5 |
def set_input(self, input): <NEW_LINE> <INDENT> AtoB = self.opt.which_direction == 'AtoB' <NEW_LINE> input_A = input['A' if AtoB else 'B'] <NEW_LINE> input_B = input['B' if AtoB else 'A'] <NEW_LINE> self.input_A.resize_(input_A.size()).copy_(input_A).to(self.device) <NEW_LINE> self.input_B.resize_(input_B.size()).copy_... | Set the order of the inputs(A, B) according to the direction.
After preprocessing the input, we will define real_A, fake_B, real_B according to the training or testing phase. | 625941e0d268445f265b51ea |
def test_parse_simple(self): <NEW_LINE> <INDENT> data = parse_manifest(get_test_file('manifest_simple.ini')) <NEW_LINE> self.assertEqual( data, ({'src/package/': ['__init__.py'], 'src/': ['README.txt'], './': ['setup.py']}, {})) | Parse a manifest with only simple rules
| 625941e0187af65679ca549b |
def start_requests(self): <NEW_LINE> <INDENT> return [Request('https://www.zhihu.com/#signin',headers=self.headers,callback=self.login)] | 第一个执行的函数,准备登录 | 625941e001c39578d7e751b7 |
def delete_request(URL, headers): <NEW_LINE> <INDENT> resp = requests.delete(URL, headers=headers) <NEW_LINE> check_response(resp) <NEW_LINE> return resp.json() | Makes a delete request, checks and returns the response.
:param URL: url to make the request to.
:param headers: Header dict to include in the request.
:return: Deserialized JSON body of the response. | 625941e04d74a7450ccd453f |
def client_mrn(): <NEW_LINE> <INDENT> for hdr in connexion.request.headers: <NEW_LINE> <INDENT> if hdr[0] == 'Ssl-Dn': <NEW_LINE> <INDENT> for field in hdr[1].split('/'): <NEW_LINE> <INDENT> if len(field) > 5: <NEW_LINE> <INDENT> if field[0:4] == 'UID=': <NEW_LINE> <INDENT> print(field[4:]) <NEW_LINE> return field[4:] ... | Get the real DN name of the requestor
or return the testing requestor | 625941e0046cf37aa974d0c0 |
def read_train_csv(filename): <NEW_LINE> <INDENT> reader = csv.reader(open(filename, 'rb')) <NEW_LINE> reader.next() <NEW_LINE> X = [] <NEW_LINE> y = [] <NEW_LINE> for row in reader: <NEW_LINE> <INDENT> X.append(row[2:]) <NEW_LINE> y.append(row[1]) <NEW_LINE> <DEDENT> return np.array(X), np.array(y) | Reads a CSV file by filename and returns the numpy
array of the features and targets. | 625941e0d99f1b3c44c67904 |
@adminbg.route("/admin/basicinfo/campus/delete", methods=['POST']) <NEW_LINE> @login_required <NEW_LINE> @admin_required <NEW_LINE> def basic_c_detele(): <NEW_LINE> <INDENT> result = basic_campus_delete() <NEW_LINE> return result | 校区删除
:return: | 625941e0656771135c3ebbee |
def get_hemming_distance_matrix(merged_population): <NEW_LINE> <INDENT> dist_matrix = [] <NEW_LINE> for indiv1 in merged_population: <NEW_LINE> <INDENT> dist_arr = [normalized_hamming_distance(indiv1, indiv2) for indiv2 in merged_population] <NEW_LINE> dist_matrix.append(dist_arr) <NEW_LINE> <DEDENT> return dist_matrix | Small helper function to get the normalized hemming distance
Args:
merged_population: merged population of instances of type "individual"
Returns: distance matrix of all individuals contained | 625941e023849d37ff7b3408 |
def db_serch_name(uname): <NEW_LINE> <INDENT> with open(path_db_users, 'r', encoding='utf-8') as fr: <NEW_LINE> <INDENT> for line in fr: <NEW_LINE> <INDENT> user = line.split('|') <NEW_LINE> if uname == user[0]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return False | uname 存在 True 不存在 False
:param uname:
:return:boolean | 625941e010dbd63aa1bd2f1e |
def output_move(self, source, dest): <NEW_LINE> <INDENT> string = '{} {} -> {} {} \n'.format(*source, *dest) <NEW_LINE> return string | :param source: Coordinates of the source (tuple in board coordinates)
:param dest: Coordinates of the destination (tuple in board coordinates
:return: The string output | 625941e0596a897236089e38 |
def logDistance(self, **kwargs): <NEW_LINE> <INDENT> gr = kwargs['node1'].params['antennaGain'][kwargs['wif']] <NEW_LINE> pt = kwargs['node2'].params['txpower'][0] <NEW_LINE> gt = kwargs['node2'].params['antennaGain'][0] <NEW_LINE> gains = pt + gt + gr <NEW_LINE> ref_d = 1 <NEW_LINE> pl = self.pathLoss(kwargs['node1'],... | Log Distance Propagation Loss Model:
ref_d (m): The distance at which the reference loss is
calculated
exponent: The exponent of the Path Loss propagation model, where 2
is for propagation in free space
(dist) is the distance between the transmitter and the receiver (m) | 625941e0377c676e91272523 |
def test_show_color_temp_only_if_command_topic(self): <NEW_LINE> <INDENT> config = {light.DOMAIN: { 'platform': 'mqtt', 'name': 'test', 'color_temp_command_topic': 'test_light_rgb/brightness/set', 'command_topic': 'test_light_rgb/set', 'state_topic': 'test_light_rgb/status' }} <NEW_LINE> with assert_setup_component(1, ... | Test the color temp only if a command topic is present. | 625941e0851cf427c661a888 |
def test_no_deletion(self): <NEW_LINE> <INDENT> analyze_text(self.filename) <NEW_LINE> self.assertTrue(os.path.exists(self.filename)) | Check function does not delete the input file | 625941e0a934411ee3751a10 |
def create_configs_with_file_option(test): <NEW_LINE> <INDENT> create_configs(test) <NEW_LINE> test.breezy_config.set_user_option('file', 'breezy') <NEW_LINE> test.locations_config.set_user_option('file', 'locations') <NEW_LINE> test.branch_config.set_user_option('file', 'branch') | Create configuration files with a ``file`` option set in each.
This builds on ``create_configs`` and add one ``file`` option in each
configuration with a value which allows identifying the configuration file. | 625941e0dc8b845886cb58b2 |
@Profile(stats=PERFORMANCE_STATS) <NEW_LINE> def build_structures(shape): <NEW_LINE> <INDENT> type_map = {'+': {'ul', 'ur', 'll', 'lr'}, '-': {'u', 'd'}, '|': {'r', 'l'}, ' ': {' '}, } <NEW_LINE> for row, shape_line in enumerate(shape.txt_lines): <NEW_LINE> <INDENT> for col, type_char in enumerate(shape_line): <NEW_LIN... | Build a number of data structures that accelerate the search for border
and space elements. | 625941e092d797404e304507 |
def getEncoding(self): <NEW_LINE> <INDENT> return self.encoding | Public method to return the current encoding.
@return current encoding (string) | 625941e04c3428357757c6a2 |
def get_curriculum_twelve( epochs, num_nodes, train_size, val_size, seed, regen, debug ): <NEW_LINE> <INDENT> steps = [ (get_tiny_quad_param, 20), ] <NEW_LINE> val_param = get_tiny_quad_param(NUM_TILES) <NEW_LINE> return make_curriculum( epochs, num_nodes, train_size, val_size, steps, val_param, seed, regen, debug, ) | Create curriculum for experiment twelve. | 625941e0379a373c97cfaec2 |
def find_contours(img, frame, show=False): <NEW_LINE> <INDENT> im2, contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) <NEW_LINE> filtered = [] <NEW_LINE> for i in range(len(contours)): <NEW_LINE> <INDENT> if len(contours[i]) > 50: <NEW_LINE> <INDENT> filtered.append(contours[i]) <NEW_L... | :param img: processed input image
:param frame: original frame
:param show: flag to display the window or not
:return: list of contours | 625941e07d43ff24873a301e |
def vert_boxes(self): <NEW_LINE> <INDENT> top_data = [d for d in self.data if d.y >= (self.y - self.height / 2)] <NEW_LINE> bot_data = [d for d in self.data if d.y < (self.y - self.height / 2)] <NEW_LINE> top = Box(self.x, self.y, self.height / 2, self.width, top_data) <NEW_LINE> bot = Box(self.x, self.y - self.height ... | Slices the box in half and returns resulting box objects. | 625941e09b70327d1c4e1152 |
def increment(n): <NEW_LINE> <INDENT> def inc(k): <NEW_LINE> <INDENT> return n + k <NEW_LINE> <DEDENT> return inc | Returns a function that takes in k and adds it to n. | 625941e03c8af77a43ae3b1f |
def item_info(fullinventory): <NEW_LINE> <INDENT> item_code = input("Enter item code: ") <NEW_LINE> if item_code in fullinventory: <NEW_LINE> <INDENT> print_dict = fullinventory[item_code] <NEW_LINE> for k, value in print_dict.items(): <NEW_LINE> <INDENT> print("{}:{}".format(k, value)) <NEW_LINE> <DEDENT> <DEDENT> els... | item_info | 625941e05510c4643540f757 |
def euclidean_distances(X, Y=None, Y_norm_squared=None, squared=False): <NEW_LINE> <INDENT> X, Y = check_pairwise_arrays(X, Y) <NEW_LINE> if Y_norm_squared is not None: <NEW_LINE> <INDENT> YY = array2d(Y_norm_squared) <NEW_LINE> if YY.shape != (1, Y.shape[0]): <NEW_LINE> <INDENT> raise ValueError( "Incompatible dimensi... | Considering the rows of X (and Y=X) as vectors, compute the
distance matrix between each pair of vectors.
For efficiency reasons, the euclidean distance between a pair of row
vector x and y is computed as::
dist(x, y) = sqrt(dot(x, x) - 2 * dot(x, y) + dot(y, y))
This formulation has two advantages over other wa... | 625941e0be7bc26dc91cd975 |
def lda_model(): <NEW_LINE> <INDENT> dictionary = corpora.Dictionary(contents_clean_list) <NEW_LINE> corpus = [dictionary.doc2bow(sentence) for sentence in contents_clean_list] <NEW_LINE> lda = gensim.models.ldamodel.LdaModel(corpus=corpus, id2word=dictionary, num_topics=20) <NEW_LINE> for topic in (lda.print_topics(nu... | LDA 主题模型
:return: | 625941e0167d2b6e31218f11 |
def get(self, populate=False): <NEW_LINE> <INDENT> result = self.do_request( 'GET', 'edges/{0}/?populate={1}'.format(self._key, to_string_url(populate))) <NEW_LINE> result = self.parent.cast(result) <NEW_LINE> return result | Get the edge by its _key
:param populate: Populate `edge.createdBy` and `edge.updatedBy` with User object
:type populate: boolean, optional
:returns: Edge object
:rtype: :class:`~aquarium.edge.Edge` | 625941e085dfad0860c3b1d8 |
def update(self, request, *args, **kwargs): <NEW_LINE> <INDENT> object = self.get_object() <NEW_LINE> signals.release_pre_update.send(sender=object.__class__, release=object, request=request) <NEW_LINE> response = super(ReleaseViewSet, self).update(request, *args, **kwargs) <NEW_LINE> if response.status_code == status.... | This end-point allows updating a release.
When using the `PUT` method, if an optional field is not specified in
the input, it will be erased.
This applies also to Bugzilla and DistGit mapping: if it is not specified,
it will be cleared.
__Method__: PUT, PATCH
__URL__: $LINK:release-detail:release_id$
__Data__:
%(... | 625941e07cff6e4e81117d01 |
def __init__(self, im_size, hidden_dim, kernel_size, n_classes): <NEW_LINE> <INDENT> super(CNN, self).__init__() <NEW_LINE> C, H, W = im_size; <NEW_LINE> self.conv1 = torch.nn.Conv2d(C, hidden_dim, kernel_size); <NEW_LINE> Hout = np.int64(1 + H - kernel_size); <NEW_LINE> Wout = np.int64(1 + W - kernel_size); <NEW_LINE>... | Create components of a CNN classifier and initialize their weights.
Arguments:
im_size (tuple): A tuple of ints with (channels, height, width)
hidden_dim (int): Number of hidden activations to use
kernel_size (int): Width and height of (square) convolution filters
n_classes (int): Number of classes to ... | 625941e024f1403a92600edf |
def random_graph(n, p=0.5): <NEW_LINE> <INDENT> points = numpy.random.rand(n, 2) <NEW_LINE> im = [[] for i in range(n)] <NEW_LINE> for i in range(n-1): <NEW_LINE> <INDENT> for j in range(i+1, n): <NEW_LINE> <INDENT> if numpy.random.random_sample() < p: <NEW_LINE> <INDENT> im[i].append(j) <NEW_LINE> im[j].append(i) <NEW... | generate a graph whose nodes are uniformly distributed in [0, 1]*[0,1]
:param n: the number of nodes
:param p: how many edges in the graph
:return: | 625941e0fbf16365ca6f6546 |
def cmd_right(self): <NEW_LINE> <INDENT> level = self.levels[-1] <NEW_LINE> self.report("right") <NEW_LINE> level.moveto(level.curx+self.stepx, level.cury) | Move the cursor right. | 625941e00a366e3fb873eb99 |
def get_all_selected_sets(self): <NEW_LINE> <INDENT> oModel, aSelectedRows = self._oSelection.get_selected_rows() <NEW_LINE> if len(aSelectedRows) < 1: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> aSets = [] <NEW_LINE> for oPath in aSelectedRows: <NEW_LINE> <INDENT> aSets.append(oModel.get_name_from_path(oPath))... | Return a list of all the selected sets | 625941e0293b9510aa2c360e |
def p_function_define(p): <NEW_LINE> <INDENT> if (p[3] in global_functions): <NEW_LINE> <INDENT> raise NameError("ERROR("+ str(size_of_input-statement_count) +"): function already exists '"+ str(p[3]) +"' ") <NEW_LINE> <DEDENT> if (len(p) == 7): <NEW_LINE> <INDENT> def_funct = FunctionNode(p[5],p[2],p[3]) <NEW_LINE> ne... | function_define : FUNCTION_DEFINE type_node ID '(' function_params ')'
| FUNCTION_DEFINE type_node ID '(' ')' | 625941e0ab23a570cc250501 |
@threaded_execution <NEW_LINE> def long_long_function(filename): <NEW_LINE> <INDENT> logger.info("Filename to work with: {}".format(filename)) <NEW_LINE> run_tracker.append(filename) <NEW_LINE> time.sleep(span_time) <NEW_LINE> mod_filename = 'truncated_' + filename <NEW_LINE> with open(filename, 'r+') as first_file, op... | Decorated function | 625941e08c3a87329515873a |
def generate(self, sess, saved_args, n, z_mu=None): <NEW_LINE> <INDENT> if z_mu is None: <NEW_LINE> <INDENT> z_mu = np.random.normal(size=(n, saved_args.n_z)) <NEW_LINE> <DEDENT> return sess.run(self.generated_images, feed_dict={self.guessed_z: z_mu}) | Generate data by sampling from latent space. | 625941e04e696a04525c97c8 |
def randomlySelectFalseClause(self,clauses,model): <NEW_LINE> <INDENT> falseClauses = [] <NEW_LINE> for c in clauses: <NEW_LINE> <INDENT> if not model.determineValue(c): <NEW_LINE> <INDENT> falseClauses.append(c) <NEW_LINE> <DEDENT> <DEDENT> return random.choice(falseClauses) | :rtype: Clause | 625941e063b5f9789fde7462 |
def updateFileList( self, curDir=None, filterFmt=None ): <NEW_LINE> <INDENT> if curDir==None: <NEW_LINE> <INDENT> curDir = self.curDir <NEW_LINE> <DEDENT> self.removeFileList() <NEW_LINE> self.elemList = [] <NEW_LINE> Util.trace( "curDir [%s] updateFileList" %(curDir) ) <NEW_LINE> listdir = os.listdir( curDir ) <NEW_LI... | ファイルリストを更新
| 625941e050485f2cf553d117 |
def assertSubmissionInDb(self, timestamp, task, language, files): <NEW_LINE> <INDENT> db_submissions = self.session.query(Submission) .filter(Submission.timestamp == make_datetime(timestamp)) .filter(Submission.task_id == task.id).all() <NEW_LINE> self.assertEqual(len(db_submissions), 1) <NEW_LINE... | Assert that the submission with the given data is in the DB. | 625941e091f36d47f21ac872 |
def intersection(self, A, B, C, D): <NEW_LINE> <INDENT> if A.x == B.x and C.x == D.x: return None <NEW_LINE> elif (A.x == B.x): <NEW_LINE> <INDENT> c = (C.y - D.y)/(C.x - D.x) <NEW_LINE> d = C.y - (c*C.x) <NEW_LINE> x = A.x <NEW_LINE> y = c*x + d <NEW_LINE> <DEDENT> elif (C.x == D.x): <NEW_LINE> <INDENT> a = (A.y - B.y... | Retourne l'intersection des secgments [point1 point2] et [point3 point4] en 2 dimentions | 625941e076d4e153a657eeae |
@curry <NEW_LINE> @add_repr <NEW_LINE> def append_bytes(path: str, content: bytes) -> Effect[HasFiles, OSError, None]: <NEW_LINE> <INDENT> return depend(HasFiles).and_then( lambda env: env.files.append_bytes(path, content) ) | Get an `Effect` that appends to a file
Example:
>>> class Env:
... files = Files()
>>> append_bytes('foo.txt')(b'content of foo.txt')\
... .discard_and_then(read('foo.txt'))\
... .run(Env())
'content of foo.txt'
Args:
path: the path of the file to be written
content the con... | 625941e031939e2706e4d1e1 |
def _maxc(self, clef, valeur): <NEW_LINE> <INDENT> self.valeurs[clef] = max(self.valeurs.get(clef, valeur), valeur) | max des valeurs en mode alpha | 625941e0d58c6744b4257fda |
@app.route('/hidden', methods=['GET']) <NEW_LINE> @auth.oidc_auth <NEW_LINE> def hidden(): <NEW_LINE> <INDENT> metadata = get_metadata() <NEW_LINE> if metadata['is_admin']: <NEW_LINE> <INDENT> quotes = get_quote_query(include_hidden=True).filter( Quote.hidden ).all() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> quotes... | Presents hidden quotes to qualified users
Users who submitted a hidden quote or were quoted in a hidden quote will see those only
Admins see all hidden quotes | 625941e0a8370b7717052c1a |
def predict_proba(self, context): <NEW_LINE> <INDENT> counts = self.get_counts(context) <NEW_LINE> return counts / counts.sum() | Estimate probability of all symbols that may follow the context
Parameters:
context - text string (only the last self.order chars matter)
Returns:
freq - vector of letter conditional frequencies, as pandas.Series | 625941e0090684286d50f066 |
def by_paths(self, paths, admin_unit_id=None): <NEW_LINE> <INDENT> admin_unit_id = admin_unit_id or get_current_admin_unit().id() <NEW_LINE> query = self.restrict().filter_by(admin_unit_id=admin_unit_id) <NEW_LINE> return query.filter(Task.physical_path.in_(paths)).all() | Returns all tasks whos physical_path is listed in `paths`.
| 625941e03c8af77a43ae3b20 |
def unify_row_meta_column_names(adats: List[Adat]) -> List[Adat]: <NEW_LINE> <INDENT> all_row_meta_names = [] <NEW_LINE> for adat in adats: <NEW_LINE> <INDENT> all_row_meta_names.append(list(adat.index.names)) <NEW_LINE> <DEDENT> ordered_row_meta_names = order_merge_row_meta_names(all_row_meta_names) <NEW_LINE> new_ada... | Given a list of adat dataframes, returns the list of adats with matching row metadata columns.
An adat concatenation method that prepares adats with disparate row metadata for merging by unifying their
row metadata. Since the core concatenator, by default, requires that the row metadata columns match exactly,
this fun... | 625941e05fcc89381b1e1a3d |
def create_node_instances(dummy_internet, number_of_nodes_to_create: int, is_program_running, preferred_no_of_mining_nodes=0, ): <NEW_LINE> <INDENT> assert number_of_nodes_to_create > 0, "number of admins to create must be at least 1" <NEW_LINE> assert number_of_nodes_to_create >= preferred_no_of_mining_nodes, "number ... | :param dummy_internet:
:param number_of_nodes_to_create:
:param preferred_no_of_mining_nodes: number of mining nodes from nodes created
:param genesis_start: tells competing node to start create block 1 without waiting for blocks.
(only block available should be block 0 aka genesis block)
:return: | 625941e0e5267d203edce015 |
def p_expression(p): <NEW_LINE> <INDENT> pass | expression : LBRAC subexpression RBRAC
| string | 625941e01b99ca400220ae2f |
def parseFasta(fastaFile): <NEW_LINE> <INDENT> with open(fastaFile) as fastFile: <NEW_LINE> <INDENT> data = '' <NEW_LINE> Seqs = {} <NEW_LINE> for line in fastFile: <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> if line.startswith(">"): <NEW_LINE> <INDENT> if data: <NEW_LINE> <INDENT> Seqs[inKey] = data <NEW_LINE> ... | This function takes a fasta file as input and returns the header of each sequence as a key and the fasta sequence
as the value | 625941e091af0d3eaac9bd98 |
def test_plus(self): <NEW_LINE> <INDENT> self.assertEqual((PosixPath('some/file.txt') + '.bak').path, b'some/file.txt.bak') <NEW_LINE> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> PosixPath('some/file.txt') + PosixPath('.bak') <NEW_LINE> <DEDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> PosixPa... | Tests the plus operator. | 625941e0627d3e7fe0d691ce |
def test_event(self): <NEW_LINE> <INDENT> input_string = open(os.path.dirname(__file__) + '/data_samples/dionaea_mwbinary_sample1.txt', 'r').read() <NEW_LINE> expected_file = {'encoding': 'hex', 'content_guess': 'PE32 executable (DLL) (GUI) Intel 80386, for MS Windows, UPX compressed', 'data': input_string, 'hashes': {... | Test extraction of binary from dionaea and generation of correct hashes. | 625941e05fdd1c0f98dc05b1 |
def connect_juju_client(env_name, retries=3, logging=None): <NEW_LINE> <INDENT> env = None <NEW_LINE> for _ in xrange(retries): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> env = jujuclient.Environment.connect(env_name=env_name) <NEW_LINE> break <NEW_LINE> <DEDENT> except socket.timeout: <NEW_LINE> <INDENT> if logging:... | Connect to jujuclient. | 625941e0b545ff76a8914192 |
def get_format_string(self): <NEW_LINE> <INDENT> return self.format_string | Retrieves the currently associated string for formatting
in the current format tuple.
@rtype: String
@return: The currently available format string. | 625941e0d10714528d600063 |
def parse_bot_commands(slack_events): <NEW_LINE> <INDENT> for event in slack_events: <NEW_LINE> <INDENT> if event["type"] == "message" and not "subtype" in event: <NEW_LINE> <INDENT> user_id, message = parse_direct_mention(event["text"]) <NEW_LINE> if user_id == starterbot_id: <NEW_LINE> <INDENT> return message, event[... | Parses a list of events coming from the Slack RTM API to find bot commands.
If a bot command is found, this function returns a tuple of command and channel.
If its not found, then this function returns None, None. | 625941e0aad79263cf390dc3 |
def test_calculate_gb_label(self): <NEW_LINE> <INDENT> size_str = '15gb' <NEW_LINE> drive_size = 20 * 10**9 <NEW_LINE> drive = BlockDevice(None, size=drive_size, available_size=drive_size) <NEW_LINE> calc_size = ApplyNodeStorage.calculate_bytes( size_str=size_str, context=drive) <NEW_LINE> assert calc_size == 15 * 10**... | Convert gigabyte labels to x * 10^9 bytes. | 625941e0d18da76e23532857 |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> Module.__init__(self, kwargs=kwargs) <NEW_LINE> self.url_pattern = re.compile('http://[^ #]+') | Constructor | 625941e0f7d966606f6aa385 |
def _get_fontsize(size_name): <NEW_LINE> <INDENT> font_sizes = { "xx-small": 5.79, "x-small": 6.94, "small": 8.33, "medium": 10.0, "large": 12.0, "x-large": 14.4, "xx-large": 17.28, "larger": 12.0, "smaller": 8.33, } <NEW_LINE> return font_sizes[size_name] | Return a fontsize based on matplotlib labels. | 625941e0f8510a7c17cf9a7b |
def _try_resolve_sam_resource_id_refs(self, input, supported_resource_id_refs): <NEW_LINE> <INDENT> if not self._is_intrinsic_dict(input): <NEW_LINE> <INDENT> return input <NEW_LINE> <DEDENT> function_type = list(input.keys())[0] <NEW_LINE> return self.supported_intrinsics[function_type].resolve_resource_id_refs(input,... | Try to resolve SAM resource id references on the given template. If the given object looks like one of the
supported intrinsics, it calls the appropriate resolution on it. If not, this method returns the original input
unmodified.
:param dict input: Dictionary that may represent an intrinsic function
:param dict suppo... | 625941e007d97122c4178c10 |
def _do_first_msg(self, event): <NEW_LINE> <INDENT> msg = 'action=sendClientFirstMessage&clientFirstMessage=n,,%s' % self.client_first_msg <NEW_LINE> cookies = dict(niagara_userid = self._session._username) <NEW_LINE> try: <NEW_LINE> <INDENT> self._session._post('%s/j_security_check' % (self._login_uri), body=msg.encod... | Send the client first message to server | 625941e0fff4ab517eb2f7ba |
def __init__(self, flags_attr, required_flags): <NEW_LINE> <INDENT> self._flags_attr = flags_attr <NEW_LINE> self._required_flags = required_flags | Creates a new FlagDecider with the specified flag attribute and
required flag names.
:param flags_attr: The attribute that stores the flag value.
:param required_flags: The names of all flags that have to be set. | 625941e06aa9bd52df037122 |
def getInfo(self): <NEW_LINE> <INDENT> return { 'name' : self.name, 'start' : self.start, 'end' : self.end, 'step' : self.step, 'values' : list(self), 'pathExpression' : self.pathExpression, } | Pickle-friendly representation of the series | 625941e09f2886367277ac08 |
def controller_python(version): <NEW_LINE> <INDENT> return filter_python(version, CONTROLLER_PYTHON_VERSIONS) | If a Python version is given and is supported by the controller, return that Python version, otherwise return None. | 625941e01d351010ab855e98 |
def gspan_to_eden(input=None, options=dict()): <NEW_LINE> <INDENT> header = '' <NEW_LINE> string_list = [] <NEW_LINE> for line in util.read(input): <NEW_LINE> <INDENT> if line.strip(): <NEW_LINE> <INDENT> if line[0] in ['g', 't']: <NEW_LINE> <INDENT> if string_list: <NEW_LINE> <INDENT> yield gspan_to_networkx(header, s... | Takes a string list in the extended gSpan format and yields networkx graphs.
Parameters
----------
input : string
A pointer to the data source. | 625941e08a349b6b435e84f0 |
def frequence_cumule(liste = []): <NEW_LINE> <INDENT> fq = frequence(liste) <NEW_LINE> cle = [x for x in fq.keys()] <NEW_LINE> cle.sort() <NEW_LINE> val = [x for x in fq.values()] <NEW_LINE> fq_c = fq <NEW_LINE> for i in range(1, len(cle)): <NEW_LINE> <INDENT> fq_c[cle[i]] = sum(val[:i+1]) <NEW_LINE> <DEDENT> return fq | frequence cumules | 625941e0d10714528d600064 |
def test_yapf(): <NEW_LINE> <INDENT> pkg_paths = list(os.environ["PYSH_YAPF_PKG_PATH"].split(",")) <NEW_LINE> proc = SH.python3('-m', 'yapf', '-d', '--recursive', *pkg_paths) <NEW_LINE> out, _err = proc <NEW_LINE> proj_path = os.environ.get("PYSH_PROJ_PATH", os.path.dirname(pkg_paths[0])) <NEW_LINE> target_path = os.pa... | Check current code-base for yapf formatting | 625941e07c178a314d6ef7e2 |
def out_16(library, session, space, offset, data, extended=False): <NEW_LINE> <INDENT> if extended: <NEW_LINE> <INDENT> library.viOut16Ex(session, space, offset, data, extended=False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> library.viOut16(session, space, offset, data, extended=False) | Write in an 16-bit value from the specified memory space and offset.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
... | 625941e016aa5153ce3627f5 |
def test_subprocess_called_correctly(self): <NEW_LINE> <INDENT> fix = SihcStandardNameAdd( 'sihc_components.nc', '/a' ) <NEW_LINE> fix.apply_fix() <NEW_LINE> self.mock_subprocess.assert_called_once_with( "ncatted -h -a standard_name,sihc,o,c," "'sea_ice_temperature_expressed_as_heat_content' " "/a/sihc_components.nc", ... | Test that an external call's been made correctly for
SihcStandardNameAdd | 625941e007f4c71912b11801 |
def generate_platforms(bottom_height: int, top_height: int) -> list: <NEW_LINE> <INDENT> h = top_height <NEW_LINE> platforms = [] <NEW_LINE> while h > bottom_height: <NEW_LINE> <INDENT> x = random.randint(0, screen_width) <NEW_LINE> p = random.randint(0, 100) <NEW_LINE> if p <= 80: <NEW_LINE> <INDENT> typ = 0 <NEW_LINE... | Функция, генерирующая платформы на высоте от **bottom_height**
до **top_height**
Возвращает список сгенерированных платформ | 625941e06e29344779a6298d |
@pytest.fixture <NEW_LINE> def tmp_real_vid(create_tmp_file: TmpFileCreator) -> Path: <NEW_LINE> <INDENT> return create_tmp_file("VID_20190202_184513_634.mp4") | Copy a video to the temporary testing directory.
This video is a real files which contain origina metadata, preserved
without any modification or deletion. | 625941e0d268445f265b51eb |
def isBlank(self, fallOffObject, position=None): <NEW_LINE> <INDENT> if not position: <NEW_LINE> <INDENT> position = self.position <NEW_LINE> <DEDENT> x1, y1 = position['offset'] <NEW_LINE> x2 = x1 + self.enabledWidth <NEW_LINE> y2 = y1 + self.enabledHeight <NEW_LINE> mask = self.getFilteredImages(position)[0].split()[... | Return True if the enabled region of the image specified by the
current position is blank.
Args:
fallOffObject: If True, the image is considered blank only if the
mask is entirely black. Otherwise, it is considered
blank if any of mask is black
position: Position to use. Use... | 625941e04f88993c3716c3e1 |
def test_search_questions_without_results(self): <NEW_LINE> <INDENT> res = self.client().post('/search', json={'searchTerm': 1993}) <NEW_LINE> data = json.loads(res.data) <NEW_LINE> self.assertEqual(res.status_code, 200) <NEW_LINE> self.assertTrue(data['success']) <NEW_LINE> self.assertEqual(len(data['questions']), 0) ... | Test questions are not retrieved by keyword. | 625941e0460517430c3944fa |
def get_most_common_words(self, number): <NEW_LINE> <INDENT> logger.info('Gathering most common words') <NEW_LINE> most_common = [Result(orth, count, self.build_matches(orth)) for orth, count in self.counter.most_common(number)] <NEW_LINE> return most_common | Return list containing matches for given number of most commonly
occurring words in corpus. | 625941e0c432627299f04fc6 |
def det2(A): <NEW_LINE> <INDENT> det = (A[0, 0] * A[1, 1]) - (A[0, 1] - A[1, 0]) <NEW_LINE> return det | Calculate determinant of 2x2 system | 625941e0d7e4931a7ee9e29c |
def step(self, action, memory_increment=0) -> Tuple[np.ndarray, float, bool, dict]: <NEW_LINE> <INDENT> raise NotImplementedError() | Take a step in the environment using the given action.
Parameters
----------
action : int
The action that the neural network has decided to take. This may
either be a value returned from the actual Keras model, or it may
be a value returned from this own class' `get_sample_action`.
memory_increment : int, ... | 625941e04c3428357757c6a3 |
def _sensor_shape(coil): <NEW_LINE> <INDENT> rrs = np.empty([0, 2]) <NEW_LINE> tris = np.empty([0, 3], int) <NEW_LINE> id_ = coil['type'] & 0xFFFF <NEW_LINE> if id_ in (2, 3012, 3013, 3011): <NEW_LINE> <INDENT> long_side = coil['size'] <NEW_LINE> offset = 0.0025 <NEW_LINE> rrs = np.array([ [offset, -long_side / 2.], [l... | Get the sensor shape vertices. | 625941e0099cdd3c635f0fd6 |
def run_command(*args, **kwargs): <NEW_LINE> <INDENT> redirect_out = list(map(str.strip, " ".join(args).split(" > "))) <NEW_LINE> if len(redirect_out) > 1: <NEW_LINE> <INDENT> args, filepath = redirect_out[0].split(), redirect_out[-1] <NEW_LINE> kwargs.update(stdout=open(filepath, "w")) <NEW_LINE> <DEDENT> return subpr... | Runs an os command using subprocess module. | 625941e04e4d5625662d4750 |
def test1EntryNoImportLib(self): <NEW_LINE> <INDENT> sys.modules['importlib'] = None <NEW_LINE> global entry <NEW_LINE> self._ReloadEntry() <NEW_LINE> entry.Entry.Create(None, self.GetNode(), 'u-boot') <NEW_LINE> self.assertFalse(entry.have_importlib) | Test that we can import Entry subclassess successfully | 625941e05fdd1c0f98dc05b2 |
def nitems_written(self, which_output): <NEW_LINE> <INDENT> return _qbee_swig.qbee_deframer_sptr_nitems_written(self, which_output) | nitems_written(qbee_deframer_sptr self, unsigned int which_output) -> uint64_t | 625941e01b99ca400220ae30 |
def format_element(bfo): <NEW_LINE> <INDENT> journal_name = bfo.field(journal_name_tag) <NEW_LINE> journal_name = journal_name.lower().strip() <NEW_LINE> if journal_name.endswith("[online]"): <NEW_LINE> <INDENT> journal_name = journal_name[:-8].rstrip() <NEW_LINE> <DEDENT> return issns.get(journal_name, '') | Returns the ISSN of the record, if known.<br/>
Note that you HAVE to pre-generate the correspondances
journal->ISSN if you want this element
to return something (Run <code>python bfe_issn.py -h</code> to get help). | 625941e0dd821e528d63b523 |
def clip(raster, geometry=None, clip_outside=True, astype=None): <NEW_LINE> <INDENT> layer, raster, raster_ra = _raster_input(raster) <NEW_LINE> template_dict = { "rasterFunction": "Clip", "rasterFunctionArguments": { "ClippingGeometry": geometry, "ClipType": 1 if clip_outside else 2, "Raster": raster } } <NEW_LINE> if... | Clips a raster using a rectangular shape according to the extents defined or will clip a raster to the shape of an
input polygon. The shape defining the clip can clip the extent of the raster or clip out an area within the raster.
:param raster: input raster
:param geometry: clipping geometry
:param clip_outside: bool... | 625941e021a7993f00bc8073 |
def second_stage(data, h, w, i, j): <NEW_LINE> <INDENT> windows = [(0,1),(-1,0),(1,1),(-1,-1),(0,1),(0,-1),(-1,1),(1,-1)] <NEW_LINE> grads = [] <NEW_LINE> for window in windows: <NEW_LINE> <INDENT> grads.append(compute_gradient(data, h, w, i, j, window[1], window[0])) <NEW_LINE> <DEDENT> return max(grads) | The pixel (i,j) is an edge candidate within the data.
Determine whether (i,j) is actually an edge pixel. | 625941e09b70327d1c4e1153 |
def generate(self, parse_obj): <NEW_LINE> <INDENT> with ace.AceGenerator(self.gram_file, executable=self.ace_bin) as generator: <NEW_LINE> <INDENT> response = generator.interact(str(parse_obj.mrs())) <NEW_LINE> sents = [] <NEW_LINE> if response and 'RESULTS' in response: <NEW_LINE> <INDENT> for res in response['RESULTS... | Generate text from coolisf.model.Parse object | 625941e0fff4ab517eb2f7bb |
def mn_generate_data(para_mat, para_val, n, oc, batch_size=1, random_state=None): <NEW_LINE> <INDENT> p = mn_joint_dist(para_mat, para_val, oc) <NEW_LINE> ind = np.repeat(np.arange(oc.shape[0]), ss.multinomial.rvs(n, p, size=1, random_state=random_state).ravel()) <NEW_LINE> return ind | Generate data from a log-linear model using exact sampling.
Parameters
----------
para_mat : float or arraylike
Logical matrix representing log-linear parameters.
para_val : float or arraylike
Numerical values of the log-linear parameters.
n : int
number of samples.
Returns
-------
data : Sampled data mat... | 625941e0d486a94d0b98e4c4 |
def upsert_vertices(self, label): <NEW_LINE> <INDENT> def upsert_vertices_for_label(rows): <NEW_LINE> <INDENT> conn = self.remote_connection() <NEW_LINE> g = self.traversal_source(conn) <NEW_LINE> for row in rows: <NEW_LINE> <INDENT> entries = row.asDict() <NEW_LINE> create_traversal = __.addV(label) <NEW_LINE> for key... | Conditionally adds vertices for the rows in a DataFrame partition using the Gremlin coalesce() idiom.
The DataFrame must contain an '~id' column.
Example:
>>> dynamicframe.toDF().foreachPartition(neptune.upsert_vertices('Product')) | 625941e0d6c5a102081443cb |
@pytest.mark.parametrize("w,h", [(1, 1), (2, 2), (2, 4), (4, 2), (7, 15)]) <NEW_LINE> def test_hilbert_chip_order(w, h): <NEW_LINE> <INDENT> machine = Machine(w, h) <NEW_LINE> assert set(hilbert_chip_order(machine)).issuperset(set(machine)) | Make sure the iterator covers the whole machine. | 625941e03d592f4c4ed1d3e2 |
def cd(self, args): <NEW_LINE> <INDENT> _dirs=self._parse_args(args, force_phonefs=True) <NEW_LINE> if _dirs: <NEW_LINE> <INDENT> _dirname=_dirs[0]['name'] <NEW_LINE> if _dirname=='/': <NEW_LINE> <INDENT> _dirname=self._rootdir <NEW_LINE> <DEDENT> if self.phone.exists(_dirname): <NEW_LINE> <INDENT> self._pwd=_dirname <... | Change the current working dir on the phone FS.
@param args: dir name(s), only args[0] matters.
@returns: (True, None) if successful, (False, error code) otherwise | 625941e0e76e3b2f99f3ab83 |
def set_event(self, event): <NEW_LINE> <INDENT> self._event = event <NEW_LINE> if len(self._buffer) > 0: <NEW_LINE> <INDENT> event.set() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> event.clear() | Set an event on this buffer. When data is ready to be read (or the
buffer has been closed), the event will be set. When no data is
ready, the event will be cleared.
:param threading.Event event: the event to set/clear | 625941e066656f66f7cbc52a |
def documentMargin(self): <NEW_LINE> <INDENT> return 0.0 | QTextDocument.documentMargin() -> float | 625941e091af0d3eaac9bd99 |
def __init__(self, regions, seg_key="seg", output_key="seg", seg_channel=0): <NEW_LINE> <INDENT> self.seg_channel = seg_channel <NEW_LINE> self.output_key = output_key <NEW_LINE> self.seg_key = seg_key <NEW_LINE> self.regions = regions | regions are tuple of tuples where each inner tuple holds the class indices that are merged into one region, example:
regions= ((1, 2), (2, )) will result in 2 regions: one covering the region of labels 1&2 and the other just 2
:param regions:
:param seg_key:
:param output_key: | 625941e04d74a7450ccd4541 |
def debug(self, msg: object) -> None: <NEW_LINE> <INDENT> self._trace(msg, level=7) | Write trace output at 'debug' (7) level. | 625941e056b00c62f0f149d9 |
def evaluate_generator(self, generator, val_samples, max_q_size=10, nb_worker=1, pickle_safe=False): <NEW_LINE> <INDENT> self._make_test_function() <NEW_LINE> processed_samples = 0 <NEW_LINE> wait_time = 0.01 <NEW_LINE> all_outs = [] <NEW_LINE> weights = [] <NEW_LINE> data_gen_queue, _stop, generator_threads = generato... | Evaluates the model on a data generator. The generator should
return the same kind of data as accepted by `test_on_batch`.
Arguments:
generator:
generator yielding tuples (inputs, targets)
or (inputs, targets, sample_weights)
val_samples:
total number of samples to generate from `genera... | 625941e0adb09d7d5db6cb0b |
def add_box(self, box): <NEW_LINE> <INDENT> ra = box.center.x <NEW_LINE> dec = box.center.y <NEW_LINE> ra_span = 2. * box.radius.x <NEW_LINE> dec_span = 2. * box.radius.y <NEW_LINE> self.table.add_row([ra, dec, ra_span, dec_span]) | This function ...
:param box:
:return: | 625941e00383005118ecf95f |
def get_random_proxy(self): <NEW_LINE> <INDENT> proxies = self.red.getip() <NEW_LINE> proxy = random.choice(proxies).strip() <NEW_LINE> proxy = 'http://' + proxy <NEW_LINE> return proxy | 随机从文件中读取proxy | 625941e0498bea3a759b9e2c |
def pageTextPost(url, parameters): <NEW_LINE> <INDENT> gotInfo = False <NEW_LINE> while not gotInfo: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> commonsHelperPage = urlopen( "http://tools.wmflabs.org/commonshelper/index.php", parameters) <NEW_LINE> data = commonsHelperPage.read().decode('utf-8') <NEW_LINE> gotInfo = T... | Get data from commons helper page. | 625941e0851cf427c661a88a |
def types_in_package(self, package): <NEW_LINE> <INDENT> types = [] <NEW_LINE> search_types = [ "interface", "class", "enum", "exception", "error", "type", "annotation" ] <NEW_LINE> for search_type in search_types: <NEW_LINE> <INDENT> if search_type in package: <NEW_LINE> <INDENT> types.extend( class_info["name"] for c... | Returns a list of types in specified package
@param package: a package retrieved from Packages Manager | 625941e04d74a7450ccd4542 |
def save_image_to_list(self, instrument_id, image): <NEW_LINE> <INDENT> self._r.lpush("instruments:" + str(instrument_id) + ":images", image) <NEW_LINE> self._r.ltrim("instruments:" + str(instrument_id) + ":images", 0, 15) | Push a string to the front of Redis list with the key 'instruments:<instrument_id>:images', then trimming the
right images off the list to keep it at a length of 16. Meant to contain a sequence of images as strings. | 625941e0435de62698dfdfcb |
def sum_of_squares(v: Vector) -> float: <NEW_LINE> <INDENT> return dot(v, v) | Computes the sum of squared elements in v | 625941e0cc40096d61595ccd |
@pytest.mark.hookwrapper <NEW_LINE> def pytest_pyfunc_call(pyfuncitem): <NEW_LINE> <INDENT> if not enable_rbac: <NEW_LINE> <INDENT> yield <NEW_LINE> return <NEW_LINE> <DEDENT> if 'rbac_role' in pyfuncitem.fixturenames: <NEW_LINE> <INDENT> user = pyfuncitem._request.getfuncargvalue('rbac_role') <NEW_LINE> really_logout(... | Inspects and consumes certain exceptions
The guts of this function are explained above in the module documentation.
Args:
pyfuncitem: A pytest test item. | 625941e06fece00bbac2dac0 |
def process_data(samples_df, training ): <NEW_LINE> <INDENT> print('Training mode:', training) <NEW_LINE> num_obs = samples_df.shape[0] <NEW_LINE> print('Num initial observations in the dataset: ', num_obs) <NEW_LINE> image_url = samples_df.img_url.tolist() <NEW_LINE> angles = samples_df.steering.tolist() <NEW_LINE> X ... | The input is a dataframe in the log format from the simulator.
For each row in the log, we add these 3 and the corresponding flipped ones to a
X, y arrays, that are the output of the function | 625941e07b25080760e397d5 |
def searchGff( gene, gffFile, reference ): <NEW_LINE> <INDENT> refdb = reference + '.db' <NEW_LINE> geneInfo = [] <NEW_LINE> if not os.path.exists(refdb): <NEW_LINE> <INDENT> db = gffutils.create_db(gffFile, dbfn=refdb, force=True) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> tdb = gffutils.FeatureDB(refdb, keep_order=... | Parse the reference gff file for specified gene ( in yeast ORF format, YAL046C)
Return left & right positions, chromosome and strand as a list
use gfftutils | 625941e0711fe17d825426e1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.