id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
70252
<reponame>HaardikBhagtani/healthy from time import time from musiconloop import musiconloop from lognow import log_now print("Welcome to the Beautiful Day") user_name = input("Enter Your name\n").capitalize() if __name__ == '__main__': init_water = time() init_eyes = time() init_exercise = time() water_secs = 40*60 # water sound playing time every 40 minutes exercise_secs = 30*60 # exercise sound playing time every 30 minutes eyes_secs = 45*60 # eyes sound playing time every 30 minutes while True: if time() - init_water > water_secs: print(f"Water Drinking time {user_name}.\nEnter 'drank' to stop the alarm.") musiconloop('water.mp3', 'drank') init_water = time() log_now("Drank Water at ") if time() - init_eyes > eyes_secs: print(f"Eye exercise time {user_name}.\nEnter 'done eyes' to stop the alarm.") musiconloop('eyes.mp3', 'done eyes') init_eyes = time() log_now("Eyes Relaxed at ") if time() - init_exercise > exercise_secs: print(f"Physical Activity Time {user_name}.\nEnter 'done exercise' to stop the alarm.") musiconloop('physical.mp3', 'done exercise') init_exercise = time() log_now("Physical Activity done at ")
StarcoderdataPython
1777309
<filename>src/qcar/src/qcarnode.py #!/usr/bin/env python3 from __future__ import division, print_function, absolute_import import rospy import numpy as np from qcar.product_QCar import QCar from qcar.q_interpretation import * from std_msgs.msg import String, Float64 from geometry_msgs.msg import Vector3Stamped from sensor_msgs.msg import BatteryState import time class QCarNode(object): def __init__(self): super().__init__() self.battery_pub_ = rospy.Publisher('/qcar/battery_state', BatteryState, queue_size=10) self.carvel_pub_ = rospy.Publisher('/qcar/velocity_actual', Vector3Stamped, queue_size=10) self.myCar = QCar() self.sample_time = 0.001 self.throttle = 0.0 self.steering = 0.0 self.velocity_sub = rospy.Subscriber('/qcar/velocity_target', Float64, self.process_velocity, queue_size=10) self.steering_sub = rospy.Subscriber('/qcar/steering_target', Float64, self.process_steering, queue_size=10) def looping(self): rate = rospy.Rate(50) while not rospy.is_shutdown(): # Generate Commands LEDs = np.array([0, 0, 0, 0, 0, 0, 1, 1]) self.command = np.array([self.throttle, self.steering]) current, batteryVoltage, encoderCounts = self.myCar.read_write_std(self.command, LEDs) battery_state = BatteryState() battery_state.header.stamp = rospy.Time.now() battery_state.header.frame_id = 'battery_voltage' battery_state.voltage = batteryVoltage self.battery_pub_.publish(battery_state) longitudinal_car_speed = basic_speed_estimation(encoderCounts) velocity_state = Vector3Stamped() velocity_state.header.stamp = rospy.Time.now() velocity_state.header.frame_id = 'car_velocity' velocity_state.vector.x = float(np.cos(self.command[1]) * longitudinal_car_speed) velocity_state.vector.y = float(np.sin(self.command[1]) * longitudinal_car_speed) self.carvel_pub_.publish(velocity_state) rate.sleep() self.myCar.terminate() def process_velocity(self, speed): self.throttle = speed.data / 30.0 def process_steering(self, steering): self.steering = steering.data if __name__ == '__main__': rospy.init_node('qcar_node') r = QCarNode() r.looping() rospy.spin() # print('Im here')
StarcoderdataPython
1610603
<reponame>ogorodnikov/m1 import signal # https://stackoverflow.com/questions/492519/timeout-on-a-function-call def plot_timeout_handler(signal_number, stack_frame): raise TimeoutError(f"Plot timeout: {PLOT_STATEVECTOR_TIMEOUT} seconds") def plot_statevector_figure(task_id, statevector): signal.signal(signal.SIGALRM, plot_timeout_handler) signal.alarm(PLOT_STATEVECTOR_TIMEOUT) try: figure = plot_bloch_multivector(statevector) # time.sleep(10) task_log(task_id, f'RUNNER figure: {figure}') figure_path = app.static_folder + f'/figures/bloch_multivector_task_{task_id}.png' figure.savefig(figure_path, transparent=True, bbox_inches='tight') except TimeoutError as exception: task_log(task_id, exception) signal.alarm(0)
StarcoderdataPython
3319805
<filename>orders/tasks.py from celery import task from django.core.mail import send_mail from .models import Order @task def order_created(order_id): """Task to send and email notification when an order is succesfully created.""" order = Order.objects.get(id=order_id) subject = f'Order nr. {order_id}' message = f'Dear {order.first_name},\n\nYou have successfully placed an order. Your order ID is {order.id}' mail_sent = send_mail(subject, message, '<EMAIL>', [order.email]) return mail_sent
StarcoderdataPython
1668399
from .sql_database_backend_service import SqlDatabaseBackendService # noqa from .sql_occ_locker_backend_service import SqlOccLockerBackendService # noqa
StarcoderdataPython
3320946
<gh_stars>0 class LoggingMixin(): """ Mixin class with methods for logging of configurations. """ def get_option_and_log(self, key): value = self.get_option(key) self.config.log(f"{self.configuration_key}.{key} set to {value}") return value
StarcoderdataPython
98570
<reponame>DataCanvasIO/tabular-toolbox<gh_stars>1-10 # -*- coding:utf-8 -*- __author__ = 'yangjian' """ """ import copy import time import dask import dask.array as da import dask.dataframe as dd import numpy as np import pandas as pd from lightgbm.sklearn import LGBMClassifier from sklearn import model_selection as sksel from sklearn.ensemble import RandomForestClassifier from sklearn.impute import SimpleImputer from sklearn.metrics import roc_auc_score, matthews_corrcoef, make_scorer from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.tree import DecisionTreeClassifier from tabular_toolbox import dask_ex as dex from tabular_toolbox import sklearn_ex as skex from tabular_toolbox.column_selector import column_object_category_bool, column_number_exclude_timedelta from tabular_toolbox.dataframe_mapper import DataFrameMapper from tabular_toolbox.utils import logging logger = logging.getLogger(__name__) roc_auc_scorer = make_scorer(roc_auc_score, greater_is_better=True, needs_threshold=True) matthews_corrcoef_scorer = make_scorer(matthews_corrcoef) def general_preprocessor(X): if dex.is_dask_dataframe(X): import dask_ml.impute as dimp import dask_ml.preprocessing as dpre cat_steps = [('imputer_cat', dimp.SimpleImputer(strategy='constant', fill_value='')), ('encoder', dex.SafeOrdinalEncoder())] num_steps = [('imputer_num', dimp.SimpleImputer(strategy='mean')), ('scaler', dpre.StandardScaler())] else: cat_steps = [('imputer_cat', SimpleImputer(strategy='constant', fill_value='')), ('encoder', skex.SafeOrdinalEncoder())] num_steps = [('imputer_num', SimpleImputer(strategy='mean')), ('scaler', StandardScaler())] cat_transformer = Pipeline(steps=cat_steps) num_transformer = Pipeline(steps=num_steps) preprocessor = DataFrameMapper(features=[(column_object_category_bool, cat_transformer), (column_number_exclude_timedelta, num_transformer)], input_df=True, df_out=True) return preprocessor def _wrap_predict_proba(estimator): orig_predict_proba = estimator.predict_proba def __predict_proba(*args, **kwargs): proba = orig_predict_proba(*args, **kwargs) proba = dex.fix_binary_predict_proba_result(proba) return proba setattr(estimator, '_orig_predict_proba', orig_predict_proba) setattr(estimator, 'predict_proba', __predict_proba) return estimator def _get_estimator(X, estimator=None): def default_gbm(): return LGBMClassifier(n_estimators=50, num_leaves=15, max_depth=5, subsample=0.5, subsample_freq=1, colsample_bytree=0.8, reg_alpha=1, reg_lambda=1, importance_type='gain', ) def default_dt(): return DecisionTreeClassifier(min_samples_leaf=20, min_impurity_decrease=0.01) def default_rf(): return RandomForestClassifier(min_samples_leaf=20, min_impurity_decrease=0.01) def default_dask_xgb(): import dask_xgboost return dask_xgboost.XGBClassifier(max_depth=5, n_estimators=50, min_child_weight=3, gamma=1, # reg_alpha=0.1, # reg_lambda=0.1, subsample=0.6, colsample_bytree=0.6, eval_metric='auc', # objective='binary:logitraw', tree_method='approx', ) if dex.is_dask_dataframe(X): try: estimator_ = default_dask_xgb() estimator_ = _wrap_predict_proba(estimator_) except ImportError: # failed to import dask_xgboost estimator_ = default_gbm() estimator_ = dex.wrap_local_estimator(estimator_) else: if estimator is None or estimator == 'gbm': estimator_ = default_gbm() elif estimator == 'dt': estimator_ = default_dt() elif estimator == 'rf': estimator_ = default_rf() else: estimator_ = copy.deepcopy(estimator) return estimator_ class FeatureSelectionCallback(): def on_round_start(self, round_no, features, ): pass def on_round_end(self, round_no, auc, features, remove_features, elapsed): pass def on_remove_shift_variable(self, shift_score, remove_features): pass def on_task_break(self, round_no, auc, features): pass def on_task_finished(self, round_no, auc, features): pass def feature_selection(X_train, X_test, remove_shift_variable=True, variable_shift_threshold=0.7, variable_shift_scorer=None, auc_threshold=0.55, min_features=10, remove_size=0.1, preprocessor=None, estimator=None, sample_balance=True, max_test_samples=None, cv=5, random_state=9527, copy_data=False, callbacks=None): logger.info('Feature selection to try to eliminate the concept drift.') if copy_data: X_train = X_train.copy() if isinstance(X_train, dd.DataFrame) else copy.deepcopy(X_train) X_test = X_test.copy() if isinstance(X_test, dd.DataFrame) else copy.deepcopy(X_test) scores = None if remove_shift_variable: scores = covariate_shift_score(X_train, X_test, scorer=variable_shift_scorer) remain_features = [] remove_features = [] for col, score in scores.items(): if score <= variable_shift_threshold: remain_features.append(col) else: remove_features.append(col) logger.info(f'Remove shift variables:{col}, score:{score}') if len(remain_features) < X_train.shape[1]: X_train = X_train[remain_features] X_test = X_test[remain_features] if callbacks is not None: for callback in callbacks: callback.on_remove_shift_variable(scores, remove_features) round = 1 history = [] while True: start_time = time.time() if callbacks is not None: for callback in callbacks: callback.on_round_start(round_no=round, features=X_train.columns.to_list()) logger.info(f'\nRound: {round}\n') detector = DriftDetector(preprocessor, estimator, random_state) detector.fit(X_train, X_test, sample_balance=sample_balance, max_test_samples=max_test_samples, cv=cv) logger.info(f'AUC:{detector.auc_}, Features:{detector.feature_names_}') elapsed = time.time() - start_time history.append({'auc': detector.auc_, 'n_features': len(detector.feature_names_), 'elapsed': elapsed }) if detector.auc_ <= auc_threshold: logger.info( f'AUC:{detector.auc_} has dropped below the threshold:{auc_threshold}, feature selection is over.') if callbacks is not None: for callback in callbacks: callback.on_task_finished(round_no=round, auc=detector.auc_, features=detector.feature_names_) return detector.feature_names_, history, scores indices = np.argsort(detector.feature_importances_) if indices.shape[0] <= min_features: logger.warn(f'The number of remaining features is insufficient to continue remove features. ' f'AUC:{detector.auc_} ' f'Remaining features:{detector.feature_names_}') if callbacks is not None: for callback in callbacks: callback.on_task_break(round_no=round, auc=detector.auc_, features=detector.feature_names_) return detector.feature_names_, history, scores removes = int(indices.shape[0] * remove_size) if removes <= 0: logger.warn(f'The number of remaining features is insufficient to continue remove features. ' f'AUC:{detector.auc_} ' f'Remaining features:({len(detector.feature_names_)}) / {detector.feature_names_}') if callbacks is not None: for callback in callbacks: callback.on_task_break(round_no=round, auc=detector.auc_, features=detector.feature_names_) return detector.feature_names_, history, scores if (indices.shape[0] - removes) < min_features: removes = indices.shape[0] - min_features remain_features = list(np.array(detector.feature_names_)[indices[:-removes]]) remove_features = list(set(detector.feature_names_) - set(remain_features)) logger.info(f'Removed features: {remove_features}') X_train = X_train[remain_features] X_test = X_test[remain_features] if callbacks is not None: for callback in callbacks: callback.on_round_end(round_no=round, auc=detector.auc_, features=detector.feature_names_, remove_features=remove_features, elapsed=elapsed) round += 1 class DriftDetector(): def __init__(self, preprocessor=None, estimator=None, random_state=9527): self.preprocessor = preprocessor self.estimator_ = estimator self.random_state = random_state self.auc_ = None self.feature_names_ = None self.feature_importances_ = None self.fitted = False def fit(self, X_train, X_test, sample_balance=True, max_test_samples=None, cv=5): logger.info('Fit data for concept drift detection') assert X_train.shape[1] == X_test.shape[1], 'The number of columns in X_train and X_test must be the same.' assert len(set(X_train.columns.to_list()) - set( X_test.columns.to_list())) == 0, 'The name of columns in X_train and X_test must be the same.' if dex.exist_dask_dataframe(X_train, X_test): import dask_ml.model_selection as dsel train_shape, test_shape = dask.compute(X_train.shape, X_test.shape) iterators = dsel.KFold(n_splits=cv, shuffle=True, random_state=1001) else: train_shape, test_shape = X_train.shape, X_test.shape iterators = sksel.StratifiedKFold(n_splits=cv, shuffle=True, random_state=1001) if max_test_samples is not None and max_test_samples < test_shape[0]: X_test, _ = dex.train_test_split(X_test, train_size=max_test_samples, random_state=self.random_state) test_shape = (max_test_samples, test_shape[0]) if sample_balance: if test_shape[0] > train_shape[0]: X_test, _ = dex.train_test_split(X_test, train_size=train_shape[0], random_state=self.random_state) test_shape = (train_shape[0], test_shape[1]) elif test_shape[0] < train_shape[0]: X_train, _ = dex.train_test_split(X_train, train_size=test_shape[0], random_state=self.random_state) train_shape = (test_shape[0], train_shape[1]) target_col = '__drift_detection_target__' if hasattr(X_train, 'insert'): X_train.insert(0, target_col, 0) else: X_train[target_col] = 0 if hasattr(X_test, 'insert'): X_test.insert(0, target_col, 1) else: X_test[target_col] = 1 X_merge = dex.concat_df([X_train, X_test], repartition=True) y = X_merge.pop(target_col) logger.info('Preprocessing...') if self.preprocessor is None: self.preprocessor = general_preprocessor(X_merge) X_merge = self.preprocessor.fit_transform(X_merge) self.feature_names_ = X_merge.columns.to_list() self.feature_importances_ = [] auc_all = [] importances = [] estimators = [] if dex.is_dask_dataframe(X_merge): X_values, y_values = X_merge.to_dask_array(lengths=True), y.to_dask_array(lengths=True) else: # X_values, y_values = X_merge.values, y.values X_values, y_values = X_merge, y for n_fold, (train_idx, valid_idx) in enumerate(iterators.split(X_values, y_values)): logger.info(f'Fold:{n_fold + 1}') if dex.is_dask_dataframe(X_merge): x_train_fold, y_train_fold = X_values[train_idx], y_values[train_idx] x_val_fold, y_val_fold = X_values[valid_idx], y_values[valid_idx] x_train_fold = dex.array_to_df(x_train_fold, meta=X_merge) x_val_fold = dex.array_to_df(x_val_fold, meta=X_merge) else: x_train_fold, y_train_fold = X_values.iloc[train_idx], y_values.iloc[train_idx] x_val_fold, y_val_fold = X_values.iloc[valid_idx], y_values.iloc[valid_idx] estimator = _get_estimator(X_merge, self.estimator_) kwargs = {} # if isinstance(estimator, dask_xgboost.XGBClassifier): # kwargs['eval_set'] = [(x_val_fold.compute(), y_val_fold.compute())] # kwargs['early_stopping_rounds'] = 10 if isinstance(estimator, LGBMClassifier): kwargs['eval_set'] = (x_val_fold, y_val_fold) kwargs['early_stopping_rounds'] = 10 kwargs['verbose'] = 0 estimator.fit(x_train_fold, y_train_fold, **kwargs) proba = estimator.predict_proba(x_val_fold)[:, 1] if dex.is_dask_dataframe(X_merge): y_val_fold, proba = dex.compute(y_val_fold, proba, traverse=False) auc = roc_auc_score(y_val_fold, proba) logger.info(f'auc: {auc}') auc_all.append(auc) estimators.append(estimator) importances.append(estimator.feature_importances_) self.estimator_ = estimators self.auc_ = np.mean(auc_all) self.feature_importances_ = np.mean(importances, axis=0) self.fitted = True X_test.pop(target_col) X_train.pop(target_col) return self def predict_proba(self, X): assert self.fitted, 'Please fit it first.' X = X.copy() if dex.is_dask_dataframe(X) else copy.deepcopy(X) cat_cols = column_object_category_bool(X) num_cols = column_number_exclude_timedelta(X) # X.loc[:, cat_cols + num_cols] = self.preprocessor.transform(X) Xt = self.preprocessor.transform(X) diff_cols = set(X.columns.tolist()) - set(cat_cols + num_cols) if diff_cols: # X.loc[:, cat_cols + num_cols] = Xt X = dex.concat_df([X[diff_cols], Xt[cat_cols + num_cols]], axis=1) else: X = Xt oof_proba = [] for i, estimator in enumerate(self.estimator_): proba = estimator.predict_proba(X)[:, 1] oof_proba.append(proba) if dex.is_dask_dataframe(X): proba = da.mean(dex.hstack_array(oof_proba), axis=1) else: proba = np.mean(oof_proba, axis=0) return proba def train_test_split(self, X, y, test_size=0.25, remain_for_train=0.3): if dex.exist_dask_object(X, y): return self.train_test_split_by_dask(X, y, test_size=test_size, remain_for_train=remain_for_train) assert remain_for_train < 1.0 and remain_for_train >= 0, '`remain_for_train` must be < 1.0 and >= 0.' if isinstance(test_size, float): assert test_size < 1.0 and test_size > 0, '`test_size` must be < 1.0 and > 0.' test_size = int(X.shape[0] * test_size) assert isinstance(test_size, int), '`test_size` can only be int or float' split_size = int(test_size + test_size * remain_for_train) assert split_size < X.shape[0], \ 'test_size+test_size*remain_for_train must be less than the number of samples in X.' proba = self.predict_proba(X) sorted_indices = np.argsort(proba) target = '__train_test_split_y__' X.insert(0, target, y) if remain_for_train == 0: X_train = X.iloc[sorted_indices[:-test_size]] X_test = X.iloc[sorted_indices[-test_size:]] y_train = X_train.pop(target) y_test = X_test.pop(target) return X_train, X_test, y_train, y_test else: X_train_1 = X.iloc[sorted_indices[:-split_size]] X_mixed = X.iloc[sorted_indices[-split_size:]] X_train_2, X_test = dex.train_test_split(X_mixed, test_size=test_size, shuffle=True, random_state=self.random_state) X_train = pd.concat([X_train_1, X_train_2], axis=0) y_train = X_train.pop(target) y_test = X_test.pop(target) return X_train, X_test, y_train, y_test def train_test_split_by_dask(self, X, y, test_size=0.25, remain_for_train=0.3): x_shape = dex.compute(X.shape)[0] assert remain_for_train < 1.0 and remain_for_train >= 0, '`remain_for_train` must be < 1.0 and >= 0.' if isinstance(test_size, float): assert test_size < 1.0 and test_size > 0, '`test_size` must be < 1.0 and > 0.' test_size = int(x_shape[0] * test_size) assert isinstance(test_size, int), '`test_size` can only be int or float' split_size = int(test_size + test_size * remain_for_train) assert split_size < x_shape[0], \ 'test_size+test_size*remain_for_train must be less than the number of samples in X.' X = X.copy() proba = self.predict_proba(X) sorted_indices = np.argsort(proba.compute()) target = '__train_test_split_y__' X[target] = y X_values = X.to_dask_array(lengths=True) if remain_for_train == 0: X_train = dex.array_to_df(X_values[sorted_indices[:-test_size]], meta=X) X_test = dex.array_to_df(X_values[sorted_indices[-test_size:]], meta=X) y_train = X_train.pop(target) y_test = X_test.pop(target) return X_train, X_test, y_train, y_test else: X_train_1 = dex.array_to_df(X_values[sorted_indices[:-split_size]], meta=X) X_mixed = dex.array_to_df(X_values[sorted_indices[-split_size:]], meta=X) X_train_2, X_test = dex.train_test_split(X_mixed, test_size=test_size, shuffle=True, random_state=self.random_state) X_train = dex.concat_df([X_train_1, X_train_2], axis=0) y_train = X_train.pop(target) y_test = X_test.pop(target) return X_train, X_test, y_train, y_test def covariate_shift_score(X_train, X_test, scorer=None, cv=None, copy_data=True): assert all(isinstance(x, (pd.DataFrame, dd.DataFrame)) for x in (X_train, X_test)), \ 'X_train and X_test must be a pandas or dask DataFrame.' assert len(set(X_train.columns.to_list()) - set( X_test.columns.to_list())) == 0, 'The columns in X_train and X_test must be the same.' if scorer is None: scorer = roc_auc_scorer if copy_data: train = X_train.copy() if dex.is_dask_dataframe(X_train) else copy.deepcopy(X_train) test = X_test.copy() if dex.is_dask_dataframe(X_test) else copy.deepcopy(X_test) else: train = X_train test = X_test # Set target value target_col = '__hypernets_csd__target__' if hasattr(train, 'insert'): train.insert(0, target_col, 0) else: train[target_col] = 0 if hasattr(test, 'insert'): test.insert(0, target_col, 1) else: test[target_col] = 1 X_merge = dex.concat_df([train, test], axis=0) y = X_merge.pop(target_col) if dex.is_dask_dataframe(X_merge): y = y.compute() logger.info('Preprocessing...') # Preprocess data: imputing and scaling preprocessor = general_preprocessor(X_merge) X_merge = preprocessor.fit_transform(X_merge) if dex.is_dask_dataframe(X_merge): X_merge = X_merge.persist() # Calculate the shift score for each column separately. scores = {} logger.info('Scoring...') for c in X_merge.columns: x = X_merge[[c]] if dex.is_dask_dataframe(X_merge): x = x.compute() model = LGBMClassifier() if cv is None: mixed_x_train, mixed_x_test, mixed_y_train, mixed_y_test = sksel.train_test_split(x, y, test_size=0.3, random_state=9527, stratify=y) model.fit(mixed_x_train, mixed_y_train, eval_set=(mixed_x_test, mixed_y_test), early_stopping_rounds=20, verbose=False) score = scorer(model, mixed_x_test, mixed_y_test) else: score_ = sksel.cross_val_score(model, X=x, y=y, verbose=0, scoring=scorer, cv=cv) score = np.mean(score_) logger.info(f'column:{c}, score:{score}') scores[c] = score return scores
StarcoderdataPython
136135
<gh_stars>100-1000 def append_text(new_text): ''' Write the code instruction to be exported later on Args. new_text (str): the text that will be appended to the base string ''' global code_base_text code_base_text = code_base_text + new_text
StarcoderdataPython
147198
""" Represent classes found in European Medicines Agency (EMA) documents """ class SectionLeaflet: """ Class to represent individual section of a Package Leaflet """ def __init__(self, title, section_content, entity_recognition=None): self.title = title self.section_content = section_content self.is_duplicate = False self.entity_recognition = entity_recognition self.generated_content = None def print_original_info(self): """ Display original information about a section """ print("The name of the section: \n", self.title, "\n===================\n") print("Original content of the section: \n", self.section_content, "\n===================\n") def print_entities(self): """ Print entities of the current section with corresponding Category, Type and Confidence Score """ if self.entity_recognition is not None: for entity in self.entity_recognition: print("{0} ({1}, type: {2}, score:{3:.2f})".format(entity["Text"], entity["Category"], entity["Type"], entity["Score"])) def compare_contents(self): """ Compare original content of a section to generated content """ print("Original Content: \n", self.section_content, "\n===================\n") print("Generated Content: \n", self.generated_content, "\n===================\n") def print_all_info(self): """ Display all information about a section """ print("The name of the section: \n", self.title, "\n===================\n") print("Original content of the section: \n", self.section_content, "\n===================\n") print("Named entity recognition: \n", self.entity_recognition, "\n===================\n") print("Generated content of the section: \n", self.generated_content, "\n===================\n") class Leaflet: """ Class to represent Package Leaflet, containing 6 sections """ def __init__(self, product_name, product_url, product_id, product_content, section1=None, section2=None, section3=None, section4=None, section5=None, section6=None): # leaflet attributes self.product_name = product_name self.url = product_url self.id = product_id self.content = product_content # extracted sections self.section1 = section1 self.section2 = section2 self.section3 = section3 self.section4 = section4 self.section5 = section5 self.section6 = section6 def display_info(self, full_content=True): """ Show information about a package leaflet""" print("Product Name: \n", self.product_name, "\n===================\n") print("Url: \n", self.url, "\n===================\n") print("Product ID: \n", self.id, "\n===================\n") if full_content == True: print("Full Leaflet Content: \n", self.content, "\n===================\n") def print_section(self, section_type=None): """ Display a particular section of a package leaflet """ if section_type == "1" and self.section1 is not None: self.section1.print_all_info() else: print("No section1 in the current leaflet - ", self.product_name) if section_type == "2" and self.section2 is not None: self.section2.print_all_info() else: print("No section2 in the current leaflet - ", self.product_name) if section_type == "3" and self.section3 is not None: self.section3.print_all_info() else: print("No section3 in the current leaflet - ", self.product_name) if section_type == "4" and self.section4 is not None: self.section4.print_all_info() else: print("No section4 in the current leaflet - ", self.product_name) if section_type == "5" and self.section5 is not None: self.section5.print_all_info() else: print("No section5 in the current leaflet - ", self.product_name) if section_type == "6" and self.section6 is not None: self.section6.print_all_info() else: print("No section6 in the current leaflet - ", self.product_name)
StarcoderdataPython
157458
from pyULIS4 import * import math # Keep in mind the coordinate system # starts at (0;0) in the bottom left # corner, since we are working in an # OpenGL context. pool = FThreadPool() queue = FCommandQueue( pool ) fmt = Format_RGBA8 ctx = FContext( queue, fmt ) canvas = FBlock( 800, 600, fmt ) temp = FBlock( 800, 600, fmt ) elapsed = 0.0 # Called once at the beginning of play. def start(): global fmt global ctx global canvas # Called every frame during play. def update( delta ): global fmt global ctx global canvas global elapsed elapsed += delta radius = ( ( math.sin( elapsed / 1 ) + 1 ) * 100 ) eventFill = FEvent() eventClear = FEvent() eventCircle = FEvent() ctx.Fill( canvas, FColor.White, event = eventFill ) ctx.Clear( temp, event = eventClear ) ctx.Finish() ctx.DrawCircleBresenhamSP( temp, FVec2F( 400, 300 ), radius, FColor.Black, True, waitList = [ eventFill, eventClear ], event = eventCircle ) ctx.Finish() ctx.Blend( temp, canvas, waitList = [ eventCircle ] ) ctx.Finish()
StarcoderdataPython
3291840
<reponame>Festusali/django-browser-reload<filename>tests/test_middleware.py from __future__ import annotations from django.http import HttpRequest, HttpResponse, StreamingHttpResponse from django.test import RequestFactory, SimpleTestCase, override_settings from django_browser_reload.middleware import BrowserReloadMiddleware @override_settings(DEBUG=True) class BrowserReloadMiddlewareTests(SimpleTestCase): request_factory = RequestFactory() def setUp(self): self.request = self.request_factory.get("/") self.response = HttpResponse("<html><body></body></html>") def get_response(request: HttpRequest) -> HttpResponse: return self.response self.middleware = BrowserReloadMiddleware(get_response) @override_settings(DEBUG=False) def test_not_debug(self): response = self.middleware(self.request) assert response.content == b"<html><body></body></html>" def test_streaming_response(self): # content that the middleware could inject in if it supported streaming # responses content_iter = iter(["<html><body>", "</body></html>"]) self.response = StreamingHttpResponse(content_iter) response = self.middleware(self.request) content = b"".join(response.streaming_content) assert content == b"<html><body></body></html>" def test_encoded_response(self): self.response["Content-Encoding"] = "zabble" response = self.middleware(self.request) assert response.content == b"<html><body></body></html>" def test_text_response(self): self.response["Content-Type"] = "text/plain" response = self.middleware(self.request) assert response.content == b"<html><body></body></html>" def test_no_match(self): self.response = HttpResponse("<html><body>Woops") response = self.middleware(self.request) assert response.content == b"<html><body>Woops" def test_success(self): self.response = HttpResponse("<html><body></body></html>") self.response["Content-Length"] = len(self.response.content) response = self.middleware(self.request) assert response.content == ( b"<html><body>" + b'<script src="/static/django-browser-reload/reload-listener.js"' + b' data-worker-script-path="/static/django-browser-reload/' + b'reload-worker.js"' + b' data-events-path="/__reload__/events/" defer></script>' + b"</body></html>" ) def test_multipart_content_type(self): self.response["Content-Type"] = "text/html; thingy=that; charset=utf-8" response = self.middleware(self.request) assert response.content == ( b"<html><body>" + b'<script src="/static/django-browser-reload/reload-listener.js"' + b' data-worker-script-path="/static/django-browser-reload/' + b'reload-worker.js"' + b' data-events-path="/__reload__/events/" defer></script>' + b"</body></html>" ) def test_two_matches(self): self.response = HttpResponse("<html><body></body><body></body></html>") response = self.middleware(self.request) assert response.content == ( b"<html><body></body><body>" + b'<script src="/static/django-browser-reload/reload-listener.js"' + b' data-worker-script-path="/static/django-browser-reload/' + b'reload-worker.js"' + b' data-events-path="/__reload__/events/" defer></script>' + b"</body></html>" )
StarcoderdataPython
1737111
import pytest from app import tasks pytestmark = [ pytest.mark.django_db, ] @pytest.fixture(autouse=True) def mass_update_subscription(mocker): return mocker.patch('app.integrations.mailchimp.client.AppMailchimp.mass_update_subscription') @pytest.fixture(autouse=True) def set_tags(mocker): return mocker.patch('app.integrations.mailchimp.client.AppMailchimp.set_tags') def test_task(user, mass_update_subscription, mailchimp_member): tasks.subscribe_to_mailchimp.delay(user.pk) mass_update_subscription.assert_called_once_with( list_id='123cba', members=[mailchimp_member], status='subscribed', ) def test_particular_list_id(user, mass_update_subscription, mailchimp_member): tasks.subscribe_to_mailchimp.delay( user_id=user.pk, list_id='TESTING-LIST-ID', ) mass_update_subscription.assert_called_once_with( list_id='TESTING-LIST-ID', members=[ mailchimp_member, ], status='subscribed', ) def test_tags(user, mailchimp_member, set_tags): tasks.subscribe_to_mailchimp.delay( user_id=user.pk, list_id='TESTING-LIST-ID', tags=['aatag', 'bbtag'], ) set_tags.assert_called_once_with( list_id='TESTING-LIST-ID', members=[mailchimp_member], tags=['aatag', 'bbtag'], ) def test_task_does_not_do_things_if_there_is_no_mailchimp_contact_list_id(user, mass_update_subscription, settings): settings.MAILCHIMP_CONTACT_LIST_ID = None tasks.subscribe_to_mailchimp.delay(user.pk) mass_update_subscription.assert_not_called()
StarcoderdataPython
86764
<reponame>tdimnet/integrations-core # (C) Datadog, Inc. 2021-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import click from ...console import CONTEXT_SETTINGS from .pdh import pdh ALL_COMMANDS = [pdh] @click.group(context_settings=CONTEXT_SETTINGS, short_help='Windows utilities') def windows(): pass for command in ALL_COMMANDS: windows.add_command(command)
StarcoderdataPython
65117
from seleniumbase import MasterQA class MasterQATests(MasterQA): def test_xkcd(self): self.open("https://xkcd.com/1512/") for i in range(4): self.click('a[rel="next"]') for i in range(3): self.click('a[rel="prev"]') self.verify() self.open("https://xkcd.com/1520/") for i in range(2): self.click('a[rel="next"]') self.verify("Can you find the moon?") self.click('a[rel="next"]') self.verify("Do the drones look safe?") self.open("https://store.xkcd.com/collections/everything") self.update_text("input.search-input", "book\n") self.verify("Do you see books in the search results?") self.open("https://xkcd.com/213/") for i in range(5): self.click('a[rel="prev"]') self.verify("Does the page say 'Abnormal Expressions'?")
StarcoderdataPython
4801184
<gh_stars>0 try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from ...sipmessaging import SIPHeaderField from ...sipmessaging import classproperty class DateSIPHeaderField(SIPHeaderField): # noinspection PyNestedDecorators @classproperty @classmethod def canonical_field_name(cls): return 'Date' @classmethod def new_for_attributes(cls, field_name="Date", field_value_string=""): return cls.new_for_field_name_and_value_string(field_name=field_name, field_value_string=field_value_string) @property def is_date(self): return True
StarcoderdataPython
1702784
<reponame>MasterMeng/PKCS11_example from PyKCS11 import * # import ptvsd # ptvsd.enable_attach(address=('0.0.0.0', 5678)) # ptvsd.wait_for_attach() aes_iv = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f] class OpenCryptoKi: def __init__(self, libpath): self.pkcs11 = PyKCS11Lib() self.pkcs11.load(libpath) self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0] def login(self, userpin): self.session = self.pkcs11.openSession( self.slot, CKF_SERIAL_SESSION | CKF_RW_SESSION) self.session.login(userpin, user_type=CKU_USER) def logout(self): self.session.logout() self.session.closeSession() def initpin(self, sopin, userpin): self.session = self.pkcs11.openSession( self.slot, CKF_SERIAL_SESSION | CKF_RW_SESSION) self.session.login(sopin, user_type=CKU_SO) self.session.initPin(userpin) self.session.logout() self.session.closeSession() def genhamc(self, label): tem = [ (CKA_CLASS, CKO_SECRET_KEY), (CKA_KEY_TYPE, CKK_GENERIC_SECRET), (CKA_VALUE_LEN, 32), (CKA_LABEL, label), (CKA_PRIVATE, True), (CKA_SENSITIVE, True), (CKA_ENCRYPT, True), (CKA_DECRYPT, True), (CKA_TOKEN, True), (CKA_EXTRACTABLE, False), ] hmacs = self.session.findObjects( [(CKA_CLASS, CKO_SECRET_KEY), (CKA_KEY_TYPE, CKK_GENERIC_SECRET), (CKA_LABEL, label), ]) for hmac in hmacs: self.session.destroyObject(hmac) self.session.generateKey( tem, mecha=Mechanism(CKM_GENERIC_SECRET_KEY_GEN)) def genmkek(self, key_type, key_len, label): tem = [ (CKA_CLASS, CKO_SECRET_KEY), (CKA_KEY_TYPE, key_type), (CKA_VALUE_LEN, key_len), (CKA_LABEL, label), (CKA_PRIVATE, True), (CKA_SENSITIVE, True), (CKA_ENCRYPT, True), (CKA_DECRYPT, True), (CKA_TOKEN, True), (CKA_EXTRACTABLE, False), (CKA_SIGN, True), (CKA_VERIFY, True), (CKA_WRAP, True), (CKA_UNWRAP, True), ] mkeks = self.session.findObjects( [(CKA_CLASS, CKO_SECRET_KEY), (CKA_KEY_TYPE, key_type), (CKA_LABEL, label), ]) for mkek in mkeks: self.session.destroyObject(mkek) self.session.generateKey(tem, MechanismAESGENERATEKEY) def findobjs(self, key_class, key_type, label): objs = self.session.findObjects( [(CKA_CLASS, key_class), (CKA_KEY_TYPE, key_type), (CKA_LABEL, label), ]) return objs def genkey(self, key_class, key_type, key_len, label): tem = [ (CKA_CLASS, key_class), (CKA_KEY_TYPE, key_type), (CKA_VALUE_LEN, key_len), (CKA_LABEL, label), (CKA_PRIVATE, True), (CKA_SENSITIVE, True), (CKA_ENCRYPT, True), (CKA_DECRYPT, True), (CKA_TOKEN, True), (CKA_EXTRACTABLE, True), ] objs = self.session.findObjects( [(CKA_CLASS, key_class), (CKA_KEY_TYPE, key_type), (CKA_VALUE_LEN, key_len), (CKA_LABEL, label), ]) for obj in objs: self.session.destroyObject(obj) self.session.generateKey(tem, MechanismRSAGENERATEKEYPAIR) def genkeypair(self, label): pubTem = [ (CKA_MODULUS_BITS, 0x0400), (CKA_PUBLIC_EXPONENT, (0x01, 0x00, 0x01)), ] priTem = [ ] return self.session.generateKeyPair( pubTem, priTem, MechanismRSAGENERATEKEYPAIR) def wrap(self, key, wrapping): return self.session.wrapKey(key, wrapping, Mechanism(CKM_AES_CBC_PAD, aes_iv)) def unwrap(self, key, wrapped, wrapped_class): return self.session.unwrapKey(key, wrapped, [(CKA_CLASS, wrapped_class)], Mechanism(CKM_AES_CBC_PAD, aes_iv)) def encrypt(self, key, msg): enc = self.session.encrypt( key, msg.encode('utf-8'), Mechanism(CKM_AES_CBC)) return bytes(enc) def decrypt(self, key, enc): dec = self.session.decrypt(key, enc, Mechanism(CKM_AES_CBC)) return bytes(dec) if __name__ == "__main__": t = OpenCryptoKi('/usr/local/lib/opencryptoki/libopencryptoki.so') t.login('123456') t.genmkek(CKK_AES, 32, 'MKEK') # print('######## MKEK #######') obj = t.findobjs(CKO_SECRET_KEY, CKK_AES, 'MKEK')[0] # for obj in objs: # print(obj) # t.genhamc('HMAC') # print('######## HMAC #######') # objs = t.findobjs(CKO_SECRET_KEY,CKK_GENERIC_SECRET, 'HMAC') # for obj in objs: # print(obj) pub, pri = t.genkeypair('RSA Key') pri = t.findobjs(CKO_PRIVATE_KEY, CKK_RSA, 'RSA Key')[0] # print(pri) wrapped = t.wrap(obj, pri) print(wrapped) print(bytes(wrapped)) t.logout()
StarcoderdataPython
121108
# valueIterationAgents.py # ----------------------- # Licensing Information: Please do not distribute or publish solutions to this # project. You are free to use and extend these projects for educational # purposes. The Pacman AI projects were developed at UC Berkeley, primarily by # <NAME> (<EMAIL>) and <NAME> (<EMAIL>). # For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html import mdp, util from learningAgents import ValueEstimationAgent class ValueIterationAgent(ValueEstimationAgent): """ * Please read learningAgents.py before reading this.* A ValueIterationAgent takes a Markov decision process (see mdp.py) on initialization and runs value iteration for a given number of iterations using the supplied discount factor. """ def __init__(self, mdp, discount = 0.9, iterations = 100): """ Your value iteration agent should take an mdp on construction, run the indicated number of iterations and then act according to the resulting policy. Some useful mdp methods you will use: mdp.getStates() mdp.getPossibleActions(state) mdp.getTransitionStatesAndProbs(state, action) mdp.getReward(state, action, nextState) """ self.mdp = mdp self.discount = discount self.iterations = iterations self.values = util.Counter() # A Counter is action dict with default 0 "*** YOUR CODE HERE ***" for i in range(iterations): self.prevBatch = self.values.copy() for state in mdp.getStates(): qValues = util.Counter() for action in mdp.getPossibleActions(state): for (statePrime, tValue) in mdp.getTransitionStatesAndProbs(state, action): qValues[action] += tValue * (mdp.getReward(state, action, statePrime) + self.discount * self.prevBatch[statePrime]) self.values[state] = qValues[qValues.argMax()] def getValue(self, state): """ Return the value of the state (computed in __init__). """ return self.values[state] def getQValue(self, state, action): """ The q-value of the state action pair (after the indicated number of value iteration passes). Note that value iteration does not necessarily create this quantity and you may have to derive it on the fly. """ "*** YOUR CODE HERE ***" qValue = 0 for (sp, tValue) in self.mdp.getTransitionStatesAndProbs(state, action): qValue += tValue * (self.mdp.getReward(state, action, sp) + self.discount * self.values[sp] ) return qValue; #util.raiseNotDefined() def getPolicy(self, state): """ The policy is the best action in the given state according to the values computed by value iteration. You may break ties any way you see fit. Note that if there are no legal actions, which is the case at the terminal state, you should return None. """ "*** YOUR CODE HERE ***" if self.mdp.isTerminal(state) : return None else: qValues = util.Counter() actions = self.mdp.getPossibleActions(state) for action in actions: qValues[actions.index(action)] = self.getQValue(state, action) return actions[qValues.argMax()]; #util.raiseNotDefined() def getAction(self, state): "Returns the policy at the state (no exploration)." return self.getPolicy(state)
StarcoderdataPython
4810276
<filename>work/03_load_sql.py #!/usr/bin/python3 import psycopg2 # connect to database connect_str = 'host=postgres port=5432 dbname=bakery user=postgres password=<PASSWORD>' conn = psycopg2.connect(connect_str) conn.autocommit = True cursor = conn.cursor() # execute sql script sql_file = open('bakery.sql', 'r') sqlFile = sql_file.read() sql_file.close() sqlCommands = sqlFile.split(';') for command in sqlCommands: print(command) if command.strip() != '': cursor.execute(command) # import data from csv file with open('BreadBasket_DMS.csv', 'r') as f: next(f) # Skip the header row. cursor.copy_from( f, 'transactions', sep=',', columns=('date', 'time', 'transaction', 'item') ) conn.commit() # confirm by selecting record command = 'SELECT COUNT(*) FROM public.transactions;' cursor.execute(command) recs = cursor.fetchall() print('Row count: %d' % recs[0])
StarcoderdataPython
3366977
<gh_stars>0 # Generated by Django 3.0.8 on 2020-07-14 08:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0002_client_instansi'), ] operations = [ migrations.AlterField( model_name='client', name='instansi', field=models.CharField(blank=True, max_length=200, null=True), ), ]
StarcoderdataPython
1709905
from typing import Tuple import tensorflow as tf from tensorflow.python.ops import gen_array_ops def decode_png(filename: str, channels: int = 1): """ Read image from `filename` with `channels`. Parameters ---------- filename : str A filename to read. channels : int, optional Number of channel. 3 for RGB, 1 for Grayscale, by default 1 Returns ------- tf.float32 `Tensor` of Image Image Tensor Examples -------- >>> from imagemodel.common.utils import tf_images >>> sample_img = tf_images.decode_png("tests/test_resources/sample.png", 3) >>> tf.shape(sample_img) tf.Tensor([180 180 3], shape=(3,), dtype=int32) """ bits = tf.io.read_file(filename) image = tf.image.decode_png(bits, channels) image = tf.cast(image, tf.float32) # image = tf.image.convert_image_dtype(image, dtype=tf.float32, saturate=False) return image def save_img(tf_img, filename: str): """ Save `Tensor` of `tf_img` to file. Parameters ---------- tf_img : `Tensor` `Tensor` of image. filename : str File path to save. Examples -------- >>> from imagemodel.common.utils import tf_images >>> # tf_img = ... >>> tf_images.save_img(tf_img, "file_name.png") """ tf.keras.preprocessing.image.save_img(filename, tf_img) def tf_img_to_minmax(tf_img, threshold: float, min_max: Tuple[float, float] = (0.0, 1.0)): """ Convert grayscale `Tensor` of image, to `Tensor` of `min_max` value. Parameters ---------- tf_img : `Tensor` of Image Should be grayscale image. (channel 1) threshold : float Threshold value to determine `min_max` min_max : Tuple[float, float], optional Min max value for `tf_img`, by default (0.0, 1.0) Returns ------- `Tensor` of Image In image, exist only min_max values. Examples -------- >>> from imagemodel.common.utils import tf_images >>> from tensorflow.python.ops import gen_array_ops >>> grayscale_sample_img = tf_images.decode_png("tests/test_resources/sample.png", 1) >>> min_maxed_grayscale_tf_image = tf_images.tf_img_to_minmax(grayscale_sample_img, 127, (0, 255)) >>> reshaped_min_maxed_grayscale_tf_image = tf.reshape(min_maxed_grayscale_tf_image, (-1, 1)) >>> print(gen_array_ops.unique_v2(reshaped_min_maxed_grayscale_tf_image, axis=[-2])) UniqueV2(y=<tf.Tensor: shape=(2, 1), dtype=float32, numpy=array([[255.], [ 0.]], dtype=float32)>, idx=<tf.Tensor: shape=(32400,), dtype=int32, numpy=array([0, 0, 0, ..., 0, 0, 0], dtype=int32)>) >>> print(tf.math.count_nonzero(min_maxed_grayscale_tf_image)) tf.Tensor(31760, shape=(), dtype=int64) """ cond = tf.greater(tf_img, tf.ones_like(tf_img) * threshold) mask = tf.where(cond, tf.ones_like(tf_img) * min_max[1], tf.ones_like(tf_img) * min_max[0]) return mask def tf_equalize_histogram(tf_img): """ Tensorflow Image Histogram Equalization https://stackoverflow.com/questions/42835247/how-to-implement-histogram-equalization-for-images-in-tensorflow Parameters ---------- tf_img : `Tensor` of image Input `Tensor` image `tf_img` Returns ------- `Tensor` of image Equalized histogram image of input `Tensor` image `tf_img`. """ values_range = tf.constant([0.0, 255.0], dtype=tf.float32) histogram = tf.histogram_fixed_width(tf.cast(tf_img, tf.float32), values_range, 256) cdf = tf.cumsum(histogram) cdf_min = cdf[tf.reduce_min(tf.where(tf.greater(cdf, 0)))] img_shape = tf.shape(tf_img) pix_cnt = img_shape[-3] * img_shape[-2] px_map = tf.round(tf.cast(cdf - cdf_min, tf.float32) * 255.0 / tf.cast(pix_cnt - 1, tf.float32)) px_map = tf.cast(px_map, tf.uint8) eq_hist = tf.expand_dims(tf.gather_nd(px_map, tf.cast(tf_img, tf.int32)), 2) return eq_hist def tf_get_all_colors(tf_img): """ Get all colors in `Tensor` image `tf_img`. The result always contains [0, 0, 0]. Parameters ---------- tf_img : `Tensor` of image Input `Tensor` image `tf_img`. Should be color image. Returns ------- `Tensor` array of colors All colors in `Tensor` image. Examples -------- >>> from imagemodel.common.utils import tf_images >>> sample_img = tf_images.decode_png("tests/test_resources/sample.png", 3) >>> print(tf_images.tf_get_all_colors(sample_img)) tf.Tensor( [[245. 245. 245.] [ 71. 71. 71.] [ 0. 0. 0.] [255. 145. 77.] [ 72. 72. 72.]], shape=(5, 3), dtype=float32) """ scs = tf.reshape(tf_img, (-1, 3)) scs = gen_array_ops.unique_v2(scs, axis=[-2])[0] scs = tf.cond( tf.reduce_any(tf.reduce_all(tf.equal(scs, [0, 0, 0]), axis=-1)), lambda: scs, lambda: tf.concat([tf.constant([[0, 0, 0]], dtype=tf_img.dtype), scs], axis=-2)) scs = tf.cast(scs, tf.float32) return scs def tf_generate_color_map(img): img_color = tf_get_all_colors(img) img_color_index = tf.range(tf.shape(img_color)[-2], dtype=tf.float32) return img_color_index, img_color def tf_image_shrink(detached_img, bin_num: int, resize_by_power_of_two: int = 0): ratio = 2 ** resize_by_power_of_two result = tf.map_fn( lambda x: tf_shrink3D(x, tf.shape(x)[-3] // ratio, tf.shape(x)[-2] // ratio, bin_num), detached_img) result = tf.divide(result, ratio ** 2) return result # noinspection PyPep8Naming def tf_shrink3D(data, rows: int, cols: int, channels: int): """ Shrink 3D `Tensor` data. Parameters ---------- data : `Tensor` `Tensor` data to shrink. Shape should be 3-dimension. rows : int Number of rows cols : int Number of columns channels : int Number of channels Returns ------- Shrinked `Tensor` array Shrinked 3d `Tensor` Examples -------- >>> import numpy as np >>> from imagemodel.common.utils import tf_images >>> a = tf.constant( ... np.array( ... [ ... [[1, 2], [3, 4]], ... [[5, 6], [7, 8]], ... [[9, 10], [11, 12]], ... [[13, 14], [15, 16]], ... ] ... ) ... ) >>> print(tf_shrink3D(a,2,1,2)) tf.Tensor( [[[16 20]] # [[[ 1+3+5+7, 2+4+6+8]], [[48 52]]], shape=(2, 1, 2), dtype=int64) # [[9+11+13+15, 10+12+14+16]]] >>> print(tf_shrink3D(a,2,1,1)) tf.Tensor( [[[ 36]] # [[[ 1+3+5+7+2+4+6+8]], [[100]]], shape=(2, 1, 1), dtype=int64) # [[9+11+13+15+10+12+14+16]]] """ return tf.reduce_sum( tf.reduce_sum( tf.reduce_sum( tf.reshape( data, [ rows, tf.shape(data)[-3] // rows, cols, tf.shape(data)[-2] // cols, channels, tf.shape(data)[-1] // channels, ]), axis=-5 # axis=1 ), axis=-3 # axis=2 ), axis=-1) # axis=3 def get_dynamic_size(_tensor): return tf.where([True, True, True, True], tf.shape(_tensor), [0, 0, 0, 0]) def tf_extract_patches(tf_array, ksize, img_wh, channel): """ Extract Patches from `tf_array`. Other implementation of `tf.image.extract_patches`. Improved `tf_extract_patches`. Should be reshape after with `tf.reshape(results, (batch, img_wh, img_wh, ksize*ksize, channel))`. - Conditions. - Padding is "SAME". - Stride is 1. - Width and Height are equal. Parameters ---------- tf_array : `Tensor` Tensor array to extract patches. Shape should be (batch, height, width, channel). ksize : int Should be odd integer. img_wh : int Width and Height of square image. channel : int Number of channels. Returns ------- `Tensor` Patch extracted `tf_array` """ padding_size = max((ksize - 1), 0) // 2 zero_padded_image = tf.keras.layers.ZeroPadding2D((padding_size, padding_size))(tf_array) # zero_padded_image = tf.pad( # batch_image, # [[0, 0], [padding_size, padding_size], [padding_size, padding_size], [0, 0]], # ) b_size = get_dynamic_size(tf_array) batch_size = b_size[0] wh_indices = tf.range(ksize) + tf.range(img_wh)[:, tf.newaxis] a1 = tf.repeat(tf.repeat(wh_indices, ksize, axis=1), img_wh, axis=0) a2 = tf.tile(wh_indices, (img_wh, ksize)) m = tf.stack([a1, a2], axis=-1) m = tf.expand_dims(m, axis=0) m1 = tf.repeat(m, batch_size, axis=0) m2 = tf.reshape(m1, (-1, img_wh, img_wh, ksize, ksize, 2)) gg = tf.gather_nd(zero_padded_image, m2, batch_dims=1) gg2 = tf.reshape(gg, (-1, img_wh, img_wh, ksize * ksize * channel)) return gg2
StarcoderdataPython
1790102
import asyncio def flatten(to_flatten): return list(flatten_generator(to_flatten)) def flatten_generator(to_flatten): return ( item for sub_list_or_generator in to_flatten for item in sub_list_or_generator ) async def repeat_until_cancelled(context, exception_intervals, to_repeat, to_repeat_args=(), min_duration=0): loop = asyncio.get_running_loop() num_exceptions_in_chain = 0 while True: try: start = loop.time() await to_repeat(*to_repeat_args) end = loop.time() num_exceptions_in_chain = 0 await asyncio.sleep(max(min_duration - (end - start), 0)) except asyncio.CancelledError: break except BaseException: interval_index = min(num_exceptions_in_chain, len(exception_intervals) - 1) exception_interval = exception_intervals[interval_index] num_exceptions_in_chain += 1 context.logger.exception( 'Raised exception in async_repeat_until_cancelled. ' 'Waiting %s seconds until looping.', exception_interval) context.raven_client.captureException() try: await asyncio.sleep(exception_interval) except asyncio.CancelledError: break
StarcoderdataPython
4837678
from datetime import date from pathlib import Path import re import sys from typing import Tuple from invoke import task TOP_DIR = Path(__file__).parent.resolve() def update_file(filename: str, sub_line: Tuple[str, str], strip: str = None): """Utility function for tasks to read, update, and write files""" with open(filename, "r") as handle: lines = [ re.sub(sub_line[0], sub_line[1], line.rstrip(strip)) for line in handle ] with open(filename, "w") as handle: handle.write("\n".join(lines)) handle.write("\n") @task def update_version(_, version=""): """Update package version to today's date using CalVer""" if version: if re.match(r"20[2-9][0-9]\.1?[0-9]\.[1-3]?[0-9].*", version) is None: sys.exit( f"Error: Passed version ({version}) does to match a date in the format " "YYYY.(M)M.(D)D." ) else: # Use today's date today = date.today() version = f"{today.year}.{today.month}.{today.day}" update_file( TOP_DIR.joinpath("tools_optimade_client/__init__.py"), (r"__version__ = .+", f'__version__ = "{version}"'), ) update_file( TOP_DIR.joinpath("setup.py"), (r"version=([^,]+),", f'version="{version}",') ) print(f"Bumped version to {version} !")
StarcoderdataPython
18039
#!/usr/bin/env python # # Creates resources # This script creates VPC/security group/keypair if not already present import logging import os import sys import time from . import aws_util as u from . import util DRYRUN = False DEBUG = True # Names of Amazon resources that are created. These settings are fixed across # all runs, and correspond to resources created once per user per region. PUBLIC_TCP_RANGES = [ 22, # ssh (8888, 8899), # ipython notebook ports 6379, # redis port (6006, 6016) # tensorboard ports ] PUBLIC_UDP_RANGES = [(60000, 61000)] # mosh ports logger = logging.getLogger(__name__) def network_setup(): """Creates VPC if it doesn't already exists, configures it for public internet access, returns vpc, subnet, security_group""" ec2 = u.get_ec2_resource() client = u.get_ec2_client() existing_vpcs = u.get_vpc_dict() zones = u.get_zones() # create VPC from scratch. Remove this if default VPC works well enough. vpc_name = u.get_vpc_name() if u.get_vpc_name() in existing_vpcs: logger.info("Reusing VPC " + vpc_name) vpc = existing_vpcs[vpc_name] else: logger.info("Creating VPC " + vpc_name) vpc = ec2.create_vpc(CidrBlock='192.168.0.0/16') # enable DNS on the VPC local_response = vpc.modify_attribute(EnableDnsHostnames={"Value": True}) assert u.is_good_response(local_response) local_response = vpc.modify_attribute(EnableDnsSupport={"Value": True}) assert u.is_good_response(local_response) vpc.create_tags(Tags=u.create_name_tags(vpc_name)) vpc.wait_until_available() gateways = u.get_gateway_dict(vpc) gateway_name = u.get_gateway_name() if gateway_name in gateways: logger.info("Reusing gateways " + gateway_name) else: logger.info("Creating internet gateway " + gateway_name) ig = ec2.create_internet_gateway() ig.attach_to_vpc(VpcId=vpc.id) ig.create_tags(Tags=u.create_name_tags(gateway_name)) # check that attachment succeeded attach_state = u.extract_attr_for_match(ig.attachments, State=-1, VpcId=vpc.id) assert attach_state == 'available', "vpc %s is in state %s" % (vpc.id, attach_state) route_table = vpc.create_route_table() route_table_name = u.get_route_table_name() route_table.create_tags(Tags=u.create_name_tags(route_table_name)) dest_cidr = '0.0.0.0/0' route_table.create_route(DestinationCidrBlock=dest_cidr, GatewayId=ig.id) assert len(zones) <= 16 # for cidr/20 to fit into cidr/16 ip = 0 for zone in zones: cidr_block = '192.168.%d.0/20' % (ip,) ip += 16 logging.info("Creating subnet %s in zone %s" % (cidr_block, zone)) subnet = vpc.create_subnet(CidrBlock=cidr_block, AvailabilityZone=zone) subnet.create_tags(Tags=[{'Key': 'Name', 'Value': f'{vpc_name}-subnet'}, {'Key': 'Region', 'Value': zone}]) local_response = client.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet.id) assert u.is_good_response(local_response) u.wait_until_available(subnet) assert subnet.map_public_ip_on_launch, "Subnet doesn't enable public IP by default, why?" route_table.associate_with_subnet(SubnetId=subnet.id) existing_security_groups = u.get_security_group_dict(vpc.id) security_group_name = u.get_security_group_name() if security_group_name in existing_security_groups: logger.info("Reusing security group " + security_group_name) security_group = existing_security_groups[security_group_name] assert security_group.vpc_id == vpc.id, f"Found security group {security_group} " \ f"attached to {security_group.vpc_id} but expected {vpc.id}" else: logging.info("Creating security group " + security_group_name) security_group = ec2.create_security_group( GroupName=security_group_name, Description=security_group_name, VpcId=vpc.id) cidr_ip = os.environ.get('SCLUSTER_SECURITY_GROUP_CidrIp', '0.0.0.0/0') security_group.create_tags(Tags=u.create_name_tags(security_group_name)) # allow ICMP access for public ping security_group.authorize_ingress( CidrIp='0.0.0.0/0', IpProtocol='icmp', FromPort=-1, ToPort=-1 ) # open public ports # always include SSH port which is required for basic functionality assert 22 in PUBLIC_TCP_RANGES, "Must enable SSH access" for port in PUBLIC_TCP_RANGES: if util.is_iterable(port): assert len(port) == 2 from_port, to_port = port else: from_port, to_port = port, port response = security_group.authorize_ingress( IpProtocol="tcp", CidrIp=cidr_ip, FromPort=from_port, ToPort=to_port ) assert u.is_good_response(response) for port in PUBLIC_UDP_RANGES: if util.is_iterable(port): assert len(port) == 2 from_port, to_port = port else: from_port, to_port = port, port response = security_group.authorize_ingress(IpProtocol="udp", CidrIp=cidr_ip, FromPort=from_port, ToPort=to_port) assert u.is_good_response(response) return vpc, security_group def keypair_setup(): """Creates keypair if necessary, saves private key locally, returns contents of private key file.""" os.system('mkdir -p ' + u.PRIVATE_KEY_LOCATION) keypair_name = u.get_keypair_name() keypair = u.get_keypair_dict().get(keypair_name, None) keypair_fn = u.get_keypair_fn() if keypair: print("Reusing keypair " + keypair_name) # check that local pem file exists and is readable assert os.path.exists( keypair_fn), "Keypair %s exists, but corresponding .pem file %s is not found, delete keypair %s through " \ "console and run again to recreate keypair/.pem together" % ( keypair_name, keypair_fn, keypair_name) keypair_contents = open(keypair_fn).read() assert len(keypair_contents) > 0 else: print("Creating keypair " + keypair_name) ec2 = u.get_ec2_resource() assert not os.path.exists( keypair_fn), "previous keypair exists, delete it with 'sudo rm %s' and also delete corresponding " \ "keypair through console" % (keypair_fn) keypair = ec2.create_key_pair(KeyName=keypair_name) open(keypair_fn, 'w').write(keypair.key_material) os.system('chmod 400 ' + keypair_fn) return keypair def placement_group_setup(group_name): """Creates placement_group group if necessary. Returns True if new placement_group group was created, False otherwise.""" existing_placement_groups = u.get_placement_group_dict() group = existing_placement_groups.get(group_name, None) if group: assert group.state == 'available' assert group.strategy == 'cluster' print("Reusing group ", group.name) return group print("Creating group " + group_name) ec2 = u.get_ec2_resource() group = ec2.create_placement_group(GroupName=group_name, Strategy='cluster') return group def create_resources(): logger.info(f"Creating {u.get_prefix()} resources in region {u.get_region()}") vpc, security_group = network_setup() keypair_setup() # saves private key locally to keypair_fn # create EFS efss = u.get_efs_dict() efs_name = u.get_efs_name() efs_id = efss.get(efs_name, '') if not efs_id: logger.info("Creating EFS " + efs_name) efs_id = u.create_efs(efs_name) else: logger.info("Reusing EFS " + efs_name) efs_client = u.get_efs_client() # create mount target for each subnet in the VPC # added retries because efs is not immediately available max_failures = 10 retry_interval_sec = 1 for subnet in vpc.subnets.all(): for retry_attempt in range(max_failures): try: sys.stdout.write("Creating efs mount target for %s ... " % (subnet.availability_zone,)) sys.stdout.flush() response = efs_client.create_mount_target( FileSystemId=efs_id, SubnetId=subnet.id, SecurityGroups=[security_group.id] ) if u.is_good_response(response): logger.info("success") break except Exception as e: if 'already exists' in str(e): # ignore "already exists" errors logger.info('already exists') break # Takes couple of seconds for EFS to come online, with # errors like this: # Creating efs mount target for us-east-1f ... Failed with An error occurred (IncorrectFileSystemLifeCycleState) when calling the CreateMountTarget operation: None, retrying in 1 sec logger.info("Got %s, retrying in %s sec" % (str(e), retry_interval_sec)) time.sleep(retry_interval_sec) else: logger.info("Giving up.") if __name__ == '__main__': create_resources()
StarcoderdataPython
4815304
<reponame>Ricyteach/candemachine def process(ilines): pass
StarcoderdataPython
163686
<filename>packages/pyre/h5/Schema.py<gh_stars>0 #-*- coding: utf-8 -*- # # <NAME> <<EMAIL>> # (c) 1998-2022 all rights reserved # superclass from pyre.patterns.AttributeClassifier import AttributeClassifier # the base class for my descriptors from .Identifier import Identifier # dataset harvester class Schema(AttributeClassifier): """ Harvest dataset descriptors from h5 groups """ # metamethods def __new__(cls, name, bases, attributes, **kwds): """ Build the class record of a new h5 group """ # N.B.: # if there are any additional class variables to be attached to the class record # they must be added carefully to make sure {__setattr__} doesn't trigger # here, for example, we modify {attributes} before chaining up in order to build and # attach the {pyre_identifiers} # make a table with the known identifiers and add it to the pile of attributes attributes["pyre_identifiers"] = { name: identifier for name, identifier in cls.pyre_harvestIdentifiers(attributes=attributes) } # build the record and return it return super().__new__(cls, name, bases, attributes, **kwds) def __call__(self, **kwds): """ Build an instance of one of my classes """ # build the instance location = super().__call__(**kwds) # and return the new instance return location def __getattr__(self, name): """ Look up the value of {name} in one of my instances """ # we are here only when normal attribute look up fails in one of my instances # currently, there is nothing useful for me to do here, so complain raise AttributeError # as of 3.10: AttributeError(name=name, obj=self) def __setattr__(self, name, value): """ Assign {name} to {value} in one of my instances """ # check whether try: # {name} is one the identifiers in my {pyre_identifiers} identifier = self.pyre_identifiers[name] # if not except KeyError: # move on pass # if it is else: # interpret this assignment as an attempt to set a new default value for it identifier.default = value # and done return # if {value} is an {Identifier} instance if isinstance(value, Identifier): # add it to {pyre_identifiers} self.pyre_identifiers[name] = value # and bind it value.__set_name__(cls=self, name=name) # chain up to handle normal assignment return super().__setattr__(name, value) # implementation details @classmethod def pyre_harvestIdentifiers(cls, attributes): """ Scan {attributes} for identifiers """ # examine the attributes and select the identifiers yield from cls.pyre_harvest(attributes=attributes, descriptor=Identifier) # all done return # end of file
StarcoderdataPython
1669209
import ujson with open("config.json") as f: CONFIG = ujson.load(f)
StarcoderdataPython
1701156
<reponame>01studio-lab/MicroPython_Examples ''' 实验名称:水位传感器 版本:v1.0 日期:2021.5 作者:01Studio 【www.01Studio.org】 开发平台:01Studio 达芬奇 说明:通过水位传感器对水位测量并显示。 ''' #导入相关模块 from machine import Pin, ADC from tftlcd import LCD43R import time #定义常用颜色 WHITE=(255,255,255) BLACK = (0,0,0) BLUE=(0,0,255) #初始化LCD d=LCD43R() d.fill(WHITE)#填充白色 #初始化ADC Water_level = ADC('B1') #显示标题 d.printStr('01Studio Water Level Test', 10, 10, BLUE, size=4) while True: value=Water_level.read_u16() #获取ADC数值 #LCD显示 d.printStr('Vol:'+str('%.2f'%(value/4095*3.3))+" V", 10, 100, BLACK, size=4) d.printStr('Value:'+str(value)+" ", 10, 200, BLACK, size=4) d.printStr("(4095)", 300, 200, BLACK, size=4) #判断水位,分5档 if 0 <= value <=600: d.printStr('0cm', 10, 300, BLACK, size=4) if 600 < value <=900: d.printStr('1cm', 10, 300, BLACK, size=4) if 900 < value <=1200: d.printStr('2cm', 10, 300, BLACK, size=4) if 1200 < value <=1300: d.printStr('3cm ', 10, 300, BLACK, size=4) if 1300 < value: d.printStr('4cm ', 10, 300, BLACK, size=4) time.sleep(1)#延时1秒
StarcoderdataPython
1436
import requests from bs4 import BeautifulSoup import urllib.request import os import random import time def html(url): user_agents = [ 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11', 'Opera/9.25 (Windows NT 5.1; U; en)', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)', 'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12', 'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9', "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.04 Chromium/16.0.912.77 Chrome/16.0.912.77 Safari/535.7", "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0 "] user_agent = random.choice(user_agents) headers = { 'User-Agent': user_agent, 'Accept-Encoding': 'gzip'} req = requests.get(url=url, headers=headers) html_doc = req.text soup = BeautifulSoup(html_doc, "html.parser") times = soup.select("time") views = soup.select("p.label-key > b") active_str = str(views[2]) active = active_str[active_str.find("title=\"") + 7:active_str.find("Z")] answers = soup.select("#answers-header > div > h2 >span") question_content = soup.select("div.post-text") tags = soup.select("#question > div.post-layout > div.postcell.post-layout--right > " "div.post-taglist.grid.gs4.gsy.fd-column > div >a") title = soup.select("h1 >a") tags_str = "" item = [] for tag in tags: tags_str += tag.get_text() + "," answer_contetnts = [] for i in range(1, len(question_content)): answer_contetnts.append(question_content[i]) for i in range(len(times)): if len(times[i].get_text()) > 1: asked_time = times[i].get("datetime").replace("T", " ") item.append(title[ 0].get_text()) # title views answersnum asked_time tag_str active_time quest_content_ text answer_content_list item.append(views[1].get_text()) item.append(answers[0].get_text()) item.append(asked_time) item.append(tags_str) item.append(active) item.append(question_content[0]) item.append(answer_contetnts) print(item) # updatetosql(item) def updatetosql(item): ansers_text = "[split]".join(item[7]) updatesql = "UPDATE `t_stackoverflow_question` " \ "SET `tags`='%s', `views`='%s', `answers_num`='%s', `asked_time`='%s', `last_active_time`='%s', `question_content`='%s', `answers_contetnt`='%s' " \ "WHERE (`question_id`='%s') " \ % (item[4], item[1], item[2], item[3], item[5], item[6], ansers_text, item[0],) pass if __name__ == '__main__': html("https://stackoverflow.com/questions/50119673/nginx-fast-cgi-cache-on-error-page-404")
StarcoderdataPython
1741749
<reponame>drcrook1/iot_edge_starter<filename>EdgeSolution/modules/SampleModule/sample_module.py<gh_stars>0 """ @Author: <NAME> @Copyright: Microsoft Corporation 2022 """ from enum import Enum import logging import asyncio from azure.iot.device.aio import IoTHubModuleClient from azure.iot.device import MethodResponse # TODO: Module 2 Module Comms & Upstream Telemetry/Messages class Sample_Twin_Properties(): """ Class encapsulating the Twin Properties for this module. """ SleepTime : int = None def to_dict(self) -> dict: """ returns a dictionary representation """ result = {} for k,v in self.__dict__.items(): result[k] = v return result class Sample_Module(): """ Representation of the Module Object """ module_client : IoTHubModuleClient = None module_twin_properties : Sample_Twin_Properties = None def initialize(self): """ Initialize the stateful object of this module. """ self.module_twin_properties = Sample_Twin_Properties() self.module_twin_properties.SleepTime = 25 # Configure Client & Handlers self.module_client = IoTHubModuleClient.create_from_edge_environment() self.module_client.on_twin_desired_properties_patch_received = self._receive_twin_patch_handler self.module_client.on_method_request_received = self._hello_module_command self.module_client.on_message_received = self._handle_message_received def _handle_message_received(self, message): """ Handler for receiving a message """ print("input: {} - data: {} - properties: {}".format(message.input_name, message.data, message.custom_properties)) async def _receive_twin_patch_handler(self, twin_patch): """ Receive a twin patch update. """ logging.info("Twin Patch received") print("I received a twin patch") # Did they update Temperature Threshold? if("SleepTime" in twin_patch): self.module_twin_properties.SleepTime = twin_patch["SleepTime"] await self.module_client.patch_twin_reported_properties({"SleepTime" : self.module_twin_properties.SleepTime}) async def _hello_module_command(self, method_request): """ Receive and handle a method request/command, note, you must respond to the command for it to read as success, otherwise it will fail. """ print("HELLO!!!!!") method_response = MethodResponse.create_from_method_request(method_request, 200, "HELLO!!!!") await self.module_client.send_method_response(method_response)
StarcoderdataPython
1709723
<gh_stars>0 from ConfigLoader import ConfigLoader import numpy as np from numpy import linalg as LA from Plotter import Plotter class FindEquilibria: ''' this class implements the algorithms to find the equilibria of the system ''' def __init__(self): config = ConfigLoader() self.config = config.params self.a, self.b = self.setParameters() self.plotter = Plotter() self.k, self.sigma = self.setPositiveControlParameters() def setParameters(self): a = [[self.config['a11'], self.config['a12'], self.config['a13'], self.config['a14']], \ [self.config['a21'], self.config['a22'], self.config['a23'], self.config['a24']], \ [self.config['a31'], self.config['a32'], self.config['a33'], self.config['a34']], \ [self.config['a41'], self.config['a42'], self.config['a43'], self.config['a44']]] b = [self.config['b1'], self.config['b2'], self.config['b3'], self.config['b4']] if 'X' in self.config and 'Y' in self.config: X = self.config['X'] Y = self.config['Y'] a[1][2] = -X a[2][1] = X/2 a[1][3] = -Y a[3][1] = Y/2 return a, b def setPositiveControlParameters(self): k = [self.config['k1'], self.config['k2'], self.config['k3'], self.config['k4']] sigma = self.config['sigma'] return k, sigma def setParametersAgain(self): self.a, self.b = self.setParameters() def findEquilibria(self, printEq=True): eq = np.matmul(np.linalg.inv(np.array(self.a)), self.b).tolist() if self.config['printEquilibria']: print('The equilibria of the system are:\n') if printEq: for el in eq: print(str(el) + '\n') return eq def linearise(self, equilibrium, considerControl:bool=False, *args): # linearised dynamics b = self.b a = self.a k = self.k x0 = equilibrium[0] y0 = equilibrium[1] z0 = equilibrium[2] w0 = equilibrium[3] for el in args: u = el break if self.config['useControl'] and considerControl and self.config['usePositiveControl']: dyn_lin = [[b[0] - 2*a[0][0]*x0 - a[0][1]*y0 - a[0][2]*z0 - a[0][3]*w0 + k[0]*u, -a[0][1]*x0, -a[0][2]*x0, -a[0][3]*x0], \ [-a[1][0]*y0, b[1] - a[1][0]*x0 - 2*a[1][1]*y0 - a[1][2]*z0 - a[1][3]*w0 + k[1]*u, -a[1][2]*y0, -a[1][3]*y0], \ [-a[2][0]*z0, -a[2][1]*z0, b[2] - a[2][0]*x0 - a[2][1]*y0 - 2*a[2][2]*z0 - a[2][3]*w0 + k[2]*u, -a[2][3]*z0], \ [-a[3][0]*w0, -a[3][1]*w0, -a[3][2]*w0, b[3] - a[3][0]*x0 - a[3][1]*y0 - a[3][2]*z0 - 2*a[3][3]*w0 + k[3]*u]] else: dyn_lin = [[b[0] - 2*a[0][0]*x0 - a[0][1]*y0 - a[0][2]*z0 - a[0][3]*w0, -a[0][1]*x0, -a[0][2]*x0, -a[0][3]*x0], \ [-a[1][0]*y0, b[1] - a[1][0]*x0 - 2*a[1][1]*y0 - a[1][2]*z0 - a[1][3]*w0, -a[1][2]*y0, -a[1][3]*y0], \ [-a[2][0]*z0, -a[2][1]*z0, b[2] - a[2][0]*x0 - a[2][1]*y0 - 2*a[2][2]*z0 - a[2][3]*w0, -a[2][3]*z0], \ [-a[3][0]*w0, -a[3][1]*w0, -a[3][2]*w0, b[3] - a[3][0]*x0 - a[3][1]*y0 - a[3][2]*z0 - 2*a[3][3]*w0]] if self.config['printEquilibria']: print(equilibrium) print('---') print(dyn_lin) return dyn_lin def getEigens(self): eq = self.findEquilibria() dyn_lin = self.linearise(eq) eigenvalues, _ = LA.eig(dyn_lin) if self.config['plotEigenvalues'] and not self.config['plotStabilityXY']: self.plotter.plotEigen(eigenvalues) return eigenvalues
StarcoderdataPython
147918
<filename>tests/mock-webserver.py #!/usr/bin/env python ''' A bottle+gevent based webservice suitable for testing CoCrawler ''' try: from gevent import monkey monkey.patch_all() except ImportError: print('gevent not present; that\'s OK for test purposes') pass import os import random from bottle import route, run, request, abort, redirect def generate_robots(host): if host.startswith('robotsdenyall'): return 'User-Agent: *\nDisallow: /\n' if host.startswith('404'): abort(404, 'No robots.txt here') if host.startswith('500'): abort(500, 'I don\'t know what I\'m doing!') if host.startswith('302'): # unfortunately, we can't use a fake hostname here. # XXX figure out how to get this constant out of here... header? redirect('http://127.0.0.1:8080/robots.txt.302') if host.startswith('pdfrobots'): return '%PDF-1.3\n' return 'User-Agent: *\nDisallow: /denied/\n' def generate_robots_302(host): host = 'do-not-redirect-me' return generate_robots(host) siteheader = '''<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> ''' sitelink = '<url><loc>/ordinary/{}</loc></url>\n' sitefooter = '</urlset>\n' def generate_sitemap(host): mylinks = '' for i in range(10): mylinks += sitelink.format(i) return siteheader + mylinks + sitefooter header = ''' <html><head><title>Title</title></head><body> ''' links = '''<ul> <li><a href="{}">next link</a> <li><a href="{}">next link</a> <li><a href="/denied/">but not this one</a> </ul> ''' trailer = ''' </body></html> ''' def generate_ordinary(name, host): # send 302.foo/ordinary/0 to 302.foo/ordinary/1, which will not be a redirect if host.startswith('302') and name <= 0: redirect('/ordinary/{}'.format(name+1)) if host.startswith('503'): abort(503, 'Slow down, you move too fast. You got to make the morning last.\n') mylinks = links.format((name+1) % 1000, (2*name) % 1000) return header + mylinks + trailer def generate_ordinary_503s(name, host): if random.randint(1, 9) < 2: # 10% chance abort(503, 'Slow down, you move too fast. You got to make the morning last.\n') return generate_ordinary(name, host) def generate_code(code, host): abort(code, 'Here is your code {}; host is {}\n'.format(code, host)) def generate_trap(name, host): mylinks = links.format(name+1, 2*name) return header + mylinks + trailer # bottle stuff ------------------------------------------------------------ @route('/hello') def hello(): return 'Hello World! Host is {}\n'.format(request.get_header('Host')) @route('/robots.txt') def robots(): host = request.get_header('Host') return generate_robots(host) @route('/robots.txt.302') def robots302(): host = request.get_header('Host') return generate_robots_302(host) @route('/sitemap.xml') def sitemap(): host = request.get_header('Host') return generate_sitemap(host) @route('/ordinary/<name:int>') def ordinary(name): host = request.get_header('Host') return generate_ordinary(name, host) @route('/ordinary-with-503s/<name:int>') def ordinary503(name): host = request.get_header('Host') return generate_ordinary_503s(name, host, ua) @route('/code/<code:int>') def code(code): host = request.get_header('Host') return generate_code(code, host) @route('/trap/<name:int>/') def trap(name): host = request.get_header('Host') return generate_trap(name, host) port = os.getenv('PORT') or 8080 run(host='localhost', port=port)
StarcoderdataPython
1737054
import random import time import matplotlib.pyplot as plt # ------------------------------------------------------------------------------ def objective_function(O): x = O[0] y = O[1] nonlinear_constraint = (x - 1) ** 3 - y + 1 linear_constraint = x + y - 2 if nonlinear_constraint > 0: penalty1 = 1 else: penalty1 = 0 if linear_constraint > 0: penalty2 = 1 else: penalty2 = 0 z = (1 - x) ** 2 + 100 * (y - x ** 2) ** 2 + penalty1 + penalty2 return z bounds = [(-1.5, 1.5), (-0.5, 2.5)] # upper and lower bounds of variables nv = 2 # number of variables mm = -1 # if minimization problem, mm = -1; if maximization problem, mm = 1 # PARAMETERS OF PSO particle_size = 120 # number of particles iterations = 200 # max number of iterations w = 0.8 # inertia constant c1 = 1 # cognative constant c2 = 2 # social constant # Visualization fig = plt.figure() ax = fig.add_subplot() fig.show() plt.title('Evolutionary process of the objective function value') plt.xlabel("Iteration") plt.ylabel("Objective function") # ------------------------------------------------------------------------------ class Particle: def __init__(self, bounds): self.particle_position = [] # particle position self.particle_velocity = [] # particle velocity self.local_best_particle_position = [] # best position of the particle self.fitness_local_best_particle_position = initial_fitness # initial objective function value of the best particle position self.fitness_particle_position = initial_fitness # objective function value of the particle position for i in range(nv): self.particle_position.append( random.uniform(bounds[i][0], bounds[i][1])) # generate random initial position self.particle_velocity.append(random.uniform(-1, 1)) # generate random initial velocity def evaluate(self, objective_function): self.fitness_particle_position = objective_function(self.particle_position) if mm == -1: if self.fitness_particle_position < self.fitness_local_best_particle_position: self.local_best_particle_position = self.particle_position # update the local best self.fitness_local_best_particle_position = self.fitness_particle_position # update the fitness of the local best if mm == 1: if self.fitness_particle_position > self.fitness_local_best_particle_position: self.local_best_particle_position = self.particle_position # update the local best self.fitness_local_best_particle_position = self.fitness_particle_position # update the fitness of the local best def update_velocity(self, global_best_particle_position): for i in range(nv): r1 = random.random() r2 = random.random() cognitive_velocity = c1 * r1 * (self.local_best_particle_position[i] - self.particle_position[i]) social_velocity = c2 * r2 * (global_best_particle_position[i] - self.particle_position[i]) self.particle_velocity[i] = w * self.particle_velocity[i] + cognitive_velocity + social_velocity def update_position(self, bounds): for i in range(nv): self.particle_position[i] = self.particle_position[i] + self.particle_velocity[i] # check and repair to satisfy the upper bounds if self.particle_position[i] > bounds[i][1]: self.particle_position[i] = bounds[i][1] # check and repair to satisfy the lower bounds if self.particle_position[i] < bounds[i][0]: self.particle_position[i] = bounds[i][0] class PSO: def __init__(self, objective_function, bounds, particle_size, iterations): fitness_global_best_particle_position = initial_fitness global_best_particle_position = [] swarm_particle = [] for i in range(particle_size): swarm_particle.append(Particle(bounds)) A = [] for i in range(iterations): for j in range(particle_size): swarm_particle[j].evaluate(objective_function) if mm == -1: if swarm_particle[j].fitness_particle_position < fitness_global_best_particle_position: global_best_particle_position = list(swarm_particle[j].particle_position) fitness_global_best_particle_position = float(swarm_particle[j].fitness_particle_position) if mm == 1: if swarm_particle[j].fitness_particle_position > fitness_global_best_particle_position: global_best_particle_position = list(swarm_particle[j].particle_position) fitness_global_best_particle_position = float(swarm_particle[j].fitness_particle_position) for j in range(particle_size): swarm_particle[j].update_velocity(global_best_particle_position) swarm_particle[j].update_position(bounds) A.append(fitness_global_best_particle_position) # record the best fitness # Visualization ax.plot(A, color='r') fig.canvas.draw() ax.set_xlim(left=max(0, i - iterations), right=i + 3) time.sleep(0.001) print('RESULT:') print('Optimal solution:', global_best_particle_position) print('Objective function value:', fitness_global_best_particle_position) # ------------------------------------------------------------------------------ if mm == -1: initial_fitness = float("inf") # for minimization problem if mm == 1: initial_fitness = -float("inf") # for maximization problem # ------------------------------------------------------------------------------ # Main PSO PSO(objective_function, bounds, particle_size, iterations) plt.show()
StarcoderdataPython
3365406
<reponame>sacherjj/array_devices<gh_stars>1-10 from .array3710 import Load, Program, ProgramStep
StarcoderdataPython
15177
<gh_stars>0 # -*- coding: utf-8 -*- """ Created on Sat Feb 24 23:18:54 2018 @author: Rupesh """ # Multiple Linear Regression import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns plt.style.use("ggplot") # loading dependies df = pd.read_csv("50_Startups.csv") df.head() X = df.iloc[:, :-1].values y = df.iloc[:, 4].values from sklearn.preprocessing import LabelEncoder, OneHotEncoder X_cat = LabelEncoder() X[:, 3] = X_cat.fit_transform(X[:, 3]) onehot = OneHotEncoder(categorical_features = [3]) X = onehot.fit_transform(X).toarray() # avoiding the dummy variable trap X = X[:, 1:] # train test split from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2) # model from sklearn.linear_model import LinearRegression reg = LinearRegression() reg.fit(X_train, y_train) # predict y_pred = reg.predict(X_test) import skl
StarcoderdataPython
3323415
''' Created on Aug 21, 2014 @author: moloyc ''' import os import sys sys.path.insert(0,os.path.abspath(os.path.dirname(__file__) + '/' + '../..')) #trick to make it run from CLI import unittest from jnpr.openclos.util import * class TestFunctions(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testLoadDefaultConfig(self): self.assertIsNotNone(loadConfig()) def testLoadNonExistingConfig(self): self.assertIsNone(loadConfig('non-existing.yaml')) def testGetPortNamesForDeviceFamilyNullConf(self): with self.assertRaises(ValueError) as ve: getPortNamesForDeviceFamily(None, None) def testGetPortNamesForDeviceFamilyUnknownFamily(self): with self.assertRaises(ValueError) as ve: getPortNamesForDeviceFamily('unknown', {'QFX5100-24Q': {}}) error = ve.exception.message self.assertTrue('unknown' in error) def testGetPortNamesForDeviceFamily24Q(self): portNames = getPortNamesForDeviceFamily('QFX5100-24Q', {'QFX5100-24Q': {'ports':'et-0/0/[0-23]'}}) self.assertEqual(0, len(portNames['uplinkPorts'])) self.assertEqual(0, len(portNames['downlinkPorts'])) self.assertEqual(24, len(portNames['ports'])) def testGetPortNamesForDeviceFamily48S(self): portNames = getPortNamesForDeviceFamily('QFX5100-48S', {'QFX5100-48S': {'uplinkPorts':'et-0/0/[48-53]', 'downlinkPorts': 'xe-0/0/[0-47]'}}) self.assertEqual(6, len(portNames['uplinkPorts'])) self.assertEqual(48, len(portNames['downlinkPorts'])) self.assertEqual(0, len(portNames['ports'])) def testGetPortNamesForDeviceFamily96S(self): portNames = getPortNamesForDeviceFamily('QFX5100-96S', {'QFX5100-96S': {'uplinkPorts':'et-0/0/[96-103]', 'downlinkPorts': 'xe-0/0/[0-95]'}}) self.assertEqual(8, len(portNames['uplinkPorts'])) self.assertEqual(96, len(portNames['downlinkPorts'])) self.assertEqual(0, len(portNames['ports'])) def testExpandPortNameBadRegex1(self): with self.assertRaises(ValueError) as ve: expandPortName('xe-0/0/[1-1000]') def testExpandPortNameBadRegex2(self): with self.assertRaises(ValueError) as ve: expandPortName('xe-0//[1-10]') def testExpandPortNameBadRegex3(self): with self.assertRaises(ValueError) as ve: expandPortName('-0/0/[1-10]') def testExpandPortNameEmpty(self): portNames = expandPortName('') self.assertEqual(0, len(portNames)) portNames = expandPortName(None) self.assertEqual(0, len(portNames)) def testExpandPortName(self): portNames = expandPortName('xe-0/0/[1-10]') self.assertEqual(10, len(portNames)) self.assertEqual('xe-0/0/1', portNames[0]) self.assertEqual('xe-0/0/10', portNames[9]) def testFixSqlliteDbUrlForRelativePath(self): dbUrl = fixSqlliteDbUrlForRelativePath('sqlite:////absolute-path/sqllite3.db') self.assertEqual(5, dbUrl.count('/')) dbUrl = fixSqlliteDbUrlForRelativePath('sqlite:///relative-path/sqllite3.db') if isPlatformWindows(): self.assertTrue("C:\\" in dbUrl) else: self.assertTrue(dbUrl.count('/') > 4) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
StarcoderdataPython
1655872
import random import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import onqg.dataset.Constants as Constants from onqg.models.modules.Attention import ConcatAttention from onqg.models.modules.MaxOut import MaxOut from onqg.models.modules.DecAssist import StackedRNN, DecInit class RNNDecoder(nn.Module): """ Input: (1) inputs['tgt_seq'] (2) inputs['src_seq'] (3) inputs['src_indexes'] (4) inputs['enc_output'] (5) inputs['hidden'] (6) inputs['feat_seqs'] Output: (1) rst['pred'] (2) rst['attn'] (3) rst['context'] (4) rst['copy_pred']; rst['copy_gate'] (5) rst['coverage_pred'] """ def __init__(self, n_vocab, ans_n_vocab, d_word_vec, d_model, n_layer, rnn, d_k, feat_vocab, d_feat_vec, d_enc_model, n_enc_layer, input_feed, copy, answer, separate, coverage, layer_attn, maxout_pool_size, dropout, device=None, encoder_word_emb=None): self.name = 'rnn' super(RNNDecoder, self).__init__() self.n_layer = n_layer self.layer_attn = layer_attn self.separate = separate self.coverage = coverage self.copy = copy self.maxout_pool_size = maxout_pool_size self.n_vocab_size = n_vocab input_size = d_word_vec self.input_feed = input_feed if input_feed: input_size += d_enc_model self.ans_emb_weight = encoder_word_emb self.answer = answer tmp_in = d_word_vec if answer else d_enc_model self.decInit = DecInit(d_enc=tmp_in, d_dec=d_model, n_enc_layer=n_enc_layer) self.feature = False if not feat_vocab else True if self.feature: self.feat_embs = nn.ModuleList([ nn.Embedding(n_f_vocab, d_feat_vec, padding_idx=Constants.PAD) for n_f_vocab in feat_vocab ]) # input_size += len(feat_vocab) * d_feat_vec # PS: only for test !!! feat_size = len(feat_vocab) * d_feat_vec if self.feature else 0 self.d_enc_model = d_enc_model self.word_emb_type = ans_n_vocab == n_vocab self.word_emb = nn.Embedding(n_vocab, d_word_vec, padding_idx=Constants.PAD) self.rnn = StackedRNN(n_layer, input_size, d_model, dropout, rnn=rnn) self.attn = ConcatAttention(d_enc_model + feat_size, d_model, d_k, coverage) self.readout = nn.Linear((d_word_vec + d_model + self.d_enc_model), d_model) self.maxout = MaxOut(maxout_pool_size) if copy: self.copy_switch = nn.Linear(d_enc_model + d_model, 1) self.hidden_size = d_model self.dropout = nn.Dropout(dropout) self.device = device @classmethod def from_opt(cls, opt): return cls(opt['n_vocab'], opt['ans_n_vocab'], opt['d_word_vec'], opt['d_model'], opt['n_layer'], opt['rnn'], opt['d_k'], opt['feat_vocab'], opt['d_feat_vec'], opt['d_enc_model'], opt['n_enc_layer'], opt['input_feed'], opt['copy'], opt['answer'], opt['separate'], opt['coverage'], opt['layer_attn'], opt['maxout_pool_size'], opt['dropout'], opt['device'], opt['encoder_word_emb']) def attn_init(self, context): if isinstance(context, list): context = context[-1] if isinstance(context, tuple): context = torch.cat(context, dim=-1) batch_size = context.size(0) hidden_sizes = (batch_size, self.d_enc_model) return Variable(context.data.new(*hidden_sizes).zero_(), requires_grad=False) def forward(self, inputs, max_length=300, rl_type='', generator=None): tgt_seq, src_seq, src_indexes = inputs['tgt_seq'], inputs['src_seq'], inputs['src_indexes'] if self.answer: ans_seq = inputs['ans_seq'] enc_output, hidden, feat_seqs = inputs['enc_output'], inputs['hidden'], inputs['feat_seqs'] src_pad_mask = Variable(src_seq.data.eq(50256).float(), requires_grad=False, volatile=False) # TODO: fix this magic number later if self.layer_attn: n_enc_layer = len(enc_output) src_pad_mask = src_pad_mask.repeat(1, n_enc_layer) enc_output = torch.cat(enc_output, dim=1) feat_inputs = None if self.feature: feat_inputs = [feat_emb(feat_seq) for feat_seq, feat_emb in zip(feat_seqs, self.feat_embs)] feat_inputs = torch.cat(feat_inputs, dim=2) if self.layer_attn: feat_inputs = feat_inputs.repeat(1, n_enc_layer, 1) # enc_output = torch.cat((enc_output, feat_inputs), dim=2) # PS: only for test !!! cur_context = self.attn_init(enc_output) if self.answer: ans_words = torch.sum(F.embedding(ans_seq, self.ans_emb_weight), dim=1) hidden = self.decInit(ans_words).unsqueeze(0) else: hidden = self.decInit(hidden).unsqueeze(0) self.attn.apply_mask(src_pad_mask) if rl_type: return self.rl_forward(rl_type, generator, tgt_seq, cur_context, hidden, enc_output, feat_inputs, src_indexes) else: return self.nll_forward(tgt_seq, cur_context, hidden, enc_output, feat_inputs, src_indexes) def nll_forward(self, tgt_seq, cur_context, hidden, enc_output, feat_inputs, src_indexes): tmp_context, tmp_coverage = None, None dec_outputs, coverage_output, copy_output, copy_gate_output = [], [], [], [] dec_input = self.word_emb(tgt_seq) dec_input = dec_input.transpose(0, 1) for seq_idx, dec_input_emb in enumerate(dec_input.split(1)): dec_input_emb = dec_input_emb.squeeze(0) raw_dec_input_emb = dec_input_emb if self.input_feed: dec_input_emb = torch.cat((dec_input_emb, cur_context), dim=1) dec_output, hidden = self.rnn(dec_input_emb, hidden) if self.coverage: if tmp_coverage is None: tmp_coverage = Variable(torch.zeros((enc_output.size(0), enc_output.size(1)))) if self.device: tmp_coverage = tmp_coverage.to(self.device) cur_context, attn, tmp_context, next_coverage = self.attn(dec_output, enc_output, precompute=tmp_context, coverage=tmp_coverage, feat_inputs=feat_inputs, feature=self.feature) avg_tmp_coverage = tmp_coverage / max(1, seq_idx) coverage_loss = torch.sum(torch.min(attn, avg_tmp_coverage), dim=1) tmp_coverage = next_coverage coverage_output.append(coverage_loss) else: cur_context, attn, tmp_context = self.attn(dec_output, enc_output, precompute=tmp_context, feat_inputs=feat_inputs, feature=self.feature) if self.copy: copy_prob = self.copy_switch(torch.cat((dec_output, cur_context), dim=1)) copy_prob = torch.sigmoid(copy_prob) if self.layer_attn: attn = attn.view(attn.size(0), len(enc_output), -1) attn = attn.sum(1) if self.separate: out = torch.zeros([len(attn), max_length], device=self.device if self.device else None) for i in range(len(attn)): data_length = src_indexes[i] out[i].narrow(0, 1, data_length - 1).copy_(attn[i][1:src_indexes[i]]) attn = out norm_term = attn.sum(1, keepdim=True) attn = attn / norm_term copy_output.append(attn) copy_gate_output.append(copy_prob) readout = self.readout(torch.cat((raw_dec_input_emb, dec_output, cur_context), dim=1)) maxout = self.maxout(readout) output = self.dropout(maxout) dec_outputs.append(output) dec_output = torch.stack(dec_outputs).transpose(0, 1) rst = {} rst['pred'], rst['attn'], rst['context'] = dec_output, attn, cur_context if self.copy: copy_output = torch.stack(copy_output).transpose(0, 1) copy_gate_output = torch.stack(copy_gate_output).transpose(0, 1) rst['copy_pred'], rst['copy_gate'] = copy_output, copy_gate_output if self.coverage: coverage_output = torch.stack(coverage_output).transpose(0, 1) rst['coverage_pred'] = coverage_output return rst def rl_forward(self, rl_type, generator, tgt_seq, cur_context, hidden, enc_output, feat_inputs, src_indexes): tmp_context, tmp_coverage, seq_idx = None, None, 0 dec_outputs, coverage_output, copy_output, copy_gate_output = [], [], [], [] max_length, input_seq = tgt_seq.size(-1), tgt_seq.transpose(0, 1)[0] rand_input_seq = input_seq.clone().detach() decoded_text, rand_decoded_text = [], [] init_tokens = torch.zeros(input_seq.size(), device=input_seq.device).long() rand_tokens = torch.zeros(input_seq.size(), device=input_seq.device).long() rand_choice_list = [0, 102] + [idd for idd in range(1001, self.n_vocab_size)] for i in range(max_length): decoded_text.append(input_seq.long()) rand_decoded_text.append(rand_input_seq.long()) dec_input_emb = self.word_emb(input_seq.long()) raw_dec_input_emb = dec_input_emb if self.input_feed: dec_input_emb = torch.cat((dec_input_emb, cur_context), dim=1) dec_output, hidden = self.rnn(dec_input_emb, hidden) if self.coverage: if tmp_coverage is None: tmp_coverage = Variable(torch.zeros((enc_output.size(0), enc_output.size(1)))) if self.device: tmp_coverage = tmp_coverage.to(self.device) cur_context, attn, tmp_context, next_coverage = self.attn(dec_output, enc_output, precompute=tmp_context, coverage=tmp_coverage, feat_inputs=feat_inputs, feature=self.feature) avg_tmp_coverage = tmp_coverage / max(1, seq_idx) coverage_loss = torch.sum(torch.min(attn, avg_tmp_coverage), dim=1) tmp_coverage = next_coverage coverage_output.append(coverage_loss) else: cur_context, attn, tmp_context = self.attn(dec_output, enc_output, precompute=tmp_context, feat_inputs=feat_inputs, feature=self.feature) if self.copy: copy_prob = self.copy_switch(torch.cat((dec_output, cur_context), dim=1)) copy_prob = torch.sigmoid(copy_prob) if self.layer_attn: attn = attn.view(attn.size(0), len(enc_output), -1) attn = attn.sum(1) if self.separate: out = torch.zeros([len(attn), max_length], device=self.device if self.device else None) for i in range(len(attn)): data_length = src_indexes[i] out[i].narrow(0, 1, data_length - 1).copy_(attn[i][1:src_indexes[i]]) attn = out norm_term = attn.sum(1, keepdim=True) attn = attn / norm_term copy_output.append(attn) copy_gate_output.append(copy_prob) readout = self.readout(torch.cat((raw_dec_input_emb, dec_output, cur_context), dim=1)) maxout = self.maxout(readout) output = self.dropout(maxout) dec_outputs.append(output) paddings = (input_seq.eq(Constants.PAD).float() + input_seq.eq(102).float()).eq(0).float() # TODO magic number [SEP] rand_paddings = (rand_input_seq.eq(Constants.PAD).float() + rand_input_seq.eq(102).float()).eq(0).float() ##=== next token predict ===## token_dict = F.softmax(generator(output), dim=-1) for b in range(input_seq.size(0)): ## sampling strategy 1 selected_idx = token_dict[b].multinomial(1, replacement=False).view(-1).data[0] ## sampling strategy 2 # topk = torch.topk(token_dict[b], k=5, dim=-1) # TODO magic number # selected_idx = topk[1][random.choice(range(5))].data init_tokens[b] = selected_idx.item() rand_tokens[b] = random.choice(rand_choice_list) input_seq = torch.where(paddings > 0, init_tokens, paddings.long()) rand_input_seq = torch.where(rand_paddings > 0, rand_tokens, rand_paddings.long()) seq_idx += 1 decoded_text.append(input_seq) rand_decoded_text.append(rand_input_seq) dec_output = torch.stack(dec_outputs).transpose(0, 1) rst = {} rst['pred'], rst['attn'], rst['context'] = dec_output, attn, cur_context rst['decoded_text'] = torch.stack(decoded_text).transpose(0, 1) rst['rand_decoded_text'] = torch.stack(rand_decoded_text).transpose(0, 1) if self.copy: copy_output = torch.stack(copy_output).transpose(0, 1) copy_gate_output = torch.stack(copy_gate_output).transpose(0, 1) rst['copy_pred'], rst['copy_gate'] = copy_output, copy_gate_output if self.coverage: coverage_output = torch.stack(coverage_output).transpose(0, 1) rst['coverage_pred'] = coverage_output return rst
StarcoderdataPython
78232
<filename>non_semantic_speech_benchmark/eval_embedding/finetune/models_test.py<gh_stars>1-10 # coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for non_semantic_speech_benchmark.eval_embedding.finetune.models.""" from absl.testing import absltest from absl.testing import parameterized import tensorflow as tf from non_semantic_speech_benchmark.eval_embedding.finetune import models class ModelTest(parameterized.TestCase): @parameterized.parameters( {'num_clusters': 0, 'alpha_init': 0}, {'num_clusters': 4, 'alpha_init': 0}, {'num_clusters': 0, 'alpha_init': 1.0}, ) def test_basic_model(self, num_clusters, alpha_init): m = models.get_keras_model(num_classes=5, input_length=16000, num_clusters=num_clusters, alpha_init=alpha_init) o = m(tf.zeros([4, 16000], dtype=tf.float32)) self.assertEqual(o.shape, (4, 5)) if __name__ == '__main__': absltest.main()
StarcoderdataPython
1769703
""" Lhs functions are inspired by https://github.com/clicumu/pyDOE2/blob/ master/pyDOE2/doe_lhs.py """ import numpy as np from sklearn.utils import check_random_state from scipy import spatial from ..space import Space, Categorical from .base import InitialPointGenerator def _random_permute_matrix(h, random_state=None): rng = check_random_state(random_state) h_rand_perm = np.zeros_like(h) samples, n = h.shape for j in range(n): order = rng.permutation(range(samples)) h_rand_perm[:, j] = h[order, j] return h_rand_perm class Lhs(InitialPointGenerator): """Latin hypercube sampling Parameters ---------- lhs_type : str, default='classic' - 'classic' - a small random number is added - 'centered' - points are set uniformly in each interval criterion : str or None, default='maximin' When set to None, the LHS is not optimized - 'correlation' : optimized LHS by minimizing the correlation - 'maximin' : optimized LHS by maximizing the minimal pdist - 'ratio' : optimized LHS by minimizing the ratio `max(pdist) / min(pdist)` iterations : int Defines the number of iterations for optimizing LHS """ def __init__(self, lhs_type="classic", criterion="maximin", iterations=1000): self.lhs_type = lhs_type self.criterion = criterion self.iterations = iterations def generate(self, dimensions, n_samples, random_state=None): """Creates latin hypercube samples. Parameters ---------- dimensions : list, shape (n_dims,) List of search space dimensions. Each search dimension can be defined either as - a `(lower_bound, upper_bound)` tuple (for `Real` or `Integer` dimensions), - a `(lower_bound, upper_bound, "prior")` tuple (for `Real` dimensions), - as a list of categories (for `Categorical` dimensions), or - an instance of a `Dimension` object (`Real`, `Integer` or `Categorical`). n_samples : int The order of the LHS sequence. Defines the number of samples. random_state : int, RandomState instance, or None (default) Set random state to something other than None for reproducible results. Returns ------- np.array, shape=(n_dim, n_samples) LHS set """ rng = check_random_state(random_state) space = Space(dimensions) transformer = space.get_transformer() n_dim = space.n_dims space.set_transformer("normalize") if self.criterion is None or n_samples == 1: h = self._lhs_normalized(n_dim, n_samples, rng) h = space.inverse_transform(h) space.set_transformer(transformer) return h else: h_opt = self._lhs_normalized(n_dim, n_samples, rng) h_opt = space.inverse_transform(h_opt) if self.criterion == "correlation": mincorr = np.inf for i in range(self.iterations): # Generate a random LHS h = self._lhs_normalized(n_dim, n_samples, rng) r = np.corrcoef(np.array(h).T) if len(np.abs(r[r != 1])) > 0 and \ np.max(np.abs(r[r != 1])) < mincorr: mincorr = np.max(np.abs(r - np.eye(r.shape[0]))) h_opt = h.copy() h_opt = space.inverse_transform(h_opt) elif self.criterion == "maximin": maxdist = 0 # Maximize the minimum distance between points for i in range(self.iterations): h = self._lhs_normalized(n_dim, n_samples, rng) d = spatial.distance.pdist(np.array(h), 'euclidean') if maxdist < np.min(d): maxdist = np.min(d) h_opt = h.copy() h_opt = space.inverse_transform(h_opt) elif self.criterion == "ratio": minratio = np.inf # Maximize the minimum distance between points for i in range(self.iterations): h = self._lhs_normalized(n_dim, n_samples, rng) p = spatial.distance.pdist(np.array(h), 'euclidean') if np.min(p) == 0: ratio = np.max(p) / 1e-8 else: ratio = np.max(p) / np.min(p) if minratio > ratio: minratio = ratio h_opt = h.copy() h_opt = space.inverse_transform(h_opt) else: raise ValueError("Wrong criterion." "Got {}".format(self.criterion)) space.set_transformer(transformer) return h_opt def _lhs_normalized(self, n_dim, n_samples, random_state): rng = check_random_state(random_state) x = np.linspace(0, 1, n_samples + 1) u = rng.rand(n_samples, n_dim) h = np.zeros_like(u) if self.lhs_type == "centered": for j in range(n_dim): h[:, j] = np.diff(x) / 2.0 + x[:n_samples] elif self.lhs_type == "classic": for j in range(n_dim): h[:, j] = u[:, j] * np.diff(x) + x[:n_samples] else: raise ValueError("Wrong lhs_type. Got ".format(self.lhs_type)) return _random_permute_matrix(h, random_state=rng)
StarcoderdataPython
163915
from pytest import raises, warns from bidso.find import find_in_bids, find_root, _generate_pattern from .paths import BIDS_PATH, task_ieeg filename = task_ieeg.get_filename(BIDS_PATH) def test_find_root(): assert find_root(filename).name == 'bids' assert find_root(filename, target='subject').name == 'sub-bert' assert find_root(filename, target='session').name == 'ses-day02' def test_find_in_bids_01(): found = find_in_bids(filename, subject='bert', session='day01', run='1', extension='.nii.gz', upwards=True) assert found.name == 'sub-bert_ses-day01_task-motor_run-1_bold.nii.gz' with warns(UserWarning): find_in_bids(filename, subject='bert', useless='xxx', task='motor', modality='channels', upwards=True) def test_find_in_bids_02(): with raises(FileNotFoundError): find_in_bids(filename, upwards=True, subject='xxx') def test_find_in_bids_03(): with raises(FileNotFoundError): find_in_bids(filename, upwards=True, subject='bert') def test_find_in_bids_04(): assert sum(1 for x in find_in_bids(BIDS_PATH, generator=True, subject='bert')) == 21 def test_find_in_bids_05(): with raises(FileNotFoundError): find_in_bids(BIDS_PATH, subject='xxx') with raises(StopIteration): next(find_in_bids(BIDS_PATH, subject='xxx', generator=True)) def test_find_in_bids_06(): with raises(ValueError): find_in_bids(BIDS_PATH, upwards=True, generator=True) def test_generate_pattern(): assert _generate_pattern(True, dict(subject='test')) == 'sub-test_*.*' assert _generate_pattern(False, dict(subject='test')) == 'sub-test.*' assert _generate_pattern(True, dict(subject='test', session='sess')) == 'sub-test_ses-sess_*.*' assert _generate_pattern(True, dict(subject='test', modality='mod')) == 'sub-test_*_mod.*' assert _generate_pattern(True, dict(session='sess', extension='.nii.gz')) == '*_ses-sess_*.nii.gz' assert _generate_pattern(True, dict(modality='mod', extension='.nii.gz')) == '*_mod.nii.gz' def test_wildcard_subject(): with raises(ValueError): _generate_pattern(False, dict())
StarcoderdataPython
4820252
<filename>example/blog/models.py<gh_stars>1-10 # coding: utf-8 from __future__ import unicode_literals import random try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse from django.utils.encoding import python_2_unicode_compatible from django.db import models @python_2_unicode_compatible class Category(models.Model): title = models.CharField('title', max_length=255) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.title @python_2_unicode_compatible class Tag(models.Model): title = models.CharField('title', max_length=255) class Meta: verbose_name = 'tag' verbose_name_plural = 'tags' def __str__(self): return self.title @property def colour_class(self): """Return a random CSS class for the tag.""" choices = ['primary', 'secondary', 'success', 'danger', 'warning', 'info', 'dark'] return random.choice(choices) @python_2_unicode_compatible class BlogPost(models.Model): title = models.CharField('title', max_length=255) lead = models.TextField('lead') body = models.TextField('body') category = models.ForeignKey( Category, related_name='blog_posts', blank=True, null=True, on_delete=models.PROTECT) tags = models.ManyToManyField(Tag, related_name='blog_post') class Meta: verbose_name = 'blog post' verbose_name_plural = 'blog posts' def __str__(self): return self.title def get_absolute_url(self): return reverse('blog_post_detail', kwargs={'pk': self.pk}) @python_2_unicode_compatible class TextBlock(models.Model): blog_post = models.ForeignKey(BlogPost, related_name='blocks', on_delete=models.PROTECT) title = models.CharField('title', max_length=255) body = models.TextField('body') class Meta: verbose_name = 'text block' verbose_name_plural = 'text blocks' def __str__(self): return self.title
StarcoderdataPython
1768616
<gh_stars>0 # Array; Greedy; Queue # Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle. # # However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle. # # You need to return the least number of intervals the CPU will take to finish all the given tasks. # # # # Example: # # Input: tasks = ["A","A","A","B","B","B"], n = 2 # Output: 8 # Explanation: A -> B -> idle -> A -> B -> idle -> A -> B. # # # Note: # # The number of tasks is in the range [1, 10000]. # The integer n is in the range [0, 100]. class Solution: def leastInterval(self, tasks, n): """ :type tasks: List[str] :type n: int :rtype: int """ tasksDict = collections.Counter(tasks) valList = tasksDict.values() maxLen = max(valList) output = (maxLen-1) * (n+1) for val in valList: output += val == maxLen and 1 or 0 return max(len(tasks), output)
StarcoderdataPython
19089
<filename>src/arch/riscv/RiscvCPU.py<gh_stars>1-10 # Copyright 2021 Google, Inc. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from m5.objects.BaseAtomicSimpleCPU import BaseAtomicSimpleCPU from m5.objects.BaseNonCachingSimpleCPU import BaseNonCachingSimpleCPU from m5.objects.BaseTimingSimpleCPU import BaseTimingSimpleCPU from m5.objects.BaseO3CPU import BaseO3CPU from m5.objects.BaseMinorCPU import BaseMinorCPU from m5.objects.RiscvDecoder import RiscvDecoder from m5.objects.RiscvMMU import RiscvMMU from m5.objects.RiscvInterrupts import RiscvInterrupts from m5.objects.RiscvISA import RiscvISA class RiscvCPU: ArchDecoder = RiscvDecoder ArchMMU = RiscvMMU ArchInterrupts = RiscvInterrupts ArchISA = RiscvISA class RiscvAtomicSimpleCPU(BaseAtomicSimpleCPU, RiscvCPU): mmu = RiscvMMU() class RiscvNonCachingSimpleCPU(BaseNonCachingSimpleCPU, RiscvCPU): mmu = RiscvMMU() class RiscvTimingSimpleCPU(BaseTimingSimpleCPU, RiscvCPU): mmu = RiscvMMU() class RiscvO3CPU(BaseO3CPU, RiscvCPU): mmu = RiscvMMU() class RiscvMinorCPU(BaseMinorCPU, RiscvCPU): mmu = RiscvMMU()
StarcoderdataPython
41488
try: print('enter try statement') raise Exception() print('exit try statement') except Exception as inst: print(inst.__class__.__name__)
StarcoderdataPython
1783722
#!/usr/bin/env python3 from scipy.stats import kendalltau from sklearn.metrics import accuracy_score, recall_score import numpy as np def get_combined_score(pr_mean, tr_mean, rr_std, pred_ids, labels): ''' Get combined performance score ''' k_pr_mean = kendalltau(pr_mean, labels[:, 0])[0] k_tr_mean = kendalltau(tr_mean, labels[:, 1])[0] k_rr_std = kendalltau(rr_std, labels[:, 2])[0] label_acc = recall_score( labels[:, 3], pred_ids, average='macro') label_acc = (1 - ((1 - label_acc)/(1-1/32))) kendall_avg = np.mean([k_pr_mean, k_tr_mean, k_rr_std]) combined_score = np.power( k_rr_std * k_pr_mean * k_tr_mean * label_acc, 0.25) message = "Kendall TR: {} \n".format(k_tr_mean) message += "Kendall RR: {} \n".format(k_rr_std) message += "Kendall PR: {} \n".format(k_pr_mean) message += "ID acc: {} \n".format(label_acc) message += "Avg Kendall: {} \n".format(kendall_avg) message += "Combined: {} \n".format(combined_score) return message
StarcoderdataPython
3320849
# -*- coding: utf-8 -*- """ Created on Thu Apr 16 13:32:08 2020 @author: ingvord """ from flask import request from flask_restful import Resource from functools import reduce import time class PiController(Resource): def get(self, id): return {'version': request.pi_device.qVER()} class PiControllerServoMode(Resource): def get(self, **kwargs): return request.pi_device.qSVO() def put(self, **kwargs): data = request.json request.pi_device.SVO(data) return request.pi_device.qSVO() class PiControllerReference(Resource): def get(self, **kwargs): return request.pi_device.qFRF() def put(self, **kwargs): data = request.json request.pi_device.FRF(data) stopped = False while not stopped: time.sleep(0.1) stopped = not reduce(lambda a, b: a or b, request.pi_device.IsMoving(data).values()) return request.pi_device.qPOS() class PiControllerPosition(Resource): def get(self, **kwargs): return request.pi_device.qPOS() def put(self, **kwargs): data = request.json request.pi_device.MOV(data) stopped = False while not stopped: time.sleep(0.1) stopped = not reduce(lambda a, b: a or b, request.pi_device.IsMoving(list(data.keys())).values()) return request.pi_device.qPOS() class PiControllerHome(Resource): def put(self, **kwargs): # TODO send to home all axis pass class PiControllerStop(Resource): def put(self, **kwargs): data = request.json request.pi_device.HLT(data, True) pass class PiControllerReboot(Resource): def put(self, **kwargs): request.pi_device.RBT() pass
StarcoderdataPython
1739155
<reponame>xuziheng1002/django-river<gh_stars>0 from __future__ import unicode_literals from django.db import models, transaction from django.db.models import PROTECT from django.db.models.signals import post_save, pre_delete from django.utils.translation import ugettext_lazy as _ from river.config import app_config from river.models import Workflow from river.models.base_model import BaseModel from river.models.managers.transitionmetada import TransitionApprovalMetadataManager from river.models.transitionmeta import TransitionMeta __author__ = 'ahmetdal' class TransitionApprovalMeta(BaseModel): class Meta: app_label = 'river' verbose_name = _("Transition Approval Meta") verbose_name_plural = _("Transition Approval Meta") unique_together = [('workflow', 'transition_meta', 'priority')] objects = TransitionApprovalMetadataManager() workflow = models.ForeignKey(Workflow, verbose_name=_("Workflow"), related_name='transition_approval_metas', on_delete=PROTECT) transition_meta = models.ForeignKey(TransitionMeta, verbose_name=_("Transition Meta"), related_name='transition_approval_meta', on_delete=PROTECT) permissions = models.ManyToManyField(app_config.PERMISSION_CLASS, verbose_name=_('Permissions'), blank=True) groups = models.ManyToManyField(app_config.GROUP_CLASS, verbose_name=_('Groups'), blank=True) priority = models.IntegerField(default=0, verbose_name=_('Priority'), null=True) parents = models.ManyToManyField('self', verbose_name='parents', related_name='children', symmetrical=False, db_index=True, blank=True) def __str__(self): return 'Transition: %s,Permissions: %s, Groups: %s, Order: %s' % ( self.transition_meta, ','.join(self.permissions.values_list('name', flat=True)), ','.join(self.groups.values_list('name', flat=True)), self.priority) def post_save_model(sender, instance, *args, **kwargs): parents = TransitionApprovalMeta.objects \ .filter(workflow=instance.workflow, transition_meta__destination_state=instance.transition_meta.source_state) \ .exclude(pk__in=instance.parents.values_list('pk', flat=True)) \ .exclude(pk=instance.pk) children = TransitionApprovalMeta.objects \ .filter(workflow=instance.workflow, transition_meta__source_state=instance.transition_meta.destination_state) \ .exclude(parents__in=[instance.pk]) \ .exclude(pk=instance.pk) instance = TransitionApprovalMeta.objects.get(pk=instance.pk) if parents: instance.parents.add(*parents) for child in children: child.parents.add(instance) @transaction.atomic def pre_delete_model(sender, instance, *args, **kwargs): from river.models.transitionapproval import PENDING instance.transition_approvals.filter(status=PENDING).delete() post_save.connect(post_save_model, sender=TransitionApprovalMeta) pre_delete.connect(pre_delete_model, sender=TransitionApprovalMeta)
StarcoderdataPython
96115
import os import datetime import subprocess import os.path def normalize_time(month, day, hour, minute, round_to_nearest_5m=True): if int(month) <= 9: month = "0" + month if int(day) <= 9: day = "0" + day if int(hour) <= 9: hour = "0" + hour if int(minute) <= 9: minute = "0" + minute return [month, day, hour, minute] def generate_timestamp(time): print("Generating timestamp for " + str(time)) month = str(time.month) day = str(time.day) year = str(time.year)[-2::] hour = str(time.hour) minute = str(time.minute) month, day, hour, minute = normalize_time(month, day, hour, minute) return str(month + day + year + "_" + hour + minute) def launch_kiwiclient(server, port, frequency, mode, filename, out_directory, time): args = ['python', 'kiwirecorder.py', '-s', server, '-p', str(port), '-f', str(frequency), '-m', mode, '--filename', filename, '--time-limit', f'{time+1}', '--dir', out_directory] for item in args: print(item + " ", end='') os.chdir(out_directory) output_file = out_directory + filename + ".wav" file_already_exists = os.path.exists(output_file) print(os.listdir()) this_dir = os.path.dirname(os.path.realpath(__file__)) os.chdir(this_dir) os.chdir("./kiwiclient-master") print("File exists: " + str(file_already_exists)) if not file_already_exists: print("\n" + output_file + " doesn't exist; recording...") process = subprocess.Popen(args) else: print("Error: " + output_file + " already exists; is another recording of this station currently in progress?") return # Sometimes the --time-limit argument sporadically doesn't work; This will just forcefully kill kiwirecorder # at the time limit in case it isn't already dead... try: print(f"Recording for {time} seconds... (PID={process.pid})") process.wait(timeout=time) except subprocess.TimeoutExpired: print('Time is up... killing', process.pid) process.kill() print("Done") def record(server, port, name, frequency, mode, time, start_time, out_directory): current_directory = os.path.realpath(os.getcwd()) this_dir = os.path.dirname(os.path.realpath(__file__)) # Switch to the directory containing this file os.chdir(this_dir) os.chdir("./kiwiclient-master") timestamp = generate_timestamp(start_time) filename = name + "_" + timestamp frequency = frequency.strip(',').strip("kHz") launch_kiwiclient(server, port, frequency, mode, filename, out_directory, time) os.chdir(current_directory)
StarcoderdataPython
3218230
<reponame>hettlage/salt-data-quality-site def title(): return '' def content(): return 'This is a placeholder for plots displaying telescope statistics for a week.'
StarcoderdataPython
1636244
# noqa if __name__ == "__main__": from dotenv import load_dotenv load_dotenv('.flaskenv') from robotehr.models import Base, engine from robotehr.models.cohort import * from robotehr.models.training import * from robotehr.models.data import * from robotehr.models.predictor import * Base.metadata.create_all(engine) print("Database schema update complete ...")
StarcoderdataPython
4809336
<reponame>sergiors/pyramda<gh_stars>100-1000 from .assert_dicts_equal import assert_dicts_equal from .assert_domain import assert_in_domain, assert_not_in_domain from .assert_equal import assert_equal, assert_not_equal from .assert_iterables_equal import assert_iterables_equal from .assert_pred import assert_pred_cases, true_case, false_case
StarcoderdataPython
3201779
import copy from zopeskel import abstract_buildout from zopeskel.base import var, EASY, EXPERT from zopeskel.vars import StringVar, StringChoiceVar class SilvaBuildout(abstract_buildout.AbstractBuildout): _template_dir = 'templates/silva_buildout' summary = "A buildout for Silva projects" help = """ This template creates an installation of Silva (http://www.infrae.com/products/silva). """ post_run_msg = """ Generation finished. You probably want to run python bootstrap.py and then edit buildout.cfg before running bin/buildout -v". See README.txt for details. """ required_templates = [] use_cheetah = True vars = copy.deepcopy(abstract_buildout.AbstractBuildout.vars) vars.extend([ abstract_buildout.VAR_Z2_INSTALL, StringChoiceVar( 'silva_distribution', title='Silva Distribution', description='Version of Silva to install, "stable" or "development"', default="stable", modes=(EASY, EXPERT), page='Main', choices=('stable','development'), ), abstract_buildout.VAR_ZOPE_USER, abstract_buildout.VAR_ZOPE_PASSWD, abstract_buildout.VAR_HTTP, abstract_buildout.VAR_DEBUG_MODE, abstract_buildout.VAR_VERBOSE_SEC, ] )
StarcoderdataPython
118975
"""Incorporate ETH Zurich's BIWI (EWAP) dataset into simple gridworld.""" import os from pathlib import Path from matplotlib.image import imread import matplotlib.pyplot as plt import numpy as np from .simple_gw import SimpleGridworld # Grid constants OBSTACLE = 2 GOAL = 6 PERSON = 9 ROBOT = 15 class EwapDataset: """ Contains all relevant information for EWAP dataset. """ def __init__( self, dataset_root='datasets/ewap_dataset', sequence='seq_hotel' ): dataset_path = Path(os.path.abspath(__file__)).parents[0] self.sequence_path = dataset_path / dataset_root / sequence # get obstacle map obs_map_path = self.sequence_path / 'hmap.png' self.obstacle_map = imread(str(obs_map_path.resolve())) # get pedestrian position and velocity data (obsmat.txt) self.pedestrian_data = np.loadtxt(self.sequence_path / 'obsmat.txt') # get shift and scale amount for this sequence self.pos_shift = np.loadtxt(self.sequence_path / 'shift.txt') self.scale_factor = np.loadtxt(self.sequence_path / 'scale.txt') self.frame_id = 0 self.processed_data = self.process_data() def scale(self, raw_data): scaled_data = raw_data.copy() scaled_data[:, 2:] *= self.scale_factor return scaled_data def shift(self, scaled_ped_data): shifted_ped_data = scaled_ped_data.copy() shifted_ped_data[:, 2] = shifted_ped_data[:, 2] - self.pos_shift[0] shifted_ped_data[:, 4] = shifted_ped_data[:, 4] - self.pos_shift[1] return shifted_ped_data def discretize(self, scaled_shifted_data): discrete_data = np.round(scaled_shifted_data).astype(np.int64) return discrete_data def normalize_frames(self, unnormalied_data): """ Normalizers the data frames, so first frame is integer 0. """ normalized_data = unnormalied_data.copy() normalized_data[:, 0] -= np.min(normalized_data[:, 0]) normalized_data[:, 0] = normalized_data[:, 0] / 10 return normalized_data def process_data(self): """ scales, shifts, and discretizes input data according to parameters generated by map2world.py script. normalizes frame numbers. """ scaled_data = self.scale(self.pedestrian_data) shifted_data = self.shift(scaled_data) discrete_data = self.discretize(shifted_data) # normalize frames processed_data = self.normalize_frames(discrete_data) return processed_data def pad_dataset(self, pad_amount): """ Pad dataset with obstacle pixels to ensure 2*vision_radius+1 squares are possible for feature extractor. """ self.obstacle_map = np.pad( self.obstacle_map, pad_amount + 1, # for when agent runs into edges mode='constant', constant_values=1.0 ) # shift dataset to accomodate padding self.processed_data[:, 2] += pad_amount self.processed_data[:, 4] += pad_amount def pedestrian_goal(self, pedestrian_id): """Return goal of pedestrian with the given ID. :param pedestrian_id: ID of pedestrian. """ pedestrian_mask = (self.processed_data[:, 1] == pedestrian_id) pedestrian_traj = self.processed_data[pedestrian_mask] return (pedestrian_traj[-1, 2], pedestrian_traj[-1, 4]) def get_max_frame(self): return np.max(self.processed_data[:, 0]) class EwapGridworld(SimpleGridworld): """ Env that incorporates ETHZ BIWI (EWAP) dataset. make sure the correct directory sturcture exists in order to run, i.e. /envs/datasets/ewap_dataset/seq_eth /envs/datasets/ewap_dataset/seq_hotel folders exist. Additionally, run script map2world.py for both sequences, instruction found in the script at /envs/datasets/ewap_dataset/map2world.py """ def __init__( self, ped_id, sequence='seq_hotel', dataset_root='datasets/ewap_dataset', person_thickness=2, vision_radius=40, render=False, ): """ Initialize EWAP gridworld. Make sure all files in the correct directories as specified above! :param ped_id: ID of pedestrian whose goal we adopt. :param sequence: Sequence to base world on. example: 'seq_hotel' :param dataset_root: path to root of dataset directory. :param person_thickness: The dimensions of the nxn boxes that will represent people. """ self.dataset = EwapDataset( sequence=sequence, dataset_root=dataset_root ) self.vision_radius = vision_radius self.speed = 4 self.dataset.pad_dataset(vision_radius + 2 * self.speed) self.person_thickness = person_thickness obstacle_array = np.where(self.dataset.obstacle_map == 1.0) obstacle_array = np.array(obstacle_array).T goals = self.dataset.pedestrian_goal(ped_id) super().__init__( self.dataset.obstacle_map.shape, obstacle_array, goals ) # agent velociy self.player_vel = np.zeros(2) # construct goal map self.adopt_goal(ped_id) # seperate for people position incase we want to do processing. self.person_map = self.obstacle_grid.copy() self.person_map.fill(0) # Play only until video exists self.max_steps = self.dataset.get_max_frame() # counters for debuggging data self.png_number = 0 # rendering self.render = render if self.render: self.enable_rendering() def enable_rendering(self): self.render = True self.fig = plt.figure() self.gridspec = self.fig.add_gridspec(4, 2) # setup axis ax_obs = self.fig.add_subplot(self.gridspec[0, 0]) ax_persons = self.fig.add_subplot(self.gridspec[0, 1]) ax_goal = self.fig.add_subplot(self.gridspec[1, 0]) ax_gridworld = self.fig.add_subplot(self.gridspec[2:, :]) dummy_surrounding = np.eye(2, 2) self.im_obs = ax_obs.imshow(dummy_surrounding) self.im_persons = ax_persons.imshow(dummy_surrounding) self.im_goal = ax_goal.imshow(dummy_surrounding) self.im_gridworld = ax_gridworld.imshow(self.obstacle_grid) self.im_gridworld.set_clim(vmin=0, vmax=ROBOT) self.fig.canvas.draw() plt.pause(0.000001) def disable_rendering(self): self.render = False def thicken(self, grid, target_thickness): """ thicken pixel by specified target_thickness parameter in supplied grid. :param target_thickness: thickness amount. :param grid: grid in which pixels reside. """ row_ind, col_ind = np.where(grid != 0) thick = grid.copy() assert row_ind.size == col_ind.size for i in range(row_ind.size): row = row_ind[i] col = col_ind[i] thick[ row - target_thickness:row + target_thickness + 1, col - target_thickness:col + target_thickness + 1 ] = thick[row, col] return thick def populate_person_map(self, frame_num): """Populates the person map based on input frame_num, which is the frame id of EWAP database's footage. :param frame_num: frame to get positions from. """ # clear person map self.person_map.fill(0) # Get data for current frame of simulation. frame_pedestrians = self.dataset.processed_data[ self.dataset.processed_data[:, 0] == frame_num ] self.person_map[frame_pedestrians[:, 2], frame_pedestrians[:, 4]] = 1.0 self.person_map = self.thicken(self.person_map, self.person_thickness) def adopt_goal(self, pedestrian_id): """Change the goal to the one used by pedestrian. :param pedestrian_id: ID of pedestrian whose goal we adopt. """ self.goal_pos = self.dataset.pedestrian_goal(pedestrian_id) self.goal_grid[self.goal_pos] = 1.0 # thicken the goal, making it area instead of pixel goal_thickness = self.person_thickness * 5 self.goal_grid = self.thicken(self.goal_grid, goal_thickness) def reset(self): """ reset gridworld to initial positon, with all trajectories starting again at first frame. """ super().reset() assert self.step_number == 0, 'Step number non-zero after reset!' self.player_vel = np.zeros(2) self.populate_person_map(self.step_number) return self.state_extractor().astype('float32') def reward_function(self, state, action, next_state): reward = np.array(0.0) if self.goal_grid[tuple(self.player_pos)] == 1.0: reward += 1.0 if self.obstacle_grid[tuple(self.player_pos)] == 1.0: reward += -1.0 if self.person_map[tuple(self.player_pos)] == 1.0: reward += -2.0 dist_to_goal = np.sum(np.abs(state[-2:] - state[-4:-2])) next_dist_to_goal = np.sum(np.abs(next_state[-2:] - next_state[-4:-2])) if next_dist_to_goal > dist_to_goal: reward -= 0.001 elif next_dist_to_goal < dist_to_goal: reward += 0.001 return reward def state_extractor(self): """ Extract state for CURRENT internal state of gridworld. """ row_low = self.player_pos[0] - self.vision_radius row_high = self.player_pos[0] + self.vision_radius + 1 col_low = self.player_pos[1] - self.vision_radius col_high = self.player_pos[1] + self.vision_radius + 1 obstacles = self.obstacle_grid[row_low: row_high, col_low: col_high] people = self.person_map[row_low: row_high, col_low: col_high] goals = self.goal_grid[row_low: row_high, col_low: col_high] if self.render: self.im_obs.set_data(obstacles) self.im_persons.set_data(people) self.im_goal.set_data(goals) expected_shape = ( 2 * self.vision_radius + 1, 2 * self.vision_radius + 1 ) assert obstacles.shape == expected_shape assert people.shape == expected_shape assert goals.shape == expected_shape # state vector is surroundings concatenated with player pos and goal # pos, hence the +4 size state = np.zeros(obstacles.size + people.size + goals.size + 6) local_map = np.concatenate( ( obstacles.flatten(), people.flatten(), goals.flatten() ) ) # populate state vector state[:-6] = local_map state[-6:-4] = self.player_pos state[-4:-2] = self.player_vel state[-2:] = np.array(self.goal_pos) return state def step(self, action): """ Advance the gridworld player based on action. 'done' is set when environment reaches goal, hits obstacle, or exceeds max step number, which is heuristically set to length*height of gridworld. :param action: Action peformed by player. :return (next_state, reward, done, False) """ assert self.action_space.contains(action), "Invalid action!" # extract current state = self.state_extractor().astype('float32') # advance player based on action action_vector = self.speed * self.action_dict[action] self.player_vel = action_vector next_pos = self.player_pos + action_vector self.step_number += 1 # update pedestrian positions self.populate_person_map(self.step_number) # extract next state self.player_pos = next_pos next_state = self.state_extractor().astype('float32') # reward function r(s_t, a_t, s_t+1) reward = self.reward_function(state, action, next_state) # position reset condition goal_reached = (self.goal_grid[tuple(self.player_pos)] == 1.0) obstacle_hit = (self.obstacle_grid[tuple(self.player_pos)] == 1.0) person_hit = (self.person_map[tuple(self.player_pos)] == 1.0) if obstacle_hit or person_hit: self.reset_player_pos() # temrination conditions max_steps_elapsed = self.step_number > self.max_steps done = max_steps_elapsed if self.render: self.render_gridworld() return next_state, reward, done, max_steps_elapsed def overlay(self, overlay, overlaid_on, const): """Overlays value 'const' on numpy array 'overlaid_on' in indices where 'overlay' is non-zero. :param overlay: numpy to overlay on another array. :param overlaid_on: overlay is applied on this array. :param const: constant to overlay with, e.g. const=2 will put 2s where overlay is nonzero. """ output = np.copy(overlaid_on) output[overlay != 0.0] = const return output def render_gridworld(self): to_render = self.obstacle_grid.copy() * OBSTACLE to_render = self.overlay(self.person_map, to_render, PERSON) to_render = self.overlay(self.goal_grid, to_render, GOAL) to_render[tuple(self.player_pos)] = ROBOT self.im_gridworld.set_data(to_render) self.fig.canvas.draw() self.fig.canvas.flush_events() def dump_png(self, path='./png_dumps/'): """Saves a PNG image of current state. :param path: path to save image to. """ impath = Path(path) image_name = str(self.png_number) + '.png' to_save = self.obstacles_map + self.goal_grid + self.obstacle_grid to_save[tuple(self.player_pos)] = ROBOT plt.imsave(str((impath / image_name).resolve()), to_save) self.png_number += 1
StarcoderdataPython
3233847
<filename>PackageTests/test_namespace.py import unittest import spelling class TestNameSpace(unittest.TestCase): def test_predict(self): # As such because the built in model is not trained, only all words are added self.assertIn(spelling.predict("bway"), ["way", "bay", "away", "sway", "tway", "bray"])
StarcoderdataPython
191719
<reponame>huawei-cloud/compass<filename>compass/tests/config_management/utils/test_config_merger_callbacks.py import unittest2 from compass.config_management.utils import config_merger_callbacks from compass.config_management.utils import config_reference class TestAssignRoles(unittest2.TestCase): def test_assign_roles(self): lower_configs = { 1: {'roles': ['control']}, 2: {'roles': ['api', 'compute']}, 3: {'roles': []}, 4: {}, 5: {}, } lower_refs = {} for hostid, config in lower_configs.items(): lower_refs[hostid] = config_reference.ConfigReference(config) roles = ['control', 'api', 'compute'] maxs = {'control': 1, 'api': 2, 'compute': -1} default_min = 1 exclusives = ['control'] assigned = config_merger_callbacks.assign_roles( None, None, lower_refs, 'roles', roles=roles, maxs=maxs, default_min=default_min, exclusives=exclusives) self.assertEqual(assigned, {1: ['control'], 2: ['api', 'compute'], 3: ['api'], 4: ['compute'], 5: ['compute']}) default_min = 2 maxs = {'control': 1, 'api': 2, 'compute': 2} lower_configs = { 1: {'roles': ['control']}, 2: {'roles': ['api', 'compute']}, 3: {'roles': []}, 4: {}, 5: {}, } lower_refs = {} for hostid, config in lower_configs.items(): lower_refs[hostid] = config_reference.ConfigReference(config) assigned = config_merger_callbacks.assign_roles( None, None, lower_refs, 'roles', roles=roles, maxs=maxs, default_min=default_min, exclusives=exclusives) self.assertEqual(assigned, {1: ['control'], 2: ['api', 'compute'], 3: ['control'], 4: ['api'], 5: ['compute']}) default_min = 1 roles = ['control', 'api', 'compute', 'mysql'] maxs = {'control': 1, 'api': 2, 'compute': -1, 'mysql': 2} bundles = [['control', 'api']] lower_configs = { 1: {}, 2: {}, 3: {}, 4: {}, 5: {}, } lower_refs = {} for hostid, config in lower_configs.items(): lower_refs[hostid] = config_reference.ConfigReference(config) assigned = config_merger_callbacks.assign_roles( None, None, lower_refs, 'roles', roles=roles, maxs=maxs, default_min=default_min, exclusives=exclusives, bundles=bundles) self.assertEqual(assigned, {1: ['control', 'api'], 2: ['compute'], 3: ['mysql'], 4: ['mysql'], 5: ['compute']}) if __name__ == '__main__': unittest2.main()
StarcoderdataPython
173619
from sys import maxsize class Contact: def __init__(self, first_name=None, middle_name=None, last_name=None, nick_name=None, title=None, company=None, address=None, home_phone=None, mobile_phone=None, work_phone=None, fax=None, email=None, email2=None, email3=None, home_page=None, bday=None, bmonth=None, byear=None, aday=None, amonth=None, ayear=None, address2=None, phone2=None, notes=None, id=None, all_phones_from_home_page=None, all_email_from_home_page=None): self.first_name = first_name self.middle_name = middle_name self.last_name = last_name self.nick_name = nick_name self.title = title self.company = company self.address = address self.home_phone = home_phone self.mobile_phone = mobile_phone self.work_phone = work_phone self.fax = fax self.email = email self.email2 = email2 self.email3 = email3 self.home_page = home_page self.bday = bday self.bmonth = bmonth self.byear = byear self.aday = aday self.amonth = amonth self.ayear = ayear self.address2 = address2 self.phone2 = phone2 self.notes = notes self.id = id self.all_phones_from_home_page = all_phones_from_home_page self.all_email_from_home_page = all_email_from_home_page def __repr__(self): return "%s---%s---%s---%s---%s---%s" % (self.id, self.last_name, self.first_name, self.mobile_phone, self.bday, self.bmonth) def __eq__(self, other): return (self.id is None or other.id is None or self.id == other.id) and self.first_name == other.first_name and\ self.last_name == other.last_name def id_or_max(self): if self.id: return int(self.id) else: return maxsize
StarcoderdataPython
3238314
# Copyright 2017 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Base class for voxel generation model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import os import numpy as np from six.moves import xrange import tensorflow as tf import input_generator import utils slim = tf.contrib.slim class Im2Vox(object): """Defines the voxel generation model.""" __metaclass__ = abc.ABCMeta def __init__(self, params): self._params = params @abc.abstractmethod def get_metrics(self, inputs, outputs): """Gets dictionaries from metrics to value `Tensors` & update `Tensors`.""" pass @abc.abstractmethod def get_loss(self, inputs, outputs): pass @abc.abstractmethod def get_regularization_loss(self, scopes): pass def set_params(self, params): self._params = params def get_inputs(self, dataset_dir, dataset_name, split_name, batch_size, image_size, vox_size, is_training=True): """Loads data for a specified dataset and split.""" del image_size, vox_size with tf.variable_scope('data_loading_%s/%s' % (dataset_name, split_name)): common_queue_min = 64 common_queue_capacity = 256 num_readers = 4 inputs = input_generator.get( dataset_dir, dataset_name, split_name, shuffle=is_training, num_readers=num_readers, common_queue_min=common_queue_min, common_queue_capacity=common_queue_capacity) images, voxels = tf.train.batch( [inputs['image'], inputs['voxel']], batch_size=batch_size, num_threads=8, capacity=8 * batch_size, name='batching_queues/%s/%s' % (dataset_name, split_name)) outputs = dict() outputs['images'] = images outputs['voxels'] = voxels outputs['num_samples'] = inputs['num_samples'] return outputs def preprocess(self, raw_inputs, step_size): """Selects the subset of viewpoints to train on.""" (quantity, num_views) = raw_inputs['images'].get_shape().as_list()[:2] inputs = dict() inputs['voxels'] = raw_inputs['voxels'] for k in xrange(step_size): inputs['images_%d' % (k + 1)] = [] inputs['matrix_%d' % (k + 1)] = [] for n in xrange(quantity): selected_views = np.random.choice(num_views, step_size, replace=False) for k in xrange(step_size): view_selected = selected_views[k] inputs['images_%d' % (k + 1)].append(raw_inputs['images'][n, view_selected, :, :, :]) tf_matrix = self.get_transform_matrix(view_selected) inputs['matrix_%d' % (k + 1)].append(tf_matrix) for k in xrange(step_size): inputs['images_%d' % (k + 1)] = tf.stack(inputs['images_%d' % (k + 1)]) inputs['matrix_%d' % (k + 1)] = tf.stack(inputs['matrix_%d' % (k + 1)]) return inputs def get_init_fn(self, scopes): """Initialization assignment operator function used while training.""" if not self._params.init_model: return None is_trainable = lambda x: x in tf.trainable_variables() var_list = [] for scope in scopes: var_list.extend( filter(is_trainable, tf.contrib.framework.get_model_variables(scope))) init_assign_op, init_feed_dict = slim.assign_from_checkpoint( self._params.init_model, var_list) def init_assign_function(sess): sess.run(init_assign_op, init_feed_dict) return init_assign_function def get_train_op_for_scope(self, loss, optimizer, scopes): """Train operation function for the given scope used file training.""" is_trainable = lambda x: x in tf.trainable_variables() var_list = [] update_ops = [] for scope in scopes: var_list.extend( filter(is_trainable, tf.contrib.framework.get_model_variables(scope))) update_ops.extend(tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope)) return slim.learning.create_train_op( loss, optimizer, update_ops=update_ops, variables_to_train=var_list, clip_gradient_norm=self._params.clip_gradient_norm) def write_disk_grid(self, global_step, log_dir, input_images, gt_projs, pred_projs, pred_voxels=None): """Function called by TF to save the prediction periodically.""" summary_freq = self._params.save_every def write_grid(input_images, gt_projs, pred_projs, pred_voxels, global_step): """Native python function to call for writing images to files.""" grid = _build_image_grid(input_images, gt_projs, pred_projs, pred_voxels) if global_step % summary_freq == 0: img_path = os.path.join(log_dir, '%s.jpg' % str(global_step)) utils.save_image(grid, img_path) with open( os.path.join(log_dir, 'pred_voxels_%s' % str(global_step)), 'w') as fout: np.save(fout, pred_voxels) with open( os.path.join(log_dir, 'input_images_%s' % str(global_step)), 'w') as fout: np.save(fout, input_images) return grid py_func_args = [ input_images, gt_projs, pred_projs, pred_voxels, global_step ] save_grid_op = tf.py_func(write_grid, py_func_args, [tf.uint8], 'wrtie_grid')[0] slim.summaries.add_image_summary( tf.expand_dims(save_grid_op, axis=0), name='grid_vis') return save_grid_op def _build_image_grid(input_images, gt_projs, pred_projs, pred_voxels): """Build the visualization grid with py_func.""" quantity, img_height, img_width = input_images.shape[:3] for row in xrange(int(quantity / 3)): for col in xrange(3): index = row * 3 + col input_img_ = input_images[index, :, :, :] gt_proj_ = gt_projs[index, :, :, :] pred_proj_ = pred_projs[index, :, :, :] pred_voxel_ = utils.display_voxel(pred_voxels[index, :, :, :, 0]) pred_voxel_ = utils.resize_image(pred_voxel_, img_height, img_width) if col == 0: tmp_ = np.concatenate([input_img_, gt_proj_, pred_proj_, pred_voxel_], 1) else: tmp_ = np.concatenate( [tmp_, input_img_, gt_proj_, pred_proj_, pred_voxel_], 1) if row == 0: out_grid = tmp_ else: out_grid = np.concatenate([out_grid, tmp_], 0) out_grid = out_grid.astype(np.uint8) return out_grid
StarcoderdataPython
82535
<reponame>misads/torch_image_template import os tags = ['fold_1', 'fold_2'] for tag in tags: cmd = "python3 test.py --load %s" % tag print(cmd) os.system(cmd)
StarcoderdataPython
96295
from arcgis import GIS from arcgis.features import GeoAccessor, GeoSeriesAccessor import arcpy from arcpy import env from arcpy.sa import * import numpy as np import os import pandas as pd ##### arcpy.env.overwriteOutput = True arcpy.CheckOutExtension("Spatial") def select_feature_by_attributes_arcgis(input,Attri_NM,Attri_v,output): where_clause = '"%s" IN' % (Attri_NM) where_clause = where_clause + " (" for i in range(0,len(Attri_v)): if i == 0: where_clause = where_clause + str(Attri_v[i]) else: where_clause = where_clause + "," + str(Attri_v[i]) where_clause = where_clause + ")" arcpy.Select_analysis(input, output, where_clause) return ################## def Remove_Unselected_Lake_Attribute_In_Finalcatinfo_Arcgis(finalcat_ply, Conn_Lake_Ids): """Functions will set lake id not in Conn_Lake_Ids to -1.2345 in attribute table of Path_Finalcatinfo ---------- Notes ------- Returns: ------- None, the attribute table of Path_shpfile will be updated """ mask1 = np.logical_not(finalcat_ply['HyLakeId'].isin(Conn_Lake_Ids)) mask2 = finalcat_ply['Lake_Cat'] != 2 mask = np.logical_and(mask1,mask2) finalcat_ply.loc[mask,'HyLakeId'] = 0 finalcat_ply.loc[mask,'LakeVol'] = 0 finalcat_ply.loc[mask,'LakeArea'] = 0 finalcat_ply.loc[mask,'LakeDepth'] = 0 finalcat_ply.loc[mask,'Laketype'] =0 finalcat_ply.loc[mask,'Lake_Cat'] = 0 return finalcat_ply def save_modified_attributes_to_outputs(mapoldnew_info,tempfolder,OutputFolder,cat_name,riv_name,Path_final_riv,dis_col_name='SubId'): mapoldnew_info.spatial.to_featureclass(location=os.path.join(tempfolder,'updateattri.shp'),overwrite=True,sanitize_columns=False) arcpy.Dissolve_management(os.path.join(tempfolder,'updateattri.shp'), os.path.join(OutputFolder,cat_name), [dis_col_name]) arcpy.JoinField_management(os.path.join(OutputFolder,cat_name), dis_col_name, os.path.join(tempfolder,'updateattri.shp'), dis_col_name) arcpy.DeleteField_management(os.path.join(OutputFolder,cat_name), ["SubId_1", "Id","nsubid2", "nsubid","ndownsubid","Old_SubId","Old_DowSub","Join_Count","TARGET_FID","Id","SubID_Oldr","HRU_ID_N_1","HRU_ID_N_2","facters"] ) if riv_name != '#': arcpy.CalculateGeometryAttributes_management(os.path.join(OutputFolder, cat_name), [["centroid_x", "CENTROID_X"], ["centroid_y", "CENTROID_Y"]]) cat_colnms = mapoldnew_info.columns drop_cat_colnms = cat_colnms[cat_colnms.isin(["SHAPE","SubId_1", "Id","nsubid2", "nsubid","ndownsubid","Old_DowSub","Join_Count","TARGET_FID","Id","SubID_Oldr","HRU_ID_N_1","HRU_ID_N_2","facters","Old_DowSubId"])] cat_pd = mapoldnew_info.drop(columns=drop_cat_colnms) riv_pd = pd.DataFrame.spatial.from_featureclass(Path_final_riv) riv_pd['Old_SubId'] = riv_pd['SubId'] # remove all columns riv_pd = riv_pd[['SHAPE','Old_SubId']] riv_pd = pd.merge(riv_pd, cat_pd, on='Old_SubId', how='left') riv_pd = riv_pd.drop(columns=['Old_SubId']) riv_pd.spatial.to_featureclass(location=os.path.join(tempfolder,'riv_attri.shp'),overwrite=True,sanitize_columns=False) arcpy.Dissolve_management(os.path.join(tempfolder,'riv_attri.shp'), os.path.join(OutputFolder,riv_name), ["SubId"]) arcpy.JoinField_management(os.path.join(OutputFolder,riv_name), "SubId", os.path.join(tempfolder,'riv_attri.shp'), "SubId") arcpy.DeleteField_management(os.path.join(OutputFolder,riv_name), ["SubId_1", "Id","nsubid2", "nsubid","ndownsubid","Old_SubId","Old_DowSub","Join_Count","TARGET_FID","Id","SubID_Oldr","HRU_ID_N_1","HRU_ID_N_2","facters"] ) def clean_attribute_name_arcgis(table,names): remove_column_names = table.columns[np.logical_not(np.isin(table.columns,names))] table = table.drop(columns=remove_column_names) return table
StarcoderdataPython
91339
<reponame>Slewentogzz/hk_ros_2021<filename>hk_ros_2021/scripts/scan.py #! /usr/bin/env python import rospy from sensor_msgs.msg import LaserScan from darknet_ros_msgs.msg import BoundingBoxes import tf2_ros import tf2_msgs.msg import geometry_msgs.msg #def callback(msg): #class animal_pos: # def __init__(self): # self.angle = 0 # self.dist = 0 class Callbacks: def __init__(self): self.lidar_list = [] self.object = geometry_msgs.msg.TransformStamped() self.lidar = rospy.Subscriber('/scan', LaserScan, self.lidar_callback) self.darknet = rospy.Subscriber('/darknet_ros/bounding_boxes', BoundingBoxes, self.darknet_callback) self.pub_tf = rospy.Publisher("/tf",tf2_msgs.msg.TFMessage,queue_size=1) def darknet_callback(self, darknet): for i in darknet.bounding_boxes: if (i.Class == 'cat' or i.Class == 'dog' or i.Class == 'cow') and i.probability > 0.3: #rospy.loginfo("len: "+str(len(self.lidar_list)) + " index:"+str(int(round((i.xmin+i.xmax)*62.5/(2*638)-31.25)))) print str(i.Class) + " prob: "+str(i.probability)#xMax: " + str(i.xmax) +"\nxmin: " + str(i.xmin)+"\npos: "+str((i.xmin+i.xmax)*62.5/(2*638)-31.25)+"\ndist: "+str(self.lidar_list[int(round((i.xmin+i.xmax)*62.5/(2*638)-31.25))]) #self.object = geometry_msgs.msg.TransformStamped() rospy.sleep(0.1) self.object.header.frame_id = "camera" self.object.header.stamp = rospy.Time.now() self.object.child_frame_id = "animal" self.object.transform.translation.x = 0.0 self.object.transform.translation.y = 0.0 self.object.transform.translation.z = 0.0 self.object.transform.rotation.x = 0.0 self.object.transform.rotation.y = 0.0 angle = int(-round((i.xmin+i.xmax)*62.5/(2*638)-31.25)) self.object.transform.rotation.z = angle smallest = self.lidar_list[angle] for i in range(-10,10): if self.lidar_list[angle+i] < smallest and self.lidar_list[angle+i] > 0.0: smallest = self.lidar_list[angle+i] self.object.transform.rotation.z = angle+i self.object.transform.rotation.w = smallest self.pub_tf.publish(tf2_msgs.msg.TFMessage([self.object])) def lidar_callback(self, lidar): self.lidar_list = lidar.ranges[:] def talker(self): #pub = rospy.Publisher('animal_pos',tfMessage,queue_size = 10) #rospy.init_node('talker',anonymous=True) #rate = Rate(10) #behovs? rospy.loginfo("Loginfo????") self.pub_tf.publish(tf2_msgs.msg.TFMessage([self.object])) if __name__ == '__main__': rospy.init_node('scan_values') values = Callbacks() rospy.spin() #rospy.init_node('scan_values') #sub = rospy.Subscriber('/scan', LaserScan, callback) #rospy.spin()
StarcoderdataPython
3382903
from .utils import getNormBackground, getNormBackground, getNormBackground
StarcoderdataPython
1675208
from request_validation import BaseValidator, RequestParamError, add_into_dtype_map @add_into_dtype_map class CommaStringListValidator(BaseValidator): dtype = "commalist" def _validate(self, data): if self.dtype is not str: raise RequestParamError(f"{self._log_prefix} need to be string") data = data.split(",") return data def main(): return if __name__ == "__main__": main()
StarcoderdataPython
4810216
<reponame>rexzhang/ddns-clienter from dataclasses import dataclass, asdict as dataclass_as_dict from datetime import timedelta from logging import getLogger from django.conf import settings from django.forms.models import model_to_dict from django.utils import timezone from ddns_clienter_core.constants import AddressInfo, EventLevel from ddns_clienter_core import models from ddns_clienter_core.runtimes.config import AddressConfig, TaskConfig from ddns_clienter_core.runtimes.address_providers import ( get_ip_address_from_provider, AddressProviderException, ) from ddns_clienter_core.runtimes.dns_providers import ( update_address_to_dns_provider, DDNSProviderException, ) from ddns_clienter_core.runtimes.event import send_event logger = getLogger(__name__) @dataclass class AddressDataItem: config: AddressConfig config_changed: bool ipv4_changed: bool ipv6_changed: bool newest_address: AddressInfo @property def there_ars_changes(self) -> bool: """config changed or address changed""" if self.config_changed or self.ipv4_changed or self.ipv6_changed: return True return False class CannotMatchAddressException(Exception): pass def compare_and_update_from_dataclass_to_db(dc_obj, db_obj) -> bool: changed = False data = model_to_dict(db_obj) for k, v in dataclass_as_dict(dc_obj).items(): if data.get(k) != v: changed = True db_obj.__setattr__(k, v) return changed class AddressHub: # 导入 Address Config+DB 信息 # 计算获取 需要获取的 addresses 清单,交给 address_provider 去并行处理 # 等待并导入所有并行处理结果 # 获得已经改变的 changed_address_names _data: dict[str, AddressDataItem] _changed_names: set[str] @staticmethod def _compare_and_update_from_config_to_db( address_c: AddressConfig, ) -> (bool, AddressInfo): address_db = models.Address.objects.filter(name=address_c.name).first() if address_db is None: address_db = models.Address(**dataclass_as_dict(address_c)) address_db.save() logger.info( "Cannot found address:{} from db, create it.".format(address_c.name) ) return True, AddressInfo() changed = compare_and_update_from_dataclass_to_db(address_c, address_db) if changed: address_db.save() logger.info( "The address[{}]'s config has changed, update to db.".format( address_c.name ) ) return ( True, AddressInfo( address_db.ipv4_last_address, address_db.ipv6_last_address, ), ) logger.debug("The address[{}] no change in config".format(address_c.name)) return ( False, AddressInfo( address_db.ipv4_last_address, address_db.ipv6_last_address, ), ) def __init__(self, addresses_c: dict[str, AddressConfig]): self._data = dict() for address_c in addresses_c.values(): (config_changed, address_info) = self._compare_and_update_from_config_to_db( address_c ) self._data.update( { address_c.name: AddressDataItem( address_c, config_changed, False, False, address_info ) } ) @property def to_be_update_addresses(self) -> list[AddressConfig]: data = list() for item in self._data.values(): data.append(item.config) logger.debug("To be update addresses:{}".format(data)) return data def update_ip_address( self, name: str, newest_address: AddressInfo, ): address_data = self._data.get(name) now = timezone.now() address_db = models.Address.objects.filter(name=name).first() if ( newest_address.ipv4_address is not None and newest_address.ipv4_address != address_data.newest_address.ipv4_address ): address_data.ipv4_changed = True address_data.newest_address.ipv4_address = newest_address.ipv4_address address_db.ipv4_previous_address = address_db.ipv4_last_address address_db.ipv4_last_address = newest_address.ipv4_address address_db.ipv4_last_change_time = now message = "{}'s ipv4 changed:{}->{}".format( name, address_db.ipv4_previous_address, address_db.ipv4_last_address, ) logger.info(message) send_event(message) if newest_address.ipv6_address is not None and ( newest_address.ipv6_address != address_data.newest_address.ipv6_address ): message = "{}'s ipv6 changed:{}->{}/{}".format( name, address_db.ipv6_last_address, # last newest_address.ipv6_address, # new address_data.config.ipv6_prefix_length, ) logger.info(message) send_event(message) # update to self._data address_data.ipv6_changed = True address_data.newest_address.ipv6_address = newest_address.ipv6_address address_data.newest_address.ipv6_prefix_length = ( address_data.config.ipv6_prefix_length ) # update to db address_db.ipv6_previous_address = address_db.ipv6_last_address address_db.ipv6_last_address = newest_address.ipv6_address address_db.ipv6_prefix_length = address_data.config.ipv6_prefix_length address_db.ipv6_last_change_time = now address_db.save() def get_address_info_if_changed( self, name: str, force_update: bool # TODO ) -> AddressInfo | None: address_data = self._data.get(name) if address_data is None: raise CannotMatchAddressException() if force_update or address_data.there_ars_changes: return address_data.newest_address return None @dataclass class TaskDataItem: config: TaskConfig _config_changed: bool _last_update_success: bool _force_update_intervals_timeout: bool @property def force_update(self) -> bool: return ( self._config_changed or not self._last_update_success or self._force_update_intervals_timeout ) class TaskHub: # 根据 changed_address_names 获取更新信息清单,交给 dns_provider 去并行处理 # 等待并导入所有并行处理结果 # 将更新任务结果存储到 DB _data: dict[str, TaskDataItem] @staticmethod def _compare_and_update_from_config_to_db(task_c: TaskConfig) -> (bool, bool): task_db = models.Task.objects.filter(name=task_c.name).first() if task_db is None: task_db = models.Task(**dataclass_as_dict(task_c)) task_db.save() logger.info( "Cannot found task:{} from db, create it in db.".format(task_c.name) ) return True, False changed = compare_and_update_from_dataclass_to_db(task_c, task_db) if changed: task_db.save() logger.info( "The task[{}]'s config has changed, update to db.".format(task_c.name) ) return True, task_db.last_update_success logger.debug("The task[{}] no change in config".format(task_c.name)) return False, task_db.last_update_success def __init__(self, tasks_c: dict[str, TaskConfig]): self._data = dict() for tasks_c in tasks_c.values(): ( config_changed, last_update_success, ) = self._compare_and_update_from_config_to_db(tasks_c) self._data.update( { tasks_c.name: TaskDataItem( tasks_c, config_changed, last_update_success, False, ) } ) @property def to_be_update_tasks(self) -> list[TaskDataItem]: now = timezone.now() data = list() for item in self._data.values(): task_db = models.Task.objects.filter(name=item.config.name).first() if task_db.last_update_success_time is None or ( task_db.last_update_success_time + timedelta(minutes=settings.CONFIG.common.force_update_intervals) < now ): # force_update_intervals timeout item._force_update_intervals_timeout = True data.append(item) continue # other task data.append(item) logger.debug("To be update tasks:{}".format(data)) return data @staticmethod def set_task_skipped(name: str): task_db = models.Task.objects.filter(name=name).first() task_db.save() @staticmethod def save_update_status_to_db( name: str, address_info: AddressInfo, update_success: bool ): db_task = models.Task.objects.filter(name=name).first() now = timezone.now() if update_success: new_addresses = str() if db_task.ipv4 and address_info.ipv4_address is not None: new_addresses += address_info.ipv4_address_str if db_task.ipv6 and address_info.ipv6_address is not None: if len(new_addresses) != 0: new_addresses += "," new_addresses += address_info.ipv6_address_str_with_prefix db_task.last_update_time = now db_task.last_update_success = True db_task.previous_ip_addresses = db_task.last_ip_addresses db_task.last_ip_addresses = new_addresses db_task.last_update_success_time = now else: db_task.last_update_time = now db_task.last_update_success = False db_task.save() def check_and_update(config_file_name: str | None = None, real_update: bool = True): if config_file_name is not None: raise "TODO" # import address data from config and db ah = AddressHub(settings.CONFIG.addresses) # get ip address, update ip address into hub for address_c in ah.to_be_update_addresses: try: address_info = get_ip_address_from_provider(address_c) except AddressProviderException as e: message = str(e) logger.error(message) send_event(message, level=EventLevel.ERROR) continue ah.update_ip_address(address_c.name, address_info) logger.debug("address info:{}, {}".format(address_c.name, address_info)) # import address data from config and db th = TaskHub(settings.CONFIG.tasks) # update to DNS provider for task in th.to_be_update_tasks: try: address_info = ah.get_address_info_if_changed( task.config.address_name, task.force_update ) except CannotMatchAddressException: message = "Cannot found address:{}".format(task.config.address_name) logger.warning(message) send_event(message, level=EventLevel.WARNING) continue if address_info is None: logger.debug( "Skip task:{}, because address have not any change".format( task.config.name ) ) th.set_task_skipped(task.config.name) continue if address_info.ipv4_address is None and address_info.ipv6_address is None: message = "{}: ipv4_address and ipv6_address both None".format( task.config.address_name ) logger.warning(message) send_event(message, level=EventLevel.WARNING) th.set_task_skipped(task.config.name) continue # check ip address if not task.config.ipv4: address_info.ipv4_address = None if not task.config.ipv6: address_info.ipv6_address = None address_info.ipv6_prefix_length = None if address_info.ipv4_address is None and address_info.ipv6_address is None: message = "Skip task:{}, because address do not need update".format( task.config.name ) logger.warning(message) send_event(message, level=EventLevel.WARNING) th.set_task_skipped(task.config.name) continue try: update_success, update_message = update_address_to_dns_provider( task.config, address_info, real_update ) except DDNSProviderException as e: message = str(e) logger.error(message) send_event(message, level=EventLevel.ERROR) continue if update_success: message = "update task:{} finished".format(task.config.name) logger.info(message) send_event(message) else: message = "update task:{} failed".format(task.config.name) logger.warning(message) send_event(message, level=EventLevel.WARNING) th.save_update_status_to_db(task.config.name, address_info, update_success)
StarcoderdataPython
3323250
<filename>scripts/3_training/train.py import os import sys curr_path = os.getcwd() package_path = (os.path.abspath(os.path.join(curr_path, os.pardir))).replace('\\', '/')+'/' sys.path.insert(1, package_path) from config.config import * from processing_scripts.model_preprocessing import * df_full= pd.read_csv(Train_path_final) df_full.drop(['Unnamed: 0'] , axis=1 , inplace=True) df_train= get_model_data(df_full , train_years) df_valid = get_model_data(df_full , valid_years) X_full , y_full = df_full.drop(["status","launch_year","deadline"], axis=1) , df_full['status'] X_train , y_train = df_train.drop(["status","launch_year","deadline"] , axis=1) , df_train['status'] X_valid , y_valid = df_valid.drop(["status","launch_year","deadline"] , axis=1) , df_valid['status'] print("Training.....") scores = XG_score(X_train ,y_train ,X_valid , y_valid) print("Accuracy of the model on validation set-2019") print(scores) print("Final Training Model.....") model = XG_train(X_full , y_full) try: os.remove(model_path) print("removed the model file") except: pass print("saving the model") joblib.dump(model, model_path)
StarcoderdataPython
1761933
<filename>test_logtailer.py import unittest import logtailer class TestConstructor(unittest.TestCase): def setUp(self): self.matches = [] self.tail = logtailer.Tail("test_file.txt", []) def dummy_callback_function(self, index, matched_pattern): self.matches.append({index, matched_pattern}) def test_initiate(self): pattern = ['.*', 'Error'] log_tail = logtailer.Tail("sample_file.txt", pattern) self.assertEqual("sample_file.txt", log_tail.file_name) self.assertListEqual(pattern, log_tail.pattern_list) def test_initialize(self): pattern = ['.*', 'Error'] log_tail = logtailer.Tail() self.assertEqual("", log_tail.file_name) self.assertListEqual(['.*'], log_tail.pattern_list) # Initialize class log_tail.initialize("sample_file.txt", pattern) self.assertEqual("sample_file.txt", log_tail.file_name) self.assertListEqual(pattern, log_tail.pattern_list) def test_start_empty_file_name(self): log_tail = logtailer.Tail() self.assertFalse(log_tail.start(self.dummy_callback_function)) def test_add_pattern(self): log_tail = logtailer.Tail("test_file.txt", []) log_tail.add_pattern('.*') self.assertListEqual(['.*'], log_tail.pattern_list) log_tail.add_pattern('Error') self.assertListEqual(['.*', 'Error'], log_tail.pattern_list) def test_remove_pattern(self): pattern = ['.*', 'Error'] log_tail = logtailer.Tail("test_file.txt", pattern) self.assertTrue(log_tail.remove_pattern(1)) self.assertListEqual(['.*'], log_tail.pattern_list) # Remove out of range element self.assertFalse(log_tail.remove_pattern(10)) self.assertFalse(log_tail.remove_pattern(-10)) if __name__ == '__main__': unittest.main()
StarcoderdataPython
179016
<gh_stars>0 #/usr/bin/env python3 ''' 这是书中1.5节的练习3 创建一些词汇列表,比如,冠词("the", "a"等)、主题("cat", "dog", "man", "woman")、动词(“sang”, "ran", "jumped")与状语("loudly", "quietly", "well")等, 之后循环5次,每次迭代中,使用random.choice()函数选取冠词、主题、动词、状语等内容。 使用random.randint()函数在两种语句结构之间进行选择: 冠词、主题、动词、状语; 只包括冠词、主题与动词,之后打印语句。 输入:awfulpoetry1_ans.py 输出例子: another boy laughed badly the woman jumped a boy hoped a horse jumped another man laughed rudely tip: 可以使用random包 ''' import random art = ["another", "a", "no", "any"] theme = ["dog", "man", "book", "game", "Lanister", "cat", "taylor"] verb = ["paid", "got", "played", "laughed", "hoped", "ran", "fucked", "knew"] adv = ["sadly", "well", "rudely", "only", "quietly", "badly", "widely", "quickly", "slowly"] struct1 = [art, theme, verb, adv] struct2 = [art, theme, verb] Struct = [struct1, struct2] time = 0 while time<5: line = "" struct = Struct[random.randint(0,1)] for word in struct: line += random.choice(word) line += " " print(line) time += 1
StarcoderdataPython
4832260
<reponame>Hadrien-Montanelli/chebpy<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 2 15:37:10 2020 Copyright 2020 by <NAME>. """ # %% Imports. # Standard library import: from math import pi import numpy as np # Chebpy imports: from chebpy.trig import coeffs2vals, trigpts, vals2coeffs # %% Transforms (1D) on [-1,1]. f = lambda x: np.cos(10000*pi*x) + np.cos(5*pi*x) n = 100 x = trigpts(n) error = coeffs2vals(vals2coeffs(f(x))) - f(x) print(f'Error (1D): {np.max(np.abs(error)):.2e}') # %% Transforms (1D) on [0,2*pi]. f = lambda x: np.exp(np.cos(10*pi*x)**2) n = 120 x = trigpts(n, [0, 2*pi]) error = coeffs2vals(vals2coeffs(f(x))) - f(x) print(f'Error (1D): {np.max(np.abs(error)):.2e}') # %% Transforms (2D) on [-1,1]x[-1,1]. f = lambda x, y: np.exp(np.cos(10*pi*x)**2)*np.sin(pi*y)**2 n = 100 x = trigpts(n) y = trigpts(n) X, Y = np.meshgrid(x, y) values = f(X, Y) coeffs = vals2coeffs(vals2coeffs(values).T).T values2 = coeffs2vals(coeffs2vals(coeffs).T).T error = values2 - values print(f'Error (2D): {np.max(np.abs(error)):.2e}') # %% Transforms (2D) on [-pi,pi]x[0,4*pi]. f = lambda x, y: np.exp(np.cos(10*pi*x)**2)*np.sin(pi*y)**2 n = 100 x = trigpts(n, [-pi, pi]) y = trigpts(n, [0, 4*pi]) X, Y = np.meshgrid(x, y) values = f(X, Y) coeffs = vals2coeffs(vals2coeffs(values).T).T values2 = coeffs2vals(coeffs2vals(coeffs).T).T error = values2 - values print(f'Error (2D): {np.max(np.abs(error)):.2e}')
StarcoderdataPython
3388943
<filename>python/add_pixscale.py """ Does exactly what the name says, adds a pixel scale (given in arcsec/pix) to a fits file. This code does _not_ change the crpix or crval -- only the pixel scale. """ import sys import glob from astropy.io import fits as pf """ Check the command line syntax """ if len(sys.argv) < 3: print('') print('Usage: python add_pixscale.py [pixscale] ' '[file / file list / wildcard]') print('') print('Examples:') print(' python add_pixscale 0.211 myobj.fits') print(' python add_pixscale 0.211 my*fits') print('') print('NOTE: the pixel scale should be in arcsec/pix') print('') exit() """ Get the information from the command line """ try: pixscale = float(sys.argv[1]) / 3600. except: print('') print('ERROR: Expected the first passed parameter to be a number') print('') infiles = sys.argv[2:] """ Add the pixel scale to the input files """ print('') for i in infiles: hdu = pf.open(i, mode='update') hdr = hdu[0].header """ Delete any old CD matrix that may exist """ for j in ['cd1_1', 'cd1_2', 'cd2_1', 'cd2_2']: if j in hdr.keys(): del hdr[j] """ Add in the new pixel information """ hdr['cdelt1'] = -1.*pixscale hdr['cdelt2'] = pixscale hdu.flush() print('Added pixel scale information to %s' % i) print('')
StarcoderdataPython
90149
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals # This file is only used if you use `make publish` or # explicitly specify it as your config file. import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = 'https://ankursinha.in' FEED_DOMAIN = SITEURL FEED_ALL_ATOM = 'feeds/all.atom.xml' FEED_ALL_RSS = 'feeds/all.rss.xml' CATEGORY_FEED_ATOM = 'feeds/categories/{slug}.atom.xml' CATEGORY_FEED_RSS = 'feeds/categories/{slug}.rss.xml' TAG_FEED_ATOM = 'feeds/tags/{slug}.atom.xml' TAG_FEED_RSS = 'feeds/tags/{slug}.rss.xml' AUTHOR_FEED_ATOM = 'feeds/authors/{slug}.atom.xml' AUTHOR_FEED_RSS = 'feeds/authors/{slug}.rss.xml' FEED_MAX_ITEMS = 10 DELETE_OUTPUT_DIRECTORY = False DISQUS_SITENAME = u'ankursinha' GOOGLE_ANALYTICS = "UA-60261100-1"
StarcoderdataPython
78557
<gh_stars>0 # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from neutron._i18n import _ class _FeatureFlag(object): def is_compatible(self, value): if value == self.requires: return True if value and self.supports: return True return False def __init__(self, supports, requires): self.supports = supports self.requires = requires if requires and not supports: raise RuntimeError(_("A driver can't require a feature and not " "support it.")) UNSUPPORTED = _FeatureFlag(supports=False, requires=False) OPTIONAL = _FeatureFlag(supports=True, requires=False) MANDATORY = _FeatureFlag(supports=True, requires=True) class L3ServiceProvider(object): """Base class for L3 service providers. On __init__ this will be given a handle to the l3 plugin. It is then the responsibility of the driver to subscribe to the events it is interested in (e.g. router_create, router_update, router_delete, etc). The 'ha' and 'distributed' attributes below are used to determine if a router request with the 'ha' or 'distributed' attribute can be supported by this particular driver. These attributes must be present. """ ha_support = UNSUPPORTED distributed_support = UNSUPPORTED def __init__(self, l3plugin): self.l3plugin = l3plugin
StarcoderdataPython
1755346
<filename>moler/cmd/unix/gunzip.py # -*- coding: utf-8 -*- """ Gunzip command module. """ __author__ = '<NAME>' __copyright__ = 'Copyright (C) 2018, Nokia' __email__ = '<EMAIL>' from moler.cmd.unix.genericunix import GenericUnixCommand from moler.exceptions import CommandFailure from moler.exceptions import ParsingDone import re class Gunzip(GenericUnixCommand): def __init__(self, connection, archive_name, output_file_name=None, options=None, overwrite=False, prompt=None, newline_chars=None, runner=None): super(Gunzip, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, runner=runner) self.archive_name = archive_name self.output_file_name = output_file_name self.options = options self.overwrite = overwrite self.keys = list() self.current_ret['RESULT'] = list() # private variables self._answered_file = None self._asks_to_overwrite_send = False def build_command_string(self): cmd = 'gunzip' if self.options: cmd = '{} {}'.format(cmd, self.options) if self.archive_name: for file in self.archive_name: cmd = '{} {}'.format(cmd, file) if self.output_file_name: cmd = '{} > {}'.format(cmd, self.output_file_name) return cmd def on_new_line(self, line, is_full_line): try: self._parse_info_output(line) self._asks_to_overwrite(line) self._create_dictionary_at_l_option(line) self._command_failure(line) except ParsingDone: pass return super(Gunzip, self).on_new_line(line, is_full_line) _re_info_output = re.compile(r" -- replaced with") def _parse_info_output(self, line): if self._regex_helper.search_compiled(Gunzip._re_info_output, line): self.current_ret['RESULT'].append(line) raise ParsingDone _re_overwrite = re.compile(r"gzip:\s+(?P<FILE_NAME>.*)\s+already exists", re.IGNORECASE) def _asks_to_overwrite(self, line): if self._regex_helper.search_compiled(Gunzip._re_overwrite, line): current_file = self._regex_helper.group("FILE_NAME") if current_file != self._answered_file: if self.overwrite: self.connection.sendline('y') else: self.connection.sendline('n') self.set_exception(CommandFailure(self, "ERROR: {} already exists".format(current_file))) self._answered_file = current_file raise ParsingDone _re_l_option = re.compile(r"(?P<L_OPTION> compressed\s*uncompressed\s*ratio\s*uncompressed_name.*)", re.IGNORECASE) def _create_dictionary_at_l_option(self, line): if self.keys and not self.current_ret['RESULT']: self.values = line.strip().split() if 'date' in self.keys: self.values = self.values[:2] + ['{} {}'.format(self.values[2], self.values[3])] + self.values[4:] self.current_ret['RESULT'].append(dict(zip(self.keys, self.values))) raise ParsingDone if self._regex_helper.search_compiled(Gunzip._re_l_option, line): self.keys = line.strip().split() raise ParsingDone _re_error = re.compile(r"gzip:\s(?P<ERROR_MSG>.*)", re.IGNORECASE) def _command_failure(self, line): if self._regex_helper.search_compiled(Gunzip._re_error, line): self.set_exception(CommandFailure(self, "ERROR: {}".format(self._regex_helper.group("ERROR_MSG")))) raise ParsingDone COMMAND_OUTPUT_without_options = """ xyz@debian:~$ gunzip new.gz xyz@debian:~$""" COMMAND_KWARGS_without_options = { 'archive_name': ['new.gz'] } COMMAND_RESULT_without_options = { 'RESULT': [] } COMMAND_OUTPUT_loud_options = """ xyz@debian:~$ gunzip -v new.gz new.gz: -7.7% -- replaced with new xyz@debian:~$""" COMMAND_KWARGS_loud_options = { 'archive_name': ['new.gz'], 'options': '-v' } COMMAND_RESULT_loud_options = { 'RESULT': ['new.gz:\t -7.7% -- replaced with new'] } COMMAND_OUTPUT_overwrite = """ xyz@debian:~$ gunzip new.gz gzip: new already exists; do you wish to overwrite (y or n)? xyz@debian:~$""" COMMAND_KWARGS_overwrite = { 'archive_name': ['new.gz'], 'overwrite': 'True' } COMMAND_RESULT_overwrite = { 'RESULT': [] } COMMAND_OUTPUT_send_to_another_directory = """ xyz@debian:~$ gunzip afile.gz > sed/afile xyz@debian:~$""" COMMAND_KWARGS_send_to_another_directory = { 'archive_name': ['afile.gz'], 'output_file_name': 'sed/afile' } COMMAND_RESULT_send_to_another_directory = { 'RESULT': [] } COMMAND_OUTPUT_on_l_option = """ xyz@debian:~$ gunzip -l afile.gz compressed uncompressed ratio uncompressed_name 26 0 0.0% afile xyz@debian:~$""" COMMAND_KWARGS_on_l_option = { 'archive_name': ['afile.gz'], 'options': '-l' } COMMAND_RESULT_on_l_option = { 'RESULT': [{'compressed': '26', 'uncompressed': '0', 'ratio': '0.0%', 'uncompressed_name': 'afile'}] } COMMAND_OUTPUT_on_vl_option = """ xyz@debian:~$ gunzip -vl afile.gz method crc date time compressed uncompressed ratio uncompressed_name defla 00000000 Aug 9 12:27 26 0 0.0% afile xyz@debian:~$""" COMMAND_KWARGS_on_vl_option = { 'archive_name': ['afile.gz'], 'options': '-vl' } COMMAND_RESULT_on_vl_option = { 'RESULT': [{'method': 'defla', 'crc': '00000000', 'date': 'Aug 9', 'time': '12:27', 'compressed': '26', 'uncompressed': '0', 'ratio': '0.0%', 'uncompressed_name': 'afile'}] }
StarcoderdataPython
1767624
<reponame>CD3/BaseballSimulator # from .Simulator import * # from .Pitchers import *
StarcoderdataPython
3340738
class NewRecreationPage(): def __init__(self, page): self.page = page def open(self): self.page.goto("/places/new")
StarcoderdataPython
1640932
<filename>reddit_user.py # -*- coding: utf-8 -*- import csv import datetime import re import json import time import sys import calendar from collections import Counter from itertools import groupby from urlparse import urlparse import requests import pytz from subreddits import subreddits_dict, ignore_text_subs, default_subs from text_parser import TextParser parser = TextParser() class UserNotFoundError(Exception): pass class NoDataError(Exception): pass class Util: """ Contains a collection of common utility methods. """ @staticmethod def sanitize_text(text): """ Returns text after removing unnecessary parts. """ MAX_WORD_LENGTH = 1024 _text = " ".join([ l for l in text.strip().split("\n") if ( not l.strip().startswith("&gt;") ) ]) substitutions = [ (r"\[(.*?)\]\((.*?)\)", r""), # Remove links from Markdown (r"[\"](.*?)[\"]", r""), # Remove text within quotes (r" \'(.*?)\ '", r""), # Remove text within quotes (r"\.+", r". "), # Remove ellipses (r"\(.*?\)", r""), # Remove text within round brackets (r"&amp;", r"&"), # Decode HTML entities (r"http.?:\S+\b", r" ") # Remove URLs ] for pattern, replacement in substitutions: _text = re.sub(pattern, replacement, _text, flags=re.I) # Remove very long words _text = " ".join( [word for word in _text.split(" ") if len(word) <= MAX_WORD_LENGTH] ) return _text @staticmethod def coalesce(l): """ Given a list, returns the last element that is not equal to "generic". """ l = [x for x in l if x.lower() != "generic"] return next(iter(l[::-1]), "") @staticmethod def humanize_days(days): """ Return text with years, months and days given number of days. """ y = days/365 if days > 365 else 0 m = (days - y*365)/31 if days > 30 else 0 d = (days - m*31 - y*365) yy = str(y) + " year" if y else "" if y > 1: yy += "s" mm = str(m) + " month" if m else "" if m > 1: mm += "s" dd = str(d) + " day" if d>1 or d==0: dd += "s" return (yy + " " + mm + " " + dd).strip() @staticmethod def scale(val, src, dst): """ Scale the given value from the scale of src to the scale of dst. """ return ((val - src[0])/(src[1] - src[0])) * (dst[1]-dst[0]) + dst[0] # Base class for comments and submissions class Post(object): """ A class for "posts" - a post can either be a submission or a comment. """ def __init__( self, id, subreddit, text, created_utc, score, permalink, gilded ): # Post id self.id = id # Subreddit in which this comment or submission was posted self.subreddit = subreddit # For comments, the comment body and for submissions, the self-text self.text = text # UTC timestamp when post was created self.created_utc = created_utc # Post score self.score = score # Permalink to post self.permalink = permalink # Gilded self.gilded = gilded class Comment(Post): """ A class for comments derived from Post. """ def __init__( self, id, subreddit, text, created_utc, score, permalink, submission_id, edited, top_level, gilded ): super(Comment, self).__init__( id, subreddit, text, created_utc, score, permalink, gilded ) # Link ID where comment was posted self.submission_id = submission_id # Edited flag self.edited = edited # Top-level flag self.top_level = top_level class Submission(Post): """ A class for submissions derived from Post. """ def __init__( self, id, subreddit, text, created_utc, score, permalink, url, title, is_self, gilded, domain ): super(Submission, self).__init__( id, subreddit, text, created_utc, score, permalink, gilded ) # Submission link URL self.url = url # Submission title self.title = title # Self post? self.is_self = is_self # Domain self.domain = domain class RedditUser: """ Models a redditor object. Contains methods for processing comments and submissions. """ # If user has posted in a sub 3 times or more, they are # probably interested in the topic. MIN_THRESHOLD = 3 MIN_THRESHOLD_FOR_DEFAULT = 10 HEADERS = { 'User-Agent': 'Sherlock v0.1 by /u/orionmelt' } IMAGE_DOMAINS = ["imgur.com", "flickr.com"] VIDEO_DOMAINS = ["youtube.com", "youtu.be", "vimeo.com", "liveleak.com"] IMAGE_EXTENSIONS = ["jpg", "png", "gif", "bmp"] def __init__(self, username, json_data=None): # Populate username and about data self.username = username self.comments = [] self.submissions = [] if not json_data: # Retrieve about self.about = self.get_about() if not self.about: raise UserNotFoundError # Retrieve comments and submissions self.comments = self.get_comments() self.submissions = self.get_submissions() else: data = json.loads(json_data) self.about = { "created_utc" : datetime.datetime.fromtimestamp( data["about"]["created_utc"], tz=pytz.utc ), "link_karma" : data["about"]["link_karma"], "comment_karma" : data["about"]["comment_karma"], "name" : data["about"]["name"], "reddit_id" : data["about"]["id"], "is_mod" : data["about"]["is_mod"] } for c in data["comments"]: self.comments.append( Comment( id=c["id"], subreddit=c["subreddit"], text=c["text"], created_utc=c["created_utc"], score=c["score"], permalink=c["permalink"], submission_id=c["submission_id"], edited=c["edited"], top_level=c["top_level"], gilded=c["gilded"] ) ) for s in data["submissions"]: self.submissions.append( Submission( id=s["id"], subreddit=s["subreddit"], text=s["text"], created_utc=s["created_utc"], score=s["score"], permalink=s["permalink"], url=s["url"], title=s["title"], is_self=s["is_self"], gilded=s["gilded"], domain=s["domain"] ) ) self.username = self.about["name"] self.signup_date = self.about["created_utc"] self.link_karma = self.about["link_karma"] self.comment_karma = self.about["comment_karma"] self.reddit_id = self.about["reddit_id"] self.is_mod = self.about["is_mod"] # Initialize other properties self.today = datetime.datetime.now(tz=pytz.utc).date() start = self.signup_date.date() self.age_in_days = (self.today - start).days self.first_post_date = None self.earliest_comment = None self.latest_comment = None self.best_comment = None self.worst_comment = None self.earliest_submission = None self.latest_submission = None self.best_submission = None self.worst_submission = None self.metrics = { "date" : [], "weekday" : [], "hour" : [], "subreddit" : [], "heatmap" : [], "recent_karma" : [], "recent_posts" : [] } self.submissions_by_type = { "name" : "All", "children" : [ { "name" : "Self", "children" : [] }, { "name" : "Image", "children" : [] }, { "name" : "Video", "children" : [] }, { "name" : "Other", "children" : [] } ] } self.metrics["date"] = [ { "date" : (year, month), "comments" : 0, "submissions": 0, "comment_karma": 0, "submission_karma": 0 } for (year, month) in sorted( list( set([ ( (self.today - datetime.timedelta(days=x)).year, (self.today - datetime.timedelta(days=x)).month ) for x in range(0, (self.today - start).days) ]) ) ) ] self.metrics["heatmap"] = [0] * 24 * 61 self.metrics["recent_karma"] = [0] * 61 self.metrics["recent_posts"] = [0] * 61 self.metrics["hour"] = [ { "hour": hour, "comments": 0, "submissions": 0, "comment_karma": 0, "submission_karma": 0 } for hour in range(0, 24) ] self.metrics["weekday"] = [ { "weekday": weekday, "comments": 0, "submissions": 0, "comment_karma": 0, "submission_karma": 0 } for weekday in range(0, 7) ] self.genders = [] self.orientations = [] self.relationship_partners = [] # Data that we are reasonably sure that *are* names of places. self.places_lived = [] # Data that looks like it could be a place, but we're not sure. self.places_lived_extra = [] # Data that we are reasonably sure that *are* names of places. self.places_grew_up = [] # Data that looks like it could be a place, but we're not sure. self.places_grew_up_extra = [] self.family_members = [] self.pets = [] self.attributes = [] self.attributes_extra = [] self.possessions = [] self.possessions_extra = [] self.actions = [] self.actions_extra = [] self.favorites = [] self.sentiments = [] self.derived_attributes = { "family_members" : [], "gadget" : [], "gender" : [], "locations" : [], "orientation" : [], "physical_characteristics" : [], "political_view" : [], "possessions" : [], "religion and spirituality" : [] } self.corpus = "" self.commented_dates = [] self.submitted_dates = [] self.lurk_period = None self.comments_gilded = 0 self.submissions_gilded = 0 self.process() def __str__(self): return str(self.results()) def get_about(self): """ Returns basic data about redditor. """ url = r"http://www.reddit.com/user/%s/about.json" % self.username response = requests.get(url, headers=self.HEADERS) response_json = response.json() if "error" in response_json and response_json["error"] == 404: return None about = { "created_utc" : datetime.datetime.fromtimestamp( response_json["data"]["created_utc"], tz=pytz.utc ), "link_karma" : response_json["data"]["link_karma"], "comment_karma" : response_json["data"]["comment_karma"], "name" : response_json["data"]["name"], "reddit_id" : response_json["data"]["id"], "is_mod" : response_json["data"]["is_mod"] } return about def get_comments(self, limit=None): """ Returns a list of redditor's comments. """ comments = [] more_comments = True after = None base_url = r"http://www.reddit.com/user/%s/comments/.json?limit=100" \ % self.username url = base_url while more_comments: response = requests.get(url, headers=self.HEADERS) response_json = response.json() # TODO - Error handling for user not found (404) and # rate limiting (429) errors for child in response_json["data"]["children"]: id = child["data"]["id"].encode("ascii", "ignore") subreddit = child["data"]["subreddit"].\ encode("ascii", "ignore") text = child["data"]["body"].encode("ascii", "ignore") created_utc = child["data"]["created_utc"] score = child["data"]["score"] submission_id = child["data"]["link_id"].\ encode("ascii", "ignore").lower()[3:] edited = child["data"]["edited"] top_level = True \ if child["data"]["parent_id"].startswith("t3") else False gilded = child["data"]["gilded"] permalink = "http://www.reddit.com/r/%s/comments/%s/_/%s" \ % (subreddit, submission_id, id) comment = Comment( id=id, subreddit=subreddit, text=text, created_utc=created_utc, score=score, permalink=permalink, submission_id=submission_id, edited=edited, top_level=top_level, gilded=gilded ) comments.append(comment) after = response_json["data"]["after"] if after: url = base_url + "&after=%s" % after # reddit may rate limit if we don't wait for 2 seconds # between successive requests. If that happens, # uncomment and increase sleep time in the following line. #time.sleep(0.5) else: more_comments = False return comments def get_submissions(self, limit=None): """ Returns a list of redditor's submissions. """ submissions = [] more_submissions = True after = None base_url = r"http://www.reddit.com/user/%s/submitted/.json?limit=100" \ % self.username url = base_url while more_submissions: response = requests.get(url, headers=self.HEADERS) response_json = response.json() # TODO - Error handling for user not found (404) and # rate limiting (429) errors for child in response_json["data"]["children"]: id = child["data"]["id"].encode("ascii","ignore") subreddit = child["data"]["subreddit"].\ encode("ascii", "ignore") text = child["data"]["selftext"].\ encode("ascii", "ignore").lower() created_utc = child["data"]["created_utc"] score = child["data"]["score"] permalink = "http://www.reddit.com" + \ child["data"]["permalink"].\ encode("ascii", "ignore").lower() url = child["data"]["url"].encode("ascii", "ignore").lower() title = child["data"]["title"].encode("ascii", "ignore") is_self = child["data"]["is_self"] gilded = child["data"]["gilded"] domain = child["data"]["domain"] submission = Submission( id=id, subreddit=subreddit, text=text, created_utc=created_utc, score=score, permalink=permalink, url=url, title=title, is_self=is_self, gilded=gilded, domain=domain ) submissions.append(submission) after = response_json["data"]["after"] if after: url = base_url + "&after=%s" % after # reddit may rate limit if we don't wait for 2 seconds # between successive requests. If that happens, # uncomment and increase sleep time in the following line. #time.sleep(0.5) else: more_submissions = False return submissions def process(self): """ Retrieves redditor's comments and submissions and processes each of them. """ if self.comments: self.process_comments() if self.submissions: self.process_submissions() if self.comments or self.submissions: self.derive_attributes() def process_comments(self): """ Process list of redditor's comments. """ if not self.comments: return self.earliest_comment = self.comments[-1] self.latest_comment = self.comments[0] self.best_comment = self.comments[0] self.worst_comment = self.comments[0] for comment in self.comments: self.process_comment(comment) def process_submissions(self): """ Process list of redditor's submissions. """ if not self.submissions: return self.earliest_submission = self.submissions[-1] self.latest_submission = self.submissions[0] self.best_submission = self.submissions[0] self.worst_submission = self.submissions[0] for submission in self.submissions: self.process_submission(submission) def process_comment(self, comment): """ Process a single comment. * Updates metrics * Sanitizes and extracts chunks from comment. """ # Sanitize comment text. text = Util.sanitize_text(comment.text) # Add comment text to corpus. self.corpus += text.lower() comment_timestamp = datetime.datetime.fromtimestamp( comment.created_utc, tz=pytz.utc ) self.commented_dates.append(comment_timestamp) self.comments_gilded += comment.gilded days_ago_60 = self.today - datetime.timedelta(60) if (comment_timestamp.date() - days_ago_60).days > 0: self.metrics["heatmap"][ (comment_timestamp.date() - days_ago_60).days*24 + \ comment_timestamp.hour ] += 1 self.metrics["recent_karma"][ (comment_timestamp.date() - days_ago_60).days ] += comment.score self.metrics["recent_posts"][ (comment_timestamp.date() - days_ago_60).days ] += 1 # Update metrics for i, d in enumerate(self.metrics["date"]): if d["date"] == ( comment_timestamp.date().year, comment_timestamp.date().month ): d["comments"] += 1 d["comment_karma"] += comment.score self.metrics["date"][i] = d break for i, h in enumerate(self.metrics["hour"]): if h["hour"] == comment_timestamp.hour: h["comments"] += 1 h["comment_karma"] += comment.score self.metrics["hour"][i] = h break for i, w in enumerate(self.metrics["weekday"]): if w["weekday"] == comment_timestamp.date().weekday(): w["comments"] += 1 w["comment_karma"] += comment.score self.metrics["weekday"][i] = w break if comment.score > self.best_comment.score: self.best_comment = comment elif comment.score < self.worst_comment.score: self.worst_comment = comment # If comment is in a subreddit in which comments/self text # are to be ignored (such as /r/jokes, /r/writingprompts, etc), # do not process it further. if comment.subreddit in ignore_text_subs: return False # If comment text does not contain "I" or "my", why even bother? if not re.search(r"\b(i|my)\b", text, re.I): return False # Now, this is a comment that needs to be processed. (chunks, sentiments) = parser.extract_chunks(text) self.sentiments += sentiments for chunk in chunks: self.load_attributes(chunk, comment) return True def process_submission(self, submission): """ Process a single submission. * Updates metrics * Sanitizes and extracts chunks from self text. """ if(submission.is_self): text = Util.sanitize_text(submission.text) self.corpus += text.lower() submission_timestamp = datetime.datetime.fromtimestamp( submission.created_utc, tz=pytz.utc ) self.submitted_dates.append(submission_timestamp) self.submissions_gilded += submission.gilded days_ago_60 = self.today - datetime.timedelta(60) if (submission_timestamp.date() - days_ago_60).days>0: self.metrics["heatmap"][ ((submission_timestamp.date() - days_ago_60).days-1)*24 + \ submission_timestamp.hour ] += 1 self.metrics["recent_karma"][ (submission_timestamp.date() - days_ago_60).days ] += submission.score self.metrics["recent_posts"][ (submission_timestamp.date() - days_ago_60).days ] += 1 for i, d in enumerate(self.metrics["date"]): if d["date"] == ( submission_timestamp.date().year, submission_timestamp.date().month ): d["submissions"] += 1 d["submission_karma"] += submission.score self.metrics["date"][i] = d break for i, h in enumerate(self.metrics["hour"]): if h["hour"] == submission_timestamp.hour: h["submissions"] += 1 h["submission_karma"] += submission.score self.metrics["hour"][i] = h break for i, w in enumerate(self.metrics["weekday"]): if w["weekday"] == submission_timestamp.date().weekday(): w["submissions"] += 1 w["submission_karma"] += submission.score self.metrics["weekday"][i] = w break submission_type = None submission_domain = None submission_url_path = urlparse(submission.url).path if submission.domain.startswith("self."): submission_type = "Self" submission_domain = submission.subreddit elif ( submission_url_path.endswith(tuple(self.IMAGE_EXTENSIONS)) or submission.domain.endswith(tuple(self.IMAGE_DOMAINS)) ): submission_type = "Image" submission_domain = submission.domain elif submission.domain.endswith(tuple(self.VIDEO_DOMAINS)): submission_type = "Video" submission_domain = submission.domain else: submission_type = "Other" submission_domain = submission.domain t = [ x for x in self.submissions_by_type["children"] \ if x["name"]==submission_type ][0] d = ( [x for x in t["children"] if x["name"]==submission_domain] or \ [None] )[0] if d: d["size"] += 1 else: t["children"].append({ "name" : submission_domain, "size" : 1 }) if submission.score > self.best_submission.score: self.best_submission = submission elif submission.score < self.worst_submission.score: self.worst_submission = submission # If submission is in a subreddit in which comments/self text # are to be ignored (such as /r/jokes, /r/writingprompts, etc), # do not process it further. if submission.subreddit in ignore_text_subs: return False # Only process self texts that contain "I" or "my" if not submission.is_self or not re.search(r"\b(i|my)\b",text,re.I): return False (chunks, sentiments) = parser.extract_chunks(text) self.sentiments += sentiments for chunk in chunks: self.load_attributes(chunk, submission) return True def load_attributes(self, chunk, post): """ Given an extracted chunk, load appropriate attribtues from it. """ # Is this chunk a possession/belonging? if chunk["kind"] == "possession" and chunk["noun_phrase"]: # Extract noun from chunk noun_phrase = chunk["noun_phrase"] noun_phrase_text = " ".join([w for w, t in noun_phrase]) norm_nouns = " ".join([ parser.normalize(w, t) \ for w,t in noun_phrase if t.startswith("N") ]) noun = next( (w for w, t in noun_phrase if t.startswith("N")), None ) if noun: # See if noun is a pet, family member or a relationship partner pet = parser.pet_animal(noun) family_member = parser.family_member(noun) relationship_partner = parser.relationship_partner(noun) if pet: self.pets.append((pet, post.permalink)) elif family_member: self.family_members.append((family_member, post.permalink)) elif relationship_partner: self.relationship_partners.append( (relationship_partner, post.permalink) ) else: self.possessions_extra.append((norm_nouns, post.permalink)) # Is this chunk an action? elif chunk["kind"] == "action" and chunk["verb_phrase"]: verb_phrase = chunk["verb_phrase"] verb_phrase_text = " ".join([w for w, t in verb_phrase]) # Extract verbs, adverbs, etc from chunk norm_adverbs = [ parser.normalize(w,t) \ for w, t in verb_phrase if t.startswith("RB") ] adverbs = [w.lower() for w, t in verb_phrase if t.startswith("RB")] norm_verbs = [ parser.normalize(w,t) \ for w, t in verb_phrase if t.startswith("V") ] verbs = [w.lower() for w, t in verb_phrase if t.startswith("V")] prepositions = [w for w, t in chunk["prepositions"]] noun_phrase = chunk["noun_phrase"] noun_phrase_text = " ".join( [w for w, t in noun_phrase if t not in ["DT"]] ) norm_nouns = [ parser.normalize(w,t) \ for w, t in noun_phrase if t.startswith("N") ] proper_nouns = [w for w, t in noun_phrase if t == "NNP"] determiners = [ parser.normalize(w, t) \ for w, t in noun_phrase if t.startswith("DT") ] prep_noun_phrase = chunk["prep_noun_phrase"] prep_noun_phrase_text = " ".join([w for w, t in prep_noun_phrase]) pnp_prepositions = [ w.lower() for w, t in prep_noun_phrase if t in ["TO", "IN"] ] pnp_norm_nouns = [ parser.normalize(w, t) \ for w, t in prep_noun_phrase if t.startswith("N") ] pnp_determiners = [ parser.normalize(w, t) \ for w, t in prep_noun_phrase if t.startswith("DT") ] full_noun_phrase = ( noun_phrase_text + " " + prep_noun_phrase_text ).strip() # TODO - Handle negative actions (such as I am not...), # but for now: if any( w in ["never", "no", "not", "nothing"] \ for w in norm_adverbs+determiners ): return # I am/was ... if (len(norm_verbs) == 1 and "be" in norm_verbs and not prepositions and noun_phrase): # Ignore gerund nouns for now if ( "am" in verbs and any(n.endswith("ing") for n in norm_nouns) ): self.attributes_extra.append( (full_noun_phrase, post.permalink) ) return attribute = [] for noun in norm_nouns: gender = None orientation = None if "am" in verbs: gender = parser.gender(noun) orientation = parser.orientation(noun) if gender: self.genders.append((gender, post.permalink)) elif orientation: self.orientations.append( (orientation, post.permalink) ) # Include only "am" phrases elif "am" in verbs: attribute.append(noun) if attribute and ( ( # Include only attributes that end # in predefined list of endings... any( a.endswith( parser.include_attribute_endings ) for a in attribute ) and not ( # And exclude... # ...certain lone attributes ( len(attribute) == 1 and attribute[0] in parser.skip_lone_attributes and not pnp_norm_nouns ) or # ...predefined skip attributes any(a in attribute for a in parser.skip_attributes) or # ...attributes that end in predefined # list of endings any( a.endswith( parser.exclude_attribute_endings ) for a in attribute ) ) ) or ( # And include special attributes with different endings any(a in attribute for a in parser.include_attributes) ) ): self.attributes.append( (full_noun_phrase, post.permalink) ) elif attribute: self.attributes_extra.append( (full_noun_phrase, post.permalink) ) # I live(d) in ... elif "live" in norm_verbs and prepositions and norm_nouns: if any( p in ["in", "near", "by"] for p in prepositions ) and proper_nouns: self.places_lived.append( ( " ".join(prepositions) + " " + noun_phrase_text, post.permalink ) ) else: self.places_lived_extra.append( ( " ".join(prepositions) + " " + noun_phrase_text, post.permalink ) ) # I grew up in ... elif "grow" in norm_verbs and "up" in prepositions and norm_nouns: if any( p in ["in", "near", "by"] for p in prepositions ) and proper_nouns: self.places_grew_up.append( ( " ".join( [p for p in prepositions if p != "up"] ) + " " + noun_phrase_text, post.permalink ) ) else: self.places_grew_up_extra.append( ( " ".join( [p for p in prepositions if p != "up"] ) + " " + noun_phrase_text, post.permalink ) ) elif( len(norm_verbs) == 1 and "prefer" in norm_verbs and norm_nouns and not determiners and not prepositions ): self.favorites.append((full_noun_phrase, post.permalink)) elif norm_nouns: actions_extra = " ".join(norm_verbs) self.actions_extra.append((actions_extra, post.permalink)) def derive_attributes(self): """ Derives attributes using activity data. """ for name, count in self.commented_subreddits(): subreddit = subreddits_dict[name] \ if name in subreddits_dict else None if ( subreddit and subreddit["attribute"] and count >= self.MIN_THRESHOLD ): self.derived_attributes[subreddit["attribute"]].append( subreddit["value"].lower() ) for name, count in self.submitted_subreddits(): subreddit = subreddits_dict[name] \ if name in subreddits_dict else None if ( subreddit and subreddit["attribute"] and count >= self.MIN_THRESHOLD ): self.derived_attributes[subreddit["attribute"]].append( subreddit["value"].lower() ) # If someone mentions their wife, # they should be male, and vice-versa (?) if "wife" in [v for v, s in self.relationship_partners]: self.derived_attributes["gender"].append("male") elif "husband" in [v for v, s in self.relationship_partners]: self.derived_attributes["gender"].append("female") commented_dates = sorted(self.commented_dates) submitted_dates = sorted(self.submitted_dates) active_dates = sorted(self.commented_dates + self.submitted_dates) min_date = datetime.datetime(datetime.MINYEAR, 1, 1, tzinfo=pytz.utc) first_comment_date = \ min(commented_dates) if commented_dates else min_date first_submission_date = \ min(submitted_dates) if submitted_dates else min_date self.first_post_date = max(first_comment_date, first_submission_date) active_dates += [datetime.datetime.now(tz=pytz.utc)] commented_dates += [datetime.datetime.now(tz=pytz.utc)] submitted_dates += [datetime.datetime.now(tz=pytz.utc)] # Find the longest period of inactivity comment_lurk_period = max( [ { "from" : calendar.timegm(d1.utctimetuple()), "to" : calendar.timegm(d2.utctimetuple()), "days" : (d2 - d1).seconds, } for d1, d2 in zip( commented_dates[:-1], commented_dates[1:] ) ], key=lambda x:x["days"] ) if len(commented_dates) > 1 else {"days":-1} submission_lurk_period = max( [ { "from" : calendar.timegm(d1.utctimetuple()), "to" : calendar.timegm(d2.utctimetuple()), "days" : (d2 - d1).seconds, } for d1, d2 in zip( submitted_dates[:-1], submitted_dates[1:] ) ], key=lambda x:x["days"] ) if len(submitted_dates) > 1 else {"days":-1} post_lurk_period = max( [ { "from" : calendar.timegm(d1.utctimetuple()), "to" : calendar.timegm(d2.utctimetuple()), "days" : (d2 - d1).seconds, } for d1, d2 in zip( active_dates[:-1], active_dates[1:] ) ], key=lambda x:x["days"] ) self.lurk_period = min( [ x for x in [ comment_lurk_period, submission_lurk_period, post_lurk_period ] if x["days"]>=0 ], key=lambda x:x["days"] ) del self.lurk_period["days"] def commented_subreddits(self): """ Returns a list of subreddits redditor has commented on. """ return [ (name, count) for (name, count) in Counter( [comment.subreddit for comment in self.comments] ).most_common() ] def submitted_subreddits(self): """ Returns a list of subreddits redditor has submitted to. """ return [ (name,count) for (name,count) in Counter( [submission.subreddit for submission in self.submissions] ).most_common() ] def results(self): """ Returns accumulated data as JSON. """ # Redditor has no data? if not (self.comments or self.submissions): raise NoDataError # Format metrics metrics_date = [] for d in self.metrics["date"]: metrics_date.append( { "date" : "%d-%02d-01" % (d["date"][0], d["date"][1]), "comments" : d["comments"], "submissions" : d["submissions"], "posts" : d["comments"] + d["submissions"], "comment_karma" : d["comment_karma"], "submission_karma" : d["submission_karma"], "karma" : d["comment_karma"] + d["submission_karma"] } ) metrics_hour = [] for h in self.metrics["hour"]: metrics_hour.append( { "hour" : h["hour"], "comments" : h["comments"], "submissions" : h["submissions"], "posts" : h["comments"] + h["submissions"], "comment_karma" : h["comment_karma"], "submission_karma" : h["submission_karma"], "karma" : h["comment_karma"] + h["submission_karma"] } ) weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] metrics_weekday = [] for w in self.metrics["weekday"]: metrics_weekday.append( { "weekday" : weekdays[w["weekday"]], "comments" : w["comments"], "submissions" : w["submissions"], "posts" : w["comments"] + w["submissions"], "comment_karma" : w["comment_karma"], "submission_karma" : w["submission_karma"], "karma" : w["comment_karma"] + w["submission_karma"] } ) metrics_subreddit = { "name" : "All", "children" : [] } for (name, [comments, comment_karma]) in [ (s, [sum(x) for x in zip(*[(1, r[1]) for r in group])]) \ for s, group in groupby( sorted( [ (p.subreddit, p.score) for p in self.comments ], key=lambda x: x[0] ), lambda x: x[0] ) ]: subreddit = subreddits_dict[name] \ if name in subreddits_dict else None if subreddit and subreddit["topic_level1"] != "Other": topic_level1 = subreddit["topic_level1"] else: topic_level1 = "Other" level1 = ( [ t for t in metrics_subreddit["children"] \ if t["name"] == topic_level1 ] or [None] )[0] if level1: level1["children"].append( { "name" : name, "comments" : comments, "submissions" : 0, "posts" : comments, "comment_karma" : comment_karma, "submission_karma" : 0, "karma" : comment_karma } ) else: metrics_subreddit["children"].append( { "name" : topic_level1, "children" : [ { "name" : name, "comments" : comments, "submissions" : 0, "posts" : comments, "comment_karma" : comment_karma, "submission_karma" : 0, "karma" : comment_karma } ] } ) for (name, [submissions, submission_karma]) in [ (s, [sum(x) for x in zip(*[(1,r[1]) for r in group])]) \ for s, group in groupby( sorted( [ (p.subreddit, p.score) for p in self.submissions ], key=lambda x: x[0] ), lambda x: x[0] ) ]: subreddit = subreddits_dict[name] \ if name in subreddits_dict else None if subreddit and subreddit["topic_level1"] != "Other": topic_level1 = subreddit["topic_level1"] else: topic_level1 = "Other" level1 = ( [ t for t in metrics_subreddit["children"] \ if t["name"] == topic_level1 ] or [None] )[0] if level1: sub_in_level1 = ( [ s for s in level1["children"] if s["name"] == name ] or [None] )[0] if sub_in_level1: sub_in_level1["submissions"] = submissions sub_in_level1["submission_karma"] = submission_karma sub_in_level1["posts"] += submissions sub_in_level1["karma"] += submission_karma else: level1["children"].append( { "name" : name, "comments" : 0, "submissions" : submissions, "posts" : submissions, "comment_karma" : 0, "submission_karma" : submission_karma, "karma" : submission_karma } ) else: metrics_subreddit["children"].append( { "name" : topic_level1, "children" : [ { "name" : name, "comments" : 0, "submissions" : submissions, "posts" : submissions, "comment_karma" : 0, "submission_karma" : submission_karma, "karma" : submission_karma } ] } ) metrics_topic = { "name" : "All", "children" : [] } # We need both topics (for Posts across topics) and # synopsis_topics (for Synopsis) because we want to include only # topics that meet the threshold limits in synopsis_topics synopsis_topics = [] for name, count in Counter( [s.subreddit for s in self.submissions] + [c.subreddit for c in self.comments] ).most_common(): if ( name in default_subs and count >= self.MIN_THRESHOLD_FOR_DEFAULT ) or count >= self.MIN_THRESHOLD: subreddit = subreddits_dict[name] \ if name in subreddits_dict else None if subreddit: topic = subreddit["topic_level1"] if subreddit["topic_level2"]: topic += ">" + subreddit["topic_level2"] else: topic += ">" + "Generic" if subreddit["topic_level3"]: topic += ">" + subreddit["topic_level3"] else: topic += ">" + "Generic" synopsis_topics += [topic] * count topics = [] for comment in self.comments: subreddit = subreddits_dict[comment.subreddit] \ if comment.subreddit in subreddits_dict else None if subreddit and subreddit["topic_level1"] != "Other": topic = subreddit["topic_level1"] if subreddit["topic_level2"]: topic += ">" + subreddit["topic_level2"] else: topic += ">" + "Generic" if subreddit["topic_level3"]: topic += ">" + subreddit["topic_level3"] else: topic += ">" + "Generic" topics.append(topic) else: topics.append("Other") for submission in self.submissions: subreddit = subreddits_dict[submission.subreddit] \ if submission.subreddit in subreddits_dict else None if subreddit and subreddit["topic_level1"] != "Other": topic = subreddit["topic_level1"] if subreddit["topic_level2"]: topic += ">" + subreddit["topic_level2"] else: topic += ">" + "Generic" if subreddit["topic_level3"]: topic += ">" + subreddit["topic_level3"] else: topic += ">" + "Generic" topics.append(topic) else: topics.append("Other") for topic, count in Counter(topics).most_common(): level_topics = filter(None, topic.split(">")) current_node = metrics_topic for i, level_topic in enumerate(level_topics): children = current_node["children"] if i+1 < len(level_topics): found_child = False for child in children: if child["name"] == level_topic: child_node = child found_child = True break if not found_child: child_node = { "name" : level_topic, "children" : [] } children.append(child_node) current_node = child_node else: child_node = { "name" : level_topic, "size" : count } children.append(child_node) common_words = [ { "text" : word, "size" : count } for word, count in Counter( parser.common_words(self.corpus) ).most_common(200) ] total_word_count = parser.total_word_count(self.corpus) unique_word_count = parser.unique_word_count(self.corpus) # Let's use an average of 40 WPM hours_typed = round(total_word_count/(40.00*60.00), 2) gender = [] for value, count in Counter( [value for value, source in self.genders] ).most_common(1): sources = [s for v, s in self.genders if v == value] gender.append( { "value" : value, "count" : count, "sources" : sources } ) orientation = [] for value, count in Counter( [value for value, source in self.orientations] ).most_common(1): sources = [s for v, s in self.orientations if v == value] orientation.append( { "value" : value, "count" : count, "sources" : sources } ) relationship_partner = [] for value, count in Counter( [value for value, source in self.relationship_partners] ).most_common(1): sources = [s for v, s in self.relationship_partners if v == value] relationship_partner.append( { "value" : value, "count" : count, "sources" : sources } ) places_lived = [] for value, count in Counter( [value for value, source in self.places_lived] ).most_common(): sources = [s for v, s in self.places_lived if v == value] places_lived.append( { "value" : value, "count" : count, "sources" : sources } ) places_lived_extra = [] for value, count in Counter( [value for value, source in self.places_lived_extra] ).most_common(): sources = [s for v, s in self.places_lived_extra if v == value] places_lived_extra.append( { "value" : value, "count" : count, "sources" : sources } ) places_grew_up = [] for value, count in Counter( [value for value, source in self.places_grew_up] ).most_common(): sources = [s for v, s in self.places_grew_up if v == value] places_grew_up.append( { "value" : value, "count" : count, "sources" : sources } ) places_grew_up_extra = [] for value, count in Counter( [value for value, source in self.places_grew_up_extra] ).most_common(): sources = [s for v, s in self.places_grew_up_extra if v == value] places_grew_up_extra.append( { "value" : value, "count" : count, "sources" : sources } ) family_members = [] for value, count in Counter( [value for value, source in self.family_members] ).most_common(): sources = [s for v, s in self.family_members if v == value] family_members.append( { "value" : value, "count" : count, "sources" : sources } ) pets = [] for value, count in Counter( [value for value, source in self.pets] ).most_common(): sources = [s for v, s in self.pets if v == value] pets.append( { "value" : value, "count" : count, "sources" : sources } ) favorites = [] for value, count in Counter( [value for value, source in self.favorites] ).most_common(): sources = [s for v, s in self.favorites if v == value] favorites.append( { "value" : value, "count" : count, "sources" : sources } ) attributes = [] for value, count in Counter( [value for value, source in self.attributes] ).most_common(): sources = [s for v, s in self.attributes if v == value] attributes.append( { "value" : value, "count" : count, "sources" : sources } ) attributes_extra = [] for value, count in Counter( [value for value, source in self.attributes_extra] ).most_common(): sources = [s for v, s in self.attributes_extra if v == value] attributes_extra.append( { "value" : value, "count" : count, "sources" : sources } ) possessions = [] for value, count in Counter( [value for value, source in self.possessions] ).most_common(): sources = [s for v, s in self.possessions if v == value] possessions.append( { "value" : value, "count" : count, "sources" : sources } ) possessions_extra = [] for value, count in Counter( [value for value, source in self.possessions_extra] ).most_common(): sources = [s for v, s in self.possessions_extra if v == value] possessions_extra.append( { "value" : value, "count" : count, "sources" : sources } ) actions = [] for value, count in Counter( [value for value, source in self.actions] ).most_common(): sources = [s for v, s in self.actions if v == value] actions.append( { "value" : value, "count" : count, "sources" : sources } ) actions_extra = [] for value, count in Counter( [value for value, source in self.actions_extra] ).most_common(): sources = [s for v, s in self.actions_extra if v == value] actions_extra.append( { "value" : value, "count" : count, "sources" : sources } ) synopsis = {} if gender: synopsis["gender"] = { "data" : gender } if orientation: synopsis["orientation"] = { "data" : orientation } if relationship_partner: synopsis["relationship_partner"] = { "data" : relationship_partner } if places_lived: synopsis["places_lived"] = { "data" : places_lived } if places_lived_extra: if "places_lived" in synopsis: synopsis["places_lived"].update( { "data_extra" : places_lived_extra } ) else: synopsis["places_lived"] = { "data_extra" : places_lived_extra } if places_grew_up: synopsis["places_grew_up"] = { "data" : places_grew_up } if places_grew_up_extra: if "places_grew_up" in synopsis: synopsis["places_grew_up"].update( { "data_extra" : places_grew_up_extra } ) else: synopsis["places_grew_up"] = { "data_extra" : places_grew_up_extra } if family_members: synopsis["family_members"] = { "data" : family_members } if pets: synopsis["pets"] = { "data" : pets } if favorites: synopsis["favorites"] = { "data" : favorites } if attributes: synopsis["attributes"] = { "data" : attributes } if attributes_extra: if "attributes" in synopsis: synopsis["attributes"].update( { "data_extra" : attributes_extra } ) else: synopsis["attributes"] = { "data_extra" : attributes_extra } if possessions: synopsis["possessions"] = { "data" : possessions } if possessions_extra: if "possessions" in synopsis: synopsis["possessions"].update( { "data_extra" : possessions_extra } ) else: synopsis["possessions"] = { "data_extra" : possessions_extra } ''' Will work on actions later if actions: synopsis["actions"] = { "data" : actions } if actions_extra: if "actions" in synopsis: synopsis["actions"].update( { "data_extra" : actions_extra } ) else: synopsis["actions"] = { "data_extra" : actions_extra } ''' level1_topic_groups = [ "business","entertainment", "gaming", "hobbies and interests", "lifestyle", "locations", "music", "science", "sports", "technology", "news and politics" ] level2_topic_groups = [ "television", "books", "celebrities", # Entertainment "religion and spirituality", # Lifestyle ] exclude_topics = ["general", "drugs", "meta", "adult and nsfw", "other"] exclude_coalesced_topics = [ "religion and spirituality", "more interests", "alternative" ] topic_min_levels = { "business" : 2, "entertainment" : 3, "gaming" : 2, "hobbies and interests" : 2, "lifestyle" : 2, "locations" : 3, "music" : 2, "science" : 2, "sports" : 2, "technology" : 2, "news and politics" : 2 } for topic, count in Counter(synopsis_topics).most_common(): if count < self.MIN_THRESHOLD: continue level_topics = [ x.lower() for x in topic.split(">") if x.lower() != "generic" ] key = None if level_topics[0] not in exclude_topics: m = 2 if level_topics[0] in level1_topic_groups: m = topic_min_levels[level_topics[0]] if ( len(level_topics) >= m and level_topics[1] in level2_topic_groups and level_topics[1] not in exclude_topics ): key = level_topics[1] elif ( len(level_topics) >= m and level_topics[1] not in exclude_topics ): key = level_topics[0] elif level_topics[0] not in level1_topic_groups: key = "other" coalesced_topic = Util.coalesce(level_topics).lower() if key and coalesced_topic not in exclude_coalesced_topics: if key in synopsis: if key not in ["gender", "religion and spirituality"]: synopsis[key]["data"].append( { "value" : coalesced_topic, "count" : count } ) else: synopsis[key] = { "data" : [ { "value" : coalesced_topic, "count" : count } ] } for k in {k: v for k, v in self.derived_attributes.items() if len(v)}: dd = [ { "value" : v, "count" : c, "sources" : None } for v, c in Counter(self.derived_attributes[k]).most_common() ] if k in ["gender", "religion and spirituality"]: dd = dd[:1] if k in synopsis: synopsis[k].update( { "data_derived" : dd } ) else: synopsis[k] = { "data_derived" : dd } computed_comment_karma = sum( [x["comment_karma"] for x in metrics_date] ) computed_submission_karma = sum( [x["submission_karma"] for x in metrics_date] ) hmin = min(self.metrics["heatmap"])*1.0 or 1.0 hmax = max(self.metrics["heatmap"])*1.0 if hmin < hmax: heatmap = ''.join( [ hex( int(Util.scale(h, (hmin, hmax), (1, 15))) )[2:] if h > 0 else "0" for h in self.metrics["heatmap"] ] ) else: heatmap = "0" * 1464 results = { "username" : self.username, "version" : 8, "metadata" : { "reddit_id" : self.reddit_id, "latest_comment_id" : self.latest_comment.id \ if self.latest_comment else None, "latest_submission_id" : self.latest_submission.id \ if self.latest_submission else None }, "summary" : { "signup_date" : calendar.timegm( self.signup_date.utctimetuple() ), "first_post_date" : calendar.timegm( self.first_post_date.utctimetuple() ), "lurk_period" : self.lurk_period, "comments" : { "count" : len(self.comments), "gilded" : self.comments_gilded, "best" : { "text" : self.best_comment.text \ if self.best_comment else None, "permalink" : self.best_comment.permalink \ if self.best_comment else None }, "worst" : { "text" : self.worst_comment.text \ if self.worst_comment else None, "permalink" : self.worst_comment.permalink \ if self.worst_comment else None }, "all_time_karma" : self.comment_karma, "computed_karma" : computed_comment_karma, "average_karma" : round( computed_comment_karma/(len(self.comments) or 1), 2 ), "total_word_count" : total_word_count, "unique_word_count" : unique_word_count, "hours_typed" : hours_typed, "karma_per_word" : round( computed_comment_karma/(total_word_count*1.00 or 1), 2 ) }, "submissions" : { "count" : len(self.submissions), "gilded" : self.submissions_gilded, "best" : { "title" : self.best_submission.title \ if self.best_submission else None, "permalink" : self.best_submission.permalink \ if self.best_submission else None }, "worst" : { "title" : self.worst_submission.title \ if self.worst_submission else None, "permalink" : self.worst_submission.permalink \ if self.worst_submission else None }, "all_time_karma" : self.link_karma, "computed_karma" : computed_submission_karma, "average_karma" : round( computed_submission_karma / (len(self.submissions) or 1), 2 ), "type_domain_breakdown" : self.submissions_by_type } }, "synopsis" : synopsis, "metrics" : { "date" : metrics_date, "hour" : metrics_hour, "weekday" : metrics_weekday, "subreddit" : metrics_subreddit, "topic" : metrics_topic, "common_words" : common_words, "recent_activity_heatmap" : heatmap, "recent_karma" : self.metrics["recent_karma"], "recent_posts" : self.metrics["recent_posts"] } } return json.dumps(results)
StarcoderdataPython
118402
DynamoTable # unused import (dynamo_query/__init__.py:8) DynamoRecord # unused variable (dynamo_query/__init__.py:12) create # unused function (dynamo_query/data_table.py:119) memo # unused variable (dynamo_query/data_table.py:137) filter_keys # unused function (dynamo_query/data_table.py:299) get_column # unused function (dynamo_query/data_table.py:472) drop_duplicates # unused function (dynamo_query/data_table.py:734) sanitize_key # unused function (dynamo_query/dictclasses/dictclass.py:127) compute_key # unused function (dynamo_query/dictclasses/dictclass.py:131) sanitize # unused function (dynamo_query/dictclasses/dictclass.py:351) get_field_names # unused function (dynamo_query/dictclasses/dynamo_dictclass.py:32) DynamoAutoscaler # unused class (dynamo_query/dynamo_autoscaler.py:17) deregister_auto_scaling # unused function (dynamo_query/dynamo_autoscaler.py:47) register_auto_scaling # unused function (dynamo_query/dynamo_autoscaler.py:76) get_last_evaluated_key # unused function (dynamo_query/dynamo_query_main.py:648) reset_start_key # unused function (dynamo_query/dynamo_query_main.py:677) get_raw_responses # unused function (dynamo_query/dynamo_query_main.py:684) DynamoTable # unused class (dynamo_query/dynamo_table.py:63) delete_table # unused function (dynamo_query/dynamo_table.py:232) invalidate_cache # unused function (dynamo_query/dynamo_table.py:546) cached_batch_get # unused function (dynamo_query/dynamo_table.py:552) batch_get_records # unused function (dynamo_query/dynamo_table.py:729) batch_delete_records # unused function (dynamo_query/dynamo_table.py:747) batch_upsert_records # unused function (dynamo_query/dynamo_table.py:762) cached_get_record # unused function (dynamo_query/dynamo_table.py:829) upsert_record # unused function (dynamo_query/dynamo_table.py:851) delete_record # unused function (dynamo_query/dynamo_table.py:920) clear_records # unused function (dynamo_query/dynamo_table.py:1131) NE # unused variable (dynamo_query/enums.py:58) IN # unused variable (dynamo_query/enums.py:59) EXISTS # unused variable (dynamo_query/enums.py:65) NOT_EXISTS # unused variable (dynamo_query/enums.py:66) CONTAINS # unused variable (dynamo_query/enums.py:68) default # unused function (dynamo_query/json_tools.py:40) pluralize # unused function (dynamo_query/utils.py:91) get_nested_item # unused function (dynamo_query/utils.py:112)
StarcoderdataPython
1628739
<filename>hyperts/utils/tstoolbox.py import numpy as np import pandas as pd from sklearn.model_selection import train_test_split as sklearn_tts from hypernets.tabular.toolbox import ToolBox from hyperts.utils import tscvsplit, ensemble from hyperts.utils import consts, metrics as metrics_ from hyperts.utils.holidays import get_holidays class TSToolBox(ToolBox): @staticmethod def DataFrame(data=None, index = None, columns = None, dtype = None, copy = False): """Two-dimensional, size-mutable, potentially heterogeneous tabular data. Parameters ---------- data : ndarray (structured or homogeneous), Iterable, dict, or DataFrame Dict can contain Series, arrays, constants, or list-like objects. .. versionchanged:: 0.23.0 If data is a dict, column order follows insertion-order for Python 3.6 and later. .. versionchanged:: 0.25.0 If data is a list of dicts, column order follows insertion-order for Python 3.6 and later. index : Index or array-like Index to use for resulting frame. Will default to RangeIndex if no indexing information part of input data and no index provided. columns : Index or array-like Column labels to use for resulting frame. Will default to RangeIndex (0, 1, 2, ..., n) if no column labels are provided. dtype : dtype, default None Data type to force. Only a single dtype is allowed. If None, infer. copy : bool, default False Copy data from inputs. Only affects DataFrame / 2d ndarray input. """ return pd.DataFrame(data=data, index=index, columns=columns, dtype=dtype, copy=copy) @staticmethod def join_df(df1: pd.DataFrame, df2: pd.DataFrame, on: None): """Join columns of another DataFrame. Parameters ---------- on : str, list of str, or array-like, optional Column or index level name(s) in the caller to join on the index in `other`, otherwise joins index-on-index. If multiple values given, the `other` DataFrame must have a MultiIndex. Can pass an array as the join key if it is not already contained in the calling DataFrame. Like an Excel VLOOKUP operation. Returns ------- DataFrame A dataframe containing columns from both the caller and `other`. """ return df1.join(df2.set_index(on), on=on) @staticmethod def to_datetime(df: pd.DataFrame, **kwargs): """Convert argument to datetime. """ return pd.to_datetime(df, **kwargs) @staticmethod def date_range(start=None, end=None, periods=None, freq=None, **kwargs): """Return a fixed frequency DatetimeIndex. Parameters ---------- start : str or datetime-like, optional Left bound for generating dates. end : str or datetime-like, optional Right bound for generating dates. periods : int, optional Number of periods to generate. freq : str or DateOffset, default 'D' Frequency strings can have multiples, e.g. '5H'. See :ref:`here <timeseries.offset_aliases>` for a list of frequency aliases. """ return pd.date_range(start=start, end=end, periods=periods, freq=freq, **kwargs) @staticmethod def datetime_format(df: pd.DataFrame, format='%Y-%m-%d %H:%M:%S'): """Convert datetime format. """ if format != None: return pd.to_datetime(df.astype('str')).dt.strftime(format) else: return pd.to_datetime(df.astype('str')) @staticmethod def select_1d_forward(arr, indices): """ Select by indices from the first axis(0) with forward. """ if hasattr(arr, 'iloc'): return arr.iloc[:indices] else: return arr[:indices] @staticmethod def select_1d_reverse(arr, indices): """ Select by indices from the first axis(0) with reverse. """ if hasattr(arr, 'iloc'): return arr.iloc[-indices:] else: return arr[-indices:] @staticmethod def columns_values(df: pd.DataFrame): """ Get column values. """ return df.columns.values @staticmethod def sort_values(df: pd.DataFrame, ts_name: str = consts.TIMESTAMP): """ Sort in time order. """ return df.sort_values(by=[ts_name]) @staticmethod def drop(df: pd.DataFrame, labels=None, index=None, columns=None, axis: int = 0, inplace: bool = False): """ Drop specified labels from rows or columns. """ return df.drop(labels=labels, axis=axis, index=index, columns=columns, inplace=inplace) @staticmethod def arange(*args): """ Return evenly spaced values within a given interval. """ return np.arange(*args) @staticmethod def infer_ts_freq(df: pd.DataFrame, ts_name: str = consts.TIMESTAMP): """ Infer the frequency of the time series. Parameters ---------- ts_name: 'str', time column name. """ return _infer_ts_freq(df, ts_name) @staticmethod def multi_period_loop_imputer(df: pd.DataFrame, freq: str, offsets: list = None, max_loops: int = 10): """Multiple period loop impute NAN. Parameters ---------- freq: str 'S' - second 'T' - minute 'H' - hour 'D' - day 'M' - month 'Y','A', A-DEC' - year offsets: list, offset lag. max_loops: 'int', maximum number of loop imputed. """ if not isinstance(freq, str): return df if freq is consts.DISCRETE_FORECAST: offsets = [-1, 1] elif offsets is None and freq in 'W' or 'W-' in freq or 'WOM-' in freq: offsets = [-1, -2, -3, -4, 1, 2, 3, 4] elif offsets is None and freq in ['M', 'MS', 'BM', 'CBM', 'CBMS']: offsets = [-1, -2, -3, -4, 1, 2, 3, 4] elif offsets is None and freq in ['SM', '15D', 'SMS']: offsets = [-1, -2, -4, -6, -8, 1, 2, 4, 6, 8] elif offsets is None and 'Q' in freq or 'Q-' in freq or 'BQ' in freq or 'BQ-' in freq or 'QS-' in freq or 'BQS-' in freq: offsets = [-1, -4, -8, -12, 1, 4, 8, 12] elif offsets is None and freq in ['A', 'Y'] or 'A-' in freq or 'BA-' in freq or 'AS-' in freq or 'BAS-' in freq: offsets = [-1, -2, -3, -4, 1, 2, 3, 4] elif offsets is None and 'S' in freq or 'T' in freq or 'min' in freq: offsets = [-60*4, -60*3, -60*2, -60*1, -1, 1, 60*1, 60*2, 60*3, 60*4] elif offsets is None and 'H' in freq: offsets = [-24*4, -24*3, -24*2, -24*1, -1, 1, 24*1, 24*2, 24*3, 24*4, -168*4, -168*3, -168*2, -168*1, 168*1, 168*2, 168*3, 168*4] elif offsets is None and 'BH' in freq or '8H' in freq: offsets = [-8*4, -8*3, -8*2, -8*1, -1, 1, 8*1, 8*2, 8*3, 8*4, -40*4, -40*3, -40*2, -40*1, 40*1, 40*2, 40*3, 40*4] elif offsets is None and 'D' in freq: offsets = [-1, -7, -7*2, 7*3, -7*4, 1, 7, 7*2, 7*3, 7*4] elif offsets is None and freq in ['C', 'B']: offsets = [-1, -5, -5*2, 5*3, -5*4, 1, 5, 5*2, 5*3, 5*4] elif offsets is None and 'L' in freq or 'U' in freq or 'N' in freq or 'ms' in freq: offsets = [-1, -50, -100, -200, -1000, 1, 50, 100, 200, 1000] elif offsets == None: offsets = [-1, 1] if freq != consts.DISCRETE_FORECAST: offsets = _expand_list(freq=freq, pre_list=offsets) values = df.values.copy() loop, missing_rate = 0, 1 while loop < max_loops and missing_rate > 0: values, missing_rate = _impute(values, offsets) loop += 1 values[np.where(np.isnan(values))] = np.nanmean(values) fill_df = pd.DataFrame(values, columns=df.columns) return fill_df @staticmethod def forward_period_imputer(df: pd.DataFrame, offset: int): """ Forward period imputer. Parameters ---------- offsets: 'int', offset lag. """ fill_df = df.fillna(df.rolling(window=offset, min_periods=1).agg(lambda x: x.iloc[0])) return fill_df @staticmethod def simple_numerical_imputer(df: pd.DataFrame, mode='mean'): """Fill NaN with mean, mode, 0.""" if mode == 'mean': df = df.fillna(df.mean().fillna(0).to_dict()) elif mode == 'mode': df = df.fillna(df.mode().fillna(0).to_dict()) else: df = df.fillna(0) return df @staticmethod def drop_duplicated_ts_rows(df: pd.DataFrame, ts_name: str = consts.TIMESTAMP, keep_data: str = 'last'): """Returns without duplicate time series, the last be keeped by default. Example: TimeStamp y 2021-03-01 3.4 2021-03-02 5.2 2021-03-03 9.3 2021-03-03 9.5 2021-03-04 6.7 2021-03-05 2.3 >> TimeStamp y 2021-03-01 3.4 2021-03-02 5.2 2021-03-03 9.5 2021-03-04 6.7 2021-03-05 2.3 """ assert isinstance(df, pd.DataFrame) drop_df = df.drop_duplicates(subset=[ts_name], keep=keep_data) drop_df.reset_index(drop=True, inplace=True) return drop_df @staticmethod def smooth_missed_ts_rows(df: pd.DataFrame, freq: str = None, ts_name: str = consts.TIMESTAMP): """Returns full time series. Example: TimeStamp y 2021-03-01 3.4 2021-03-02 5.2 2021-03-04 6.7 2021-03-05 2.3 >> TimeStamp y 2021-03-01 3.4 2021-03-02 5.2 2021-03-03 NaN 2021-03-04 6.7 2021-03-05 2.3 """ assert isinstance(df, pd.DataFrame) if freq == None: freq = _infer_ts_freq(df, ts_name) if df[ts_name].dtypes == object: df[ts_name] = pd.to_datetime(df[ts_name]) df = df.sort_values(by=ts_name) if freq is not None and freq is not consts.DISCRETE_FORECAST: start, end = df[ts_name].iloc[0], df[ts_name].iloc[-1] full_ts = pd.DataFrame(pd.date_range(start=start, end=end, freq=freq), columns=[ts_name]) if full_ts[ts_name].iloc[-1] == df[ts_name].iloc[-1]: df = full_ts.join(df.set_index(ts_name), on=ts_name) return df @staticmethod def clip_to_outliers(df, std_threshold: int = 3): """Replace outliers above threshold with that threshold. Parameters ---------- std_threshold: 'float', the number of standard deviations away from mean to count as outlier. """ if not isinstance(df, pd.DataFrame): df = pd.DataFrame(df) df_std = df.std(axis=0, skipna=True) df_mean = df.mean(axis=0, skipna=True) lower = df_mean - (df_std * std_threshold) upper = df_mean + (df_std * std_threshold) df_outlier = df.clip(lower=lower, upper=upper, axis=1) return df_outlier @staticmethod def nan_to_outliers(df, std_threshold: int = 3): """Replace outliers above threshold with that threshold. Parameters ---------- std_threshold: 'float', the number of standard deviations away from mean to count as outlier. """ if not isinstance(df, pd.DataFrame): df = pd.DataFrame(df) df_outlier = df.copy() df_std = df.std(axis=0, skipna=True) df_mean = df.mean(axis=0, skipna=True) outlier_indices = np.abs(df - df_mean) > df_std * std_threshold df_outlier = df_outlier.mask(outlier_indices, other=np.nan) return df_outlier @staticmethod def infer_window_size(max_size: int, freq: str): """Infer window of neural net. Parameters ---------- max_size: int, maximum time window allowed. freq: str or DateOffset. """ if freq in 'W' or 'W-' in freq or 'WOM-' in freq: window = list(filter(lambda x: x<=max_size, [7, 7*2, 7*3, 7*4, 52])) elif freq in ['SM', 'M', 'MS', 'SMS', 'BM', 'CBM', 'CBMS', '15D']: window = list(filter(lambda x: x <= max_size, [6, 12, 24, 36, 48])) elif 'Q' in freq or 'Q-' in freq or 'BQ' in freq or 'BQ-' in freq or 'QS-' in freq or 'BQS-' in freq: window = list(filter(lambda x: x <= max_size, [4, 8, 12, 16, 16*2, 16*3])) elif freq in ['A', 'Y'] or 'A-' in freq or 'BA-' in freq or 'AS-' in freq or 'BAS-' in freq: window = list(filter(lambda x: x<=max_size, [3, 6, 12, 24])) elif 'S' in freq or 'T' in freq or 'min' in freq: window = list(filter(lambda x: x<=max_size, [10, 30, 60, 60*2, 60*3])) elif 'H' in freq: window = list(filter(lambda x: x<=max_size, [24, 48, 48*2, 24*7])) elif 'BH' in freq or '8H' in freq: window = list(filter(lambda x: x<=max_size, [8, 16, 24, 24*2, 24*7])) elif 'D' in freq: window = list(filter(lambda x: x<=max_size, [7, 14, 21, 21*2, 21*3])) elif freq in ['C', 'B']: window = list(filter(lambda x: x<=max_size, [10, 15, 20, 20*2, 20*3])) elif 'L' in freq or 'U' in freq or 'N' in freq or 'ms' in freq: window = list(filter(lambda x: x <= max_size, [50, 100, 200, 500, 1000])) else: window = list(filter(lambda x: x <= max_size, [5, 7, 12, 24, 24*2, 24*3, 24*7])) final_win_list = _expand_list(freq=freq, pre_list=window) while 0 in final_win_list: final_win_list.remove(0) if len(final_win_list) != 0: return final_win_list else: raise RuntimeError('Unable to infer the sliding window size of dl, please specify dl_forecast_window.') @staticmethod def fft_infer_period(data): """Fourier inference period. References ---------- https://github.com/xuawai/AutoPeriod/blob/master/auto_period.ipynb """ try: if isinstance(data, pd.DataFrame): data = data.values.reshape(-1,) ft = np.fft.rfft(data) freqs = np.fft.rfftfreq(len(data), 1) mags = abs(ft) inflection = np.diff(np.sign(np.diff(mags))) peaks = (inflection < 0).nonzero()[0] + 1 peak = peaks[mags[peaks].argmax()] signal_freq = freqs[peak] period = int(1 / signal_freq) except: period = 2 return period @staticmethod def generate_ts_covariables(start_date, periods, freq='H'): """Generate covariates about time. Parameters ---------- start_date: 'str' or datetime-like. Left bound for generating dates. periods: 'int'. Number of periods to generate. freq: str or DateOffset, default 'H'. """ dstime = pd.date_range(start_date, periods=periods, freq=freq) fds = pd.DataFrame(dstime, columns={'TimeStamp'}) fds['Hour'] = fds['TimeStamp'].dt.hour fds['WeekDay'] = fds['TimeStamp'].dt.weekday period_dict = { 23: 0, 0: 0, 1: 0, 2: 1, 3: 1, 4: 1, 5: 2, 6: 2, 7: 2, 8: 3, 9: 3, 10: 3, 11: 3, 12: 4, 13: 4, 14: 5, 15: 5, 16: 5, 17: 5, 18: 6, 19: 7, 20: 7, 21: 7, 22: 7, } fds['TimeSegmnet'] = fds['Hour'].map(period_dict) fds['MonthStart'] = fds['TimeStamp'].apply(lambda x: x.is_month_start * 1) fds['MonthEnd'] = fds['TimeStamp'].apply(lambda x: x.is_month_end * 1) fds['SeasonStart'] = fds['TimeStamp'].apply(lambda x: x.is_quarter_start * 1) fds['SeasonEnd'] = fds['TimeStamp'].apply(lambda x: x.is_quarter_end * 1) fds['Weekend'] = fds['TimeStamp'].apply(lambda x: 1 if x.dayofweek in [5, 6] else 0) # public_holiday_list = get_holidays(year=int(start_date[:4])) # public_holiday_list = public_holiday_list['Date'].to_list() fds['Date'] = fds['TimeStamp'].apply(lambda x: x.strftime('%Y%m%d')) # fds['Holiday'] = fds['Date'].apply(lambda x: 1 if x in public_holiday_list else 0) fds.drop(['Date'], axis=1, inplace=True) return fds @staticmethod def df_mean_std(data: pd.DataFrame): """Get the mean and standard deviation of the data. """ mean = data.mean() std = data.std() return mean, std @staticmethod def infer_forecast_interval(forecast, prior_mu, prior_sigma, n: int = 5, confidence_level: float = 0.9): """A corruption of Bayes theorem. It will be sensitive to the transformations of the data. """ from scipy.stats import norm p_int = 1 - ((1 - confidence_level) / 2) adj = norm.ppf(p_int) upper_forecast, lower_forecast = pd.DataFrame(), pd.DataFrame() for index, row in forecast.iterrows(): data_mu = row post_mu = ((prior_mu / prior_sigma ** 2) + ((n * data_mu) / prior_sigma ** 2) ) / ((1 / prior_sigma ** 2) + (n / prior_sigma ** 2)) lower = pd.DataFrame(post_mu - adj * prior_sigma).transpose() lower = lower.where(lower <= data_mu, data_mu, axis=1) upper = pd.DataFrame(post_mu + adj * prior_sigma).transpose() upper = upper.where(upper >= data_mu, data_mu, axis=1) lower_forecast = pd.concat([lower_forecast, lower], axis=0) upper_forecast = pd.concat([upper_forecast, upper], axis=0) lower_forecast.index = forecast.index upper_forecast.index = forecast.index return upper_forecast, lower_forecast @staticmethod def from_3d_array_to_nested_df(data: np.ndarray, columns: str = None, cells_as_array: bool = False): """Convert Numpy ndarray with shape (nb_samples, series_length, nb_variables) into nested pandas DataFrame (with time series as numpy array or pandas Series in cells) Parameters ---------- data : np.ndarray 3-dimensional Numpy array to convert to nested pandas DataFrame format columns: list-like, default = None Optional list of names to use for naming nested DataFrame's columns cells_as_array : bool, default = False If True, then nested cells contain Numpy array If False, then nested cells contain pandas Series Returns ---------- df : pd.DataFrame References ---------- sktime_data_processing: https://github.com/Riyabelle25/sktime/blob/main/sktime/utils/data_processing.py """ df = pd.DataFrame() nb_samples, series_length, nb_variables = data.shape cell = np.array if cells_as_array else pd.Series if columns is None: columns = [f'Var_{i}' for i in range(nb_variables)] else: if len(columns) != nb_variables: raise ValueError(f'The number of column names supplied [{len(columns)}] \ does not match the number of data variables [{nb_variables}].') for i, columns_name in enumerate(columns): df[columns_name] = [cell(data[j, :, i]) for j in range(nb_samples)] return df @staticmethod def from_nested_df_to_3d_array(data: pd.DataFrame): """Convert nested pandas DataFrame (with time series as numpy array or pandas Series in cells) into Numpy ndarray with shape (nb_samples, series_length, nb_variables). Parameters ---------- data : pd.DataFrame Nested pandas DataFrame Returns ------- data_3d : np.arrray 3-dimensional NumPy array References ----------from_nested_to_3d_numpy sktime_data_processing: https://github.com/Riyabelle25/sktime/blob/main/sktime/utils/data_processing.py """ nested_col_mask = [*data.applymap(lambda cell: isinstance(cell, (np.ndarray, pd.Series))).any().values] if nested_col_mask.count(True) == len(nested_col_mask): res = np.stack(data.applymap(lambda cell: cell.to_numpy() if isinstance(cell, pd.Series) else cell) .apply(lambda row: np.stack(row), axis=1) .to_numpy()) else: raise ValueError return res.transpose(0, 2, 1) @staticmethod def is_nested_dataframe(data: pd.DataFrame): """Determines whether data is a nested Dataframe. Returns ------- bool : True or False. """ is_dataframe = isinstance(data, pd.DataFrame) is_nested = isinstance(data.iloc[0, 0], (np.ndarray, pd.Series)) return is_dataframe and is_nested @staticmethod def random_train_test_split(*arrays, test_size=None, train_size=None, random_state=None, shuffle=True, stratify=None): """Split arrays or matrices into random train and test subsets. This is a wrapper of scikit-learn's ``train_test_split`` that has shuffle. """ results = sklearn_tts(*arrays, test_size=test_size, train_size=train_size, random_state=random_state, shuffle=shuffle, stratify=stratify) return results @staticmethod def temporal_train_test_split(*arrays, test_size=None, train_size=None, test_horizon=None): """Split arrays or matrices into sequential train and test subsets.This is a wrapper of scikit-learn's ``train_test_split`` that does not shuffle. Parameters ---------- *arrays : sequence of indexables with same length / shape[0] Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas dataframes. test_size : float, int or None, optional (default=None) If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. If int, represents the absolute number of test samples. If None, the value is set to the complement of the train size. If ``train_size`` is also None, it will be set to 0.25. train_size : float, int, or None, (default=None) If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split. If int, represents the absolute number of train samples. If None, the value is automatically set to the complement of the test size. test_horizon: int or None, (default=None) If int, represents the forecast horizon length. Returns ------- splitting : list, length=2 * len(arrays) List containing train-test split of inputs. """ test_size = test_horizon if test_horizon != None else test_size if test_horizon != None and test_horizon > arrays[0].shape[0]: raise ValueError(f'{test_horizon} is greater than data shape {arrays[0].shape[0]}.') results = sklearn_tts( *arrays, test_size=test_size, train_size=train_size, shuffle=False, stratify=None) return [pd.DataFrame(item) if isinstance(item, pd.Series) else item for item in results] @staticmethod def list_diff(p: list, q: list): """Gets the difference set of two lists. Parameters ---------- p: list. q: list. Returns A list. ------- Example p = [1, 2, 3, 4, 5], q = [2, 4] >> list_diff(p, q) >> [1, 3, 5] p = [1, 2, 3, 4, 5], q = [] >> list_diff(p, q) >> [1, 2, 3, 4, 5] """ if q is not None and len(q) > 0: # return list(set(p).difference(set(q))) return list(filter(lambda x: x not in q, p)) else: return p @staticmethod def infer_pos_label(y_true, task, pos_label=None): y_true = np.array(y_true) if not isinstance(y_true, np.ndarray) else y_true if task in consts.TASK_LIST_CLASSIFICATION and pos_label is None: if 1 in y_true: pos_label = 1 elif 'yes' in y_true: pos_label = 'yes' elif 'true' in y_true: pos_label = 'true' else: pos_label = y_true[0] elif task in consts.TASK_LIST_CLASSIFICATION and pos_label is not None: if pos_label in y_true: pos_label = pos_label else: pos_label = y_true[0] else: pos_label = None return pos_label metrics = metrics_.Metrics _preqfold_cls = tscvsplit.PrequentialSplit _greedy_ensemble_cls = ensemble.TSGreedyEnsemble @classmethod def preqfold(cls, strategy='preq-bls', base_size=None, n_splits=5, stride=1, *, max_train_size=None, test_size=None, gap_size=0): return cls._preqfold_cls(strategy=strategy, base_size=base_size, n_splits=n_splits, stride=stride, max_train_size=max_train_size, test_size=test_size, gap_size=gap_size) @classmethod def greedy_ensemble(cls, task, estimators, need_fit=False, n_folds=5, method='soft', random_state=9527, target_dims=1, scoring='neg_log_loss', ensemble_size=0): return cls._greedy_ensemble_cls(task, estimators, need_fit=need_fit, n_folds=n_folds, method=method, target_dims=target_dims, random_state=random_state, scoring=scoring, ensemble_size=ensemble_size) def _infer_ts_freq(df: pd.DataFrame, ts_name: str = consts.TIMESTAMP): """ Infer the frequency of the time series. Parameters ---------- ts_name: 'str', time column name. """ df[ts_name] = pd.to_datetime(df[ts_name]) df = df.sort_values([ts_name]) dateindex = pd.DatetimeIndex(df[ts_name]) freq = pd.infer_freq(dateindex) if freq is not None: return freq else: for i in range(len(df)): freq = pd.infer_freq(dateindex[i:i + 3]) if freq != None: return freq return None def _impute(values, offsets): """ Index slide imputation. Parameters ---------- offsets: list, offset lag. """ indices0, indices1 = np.where(np.isnan(values)) if len(indices0) > 0 and len(indices1) > 0: padding = [] for offset in offsets: offset_indices0 = indices0 + offset start_bound_limit = np.where(indices0 + offset < 0) end_bound_limit = np.where(indices0 + offset > len(values) - 1) offset_indices0[start_bound_limit] = indices0[start_bound_limit] offset_indices0[end_bound_limit] = indices0[end_bound_limit] padding.append(values[(offset_indices0, indices1)]) values[(indices0, indices1)] = np.nanmean(padding, axis=0) missing_rate = np.sum(np.isnan(values)) / values.size else: missing_rate = 0. return values, missing_rate def _expand_list(freq, pre_list): try: import re s = int(re.findall(r'\d+', freq)[0]) return list(map(lambda x: x // s + 1, pre_list)) except: return pre_list __all__ = [ TSToolBox.__name__, ]
StarcoderdataPython
1655707
<filename>multiexplorer/wallet/migrations/0005_delete_cachedtransaction.py<gh_stars>10-100 # -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-04-25 01:12 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wallet', '0004_cachedtransaction'), ] operations = [ migrations.DeleteModel( name='CachedTransaction', ), ]
StarcoderdataPython
81707
<gh_stars>10-100 # -*- coding: utf-8 -*- from datetime import timedelta from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from gui.utils import parse_date_range, country_sites from gui.forms import TrendsPanelForm, SUM, AVERAGE from core.decorators import log_activity from core.general import catch_error, get_status, permission_required from core.models import SITE_MODEL, ITEM_MODEL, user_country_access from core.analytics import items_sum, items_average @catch_error @log_activity @login_required @permission_required def trends_listings(request): context = get_status(request) context['app'] = 'items_panel' context['country_sites'] = country_sites(user_country_access(request.user)) context['form'] = TrendsPanelForm( user=request.user, initial=request.session.get('form_session')) return render_to_response('trends_panel.html', context, context_instance=RequestContext(request)) @catch_error @login_required @permission_required def trends_div(request): context = get_status(request) form = TrendsPanelForm(user=request.user, data=request.GET) if not form.is_valid(): return render_to_response('main/form_error.html', context) start_date, end_date = parse_date_range(form) sites = [SITE_MODEL.objects.get(id=site_id) for site_id in [int(site_id) for site_id in form.cleaned_data['players']]] fields = form.cleaned_data['fields'] metric = form.cleaned_data['metric'] def get_items(start_date, end_date): return ITEM_MODEL.objects.filter(site__in=sites, date_time__gte=start_date, date_time__lte=end_date) def analyze_items(items, field): if metric == SUM: return items_sum(items, field) elif metric == AVERAGE: return items_average(items, field) evolution = {} for field in fields: # Find how the field has evolved over time # Step over every day between the start and end date delta = (end_date - start_date) metric_evolution = [] for i in range(delta.days + 1): start_day = (start_date + timedelta(days=i)) end_day = start_day + timedelta(days=1) items = get_items(start_day, end_day) analysis = analyze_items(items, field) if analysis: metric_evolution += [(start_day.strftime('%s'), analysis)] evolution[field] = metric_evolution context['evolution'] = evolution return render_to_response('trends_div.html', context, context_instance=RequestContext(request))
StarcoderdataPython
20397
import torch import numpy as np PAD_TOKEN_INDEX = 0 def pad_masking(x, target_len): # x: (batch_size, seq_len) batch_size, seq_len = x.size() padded_positions = x == PAD_TOKEN_INDEX # (batch_size, seq_len) pad_mask = padded_positions.unsqueeze(1).expand(batch_size, target_len, seq_len) return pad_mask def subsequent_masking(x): # x: (batch_size, seq_len - 1) batch_size, seq_len = x.size() subsequent_mask = np.triu(np.ones(shape=(seq_len, seq_len)), k=1).astype('uint8') subsequent_mask = torch.tensor(subsequent_mask).to(x.device) subsequent_mask = subsequent_mask.unsqueeze(0).expand(batch_size, seq_len, seq_len) return subsequent_mask
StarcoderdataPython
55179
from django.apps import AppConfig class RealmConfig(AppConfig): name = 'etools_permissions'
StarcoderdataPython
1770429
<filename>arxiv_latex_cleaner.py # coding=utf-8 # Copyright 2018 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Cleans the LaTeX code of your paper to submit to arXiv.""" import argparse import collections import json import os import re import shutil from PIL import Image # Fix for Windows: Even if '\' (os.sep) is the standard way of making paths on # Windows, it interferes with regular expressions. We just change os.sep to '/' # and os.path.join to a version using '/' as Windows will handle it the right # way. if os.name == 'nt': global old_os_path_join def new_os_join(path, *args): res = old_os_path_join(path, *args) res = res.replace('\\','/') return res old_os_path_join = os.path.join os.sep = '/' os.path.join = new_os_join def _create_dir_erase_if_exists(path): if os.path.exists(path): shutil.rmtree(path) os.makedirs(path) def _create_dir_if_not_exists(path): if not os.path.exists(path): os.makedirs(path) def _keep_pattern(haystack, patterns_to_keep): """Keeps the strings that match 'patterns_to_keep'.""" out = [] for item in haystack: if any((re.findall(rem, item) for rem in patterns_to_keep)): out.append(item) return out def _remove_pattern(haystack, patterns_to_remove): """Removes the strings that match 'patterns_to_remove'.""" return [ item for item in haystack if item not in _keep_pattern(haystack, patterns_to_remove) ] def _list_all_files(in_folder, ignore_dirs=None): if ignore_dirs is None: ignore_dirs = [] to_consider = [ os.path.join(os.path.relpath(path, in_folder), name) for path, _, files in os.walk(in_folder) for name in files ] return _remove_pattern(to_consider, ignore_dirs) def _copy_file(filename, params): _create_dir_if_not_exists( os.path.join(params['output_folder'], os.path.dirname(filename))) shutil.copy( os.path.join(params['input_folder'], filename), os.path.join(params['output_folder'], filename)) def _remove_comments(text): """Removes the comments from the string 'text'.""" if 'auto-ignore' in text: return text if text.lstrip(' ').startswith('%'): return '' match = re.search(r'(?<!\\)%', text) if match: return text[:match.end()] + '\n' else: return text def _read_file_content(filename): with open(filename, 'r') as fp: return fp.readlines() def _write_file_content(content, filename): with open(filename, 'w') as fp: return fp.write(content) def _read_remove_comments_and_write_file(filename, parameters): """Reads a file, erases all LaTeX comments in the content, and writes it.""" _create_dir_if_not_exists( os.path.join(parameters['output_folder'], os.path.dirname(filename))) content = _read_file_content( os.path.join(parameters['input_folder'], filename)) content_out = [_remove_comments(line) for line in content] _write_file_content(''.join(content_out), os.path.join(parameters['output_folder'], filename)) def _resize_and_copy_figure(filename, origin_folder, destination_folder, dest_size=600): """Copies a file while erasing all the LaTeX comments in its content.""" _create_dir_if_not_exists( os.path.join(destination_folder, os.path.dirname(filename))) if os.path.splitext(filename)[1].lower() in ['.jpg', '.jpeg', '.png']: im = Image.open(os.path.join(origin_folder, filename)) if max(im.size) > dest_size: im = im.resize( tuple([int(x * float(dest_size) / max(im.size)) for x in im.size]), Image.ANTIALIAS) if os.path.splitext(filename)[1].lower() in ['.jpg', '.jpeg']: im.save(os.path.join(destination_folder, filename), 'JPEG', quality=90) elif os.path.splitext(filename)[1].lower() in ['.png']: im.save(os.path.join(destination_folder, filename), 'PNG') else: shutil.copy( os.path.join(origin_folder, filename), os.path.join(destination_folder, filename)) def _resize_and_copy_figures(parameters, splits): out_size = collections.defaultdict(lambda: parameters['im_size']) out_size.update(parameters['images_whitelist']) for image_file in _keep_only_referenced( splits['figures'], [os.path.join(parameters['output_folder'], fn) for fn in splits['tex']]): _resize_and_copy_figure( image_file, parameters['input_folder'], parameters['output_folder'], dest_size=out_size[image_file]) def _keep_only_referenced(filenames, container_files): """Returns the filenames referenced from the content of container_files.""" referenced = set() for container in container_files: with open(container, 'r') as fp: data = fp.read() for fn in filenames: if os.path.splitext(fn)[0] in data: referenced.add(fn) return referenced def _split_all_files(parameters): """Splits the files into types or location to know what to do with them.""" file_splits = { 'all': _list_all_files( parameters['input_folder'], ignore_dirs=['.git' + os.sep]), 'in_root': [ f for f in os.listdir(parameters['input_folder']) if os.path.isfile(os.path.join(parameters['input_folder'], f)) ] } file_splits['not_in_root'] = [ f for f in file_splits['all'] if f not in file_splits['in_root'] ] file_splits['to_copy_in_root'] = _remove_pattern( file_splits['in_root'], parameters['to_delete_in_root'] + parameters['figures_to_copy_if_referenced']) file_splits['to_copy_not_in_root'] = _remove_pattern( file_splits['not_in_root'], parameters['to_delete_in_root'] + parameters['figures_to_copy_if_referenced']) file_splits['figures'] = _keep_pattern( file_splits['all'], parameters['figures_to_copy_if_referenced']) file_splits['tex'] = _keep_pattern( file_splits['to_copy_in_root'] + file_splits['to_copy_not_in_root'], ['.tex$']) file_splits['non_tex'] = _remove_pattern( file_splits['to_copy_in_root'] + file_splits['to_copy_not_in_root'], ['.tex$']) return file_splits def _create_out_folder(input_folder): """Creates the output folder, erasing it if existed.""" out_folder = input_folder.rstrip(os.sep) + '_arXiv' _create_dir_erase_if_exists(out_folder) return out_folder def _handle_arguments(): """Defines and returns the arguments.""" parser = argparse.ArgumentParser( description=('Clean the LaTeX code of your paper to submit to arXiv. ' 'Check the README for more information on the use.')) parser.add_argument( 'input_folder', type=str, help='Input folder containing the LaTeX code.') parser.add_argument( '--im_size', default=500, type=int, help=('Size of the output images (in pixels, longest side). Fine tune ' 'this to get as close to 10MB as possible.')) parser.add_argument( '--images_whitelist', default={}, type=json.loads, help=('Images that won\'t be resized to the default resolution, but the ' 'one provided here in a dictionary as follows ' '\'{"path/to/im.jpg": 1000}\'')) return vars(parser.parse_args()) def _run_arxiv_cleaner(parameters): """Core of the code, runs the actual arXiv cleaner.""" parameters.update({ 'to_delete_in_root': [ '.aux$', '.sh$', '.bib$', '.blg$', '.log$', '.out$', '.ps$', '.dvi$', '.synctex.gz$', '~$', '.backup$', '.gitignore$', '.DS_Store$', '.svg$' ], 'to_delete_not_in_root': ['.DS_Store$', '.gitignore$', '.svg$'], 'figures_to_copy_if_referenced': ['.png$', '.jpg$', '.jpeg$', '.pdf$'] }) splits = _split_all_files(parameters) parameters['output_folder'] = _create_out_folder(parameters['input_folder']) for non_tex_file in splits['non_tex']: _copy_file(non_tex_file, parameters) for tex_file in splits['tex']: _read_remove_comments_and_write_file(tex_file, parameters) _resize_and_copy_figures(parameters, splits) def main(): command_line_parameters = _handle_arguments() _run_arxiv_cleaner(command_line_parameters) if __name__ == '__main__': main()
StarcoderdataPython
1687307
# This file is part of rinohtype, the Python document preparation system. # # Copyright (c) <NAME>. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. import os from os import path import docutils from docutils.nodes import GenericNodeVisitor, SkipNode from sphinx import addnodes from sphinx.builders import Builder from sphinx.locale import _ from sphinx.util.console import bold, darkgreen, brown from sphinx.util.nodes import inline_all_toctrees from sphinx.util.osutil import ensuredir, os_path, SEP from sphinx.util import logging from rinoh.flowable import StaticGroupedFlowables from rinoh.highlight import pygments_style_to_stylesheet from rinoh.index import IndexSection, IndexLabel, IndexEntry from rinoh.language import Language from rinoh.paper import A4, LETTER from rinoh.style import StyleSheet from rinoh.template import (DocumentTemplate, TemplateConfiguration, TemplateConfigurationFile) from rinoh.text import SingleStyledText from rinoh import __version__ as rinoh_version from rinoh.frontend.rst import ReStructuredTextReader from . import nodes logger = logging.getLogger(__name__) class RinohTreePreprocessor(GenericNodeVisitor): """Preprocess the docutils document tree to prepare it for mapping to the rinohtype document tree""" def __init__(self, document, builder): super().__init__(document) self.default_highlight_language = builder.config.highlight_language self.highlight_stack = [self.default_highlight_language] self.current_docname = None def default_visit(self, node): try: if 'refid' in node: node['refid'] = fully_qualified_id(self.current_docname, node['refid']) elif 'refuri' in node and node.get('internal', False): node['refid'] = node.attributes.pop('refuri') ids, module_ids = [], [] for id in node['ids']: if id.startswith('module-'): module_ids.append(id) else: ids.append(fully_qualified_id(self.current_docname, id)) node['ids'] = ids + module_ids except (TypeError, KeyError): pass def default_departure(self, node): pass def visit_start_of_file(self, node): self.current_docname = node['docname'] self.highlight_stack.append(self.default_highlight_language) def depart_start_of_file(self, node): self.highlight_stack.pop() def visit_highlightlang(self, node): self.highlight_stack[-1] = node.get('lang') raise SkipNode def visit_rubric(self, node): if node.children[0].astext() in ('Footnotes', _('Footnotes')): node.tagname = 'footnotes-rubric' # mapped to a DummyFlowable raise SkipNode def visit_literal_block(self, node): self.default_visit(node) if 'language' not in node.attributes: node.attributes['language'] = self.highlight_stack[-1] class RinohBuilder(Builder): """Renders to a PDF using rinohtype.""" name = 'rinoh' format = 'pdf' supported_image_types = ['application/pdf', 'image/png', 'image/jpeg'] def get_outdated_docs(self): return 'all documents' def get_target_uri(self, docname, typ=None): return '%' + docname def get_relative_uri(self, from_, to, typ=None): # ignore source return self.get_target_uri(to, typ) def preprocess_tree(self, tree): """Transform internal refuri targets in reference nodes to refids and transform footnote rubrics so that they do not end up in the output""" visitor = RinohTreePreprocessor(tree, self) tree.walkabout(visitor) def prepare_writing(self, docnames): # toc = self.env.get_toctree_for(self.config.master_doc, self, False) pass def assemble_doctree(self, indexfile, toctree_only): docnames = set([indexfile]) logger.info(darkgreen(indexfile) + " ", nonl=1) tree = self.env.get_doctree(indexfile) tree['docname'] = indexfile new_tree = docutils.utils.new_document(tree['source']) if toctree_only: # extract toctree nodes from the tree and put them in a # fresh document for node in tree.traverse(addnodes.toctree): new_tree += node else: for node in tree.children: if node.tagname == 'section': for child in node.children: if child.tagname != 'title': new_tree += child else: new_tree += node largetree = inline_all_toctrees(self, docnames, indexfile, new_tree, darkgreen, [indexfile]) largetree['docname'] = indexfile logger.info("resolving references...") self.env.resolve_references(largetree, indexfile, self) # resolve :ref:s to distant tex files -- we can't add a cross-reference, # but append the document name for pendingnode in largetree.traverse(addnodes.pending_xref): docname = pendingnode['refdocname'] sectname = pendingnode['refsectname'] newnodes = [nodes.emphasis(sectname, sectname)] for subdir, title in self.titles: if docname.startswith(subdir): newnodes.append(nodes.Text(_(' (in '), _(' (in '))) newnodes.append(nodes.emphasis(title, title)) newnodes.append(nodes.Text(')', ')')) break else: pass pendingnode.replace_self(newnodes) return largetree, docnames def generate_indices(self, docnames): def index_flowables(content): for section, entries in content: yield IndexLabel(str(section)) for (name, subtype, docname, anchor, _, _, _) in entries: target_ids = ([anchor] if anchor else None) entry_name = SingleStyledText(name, style='domain') yield IndexEntry(entry_name, level=2 if subtype == 2 else 1, target_ids=target_ids) indices_config = self.config.rinoh_domain_indices if indices_config: for domain in self.env.domains.values(): for indexcls in domain.indices: indexname = '%s-%s' % (domain.name, indexcls.name) if isinstance(indices_config, list): if indexname not in indices_config: continue content, collapsed = indexcls(domain).generate(docnames) if not content: continue index_section_label = str(indexcls.localname) yield IndexSection(SingleStyledText(index_section_label), index_flowables(content)) def init_document_data(self): document_data = [] preliminary_document_data = [list(entry) for entry in self.config.rinoh_documents] if not preliminary_document_data: logger.warning('no "rinoh_documents" config value found; ' 'no documents will be written') return # assign subdirs to titles self.titles = [] for entry in preliminary_document_data: docname = entry[0] if docname not in self.env.all_docs: logger.warning('"rinoh_documents" config value references unknown ' 'document %s' % docname) continue document_data.append(entry) if docname.endswith(SEP + 'index'): docname = docname[:-5] self.titles.append((docname, entry[2])) return document_data def write(self, *ignored): document_data = self.init_document_data() for entry in document_data: docname, targetname, title, author = entry[:4] toctree_only = entry[4] if len(entry) > 4 else False logger.info("processing " + targetname + "... ", nonl=1) doctree, docnames = self.assemble_doctree(docname, toctree_only) self.preprocess_tree(doctree) self.post_process_images(doctree) logger.info("rendering... ") doctree.settings.author = author doctree.settings.title = title doctree.settings.docname = docname self.write_doc(docname, doctree, docnames, targetname) logger.info("done") def write_doc(self, docname, doctree, docnames, targetname): config = self.config parser = ReStructuredTextReader() rinoh_tree = parser.from_doctree(doctree['source'], doctree) template_cfg = template_from_config(config, self.confdir, logger.warning) rinoh_document = template_cfg.document(rinoh_tree) extra_indices = StaticGroupedFlowables(self.generate_indices(docnames)) rinoh_document.insert('back_matter', extra_indices, 0) rinoh_logo = config.rinoh_logo if rinoh_logo: rinoh_document.metadata['logo'] = rinoh_logo rinoh_document.metadata['title'] = doctree.settings.title rinoh_document.metadata['subtitle'] = ('Release {}' .format(config.release)) rinoh_document.metadata['author'] = doctree.settings.author outfilename = path.join(self.outdir, os_path(targetname)) ensuredir(path.dirname(outfilename)) rinoh_document.render(outfilename) def template_from_config(config, confdir, warn): template_cfg = {} if isinstance(config.rinoh_template, str): tmpl_path = path.join(confdir, config.rinoh_template) if path.isfile(tmpl_path): template_cfg['base'] = TemplateConfigurationFile(tmpl_path) template_cls = template_cfg['base'].template else: template_cls = DocumentTemplate.from_string(config.rinoh_template) elif isinstance(config.rinoh_template, TemplateConfiguration): template_cfg['base'] = config.rinoh_template template_cls = config.rinoh_template.template else: template_cls = config.rinoh_template if isinstance(config.rinoh_stylesheet, str): stylesheet_path = path.join(confdir, config.rinoh_stylesheet) stylesheet = StyleSheet.from_string(stylesheet_path if path.isfile(stylesheet_path) else config.rinoh_stylesheet) else: stylesheet = config.rinoh_stylesheet if config.pygments_style is not None: if stylesheet is not None: base = stylesheet elif 'base' in template_cfg: base = template_cfg['base']['stylesheet'] else: base = template_cls.stylesheet.default_value stylesheet = pygments_style_to_stylesheet(config.pygments_style, base) if stylesheet is not None: template_cfg['stylesheet'] = stylesheet language = config.language if language: try: template_cfg['language'] = Language.from_string(language) except KeyError: warn('The language "{}" is not supported by rinohtype.') variables = {} if config.rinoh_paper_size: variables['paper_size'] = config.rinoh_paper_size sphinx_config = template_cls.Configuration('Sphinx conf.py options', **template_cfg) sphinx_config.variables.update(variables) return sphinx_config def fully_qualified_id(docname, id): return id if id.startswith('%') else '%' + docname + '#' + id def info_config_conversion(config_option, latex_option=None): latex_option = latex_option or config_option print("'rinoh_{0}' config variable not set, automatically converting " "from 'latex_{0}'".format(latex_option)) def default_documents(config): def latex_document_to_rinoh_document(entry): startdocname, targetname, title, author, documentclass = entry[:5] toctree_only = entry[5] if len(entry) > 5 else False targetname_root, _ = os.path.splitext(targetname) return startdocname, targetname_root, title, author, toctree_only info_config_conversion('documents') return [latex_document_to_rinoh_document(entry) for entry in config.latex_documents] def default_paper_size(config): info_config_conversion('elements/papersize') latex_paper_size = config.latex_elements.get('papersize', 'letterpaper') return dict(a4paper=A4, letterpaper=LETTER)[latex_paper_size] def default_logo(config): info_config_conversion('logo') return config.latex_logo def default_domain_indices(config): info_config_conversion('domain_indices') return config.latex_domain_indices def setup(app): app.add_builder(RinohBuilder) app.add_config_value('rinoh_documents', default_documents, 'env') app.add_config_value('rinoh_stylesheet', None, 'html') app.add_config_value('rinoh_paper_size', default_paper_size, 'html') app.add_config_value('rinoh_logo', default_logo, 'html') app.add_config_value('rinoh_domain_indices', default_domain_indices, 'html') app.add_config_value('rinoh_template', 'book', 'html') return dict(version=rinoh_version)
StarcoderdataPython
4823462
<reponame>Puriney/scanpy try: from bbknn import bbknn except ImportError: def bbknn(*args, **kwargs): raise ImportError('Please install BBKNN: `pip3 install bbknn`')
StarcoderdataPython
1749910
import numpy as np def merge_data(data, metric): merged_outcomes = {} for key in data.keys(): results = data[key] if metric == 1: merged_outcomes[key] = list(map(np.mean, zip(*results))) if metric == 2: merged_outcomes[key] = list(map(min, zip(*results))) if metric == 3: merged_outcomes[key] = list(map(max, zip(*results))) return merged_outcomes
StarcoderdataPython
3290797
<reponame>lowrybg/PythonAdvanced def concatenate(*args): return ''.join(args) print(concatenate("Soft", "Uni", "Is", "Great", "!"))
StarcoderdataPython
98287
#!/usr/bin/env python """ MiP Sound tester. To Use: mip_test_sound.py -i hci0 -b D0:39:72:C4:7A:01 -s <n> <n> 1 - 106 1 = beep 2 = burp 3 = ewwp - ah 4 = la la la la (lower) 5 = small raspberry? 6 = rerrr 7 = punching sound 8 = punching sound 9 = harder punching sound 10 = lep 11 = lep 12 = lep 13 = lep 14 = ahhh! (interested) 15 = arhhh! (disapointed) 16 = oh yeah 17 = meh (derogatory?) 18 = beh 19 = see yah? 20 = bad a bad a bad a (MiP talking to himself?) 21 = bad a bad a bad a (MiP talking to himself?) 22 = stop? 23 = goodnight? 24 = bang of drum 25 = bang of drum (different) 26 = Hi Yah! 27 = some word.. gay? 28 = Ha Ha Ha lep 29 = lets go! 30 = bah bah bah (low) 31 = her (low) 32 = eigh (something horrible) 33 = narrrh 34 = lets go it? 35 = hellllooo (sexy) 36 = bah? (questioning) 37 = ohaye 38 = huh? 39 = dur dur dur dur dooo (humming to himself) 40 = la la la la laaa (humming to himself) 41 = hah ha hah, hah hah hahaha... 42 = heaaahhh 43 = harp sound plus he says something 44 = lets MiP? 45 = talks to himself 46 = 'kay (as when in training mode) 47 = Music (part one) 48 = Music (part two) 49 = Out of power sound 50 = Happy! 51 = yeuh (collision warning sound in roam mode) 52 = Yah ha ha ha 53 = Music (MiP says music not plays it) 54 = oh ah (collision warning sound in roam mode) 55 = Oh Oh (something bad) (part of power down noise?) 56 = Oh yeah! 57 = high pitch 'Happy!' 58 = howell (sound when MiP sees a wall in cage mode?) 59 = howell (higher pitch) 60 = play 61 = lets fish? 62 = fire? 63 = click click 64 = rar 65 = la la la la la (derogatory sound) 66 = ah-choo (sneeze?) 67 = snoring 68 = feck? 69 = whish (sound made when recognising a gesture) 70 = whish (sound made when recognising a gesture) 71 = X? 72 = lets trick 73 = duh duh duh duh duh duh (cage escape sound) 74 = waaaah 75 = wakey wakey? 76 = yay 0xfd = 77 = roam whistle 78 = waaaaahhhh 79 = wuuuy (higher pitch) 80 = yeuh 81 = Yeah! 82 = You (low pitch) 83 = happy/snappy? (low pitch) 84 = oooee (low pitch) 85 = aaeeeh (higher pitch) 86 = ribit 87 = Boring 88 = errr (low pich) 89 = lets go 90 = yipppee! (higher pitch) 91 = ho ho ho ho ho 92 = crafteee? 93 = crafty 94 = ha ha 95 = this is mip (low pitch) 96 = sigharhhh 97 = MiP crying (lost the cage game?) 98 = nuh (low pitch) 99 = snifty? 100 = Aaahhhh (large sigh) 101 = funny little beeping sound 102 = drum 103 = laser beam 104 = swanny whistle sound 105 = No sound - stop sound playing 106 = mip """ import mippy import argparse if __name__ == '__main__': parser = argparse.ArgumentParser(description='Test MiP Sounds.') mippy.add_arguments(parser) parser.add_argument( '-s', '--sound', default=0x4d, help='Specify sound number (1-106). 105 is no sound', type=int) args = parser.parse_args() gt = mippy.GattTool(args.adaptor, args.device) mip = mippy.Mip(gt) # roam whistle mip.playSound(args.sound)
StarcoderdataPython
3375382
# Importing boto3, pickle import boto3 import _pickle as pickle # Creating the connection ec2Client = boto3.client('ec2', region_name='ap-south-1' ) ec2 = boto3.resource('ec2', region_name='ap-south-1', ) # Checking what instances are running and specs def printInstances(): instances = ec2.instances.filter( Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]) for instance in instances: inst_names = [tag['Value'] for tag in instance.tags if tag['Key'] == 'Name'] print(inst_names, instance.id, instance.cpu_options, instance.instance_type, instance.architecture, instance.image_id, instance.key_name) # Print Instance name, ID, CPU Spec, CPU Architecture, AMI ID, ssh-key name # Generating ssh-key pairs def sshKeyGen(): outfile = open('id_rsa_mainak.pem', 'w') key_pair = ec2.create_key_pair(KeyName='id_rsa_mainak') KeyPairOut = key_pair.key_material print(str(KeyPairOut)) outfile.write(KeyPairOut) outfile.close() # Launch an instance def launchInstance(): print("Input 1 for Intel instance \n" "Input 2 for ARM instance") num_input = int(input()) if num_input == 1: ami_id = 'ami-0c1a7f89451184c8b' instance_type = 't2.medium' vm_name = 'intel-vm' elif num_input == 2: ami_id = 'ami-0d18acc6e813fd2e0' instance_type = 't4g.medium' vm_name = 'arm-vm' else: exit() instance_list1 = ec2.create_instances(ImageId=ami_id, MinCount=1, MaxCount=1, InstanceType=instance_type, KeyName='id_rsa_mainak', TagSpecifications=[ { 'ResourceType': 'instance', 'Tags': [{ 'Key': 'Name', 'Value': vm_name }] } ], BlockDeviceMappings=[ { 'DeviceName': '/dev/sda1', 'Ebs': { 'DeleteOnTermination': True, 'VolumeSize': 50, 'VolumeType': 'standard' }, }, ] ) instance_list1[0].wait_until_running() # Waiting to launch before assigning the elastic IP address eip = ec2Client.allocate_address(Domain='vpc') print(eip) with open('allocation.txt', 'wb') as f: pickle.dump(eip, f) with open('instance_id.txt', 'wb') as f: pickle.dump(instance_list1[0].id, f) ec2Client.associate_address( InstanceId=instance_list1[0].id, AllocationId=eip["AllocationId"]) # Release Elastic IP def releaseEip(): with open("allocation.txt", 'rb') as f: eip = pickle.load(f) print(eip) ec2Client.release_address(AllocationId=eip['AllocationId']) print('Address released') # Terminate Instances def termInstance(): with open("instance_id.txt", 'rb') as f: i_id = pickle.load(f) ec2Client.terminate_instances(InstanceIds=[i_id]) print("Instance Terminated") # Main function if __name__ == "__main__": print("Input 1 for List all VMs, Template IDs and CPU architectures \n" "Input 2 for generate public and private key pairs \n" "Input 3 for Launching VM Instance \n" "Input 4 for Release Elastic IP \n" "Input 5 for Delete VM ") num = int(input()) if num == 1: printInstances() elif num == 2: sshKeyGen() elif num == 3: launchInstance() elif num == 4: releaseEip() elif num == 5: termInstance() else: exit()
StarcoderdataPython
51763
<reponame>marcgarrofe/Twitter-Sentiment-Analysis import pandas as pd import numpy as np def count_class_type(dataset: pd.DataFrame, column_label: str): """ Counts de class type of the dataset :param dataset: Input data :param column_label: Name of the column to be analyzed """ assert dataset.size > 0, 'count_class_type() : dataset empty' assert column_label in dataset.columns, 'count_class_type() : column_label not in dataset' zero_count = 0 one_count = 0 for value in dataset[column_label]: if value == 0: zero_count += 1 elif value == 1: one_count += 1 print('\nClass Counter :') print(' 0 appeared ', zero_count, ' times') print(' 1 appeared ', one_count, ' times\n') def confusion_matrix(actual: np.ndarray, predicted: np.ndarray): """ Given the actual classification (or true classification) and the predicted by the algorithm, returns the confusion matrix :param actual: True classification :param predicted: Classification of the implemented algorithm. Example [[27, 2],[5, 22]] :return: """ assert actual.size == predicted.size, 'confusion_matrix() : actual and predicted not the same size' assert actual.size > 0, 'confusion_matrix() : actual empty' matrix = np.array([[0, 0], [0, 0]]) for i in range(actual.size): if actual[i] == predicted[i]: if actual[i] == 1: matrix[0][0] += 1 else: matrix[1][1] += 1 else: if actual[i] == 1: matrix[1][0] += 1 else: matrix[0][1] += 1 return matrix def accuracy(conf_matrix: np.ndarray): """ Accuracy = ( TP + TN ) / ( TP + FP + FN + TN ) :param conf_matrix: Input confusion matrix :return: accuracy calculated from the confusion matrix """ return (conf_matrix[0][0] + conf_matrix[1][1]) / (conf_matrix[0][0] + conf_matrix[0][1] + conf_matrix[1][0] + conf_matrix[1][1]) def precision(conf_matrix: np.ndarray): """ Precision = TP / ( TP + FP ) :param conf_matrix: Input confusion matrix :return: precision calculated from the confusion matrix """ return conf_matrix[0][0] / (conf_matrix[0][0] + conf_matrix[0][1]) def recall(conf_matrix: np.ndarray): """ Recall = TP / ( TP + FN ) :param conf_matrix: Input confusion matrix :return: recall calculated from the confusion matrix """ return conf_matrix[0][0] / (conf_matrix[0][0] + conf_matrix[1][0])
StarcoderdataPython
3374929
<filename>tests/test_pandas.py import os import bln import pandas as pd bln.pandas.register(pd) def test_pandas_read(): """Test the `read_bln` method.""" project_id = "UHJvamVjdDpiZGM5NmU1MS1kMzBhLTRlYTctODY4Yi04ZGI4N2RjMzQ1ODI=" file_name = "ia.csv" tier = os.getenv("BLN_TEST_ENV", "dev") df = pd.read_bln(project_id, file_name, tier=tier) assert len(df) > 0 def test_pandas_write(): """Test the `writer_bln` method.""" df = pd.read_csv("tests/test.csv") project_id = "UHJvamVjdDpiZGM5NmU1MS1kMzBhLTRlYTctODY4Yi04ZGI4N2RjMzQ1ODI=" file_name = "test.csv" tier = os.getenv("BLN_TEST_ENV", "dev") df.to_bln(project_id, file_name, tier=tier, index=False)
StarcoderdataPython
174996
from apiclient import errors from apiclient.http import BatchHttpRequest class Gmail(object): def __init__(self, http, service): self.connected = False self.labels = {} self.events = { 'on_message': [] } self._http = http self._service = service self._users = service.users() self._labels = self._get_labels() self._start() self.connected = True def _start(self): for label in self._labels: self.labels[label['id']] = label['name'] def _get_labels(self): try: results = self._users.labels().list(userId='me').execute() labels = results.get('labels', []) except errors.HttpError: labels = {} return labels def _get_message_ids(self, max_results, label_ids, page_token): try: if not page_token: response = self._users.messages().list(userId='me', labelIds=label_ids, maxResults=max_results ).execute() else: response = self._users.messages().list(userId='me', labelIds=label_ids, maxResults=max_results, pageToken=page_token ).execute() return response except (errors.HttpError, ConnectionResetError): return None def get_messages(self, max_results=10, request_format=None, label_ids=[], page_token=None): response = self._get_message_ids(max_results, label_ids, page_token) if not response: return [] if not request_format: request_format = 'metadata' messages = [] def on_get_message(request_id, response, exception): if exception is not None: return messages.append(response) batch = BatchHttpRequest(callback=on_get_message) try: for message in response['messages']: # message_ids.append(message['id']) batch.add(self._users.messages().get(id=message['id'], userId='me', format=request_format)) batch.execute(http=self._http) except KeyError: return messages return messages def get_message_raw(self, message_id): response = self._users.messages().get(id=message_id, userId='me', format='raw').execute() return response['raw'] def modify_message(self, message_id, removeLabelIds=[], addLabelIds=[]): try: body = {'addLabelIds': addLabelIds, 'removeLabelIds': removeLabelIds} response = self._users.messages().modify(id=message_id, userId='me', body=body).execute() return response except errors.HttpError as error: print(error) def trash_message(self, message_id): try: self._users.messages().trash(id=message_id, userId='me').execute() except errors.HttpError as error: print(error)
StarcoderdataPython
6782
from selenium import webdriver from time import sleep from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait def Dm(driver,user,message): ''' This function is used to direct message a single user/group ''' driver.get('https://www.instagram.com/direct/inbox/') send_message_button = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div/div[3]/div/button'))).click() search_user = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[5]/div/div/div[2]/div[1]/div/div[2]/input'))) search_user.send_keys(user) selector = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[5]/div/div/div[2]/div[2]/div/div/div[3]/button/span'))).click() next_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[5]/div/div/div[1]/div/div[2]/div/button/div'))).click() try: text = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[2]/textarea'))) text.send_keys(message) send = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[3]/button'))).click() driver.get('https://www.instagram.com/direct/inbox/') except: print('No message sent to '+user) driver.get('https://www.instagram.com/direct/inbox/')
StarcoderdataPython
76806
<gh_stars>0 from flask import Blueprint, render_template, url_for, flash, redirect, session, request from werkzeug.security import generate_password_hash, check_password_hash from forms import UserForm, NewsForm from functools import wraps from application import db from modules import User, News from datetime import datetime admin = Blueprint('admin', __name__) # 定义一个实现访问控制的装饰器 admin_login_require def admin_login_require(f): # 使用functools.wraps装饰器装饰内函数wrapper,从而可以保留被修饰的函数属性 @wraps(f) def wrapper(*args, **kwargs): # 判断是否登录 if 'userid' not in session: # 如果session中没有userid的键名,则重定向到登录页 return redirect(url_for('admin.login')) return f(*args, **kwargs) return wrapper @admin.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] user = User.query.filter_by(username=username, is_valid=1).first() if user and check_password_hash(user.password, password): session['username'] = user.username session['userid'] = user.id return redirect(url_for('admin.index')) else: flash("您输入的用户名或密码错误", category='error') return render_template('admin/login.html') @admin.route('/') @admin_login_require def index(): return render_template('admin/index.html') # 退出 @admin.route('/logout') # @admin_login_require def logout(): session.pop('username', None) session.pop('userid', None) return redirect(url_for('admin.login')) # 修改密码 @admin.route('/changePassword', methods=['GET', 'POST']) @admin_login_require def changePassword(): print(session['username'],session['userid']) _id = session['userid'] user1 = User.query.get(_id) form = UserForm(obj=user1) if form.validate_on_submit(): user1.password = generate_password_hash(form.password.data) db.session.add(user1) db.session.commit() flash('修改密码成功! 请重新登录') return redirect(url_for('admin.login')) return render_template('admin/changePassword.html', form=form) @admin.errorhandler(404) def get_error(error): return render_template('admin/error.html'), 404 @admin.route('/user/') @admin.route('/user/<int:page>') @admin_login_require def manager_user(page=None): # 分页查询 if page is None: page = 1 # 接收查询的值 keyword = request.args.get('search') if keyword: try: user_list = User.query.filter(User.username.contains(keyword)).\ order_by(User.id).\ paginate(page=page, per_page=2) condition = "?search=" + keyword return render_template('admin/user_index.html', user_list=user_list, condition=condition) except: flash('搜索失败!') else: user_list = User.query.paginate(page=page, per_page=5) return render_template('admin/user_index.html', user_list=user_list) @admin.route('/user/add', methods=['GET', 'POST']) @admin_login_require def user_add(): form = UserForm() # print(form.__dict__) # 判断表单是否通过 try: if form.validate_on_submit(): user = User(form.username.data, form.password.data, form.is_valid.data) db.session.add(user) db.session.commit() flash('添加成功!') return redirect(url_for('admin.manager_user')) except: flash('你输入的用户名已存在!', category='error') return render_template('admin/user_add.html', form=form) @admin.route('/user/delete/<int:_id>') @admin_login_require def delete_user(_id=None): try: user = User.query.get(_id) db.session.delete(user) db.session.commit() flash('删除成功!') return redirect(url_for('admin.manager_user')) except: flash('删除失败!', category='error') @admin.route('/user/update/<int:_id>', methods=['GET', 'POST']) @admin_login_require def update_user(_id): user = User.query.get(_id) if user is None: return redirect(url_for('admin.manager_user')) form = UserForm(obj=user) if form.validate_on_submit(): try: user.username = form.username.data user.password = <PASSWORD>_password_hash(form.password.data) user.is_valid = form.is_valid.data db.session.add(user) db.session.commit() flash('成功修改管理员') except: flash('您输入的用户名已存在!', category='error') return render_template('admin/user_update.html', form=form) @admin.route('/detail') @admin_login_require def news_detail(): news_list = News.query.all() return render_template('admin/news_detail.html', news_list=news_list) @admin.route('/detail/add', methods=['GET', 'POST']) @admin_login_require def news_add(): form = NewsForm() form.created_at.data = datetime.now() try: if form.validate_on_submit(): news = News(form.title.data, form.content.data, form.types.data, form.img_url.data, form.author.data, form.view_count.data, form.created_at.data, form.is_valid.data, form.is_recommend.data) db.session.add(news) db.session.commit() flash('添加新闻成功!') return redirect(url_for('admin.news_detail')) except: flash('添加新闻失败!', category='error') return render_template('admin/news_add.html', form=form)
StarcoderdataPython
1775058
<gh_stars>1-10 import cv2 from plantcv.plantcv import rgb2gray def test_rgb2gray(test_data): """Test for PlantCV.""" # Read in test data img = cv2.imread(test_data.small_rgb_img) gray_img = rgb2gray(rgb_img=img) # Assert that the output image has the dimensions of the input image but is only a single channel assert img.shape[:2] == gray_img.shape
StarcoderdataPython
69877
import re import pytest import responses from quickbuild import QBError DASHBOARDS_XML = r"""<?xml version="1.0" encoding="UTF-8"?> <list> <com.pmease.quickbuild.model.Dashboard> <id>1</id> <user>1</user> <name>Default</name> <description>System default dashboard</description> <primary>false</primary> <columns> <com.pmease.quickbuild.web.page.dashboard.LayoutColumn> <width>100</width> <gadgetDOMs> <com.pmease.quickbuild.web.gadget.ConfigurationTreeGadget revision="0.0.1"> <title>All Configurations</title> <treeRoot>1</treeRoot> <displayTreeRoot>true</displayTreeRoot> <displaySchedule>false</displaySchedule> <displayRequestCount>true</displayRequestCount> <displayHistoryCount>true</displayHistoryCount> </com.pmease.quickbuild.web.gadget.ConfigurationTreeGadget> </gadgetDOMs> </com.pmease.quickbuild.web.page.dashboard.LayoutColumn> </columns> </com.pmease.quickbuild.model.Dashboard> </list> """ DASHBOARD_INFO_XML = r"""<?xml version="1.0" encoding="UTF-8"?> <com.pmease.quickbuild.model.Dashboard> <id>1</id> <user>1</user> <name>Default</name> <description>System default dashboard</description> <primary>false</primary> <columns> <com.pmease.quickbuild.web.page.dashboard.LayoutColumn> <width>100</width> <gadgetDOMs> <com.pmease.quickbuild.web.gadget.ConfigurationTreeGadget revision="0.0.1"> <title>All Configurations</title> <treeRoot>1</treeRoot> <displayTreeRoot>true</displayTreeRoot> <displaySchedule>false</displaySchedule> <displayRequestCount>true</displayRequestCount> <displayHistoryCount>true</displayHistoryCount> </com.pmease.quickbuild.web.gadget.ConfigurationTreeGadget> <com.pmease.quickbuild.plugin.report.changes.gadget.CommitStatsGadget revision="0.0.0.0.0.0"> <title>Commits</title> <configurationPath>root</configurationPath> <reportsets/> <indicators> <string>Commits</string> <string>Modifications</string> </indicators> <groupBy>BY_DAY</groupBy> <excludingFailed>false</excludingFailed> <ignoreNoBuildDays>false</ignoreNoBuildDays> </com.pmease.quickbuild.plugin.report.changes.gadget.CommitStatsGadget> </gadgetDOMs> </com.pmease.quickbuild.web.page.dashboard.LayoutColumn> </columns> </com.pmease.quickbuild.model.Dashboard> """ DASHBOARD_INFO_JSON = """{ "id" : 1, "user" : 1, "name" : "Default", "description" : "System default dashboard", "primary" : false, "columns" : [ { "width" : 100, "gadgetDOMs" : [ { "title" : "All Configurations", "treeRoot" : 1, "displayTreeRoot" : true, "displaySchedule" : false, "displayRequestCount" : true, "displayHistoryCount" : true, "@class" : "com.pmease.quickbuild.web.gadget.ConfigurationTreeGadget" }, { "title" : "Commits", "configurationPath" : "root", "reportsets" : [ ], "indicators" : [ "Commits", "Modifications" ], "groupBy" : "BY_DAY", "excludingFailed" : false, "ignoreNoBuildDays" : false, "@class" : "com.pmease.quickbuild.plugin.report.changes.gadget.CommitStatsGadget" } ] } ] } """ @responses.activate def test_get(client): responses.add( responses.GET, re.compile(r'.*/rest/dashboards'), content_type='application/xml', body=DASHBOARDS_XML, ) response = client.dashboards.get() assert len(response) == 1 assert response[0]['id'] == 1 assert response[0]['user'] == 1 assert response[0]['name'] == 'Default' assert response[0]['primary'] is False assert response[0]['columns'][0]['width'] == 100 @responses.activate def test_get_info(client): responses.add( responses.GET, re.compile(r'.*/rest/dashboards'), content_type='application/xml', body=DASHBOARD_INFO_XML, ) response = client.dashboards.get_info(1) assert response['@class'] == 'com.pmease.quickbuild.model.Dashboard' assert response['id'] == 1 assert response['columns'][0]['gadgetDOMs'][0]['@revision'] == '0.0.1' @responses.activate def test_update(client): responses.add( responses.POST, re.compile(r'.*/rest/dashboards'), content_type='application/xml', body='10', ) response = client.dashboards.update(DASHBOARD_INFO_XML) assert response == 10 @responses.activate def test_create(client): responses.add( responses.POST, re.compile(r'.*/rest/dashboards'), content_type='application/xml', body='11', ) configuration_without_id = DASHBOARD_INFO_XML.replace('<id>1</id>', '') response = client.dashboards.create(configuration_without_id) assert response == 11 with pytest.raises(QBError): client.dashboards.create(DASHBOARD_INFO_XML) with pytest.raises(QBError): client.dashboards.create(DASHBOARD_INFO_JSON) @responses.activate def test_delete(client): responses.add( responses.DELETE, re.compile(r'.*/rest/dashboards'), body='12', ) response = client.dashboards.delete(12) assert response == 12
StarcoderdataPython
3392951
<filename>server/inv/site.py from flask import Blueprint, redirect, url_for, render_template site = Blueprint('site',__name__,template_folder='templates') @site.route('/', methods=['GET']) def home(): return redirect(url_for('site.about')) @site.route('/about', methods=['GET']) def about(): return render_template('about.html') @site.route('/doc', methods=['GET']) def doc(): return render_template('doc.html') @site.route('/support', methods=['GET']) def support(): return render_template('support.html')
StarcoderdataPython
1621581
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from flier.admin import register from flier.utils import render class MailAdmin(admin.ModelAdmin): list_filter = ('status', ) list_excludes = ('body', 'html', ) list_additionals = ('instance_link', ) readonly_fields = ('instance_link', ) raw_id_fields = ('sender', ) def instance_link(self, obj): p = dict( id=obj.instance.id, a=obj.instance._meta.app_label, m=obj.instance._meta.model_name) p['u'] = "admin:{a}_{m}_change".format(**p) return render(u''' <a href="{% url u id %}">{{a}}.{{m}}</a> ''', **p) instance_link.short_description = _('Concret Instance') class MailTemplateAdmin(admin.ModelAdmin): list_excludes = ('body', 'html', ) class NotificationAdmin(admin.ModelAdmin): raw_id_fields = ['sender', 'content_type', ] register(__name__, globals())
StarcoderdataPython
160498
#!/usr/bin/env /Users/alexrudy/.pyenv/versions/bitly-boto/bin/python import subprocess import click import re import tempfile import shlex import os import typing as t from pathlib import Path from collections import OrderedDict @click.command() @click.option( "--name", type=str, help="Name of the GCE instance to query for.", required=True ) @click.option("--username", type=str, help="Username for the GCE instance") @click.option("--hostname", type=str, help="Hostname in the SSH Config.") @click.option("--config", type=str, help="Path to the SSH Config to update.") @click.option( "--key-file", type=str, default="~/.ssh/id_rsa", help="Path to SSH key file" ) @click.option("--zone", type=str, help="GCE Zone") def main(name, hostname, username, config, key_file, zone): """Find a GCE box by name and print the IP address for it. Optionally, update the `HOSTNAME` line in an SSH config """ key_file = os.path.expanduser(key_file) args = [ "gcloud", "compute", "ssh", f"{username}@{name}", f"--ssh-key-file={key_file}", "--dry-run", ] if zone: args.append(f"--zone={zone}") raw_cmd = subprocess.check_output( args ).decode('utf-8').strip() args = shlex.split(raw_cmd) user, address = args[-1].split("@", 1) config_options = {} for i, arg in enumerate(args): if arg == "-o": copt = args[i + 1] name, value = copt.split("=", 1) config_options[name.lower()] = value click.echo(f"IP: {address}") config_options['hostname'] = address config_options['user'] = user if config is not None and hostname is not None: click.echo(f"Updating {config!s} {hostname}") update_config(config, hostname, config_options) def update_config(config, hostname, config_options): """Update the SSH Config with a new IP address""" target = Path(config) with tempfile.TemporaryDirectory() as tmpdirname: target_backup = Path(tmpdirname) / target.name with target_backup.open("w") as out_stream, target.open("r") as in_stream: for line in iter_new_config(in_stream, hostname, config_options): out_stream.write(line) target_backup.replace(target) class Entry(t.NamedTuple): line: str match: t.Optional[re.Match] @property def key(self) -> t.Optional[str]: return self.match.group('key').lower() if self.match else None @property def value(self) -> t.Optional[str]: return self.match.group('value') @classmethod def parse(cls, line) -> t.Optional["Entry"]: m = re.match(r"^(?P<indent>\s*)(?P<key>\w+)(?P<sep>=|\s+)(?P<value>\S.+\S?)(?P<comment>\s+#.+)?$", line, flags=re.I) return cls(line, m) def replace(self, value: str): return self.match.expand("\g<indent>\g<key>\g<sep>") + value + self.match.expand("\g<comment>") + "\n" def iter_new_config(lines, target_host, new_options): options = set() new_options = {k.lower().strip():v for k,v in new_options.items()} # Construct the entire config in memory config = OrderedDict() current_hosts = frozenset() for line in lines: entry = Entry.parse(line) if entry.key == 'host': current_hosts = frozenset(entry.value.split()) config[current_hosts] = host_config = OrderedDict() host_config[entry.key] = entry else: host_config[entry.key] = entry # Iterate and retrun modified configuration for hosts, host_config in config.items(): for entry in host_config.values(): line = entry.line if target_host in hosts and entry.key in new_options: new_value = new_options[entry.key] if new_value != entry.value: line = entry.replace(new_value) options.add(entry.key) yield line if not options: raise ValueError("No options were replaced") if __name__ == "__main__": main(auto_envvar_prefix="GET_GCP_IP")
StarcoderdataPython
3299655
"""Comment CRUD functionality""" from app.api.v2.dbmodel import QuestionerDb class CommentModel: """Comment class model""" def create_comment(self, question, comment): """Method to create a comment""" comment_query = """INSERT INTO comments (question, comment) VALUES (%s, %s) RETURNING question, comment""" comment_tuple = (question, comment) response = QuestionerDb.add_to_db(comment_query, comment_tuple) return response
StarcoderdataPython
144508
<gh_stars>0 import os import re import sys import subprocess # Use the official chef lex file # Compile from source each time path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'swedish_chef.l') COMPILE_CMD = "lex -o /tmp/swedish_chef.c {0} && cc /tmp/swedish_chef.c -o /tmp/swedish_chef -ll".format(path) subprocess.Popen(COMPILE_CMD, stdout=subprocess.PIPE, shell=True).wait() RUN_CMD = "/tmp/swedish_chef" def filter(text): """ >>> filter("Turn flash on.") 'Toorn flesh oon.' >>> filter("Cancel") 'Cuncel' >>> filter("card.io") 'cerd.iu' """ p = subprocess.Popen(RUN_CMD, stdout=subprocess.PIPE, stdin=subprocess.PIPE) stdout, stderr = p.communicate(input=text) return stdout if __name__ == "__main__": import doctest doctest.testmod()
StarcoderdataPython
1739710
#!/usr/bin/env python3 import argparse import os import sys import json import numpy as np PROG = os.path.basename(sys.argv[0]) def main(): parser = argparse.ArgumentParser( description='Fix a raman.json file created before 99e7a42a5 (June 14)', ) parser.add_argument('INPUT', nargs='*') parser.add_argument( '--temperature', type=float, help="specify temperature, for double checking that the missing prefactor matches expectation.", ) parser.add_argument( '--mistake-no', type=parse_mistake, default=1, help="which mistake defines our expectation?" " 1: first mistake (completely missing)," " 2: second mistake (missing sqrt)," " *: any of the above mistakes", ) args = parser.parse_args() for path in args.INPUT: corrected_loc = path + '.corrected' with open(path) as f: d = json.load(f) frequencies = np.array(d['frequency']) correct_averages = np.array(d['average-3d']) recorded_tensors = np.array(d['raman-tensor']) actual_averages = np.sum(recorded_tensors**2, axis=(1,2)) / 9 if np.allclose(correct_averages, actual_averages, rtol=1e-10, atol=0): continue missing_prefactors = correct_averages / actual_averages missing_prefactors[frequencies <= 0] = 0 if args.temperature is not None: if check_expected_prefactors(frequencies, temperature=args.temperature, mistake=args.mistake_no, missing_prefactors=missing_prefactors): warn(f"{path} has missing prefactors that match expectation") else: warn(f"{path} has missing prefactors that DO NOT match expectation!!") # print(np.hstack([correct_averages[:, None], actual_averages[:, None]]), file=sys.stderr) # print(np.hstack([expected_prefactors[:, None], missing_prefactors[:, None]]), file=sys.stderr) else: warn(f"{path} has missing prefactors") warn(f"Writing {corrected_loc}") correct_tensors = recorded_tensors * np.sqrt(missing_prefactors[:, None, None]) d['raman-tensor'] = correct_tensors.tolist() with open(corrected_loc, 'w') as f: json.dump(d, f) print(file=f) ANY_MISTAKE = object() def parse_mistake(s): if s == '*': return ANY_MISTAKE elif s in '12': return int(s) else: raise ValueError(f'invalid mistake: {repr(s)}') def check_expected_prefactors(frequencies, temperature, missing_prefactors, mistake): if mistake is ANY_MISTAKE: return any( check_expected_prefactors( frequencies=frequencies, temperature=temperature, missing_prefactors=missing_prefactors, mistake=m, ) for m in [1, 2] ) hk = 0.22898852319 if temperature == 0: bose_occupation = 1 else: expm1 = np.expm1(hk * frequencies / temperature) bose_occupation = (1.0 + 1.0 / expm1) prefactors = bose_occupation / frequencies if mistake == 1: expected_prefactors = np.where(frequencies <= 0.0, 0.0, prefactors) elif mistake == 2: expected_prefactors = np.where(frequencies <= 0.0, 0.0, prefactors ** -1) else: raise ValueError('mistake') return np.allclose(expected_prefactors, missing_prefactors, atol=0) # ------------------------------------------------------ def warn(*args, **kw): print(f'{PROG}:', *args, file=sys.stderr, **kw) def die(*args, code=1): warn('Fatal:', *args) sys.exit(code) # ------------------------------------------------------ if __name__ == '__main__': main()
StarcoderdataPython
4818816
from . import basicauth, jwt from .. import exceptions token_identifiers = [ jwt.parse, basicauth.parse, ] def identify(region, service, headers): for fn in token_identifiers: try: return fn(region, service, headers) except exceptions.Unsigned: continue raise exceptions.Unsigned()
StarcoderdataPython