content
stringlengths
22
815k
id
int64
0
4.91M
def get_content_from_pub_json(pub, format): """Get text content based on a given format from a publication JSON. In the case of abstract, the content is returned from the JSON directly. For pdf, the content is returned as bytes that can be dumped into a file. For txt and xml, the text is processed ...
65,100
async def publish_output( reader: asyncio.StreamReader, socket: zmq.asyncio.Socket, message: Message, stream: Stream, tee: bool = False ) -> None: """Publish stream data to a ZMQ socket. Parameters ---------- reader: asyncio.StreamReader Source reader for providing data socket: zmq.asyn...
65,101
def getFromLongestMatchingKey(object, listOfKeys, caseInsensitive=True): """ Function to take an object and a list of keys and return the value of the longest matching key or None if no key matches. :param object: The object with the keys. :type object: dict :param listOfKeys: A list of keys to...
65,102
def get_subscribers(): """Get all global subs""" return _SUBSCRIBERS
65,103
def python_version_is_greater_or_equal(major, minor=0, micro=0): """Alias for `~json_indent.pyversion.python_version_is_at_least()`:py:func:.""" return python_version_is_at_least(major, minor, micro)
65,104
def parse_mimetype(mimetype): """Parses a MIME type into its components. :param str mimetype: MIME type :returns: 4 element tuple for MIME type, subtype, suffix and parameters :rtype: tuple Example: >>> parse_mimetype('text/html; charset=utf-8') ('text', 'html', '', {'charset': 'utf-8'}) ...
65,105
def generate_summary_movement_report( movement_detail_report: pd.DataFrame, ) -> pd.DataFrame: """ Aggregate by source time for period statistics. """ summary_movement_report = movement_detail_report.groupby("source_time")[ [ "transportation_units", "transportation_co...
65,106
def object_key(obj): """Generate a checksum for a nested object or list.""" key = sha1() if isinstance(obj, (list, set, tuple)): for o in obj: o = object_key(o) if o is not None: key.update(o) elif isinstance(obj, dict): for k, v in obj.items(): ...
65,107
def gfalternate_gotdataforgaps(data,data_alternate,alternate_info,mode="verbose"): """ Returns true if the alternate series has data where the composite series has gaps. """ return_code = True ind = numpy.where((numpy.ma.getmaskarray(data)==True)&(numpy.ma.getmaskarray(data_alternate)==False))[0] ...
65,108
def main(): """ The main function """ django.setup() finished_delete = False while finished_delete == False: the_device_name = raw_input("Enter device name to delete: ") try: device_to_delete = NetworkDevice.objects.get(device_name=the_device_name) print ...
65,109
def file_eq(expect_path, *args, **kwargs): """If actual is not expect_path, throw assertion with calling context. If `expect_path` ends in ``.json``, `pkjson` will be used. Otherwise, `expect_path` will be read as plain text. Same for `actual_path`. If `expect_path` ends with ``.jinja``, it will b...
65,110
def tf_gpu_library(deps = None, cuda_deps = None, copts = tf_copts(), **kwargs): """Generate a cc_library with a conditional set of CUDA dependencies. When the library is built with --config=cuda: - Both deps and cuda_deps are used as dependencies. - The cuda runtime is added as a dependency (if neces...
65,111
def key_type(key): """String identifying if the key is a 'name' or an 'ID', or '' for None. This is most useful when paired with key_id_or_name_as_string. Args: key: A datastore Key Returns: The type of the leaf identifier of the Key, 'ID', 'name', or ''. """ if key.id(): return 'ID' elif k...
65,112
def cvReadString(*args): """cvReadString(CvFileNode node, char default_value=None) -> char""" return _cv.cvReadString(*args)
65,113
def compare_graph_properties(graph_properties): """ This function takes a dataframe of graph properties. Each graph property is compared to other groups with the Mann-Whitney test. Takes a pandas dataframe of graph properties with the following columns: Network, Group, Network type, Conserved fract...
65,114
def _select_encoding(consumes, form=False): """ Given an OpenAPI 'consumes' list, return a single 'encoding' for CoreAPI. """ if form: preference = [ 'multipart/form-data', 'application/x-www-form-urlencoded', 'application/json' ] else: pre...
65,115
def execute_command(command: str, new_image: Image, threshold=True) -> Image: """ __author__ = "Trong Nguyen" Return a new image given a valid command, an image and if required, a threshold value. >>> execute_command("E", new_image, 10) """ functions = {"L": load, "S": sav...
65,116
def deep_getsizeof(o, ids): """Find the memory footprint of a Python object This is a recursive function that rills down a Python object graph like a dictionary holding nested ditionaries with lists of lists and tuples and sets. The sys.getsizeof function does a shallow size of only. It counts each ...
65,117
def previous_prime(x): """前一个质数""" if x <= 2: return None if x == 3: return 2 if x % 2 == 0: x -= 1 else: x -= 2 while True: if is_prime(x): return x else: x -= 2
65,118
def other_classes(nb_classes, class_ind): """ Heper function that returns a list of class indices without one class :param nb_classes: number of classes in total :param class_ind: the class index to be omitted :return: list of class indices without one class """ other_classes_list = list(ra...
65,119
def region_shear_bulk(cmap=plt.cm.Blues): """ Region plot for both eta/s and zeta/s. """ fig, axes = plt.subplots(ncols=2, figsize=figsize(1, .4)) for (name, legend), ax in zip( [('shear', 'upper left'), ('bulk', False)], axes ): _region(ax, name, legend=legend,...
65,120
def manage_frozen_objects(): """ Manage objects that have been frozen due to being unsuitable for preservation for time being """ return render_template( "tabs/manage_frozen_objects/manage_frozen_objects.html" )
65,121
def retrieve_datasets(source_path, countries_cities_dict, pollutants, years): """ Retrieve the selected EEA air pollution datasets from the local storage. The EEA datasets are csv files. Parameters ---------- source_path : str Local path in which the selected datasets are sear...
65,122
def get_gvf(data_list, num_classes): """ The Goodness of Variance Fit (GVF) is found by taking the difference between the squared deviations from the array mean (SDAM) and the squared deviations from the class means (SDCM), and dividing by the SDAM """ breaks = get_jenks_breaks(data_list, num_class...
65,123
def test_et_classification_permu(): """ Test basic extra trees classification :return: """ # TODO: set these up as fixtures x = numpy.arange(0, 8 * numpy.pi, 0.5) y1 = numpy.sqrt(x) c = rfcorr.extra_trees.get_pairwise_corr( numpy.vstack((sign_without_zero(x), sign_without_zero(y...
65,124
def main(): """ Main script function. Does the following: 1) Read the WeeBit dataset from files 2) Cleans the dataset 3) Undersamples level 4 class 4) Splits dataset into train and test sets 5) Saves train, test and whole dataset into CSV files. The file names are defined by TRAIN_SET_CS...
65,125
def init_capacities(edges, transactions, amount_sat, verbose=False): """Initialize capacity map for path search""" tx_targets = set(transactions["target"]) # init capacity dict keys = list(zip(edges["src"], edges["trg"])) is_trg = edges["trg"].apply(lambda x: x in tx_targets) # [current_cap, tot...
65,126
def train(net, dataloader, emb, caption, device, n_epoch=10, unfreeze_epoch=0, lr=1e-5, verbose=True, ignore_bg=False, floss=F.l1_loss): """ :param net: neural network to be trained :param dataloader: dataset :param emb: embedding system (see embeddings) :param caption: the name of fi...
65,127
def calculate_iou(gt, pr, form='pascal_voc') -> float: """Calculates the Intersection over Union. Args: gt: (np.ndarray[Union[int, float]]) coordinates of the ground-truth box pr: (np.ndarray[Union[int, float]]) coordinates of the prdected box form: (str) gt/pred coordinates format ...
65,128
def create_task(tenant_id='tenant_id'): """ Create a new task entry. POST format: { "name": "My New Task", "config": "\{\"task\": \"do something\"\}", "agent_url": "swift://region-a.geo-1/mycontainer/myagent.py", "email": "jeff.kramer@hp.com", "interval": "300", "start_at": "0" } """ if not identity_...
65,129
def interpolate(s: str, registers: Dict) -> str: """ Interpolates variables in a string with values from a supplied dictionary of registers. The parser is very lax and will not interpolate variables that don't exist, as users may not be intending to interpolate a variable when they type the hash charac...
65,130
def main(): """ 主函数 :return: """ with open(os.path.join(sys.path[0], "config.json"), "r") as fp: config = json.load(fp) arg_map = ArgumentsMap(sys.argv) filter_map = {k: set(v.split(",")) for k, v in arg_map.query_all().items() if k not in { "topic", "bootstrap_server...
65,131
def assert_allclose( actual: numpy.ndarray, desired: numpy.ndarray, atol: float, err_msg: Literal["TweedieRegressor"], ): """ usage.sklearn: 2 """ ...
65,132
def login(user=None, verified=False, admin=False, overrides=None, return_field=None): """ Logs in user and returns the User object. If a user object is not specified, one is randomly generated. The user object is force authenticated on the DRF API client. If the return_field is specified it returns the ...
65,133
def retrieve_from_any(ecli, rootpath=None): """ Checks if it can find the xml document in the filesystem, otherwise retrieves it from the web. :param ecli: :param rootpath: :return: xml element """ el = None if rootpath is not None: el = retrieve_xml_from_filesystem(ecli, r...
65,134
def defineNodePositions(smax,pmin,fun,nodegap,L=200.): """ Loop through sections and determine optimal placement of nodes in order to prevent vignetting/collisions """ #Loop through sections and construct node positions N = len(smax) rsec = [] rext = [] gap = L*3e-3+0.4 #.4 mm glass ...
65,135
def normalize_mi_ma(x, mi, ma, clip=True, eps=1e-20, dtype=np.float32): # dtype=np.float32 """This function is adapted from Martin Weigert""" if dtype is not None: x = x.astype(dtype, copy=False) mi = dtype(mi) if np.isscalar(mi) else mi.astype(dtype, copy=False) ma = dtype(ma) if np.is...
65,136
def mutliplier(images, n_times): """Generator expression to loop over the same batch of images n times""" # imgaug way of doing things seems to be placing image copies into RAM # or running with training batches. We, on the other hand, need to dump # the augmented images to RAM, but the library isn't v...
65,137
def read_image(img_path): """Keep reading image until succeed. This can avoid IOError incurred by heavy IO process.""" got_img = False while not got_img: try: img = Image.open(img_path).convert('RGB') got_img = True except IOError: print("IOEr...
65,138
def check_image_valid(im_source, im_search): """Check if the input images valid or not.""" if im_source is not None and im_source.any() and im_search is not None and im_search.any(): return True else: return False
65,139
def fabric_inband_net_create(module, inband_static_part): """ Method to create in-band network. :param module: The Ansible module to fetch input parameters. :param inband_static_part: It contains ip address of inband ip till third octet. :return: The output messages fo...
65,140
def pytest_addoption(parser): """ :param parser: :return: """ group = parser.getgroup('terminal reporting') group.addoption('--stats-d', action='store_true', help='send test results to graphite') group.addoption('--stats-host', action='store', dest='stats_host', ...
65,141
def create_match_apds_input_filenames(from_date, to_date, datestring): """ Create the list of filenames for match_apt_trajectories.py. """ return [create_flights_filename(CPR_FR24, datestring), create_apds_flights_filename(from_date, to_date), create_events_filename(CPR_FR24, datestring)...
65,142
def get_emoji_modifier_sequences(age=None): """Return map of modifier sequences to name, optionally limited to those <= the provided age.""" _load_emoji_sequence_data() return _age_map_select(_emoji_modifier_sequences, age)
65,143
def update_taxes_with_shipping_lines(taxes, shipping_lines, shopify_settings): """Shipping lines represents the shipping details, each such shipping detail consists of a list of tax_lines""" for shipping_charge in shipping_lines: if shipping_charge.get("price"): taxes.append({ "charge_type": _("Actual"), ...
65,144
def equal_accuracy(confusion_matrix_list: List[np.ndarray], tolerance: float = 0.2, label_index: int = 0) -> np.ndarray: """ Checks if accuracy difference of all grouping pairs is within tolerance. .. note:: This function expects a list of confusion matrices per...
65,145
def _remove_model_from_cache(model_id: str): """Deletes the given model_id from cache. Args: model_id (str): Unique id representing the model. """ if _is_model_in_cache(model_id): del model_cache[model_id]
65,146
def vm_snapshot_list_cb(result, task_id, vm_uuid=None, snap_ids=None): """ A callback function for DELETE api.vm.snapshot.views.vm_snapshot_list. """ snaps = Snapshot.objects.filter(id__in=snap_ids) action = result['meta']['apiview']['method'] if result['returncode'] == 0: vm = snaps[0]...
65,147
def test_get_ip_reputation_score(input_data, expected_output): """ Tests various combinations of GreyNoise classification data. """ response = GreyNoise.get_ip_reputation_score(input_data) assert response == expected_output
65,148
def fpart(x): """FRACTIONAL PART OF A REAL NUMBER""" if type(x) in [array, list]: if len(x) == 1: x = x[0] return math.modf(x)[0]
65,149
def get_mfp(path, recursive): """many,flat,prefix""" path = normalize_path(path) flat = not recursive many = recursive prefix = "" if path[-2:] == "**": many = True flat = False prefix = os.path.basename(path[:-2]) elif path[-1:] == "*": many = True flat = True prefix = os.path.bas...
65,150
def jobs(dataset, target_col, max_leave_n, exclude_cols=None): """ Returns an iterable of the args, kwargs for each job """ # First get the name of all features features = feature_names(dataset, target_col, exclude_cols=exclude_cols) n_features = len(features) for leave_n in range(max_leave_...
65,151
def BinomialNum(n, p): """Generate a binomially distributed random number with parameters n (int) and p (float)""" assert type(n) == int, "n must be an integer" assert n >= 1, "n must be greater than or equal to 1" assert 0 < p < 1, "p must be between 0 and 1, exclusive" return sum([BernoulliNum(p) for x in range(...
65,152
def graph_size_filter(graph, edge_weigths, node_sizes, min_size, node_labels=None, relabel=False): """ """ n_nodes = graph.numberOfNodes if node_labels is None: seeds = np.zeros(n_nodes, dtype='uint64') assert n_nodes == len(node_sizes) keep_nodes = node_si...
65,153
def create_or_update_virtualenvs(env_name, topology_name, options, virtualenv_name=None, requirements_paths=None, config_file=None, overwrite_virtualenv=False, user='root'): """Create or update virtualenvs on remote s...
65,154
def prepare_arguments_deps(parser): """Parse arguments that belong to this verb. Args: parser (argparser): Argument parser Returns: argparser: Parser that knows about our flags. """ parser.description = """ Manage dependencies for one or more packages in a catkin workspace....
65,155
def timer(name): """A context manager to emit start/stop events. Args: name: A name for the timer event. Yields: Context for context manager surrounding event emission. """ # Timer events use a |arg| to disambiguate in case of multiple concurrent or # overlapping timers with the same name. key =...
65,156
def bar(a: Optional[int], b: t.Optional[int]) -> int: """WHAT""" return (a or 42) + (b or 0)
65,157
def checkarrays(f): """ Similar to the @accepts decorator """ def new_f(*args, **kwd): assert reduce(lambda x, y: x == y, map(np.shape, args))\ , """Array and Subarray must have same dimensions, got %s and %s"""\ .replace(' ', '') % (args[0].shape, args[1].shape,) ...
65,158
def outlier_detection(X, scaling, method='MULTIVARIATE TRIMMING', trimming_threshold=0.5, quantile_threshold=0.9899, verbose=False): """ Finds outliers in the original data set, :math:`\mathbf{X}`, and returns indices of observations without outliers as well as indices of the outliers themselves. Two op...
65,159
def read_coverage(chrom, cov=10, length=249250621, path="data/exacv2.chr{chrom}.cov.txt.gz"): #length may need to be fixed in the future, if new chromosome lengths are established in GRCh38 #or data/Panel.chr{chrom}.coverage.txt.gz for exacv1 """ read ExAC coverage from a single chrom into a numpy array. If no ...
65,160
def list_to_mathutils(values: typing.List[float], data_path: str) -> typing.Union[Vector, Quaternion, Euler]: """Transform a list to blender py object.""" target = get_target_property_name(data_path) if target == 'delta_location': return Vector(values) # TODO Should be Vector(values) - Vector(some...
65,161
def count_smileys(arr): """count valid smileys from an array, better reading""" count = 0 eyes = ":;" noses = "-~" smiles = ")D" for i in arr: if len(list(i)) > 2: if i[0] in eyes and i[1] in noses and i[2] in smiles: count += 1 else: if i[0] in eyes and i[1] in...
65,162
def test_get_assets(assets_keys, symbol=None): """Test an API call to get assets' info """ response = client.get_assets(symbol) assert isinstance(response, dict) assert set(assets_keys).issubset(response.keys())
65,163
def apply_mlrun( model, context: mlrun.MLClientCtx = None, X_test=None, y_test=None, model_name=None, generate_test_set=True, **kwargs ): """ Wrap the given model with MLRun model, saving the model's attributes and methods while giving it mlrun's additional features. examples...
65,164
def process_file(filename,word_to_id,cat_to_id,max_length=600): """ Args: filename:train_filename or test_filename or val_filename word_to_id:get from def read_vocab() cat_to_id:get from def read_category() max_length:allow max length of sentence Returns: x_pad: sequence data from preprocessing sentence ...
65,165
def get_key_list(u_id: str, um_status: int) -> list: """ 获取某个用户保存的友盟keys :param u_id: :param um_status: :return: """ _filter: Q = Q(u_id=u_id) & Q(um_status=um_status) return list(UmKey.objects.filter(_filter).values())
65,166
def balanced_tree(ordered): """Create balanced binary tree from ordered collection""" bt = BinaryTree() add_range(bt, ordered, 0, len(ordered)-1) return bt
65,167
def loadLogs(path, store): """Load log data from a file and store it in a SQLite database. @param path: The path of the log file to parse. @param store: The SQLite database to store parsed results in. """ parser = LogParser() for i, item in enumerate(parser.parse(path)): store.add(item)...
65,168
def tf_split(x, num_or_size_splits, axis=0, num=None, keep_dims=False): """Split feature map of high dimension into list of feature map of low dimension.""" x_list = tf.split(x, num_or_size_splits, axis, num) if not keep_dims: x_list2 = [tf.squeeze(x_, axis) for x_ in x_list] return x_list2...
65,169
def stringify_edge_set(s: set): """ Convert an agent-piece graph into a string, for display and testing """ return str(sorted([(agent.name(), piece) for (agent,piece) in s]))
65,170
def test_valid_env_vars(env_vars): """ Verifies whether the environment variable-checker function is working as intended, by feeding it non-empty data. """ # here, if the check_env_vars function runs without any problems then that # means that all env vars have a value and that should be the ca...
65,171
def rholoc(A1: tn.Tensor, A2: tn.Tensor) -> tn.Tensor: """ -----A1-----A2----- | |(3) |(4) | | | | | | |(1) |(2) | -----A1*----A2*----- returned as a (1:2)x(3:4) matrix. Assuming the appropriate Schmidt vectors have been contracted into the As, np.trac...
65,172
def status(ctx): """Report if the daemon is running.""" ctx.parent.command.daemon.do_action("status")
65,173
def main(access_key, secret_key): """Main function for delete.py""" logger.info(' Running the delete.py script') # Global var global headers headers = { 'accept': "application/json", 'content-type': "application/json", 'x-apikeys': f"accessKey={access_key};secretKey={secre...
65,174
def _d(n, j, prec, sq23pi, sqrt8): """ Compute the sinh term in the outer sum of the HRR formula. The constants sqrt(2/3*pi) and sqrt(8) must be precomputed. """ j = from_int(j) pi = mpf_pi(prec) a = mpf_div(sq23pi, j, prec) b = mpf_sub(from_int(n), from_rational(1,24,prec), prec) c ...
65,175
def add_ext_grids_to_boundaries(net, boundary_buses, adapt_va_degree=False, calc_volt_angles=True, allow_net_change_for_convergence=False): """ adds ext_grids for the given network. If the bus results are available, ext_grids are created according to the given bus results; ...
65,176
def render_show_category_json(category_id): """ METHOD=GET. Returns a JSON object of a specific category """ category = session.query(Category).filter_by(id=category_id).one() items = session.query(Item).filter_by(category_id=category_id).all() if category and items: return jsonify(...
65,177
def get_fully_qualified_class_name(cls): """Returns fully dot-qualified path of a class, e.g. `ludwig.models.trainer.TrainerConfig` given `TrainerConfig`.""" return ".".join([cls.__module__, cls.__name__])
65,178
def set_completed_todo(todo_id): """The route handler setting a todo item to completed. Args: todo_id: A str representing the id of the todo item that was completed Returns: Response: A json object signalling the update request was successful """ error = False try: com...
65,179
def extARRAYPROC_ZIP(argu): """ allow processing the data using multicore capabilities This is a temporary method, as python cannot process using multicores within classes. So we have to call a method from within the class to run multicores. you provide a - ** parameters**, **types**, **return**, and ...
65,180
def convert_bytes(bytes: int, unit: str = "Mi") -> Union[str, int]: """Converts a number of bytes to a string representation. By default, the output is in MiB('Mi') format. If unit is 'b', the output would be an integer value. (e.g., convert_bytes(1024, 'b') -> 1024) Only one decimal point would b...
65,181
def global_settings(request): """ Expose various settings """ return { 'global_settings': { 'google_analytics_tracking_id': settings.GOOGLE_ANALYTICS_TRACKING_ID, 'IMIS_SSO_LOGIN_URL': settings.IMIS_SSO_LOGIN_URL, 'HELIX_LOGOUT_URL': settings.HELIX_LOGOUT_URL ...
65,182
def count_rfc_in_all_reports(): """iterates over all reports""" reports = [file for file in os.listdir(os.getcwd() + os.sep + "Raw IPCC Strings") if file[-4:] == ".csv" ] for report in reports: print("Starting with " + report) count_rfc(report)
65,183
def main(): """Our workflow""" pgconn = util.get_dbconn(rw=True) hourly(pgconn) daily(pgconn) cleanup(pgconn)
65,184
def remote_assert_empty(path): """ Assert that nothing exists at path in Dropbox. Raises: ValueError """ path = normpath(path) try: remote = get_remote(path) except ValueError: # Nothing exists at path, nothing to worry about. return raise ValueError("Something exists at...
65,185
def index(): """ The landing page of the site :return: Returns a rendering of the landing page. """ form = Transaction(request.form) return render_template("transaction.html", form=form)
65,186
def determine_flow_unit(stock_unit: str, time_unit: str = "h"): """For example: >>> determine_flow_unit("m³") # m³/h >>> determine_flow_unit("kWh") # kW """ flow = to_preferred(ur.Quantity(stock_unit) / ur.Quantity(time_unit)) return "{:~P}".format(flow.units)
65,187
def testfiles(): """Test all audio files""" import pyechonest.track for file in get_many_mp3(status=0): if file.track_details['length'] < 700: print("Name: {} Length: {}".format(file.filename, file.track_details['length'])) # TODO: Should this be pyechonest.track.track_from_filename? track = track.track_f...
65,188
def handle_hosts( actapi: act.api.Act, content: Text, hosts: List[Text] ) -> List[act.api.fact.Fact]: """handle the hosts part of a hybrid-analysis report""" feeds_facts: List[act.api.fact.Fact] = [] for host in hosts: (ip_type, ip) = act.api.helpers.ip_obj(host) chain = [] c...
65,189
def parsevROps(payload, alert): """ Parse vROps JSON from alert webhook. Returns a dict. """ if (not 'alertId' in payload): return alert alert.update({ "hookName": "vRealize Operations Manager", "AlertName": payload['alertName'] if ('alertName' in payload and payloa...
65,190
def as_chunks(l, num): """ :param list l: :param int num: Size of split :return: Split list :rtype: list """ chunks = [] for i in range(0, len(l), num): chunks.append(l[i:i + num]) return chunks
65,191
def extract_average_values_roc(nb_random_realizations, fpr_list, tpr_list, auc_values): """This function extracts the average values for the ROC curve across the random realizations Args: nb_random_realizations (int): number of cross-validation runs that were performed fpr_list (list...
65,192
def prepare_for_training(data, polynomial_degree=0, sinusoid_degree=0, normalize_data=True): """Prepare dataset for training on prediction.""" # Calculate the number of examples. num_examples = data.shape[0] # Prevent original data from being modified. data_processed = np.copy(data) # Normali...
65,193
def z_curvature_stacks(z_fit_params, z_contour_stack): """ Calculates curvature, normal, and tangent vectors of contours on a given image stack on z-slice Iteratively steps through z_fit_params and z_contour_stack and calls curvature_z_slice Parameters ---------- z_fit_params : list ...
65,194
def get_ec2_instance_ip(): """Try to obtain the IP address of the current EC2 instance in AWS""" try: ip = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4', timeout=0.01).text except requests.exceptions.ConnectionError: return None return ip
65,195
def e_greedy(options, e=0., reverse=False): """ Epsilon-greedy algorithm for selecting sampled bandits Parameters ---------- options : list list of the bandits samples e : float, default = 0 epsilon value between 0 and 1 that determines how random the chosen bandit is. e=0 fully gre...
65,196
def get_all_serialization_annotations( annotation: Annotation ) -> Tuple[Annotation, List[SerializationAnnotation]]: """Gets the type T of Annotation[T, SerializationAnnotation] Args: annotation (Any): The annotation Returns: Tuple[Annotation, List[SerializationAnnotation]]: The ty...
65,197
def c_start(update: Update, ctx: CallbackContext) -> None: """General info about the bot and command help.""" text = ( "Hello there! 👋🏻 " "I'm a bot that can help you write messages in cool looking, weird (and beautiful) unicode fonts!\n", "⚠️ Some devices may not support the custom fonts, so keep that in mi...
65,198
def rmWebhooks(repo): """Checks for and removes stale web hooks""" url = "https://api.github.com/repos/apache/%s/hooks?access_token=%s" % (repo, ORG_TOKEN) response = urllib2.urlopen(url) data = json.load(response) for hook in data: # Is this an old git-wip hook? if 'config' in hook ...
65,199