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
00c78dcf4e1fcca8f84c222f
train
function
def log_likelihood(emp_cov, precision): """Computes the sample mean of the log_likelihood under a covariance model computes the empirical expected log-likelihood (accounting for the normalization terms and scaling), allowing for universal comparison (beyond this software package) Parameters --...
def log_likelihood(emp_cov, precision):
"""Computes the sample mean of the log_likelihood under a covariance model computes the empirical expected log-likelihood (accounting for the normalization terms and scaling), allowing for universal comparison (beyond this software package) Parameters ---------- emp_cov : ndarray of shape ...
warnings import numpy as np from scipy import linalg from .. import config_context from ..base import BaseEstimator from ..utils import check_array from ..utils.extmath import fast_logdet from ..metrics.pairwise import pairwise_distances def log_likelihood(emp_cov, precision):
64
64
198
9
54
talahajeer/scikit-learn
sklearn/covariance/_empirical_covariance.py
Python
log_likelihood
log_likelihood
24
48
24
24
34a3c2b6e80828b88b5877e90b7308753e28f4d8
bigcode/the-stack
train
cb9958887c19eb4e3ef5b666
train
function
def empirical_covariance(X, *, assume_centered=False): """Computes the Maximum likelihood covariance estimator Parameters ---------- X : ndarray of shape (n_samples, n_features) Data from which to compute the covariance estimate assume_centered : bool, default=False If True, data ...
def empirical_covariance(X, *, assume_centered=False):
"""Computes the Maximum likelihood covariance estimator Parameters ---------- X : ndarray of shape (n_samples, n_features) Data from which to compute the covariance estimate assume_centered : bool, default=False If True, data will not be centered before computation. Useful...
The precision matrix of the covariance model to be tested. Returns ------- log_likelihood_ : float Sample mean of the log-likelihood. """ p = precision.shape[0] log_likelihood_ = -np.sum(emp_cov * precision) + fast_logdet(precision) log_likelihood_ -= p * np.log(2 * np.pi) ...
110
111
373
12
98
talahajeer/scikit-learn
sklearn/covariance/_empirical_covariance.py
Python
empirical_covariance
empirical_covariance
51
98
51
51
eb16c90321fae7229045d6ea87c9ac634619bf35
bigcode/the-stack
train
fbf06568659f485dc3a43aaf
train
function
def unneeded_not(): """This is not ok """ bool_var = True someint = 2 if not not bool_var: # [unneeded-not] pass if not someint == 1: # [unneeded-not] pass if not someint != 1: # [unneeded-not] pass if not someint < 1: # [unneeded-not] pass if not ...
def unneeded_not():
"""This is not ok """ bool_var = True someint = 2 if not not bool_var: # [unneeded-not] pass if not someint == 1: # [unneeded-not] pass if not someint != 1: # [unneeded-not] pass if not someint < 1: # [unneeded-not] pass if not someint > 1: # [unn...
"""Check exceeding negations in boolean expressions trigger warnings""" # pylint: disable=singleton-comparison,too-many-branches,too-few-public-methods,undefined-variable def unneeded_not():
40
86
287
5
34
KeynesYouDigIt/nimbleBlog
lib/python2.7/site-packages/pylint/test/functional/unneeded_not.py
Python
unneeded_not
unneeded_not
5
37
5
5
58e309637293d0d6a136780a6bb47eb697713e66
bigcode/the-stack
train
3de28f97b288329dfeb6ee6c
train
class
class Klass(object): """This is also ok""" def __ne__(self, other): return not self == other
class Klass(object):
"""This is also ok""" def __ne__(self, other): return not self == other
<= someint < 3 < 4: pass if not set('bar') <= set('foobaz'): pass if not set(something) <= 3: pass if not frozenset(something) <= 3: pass class Klass(object):
64
64
27
4
59
KeynesYouDigIt/nimbleBlog
lib/python2.7/site-packages/pylint/test/functional/unneeded_not.py
Python
Klass
Klass
60
63
60
60
bc98abb900599bd658b8a0c05931829f87c09895
bigcode/the-stack
train
144deb90583004d70d326bdd
train
function
def tolerated_statements(): """This is ok""" bool_var = True someint = 2 if not(bool_var == False and someint == 1): pass if 2 not in [3, 4]: pass if not someint == bool_var == 2: pass if not 2 <= someint < 3 < 4: pass if not set('bar') <= set('foobaz'): ...
def tolerated_statements():
"""This is ok""" bool_var = True someint = 2 if not(bool_var == False and someint == 1): pass if 2 not in [3, 4]: pass if not someint == bool_var == 2: pass if not 2 <= someint < 3 < 4: pass if not set('bar') <= set('foobaz'): pass if not set(s...
if not True == True: # [unneeded-not] pass if not 2 in [3, 4]: # [unneeded-not] pass if not someint is 'test': # [unneeded-not] pass def tolerated_statements():
64
64
136
5
58
KeynesYouDigIt/nimbleBlog
lib/python2.7/site-packages/pylint/test/functional/unneeded_not.py
Python
tolerated_statements
tolerated_statements
40
57
40
40
d42559c9062e366c4d003d734e15cd98d74b056d
bigcode/the-stack
train
b0e6b02ca16c52f1721bf463
train
function
def version_specific(version, v3_subcon, v4_subcon): """ There are some differences in the parsing structure between v3 and v4. Some fields are different length and some exist only in one of the versions. this returns the relevant parsing structure by version :param version: int 3 or 4 :param v3_sub...
def version_specific(version, v3_subcon, v4_subcon):
""" There are some differences in the parsing structure between v3 and v4. Some fields are different length and some exist only in one of the versions. this returns the relevant parsing structure by version :param version: int 3 or 4 :param v3_subcon: the parsing struct if version is 3 :param v4...
from construct import * def version_specific(version, v3_subcon, v4_subcon):
19
64
131
15
4
ur1katz/access_parser
access_parser/parsing_primitives.py
Python
version_specific
version_specific
4
15
4
4
a493a13b3df5b37540620d53118b01f9e8a59367
bigcode/the-stack
train
bd5f434c34c152545fc5c60e
train
function
def parse_table_data(buffer, real_index_count, column_count, version=3): REAL_INDEX = Struct( "unk1" / Int32ul, "index_row_count" / Int32ul, "ver4_always_zero" / If(lambda x: version > 3, Int32ul)) VARIOUS_TEXT_V3 = Struct( "LCID" / Int16ul, "code_page" / Int16ul, ...
def parse_table_data(buffer, real_index_count, column_count, version=3):
REAL_INDEX = Struct( "unk1" / Int32ul, "index_row_count" / Int32ul, "ver4_always_zero" / If(lambda x: version > 3, Int32ul)) VARIOUS_TEXT_V3 = Struct( "LCID" / Int16ul, "code_page" / Int16ul, "various_text3_unknown" / Int16ul) VARIOUS_TEXT_V4 = Struct( ...
ul), "complex_autonumber" / If(lambda x: version > 3, Int32ul), "ver4_unknown_1" / If(lambda x: version > 3, Int32ul), "ver4_unknown_2" / If(lambda x: version > 3, Int32ul), # 0x53 system table # 0x4e user table "table_type_flags" / Int8ul, "next_column_id" / Int1...
202
202
675
17
185
ur1katz/access_parser
access_parser/parsing_primitives.py
Python
parse_table_data
parse_table_data
112
180
112
112
faef8176e13f8847254b10934444464667d5c077
bigcode/the-stack
train
24e83e8a0ebd991ea8116be6
train
function
def parse_data_page_header(buffer, version=3): return Struct( Const(b"\x01\x01"), "data_free_space" / Int16ul, "owner" / Int32ul, "ver4_unknown_dat1" / If(lambda x: version > 3, Int32ul), "record_count" / Int16ul, "record_offsets" / Array(lambda x: x.record_count, Int...
def parse_data_page_header(buffer, version=3):
return Struct( Const(b"\x01\x01"), "data_free_space" / Int16ul, "owner" / Int32ul, "ver4_unknown_dat1" / If(lambda x: version > 3, Int32ul), "record_count" / Int16ul, "record_offsets" / Array(lambda x: x.record_count, Int16ul)).parse(buffer)
errors when parsing some DB files. We currently don't use any of the values from # then anyway # # Array(lambda x: x.real_index_count, REAL_INDEX2), # Array(lambda x: x.index_count, ALL_INDEXES)) def parse_data_page_header(buffer, version=3):
64
64
97
11
53
ur1katz/access_parser
access_parser/parsing_primitives.py
Python
parse_data_page_header
parse_data_page_header
189
196
189
189
b34cee7a099c99c23667d31ef2e2b2524b666e08
bigcode/the-stack
train
87a74a34e2a352cd4140b677
train
function
def parse_relative_object_metadata_struct(buffer, variable_jump_tables_cnt=0, version=3): return Struct( "variable_length_field_count" / version_specific(version, Int8ul, Int16ul), "variable_length_jump_table" / If(lambda x: version == 3, Array(variable_jump_tables_cnt, Int8ul)), # This curr...
def parse_relative_object_metadata_struct(buffer, variable_jump_tables_cnt=0, version=3):
return Struct( "variable_length_field_count" / version_specific(version, Int8ul, Int16ul), "variable_length_jump_table" / If(lambda x: version == 3, Array(variable_jump_tables_cnt, Int8ul)), # This currently supports up to 255 columns for versions > 3 "variable_length_field_offsets" ...
Int32ul), "record_count" / Int16ul, "record_offsets" / Array(lambda x: x.record_count, Int16ul)).parse(buffer) # buffer should be the record data in reverse def parse_relative_object_metadata_struct(buffer, variable_jump_tables_cnt=0, version=3):
64
64
164
19
44
ur1katz/access_parser
access_parser/parsing_primitives.py
Python
parse_relative_object_metadata_struct
parse_relative_object_metadata_struct
200
210
200
200
33942f55f8e8536f0b9e4b4352883f936adf742d
bigcode/the-stack
train
7ab72c0b176837632749b1c6
train
function
def parse_table_head(buffer, version=3): REAL_INDEX2 = Struct( "unknown_b1" / If(lambda x: version > 3, Int32ul), "unk_struct" / Array(10, Struct("col_id" / Int16ul, "idx_flags" / Int8ul)), "runk" / Int32ul, "first_index_page" / Int32ul, "flags" / version_specific(version, In...
def parse_table_head(buffer, version=3):
REAL_INDEX2 = Struct( "unknown_b1" / If(lambda x: version > 3, Int32ul), "unk_struct" / Array(10, Struct("col_id" / Int16ul, "idx_flags" / Int8ul)), "runk" / Int32ul, "first_index_page" / Int32ul, "flags" / version_specific(version, Int8ul, Int16ul), "unknown_b3" / If...
"fixed_length" / Flag, "unk_3" / Flag, "unk_4" / Flag, "unk_5" / Flag, 'modern_package_type' / Flag, "unk_6" / Flag, "unk_7" / Flag, "unk_8" / Flag, "compressed_unicode" / Flag) TDEF_HEADER = Struct( Const(b'\02\x01'), "peek_version" / Peek(Int16ul), "tdef_ver" / IfThenElse...
162
162
542
10
152
ur1katz/access_parser
access_parser/parsing_primitives.py
Python
parse_table_head
parse_table_head
67
109
67
67
1592db1025b2069a38f363201f20dc1cd90a97ec
bigcode/the-stack
train
499fa7f26716bdb7fd329653
train
function
def points_on_line(p1, p2): def flexrange(a, b): if b >= a: return range(a, b+1) else: return range(a, b-1, -1) points = [] if p1.x == p2.x: points = [Point(p1.x, y) for y in range(min(p1.y,p2.y),(max(p1.y,p2.y) + 1))] elif p1.y == p2.y: points =...
def points_on_line(p1, p2):
def flexrange(a, b): if b >= a: return range(a, b+1) else: return range(a, b-1, -1) points = [] if p1.x == p2.x: points = [Point(p1.x, y) for y in range(min(p1.y,p2.y),(max(p1.y,p2.y) + 1))] elif p1.y == p2.y: points = [Point(x, p1.y) for x in ra...
(x1, y1) = map(int,p1.split(',')) (x2, y2) = map(int,p2.split(',')) point_pairs.append((Point(x1,y1), Point(x2,y2))) return point_pairs def points_on_line(p1, p2):
64
64
187
10
53
kforiordan/advent-of-code
05-hydrothermal-venture/05-hydrothermal-venture-02.py
Python
points_on_line
points_on_line
31
47
31
31
6cbf6460ed1e5cdd2c095a9f5edf51274de0a813
bigcode/the-stack
train
6caee9c3047fd0252a02ceaf
train
function
def get_point_pairs(fh): point_pairs = [] for line in fh: (p1,arrow,p2) = line.strip().split() (x1, y1) = map(int,p1.split(',')) (x2, y2) = map(int,p2.split(',')) point_pairs.append((Point(x1,y1), Point(x2,y2))) return point_pairs
def get_point_pairs(fh):
point_pairs = [] for line in fh: (p1,arrow,p2) = line.strip().split() (x1, y1) = map(int,p1.split(',')) (x2, y2) = map(int,p2.split(',')) point_pairs.append((Point(x1,y1), Point(x2,y2))) return point_pairs
def __hash__(self): return hash('{},{}'.format(self.x, self.y)) def __eq__(self, other): return (self.__class__ == other.__class__ and \ self.x == other.x and \ self.y == other.y) def get_point_pairs(fh):
64
64
87
7
57
kforiordan/advent-of-code
05-hydrothermal-venture/05-hydrothermal-venture-02.py
Python
get_point_pairs
get_point_pairs
19
28
19
19
f913bf627400357eaa5af4a436eff23bad54450e
bigcode/the-stack
train
f6c1cbcc3de8b8afc5d6ef93
train
class
class Point(NamedTuple): x: int y: int def __hash__(self): return hash('{},{}'.format(self.x, self.y)) def __eq__(self, other): return (self.__class__ == other.__class__ and \ self.x == other.x and \ self.y == other.y)
class Point(NamedTuple):
x: int y: int def __hash__(self): return hash('{},{}'.format(self.x, self.y)) def __eq__(self, other): return (self.__class__ == other.__class__ and \ self.x == other.x and \ self.y == other.y)
import sys from typing import NamedTuple class Point(NamedTuple):
16
64
74
6
9
kforiordan/advent-of-code
05-hydrothermal-venture/05-hydrothermal-venture-02.py
Python
Point
Point
6
16
6
6
40ce5f00a5b96c9f185c74d3e8481220eb0b6679
bigcode/the-stack
train
007f1e663f09a8eaefa26ae9
train
class
@add_start_docstrings( """ Hubert Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like SUPERB Keyword Spotting. """, HUBERT_START_DOCSTRING, ) # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForSequenceClassification with Wav2Ve...
@add_start_docstrings( """ Hubert Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like SUPERB Keyword Spotting. """, HUBERT_START_DOCSTRING, ) # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForSequenceClassification with Wav2Ve...
def __init__(self, config): super().__init__(config) if hasattr(config, "add_adapter") and config.add_adapter: raise ValueError( "Sequence classification does not support the use of Hubert adapters (config.add_adapter=True)" ) self.hubert = HubertMode...
) with torch.backends.cudnn.flags(enabled=False): loss = nn.functional.ctc_loss( log_probs, flattened_targets, input_lengths, target_lengths, blank=self.config.pad_token_id, ...
256
256
1,125
115
141
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertForSequenceClassification
HubertForSequenceClassification
1,212
1,334
1,212
1,220
d07376e0d9a230e10585e307d7bff0e58262231c
bigcode/the-stack
train
2a5ce63ee351d46535ffb56c
train
class
class HubertEncoderStableLayerNorm(nn.Module): def __init__(self, config): super().__init__() self.config = config self.pos_conv_embed = HubertPositionalConvEmbedding(config) self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropo...
class HubertEncoderStableLayerNorm(nn.Module):
def __init__(self, config): super().__init__() self.config = config self.pos_conv_embed = HubertPositionalConvEmbedding(config) self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout) self.layers =...
_mask, ) else: layer_outputs = layer( hidden_states, attention_mask=attention_mask, output_attentions=output_attentions ) hidden_states = layer_outputs[0] if skip_the_layer: l...
211
211
706
9
201
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertEncoderStableLayerNorm
HubertEncoderStableLayerNorm
726
812
726
726
449eaea313da27e37844cacdef2dd22aafdbe9a2
bigcode/the-stack
train
40c36a6b7943c38f15bbaac8
train
class
class HubertFeatureExtractor(HubertFeatureEncoder): def __init__(self, config): super().__init__(config) warnings.warn( f"The class `{self.__class__.__name__}` has been depreciated " "and will be removed in Transformers v5. " f"Use `{self.__class__.__bases__[0].__...
class HubertFeatureExtractor(HubertFeatureEncoder):
def __init__(self, config): super().__init__(config) warnings.warn( f"The class `{self.__class__.__name__}` has been depreciated " "and will be removed in Transformers v5. " f"Use `{self.__class__.__bases__[0].__name__}` instead.", FutureWarning, ...
(*inputs): return module(*inputs) return custom_forward hidden_states = torch.utils.checkpoint.checkpoint( create_custom_forward(conv_layer), hidden_states, ) else: hidden_st...
64
64
83
9
54
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertFeatureExtractor
HubertFeatureExtractor
369
377
369
369
4fc81713f244c94c98f887679a44ad119a814480
bigcode/the-stack
train
f0157ec030510e382f9bcce7
train
class
class HubertFeedForward(nn.Module): def __init__(self, config): super().__init__() self.intermediate_dropout = nn.Dropout(config.activation_dropout) self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): s...
class HubertFeedForward(nn.Module):
def __init__(self, config): super().__init__() self.intermediate_dropout = nn.Dropout(config.activation_dropout) self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[con...
.out_proj(attn_output) return attn_output, attn_weights_reshaped, past_key_value # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2FeedForward with Wav2Vec2->Hubert class HubertFeedForward(nn.Module):
64
64
184
7
56
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertFeedForward
HubertFeedForward
547
568
547
547
9caf1e5c6c40c80403d5f5203be601bf4175694c
bigcode/the-stack
train
fecf68d12777b27af81ad087
train
class
class HubertFeatureEncoder(nn.Module): """Construct the features from raw audio waveform""" def __init__(self, config): super().__init__() if config.feat_extract_norm == "group": conv_layers = [HubertGroupNormConvLayer(config, layer_id=0)] + [ HubertNoLayerNormConvL...
class HubertFeatureEncoder(nn.Module):
"""Construct the features from raw audio waveform""" def __init__(self, config): super().__init__() if config.feat_extract_norm == "group": conv_layers = [HubertGroupNormConvLayer(config, layer_id=0)] + [ HubertNoLayerNormConvLayer(config, layer_id=i + 1) for i in r...
_embeddings): super().__init__() self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0 def forward(self, hidden_states): if self.num_pad_remove > 0: hidden_states = hidden_states[:, :, : -self.num_pad_remove] return hidden_states # Copied from transformers...
109
109
365
7
101
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertFeatureEncoder
HubertFeatureEncoder
318
366
318
318
be772c8ef47baaaa24ebc918a9135aca121079c9
bigcode/the-stack
train
d44fe3775772bd65ee222173
train
class
class HubertPositionalConvEmbedding(nn.Module): def __init__(self, config): super().__init__() self.conv = nn.Conv1d( config.hidden_size, config.hidden_size, kernel_size=config.num_conv_pos_embeddings, padding=config.num_conv_pos_embeddings // 2, ...
class HubertPositionalConvEmbedding(nn.Module):
def __init__(self, config): super().__init__() self.conv = nn.Conv1d( config.hidden_size, config.hidden_size, kernel_size=config.num_conv_pos_embeddings, padding=config.num_conv_pos_embeddings // 2, groups=config.num_conv_pos_embedding_grou...
hidden_states): hidden_states = self.conv(hidden_states) hidden_states = self.layer_norm(hidden_states) hidden_states = self.activation(hidden_states) return hidden_states # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2PositionalConvEmbedding with Wav2Vec2->Huber...
81
81
273
9
71
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertPositionalConvEmbedding
HubertPositionalConvEmbedding
270
302
270
270
d05e0752167e49ab78b6e5b78d705d92106ca0af
bigcode/the-stack
train
983d5274baf6bf16f802298d
train
class
@add_start_docstrings( "The bare Hubert Model transformer outputting raw hidden-states without any specific head on top.", HUBERT_START_DOCSTRING, ) class HubertModel(HubertPreTrainedModel): def __init__(self, config: HubertConfig): super().__init__(config) self.config = config self....
@add_start_docstrings( "The bare Hubert Model transformer outputting raw hidden-states without any specific head on top.", HUBERT_START_DOCSTRING, ) class HubertModel(HubertPreTrainedModel):
def __init__(self, config: HubertConfig): super().__init__(config) self.config = config self.feature_extractor = HubertFeatureEncoder(config) self.feature_projection = HubertFeatureProjection(config) if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0: ...
`config.return_attention_mask == False`, such as [hubert-base](https://huggingface.co/facebook/hubert-base-ls960), `attention_mask` should **not** be passed to avoid degraded performance when doing batched inference. For such models `input_values` should simply be padded with 0 and ...
256
256
1,232
44
212
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertModel
HubertModel
941
1,081
941
945
6ff94756199cd4098bf4180b2299ae05d278a1d3
bigcode/the-stack
train
b1f5dd1230fcb03d6c47f241
train
class
class HubertAttention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, embed_dim: int, num_heads: int, dropout: float = 0.0, is_decoder: bool = False, bias: bool = True, ): super().__init__() ...
class HubertAttention(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, embed_dim: int, num_heads: int, dropout: float = 0.0, is_decoder: bool = False, bias: bool = True, ): super().__init__() self.embed_dim = embed_dim ...
__(self, config): super().__init__(config) warnings.warn( f"The class `{self.__class__.__name__}` has been depreciated " "and will be removed in Transformers v5. " f"Use `{self.__class__.__bases__[0].__name__}` instead.", FutureWarning, ) class H...
256
256
1,646
6
249
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertAttention
HubertAttention
399
543
399
399
7c14d81b2c40e8414348ff6333c2b801f54e3284
bigcode/the-stack
train
f381827f98e36516b37ac39c
train
class
class HubertPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = HubertConfig base_model_prefix = "hubert" main_input_name = "input_values" supports_gradient_chec...
class HubertPreTrainedModel(PreTrainedModel):
""" An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = HubertConfig base_model_prefix = "hubert" main_input_name = "input_values" supports_gradient_checkpointing = True _keys_to_ignore_on_load_m...
point.checkpoint( create_custom_forward(layer), hidden_states, attention_mask, ) else: layer_outputs = layer( hidden_states, attention_mask=attention_mask, output_atten...
204
204
683
12
192
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertPreTrainedModel
HubertPreTrainedModel
815
881
815
815
d784d648b468a4d6992e8a59a5f7a8d0909c0885
bigcode/the-stack
train
51ac53cec7675ad5743a4170
train
class
class HubertEncoderLayer(nn.Module): def __init__(self, config): super().__init__() self.attention = HubertAttention( embed_dim=config.hidden_size, num_heads=config.num_attention_heads, dropout=config.attention_dropout, is_decoder=False, ) ...
class HubertEncoderLayer(nn.Module):
def __init__(self, config): super().__init__() self.attention = HubertAttention( embed_dim=config.hidden_size, num_heads=config.num_attention_heads, dropout=config.attention_dropout, is_decoder=False, ) self.dropout = nn.Dropout(config....
hidden_states = self.intermediate_dropout(hidden_states) hidden_states = self.output_dense(hidden_states) hidden_states = self.output_dropout(hidden_states) return hidden_states # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2EncoderLayer with Wav2Vec2->Hubert cla...
77
77
258
7
69
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertEncoderLayer
HubertEncoderLayer
572
603
572
572
a6fb2d35e84b46b032668b0c203988463d3c6112
bigcode/the-stack
train
f53661655437f6f089acebb5
train
class
@add_start_docstrings( """Hubert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).""", HUBERT_START_DOCSTRING, ) # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForCTC with Wav2Vec2->Hubert, wav2vec2->hubert, WAV_2_VEC_2->HUBERT class HubertForCTC...
@add_start_docstrings( """Hubert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).""", HUBERT_START_DOCSTRING, ) # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForCTC with Wav2Vec2->Hubert, wav2vec2->hubert, WAV_2_VEC_2->HUBERT class HubertForCTC...
def __init__(self, config): super().__init__(config) self.hubert = HubertModel(config) self.dropout = nn.Dropout(config.final_dropout) if config.vocab_size is None: raise ValueError( f"You are trying to instantiate {self.__class__} with a configuration t...
_feature_vector_attention_mask(extract_features.shape[1], attention_mask) hidden_states = self.feature_projection(extract_features) hidden_states = self._mask_hidden_states(hidden_states, mask_time_indices=mask_time_indices) encoder_outputs = self.encoder( hidden_states, ...
256
256
1,137
105
151
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertForCTC
HubertForCTC
1,084
1,209
1,084
1,089
0d83e70999a9a2f35763f82aca9dcf94f10e003c
bigcode/the-stack
train
cc1393072a3367d224519df1
train
class
class HubertLayerNormConvLayer(nn.Module): def __init__(self, config, layer_id=0): super().__init__() self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1 self.out_conv_dim = config.conv_dim[layer_id] self.conv = nn.Conv1d( self.in_conv_dim, ...
class HubertLayerNormConvLayer(nn.Module):
def __init__(self, config, layer_id=0): super().__init__() self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1 self.out_conv_dim = config.conv_dim[layer_id] self.conv = nn.Conv1d( self.in_conv_dim, self.out_conv_dim, kernel_siz...
self.conv(hidden_states) hidden_states = self.activation(hidden_states) return hidden_states # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2LayerNormConvLayer with Wav2Vec2->Hubert class HubertLayerNormConvLayer(nn.Module):
64
64
211
9
54
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertLayerNormConvLayer
HubertLayerNormConvLayer
217
241
217
217
8f32b576470da20058a04be6265ed268a3b706f9
bigcode/the-stack
train
16bcf06e0cac3ed1347c38fe
train
class
class HubertNoLayerNormConvLayer(nn.Module): def __init__(self, config, layer_id=0): super().__init__() self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1 self.out_conv_dim = config.conv_dim[layer_id] self.conv = nn.Conv1d( self.in_conv_dim, ...
class HubertNoLayerNormConvLayer(nn.Module):
def __init__(self, config, layer_id=0): super().__init__() self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1 self.out_conv_dim = config.conv_dim[layer_id] self.conv = nn.Conv1d( self.in_conv_dim, self.out_conv_dim, kernel_siz...
spec_aug_mask_idxs, 1, -1) return spec_aug_mask # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2NoLayerNormConvLayer with Wav2Vec2->Hubert class HubertNoLayerNormConvLayer(nn.Module):
64
64
157
10
53
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertNoLayerNormConvLayer
HubertNoLayerNormConvLayer
195
213
195
195
b453e089cc842549567083b5698e5a019b05ec3b
bigcode/the-stack
train
9eec7adb8cff75906ed1de47
train
function
def _compute_mask_indices( shape: Tuple[int, int], mask_prob: float, mask_length: int, attention_mask: Optional[torch.LongTensor] = None, min_masks: int = 0, ) -> np.ndarray: """ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method f...
def _compute_mask_indices( shape: Tuple[int, int], mask_prob: float, mask_length: int, attention_mask: Optional[torch.LongTensor] = None, min_masks: int = 0, ) -> np.ndarray:
""" Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for ASR](https://arxiv.org/abs/1904.08779). Note that this method is not optimized to run on TPU and should be run on CPU as part of the preprocessing during training. Args: s...
ubert-large-ls960-ft" _EXPECTED_OUTPUT_SHAPE = [1, 292, 768] # CTC docstring _CTC_EXPECTED_OUTPUT = "'MISTER QUILTER IS THE APOSTLE OF THE MIDDLE CLASSES AND WE ARE GLAD TO WELCOME HIS GOSPEL'" _CTC_EXPECTED_LOSS = 22.68 # Audio class docstring _FEAT_EXTRACTOR_FOR_DOC = "Wav2Vec2FeatureExtractor" _SEQ_CLASS_CHECKPOIN...
256
256
1,182
53
202
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
_compute_mask_indices
_compute_mask_indices
75
191
75
81
edb51d578f776d93f9fe730373a1b6b456cdf8ac
bigcode/the-stack
train
505f75d032923baea3af9915
train
class
class HubertSamePadLayer(nn.Module): def __init__(self, num_conv_pos_embeddings): super().__init__() self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0 def forward(self, hidden_states): if self.num_pad_remove > 0: hidden_states = hidden_states[:, :, : -self.n...
class HubertSamePadLayer(nn.Module):
def __init__(self, num_conv_pos_embeddings): super().__init__() self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0 def forward(self, hidden_states): if self.num_pad_remove > 0: hidden_states = hidden_states[:, :, : -self.num_pad_remove] return hidden_...
(hidden_states) hidden_states = hidden_states.transpose(1, 2) return hidden_states # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2SamePadLayer with Wav2Vec2->Hubert class HubertSamePadLayer(nn.Module):
64
64
86
8
55
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertSamePadLayer
HubertSamePadLayer
306
314
306
306
c06cdeed53b46591415608cce08ad4381253e707
bigcode/the-stack
train
744a355521f05afc33bd020f
train
class
class HubertFeatureProjection(nn.Module): def __init__(self, config): super().__init__() self.feat_proj_layer_norm = config.feat_proj_layer_norm if self.feat_proj_layer_norm: self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps) self.projection = ...
class HubertFeatureProjection(nn.Module):
def __init__(self, config): super().__init__() self.feat_proj_layer_norm = config.feat_proj_layer_norm if self.feat_proj_layer_norm: self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps) self.projection = nn.Linear(config.conv_dim[-1], config.hidd...
warnings.warn( f"The class `{self.__class__.__name__}` has been depreciated " "and will be removed in Transformers v5. " f"Use `{self.__class__.__bases__[0].__name__}` instead.", FutureWarning, ) class HubertFeatureProjection(nn.Module):
64
64
159
7
57
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertFeatureProjection
HubertFeatureProjection
380
395
380
380
53b1c427e3007633dcfa485325189232a05d0e7b
bigcode/the-stack
train
b976492e9072cb5456f2412c
train
class
class HubertGroupNormConvLayer(nn.Module): def __init__(self, config, layer_id=0): super().__init__() self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1 self.out_conv_dim = config.conv_dim[layer_id] self.conv = nn.Conv1d( self.in_conv_dim, ...
class HubertGroupNormConvLayer(nn.Module):
def __init__(self, config, layer_id=0): super().__init__() self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1 self.out_conv_dim = config.conv_dim[layer_id] self.conv = nn.Conv1d( self.in_conv_dim, self.out_conv_dim, kernel_siz...
2, -1) hidden_states = self.activation(hidden_states) return hidden_states # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2GroupNormConvLayer with Wav2Vec2->Hubert class HubertGroupNormConvLayer(nn.Module):
64
64
191
9
54
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertGroupNormConvLayer
HubertGroupNormConvLayer
245
266
245
245
4c552e8742b82422580f0b20fd8dd983d0b1e3ca
bigcode/the-stack
train
e37bae8f615cac5a804c1b42
train
class
class HubertEncoderLayerStableLayerNorm(nn.Module): def __init__(self, config): super().__init__() self.attention = HubertAttention( embed_dim=config.hidden_size, num_heads=config.num_attention_heads, dropout=config.attention_dropout, is_decoder=False,...
class HubertEncoderLayerStableLayerNorm(nn.Module):
def __init__(self, config): super().__init__() self.attention = HubertAttention( embed_dim=config.hidden_size, num_heads=config.num_attention_heads, dropout=config.attention_dropout, is_decoder=False, ) self.dropout = nn.Dropout(config....
_states) outputs = (hidden_states,) if output_attentions: outputs += (attn_weights,) return outputs # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2EncoderLayerStableLayerNorm with Wav2Vec2->Hubert class HubertEncoderLayerStableLayerNorm(nn.Module):
76
76
254
10
65
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertEncoderLayerStableLayerNorm
HubertEncoderLayerStableLayerNorm
607
636
607
607
1e2908c1e0ce807a21b511c59f9217d54c0a4645
bigcode/the-stack
train
b2f7c68d533ffb2198855680
train
class
class HubertEncoder(nn.Module): def __init__(self, config): super().__init__() self.config = config self.pos_conv_embed = HubertPositionalConvEmbedding(config) self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidde...
class HubertEncoder(nn.Module):
def __init__(self, config): super().__init__() self.config = config self.pos_conv_embed = HubertPositionalConvEmbedding(config) self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout) self.layers =...
.feed_forward = HubertFeedForward(config) self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) def forward(self, hidden_states, attention_mask=None, output_attentions=False): attn_residual = hidden_states hidden_states = self.layer_norm(hidden_states) ...
201
201
673
6
194
bugface/transformers
src/transformers/models/hubert/modeling_hubert.py
Python
HubertEncoder
HubertEncoder
640
722
640
640
a631127a4e85ab8afc65d8a8b50711bd92ec7095
bigcode/the-stack
train
2646d09d87dcb36480308116
train
class
class Recipe(list): """ A Recipe is an ordered list that represents a program for creating a collection of tiddlers. Each line in the recipe is the combination of a bag and a filter string. For this implementation we have a list of lists. In common usage a recipe contains only strings ...
class Recipe(list):
""" A Recipe is an ordered list that represents a program for creating a collection of tiddlers. Each line in the recipe is the combination of a bag and a filter string. For this implementation we have a list of lists. In common usage a recipe contains only strings representing bags an...
""" The Recipe class. """ from tiddlyweb.model.policy import Policy class Recipe(list):
20
93
313
4
15
angeluseve/tiddlyweb
tiddlyweb/model/recipe.py
Python
Recipe
Recipe
8
56
8
8
9f791b150c35ab6c16a778ac083cfbeca4edd6ce
bigcode/the-stack
train
69b86365178fa5c3206e0ba5
train
function
def main(): # init conv net net = CNNEncoder() if os.path.exists("./model.pkl"): net.load_state_dict(torch.load("./model.pkl",map_location=lambda storage, loc: storage)) print("load model") #net.eval() print("load ok") while True: pull_screenshot("autojump.png") # obt...
def main(): # init conv net
net = CNNEncoder() if os.path.exists("./model.pkl"): net.load_state_dict(torch.load("./model.pkl",map_location=lambda storage, loc: storage)) print("load model") #net.eval() print("load ok") while True: pull_screenshot("autojump.png") # obtain screen and save it to autojump...
position_y = 1003 * (h / 1280.0) + 10 + int(random.uniform(-10,10)) def jump(press_time): print("jump:",press_time) session.tap_hold(position_x, position_y, press_time) def main(): # init conv net
64
64
166
9
55
songrotek/wechat_jump_end_to_end
run_ios.py
Python
main
main
92
115
92
95
a2d630372a6995c728fca3e2e9ed4747e14bda9e
bigcode/the-stack
train
4d78bfb38f333039a7994b7b
train
function
def jump(press_time): print("jump:",press_time) session.tap_hold(position_x, position_y, press_time)
def jump(press_time):
print("jump:",press_time) session.tap_hold(position_x, position_y, press_time)
,position_y w, h = image.size position_x = w / 2 + int(random.uniform(-10,10)) position_y = 1003 * (h / 1280.0) + 10 + int(random.uniform(-10,10)) def jump(press_time):
64
64
27
6
58
songrotek/wechat_jump_end_to_end
run_ios.py
Python
jump
jump
87
89
87
87
8c67f00724d58ba9f2ea3c8111dcb84c714d9599
bigcode/the-stack
train
31c3ebb6347998d6091b560c
train
function
def preprocess(image): w, h = image.size top = (h - w)/2 image = image.crop((0,top,w,w+top)) image = image.convert('RGB') image = image.resize((224,224), resample=Image.LANCZOS) normalize = transforms.Normalize(mean=[0.92206, 0.92206, 0.92206], std=[0.08426, 0.08426, 0.08426]) transform =...
def preprocess(image):
w, h = image.size top = (h - w)/2 image = image.crop((0,top,w,w+top)) image = image.convert('RGB') image = image.resize((224,224), resample=Image.LANCZOS) normalize = transforms.Normalize(mean=[0.92206, 0.92206, 0.92206], std=[0.08426, 0.08426, 0.08426]) transform = transforms.Compose([tr...
out = self.layer2(out) out = self.layer3(out) out = self.layer4(out) out = self.layer5(out) out = out.view(out.size(0),-1) out = self.layer6(out) return out # 64 def preprocess(image):
64
64
130
4
59
songrotek/wechat_jump_end_to_end
run_ios.py
Python
preprocess
preprocess
66
79
66
66
3284c0e98b3be02af12c73c862ade297070a1ed6
bigcode/the-stack
train
82328d54fa8bebe5a6c6ab71
train
class
class CNNEncoder(nn.Module): """docstring for ClassName""" def __init__(self): super(CNNEncoder, self).__init__() self.layer1 = nn.Sequential( nn.Conv2d(3,64,kernel_size=3,padding=0), nn.BatchNorm2d(64, momentum=1, affine=True), ...
class CNNEncoder(nn.Module):
"""docstring for ClassName""" def __init__(self): super(CNNEncoder, self).__init__() self.layer1 = nn.Sequential( nn.Conv2d(3,64,kernel_size=3,padding=0), nn.BatchNorm2d(64, momentum=1, affine=True), nn.ReLU(), ...
# coding: utf-8 import os import sys import subprocess import time import random from PIL import Image import torch import torch.nn as nn import torchvision.transforms as transforms from torch.autograd import Variable import wda SCALE = 0.93 client = wda.Client("http://169.254.105.154:8100") session = client.sessio...
108
120
403
6
102
songrotek/wechat_jump_end_to_end
run_ios.py
Python
CNNEncoder
CNNEncoder
24
64
24
24
b55c994dda772c84c451f1e59e67eb36da3f84fb
bigcode/the-stack
train
c835504cef00df961951a6d2
train
function
def set_touch_position(image): global position_x,position_y w, h = image.size position_x = w / 2 + int(random.uniform(-10,10)) position_y = 1003 * (h / 1280.0) + 10 + int(random.uniform(-10,10))
def set_touch_position(image):
global position_x,position_y w, h = image.size position_x = w / 2 + int(random.uniform(-10,10)) position_y = 1003 * (h / 1280.0) + 10 + int(random.uniform(-10,10))
.92206, 0.92206, 0.92206], std=[0.08426, 0.08426, 0.08426]) transform = transforms.Compose([transforms.ToTensor(),normalize]) image = transform(image) return image def set_touch_position(image):
64
64
68
6
57
songrotek/wechat_jump_end_to_end
run_ios.py
Python
set_touch_position
set_touch_position
81
85
81
81
06ef1d2a388697f0d1dfe5a47f4c4236231ed48e
bigcode/the-stack
train
9844729f16f31646ce8be9ea
train
function
def pull_screenshot(name="autojump.png"): client.screenshot(name)
def pull_screenshot(name="autojump.png"):
client.screenshot(name)
.nn as nn import torchvision.transforms as transforms from torch.autograd import Variable import wda SCALE = 0.93 client = wda.Client("http://169.254.105.154:8100") session = client.session() def pull_screenshot(name="autojump.png"):
64
64
17
11
53
songrotek/wechat_jump_end_to_end
run_ios.py
Python
pull_screenshot
pull_screenshot
21
22
21
21
f894841da90caef7439a8001fa65868972f788a6
bigcode/the-stack
train
22c6452a757a5361c6602284
train
function
def get_total_usage_count_for_short_url(shortened_url): return db.session.query(ShortenedUrlUsage.id).filter_by(shortened_url=shortened_url).count()
def get_total_usage_count_for_short_url(shortened_url):
return db.session.query(ShortenedUrlUsage.id).filter_by(shortened_url=shortened_url).count()
ShortenedUrlUsage from sqlalchemy import func def create(shortened_url:ShortenedUrl): shortened_url_usage = ShortenedUrlUsage(shortened_url=shortened_url) db.session.add(shortened_url_usage) return shortened_url_usage def get_total_usage_count_for_short_url(shortened_url):
64
64
36
12
51
RichardOB/url-shortener-api
api/daos/shortened_url_usage_dao.py
Python
get_total_usage_count_for_short_url
get_total_usage_count_for_short_url
10
11
10
10
a3ffaa907107685826422ab0f0b426a5c6af77b0
bigcode/the-stack
train
11567a5c051d23e40106a18a
train
function
def create(shortened_url:ShortenedUrl): shortened_url_usage = ShortenedUrlUsage(shortened_url=shortened_url) db.session.add(shortened_url_usage) return shortened_url_usage
def create(shortened_url:ShortenedUrl):
shortened_url_usage = ShortenedUrlUsage(shortened_url=shortened_url) db.session.add(shortened_url_usage) return shortened_url_usage
import uuid from api.model.models import db, ShortenedUrl, ShortenedUrlUsage from sqlalchemy import func def create(shortened_url:ShortenedUrl):
34
64
42
10
23
RichardOB/url-shortener-api
api/daos/shortened_url_usage_dao.py
Python
create
create
5
8
5
5
830745c767fe2872e94e7e9e98e94ae231caf765
bigcode/the-stack
train
d0a011b438fbbf7d39ad7092
train
function
def get_last_visit_for_url(shortened_url): return db.session.query(ShortenedUrlUsage).filter_by(shortened_url=shortened_url).order_by(ShortenedUrlUsage.used_at.desc()).first()
def get_last_visit_for_url(shortened_url):
return db.session.query(ShortenedUrlUsage).filter_by(shortened_url=shortened_url).order_by(ShortenedUrlUsage.used_at.desc()).first()
ened_url) db.session.add(shortened_url_usage) return shortened_url_usage def get_total_usage_count_for_short_url(shortened_url): return db.session.query(ShortenedUrlUsage.id).filter_by(shortened_url=shortened_url).count() def get_last_visit_for_url(shortened_url):
64
64
44
10
54
RichardOB/url-shortener-api
api/daos/shortened_url_usage_dao.py
Python
get_last_visit_for_url
get_last_visit_for_url
13
14
13
13
c4aa1d7008d4e1a1cd2fc10a2b84a0e69eac5933
bigcode/the-stack
train
04fb15fe77e605b183a55ef1
train
class
class Group(FedAvgTrainer): def __init__(self, idx, total_client_indexes, train_data_local_dict, test_data_local_dict, train_data_local_num_dict, args, device, model): self.idx = idx self.args = args self.device = device self.client_dict = {} self.train_data_local_num_dict =...
class Group(FedAvgTrainer):
def __init__(self, idx, total_client_indexes, train_data_local_dict, test_data_local_dict, train_data_local_num_dict, args, device, model): self.idx = idx self.args = args self.device = device self.client_dict = {} self.train_data_local_num_dict = train_data_local_num_dict ...
import logging from fedml_api.standalone.hierarchical_fl.client import Client from fedml_api.standalone.fedavg.fedavg_trainer import FedAvgTrainer class Group(FedAvgTrainer):
45
128
429
7
37
Alex-Roudjiat/Federated-ML-AI-Federated-ML-
fedml_api/standalone/hierarchical_fl/group.py
Python
Group
Group
6
46
6
7
16fa5eb6d0620d83af88d0c88376919513c27517
bigcode/the-stack
train
a889f3a0493710e97801a6d0
train
class
class MoveBaseProfiler(LogFileProfiler): def __init__(self, ip_addr, username, hostname) -> None: super().__init__(ip_addr, username, hostname) def process_log_files(self, output_folder, move_base_on_pc=True): ssh_client = None sftp_client = None move_base_log_file = None ...
class MoveBaseProfiler(LogFileProfiler):
def __init__(self, ip_addr, username, hostname) -> None: super().__init__(ip_addr, username, hostname) def process_log_files(self, output_folder, move_base_on_pc=True): ssh_client = None sftp_client = None move_base_log_file = None navigation_results_log_file = None ...
import os import pandas as pd from datetime import datetime from paramiko import SSHClient, AutoAddPolicy from Plugins.Profilers.LogFileProfiler import LogFileProfiler from ProgressManager.Output.OutputProcedure import OutputProcedure class MoveBaseProfiler(LogFileProfiler):
55
256
1,296
8
46
minana96/robot-runner
robot-runner/Plugins/Profilers/MoveBaseProfiler.py
Python
MoveBaseProfiler
MoveBaseProfiler
9
154
9
10
7456e47f52718959d041b448ef336c5bf0835970
bigcode/the-stack
train
5e14f15d7e2bd4fa334a47d6
train
function
def intensity_histogram_measures(regionmask: np.ndarray, intensity: np.ndarray): """Computes Intensity Distribution features This functions computes features that describe the distribution characteristic of the intensity. Args: regionmask : binary background mask intensity : inten...
def intensity_histogram_measures(regionmask: np.ndarray, intensity: np.ndarray):
"""Computes Intensity Distribution features This functions computes features that describe the distribution characteristic of the intensity. Args: regionmask : binary background mask intensity : intensity image """ feat = { "int_min": np.percentile(intensity[regio...
)), "hc_content_dna_content": np.sum(np.where(intensity[regionmask] >= hc, intensity[regionmask], 0)) / np.sum(np.where(intensity[regionmask] > 0, intensity[regionmask], 0)) } return feat def intensity_histogram_measures(regionmask: np.ndarray, intensity: np.ndarray):
77
77
257
17
59
SaradhaVenkatachalapathy/NMCO-Image-Features
nmco/nuclear_features/int_dist_features.py
Python
intensity_histogram_measures
intensity_histogram_measures
48
72
48
48
541dee4861c0a897fc425f9b9412157127e69a52
bigcode/the-stack
train
c57303a0132796f9560ae5b2
train
function
def measure_intensity_features(regionmask: np.ndarray, intensity: np.ndarray, measure_int_dist:bool = True, measure_hc_ec_ratios:bool = True, hc_alpha: int = 1): """Compute all intensity distribution features This function computes all features that describe the distribution of the gray levels. Args: ...
def measure_intensity_features(regionmask: np.ndarray, intensity: np.ndarray, measure_int_dist:bool = True, measure_hc_ec_ratios:bool = True, hc_alpha: int = 1):
"""Compute all intensity distribution features This function computes all features that describe the distribution of the gray levels. Args: regionmask : binary background mask intensity : intensity image Returns: A pandas dataframe with all the features for the given image """ ...
"entropy": shannon_entropy((intensity * regionmask)), } return feat def measure_intensity_features(regionmask: np.ndarray, intensity: np.ndarray, measure_int_dist:bool = True, measure_hc_ec_ratios:bool = True, hc_alpha: int = 1):
64
64
164
43
20
SaradhaVenkatachalapathy/NMCO-Image-Features
nmco/nuclear_features/int_dist_features.py
Python
measure_intensity_features
measure_intensity_features
75
91
75
75
41f33244583bb6caef828d353c3787e93c6361ad
bigcode/the-stack
train
ff0dd0a034acb36dab7fda84
train
function
def hetero_euchro_measures(regionmask: np.ndarray, intensity: np.ndarray, alpha: float = 1.0): """Computes Heterochromatin to Euchromatin features This functions obtains the Heterochromatin (high intensity) and Euchromatin (low intensity) and computes features that describe the relationship between the...
def hetero_euchro_measures(regionmask: np.ndarray, intensity: np.ndarray, alpha: float = 1.0):
"""Computes Heterochromatin to Euchromatin features This functions obtains the Heterochromatin (high intensity) and Euchromatin (low intensity) and computes features that describe the relationship between the two Args: regionmask : binary background mask intensity : intensity ...
Computes Heterochromatin to Euchromatin features -intensity_histogram_measures: Computes descriptors of the intensity histogram -measure_intensity_features: Computes all intensity distribution features """ # Import modules import numpy as np import pandas as pd from scipy import stats from skimage.measure import shanno...
111
111
370
28
82
SaradhaVenkatachalapathy/NMCO-Image-Features
nmco/nuclear_features/int_dist_features.py
Python
hetero_euchro_measures
hetero_euchro_measures
20
45
20
20
70bd60b828ac53305504cf0420a87c7d544c4978
bigcode/the-stack
train
9154aa8214bd370dec0df09b
train
function
def test_running_mean(): assert_almost_equal(running_mean([1, 2, 3], window_size=1), [1, 2, 3]) assert_almost_equal(running_mean([1, 2, 3], window_size=2), [1.5, 2.5]) assert_almost_equal(running_mean([2, 2, 2], window_size=3), [2]) assert_almost_equal(running_mean([3, 4, 5], window_size=20), [4])
def test_running_mean():
assert_almost_equal(running_mean([1, 2, 3], window_size=1), [1, 2, 3]) assert_almost_equal(running_mean([1, 2, 3], window_size=2), [1.5, 2.5]) assert_almost_equal(running_mean([2, 2, 2], window_size=3), [2]) assert_almost_equal(running_mean([3, 4, 5], window_size=20), [4])
_output_to_channel(11, 1) == 33 with pytest.raises(ValueError): module_output_to_channel(0, 1) # Invalid module with pytest.raises(ValueError): module_output_to_channel(2, 0) # Invalid output def test_running_mean():
64
64
118
5
58
KenMighell/lightkurve
lightkurve/tests/test_utils.py
Python
test_running_mean
test_running_mean
40
44
40
40
ccc89fa512e36449d7f4eb83a6efdbf43ae82a48
bigcode/the-stack
train
84d3496b98dbca9bdd2e4083
train
function
def test_import(): """Regression test for #605; `lk.utils` resolved to `lk.seismology.utils`""" from .. import utils assert hasattr(utils, "btjd_to_astropy_time")
def test_import():
"""Regression test for #605; `lk.utils` resolved to `lk.seismology.utils`""" from .. import utils assert hasattr(utils, "btjd_to_astropy_time")
0 def test_validate_method(): assert validate_method("foo", ["foo", "bar"]) == "foo" assert validate_method("FOO", ["foo", "bar"]) == "foo" with pytest.raises(ValueError): validate_method("foo", ["bar"]) def test_import():
63
64
45
4
59
KenMighell/lightkurve
lightkurve/tests/test_utils.py
Python
test_import
test_import
101
104
101
101
90ea8132b28f9706058756d9a96629ab32cffd9d
bigcode/the-stack
train
e11b98b6fb6ae48636d1a62d
train
function
def test_module_output_to_channel(): assert module_output_to_channel(2, 1) == 1 assert module_output_to_channel(13, 2) == 42 assert module_output_to_channel(24, 4) == 84 assert module_output_to_channel(11, 1) == 33 with pytest.raises(ValueError): module_output_to_channel(0, 1) # Invalid mod...
def test_module_output_to_channel():
assert module_output_to_channel(2, 1) == 1 assert module_output_to_channel(13, 2) == 42 assert module_output_to_channel(24, 4) == 84 assert module_output_to_channel(11, 1) == 33 with pytest.raises(ValueError): module_output_to_channel(0, 1) # Invalid module with pytest.raises(ValueError...
13, 2) assert channel_to_module_output(84) == (24, 4) assert channel_to_module_output(33) == (11, 1) with pytest.raises(ValueError): channel_to_module_output(0) # Invalid channel def test_module_output_to_channel():
64
64
117
7
56
KenMighell/lightkurve
lightkurve/tests/test_utils.py
Python
test_module_output_to_channel
test_module_output_to_channel
29
37
29
29
c7c9edfcbd7be429c57008190044d6038b3242c3
bigcode/the-stack
train
03cf6da7cff1ad3f56d08169
train
function
@pytest.mark.xfail # Lightkurve v2.x no longer support NaNs in time values def test_lightkurve_warning(): """Can we ignore Lightkurve warnings?""" with warnings.catch_warnings(record=True) as warns: warnings.simplefilter('ignore', LightkurveWarning) time = np.array([1, 2, 3, np.nan]) fl...
@pytest.mark.xfail # Lightkurve v2.x no longer support NaNs in time values def test_lightkurve_warning():
"""Can we ignore Lightkurve warnings?""" with warnings.catch_warnings(record=True) as warns: warnings.simplefilter('ignore', LightkurveWarning) time = np.array([1, 2, 3, np.nan]) flux = np.array([1, 2, 3, 4]) lc = LightCurve(time=time, flux=flux) assert len(warns) == 0
(ValueError) as err: KeplerQualityFlags.create_quality_mask(quality, bitmask='invalidoption') assert "not supported" in err.value.args[0] @pytest.mark.xfail # Lightkurve v2.x no longer support NaNs in time values def test_lightkurve_warning():
64
64
119
28
36
KenMighell/lightkurve
lightkurve/tests/test_utils.py
Python
test_lightkurve_warning
test_lightkurve_warning
83
91
83
84
2039d9feadb9ea40b249e881e9ca0df820c595b2
bigcode/the-stack
train
0478ef897d7af7f952e18c8d
train
function
def test_centroid_quadratic(): """Test basic operation of the quadratic centroiding function.""" # Single bright pixel in the center data = np.ones((9, 9)) data[2, 5] = 10 col, row = centroid_quadratic(data) assert np.isclose(row, 2) & np.isclose(col, 5) # Two equally-bright pixels side by ...
def test_centroid_quadratic():
"""Test basic operation of the quadratic centroiding function.""" # Single bright pixel in the center data = np.ones((9, 9)) data[2, 5] = 10 col, row = centroid_quadratic(data) assert np.isclose(row, 2) & np.isclose(col, 5) # Two equally-bright pixels side by side data = np.zeros((9, 9)...
jd_to_astropy_time(0).jd[0] == 2457000. for user_input in [[0], np.array([0])]: assert_array_equal(btjd_to_astropy_time(user_input).jd, np.array([2457000.])) def test_centroid_quadratic():
63
64
160
8
55
KenMighell/lightkurve
lightkurve/tests/test_utils.py
Python
test_centroid_quadratic
test_centroid_quadratic
119
132
119
119
7b9b7bdfa5ea6f130d41a39152b126612e1b7a3e
bigcode/the-stack
train
98a494d7014e8c3c73621926
train
function
def test_channel_to_module_output(): assert channel_to_module_output(1) == (2, 1) assert channel_to_module_output(42) == (13, 2) assert channel_to_module_output(84) == (24, 4) assert channel_to_module_output(33) == (11, 1) with pytest.raises(ValueError): channel_to_module_output(0) # Invali...
def test_channel_to_module_output():
assert channel_to_module_output(1) == (2, 1) assert channel_to_module_output(42) == (13, 2) assert channel_to_module_output(84) == (24, 4) assert channel_to_module_output(33) == (11, 1) with pytest.raises(ValueError): channel_to_module_output(0) # Invalid channel
kurveWarning from ..utils import running_mean, validate_method from ..utils import bkjd_to_astropy_time, btjd_to_astropy_time from ..utils import centroid_quadratic from ..lightcurve import LightCurve from .. import PACKAGEDIR def test_channel_to_module_output():
64
64
91
7
56
KenMighell/lightkurve
lightkurve/tests/test_utils.py
Python
test_channel_to_module_output
test_channel_to_module_output
20
26
20
20
0763e5910a55fc07c99889ef5fac66d58d8d3eef
bigcode/the-stack
train
e48848d4307ee7a6fa9402e5
train
function
def test_quality_mask(): """Can we create a quality mask using KeplerQualityFlags?""" quality = np.array([0, 0, 1]) assert np.all(KeplerQualityFlags.create_quality_mask(quality, bitmask=0)) assert np.all(KeplerQualityFlags.create_quality_mask(quality, bitmask=None)) assert np.all(KeplerQualityFlags....
def test_quality_mask():
"""Can we create a quality mask using KeplerQualityFlags?""" quality = np.array([0, 0, 1]) assert np.all(KeplerQualityFlags.create_quality_mask(quality, bitmask=0)) assert np.all(KeplerQualityFlags.create_quality_mask(quality, bitmask=None)) assert np.all(KeplerQualityFlags.create_quality_mask(quali...
5][1], flags[7][1]] assert TessQualityFlags.decode(flags[3][0] + flags[4][0] + flags[5][0]) \ == [flags[3][1], flags[4][1], flags[5][1]] def test_quality_mask():
63
64
198
5
58
KenMighell/lightkurve
lightkurve/tests/test_utils.py
Python
test_quality_mask
test_quality_mask
69
80
69
69
2e8e2f308a41d23808169ad11dc131fdf6e90f5f
bigcode/the-stack
train
a9f4897e43ee1bbb525f3643
train
function
def test_btjd_bkjd_input(): """Regression test for #607: are the bkjd/btjd functions tolerant?""" # Kepler assert bkjd_to_astropy_time(0).jd[0] == 2454833. for user_input in [[0], np.array([0])]: assert_array_equal(bkjd_to_astropy_time(user_input).jd, np.array([2454833.])) # TESS assert ...
def test_btjd_bkjd_input():
"""Regression test for #607: are the bkjd/btjd functions tolerant?""" # Kepler assert bkjd_to_astropy_time(0).jd[0] == 2454833. for user_input in [[0], np.array([0])]: assert_array_equal(bkjd_to_astropy_time(user_input).jd, np.array([2454833.])) # TESS assert btjd_to_astropy_time(0).jd[0...
validate_method("foo", ["bar"]) def test_import(): """Regression test for #605; `lk.utils` resolved to `lk.seismology.utils`""" from .. import utils assert hasattr(utils, "btjd_to_astropy_time") def test_btjd_bkjd_input():
64
64
157
9
55
KenMighell/lightkurve
lightkurve/tests/test_utils.py
Python
test_btjd_bkjd_input
test_btjd_bkjd_input
107
116
107
107
b919fafe0986621ac7613741872e7c437d17518c
bigcode/the-stack
train
ca8eb700428f6a87b254b35a
train
function
def test_centroid_quadratic_robustness(): """Test quadratic centroids in edge cases; regression test for #610.""" # Brightest pixel in upper left data = np.zeros((5, 5)) data[0, 0] = 1 centroid_quadratic(data) # Brightest pixel in bottom right data = np.zeros((5, 5)) data[-1, -1] = 1 ...
def test_centroid_quadratic_robustness():
"""Test quadratic centroids in edge cases; regression test for #610.""" # Brightest pixel in upper left data = np.zeros((5, 5)) data[0, 0] = 1 centroid_quadratic(data) # Brightest pixel in bottom right data = np.zeros((5, 5)) data[-1, -1] = 1 centroid_quadratic(data) # Data con...
, 1] = 5 data[5, 2] = 5 col, row = centroid_quadratic(data) assert np.isclose(row, 5) & np.isclose(col, 1.5) def test_centroid_quadratic_robustness():
64
64
173
12
52
KenMighell/lightkurve
lightkurve/tests/test_utils.py
Python
test_centroid_quadratic_robustness
test_centroid_quadratic_robustness
135
152
135
135
d416a16c9c9243069866d81dc119b54d62a7db1a
bigcode/the-stack
train
61b65d7784dcf700c1500b4c
train
function
def test_validate_method(): assert validate_method("foo", ["foo", "bar"]) == "foo" assert validate_method("FOO", ["foo", "bar"]) == "foo" with pytest.raises(ValueError): validate_method("foo", ["bar"])
def test_validate_method():
assert validate_method("foo", ["foo", "bar"]) == "foo" assert validate_method("FOO", ["foo", "bar"]) == "foo" with pytest.raises(ValueError): validate_method("foo", ["bar"])
veWarning) time = np.array([1, 2, 3, np.nan]) flux = np.array([1, 2, 3, 4]) lc = LightCurve(time=time, flux=flux) assert len(warns) == 0 def test_validate_method():
64
64
56
5
58
KenMighell/lightkurve
lightkurve/tests/test_utils.py
Python
test_validate_method
test_validate_method
94
98
94
94
4672d53d9c4483c41a060dc1109029a3ab1de2c8
bigcode/the-stack
train
9f34f2a22e281ace38d1cee8
train
function
def test_quality_flag_decoding_kepler(): """Can the QUALITY flags be parsed correctly?""" flags = list(KeplerQualityFlags.STRINGS.items()) for key, value in flags: assert KeplerQualityFlags.decode(key)[0] == value # Can we recover combinations of flags? assert KeplerQualityFlags.decode(flags...
def test_quality_flag_decoding_kepler():
"""Can the QUALITY flags be parsed correctly?""" flags = list(KeplerQualityFlags.STRINGS.items()) for key, value in flags: assert KeplerQualityFlags.decode(key)[0] == value # Can we recover combinations of flags? assert KeplerQualityFlags.decode(flags[5][0] + flags[7][0]) == [flags[5][1], fl...
2.5]) assert_almost_equal(running_mean([2, 2, 2], window_size=3), [2]) assert_almost_equal(running_mean([3, 4, 5], window_size=20), [4]) def test_quality_flag_decoding_kepler():
64
64
148
9
55
KenMighell/lightkurve
lightkurve/tests/test_utils.py
Python
test_quality_flag_decoding_kepler
test_quality_flag_decoding_kepler
47
55
47
47
356b4d5ca9a8e4f62e2d5fa0329d506b881e7ad6
bigcode/the-stack
train
8690a3cc80f697eb94f28683
train
function
def test_quality_flag_decoding_tess(): """Can the QUALITY flags be parsed correctly?""" flags = list(TessQualityFlags.STRINGS.items()) for key, value in flags: assert TessQualityFlags.decode(key)[0] == value # Can we recover combinations of flags? assert TessQualityFlags.decode(flags[5][0] +...
def test_quality_flag_decoding_tess():
"""Can the QUALITY flags be parsed correctly?""" flags = list(TessQualityFlags.STRINGS.items()) for key, value in flags: assert TessQualityFlags.decode(key)[0] == value # Can we recover combinations of flags? assert TessQualityFlags.decode(flags[5][0] + flags[7][0]) == [flags[5][1], flags[7]...
[7][1]] assert KeplerQualityFlags.decode(flags[3][0] + flags[4][0] + flags[5][0]) \ == [flags[3][1], flags[4][1], flags[5][1]] def test_quality_flag_decoding_tess():
63
64
144
9
54
KenMighell/lightkurve
lightkurve/tests/test_utils.py
Python
test_quality_flag_decoding_tess
test_quality_flag_decoding_tess
58
66
58
58
48d78b09fed9fd894b2d810d0647081ef051f704
bigcode/the-stack
train
9e6f2f265e2fd82c03a515e1
train
class
class RawTransactionsTest(BitcoinTestFramework): def __init__(self): super().__init__() self.setup_clean_chain = True self.num_nodes = 4 def setup_network(self, split=False): self.nodes = start_nodes(self.num_nodes, self.options.tmpdir) connect_nodes_bi(self.nodes,0,1)...
class RawTransactionsTest(BitcoinTestFramework):
def __init__(self): super().__init__() self.setup_clean_chain = True self.num_nodes = 4 def setup_network(self, split=False): self.nodes = start_nodes(self.num_nodes, self.options.tmpdir) connect_nodes_bi(self.nodes,0,1) connect_nodes_bi(self.nodes,1,2) ...
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * def ge...
126
256
6,934
9
117
CryptoDev-Project/klimatas-core
test/functional/rpc_fundrawtransaction.py
Python
RawTransactionsTest
RawTransactionsTest
17
661
17
18
6656c0da03c3e172d3ffa0e4a9651f7a244b3a90
bigcode/the-stack
train
f70f41327f587cc86e040721
train
function
def get_unspent(listunspent, amount): for utx in listunspent: if utx['amount'] == amount: return utx raise AssertionError('Could not find unspent with amount={}'.format(amount))
def get_unspent(listunspent, amount):
for utx in listunspent: if utx['amount'] == amount: return utx raise AssertionError('Could not find unspent with amount={}'.format(amount))
2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * def get_unspent(listunspent, amount):
64
64
51
10
54
CryptoDev-Project/klimatas-core
test/functional/rpc_fundrawtransaction.py
Python
get_unspent
get_unspent
10
14
10
10
62a9fa8952a3d8293a8619fff2b6be922c8cc56d
bigcode/the-stack
train
03a321c79e29d6d9e3fc6660
train
function
def get_formatted_name(first, last): """Generate a neatly formatted full name""" full_name = first + ' ' + last return full_name.title()
def get_formatted_name(first, last):
"""Generate a neatly formatted full name""" full_name = first + ' ' + last return full_name.title()
def get_formatted_name(first, last):
9
64
35
9
0
FuryBrand/study_notes
python_crash_course/codes/name_function.py
Python
get_formatted_name
get_formatted_name
1
4
1
1
332d9b920fb9020a298f97f272d0e8813aa83db5
bigcode/the-stack
train
1ad73952c8ec2fbaa7557efa
train
class
class TestScoreWeightCriteria(unittest.TestCase): pass
class TestScoreWeightCriteria(unittest.TestCase):
pass
# -*- coding: utf-8 -*- # Copyright (c) 2022, ajan and Contributors # See license.txt from __future__ import unicode_literals # import frappe import unittest class TestScoreWeightCriteria(unittest.TestCase):
50
64
11
9
40
samuraya/eportfolio
e_portfolio/e_portfolio/doctype/score_weight_criteria/test_score_weight_criteria.py
Python
TestScoreWeightCriteria
TestScoreWeightCriteria
9
10
9
9
c1236c3d75649afbee3fd1c0ea858b09f9afda37
bigcode/the-stack
train
0dd5e92d9ebe9137ff53403c
train
function
def parse_args(): import argparse # Parse command line arguments ap = argparse.ArgumentParser(description="Video processing pipeline") ap.add_argument("-i", "--input", default="0", help="path to input video file or camera identifier") ap.add_argument("-o", "--output", default="o...
def parse_args():
import argparse # Parse command line arguments ap = argparse.ArgumentParser(description="Video processing pipeline") ap.add_argument("-i", "--input", default="0", help="path to input video file or camera identifier") ap.add_argument("-o", "--output", default="output", ...
import os from tqdm import tqdm from pipeline.capture_video import CaptureVideo from pipeline.detect_faces import DetectFaces from pipeline.save_faces import SaveFaces from pipeline.save_summary import SaveSummary from pipeline.annotate_image import AnnotateImage from pipeline.display_video import DisplayVideo from pi...
70
89
298
4
65
dregula/image-processing-pipeline
process_video_pipeline.py
Python
parse_args
parse_args
13
37
13
13
1a7f23e36bb4f89040fba43052a1bf85497a8070
bigcode/the-stack
train
8624652a108ef798537b9431
train
function
def main(args): # Create pipeline steps capture_video = CaptureVideo(int(args.input) if args.input.isdigit() else args.input) detect_faces = DetectFaces(prototxt=args.prototxt, model=args.model, confidence=args.confidence, batch_size=args.batch_size) save_faces = SaveFac...
def main(args): # Create pipeline steps
capture_video = CaptureVideo(int(args.input) if args.input.isdigit() else args.input) detect_faces = DetectFaces(prototxt=args.prototxt, model=args.model, confidence=args.confidence, batch_size=args.batch_size) save_faces = SaveFaces(args.output) summary_file = os.path....
models/face_detector/res10_300x300_ssd_iter_140000.caffemodel", help="path to Caffe pre-trained model") ap.add_argument("--confidence", type=float, default=0.5, help="minimum probability to filter weak face detections") ap.add_argument("--batch-size", type=int, default=1,...
99
99
331
10
89
dregula/image-processing-pipeline
process_video_pipeline.py
Python
main
main
40
91
40
41
152491f32ee8974a2d04b9e592557793018e889e
bigcode/the-stack
train
3263b8eff453900af81f55ab
train
function
def lof(params: ParameterConfig = None, skip_pull: bool = False, timeout: Optional[Duration] = None) -> Algorithm: return Algorithm( name="LOF", main=DockerAdapter( image_name="registry.gitlab.hpi.de/akita/i/lof", skip_pull=skip_pull, timeout=timeout, ...
def lof(params: ParameterConfig = None, skip_pull: bool = False, timeout: Optional[Duration] = None) -> Algorithm:
return Algorithm( name="LOF", main=DockerAdapter( image_name="registry.gitlab.hpi.de/akita/i/lof", skip_pull=skip_pull, timeout=timeout, group_privileges="akita", ), preprocess=None, postprocess=None, param_schema=_lof_p...
"defaultValue": 42, "description": "Seed for random number generation.", "name": "random_state", "type": "int" } } def lof(params: ParameterConfig = None, skip_pull: bool = False, timeout: Optional[Duration] = None) -> Algorithm:
64
64
140
28
36
HPI-Information-Systems/TimeEval
timeeval_experiments/algorithms/lof.py
Python
lof
lof
43
59
43
43
1d4b0c7dc8b580fb46b13414464f09d74e84fdf3
bigcode/the-stack
train
be4e05339af74b50646a2b52
train
function
def change_bg(path,outputs): IMAGE_FILES = [f"{path}/{file}"for file in os.listdir(path)] for img in IMAGE_FILES: output_name = img.split('/')[-1].split('.')[0] # run_win_cmd(f"backgroundremover -i {img} -a -ae 15 -o {outputs}/{output_name}.jpg") run_win_cmd(f"backgroundremover -i {...
def change_bg(path,outputs):
IMAGE_FILES = [f"{path}/{file}"for file in os.listdir(path)] for img in IMAGE_FILES: output_name = img.split('/')[-1].split('.')[0] # run_win_cmd(f"backgroundremover -i {img} -a -ae 15 -o {outputs}/{output_name}.jpg") run_win_cmd(f"backgroundremover -i {img} -o {outputs}/{output_name...
target_img_width] image = cv2.resize(image,(768,1024)) # cv2.imshow('test',image) # cv2.waitKey(0) # cv2.destroyAllWindows() cv2.imwrite(f"{output}/{file_name}", image) #更換背景 def change_bg(path,outputs):
69
69
231
7
61
liuzihau/OutdoorAtHome
subpro_backgroundremover.py
Python
change_bg
change_bg
67
83
67
67
370f5fdb4ad24abda1034c5f901b18a1ac63f043
bigcode/the-stack
train
e992225d3f9c43f1fdd52647
train
function
def pretreat(path,output): mp_pose = mp.solutions.pose # For static images: IMAGE_FILES = [f"{path}/{file}"for file in os.listdir(path)] with mp_pose.Pose( static_image_mode=True, # model_complexity=2, # enable_segmentation=True, min_detection_confidence=0.5) as p...
def pretreat(path,output):
mp_pose = mp.solutions.pose # For static images: IMAGE_FILES = [f"{path}/{file}"for file in os.listdir(path)] with mp_pose.Pose( static_image_mode=True, # model_complexity=2, # enable_segmentation=True, min_detection_confidence=0.5) as pose: for ...
import os from shutil import copyfile import subprocess import time import mediapipe as mp import cv2 import numpy as np # 找出人物位置並置中 調成768*1024 def pretreat(path,output):
54
234
781
7
46
liuzihau/OutdoorAtHome
subpro_backgroundremover.py
Python
pretreat
pretreat
12
64
12
12
5ba9e5db5d509062f99165054643688fdb5f329c
bigcode/the-stack
train
33520a7624d2b13ba97d3798
train
function
def copy_img(folder): path = [f"{folder}\\{file}" for file in os.listdir(folder)] # print(path) for file in path: f = file.split('\\')[1] copyfile(file,f"VITON-HD/datasets/test2/image/{f}")
def copy_img(folder):
path = [f"{folder}\\{file}" for file in os.listdir(folder)] # print(path) for file in path: f = file.split('\\')[1] copyfile(file,f"VITON-HD/datasets/test2/image/{f}")
,j] = background[i,j,:] cv2.imwrite(f"{outputs}/{output_name}.jpg", conbine) # 把final_imgs 放到測試資料夾裡 # 測試資料:'VITON-HD\\datasets\\test2\\image\\' def copy_img(folder):
64
64
61
5
59
liuzihau/OutdoorAtHome
subpro_backgroundremover.py
Python
copy_img
copy_img
89
94
89
89
43cdee5966289740be52a1311103d7ab11b70fd1
bigcode/the-stack
train
e604dbba14a7b73f6bbf326c
train
function
def run_win_cmd(cmd): result = [] process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) for line in process.stdout: result.append(line) errcode = process.ret...
def run_win_cmd(cmd):
result = [] process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) for line in process.stdout: result.append(line) errcode = process.returncode for line i...
1 and ic == len(cloth)-1: f.write(f"{p} {c}") else: f.write(f"{p} {c}"+' \n') #執行腳本來生出openpose的圖跟JSON以及Human Parsing def run_win_cmd(cmd):
64
64
85
6
57
liuzihau/OutdoorAtHome
subpro_backgroundremover.py
Python
run_win_cmd
run_win_cmd
110
122
110
110
3759c252371a71b696ff89e72294b43e7da41419
bigcode/the-stack
train
e269c635299ac45b95558690
train
function
def test_pair(pair_folder,target_folder,txt_name): cloth = os.listdir(f"{pair_folder}\{target_folder}\cloth") person = os.listdir(f"{pair_folder}\{target_folder}\image") with open(f"{pair_folder}\{txt_name}",'w') as f: for ip,p in enumerate(person): for ic,c in enumerate(cloth): ...
def test_pair(pair_folder,target_folder,txt_name):
cloth = os.listdir(f"{pair_folder}\{target_folder}\cloth") person = os.listdir(f"{pair_folder}\{target_folder}\image") with open(f"{pair_folder}\{txt_name}",'w') as f: for ip,p in enumerate(person): for ic,c in enumerate(cloth): if ip == len(person)-1 and ic == len(c...
}" for file in os.listdir(folder)] # print(path) for file in path: f = file.split('\\')[1] copyfile(file,f"VITON-HD/datasets/test2/image/{f}") #製造test_pair def test_pair(pair_folder,target_folder,txt_name):
64
64
123
11
52
liuzihau/OutdoorAtHome
subpro_backgroundremover.py
Python
test_pair
test_pair
97
106
97
97
e1e167d307fa5790c2295f8dc40e9d42e6b8bc07
bigcode/the-stack
train
5756891a3cd2f926d000e5f4
train
class
class SemanticSearchFilter(filters.SearchFilter): def filter_queryset(self, request, queryset, view): search_fields = self.get_search_fields(view, request) search_terms = self.get_search_terms(request) if not search_fields or not search_terms: return queryset orm_lookup...
class SemanticSearchFilter(filters.SearchFilter):
def filter_queryset(self, request, queryset, view): search_fields = self.get_search_fields(view, request) search_terms = self.get_search_terms(request) if not search_fields or not search_terms: return queryset orm_lookups = [ self.construct_search(str(search...
import operator from functools import reduce from rest_framework.compat import distinct from django.db.models.expressions import RawSQL from django.db.models import Q from rest_framework import filters from api.semantic_search.semantic_search import semantic_search_instance from api.image_similarity import search_sim...
68
93
312
8
59
jayesh100/librephotos
api/filters.py
Python
SemanticSearchFilter
SemanticSearchFilter
12
52
12
12
132186e82c250cf9b653615649525f090ad1b655
bigcode/the-stack
train
5db9b52e31781f4bb0a3c9df
train
class
class GoogleContactsStorage(dav.CardDAVStorage): class session_class(GoogleSession): # Google CardDAV is completely bonkers. Collection discovery doesn't # work properly, well-known URI takes us directly to single collection # from where we can't discover principal or homeset URIs (the PROPF...
class GoogleContactsStorage(dav.CardDAVStorage):
class session_class(GoogleSession): # Google CardDAV is completely bonkers. Collection discovery doesn't # work properly, well-known URI takes us directly to single collection # from where we can't discover principal or homeset URIs (the PROPFINDs # 404). # # So we co...
=end_date, item_types=item_types, **kwargs, ) # This is ugly: We define/override the entire signature computed for the # docs here because the current way we autogenerate those docs are too # simple for our advanced argspec juggling in `vdirsyncer.storage.dav`. __init__....
91
91
306
10
80
dilyanpalauzov/vdirsyncer
vdirsyncer/storage/google.py
Python
GoogleContactsStorage
GoogleContactsStorage
178
210
178
178
5738d6175bc0f4f24e803cfafb46f1bebffef7be
bigcode/the-stack
train
33f287c7969734ced67d5cfd
train
class
class GoogleSession(dav.DAVSession): def __init__( self, token_file, client_id, client_secret, url=None, connector: aiohttp.BaseConnector = None, ): if not have_oauth2: raise exceptions.UserError("aiohttp-oauthlib not installed") # Req...
class GoogleSession(dav.DAVSession):
def __init__( self, token_file, client_id, client_secret, url=None, connector: aiohttp.BaseConnector = None, ): if not have_oauth2: raise exceptions.UserError("aiohttp-oauthlib not installed") # Required for discovering collections ...
import json import logging import os import urllib.parse as urlparse from pathlib import Path import aiohttp import click from atomicwrites import atomic_write from .. import exceptions from ..utils import checkdir from ..utils import expand_path from ..utils import open_graphical_browser from . import base from . im...
156
203
677
9
146
dilyanpalauzov/vdirsyncer
vdirsyncer/storage/google.py
Python
GoogleSession
GoogleSession
32
129
32
32
a801698b1e5f9a55b317dae4a01beee517a2ead2
bigcode/the-stack
train
cb087545c4529bb3409d7e88
train
class
class GoogleCalendarStorage(dav.CalDAVStorage): class session_class(GoogleSession): url = "https://apidata.googleusercontent.com/caldav/v2/" scope = ["https://www.googleapis.com/auth/calendar"] class discovery_class(dav.CalDiscover): @staticmethod def _get_collection_from_url(ur...
class GoogleCalendarStorage(dav.CalDAVStorage):
class session_class(GoogleSession): url = "https://apidata.googleusercontent.com/caldav/v2/" scope = ["https://www.googleapis.com/auth/calendar"] class discovery_class(dav.CalDiscover): @staticmethod def _get_collection_from_url(url): # Google CalDAV has collection U...
(str(e)) click.echo("Follow the instructions on the page.") code = click.prompt("Paste obtained code") self._token = await session.fetch_token( REFRESH_URL, code=code, # Google specific extra param used for cli...
90
90
302
10
80
dilyanpalauzov/vdirsyncer
vdirsyncer/storage/google.py
Python
GoogleCalendarStorage
GoogleCalendarStorage
132
175
132
132
bef76cda7d9f310a11a4e5f916cf493cb3b8fd05
bigcode/the-stack
train
638d285233ed0fa14fe55662
train
class
class Edge: """Simple representation of an edge in a graph. Goes along with GraphNode. """ def __init__(self, weight, start, end): self._weight = weight self._start = start self._end = end def __eq__(self, other): if not isinstance(other, Edge): raise ValueEr...
class Edge:
"""Simple representation of an edge in a graph. Goes along with GraphNode. """ def __init__(self, weight, start, end): self._weight = weight self._start = start self._end = end def __eq__(self, other): if not isinstance(other, Edge): raise ValueError("Cannot ...
other): return not self == other def __hash__(self): return hash(self._node_id) @property def node_id(self): return self._node_id @property def edges(self): return self._edges def add_edge(self, new_edge): self._edges.add(new_edge) class Edge:
76
76
255
3
73
boxsome/Python-Projects
Graph/graph_classes.py
Python
Edge
Edge
35
74
35
35
a652f5c65c6788c48345d448b3048337126592bb
bigcode/the-stack
train
ce2a9268b1866cf069ffa4cc
train
class
class GraphNode: """Simple representation of a node in a graph. The graph itself would be a set of these graph nodes. The graph can be either directed or undirected, depending on if two connected nodes contain the edge for each other or not. """ def __init__(self, node_id): self._node_id = ...
class GraphNode:
"""Simple representation of a node in a graph. The graph itself would be a set of these graph nodes. The graph can be either directed or undirected, depending on if two connected nodes contain the edge for each other or not. """ def __init__(self, node_id): self._node_id = node_id s...
class GraphNode:
4
64
209
4
0
boxsome/Python-Projects
Graph/graph_classes.py
Python
GraphNode
GraphNode
1
32
1
1
969ad38f8d11c872ad726b4fe63f0f18915c2ab3
bigcode/the-stack
train
767a11fa5d0d58a75dab10d3
train
class
class MultiStateSampler(object): """ Base class for samplers that sample multiple thermodynamic states using one or more replicas. This base class provides a general simulation facility for multistate from multiple thermodynamic states, allowing any set of thermodynamic states to be specified. ...
class MultiStateSampler(object):
""" Base class for samplers that sample multiple thermodynamic states using one or more replicas. This base class provides a general simulation facility for multistate from multiple thermodynamic states, allowing any set of thermodynamic states to be specified. If instantiated on its own, the t...
ab.org>, Levi N. Naden <levi.naden@choderalab.org> and John D. Chodera <john.chodera@choderalab.org> while at Memorial Sloan Kettering Cancer Center. Original version by John D. Chodera <jchodera@gmail.com> while at the University of California Berkeley. LICENSE This code is licensed under the latest available versi...
255
256
15,438
6
249
Lnaden/openmmtools
openmmtools/multistate/multistatesampler.py
Python
MultiStateSampler
MultiStateSampler
60
1,620
60
60
1cb1ed4f99b35ac42e6fa7a35defe884977e4ee4
bigcode/the-stack
train
e7fe456731ce081e18dd3fc5
train
class
class ArcStandardModel(nn.Module): def __init__(self, device, config, vocab_relation): """ Parameters ---------- device: str config: ConfigTree vocab_relation: dict[str, int] """ super().__init__() ...
class ArcStandardModel(nn.Module):
def __init__(self, device, config, vocab_relation): """ Parameters ---------- device: str config: ConfigTree vocab_relation: dict[str, int] """ super().__init__() ################ # Hy...
import torch import torch.nn as nn from transformers import AutoModel from transformers import AutoTokenizer from . import shared_functions class ArcStandardModel(nn.Module):
34
256
1,978
7
26
norikinishida/discourse-parsing
src/models/shiftreduce.py
Python
ArcStandardModel
ArcStandardModel
9
209
9
10
fc9978fb4b39625b88370d2e68148f4670ce109e
bigcode/the-stack
train
5c52e15c2606d297d5ff3b0b
train
class
class LoginUserViewTests(django_test.TestCase): CREDENTIALS = { 'username': 'User', 'email': 'user@email.com', 'password': 'testp@ss', } @classmethod def setUpClass(cls): super().setUpClass() cls.USER = UserModel.objects.create_user(**cls.CREDENTIALS) def te...
class LoginUserViewTests(django_test.TestCase):
CREDENTIALS = { 'username': 'User', 'email': 'user@email.com', 'password': 'testp@ss', } @classmethod def setUpClass(cls): super().setUpClass() cls.USER = UserModel.objects.create_user(**cls.CREDENTIALS) def test_login_with_username__when_valid_credential__e...
from django import test as django_test from django.contrib.auth import get_user_model from django.urls import reverse UserModel = get_user_model() class LoginUserViewTests(django_test.TestCase):
41
159
532
11
30
Govedarski/World-of-books
my_project/my_project/accounts/tests/views/test_LoginUserView.py
Python
LoginUserViewTests
LoginUserViewTests
8
60
8
8
207a0f691cc66efbf76d9f803cd99deb0ff39f11
bigcode/the-stack
train
1bd2bdfb8e79fae8d0635f22
train
function
def supports_api(api_id): """ Returns ``True`` if given API is supported. """ try: get_api(api_id) except ImportError: return False return True
def supports_api(api_id):
""" Returns ``True`` if given API is supported. """ try: get_api(api_id) except ImportError: return False return True
the identifier of the ``PyOpenCL``-based API.""" return 'ocl' def api_ids(): """ Returns a list of identifiers for all known (not necessarily available for the current system) APIs. """ return [ocl_id(), cuda_id()] def supports_api(api_id):
63
64
43
6
57
ringw/reikna
reikna/cluda/api_discovery.py
Python
supports_api
supports_api
22
31
22
22
20a6ce95d8b94d6828fd9eca0394590e67463bd6
bigcode/the-stack
train
7248a622378292f19137a59b
train
function
def cuda_api(): """ Returns the ``PyCUDA``-based API module. """ return get_api(cuda_id())
def cuda_api():
""" Returns the ``PyCUDA``-based API module. """ return get_api(cuda_id())
cluda.cuda return reikna.cluda.cuda elif api_id == ocl_id(): import reikna.cluda.ocl return reikna.cluda.ocl else: raise ValueError("Unrecognized API: " + str(api_id)) def cuda_api():
64
64
27
4
60
ringw/reikna
reikna/cluda/api_discovery.py
Python
cuda_api
cuda_api
56
60
56
56
3e93ba1dfbf3583e12985cc61885295d90730219
bigcode/the-stack
train
130a7bd4a9170bee02c2bd85
train
function
def cuda_id(): """Returns the identifier of the ``PyCUDA``-based API.""" return 'cuda'
def cuda_id():
"""Returns the identifier of the ``PyCUDA``-based API.""" return 'cuda'
""" This module contains functions for API discovery. """ def cuda_id():
14
64
24
4
10
ringw/reikna
reikna/cluda/api_discovery.py
Python
cuda_id
cuda_id
6
8
6
6
6bb382fc703bc4f64e7584b574806d97e373b6ac
bigcode/the-stack
train
8a43135e350ac4272cec5b12
train
function
def ocl_api(): """ Returns the ``PyOpenCL``-based API module. """ return get_api(ocl_id())
def ocl_api():
""" Returns the ``PyOpenCL``-based API module. """ return get_api(ocl_id())
a.ocl return reikna.cluda.ocl else: raise ValueError("Unrecognized API: " + str(api_id)) def cuda_api(): """ Returns the ``PyCUDA``-based API module. """ return get_api(cuda_id()) def ocl_api():
64
64
30
5
59
ringw/reikna
reikna/cluda/api_discovery.py
Python
ocl_api
ocl_api
63
67
63
63
5aaf6585dcce56052b2c479641e1a92050584a9f
bigcode/the-stack
train
28ae78d333825b0ae6eee49c
train
function
def supported_api_ids(): """ Returns a list of identifiers of supported APIs. """ return [api_id for api_id in api_ids() if supports_api(api_id)]
def supported_api_ids():
""" Returns a list of identifiers of supported APIs. """ return [api_id for api_id in api_ids() if supports_api(api_id)]
system) APIs. """ return [ocl_id(), cuda_id()] def supports_api(api_id): """ Returns ``True`` if given API is supported. """ try: get_api(api_id) except ImportError: return False return True def supported_api_ids():
64
64
37
5
58
ringw/reikna
reikna/cluda/api_discovery.py
Python
supported_api_ids
supported_api_ids
34
38
34
34
28eb935708a4daa3ae865959bd51db68da6e6186
bigcode/the-stack
train
fec3a39505dc9e1168bcfad5
train
function
def ocl_id(): """Returns the identifier of the ``PyOpenCL``-based API.""" return 'ocl'
def ocl_id():
"""Returns the identifier of the ``PyOpenCL``-based API.""" return 'ocl'
""" This module contains functions for API discovery. """ def cuda_id(): """Returns the identifier of the ``PyCUDA``-based API.""" return 'cuda' def ocl_id():
39
64
26
5
34
ringw/reikna
reikna/cluda/api_discovery.py
Python
ocl_id
ocl_id
10
12
10
10
0bd1db3291c3cc89690ac7fbd91f495923a7490c
bigcode/the-stack
train
14517d80b53f56456c17cde1
train
function
def api_ids(): """ Returns a list of identifiers for all known (not necessarily available for the current system) APIs. """ return [ocl_id(), cuda_id()]
def api_ids():
""" Returns a list of identifiers for all known (not necessarily available for the current system) APIs. """ return [ocl_id(), cuda_id()]
""" This module contains functions for API discovery. """ def cuda_id(): """Returns the identifier of the ``PyCUDA``-based API.""" return 'cuda' def ocl_id(): """Returns the identifier of the ``PyOpenCL``-based API.""" return 'ocl' def api_ids():
64
64
39
4
60
ringw/reikna
reikna/cluda/api_discovery.py
Python
api_ids
api_ids
14
19
14
14
d8802ca83f52f265df835cdd1d1f6593a7dc3d40
bigcode/the-stack
train
73308fa11cd771242cb28e9a
train
function
def get_api(api_id): """ Returns an API module with the generalized interface :py:mod:`reikna.cluda.api` for the given identifier. """ if api_id == cuda_id(): import reikna.cluda.cuda return reikna.cluda.cuda elif api_id == ocl_id(): import reikna.cluda.ocl return...
def get_api(api_id):
""" Returns an API module with the generalized interface :py:mod:`reikna.cluda.api` for the given identifier. """ if api_id == cuda_id(): import reikna.cluda.cuda return reikna.cluda.cuda elif api_id == ocl_id(): import reikna.cluda.ocl return reikna.cluda.ocl ...
: get_api(api_id) except ImportError: return False return True def supported_api_ids(): """ Returns a list of identifiers of supported APIs. """ return [api_id for api_id in api_ids() if supports_api(api_id)] def get_api(api_id):
63
64
111
6
57
ringw/reikna
reikna/cluda/api_discovery.py
Python
get_api
get_api
41
53
41
41
8c0ae9849082ddc7ff9524bc66e1bdc44dd071a1
bigcode/the-stack
train
e666d93a954b8bfae00dc4f6
train
function
def any_api(): """ Returns one of the API modules supported by the system or raises an ``Exception`` if there are not any. """ api_ids = supported_api_ids() if len(api_ids) == 0: raise Exception("No supported GPGPU APIs found") return get_api(api_ids[0])
def any_api():
""" Returns one of the API modules supported by the system or raises an ``Exception`` if there are not any. """ api_ids = supported_api_ids() if len(api_ids) == 0: raise Exception("No supported GPGPU APIs found") return get_api(api_ids[0])
(api_id)) def cuda_api(): """ Returns the ``PyCUDA``-based API module. """ return get_api(cuda_id()) def ocl_api(): """ Returns the ``PyOpenCL``-based API module. """ return get_api(ocl_id()) def any_api():
64
64
72
4
60
ringw/reikna
reikna/cluda/api_discovery.py
Python
any_api
any_api
70
78
70
70
ebcb579d5dca8efb212d1f351f9d273ae5dd5f99
bigcode/the-stack
train
1ffc3dab1bf5da29751e6c90
train
function
def _flatten(_list): for item in _list: if isinstance(item, list) or isinstance(item, tuple): yield from flatten(item) else: yield item
def _flatten(_list):
for item in _list: if isinstance(item, list) or isinstance(item, tuple): yield from flatten(item) else: yield item
ue)?$', str(value)): log.info("return True") return True elif re.match('^[Ff](?:alse)?$', str(value)): log.info("return False") return False log.info("return %s", value) return value def _flatten(_list):
64
64
39
6
57
microspectrometer/microspec
src/microspeclib/internal/util.py
Python
_flatten
_flatten
62
67
62
62
81c0c372154644d57ba1349204f61fb5cedd7076
bigcode/the-stack
train
8a266b6eb9ffef7c8d3aeb84
train
class
class MicroSpecInteger(int): """A subclass of Python int that remembers it's byte width and name so that it can be converted to bytes and str properly""" def __new__(self, value, size=1, byteorder="big", signed=False, name=None): log.info("value=%d size=%d byteorder=%s signed=%s name=%s", value, size, byte...
class MicroSpecInteger(int):
"""A subclass of Python int that remembers it's byte width and name so that it can be converted to bytes and str properly""" def __new__(self, value, size=1, byteorder="big", signed=False, name=None): log.info("value=%d size=%d byteorder=%s signed=%s name=%s", value, size, byteorder, signed, name) self ...
# Copyright 2020 by Chromation, Inc # All Rights Reserved by Chromation, Inc from microspeclib.logger import CHROMASPEC_LOGGER_UTIL as log from struct import unpack, pack import re import itertools class MicroSpecInteger(int):
58
64
213
6
51
microspectrometer/microspec
src/microspeclib/internal/util.py
Python
MicroSpecInteger
MicroSpecInteger
10
34
10
11
b7fb8687703e548217d2663abccada8baa661296
bigcode/the-stack
train
5717c99de13829fc55569265
train
function
def isInt(i): log.info("int=%s", i) try: if int(i) == i: log.info("return True") return True except: log.info("return False") return False return False
def isInt(i):
log.info("int=%s", i) try: if int(i) == i: log.info("return True") return True except: log.info("return False") return False return False
if self.name: return self.name return super().__str__() def __bytes__(self): log.info("") b = self.to_bytes(self.size, self.byteorder, signed=self.signed) log.info("return %s", b) return b def isInt(i):
64
64
55
5
58
microspectrometer/microspec
src/microspeclib/internal/util.py
Python
isInt
isInt
36
45
36
36
890b7b851481cb7abfafed246db31e8e4e1319d4
bigcode/the-stack
train
fe9e75c6f6ed61cb1d6ac947
train
function
def dehex(value): log.info("value=%s", value) if re.match('^0x[0-9a-fA-F]+$', str(value)): h = int(value, 16) log.info("return %d", h) return h elif re.match('^[Tt](?:rue)?$', str(value)): log.info("return True") return True elif re.match('^[Ff](?:alse)?$', str(value)): log.info("return ...
def dehex(value):
log.info("value=%s", value) if re.match('^0x[0-9a-fA-F]+$', str(value)): h = int(value, 16) log.info("return %d", h) return h elif re.match('^[Tt](?:rue)?$', str(value)): log.info("return True") return True elif re.match('^[Ff](?:alse)?$', str(value)): log.info("return False") return...
return b def isInt(i): log.info("int=%s", i) try: if int(i) == i: log.info("return True") return True except: log.info("return False") return False return False def dehex(value):
64
64
128
5
58
microspectrometer/microspec
src/microspeclib/internal/util.py
Python
dehex
dehex
47
60
47
47
a048bb4f4c779bf0586adb7652d71f2aec8d6a0e
bigcode/the-stack
train
f713b7ed504e9540bc5a820a
train
function
def flatten(_list): return list(_flatten(_list))
def flatten(_list):
return list(_flatten(_list))
False") return False log.info("return %s", value) return value def _flatten(_list): for item in _list: if isinstance(item, list) or isinstance(item, tuple): yield from flatten(item) else: yield item def flatten(_list):
64
64
13
5
58
microspectrometer/microspec
src/microspeclib/internal/util.py
Python
flatten
flatten
69
70
69
69
8442a6839af990e54c619d1d3057fad6d327299f
bigcode/the-stack
train
6d7ff2780a36fdaa80e974cb
train
function
@app.route("/webhooks/event", methods=['POST']) def event(): return "OK"
@app.route("/webhooks/event", methods=['POST']) def event():
return "OK"
@app.route("/webhooks/notification", methods=['POST']) def notification(): ncco = [{ "action": "talk", "text": "Your notification has been received, loud and clear" }] return jsonify(ncco) @app.route("/webhooks/event", methods=['POST']) def event():
64
64
19
14
50
Vibhuti1402agg/vonage-python-code-snippets
voice/track-ncco.py
Python
event
event
34
36
34
35
d42c479c7786f052f70ae85ca387fd5712af9d94
bigcode/the-stack
train
9e0ea248242bf5f57ae4f596
train
function
@app.route("/webhooks/answer") def answer_call(): ncco = [{ "action": "talk", "text": "Thanks for calling the notification line" }, { "action": "notify", "payload": { "foo": "bar" }, "eventUrl": [ "{url_root}webhooks/notification".format(url_root=request.url...
@app.route("/webhooks/answer") def answer_call():
ncco = [{ "action": "talk", "text": "Thanks for calling the notification line" }, { "action": "notify", "payload": { "foo": "bar" }, "eventUrl": [ "{url_root}webhooks/notification".format(url_root=request.url_root) ] }, { "action": "talk"...
from flask import Flask, request, jsonify app = Flask(__name__) @app.route("/webhooks/answer") def answer_call():
27
64
125
12
15
Vibhuti1402agg/vonage-python-code-snippets
voice/track-ncco.py
Python
answer_call
answer_call
5
24
5
6
0d64169d6c126dc5eb95bdfe6af218a8d170c021
bigcode/the-stack
train
971cce1d6f47a84a14a98ef7
train
function
@app.route("/webhooks/notification", methods=['POST']) def notification(): ncco = [{ "action": "talk", "text": "Your notification has been received, loud and clear" }] return jsonify(ncco)
@app.route("/webhooks/notification", methods=['POST']) def notification():
ncco = [{ "action": "talk", "text": "Your notification has been received, loud and clear" }] return jsonify(ncco)
".format(url_root=request.url_root) ] }, { "action": "talk", "text": "You will never hear me as the notification URL will return an NCCO " }] return jsonify(ncco) @app.route("/webhooks/notification", methods=['POST']) def notification():
64
64
50
15
49
Vibhuti1402agg/vonage-python-code-snippets
voice/track-ncco.py
Python
notification
notification
26
32
26
27
9c3329aa835c2c9af8aa4735790cb87a00977916
bigcode/the-stack
train
60e946ae1f00b87fa2e77e98
train
class
class Migration(migrations.Migration): dependencies = [ ('issues', '0012_auto_20150324_2219'), ] operations = [ migrations.CreateModel( name='TicketStatus', fields=[ ('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, prima...
class Migration(migrations.Migration):
dependencies = [ ('issues', '0012_auto_20150324_2219'), ] operations = [ migrations.CreateModel( name='TicketStatus', fields=[ ('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)), ('categor...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):
31
183
613
7
23
noracami/track-it
trackit/issues/migrations/0013_auto_20150324_2220.py
Python
Migration
Migration
7
82
7
8
954343a114d7992280c24059b1d4c0111a3bc4e9
bigcode/the-stack
train
d40773c1fe220c142ed16f8a
train
function
def calc_lonely_cow(total_cows, cow_str): total_lonely_cow = 0 #for offset in range(3, total_cows + 1): for offset in range(3, 60): for start_pos in range(0, total_cows): total_count_g = total_count_h = 0 if start_pos + offset > total_cows: break f...
def calc_lonely_cow(total_cows, cow_str):
total_lonely_cow = 0 #for offset in range(3, total_cows + 1): for offset in range(3, 60): for start_pos in range(0, total_cows): total_count_g = total_count_h = 0 if start_pos + offset > total_cows: break for cur_index in range(start_pos, start_pos...
def get_input(): total_cows = int(input("")) cow_str = input("") return total_cows, cow_str def calc_lonely_cow(total_cows, cow_str):
41
64
186
13
27
karenz50/test_repo_1
q1.2.py
Python
calc_lonely_cow
calc_lonely_cow
7
26
7
7
8264e0c4e53ed20cc90720c589c2d46ff44b6e3b
bigcode/the-stack
train
9a984e7efbe2eeabdea3ad8a
train
function
def get_input(): total_cows = int(input("")) cow_str = input("") return total_cows, cow_str
def get_input():
total_cows = int(input("")) cow_str = input("") return total_cows, cow_str
def get_input():
4
64
28
4
0
karenz50/test_repo_1
q1.2.py
Python
get_input
get_input
1
5
1
1
8ae1b91d38dd7ff4d1c7226093de3e73dfdd3d00
bigcode/the-stack
train