code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def main(input_path): <NEW_LINE> <INDENT> root = loadmat(input_path, struct_as_record=False, squeeze_me=True) <NEW_LINE> go = root['go'] <NEW_LINE> header = ['ORF'] + list(go.term_names) <NEW_LINE> print(*header, sep='\t') <NEW_LINE> for i in range(len(go.orfs)): <NEW_LINE> <INDENT> labels = go.term2orf[:, i] <NEW_LINE... | Extract GO annotations from GO MATLAB data.
| 625941dd0a50d4780f6671ae |
def set(name, value): <NEW_LINE> <INDENT> if isinstance(value, basestring): <NEW_LINE> <INDENT> val = "'{0}'".format(value) <NEW_LINE> <DEDENT> elif isinstance(value, bool): <NEW_LINE> <INDENT> val = "{0}".format(1 if value else 0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> val = value <NEW_LINE> <DEDENT> vim.comman... | To set a vim variable to a given value. | 625941ddd58c6744b4257f78 |
@cmd("emote") <NEW_LINE> @disabled_in_gamemode("if") <NEW_LINE> def do_emote(player, parsed, ctx): <NEW_LINE> <INDENT> if not parsed.unparsed: <NEW_LINE> <INDENT> raise ParseError("Emote what message?") <NEW_LINE> <DEDENT> emote_msg = lang.capital(player.title) + " " + parsed.unparsed <NEW_LINE> if not parsed.unparsed.... | Emit a custom 'emote' message literally, such as: 'emote looks stupid.' -> '<player> looks stupid. | 625941dd7047854f462a171f |
@django_view <NEW_LINE> @ajax_request <NEW_LINE> @user_permission <NEW_LINE> @csrf_protect <NEW_LINE> def grp_ajax_send_request(request, group_id, template_name='generic/simple.html'): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> prep_data(('user/group/join_request/', {'group_id': group_id}), re... | Ajax view for sending group request membership. | 625941ddcc40096d61595c69 |
def _recv_thread_func(self): <NEW_LINE> <INDENT> use_ssl = self.config.get_bool("gox", "use_ssl") <NEW_LINE> wsp = {True: "wss://", False: "ws://"}[use_ssl] <NEW_LINE> while not self._terminating: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> url = "%s%s/socket.io/1" % (wsp, self.hostname) <NEW_LINE> sym = "%s%s" % (sel... | this is the main thread that is running all the time. It will
connect and then read (blocking) on the socket in an infinite
loop. SocketIO messages ('2::', etc.) are handled here immediately
and all received json strings are dispathed with signal_recv. | 625941dd0a366e3fb873eb36 |
def getdup2ebx(fd2): <NEW_LINE> <INDENT> tmp=binstring("31 c9") <NEW_LINE> tmp+=binstring("b1")+chr(fd2) <NEW_LINE> tmp+=binstring("b0 3f") <NEW_LINE> tmp+=binstring("cd 80") <NEW_LINE> return tmp | INPUT: Wants fd1 in ebx
calls dup2 to set fd2 to fd1 | 625941dd566aa707497f487e |
def _init_urandom(): <NEW_LINE> <INDENT> node_id = uuidm.getnode() <NEW_LINE> microseconds = int(time.time() * 1e6) <NEW_LINE> ctokens = [((node_id + microseconds) >> ((i % 6) * 8)) % 256 for i in range(16)] <NEW_LINE> random.seed(node_id + microseconds) <NEW_LINE> try: <NEW_LINE> <INDENT> os.urandom(1) <NEW_LINE> have... | This function and the web2py_uuid follow from the following discussion:
http://groups.google.com/group/web2py-developers/browse_thread/thread/7fd5789a7da3f09
At startup web2py compute a unique ID that identifies the machine by adding
uuid.getnode() + int(time.time() * 1e3)
This is a 48-bit number. It converts the num... | 625941dd167d2b6e31218eae |
def b2a_hqx(*args, **kwargs): <NEW_LINE> <INDENT> pass | Encode .hqx data. | 625941dd29b78933be1e59c1 |
def selftest(self): <NEW_LINE> <INDENT> res, msg = self.check(codecs.encode(self.eicar, 'rot_13')) <NEW_LINE> if res or not 'EICAR-AV-Test' in msg: <NEW_LINE> <INDENT> raise SSSPError('Selftest failed. EICAR Virus was not detected.') <NEW_LINE> <DEDENT> return True | Run a quick selftest on the savdi daemon.
Send the eicar test string to the savdi socket and raise an exception if
the report comes back clean. | 625941dd92d797404e3044a5 |
@api_view(['GET', ]) <NEW_LINE> def list_results(request): <NEW_LINE> <INDENT> if request.user.is_authenticated: <NEW_LINE> <INDENT> results = Result.objects.filter(user=request.user) <NEW_LINE> serializer = ResultSerializer(results, many=True) <NEW_LINE> return Response(serializer.data, status.HTTP_200_OK) <NEW_LINE> ... | Generate a list of all survey results for the authenticated user.
If there is no authenticated user, return 401 UNAUTHORIZED. | 625941dd21a7993f00bc800e |
def calculate_num_statement_pagination_pages(): <NEW_LINE> <INDENT> numPages = 1 <NEW_LINE> if len(browser.find_elements_by_css_selector('.button.act.BIBHSSubmitLink1')) == 2: <NEW_LINE> <INDENT> numPages = 2 <NEW_LINE> <DEDENT> if len(browser.find_elements_by_css_selector('.button.act.BIBHSSubmitLink2')) == 2: <NEW_LI... | Get number of paginated pages to loop through (if many years of
statemens, then the bank account will have many pages of statements
to loop through
Link 1 is not a hyperlink until navigating to another page
(because each page is implemented as a html <input> for some reason. | 625941dd5fcc89381b1e19da |
def dump_sys_data(pvm_op): <NEW_LINE> <INDENT> LOG.debug("System Network Data") <NEW_LINE> LOG.debug("LPAR Virtual IO Configuration") <NEW_LINE> __run_and_log_cmd(pvm_op, "lshwres -r virtualio --rsubtype eth --level lpar") <NEW_LINE> LOG.debug("VIOS TCP/IP Configuration") <NEW_LINE> __run_and_log_cmd(pvm_op, "lstcpip") | Will provide a dump of the system level data to the log.
:param pvm_op: It is the PowerVMOperator._operator initialized
by __init__() of PowerVMOperator. | 625941dd21bff66bcd684c69 |
def masked_nresid(self, params, **kwargs): <NEW_LINE> <INDENT> _out = self.nresid(params, **kwargs)[~self.wavmask] <NEW_LINE> return _out | Masked normalized residuals
Return the normalized residuals with masked wavelengths excluded
Args:
params (lmfit.Parameters): see params in self.model
Returns:
array: normalized residuals where self.wavmask == 1 | 625941dd656771135c3ebb8b |
def test_play_episode_episode_ends(mocker, learner, agent_step_ret): <NEW_LINE> <INDENT> learner.logger = mocker.Mock() <NEW_LINE> learner.env.step = mocker.Mock(side_effect=[([0], 0, False, None), ([0], 0, False, None), ([0], 0, False, None), ([0], 2., True, None)]) <NEW_LINE> learner.agent.step.return_value = agent_s... | test play_episode when the episode terminates | 625941dd38b623060ff0b107 |
def sage_globals(): <NEW_LINE> <INDENT> return globals() | Return the Sage namespace.
EXAMPLES::
sage: 'log' in sage_globals()
True
sage: 'MatrixSpace' in sage_globals()
True
sage: 'Permutations' in sage_globals()
True
sage: 'TheWholeUniverse' in sage_globals()
False | 625941dd60cbc95b062c685d |
def unlockUser(self, uid): <NEW_LINE> <INDENT> userdn = self.searchUserDN(uid) <NEW_LINE> r = AF().log(PLUGIN_NAME, AA.SAMBA_UNLOCK_USER, [(userdn, AT.USER)]) <NEW_LINE> s = self.l.search_s(userdn, ldap.SCOPE_BASE) <NEW_LINE> c, old = s[0] <NEW_LINE> new = old.copy() <NEW_LINE> flags = new["sambaAcctFlags"][0] <NEW_LIN... | Unlock the SAMBA user | 625941dd63d6d428bbe44809 |
def test_get_subjects_dir(monkeypatch, tmpdir): <NEW_LINE> <INDENT> subjects_dir = '/foo' <NEW_LINE> assert get_subjects_dir(subjects_dir) == subjects_dir <NEW_LINE> subjects_dir = Path('/foo') <NEW_LINE> assert get_subjects_dir(subjects_dir) == str(subjects_dir) <NEW_LINE> monkeypatch.setenv('_MNE_FAKE_HOME_DIR', str(... | Test get_subjects_dir(). | 625941ddd8ef3951e3243857 |
def sign(cookie, key): <NEW_LINE> <INDENT> digest_maker = new(key, cookie.encode(), sha1) <NEW_LINE> digest_data = digest_maker.digest() <NEW_LINE> encoded_data = encodebytes(digest_data).decode().split('\n')[0] <NEW_LINE> sanitized_data = encoded_data.replace('/', '_').replace('+', '-').replace('=', '') <NEW_LINE> ret... | This function is rewrite in python from the function 'sign' of keygrip:
function sign(data, key) {
return crypto
.createHmac(algorithm, key)
.update(data).digest(encoding)
.replace(/\/|\+|=/g, function(x) {
return ({ "/": "_", "+": "-", "=": "" })[x]
})
} | 625941dd1d351010ab855e35 |
def __init__(self, adapter, host_wrapper, instance, stg_ftsk): <NEW_LINE> <INDENT> super(Create, self).__init__('crt_vm') <NEW_LINE> self.instance = instance <NEW_LINE> self.adapter = adapter <NEW_LINE> self.host_wrapper = host_wrapper <NEW_LINE> self.stg_ftsk = stg_ftsk | Creates the Task for creating a VM.
The revert method only needs to do something for failed rebuilds.
Since the rebuild and build methods have different flows, it is
necessary to clean up the destination LPAR on fails during rebuild.
The revert method is not implemented for build because the compute
manager calls the... | 625941ddd164cc6175783068 |
@pytest_asyncio.fixture <NEW_LINE> def fake_repo_exists_false_response(): <NEW_LINE> <INDENT> return { "data": {"repository": None}, "errors": [ { "type": "NOT_FOUND", "path": ["repository"], "locations": [{"line": 7, "column": 3}], "message": ( "Could not resolve to a Repository with the name" " 'FollowTheProcess/dave... | Response snippet for the check_repo_exists GraphQL
query when the requested repo does not exist. | 625941dd2eb69b55b151cbcc |
def is_entity(e) -> bool: <NEW_LINE> <INDENT> return type(e) is Entity | Returns ``True`` if `e` is a :class:`Entity`. | 625941dda05bb46b383ecb39 |
def calc_rnn_outs_with_sort(rnn, inputs, seq_lens, init_states=None): <NEW_LINE> <INDENT> seq_len = inputs.size(1) <NEW_LINE> sorted_seq_lens, seq_sort_idx = torch.sort(seq_lens, descending=True) <NEW_LINE> _, seq_unsort_idx = torch.sort(seq_sort_idx, descending=False) <NEW_LINE> inputs = torch.index_select(inputs, 0, ... | inputs: FloatTensor, (batch, seq_len, dim_ft)
seq_lens: LongTensor, (batch,) | 625941dd3346ee7daa2b3087 |
def create(self, ): <NEW_LINE> <INDENT> import os <NEW_LINE> for folder in self.folders: <NEW_LINE> <INDENT> if not os.path.exists(folder): <NEW_LINE> <INDENT> os.mkdir(folder) <NEW_LINE> <DEDENT> <DEDENT> self.database.create() | This functions creates the folder-structure and the database | 625941dd9f2886367277aba5 |
def setup_board(): <NEW_LINE> <INDENT> board = [] <NEW_LINE> for i in range(COLUMNS): <NEW_LINE> <INDENT> board.append([]) <NEW_LINE> <DEDENT> return board | Creates the board.
Board is a list of columns, all of which are empty at the start. As the game progresses,
each column will hold the pieces starting from the bottom, i.e. columns are numbered from the bottom. | 625941dd63d6d428bbe4480a |
def getTraceIndices(self): <NEW_LINE> <INDENT> return list(self.E.keys()) | Gives a list of trace indexes | 625941dd4d74a7450ccd44de |
def parentTags(self): <NEW_LINE> <INDENT> tags = [] <NEW_LINE> node = self <NEW_LINE> while node: <NEW_LINE> <INDENT> if node is not None: <NEW_LINE> <INDENT> tags.append(node.name()) <NEW_LINE> node = node.parent() <NEW_LINE> <DEDENT> <DEDENT> return tags | Get list of names for all nodes above the current node.
:return: list of strs | 625941dda219f33f34628c80 |
def connectUserToTicket(self, location_id, ticket_id, api_key, body, **kwargs): <NEW_LINE> <INDENT> allParams = ['location_id', 'ticket_id', 'api_key', 'body'] <NEW_LINE> params = locals() <NEW_LINE> for (key, val) in params['kwargs'].iteritems(): <NEW_LINE> <INDENT> if key not in allParams: <NEW_LINE> <INDENT> raise T... | Connect a user to a ticket
Args:
location_id, int: SubtleData Location ID (required)
ticket_id, int: SubtleData Location ID (required)
api_key, str: Subtledata API Key (required)
body, NewConnection: Into used to connect the user (required)
Returns: ConnectStatus | 625941ddd8ef3951e3243858 |
def CreatePortManager(forwarded_ports, container_port): <NEW_LINE> <INDENT> port_manager_obj = PortManager(container_port) <NEW_LINE> ports_list = forwarded_ports if forwarded_ports else [] <NEW_LINE> logging.debug('setting forwarded ports %s', ports_list) <NEW_LINE> port_manager_obj.Add(ports_list, 'forwarded') <NEW_L... | Construct a PortManager object with port forwarding configured.
Args:
forwarded_ports: A string containing desired mappings from VM host ports
to docker container ports.
container_port: An integer port number for the container port.
Returns:
The PortManager instance. | 625941dd2eb69b55b151cbcd |
def write_pointer_file(pointer_file, pointer_file_path): <NEW_LINE> <INDENT> pointer_dir_path = os.path.dirname(pointer_file_path) <NEW_LINE> if not os.path.isdir(pointer_dir_path): <NEW_LINE> <INDENT> os.makedirs(pointer_dir_path) <NEW_LINE> <DEDENT> pointer_file.write(pointer_file_path, pretty_print=True) | Write the pointer file to disk. creating intermediate directories as
necessary.
:param metsrw.METSDocument pointer_file:
:param str pointer_file_path: | 625941dd442bda511e8be72e |
def floodFill(self, image, sr, sc, newColor): <NEW_LINE> <INDENT> seen = set() <NEW_LINE> color = image[sr][sc] <NEW_LINE> n, m = len(image), len(image[0]) <NEW_LINE> directions = [[-1,0],[1,0],[0,-1],[0,1]] <NEW_LINE> def dfs(x,y): <NEW_LINE> <INDENT> if (x,y) not in seen: <NEW_LINE> <INDENT> seen.add((x,y)) <NEW_LINE... | :type image: List[List[int]]
:type sr: int
:type sc: int
:type newColor: int
:rtype: List[List[int]] | 625941dd0c0af96317bb8502 |
def test_idmg_cert2(self): <NEW_LINE> <INDENT> idmg = self.clecert_2.idmg <NEW_LINE> logger.debug("IDMG %s" % idmg) <NEW_LINE> self.assertEqual('QLA8z7SaLx4ZFTyRbUdPiejojm5hUfqxcPRcwsuiVR8T', idmg) | Tester extraction du IDMG a partir de l'organization (champ O) | 625941dd1f5feb6acb0c4e65 |
def longestPalindrome(self, s): <NEW_LINE> <INDENT> oldstr=s <NEW_LINE> newstr = ['#']*(2*len(s)+1) <NEW_LINE> newstr[1::2]=s <NEW_LINE> s = "".join(newstr) <NEW_LINE> maxl = 0 <NEW_LINE> maxs = "" <NEW_LINE> for i in range(len(s)): <NEW_LINE> <INDENT> leng = 0 <NEW_LINE> for offset in range(1,len(s)): <NEW_LINE> <INDE... | :type s: str
:rtype: str | 625941dd435de62698dfdf67 |
def test_parse_mismatched_filename_and_mimetype(self): <NEW_LINE> <INDENT> request = self.request_factory.post( '/', content_type='image/png', HTTP_CONTENT_DISPOSITION='attachment; filename="file.jpg"', ) <NEW_LINE> context = {'view': self.view, 'request': request} <NEW_LINE> with self.assertRaises(exceptions.ParseErro... | Test that TypedFileUploadParser raises an exception when the specified
content-type doesn't match the filename extension in the
content-disposition header. | 625941dd07d97122c4178bac |
def startcorn(): <NEW_LINE> <INDENT> return | 开始定时任务 | 625941dddd821e528d63b4c1 |
def _CreateSpot(self): <NEW_LINE> <INDENT> placement = OrderedDict() <NEW_LINE> if not util.IsRegion(self.zone): <NEW_LINE> <INDENT> placement['AvailabilityZone'] = self.zone <NEW_LINE> <DEDENT> if self.use_dedicated_host: <NEW_LINE> <INDENT> raise errors.Resource.CreationError( 'Tenancy=host is not supported for Spot ... | Create a Spot VM instance. | 625941ddd4950a0f3b08c665 |
def update(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return super(RPMViewSet, self).update(request, *args, **kwargs) | __Method__: `PUT`, `PATCH`
__URL__: $LINK:rpms-detail:instance_pk$
__Data__:
%(WRITABLE_SERIALIZER)s
If the `dependencies` key is omitted on `PATCH` request, they will not
be changed. On `PUT` request, they will be completely removed. When a
value is specified, it completely replaces existing dependencies.
The for... | 625941ddd6c5a10208144367 |
def __parse_cli(self): <NEW_LINE> <INDENT> parser = optparse.OptionParser() <NEW_LINE> parser.add_option('-d', '--daemon', dest='daemon', default=False, action='store_true', help='Run the minion as a daemon') <NEW_LINE> parser.add_option('-c', '--config', dest='config', default='/etc/salt/minion', help='Pass in an alte... | Parse the cli input | 625941ddd486a94d0b98e461 |
def reset(self): <NEW_LINE> <INDENT> self.is_open = False <NEW_LINE> self.job = self.job_url = self.pending_batches = self.finished_batches = None | Resets the state of this job to that of a new instance. This *does
not* change anything that has happened so far at Salesforce. See
`.abort()` to cancel the currently open job. | 625941dd2c8b7c6e89b35ad9 |
def test_change_policy_order(self): <NEW_LINE> <INDENT> pass | Test case for change_policy_order
Change Policy Order # noqa: E501 | 625941dd3eb6a72ae02ec7ff |
def ng_deploy(): <NEW_LINE> <INDENT> h = Helpers <NEW_LINE> prompt = h.query_yes_no <NEW_LINE> prompt() <NEW_LINE> b = AngularBuild() <NEW_LINE> ng_build = b.ng_build <NEW_LINE> prefix_prod = b.prefix_prod <NEW_LINE> prefix_hash = b.prefix_hash <NEW_LINE> ng_path = b.ng_path <NEW_LINE> os.chdir(ng_path) <NEW_LINE> comp... | Build Angular project to Django static and organise. | 625941ddbaa26c4b54cb1437 |
def get_plugin(self, plugin_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.get_plugin_with_http_info(plugin_id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.get_plugin_with_http_info(plugin_id, **... | Get plugin detail by pluginId # noqa: E501
Get detailed information about an installed plugin by pluginId # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_plugin(plugin_id, async_req=True)
>>> result = thread.g... | 625941dd73bcbd0ca4b2c390 |
def getNodeIndexByName(nodes_d, node_name): <NEW_LINE> <INDENT> retval = -1 <NEW_LINE> for i, node_d in enumerate(nodes_d): <NEW_LINE> <INDENT> if node_d.name == node_name: <NEW_LINE> <INDENT> retval = i <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return retval | Finds the NodeDef node in list of NodeDef corresponding to
the specified name.
Args:
nodes_d: List of `NodeDef` objects to process.
node_name: node to find.
Returns:
And integer index representing the index of the node in the list
passed or -1 if not found. | 625941dd21a7993f00bc800f |
def load_posts(last_post_time=None): <NEW_LINE> <INDENT> urls = [x.strip() for x in core.config.get('posts', 'urls').split(',') if x.strip()] <NEW_LINE> raw_posts = [] <NEW_LINE> pages = [] <NEW_LINE> for url in urls: <NEW_LINE> <INDENT> if '#' in url: <NEW_LINE> <INDENT> url, pages_count = url.split('#', 1) <NEW_LINE>... | Скачивалка постов согласно конфигурации. Попутно качает список блогов, если имеется. | 625941ddd99f1b3c44c678a4 |
def generate_untied_statement(self, expression_code, final=True): <NEW_LINE> <INDENT> final_symbol = ";\n" if final else "" <NEW_LINE> return "%s%s" % (expression_code, final_symbol) | generate code for a statement which is not tied (void) | 625941dd15baa723493c4292 |
def statistics_pip(): <NEW_LINE> <INDENT> ptrn = re.compile('([^ ]+) \((.+)\)') <NEW_LINE> output = subprocess.check_output('pip list', shell=True, stderr=subprocess.STDOUT) <NEW_LINE> output = output.decode('utf-8') <NEW_LINE> lines = output.split("\n") <NEW_LINE> result = {} <NEW_LINE> for l in lines: <NEW_LINE> <IND... | Detect statistics for currently installed Python libraries. | 625941dd009cb60464c636ca |
def _return_total_fd_count(self, scan_directory): <NEW_LINE> <INDENT> scan_directory = os.path.realpath(scan_directory).strip() <NEW_LINE> path, dirs, files = scandir.walk(scan_directory).next() <NEW_LINE> return (len(files), len(dirs)) | Args:
scan_directory (str): The fully qualified pathname to examine
Returns:
(File_count, dir_count) - Tupple of Integers
This is a internal use only function.
It returns the number of files, and directories in the scan_directory.
This is the actual file system, and not cached directories.
* Primarily used ... | 625941dde5267d203edcdfb3 |
def runClosedLoop(parameters, iterations, buffer_size): <NEW_LINE> <INDENT> wavefrontParameters = parameters['Wavefront'] <NEW_LINE> sensorParameters = parameters['Sensor'] <NEW_LINE> actuatorParameters = parameters['Actuator'] <NEW_LINE> simulation_parameters = parameters['Simulation'] <NEW_LINE> wf_buffer = [] <NEW_L... | Run a closed-loop simulation
The closed-loop simulation consists of
1. generating the wave-front
2. applying the deformable mirror to the wave-front
3. a) measuring intensities
3. b) determining centroids
4. reconstructing the wave-front
5. calculate the control values for the actuators,
6. actuate the mirror
7. repea... | 625941dd63b5f9789fde7400 |
def submitBlock(self, block): <NEW_LINE> <INDENT> return self.call("submitBlock", [block]) | Submits a block to the node. When the block is valid, the node will forward it to other nodes in the network.
:param block: Hex-encoded full block (including header, interlink and body). When submitting work from getWork, remember to include the suffix.
:return: Always None. | 625941dde1aae11d1e749fd4 |
@diary_app.route('/<int:diary_id>', methods=['GET']) <NEW_LINE> @login_required <NEW_LINE> def select_diary(**kwargs): <NEW_LINE> <INDENT> db = None <NEW_LINE> try: <NEW_LINE> <INDENT> db = db_connector() <NEW_LINE> if db is None: <NEW_LINE> <INDENT> return jsonify(message="DATABASE_INIT_ERROR"), 500 <NEW_LINE> <DEDENT... | 다이어리 가져오기 | 625941ddbf627c535bc134ea |
def forward_pass_rules(X, a, b): <NEW_LINE> <INDENT> cache = (X, a, b) <NEW_LINE> result = b * (X - a) <NEW_LINE> result = 1 / (1 + np.exp(result)) <NEW_LINE> return result, cache | :param X: one input (1, 2)
:param a: (num_rules, 2)
:param b: (num_rules, 2)
:return: | 625941ddadb09d7d5db6caa8 |
def get_docstring_lines(docstring): <NEW_LINE> <INDENT> paragraphs = docstring.split('\n\n') <NEW_LINE> lines = [] <NEW_LINE> for paragraph in paragraphs: <NEW_LINE> <INDENT> inner_lines = [s.strip() for s in paragraph.splitlines()] <NEW_LINE> inner_lines = [_f for _f in inner_lines if _f] <NEW_LINE> whole_line = ' '.j... | Return all docstring paragraphs as single lines.
Leading and trailing whitespace is also removed.
:param docstring: (str) a docstring
:return: A list of strings, one string per docstring paragraph. | 625941dd15fb5d323cde0e2e |
def vs (G,rho,phi): <NEW_LINE> <INDENT> nvol=phi.size <NEW_LINE> vs = np.zeros(nvol) <NEW_LINE> tmp = np.zeros(nvol) <NEW_LINE> for i in range (nvol): <NEW_LINE> <INDENT> vs[i] = np.power((G[i]/rho[i]),0.5) <NEW_LINE> <DEDENT> return vs | Shear velocity,
output is a vector[n]
rho[n]: input vecotr with density
G[n]: input vector with Shear modulus
phi[n]: input vector with porosity | 625941dde8904600ed9f224b |
def read_labels_file(file_path: str) -> np.array: <NEW_LINE> <INDENT> with open(file_path, 'r') as f: <NEW_LINE> <INDENT> f.readline() <NEW_LINE> vals = f.readlines() <NEW_LINE> <DEDENT> data = np.empty(shape=(len(vals), 1), dtype=np.int) <NEW_LINE> for val in vals: <NEW_LINE> <INDENT> val_split = val.split(",") <NEW_L... | Reads the labels from the csv file and returns it as an array
:param file_path: path to the csv file containing the labels to the files in the dataset
:return: labels as a numpy array | 625941dd57b8e32f524837b7 |
def readFile(fName): <NEW_LINE> <INDENT> f = open(fName, 'r') <NEW_LINE> aList = f.read().splitlines() <NEW_LINE> f.close() <NEW_LINE> return aList | Parameters: fName
Purpose: reads file and sorts into list
returns: a list of info | 625941ddcad5886f8bd272f3 |
def get_absolute_rmse(self): <NEW_LINE> <INDENT> result = dict() <NEW_LINE> for model in self._models: <NEW_LINE> <INDENT> result[model.get_method()] = model.get_absolute_rmse() <NEW_LINE> <DEDENT> return result | Example return format: {'knn': 300, 'rf': 340} | 625941dd097d151d1a223172 |
def _PerfdiagExceptionHandler(cls, e): <NEW_LINE> <INDENT> cls.logger.error(str(e)) | Simple exception handler to allow post-completion status. | 625941dd4428ac0f6e5bab0e |
def get_product(self, product_id): <NEW_LINE> <INDENT> product = self.persistance_manager.get_product_by_id(product_id) <NEW_LINE> if not product: <NEW_LINE> <INDENT> raise ProductNotFoundError('product with id "{}" was not found'.format(product_id)) <NEW_LINE> <DEDENT> product.pop('_id') <NEW_LINE> name = self.product... | Queries for product from data store.
Args:
self(case_study.persistance_manager.PersistanceManager)
product_id(int)
Returns:
dict: see ../schemas/product.json
Raises:
case_study.errors.ProductNotFoundError | 625941dd2ae34c7f2600d44b |
def __init__(self, name, m=3, inventory=15, holding_cost=0.5, shortage_cost=1.0, base_stock=15, strategy='base-stock-policy'): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._inventory = inventory <NEW_LINE> self._backorder = 0 <NEW_LINE> self._OO = 0 <NEW_LINE> self._demand = 0 <NEW_LINE> self._incoming = 0 <NE... | Args:
name (str): name of the stage
holding_cost (float): cost for holding one item per week
shortage_cost (float): cost for one backordered item per week | 625941dd50812a4eaa59c639 |
def _load_global_data(self): <NEW_LINE> <INDENT> jjb_config = self.registry.jjb_config <NEW_LINE> if not self.authToken: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.authToken = jjb_config.get_plugin_config('hipchat', 'authtoken') <NEW_LINE> if self.authToken == '': <NEW_LINE> <INDENT> raise jenkins_jobs.errors.Je... | Load data from the global config object.
This is done lazily to avoid looking up the '[hipchat]' section
unless actually required. | 625941dd8c0ade5d55d3ecd8 |
def stitch(self, archive_streams, output_filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with self.storage_pool.get() as storage_backend: <NEW_LINE> <INDENT> for stream in archive_streams[:1]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> storage_backend.path(stream.filename) <NEW_LINE> storage_pool = self.stora... | Stitch audio streams into single audio stream.
Note that stitching requires archive streams to be
available on the local filesystem for stitching.
If the storage_pool provided is not accessible on
the local filesystem, all streams will be downloaded
prior to stitching.
Args:
archive_streams: list of ArchiveStream... | 625941dd099cdd3c635f0f74 |
def node_insert_before(node, sibling): <NEW_LINE> <INDENT> return _lib.cmark_node_insert_before(node, sibling) | Insert sibling before node.
Returns
-------
int
``1`` on success, ``0`` on failure. | 625941dddc8b845886cb5851 |
def _compute_next_date(self, cr, uid, ids, field, arg, context=None): <NEW_LINE> <INDENT> if isinstance(ids, (int, long)): <NEW_LINE> <INDENT> ids = [ids] <NEW_LINE> <DEDENT> res = {} <NEW_LINE> for frequence in self.browse(cr, uid, ids): <NEW_LINE> <INDENT> if frequence.calculated_end_date and datetime.strptime(freque... | Compute the next date matching with the parameter of the frequency | 625941dd287bf620b61d3d7c |
def fit(self, x, y): <NEW_LINE> <INDENT> for i in range(self.num_tree): <NEW_LINE> <INDENT> bs_x, bs_y = self._get_bootstrap_sample(x, y) <NEW_LINE> if self.is_classification: <NEW_LINE> <INDENT> dt = self._fit_classification(bs_x, bs_y, feature_names, par_node={}, depth=0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>... | :param x:
:param y:
:return: | 625941dd004d5f362079a64c |
def convert_moveset(sid, moveset): <NEW_LINE> <INDENT> rows = dict() <NEW_LINE> rows[schema.movesets] = [dict(id=sid, gender=moveset.gender, item=moveset.item, level=moveset.level, happiness=moveset.happiness)] <NEW_LINE> rows[schema.moveslots] = [dict(sid=sid, idx=i, move=move) for i, move in enumerate(moveset.moves)]... | Converts a Moveset DTO to rows of values for insert expressions
Args:
sid (str) : the SID of the moveset
moveset (dto.Moveset) : the moveset to convert. Is assumed to be
sanitized.
Returns:
:obj:`dict` of :obj:`sa.Table` to :obj:`list` of :obj:`tuple` :
the corresponding insert rows. The k... | 625941dd8e7ae83300e4b2e8 |
def __init__(self, path): <NEW_LINE> <INDENT> if not os.path.isdir(path): <NEW_LINE> <INDENT> AbstractTree.__init__(self, os.path.basename(path), [], os.path.getsize(path)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> subtrees = [] <NEW_LINE> for filename in os.listdir(path): <NEW_LINE> <INDENT> subitem = os.path.join... | Store the file tree structure contained in the given file or folder.
Precondition: <path> is a valid path for this computer.
@type self: FileSystemTree
@type path: str
@rtype: None | 625941dd6fece00bbac2da5c |
def node_type(self, graph_id, node_id): <NEW_LINE> <INDENT> if graph_id not in self.graphs(): <NEW_LINE> <INDENT> raise HierarchyError( "Graph '{}' is not defined in the hierarchy!".format(graph_id) ) <NEW_LINE> <DEDENT> if node_id not in self.get_graph(graph_id).nodes(): <NEW_LINE> <INDENT> raise HierarchyError( "Grap... | Get a list of the immediate types of a node. | 625941dd6e29344779a6292a |
def prints(*a, **kw): <NEW_LINE> <INDENT> stream = kw.get('file', sys.stdout) <NEW_LINE> if stream is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> sep, end = kw.get('sep'), kw.get('end') <NEW_LINE> if sep is None: <NEW_LINE> <INDENT> sep = ' ' <NEW_LINE> <DEDENT> if end is None: <NEW_LINE> <INDENT> end = '\n' <... | Print either unicode or bytes to either binary or text mode streams | 625941dda17c0f6771cbe36a |
def test_knn(): <NEW_LINE> <INDENT> test_path="D:/knn/test" <NEW_LINE> picture_list=[] <NEW_LINE> collect_all_filenames(test_path,".",picture_list) <NEW_LINE> knn=MyKNN() <NEW_LINE> total_num=len(picture_list) <NEW_LINE> right_num=0 <NEW_LINE> wrong_num=0 <NEW_LINE> fail_num=0 <NEW_LINE> for pic in picture_list: <NEW_L... | 测试knn
在test文件夹下面有一些人工归类的图片 这些图片并未放置在calssified文件夹下 作为测试所用
:return: | 625941ddfb3f5b602dac39b1 |
def md5(str): <NEW_LINE> <INDENT> return hash.md5(str).hexdigest() | 计算字符串md5
:param str: 输入病例字符串
:return: str的md5结果 | 625941dd56b00c62f0f14976 |
def circ_mean(matrix, weights=None, axis=None, low=0, high=pi*2, normalize=False): <NEW_LINE> <INDENT> idx = numpy.nonzero(weights!=0.0)[0] <NEW_LINE> if isinstance(weights,numpy.ndarray): <NEW_LINE> <INDENT> assert matrix.shape == weights.shape <NEW_LINE> <DEDENT> if axis == None: <NEW_LINE> <INDENT> axis == 0 <NEW_LI... | Circular mean of matrix. Weighted if weights are not none.
Mean will be computed along axis axis.
Parameters
----------
matrix : ndarray
Matrix of data for which the compute the circular mean.
weights : ndarray, optional
If not none, matrix of the same size as matrix. It will be used as weight... | 625941dde64d504609d74b5a |
def referencingObjectsAndAttrs(self): <NEW_LINE> <INDENT> referencingObjectsAndAttrs = [] <NEW_LINE> selfSqlObjRef = self.sqlObjRef() <NEW_LINE> for backObjRefAttr in self.klass().backObjRefAttrs(): <NEW_LINE> <INDENT> objects = self.store().fetchObjectsOfClass(backObjRefAttr.klass(), **self.referencingObjectsAndAttrsF... | Get all referencing attributes and objects.
Returns a list of tuples of (object, attr) for all objects that have
ObjRefAttrs that reference this object. | 625941dd9c8ee82313fbba90 |
def data_writer(input_dir, gt_dir, output_file): <NEW_LINE> <INDENT> file_paths, gt_paths = data_reader(input_dir, gt_dir) <NEW_LINE> output_dir = os.path.dirname(output_file) <NEW_LINE> try: <NEW_LINE> <INDENT> os.makedirs(output_dir) <NEW_LINE> <DEDENT> except os.error as e: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDE... | Write data to tfrecords
| 625941dd4a966d76dd55132d |
def __init__(self, name, device, model, unique_id, retries): <NEW_LINE> <INDENT> super().__init__(name, device, model, unique_id, retries) <NEW_LINE> self._device_features = FEATURE_FLAGS_FAN_LESHOW_SS4 <NEW_LINE> self._available_attributes = AVAILABLE_ATTRIBUTES_FAN_LESHOW_SS4 <NEW_LINE> self._percentage = None <NEW_L... | Initialize the fan entity. | 625941dd0383005118ecf8fc |
def url(self, key): <NEW_LINE> <INDENT> if not self._baseurl: <NEW_LINE> <INDENT> raise BadRequest('PlexClient object missing baseurl.') <NEW_LINE> <DEDENT> if self._token: <NEW_LINE> <INDENT> delim = '&' if '?' in key else '?' <NEW_LINE> return '%s%s%sX-Plex-Token=%s' % (self._baseurl, key, delim, self._token) <NEW_LI... | Build a URL string with proper token argument. | 625941dd10dbd63aa1bd2ebd |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, EmailCommseqEmailResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941dd30bbd722463cc0e4 |
def assert_png_data(self, content): <NEW_LINE> <INDENT> image = Image.open(BytesIO(content)) <NEW_LINE> self.assertEqual(image.format, 'PNG') | Check whether data is PNG image | 625941ddb5575c28eb68e31d |
def validate_file(file: str, schema: str, fuzz: bool=False, backend: Backend=None, output: Dict=None) -> bool: <NEW_LINE> <INDENT> if backend is None: <NEW_LINE> <INDENT> backend, name, baseurl = resolve_path_or_url(file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = file <NEW_LINE> <DEDENT> with backend.read_co... | validate a spaceTx formatted file with a given schema.
Accepts local filepaths or files hosted at http links.
Parameters
----------
file : str
path or URL to a target json object to be validated against the schema passed
schema : str
resource path to the schema
backend : slicedimage.backends._base.Backend
... | 625941dda934411ee37519af |
def ms_to_timestamp(ms, mssep=","): <NEW_LINE> <INDENT> if ms < 0: ms = 0 <NEW_LINE> if ms > MAX_REPRESENTABLE_TIME: ms = MAX_REPRESENTABLE_TIME <NEW_LINE> h, m, s, ms = ms_to_times(ms) <NEW_LINE> return "%02d:%02d:%02d%s%03d" % (h, m, s, mssep, ms) | Convert ms to 'HH:MM:SS,mmm' | 625941dd6e29344779a6292b |
def test_to_bytes_func(self): <NEW_LINE> <INDENT> dynamixel_id = 1 <NEW_LINE> data = (0x02, 0x2b, 0x01) <NEW_LINE> raw_packet = pk.Packet(dynamixel_id, data) <NEW_LINE> expected_str = b'\xff\xff\x01\x04\x02\x2b\x01\xcc' <NEW_LINE> self.assertEqual(raw_packet.to_bytes(), expected_str) | Check the "to_bytes()" function.
Based on the Dynamixel user guide, example 2: "Reading the internal
temperature of the Dynamixel actuator with an ID of 1" (p.20). | 625941dde76e3b2f99f3ab22 |
def triTraj(wps, data, traj_type='poly'): <NEW_LINE> <INDENT> coords, l, org, scale = data['coords'], data['l'], data['org'], data['scale'] <NEW_LINE> a, b = wps[-2, :], wps[-1, :] <NEW_LINE> angle = np.arctan2(b[1]-a[1], b[0]-a[0]) <NEW_LINE> c = np.array(((np.cos(angle), np.sin(angle)))) <NEW_LINE> wps = np.vstack((w... | inputs :
-> wps, numpy array x|y
return :
-> wps_traj, traj_def | 625941dd2ae34c7f2600d44c |
def _update_extra_inputs(self, p): <NEW_LINE> <INDENT> if p.extra_input: <NEW_LINE> <INDENT> logger.debug("[{}] Found extra input: {}".format( p.template, p.extra_input)) <NEW_LINE> if p.extra_input == "default": <NEW_LINE> <INDENT> if p.input_type in self.main_raw_inputs: <NEW_LINE> <INDENT> logger.error(colored_print... | Given a process, this method updates the
:attr:`~Process.extra_inputs` attribute with the corresponding extra
inputs of that process
Parameters
----------
p : flowcraft.Process.Process | 625941dd24f1403a92600e7f |
def tearDown(self): <NEW_LINE> <INDENT> self.db_tear_down() <NEW_LINE> super(ResultTests, self).tearDown() | Reset test attributes | 625941ddd6c5a10208144368 |
def __init__( self, *, last_update_date_time: datetime.datetime, task_name: str, status: Union[str, "State"], results: Optional["EntitiesResult"] = None, **kwargs ): <NEW_LINE> <INDENT> super(TasksStateTasksEntityRecognitionTasksItem, self).__init__(last_update_date_time=last_update_date_time, task_name=task_name, stat... | :keyword results:
:paramtype results: ~azure.ai.textanalytics.v3_2_preview_2.models.EntitiesResult
:keyword last_update_date_time: Required.
:paramtype last_update_date_time: ~datetime.datetime
:keyword task_name: Required.
:paramtype task_name: str
:keyword status: Required. Possible values include: "notStarted", "run... | 625941dd63f4b57ef000142c |
def new_game(self, board_size, ship_size): <NEW_LINE> <INDENT> self.__board_size = board_size <NEW_LINE> self.__max_size_ship = ship_size <NEW_LINE> self.human_step = False <NEW_LINE> self.game_started = False <NEW_LINE> if self.c_board and self.h_board: <NEW_LINE> <INDENT> self.c_board.clear() <NEW_LINE> slef.h_board.... | Метод инициализации новой сессии игры. | 625941dda79ad161976cc460 |
def handle_new(self, instrument_class, new_id, *args, **kwargs): <NEW_LINE> <INDENT> for key, value in self._shared_attrs.items(): <NEW_LINE> <INDENT> if key in instrument_class.shared_kwargs: <NEW_LINE> <INDENT> kwargs[key] = value <NEW_LINE> <DEDENT> <DEDENT> ins = instrument_class(*args, server_name=None, **kwargs) ... | Add a new instrument to the server.
After the initial load, the instrument is referred to by its ID.
Args:
instrument_class (class): The type of instrument to construct.
new_id (int): The ID by which this instrument will be known on the
server.
*args: positional arguments to the instrument const... | 625941dde64d504609d74b5b |
def permCount(n,k): <NEW_LINE> <INDENT> return binom(n,k) * reduce(lambda a,b:a*b, range(1,k+1), 1) | Calculate P(n,k) = n!/(n-k)!, the number of permutations over n objects, taking
k of them at a time. | 625941dd004d5f362079a64d |
def __init__(self, hidden_dims, input_dim=3*32*32, num_classes=10, dropout=0, use_batchnorm=False, reg=0.0, weight_scale=1e-2, dtype=np.float32, seed=None): <NEW_LINE> <INDENT> self.use_batchnorm = use_batchnorm <NEW_LINE> self.use_dropout = dropout > 0 <NEW_LINE> self.reg = reg <NEW_LINE> self.num_layers = 1 + len(hid... | Initialize a new FullyConnectedNet.
Inputs:
- hidden_dims: A list of integers giving the size of each hidden layer.
- input_dim: An integer giving the size of the input.
- num_classes: An integer giving the number of classes to classify.
- dropout: Scalar between 0 and 1 giving dropout strength. If dropout=0 then
th... | 625941dd460517430c394499 |
def search_my_print_defaults_tool(self, search_paths=None): <NEW_LINE> <INDENT> if not search_paths: <NEW_LINE> <INDENT> search_paths = [] <NEW_LINE> <DEDENT> default_paths = [my_login_config_path()] <NEW_LINE> if search_paths: <NEW_LINE> <INDENT> default_paths.extend(search_paths) <NEW_LINE> <DEDENT> try: <NEW_LINE> <... | Search for the tool my_print_defaults.
| 625941dd26238365f5f0f18d |
def test_duplicate_image_upload(self): <NEW_LINE> <INDENT> path = "/v1/images" <NEW_LINE> response, content = self.http.request(path, 'GET') <NEW_LINE> self.assertEqual(200, response.status) <NEW_LINE> self.assertEqual('{"images": []}', content) <NEW_LINE> headers = {'Content-Type': 'application/octet-stream', 'X-Image... | Upload initial image, then attempt to upload duplicate image | 625941ddbe8e80087fb20f5a |
def cut_directions(directions, direct_num, minutes_interval, tracking_interval): <NEW_LINE> <INDENT> tracking_interval /= 60 <NEW_LINE> tracking_interval /= minutes_interval <NEW_LINE> cutted_directions = [] <NEW_LINE> if direct_num > len(directions): <NEW_LINE> <INDENT> direct_num = len(directions) <NEW_LINE> <DEDENT>... | cut number of directions while testing | 625941dd7c178a314d6ef77f |
def makeProg(self,numTab,var): <NEW_LINE> <INDENT> tab = " " <NEW_LINE> indent = "" <NEW_LINE> for i in xrange(numTab): <NEW_LINE> <INDENT> indent+=tab <NEW_LINE> <DEDENT> prog = self.down[0].makeProg(numTab,var+"0") <NEW_LINE> prog += "x"+var+"0.sort(reverse=True)\n"+indent <NEW_LINE> prog+= "x"+var+ "= x"+var+"0[:... | This function generates the code for this node for the external verification | 625941dd627d3e7fe0d6916c |
def test_forward_maximum(): <NEW_LINE> <INDENT> def check_maximum(lh_shape, rh_shape, dtype): <NEW_LINE> <INDENT> tf.reset_default_graph() <NEW_LINE> lh_data = np.random.uniform(size=lh_shape).astype(dtype) <NEW_LINE> rh_data = np.random.uniform(size=rh_shape).astype(dtype) <NEW_LINE> with tf.Graph().as_default(): <NEW... | test Op Maximum | 625941ddd58c6744b4257f7a |
def __zoomValueChanged(self, value): <NEW_LINE> <INDENT> self.currentBrowser().setZoomValue(value) | Private slot to handle value changes of the zoom widget.
@param value zoom value (integer) | 625941dd3539df3088e2e666 |
def count(self, sub, start=0, end=sys.maxsize): <NEW_LINE> <INDENT> sub_str = str(sub) <NEW_LINE> len_self, len_sub_str = self._length, len(sub_str) <NEW_LINE> if set(sub_str) != set(self._character): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if start is None: <NEW_LINE> <INDENT> start = 0 <NEW_LINE> <DEDENT> if... | Return a non-overlapping count, like that of a python string.
This behaves like the python string (and Seq object) method of the
same name, which does a non-overlapping count!
For an overlapping search use the newer count_overlap() method.
Returns an integer, the number of occurrences of substring
argument sub in th... | 625941dde8904600ed9f224c |
def load(self): <NEW_LINE> <INDENT> return True | Loads the credentials from their source & sets them on the object.
Subclasses should implement this method (by reading from disk, the
environment, the network or wherever), returning ``True`` if they were
found & loaded.
If not found, this method should return ``False``, indictating that the
``CredentialResolver`` sh... | 625941dda8370b7717052bb9 |
def calc_kappa4Theory(T_K, PCO2, a_H2CO3s): <NEW_LINE> <INDENT> T_C = KtoC(T_K) <NEW_LINE> K_2 = calc_K_2(T_K) <NEW_LINE> K_c = calc_K_c(T_K) <NEW_LINE> kappa1 = calc_kappa1(T_K) <NEW_LINE> kappa2 = calc_kappa2(T_K) <NEW_LINE> kappa3 = calc_kappa3(T_K) <NEW_LINE> a_Heq = activityHFromPCO2(PCO2, T_C=T_C) <NEW_LINE> kapp... | Calculates kappa4 in the PWP equation using the theoretical relation for kappa4 from Plummer, Wigley, and Parkhurst (1978) Equation 25 (as described in Dreybrodt [1988] equation 6.22b). In this case, a_H in the equation for kappa4 is the equilibrium surface value for the given carbonic acid concentration, as specified... | 625941ddd7e4931a7ee9e23a |
def send(request, response): <NEW_LINE> <INDENT> sse.publish({"message": response['text'].decode('utf-8')}, type='bot') | Sender function | 625941ddb57a9660fec33ba4 |
def test_next(self): <NEW_LINE> <INDENT> self._set_session_vars(**{NEXT_SESSION_KEY: '/next'}) <NEW_LINE> response = self._mock_connection_get() <NEW_LINE> self.assertRedirectsNoFollow(response, '/next') <NEW_LINE> self.assertEqual(HealthVaultUser.objects.count(), 1) <NEW_LINE> hvuser = HealthVaultUser.objects.get() <N... | Complete view should redirect to specified URL, if available. | 625941dd009cb60464c636cb |
def find_orient(img_gray, prev_orient): <NEW_LINE> <INDENT> max_val = 0 <NEW_LINE> orient = 0 <NEW_LINE> ret,img_thresh = cv2.threshold(img_gray,THRESHOLD,255,cv2.THRESH_BINARY) <NEW_LINE> temp = np.zeros_like(img_thresh) <NEW_LINE> rect = np.zeros_like(img_thresh) <NEW_LINE> rows,cols = temp.shape <NEW_LINE> cv2.recta... | Computes the orientation of the bee in given frame
:param img_gray: grayscale crooped image of the bee
:param prev_orient: orientation in the previous frame
:returns: orientation of the bee (degrees) and rectangular mask to filter bee from original image | 625941ddec188e330fd5aab5 |
def remove_fc(state_dict): <NEW_LINE> <INDENT> for key in list(state_dict.keys()): <NEW_LINE> <INDENT> if key.startswith('fc.'): <NEW_LINE> <INDENT> del state_dict[key] <NEW_LINE> <DEDENT> <DEDENT> return state_dict | Remove the fc layer parameters from state_dict. | 625941dd7b180e01f3dc4b13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.