content
stringlengths
22
815k
id
int64
0
4.91M
def image_model_saver(image_model, model_type, output_directory, training_dict, labels1, labels2, preds, results1, results2): """ Saves Keras image model and other outputs image_model: Image model to be saved model_type (string): Name of model output_directory: Directory to folder to save file in training_dict: Dictionary of training and validation values labels1: List of multimodal labels for test set labels2: List of unimodal labels for test set preds: List of model predictions after passed through argmax() results1: Dictionary of metrics on multimodal labels results2: Dictionary of metrics on uniimodal labels tokenizer: Tokenizer to be saved. Defaulted to None. """ output_directory = os.path.join(output_directory, model_type) if not os.path.exists(output_directory): os.makedirs(output_directory) os.chdir(output_directory) np.save(model_type+"_dogwhistle_train_results.npy", training_dict) #save training dict np.save(model_type+"_dogwhistle_test_results_multimodal.npy", results1) #save test metrics np.save(model_type+"_dogwhistle_test_results_unimodal.npy", results2) #save test metrics test_predictions = pd.DataFrame([labels1, labels2, preds]) #save predictions and labels test_predictions = test_predictions.T test_predictions = test_predictions.rename(columns={0: 'Multimodal Labels', 1: 'Unimodal Labels', 2: 'Predictions'}) test_predictions.to_csv(model_type+"_dogwhistle_predictions.csv") image_model.save("image_model.h5") #save model return print("Saving complete.")
19,100
def predicted_orders( daily_order_summary: pd.DataFrame, order_forecast_model: Tuple[float, float] ) -> pd.DataFrame: """Predicted orders for the next 30 days based on the fit paramters""" a, b = order_forecast_model start_date = daily_order_summary.order_date.max() future_dates = pd.date_range(start=start_date, end=start_date + pd.DateOffset(days=30)) predicted_data = model_func(x=future_dates.astype(np.int64), a=a, b=b) return pd.DataFrame({"order_date": future_dates, "num_orders": predicted_data})
19,101
def _try_command_line(command_line): """Returns the output of a command line or an empty string on error.""" _logging.debug("Running command line: %s" % command_line) try: return subprocess.check_output(command_line, stderr=subprocess.STDOUT) except Exception as e: _print_process_error(command_line, e) return None
19,102
def eval_loop(model, ldr, device): """Runs the evaluation loop on the input data `ldr`. Args: model (torch.nn.Module): model to be evaluated ldr (torch.utils.data.DataLoader): evaluation data loader device (torch.device): device inference will be run on Returns: list: list of labels, predictions, and confidence levels for each example in the dataloader """ all_preds = []; all_labels = []; all_preds_dist=[] all_confidence = [] with torch.no_grad(): for batch in tqdm.tqdm(ldr): batch = list(batch) inputs, targets, inputs_lens, targets_lens = model.collate(*batch) inputs = inputs.to(device) probs, rnn_args = model(inputs, softmax=True) probs = probs.data.cpu().numpy() preds_confidence = [decode(p, beam_size=3, blank=model.blank)[0] for p in probs] preds = [x[0] for x in preds_confidence] confidence = [x[1] for x in preds_confidence] all_preds.extend(preds) all_confidence.extend(confidence) all_labels.extend(batch[1]) return list(zip(all_labels, all_preds, all_confidence))
19,103
def get_total_frts(): """ Get total number of FRTs for a single state. Arguments: Returns: {JSON} -- Returns headers of the columns and data in list """ query = """ SELECT place.state AS state , COUNT(DISTINCT frt.id) AS state_total FROM panoptic.place AS place LEFT JOIN panoptic.frt_place_link AS link ON place.id = link.place__key LEFT JOIN panoptic.frt AS frt ON link.frt__key = frt.id GROUP BY place.state """ headers, data = execute_select_query(query) results = [] while data: results.append(dict(zip(headers, data.pop()))) return results
19,104
def test_from_transform(): """Initialize from inverse of q0 via transform matrix""" q = Quat(q0.transform.transpose()) assert np.allclose(q.q[0], -0.26853582) assert np.allclose(q.q[1], 0.14487813) assert np.allclose(q.q[2], -0.12767944) assert np.allclose(q.q[3], 0.94371436) q = Quat(q0.transform) assert np.allclose(q.roll0, 30) assert np.allclose(q.ra0, 10) q1 = Quat(transform=q0.transform) assert np.all(q1.q == q.q)
19,105
def newton_sqrt(n: float, a: float) -> float: """Approximate sqrt(n) starting from a, using the Newton-Raphson method.""" r = within(0.00001, repeat_f(next_sqrt_approx(n), a)) return next(r)
19,106
def prismatic(xyz, rpy, axis, qi): """Returns the dual quaternion for a prismatic joint. """ # Joint origin rotation from RPY ZYX convention roll, pitch, yaw = rpy[0], rpy[1], rpy[2] # Origin rotation from RPY ZYX convention cr = cs.cos(roll/2.0) sr = cs.sin(roll/2.0) cp = cs.cos(pitch/2.0) sp = cs.sin(pitch/2.0) cy = cs.cos(yaw/2.0) sy = cs.sin(yaw/2.0) # The quaternion associated with the origin rotation # Note: quat = w + ix + jy + kz x_or = cy*sr*cp - sy*cr*sp y_or = cy*cr*sp + sy*sr*cp z_or = sy*cr*cp - cy*sr*sp w_or = cy*cr*cp + sy*sr*sp # Joint origin translation as a dual quaternion x_ot = 0.5*xyz[0]*w_or + 0.5*xyz[1]*z_or - 0.5*xyz[2]*y_or y_ot = - 0.5*xyz[0]*z_or + 0.5*xyz[1]*w_or + 0.5*xyz[2]*x_or z_ot = 0.5*xyz[0]*y_or - 0.5*xyz[1]*x_or + 0.5*xyz[2]*w_or w_ot = - 0.5*xyz[0]*x_or - 0.5*xyz[1]*y_or - 0.5*xyz[2]*z_or Q_o = [x_or, y_or, z_or, w_or, x_ot, y_ot, z_ot, w_ot] # Joint displacement orientation is just identity x_jr = 0.0 y_jr = 0.0 z_jr = 0.0 w_jr = 1.0 # Joint displacement translation along axis x_jt = qi*axis[0]/2.0 y_jt = qi*axis[1]/2.0 z_jt = qi*axis[2]/2.0 w_jt = 0.0 Q_j = [x_jr, y_jr, z_jr, w_jr, x_jt, y_jt, z_jt, w_jt] # Get resulting dual quaternion return product(Q_o, Q_j)
19,107
def markov_chain(bot_id, previous_posts): """ Caches are triplets of consecutive words from the source Beginning=True means the triplet was the beinning of a messaeg Starts with a random choice from the beginning caches Then makes random choices from the all_caches set, constructing a markov chain 'randomness' value determined by totalling the number of words that were chosen randomly """ bot = TwitterBot.objects.get(id=bot_id) beginning_caches = bot.twitterpostcache_set.filter(beginning=True) if not len(beginning_caches): print "Not enough data" return # Randomly choose one of the beginning caches to start with seed_index = random.randint(0, len(beginning_caches) - 1) seed_cache = beginning_caches[seed_index] # Start the chain new_markov_chain = [seed_cache.word1, seed_cache.word2] # Add words one by one to complete the markov chain all_caches = bot.twitterpostcache_set.all() next_cache = seed_cache while next_cache: new_markov_chain.append(next_cache.final_word) all_next_caches = all_caches.filter( word1=next_cache.word2, word2=next_cache.final_word ) if len(all_next_caches): next_cache = random.choice(all_next_caches) else: all_next_caches = all_caches.filter(word1=next_cache.final_word) if len(all_next_caches): next_cache = random.choice(all_next_caches) new_markov_chain.append(next_cache.word2) else: next_cache = None return " ".join(new_markov_chain)
19,108
def SurfaceNet_fn_trainVal(N_viewPairs4inference, default_lr, input_cube_size, D_viewPairFeature, \ num_hidden_units, CHANNEL_MEAN, return_train_fn=True, return_val_fn=True, with_weight=True): """ This function only defines the train_fn and the val_fn while training process. There are 2 training process: 1. only train the SurfaceNet without weight 2. train the softmaxWeight with(out) finetuning the SurfaceNet For the val_fn when only have validation, refer to the [TODO]. =================== >> SurfaceNet_fn_trainVal(with_weight = True) >> SurfaceNet_fn_trainVal(with_weight = False) """ train_fn = None val_fn = None tensor5D = T.TensorType('float32', (False,)*5) input_var = tensor5D('X') output_var = tensor5D('Y') similFeature_var = T.matrix('similFeature') net = __weightedAverage_net__(input_var, similFeature_var, input_cube_size, N_viewPairs4inference,\ D_viewPairFeature, num_hidden_units, with_weight) if return_val_fn: pred_fuse_val = lasagne.layers.get_output(net["output_fusionNet"], deterministic=True) # accuracy_val = lasagne.objectives.binary_accuracy(pred_fuse_val, output_var) # in case soft_gt accuracy_val = __weighted_accuracy__(pred_fuse_val, output_var) # fuseNet_val_fn = theano.function([input_var, output_var], [accuracy_val,pred_fuse_val]) val_fn_input_var_list = [input_var, similFeature_var, output_var] if with_weight\ else [input_var, output_var] val_fn_output_var_list = [accuracy_val,pred_fuse_val] if with_weight\ else [accuracy_val,pred_fuse_val] val_fn = theano.function(val_fn_input_var_list, val_fn_output_var_list) if return_train_fn: pred_fuse = lasagne.layers.get_output(net["output_fusionNet"]) output_softmaxWeights_var= lasagne.layers.get_output(net["output_softmaxWeights"]) if with_weight \ else None #loss = __weighted_MSE__(pred_fuse, output_var, w_for_1 = 0.98) \ loss = __weighted_mult_binary_crossentropy__(pred_fuse, output_var, w_for_1 = 0.96) \ + regularize_layer_params(net["output_fusionNet"],l2) * 1e-4 \ aggregated_loss = lasagne.objectives.aggregate(loss) if not params.__layer_range_tuple_2_update is None: updates = __updates__(net=net, cost=aggregated_loss, layer_range_tuple_2_update=params.__layer_range_tuple_2_update, \ default_lr=default_lr, update_algorithm='nesterov_momentum') else: params = lasagne.layers.get_all_params(net["output_fusionNet"], trainable=True) updates = lasagne.updates.nesterov_momentum(aggregated_loss, params, learning_rate=params.__lr) # accuracy = lasagne.objectives.binary_accuracy(pred_fuse, output_var) # in case soft_gt accuracy = __weighted_accuracy__(pred_fuse, output_var) train_fn_input_var_list = [input_var, similFeature_var, output_var] if with_weight \ else [input_var, output_var] train_fn_output_var_list = [loss,accuracy, pred_fuse, output_softmaxWeights_var] if with_weight \ else [loss,accuracy, pred_fuse] train_fn = theano.function(train_fn_input_var_list, train_fn_output_var_list, updates=updates) return net, train_fn, val_fn
19,109
def test_bandpass_image(): """Cube class: testing bandpass_image""" shape = (7, 2, 2) # Create a rectangular shaped bandpass response whose ends are half # way into pixels. wavelengths = np.array([1.0, 2.0, 3.0, 4.0, 5.0]) sensitivities = np.array([1.0, 1.0, 1.0, 1.0, 1.0]) # Specify a ramp for the values of the pixels in the cube versus # wavelength. spectral_values = np.arange(shape[0], dtype=float) # Specify a ramp for the variances of the pixels in the cube # versus wavelength. spectral_vars = np.arange(shape[0], dtype=float) * 0.5 # Calculate the expected weights versus wavelength for each # spectral pixels. The weight of each pixel is supposed to be # integral of the sensitivity function over the width of the pixel. # # | 0 | 1 | 2 | 3 | 4 | 5 | 6 | Pixel indexes # _______________________ # _______| |_________ Sensitivities # # 0.0 0.5 1.0 1.0 1.0 0.5 0.0 Weights # 0.0 1.0 2.0 3.0 4.0 5.0 6.0 Pixel values vs wavelength # 0.0 0.5 2.0 3.0 4.0 2.5 0.0 Pixel values * weights weights = np.array([0.0, 0.5, 1.0, 1.0, 1.0, 0.5, 0.0]) # Compute the expected weighted mean of the spectral pixel values, # assuming that no pixels are unmasked. unmasked_mean = (weights * spectral_values).sum() / weights.sum() # Compute the expected weighted mean if pixel 1 is masked. masked_pixel = 1 masked_mean = (((weights * spectral_values).sum() - weights[masked_pixel] * spectral_values[masked_pixel]) / (weights.sum() - weights[masked_pixel])) # Compute the expected variances of the unmasked and masked means. unmasked_var = (weights**2 * spectral_vars).sum() / weights.sum()**2 masked_var = (((weights**2 * spectral_vars).sum() - weights[masked_pixel]**2 * spectral_vars[masked_pixel]) / (weights.sum() - weights[masked_pixel])**2) # Create the data array of the cube, giving all map pixels the # same data and variance spectrums. data = spectral_values[:, np.newaxis, np.newaxis] * np.ones(shape) var = spectral_vars[:, np.newaxis, np.newaxis] * np.ones(shape) # Create a mask with all pixels unmasked. mask = np.zeros(shape) # Mask spectral pixel 'masked_pixel' of map index 1,1. mask[masked_pixel, 1, 1] = True # Also mask all pixels of map pixel 0,0. mask[:, 0, 0] = True # Create a test cube with the above data and mask arrays. c = generate_cube(shape=shape, data=data, mask=mask, var=var, wave=WaveCoord(crval=0.0, cdelt=1.0, crpix=1.0, cunit=u.angstrom)) # Extract an image that has the above bandpass response. im = c.bandpass_image(wavelengths, sensitivities) # Only the map pixel in which all spectral pixels are masked should # be masked in the output, so just map pixel [0,0] should be masked. expected_mask = np.array([[True, False], [False, False]], dtype=bool) # What do we expect? expected_data = ma.array( data=[[unmasked_mean, unmasked_mean], [unmasked_mean, masked_mean]], mask=expected_mask) expected_var = ma.array( data=[[unmasked_var, unmasked_var], [unmasked_var, masked_var]], mask=expected_mask) # Are the results consistent with the predicted values? assert_masked_allclose(im.data, expected_data) assert_masked_allclose(im.var, expected_var)
19,110
def _assign_data_radial(root, sweep="sweep_1"): """Assign from CfRadial1 data structure. Parameters ---------- root : xarray.Dataset Dataset of CfRadial1 file sweep : str, optional Sweep name to extract, default to first sweep. If None, all sweeps are extracted into a list. """ var = root.variables.keys() remove_root = var ^ root_vars remove_root &= var root1 = root.drop_vars(remove_root).rename({"fixed_angle": "sweep_fixed_angle"}) sweep_group_name = [] for i in range(root1.dims["sweep"]): sweep_group_name.append(f"sweep_{i + 1}") # keep all vars for now # keep_vars = sweep_vars1 | sweep_vars2 | sweep_vars3 # remove_vars = var ^ keep_vars # remove_vars &= var remove_vars = {} data = root.drop_vars(remove_vars) data.attrs = {} start_idx = data.sweep_start_ray_index.values end_idx = data.sweep_end_ray_index.values data = data.drop_vars({"sweep_start_ray_index", "sweep_end_ray_index"}) sweeps = [] for i, sw in enumerate(sweep_group_name): if sweep is not None and sweep != sw: continue tslice = slice(start_idx[i], end_idx[i] + 1) ds = data.isel(time=tslice, sweep=slice(i, i + 1)).squeeze("sweep") ds.sweep_mode.load() sweep_mode = ds.sweep_mode.item().decode() dim0 = "elevation" if sweep_mode == "rhi" else "azimuth" ds = ds.swap_dims({"time": dim0}) ds = ds.rename({"time": "rtime"}) ds.attrs["fixed_angle"] = np.round(ds.fixed_angle.item(), decimals=1) time = ds.rtime[0].reset_coords(drop=True) # get and delete "comment" attribute for time variable key = [key for key in time.attrs.keys() if "comment" in key] for k in key: del time.attrs[k] coords = { "longitude": root1.longitude, "latitude": root1.latitude, "altitude": root1.altitude, "azimuth": ds.azimuth, "elevation": ds.elevation, "sweep_mode": sweep_mode, "time": time, } ds = ds.assign_coords(**coords) sweeps.append(ds) return sweeps
19,111
def get_memory_usage(): """This method returns the percentage of total memory used in this machine""" stats = get_memstats() mfree = float(stats['buffers']+stats['cached']+stats['free']) return 1-(mfree/stats['total'])
19,112
def gamma0(R, reg=1e-13, symmetrize=True): """Integrals over the edges of a triangle called gamma_0 (line charge potentials). **NOTE: MAY NOT BE VERY PRECISE FOR POINTS DIRECTLY AT TRIANGLE EDGES.** Parameters ---------- R : (N, 3, 3) array of points (Neval, Nverts, xyz) Returns ------- res: array (Neval, Nverts) The analytic integrals for each vertex/edge """ edges = np.roll(R[0], 1, -2) - np.roll(R[0], 2, -2) # dotprods1 = np.sum(np.roll(R, 1, -2)*edges, axis=-1) # dotprods2 = np.sum(np.roll(R, 2, -2)*edges, axis=-1) dotprods1 = np.einsum("...i,...i", np.roll(R, 1, -2), edges) dotprods2 = np.einsum("...i,...i", np.roll(R, 2, -2), edges) en = norm(edges) del edges n = norm(R) # Regularize s.t. neither the denominator or the numerator can be zero # Avoid numerical issues directly at the edge nn1 = np.roll(n, 2, -1) * en nn2 = np.roll(n, 1, -1) * en res = np.log((nn1 + dotprods2 + reg) / (nn2 + dotprods1 + reg)) # Symmetrize the result since on the negative extension of the edge # there's division of two small values resulting numerical instabilities # (also incompatible with adding the reg value) if symmetrize: res2 = -np.log((nn1 - dotprods2 + reg) / (nn2 - dotprods1 + reg)) res = np.where(dotprods1 + dotprods2 > 0, res, res2) res /= en return -res
19,113
def is_even(x): """ True if obj is even. """ return (x % 2) == 0
19,114
def get_http_proxy(): """ Get http_proxy and https_proxy from environment variables. Username and password is not supported now. """ host = conf.get_httpproxy_host() port = conf.get_httpproxy_port() return host, port
19,115
def get_parser_udf( structural=True, # structural information blacklist=["style", "script"], # ignore tag types, default: style, script flatten=["span", "br"], # flatten tag types, default: span, br language="en", lingual=True, # lingual information lingual_parser=None, strip=True, replacements=[("[\u2010\u2011\u2012\u2013\u2014\u2212]", "-")], tabular=True, # tabular information visual=False, # visual information visual_parser=None, ): """Return an instance of ParserUDF.""" parser_udf = ParserUDF( structural=structural, blacklist=blacklist, flatten=flatten, lingual=lingual, lingual_parser=lingual_parser, strip=strip, replacements=replacements, tabular=tabular, visual=visual, visual_parser=visual_parser, language=language, ) return parser_udf
19,116
def img_preprocess2(image, target_shape,bboxes=None, correct_box=False): """ RGB转换 -> resize(resize不改变原图的高宽比) -> normalize 并可以选择是否校正bbox :param image_org: 要处理的图像 :param target_shape: 对图像处理后,期望得到的图像shape,存储格式为(h, w) :return: 处理之后的图像,shape为target_shape """ h_target, w_target = target_shape h_org, w_org, _ = image.shape image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32) resize_ratio = min(1.0 * w_target / w_org, 1.0 * h_target / h_org) resize_w = int(resize_ratio * w_org) resize_h = int(resize_ratio * h_org) image_resized = cv2.resize(image, (resize_w, resize_h)) image_paded = np.full((h_target, w_target, 3), 128.0) dw = int((w_target - resize_w) / 2) dh = int((h_target - resize_h) / 2) image_paded[dh:resize_h+dh, dw:resize_w+dw,:] = image_resized image = image_paded / 255.0 image = normalize(image) if correct_box: bboxes[:, [0, 2]] = bboxes[:, [0, 2]] * resize_ratio + dw bboxes[:, [1, 3]] = bboxes[:, [1, 3]] * resize_ratio + dh return image, bboxes return image,resize_ratio,dw,dh
19,117
def pivot_timeseries(df, var_name, timezone=None): """ Pivot timeseries DataFrame and shift UTC by given timezone offset Parameters ---------- df : pandas.DataFrame Timeseries DataFrame to be pivoted with year, month, hour columns var_name : str Name for new column describing data timezone : int, optional UTC offset to apply to DatetimeIndex, by default None Returns ------- pandas.DataFrame Seaborn style long table with source, year, month, hour columns """ sns_df = [] for name, col in df.iteritems(): col = col.to_frame() col.columns = [var_name] col['source'] = name col['year'] = col.index.year col['month'] = col.index.month col['hour'] = col.index.hour if timezone is not None: td = pd.to_timedelta('{:}h'.format(timezone)) col['local_hour'] = (col.index + td).hour sns_df.append(col) return pd.concat(sns_df)
19,118
def _preprocess_stored_query(query_text, config): """Inject some default code into each stored query.""" ws_id_text = " LET ws_ids = @ws_ids " if 'ws_ids' in query_text else "" return '\n'.join([ config.get('query_prefix', ''), ws_id_text, query_text ])
19,119
def handler_request_exception(response: Response): """ Args: response (Response): """ status_code = response.status_code data = response.json() if "details" in data and len(data.get("details")) > 0: data = data.get("details")[0] kwargs = { "error_code": data.get("error_code") or data.get("error") or str(data.get("status_code")), "description": data.get("description_detail") or data.get("description") or data.get("error_description") or data.get("message"), "response": response, } message = "{} {} ({})".format( kwargs.get("error_code"), kwargs.get("description"), response.url, ) if status_code == 400: return errors.BadRequest(message, **kwargs) elif status_code == 402: return errors.BusinessError(message, **kwargs) elif status_code == 404: return errors.NotFound(message, **kwargs) elif status_code == 500: return errors.ServerError(message, **kwargs) elif status_code == 503: return errors.ServiceUnavailable(message, **kwargs) elif status_code == 504: return errors.GatewayTimeout(message, **kwargs) else: return errors.RequestError(message, **kwargs)
19,120
def n_real_inputs(): """This gives the number of 'real' inputs. This is determined by trimming away inputs that have no connection to the logic. This is done by the ABC alias 'trm', which changes the current circuit. In some applications we do not want to change the circuit, but just to know how may inputs would go away if we did this. So the current circuit is saved and then restored afterwards.""" ## abc('w %s_savetempreal.aig; logic; trim; st ;addpi'%f_name) abc('w %s_savetempreal.aig'%f_name) with redirect.redirect( redirect.null_file, sys.stdout ): ## with redirect.redirect( redirect.null_file, sys.stderr ): reparam() n = n_pis() abc('r %s_savetempreal.aig'%f_name) return n
19,121
def get_stats_for_dictionary_file(dictionary_path): """Calculate size of manual and recommended sections of given dictionary.""" if not dictionary_path or not os.path.exists(dictionary_path): return 0, 0 dictionary_content = utils.read_data_from_file( dictionary_path, eval_data=False) dictionaries = dictionary_content.split(RECOMMENDED_DICTIONARY_HEADER) # If there are any elements before RECOMMENDED_DICTIONARY_HEADER, those are # from "manual" dictionary stored in the repository. manual_dictionary_size = get_dictionary_size(dictionaries[0]) if len(dictionaries) < 2: return manual_dictionary_size, 0 # Any elements after RECOMMENDED_DICTIONARY_HEADER are recommended dictionary. recommended_dictionary_size = get_dictionary_size(dictionaries[1]) return manual_dictionary_size, recommended_dictionary_size
19,122
def log_speed(speed_logs, message): """Measures and logs the duration of a context. Parameters ---------- speed_logs : list of str Text logs regarding processing speed. message : str A log message, which will be processed using ``string.format()`` with the duration of a context as the only parameter. """ start_time = time() yield stop_time = time() duration = stop_time - start_time speed_log = message.format(duration) speed_logs.append(speed_log) LOGGER.info(speed_log)
19,123
def delete_bucket_tagging(Bucket=None): """ Deletes the tags from the bucket. To use this operation, you must have permission to perform the s3:PutBucketTagging action. By default, the bucket owner has this permission and can grant this permission to others. The following operations are related to DeleteBucketTagging : See also: AWS API Documentation Examples The following example deletes bucket tags. Expected Output: :example: response = client.delete_bucket_tagging( Bucket='string' ) :type Bucket: string :param Bucket: [REQUIRED]\nThe bucket that has the tag set to be removed.\n :return: response = client.delete_bucket_tagging( Bucket='examplebucket', ) print(response) """ pass
19,124
def mlrPredict(W, data): """ mlrObjFunction predicts the label of data given the data and parameter W of Logistic Regression Input: W: the matrix of weight of size (D + 1) x 10. Each column is the weight vector of a Logistic Regression classifier. X: the data matrix of size N x D Output: label: vector of size N x 1 representing the predicted label of corresponding feature vector given in data matrix """ label = np.zeros((data.shape[0], 1)) ################## # YOUR CODE HERE # ################## # HINT: Do not forget to add the bias term to your input data """ Add the bias term at the beginning """ n_data = data.shape[0] bias = np.ones((n_data,1)) """ Concatenate the bias to the training data """ data = np.concatenate( (bias,data),axis=1) outputs = np.zeros([n_data,W.shape[1]],dtype=float) outputs = np.dot(data,W) #print (outputs[0]) i = 0 for i in range(n_data): label[i][0] = np.argmax(outputs[i],axis=0) return label
19,125
def create_app(): """Create Flask application.""" app = Flask(__name__, instance_relative_config=False) from .error_pages import add_error_pages app = add_error_pages(app) app.config.from_object("config") with app.app_context(): from .global_variables import init_global init_global() # # Import parts of our application from .home import home_page from .rules import rule_page from .create_game import create_game_page, root_url_games from .global_stats import global_stats_page, page_url from .utils.add_dash_table import add_dash as add_dash_table from .utils.add_dash_games import add_dash_games from .admin import admin_page bootstrap = Bootstrap() app.register_blueprint(home_page) Markdown(app) app.register_blueprint(rule_page) app.register_blueprint(create_game_page) app.register_blueprint(global_stats_page) bootstrap.init_app(app) app = add_dash_table(app, page_url) app = add_dash_games(app, root_url_games) app.register_blueprint(admin_page) return app
19,126
def process_integration(request, case_id): """Method to process case.""" try: case = OVCBasicCRS.objects.get(case_id=case_id, is_void=False) county_code = int(case.county) const_code = int(case.constituency) county_id, const_id = 0, 0 crs_id = str(case_id).replace('-', '') user_counties, user_geos = get_person_geo(request) # Get person orgs ou_ids = get_person_orgs(request) if request.method == 'POST': response = handle_integration(request, case, case_id) print(response) check_fields = ['sex_id', 'case_category_id', 'case_reporter_id', 'family_status_id', 'household_economics', 'risk_level_id', 'mental_condition_id', 'perpetrator_status_id', 'other_condition_id', 'physical_condition_id', 'yesno_id'] vals = get_dict(field_name=check_fields) category = OVCBasicCategory.objects.filter( case_id=case_id, is_void=False) person = OVCBasicPerson.objects.filter(case_id=case_id, is_void=False) # Attached Geos and Org Units for the user # ou_ids = [] org_id = request.session.get('ou_primary', 0) ou_ids.append(org_id) ou_attached = request.session.get('ou_attached', 0) user_level = request.session.get('user_level', 0) user_type = request.session.get('user_type', 0) print(org_id, ou_attached, user_level, user_type) # person_id = request.user.reg_person_id county = SetupGeography.objects.filter( area_code=county_code, area_type_id='GPRV') for c in county: county_id = c.area_id # Get constituency constituency = SetupGeography.objects.filter( area_code=const_code, area_type_id='GDIS') for c in constituency: const_id = c.area_id ous = RegOrgUnit.objects.filter(is_void=False) counties = SetupGeography.objects.filter(area_type_id='GPRV') if user_counties: counties = counties.filter(area_id__in=user_counties) if request.user.is_superuser: all_ou_ids = ['TNGD'] ous = ous.filter(org_unit_type_id__in=all_ou_ids) geos = SetupGeography.objects.filter( area_type_id='GDIS', parent_area_id=county_id) else: ous = ous.filter(id__in=ou_ids) geos = SetupGeography.objects.filter( area_type_id='GDIS', parent_area_id=county_id) return render(request, 'management/integration_process.html', {'form': {}, 'case': case, 'vals': vals, 'category': category, 'person': person, 'geos': geos, 'ous': ous, 'counties': counties, 'county_id': county_id, 'const_id': const_id, 'crs_id': crs_id}) except Exception as e: print('Error processing integration - %s' % (e)) else: pass
19,127
def get_aabb(pts): """axis-aligned minimum bounding box""" x, y = np.floor(pts.min(axis=0)).astype(int) w, h = np.ceil(pts.ptp(axis=0)).astype(int) return x, y, w, h
19,128
def _solve(f, *symbols, **flags): """Return a checked solution for f in terms of one or more of the symbols. A list should be returned except for the case when a linear undetermined-coefficients equation is encountered (in which case a dictionary is returned). If no method is implemented to solve the equation, a NotImplementedError will be raised. In the case that conversion of an expression to a Poly gives None a ValueError will be raised.""" not_impl_msg = "No algorithms are implemented to solve equation %s" if len(symbols) != 1: soln = None free = f.free_symbols ex = free - set(symbols) if len(ex) != 1: ind, dep = f.as_independent(*symbols) ex = ind.free_symbols & dep.free_symbols if len(ex) == 1: ex = ex.pop() try: # soln may come back as dict, list of dicts or tuples, or # tuple of symbol list and set of solution tuples soln = solve_undetermined_coeffs(f, symbols, ex, **flags) except NotImplementedError: pass if soln: if flags.get('simplify', True): if isinstance(soln, dict): for k in soln: soln[k] = simplify(soln[k]) elif isinstance(soln, list): if isinstance(soln[0], dict): for d in soln: for k in d: d[k] = simplify(d[k]) elif isinstance(soln[0], tuple): soln = [tuple(simplify(i) for i in j) for j in soln] else: raise TypeError('unrecognized args in list') elif isinstance(soln, tuple): sym, sols = soln soln = sym, {tuple(simplify(i) for i in j) for j in sols} else: raise TypeError('unrecognized solution type') return soln # find first successful solution failed = [] got_s = set([]) result = [] for s in symbols: xi, v = solve_linear(f, symbols=[s]) if xi == s: # no need to check but we should simplify if desired if flags.get('simplify', True): v = simplify(v) vfree = v.free_symbols if got_s and any([ss in vfree for ss in got_s]): # sol depends on previously solved symbols: discard it continue got_s.add(xi) result.append({xi: v}) elif xi: # there might be a non-linear solution if xi is not 0 failed.append(s) if not failed: return result for s in failed: try: soln = _solve(f, s, **flags) for sol in soln: if got_s and any([ss in sol.free_symbols for ss in got_s]): # sol depends on previously solved symbols: discard it continue got_s.add(s) result.append({s: sol}) except NotImplementedError: continue if got_s: return result else: raise NotImplementedError(not_impl_msg % f) symbol = symbols[0] # /!\ capture this flag then set it to False so that no checking in # recursive calls will be done; only the final answer is checked flags['check'] = checkdens = check = flags.pop('check', True) # build up solutions if f is a Mul if f.is_Mul: result = set() for m in f.args: if m in set([S.NegativeInfinity, S.ComplexInfinity, S.Infinity]): result = set() break soln = _solve(m, symbol, **flags) result.update(set(soln)) result = list(result) if check: # all solutions have been checked but now we must # check that the solutions do not set denominators # in any factor to zero dens = flags.get('_denominators', _simple_dens(f, symbols)) result = [s for s in result if all(not checksol(den, {symbol: s}, **flags) for den in dens)] # set flags for quick exit at end; solutions for each # factor were already checked and simplified check = False flags['simplify'] = False elif f.is_Piecewise: result = set() for i, (expr, cond) in enumerate(f.args): if expr.is_zero: raise NotImplementedError( 'solve cannot represent interval solutions') candidates = _solve(expr, symbol, **flags) # the explicit condition for this expr is the current cond # and none of the previous conditions args = [~c for _, c in f.args[:i]] + [cond] cond = And(*args) for candidate in candidates: if candidate in result: # an unconditional value was already there continue try: v = cond.subs(symbol, candidate) _eval_simpify = getattr(v, '_eval_simpify', None) if _eval_simpify is not None: # unconditionally take the simpification of v v = _eval_simpify(ratio=2, measure=lambda x: 1) except TypeError: # incompatible type with condition(s) continue if v == False: continue result.add(Piecewise( (candidate, v), (S.NaN, True))) # set flags for quick exit at end; solutions for each # piece were already checked and simplified check = False flags['simplify'] = False else: # first see if it really depends on symbol and whether there # is only a linear solution f_num, sol = solve_linear(f, symbols=symbols) if f_num is S.Zero or sol is S.NaN: return [] elif f_num.is_Symbol: # no need to check but simplify if desired if flags.get('simplify', True): sol = simplify(sol) return [sol] result = False # no solution was obtained msg = '' # there is no failure message # Poly is generally robust enough to convert anything to # a polynomial and tell us the different generators that it # contains, so we will inspect the generators identified by # polys to figure out what to do. # try to identify a single generator that will allow us to solve this # as a polynomial, followed (perhaps) by a change of variables if the # generator is not a symbol try: poly = Poly(f_num) if poly is None: raise ValueError('could not convert %s to Poly' % f_num) except GeneratorsNeeded: simplified_f = simplify(f_num) if simplified_f != f_num: return _solve(simplified_f, symbol, **flags) raise ValueError('expression appears to be a constant') gens = [g for g in poly.gens if g.has(symbol)] def _as_base_q(x): """Return (b**e, q) for x = b**(p*e/q) where p/q is the leading Rational of the exponent of x, e.g. exp(-2*x/3) -> (exp(x), 3) """ b, e = x.as_base_exp() if e.is_Rational: return b, e.q if not e.is_Mul: return x, 1 c, ee = e.as_coeff_Mul() if c.is_Rational and c is not S.One: # c could be a Float return b**ee, c.q return x, 1 if len(gens) > 1: # If there is more than one generator, it could be that the # generators have the same base but different powers, e.g. # >>> Poly(exp(x) + 1/exp(x)) # Poly(exp(-x) + exp(x), exp(-x), exp(x), domain='ZZ') # # If unrad was not disabled then there should be no rational # exponents appearing as in # >>> Poly(sqrt(x) + sqrt(sqrt(x))) # Poly(sqrt(x) + x**(1/4), sqrt(x), x**(1/4), domain='ZZ') bases, qs = list(zip(*[_as_base_q(g) for g in gens])) bases = set(bases) if len(bases) > 1 or not all(q == 1 for q in qs): funcs = set(b for b in bases if b.is_Function) trig = set([_ for _ in funcs if isinstance(_, TrigonometricFunction)]) other = funcs - trig if not other and len(funcs.intersection(trig)) > 1: newf = TR1(f_num).rewrite(tan) if newf != f_num: # don't check the rewritten form --check # solutions in the un-rewritten form below flags['check'] = False result = _solve(newf, symbol, **flags) flags['check'] = check # just a simple case - see if replacement of single function # clears all symbol-dependent functions, e.g. # log(x) - log(log(x) - 1) - 3 can be solved even though it has # two generators. if result is False and funcs: funcs = list(ordered(funcs)) # put shallowest function first f1 = funcs[0] t = Dummy('t') # perform the substitution ftry = f_num.subs(f1, t) # if no Functions left, we can proceed with usual solve if not ftry.has(symbol): cv_sols = _solve(ftry, t, **flags) cv_inv = _solve(t - f1, symbol, **flags)[0] sols = list() for sol in cv_sols: sols.append(cv_inv.subs(t, sol)) result = list(ordered(sols)) if result is False: msg = 'multiple generators %s' % gens else: # e.g. case where gens are exp(x), exp(-x) u = bases.pop() t = Dummy('t') inv = _solve(u - t, symbol, **flags) if isinstance(u, (Pow, exp)): # this will be resolved by factor in _tsolve but we might # as well try a simple expansion here to get things in # order so something like the following will work now without # having to factor: # # >>> eq = (exp(I*(-x-2))+exp(I*(x+2))) # >>> eq.subs(exp(x),y) # fails # exp(I*(-x - 2)) + exp(I*(x + 2)) # >>> eq.expand().subs(exp(x),y) # works # y**I*exp(2*I) + y**(-I)*exp(-2*I) def _expand(p): b, e = p.as_base_exp() e = expand_mul(e) return expand_power_exp(b**e) ftry = f_num.replace( lambda w: w.is_Pow or isinstance(w, exp), _expand).subs(u, t) if not ftry.has(symbol): soln = _solve(ftry, t, **flags) sols = list() for sol in soln: for i in inv: sols.append(i.subs(t, sol)) result = list(ordered(sols)) elif len(gens) == 1: # There is only one generator that we are interested in, but # there may have been more than one generator identified by # polys (e.g. for symbols other than the one we are interested # in) so recast the poly in terms of our generator of interest. # Also use composite=True with f_num since Poly won't update # poly as documented in issue 8810. poly = Poly(f_num, gens[0], composite=True) # if we aren't on the tsolve-pass, use roots if not flags.pop('tsolve', False): soln = None deg = poly.degree() flags['tsolve'] = True solvers = {k: flags.get(k, True) for k in ('cubics', 'quartics', 'quintics')} soln = roots(poly, **solvers) if sum(soln.values()) < deg: # e.g. roots(32*x**5 + 400*x**4 + 2032*x**3 + # 5000*x**2 + 6250*x + 3189) -> {} # so all_roots is used and RootOf instances are # returned *unless* the system is multivariate # or high-order EX domain. try: soln = poly.all_roots() except NotImplementedError: if not flags.get('incomplete', True): raise NotImplementedError( filldedent(''' Neither high-order multivariate polynomials nor sorting of EX-domain polynomials is supported. If you want to see any results, pass keyword incomplete=True to solve; to see numerical values of roots for univariate expressions, use nroots. ''')) else: pass else: soln = list(soln.keys()) if soln is not None: u = poly.gen if u != symbol: try: t = Dummy('t') iv = _solve(u - t, symbol, **flags) soln = list(ordered({i.subs(t, s) for i in iv for s in soln})) except NotImplementedError: # perhaps _tsolve can handle f_num soln = None else: check = False # only dens need to be checked if soln is not None: if len(soln) > 2: # if the flag wasn't set then unset it since high-order # results are quite long. Perhaps one could base this # decision on a certain critical length of the # roots. In addition, wester test M2 has an expression # whose roots can be shown to be real with the # unsimplified form of the solution whereas only one of # the simplified forms appears to be real. flags['simplify'] = flags.get('simplify', False) result = soln # fallback if above fails # ----------------------- if result is False: # try unrad if flags.pop('_unrad', True): try: u = unrad(f_num, symbol) except (ValueError, NotImplementedError): u = False if u: eq, cov = u if cov: isym, ieq = cov inv = _solve(ieq, symbol, **flags)[0] rv = {inv.subs(isym, xi) for xi in _solve(eq, isym, **flags)} else: try: rv = set(_solve(eq, symbol, **flags)) except NotImplementedError: rv = None if rv is not None: result = list(ordered(rv)) # if the flag wasn't set then unset it since unrad results # can be quite long or of very high order flags['simplify'] = flags.get('simplify', False) else: pass # for coverage # try _tsolve if result is False: flags.pop('tsolve', None) # allow tsolve to be used on next pass try: soln = _tsolve(f_num, symbol, **flags) if soln is not None: result = soln except PolynomialError: pass # ----------- end of fallback ---------------------------- if result is False: raise NotImplementedError('\n'.join([msg, not_impl_msg % f])) if flags.get('simplify', True): result = list(map(simplify, result)) # we just simplified the solution so we now set the flag to # False so the simplification doesn't happen again in checksol() flags['simplify'] = False if checkdens: # reject any result that makes any denom. affirmatively 0; # if in doubt, keep it dens = _simple_dens(f, symbols) result = [s for s in result if all(not checksol(d, {symbol: s}, **flags) for d in dens)] if check: # keep only results if the check is not False result = [r for r in result if checksol(f_num, {symbol: r}, **flags) is not False] return result
19,129
def get_object_ratio(obj): """Calculate the ratio of the object's size in comparison to the whole image :param obj: the binarized object image :type obj: numpy.ndarray :returns: float -- the ratio """ return numpy.count_nonzero(obj) / float(obj.size)
19,130
def get_region(ds, region): """ Return a region from a provided DataArray or Dataset Parameters ---------- region_mask: xarray DataArray or list Boolean mask of the region to keep """ return ds.where(region, drop=True)
19,131
def read_borehole_file(path, fix_df=True): """Returns the df with the depths for each borehole in one single row instead instead being each chunck a new row""" df = pd.read_table(path, skiprows=41, header=None, sep='\t', ) df.rename(columns={1: 'x', 2: 'y', 3: 'name', 4: 'num', 5: 'z', 6: 'year', 10: 'altitude'}, inplace=True) if fix_df: df['name'] = df['name'] + df['num'] n_fixed_columns = 11 n_segments_per_well = 15 n_wells = df.shape[0] # Repeat fixed rows (collar name and so) df_fixed = df.iloc[:, :n_fixed_columns] df_fixed = df_fixed.loc[df_fixed.index.repeat( n_segments_per_well)] # Add a formation to each segment tiled_formations = pd.np.tile(formations, (n_wells)) df_fixed['formation'] = tiled_formations # Add the segments base to the df df_bottoms = df.iloc[:, n_fixed_columns:n_fixed_columns + n_segments_per_well] df_fixed['base'] = df_bottoms.values.reshape(-1, 1, order='C') # Adding tops column from collar and base df_fixed = ss.io.wells.add_tops_from_base_and_altitude_in_place( df_fixed, 'name', 'base', 'altitude' ) # Fixing boreholes that have the base higher than the top top_base_error = df_fixed["top"] > df_fixed["base"] df_fixed["base"][top_base_error] = df_fixed["top"] + 0.01 # Add real coord df_fixed['z'] = df_fixed['altitude'] - df_fixed['md'] df = df_fixed return df
19,132
def cpl_parse(path): """ Parse DCP CPL """ cpl = generic_parse( path, "CompositionPlaylist", ("Reel", "ExtensionMetadata", "PropertyList")) if cpl: cpl_node = cpl['Info']['CompositionPlaylist'] cpl_dcnc_parse(cpl_node) cpl_reels_parse(cpl_node) return cpl
19,133
def notfound(): """Serve 404 template.""" return make_response(render_template('404.html'), 404)
19,134
def read_network(file: str) -> Tuple[int, int, List[int]]: """ Read a Boolean network from a text file: Line 1: number of state variables Line 2: number of control inputs Line 3: transition matrix of the network (linear representation of a logical matrix) :param file: a text file :return: (n, m, Lm), where n: number of state variables m: number of control inputs Lm: network transition matrix """ with open(file, 'r') as f: n = int(f.readline().strip()) m = int(f.readline().strip()) N = 2 ** n M = 2 ** m line = f.readline().strip() assert line, f'network transition matrix must be provided!' numbers = line.split() assert len(numbers) == M * N, f'The transition matrix must have {M * N} columns' L = [int(num) for num in numbers] for i in L: assert 1 <= i <= N, f'All integers in the network transition matrix must be in range [1, {N}]' return n, m, L
19,135
def copy(srcpath, destpath, pattern=None, pred=_def_copy_pred): """ Copies all files in the source path to the specified destination path. The source path can be a file, in which case that file will be copied as long as it matches the specified pattern. If the source path is a directory, all directories in it will be recursed and any files matching the specified pattern will be copied. :param srcpath: Source path to copy files from. :param destpath: Destination path to copy files to. :param pattern: Pattern to match filenames against. :param pred: Predicate to decide which files to copy/overwrite. :return: Number of files copied. """ if os.path.isfile(srcpath): if pattern and not fnmatch.fnmatch(srcpath, pattern): return 0 if pred and pred(srcpath, destpath) == False: return 0 path, filename = os.path.split(destpath) if not os.path.exists(path): # Make sure all directories needed to copy the file exist. create_dir(path) shutil.copyfile(srcpath, destpath) return 1 num_files_copied = 0 for s in os.listdir(srcpath): src = os.path.join(srcpath , s) dest = os.path.join(destpath, s) num_files_copied += copy(src, dest, pattern) return num_files_copied
19,136
def bundle_products_list(request,id): """ This view Renders Bundle Product list Page """ bundle = get_object_or_404(Bundle, bundle_id=id) bundleProd = BundleProducts.objects.filter(bundle=id) stocks = Stock.objects.all() context = { "title": "Bundle Products List", "bundle": bundle, "bundleproducts": bundleProd, "stocks": stocks } return render(request, 'bundle_products.html',context)
19,137
def rot_x(theta): """ Rotation matrix around X axis :param theta: Rotation angle in radians, right-handed :return: Rotation matrix in form of (3,3) 2D numpy array """ return rot_axis(0,theta)
19,138
def SetupPushNotification(request, callback, customData = None, extraHeaders = None): """ Sets the Amazon Resource Name (ARN) for iOS and Android push notifications. Documentation on the exact restrictions can be found at: http://docs.aws.amazon.com/sns/latest/api/API_CreatePlatformApplication.html. Currently, Amazon device Messaging is not supported. https://docs.microsoft.com/rest/api/playfab/admin/title-wide-data-management/setuppushnotification """ if not PlayFabSettings.DeveloperSecretKey: raise PlayFabErrors.PlayFabException("Must have DeveloperSecretKey set to call this method") def wrappedCallback(playFabResult, error): if callback: callback(playFabResult, error) PlayFabHTTP.DoPost("/Admin/SetupPushNotification", request, "X-SecretKey", PlayFabSettings.DeveloperSecretKey, wrappedCallback, customData, extraHeaders)
19,139
def ValidateEntryPointNameOrRaise(entry_point): """Checks if a entry point name provided by user is valid. Args: entry_point: Entry point name provided by user. Returns: Entry point name. Raises: ArgumentTypeError: If the entry point name provided by user is not valid. """ return _ValidateArgumentByRegexOrRaise(entry_point, _ENTRY_POINT_NAME_RE, _ENTRY_POINT_NAME_ERROR)
19,140
def save_volfile(array, filename, affine=None): """ Saves an array to nii, nii.gz, or npz format. Parameters: array: The array to save. filename: Filename to save to. affine: Affine vox-to-ras matrix. Saves LIA matrix if None (default). """ if filename.endswith(('.nii', '.nii.gz')): import nibabel as nib if affine is None and array.ndim >= 3: # use LIA transform as default affine affine = np.array([[-1, 0, 0, 0], [ 0, 0, 1, 0], [ 0, -1, 0, 0], [ 0, 0, 0, 1]], dtype=float) pcrs = np.append(np.array(array.shape[:3]) / 2, 1) affine[:3, 3] = -np.matmul(affine, pcrs)[:3] nib.save(nib.Nifti1Image(array, affine), filename) elif filename.endswith('.npz'): np.savez_compressed(filename, vol=array) else: raise ValueError('unknown filetype for %s' % filename)
19,141
def park2_4_z(z, x): """ Computes the Parkd function. """ y1 = x[0][0] y2 = x[0][1] chooser = x[1] y3 = (x[2] - 103.0) / 91.0 y4 = x[3] + 10.0 x = [y1, y2, y3, y4] if chooser == 'rabbit': ret = sub_park_1(x) elif chooser == 'dog': ret = sub_park_2(x) elif chooser == 'gerbil': ret = sub_park_3(x) elif chooser in ['hamster', 'ferret']: ret = sub_park_4(x) return ret * np.exp(z - 1)
19,142
def get_string_coords(line): """return a list of string positions (tuple (start, end)) in the line """ result = [] for match in re.finditer(STRING_RGX, line): result.append( (match.start(), match.end()) ) return result
19,143
def array_from_pixbuf(p): """Convert from GdkPixbuf to numpy array" Args: p (GdkPixbuf): The GdkPixbuf provided from some window handle Returns: ndarray: The numpy array arranged for the pixels in height, width, RGBA order """ w,h,c,r=(p.get_width(), p.get_height(), p.get_n_channels(), p.get_rowstride()) assert p.get_colorspace() == GdkPixbuf.Colorspace.RGB assert p.get_bits_per_sample() == 8 if p.get_has_alpha(): assert c == 4 else: assert c == 3 assert r >= w * c a=np.frombuffer(p.get_pixels(),dtype=np.uint8) if a.shape[0] == w*c*h: return a.reshape( (h, w, c), order = 'C' ) else: b=np.zeros((h,w*c),'uint8') for j in range(h): b[j,:]=a[r*j:r*j+w*c] return b.reshape( (h, w, c) )
19,144
def entropy(x,k=3,base=2): """ The classic K-L k-nearest neighbor continuous entropy estimator x should be a list of vectors, e.g. x = [[1.3],[3.7],[5.1],[2.4]] if x is a one-dimensional scalar and we have four samples """ assert k <= len(x)-1, "Set k smaller than num. samples - 1" d = len(x[0]) N = len(x) intens = 1e-10 #small noise to break degeneracy, see doc. x = [list(p + intens*nr.rand(len(x[0]))) for p in x] tree = ss.cKDTree(x) nn = [tree.query(point,k+1,p=float('inf'))[0][k] for point in x] const = digamma(N)-digamma(k) + d*log(2) return (const + d*np.mean(map(log,nn)))/log(base)
19,145
def respond_to_command(slack_client, branch, thread_ts): """Take action on command.""" logging.debug("Responding to command: Deploy Branch-%s", branch) is_production = False if branch == 'develop': message = "Development deployment started" post_to_channel(slack_client, message, thread_ts, announce=is_production) result = deploy_develop() elif branch == 'master': is_production = True message = "Production deployment started" post_to_channel(slack_client, message, thread_ts, announce=is_production) result = deploy_production() else: # Do nothing return None if result.return_code == 0: message = "Branch {} deployed successfully.".format(branch) post_to_channel(slack_client, message, thread_ts, announce=is_production) else: message = "FAILED: Branch {} failed to deploy.".format(branch) post_to_channel(slack_client, message, thread_ts) logging.debug("Failed build stdout: %s", result.out) logging.debug("Failed build stderr: %s", result.err)
19,146
def build_bazel_rules_nodejs(**kwargs): """Rule node.js """ name = "build_bazel_rules_nodejs" ref = get_ref(name, "d334fd8e2274fb939cf447106dced97472534e80", kwargs) sha256 = get_sha256(name, "5c69bae6545c5c335c834d4a7d04b888607993027513282a5139dbbea7166571", kwargs) github_archive(name, "bazelbuild", "rules_nodejs", ref, sha256)
19,147
def write_file(graph, filename, mode=None): """ write file Arguments: ---------- graph {pydotplus.graphviz.Dot} -- graph filename {str} -- file name Keyword Arguments: ------------------ mode {str} -- type of function (default: None} Raises: ------- Exception: this raise when write function cannot be loaded Examples: --------- >>> write_file(graph, "hoge.png") # graph will be saved as hoge.png >>> write_file(graph, "hoge.png") # graph will be saved as hoge.png >>> write_file(graph, "hoge", mode="png") # the same result """ ext = _check_extension(filename) if mode is None and ext is None: raise Exception("There're no matching extension.") elif mode is None and not ext is None: mode = ext filename += f".{mode}" func_dict[mode](graph, filename)
19,148
def s3upload_start( request: HttpRequest, workflow: Optional[Workflow] = None, ) -> HttpResponse: """Upload the S3 data as first step. The four step process will populate the following dictionary with name upload_data (divided by steps in which they are set STEP 1: initial_column_names: List of column names in the initial file. column_types: List of column types as detected by pandas src_is_key_column: Boolean list with src columns that are unique step_1: URL name of the first step :param request: Web request :return: Creates the upload_data dictionary in the session """ # Bind the form with the received data form = UploadS3FileForm( request.POST or None, request.FILES or None, workflow=workflow) if request.method == 'POST' and form.is_valid(): # Dictionary to populate gradually throughout the sequence of steps. It # is stored in the session. request.session['upload_data'] = { 'initial_column_names': form.frame_info[0], 'column_types': form.frame_info[1], 'src_is_key_column': form.frame_info[2], 'step_1': reverse('dataops:csvupload_start')} return redirect('dataops:upload_s2') return render( request, 'dataops/upload1.html', { 'form': form, 'wid': workflow.id, 'dtype': 'S3 CSV', 'dtype_select': _('S3 CSV file'), 'valuerange': range(5) if workflow.has_table() else range(3), 'prev_step': reverse('dataops:uploadmerge')})
19,149
def search_explorations(query, limit, sort=None, cursor=None): """Searches through the available explorations. args: - query_string: the query string to search for. - sort: a string indicating how to sort results. This should be a string of space separated values. Each value should start with a '+' or a '-' character indicating whether to sort in ascending or descending order respectively. This character should be followed by a field name to sort on. When this is None, results are based on 'rank'. See _get_search_rank to see how rank is determined. - limit: the maximum number of results to return. - cursor: A cursor, used to get the next page of results. If there are more documents that match the query than 'limit', this function will return a cursor to get the next page. returns: a tuple: - a list of exploration ids that match the query. - a cursor if there are more matching explorations to fetch, None otherwise. If a cursor is returned, it will be a web-safe string that can be used in URLs. """ return search_services.search( query, SEARCH_INDEX_EXPLORATIONS, cursor, limit, sort, ids_only=True)
19,150
def find_resourceadapters(): """ Finds all resource adapter classes. :return List[ResourceAdapter]: a list of all resource adapter classes """ subclasses = [] def look_for_subclass(module_name): module = __import__(module_name) d = module.__dict__ for m in module_name.split('.')[1:]: d = d[m].__dict__ for key, entry in d.items(): if key == tortuga.resourceAdapter.resourceAdapter.ResourceAdapter.__name__: continue try: if issubclass(entry, tortuga.resourceAdapter.resourceAdapter.ResourceAdapter): subclasses.append(entry) except TypeError: continue for _, modulename, _ in pkgutil.walk_packages( tortuga.resourceAdapter.__path__): look_for_subclass('tortuga.resourceAdapter.{0}'.format(modulename)) return subclasses
19,151
def print_scale(skill, points): """Return TeX lines for a skill scale.""" lines = ['\\cvskill{'] lines[0] += skill lines[0] += '}{' lines[0] += str(points) lines[0] += '}\n' return lines
19,152
def test_add_op_scalar(): """ Program: fn (x, y) { return x + y; } """ x = relay.var('x', shape=()) y = relay.var('y', shape=()) func = relay.Function([x, y], add(x, y)) x_data = np.array(10.0, dtype='float32') y_data = np.array(1.0, dtype='float32') check_rts(func, [x_data, y_data], x_data + y_data)
19,153
def getsize(file: Union[TextIO, BinaryIO]) -> int: """ Overview: Get the size of the given ``file`` stream. :param file: File which size need to access. :return: File's size. Examples:: >>> import io >>> from hbutils.file import getsize >>> >>> with io.BytesIO(b'\\xde\\xad\\xbe\\xef') as file: ... print(getsize(file)) 4 >>> with open('README.md', 'r') as file: ... print(getsize(file)) 2582 .. note:: Only seekable stream can use :func:`getsize`. """ if file.seekable(): try: return os.stat(file.fileno()).st_size except OSError: with keep_cursor(file): return file.seek(0, io.SEEK_END) else: raise OSError(f'Given file {repr(file)} is not seekable, ' # pragma: no cover f'so its size is unavailable.')
19,154
def print_(fh, *args): """Implementation of perl $fh->print method""" global OS_ERROR, TRACEBACK, AUTODIE try: print(*args, end='', file=fh) return True except Exception as _e: OS_ERROR = str(_e) if TRACEBACK: cluck(f"print failed: {OS_ERROR}",skip=2) if AUTODIE: raise return False
19,155
def _expm_multiply_interval(A, B, start=None, stop=None, num=None, endpoint=None, balance=False, status_only=False): """ Compute the action of the matrix exponential at multiple time points. Parameters ---------- A : transposable linear operator The operator whose exponential is of interest. B : ndarray The matrix to be multiplied by the matrix exponential of A. start : scalar, optional The starting time point of the sequence. stop : scalar, optional The end time point of the sequence, unless `endpoint` is set to False. In that case, the sequence consists of all but the last of ``num + 1`` evenly spaced time points, so that `stop` is excluded. Note that the step size changes when `endpoint` is False. num : int, optional Number of time points to use. endpoint : bool, optional If True, `stop` is the last time point. Otherwise, it is not included. balance : bool Indicates whether or not to apply balancing. status_only : bool A flag that is set to True for some debugging and testing operations. Returns ------- F : ndarray :math:`e^{t_k A} B` status : int An integer status for testing and debugging. Notes ----- This is algorithm (5.2) in Al-Mohy and Higham (2011). There seems to be a typo, where line 15 of the algorithm should be moved to line 6.5 (between lines 6 and 7). """ if balance: raise NotImplementedError if len(A.shape) != 2 or A.shape[0] != A.shape[1]: raise ValueError('expected A to be like a square matrix') if A.shape[1] != B.shape[0]: raise ValueError('the matrices A and B have incompatible shapes') ident = _ident_like(A) n = A.shape[0] if len(B.shape) == 1: n0 = 1 elif len(B.shape) == 2: n0 = B.shape[1] else: raise ValueError('expected B to be like a matrix or a vector') u_d = 2**-53 tol = u_d mu = _trace(A) / float(n) # Get the linspace samples, attempting to preserve the linspace defaults. linspace_kwargs = {'retstep' : True} if num is not None: linspace_kwargs['num'] = num if endpoint is not None: linspace_kwargs['endpoint'] = endpoint samples, step = np.linspace(start, stop, **linspace_kwargs) # Convert the linspace output to the notation used by the publication. nsamples = len(samples) if nsamples < 2: raise ValueError('at least two time points are required') q = nsamples - 1 h = step t_0 = samples[0] t_q = samples[q] # Define the output ndarray. # Use an ndim=3 shape, such that the last two indices # are the ones that may be involved in level 3 BLAS operations. X_shape = (nsamples,) + B.shape X = np.empty(X_shape, dtype=float) t = t_q - t_0 A = A - mu * ident A_1_norm = _exact_1_norm(A) if t*A_1_norm == 0: m_star, s = 0, 1 else: ell = 2 norm_info = LazyOperatorNormInfo(t*A, A_1_norm=t*A_1_norm, ell=ell) m_star, s = _fragment_3_1(norm_info, n0, tol, ell=ell) # Compute the expm action up to the initial time point. X[0] = _expm_multiply_simple_core(A, B, t_0, mu, m_star, s) # Compute the expm action at the rest of the time points. if q <= s: if status_only: return 0 else: return _expm_multiply_interval_core_0(A, X, h, mu, m_star, s, q) elif q > s and not (q % s): if status_only: return 1 else: return _expm_multiply_interval_core_1(A, X, h, mu, m_star, s, q, tol) elif q > s and (q % s): if status_only: return 2 else: return _expm_multiply_interval_core_2(A, X, h, mu, m_star, s, q, tol) else: raise Exception('internal error')
19,156
def subprocess(mocker): """ Mock the subprocess and make sure it returns a value """ def with_return_value(value: int = 0, stdout: str = ""): mock = mocker.patch( "subprocess.run", return_value=CompletedProcess(None, returncode=0) ) mock.returncode.return_value = value mock.stdout = stdout return mock return with_return_value
19,157
def ljust(string, width): """ A version of ljust that considers the terminal width (see get_terminal_width) """ width -= get_terminal_width(string) return string + " " * width
19,158
def device_sort (device_set): """Sort a set of devices by self_id. Can't be used with PendingDevices!""" return sorted(device_set, key = operator.attrgetter ('self_id'))
19,159
def _ontology_value(curie): """Get the id component of the curie, 0000001 from CL:0000001 for example.""" return curie.split(":")[1]
19,160
def get_current_joblist(JobDir): """ -function to return current, sorted, joblist in /JobDir """ if os.path.exists(JobDir): jobdirlist = os.walk(JobDir).next()[1] jobdirlist.sort() return jobdirlist
19,161
def save_keys(profile, access_token): """ Save keys to ~/.weibowarc """ filename = default_config_filename() save_config(filename, profile, access_token) print("Keys saved to", filename)
19,162
def readpacket( timeout=1000, hexdump=False ): """Reads a HP format packet (length, data, checksum) from device. Handles error recovery and ACKing. Returns data or prints hexdump if told so. """ data = protocol.readpacket() if hexdump == True: print hpstr.tohexstr( data ) else: return data
19,163
def df_down_next_empty_pos(df, pos): """ Given a position `pos` at `(c, r)`, reads down column `c` from row `r` to find the next empty cell. Returns the position of that cell if found, or `None` otherwise. """ return df_down_next_matching_pos(df, pos, pd.isna)
19,164
def day(stats): """ Returns a random day action function based on your decided day action :return: Function tht will give a random day action """ # Later versions should read in numbers/booleans to determine this first statement input("As the sun rises it marks a new day. What will you do?") while True: WWYD = input("1: Eat, 2: Go out, 3: Stay Home") if WWYD.isdigit() is True: if int(WWYD) == 1: # Eating, later versions will allow you to have a fridge while True: confirm = input("Do I want 1: Fast food or 2: Restaurant food: ") # Currency will be implemented if confirm.isdigit() is True: if int(confirm) == 1: mall(WWYD, stats) break elif int(confirm) == 2: resturant() break else: print("Where?") else: print("Where?") elif int(WWYD) == 2: # Going out! On the toooooown while True: confirm = input("Do I want to 1: go to the gym, 2: the mall or 3: the library: ") if confirm.isdigit() is True: if int(confirm) == 1: gym() elif int(confirm) == 2: mall(WWYD,stats) elif int(confirm) == 3: library() else: print("Where?") else: print("Where?") elif int(WWYD) == 3: # Stay home, be a couch potate, or potato, I guess. while True: confirm = input("Do I want use the 1: computer, 2: phone: ") if confirm.isdigit() is True: if int(confirm) == 1: computer() elif int(confirm) == 2: phone() else: print("Where?") else: print("Where?") else: print("Wait, what am I thinking?") else: print("Wait, what am I thinking?")
19,165
def optimise_f2_thresholds(y, p, verbose=False, resolution=100): """Optimize individual thresholds one by one. Code from anokas. Inputs ------ y: numpy array, true labels p: numpy array, predicted labels """ n_labels = y.shape[1] def mf(x): p2 = np.zeros_like(p) for i in range(n_labels): p2[:, i] = (p[:, i] > x[i]).astype(np.int) score = fbeta_score(y, p2, beta=2, average='samples') return score x = [0.2]*n_labels for i in range(n_labels): best_i2 = 0 best_score = 0 for i2 in range(resolution): i2 /= resolution x[i] = i2 score = mf(x) if score > best_score: best_i2 = i2 best_score = score x[i] = best_i2 if verbose: print(i, best_i2, best_score) return x
19,166
def ipv6_generator(): """A generator for keys (type ipv6) that will skip some keys and repeat most, just for the sake of a good spread of keys. Completely random offsets are generated. """ min_ = randint(1,100) max_ = randint(min_, 100000) cur = min_ off = randrange(4294967296) while cur < max_: while random() < 0.7: yield (IPV6_PRIVATE_PREFIX + cur.to_bytes(8, "big"), off) off = randrange(off, 4294967296) cur += 1 off = randrange(4294967296)
19,167
def holding_vars(): """ input This is experimental, used to indicate unbound (free) variables in a sum or list comprehensive. This is inspired by Harrison's {a | b | c} set comprehension notation. >>> pstream(holding_vars(),', holding x,y,z') Etok(holding_vars,', holding x , y , z') """ def f(acc): ((_,_),cs) = acc return Etok(name='holding_vars',etoks=cs[0::2],raw=acc) return (comma + next_word('holding') + c.plus_comma(var())).treat(f,'holding_vars')
19,168
def select_with_several_genes(accessions, name, pattern, description_items=None, attribute='gene', max_items=3): """ This will select the best description for databases where more than one gene (or other attribute) map to a single URS. The idea is that if there are several genes we should use the lowest one (RNA5S1, over RNA5S17) and show the names of genes, if possible. This will list the genes if there are few, otherwise provide a note that there are several. """ getter = op.attrgetter(attribute) candidate = min(accessions, key=getter) genes = set(getter(a) for a in accessions if getter(a)) if not genes or len(genes) == 1: description = candidate.description # Append gene name if it exists and is not present in the description # already if genes: suffix = genes.pop() if suffix not in description: description += ' (%s)' % suffix return description regexp = pattern % getter(candidate) basic = re.sub(regexp, '', candidate.description) func = getter if description_items is not None: func = op.attrgetter(description_items) items = sorted([func(a) for a in accessions if func(a)], key=item_sorter) if not items: return basic return add_term_suffix(basic, items, name, max_items=max_items)
19,169
def list_messages_matching_query(service, user_id, query=''): """List all Messages of the user's mailbox matching the query. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. query: String used to filter messages returned. Eg.- 'from:user@some_domain.com' for Messages from a particular sender. Returns: List of Messages that match the criteria of the query. Note that the returned list contains Message IDs, you must use get with the appropriate ID to get the details of a Message. """ try: response = service.users().messages().list(userId=user_id, q=query).execute() messages = [] if 'messages' in response: messages.extend(response['messages']) while 'nextPageToken' in response: page_token = response['nextPageToken'] response = service.users().messages().list( userId=user_id, q=query, pageToken=page_token).execute() messages.extend(response['messages']) return messages except errors.HttpError as error: print('An error occurred: %s' % error)
19,170
def write_to_string(input_otio, **profile_data): """ :param input_otio: Timeline, Track or Clip :param profile_data: Properties passed to the profile tag describing the format, frame rate, colorspace and so on. If a passed Timeline has `global_start_time` set, the frame rate will be set automatically. Please note that numeric values must be passed as strings. Please check MLT website for more info on profiles. You may pass an "image_producer" argument with "pixbuf" to change image sequence producer. The default image sequence producer is "image2" :return: MLT formatted XML :rtype: `str` """ mlt_adapter = MLTAdapter(input_otio, **profile_data) return mlt_adapter.create_mlt()
19,171
def parse_IS(reply: bytes, device: str): """Parses the reply to the shutter IS command.""" match = re.search(b"\x00\x07IS=([0-1])([0-1])[0-1]{6}\r$", reply) if match is None: return False if match.groups() == (b"1", b"0"): if device in ["shutter", "hartmann_right"]: return "open" else: return "closed" elif match.groups() == (b"0", b"1"): if device in ["shutter", "hartmann_right"]: return "closed" else: return "open" else: return False
19,172
def quatXYZWFromRotMat(rot_mat): """Convert quaternion from rotation matrix""" quatWXYZ = quaternions.mat2quat(rot_mat) quatXYZW = quatToXYZW(quatWXYZ, 'wxyz') return quatXYZW
19,173
def schema_is_current(db_connection: sqlite3.Connection) -> bool: """ Given an existing database, checks to see whether the schema version in the existing database matches the schema version for this version of Gab Tidy Data. """ db = db_connection.cursor() db.execute( """ select metadata_value from _gab_tidy_data where metadata_key = 'schema_version' """ ) db_schema_version = db.fetchone()[0] return db_schema_version == data_mapping.schema_version
19,174
def xattr_writes_supported(path): """ Returns True if the we can write a file to the supplied path and subsequently write a xattr to that file. """ try: import xattr except ImportError: return False def set_xattr(path, key, value): xattr.setxattr(path, "user.%s" % key, value) # We do a quick attempt to write a user xattr to a temporary file # to check that the filesystem is even enabled to support xattrs fake_filepath = os.path.join(path, 'testing-checkme') result = True with open(fake_filepath, 'wb') as fake_file: fake_file.write(b"XXX") fake_file.flush() try: set_xattr(fake_filepath, 'hits', b'1') except IOError as e: if e.errno == errno.EOPNOTSUPP: result = False else: # Cleanup after ourselves... if os.path.exists(fake_filepath): os.unlink(fake_filepath) return result
19,175
def end(pstats_file): """Ends yappi profiling session, saves the profilinf info to a CProfile pstats file, and pretty-prints it to the console.""" yappi.stop() func_stats = yappi.get_func_stats() if func_stats: _rows = [] for _stat in func_stats._as_dict: if '/Spardaqus/' in _stat.full_name and '/venv/' not in _stat.full_name: _gizmo = _stat.full_name.split("/")[-1] _rows.append([_gizmo.split(" ")[1], _gizmo.split(" ")[0], _stat.ncall, _stat.tavg, _stat.ttot, _stat.tsub]) info("*") info("* TOP 50 CALLS BY TOT TIME") info("*") _hdr = ["NAME", "LOCATION", "CALLS", "AvgTIME", "TotTIME", "TotTIMELessSubcalls"] info("{: <40} {: <32} {: >12} {: >24} {: >24} {: >24}".format(*_hdr)) _rows.sort(key=lambda x: x[4], reverse=True) i = 0 for _row in _rows: info("{: <40} {: <32} {: >12} {: >24} {: >24} {: >24}".format(*_row)) i += 1 if i == 50: break info("*") info("* TOP 50 CALLS BY NUMBER OF CALLS") info("*") info("{: <40} {: <32} {: >12} {: >24} {: >24} {: >24}".format(*_hdr)) _rows.sort(key=lambda x: x[2], reverse=True) i = 0 for _row in _rows: info("{: <40} {: <32} {: >12} {: >24} {: >24} {: >24}".format(*_row)) i += 1 if i == 50: break func_stats.save(pstats_file, type='pstat') yappi.clear_stats()
19,176
def _lovasz_softmax(probabilities, targets, classes="present", per_image=False, ignore=None): """The multiclass Lovasz-Softmax loss. Args: probabilities: [B, C, H, W] class probabilities at each prediction (between 0 and 1). Interpreted as binary (sigmoid) output with outputs of size [B, H, W]. targets: [B, H, W] ground truth targets (between 0 and C - 1) classes: "all" for all, "present" for classes present in targets, or a list of classes to average. per_image: compute the loss per image instead of per batch ignore: void class targets """ if per_image: loss = mean( _lovasz_softmax_flat( *_flatten_probabilities(prob.unsqueeze(0), lab.unsqueeze(0), ignore), classes=classes ) for prob, lab in zip(probabilities, targets) ) else: loss = _lovasz_softmax_flat( *_flatten_probabilities(probabilities, targets, ignore), classes=classes ) return loss
19,177
def encodeDERTRequest(negoTypes = [], authInfo = None, pubKeyAuth = None): """ @summary: create TSRequest from list of Type @param negoTypes: {list(Type)} @param authInfo: {str} authentication info TSCredentials encrypted with authentication protocol @param pubKeyAuth: {str} public key encrypted with authentication protocol @return: {str} TRequest der encoded """ negoData = NegoData().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1)) #fill nego data tokens i = 0 for negoType in negoTypes: s = Stream() s.writeType(negoType) negoToken = NegoToken() negoToken.setComponentByPosition(0, s.getvalue()) negoData.setComponentByPosition(i, negoToken) i += 1 request = TSRequest() request.setComponentByName("version", univ.Integer(2).subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))) if i > 0: request.setComponentByName("negoTokens", negoData) if not authInfo is None: request.setComponentByName("authInfo", univ.OctetString(authInfo).subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 2))) if not pubKeyAuth is None: request.setComponentByName("pubKeyAuth", univ.OctetString(pubKeyAuth).subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 3))) return der_encoder.encode(request)
19,178
def p_cmdexpr_dbinspect(p): """cmdexpr : DBINSPECT | DBINSPECT arglist | DBINSPECT MACRO"""
19,179
def remove_collection(browse_layer): """ Remove Sx-Cat collection. """ collection_name = browse_layer.browse_type logger.info("Removing Sx-Cat collection '%s'.", collection_name) return_code = _sxcat_command(["remove", collection_name]) if return_code != 0: logger.warning( "Failed to remove the Sx-Cat collection. " "Check if the collection exists by the 'sxcat info %s' command and, " "if so, remove the collection manually by the " "'sxcat remove %s' command.", collection_name, collection_name ) else: logger.info("Successfully removed Sx-Cat collection.")
19,180
def _crossCorrelations(queue, n_atoms, array, variances, indices): """Calculate covariance-matrix for a subset of modes.""" n_modes = len(indices) arvar = (array[:, indices] * variances[indices]).T.reshape((n_modes, n_atoms, 3)) array = array[:, indices].T.reshape((n_modes, n_atoms, 3)) covariance = np.tensordot(array.transpose(2, 0, 1), arvar.transpose(0, 2, 1), axes=([0, 1], [1, 0])) queue.put(covariance)
19,181
def describe_config_rule_evaluation_status(ConfigRuleNames=None, NextToken=None, Limit=None): """ Returns status information for each of your AWS managed Config rules. The status includes information such as the last time AWS Config invoked the rule, the last time AWS Config failed to invoke the rule, and the related error for the last failure. See also: AWS API Documentation Exceptions :example: response = client.describe_config_rule_evaluation_status( ConfigRuleNames=[ 'string', ], NextToken='string', Limit=123 ) :type ConfigRuleNames: list :param ConfigRuleNames: The name of the AWS managed Config rules for which you want status information. If you do not specify any names, AWS Config returns status information for all AWS managed Config rules that you use.\n\n(string) --\n\n :type NextToken: string :param NextToken: The nextToken string returned on a previous page that you use to get the next page of results in a paginated response. :type Limit: integer :param Limit: The number of rule evaluation results that you want returned.\nThis parameter is required if the rule limit for your account is more than the default of 150 rules.\nFor information about requesting a rule limit increase, see AWS Config Limits in the AWS General Reference Guide .\n :rtype: dict ReturnsResponse Syntax { 'ConfigRulesEvaluationStatus': [ { 'ConfigRuleName': 'string', 'ConfigRuleArn': 'string', 'ConfigRuleId': 'string', 'LastSuccessfulInvocationTime': datetime(2015, 1, 1), 'LastFailedInvocationTime': datetime(2015, 1, 1), 'LastSuccessfulEvaluationTime': datetime(2015, 1, 1), 'LastFailedEvaluationTime': datetime(2015, 1, 1), 'FirstActivatedTime': datetime(2015, 1, 1), 'LastDeactivatedTime': datetime(2015, 1, 1), 'LastErrorCode': 'string', 'LastErrorMessage': 'string', 'FirstEvaluationStarted': True|False }, ], 'NextToken': 'string' } Response Structure (dict) -- ConfigRulesEvaluationStatus (list) -- Status information about your AWS managed Config rules. (dict) -- Status information for your AWS managed Config rules. The status includes information such as the last time the rule ran, the last time it failed, and the related error for the last failure. This action does not return status information about custom AWS Config rules. ConfigRuleName (string) -- The name of the AWS Config rule. ConfigRuleArn (string) -- The Amazon Resource Name (ARN) of the AWS Config rule. ConfigRuleId (string) -- The ID of the AWS Config rule. LastSuccessfulInvocationTime (datetime) -- The time that AWS Config last successfully invoked the AWS Config rule to evaluate your AWS resources. LastFailedInvocationTime (datetime) -- The time that AWS Config last failed to invoke the AWS Config rule to evaluate your AWS resources. LastSuccessfulEvaluationTime (datetime) -- The time that AWS Config last successfully evaluated your AWS resources against the rule. LastFailedEvaluationTime (datetime) -- The time that AWS Config last failed to evaluate your AWS resources against the rule. FirstActivatedTime (datetime) -- The time that you first activated the AWS Config rule. LastDeactivatedTime (datetime) -- LastErrorCode (string) -- The error code that AWS Config returned when the rule last failed. LastErrorMessage (string) -- The error message that AWS Config returned when the rule last failed. FirstEvaluationStarted (boolean) -- Indicates whether AWS Config has evaluated your resources against the rule at least once. true - AWS Config has evaluated your AWS resources against the rule at least once. false - AWS Config has not once finished evaluating your AWS resources against the rule. NextToken (string) -- The string that you use in a subsequent request to get the next page of results in a paginated response. Exceptions ConfigService.Client.exceptions.NoSuchConfigRuleException ConfigService.Client.exceptions.InvalidParameterValueException ConfigService.Client.exceptions.InvalidNextTokenException :return: { 'ConfigRulesEvaluationStatus': [ { 'ConfigRuleName': 'string', 'ConfigRuleArn': 'string', 'ConfigRuleId': 'string', 'LastSuccessfulInvocationTime': datetime(2015, 1, 1), 'LastFailedInvocationTime': datetime(2015, 1, 1), 'LastSuccessfulEvaluationTime': datetime(2015, 1, 1), 'LastFailedEvaluationTime': datetime(2015, 1, 1), 'FirstActivatedTime': datetime(2015, 1, 1), 'LastDeactivatedTime': datetime(2015, 1, 1), 'LastErrorCode': 'string', 'LastErrorMessage': 'string', 'FirstEvaluationStarted': True|False }, ], 'NextToken': 'string' } :returns: true - AWS Config has evaluated your AWS resources against the rule at least once. false - AWS Config has not once finished evaluating your AWS resources against the rule. """ pass
19,182
def generate_s3_strings(path): """Generates s3 bucket name, s3 key and s3 path with an endpoint from a path with path (string): s3://BUCKETNAME/KEY x --> path.find(start) returns index 0 + len(start) returns 5 --> 0 + 5 = 5 Y --> path[len(start):] = BUCKENAME/KEY --> .find(end) looking for forward slash in BUCKENAME/KEY --> returns 10 Y --> now we have to add len(start) to 10 because the index was relating to BUCKENAME/KEY and not to s3://BUCKETNAME/KEY bucket_name = path[X:Y] Prefix is the string behind the slash that is behind the bucket_name - so path.find(bucket_name) find the index of the bucket_name, add len(bucket_name) to get the index to the end of the bucket name - add 1 because we do not want the slash in the Key Args: path (string): s3://BUCKETNAME/KEY Returns: strings: path = s3://endpoint@BUCKETNAME/KEY prefix = KEY bucket_name = BUCKETNAME """ start = 's3://' end = '/' bucket_name = path[path.find(start)+len(start):path[len(start):].find(end)+len(start)] prefix = path[path.find(bucket_name)+len(bucket_name)+1:] if not prefix.endswith('/'): prefix = prefix+'/' path = 's3://'+os.environ['S3_ENDPOINT']+'@'+bucket_name+'/'+prefix return bucket_name, prefix, path
19,183
def hierholzer(network: Network, source=0): """ Hierholzer's algorithm for finding an Euler cycle Args: network (Network): network object source(int): node where starts (and ends) the path Raises: NotEulerianNetwork: if exists at least one node with odd degree NotNetworkNode: if source is not in the network Returns: list of nodes that form a path visiting all edges References: .. [1] sanjeev2552, heruslu, Code_Mech, Geeks For Geeks, A computer science portal for geeks https://www.geeksforgeeks.org/hierholzers-algorithm-directed-graph/ .. [2] Reinhard Diestel, Graph Theory, Springer, Volume 173 of Graduate texts in mathematics, ISSN 0072-5285 """ if source > network.n: raise NotNetworkNode(f"Source node {source} is not in the network (N={network.n})") path = [] temp_path = [] degrees_list = deepcopy(network.degrees_list) edges_basket = deepcopy(network.edges_basket) if network.n == 0: return path eulerian, odd_degree_nodes = is_eulerian(network) if not eulerian: raise NotEulerianNetwork(f"Network is not Eulerian, not all nodes are even degree: {odd_degree_nodes}") temp_path.append(source) temp_node = source while len(temp_path): if degrees_list[temp_node]: temp_path.append(temp_node) next_node = edges_basket[temp_node][-1] degrees_list[temp_node] -= 1 edges_basket[temp_node].pop() if not network.directed: degrees_list[next_node] -= 1 i = edges_basket[next_node].index(temp_node) del edges_basket[next_node][i] temp_node = next_node else: path.append(temp_node) temp_node = temp_path[-1] temp_path.pop() # If the network is directed we will revert the path if network.directed: return path[::-1] return path
19,184
def RemoveChromeBrowserObjectFiles(chromeos_root, board): """Remove any object files from all the posible locations.""" out_dir = os.path.join( GetChrootPath(chromeos_root), 'var/cache/chromeos-chrome/chrome-src/src/out_%s' % board) if os.path.exists(out_dir): shutil.rmtree(out_dir) logger.GetLogger().LogCmd('rm -rf %s' % out_dir) out_dir = os.path.join( GetChrootPath(chromeos_root), 'var/cache/chromeos-chrome/chrome-src-internal/src/out_%s' % board) if os.path.exists(out_dir): shutil.rmtree(out_dir) logger.GetLogger().LogCmd('rm -rf %s' % out_dir)
19,185
def fit1d(xdata,zdata,degree=1,reject=0,ydata=None,plot=None,plot2d=False,xr=None,yr=None,zr=None,xt=None,yt=None,zt=None,pfit=None,log=False,colorbar=False,size=5) : """ Do a 1D polynomial fit to data set and plot if requested Args: xdata : independent variable zdata : dependent variable to be fit Keyword args: degree: degree of polynomial to fit (default=1 for linear fit) reject : single iteration rejection of points that deviate from initial by more than specified value (default=0, no rejection) ydata : auxiliary variable for plots (default=None) plot : axes to plot into (default=None) plot2d (bool) : set to make a 2D plot with auxiliary variable, rather than 1D color-coded by auxiliary variable xr[2] : xrange for plot yr[2] : yrange for plot zr[2] : zrange for plot xt : xtitle for plot yt : ytitle for plot zt : ztitle for plot Returns : pfit : 1D polynomial fit """ # set up fitter and do fit if pfit is None : fit_p = fitting.LinearLSQFitter() p_init = models.Polynomial1D(degree=degree) pfit = fit_p(p_init, xdata, zdata) # rejection of points? if reject > 0 : gd=np.where(abs(zdata-pfit(xdata)) < reject)[0] bd=np.where(abs(zdata-pfit(xdata)) >= reject)[0] print('rejected ',len(xdata)-len(gd),' of ',len(xdata),' points') pfit = fit_p(p_init, xdata[gd], zdata[gd]) print('1D rms: ',(zdata-pfit(xdata)).std()) # plot if requested if plot is not None : if xr is None : xr = [xdata.min(),xdata.max()] if yr is None and ydata is not None : yr = [ydata.min(),ydata.max()] if log : zplot=10.**zdata else : zplot=zdata if zr is None : zr = [zplot.min(),zplot.max()] if ydata is None : x = np.linspace(xr[0],xr[1],200) if log : zfit=10.**pfit(x) else : zfit=pfit(x) # straight 1D plot plots.plotp(plot,xdata,zplot,xr=xr,yr=yr,zr=zr, xt=xt,yt=yt,size=size) plots.plotl(plot,x,zfit) elif plot2d : # 2D image plot with auxiliary variable y, x = np.mgrid[yr[1]:yr[0]:200j, xr[1]:xr[0]:200j] if log : zfit=10.**pfit(x) else : zfit=pfit(x) plots.plotc(plot,xdata,ydata,zplot,xr=xr,yr=yr,zr=zr, xt=xt,yt=xt,zt=yt,colorbar=True,size=size,cmap='rainbow') plot.imshow(zfit,extent=[xr[1],xr[0],yr[1],yr[0]], aspect='auto',vmin=zr[0],vmax=zr[1], origin='lower',cmap='rainbow') else : # 1D plot color-coded by auxiliary variable x = np.linspace(xr[0],xr[1],200) if log : zfit=10.**pfit(x) else : zfit=pfit(x) plots.plotc(plot,xdata,zplot,ydata,xr=xr,yr=zr,zr=yr, xt=xt,yt=yt,zt=zt,size=size,colorbar=colorbar) plots.plotl(plot,x,zfit,color='k') return pfit
19,186
def nucleus_sampling(data, p, replace=0, ascending=False, above=True): """ :param tensor data: Input data :param float p: Probability for filtering (or be replaced) :param float replace: Default value is 0. If value is provided, input data will be replaced by this value if data match criteria. :param bool ascending: Return ascending order or descending order. Sorting will be executed if replace is None. :param bool above: If True is passed, only value smaller than p will be kept (or not replaced) :return: tensor Filtered result """ sorted_data, sorted_indices = torch.sort(data, descending=not ascending) cum_probas = torch.cumsum(F.softmax(sorted_data, dim=-1), dim=-1) if replace is None: if above: replace_idxes = cum_probas < p else: replace_idxes = cum_probas > p idxes = sorted_indices[replace_idxes] else: if above: replace_idxes = cum_probas > p else: replace_idxes = cum_probas < p idxes = sorted_indices[~replace_idxes] if replace is None: sorted_data = sorted_data[replace_idxes] else: sorted_data[replace_idxes] = replace return sorted_data, idxes
19,187
def mark_ready_for_l10n_revision(request, document_slug, revision_id): """Mark a revision as ready for l10n.""" revision = get_object_or_404(Revision, pk=revision_id, document__slug=document_slug) if not revision.document.allows(request.user, 'mark_ready_for_l10n'): raise PermissionDenied if revision.can_be_readied_for_localization(): # We don't use update(), because that wouldn't update # Document.latest_localizable_revision. revision.is_ready_for_localization = True revision.readied_for_localization = datetime.now() revision.readied_for_localization_by = request.user revision.save() ReadyRevisionEvent(revision).fire(exclude=request.user) return HttpResponse(json.dumps({'message': revision_id})) return HttpResponseBadRequest()
19,188
def test_get_weather_observed(bear_lake_observed, manchester_vermont_observed): """Tests the get_weather_observed() function. """ # Weather observed - Bear Lake, RMNP, Colorado # Test object type assert isinstance(bear_lake_observed, gpd.geodataframe.GeoDataFrame) # Test precip amount assert ( round(bear_lake_observed.loc["2020-05-15"].precip_amount_mm, 2) == 2.40 ) # Test number of entries in the geodataframe assert len(bear_lake_observed) == 10 # Test geometry type assert isinstance( bear_lake_observed.iloc[0].geometry, shapely.geometry.polygon.Point ) # Test number of columns assert len(bear_lake_observed.columns) == 10 # Weather observed - Manchester, Vermont # Test object type assert isinstance(manchester_vermont_observed, gpd.GeoDataFrame) # Test number of entries in the geodataframe assert len(manchester_vermont_observed) == 10 # Test geometry type assert isinstance( manchester_vermont_observed.iloc[0].geometry, shapely.geometry.polygon.Point, ) # Test average precip for May 15 assert ( round( manchester_vermont_observed.loc["2020-05-15"].precip_amount_mm, 2 ) == 25.84 )
19,189
def is_all_maxed_out(bad_cube_counts, bad_cube_maximums): """Determines whether all the cubes of each type are at their maximum amounts.""" for cube_type in CUBE_TYPES: if bad_cube_counts[cube_type] < bad_cube_maximums[cube_type]: return False return True
19,190
def get_local_vars(*args): """ get_local_vars(prov, ea, out) -> bool """ return _ida_dbg.get_local_vars(*args)
19,191
def items(chatlog_path, out_path, to, realm): """ Parse chatlog items into LOKI format. """ chatlog_path = Path(chatlog_path).absolute() out_path = Path(out_path).absolute() click.echo(f"Parsing: {chatlog_path.as_posix()}") click.echo(f"Writing items into {out_path.as_posix()}") with open(chatlog_path, "r") as file: log_text = file.readlines() processed_log = process_log(log_text) if to.lower() == "loki": log_items_to_loki(processed_log, realm, out_path)
19,192
def gcc(): """ getCurrentCurve Get the last curve that was added to the last plot plot :return: The last curve :rtype: pg.PlotDataItem """ plotWin = gcf() try: return plotWin.plotWidget.plotItem.dataItems[-1] except IndexError: return None
19,193
def test_structure_roundtrip_precision(new_workdir): """Testing structure roundtrip precision ase->aiida->cp2k->aiida->ase...""" import ase.build import numpy as np from aiida.engine import run from aiida.plugins import CalculationFactory from aiida.orm import Dict, StructureData computer = get_computer(workdir=new_workdir) code = get_code(entry_point="cp2k", computer=computer) # structure epsilon = 1e-10 # expected precision in Angstrom dist = 0.74 + epsilon positions = [(0, 0, 0), (0, 0, dist)] cell = np.diag([4, -4, 4 + epsilon]) atoms = ase.Atoms("H2", positions=positions, cell=cell) structure = StructureData(ase=atoms) # parameters parameters = Dict( dict={ "GLOBAL": {"RUN_TYPE": "MD"}, "MOTION": {"MD": {"TIMESTEP": 0.0, "STEPS": 1}}, # do not move atoms "FORCE_EVAL": { "METHOD": "Quickstep", "DFT": { "BASIS_SET_FILE_NAME": "BASIS_MOLOPT", "SCF": {"MAX_SCF": 1}, "XC": {"XC_FUNCTIONAL": {"_": "LDA"}}, }, "SUBSYS": { "KIND": { "_": "DEFAULT", "BASIS_SET": "DZVP-MOLOPT-SR-GTH", "POTENTIAL": "GTH-LDA", } }, }, } ) # resources options = { "resources": {"num_machines": 1, "num_mpiprocs_per_machine": 1}, "max_wallclock_seconds": 1 * 60 * 60, } inputs = { "structure": structure, "parameters": parameters, "code": code, "metadata": {"options": options}, } result = run(CalculationFactory("cp2k"), **inputs) # check structure preservation atoms2 = result["output_structure"].get_ase() # zeros should be preserved exactly assert np.all(atoms2.positions[0] == 0.0) # other values should be preserved with epsilon precision dist2 = atoms2.get_distance(0, 1) assert abs(dist2 - dist) < epsilon # check cell preservation cell_diff = np.amax(np.abs(atoms2.cell - cell)) assert cell_diff < epsilon
19,194
async def more_lights(hass, lights): """Provide lights 'light.light_3' and 'light.light_4'.""" await make_lights(hass, ['light_3', 'light_4'], area_name="area_2")
19,195
def nfs_setup(cluster: str, headers_inc: str): """Demonstrates NFS Setup using REST APIs.""" print("Demonstrates NFS Setup using REST APIs.") print("=======================================") print() show_svm(cluster, headers_inc) print() svm_name = input( "Choose the SVM on which you would like to create a NFS Share :") print("Make sure that NAS LIFs on each nodes are created on the SVM :") print() print("Checking and Enabling NFS Protocol on SVM:-") print("===========================================") payload1 = { "enabled": bool("true"), "protocol": { "v3_enabled": bool("true") }, "svm": { "name": svm_name } } url1 = "https://{}/api/protocols/nfs/services".format(cluster) try: response = requests.post( url1, headers=headers_inc, json=payload1, verify=False) except requests.exceptions.HTTPError as err: print(str(err)) sys.exit(1) except requests.exceptions.RequestException as err: print(str(err)) sys.exit(1) url_text = response.json() if 'error' in url_text: print(url_text) print() print("Create the Export Policy:-") print("==========================") export_policy_name = input("Enter the Export Policy Name :- ") protocol = input( "Enter the protocol name for the Export Policy(nfs/cifs/any):- ") clients = input("Enter client details [0.0.0.0/0]:- ") url2 = "https://{}/api/protocols/nfs/export-policies".format(cluster) svm_uuid = get_key_svms(svm_name, cluster, headers_inc) payload2 = { "name": export_policy_name, "rules": [ { "clients": [ { "match": clients } ], "protocols": [ protocol ], "ro_rule": [ "any" ], "rw_rule": [ "any" ] } ], "svm.uuid": svm_uuid } try: response = requests.post( url2, headers=headers_inc, json=payload2, verify=False) except requests.exceptions.HTTPError as err: print(str(err)) sys.exit(1) except requests.exceptions.RequestException as err: print(str(err)) sys.exit(1) url_text = response.json() if 'error' in url_text: print(url_text) sys.exit(1) url_text = response.json() print() print("Create the Volume:-") print("===================") vol_name = input("Enter the Volume Name to create NFS Share:-") vol_size = input("Enter the Volume Size in MBs :-") aggr_name = input("Enter the aggregate name:-") v_size = get_size(vol_size) pather = "/" + vol_name payload3 = {"aggregates": [{"name": aggr_name}], "svm": {"name": svm_name}, "name": vol_name, "size": v_size, "nas": {"export_policy": {"name": export_policy_name}, "security_style": "unix", "path": pather}} url3 = "https://{}/api/storage/volumes".format(cluster) try: response = requests.post( url3, headers=headers_inc, json=payload3, verify=False) print("Volume %s created" % vol_name) except requests.exceptions.HTTPError as err: print(str(err)) sys.exit(1) except requests.exceptions.RequestException as err: print(str(err)) sys.exit(1) url_text = response.json() if 'error' in url_text: print(url_text) sys.exit(1) print("NAS creation script completed.")
19,196
def searchDevice(search): """ Method that searches the ExtraHop system for a device that matches the specified search criteria Parameters: search (dict): The device search criteria Returns: dict: The metadata of the device that matches the criteria """ url = urlunparse(("https", HOST, "/api/v1/devices/search", "", "", "")) headers = {"Authorization": "ExtraHop apikey=%s" % APIKEY} r = requests.post( url, headers=headers, verify=False, data=json.dumps(search) ) return r.json()[0]
19,197
def regularmeshH8(nelx, nely, nelz, lx, ly, lz): """ Creates a regular H8 mesh. Args: nelx (:obj:`int`): Number of elements on the X-axis. nely (:obj:`int`): Number of elements on the Y-axis. nelz (:obj:`int`): Number of elements on the Z-axis. lx (:obj:`float`): X-axis length. ly (:obj:`float`): Y-axis length. lz (:obj:`float`): Z-axis length. Returns: Tuple with the coordinate matrix, connectivity, and the indexes of each node. """ x, y, z = np.linspace(0, lx, num=nelx + 1), np.linspace(0, ly, num=nely + 1), np.linspace(0, lz, num=nelz + 1) nx, ny, nz = len(x), len(y), len(z) mat_x = (x.reshape(nx, 1)@np.ones((1, ny*nz))).T mat_y = y.reshape(ny, 1)@np.ones((1, nx)) mat_z = z.reshape(nz, 1)@np.ones((1, nx*ny)) x_t, y_t, z_t = mat_x.flatten(), np.tile(mat_y.flatten(), nz), mat_z.flatten() ind_coord = np.arange(1, (nz)* nx * ny + 1, 1, dtype=int) coord = (np.array([ind_coord, x_t, y_t, z_t])).T # processing of connectivity matrix ind_connect = np.arange(1, nelz * nelx * nely + 1, dtype=int) mat_aux = ind_connect.reshape(nely, nelx, nelz) a = np.arange(0, nely * nelz, 1) for ind in range(nely, len(a), nely): a[ind:] += nelx + 1 c = (a.reshape(len(a),1)@np.ones((1, nelx))).reshape(nely, nelx, nelz) b = (mat_aux + c).flatten() connect = np.array([ind_connect, b+(nelx+1), b, b+1, b+(nelx+2), \ b+(nelx+1)*(nely+1)+(nelx+1), b+(nelx+1)*(nely+1), \ b+1+(nelx+1)*(nely+1), b+(nelx+1)*(nely+1)+(nelx+2)], dtype=int).T return coord, connect
19,198
def test_run_component_compile_command_instance(tmp_path, capsys, instance_aware): """ Run the component compile command for a component with a postprocessing filter """ component_name = "test-component" instance_name = "test-instance" _prepare_component(tmp_path, component_name) if instance_aware: _make_instance_aware(tmp_path, component_name) result = run( _cli_command_string(tmp_path, component_name, instance_name), shell=True, capture_output=True, ) exit_status = result.returncode if not instance_aware: assert exit_status == 1 assert ( f"Error: Component {component_name} with alias {instance_name} does not support instantiation.\n" in result.stderr.decode("utf-8") ) else: assert exit_status == 0 assert ( tmp_path / "testdir" / "compiled" / instance_name / "apps" / f"{component_name}.yaml" ).exists() rendered_yaml = ( tmp_path / "testdir" / "compiled" / instance_name / component_name / "test_service_account.yaml" ) assert rendered_yaml.exists() with open(rendered_yaml) as file: target = yaml.safe_load(file) assert target["kind"] == "ServiceAccount" assert target["metadata"]["namespace"] == f"syn-{component_name}"
19,199