content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from sets import Set def uniformCostSearch(problem): """Search the node of least total cost first.""" "*** YOUR CODE HERE ***" startState = problem.getStartState() if problem.isGoalState(startState): return [] # Each element in the fringe stores the state and the cost to reach it. frin...
fd338afde09f48f73e30aace7e926c26adc2e977
30,998
def create_new_dataset(data, num_schedules): """ creates a dataset where each row is the twenty timesteps of a schedule alongside the chosen task creates a schedule array that tracks when each schedules starts and ends :return: """ X = [] Y = [] schedule_array = [] for i in range(0, ...
35f6bbc5b5e9968e7890af17ae77a6c3cbd5d0a5
31,001
def init_language(): """ 기본 언어 설정. 없으면 영어. 글-로벌 """ yaml_data = read_yaml("config.yaml", '!default') if yaml_data: lang = yaml_data.get('LANGUAGE') return lang + "\\" if lang else "" else: return ""
03ee90ead37060d843ebc71b6d857a719a6d9c7b
31,003
def __clean_term__(term, convert_letter = True, w_space = True, is_url=True): """ Prepares an input term to be queried in a url Input ---------------------------------------------------------------- term : str term to clean convert_letter : bool (default True) ...
e07f0f828227176665e85532b0f755084d0b294f
31,005
from typing import Counter def merge_vocabs(vocabs, vocab_size=None): """ Merge individual vocabularies (assumed to be generated from disjoint documents) into a larger vocabulary. Args: vocabs: `torchtext.vocab.Vocab` vocabularies to be merged vocab_size: `int` the final vocabulary si...
3926e4717317ca9fd897b98d2db28bfdced74487
31,006
def find_local_minimum(data, threshold=None): """ Find local minimum in data. :param data: input data. :param threshold: (optional) local minimum whose value is not less than threshold won't be selected. :return: a 1-D array. """ local_min_idx = argrelextrema(data, np.less) local_min_idx...
5b240627d1f5d1203e0ab592ec29be3ab71ad967
31,007
def mouse_annotations(mouse_file): """ Updates and get JSON file for mouse annotations """ zipped_rows = get_rows_from_file(mouse_file, '\n') # Too many processes causes the http requests causes the remote to respond with error pool = mp.Pool(processes=1) annotations = pool.map(mouse_single_...
ddd89a7ea9a02a6aa646691c36968d66eaa93ff3
31,008
def thomsen_parameters(vp, vs, rho, lb, dz): """ Liner, C, and T Fei (2006). Layer-induced seismic anisotropy from full-wave sonic logs: Theory, application, and validation. Geophysics 71 (6), p D183–D190. DOI:10.1190/1.2356997 Args: vp (ndarray): P-wave interval velocity. vs (ndarr...
9fb2418608d154deb2bf362a5966e32d420d9c74
31,009
def replace_last(source_string, replace_what, replace_with): """ Function that replaces the last ocurrence of a string in a word :param source_string: the source string :type source_string: str :param replace_what: the substring to be replaced :type replace_what: str :param ...
6fbc36824b960fb125b722101f21b5de732194c5
31,010
def unescape(text): """Unescapes text >>> unescape(u'abc') u'abc' >>> unescape(u'\\abc') u'abc' >>> unescape(u'\\\\abc') u'\\abc' """ # Note: We can ditch this and do it in tokenizing if tokenizing # returned typed tokens rather than a list of strings. new_text = [] esc...
7db9fa5bb786ea5c1f988ee26eed07abe66a2942
31,011
def patched_novoed_tasks(mocker): """Patched novoed-related tasks""" return mocker.patch("applications.models.novoed_tasks")
06d2e825bc9407e8e8bdd27170d457f046f8193c
31,012
def cart2spherical(x, y, z): """ Converts to spherical coordinates :param x: x-component of the vector :param y: y-component of the vector :param z: z-component of the vector :return: tuple with (r, phi, theta)-coordinates """ vectors = np.array([x, y, z]) r = np.sqrt(np.sum(vectors...
702b0fa13f21cbee1fc7fe63219ef1bc8d398269
31,013
def get_JD(year=None, month=None, day=None, hour=None, min=None, sec=None, string=None, format='yyyy-mm-dd hh:mm:ss', rtn='jd'): """compute the current Julian Date based on the given time input :param year: given year between 1901 and 2099 :param month: month 1-12 :param day: days :param...
4350177350d731ea2c98d84f5f4cb56d5c67fb07
31,014
def get_final_feature(feature_1, feature_2, metric_list): """Get the difference between two features. :param feature_1: the first feature :type feature_1: numpy array :param feature_2: the second feature :type feature_2: numpy array :param metric_list: the metrics which will be used to comp...
a67d7da73a10393f119fa549991c277004b25beb
31,015
def removeZeros(infile, outfile, prop=0.5, genecols=2): """Remove lines from `infile' in which the proportion of zeros is equal to or higher than `prop'. `genecols' is the number of columns containing gene identifiers at the beginning of each row. Writes filtered lines to `outfile'.""" nin = 0 nout = 0 ...
43feba21513be4a8292c08918e16b3e34a73c341
31,016
def cuboid(origin, bounds, direction, color=Vec4(1), normal_as_color=NAC): """ Return GeomNode of the cuboid, Args: origin: center of the cuboid bounds: 3-Tuple of length, width and height direction: normal vector of the up face color: Vec4 normal_as_color: whether t...
78578db28a0fb0e18a36f2f8de4a3bd3fc69f3ac
31,017
def fireball_get_HS_dat(cd, fname='HS.dat'): """ """ f = open(cd+'/'+fname, "r") nlines = int(f.readline()) #print(nlines) s = f.readlines() assert nlines==len(s) i2aoao = np.zeros((nlines,4), dtype=int) i2h = np.zeros((nlines)) i2s = np.zeros((nlines)) i2x = np.zeros((nlines,3)) for i,...
fd63b0def17f80c88b150087f749aa421aa45d48
31,018
def create(db: Session, request: UsersRequestSchema): """ Creates a new user. :return: UserModel """ user = UserModel( username=request.username, group=request.group ) db.add(user) db.commit() db.refresh(user) return user
f43a220fdfb654bc554f970ad01196ad5b754920
31,019
def format_timedelta(time): """Format a timedelta for use in a columnar format. This just tweaks stuff like ``'3 days, 9:00:00'`` to line up with ``'3 days, 10:00:00'`` """ result = str(strip_microseconds(time)) parts = result.split() if len(parts) == 3 and len(parts[-1]) == 7: retu...
1913b4492bfee4541dc7266dd72989d2b38b4dc4
31,020
def describe_protein(s1, s2, codon_table=1): """ """ codons = util.codon_table_string(codon_table) description = ProteinAllele() s1_swig = util.swig_str(s1) s2_swig = util.swig_str(s2) codons_swig = util.swig_str(codons) extracted = extractor.extract(s1_swig[0], s1_swig[1], s2...
12da2ca688b35324fadc2d897fa076daeb14b91f
31,021
from typing import Any from typing import Mapping import logging import itertools import inspect def _convert_gradient_function( proto: tf.compat.v1.NodeDef, graph: Any, library: Mapping[str, _LibraryFunction], ) -> Mapping[str, _LibraryFunction]: """Convert a custom_gradient function.""" op = graph.a...
0cdfbe6c6a302e3b454be77e1cd03a0419dcd64f
31,022
def generate_warp_function(chromatic_consts=None, drift=None, n_dim=3, verbose=True): """Function to generate a spot translating function""" ## check inputs if chromatic_consts is None: _ch_consts = np.zeros([n_dim,...
38ebf2303494017f2e401a034fa800d04627a790
31,023
import pdb def Dfunc(sign,k,N,dphi,si,sd,xF=[],F=[],beta=np.pi/2): """ Parameters ---------- sign : int +1 | -1 k : wave number N : wedge parameter dphi : phi-phi0 or phi+phi0 si : distance source-D sd : distance D-observation beta : skew incidence angle xF : arra...
6e85c3f708d6333307fc80c82910361c09dc892c
31,024
def deprecated(since=nicos_version, comment=''): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. The parameter ``since`` should contain the NICOS version number on which the deprecation starts. The ``co...
04b77c3daf7aa92cab8dfdaf8fc2afca6eda0d24
31,025
import resource def create_rlimits(): """ Create a list of resource limits for our jailed processes. """ rlimits = [] # Allow a small number of subprocess and threads. One limit controls both, # and at least OpenBLAS (imported by numpy) requires threads. nproc = LIMITS["NPROC"] if np...
ac8fbfeeae471068ef75cc80520a016902f5d887
31,026
def save_processed_image_uuid(username, uuid): """Updates existing user by adding the uuid of the processed image :param username: user email as string type which serves as user id :param uuid: UUID4 of processed image :returns: adds uuid of processed image to mongo database """ try:...
f1a063d417a66c5436efe65bbb024478d11ec05c
31,028
def web_request(): """Mock web request for views testing.""" return web_request_func()
a8327e14fd793181f4b3e669d69e7ccc8edd8213
31,029
def _NormalizeDiscoveryUrls(discovery_url): """Expands a few abbreviations into full discovery urls.""" if discovery_url.startswith('http'): return [discovery_url] elif '.' not in discovery_url: raise ValueError('Unrecognized value "%s" for discovery url') api_name, _, api_version = disc...
f361d01006a6e7f7487e06db375ae703ffde0021
31,030
def computeAirmass(dec, ha, lat=config['observatory']['latitude'], correct=[75., 10.]): """Calculates the airmass for a given declination and HA (in degrees). By default, assumes that the latitude of the observation is the one set in the configuration file. If correct is defined, abs(HA)...
df9513e23932fe646bf13df85283380eff5bb871
31,031
def metric_op(metric): """Converts Keras metrics into a metric op tuple. NOTE: If this method is called in for loop, the runtime is O(n^2). However the number of eval metrics at any given time should be small enough that this does not affect performance. Any impact is only during graph construction time, and...
52ad2f5092aa5203e1e850eae628d8e804447847
31,032
def get_geostore(geostore_id, format='esri'): """ make request to geostore microservice for user given geostore ID """ config = { 'uri': '/geostore/{}?format={}'.format(geostore_id, format), 'method': 'GET', } return request_to_microservice(config)
1e5ebdd04f62930de40942efd4894d79d7a7cfd4
31,033
def srmi(df, n=9): """ SRMIMI修正指标 srmi(9) 如果收盘价>N日前的收盘价,SRMI就等于(收盘价-N日前的收盘价)/收盘价 如果收盘价<N日前的收盘价,SRMI就等于(收盘价-N日签的收盘价)/N日前的收盘价 如果收盘价=N日前的收盘价,SRMI就等于0 """ _srmi = pd.DataFrame() _srmi['date'] = df.date _m = pd.DataFrame() _m['close'] = df.close _m['cp'] = df.close.shift(n) _m...
28bd0e715b34707b742e13230d93a4a104fd80ba
31,034
def define_pairs(grid: 'np.ndarray'): """Take a sequence grid and return all pairs of neighbours. Returns a list of dictionaries containing the indices of the pairs (neighbouring only), and the corresponding sequence numbers (corresponding to the image array) """ nx, ny = grid.shape footpr...
6c4aa1fcc22641f07054a3bcfe11a7edc21a3c56
31,035
def _length_normalization(length_norm_power, length, dtype=tf.float32): """Returns length normalization factor.""" return tf.pow(((5. + tf.cast(length, dtype)) / 6.), length_norm_power)
d012f3c5c24165e7f529ec55976f969edbcca6e6
31,036
def unregistercls(self, schemacls=None, data_types=None): """Unregister schema class or associated data_types. :param type schemacls: sub class of Schema. :param list data_types: data_types to unregister. """ return _REGISTRY.unregistercls(schemacls=schemacls, data_types=data_types)
50744b0f9fbf96b5f1e0213c216e4c3e6419f0d0
31,037
def get_relation_mapper() -> RelationMapper: """Get the relation mapper. Create and load if necessary.""" global _relation_mapper if _relation_mapper is not None: return _relation_mapper path = mapping_root.joinpath("reltoid") if not path.is_file(): create_mapping() _relation_ma...
5a487c37dbca6b197b781ac8cab3b1f91bcbaf3e
31,038
def griffin_lim(stftm_matrix, max_iter=100): """"Iterative method to 'build' phases for magnitudes.""" stft_matrix = np.random.random(stftm_matrix.shape) y = librosa.core.istft(stft_matrix, hop_size, window_size) for i in range(max_iter): stft_matrix = librosa.core.stft(y, fft_size, hop_size, wi...
ada8e7442d1d2c8ed1224d50be42b274fe1229fe
31,039
from typing import Union from typing import Optional def parse_subtitle_stream_id(input_file: str, input_sid: Union[int, str, None]) -> Optional[int]: """Translate the CLI `-s` parameter into a stream index suitable for subtitle_options().""" subtitle_streams = tuple(list_subtitle_streams(input_file)) ext...
93d62eae4e3080eab7d94bb4fd9a5ed3aabbce0e
31,041
from typing import Optional from typing import Iterable from typing import Dict import json def routes_to_geojson( feed: "Feed", route_ids: Optional[Iterable[str]] = None, *, split_directions: bool = False, include_stops: bool = False, ) -> Dict: """ Return a GeoJSON FeatureCollection of M...
f74bb2f1b533a8c3ae84da59d77daf2e96fb573b
31,043
def read_input(): """ Read user input and return state of running the game. If user press Esc or exit game window stop game main loop. Returns: bool: Should game still be running? """ # Should we still run game after parsing all inputs? running = True # Look at every event in ...
983661f2a63d0f68ac073ff52d49afe1c98c5ef3
31,044
from dateutil.relativedelta import relativedelta def add_to_date(date, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, as_string=False, as_datetime=False): """Adds `days` to the given date""" if date==None: date = now_datetime() if hours: as_datetime = True if isinstance(date, string_typ...
eec228e54f90a0dfc41be802ba0120906550a007
31,045
def mandel(x, y, max_iters): """ Given the real and imaginary parts of a complex number, determine if it is a candidate for membership in the Mandelbrot set given a fixed number of iterations. """ c = complex(x, y) z = 0.0j for i in range(max_iters): z = z*z + c if (z.rea...
d04e2a94470ca540fced5fc3b1b0a9321421de22
31,046
def IntegerHeap(i): """Return an integer heap for 2^i-bit integers. We use a BitVectorHeap for small i and a FlatHeap for large i. Timing tests indicate that the cutoff i <= 3 is slightly faster than the also-plausible cutoff i <= 2, and that both are much faster than the way-too-large cutoff i...
61a7f44cfd37b38c91a8bcdf3b83b1dc2af98b5b
31,048
def list_sensors(name_pattern=Sensor.SYSTEM_DEVICE_NAME_CONVENTION, **kwargs): """ This is a generator function that enumerates all sensors that match the provided arguments. Parameters: name_pattern: pattern that device name should match. For example, 'sensor*'. Default value: '*'....
b4ddc4508988e8c93d1388ce6857e736da7fc624
31,049
def preprocessBoilerPower(df2, key): """ calculates the average boiler power, because we have timestamps where the boiler is turned off/on often not following the capture period preprocessing is done as well (set index, interpolation) :param df2: dataframe of boiler :param key: sensorname :r...
1deaab79bd82b9df2b91fc296f87deebfb1c03cd
31,050
def ProbLate(pmf): """Computes the probability of a birth in Week 41 or later. Args: pmf: Pmf object Returns: float probability """ return ProbRange(pmf, 41, 50)
c04f1047eeff6336975c490a66c736a7519f70b1
31,051
def inrange(inval, minimum=-1., maximum=1.): """ Make sure values are within min/max """ inval = np.array(inval) below = np.where(inval < minimum) inval[below] = minimum above = np.where(inval > maximum) inval[above] = maximum return inval
3277ed0d780217713f22f5ca27e7fd15b6758d1c
31,052
def default_error(exception=None): """Render simple error page. This should be overidden in applications.""" # pylint: disable=unused-argument return HttpResponse("There was an LTI communication error: {}".format(exception), status=500)
bb2df5f1fe38c6d72dd383b12713ac0ccc6d9f20
31,053
def index_for_shop(shop_id, page): """List orders for that shop.""" shop = _get_shop_or_404(shop_id) brand = brand_service.get_brand(shop.brand_id) per_page = request.args.get('per_page', type=int, default=15) search_term = request.args.get('search_term', default='').strip() only_payment_sta...
d9be41ba01991aaa08f74bf9546f18b565d9ac8e
31,054
from typing import Tuple import requests def create_token(author: str, password: str, token_name: str) -> Tuple[int, str]: """ Create an account verification token. This token allows for avoiding HttpBasicAuth for subsequent calls. Args: author (`str`): The account name. ...
ec0d5d4e208fb7fd6c77bfec554c1ea51d0838f4
31,055
def getPositionPdf(i): """Return the position of the square on the pdf page""" return [int(i/5), i%5]
859fd00c1475cfcb4cd93800299181b77fdd6e93
31,056
def plm_colombo(LMAX, x, ASTYPE=np.float): """ Computes fully-normalized associated Legendre Polynomials and their first derivative using a Standard forward column method Arguments --------- LMAX: Upper bound of Spherical Harmonic Degrees x: elements ranging from -1 to 1 Keyword argume...
b54f5802fa5d0989c5813f85e3b0e37c653ca5aa
31,057
import logging def describe_entity_recognizer( describe_entity_recognizer_request: EntityRecognizer, ): """[Describe a Entity Recognizer Router] Args: describe_entity_recognizer_request (EntityRecognizer): [Based on Input Schema] Raises: error: [Error] Returns: [type]: [...
80ee32329b5393d18d4689caeeb50a2332660f20
31,058
def tool_factory(clsname, command_name, base=CommandBase): """ Factory for WESTPA commands.""" clsdict = { 'command_name': command_name, } return type(clsname, (base,), clsdict)
f4fe71f0938dfa17399e81d15233839a547844be
31,059
from typing import Union from typing import Sequence from typing import Any from typing import Tuple from typing import cast from typing import Dict def plot_single_sd( sd: SpectralDistribution, cmfs: Union[ MultiSpectralDistributions, str, Sequence[Union[MultiSpectralDistributions, st...
b5523c7f278c5bd5fdd91d73f855af3b17c6a63e
31,060
def dur_attributes_to_dur(d_half, d_semiqvr): """ Convert arrays of d_hlf and d_sqv to d. - See eq. (2) of the paper. """ def d_hlf_dur_sqv_to_d(d_hlf, d_sqv): return 8 * d_hlf + d_sqv d = d_hlf_dur_sqv_to_d(d_half, d_semiqvr) return d
aeea74f929ef94d94178444df66a30d0d017fd4e
31,061
import shutil import traceback def copy_dir(source, destination): """ Copy a directory tree and returns destination path. Parameters: source (string): source containing root directory path destination (string): target root directory path Returns: ...
5751da6232a64902f0030271671f3e74ecda97e0
31,062
def polyder_vec(p, m): """Vectorized version of polyder for differentiating multiple polynomials of the same degree Parameters ---------- p : ndarray, shape(N,M) polynomial coefficients. Each row is 1 polynomial, in descending powers of x, each column is a power of x m : int >=0 ...
25d0455c4649f0986ea592ec32c49ded921f73e9
31,063
def normalize_data(data:np.ndarray) -> np.ndarray: """ Subtracts the zero point of the time array and removes nans and infs :param data: Dataset :return: zeroed in dataset """ x = data[0] y = data[1] for i in [np.inf,-np.inf,np.nan]: if i in y: n = len(y[y==i]) ...
26f334e5cebabf6d66cee79a47159bb34dd6e18f
31,064
def _scale_fct_fixed(*args, scale=0): """ This is a helper function that is necessary because multiprocessing requires a picklable (i.e. top-level) object for parallel computation. """ return scale
75eb728f37466aee8664d5fe435d379cf5d7c6f2
31,065
def authorize(vendor_api_key, user_api_key, client_class=Client): """Authorize use of the Leaf Data Systems API using an API key and MME (licensee) code. This is a shortcut function which instantiates `client_class`. By default :class:`cannlytics.traceability.leaf.Client` is used. Returns:...
bf005a58d0063f5171a5b884da59bce361d9df98
31,066
import six def isclass(obj): # type: (Any) -> bool """ Evaluate an object for :class:`class` type (ie: class definition, not an instance nor any other type). """ return isinstance(obj, (type, six.class_types))
a1116d44513c05407368517dc031f023f86d64a7
31,067
def filter_score_grouped_pair(post_pair): """ Filter posts with a positive score. :param post_pair: pair of post_id, dict with score, text blocks, and comments :return: boolean indicating whether post has a positive score """ _, post_dict = post_pair post_score = post_dict['score'] retur...
c824eacd43b44c85fc7acf102fdde2413a7c4d0e
31,068
def post_nodes(): """ .. :quickref: Dev API; Update cluster nodes **Developer documentation** *Requires admin user.* Update the status of cluster nodes specified in the request. The endpoint can be used to notify CC-Server after a dead cluster node has been repaired. **Example request** ...
5fc105ffa236a798c1646282aa5221bec223179f
31,069
import torch def to_one_hot(y_tensor, n_dims=None): """ Take integer y (tensor or variable) with n dims & convert it to 1-hot representation with n+1 dims. """ if(n_dims is None): n_dims = int(y_tensor.max()+ 1) _,h,w = y_tensor.size() y_tensor = y_tensor.type(torch.LongTensor).vie...
f70fd5ab95386c6e471019801d9fe0a5dc0dcbda
31,070
def names(): """List the names of the available satellites Returns: List: List of strings with the names of the available satellites """ return sorted(satellites().keys())
e5627ef1e6981f529b0cf1cf547a0364beb9f498
31,071
import re def read_exechours(filename, verbose = False): """ Read exechours_SEMESTER.txt file and return columns as '~astropy.table.Table'. Parameters ---------- filename : string program exec hours text file name. Returns ------- progtable : '~astropy.table.Table' Pr...
24409895c3d9bef6149a84ecb9eded576fae75fd
31,072
def is_cond_comment(soup): """test whether an element is a conditional comment, return a boolean. :param soup: a BeautifulSoup of the code to reduce :type soup: bs4.BeautifulSoup """ return isinstance(soup, bs4.element.Comment) \ and re_cond_comment.search(soup.string)
8976343f96fdaf144a324fe76709816fbe500b4d
31,073
def sequences_end_with_value(sequences, value, axis=-1): """Tests if `sequences` and with `value` along `axis`. Args: sequences: A matrix of integer-encoded sequences. value: An integer value. axis: Axis of `sequences` to test. Returns: A boolean `np.nadarray` that indicates for each sequences i...
fb4b8091ede9c9f06cd8e1419b6a8f973811e923
31,074
def shortest_path_search(start, successors, is_goal): """Find the shortest path from start state to a state such that is_goal(state) is true.""" # your code here if is_goal(start): return [start] explored = set() # set of states we have visited frontier = [ [start] ] # ordered list of pa...
9bd14c1d848f00dec27a88ec25f3062055f5967b
31,076
from typing import Union from typing import Optional def to_tensor(X: Union[np.ndarray, tf.Tensor], **kwargs) -> Optional[tf.Tensor]: """ Converts tensor to tf.Tensor Returns ------- tf.Tensor conversion. """ if X is not None: if isinstance(X, tf.Tensor): return X ...
77e6fc1e52101717ba3671e3a357803c0a13630d
31,077
def get_explicit_positions(parsed_str_format): """ >>> parsed = parse_str_format("all/{}/is/{2}/position/{except}{this}{0}") >>> get_explicit_positions(parsed) {0, 2} """ return set( map( int, filter( lambda x: isinstance(x, str) and str.isnumeric(...
f6f3720443385f5d514de15d3d63d45cd4ef3408
31,078
def msg_parser_disable(id): """ Disable a Parser - Disconnect a Parser from a Channel CLI API for shell scripts & to be called by S3Method """ db = current.db s3db = current.s3db table = s3db.msg_parser record = db(table.id == id).select(table.id, # needed for update_re...
0e3ff7006fba205eec47fd92e8b15bb4f52ae454
31,080
def filter_is(field, target): """ Check if a log field is the specified value. A boolean is returned. Case-insensitive checks are made. """ lowfield = field.lower() retval = lowfield == target # print "is:\t<%s>\t<%s>\t" % (field, target), retval return(retval)
2975560c54736362f8986d5a9f92af351c4e40fe
31,081
async def get_server_port(node: Node) -> int: """ Returns the port which the WebSocket server is running on """ client = node.create_client(GetParameters, "/rosbridge_websocket/get_parameters") try: if not client.wait_for_service(5): raise RuntimeError("GetParameters service not ...
5a409440312e6c0b0c01be53741f4182a6dc8f70
31,082
import sqlite3 def search_vac(search_phrase): """Get vacancies with search phrase in JSON""" con = sqlite3.connect("testdb.db") cur = con.cursor() sql = 'SELECT * FROM vacancies WHERE json LIKE "%{}%" ORDER BY id DESC LIMIT 100;'.format(search_phrase) cur.execute(sql) vac = cur.fetchall() ...
8669e4ecd50b47a385929536f5cf0faf62577361
31,083
from dso.task.regression.regression import RegressionTask from dso.task.control.control import ControlTask def make_task(task_type, **config_task): """ Factory function for Task object. Parameters ---------- task_type : str Type of task: "regression" : Symbolic regression task. ...
6ebee30330750ab607626b4aa52701b208d70ade
31,084
def detectar_lenguaje(texto, devolver_proba=False): """ Identifica el lenguaje en el que está escrito el texto de entrada. :param texto: Texto de entrada. :type texto: str :param devolver_proba: Indica si se retorna el porcentaje de \ confiabilidad del lenguaje identificado. Valor por \ ...
1382cc2fb41d53fbc286a425f46171ece102f0aa
31,085
def get_tablenames(): """get table names from database. """ con = get_db() cursor = con.cursor() select_tn_cmd = "SELECT name FROM sqlite_master WHERE type='table';" tablenames, res = [], cursor.execute(select_tn_cmd).fetchall() for tn in res: tablenames += [tn['name']] return tablen...
1fd55b54dfd06d5735bb56ff0287954132ba6a94
31,086
def expando_distinct_values(model_class, field_name): """ Returns all possible values for a specific expando field. Useful for search forms widgets. """ ct = ContentType.objects.get_for_model(model_class) qs = Expando.objects.filter(content_type=ct, key=field_name) return qs.distinct().value...
0883022b25bf72f13b2eee98b5ddd98deb8b5991
31,087
def oconner(w, r): """ Optimistic for low reps. Between Lombardi and Brzycki for high reps. """ return w * (1 + r/40)
cdcdc44a06e44910361c55217366e3891e76b6a5
31,088
def unionPart(* partsList): """Finds the union of several partitions""" mat = part2graph(util.concat(* partsList)) parts = graph.connectedComponents(mat.keys(), lambda x: mat[x].keys()) # remove parition ids from partitioning parts = map(lambda part: filter(lambda x: type(x) != int, part), parts) ...
1aa54b80d37d51e9f75c80a0d95fed24e4c57853
31,089
def add_upper_log_level(logger, method_name, event_dict): """ Add the log level to the event dict. """ event_dict["level"] = method_name.upper() return event_dict
36ccdf335473136fe8188ff99ed539920ee39fa7
31,090
def tanh_cl(a): """ Hyperbolic tangent of GPUArray elements. Parameters ---------- a : gpuarray GPUArray with elements to be operated on. Returns ------- gpuarray tanh(GPUArray) Examples -------- >>> a = tanh_cl(give_cl(queue, [0, pi/4])) [ 0., 0.6557942]...
d4fbb13033f48773bd20539837c69d6c66528f7f
31,091
import time def sweep_depth(sketch_class): """Return a table of shape (len(depth_values), 2) counting number of times the sketch correctly found the heaviest key.""" # 1st column is for the median, 2nd is for the sign alignment estimator print(sketch_class.__name__) num_success = np.zeros((len(depth_values), ...
9c034ac6ef0c93488b30bbb6aef3b693489d6490
31,094
def plot_ensemble_results(model, ensemble, expts = None, style='errorbars', show_legend = True, loc = 'upper left', plot_data = True, plot_trajectories = True): """ Plot the fits to the given experiments over an ensemble. Note ...
38d36373dde4959cce8f51d2c52a2c404ee73e4c
31,095
import math import tqdm def generate_synthetic_gaps( mean: np.ndarray, covariance: np.ndarray, size: int, chunk_size: int, threshold: int, seed: int ) -> np.ndarray: """Return numpy array with the coordinates of gaps in matrix mask. Parameters ------------------ mean: np.ndarr...
fcfaa5c0dc7a3b1dc47d7d4947504c8a7794d6d1
31,096
def ulmfit_document_classifier(*, model_type, pretrained_encoder_weights, num_classes, spm_model_args=None, fixed_seq_len=None, with_batch_normalization=False, activation='softmax'): """ Document classification head as per the ULMFiT paper: - ...
639c7b2b94722a92fda94344529563b05fa2adbc
31,098
def is_zero_dict( dict ): """ Identifies empty feature vectors """ has_any_features = False for key in dict: has_any_features = has_any_features or dict[key] return not has_any_features
eefb3df1547917fbc11751bbf57212f95388e8b2
31,099
from typing import Dict from typing import Callable def register_scale( convert_to: Dict[str, Callable] = None, convert_from: Dict[str, Callable] = None ) -> Callable[[Callable], Callable]: """Decorator used to register new time scales The scale name is read from the .scale attribute of the Time class. ...
3adcd0d53a3c1622f81a1c444da19c4f2b332d14
31,100
def read_project(config_path, timesheet_path=None, replicon_options=None): """ Read a project dictionary from a YAML file located at the path ``config_path``, and read a project timesheet from the path ``timesheet_path``. Parse these files, check them, and, if successful, return a corresponding Project inst...
b3b13bd1594f3d1ba0ba3b53af5f8546c59f39ee
31,102
from typing import Union from typing import Tuple def _parse_query_location( location: Union[Tuple[float, float], Point, MultiPoint, Polygon] ) -> str: """Convert given locations into WKT representations. Args: location (QueryLocation): Provided location definition. Raises: ValueErro...
17e57b9521144c61c6069d52a8ebcad6101882aa
31,103
def getuniqueitems(userchoices): """return a list of unique items given a bunch of userchoices""" items = [] for userchoice in userchoices: if userchoice.item not in items: items.append(userchoice.item) return items
a7885556604153cf756fb6a29c2e870c27d47337
31,104
def _as_array(arr, dtype=None): """Convert an object to a numerical NumPy array. Avoid a copy if possible. """ if arr is None: return None if isinstance(arr, np.ndarray) and dtype is None: return arr if isinstance(arr, integer_types + (float,)): arr = [arr] out = np.a...
d0336a8cedcd324d5dd26a7b98f59d70f691cf1d
31,105
def add_region(): """ add a region page function """ # init variables entry = Region() # creates a model.py instance, instance only has a name right now error_msg = {} form_is_valid = True country_list = Country.query.all() if request.method == 'GET': return render_template('regio...
0798a7bec6474cf83dd870b6529e8f57b69bc882
31,107
import six def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'): """ This function was excerpted from Django project, modifications have been applied. The original license is as follows: ``` Copyright (c) Django Software Foundation and individual contributors. All rights reserv...
e4040ea31669acbdbfee5db9f6ce30acdc40bae1
31,108
def get_host(hostname): """ Get information about backups for a particular host """ print(f"\nSearching for host '{ hostname }'...\n") backuppc_data = get_backup_data() for host in backuppc_data: if host['hostname'] == hostname: return host
5b017be557d9b5340e44905a49ea6ee2b1ea30b3
31,109
def gazebo_get_gravity() -> Vector3: """ Function to get the current gravity vector for gazebo. :return: the gravity vector. :rtype: Vector3 """ rospy.wait_for_service("/gazebo/get_physics_properties") client_get_physics = rospy.ServiceProxy("/gazebo/get_physics_properties", GetPhysicsProp...
8ec560e1fd276be9d2677f94dc5d9b5017e81d23
31,110
def make_mock_device(): """ Create a mock host device """ def _make_mock_device(xml_def): mocked_conn = virt.libvirt.openAuth.return_value if not isinstance(mocked_conn.nodeDeviceLookupByName, MappedResultMock): mocked_conn.nodeDeviceLookupByName = MappedResultMock() ...
80b9b51f586c2b373478020b2a08276e97a6d5ba
31,111
from typing import Union def load_file(file_name: str, mode: str = "rb") -> Union[str, bytes]: """Loads files from resources.""" file_path = get_resource_path(file_name) with open(file_path, mode) as file: return file.read()
ed535b091f3ae853e60610022ef01bb38c67b41e
31,112