uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
88fdf362e81f540a7c6ed9e5 | train | class | class ResidualTabularModel(Module):
"Residual model for tabular data."
def __init__(self, emb_szs, n_cont, out_sz, layers, ps=None, embed_p=0.,
y_range=None, use_bn=True, bn_final=False, bn_cont=True, act_cls=nn.ReLU(inplace=True),
lin_first=True):
ps = ifnone(ps, [0]*l... | class ResidualTabularModel(Module):
| "Residual model for tabular data."
def __init__(self, emb_szs, n_cont, out_sz, layers, ps=None, embed_p=0.,
y_range=None, use_bn=True, bn_final=False, bn_cont=True, act_cls=nn.ReLU(inplace=True),
lin_first=True):
ps = ifnone(ps, [0]*len(layers))
if not is_listy(... | .datum: list = []
self.records: list = []
self.c_idx: int = -1
def before_fit(self):
self.datum.append(L())
self.records.append({'loss': [], 'predictions': []})
self.c_idx += 1
def after_batch(self):
vals = self.learn.to_detach((self.xb,self.yb,self.pred,self.... | 239 | 239 | 797 | 8 | 230 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | ResidualTabularModel | ResidualTabularModel | 812 | 868 | 812 | 812 | 1f83602b06346e9d4b3c6f163a24a0f1834776de | bigcode/the-stack | train |
901491203b7a1dfd0cabb588 | train | class | class LazyGraphCallback(Callback):
'''
Class defines a callback that is passed to the fastai learner that
saves the validation and training loss metrics to graph when
calling the .plot_graph() method
This allows us to display the train/validation loss graph after the... | class LazyGraphCallback(Callback):
| '''
Class defines a callback that is passed to the fastai learner that
saves the validation and training loss metrics to graph when
calling the .plot_graph() method
This allows us to display the train/validation loss graph after the
experiment is run,... | `log` and call the old logger."
if(self.flag):
self.df = pd.DataFrame([log], columns=self.recorder.metric_names)
self.flag = False
else:
if (len(log) == len(self.df.columns)):
self.new_row = pd.DataFrame([log], columns=self.recorder.metric_names)
... | 131 | 131 | 438 | 7 | 123 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | LazyGraphCallback | LazyGraphCallback | 724 | 769 | 724 | 724 | c034ebd09558fe06f84f3159985199e1fff78752 | bigcode/the-stack | train |
775b9c64cb8d0c6c4441f566 | train | function | def create_n_cloud_from_dataset(df: pd.DataFrame, n_points: int = 100, target_label: str = 'label', allow_partial: bool = False, segmented=True):
'''
Function takes a dataframe and splits it into point clouds with n_points each.
The generated clouds will all have the indicated number of points,... | def create_n_cloud_from_dataset(df: pd.DataFrame, n_points: int = 100, target_label: str = 'label', allow_partial: bool = False, segmented=True):
| '''
Function takes a dataframe and splits it into point clouds with n_points each.
The generated clouds will all have the indicated number of points, discarding the remainder if allow_partial is False.
The generated clouds will be partitioned by the classes contained within the targ... | _data, 'Merged Type')
merged_y = merged_df['Merged Type']
new_labels: list = []
for l in labels:
new_labels.append([])
for x in merged_y:
split_label = x.split('_')
for i in range(len(split_label)):
new_labels[i].append(split_label[i])
for i, x in enumerate(l... | 150 | 151 | 505 | 38 | 111 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | create_n_cloud_from_dataset | create_n_cloud_from_dataset | 1,962 | 2,012 | 1,962 | 1,962 | 9bc151f0a872f81b81a2941653e569a8ce9125cc | bigcode/the-stack | train |
15405ab93792bb71d017da34 | train | function | def check_zeros_over_threshold_percentage(data_summary: dict, threshold: float) -> pd.DataFrame:
'''
Function will return a dataframe of features with all features with
a frequency of 0 values greater than the threshold
'''
vals: pd.DataFrame = data_summary['Feature_stats']
size: int = ... | def check_zeros_over_threshold_percentage(data_summary: dict, threshold: float) -> pd.DataFrame:
| '''
Function will return a dataframe of features with all features with
a frequency of 0 values greater than the threshold
'''
vals: pd.DataFrame = data_summary['Feature_stats']
size: int = data_summary['Dataset'].shape[0]
zero_df = vals[vals['Value'] == 'Zero'].T
zero_df_bottom... | ']
zero_df = vals[vals['Value'] == 'Zero'].T
zero_df_bottom = zero_df[2:]
return zero_df_bottom[zero_df_bottom[2] > threshold]
def check_zeros_over_threshold_percentage(data_summary: dict, threshold: float) -> pd.DataFrame:
| 63 | 64 | 120 | 21 | 42 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | check_zeros_over_threshold_percentage | check_zeros_over_threshold_percentage | 508 | 519 | 508 | 508 | 0bb6a9097bafa24001277704e77f88595eae3ec3 | bigcode/the-stack | train |
a84918a7da9375b69eaa812f | train | function | def test_infs(data_summary: dict) -> bool:
'''
Function asserts the dataset has no inf values.
'''
vals: pd.DataFrame = data_summary['Feature_stats']
inf_df = vals[vals['Value'] == 'Inf'].T
assert inf_df[inf_df[0] != 0].shape[0] == 2, 'Dataset has inf values'
return True
| def test_infs(data_summary: dict) -> bool:
| '''
Function asserts the dataset has no inf values.
'''
vals: pd.DataFrame = data_summary['Feature_stats']
inf_df = vals[vals['Value'] == 'Inf'].T
assert inf_df[inf_df[0] != 0].shape[0] == 2, 'Dataset has inf values'
return True
| with all rows that do not have the values in the column removed
'''
new_df = pd.DataFrame()
for v in value:
new_df = new_df.append(df[df[column] == v].copy())
return new_df
def test_infs(data_summary: dict) -> bool:
| 64 | 64 | 88 | 12 | 51 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | test_infs | test_infs | 625 | 635 | 625 | 625 | f7e62d365fc036d56d10f747a1bc7cffbafdb535 | bigcode/the-stack | train |
941d31b4c9e623d4022a6aac | train | function | def visualize_report(model_data: tuple, ax=None, cmap='Blues') -> yb.classifier:
'''
Takes a 10-tuple from the run_experiments function and creates a report
detailing the Precision, Recall, f1, and Support scores for all
classification outcomes
model_data: tuple = (name, model, cla... | def visualize_report(model_data: tuple, ax=None, cmap='Blues') -> yb.classifier:
| '''
Takes a 10-tuple from the run_experiments function and creates a report
detailing the Precision, Recall, f1, and Support scores for all
classification outcomes
model_data: tuple = (name, model, classes, X_train, y_train, X_test, y_test, to, dls, model_type)
'''
visuali... | .PrecisionRecallCurve(model_data[1], title=model_data[0], ax=ax, cmap=cmap)
visualizer.score(model_data[5], model_data[6])
return visualizer
def visualize_report(model_data: tuple, ax=None, cmap='Blues') -> yb.classifier:
| 64 | 64 | 155 | 22 | 41 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | visualize_report | visualize_report | 2,084 | 2,096 | 2,084 | 2,084 | 9c147ff9ec7bb0e45379ba0cfe9788dce41d33d3 | bigcode/the-stack | train |
f5645e1a0898932846e8437e | train | function | def check_zeros(data_summary: dict) -> pd.DataFrame:
'''
Function will return a dataframe of features with a value of 0.
'''
vals: pd.DataFrame = data_summary['Feature_stats']
zero_df = vals[vals['Value'] == 'Zero'].T
return zero_df[zero_df[2] != 0]
| def check_zeros(data_summary: dict) -> pd.DataFrame:
| '''
Function will return a dataframe of features with a value of 0.
'''
vals: pd.DataFrame = data_summary['Feature_stats']
zero_df = vals[vals['Value'] == 'Zero'].T
return zero_df[zero_df[2] != 0]
| NaN.
'''
vals: pd.DataFrame = data_summary['Feature_stats']
nan_df = vals[vals['Value'] == 'NaN'].T
return nan_df[nan_df[1] != 0]
def check_zeros(data_summary: dict) -> pd.DataFrame:
| 63 | 64 | 76 | 14 | 49 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | check_zeros | check_zeros | 483 | 491 | 483 | 483 | 62256c52d869b5b102f817a7229b9435bd66dd6b | bigcode/the-stack | train |
39026bbde568fd52a80c7e9f | train | function | def normalize_bilabel_dataset_between_0_1(df: pd.DataFrame, labels = ['Traffic Type', 'Application Type']) -> pd.DataFrame:
'''
Function takes a dataframe and merges its labels before normalizing data.
The labels are then split back into their original form, but the merged label is kept for verific... | def normalize_bilabel_dataset_between_0_1(df: pd.DataFrame, labels = ['Traffic Type', 'Application Type']) -> pd.DataFrame:
| '''
Function takes a dataframe and merges its labels before normalizing data.
The labels are then split back into their original form, but the merged label is kept for verification purposes.
returns a trilabel dataframe with the new label under the 'Merged Type' column
'''
inter_df... |
"""
X = model_data.X_train
y = model_data.y_train
classes = model_data.classes
Xy_df = pd.DataFrame(X)
y_s: list = []
for x in y:
y_s.append(classes[x])
Xy_df[target_label] = y_s
return Xy_df
def normalize_bilabel_dataset_between_0_1(df: pd.DataFrame, labels = ['Traffic Ty... | 105 | 105 | 351 | 32 | 72 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | normalize_bilabel_dataset_between_0_1 | normalize_bilabel_dataset_between_0_1 | 1,908 | 1,958 | 1,908 | 1,908 | 18fef73dfd4d61d1cdd5da51f0788b869526c552 | bigcode/the-stack | train |
2f8b21a4126f3a57946d4af1 | train | function | def show_feature_importance_TA(model: Learner, df: pd.DataFrame, ax = None, figsize = (15,5), title='Feature Importances') -> tuple:
'''
Function shows the feature importance calculated by the attention layer of the TabNet model.
'''
dl = model.dls.test_dl(df, bs=64)
feature_importances = tabn... | def show_feature_importance_TA(model: Learner, df: pd.DataFrame, ax = None, figsize = (15,5), title='Feature Importances') -> tuple:
| '''
Function shows the feature importance calculated by the attention layer of the TabNet model.
'''
dl = model.dls.test_dl(df, bs=64)
feature_importances = tabnet_feature_importances(model.model, dl)
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
ax.bar(dl.x_name... | _ax.set_ylabel('')
current_ax.yaxis.set_ticklabels([])
plt.tight_layout()
return (fig, ax)
def show_feature_importance_TA(model: Learner, df: pd.DataFrame, ax = None, figsize = (15,5), title='Feature Importances') -> tuple:
| 64 | 64 | 159 | 38 | 26 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | show_feature_importance_TA | show_feature_importance_TA | 2,350 | 2,367 | 2,350 | 2,350 | cfb3583f5555fb9642cd68ef7a6d453573533e2b | bigcode/the-stack | train |
e73d1de87ee0d16a7e271f59 | train | class | class ResidualBlock(Module):
def __init__(self, module, layer):
# super().__init__()
self.module = module
self.layer = layer
def forward(self, inputs):
fx = self.module(inputs)
if(inputs.shape != fx.shape):
print('mismatch at layer:', self.layer ,inputs.shape... | class ResidualBlock(Module):
| def __init__(self, module, layer):
# super().__init__()
self.module = module
self.layer = layer
def forward(self, inputs):
fx = self.module(inputs)
if(inputs.shape != fx.shape):
print('mismatch at layer:', self.layer ,inputs.shape, fx.shape)
return fx... | append(vals)
self.records[self.c_idx]['predictions'].append(vals[2])
self.records[self.c_idx]['loss'].append(vals[3])
self.records[self.c_idx]['iters'] = range_of(self.recorder.losses)
## pytorch --> fastai models
class ResidualBlock(Module):
| 64 | 64 | 80 | 6 | 57 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | ResidualBlock | ResidualBlock | 799 | 809 | 799 | 799 | cc7d7d84964e434ed5eb406ef8a34ba73cda2d38 | bigcode/the-stack | train |
496183123282bdf2e917a723 | train | function | def visualize_class_balance(model_data: tuple, ax=None, cmap='Blues') -> yb.classifier:
'''
Takes a 10-tuple from the run_experiments function and creates a histogram
detailing the balance between classification outcomes
model_data: tuple = (name, model, classes, X_train, y_train, X_test, y... | def visualize_class_balance(model_data: tuple, ax=None, cmap='Blues') -> yb.classifier:
| '''
Takes a 10-tuple from the run_experiments function and creates a histogram
detailing the balance between classification outcomes
model_data: tuple = (name, model, classes, X_train, y_train, X_test, y_test, to, dls, model_type)
'''
visualizer = yb.target.ClassBalance(labels=mode... | classes=model_data[2], title=model_data[0], support=True, ax=ax, cmap=cmap)
visualizer.score(model_data[5], model_data[6])
return visualizer
def visualize_class_balance(model_data: tuple, ax=None, cmap='Blues') -> yb.classifier:
| 64 | 64 | 129 | 23 | 40 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | visualize_class_balance | visualize_class_balance | 2,100 | 2,111 | 2,100 | 2,100 | a9a0fdf80819cc2035b6794f5cf4e6400d7a70e3 | bigcode/the-stack | train |
b0a2c860748d7b7d4a51dd64 | train | function | def clean_data(df: pd.DataFrame, prune: list) -> pd.DataFrame:
'''
Function will take a dataframe and remove the columns that match a value in prune
Inf and Nan values will also be removed once appropriate rows and columns
have been removed,
we will return the dataframe with the a... | def clean_data(df: pd.DataFrame, prune: list) -> pd.DataFrame:
| '''
Function will take a dataframe and remove the columns that match a value in prune
Inf and Nan values will also be removed once appropriate rows and columns
have been removed,
we will return the dataframe with the appropriate values
'''
# remove the features in the pru... |
else:
j = 2
indexNames = df[df[col] == value].index
if not indexNames.empty:
feature[j] += len(indexNames)
stats[col] = feature
return pd.DataFrame(stats)
def clean_data(df: pd.DataFrame, prune: list) -> pd.DataFrame:
| 72 | 72 | 241 | 18 | 54 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | clean_data | clean_data | 207 | 237 | 207 | 207 | 3c54988f1fc236803b151e9b67a71fc628a50be3 | bigcode/the-stack | train |
5ad5b3d6927f7fa33b821a1a | train | class | class Normal(DisplayedTransform):
'''
A data processing tool inherited from the fastai library.
This is a modified version of the normalize function that performs MinMax scaling and is able to be
used in our preprocessing pipeline.
The original normalizes the data to have a mea... | class Normal(DisplayedTransform):
| '''
A data processing tool inherited from the fastai library.
This is a modified version of the normalize function that performs MinMax scaling and is able to be
used in our preprocessing pipeline.
The original normalizes the data to have a mean centered at 0 and a standard dev... | ].values.astype('float32')
if self.add_col:
for i in range(self.n_comps):
if f'pca_{i+1}' not in to.cont_names: to.cont_names.append(f'pca_{i+1}')
return self(to)
class Normal(DisplayedTransform):
| 64 | 64 | 204 | 6 | 58 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | Normal | Normal | 351 | 370 | 351 | 351 | f63c2319b564b4a802bd7af0757b9960ff0d9257 | bigcode/the-stack | train |
b4340bae7b2179b392850b3e | train | function | def run_tabnet_experiment(
df: pd.DataFrame,
file_name: str,
target_label: str,
split=0.2,
name: str or None = None,
categorical: list = ['Protocol'],
procs = [FillMissing, Categorify, Normalize],
leave_out: list = [],
epochs: int = 10,
steps: int = 1,
batch_size: int = ... | def run_tabnet_experiment(
df: pd.DataFrame,
file_name: str,
target_label: str,
split=0.2,
name: str or None = None,
categorical: list = ['Protocol'],
procs = [FillMissing, Categorify, Normalize],
leave_out: list = [],
epochs: int = 10,
steps: int = 1,
batch_size: int = ... | '''
Function trains a TabNet model on the dataframe and returns a model data named tuple
Based on TabNet: Attentive Interpretable Tabular Learning by Sercan Arik and Tomas Pfister from Google Cloud AI (2016)
where a DNN selects features from the input features based on an attention layer. Ea... | _type_ = 'multiclass'
else:
print('Must be more than one class to perform classification')
raise ValueError('Wrong number of classes')
wrapped_model._target_labels = target_label
model_data: Model_data = Model_data(file_name, wrapped_model, classes, X_train, y_train, X_test, y_test... | 256 | 256 | 1,536 | 170 | 85 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | run_tabnet_experiment | run_tabnet_experiment | 1,726 | 1,888 | 1,726 | 1,745 | 00a11bafb1b4a39bad40037878ad795188de9b9e | bigcode/the-stack | train |
0d1c1d1fa375b69a7b0cc93e | train | class | class ResidualTabularModel(Module):
"Residual model for tabular data."
def __init__(self, emb_szs, n_cont, out_sz, layers, ps=None, embed_p=0.,
y_range=None, use_bn=True, bn_final=False, bn_cont=True, act_cls=nn.ReLU(inplace=True),
lin_first=True, cardinality: list or None = No... | class ResidualTabularModel(Module):
| "Residual model for tabular data."
def __init__(self, emb_szs, n_cont, out_sz, layers, ps=None, embed_p=0.,
y_range=None, use_bn=True, bn_final=False, bn_cont=True, act_cls=nn.ReLU(inplace=True),
lin_first=True, cardinality: list or None = None):
ps = ifnone(ps, [0]*len... | input modules
in the branches list parameter.
the residual connection is put through a linear batchnormed layer if the
input size is different from the output size
Then, the output of the branches is summed together along with the possibly transformed input
'''
... | 210 | 210 | 702 | 8 | 201 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | ResidualTabularModel | ResidualTabularModel | 966 | 1,014 | 966 | 966 | 876159d3aa401585d7a05ec26f6d8b3afa10bcae | bigcode/the-stack | train |
1c34ed22a2198d9380c4ff6a | train | class | class SklearnWrapper(BaseEstimator):
'''
A wrapper for fastai learners for creating visualizations using yellowbrick
code sourced from:
forums.fast.ai/t/fastai-with-yellowbrics-how-to-get-roc-curves-more/79408
'''
_estimator_type = "classifier"
def __init__(self, model)... | class SklearnWrapper(BaseEstimator):
| '''
A wrapper for fastai learners for creating visualizations using yellowbrick
code sourced from:
forums.fast.ai/t/fastai-with-yellowbrics-how-to-get-roc-curves-more/79408
'''
_estimator_type = "classifier"
def __init__(self, model):
self.model = model
... | plotly graph
'''
colors = []
for i in range(n):
color = colorsys.hls_to_rgb(
i / n,
luminosity,
saturation,
)
colors.append(f'rgba({color[0] * 255}, {color[1] * 255}, {color[2] * 255}, {opacity})')
return colors
# Skl... | 95 | 95 | 318 | 7 | 87 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | SklearnWrapper | SklearnWrapper | 280 | 316 | 280 | 280 | b76c3696a122ea57c8fb7a611faa0e389f0575a9 | bigcode/the-stack | train |
25e8e7dc30e5eb6c41ac9cc3 | train | class | class ModelStatsCallback(Callback):
'''
Collect all batches, along with `pred` and `loss`, into `self.datum`.
This allows the data to be used after the model is used.
'''
order=60 # mysterious param we need to investigate
def __init__(self):
self.datum: list = []
self.rec... | class ModelStatsCallback(Callback):
| '''
Collect all batches, along with `pred` and `loss`, into `self.datum`.
This allows the data to be used after the model is used.
'''
order=60 # mysterious param we need to investigate
def __init__(self):
self.datum: list = []
self.records: list = []
self.c_idx: ... | ax.set_ylabel('Loss')
ax.plot(params[0][0][0], params[0][0][1], label='Training')
ax.plot(params[0][1][0], params[0][1][1], label='Validation')
ax.legend()
class ModelStatsCallback(Callback):
| 64 | 64 | 209 | 7 | 57 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | ModelStatsCallback | ModelStatsCallback | 773 | 795 | 773 | 773 | 2e208a0c24748bbba6a556ecf4fc7e8f8f780ed7 | bigcode/the-stack | train |
a31162c1958439c1d7e9254b | train | function | def test_nans(data_summary: dict) -> bool:
'''
Function asserts the dataset has no NaN values
'''
vals: pd.DataFrame = data_summary['Feature_stats']
nan_df = vals[vals['Value'] == 'NaN'].T
assert nan_df[nan_df[1] != 0].shape[0] == 2, 'Dataset has NaN values'
return True
| def test_nans(data_summary: dict) -> bool:
| '''
Function asserts the dataset has no NaN values
'''
vals: pd.DataFrame = data_summary['Feature_stats']
nan_df = vals[vals['Value'] == 'NaN'].T
assert nan_df[nan_df[1] != 0].shape[0] == 2, 'Dataset has NaN values'
return True
| Feature_stats']
inf_df = vals[vals['Value'] == 'Inf'].T
assert inf_df[inf_df[0] != 0].shape[0] == 2, 'Dataset has inf values'
return True
def test_nans(data_summary: dict) -> bool:
| 64 | 64 | 90 | 12 | 51 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | test_nans | test_nans | 639 | 650 | 639 | 639 | 82217b219771800ed08b640eba38c78bf4292254 | bigcode/the-stack | train |
de46e5162bdc55221720cdc2 | train | function | def prune_feature_by_values(df: pd.DataFrame, column: str, value: list) -> pd.DataFrame:
'''
Function takes a dataframe, a column name, and a list of values and returns a dataframe
with all rows that do not have the values in the column removed
Deprecated, use reduce_feature_to_values:
... | def prune_feature_by_values(df: pd.DataFrame, column: str, value: list) -> pd.DataFrame:
| '''
Function takes a dataframe, a column name, and a list of values and returns a dataframe
with all rows that do not have the values in the column removed
Deprecated, use reduce_feature_to_values:
ambiguous name implied it is removing values, not keeping them
'''
new_df... | dataset with all the columns in the prune list removed.
'''
df: pd.DataFrame = data_summary['Dataset'].copy()
df = clean_data(df, prune)
return df
def prune_feature_by_values(df: pd.DataFrame, column: str, value: list) -> pd.DataFrame:
| 64 | 64 | 120 | 24 | 39 | Karson-Fye/CMUDarknet | experiments/data_generation/VAE/utilities.py | Python | prune_feature_by_values | prune_feature_by_values | 596 | 608 | 596 | 596 | 1fff09176027c8613525d8690966749c2864bacc | bigcode/the-stack | train |
08e92677ba7ff4ed28e3a46b | train | function | def train(data_loader, model, cfg):
# avg_meters =
model.train()
end = time.time()
for iter, batch in enumerate(data_loader):
data_time = time.time() - end
iter += 1
outputs = model(batch)
| def train(data_loader, model, cfg):
# avg_meters =
| model.train()
end = time.time()
for iter, batch in enumerate(data_loader):
data_time = time.time() - end
iter += 1
outputs = model(batch)
| import time
import torch
def train(data_loader, model, cfg):
# avg_meters =
| 21 | 64 | 57 | 15 | 5 | f121606/OrigNet | lib/train/MNIST.py | Python | train | train | 6 | 14 | 6 | 7 | e7d17d3872d2cc3f56f90948617b09955a4c60f7 | bigcode/the-stack | train |
ba056e4dd11e473c69622737 | train | class | class SynapseLogin(DefaultOAuth2Login):
def __init__(self):
super(SynapseLogin, self).__init__(
idp_name=IdentityProvider.synapse, client=flask.current_app.synapse_client
)
| class SynapseLogin(DefaultOAuth2Login):
| def __init__(self):
super(SynapseLogin, self).__init__(
idp_name=IdentityProvider.synapse, client=flask.current_app.synapse_client
)
| from datetime import datetime, timezone, timedelta
import flask
from flask_sqlalchemy_session import current_session
from fence.config import config
from fence.models import IdentityProvider
from fence.blueprints.login.base import DefaultOAuth2Login, DefaultOAuth2Callback
class SynapseLogin(DefaultOAuth2Login):
| 60 | 64 | 49 | 9 | 50 | themarcelor/fence | fence/blueprints/login/synapse.py | Python | SynapseLogin | SynapseLogin | 12 | 16 | 12 | 12 | ac7af7dc82460accf3dc097c94b34e89ec748ad1 | bigcode/the-stack | train |
4d75f08b2ba1d26508619912 | train | class | class SynapseCallback(DefaultOAuth2Callback):
def __init__(self):
super(SynapseCallback, self).__init__(
idp_name=IdentityProvider.synapse,
client=flask.current_app.synapse_client,
username_field="fence_username",
)
def post_login(self, user, token_result):
... | class SynapseCallback(DefaultOAuth2Callback):
| def __init__(self):
super(SynapseCallback, self).__init__(
idp_name=IdentityProvider.synapse,
client=flask.current_app.synapse_client,
username_field="fence_username",
)
def post_login(self, user, token_result):
user.id_from_idp = token_result["sub"]
... | _session import current_session
from fence.config import config
from fence.models import IdentityProvider
from fence.blueprints.login.base import DefaultOAuth2Login, DefaultOAuth2Callback
class SynapseLogin(DefaultOAuth2Login):
def __init__(self):
super(SynapseLogin, self).__init__(
idp_name... | 93 | 93 | 311 | 9 | 84 | themarcelor/fence | fence/blueprints/login/synapse.py | Python | SynapseCallback | SynapseCallback | 19 | 54 | 19 | 19 | f3ff4e804c41c794e2d5428d3b38bd1a686fffbe | bigcode/the-stack | train |
755012fd326d6ce2adb8b44b | train | class | class PostcardsApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client):
self.api_client = api_client
def get_all(self, **kwargs): #... | class PostcardsApi(object):
| """NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client):
self.api_client = api_client
def get_all(self, **kwargs): # noqa: E501
"""List ... | # coding: utf-8
"""
Mailchimp Marketing API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 3.0.12
Contact: apihelp@mailchimp.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from _... | 127 | 256 | 1,234 | 6 | 120 | daviddaven-port/mailchimp-marketing-python | build/lib/mailchimp_marketing/api/postcards_api.py | Python | PostcardsApi | PostcardsApi | 24 | 143 | 24 | 24 | 713c20febce6b32fb617e6860a9b1a714bf619c7 | bigcode/the-stack | train |
4d6e81be6bc40499f98dc863 | train | function | def countryM(df):
return list(set(map(lambda x: x[0], df.index))) | def countryM(df):
| return list(set(map(lambda x: x[0], df.index))) | ' string을 int64로 바꿔주는 메서드
def timeToInt(df):
df = df['time'].apply(lambda x : int(x[2:]))
return df
# 데이터 프레임에서 country list 뽑아주는 메서드
def countryM(df):
| 64 | 64 | 20 | 5 | 58 | i-zro/GenderEDAProject | gedaTools.py | Python | countryM | countryM | 7 | 8 | 7 | 7 | a984407a8a3bd0b4ff6d39ec021af01c671b7928 | bigcode/the-stack | train |
c593a4bfb9e2b017f8972a35 | train | function | def timeToInt(df):
df = df['time'].apply(lambda x : int(x[2:]))
return df
| def timeToInt(df):
| df = df['time'].apply(lambda x : int(x[2:]))
return df
| # 데이터프레임의 time(연도) 'YR~' string을 int64로 바꿔주는 메서드
def timeToInt(df):
| 35 | 64 | 27 | 6 | 28 | i-zro/GenderEDAProject | gedaTools.py | Python | timeToInt | timeToInt | 2 | 4 | 2 | 2 | 152a2424217bb57422d02a7bad8de462cd7a6d92 | bigcode/the-stack | train |
05c954ead6d486ccc8da3446 | train | function | def mass_center(mass, xpos):
return (np.sum(mass * xpos, 0) / np.sum(mass))[0]
| def mass_center(mass, xpos):
| return (np.sum(mass * xpos, 0) / np.sum(mass))[0]
| from .agent import Agent
from .humanoid_kicker import HumanoidKicker
from gym.spaces import Box
import numpy as np
def mass_center(mass, xpos):
| 38 | 64 | 29 | 8 | 29 | MachengShen/torchbeast | multiagent-competition/gym-compete/gym_compete/new_envs/agents/humanoid_goalkeeper.py | Python | mass_center | mass_center | 7 | 8 | 7 | 7 | b3ae9a3a38a683da52e032567f8e15be86c11737 | bigcode/the-stack | train |
1101e8c0217dc6bd980ac638 | train | class | class HumanoidGoalKeeper(HumanoidKicker):
def __init__(self, agent_id, xml_path=None, team='blocker', goal_x=4, goal_y=3):
super(HumanoidGoalKeeper, self).__init__(agent_id, xml_path)
self.team = team
self.GOAL_X = goal_x
self.GOAL_Y = goal_y
def before_step(self):
pass... | class HumanoidGoalKeeper(HumanoidKicker):
| def __init__(self, agent_id, xml_path=None, team='blocker', goal_x=4, goal_y=3):
super(HumanoidGoalKeeper, self).__init__(agent_id, xml_path)
self.team = team
self.GOAL_X = goal_x
self.GOAL_Y = goal_y
def before_step(self):
pass
def after_step(self, action):
... | from .agent import Agent
from .humanoid_kicker import HumanoidKicker
from gym.spaces import Box
import numpy as np
def mass_center(mass, xpos):
return (np.sum(mass * xpos, 0) / np.sum(mass))[0]
class HumanoidGoalKeeper(HumanoidKicker):
| 70 | 142 | 474 | 11 | 59 | MachengShen/torchbeast | multiagent-competition/gym-compete/gym_compete/new_envs/agents/humanoid_goalkeeper.py | Python | HumanoidGoalKeeper | HumanoidGoalKeeper | 11 | 59 | 11 | 12 | 2731c78b3d97991184fec01f3c478b24c85533a8 | bigcode/the-stack | train |
5b0562d328dc9d1b96c5b3e4 | train | function | def lockdown_widget(lockdown_at, start_date, lockdown_label_y, ymax, lockdown_label, ax, ls='--', xshift=0.0):
# Convert x-axis into posix timestamps and use pandas to plot as dates
lckdn_x = days_to_datetime(lockdown_at, start_date=start_date)
ax.plot([lckdn_x, lckdn_x], [0, ymax], linewidth=2.5, linestyle... | def lockdown_widget(lockdown_at, start_date, lockdown_label_y, ymax, lockdown_label, ax, ls='--', xshift=0.0):
# Convert x-axis into posix timestamps and use pandas to plot as dates
| lckdn_x = days_to_datetime(lockdown_at, start_date=start_date)
ax.plot([lckdn_x, lckdn_x], [0, ymax], linewidth=2.5, linestyle=ls,
color='black', label='_nolegend_')
lockdown_label_y = lockdown_label_y or ymax*0.4
ax.text(x=lckdn_x - pd.Timedelta(2.1 + xshift, unit='d'),
y=lockdo... | _date).timestamp()
return pd.to_datetime(ts, unit='s')
def lockdown_widget(lockdown_at, start_date, lockdown_label_y, ymax, lockdown_label, ax, ls='--', xshift=0.0):
# Convert x-axis into posix timestamps and use pandas to plot as dates
| 64 | 64 | 165 | 49 | 15 | MPI-SWS/simulator | sim/lib/plot.py | Python | lockdown_widget | lockdown_widget | 58 | 65 | 58 | 59 | 33285af0572d9caa9d98074cb91ea3d18bde1997 | bigcode/the-stack | train |
887a52187496c6b4880db643 | train | class | class Plotter(object):
"""
Plotting class
"""
def __init__(self):
# plot constants
# check out https://colorhunt.co/
self.color_expo = '#ffcc00'
self.color_iasy = '#00a8cc'
self.color_ipre = '#005082'
self.color_isym = '#000839'
self.color_test... | class Plotter(object):
| """
Plotting class
"""
def __init__(self):
# plot constants
# check out https://colorhunt.co/
self.color_expo = '#ffcc00'
self.color_iasy = '#00a8cc'
self.color_ipre = '#005082'
self.color_isym = '#000839'
self.color_testing = '#ffa41b'
... | _widget(lockdown_at, start_date, lockdown_label_y, ymax, lockdown_label, ax, ls='--', xshift=0.0):
# Convert x-axis into posix timestamps and use pandas to plot as dates
lckdn_x = days_to_datetime(lockdown_at, start_date=start_date)
ax.plot([lckdn_x, lckdn_x], [0, ymax], linewidth=2.5, linestyle=ls,
... | 256 | 256 | 11,672 | 5 | 251 | MPI-SWS/simulator | sim/lib/plot.py | Python | Plotter | Plotter | 75 | 1,146 | 75 | 75 | 6dd7d33c28ee760c42cc86c16cc51ab61509fe92 | bigcode/the-stack | train |
d0f43cb8527fdfbf36c91f83 | train | function | def days_to_datetime(arr, start_date):
# timestamps
ts = arr * 24 * 60 * 60 + pd.Timestamp(start_date).timestamp()
return pd.to_datetime(ts, unit='s')
| def days_to_datetime(arr, start_date):
# timestamps
| ts = arr * 24 * 60 * 60 + pd.Timestamp(start_date).timestamp()
return pd.to_datetime(ts, unit='s')
| xtick.labelsize": 14,
"ytick.labelsize": 14,
"lines.linewidth": 2.0,
"lines.markersize": 4,
"grid.linewidth": 0.4,
})
def days_to_datetime(arr, start_date):
# timestamps
| 64 | 64 | 45 | 13 | 51 | MPI-SWS/simulator | sim/lib/plot.py | Python | days_to_datetime | days_to_datetime | 52 | 55 | 52 | 53 | 226f6ade26d90826f56056e2acbc588f8b040137 | bigcode/the-stack | train |
544ba757397327e3e7158c83 | train | function | def target_widget(show_target,start_date, ax):
txx = np.linspace(0, show_target.shape[0] - 1, num=show_target.shape[0])
txx = days_to_datetime(txx, start_date=start_date)
ax.plot(txx, show_target, linewidth=4, linestyle='', marker='X', ms=6,
color='red', label='COVID-19 case data')
| def target_widget(show_target,start_date, ax):
| txx = np.linspace(0, show_target.shape[0] - 1, num=show_target.shape[0])
txx = days_to_datetime(txx, start_date=start_date)
ax.plot(txx, show_target, linewidth=4, linestyle='', marker='X', ms=6,
color='red', label='COVID-19 case data')
| _y = lockdown_label_y or ymax*0.4
ax.text(x=lckdn_x - pd.Timedelta(2.1 + xshift, unit='d'),
y=lockdown_label_y, s=lockdown_label, rotation=90)
def target_widget(show_target,start_date, ax):
| 64 | 64 | 88 | 10 | 54 | MPI-SWS/simulator | sim/lib/plot.py | Python | target_widget | target_widget | 68 | 72 | 68 | 68 | f751433b43dd1da0dc7f68734d735468328af095 | bigcode/the-stack | train |
0e231f8e1fec462791fb6c87 | train | class | class SyncCommand(TransferCommand):
command = "sync"
usage = (
"%(prog)s <source-path> <dest-path> [-c <conf_file> --delete "
"--exclude <pattern value> --include <pattern value> --rate-limit <pattern value>]"
)
@classmethod
def add_transfer_arguments(cls, parser):
parser.a... | class SyncCommand(TransferCommand):
| command = "sync"
usage = (
"%(prog)s <source-path> <dest-path> [-c <conf_file> --delete "
"--exclude <pattern value> --include <pattern value> --rate-limit <pattern value>]"
)
@classmethod
def add_transfer_arguments(cls, parser):
parser.add_argument(
"--delete",
... | # -*- coding: utf-8 -*-
# =========================================================================
# Copyright (C) 2016 Yunify, Inc.
# -------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this work except in compli... | 216 | 256 | 856 | 7 | 208 | frostyplanet/qsctl | qingstor/qsctl/commands/sync.py | Python | SyncCommand | SyncCommand | 30 | 139 | 30 | 31 | 4b7c056b5932df6c65416868b3b3c4830d3042f1 | bigcode/the-stack | train |
2d4846b0715752b44b026ec3 | train | function | def cv_evaluate(clf, train_data, train_labels):
""" evaluation with cross validation in classifiers, by default: 10-CV.
report the precision, recall, and f1-measure
Args:
--------
clf: the classifier
train_data: the training data
train_labels: the training labels
Returns:
--------
"""
print("Using cross va... | def cv_evaluate(clf, train_data, train_labels):
| """ evaluation with cross validation in classifiers, by default: 10-CV.
report the precision, recall, and f1-measure
Args:
--------
clf: the classifier
train_data: the training data
train_labels: the training labels
Returns:
--------
"""
print("Using cross validation")
scoring = ['precision', 'recall', 'f... | author__ = 'Shilin He'
import sys
sys.path.append('/loglizer')#drain __init__.py
from sklearn.metrics import precision_recall_fscore_support
import numpy as np
from sklearn.model_selection import cross_validate
def cv_evaluate(clf, train_data, train_labels):
| 64 | 64 | 205 | 13 | 50 | elieser1101/loglizer | utils/evaluation.py | Python | cv_evaluate | cv_evaluate | 12 | 29 | 12 | 12 | d8a79d28d26e025f0cd0c65ee2ecc5927eea5a6f | bigcode/the-stack | train |
d294669813374f1aabc97dbe | train | function | def evaluate(testing_labels, prediction):
""" evaluation with precision, recall, and f1-measure.
Args:
--------
testing_labels: labels of testing data
prediction: predicted labels of a model
Returns:
--------
"""
precision, recall, f1_score, _ = np.array(list(precision_recall_fscore_support(testing_labels, p... | def evaluate(testing_labels, prediction):
| """ evaluation with precision, recall, and f1-measure.
Args:
--------
testing_labels: labels of testing data
prediction: predicted labels of a model
Returns:
--------
"""
precision, recall, f1_score, _ = np.array(list(precision_recall_fscore_support(testing_labels, prediction)))[:, 1]
print('=' * 20, 'RESUL... | ['test_f1']], axis=1)
print('=' * 20, 'RESULT', '=' * 20)
print("Precision: %.6f, Recall: %.6f, F1_score: %.6f" % (precision, recall, f1_score))
def evaluate(testing_labels, prediction):
| 64 | 64 | 131 | 8 | 56 | elieser1101/loglizer | utils/evaluation.py | Python | evaluate | evaluate | 32 | 45 | 32 | 32 | e8a2c39284cb7cfb891377d60f96411fef0609c1 | bigcode/the-stack | train |
919b24f61a853e8612d76ecb | train | function | def moving_taiqi(arm=arm):
# Taiqi
print('Taiqi starts ...')
for _ in range(30):
axis_ = arm.upper_arm_axis.cross(arm.upper_arm_subaxis).norm()
arm.upper_arm_axis = arm.upper_arm_axis.rotate(
axis=axis_, angle=radians(2))
arm.upper_arm_subaxis = arm.upper_arm_subaxis.rota... | def moving_taiqi(arm=arm):
# Taiqi
| print('Taiqi starts ...')
for _ in range(30):
axis_ = arm.upper_arm_axis.cross(arm.upper_arm_subaxis).norm()
arm.upper_arm_axis = arm.upper_arm_axis.rotate(
axis=axis_, angle=radians(2))
arm.upper_arm_subaxis = arm.upper_arm_subaxis.rotate(
axis=axis_, angle=radia... | ))
scene.title = 'Arm v0'
scene.forward = vector(0, 0, -1)
scene.up = vector(1, 0, 0)
scene.range = 100
arm = Arm()
arm.init_parts()
def moving_taiqi(arm=arm):
# Taiqi
| 64 | 64 | 114 | 15 | 49 | listenzcc/3D_model_matlab | vpython_script/zcc_demo_body_v0.py | Python | moving_taiqi | moving_taiqi | 217 | 228 | 217 | 218 | 3e5a7d41dfa1282e138a23c9a46c0245253b6b12 | bigcode/the-stack | train |
4e11e6373d02c95918dcc31b | train | function | def moving_waizhan(arm=arm):
# Waizhan
print('Waizhan starts ...')
for _ in range(30):
arm.upper_arm_axis = arm.upper_arm_axis.rotate(
axis=arm.upper_arm_subaxis, angle=radians(-2))
rate(30)
arm.update_parts()
print('Waizhan done.')
| def moving_waizhan(arm=arm):
# Waizhan
| print('Waizhan starts ...')
for _ in range(30):
arm.upper_arm_axis = arm.upper_arm_axis.rotate(
axis=arm.upper_arm_subaxis, angle=radians(-2))
rate(30)
arm.update_parts()
print('Waizhan done.')
| =radians(2))
arm.upper_arm_subaxis = arm.upper_arm_subaxis.rotate(
axis=axis_, angle=radians(2))
rate(30)
arm.update_parts()
print('Taiqi done')
def moving_waizhan(arm=arm):
# Waizhan
| 64 | 64 | 79 | 17 | 47 | listenzcc/3D_model_matlab | vpython_script/zcc_demo_body_v0.py | Python | moving_waizhan | moving_waizhan | 231 | 239 | 231 | 232 | 800de8996c2f9ce592d2a0807b6c949cfacf73ab | bigcode/the-stack | train |
fb857fcec3ffe22ec2eab381 | train | function | def moving_quzhou(arm=arm):
# Quzhou
print('Quzhou starts ...')
for _ in range(30):
arm.small_arm_flex += 2
rate(30)
arm.update_parts()
print('Quzhou done.')
| def moving_quzhou(arm=arm):
# Quzhou
| print('Quzhou starts ...')
for _ in range(30):
arm.small_arm_flex += 2
rate(30)
arm.update_parts()
print('Quzhou done.')
| range(30):
arm.upper_arm_axis = arm.upper_arm_axis.rotate(
axis=arm.upper_arm_subaxis, angle=radians(-2))
rate(30)
arm.update_parts()
print('Waizhan done.')
def moving_quzhou(arm=arm):
# Quzhou
| 63 | 64 | 57 | 14 | 49 | listenzcc/3D_model_matlab | vpython_script/zcc_demo_body_v0.py | Python | moving_quzhou | moving_quzhou | 242 | 249 | 242 | 243 | 79a9798a3358239c1ba3d891f2bccaba442cfc67 | bigcode/the-stack | train |
16fa81ddb7a40edaf3122a49 | train | class | class Arm:
def __init__(self):
self.up = vector(1, 0, 0)
self.right = vector(0, 1, 0)
self.front = vector(0, 0, 1)
self.note_len = 20
self.sketch_rad = 3
self.heart_pos = vector(0, 0, 0)
self.heart_rad = 5
self.shoulder_pos = vector(0, 30, 0)
... | class Arm:
| def __init__(self):
self.up = vector(1, 0, 0)
self.right = vector(0, 1, 0)
self.front = vector(0, 0, 1)
self.note_len = 20
self.sketch_rad = 3
self.heart_pos = vector(0, 0, 0)
self.heart_rad = 5
self.shoulder_pos = vector(0, 30, 0)
self.shou... | # coding: utf-8
from vpython import arrow, box, color, cylinder, radians, rate, scene, sphere, vector
class Arm:
| 32 | 256 | 1,773 | 3 | 28 | listenzcc/3D_model_matlab | vpython_script/zcc_demo_body_v0.py | Python | Arm | Arm | 6 | 206 | 6 | 6 | f0869fe1de32a976a50eb02ee00eb4428440c962 | bigcode/the-stack | train |
2222450a2c41610c7012b9f7 | train | function | def moving_backing(arm=arm):
# Back
print('Backing...')
while arm.back_parts():
rate(30)
arm.update_parts()
print('Baking done')
| def moving_backing(arm=arm):
# Back
| print('Backing...')
while arm.back_parts():
rate(30)
arm.update_parts()
print('Baking done')
| arm):
# Quzhou
print('Quzhou starts ...')
for _ in range(30):
arm.small_arm_flex += 2
rate(30)
arm.update_parts()
print('Quzhou done.')
def moving_backing(arm=arm):
# Back
| 63 | 64 | 41 | 13 | 50 | listenzcc/3D_model_matlab | vpython_script/zcc_demo_body_v0.py | Python | moving_backing | moving_backing | 252 | 258 | 252 | 253 | 8368b0e6ec636d9bea07ab6d5fde60d7426322fb | bigcode/the-stack | train |
1d965b31243123bf8f5ce656 | train | function | def create_tuple_placeholders_with_default(inputs, extra_dims, shape):
if isinstance(shape, int):
result = tf.placeholder_with_default(
inputs, list(extra_dims) + [shape])
else:
subplaceholders = [create_tuple_placeholders_with_default(
subinputs, extra_dims, subshape)
for... | def create_tuple_placeholders_with_default(inputs, extra_dims, shape):
| if isinstance(shape, int):
result = tf.placeholder_with_default(
inputs, list(extra_dims) + [shape])
else:
subplaceholders = [create_tuple_placeholders_with_default(
subinputs, extra_dims, subshape)
for subinputs, subshape in zip(inputs, shape)]
t = type(shape)
if ... | # optimizer = tf.train.RMSPropOptimizer(learning_rate, decay_rate)
optimizer = tf.train.AdamOptimizer(self.learning_rate)
self.train_op = optimizer.apply_gradients(zip(grads, tvars),
global_step=self.global_step)
def create_tuple_placeholders_with_default(in... | 64 | 64 | 115 | 14 | 50 | is8ac/aural2 | gen_train_graph.py | Python | create_tuple_placeholders_with_default | create_tuple_placeholders_with_default | 234 | 247 | 234 | 234 | e7689b3a184a7292d6a9b1b5c2ac03beef049115 | bigcode/the-stack | train |
c7a27c2d1d870e1ad588f0a6 | train | class | class CharRNN(object):
"""Character RNN model."""
def __init__(self, params, is_training=True, use_batch=True, seq_len=7):
batch_size = params['batch_size']
num_unrollings = seq_len
if not use_batch:
batch_size = 1
hidden_size = params['hidden_size']
max_grad_norm = params['max_grad_norm'... | class CharRNN(object):
| """Character RNN model."""
def __init__(self, params, is_training=True, use_batch=True, seq_len=7):
batch_size = params['batch_size']
num_unrollings = seq_len
if not use_batch:
batch_size = 1
hidden_size = params['hidden_size']
max_grad_norm = params['max_grad_norm']
num_layers = para... | finalStateNames.append(i.c.op.name)
finalStateNames.append(i.h.op.name)
seq_initialStateConst = tf.constant(initialStateNames, name="initial_state_names")
seq_finalStateNamesConst = tf.constant(finalStateNames, name="final_state_names")
with tf.Session(gra... | 256 | 256 | 1,322 | 6 | 250 | is8ac/aural2 | gen_train_graph.py | Python | CharRNN | CharRNN | 99 | 231 | 99 | 99 | 94c1408fe4e81c01cfd57a2d7e89cb190e49e470 | bigcode/the-stack | train |
2ffcc2eabf8ecabdf6481d8d | train | function | def create_tuple_placeholders(dtype, extra_dims, shape):
if isinstance(shape, int):
result = tf.placeholder(dtype, list(extra_dims) + [shape])
else:
subplaceholders = [create_tuple_placeholders(dtype, extra_dims, subshape)
for subshape in shape]
t = type(shape)
# Handles both... | def create_tuple_placeholders(dtype, extra_dims, shape):
| if isinstance(shape, int):
result = tf.placeholder(dtype, list(extra_dims) + [shape])
else:
subplaceholders = [create_tuple_placeholders(dtype, extra_dims, subshape)
for subshape in shape]
t = type(shape)
# Handles both tuple and LSTMStateTuple.
if t == tuple:
resul... | subshape)
for subinputs, subshape in zip(inputs, shape)]
t = type(shape)
if t == tuple:
result = t(subplaceholders)
else:
result = t(*subplaceholders)
return result
def create_tuple_placeholders(dtype, extra_dims, shape):
| 64 | 64 | 109 | 12 | 51 | is8ac/aural2 | gen_train_graph.py | Python | create_tuple_placeholders | create_tuple_placeholders | 250 | 263 | 250 | 250 | 8ca15e98e9a2f4d03ef9369b008fb8bbaac2f137 | bigcode/the-stack | train |
169a74e2e8b8085afea1bb58 | train | function | def main():
params = {
"batch_size": 7,
"dropout": 0.0,
"embedding_size": 0,
"hidden_size": 64,
"input_dropout": 0.0,
"input_size": 13,
"learning_rate": 0.0003,
"max_grad_norm": 5.0,
"num_layers": 2,
... | def main():
| params = {
"batch_size": 7,
"dropout": 0.0,
"embedding_size": 0,
"hidden_size": 64,
"input_dropout": 0.0,
"input_size": 13,
"learning_rate": 0.0003,
"max_grad_norm": 5.0,
"num_layers": 2,
"num_unr... | # Descended from https://github.com/sherjilozair/char-rnn-tensorflow
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import argparse
import codecs
import json
import logging
import os
import shutil
import sys
from tensorflow.python.framework import graph_util
import numpy as np
from six import iteritems
import time
i... | 87 | 205 | 686 | 3 | 83 | is8ac/aural2 | gen_train_graph.py | Python | main | main | 19 | 92 | 19 | 19 | de4f4b79f20cb16b7ab95264f1c9010538dba7bf | bigcode/the-stack | train |
b443e52f072f7d547293692c | train | class | class TensorQuantile(TensorOperand, TensorOperandMixin):
__slots__ = 'q_error_msg',
_op_type_ = OperandDef.QUANTILE
_a = KeyField('a')
_q = AnyField('q')
_axis = AnyField('axis')
_out = KeyField('out')
_overwrite_input = BoolField('overwrite_input')
_interpolation = StringField('interpo... | class TensorQuantile(TensorOperand, TensorOperandMixin):
| __slots__ = 'q_error_msg',
_op_type_ = OperandDef.QUANTILE
_a = KeyField('a')
_q = AnyField('q')
_axis = AnyField('axis')
_out = KeyField('out')
_overwrite_input = BoolField('overwrite_input')
_interpolation = StringField('interpolation')
_keepdims = BoolField('keepdims')
def _... | axis, 0)
if zerod:
x1 = x1.squeeze(0)
x2 = x2.squeeze(0)
if out is not None:
r = add(x1, x2, out=out)
else:
r = add(x1, x2)
if isinstance(n, TENSOR_TYPE):
if zerod:
if ap.ndim == 1:
r.data = where(tensor_... | 255 | 256 | 1,181 | 12 | 243 | hxri/mars | mars/tensor/statistics/quantile.py | Python | TensorQuantile | TensorQuantile | 184 | 329 | 184 | 184 | e6b5a5825425177b2d143a0cab3e1e2061392a9b | bigcode/the-stack | train |
4359e32b3c7db15e61d1a680 | train | function | def _quantile_ureduce_func(a, q, axis=None, out=None, overwrite_input=False,
interpolation='linear', keepdims=False):
a = astensor(a)
out = astensor(out) if out is not None else None
if q.ndim == 0:
# Do not allow 0-d arrays because following code fails for scalar
... | def _quantile_ureduce_func(a, q, axis=None, out=None, overwrite_input=False,
interpolation='linear', keepdims=False):
| a = astensor(a)
out = astensor(out) if out is not None else None
if q.ndim == 0:
# Do not allow 0-d arrays because following code fails for scalar
zerod = True
q = q[None]
else:
zerod = False
# prepare a for partitioning
if overwrite_input:
if axis is No... | from ...utils import has_unknown_shape
from ..datasource import tensor as astensor
from ..base import moveaxis, where
from ..indexing import take
from ..arithmetic import isnan, add
from ..reduction import any as tensor_any
from ..operands import TensorOperand, TensorOperandMixin
from ..core import TENSOR_TYPE, TENSOR_... | 256 | 256 | 1,080 | 31 | 224 | hxri/mars | mars/tensor/statistics/quantile.py | Python | _quantile_ureduce_func | _quantile_ureduce_func | 50 | 178 | 50 | 51 | 454aed2dc1c6a4e38b71942fc42b6fe9e68b1b48 | bigcode/the-stack | train |
edf532e6026cf5725cb1a94c | train | function | def _quantile_unchecked(a, q, axis=None, out=None, overwrite_input=False,
interpolation='linear', keepdims=False,
q_error_msg=None, handle_non_numeric=None):
a = astensor(a)
raw_dtype = a.dtype
need_view_back = False
if handle_non_numeric and not np.issubd... | def _quantile_unchecked(a, q, axis=None, out=None, overwrite_input=False,
interpolation='linear', keepdims=False,
q_error_msg=None, handle_non_numeric=None):
| a = astensor(a)
raw_dtype = a.dtype
need_view_back = False
if handle_non_numeric and not np.issubdtype(a.dtype, np.number):
# enable handle_non_numeric is often used
# to handle the datetime-like dtype
a = a.astype('i8')
need_view_back = True
if isinstance(q, ENTITY_T... | 0]
out = inputs[-1].copy() if op.out is not None else None
with device(device_id):
ctx[op.outputs[0].key] = xp.quantile(a, q=op.q, axis=op.axis, out=out,
interpolation=op.interpolation,
keepdim... | 132 | 133 | 445 | 40 | 92 | hxri/mars | mars/tensor/statistics/quantile.py | Python | _quantile_unchecked | _quantile_unchecked | 335 | 380 | 335 | 337 | 2a95c0d03303020e2a9ec2166960be02425f1eaf | bigcode/the-stack | train |
a1a6a0a31bd0b776968735fb | train | function | def _quantile_is_valid(q):
# avoid expensive reductions, relevant for arrays with < O(1000) elements
if q.ndim == 1 and q.size < 10:
for i in range(q.size):
if q[i] < 0.0 or q[i] > 1.0:
return False
else:
# faster than any()
if np.count_nonzero(q < 0.0) or... | def _quantile_is_valid(q):
# avoid expensive reductions, relevant for arrays with < O(1000) elements
| if q.ndim == 1 and q.size < 10:
for i in range(q.size):
if q[i] < 0.0 or q[i] > 1.0:
return False
else:
# faster than any()
if np.count_nonzero(q < 0.0) or np.count_nonzero(q > 1.0):
return False
return True
| _TYPE, TENSOR_CHUNK_TYPE, TensorOrder
from ..utils import check_out_param
from ..array_utils import as_same_device, device
from .core import _ureduce
def _quantile_is_valid(q):
# avoid expensive reductions, relevant for arrays with < O(1000) elements
| 64 | 64 | 115 | 26 | 37 | hxri/mars | mars/tensor/statistics/quantile.py | Python | _quantile_is_valid | _quantile_is_valid | 37 | 47 | 37 | 38 | e64bc0b53c4f0caee5f391e140a6a031676bfd64 | bigcode/the-stack | train |
31eccee93cce0f763d0599a9 | train | function | def quantile(a, q, axis=None, out=None, overwrite_input=False,
interpolation='linear', keepdims=False, **kw):
"""
Compute the q-th quantile of the data along the specified axis.
Parameters
----------
a : array_like
Input tensor or object that can be converted to a tensor.
q... | def quantile(a, q, axis=None, out=None, overwrite_input=False,
interpolation='linear', keepdims=False, **kw):
| """
Compute the q-th quantile of the data along the specified axis.
Parameters
----------
a : array_like
Input tensor or object that can be converted to a tensor.
q : array_like of float
Quantile or sequence of quantiles to compute, which must be between
0 and 1 inclusiv... | , got {type(out)}')
if interpolation not in INTERPOLATION_TYPES:
raise ValueError("interpolation can only be 'linear', 'lower' "
"'higher', 'midpoint', or 'nearest'")
# infer dtype
q_tiny = np.random.rand(2 if q.size % 2 == 0 else 1).astype(q.dtype)
if handle_non_numer... | 256 | 256 | 1,169 | 29 | 226 | hxri/mars | mars/tensor/statistics/quantile.py | Python | quantile | quantile | 383 | 489 | 383 | 384 | f83752d092c248225e582372657cab846849d512 | bigcode/the-stack | train |
5a59441185b960c5ecf8708e | train | function | def send_email(emailto, title, content):
from DjangoBlog.blog_signals import send_email_signal
send_email_signal.send(
send_email.__class__,
emailto=emailto,
title=title,
content=content)
| def send_email(emailto, title, content):
| from DjangoBlog.blog_signals import send_email_signal
send_email_signal.send(
send_email.__class__,
emailto=emailto,
title=title,
content=content)
| follow, text)
class CommonMarkdown():
@staticmethod
def get_markdown(value):
renderer = BlogMarkDownRenderer(inlinestyles=False)
mdp = mistune.Markdown(escape=True, renderer=renderer)
return mdp(value)
def send_email(emailto, title, content):
| 64 | 64 | 50 | 10 | 54 | huulinhcvp/DjangoBlog | DjangoBlog/utils.py | Python | send_email | send_email | 181 | 187 | 181 | 181 | 8f8a1b4775679e8de279421af302619c76f3d5cf | bigcode/the-stack | train |
52c088ffb79b83f733b726b2 | train | class | class BlogMarkDownRenderer(mistune.Renderer):
'''
markdown渲染
'''
def block_code(self, text, lang=None):
# renderer has an options
inlinestyles = self.options.get('inlinestyles')
linenos = self.options.get('linenos')
return block_code(text, lang, inlinestyles, linenos)
... | class BlogMarkDownRenderer(mistune.Renderer):
| '''
markdown渲染
'''
def block_code(self, text, lang=None):
# renderer has an options
inlinestyles = self.options.get('inlinestyles')
linenos = self.options.get('linenos')
return block_code(text, lang, inlinestyles, linenos)
def autolink(self, link, is_email=False):
... | :
return '<div class="highlight">%s</div>\n' % code
return code
except BaseException:
return '<pre class="%s"><code>%s</code></pre>\n' % (
lang, mistune.escape(text)
)
@cache_decorator()
def get_current_site():
site = Site.objects.get_current()
return site
c... | 90 | 90 | 303 | 11 | 78 | huulinhcvp/DjangoBlog | DjangoBlog/utils.py | Python | BlogMarkDownRenderer | BlogMarkDownRenderer | 137 | 169 | 137 | 137 | 23e9571ae0d49c644f3142208b1ae43fc99050b5 | bigcode/the-stack | train |
959cb312c3803c0b9103bc88 | train | function | def block_code(text, lang, inlinestyles=False, linenos=False):
'''
markdown代码高亮
:param text:
:param lang:
:param inlinestyles:
:param linenos:
:return:
'''
if not lang:
text = text.strip()
return u'<pre><code>%s</code></pre>\n' % mistune.escape(text)
try:
... | def block_code(text, lang, inlinestyles=False, linenos=False):
| '''
markdown代码高亮
:param text:
:param lang:
:param inlinestyles:
:param linenos:
:return:
'''
if not lang:
text = text.strip()
return u'<pre><code>%s</code></pre>\n' % mistune.escape(text)
try:
lexer = get_lexer_by_name(lang, stripall=True)
formatt... | key_prefix, cache=cache)
if key:
logger.info('expire_view_cache:get key:{path}'.format(path=path))
if cache.get(key):
cache.delete(key)
return True
return False
def block_code(text, lang, inlinestyles=False, linenos=False):
| 64 | 64 | 199 | 17 | 46 | huulinhcvp/DjangoBlog | DjangoBlog/utils.py | Python | block_code | block_code | 103 | 128 | 103 | 103 | f8a07418e778fcd31582cb25a1a2c5906d4d3966 | bigcode/the-stack | train |
985d369be88f4dabf7312640 | train | function | @cache_decorator()
def get_current_site():
site = Site.objects.get_current()
return site
| @cache_decorator()
def get_current_site():
| site = Site.objects.get_current()
return site
| '<div class="highlight">%s</div>\n' % code
return code
except BaseException:
return '<pre class="%s"><code>%s</code></pre>\n' % (
lang, mistune.escape(text)
)
@cache_decorator()
def get_current_site():
| 64 | 64 | 22 | 10 | 54 | huulinhcvp/DjangoBlog | DjangoBlog/utils.py | Python | get_current_site | get_current_site | 131 | 134 | 131 | 132 | 1ae3258c688fafb309449b8bccc3802324981ce0 | bigcode/the-stack | train |
81004f220be5c1a76a4a8fbc | train | function | def get_blog_setting():
value = cache.get('get_blog_setting')
if value:
return value
else:
from blog.models import BlogSettings
if not BlogSettings.objects.count():
setting = BlogSettings()
setting.sitename = 'DjangoBlog'
setting.site_description =... | def get_blog_setting():
| value = cache.get('get_blog_setting')
if value:
return value
else:
from blog.models import BlogSettings
if not BlogSettings.objects.count():
setting = BlogSettings()
setting.sitename = 'DjangoBlog'
setting.site_description = 'Django-based blog syst... | =title,
content=content)
def parse_dict_to_url(dict):
from urllib.parse import quote
url = '&'.join(['{}={}'.format(quote(k, safe='/'), quote(v, safe='/'))
for k, v in dict.items()])
return url
def get_blog_setting():
| 64 | 64 | 198 | 5 | 58 | huulinhcvp/DjangoBlog | DjangoBlog/utils.py | Python | get_blog_setting | get_blog_setting | 197 | 221 | 197 | 197 | 2f5cc9c49a13c587b3182430d696869ae88007d9 | bigcode/the-stack | train |
5aa7c0ed3fd5f494955c8445 | train | function | def get_sha256(str):
m = sha256(str.encode('utf-8'))
return m.hexdigest()
| def get_sha256(str):
| m = sha256(str.encode('utf-8'))
return m.hexdigest()
|
import logging
import requests
import uuid
import os
logger = logging.getLogger(__name__)
def get_max_articleid_commentid():
from blog.models import Article
from comments.models import Comment
return (Article.objects.latest().pk, Comment.objects.latest().pk)
def get_sha256(str):
| 64 | 64 | 24 | 6 | 58 | huulinhcvp/DjangoBlog | DjangoBlog/utils.py | Python | get_sha256 | get_sha256 | 37 | 39 | 37 | 37 | 1d7455b3e9030bab4106667d84dff4a26d37e55b | bigcode/the-stack | train |
1135e30fda9c3f14da827eb0 | train | function | def parse_dict_to_url(dict):
from urllib.parse import quote
url = '&'.join(['{}={}'.format(quote(k, safe='/'), quote(v, safe='/'))
for k, v in dict.items()])
return url
| def parse_dict_to_url(dict):
| from urllib.parse import quote
url = '&'.join(['{}={}'.format(quote(k, safe='/'), quote(v, safe='/'))
for k, v in dict.items()])
return url
| )
return mdp(value)
def send_email(emailto, title, content):
from DjangoBlog.blog_signals import send_email_signal
send_email_signal.send(
send_email.__class__,
emailto=emailto,
title=title,
content=content)
def parse_dict_to_url(dict):
| 64 | 64 | 51 | 7 | 57 | huulinhcvp/DjangoBlog | DjangoBlog/utils.py | Python | parse_dict_to_url | parse_dict_to_url | 190 | 194 | 190 | 190 | 4f6aeb6d135526503ba7a91ae0cca051733a6e88 | bigcode/the-stack | train |
07cdeced8d74ba7d8e357da1 | train | class | class CommonMarkdown():
@staticmethod
def get_markdown(value):
renderer = BlogMarkDownRenderer(inlinestyles=False)
mdp = mistune.Markdown(escape=True, renderer=renderer)
return mdp(value)
| class CommonMarkdown():
@staticmethod
| def get_markdown(value):
renderer = BlogMarkDownRenderer(inlinestyles=False)
mdp = mistune.Markdown(escape=True, renderer=renderer)
return mdp(value)
| %s>%s</a>' % (link, nofollow, text)
title = escape(title, quote=True)
return '<a href="%s" title="%s" %s>%s</a>' % (
link, title, nofollow, text)
class CommonMarkdown():
@staticmethod
| 64 | 64 | 50 | 8 | 56 | huulinhcvp/DjangoBlog | DjangoBlog/utils.py | Python | CommonMarkdown | CommonMarkdown | 172 | 178 | 172 | 173 | 3a15cf58d42ee6216a924de5ce2dcaabddfd92f6 | bigcode/the-stack | train |
1beec465eb2ea698c162f22c | train | function | def delete_view_cache(prefix, keys):
from django.core.cache.utils import make_template_fragment_key
key = make_template_fragment_key(prefix, keys)
cache.delete(key)
| def delete_view_cache(prefix, keys):
| from django.core.cache.utils import make_template_fragment_key
key = make_template_fragment_key(prefix, keys)
cache.delete(key)
| .models import LinkShowType
keys = (
make_template_fragment_key(
'sidebar', [
username + x]) for x in LinkShowType.values)
for k in keys:
logger.info('delete sidebar key:' + k)
cache.delete(k)
def delete_view_cache(prefix, keys):
| 64 | 64 | 36 | 8 | 56 | huulinhcvp/DjangoBlog | DjangoBlog/utils.py | Python | delete_view_cache | delete_view_cache | 274 | 277 | 274 | 274 | 7ab5f06c5fc17866857d3f922ef67c08a3ac1b9a | bigcode/the-stack | train |
663ec1e43fb3b3abbf4a8727 | train | function | def expire_view_cache(path, servername, serverport, key_prefix=None):
'''
刷新视图缓存
:param path:url路径
:param servername:host
:param serverport:端口
:param key_prefix:前缀
:return:是否成功
'''
from django.http import HttpRequest
from django.utils.cache import get_cache_key
request = Htt... | def expire_view_cache(path, servername, serverport, key_prefix=None):
| '''
刷新视图缓存
:param path:url路径
:param servername:host
:param serverport:端口
:param key_prefix:前缀
:return:是否成功
'''
from django.http import HttpRequest
from django.utils.cache import get_cache_key
request = HttpRequest()
request.META = {'SERVER_NAME': servername, 'SERVER_PORT... | args, **kwargs)
if value is None:
cache.set(key, '__default_cache_value__', expiration)
else:
cache.set(key, value, expiration)
return value
return news
return wrapper
def expire_view_cache(path, servername, serverport... | 64 | 64 | 176 | 16 | 47 | huulinhcvp/DjangoBlog | DjangoBlog/utils.py | Python | expire_view_cache | expire_view_cache | 78 | 100 | 78 | 78 | e88f7802246ed3a75650bf66eb68a8de10c56cf1 | bigcode/the-stack | train |
ab59d41e72de69ed7b9502cd | train | function | def save_user_avatar(url):
'''
保存用户头像
:param url:头像url
:return: 本地路径
'''
setting = get_blog_setting()
logger.info(url)
try:
imgname = url.split('/')[-1]
if imgname:
path = r'{basedir}/avatar/{img}'.format(
basedir=setting.resource_path, img=img... | def save_user_avatar(url):
| '''
保存用户头像
:param url:头像url
:return: 本地路径
'''
setting = get_blog_setting()
logger.info(url)
try:
imgname = url.split('/')[-1]
if imgname:
path = r'{basedir}/avatar/{img}'.format(
basedir=setting.resource_path, img=imgname)
if os.pat... | setting.sidebar_comment_count = 5
setting.show_google_adsense = False
setting.open_site_comment = True
setting.analyticscode = ''
setting.beiancode = ''
setting.show_gongan_code = False
setting.save()
value = BlogSettings.object... | 90 | 90 | 303 | 6 | 83 | huulinhcvp/DjangoBlog | DjangoBlog/utils.py | Python | save_user_avatar | save_user_avatar | 224 | 259 | 224 | 224 | 617466123ccfbf084c244755786761ac4d61fa60 | bigcode/the-stack | train |
f89bd6295d1abe2f464b39ad | train | function | def get_max_articleid_commentid():
from blog.models import Article
from comments.models import Comment
return (Article.objects.latest().pk, Comment.objects.latest().pk)
| def get_max_articleid_commentid():
| from blog.models import Article
from comments.models import Comment
return (Article.objects.latest().pk, Comment.objects.latest().pk)
|
from mistune import escape, escape_link
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import html
import logging
import requests
import uuid
import os
logger = logging.getLogger(__name__)
def get_max_articleid_commentid():
| 64 | 64 | 37 | 8 | 56 | huulinhcvp/DjangoBlog | DjangoBlog/utils.py | Python | get_max_articleid_commentid | get_max_articleid_commentid | 31 | 34 | 31 | 31 | 2623e75ffad86cbe1de9e5e9bbe31544c2b8002f | bigcode/the-stack | train |
f466ee3185b0c806899e87fc | train | function | def cache_decorator(expiration=3 * 60):
def wrapper(func):
def news(*args, **kwargs):
try:
view = args[0]
key = view.get_cache_key()
except BaseException:
key = None
if not key:
unique_str = repr((func, args,... | def cache_decorator(expiration=3 * 60):
| def wrapper(func):
def news(*args, **kwargs):
try:
view = args[0]
key = view.get_cache_key()
except BaseException:
key = None
if not key:
unique_str = repr((func, args, kwargs))
m = sha256(un... | id_commentid():
from blog.models import Article
from comments.models import Comment
return (Article.objects.latest().pk, Comment.objects.latest().pk)
def get_sha256(str):
m = sha256(str.encode('utf-8'))
return m.hexdigest()
def cache_decorator(expiration=3 * 60):
| 69 | 69 | 233 | 12 | 57 | huulinhcvp/DjangoBlog | DjangoBlog/utils.py | Python | cache_decorator | cache_decorator | 42 | 75 | 42 | 42 | 8da0fbe3f5c119e1ce8901474625080d387b76b9 | bigcode/the-stack | train |
ba66e6521093208dc0be1259 | train | function | def delete_sidebar_cache(username):
from django.core.cache.utils import make_template_fragment_key
from blog.models import LinkShowType
keys = (
make_template_fragment_key(
'sidebar', [
username + x]) for x in LinkShowType.values)
for k in keys:
logger.info('d... | def delete_sidebar_cache(username):
| from django.core.cache.utils import make_template_fragment_key
from blog.models import LinkShowType
keys = (
make_template_fragment_key(
'sidebar', [
username + x]) for x in LinkShowType.values)
for k in keys:
logger.info('delete sidebar key:' + k)
cac... | basepath + savefilename)
with open(basepath + savefilename, 'wb+') as file:
file.write(rsp.content)
return 'https://resource.lylinux.net/avatar/' + savefilename
except Exception as e:
logger.error(e)
return url
def delete_sidebar_cache(username):
| 64 | 64 | 77 | 6 | 57 | huulinhcvp/DjangoBlog | DjangoBlog/utils.py | Python | delete_sidebar_cache | delete_sidebar_cache | 262 | 271 | 262 | 262 | a1c1622f44a91403c2d8b6c7c61983bfe6bc0135 | bigcode/the-stack | train |
01fd432c5655e977bf91638f | train | function | def test_cannot_register_crypto_twice():
"""Test we cannot register a crytpo twice."""
aea.crypto.registries.register_crypto(
"my_custom_crypto", entry_point="tests.data.custom_crypto:CustomCrypto"
)
with pytest.raises(AEAException, match="Cannot re-register id: 'my_custom_crypto'"):
ae... | def test_cannot_register_crypto_twice():
| """Test we cannot register a crytpo twice."""
aea.crypto.registries.register_crypto(
"my_custom_crypto", entry_point="tests.data.custom_crypto:CustomCrypto"
)
with pytest.raises(AEAException, match="Cannot re-register id: 'my_custom_crypto'"):
aea.crypto.registries.register_crypto(
... | 1 = aea.crypto.registries.make_crypto("my_custom_crypto")
assert type(my_crypto) == type(my_crypto_1)
assert my_crypto != my_crypto_1
aea.crypto.registries.crypto_registry.specs.pop("my_custom_crypto")
def test_cannot_register_crypto_twice():
| 64 | 64 | 117 | 9 | 55 | marcofavorito/agents-aea | tests/test_crypto/test_registry/test_crypto_registry.py | Python | test_cannot_register_crypto_twice | test_cannot_register_crypto_twice | 112 | 123 | 112 | 112 | 63a6716ae9e50282f613566c0e680c8098ff4215 | bigcode/the-stack | train |
0fb19f5ed6d270bc736390a0 | train | function | def test_make_fetchai():
"""Test the 'make' method for 'fetchai' crypto."""
fetchai_crypto = aea.crypto.registries.make_crypto(FETCHAI)
assert type(fetchai_crypto) == FetchAICrypto
# calling 'make' again will give a different object.
fetchai_crypto_1 = aea.crypto.registries.make_crypto(FETCHAI)
... | def test_make_fetchai():
| """Test the 'make' method for 'fetchai' crypto."""
fetchai_crypto = aea.crypto.registries.make_crypto(FETCHAI)
assert type(fetchai_crypto) == FetchAICrypto
# calling 'make' again will give a different object.
fetchai_crypto_1 = aea.crypto.registries.make_crypto(FETCHAI)
assert type(fetchai_cry... | from tests.conftest import COSMOS, ETHEREUM, FETCHAI
from tests.data.custom_crypto import CustomCrypto
logger = logging.getLogger(__name__)
forbidden_special_characters = "".join(
filter(lambda c: c not in "_:/.", string.punctuation)
)
def test_make_fetchai():
| 64 | 64 | 111 | 6 | 58 | marcofavorito/agents-aea | tests/test_crypto/test_registry/test_crypto_registry.py | Python | test_make_fetchai | test_make_fetchai | 46 | 55 | 46 | 46 | 9f76e93964fa083585606e3d244be30fc7cf3527 | bigcode/the-stack | train |
5d6a702a54378f60de50f93b | train | class | class TestRegisterWithMalformedId:
"""Test the error message when we try to register a crypto whose identifier is malformed."""
MESSAGE_REGEX = "Malformed .*: '.*'. It must be of the form '.*'."
def test_wrong_spaces(self):
"""Spaces not allowed in a Crypto ID."""
# beginning space
... | class TestRegisterWithMalformedId:
| """Test the error message when we try to register a crypto whose identifier is malformed."""
MESSAGE_REGEX = "Malformed .*: '.*'. It must be of the form '.*'."
def test_wrong_spaces(self):
"""Spaces not allowed in a Crypto ID."""
# beginning space
with pytest.raises(AEAException, m... | _point="path.to.module:SomeCrypto"
)
with pytest.raises(
AEAException,
match="A module (.*) was specified for the item but was not found",
):
aea.crypto.registries.make_crypto("some_crypto", module="some.module")
aea.crypto.registries.crypto_registry.specs.pop("some_crypto")
clas... | 82 | 82 | 274 | 7 | 75 | marcofavorito/agents-aea | tests/test_crypto/test_registry/test_crypto_registry.py | Python | TestRegisterWithMalformedId | TestRegisterWithMalformedId | 140 | 171 | 140 | 140 | 9c96f3e8c0a641fc4fd8c557a06e50f123a85de0 | bigcode/the-stack | train |
910bf44b833ed79a42cd54f1 | train | function | @mock.patch("importlib.import_module", side_effect=ImportError)
def test_import_error(*mocks):
"""Test import errors."""
aea.crypto.registries.register_crypto(
"some_crypto", entry_point="path.to.module:SomeCrypto"
)
with pytest.raises(
AEAException,
match="A module (.*) was spec... | @mock.patch("importlib.import_module", side_effect=ImportError)
def test_import_error(*mocks):
| """Test import errors."""
aea.crypto.registries.register_crypto(
"some_crypto", entry_point="path.to.module:SomeCrypto"
)
with pytest.raises(
AEAException,
match="A module (.*) was specified for the item but was not found",
):
aea.crypto.registries.make_crypto("some_c... | istries.register_crypto(
"my_custom_crypto", entry_point="tests.data.custom_crypto:CustomCrypto"
)
aea.crypto.registries.crypto_registry.specs.pop("my_custom_crypto")
@mock.patch("importlib.import_module", side_effect=ImportError)
def test_import_error(*mocks):
| 64 | 64 | 120 | 23 | 41 | marcofavorito/agents-aea | tests/test_crypto/test_registry/test_crypto_registry.py | Python | test_import_error | test_import_error | 126 | 137 | 126 | 127 | 69e234ff549aed22e8ea6f5e7a9311d329e68cf4 | bigcode/the-stack | train |
6aba219d1a58a1898d942ec2 | train | function | def test_make_ethereum():
"""Test the 'make' method for 'ethereum' crypto."""
ethereum_crypto = aea.crypto.registries.make_crypto(ETHEREUM)
assert type(ethereum_crypto) == EthereumCrypto
# calling 'make' again will give a different object.
ethereum_crypto_1 = aea.crypto.registries.make_crypto(ETHE... | def test_make_ethereum():
| """Test the 'make' method for 'ethereum' crypto."""
ethereum_crypto = aea.crypto.registries.make_crypto(ETHEREUM)
assert type(ethereum_crypto) == EthereumCrypto
# calling 'make' again will give a different object.
ethereum_crypto_1 = aea.crypto.registries.make_crypto(ETHEREUM)
assert type(ethe... | calling 'make' again will give a different object.
fetchai_crypto_1 = aea.crypto.registries.make_crypto(FETCHAI)
assert type(fetchai_crypto) == type(fetchai_crypto_1)
assert fetchai_crypto.address != fetchai_crypto_1
def test_make_ethereum():
| 64 | 64 | 107 | 6 | 57 | marcofavorito/agents-aea | tests/test_crypto/test_registry/test_crypto_registry.py | Python | test_make_ethereum | test_make_ethereum | 58 | 67 | 58 | 58 | 4a1e8dcb4968c8c46c42f1af719c2f104092da1c | bigcode/the-stack | train |
cbf52507b4e9e14a9484e09f | train | function | def test_register_custom_crypto():
"""Test the 'register' method with a custom crypto object."""
aea.crypto.registries.register_crypto(
"my_custom_crypto", entry_point="tests.data.custom_crypto:CustomCrypto"
)
assert (
aea.crypto.registries.crypto_registry.specs.get("my_custom_crypto")... | def test_register_custom_crypto():
| """Test the 'register' method with a custom crypto object."""
aea.crypto.registries.register_crypto(
"my_custom_crypto", entry_point="tests.data.custom_crypto:CustomCrypto"
)
assert (
aea.crypto.registries.crypto_registry.specs.get("my_custom_crypto") is not None
)
actual_spec ... | _crypto(COSMOS)
assert type(cosmos_crypto) == CosmosCrypto
# calling 'make' again will give a different object.
cosmos_crypto_1 = aea.crypto.registries.make_crypto(COSMOS)
assert type(cosmos_crypto) == type(cosmos_crypto_1)
assert cosmos_crypto.address != cosmos_crypto_1.address
def test_register_... | 80 | 80 | 268 | 6 | 73 | marcofavorito/agents-aea | tests/test_crypto/test_registry/test_crypto_registry.py | Python | test_register_custom_crypto | test_register_custom_crypto | 82 | 109 | 82 | 82 | d3c546b1b34b175ff1ed8dd206cd2c87fba3bdde | bigcode/the-stack | train |
903c73160e8bfe1640bc8556 | train | function | def test_make_cosmos():
"""Test the 'make' method for 'cosmos' crypto."""
cosmos_crypto = aea.crypto.registries.make_crypto(COSMOS)
assert type(cosmos_crypto) == CosmosCrypto
# calling 'make' again will give a different object.
cosmos_crypto_1 = aea.crypto.registries.make_crypto(COSMOS)
assert... | def test_make_cosmos():
| """Test the 'make' method for 'cosmos' crypto."""
cosmos_crypto = aea.crypto.registries.make_crypto(COSMOS)
assert type(cosmos_crypto) == CosmosCrypto
# calling 'make' again will give a different object.
cosmos_crypto_1 = aea.crypto.registries.make_crypto(COSMOS)
assert type(cosmos_crypto) == ... | # calling 'make' again will give a different object.
ethereum_crypto_1 = aea.crypto.registries.make_crypto(ETHEREUM)
assert type(ethereum_crypto) == type(ethereum_crypto_1)
assert ethereum_crypto.address != ethereum_crypto_1.address
def test_make_cosmos():
| 64 | 64 | 106 | 6 | 57 | marcofavorito/agents-aea | tests/test_crypto/test_registry/test_crypto_registry.py | Python | test_make_cosmos | test_make_cosmos | 70 | 79 | 70 | 70 | 06a8b0654bbfc55999d79e39830a3f9f2fb51794 | bigcode/the-stack | train |
98bdb64788722a126d0695f4 | train | class | class TestRegisterWithMalformedEntryPoint:
"""Test the error message when we try to register a crypto with a wrong entry point."""
MESSAGE_REGEX = "Malformed .*: '.*'. It must be of the form '.*'."
def test_wrong_spaces(self):
"""Spaces not allowed in a Crypto ID."""
# beginning space
... | class TestRegisterWithMalformedEntryPoint:
| """Test the error message when we try to register a crypto with a wrong entry point."""
MESSAGE_REGEX = "Malformed .*: '.*'. It must be of the form '.*'."
def test_wrong_spaces(self):
"""Spaces not allowed in a Crypto ID."""
# beginning space
with pytest.raises(AEAException, match=... | special_character", forbidden_special_characters)
def test_special_characters(self, special_character):
"""Special characters are not allowed (only underscore)."""
with pytest.raises(AEAException, match=self.MESSAGE_REGEX):
aea.crypto.registries.register_crypto(
"malforme... | 82 | 82 | 276 | 8 | 74 | marcofavorito/agents-aea | tests/test_crypto/test_registry/test_crypto_registry.py | Python | TestRegisterWithMalformedEntryPoint | TestRegisterWithMalformedEntryPoint | 174 | 205 | 174 | 174 | cf71700abe7a6637db82aa702c45987eee2a2b6e | bigcode/the-stack | train |
0edd51aaef3cda904112b883 | train | class | class MaxPoolingAggregator(Layer):
""" Aggregates via max-pooling over MLP functions.
"""
def __init__(self, input_dim, output_dim, model_size="small", neigh_input_dim=None,
dropout=0., bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs):
super(MaxPoolingAggregator, self).__in... | class MaxPoolingAggregator(Layer):
| """ Aggregates via max-pooling over MLP functions.
"""
def __init__(self, input_dim, output_dim, model_size="small", neigh_input_dim=None,
dropout=0., bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs):
super(MaxPoolingAggregator, self).__init__(**kwargs)
self.dropou... | -self.dropout)
# Reshape from [batch_size, depth] to [batch_size, 1, depth] for matmul.
query = tf.expand_dims(self_vecs, 1)
neigh_self_vecs = tf.concat([neigh_vecs, query], axis=1)
score = tf.matmul(query, neigh_self_vecs, transpose_b=True)
score = tf.nn.softmax(score, ... | 181 | 181 | 604 | 7 | 174 | parth-couture-ai/RecommenderSystems | socialRec/dgrec/aggregators.py | Python | MaxPoolingAggregator | MaxPoolingAggregator | 181 | 257 | 181 | 181 | 630213eb3b091bb719e83adb335039d022acc908 | bigcode/the-stack | train |
87027bfc525edf7c94eea5df | train | class | class MeanPoolingAggregator(Layer):
""" Aggregates via mean-pooling over MLP functions.
"""
def __init__(self, input_dim, output_dim, model_size="small", neigh_input_dim=None,
dropout=0., bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs):
super(MeanPoolingAggregator, self)._... | class MeanPoolingAggregator(Layer):
| """ Aggregates via mean-pooling over MLP functions.
"""
def __init__(self, input_dim, output_dim, model_size="small", neigh_input_dim=None,
dropout=0., bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs):
super(MeanPoolingAggregator, self).__init__(**kwargs)
self.drop... | (batch_size * num_neighbors, self.neigh_input_dim))
for l in self.mlp_layers:
h_reshaped = l(h_reshaped)
neigh_h = tf.reshape(h_reshaped, (batch_size, num_neighbors, self.hidden_dim))
neigh_h = tf.reduce_max(neigh_h, axis=1)
from_neighs = tf.matmul(neigh_h, self.va... | 181 | 181 | 605 | 7 | 174 | parth-couture-ai/RecommenderSystems | socialRec/dgrec/aggregators.py | Python | MeanPoolingAggregator | MeanPoolingAggregator | 260 | 336 | 260 | 260 | 0e11bd9e09eb596089702dd8bc8443fb6af25e4c | bigcode/the-stack | train |
d86a24083ba6f8f37fdb4b22 | train | class | class GCNAggregator(Layer):
"""
Aggregates via mean followed by matmul and non-linearity.
Same matmul parameters are used self vector and neighbor vectors.
"""
def __init__(self, input_dim, output_dim, neigh_input_dim=None,
dropout=0., bias=False, act=tf.nn.relu, name=None, concat=False... | class GCNAggregator(Layer):
| """
Aggregates via mean followed by matmul and non-linearity.
Same matmul parameters are used self vector and neighbor vectors.
"""
def __init__(self, input_dim, output_dim, neigh_input_dim=None,
dropout=0., bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs):
super(G... | _dim]
from_neighs = tf.matmul(neigh_means, self.vars['neigh_weights'])
from_self = tf.matmul(self_vecs, self.vars["self_weights"])
if not self.concat:
output = tf.add_n([from_self, from_neighs])
else:
output = tf.concat([from_self, from_neighs], axis=1)... | 113 | 113 | 379 | 8 | 105 | parth-couture-ai/RecommenderSystems | socialRec/dgrec/aggregators.py | Python | GCNAggregator | GCNAggregator | 70 | 120 | 70 | 70 | 5560887f2d9e39eb24e60b0e0cefc210d0bd64f6 | bigcode/the-stack | train |
d3ec90b0bdf1b5a9291c89f0 | train | class | class MeanAggregator(Layer):
"""
Aggregates via mean followed by matmul and non-linearity.
"""
def __init__(self, input_dim, output_dim, neigh_input_dim=None,
dropout=0., bias=False, act=tf.nn.relu,
name=None, concat=False, **kwargs):
super(MeanAggregator, self).__init_... | class MeanAggregator(Layer):
| """
Aggregates via mean followed by matmul and non-linearity.
"""
def __init__(self, input_dim, output_dim, neigh_input_dim=None,
dropout=0., bias=False, act=tf.nn.relu,
name=None, concat=False, **kwargs):
super(MeanAggregator, self).__init__(**kwargs)
self.dro... | import tensorflow as tf
from .layers import Layer, Dense
from .inits import glorot, zeros
# Mean, MaxPool, GCN aggregators are collected from
# https://github.com/williamleif/GraphSAGE
# which is also under the MIT license
class MeanAggregator(Layer):
| 67 | 131 | 437 | 6 | 60 | parth-couture-ai/RecommenderSystems | socialRec/dgrec/aggregators.py | Python | MeanAggregator | MeanAggregator | 10 | 68 | 10 | 10 | a89056da37b6db58e15203f0581b9ebeb6d31249 | bigcode/the-stack | train |
b03b628eff2a7f5d43edc563 | train | class | class AttentionAggregator(Layer):
def __init__(self, input_dim, output_dim, neigh_input_dim=None,
dropout=0., bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs):
super(AttentionAggregator, self).__init__(**kwargs)
self.dropout = dropout
self.bias = bias
... | class AttentionAggregator(Layer):
| def __init__(self, input_dim, output_dim, neigh_input_dim=None,
dropout=0., bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs):
super(AttentionAggregator, self).__init__(**kwargs)
self.dropout = dropout
self.bias = bias
self.act = act
self.concat = co... | _vecs = inputs
neigh_vecs = tf.nn.dropout(neigh_vecs, 1-self.dropout)
self_vecs = tf.nn.dropout(self_vecs, 1-self.dropout)
means = tf.reduce_mean(tf.concat([neigh_vecs,
tf.expand_dims(self_vecs, axis=1)], axis=1), axis=1)
# [nodes] x [out_dim]
output = tf.ma... | 130 | 130 | 435 | 7 | 123 | parth-couture-ai/RecommenderSystems | socialRec/dgrec/aggregators.py | Python | AttentionAggregator | AttentionAggregator | 123 | 178 | 123 | 124 | a7c4e774c99a84cbf354da1657dead96d6a79a57 | bigcode/the-stack | train |
c8ec384963a977c22e4bc657 | train | class | class TestFilterableListForm(TestCase):
def setUpFilterableForm(self, data=None):
filterable_pages = AbstractFilterPage.objects.live()
form = FilterableListForm(filterable_pages=filterable_pages,
wagtail_block=None)
form.is_bound = True
form.cleaned_data = data
... | class TestFilterableListForm(TestCase):
| def setUpFilterableForm(self, data=None):
filterable_pages = AbstractFilterPage.objects.live()
form = FilterableListForm(filterable_pages=filterable_pages,
wagtail_block=None)
form.is_bound = True
form.cleaned_data = data
return form
def test_filter_by_ca... | from __future__ import unicode_literals
from django.test import TestCase
from wagtail.wagtailcore.models import Site
from v1.forms import FilterableListForm
from v1.models import BlogPage
from v1.models.base import CFGOVPageCategory
from v1.models.learn_page import AbstractFilterPage, EventPage
from v1.tests.wagtail... | 100 | 256 | 1,057 | 9 | 90 | hillaryj/cfgov-refresh | cfgov/v1/tests/test_filterable_list_form.py | Python | TestFilterableListForm | TestFilterableListForm | 15 | 114 | 15 | 16 | fa22628e9c73848759e186468af0a0339c59c7e3 | bigcode/the-stack | train |
a102f8f009efd5135152ad5e | train | class | class DnsRequestsResponse(BaseResponse):
dns_requests: List[DnsRequestData]
| class DnsRequestsResponse(BaseResponse):
| dns_requests: List[DnsRequestData]
| from typing import List
from pydantic import BaseModel
from boucanpy.core.base.responses import BaseResponse
from boucanpy.core.dns_request.data import DnsRequestData
class DnsRequestResponse(BaseResponse):
dns_request: DnsRequestData
class DnsRequestsResponse(BaseResponse):
| 64 | 64 | 18 | 8 | 55 | bbhunter/boucanpy | boucanpy/core/dns_request/responses.py | Python | DnsRequestsResponse | DnsRequestsResponse | 13 | 14 | 13 | 13 | f153c25fd18da14723c4df6169462709b6cdabc4 | bigcode/the-stack | train |
76fbbc1f2eb18bbf9be178a2 | train | class | class DnsRequestResponse(BaseResponse):
dns_request: DnsRequestData
| class DnsRequestResponse(BaseResponse):
| dns_request: DnsRequestData
| from typing import List
from pydantic import BaseModel
from boucanpy.core.base.responses import BaseResponse
from boucanpy.core.dns_request.data import DnsRequestData
class DnsRequestResponse(BaseResponse):
| 47 | 64 | 17 | 8 | 38 | bbhunter/boucanpy | boucanpy/core/dns_request/responses.py | Python | DnsRequestResponse | DnsRequestResponse | 9 | 10 | 9 | 9 | 4ad958cceb0e3fa928c35dec42bc3af22bf661f3 | bigcode/the-stack | train |
6dd86090fb5de5d6384e0705 | train | class | class Migration(migrations.Migration):
dependencies = [
('gyoithon', '0026_auto_20210514_1813'),
]
operations = [
migrations.AlterField(
model_name='assessment',
name='scan_date',
field=models.DateTimeField(default=datetime.datetime(2021, 5, 14, 11, 52, ... | class Migration(migrations.Migration):
| dependencies = [
('gyoithon', '0026_auto_20210514_1813'),
]
operations = [
migrations.AlterField(
model_name='assessment',
name='scan_date',
field=models.DateTimeField(default=datetime.datetime(2021, 5, 14, 11, 52, 41, 517839, tzinfo=utc)),
),
... | # Generated by Django 3.1.7 on 2021-05-14 11:52
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
| 49 | 78 | 263 | 7 | 41 | gyoisamurai/GyoiBoard | gyoithon/migrations/0027_auto_20210514_2052.py | Python | Migration | Migration | 8 | 35 | 8 | 9 | 5a4d3556b5c01ad346e992b1bff89628fba5a579 | bigcode/the-stack | train |
5f5578799d9b9fa4d7bdf921 | train | class | class ValidatorFactory():
'''Basic Factory class for validators'''
def __init__(self):
pass
@staticmethod
def create_realtime_validator(validator_type, address_df):
'''Instantiates and returns the requested validator, based on input'''
if validator_type == 'Census':
... | class ValidatorFactory():
| '''Basic Factory class for validators'''
def __init__(self):
pass
@staticmethod
def create_realtime_validator(validator_type, address_df):
'''Instantiates and returns the requested validator, based on input'''
if validator_type == 'Census':
return census.CensusValida... | __(self, address_df=None):
self.address_df = address_df
def get_validator_matches(self):
'''Generic base method for validator matches'''
return self.address_df
import CREDA_tools.geocoding.census as census
import CREDA_tools.geocoding.generic as generic
class ValidatorFactory():
| 64 | 64 | 144 | 4 | 59 | KI-Research-Services/CREDA_tools | CREDA_tools/geocoding/validators.py | Python | ValidatorFactory | ValidatorFactory | 20 | 37 | 20 | 20 | 1d4daa1a91e396e34c1976f1881f55d519469551 | bigcode/the-stack | train |
e33a6771f094fa0f8fdcba20 | train | class | class AddressValidator(): # pylint: disable=too-few-public-methods
'''This is the parent object that all Validators inherit from'''
def __init__(self, address_df=None):
self.address_df = address_df
def get_validator_matches(self):
'''Generic base method for validator matches'''
retu... | class AddressValidator(): # pylint: disable=too-few-public-methods
| '''This is the parent object that all Validators inherit from'''
def __init__(self, address_df=None):
self.address_df = address_df
def get_validator_matches(self):
'''Generic base method for validator matches'''
return self.address_df
| # -*- coding: utf-8 -*-
"""
Created on Mon Mar 9 13:13:49 2020
@author: fisherd
"""
class AddressValidator(): # pylint: disable=too-few-public-methods
| 48 | 64 | 70 | 16 | 32 | KI-Research-Services/CREDA_tools | CREDA_tools/geocoding/validators.py | Python | AddressValidator | AddressValidator | 8 | 15 | 8 | 8 | ba8b7015ed017ed74dcb4ec96396646745b42aa5 | bigcode/the-stack | train |
3cc8eb4d07739c78fe33e8a3 | train | class | class Migration(migrations.Migration):
dependencies = [
('wildlifecompliance', '0470_auto_20200424_0853'),
]
operations = [
migrations.AlterField(
model_name='applicationselectedactivitypurpose',
name='processing_status',
field=models.CharField(choices=[... | class Migration(migrations.Migration):
| dependencies = [
('wildlifecompliance', '0470_auto_20200424_0853'),
]
operations = [
migrations.AlterField(
model_name='applicationselectedactivitypurpose',
name='processing_status',
field=models.CharField(choices=[('selected', 'Selected for Proposal'), (... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2020-04-24 01:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| 54 | 64 | 116 | 7 | 46 | preranaandure/wildlifecompliance | wildlifecompliance/migrations/0471_auto_20200424_0910.py | Python | Migration | Migration | 8 | 20 | 8 | 9 | ef82a82911199700e4721f3bd6c61a3b12843af5 | bigcode/the-stack | train |
6c1a87c4887c4dcef3acf02e | train | class | class AntMerchantExpandIndirectCreateResponse(AlipayResponse):
def __init__(self):
super(AntMerchantExpandIndirectCreateResponse, self).__init__()
self._sub_merchant_id = None
@property
def sub_merchant_id(self):
return self._sub_merchant_id
@sub_merchant_id.setter
def sub... | class AntMerchantExpandIndirectCreateResponse(AlipayResponse):
| def __init__(self):
super(AntMerchantExpandIndirectCreateResponse, self).__init__()
self._sub_merchant_id = None
@property
def sub_merchant_id(self):
return self._sub_merchant_id
@sub_merchant_id.setter
def sub_merchant_id(self, value):
self._sub_merchant_id = value... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AntMerchantExpandIndirectCreateResponse(AlipayResponse):
| 44 | 64 | 147 | 12 | 31 | cuhk-mobitec/S3KVetter | payment_lib_examples/alipay-sdk-python/virtual_environment/lib/python3.4/site-packages/alipay/aop/api/response/AntMerchantExpandIndirectCreateResponse.py | Python | AntMerchantExpandIndirectCreateResponse | AntMerchantExpandIndirectCreateResponse | 8 | 25 | 8 | 9 | 98fcbf85a873128922ce02809adc4cef51bac60a | bigcode/the-stack | train |
943846423f3ab31efe836c6e | train | class | @MODEL_REGISTRY.register(name_prefix=__name__)
class Generator_Diffcam_FreezeNeRF(Generator_Diffcam):
def load_nerf_ema(self, G_ema):
ret = self.nerf_net.load_state_dict(G_ema.nerf_net.state_dict())
ret = self.mapping_shape.load_state_dict(G_ema.mapping_shape.state_dict())
ret = self.mapping_app.load_sta... | @MODEL_REGISTRY.register(name_prefix=__name__)
class Generator_Diffcam_FreezeNeRF(Generator_Diffcam):
| def load_nerf_ema(self, G_ema):
ret = self.nerf_net.load_state_dict(G_ema.nerf_net.state_dict())
ret = self.mapping_shape.load_state_dict(G_ema.mapping_shape.state_dict())
ret = self.mapping_app.load_state_dict(G_ema.mapping_app.state_dict())
ret = self.aux_to_rbg.load_state_dict(G_ema.aux_to_rbg.sta... | _noise,
white_back=white_back,
last_back=last_back,
return_aux_img=return_aux_img,
forward_points=forward_points,
camera_pos=camera_pos,
camera_lookup=camera_lookup,
)
return imgs, pitch_yaw
@MODEL_REGISTRY.register(name_prefix=__name__)
class Generator_Diffca... | 82 | 82 | 276 | 26 | 55 | PeterouZh/CIPS-3D | exp/cips3d_inversion/models/generator_v4.py | Python | Generator_Diffcam_FreezeNeRF | Generator_Diffcam_FreezeNeRF | 1,275 | 1,308 | 1,275 | 1,277 | 724a24686b9777e4e5965b723979cc0e7a86a1d2 | bigcode/the-stack | train |
272460e646bf38541755e329 | train | class | class ModSinLayer(nn.Module):
def __repr__(self): return f"{self.__class__.__name__}({self.repr})"
def __init__(self,
in_dim,
use_style_fc=False,
style_dim=None,
which_linear=nn.Linear,
spectral_norm=False,
eps=1e-5,
... | class ModSinLayer(nn.Module):
| def __repr__(self): return f"{self.__class__.__name__}({self.repr})"
def __init__(self,
in_dim,
use_style_fc=False,
style_dim=None,
which_linear=nn.Linear,
spectral_norm=False,
eps=1e-5,
freq=1,
... | x, style),
name_prefix=f"{self.name_prefix}.network.{index}.1.")
x = _layer(x, style)
if global_cfg.tl_debug:
VerboseModel.forward_verbose(self.to_rbgs[index],
inputs_args=(x, rgb),
name_p... | 182 | 182 | 607 | 7 | 174 | PeterouZh/CIPS-3D | exp/cips3d_inversion/models/generator_v4.py | Python | ModSinLayer | ModSinLayer | 296 | 374 | 296 | 296 | 0c5160ce34001274cb505e90e514b4051e27b8fe | bigcode/the-stack | train |
33cb389642aceeddb78430fd | train | class | class ToRGB(nn.Module):
def __init__(self,
in_dim,
dim_rgb=3,
use_equal_fc=False):
super().__init__()
self.in_dim = in_dim
self.dim_rgb = dim_rgb
if use_equal_fc:
self.linear = mod_conv_fc.EqualLinear(in_dim, dim_rgb, scale=1.)
else:
self.l... | class ToRGB(nn.Module):
| def __init__(self,
in_dim,
dim_rgb=3,
use_equal_fc=False):
super().__init__()
self.in_dim = in_dim
self.dim_rgb = dim_rgb
if use_equal_fc:
self.linear = mod_conv_fc.EqualLinear(in_dim, dim_rgb, scale=1.)
else:
self.linear = nn.Linear(in_dim... | return out
def __repr__(self):
repr = f"{self.__class__.__name__}(in_dim={self.in_dim}, " \
f"out_dim={self.out_dim}, " \
f"style_dim={self.style_dim})"
return repr
class ToRGB(nn.Module):
| 64 | 64 | 130 | 6 | 57 | PeterouZh/CIPS-3D | exp/cips3d_inversion/models/generator_v4.py | Python | ToRGB | ToRGB | 538 | 561 | 538 | 538 | 8f788d81ee9c94bae608572707b294df8fe5891d | bigcode/the-stack | train |
01d0156ad7b27e59c51ec0a7 | train | class | class LinearSinAct(nn.Module):
def __init__(self,
in_features,
out_features):
super(LinearSinAct, self).__init__()
self.linear = nn.Linear(in_features=in_features, out_features=out_features)
self.sin = SinAct()
pass
def forward(self, x, *args, **kwargs):
x = self.... | class LinearSinAct(nn.Module):
| def __init__(self,
in_features,
out_features):
super(LinearSinAct, self).__init__()
self.linear = nn.Linear(in_features=in_features, out_features=out_features)
self.sin = SinAct()
pass
def forward(self, x, *args, **kwargs):
x = self.linear(x)
x = self.sin(x)
... | 1) / math.pi
out = (x0 + x1)
return out
class SinAct(nn.Module):
def __init__(self, ):
super(SinAct, self).__init__()
def forward(self, x):
return torch.sin(x)
class LinearSinAct(nn.Module):
| 64 | 64 | 91 | 7 | 57 | PeterouZh/CIPS-3D | exp/cips3d_inversion/models/generator_v4.py | Python | LinearSinAct | LinearSinAct | 60 | 73 | 60 | 60 | 0ee9d13509efc0dc545f6a86e03792966f09c60a | bigcode/the-stack | train |
10d08dde08dabd8f1bda7174 | train | class | class SinBlock(nn.Module):
def __init__(self,
in_dim,
out_dim,
style_dim,
name_prefix,
):
super().__init__()
self.in_dim = in_dim
self.out_dim = out_dim
self.style_dim = style_dim
self.name_prefix = name_prefix
self.st... | class SinBlock(nn.Module):
| def __init__(self,
in_dim,
out_dim,
style_dim,
name_prefix,
):
super().__init__()
self.in_dim = in_dim
self.out_dim = out_dim
self.style_dim = style_dim
self.name_prefix = name_prefix
self.style_dim_dict = {}
# se... | pass
def forward(self,
x,
style):
"""
Calculate class-conditional gains and biases.
:param x: (b, c) or (b, n, c)
:param style: (b, c)
:return:
"""
assert style.shape[-1] == self.style_dim
if self.use_style_fc:
gain = self.gain_fc(style) + 1.
e... | 221 | 221 | 739 | 6 | 214 | PeterouZh/CIPS-3D | exp/cips3d_inversion/models/generator_v4.py | Python | SinBlock | SinBlock | 448 | 535 | 448 | 448 | 1656ad5247eb587150d07d5796d1631cb259233e | bigcode/the-stack | train |
f7e6347cad71a6a95aa93eb3 | train | class | class ModSinLayer_NoBias(nn.Module):
def __repr__(self): return f"{self.__class__.__name__}({self.repr})"
def __init__(self,
in_dim,
use_style_fc=False,
style_dim=None,
which_linear=nn.Linear,
spectral_norm=False,
eps=1e-5,
... | class ModSinLayer_NoBias(nn.Module):
| def __repr__(self): return f"{self.__class__.__name__}({self.repr})"
def __init__(self,
in_dim,
use_style_fc=False,
style_dim=None,
which_linear=nn.Linear,
spectral_norm=False,
eps=1e-5,
freq=1,
... | 1.
if x.dim() == 3:
gain = rearrange(gain, "b c -> b 1 c")
bias = rearrange(bias, "b c -> b 1 c")
elif x.dim() == 2:
pass
else:
assert 0
# x = torch.sin(self.freq * x + self.phase)
# out = x * gain + bias
x = x * torch.rsqrt(torch.mean(x ** 2, dim=-1, keepdim=True) + ... | 150 | 150 | 501 | 9 | 140 | PeterouZh/CIPS-3D | exp/cips3d_inversion/models/generator_v4.py | Python | ModSinLayer_NoBias | ModSinLayer_NoBias | 377 | 445 | 377 | 377 | e76b97ee84013af92c85e85414981a7742b03cca | bigcode/the-stack | train |
1c4dc762ac7d8fff983336fb | train | class | class INRNetwork_Skip(nn.Module):
def __repr__(self): return f"{self.__class__.__name__}({self.repr})"
def __init__(self,
input_dim,
style_dim,
hidden_layers,
dim_scale=1,
rgb_dim=3,
device=None,
name_prefix='i... | class INRNetwork_Skip(nn.Module):
| def __repr__(self): return f"{self.__class__.__name__}({self.repr})"
def __init__(self,
input_dim,
style_dim,
hidden_layers,
dim_scale=1,
rgb_dim=3,
device=None,
name_prefix='inr',
**kwargs):
... | b (n c) -> b n c", n=2)
gain, bias = style.unbind(dim=1)
gain = self.gain_scale(gain)
if x.dim() == 3:
gain = rearrange(gain, "b c -> b 1 c")
bias = rearrange(bias, "b c -> b 1 c")
elif x.dim() == 2:
pass
else:
assert 0
x = self.linear(x)
x = x * torch.rsqrt(to... | 256 | 256 | 1,051 | 8 | 247 | PeterouZh/CIPS-3D | exp/cips3d_inversion/models/generator_v4.py | Python | INRNetwork_Skip | INRNetwork_Skip | 156 | 292 | 156 | 156 | f12f19cc45850fc9157bef8d884ea7d50f855b16 | bigcode/the-stack | train |
7d1323b422e1a22df2922051 | train | class | @MODEL_REGISTRY.register(name_prefix=__name__)
# class Generator_Diffcam(GeneratorNerfINR_base):
class Generator_Diffcam(nn.Module):
def __repr__(self):
return tl2_utils.get_class_repr(self)
def __init__(self,
nerf_cfg,
mapping_shape_cfg,
mapping_app_cfg,
... | @MODEL_REGISTRY.register(name_prefix=__name__)
# class Generator_Diffcam(GeneratorNerfINR_base):
class Generator_Diffcam(nn.Module):
| def __repr__(self):
return tl2_utils.get_class_repr(self)
def __init__(self,
nerf_cfg,
mapping_shape_cfg,
mapping_app_cfg,
inr_cfg,
mapping_inr_cfg,
shape_block_end_index=None,
app_block_end_index=None,
... | x_orig.shape[-1]:
# out = (out + x_orig) / 1.41421
out = self.skip(out, x_orig)
return out
def __repr__(self):
repr = f"{self.__class__.__name__}(in_dim={self.in_dim}, " \
f"out_dim={self.out_dim}, " \
f"style_dim={self.style_dim})"
return repr
class ToRGB(nn.Module):... | 256 | 256 | 5,857 | 34 | 221 | PeterouZh/CIPS-3D | exp/cips3d_inversion/models/generator_v4.py | Python | Generator_Diffcam | Generator_Diffcam | 564 | 1,272 | 564 | 567 | 9bcd76c1f1901eeef098eabd34b7daca47b88432 | bigcode/the-stack | train |
b410d35a1a8e421cf1cfa633 | train | class | class FiLMLayer(nn.Module):
def __init__(self,
in_dim,
out_dim,
style_dim,
use_style_fc=True,
which_linear=nn.Linear,
**kwargs):
super(FiLMLayer, self).__init__()
self.in_dim = in_dim
self.out_dim = out_dim
self... | class FiLMLayer(nn.Module):
| def __init__(self,
in_dim,
out_dim,
style_dim,
use_style_fc=True,
which_linear=nn.Linear,
**kwargs):
super(FiLMLayer, self).__init__()
self.in_dim = in_dim
self.out_dim = out_dim
self.style_dim = style_dim
s... | super(SkipLayer, self).__init__()
def forward(self, x0, x1):
# out = (x0 + x1) / math.pi
out = (x0 + x1)
return out
class SinAct(nn.Module):
def __init__(self, ):
super(SinAct, self).__init__()
def forward(self, x):
return torch.sin(x)
class LinearSinAct(nn.Module):
def __init__(s... | 186 | 186 | 621 | 8 | 177 | PeterouZh/CIPS-3D | exp/cips3d_inversion/models/generator_v4.py | Python | FiLMLayer | FiLMLayer | 76 | 153 | 76 | 76 | 8ff20fac12fcda492d1ea99e5ff79310869373b7 | bigcode/the-stack | train |
c2f741cdb5cc7fce171d9b38 | train | class | class SinAct(nn.Module):
def __init__(self, ):
super(SinAct, self).__init__()
def forward(self, x):
return torch.sin(x)
| class SinAct(nn.Module):
| def __init__(self, ):
super(SinAct, self).__init__()
def forward(self, x):
return torch.sin(x)
| def __init__(self, ):
super(SkipLayer, self).__init__()
def forward(self, x0, x1):
# out = (x0 + x1) / math.pi
out = (x0 + x1)
return out
class SinAct(nn.Module):
| 64 | 64 | 37 | 6 | 57 | PeterouZh/CIPS-3D | exp/cips3d_inversion/models/generator_v4.py | Python | SinAct | SinAct | 52 | 57 | 52 | 52 | b55f9ef9c54ed78b1da768da5b6c3204d32557ec | bigcode/the-stack | train |
ae4da6bd20aba3add75f4344 | train | class | class SkipLayer(nn.Module):
def __init__(self, ):
super(SkipLayer, self).__init__()
def forward(self, x0, x1):
# out = (x0 + x1) / math.pi
out = (x0 + x1)
return out
| class SkipLayer(nn.Module):
| def __init__(self, ):
super(SkipLayer, self).__init__()
def forward(self, x0, x1):
# out = (x0 + x1) / math.pi
out = (x0 + x1)
return out
| R_base
from exp.comm import comm_utils
from exp.comm.models import nerf_network
from exp.comm.models import inr_network
from exp.comm.models import film_layer
from exp.comm.models import mod_conv_fc
# from exp.cips3d.models import multi_head_mapping
class SkipLayer(nn.Module):
| 64 | 64 | 64 | 6 | 57 | PeterouZh/CIPS-3D | exp/cips3d_inversion/models/generator_v4.py | Python | SkipLayer | SkipLayer | 41 | 48 | 41 | 41 | 0d61e025a3406ee369fb23255e6bd32351d99153 | bigcode/the-stack | train |
da970fb41c37ab1c6ad7d52d | train | function | def create_postgres_session(engine):
Session = sessionmaker(bind=engine)
return Session
| def create_postgres_session(engine):
| Session = sessionmaker(bind=engine)
return Session
| port = os.getenv("POSTGRES_PORT", "5432")
db = os.getenv('POSTGRES_DB')
engine = create_engine(
f"postgresql+psycopg2://{username}:{password}@{hostname}:{port}/{db}")
return engine
def create_postgres_session(engine):
| 64 | 64 | 20 | 7 | 56 | hackla-engage/engage-scraper | engage_scraper/scraper_utils/dbutils.py | Python | create_postgres_session | create_postgres_session | 21 | 23 | 21 | 21 | c63f79cad698540687214f74f2b4c79abfdf8285 | bigcode/the-stack | train |
569e0d4ad62c49c6e7312e17 | train | function | def create_postgres_tables(Base, engine):
Base.metadata.create_all(engine)
| def create_postgres_tables(Base, engine):
| Base.metadata.create_all(engine)
| import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
def create_postgres_tables(Base, engine):
| 25 | 64 | 16 | 9 | 15 | hackla-engage/engage-scraper | engage_scraper/scraper_utils/dbutils.py | Python | create_postgres_tables | create_postgres_tables | 6 | 7 | 6 | 6 | ab829b9735c99c1628e2687eddabd425c87a47e8 | bigcode/the-stack | train |
48b0a763fcfea82bc408fc94 | train | function | def create_postgres_connection():
username = os.getenv("POSTGRES_USER")
password = os.getenv("POSTGRES_PASSWORD")
hostname = os.getenv('POSTGRES_HOST', "localhost")
port = os.getenv("POSTGRES_PORT", "5432")
db = os.getenv('POSTGRES_DB')
engine = create_engine(
f"postgresql+psycopg2://{us... | def create_postgres_connection():
| username = os.getenv("POSTGRES_USER")
password = os.getenv("POSTGRES_PASSWORD")
hostname = os.getenv('POSTGRES_HOST', "localhost")
port = os.getenv("POSTGRES_PORT", "5432")
db = os.getenv('POSTGRES_DB')
engine = create_engine(
f"postgresql+psycopg2://{username}:{password}@{hostname}:{por... | import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
def create_postgres_tables(Base, engine):
Base.metadata.create_all(engine)
def create_postgres_connection():
| 38 | 64 | 97 | 6 | 32 | hackla-engage/engage-scraper | engage_scraper/scraper_utils/dbutils.py | Python | create_postgres_connection | create_postgres_connection | 10 | 18 | 10 | 10 | d9f625ce93cbf35851e143ddcc126d29d87dbe86 | bigcode/the-stack | train |
fc09e301eaeec6cbbf4c81f5 | train | class | class PrinsScraper(RealWorksScraper):
MAKELAARDIJ: str = "prins"
BASE_URL: str = "https://www.prinsmakelaardij.nl"
| class PrinsScraper(RealWorksScraper):
| MAKELAARDIJ: str = "prins"
BASE_URL: str = "https://www.prinsmakelaardij.nl"
| import asyncio
from app.scrapers.realworks import RealWorksScraper
class PrinsScraper(RealWorksScraper):
| 25 | 64 | 40 | 10 | 14 | damienallen/makelaardij-notify | server/app/scrapers/prins.py | Python | PrinsScraper | PrinsScraper | 6 | 9 | 6 | 7 | 8b038fcfa65795366c89a5211782e79f0c625e5e | bigcode/the-stack | train |
bb05799d2d79592703b52c6b | train | class | class TestTimestampUnaryOps:
# --------------------------------------------------------------
# Timestamp.round
@pytest.mark.parametrize('timestamp, freq, expected', [
('20130101 09:10:11', 'D', '20130101'),
('20130101 19:10:11', 'D', '20130102'),
('20130201 12:00:00', 'D', '2013020... | class TestTimestampUnaryOps:
# --------------------------------------------------------------
# Timestamp.round
@pytest.mark.parametrize('timestamp, freq, expected', [
('20130101 09:10:11', 'D', '20130101'),
('20130101 19:10:11', 'D', '20130102'),
('20130201 12:00:00', 'D', '2013020... | def test_round_frequencies(self, timestamp, freq, expected):
dt = Timestamp(timestamp)
result = dt.round(freq)
expected = Timestamp(expected)
assert result == expected
def test_round_tzaware(self):
dt = Timestamp('20130101 09:10:11', tz='US/Eastern')
result = dt.... |
from pandas.compat import PY36
import pandas.util._test_decorators as td
from pandas import NaT, Timestamp
import pandas.util.testing as tm
from pandas.tseries.frequencies import to_offset
class TestTimestampUnaryOps:
# --------------------------------------------------------------
# Timestamp.round
@py... | 256 | 256 | 4,004 | 212 | 43 | fdroessler/pandas | pandas/tests/scalar/timestamp/test_unary_ops.py | Python | TestTimestampUnaryOps | TestTimestampUnaryOps | 20 | 374 | 20 | 32 | 20ffbb42ffffb887cfa4815cfebc1d66743679e5 | bigcode/the-stack | train |
aae2950b8c1e6ff8df78de25 | train | function | def violentMatch(s, p):
"""暴力匹配"""
slen = len(s)
plen = len(p)
i = 0
j = 0
while i < slen and j < plen:
if s[i] == p[j]:
# 匹配成功
i += 1
j += 1
else:
# 匹配失败,回溯
i = i-j+1
j = 0
# 成功返回p在s中的位置,否则返回 -1
... | def violentMatch(s, p):
| """暴力匹配"""
slen = len(s)
plen = len(p)
i = 0
j = 0
while i < slen and j < plen:
if s[i] == p[j]:
# 匹配成功
i += 1
j += 1
else:
# 匹配失败,回溯
i = i-j+1
j = 0
# 成功返回p在s中的位置,否则返回 -1
if j == plen:
r... | # 暴力匹配算法
def violentMatch(s, p):
| 15 | 64 | 140 | 7 | 7 | lp1225/my_algorithm | other_algorithm/ViolentMatch.py | Python | violentMatch | violentMatch | 3 | 23 | 3 | 3 | 60d29adcd143655e340a57e600b2df9d9516e86b | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.