content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_main_workflow_sql(project_id: str, dataset_id: str, merchant_id: str, customer_id: str) -> str: """Returns main workflow sql. Args: project_id: A cloud project id. dataset_id: BigQuery dataset id. merchant_id: Merchant center id. customer_id: Google Ads customer id...
f4ac6663a3a6246ef0fef4bb63134b088d499ce4
67,591
def dividend( tickers, typ='all', start_date=None, end_date=None, **kwargs ) -> pd.DataFrame: """ Bloomberg dividend / split history Args: tickers: list of tickers typ: dividend adjustment type `all`: `DVD_Hist_All` `dvd`: `DVD_Hist` `...
5e2c99e74557c53ed2dd6b9a6444fdb77771bc31
67,592
def get_next_mini_batch(): """Return the next mini batch of training data. Returns x_trn_mb: mini batch of training x values y_trn_mb: batch of training y values """ global idx_in_epoch, epoch, ids, x_trn, y_trn start = idx_in_epoch idx_in_epoch += mb_size ...
c0ba5720045b9452e54e74987011c3078c5ec765
67,593
def put(value): """Store an object in the object store. The object may not be evicted while a reference to the returned ID exists. Args: value: The Python object to be stored. Returns: The object ref assigned to this value. """ worker = global_worker worker.check_connected...
d5e245d63c162a4c72b20fec2ff04d281331ca32
67,594
def get_accuracy(data_loader, model, device): """ Calculates the accuracy of the model given (inference mode) applied in the dataset of the data_loader :param data_loader: Data loader :param model: Model to be used for predictions :param device: Device to be used :return: accuracy percentage % ...
afdd5fc792ba726969057c1d12c3287c15778d65
67,596
def grayscale(image): """ Change the image to be grayscale using the NTSC luminosity formula and return it. """ for pixel in image: luminosity = compute_luminosity (pixel.red, pixel.green, pixel.blue) pixel.red = luminosity pixel.green = luminosity pixel.blue = luminosity...
155eb30b4a4da0d830e0f1b36a0adf13ddee4e65
67,597
import tensorflow as tf from art.classifiers import TFClassifier def get_classifier_tf(): """ Standard Tensorflow classifier for unit testing. The following hyper-parameters were used to obtain the weights and biases: learning_rate: 0.01 batch size: 10 number of epochs: 2 optimizer: tf.tr...
7df7f0d823da0285f6e82090eefa0cb23bbfbae6
67,598
def version(): """Get the current version.""" return _version_info
42c08ec4d051646ed3dc6bf2e59cd29944136723
67,599
import warnings def wsgi_proxyfix(factory=None): """Fix Flask environment according to ``X-Forwarded-_`` headers. .. note:: You must set ``WSGI_PROXIES`` to the correct number of proxies, otherwise you application is susceptible to malicious attacks. .. versionadded:: 1.0.0 .. note::...
4fd7cc6048672db0e9f27669bcc56deeb84e29a7
67,600
from api.v2.serializers import keys_hyphens_to_underscores import requests def export_content_list(request): """ View for listing metadata for all exportable contents. """ proto = request.META['wsgi.url_scheme'] host = request.META['HTTP_HOST'] resp = requests.get('{}://{}/api/v2/exportab...
6e81226260bbc438f87421e8b8695b5bd0a6fdd0
67,601
def make_dag1D_params(): """Make parameters for a triangle graph with 1D treatment.""" alpha = np.array([0.9]) gamma = np.array([[1.9]]) beta = np.array([1.2]) eps = 0.3 nu = 0.3 return alpha, gamma, beta, eps, nu
fa169ce64277fe0e39b2c730613fd91f8966aa65
67,602
import json def check_json_exists(): """Loads courseId_folderId_pairs.json as dict if exists, returns empty dict if not Returns: [dict]: dict(courseId_folderId_pairs) """ try: with open(f"{BASE}/data/courseId_folderId_pairs.json") as f: courseId_folderId_pairs = json.load(f...
49e7f70b1f0de780f407357738c1a52514df6b0f
67,603
import requests def info(): """ get api info """ res = requests.request("GET", URL, headers=HEADERS) return _decode_response(res.content)
6d6b886c68b89ad1f336bde87179834d7b5915a2
67,606
import copy def plugin_init(config): """ Initialise the plugin. Args: config: JSON configuration document for the South plugin configuration category Returns: data: JSON object to be used in future calls to the plugin Raises: """ data = copy.deepcopy(config) return data
5bf5b8d160712de1305071605cedc10e82a23926
67,607
def _int_size(x): """Return the smallest size int that can store the value""" if -0x80 <= x <= 0x7F: return 1 elif -0x8000 <= x <= 0x7FFF: return 2 elif -0x80000000 <= x <= 0x7FFFFFFF: return 4 elif long(-0x8000000000000000) <= x <= long(0x7FFFFFFFFFFFFFFF): return 8 ...
c22b8a4789f8cf6150959b30fdf1c444b585e0e7
67,608
def _build_sudoku_instance_graph(elements): """Creates a graph representation of a sudoku instance. Arguments: elements (list[list[int]]): A matrix representation of the sudoku instance. Returns: A networkx.Graph object representation of the sudoku instance. """ size = len(elements)...
c10395318a5dd43920bb3c2644700e3434e3bc97
67,610
def send_contract(post_data): """ Due to the potentially sensitive nature of TAC case data, it is necessary (for the time being) to limit CASE API access to Cisco employees and contractors, until such time as a more appropriate authentication method can be added """ # Check if user is cisco.com ...
02aa3b95d5c9fdf98cc73e908a0f6c18fd25aa4c
67,611
from operator import invert def _select_period(detected, true_values): """For the detected values, we check when it goes above/below the selection. Parameters ---------- detected : ndarray (dtype='int') N x 3 matrix with starting and ending times. true_values : ndarray (dtype='bool') ...
6f39bc04014b44d45bec08bcaa0dd441336adfb8
67,613
from typing import List from typing import Type from typing import Union def gini_cols( data: np.ndarray, distributions: List[Type[Leaf]], domains: List[Union[list, tuple]], random_state: np.random.RandomState, e: float = 0.3, alpha: float = 0.1 ) -> np.ndarray: """ Gini index column s...
a858966337caa68f1f39785428908a1969d957b4
67,614
def Rg(*args): """Earth return resistance value used to compute line impedances at power frequency""" # Getter if len(args) == 0: return lib.Lines_Get_Rg() # Setter Value, = args lib.Lines_Set_Rg(Value)
3f7daa7da2e5b7fdf56375386603cfb94bbf55a8
67,615
def reshape_non_gcp_df(flight_line_df, multi_buffers): """ get the time column back where it belongs efore exporting result """ temp_df = remove_non_gcp(flight_line_df, multi_buffers) if temp_df is None: return None temp_df.insert(loc=7, column='time', ...
c0842587316367ea896af26a219a66e349f9dd1a
67,616
def learn_pool(tickers: tuple, last_date: pd.Timestamp, freq: Freq, lags: int = 5): """Возвращает обучающие кейсы до указанной даты включительно в формате Pool Кейсы состоят из значений дивидендной доходности за последние years лет с частотой freq за период с начала данных до last_date Parameters ...
ba84a9844d75dd59dc3748d311d8d5f7f350adc6
67,617
def chart(symbol, timeframe="1m", date=None, token="", version="", filter=""): """Historical price/volume data, daily and intraday https://iexcloud.io/docs/api/#historical-prices Data Schedule 1d: -9:30-4pm ET Mon-Fri on regular market trading days -9:30-1pm ET on early close trading days A...
4df7842c3febab86216ef738e66a0c4628f85355
67,618
from typing import Any async def async_setup(hass: HomeAssistant, config: dict[str, Any]) -> bool: """Set up the Verisure integration.""" if DOMAIN in config: hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPO...
f21f231d562a81efcc937f88d479aa0236741d0a
67,619
def q_response(frequency, nmax): """ Compute the Q-response for a given conductivity model of Earth. The conductivity model is loaded during the computation from ``basicConfig['file.Earth_conductivity']``. Parameters ---------- frequency : ndarray, shape (N,) Vector of `N` frequenc...
d484c0991d11d4f0441c91c6503727a5faee0952
67,620
def convert_bytes(size: float) -> str: """humanize size""" if not size: return "" power = 1024 t_n = 0 power_dict = {0: " ", 1: "Ki", 2: "Mi", 3: "Gi", 4: "Ti"} while size > power: size /= power t_n += 1 return "{:.2f} {}B".format(size, power_dict[t_n])
cf73b50454c25ce32148697b520069aea6b44d23
67,621
def svn_txdelta_compose_windows(*args): """ svn_txdelta_compose_windows(svn_txdelta_window_t window_A, svn_txdelta_window_t window_B, apr_pool_t pool) -> svn_txdelta_window_t """ return apply(_delta.svn_txdelta_compose_windows, args)
a33c4dca58e3a658739b78f038bba2511774dc86
67,622
def compute_metrics(preds): """Computes a set of metrics (accuracy, f1-score, precision and recall). Args: preds (transformers.trainer_utils.PredictionOutput): Predictions and potential metrics. Returns: A dictionary containing a set of metrics. """ # True labels y_true = pre...
21644eb9a30f5425d94482b241d4617c381849df
67,623
from typing import List def generate_additional_num_features( X: pd.DataFrame, num_features: List[str] ) -> pd.DataFrame: """ Generate additional numerical features by applying mathematical operations on combinations of features :param X: Data :param num_features: Numerical features in...
6ab5de5adc298f03c28f985bd2d3f704699cf702
67,624
from typing import OrderedDict def normalize_inp_config(inp_obects): """ Unpack the config details for each inp section and organize in a standard format. This allows the YAML file to be more short hand and human readable. :param inp_obects: :return: >>> from swmmio.defs import INP_OBJECTS ...
568a83cd734f0ad5b613a83d9a35b2bfb145fb5a
67,625
def normalize_image(img, circle_center, circle_radius, target_circle_radius): """ Transform an image such that the provided circle is moved to the image center and scaled to the specified size. :param img: An image :param circle_center: Circle center :param circle_radius: Circle radius :par...
f8e6009f2f87effd90382d1500230d41eb0f38a7
67,627
from typing import Dict from typing import Any from typing import Callable from typing import Generator import tempfile def run_lambda( event: Dict, context: Any, parsing_function: Callable[[str, str, str], Generator[Dict, None, None]]): """ Encapsulates all of the work performed by a ...
465bf5b77f8f3bdd0ca3bdcc88d51a183eda27b5
67,628
import six import json def read_key(key): """Returns the value of the specified key, or None if it is not present.""" clt = get_etcd_client() val, meta = clt.get(key) if val is not None: val = six.ensure_text(val) return json.loads(val)
2231e188e1d4644cd53dab70d671393379f9006b
67,629
def extract(typ, src): """ DataObject value type converter. :param typ: the type to extract. :param src: the source to extract as type typ. :return: if the type has the ability to extract (convert), otherwise the original version is returned. """ if hasattr(typ, 'extract'): ...
4fd3636970ca0f3785414e436e3fab3156daa17f
67,630
def ComputeErrorRates(label_counts, word_counts, seq_errors, num_seqs): """Returns an ErrorRates corresponding to the given counts. Args: label_counts: ErrorCounts for the character labels word_counts: ErrorCounts for the words seq_errors: Number of sequence errors num_seqs: Total sequences ...
f95ed337f3f4dda019518b84b111994ff5396e3f
67,631
def prediction_to_dict(instances, img_id): """ Args: instances (Instances): the output of the model img_id (str): the image id in COCO Returns: list[dict]: the results in densepose evaluation format """ scores = instances.scores.tolist() segmentations = ToMaskConverter.c...
e9556de43cd9b193c174a447c9890869cfd965b8
67,632
def gen_keys_condition(allStar,elems,dr='16',uplim=0.05,downlim=-1000, snrlim=50,gerrlim=0.2,terrlim=100,tuplim=5000, tlolim=3500,guplim=4,glolim=0): """ allStar: numpy structured array or pandas dataframe with the following keys: ...
9bba937ac60c21c88c41bd2d442e508dbb655f71
67,633
def read_format(info): """input info and return readable format""" info_name = info["name"] info_desc = info["description"] info_coun = info["country"] return f"{info_name}, a {info_desc}, from {info_coun}"
1804b25b8d1d01b2525887e9f4ba75d031cdf515
67,634
import zipfile def test_zip(obj: zipfile.ZipFile) -> (str, bool): """ Test a zip file. Args: obj: a ZipFile object Returns: str: HTML output bool: test ok """ try: result = obj.testzip() except Exception as exception: # pylint: disable=broad-except ...
cb0836465278e46bc61827a0013faf864e252f0d
67,635
def attach_from_parents(routing_tree, id_to_idx, parents, visited): """ Attach children routing tree starting from list of parent routing trees. routing_tree : RoutingTree A node cache that contains all routing branches in the net. id_to_idx : dict object id to int Map of object id to idx ...
58b441cb30fcd81dbc7c1bd9a330aec107448e8f
67,636
def cvFirstType(*args): """cvFirstType() -> CvTypeInfo""" return _cv.cvFirstType(*args)
daf0c19c706e9fa8b91f3c2d2154b6877d1617bf
67,638
def flatten_issue(get_issue, issue, expand_subtasks=False): """ story is broken down into subtasks """ issues = [issue] if is_parent_issue(issue): if expand_subtasks: issues += [ get_issue(s.key, expand='changelog') for s in issue.fields.subtasks ...
59e8f3fcd6ac4e27cbc269358f4c6393ca462497
67,639
def score_function(nom_cosine, w): """ 最终得分值为归一化的余弦距离 * 权重项 :param nom_cosine: :param w: :return: """ return nom_cosine * w
99468bca131a42148b0bf012f5f3c61215716b57
67,640
def load_motion_masks(motion_root): """Load motion masks from disk. Args: motion_root (Path): Points to a directory which contains a subdirectory for each sequence, which in turn contains a .png for each frame in the sequence. Returns: motion_masks (dict): Map seque...
babe7c83b7f2c7a1cade2d4fcb3de8461d88ba00
67,641
import numpy def ltp(epj): """ Wrapper for ERFA function ``eraLtp``. Parameters ---------- epj : double array Returns ------- rp : double array Notes ----- The ERFA documentation is below. - - - - - - - e r a L t p - - - - - - - Long-term precession ma...
23cbc1d4b420d17553c720b4881d46167d79deee
67,643
def parse_genetic_models(models_info, case_id): """Parse the genetic models entry of a vcf Args: models_info(str): The raw vcf information case_id(str) Returns: genetic_models(list) """ genetic_models = [] if models_info: for family_info in models_info.split(",...
9d8d94d9008e2f287a875aa9bd15330c82bbf8b5
67,644
def get_watchdog_list(threadid): """Get the watchdog list of a thread. Contrary to :func:`get_current_watchdog_list` this function does not create a watchdog list, if it does not already exist. """ # The second argument of get_thread_info() is intentionally undocumented. # See C source. ret...
65da0743642d13bdf402198693eb1baa54382d7d
67,645
def make_points(reader): """Make the list of points from the CSV.""" points = [] for row in reader: points.append((ip_address(row['start']), START_POINT, row['id'])) points.append((ip_address(row['end']), END_POINT, row['id'])) return sorted(points)
cf61989c09067806701a1e5bcd23b589a13c05a1
67,646
import copy def bg_command(command_dict, bg_parameter, system_id): """Use the bg_command fixture instead.""" dict_copy = copy.deepcopy(command_dict) dict_copy["parameters"] = [bg_parameter] return Command(**dict_copy)
1d84f6ba8d541fef839cddcad620ed0780e389a4
67,647
from typing import Tuple def random_scaling_crop( scale_range: Tuple[int, int] = (0.8, 1.0), ratio_range: Tuple[int, int] = (3.0 / 4.0, 4.0 / 3.0), ): """ Random crop implementation which also randomly scales the crop taken as well as the aspect ratio of the crop. :param scale_range: the (min,...
0ef554df2b94665dee4a9f2975925ae376695163
67,648
def aluno_detail_form(**kwargs): """ Function to get Aluno's detail form. :param kwargs: form properties :return: Form """ return AlunoDetailForm(**kwargs)
c07121adfaa24b57639ea9d37a25b8da604b9040
67,649
def MeshPlane1(mesh, planes, multiple=False): """ Intersects a mesh with a collection of (infinite) planes. Args: mesh (Mesh): Mesh to intersect. planes (IEnumerable<Plane>): Planes to intersect with. Returns: Polyline[]: An array of polylines describing the intersection loops ...
43ff8e7003c331bd62045b5ca7279a2204845b66
67,650
def _normalize_au_netref(network, ref): """ Take the network and ref of an Australian road and normalise them so that the network is in the form 'AU:road-type' and the ref is numeric. This is based on a bunch of logic about what kinds of Australian roads exist. Returns new (network, ref) values. ...
f4d38ef0b7a2a611a918fd8a3126d8dab4c6b8e2
67,651
def get_table(nb_name, n_cell, n_output=0): """Get output table (or any html) from an IPython notebook on disk.""" outputs = get_outputs(nb_name, n_cell) html = outputs[n_output]['data']['text/html'] return HTML(html)
32f47baa8733723cf3182d48e96f87f4aa5fa7ba
67,652
def loadGroupActFlowFC_NoHidden(inputtype,fcdir): """Load direct input 2 output FC mappings -- control analysis""" if inputtype in ['VERTICAL','RED','HIGH','CONSTANT']: h5f = h5py.File(fcdir + inputtype + 'ToOutputLayer_FC_Group.h5','r') fcmapping = h5f['sourceToTargetMapping'][:].copy() ...
2903ef04fb48b027ad258171fe898c30fe2faafa
67,653
def bundle_selector(bundle_dict, colors, b): """ Selects bundle and color from the given bundle dictionary and color informaiton Helper function Parameters ---------- bundle_dict : dict, optional Keys are names of bundles and values are dicts that should include a key `'uid'...
3aa51f30e6e5fae6ed6b201f229f33c249e4bc3f
67,655
def func_api_view_snippet_detail(request, pk): """ Retrieve, update or delete a code snippet. """ try: snippet = Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = SnippetSeri...
89c12e138a60d8d4764256745a5747e341df3f19
67,656
def plotRegParam(sc, data, regParam_list = [0,0.001, 0.003, 0.006, 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24],\ iterations=50, iter_sgd=10, alpha=0.01, factorLength=4): """ Plot the error (rtv_pr_auc, rtv_auc, logl, mse) function of the regularization parameters ...
3f158aceb5f9d914c63073692e71ec767346148b
67,657
def generate_partial_productions(segment): """ 短语树拆分 :param segment: :return: """ pos_root = BASE_DIR + "/toolkit/stanford/stanford-corenlp-full-2017-06-09/" par_model = pos_root + "models/lexparser/chinesePCFG.ser.gz" opttype = 'penn' parser = StanfordParser(par_model, pos_root, opt...
8dced355e5a85fb152e68d93df95a95b930e6537
67,658
def zzX_abs(f): """Make all coefficients positive in Z[X]. """ if poly_univariate_p(f): return zzx_abs(f) else: return [ zzX_abs(coeff) for coeff in f ]
5b985deb4ef0d68f9ac8be752e23cb61436dc0bf
67,659
def stress_to_speed(x, y): """Convert ocean wind stress to wind speed at 10 m over the ocean. This expects that tau is in dyn/cm2. .. math:: \\tau = 0.0027 * U + 0.000142 * U2 + 0.0000764 * U3 .. note:: This is useful for looking at wind speed on the native ocean grid, rather than ...
a13761f4fdfd01b22493493730aa59d9d3f229de
67,661
def _form_save_redirect(pkg_name, action, package_type=None): """This redirects the user to the CKAN package/read page, unless there is request parameter giving an alternate location, perhaps an external website. @param pkg_name - Name of the package just edited @param action - What the action of th...
fecee05f2ec8524c96eed735c65ebeaad96e86f6
67,662
def _get_source_pulse(pulse_length, offset): """ Define source pulse start and end. By default, the source pulse is at distance 0. """ x0 = (0.0 * sc.units.us) + offset x1 = pulse_length + offset y0 = 0.0 * sc.units.m return x0, x1, y0
d1a8231d498b016c76215c772c354e3497e92e94
67,663
def read_labels(labels_file): """Get the labels from names file""" with open(labels_file, 'r') as f: lines = f.readlines() return [lab for lab in lines if len(lab) > 0]
a1b4ce5c0b5c613db5ec0d7d619910210d88106e
67,666
def id3_sort_key(mp3_path): """Create the sort key for an MP3 file. """ id3r = id3reader.Reader(mp3_path) return ( get_value(id3r, 'performer'), get_value(id3r, 'year'), get_value(id3r, 'album'), get_track(id3r), get_value(id3r, 'title'), # Provide the ori...
a1faba94f7e9ab13efb7abe0ac0c5338bcbcda25
67,667
import torch def breg_mixture_divergence(p, Y, q, X, kernel, symmetric=False): # NOTE: if you make changes in this function, do them in *_stable function under this as well. """ Compute similarity sensitive GAIT divergence of between a pair of empirical distributions p and q with supports Y and X, res...
7ce29b78841fe11d5d1b6571439367f58b674eaa
67,668
def create_example(inputs, outputs, word_vocab, char_vocab): """Given a string and a label (and a vocab dict), returns a tf.Example""" inp_seq, inp_sl, inp_maxword = encode_line_charwise(inputs, char_vocab) out_seq, out_sl1, out_maxword = encode_line_charwise(outputs, char_vocab, ...
507b8d4dbbe0173de848f12db257b080b464e047
67,670
def has_owner_rank(user, club): """Checks for if user is owner.""" return is_rank(user, club, ClubMembership.UserRoles.OWNER)
c33207d700d4b17adbb44d99d5b2f80d05a33212
67,671
from typing import List from typing import Any from typing import Sequence def _make_cat( labels: List[List[Any]], n_states: int, state_names: Sequence[str] ) -> Series: """Get categorical from list of lists.""" labels_new = np.repeat(np.nan, n_states) for i, c in enumerate(labels): labels_ne...
0dd3e8e824f7e281672880534918fa229133459f
67,672
def get_incidence_flattened(pred, c): """Converts "raw" predictions for use in generate_scenarios_* methods. This method * rolls together model and sample dimensions into a single sample_flattened dimension. * restricts forecasts to the time period of the trial * sorts by cumulative incidence Args: ...
a0a89ba3307c829577216ca78f113c271ae77114
67,673
def triang_inds(pts_w_imgs, gb1_inds, inds_arr): """ Function finds the indices of atoms which make tetrahedrons with at least one GB atom. Parameters ------------- pts_w_imgs : The position of atoms which are inside the main box and within rCut to the main box. gb1_inds : Indic...
554219f5e4b67c22fc3c31f4ca577fa1ad491564
67,675
from typing import Optional from typing import Set def enrich_pmc_citations( graph: BELGraph, *, manager: Optional[Manager] = None, group_size: Optional[int] = None, offline: bool = False, ) -> Set[str]: """Overwrite all PubMed citations with values from NCBI's eUtils lookup service. :par...
2ec80e3083c94acd3953bdc9134be9982bbd8c11
67,676
def read_file(filename): """ Reads in the file I created manually (by recompiling and adding timers) Not used any more but left for historical reasons (the first 'speedup' plots were generated with this function) """ dtype = np.dtype([('same_cell', np.int32), ('N1', np...
206a9c8122fcca20de012e8dc94c136013a1ba5b
67,677
def welcome(): """List all available api routes.""" return ( f"Welcome to Climate App<br/>" f"Available Routes:<br/>" f"Precipitation Data: /api/v1.0/precipitation<br/>" f"Stations List: /api/v1.0/stations<br/>" f"Temperature Observation for the most active station: /api/...
3fead56e744b1399b20ab24da4d2c1c9b901379e
67,678
def accum_array(group_idx, arr, func=None, default_value=None, min_n_group=None, rebuild_index=False): """groups a by indices, and then applies func to each group in turn. e.g. func example: [func=lambda g: g] or [func=np.sum] or None for speed based on https://github.com/ml31415/numpy-groupies """ ...
bec604dd48e651c29454c30917253af57e39241a
67,679
def get_ec2_instances(AwsInfo=None): # noqa: E501 """List AWS EC2 instances Get all EC2 instances in one region with match state # noqa: E501 :param AwsInfo: Request body :type AwsInfo: dict | bytes :rtype: None """ if connexion.request.is_json: AwsInfo = AwsInfo.from_dict(connex...
f1debf4d84e5261744751ed8f3a230b4555b188d
67,680
def custom_mapping_repr( mapping, # type: Mapping prefix="{", # type: str template="{key}: {value}", # type: str separator=", ", # type: str suffix="}", # type: str sorting=False, # type: bool sort_key=None, # type: Optional[Callable[[Any], Any]] reverse=False, # type: bool k...
890b1a18e0776dc5791ceec512ad026f1b94f331
67,682
from bs4 import BeautifulSoup def get_string_from_tag(row_with_tag): """Given a row with a tag, return the string from it. Ex. Given, <a href="http://www.example.com/page/index.html">Example Page</a> return the string "Example Page" """ row = BeautifulSoup(str(row_with_tag)) return u''.join([r...
7c154fa4752ae59a2a33c45aaded394db2cb42f3
67,684
def get_ami_list_from_ec2(main_region, regions, owner, credentials, filters): """Get the AMI mappings structure given the constraints represented by the args.""" amis_json = get_initialized_mappings_dicts() for region_name in regions: images_for_region = get_images_ec2(filters, owner, region_name) ...
367247948dff95bc9bab996e96216d1cf4b8b9d7
67,685
def norm_angle(a): """Return the given angle normalized to -180 < *a* <= 180 degrees.""" a = (a + 360) % 360 if a > 180: a = a - 360 return a
2f0e77a4567ca566bb958cd4efb4db24b74e37b7
67,686
import re def slug_sub(match): """Assigns id-less headers a slug that is derived from their titles. Slugs are generated by lower-casing the titles, stripping all punctuation, and converting spaces to hyphens (-). """ level = match.group(1) title = match.group(2) slug = title.lower() sl...
58c40e4ca23bd76a0e25d746aeb4ccdbed6640d7
67,687
def load_csv_data(data_path, sub_sample=False): """Loads data and returns y (class labels), tX (features) and ids (event ids)""" y = np.genfromtxt(data_path, delimiter=",", skip_header=1, dtype=str, usecols=1) x = np.genfromtxt(data_path, delimiter=",", skip_header=1) ids = x[:, 0].astype(np.int) input_data = x[:,...
496d9ffa7b1b975bf5d742bd00daabae7ac4d7cb
67,688
def sum_1_column(column,var): """ Arg: column --> df column name var --> column name abbreviation used Return: sum of occurrences of variable in column count of values in column """ return np.sum((column == var))
e711e427e203a5f8d1c65f535b6c826e630c744d
67,689
def validateIsNotEmpty(data: str, fieldName: str): """Validate if data empty""" if data == '' or data == None: return "{} Must be not empty".format(fieldName) return None
26bec771bb881e32ded022acc57e62b81b2991f9
67,690
def search2(request, template_name='searchv2/search.html'): """ Searches in Grids and Packages """ return homepage(request, template_name=template_name)
fa9d3a8e5e0b7bd9318268abb9a822180c5fe1ee
67,691
def get_message_after(response, index): """Returns next message of search response after index or None""" try: return response[index + 1].object except IndexError: return None
0208fd1f4397e77636df11b62054e86eb84fb682
67,692
from typing import Union from typing import Sequence def average_false_discovery_score( y_true: Union[Sequence[int], np.ndarray, pd.Series], y_pred: Union[Sequence[int], np.ndarray, pd.Series], ) -> float: """Calculates the average false discovery score. Used for when we have more than 2 classes and want ...
e742996870e640bd15f03206b9a6b260387b34d1
67,693
from typing import Dict from typing import Any import torch def evaluate(args: Namespace, model: nn.Module, dataloader: DataLoader, output_composer: OutputComposer, sequence_metrics: SequenceMetrics, reset: bool = True, ) -> Dict[str, Any]:...
d8f9e5ee00daa8b0b3383829a974b7330ecd6c96
67,694
import json def new_s3_bucket(s3, elb_name, account_id, region): """ Create new S3 Bucket """ bucket_name = 'elblogs-' + account_id + '-' + region try: if region == 'us-east-1': result = s3.create_bucket( ACL = 'private', Bucket = bucket_name ) else: result = s3.c...
92e2e699a789b203bd6125d8745defd32807ba3c
67,695
def should_backport(labels=None, milestone=None): """return set of PRs marked for backport""" if labels is None and milestone is None: raise ValueError("Specify one of labels or milestone.") elif labels is not None and milestone is not None: raise ValueError("Specify only one of labels or mi...
1e0794bd0a8fc57d70ecd4060a0bc5ebb86898b9
67,696
def returns(matcher): """ Matches a no-argument callable that returns a value matched by the given matcher. """ return _Returns(matcher)
0b92f04bb8d73da42c19de5e7f389eacf74ac1c4
67,697
from re import T def _get_charge_state_icon(entity: RenaultSensor[T]) -> str: """Return the icon of this entity.""" if entity.data == ChargeState.CHARGE_IN_PROGRESS.value: return "mdi:flash" return "mdi:flash-off"
dc75a1c4695fc0e214c8b5d15038f21bb183f881
67,698
def is_noiseless(model: Model) -> bool: """Check if a given (single-task) botorch model is noiseless""" if isinstance(model, ModelListGP): # pyre-ignore: [16] raise ModelError( "Checking for noisless models only applies to sub-models of ModelListGP" ) return model.__class__ in N...
a358b62b872fcd797a9f4ae70142df510e012356
67,699
from datetime import datetime from typing import Optional from re import L def day_label(dt: datetime, *, now: Optional[datetime] = None) -> str: """Returns nice date label (today, Monday, 11.12.2013).""" if now is None: now = datetime.now if now.date() == dt.date(): return L(32327, 'Today...
900b7c2e787beea3877c4f5a5384d4776ce500e5
67,700
def combine_codon_labels(c1, c2): """ Combines codon labels, assuming bases mixed randomly Ex: AAA + CCC + GGG + TTT -> NNN = (AAA, AAC, ....) Ex: ABC + CCC --> MBC """ letters = [] for b1, b2 in zip(c1, c2): b1 = b1.upper() b2 = b2.upper() _ = DEGENERATE_NUCLEOTIDE_C...
6b9731e0fda82f6c46fe4edb9a00b1a6e6ff1bf0
67,701
import time import json def result_running_callback(request, context): # pylint: disable=unused-argument """ Callback function returning 'running' JSON. """ job_result_running = { 'status': 'running', } time.sleep(1) return json.dumps(job_result_running)
cb38b44b86cdcc96706dbf40a764d8d2059de449
67,702
def polylinear_gradient(colors, n): """Returns a list of colors forming linear gradients between all sequential pairs of colors. `n` specifies the total number of desired output colors. Code from http://bsou.io/posts/color-gradients-with-python """ # The number of colors per individual linear g...
305949f20f96899c003c61d77d58668332b57d23
67,703
def applyXformToBounds(curXform, curBounds): """ Utility function to calculate the effect of an Xform (list of 16 values) to a bounds (list of 6 values) """ newBounds = None # loop through the 8 corners of the bounding box for ix, iy, iz in ( (0,2,4), (1,2,4), (0,3,4), (1,3,4), (0,2,5), (1,2,5),...
228520db56b75a2e831d7443e20bce461a121dcc
67,705
def _convert_to_binary_classification_predictions(predictions): """Converts a `Tensor` into a set of binary classification predictions. This function checks that the given `Tensor` is floating-point, and that it is trivially convertible to rank-1, i.e. has only one "nontrivial" dimension (e.g. the shapes [1000...
bd72f62ce793f398306161868c467fb8ae953fb5
67,706
from typing import Union def value_counts_v2(s: Union[pd.Series, pd.DataFrame]) -> pd.DataFrame: """ Returns that normalised and unnormalised columns in value_counts() Useful when you want to know absoluoute number any percentage """ if isinstance(s, pd.Series): s = s.to_frame() df =...
3bb053499c42b0b70c6b11b52dadcc2725a36204
67,708