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
d80ba75ee074d68118d490c3
train
class
class DeckName(Constants): CASTLE = _Globals.CASTLE.value MARKET = _Globals.MARKET.value VILLAGER = _Globals.VILLAGER.value
class DeckName(Constants):
CASTLE = _Globals.CASTLE.value MARKET = _Globals.MARKET.value VILLAGER = _Globals.VILLAGER.value
): WOOD = _Globals.WOOD.value STONE = _Globals.STONE.value GOLD = _Globals.GOLD.value LAND = _Globals.LAND.value IRON = _Globals.IRON.value BARN = _Globals.BARN.value class DeckName(Constants):
64
64
38
5
58
Karins-Coils/CastleDice
castledice/common/constants.py
Python
DeckName
DeckName
116
119
116
116
cfbc264ac8e9c5cc68627bea333cadcbfa6ab63f
bigcode/the-stack
train
b46c11114db73b7f184ae51a
train
class
@unique # unique here guarantees that no two keys share the same value in this file class _Globals(IntEnum): # Building Resources WOOD = 0 STONE = 1 GOLD = 2 LAND = 3 IRON = 4 # Animals PIG = 5 HORSE = 6 CHICKEN = 7 COW = 8 # Lone Barbarian BARBARIAN = 9 # Vil...
@unique # unique here guarantees that no two keys share the same value in this file class _Globals(IntEnum): # Building Resources
WOOD = 0 STONE = 1 GOLD = 2 LAND = 3 IRON = 4 # Animals PIG = 5 HORSE = 6 CHICKEN = 7 COW = 8 # Lone Barbarian BARBARIAN = 9 # Villagers WORKER = 50 GUARD = 51 FARMER = 52 MERCHANT = 53 # Decks CASTLE = 100 MARKET = 101 VILLAGER = 1...
", "TurnType", "VillagerCardType", "VillagerType", ] # -- Non-importable, only for use in this file -- # @unique # unique here guarantees that no two keys share the same value in this file class _Globals(IntEnum): # Building Resources
64
64
198
30
34
Karins-Coils/CastleDice
castledice/common/constants.py
Python
_Globals
_Globals
23
54
23
25
556993ff7cc7afa21f16e890d286fb196013fb71
bigcode/the-stack
train
acaf31019a7703200c693eb0
train
class
class TurnType(Constants): """ These attributes do not stem from _Globals, as their explicit numbers are needed for ordering and display """ FIRST = 1 SECOND = 2 THIRD = 3 FOURTH = 4 FIFTH = 5 SIXTH = 6 SEVENTH = 7
class TurnType(Constants):
""" These attributes do not stem from _Globals, as their explicit numbers are needed for ordering and display """ FIRST = 1 SECOND = 2 THIRD = 3 FOURTH = 4 FIFTH = 5 SIXTH = 6 SEVENTH = 7
6 WORKERS = 7 MERCHANTS = 8 BUILD = 9 BARBARIANS = 10 class SpecialPhaseType(Constants): FIRST_GATHER = 40 ANY = 100 END_GAME = 200 class TurnType(Constants):
64
64
79
5
58
Karins-Coils/CastleDice
castledice/common/constants.py
Python
TurnType
TurnType
189
201
189
189
5f928421fcc51aac47baf059334b4c749981b5b4
bigcode/the-stack
train
90af1474b8a5f578d36fbdf6
train
class
class SpecialPhaseType(Constants): FIRST_GATHER = 40 ANY = 100 END_GAME = 200
class SpecialPhaseType(Constants):
FIRST_GATHER = 40 ANY = 100 END_GAME = 200
CHOOSE = 3 ROLL = 4 GATHER = 5 MARKET = 6 WORKERS = 7 MERCHANTS = 8 BUILD = 9 BARBARIANS = 10 class SpecialPhaseType(Constants):
64
64
27
6
57
Karins-Coils/CastleDice
castledice/common/constants.py
Python
SpecialPhaseType
SpecialPhaseType
183
186
183
183
162d2652b6a5995ff6d677e87169608090534b63
bigcode/the-stack
train
a6dcfeadb7099c86b4dc37d7
train
class
class VillagerCardType(Constants): """ These attributes do not stem from _Globals, as their explicit strings are needed for ordering, display and lookup """ FARMER = "V01" GUARD = "V02" KINGS_MESSENGER = "V03" MERCHANT = "V04" SOLDIER = "V05" WISE_GRANDFATHER = "V06" WORKER ...
class VillagerCardType(Constants):
""" These attributes do not stem from _Globals, as their explicit strings are needed for ordering, display and lookup """ FARMER = "V01" GUARD = "V02" KINGS_MESSENGER = "V03" MERCHANT = "V04" SOLDIER = "V05" WISE_GRANDFATHER = "V06" WORKER = "V07"
= "M01" HUNGRY_BARBARIANS = "M02" JESTER = "M03" MAIDEN = "M04" SHEPHERD = "M05" VOLUNTEER = "M06" class VillagerCardType(Constants):
64
64
100
7
57
Karins-Coils/CastleDice
castledice/common/constants.py
Python
VillagerCardType
VillagerCardType
150
162
150
150
c5693b325097ad54304fb1a2e717fdd765254172
bigcode/the-stack
train
d5cc97b482b6750a333594b5
train
class
class ResourceType(Constants): WOOD = _Globals.WOOD.value STONE = _Globals.STONE.value GOLD = _Globals.GOLD.value LAND = _Globals.LAND.value IRON = _Globals.IRON.value
class ResourceType(Constants):
WOOD = _Globals.WOOD.value STONE = _Globals.STONE.value GOLD = _Globals.GOLD.value LAND = _Globals.LAND.value IRON = _Globals.IRON.value
# on Joan's Die # -- importable classes, used for many things -- # # Set values, easy to reference class GameConstants(Constants): MAX_RESOURCES = 10 # only 10 of each resources allowed # Sorted by Resource Preference Gathering - especially Joan class ResourceType(Constants):
64
64
53
5
58
Karins-Coils/CastleDice
castledice/common/constants.py
Python
ResourceType
ResourceType
65
70
65
65
a077c0abfe90b22dad21bea021c19923553dae2b
bigcode/the-stack
train
48476120251679a47bc9b6c7
train
class
class CastleCardType(Constants): ADVISOR = "C01" ALCHEMIST = "C02" DAUGHTER = "C03" DEEP_MOAT = "C04" GATE_HOUSE = "C05" GREAT_HALL = "C06" LOYAL_BROTHER = "C07" ROYAL_CHAMBERS = "C08" SQUIRE = "C09" STRONG_TOWER = "C10" TALL_KEEP = "C11" WALL_ANIMAL = "C12" WALL_FARM...
class CastleCardType(Constants):
ADVISOR = "C01" ALCHEMIST = "C02" DAUGHTER = "C03" DEEP_MOAT = "C04" GATE_HOUSE = "C05" GREAT_HALL = "C06" LOYAL_BROTHER = "C07" ROYAL_CHAMBERS = "C08" SQUIRE = "C09" STRONG_TOWER = "C10" TALL_KEEP = "C11" WALL_ANIMAL = "C12" WALL_FARMER = "C13" WALL_GUARD = "C14"...
IRON = _Globals.IRON.value BARN = _Globals.BARN.value class DeckName(Constants): CASTLE = _Globals.CASTLE.value MARKET = _Globals.MARKET.value VILLAGER = _Globals.VILLAGER.value class CastleCardType(Constants):
64
64
164
6
57
Karins-Coils/CastleDice
castledice/common/constants.py
Python
CastleCardType
CastleCardType
122
138
122
122
458455627dadee68ae655bdfa41f5445a5c54935
bigcode/the-stack
train
b66ff41386cd8a3fde34fa90
train
class
class JoanDieFace(Constants): WOOD = _Globals.WOOD.value STONE = _Globals.STONE.value GOLD = _Globals.GOLD.value LAND = _Globals.LAND.value IRON = _Globals.IRON.value BARN = _Globals.BARN.value
class JoanDieFace(Constants):
WOOD = _Globals.WOOD.value STONE = _Globals.STONE.value GOLD = _Globals.GOLD.value LAND = _Globals.LAND.value IRON = _Globals.IRON.value BARN = _Globals.BARN.value
PIG = _Globals.PIG.value HORSE = _Globals.HORSE.value CHICKEN = _Globals.CHICKEN.value COW = _Globals.COW.value BARBARIAN = _Globals.BARBARIAN.value class JoanDieFace(Constants):
64
64
64
6
57
Karins-Coils/CastleDice
castledice/common/constants.py
Python
JoanDieFace
JoanDieFace
106
113
106
106
bcddf85f55937105496a1ab3953a26d3b9e473bf
bigcode/the-stack
train
480b511a2b4457198a0e4bc3
train
class
class GameConstants(Constants): MAX_RESOURCES = 10 # only 10 of each resources allowed
class GameConstants(Constants):
MAX_RESOURCES = 10 # only 10 of each resources allowed
101 VILLAGER = 102 # Joan - solo play only JOAN = 200 BARN = 201 # on Joan's Die # -- importable classes, used for many things -- # # Set values, easy to reference class GameConstants(Constants):
64
64
22
5
58
Karins-Coils/CastleDice
castledice/common/constants.py
Python
GameConstants
GameConstants
60
61
60
60
51ae48aaeb4a3aa4ff22793c6d77399f7d678817
bigcode/the-stack
train
1e6bd8cc1493b4f5aba9c5ea
train
class
class AnimalType(Constants): PIG = _Globals.PIG.value HORSE = _Globals.HORSE.value CHICKEN = _Globals.CHICKEN.value COW = _Globals.COW.value
class AnimalType(Constants):
PIG = _Globals.PIG.value HORSE = _Globals.HORSE.value CHICKEN = _Globals.CHICKEN.value COW = _Globals.COW.value
): WOOD = _Globals.WOOD.value STONE = _Globals.STONE.value GOLD = _Globals.GOLD.value LAND = _Globals.LAND.value IRON = _Globals.IRON.value # Sorted by Animal Preference Gathering - especially Joan class AnimalType(Constants):
64
64
48
5
58
Karins-Coils/CastleDice
castledice/common/constants.py
Python
AnimalType
AnimalType
74
78
74
74
583f89c6ae495f9d7cdc986201852eceef4b4e01
bigcode/the-stack
train
7a152f0a80745dccde4ea2aa
train
class
class DieFace(Constants): WOOD = _Globals.WOOD.value STONE = _Globals.STONE.value GOLD = _Globals.GOLD.value LAND = _Globals.LAND.value IRON = _Globals.IRON.value PIG = _Globals.PIG.value HORSE = _Globals.HORSE.value CHICKEN = _Globals.CHICKEN.value COW = _Globals.COW.value BAR...
class DieFace(Constants):
WOOD = _Globals.WOOD.value STONE = _Globals.STONE.value GOLD = _Globals.GOLD.value LAND = _Globals.LAND.value IRON = _Globals.IRON.value PIG = _Globals.PIG.value HORSE = _Globals.HORSE.value CHICKEN = _Globals.CHICKEN.value COW = _Globals.COW.value BARBARIAN = _Globals.BARBARIA...
UARD.value FARMER = _Globals.FARMER.value MERCHANT = _Globals.MERCHANT.value # added for easy access when adding a "villager" to the playermat BARBARIAN = _Globals.BARBARIAN.value class DieFace(Constants):
64
64
110
5
58
Karins-Coils/CastleDice
castledice/common/constants.py
Python
DieFace
DieFace
91
103
91
91
5e89be7fdf972253f2f42db0c70ca74e079028bf
bigcode/the-stack
train
1f2f32cdf7325b1ff802cf3a
train
class
class TextPrint(object): """ This is a simple class that will help us print to the screen It has nothing to do with the joysticks, just outputting the information. """ def __init__(self): """ Constructor """ self.reset() self.x_pos = 10 self.y_pos = 10 se...
class TextPrint(object):
""" This is a simple class that will help us print to the screen It has nothing to do with the joysticks, just outputting the information. """ def __init__(self): """ Constructor """ self.reset() self.x_pos = 10 self.y_pos = 10 self.font = pygame.font.Fon...
Simpson College Computer Science http://programarcadegames.com/ http://simpson.edu/computer-science/ Show everything we can pull off the joystick """ import pygame # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) class TextPrint(object):
70
70
234
5
65
FinleyDavies/super-pygame-bomberman
testing/controller.py
Python
TextPrint
TextPrint
16
48
16
16
87504b234cf2cd39b101f4f0d7d8422cddf1a606
bigcode/the-stack
train
3b81a5e07aad19064f7b98c2
train
function
def train_perceptron(y, X, y_vali, X_vali, num_iter=100, seed=1231) -> LinearModel: rand = np.random.default_rng(seed) (num_examples, num_features) = X.shape assert len(y) == num_examples w = np.zeros((num_features, 1)) b = 0.0 indices = list(range(num_examples)) for iteration in range(num_i...
def train_perceptron(y, X, y_vali, X_vali, num_iter=100, seed=1231) -> LinearModel:
rand = np.random.default_rng(seed) (num_examples, num_features) = X.shape assert len(y) == num_examples w = np.zeros((num_features, 1)) b = 0.0 indices = list(range(num_examples)) for iteration in range(num_iter): rand.shuffle(indices) wrong = 0 for i in indices: ...
, y)) self.validation.append(m.score(X_vali, y_vali)) # These are the named lines that will be plotted: learning_curves: DefaultDict[str, ModelTrainingCurve] = defaultdict(ModelTrainingCurve) def train_perceptron(y, X, y_vali, X_vali, num_iter=100, seed=1231) -> LinearModel:
78
78
263
32
46
hjarai/cs451-practicals
p07-perceptron.py
Python
train_perceptron
train_perceptron
154
182
154
154
a45b572be4f9a0e8f6634d7f71bbb1d9b413ed36
bigcode/the-stack
train
d42832a0cb838f96c7234723
train
class
@dataclass class LinearModel: weights: np.ndarray # note we can't specify this is 1-dimensional bias: float = 0.0 def decision_function(self, X: np.ndarray) -> np.ndarray: """ Compute the signed distance from the self.weights hyperplane. """ (N, D) = X.shape assert self.weights.sha...
@dataclass class LinearModel:
weights: np.ndarray # note we can't specify this is 1-dimensional bias: float = 0.0 def decision_function(self, X: np.ndarray) -> np.ndarray: """ Compute the signed distance from the self.weights hyperplane. """ (N, D) = X.shape assert self.weights.shape == (D, 1) # Matrix ...
X_vali = rX_vali X_test = rX_test print(X_train.shape, X_vali.shape, X_test.shape) # Delete these generic variables that we really shouldn't use anymore now that the data is fully-prepared. del X, y, ys, rX_train, rX_vali, rX_test #%% Define and Train Models @dataclass class LinearModel:
85
85
286
7
77
hjarai/cs451-practicals
p07-perceptron.py
Python
LinearModel
LinearModel
105
130
105
106
004ffea1ed6081be28a75814411339a51e5e34cb
bigcode/the-stack
train
cf0118a644006f7e50459215
train
function
def train_averaged_perceptron( y, X, y_vali, X_vali, num_iter=100, seed=1231 ) -> LinearModel: rand = np.random.default_rng(seed) (num_examples, num_features) = X.shape assert len(y) == num_examples w_avg = np.zeros((num_features, 1)) b_avg = 0.0 w = np.zeros((num_features, 1)) b = 0.0 ...
def train_averaged_perceptron( y, X, y_vali, X_vali, num_iter=100, seed=1231 ) -> LinearModel:
rand = np.random.default_rng(seed) (num_examples, num_features) = X.shape assert len(y) == num_examples w_avg = np.zeros((num_features, 1)) b_avg = 0.0 w = np.zeros((num_features, 1)) b = 0.0 current_correct = 0 indices = list(range(num_examples)) for iteration in range(num_iter)...
! w += y_val * x_i b += y_val if wrong == 0: break tmp = LinearModel(w, b) learning_curves["Perceptron"].add_sample(tmp, X, y, X_vali, y_vali) return LinearModel(w, b) def train_averaged_perceptron( y, X, y_vali, X_vali, num_iter=100, seed=1231...
107
107
357
38
69
hjarai/cs451-practicals
p07-perceptron.py
Python
train_averaged_perceptron
train_averaged_perceptron
185
225
185
187
249851e0c4f24e3e756f923ac34c2385eab3ca8d
bigcode/the-stack
train
59abca43a9178f79fd380055
train
class
@dataclass class ModelTrainingCurve: train: List[float] = field(default_factory=list) validation: List[float] = field(default_factory=list) def add_sample( self, m: LinearModel, X: np.ndarray, y: np.ndarray, X_vali: np.ndarray, y_vali: np.ndarray, ) -> No...
@dataclass class ModelTrainingCurve:
train: List[float] = field(default_factory=list) validation: List[float] = field(default_factory=list) def add_sample( self, m: LinearModel, X: np.ndarray, y: np.ndarray, X_vali: np.ndarray, y_vali: np.ndarray, ) -> None: self.train.append(m.score...
(np.asarray(y), y_hat) def compute_auc(self, X: np.ndarray, y: np.ndarray) -> float: """ Distance to hyperplane is used for AUC-style metrics. """ return metrics.roc_auc_score(y, self.decision_function(X)) @dataclass class ModelTrainingCurve:
64
64
105
8
56
hjarai/cs451-practicals
p07-perceptron.py
Python
ModelTrainingCurve
ModelTrainingCurve
133
147
133
134
37d0911d370e95cd703412d03404c8ddff2d0e8a
bigcode/the-stack
train
086c6222dc4e083b822d2b6f
train
class
class InputPointer(NamedTuple("_InputPointer", [("solid_name", str), ("input_name", str)])): def __new__(cls, solid_name: str, input_name: str): return super(InputPointer, cls).__new__( cls, check.str_param(solid_name, "solid_name"), check.str_param(input_name, "input_nam...
class InputPointer(NamedTuple("_InputPointer", [("solid_name", str), ("input_name", str)])):
def __new__(cls, solid_name: str, input_name: str): return super(InputPointer, cls).__new__( cls, check.str_param(solid_name, "solid_name"), check.str_param(input_name, "input_name"), )
represents passing no data. This type must be used " f"via InputDefinition and no parameter should be included in the {decorator_name} decorated function." ) return resolved_type class InputPointer(NamedTuple("_InputPointer", [("solid_name", str), ("input_name", str)])):
64
64
79
24
39
dehume/dagster
python_modules/dagster/dagster/core/definitions/input.py
Python
InputPointer
InputPointer
296
302
296
296
07852b55e9d9170e3fd878328dc166f54fb10513
bigcode/the-stack
train
17549aecb95fbbc64a27df46
train
class
class InputDefinition: """Defines an argument to a solid's compute function. Inputs may flow from previous solids' outputs, or be stubbed using config. They may optionally be typed using the Dagster type system. Args: name (str): Name of the input. dagster_type (Optional[Union[Type, Da...
class InputDefinition:
"""Defines an argument to a solid's compute function. Inputs may flow from previous solids' outputs, or be stubbed using config. They may optionally be typed using the Dagster type system. Args: name (str): Name of the input. dagster_type (Optional[Union[Type, DagsterType]]]): The type...
ference import InferredInputProps from .utils import NoValueSentinel, check_valid_name if TYPE_CHECKING: from dagster.core.execution.context.input import InputContext # unfortunately since type_check functions need TypeCheckContext which is only available # at runtime, we can only check basic types before runtim...
256
256
1,802
4
251
dehume/dagster
python_modules/dagster/dagster/core/definitions/input.py
Python
InputDefinition
InputDefinition
50
274
50
50
97a26e897594f0528e40634a799e53881fd53a1f
bigcode/the-stack
train
fea938320159df53ab28f882
train
class
class FanInInputPointer( NamedTuple( "_FanInInputPointer", [("solid_name", str), ("input_name", str), ("fan_in_index", int)] ) ): def __new__(cls, solid_name: str, input_name: str, fan_in_index: int): return super(FanInInputPointer, cls).__new__( cls, check.str_param(...
class FanInInputPointer( NamedTuple( "_FanInInputPointer", [("solid_name", str), ("input_name", str), ("fan_in_index", int)] ) ):
def __new__(cls, solid_name: str, input_name: str, fan_in_index: int): return super(FanInInputPointer, cls).__new__( cls, check.str_param(solid_name, "solid_name"), check.str_param(input_name, "input_name"), check.int_param(fan_in_index, "fan_in_index"), ...
check.str_param(solid_name, "solid_name"), check.str_param(input_name, "input_name"), ) class FanInInputPointer( NamedTuple( "_FanInInputPointer", [("solid_name", str), ("input_name", str), ("fan_in_index", int)] ) ):
64
64
118
40
24
dehume/dagster
python_modules/dagster/dagster/core/definitions/input.py
Python
FanInInputPointer
FanInInputPointer
305
316
305
309
70b63cc9b9422191a2e51ec41e3c6e5d8161a3ef
bigcode/the-stack
train
6232d119c4e113f197599d39
train
class
class GraphIn(NamedTuple("_GraphIn", [("description", Optional[str])])): """ Represents information about an input that a graph maps. Args: description (Optional[str]): Human-readable description of the input. """ def __new__(cls, description=None): return super(GraphIn, cls).__new...
class GraphIn(NamedTuple("_GraphIn", [("description", Optional[str])])):
""" Represents information about an input that a graph maps. Args: description (Optional[str]): Human-readable description of the input. """ def __new__(cls, description=None): return super(GraphIn, cls).__new__(cls, description=description) def to_definition(self, name: str) ...
_type, description=self.description, default_value=self.default_value, root_manager_key=self.root_manager_key, metadata=self.metadata, asset_key=self.asset_key, asset_partitions=self.asset_partitions, ) class GraphIn(NamedTuple("_GraphIn", ...
64
64
100
18
46
dehume/dagster
python_modules/dagster/dagster/core/definitions/input.py
Python
GraphIn
GraphIn
438
450
438
438
c60923cc952abb3647a6c0972af22408bb67f42a
bigcode/the-stack
train
b5b614879d8a00f005785e12
train
function
def _check_default_value(input_name, dagster_type, default_value): if default_value is not NoValueSentinel: if dagster_type.is_nothing: raise DagsterInvalidDefinitionError( "Setting a default_value is invalid on InputDefinitions of type Nothing" ) if isinstan...
def _check_default_value(input_name, dagster_type, default_value):
if default_value is not NoValueSentinel: if dagster_type.is_nothing: raise DagsterInvalidDefinitionError( "Setting a default_value is invalid on InputDefinitions of type Nothing" ) if isinstance(dagster_type, BuiltinScalarDagsterType): type_check ...
check_valid_name if TYPE_CHECKING: from dagster.core.execution.context.input import InputContext # unfortunately since type_check functions need TypeCheckContext which is only available # at runtime, we can only check basic types before runtime def _check_default_value(input_name, dagster_type, default_value):
64
64
187
15
48
dehume/dagster
python_modules/dagster/dagster/core/definitions/input.py
Python
_check_default_value
_check_default_value
24
47
24
24
463c722fb2b0cf90cbce9f5713583e5808253e2b
bigcode/the-stack
train
85347d060b4b4661faef5966
train
class
class In( NamedTuple( "_In", [ ("dagster_type", Union[DagsterType, Type[NoValueSentinel]]), ("description", Optional[str]), ("default_value", Any), ("root_manager_key", Optional[str]), ("metadata", Optional[Mapping[str, Any]]), ...
class In( NamedTuple( "_In", [ ("dagster_type", Union[DagsterType, Type[NoValueSentinel]]), ("description", Optional[str]), ("default_value", Any), ("root_manager_key", Optional[str]), ("metadata", Optional[Mapping[str, Any]]), ...
""" Defines an argument to an op's compute function. Inputs may flow from previous op's outputs, or be stubbed using config. They may optionally be typed using the Dagster type system. Args: dagster_type (Optional[Union[Type, DagsterType]]]): The type of this input. Should only...
, FanInInputPointer]): return super(InputMapping, cls).__new__( cls, check.inst_param(definition, "definition", InputDefinition), check.inst_param(maps_to, "maps_to", (InputPointer, FanInInputPointer)), ) @property def maps_to_fan_in(self): return isi...
255
256
908
119
136
dehume/dagster
python_modules/dagster/dagster/core/definitions/input.py
Python
In
In
349
435
349
362
349ee5f58588899223ff7baedc660e6a4e5c1f1e
bigcode/the-stack
train
13efece65f569b35b3d3ac1e
train
class
class InputMapping( NamedTuple( "_InputMapping", [("definition", InputDefinition), ("maps_to", Union[InputPointer, FanInInputPointer])], ) ): """Defines an input mapping for a composite solid. Args: definition (InputDefinition): Defines the input to the composite solid. ...
class InputMapping( NamedTuple( "_InputMapping", [("definition", InputDefinition), ("maps_to", Union[InputPointer, FanInInputPointer])], ) ):
"""Defines an input mapping for a composite solid. Args: definition (InputDefinition): Defines the input to the composite solid. solid_name (str): The name of the child solid onto which to map the input. input_name (str): The name of the input to the child solid onto which to map the in...
, check.str_param(solid_name, "solid_name"), check.str_param(input_name, "input_name"), check.int_param(fan_in_index, "fan_in_index"), ) class InputMapping( NamedTuple( "_InputMapping", [("definition", InputDefinition), ("maps_to", Union[InputPointer, FanI...
79
79
265
39
40
dehume/dagster
python_modules/dagster/dagster/core/definitions/input.py
Python
InputMapping
InputMapping
319
346
319
324
1d7728f39d5285b298024e008c68d66ae5ecb90f
bigcode/the-stack
train
7a6d124e313a2856966e78b9
train
function
def _checked_inferred_type(inferred: InferredInputProps, decorator_name: str) -> DagsterType: try: resolved_type = resolve_dagster_type(inferred.annotation) except DagsterError as e: raise DagsterInvalidDefinitionError( f"Problem using type '{inferred.annotation}' from type annotatio...
def _checked_inferred_type(inferred: InferredInputProps, decorator_name: str) -> DagsterType:
try: resolved_type = resolve_dagster_type(inferred.annotation) except DagsterError as e: raise DagsterInvalidDefinitionError( f"Problem using type '{inferred.annotation}' from type annotation for argument " f"'{inferred.name}', correct the issue or explicitly set the dags...
default_value, root_manager_key=self._root_manager_key, metadata=self._metadata, asset_key=self._asset_key, asset_partitions=self._asset_partitions_fn, ) def _checked_inferred_type(inferred: InferredInputProps, decorator_name: str) -> DagsterType:
64
64
187
24
40
dehume/dagster
python_modules/dagster/dagster/core/definitions/input.py
Python
_checked_inferred_type
_checked_inferred_type
277
293
277
277
40208b513fc46e9d5f144c921f9d063bbffc9796
bigcode/the-stack
train
3d3fdd49f0d9961b259638c5
train
class
class TreeNode: __slots__ = 'data', 'right', 'left', 'size' def __init__(self, data): self.data = data self.size = 1 self.right = None self.left = None def get_children(self): if self.right and self.left: return [self.left, self.right] elif self....
class TreeNode:
__slots__ = 'data', 'right', 'left', 'size' def __init__(self, data): self.data = data self.size = 1 self.right = None self.left = None def get_children(self): if self.right and self.left: return [self.left, self.right] elif self.right: ...
# 4.11) create a binary tree class tha supports, insert, delete, find and get random node from random import randint class TreeNode:
33
158
529
4
28
Randyjp/python_algorithms
trees_and_graphs/random_node.py
Python
TreeNode
TreeNode
5
90
5
5
0e7f20d92f49388eeb19e80092d399ab4c4d73fc
bigcode/the-stack
train
45c97711930067c11f881921
train
class
class HypervisorAdminTestJSON(base.BaseV2ComputeAdminTest): """ Tests Hypervisors API that require admin privileges """ @classmethod def resource_setup(cls): super(HypervisorAdminTestJSON, cls).resource_setup() cls.client = cls.os_adm.hypervisor_client def _list_hypervisors(se...
class HypervisorAdminTestJSON(base.BaseV2ComputeAdminTest):
""" Tests Hypervisors API that require admin privileges """ @classmethod def resource_setup(cls): super(HypervisorAdminTestJSON, cls).resource_setup() cls.client = cls.os_adm.hypervisor_client def _list_hypervisors(self): # List of hypervisors resp, hypers = sel...
# Copyright 2013 IBM Corporation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
171
256
968
14
156
afaheem88/tempest_neutron
tempest/api/compute/admin/test_hypervisor.py
Python
HypervisorAdminTestJSON
HypervisorAdminTestJSON
20
130
20
21
71c2e29f0de5299b934518e4c50704ee2219a7ad
bigcode/the-stack
train
71e998160bd6eca971dac99b
train
function
def _test(): import textwrap from kivy.app import App from kivy.lang import Builder KV_CODE = textwrap.dedent(''' <Label>: font_size: '24sp' BoxLayout: orientation: 'vertical' padding: 10 spacing: 10 Label: id: label size_hint_y: N...
def _test():
import textwrap from kivy.app import App from kivy.lang import Builder KV_CODE = textwrap.dedent(''' <Label>: font_size: '24sp' BoxLayout: orientation: 'vertical' padding: 10 spacing: 10 Label: id: label size_hint_y: None ...
''' Just shows how ``asynckivy.or_()`` and ``asynckivy.and_()`` work. ''' def _test():
30
128
428
4
26
gottadiveintopython/asynckivy
examples/wait_for_multiple_coroutines_to_complete.py
Python
_test
_test
6
72
6
6
5e29784e213e6cd607283a990231ea93ca452686
bigcode/the-stack
train
d8a637924f0bc58b64209a48
train
class
class PgSqlLogWrapper(PgSqlWrapper, LogWrapper): """ Wrapper method generator for stored procedures with designation type log. """ # ------------------------------------------------------------------------------------------------------------------ def _write_result_handler(self, routine: Dict[str, ...
class PgSqlLogWrapper(PgSqlWrapper, LogWrapper):
""" Wrapper method generator for stored procedures with designation type log. """ # ------------------------------------------------------------------------------------------------------------------ def _write_result_handler(self, routine: Dict[str, Any]) -> None: """ Generates code...
from typing import Any, Dict from pystratum_common.wrapper.LogWrapper import LogWrapper from pystratum_pgsql.wrapper.PgSqlWrapper import PgSqlWrapper class PgSqlLogWrapper(PgSqlWrapper, LogWrapper):
48
64
109
13
34
DatabaseStratum/py-stratum-pgsql
pystratum_pgsql/wrapper/PgSqlLogWrapper.py
Python
PgSqlLogWrapper
PgSqlLogWrapper
8
20
8
8
a2d320e0d624a838010510d741411990631bcb9a
bigcode/the-stack
train
b66333eb9e693f9d4b3448f3
train
class
class AppInfoLoader(object): def __init__(self, log: Log, appInfoFilename: str, requestedFiles: Union[List[str], Set[str]], scanSubdirectories: bool, currentPath: str, activePlatformNameId: str) -> None: self.Log = log requestedFileSet = set(requestedFiles) if scanSubdirect...
class AppInfoLoader(object):
def __init__(self, log: Log, appInfoFilename: str, requestedFiles: Union[List[str], Set[str]], scanSubdirectories: bool, currentPath: str, activePlatformNameId: str) -> None: self.Log = log requestedFileSet = set(requestedFiles) if scanSubdirectories: foundFiles...
; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # #**************************************************...
129
129
432
6
122
alexvonduar/gtec-demo-framework
.Config/FslBuildGen/Info/AppInfoLoader.py
Python
AppInfoLoader
AppInfoLoader
44
88
44
44
e36522416393aa2a7fb4860c5980ecb4ceb39b30
bigcode/the-stack
train
aec745baaeb6698099a8bb5c
train
class
class TestMongoSemanticsDatabase: def test_no_address_semantics(self, mongo_semantics_database): sema = mongo_semantics_database.get_address_semantics("mainnet", "not_existing") assert not sema def test_save_and_get_contract_semantic( self, mongo_semantics_database, mongo_db: Database ...
class TestMongoSemanticsDatabase:
def test_no_address_semantics(self, mongo_semantics_database): sema = mongo_semantics_database.get_address_semantics("mainnet", "not_existing") assert not sema def test_save_and_get_contract_semantic( self, mongo_semantics_database, mongo_db: Database ): code_hash = "test_co...
from mongomock import Database from ethtx.providers.semantic_providers.const import MongoCollections class TestMongoSemanticsDatabase:
27
142
476
7
19
0xbhoori/ethtx
tests/providers/semantic_providers/semantics_database_test.py
Python
TestMongoSemanticsDatabase
TestMongoSemanticsDatabase
6
75
6
6
6ef7b151d55cd34d628a3b60abe3053def309e7f
bigcode/the-stack
train
7325015e28e80fc406bbce32
train
function
def setup(bot): bot.add_cog(Manager(bot))
def setup(bot):
bot.add_cog(Manager(bot))
msg.delete() elapsed = round(time.time() - start, 2) await ctx.send("Gathered all User text data. Found %s new messages in %s seconds." % (found, elapsed)) # When we load the cog, we use the name of the file. def setup(bot):
64
64
13
4
60
shadowmoose/Discord-Bot
shadowbot/cogs/manager.py
Python
setup
setup
78
79
78
78
97e90564d77be952c0776c1046dad45daa10420f
bigcode/the-stack
train
86d66c00301d815e34472e52
train
class
class Manager(Cog, command_attrs=dict(hidden=True)): """ Manages the channel events the bot needs to handle. """ def __init__(self, bot): super().__init__(bot) # self.settings.register("test", "default value") @commands.Cog.listener() @commands.guild_only() async def on_message(self, message: discord.Message)...
class Manager(Cog, command_attrs=dict(hidden=True)):
""" Manages the channel events the bot needs to handle. """ def __init__(self, bot): super().__init__(bot) # self.settings.register("test", "default value") @commands.Cog.listener() @commands.guild_only() async def on_message(self, message: discord.Message): if message.author.bot or not message.guild: re...
import discord from discord.ext import commands from cogs import Cog from cogs.user_simulator import UserSimulator import defusedxml import time defusedxml.defuse_stdlib() # Monkey-patch all XML libs. # https://gist.github.com/BananaWagon/068cef8ff640e90d3636d133fa8f72a1 class Manager(Cog, command_attrs=dict(hidde...
91
181
604
11
79
shadowmoose/Discord-Bot
shadowbot/cogs/manager.py
Python
Manager
Manager
13
74
13
13
99e58dcfc450c6b0bda4f8d9c64120c0bfec3dd0
bigcode/the-stack
train
f51e73dda7f9378840001b9a
train
class
class QueueTestCase(unittest.TestCase): """ This Case of tests checks the functionality of the implementation of Queue """ def test_data_is_stack(self): """ Test that the data in the queue has Stack type """ queue = Queue_(Stack([1, 2, 3])) self.assertTrue(isinst...
class QueueTestCase(unittest.TestCase):
""" This Case of tests checks the functionality of the implementation of Queue """ def test_data_is_stack(self): """ Test that the data in the queue has Stack type """ queue = Queue_(Stack([1, 2, 3])) self.assertTrue(isinstance(queue.data, Stack)) def test_c...
# pylint: skip-file """ Programming for linguists Tests for Queue from stack class. """ import unittest from stack.stack import Stack from queue_.queue_from_stack import Queue_ from queue_.queue_ import TooManyElementsInQueueError, QueueIsFullError class QueueTestCase(unittest.TestCase):
64
209
698
8
55
alenashuvar/programming-2021-19fpl
queue_/queue_from_stack_test.py
Python
QueueTestCase
QueueTestCase
15
108
15
15
40739cc91b8633d95d5ec545bb6a25e99fb53ead
bigcode/the-stack
train
9aeca41b6af06f3527ec2a08
train
function
def plot_results(results, df): plt.plot(df['offset'].values, df['Z'].values, 'g--') for idx, r in results.iterrows(): ws = r['ws'] wp = r['wp'] plt.plot([ws[0][0], ws[1][0]], [ws[0][1], ws[1][1]], 'b-') plt.plot([wp[0][0], wp[1][0]], [wp[0][1], wp[1][1]], 'r-')
def plot_results(results, df):
plt.plot(df['offset'].values, df['Z'].values, 'g--') for idx, r in results.iterrows(): ws = r['ws'] wp = r['wp'] plt.plot([ws[0][0], ws[1][0]], [ws[0][1], ws[1][1]], 'b-') plt.plot([wp[0][0], wp[1][0]], [wp[0][1], wp[1][1]], 'r-')
4 = (0, 2) go_up = (pt1, pt2) go_down = (pt4, pt3) vertical_up = (pt3, pt2) vertical_down = (pt4, pt1) flat = (pt1, pt3) def plot_results(results, df):
64
64
116
7
57
mel-meng/SewerAnalysis
source/test_conveyance.py
Python
plot_results
plot_results
18
24
18
18
22a38acf512f794a7fef4478030f28f4a1a8cb6b
bigcode/the-stack
train
0bbb74eb587ef6275a8421c3
train
function
def plot_line(line, name): x = [x[0] for x in line] y = [x[1] for x in line] plt.plot(x, y) plt.title(name)
def plot_line(line, name):
x = [x[0] for x in line] y = [x[1] for x in line] plt.plot(x, y) plt.title(name)
], ws[1][0]], [ws[0][1], ws[1][1]], 'b-') plt.plot([wp[0][0], wp[1][0]], [wp[0][1], wp[1][1]], 'r-') def plot_line(line, name):
64
64
45
7
57
mel-meng/SewerAnalysis
source/test_conveyance.py
Python
plot_line
plot_line
26
30
26
26
55d8435e336a464d9fa214a4d810879fcc986ba7
bigcode/the-stack
train
0387d0fd16bb579b6ffd9498
train
class
class Test(TestCase): def setUp(self) -> None: f = './test/river/cross_section.xlsx' self.f = f def test_get_length(self): f = self.f df = pd.read_excel(f, 'irregular') p = conveyance.get_length(df['station'], df['z']) assert (math.fabs(p - 53.17424804) < 0.01) ...
class Test(TestCase):
def setUp(self) -> None: f = './test/river/cross_section.xlsx' self.f = f def test_get_length(self): f = self.f df = pd.read_excel(f, 'irregular') p = conveyance.get_length(df['station'], df['z']) assert (math.fabs(p - 53.17424804) < 0.01) def test_calculate...
ws'] wp = r['wp'] plt.plot([ws[0][0], ws[1][0]], [ws[0][1], ws[1][1]], 'b-') plt.plot([wp[0][0], wp[1][0]], [wp[0][1], wp[1][1]], 'r-') def plot_line(line, name): x = [x[0] for x in line] y = [x[1] for x in line] plt.plot(x, y) plt.title(name) # plt.show() def check_result(...
256
256
2,336
5
251
mel-meng/SewerAnalysis
source/test_conveyance.py
Python
Test
Test
47
204
47
47
a4297b7480e1d99fcdf19aa9fd5eea50fc551c6a
bigcode/the-stack
train
3c4807dcebaba0ad904e9653
train
function
def check_result(level, line, check, msg, show_plot=False): pt1, pt2 = line panel = 0 if show_plot: plot_line(line, 'go_up') plt.plot([pt1[0], pt2[0]], [level, level]) plt.show() pt1 = pt1 + (0.014, 0) pt2 = pt2 + (0.014, 0) result = conveyance.calculate_line_segment(leve...
def check_result(level, line, check, msg, show_plot=False):
pt1, pt2 = line panel = 0 if show_plot: plot_line(line, 'go_up') plt.plot([pt1[0], pt2[0]], [level, level]) plt.show() pt1 = pt1 + (0.014, 0) pt2 = pt2 + (0.014, 0) result = conveyance.calculate_line_segment(level, pt1, pt2, panel) print(result) assert (result == ...
plot_line(line, name): x = [x[0] for x in line] y = [x[1] for x in line] plt.plot(x, y) plt.title(name) # plt.show() def check_result(level, line, check, msg, show_plot=False):
64
64
126
15
49
mel-meng/SewerAnalysis
source/test_conveyance.py
Python
check_result
check_result
33
44
33
33
d6c2baa28943600bb2482ca85da82d5fe0f3f4a8
bigcode/the-stack
train
8aa2e8ea5b0369810da6a617
train
function
def ff(f, n): fs = "{:f}".format(f) if len(fs) < n: return ("{:" + n + "s}").format(fs) else: return fs[:n]
def ff(f, n):
fs = "{:f}".format(f) if len(fs) < n: return ("{:" + n + "s}").format(fs) else: return fs[:n]
, collections.Callable): if c(action): eValues.append(1) continue eValues.append(math.exp(self.getQ(state, action) / self.temp)) total = sum(eValues) return [eValue / total for eValue in eValues] def ff(f, n):
64
64
48
6
58
LE-LOY/socialsims
src/qlearn.py
Python
ff
ff
225
230
225
225
72c4bbe1d209e7a21e7aa36922d4be95f5817406
bigcode/the-stack
train
a9ccf88ef79b25a8af1cbe11
train
class
class QLearn: max_states = 40 def __init__(self, actions, temp=5, epsilon=0.1, alpha=0.5, gamma=0.5): self.q = {} self.states = set() # SRE => State Residual Entropy # ARE => Agent Residual Entropy self.stat_sre = {} self.stat_are = 1.0 ...
class QLearn:
max_states = 40 def __init__(self, actions, temp=5, epsilon=0.1, alpha=0.5, gamma=0.5): self.q = {} self.states = set() # SRE => State Residual Entropy # ARE => Agent Residual Entropy self.stat_sre = {} self.stat_are = 1.0 self.dyna_...
import math import random import collections class QLearn:
13
256
1,833
4
8
LE-LOY/socialsims
src/qlearn.py
Python
QLearn
QLearn
6
222
6
6
2bd16b562eea38983c9ea77d2d4805fe86810193
bigcode/the-stack
train
db34f779cd76b18c97191642
train
class
class StatusExtension(Extension): """ Markdown extension that generates Confluence status macros (the little colored pills). Supports red, yellow, green, grey, blue, and purple. Some examples: ``` Milestone 1 &status-green:Complete; Milestone 2 &status-yellow:In Progress; Milestone 3 &status-gr...
class StatusExtension(Extension):
""" Markdown extension that generates Confluence status macros (the little colored pills). Supports red, yellow, green, grey, blue, and purple. Some examples: ``` Milestone 1 &status-green:Complete; Milestone 2 &status-yellow:In Progress; Milestone 3 &status-grey:Planning; ``` """ ...
from typing import Tuple, Any from markdown import Markdown from markdown.extensions import Extension from markdown.inlinepatterns import InlineProcessor import xml.etree.ElementTree as etree import re class StatusExtension(Extension):
44
64
196
6
37
explody/Junction
src/junction/markdown/status.py
Python
StatusExtension
StatusExtension
9
25
9
9
9e3e1cf7673140e4bf5f4b032a7ea2bfa345f476
bigcode/the-stack
train
5cbd22aba301146c545b0763
train
class
class StatusPattern(InlineProcessor): def __init__(self, color: str): self._color = color super().__init__(r"&status-{}:(?P<title>[^;]+);".format(self._color)) def handleMatch(self, match: re.Match, data: str) -> Tuple[etree.Element, int, int]: el = etree.Element( "ac:struct...
class StatusPattern(InlineProcessor):
def __init__(self, color: str): self._color = color super().__init__(r"&status-{}:(?P<title>[^;]+);".format(self._color)) def handleMatch(self, match: re.Match, data: str) -> Tuple[etree.Element, int, int]: el = etree.Element( "ac:structured-macro", { ...
StatusPattern("green"), "<reference") md.inlinePatterns.add("status-grey", StatusPattern("grey"), "<reference") md.inlinePatterns.add("status-purple", StatusPattern("purple"), "<reference") md.inlinePatterns.add("status-blue", StatusPattern("blue"), "<reference") class StatusPattern(InlineProce...
66
66
223
7
59
explody/Junction
src/junction/markdown/status.py
Python
StatusPattern
StatusPattern
28
50
28
28
82859bc51555ae82086e1639f23642597e6153ac
bigcode/the-stack
train
a9710a9be1f277a2a6d73409
train
function
def makeExtension(**kwargs: Any) -> StatusExtension: return StatusExtension(**kwargs)
def makeExtension(**kwargs: Any) -> StatusExtension:
return StatusExtension(**kwargs)
match.group( "title" ) etree.SubElement( el, "ac:parameter", {"ac:name": "colour"} ).text = self._color.capitalize() return el, match.start(0), match.end(0) def makeExtension(**kwargs: Any) -> StatusExtension:
64
64
19
12
52
explody/Junction
src/junction/markdown/status.py
Python
makeExtension
makeExtension
53
54
53
53
7041377e97e71161dfa754ece22952e312448190
bigcode/the-stack
train
6dadd6b6f0c9712edcffebae
train
function
def _get_user_listening_history(session: Session, args: GetUserListeningHistoryArgs): user_id = args["user_id"] current_user_id = args["current_user_id"] limit = args["limit"] offset = args["offset"] if user_id != current_user_id: return [] listening_history_results = ( session...
def _get_user_listening_history(session: Session, args: GetUserListeningHistoryArgs):
user_id = args["user_id"] current_user_id = args["current_user_id"] limit = args["limit"] offset = args["offset"] if user_id != current_user_id: return [] listening_history_results = ( session.query(UserListeningHistory.listening_history).filter( UserListeningHistor...
ListeningHistoryArgs): """ Returns a user's listening history Args: args: GetUserListeningHistoryArgs The parsed args from the request Returns: Array of tracks the user listened to starting from most recently listened """ db = get_db_read_replica() with db.scoped_session()...
100
100
335
19
81
lucylow/audius-protocol
discovery-provider/src/queries/get_user_listening_history.py
Python
_get_user_listening_history
_get_user_listening_history
42
90
42
42
8a037007e708529fdd446fb08e111e691398e1a3
bigcode/the-stack
train
3d1cee494b94ab6bbb4766ae
train
class
class GetUserListeningHistoryArgs(TypedDict): # The current user logged in (from route param) user_id: int # The current user logged in (from query arg) current_user_id: int # The maximum number of listens to return limit: int # The offset for the listen history offset: int
class GetUserListeningHistoryArgs(TypedDict): # The current user logged in (from route param)
user_id: int # The current user logged in (from query arg) current_user_id: int # The maximum number of listens to return limit: int # The offset for the listen history offset: int
src.queries import response_name_constants from src.queries.query_helpers import add_users_to_tracks, populate_track_metadata from src.utils import helpers from src.utils.db_session import get_db_read_replica class GetUserListeningHistoryArgs(TypedDict): # The current user logged in (from route param)
64
64
76
22
41
lucylow/audius-protocol
discovery-provider/src/queries/get_user_listening_history.py
Python
GetUserListeningHistoryArgs
GetUserListeningHistoryArgs
12
23
12
13
cfa15050102a89a6fee67a8ef0a41e32177cf8e1
bigcode/the-stack
train
eba9b663bef691500e90eb62
train
function
def get_user_listening_history(args: GetUserListeningHistoryArgs): """ Returns a user's listening history Args: args: GetUserListeningHistoryArgs The parsed args from the request Returns: Array of tracks the user listened to starting from most recently listened """ db = get_db...
def get_user_listening_history(args: GetUserListeningHistoryArgs):
""" Returns a user's listening history Args: args: GetUserListeningHistoryArgs The parsed args from the request Returns: Array of tracks the user listened to starting from most recently listened """ db = get_db_read_replica() with db.scoped_session() as session: re...
int # The current user logged in (from query arg) current_user_id: int # The maximum number of listens to return limit: int # The offset for the listen history offset: int def get_user_listening_history(args: GetUserListeningHistoryArgs):
64
64
91
14
49
lucylow/audius-protocol
discovery-provider/src/queries/get_user_listening_history.py
Python
get_user_listening_history
get_user_listening_history
26
39
26
26
ebf8bce3bb79b1aee512b88b516cd2e75c8fbf1b
bigcode/the-stack
train
1eb44725c3ee19bd8da169f8
train
function
def random_number(x): x = random.randint(0,x) return x
def random_number(x):
x = random.randint(0,x) return x
import random def random_number(x):
8
64
18
5
2
jamesanderegg/Bootcamp
pyGame/unti.py
Python
random_number
random_number
3
5
3
3
27d90083ea40c76bc1d25764696a6ca3d07db613
bigcode/the-stack
train
023fa2f8471dc0d592127d24
train
function
def custom_doc_links(name): return None
def custom_doc_links(name):
return None
dbcm.py", "latent_factor.py", "latent_factor_fxns.py"] doc_url = "https://lavinei.github.io/pybats_nbdev/" git_url = "https://github.com/lavinei/pybats_nbdev/tree/master/" def custom_doc_links(name):
63
64
9
7
56
lavinei/pybats_nbdev
pybats_nbdev/_nbdev.py
Python
custom_doc_links
custom_doc_links
166
166
166
166
390ddb9d1e2c7814108e0dcac5f5934fcac9c70b
bigcode/the-stack
train
74faba64e93d5109a6390058
train
class
class SequenceLabellerWidget(ScriptedLoadableModuleWidget, VTKObservationMixin): """Uses ScriptedLoadableModuleWidget base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def __init__(self, parent=None): """ Called when the user opens t...
class SequenceLabellerWidget(ScriptedLoadableModuleWidget, VTKObservationMixin):
"""Uses ScriptedLoadableModuleWidget base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def __init__(self, parent=None): """ Called when the user opens the module the first time and the widget is initialized. """ ScriptedLoada...
this more human readable by adding spaces self.parent.categories = ["Examples"] # TODO: set categories (folders where the module shows up in the module selector) self.parent.dependencies = [] # TODO: add here list of module names that this module requires self.parent.contributors = ["John Doe (AnyWare Co...
256
256
2,262
18
238
ColtonBarr/aigt
SequenceLabeller/SequenceLabeller.py
Python
SequenceLabellerWidget
SequenceLabellerWidget
38
249
38
38
c4828b85912ff8d10123833f5c3a7cef4af35fb3
bigcode/the-stack
train
54243efaa060227796b66afc
train
class
class SequenceLabeller(ScriptedLoadableModule): """Uses ScriptedLoadableModule base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def __init__(self, parent): ScriptedLoadableModule.__init__(self, parent) self.parent.title = "Sequence ...
class SequenceLabeller(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def __init__(self, parent): ScriptedLoadableModule.__init__(self, parent) self.parent.title = "Sequence Labeller" # TODO: make this more human readable...
import os import unittest import logging import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * from slicer.util import VTKObservationMixin # # SequenceLabeller # class SequenceLabeller(ScriptedLoadableModule):
58
95
318
11
47
ColtonBarr/aigt
SequenceLabeller/SequenceLabeller.py
Python
SequenceLabeller
SequenceLabeller
12
32
12
12
c8112ebd5d71e426cef68866a82ef9f3ff6cf932
bigcode/the-stack
train
8b796ff47ce5697a98c641e5
train
class
class SequenceLabellerLogic(ScriptedLoadableModuleLogic): """This class should implement all the actual computation done by your module. The interface should be such that other python code can import this class and make use of the functionality without requiring an instance of the Widget. Uses ScriptedLoad...
class SequenceLabellerLogic(ScriptedLoadableModuleLogic):
"""This class should implement all the actual computation done by your module. The interface should be such that other python code can import this class and make use of the functionality without requiring an instance of the Widget. Uses ScriptedLoadableModuleLogic base class, available at: https://github...
(sequenceBrowser, inputSegmentation, inputVolume, outputSequenceBrowser) except Exception as e: slicer.util.errorDisplay("Failed to compute results: "+str(e)) import traceback traceback.print_exc() finally: slicer.app.resumeRender() pass def onMarkupApply(self): try: ...
256
256
1,928
13
243
ColtonBarr/aigt
SequenceLabeller/SequenceLabeller.py
Python
SequenceLabellerLogic
SequenceLabellerLogic
257
417
257
257
925db50fc5a6fd1534bf2d6c35d881d31ffed99c
bigcode/the-stack
train
485970681a235cb53fcf5390
train
class
class SequenceLabellerTest(ScriptedLoadableModuleTest): """ This is the test case for your scripted module. Uses ScriptedLoadableModuleTest base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def setUp(self): """ Do whatever is needed ...
class SequenceLabellerTest(ScriptedLoadableModuleTest):
""" This is the test case for your scripted module. Uses ScriptedLoadableModuleTest base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def setUp(self): """ Do whatever is needed to reset the state - typically a scene clear will be eno...
TransformNode is None: sequenceNode = input_sequence_browser_node.GetSequenceNode(currentTransformNode) if sequenceNode: output_sequence_browser_node.AddSynchronizedSequenceNode(sequenceNode) output_sequence_browser_node.AddProxyNode(currentTransformNode, sequenceNode, False) currentTr...
89
89
299
13
76
ColtonBarr/aigt
SequenceLabeller/SequenceLabeller.py
Python
SequenceLabellerTest
SequenceLabellerTest
423
454
423
423
7e237c1f76ab46e2c092fa2322820783521e0bdd
bigcode/the-stack
train
ef6c4a28248425c9990eb0c5
train
function
def merge_data(in_dir, out_dir, raw_info, bins): """Merge all data into a single (regridded) file.""" var = raw_info['name'] do_bin = (bins != 0) and (bins % 2 == 0) datafile = sorted(glob.glob(in_dir + '/' + raw_info['file'] + '*.nc')) for x in datafile: ds = xr.open_dataset(x) da =...
def merge_data(in_dir, out_dir, raw_info, bins):
"""Merge all data into a single (regridded) file.""" var = raw_info['name'] do_bin = (bins != 0) and (bins % 2 == 0) datafile = sorted(glob.glob(in_dir + '/' + raw_info['file'] + '*.nc')) for x in datafile: ds = xr.open_dataset(x) da = ds[var].sel(lat=slice(None, None, -1)) #...
) cube.coordinates = 'depth' def extract_variable(var_info, raw_info, out_dir, attrs): """Extract to all vars.""" var = var_info.short_name cubes = iris.load(raw_info['file']) rawvar = raw_info['name'] for cube in cubes: if cube.var_name == rawvar: fix_var_metadata(cub...
159
159
531
14
145
YanchunHe/ESMValTool
esmvaltool/cmorizers/obs/cmorize_obs_esacci_oc.py
Python
merge_data
merge_data
84
149
84
84
7c3de70186de861171f8e4d73b54871bb650108f
bigcode/the-stack
train
c48fe7922bc91d71d864b52d
train
function
def cmorization(in_dir, out_dir, cfg, _): """Cmorization func call.""" cmor_table = cfg['cmor_table'] glob_attrs = cfg['attributes'] # run the cmorization for var, vals in cfg['variables'].items(): var_info = cmor_table.get_variable(vals['mip'], var) glob_attrs['mip'] = vals['mip'] ...
def cmorization(in_dir, out_dir, cfg, _):
"""Cmorization func call.""" cmor_table = cfg['cmor_table'] glob_attrs = cfg['attributes'] # run the cmorization for var, vals in cfg['variables'].items(): var_info = cmor_table.get_variable(vals['mip'], var) glob_attrs['mip'] = vals['mip'] raw_info = {'name': vals['raw'], '...
'_merged.nc') ds.to_netcdf(datafile, encoding=thekeys, unlimited_dims='time') logger.info("Merged data written to: %s", datafile) return (datafile, dsmeta['BINNING']) def cmorization(in_dir, out_dir, cfg, _):
64
65
218
14
50
YanchunHe/ESMValTool
esmvaltool/cmorizers/obs/cmorize_obs_esacci_oc.py
Python
cmorization
cmorization
152
173
152
152
1c08b1952c87f1f17bfd2c07479c6bac3a7a250b
bigcode/the-stack
train
dfac980bcdc297868a1f78be
train
function
def _add_depth_coord(cube): """Add depth auxiliary coordinate for CMIP5 standard.""" if not cube.coords('depth'): depth = 1. depth_coord = iris.coords.AuxCoord( depth, standard_name='depth', long_name='depth', var_name='depth', units='m...
def _add_depth_coord(cube):
"""Add depth auxiliary coordinate for CMIP5 standard.""" if not cube.coords('depth'): depth = 1. depth_coord = iris.coords.AuxCoord( depth, standard_name='depth', long_name='depth', var_name='depth', units='m', attributes={'...
name__) def _fix_data(cube, var): """Specific data fixes for different variables.""" logger.info("Fixing data ...") with constant_metadata(cube): if var == 'chl': cube *= 1.e-06 return cube def _add_depth_coord(cube):
64
64
93
8
55
YanchunHe/ESMValTool
esmvaltool/cmorizers/obs/cmorize_obs_esacci_oc.py
Python
_add_depth_coord
_add_depth_coord
46
58
46
46
27fc5e25310a4a39e73393560332dfcf8ade39a0
bigcode/the-stack
train
773f0e42d28540a1d0f86d5a
train
function
def extract_variable(var_info, raw_info, out_dir, attrs): """Extract to all vars.""" var = var_info.short_name cubes = iris.load(raw_info['file']) rawvar = raw_info['name'] for cube in cubes: if cube.var_name == rawvar: fix_var_metadata(cube, var_info) fix_coords(cub...
def extract_variable(var_info, raw_info, out_dir, attrs):
"""Extract to all vars.""" var = var_info.short_name cubes = iris.load(raw_info['file']) rawvar = raw_info['name'] for cube in cubes: if cube.var_name == rawvar: fix_var_metadata(cube, var_info) fix_coords(cube) _add_depth_coord(cube) _fix_dat...
( depth, standard_name='depth', long_name='depth', var_name='depth', units='m', attributes={'positive': 'down'}) cube.add_aux_coord(depth_coord) cube.coordinates = 'depth' def extract_variable(var_info, raw_info, out_dir, attrs):
64
64
137
14
50
YanchunHe/ESMValTool
esmvaltool/cmorizers/obs/cmorize_obs_esacci_oc.py
Python
extract_variable
extract_variable
61
81
61
61
568c1104a6ea56a914666c9431a844ac868c205c
bigcode/the-stack
train
35c738ab3065b48cc80d6982
train
function
def _fix_data(cube, var): """Specific data fixes for different variables.""" logger.info("Fixing data ...") with constant_metadata(cube): if var == 'chl': cube *= 1.e-06 return cube
def _fix_data(cube, var):
"""Specific data fixes for different variables.""" logger.info("Fixing data ...") with constant_metadata(cube): if var == 'chl': cube *= 1.e-06 return cube
omas: written. """ import glob import logging import os import iris import xarray as xr from .utilities import (constant_metadata, fix_coords, fix_var_metadata, save_variable, set_global_atts) logger = logging.getLogger(__name__) def _fix_data(cube, var):
64
64
54
9
55
YanchunHe/ESMValTool
esmvaltool/cmorizers/obs/cmorize_obs_esacci_oc.py
Python
_fix_data
_fix_data
37
43
37
37
e69fc970de88de04055f2e926e1436308e5e14da
bigcode/the-stack
train
ba325c95bd827058a1a2c5df
train
class
class Dataset_ue(Dataset): shared_dict = init_shared_dict() def __init__(self, args, set_): super().__init__(args, set_) self.clip = getattr(args, "clip", None) self.init_data(args.input_prefix, set_, args.video_slice) self.count_data() self.print_stats() self.se...
class Dataset_ue(Dataset):
shared_dict = init_shared_dict() def __init__(self, args, set_): super().__init__(args, set_) self.clip = getattr(args, "clip", None) self.init_data(args.input_prefix, set_, args.video_slice) self.count_data() self.print_stats() self.segmentation_model = None ...
.utils.image import tis from pyronan.utils.misc import init_shared_dict, mp_cache def process_features(f, select_features=None, clip=None): if select_features is not None: f = f[select_features] if clip is not None: f = f.clip(-clip, clip) f += f.sum(-1, keepdims=True) * 0 n_obj = 3 ...
256
256
3,096
7
248
rronan/Recurrent-Interaction-Network
datasets/dataset_ue.py
Python
Dataset_ue
Dataset_ue
39
310
39
39
6a07a200120e44ada03bcfa8134bb5d138d61676
bigcode/the-stack
train
6735ec4fce1f0aac937a972d
train
function
def process_features(f, select_features=None, clip=None): if select_features is not None: f = f[select_features] if clip is not None: f = f.clip(-clip, clip) f += f.sum(-1, keepdims=True) * 0 n_obj = 3 f = f[:n_obj] f = np.pad(f, ((0, n_obj - f.shape[0]), (0, 0)), constant_values...
def process_features(f, select_features=None, clip=None):
if select_features is not None: f = f[select_features] if clip is not None: f = f.clip(-clip, clip) f += f.sum(-1, keepdims=True) * 0 n_obj = 3 f = f[:n_obj] f = np.pad(f, ((0, n_obj - f.shape[0]), (0, 0)), constant_values=float("nan")) return f
Positional_Reconstruction_Network.src.datasets.dataset import Dataset from Positional_Reconstruction_Network.src.datasets.detection import make_semantic_mask from pyronan.utils.image import tis from pyronan.utils.misc import init_shared_dict, mp_cache def process_features(f, select_features=None, clip=None):
64
64
110
12
51
rronan/Recurrent-Interaction-Network
datasets/dataset_ue.py
Python
process_features
process_features
15
24
15
15
694e66e973e7246959ed63b90951801b207f7670
bigcode/the-stack
train
779c29b1d0cbf8f9b585d918
train
function
def process_depth(f, relative_depth=False, depth_noise=None): if not relative_depth and depth_noise is None: return f depth_mask = np.array([False, False, True] * 4 + [False] * 4)[np.newaxis] depth_mask = np.repeat(depth_mask, f.shape[0], axis=0) if relative_depth: f[depth_mask] -= np.na...
def process_depth(f, relative_depth=False, depth_noise=None):
if not relative_depth and depth_noise is None: return f depth_mask = np.array([False, False, True] * 4 + [False] * 4)[np.newaxis] depth_mask = np.repeat(depth_mask, f.shape[0], axis=0) if relative_depth: f[depth_mask] -= np.nanmin(f[depth_mask]) if depth_noise is not None: f[...
0 n_obj = 3 f = f[:n_obj] f = np.pad(f, ((0, n_obj - f.shape[0]), (0, 0)), constant_values=float("nan")) return f def process_depth(f, relative_depth=False, depth_noise=None):
64
64
120
13
50
rronan/Recurrent-Interaction-Network
datasets/dataset_ue.py
Python
process_depth
process_depth
27
36
27
27
c8f4a2b69cc8a261c009138fdf7be2351840abdb
bigcode/the-stack
train
fca4457bbcea1666a4e28234
train
class
class Eras (object): """ Dummy container for all the cms.Modifier instances that config fragments can use to selectively configure depending on what scenario is active. """ def __init__(self): allEras=['Run1_pA', 'Run1_peripheralPbPb', 'Run2_50ns', ...
class Eras (object):
""" Dummy container for all the cms.Modifier instances that config fragments can use to selectively configure depending on what scenario is active. """ def __init__(self): allEras=['Run1_pA', 'Run1_peripheralPbPb', 'Run2_50ns', 'Run2_50ns_HI...
from __future__ import print_function import FWCore.ParameterSet.Config as cms from FWCore.ParameterSet.Config import ModifierChain,Modifier class Eras (object):
36
256
1,513
6
29
yguler/cmssw
Configuration/StandardSequences/python/Eras.py
Python
Eras
Eras
5
130
5
5
a4e99f41cb377394c66864214870e4f100fadb68
bigcode/the-stack
train
ec5c6426a1132e0bb0e7f2ce
train
class
@admin.register(Answer) class AnswerAdmin(admin.ModelAdmin): list_display = ('user', 'question', 'text', 'created_at') list_filter = ('question', 'created_at')
@admin.register(Answer) class AnswerAdmin(admin.ModelAdmin):
list_display = ('user', 'question', 'text', 'created_at') list_filter = ('question', 'created_at')
= Choice extra = 0 @admin.register(Question) class QuestionAdmin(admin.ModelAdmin): list_display = ('number', 'text') list_display_links = ('number', 'text') inlines = [ChoiceInline] @admin.register(Answer) class AnswerAdmin(admin.ModelAdmin):
64
64
41
13
51
eyobofficial/COVID-19-Mutual-Aid
survey/admin.py
Python
AnswerAdmin
AnswerAdmin
18
21
18
19
420a261effa695e2fb9bdfd3de9c259ef5d535bd
bigcode/the-stack
train
28f666efb7da92445f26c2d4
train
class
class ChoiceInline(admin.StackedInline): model = Choice extra = 0
class ChoiceInline(admin.StackedInline):
model = Choice extra = 0
from django.contrib import admin from .models import Question, Choice, Answer, UserSession class ChoiceInline(admin.StackedInline):
27
64
19
8
18
eyobofficial/COVID-19-Mutual-Aid
survey/admin.py
Python
ChoiceInline
ChoiceInline
6
8
6
6
0b3c726522b4a7f6b00cfb9e4b2ae1fc189a5571
bigcode/the-stack
train
0e863fba3258d5475485894e
train
class
@admin.register(Question) class QuestionAdmin(admin.ModelAdmin): list_display = ('number', 'text') list_display_links = ('number', 'text') inlines = [ChoiceInline]
@admin.register(Question) class QuestionAdmin(admin.ModelAdmin):
list_display = ('number', 'text') list_display_links = ('number', 'text') inlines = [ChoiceInline]
from django.contrib import admin from .models import Question, Choice, Answer, UserSession class ChoiceInline(admin.StackedInline): model = Choice extra = 0 @admin.register(Question) class QuestionAdmin(admin.ModelAdmin):
51
64
42
13
37
eyobofficial/COVID-19-Mutual-Aid
survey/admin.py
Python
QuestionAdmin
QuestionAdmin
11
15
11
12
54ca6c408572fc723db40af862956999470aca22
bigcode/the-stack
train
bf573a9ea0b39d3075fe1c21
train
function
@pytest.mark.skipif( os.getenv("NM_ML_SKIP_PYTORCH_TESTS", False), reason="Skipping pytorch tests", ) def test_default_box_representations(): default_boxes = get_default_boxes_300() xywh_boxes = default_boxes.as_xywh() ltrb_boxes = default_boxes.as_ltrb() x = 0.5 * (ltrb_boxes[:, 2] + ltrb_boxe...
@pytest.mark.skipif( os.getenv("NM_ML_SKIP_PYTORCH_TESTS", False), reason="Skipping pytorch tests", ) def test_default_box_representations():
default_boxes = get_default_boxes_300() xywh_boxes = default_boxes.as_xywh() ltrb_boxes = default_boxes.as_ltrb() x = 0.5 * (ltrb_boxes[:, 2] + ltrb_boxes[:, 0]) y = 0.5 * (ltrb_boxes[:, 3] + ltrb_boxes[:, 1]) w = ltrb_boxes[:, 2] - ltrb_boxes[:, 0] h = ltrb_boxes[:, 3] - ltrb_boxes[:, 1] ...
the License for the specific language governing permissions and # limitations under the License. import os import pytest import torch from sparseml.pytorch.utils import get_default_boxes_300 @pytest.mark.skipif( os.getenv("NM_ML_SKIP_PYTORCH_TESTS", False), reason="Skipping pytorch tests", ) def test_defaul...
77
77
259
39
37
clementpoiret/sparseml
tests/sparseml/pytorch/utils/test_ssd_helpers.py
Python
test_default_box_representations
test_default_box_representations
23
40
23
27
864880a91b5f2dd87aa351cd498171bdf1b6c71c
bigcode/the-stack
train
3ed141005121ba49930b5d0b
train
function
@pytest.mark.skipif( os.getenv("NM_ML_SKIP_PYTORCH_TESTS", False), reason="Skipping pytorch tests", ) def test_default_box_encode_decode(): default_boxes = get_default_boxes_300() boxes = torch.FloatTensor(1, 4).uniform_(0.0, 1.0).sort()[0] # random ltrb box labels = torch.Tensor([1]) enc_boxes...
@pytest.mark.skipif( os.getenv("NM_ML_SKIP_PYTORCH_TESTS", False), reason="Skipping pytorch tests", ) def test_default_box_encode_decode():
default_boxes = get_default_boxes_300() boxes = torch.FloatTensor(1, 4).uniform_(0.0, 1.0).sort()[0] # random ltrb box labels = torch.Tensor([1]) enc_boxes, enc_labels = default_boxes.encode_image_box_labels(boxes, labels) # create scores to simulate model output scores = torch.zeros(1, 2, enc...
2] - w)) < 1e-4 assert torch.max(torch.abs(xywh_boxes[:, 3] - h)) < 1e-4 @pytest.mark.skipif( os.getenv("NM_ML_SKIP_PYTORCH_TESTS", False), reason="Skipping pytorch tests", ) def test_default_box_encode_decode():
74
74
247
38
35
clementpoiret/sparseml
tests/sparseml/pytorch/utils/test_ssd_helpers.py
Python
test_default_box_encode_decode
test_default_box_encode_decode
43
63
43
47
4581ce8fc8382aca804ff9638fdc955c29c1a03a
bigcode/the-stack
train
089e270c65f7951e95a22e16
train
class
class Point(AbstractPoint): """ Mathmatically 3d point. >>> Point() Point(x=0, y=0, z=0) """ def __repr__(self) -> str: """ Returns: str: readable representation of the values of this class. """ return "Point(x=%(x)g, y=%(y)g, z=%(z)g)" % self.__dict...
class Point(AbstractPoint):
""" Mathmatically 3d point. >>> Point() Point(x=0, y=0, z=0) """ def __repr__(self) -> str: """ Returns: str: readable representation of the values of this class. """ return "Point(x=%(x)g, y=%(y)g, z=%(z)g)" % self.__dict__ def __sub__(self, ot...
"""Mathmatical 3d point.""" from __future__ import annotations from engine.threed.base.point import AbstractPoint from engine.threed.base.vector import AbstractVector from engine.threed.vector import Vector class Point(AbstractPoint):
49
155
519
5
43
Nachtfeuer/engine
engine/threed/point.py
Python
Point
Point
10
89
10
10
8d92d9b7efa7e6e658763e5b8c24d3bd3d432b08
bigcode/the-stack
train
cc0779c42e4a79311cdf4636
train
class
class MinexponentValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="minexponent", parent_name="scattermapbox.marker.colorbar", **kwargs ): super(MinexponentValidator, self).__init__( plotly_name=plotly_name, p...
class MinexponentValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__( self, plotly_name="minexponent", parent_name="scattermapbox.marker.colorbar", **kwargs ): super(MinexponentValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "cal...
import _plotly_utils.basevalidators class MinexponentValidator(_plotly_utils.basevalidators.NumberValidator):
22
64
106
14
7
andresgreen-byte/Laboratorio-1--Inversion-de-Capital
env/Lib/site-packages/plotly/validators/scattermapbox/marker/colorbar/_minexponent.py
Python
MinexponentValidator
MinexponentValidator
4
17
4
4
e7ee12be3fb37617763fb043a8301c07fd11f26f
bigcode/the-stack
train
33cdbc920ee0d5a679d1bbfe
train
class
class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserProfile', fields=[ ('id', models.AutoField(auto_created=True, serialize=False, prima...
class Migration(migrations.Migration):
dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserProfile', fields=[ ('id', models.AutoField(auto_created=True, serialize=False, primary_key=True, verbose_name='ID')), ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration):
37
64
140
7
29
rikkt0r/django-organiser
app/users/migrations/0001_initial.py
Python
Migration
Migration
8
26
8
9
33c07c0774a937f0b3fbc80cce61509d380515dc
bigcode/the-stack
train
314c98991016a7fa21de802c
train
class
class ReshapeStream(OptimizerPass): ''' Repacks stream for Reshape layer ''' def match(self, node): # do not run optimizer pass for a flatten layer (1 output dimension) return node.__class__.__name__ == 'Reshape' and len(node.get_output_variable().shape) > 1 def transform(self, model, node)...
class ReshapeStream(OptimizerPass):
''' Repacks stream for Reshape layer ''' def match(self, node): # do not run optimizer pass for a flatten layer (1 output dimension) return node.__class__.__name__ == 'Reshape' and len(node.get_output_variable().shape) > 1 def transform(self, model, node): if model.config.backend.na...
', 'VivadoAccelerator']: templates.get_backend(backend).register_templates('Repack', repack_function_template, None, repack_include_list) templates.get_backend(backend).register_templates('Broadcast', broadcast_function_template, broadcast_config_template, broadcast_include_list) class ReshapeStream(OptimizerPa...
64
64
185
8
56
julesmuhizi/hls4ml
hls4ml/model/optimizer/passes/repack_stream.py
Python
ReshapeStream
ReshapeStream
71
90
71
71
09cafefe77c5e6a6ff41f3e10b013b7cc11360b1
bigcode/the-stack
train
fba761606696b6b52eb1fe38
train
class
class Repack(Layer): ''' Inserted between layers with different packing factors.''' def initialize(self): shape = self.attributes['target_shape'] if shape[0] is None: shape = shape[1:] dims = ['N_SIZE_{}_{}'.format(i, self.index) for i in range(1, len(shape) + 1)] s...
class Repack(Layer):
''' Inserted between layers with different packing factors.''' def initialize(self): shape = self.attributes['target_shape'] if shape[0] is None: shape = shape[1:] dims = ['N_SIZE_{}_{}'.format(i, self.index) for i in range(1, len(shape) + 1)] self.add_output_variab...
import numpy as np from hls4ml.model.optimizer import OptimizerPass from hls4ml.model.hls_model import Layer, register_layer from hls4ml.templates import templates class Repack(Layer):
47
64
137
6
40
julesmuhizi/hls4ml
hls4ml/model/optimizer/passes/repack_stream.py
Python
Repack
Repack
8
25
8
8
a1ae5caffe224d4328c6886a84c8f0adc1fcecd2
bigcode/the-stack
train
52b632101e6d1764ca809a47
train
class
class Broadcast(Layer): ''' Inserted between layers for broadcasting.''' def initialize(self): shape = self.attributes['target_shape'] if shape[0] is None: shape = shape[1:] dims = ['N_SIZE_{}_{}'.format(i, self.index) for i in range(1, len(shape) + 1)] self.add_outp...
class Broadcast(Layer):
''' Inserted between layers for broadcasting.''' def initialize(self): shape = self.attributes['target_shape'] if shape[0] is None: shape = shape[1:] dims = ['N_SIZE_{}_{}'.format(i, self.index) for i in range(1, len(shape) + 1)] self.add_output_variable(shape, dims)...
self.add_output_variable(shape, dims) def function_cpp(self): params = self._default_function_params() params['size'] = np.prod(self.get_output_variable().shape) return [self._function_template.format(**params)] def config_cpp(self): return None class Broadcast(Layer):
64
64
209
5
58
julesmuhizi/hls4ml
hls4ml/model/optimizer/passes/repack_stream.py
Python
Broadcast
Broadcast
27
47
27
27
ab0de1088b87704ddb2225522d2f833e82916d1c
bigcode/the-stack
train
319baf5b75678afe7054a7e5
train
class
class BroadcastStream(OptimizerPass): def match(self, node): if node.__class__.__name__ == 'Merge': inp1 = node.get_input_variable(node.inputs[0]) inp2 = node.get_input_variable(node.inputs[1]) return inp1.shape != inp2.shape else: return False ...
class BroadcastStream(OptimizerPass):
def match(self, node): if node.__class__.__name__ == 'Merge': inp1 = node.get_input_variable(node.inputs[0]) inp2 = node.get_input_variable(node.inputs[1]) return inp1.shape != inp2.shape else: return False def transform(self, model, node)...
': return False attrs = { 'target_shape': node.get_attr('target_shape') } # Insert new Repack node instead of Reshape repack_layer = model.make_node('Repack', 'repack_' + node.name, attrs, node.inputs.copy()) model.replace_node(node, repack_layer) ...
82
82
276
7
74
julesmuhizi/hls4ml
hls4ml/model/optimizer/passes/repack_stream.py
Python
BroadcastStream
BroadcastStream
92
124
92
92
8f5962d0f6d94f4315732b91f2d094e82994001e
bigcode/the-stack
train
d6bc7ddf5fd0482abf90c417
train
class
class RemoveFinalReshape(OptimizerPass): ''' Remove reshape if final layer ''' def match(self, node): # match if reshape is final node return node.__class__.__name__ == 'Reshape' and not node.get_output_nodes() def transform(self, model, node): if model.config.get_config_value('IOTy...
class RemoveFinalReshape(OptimizerPass):
''' Remove reshape if final layer ''' def match(self, node): # match if reshape is final node return node.__class__.__name__ == 'Reshape' and not node.get_output_nodes() def transform(self, model, node): if model.config.get_config_value('IOType') == 'io_parallel': print(...
_inp brdcst_layer = model.make_node('Broadcast', brdcst_out, attrs, [brdcst_inp].copy()) model.insert_node(brdcst_layer) node.inputs[idx] = brdcst_out return True class RemoveFinalReshape(OptimizerPass):
64
64
179
9
54
julesmuhizi/hls4ml
hls4ml/model/optimizer/passes/repack_stream.py
Python
RemoveFinalReshape
RemoveFinalReshape
126
140
126
126
25388323b66e1be2d76a2b81a373b12490118aeb
bigcode/the-stack
train
2018af6fbcd49b8223b639bb
train
function
def getWinner(ballots): """ get_winner == PEP8 (forced mixedCase by CodeWars) """ counts = Counter(ballots) flip = defaultdict(list) for a, b in counts.items(): flip[b].append(a) max_key = max(flip) max_val = flip[max_key] return max_val[0] if len(max_val) == 1 and \ max_key ...
def getWinner(ballots):
""" get_winner == PEP8 (forced mixedCase by CodeWars) """ counts = Counter(ballots) flip = defaultdict(list) for a, b in counts.items(): flip[b].append(a) max_key = max(flip) max_val = flip[max_key] return max_val[0] if len(max_val) == 1 and \ max_key > len(ballots) / 2 else ...
from collections import Counter, defaultdict def getWinner(ballots):
13
64
100
6
6
the-zebulan/CodeWars
katas/kyu_6/who_won_the_election.py
Python
getWinner
getWinner
4
13
4
4
a0c0b9f6ded3f6a011b5e69eea0b3de396ce093d
bigcode/the-stack
train
8951c2cf8df0f88a9a498538
train
function
def test_basicblock(): data = torch.randn(1, 64, 56, 56) inplanes = 64 planes = 128 expansion = BasicBlock.expansion # 不进行下采样 stride = 1 downsample = nn.Sequential( nn.Conv2d(inplanes, planes * expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * exp...
def test_basicblock():
data = torch.randn(1, 64, 56, 56) inplanes = 64 planes = 128 expansion = BasicBlock.expansion # 不进行下采样 stride = 1 downsample = nn.Sequential( nn.Conv2d(inplanes, planes * expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * expansion), ) mode...
# -*- coding: utf-8 -*- """ @date: 2020/11/21 下午3:00 @file: test_basicblock.py @author: zj @description: """ import torch import torch.nn as nn from tsn.model.backbones.basicblock import BasicBlock def test_basicblock():
67
75
253
5
61
ZJCV/Non-local
test/test_model/test_backbone/test_basicblock.py
Python
test_basicblock
test_basicblock
16
46
16
16
620bf06e137dc88a222f794e53342c4c68c43c45
bigcode/the-stack
train
2f2abde0fbce827c759a51fc
train
class
class UserViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet): serializer_class = UserSerializer queryset = User.objects.all() lookup_field = "username" permission_classes = [permissions.IsAdminUser] @action(detail=False, methods=["GET"]) def me(self, request): ...
class UserViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet):
serializer_class = UserSerializer queryset = User.objects.all() lookup_field = "username" permission_classes = [permissions.IsAdminUser] @action(detail=False, methods=["GET"]) def me(self, request): serializer = UserSerializer(request.user, context={"request": request}) return R...
RetrieveModelMixin, UpdateModelMixin from rest_framework.response import Response from rest_framework.viewsets import GenericViewSet from orochi.users.api.serializers import UserSerializer User = get_user_model() class UserViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet):
64
64
98
21
43
Shymonster94/orochi
orochi/users/api/views.py
Python
UserViewSet
UserViewSet
13
22
13
13
1204cef9b9345cd65d21ef39d46d007a139be69d
bigcode/the-stack
train
48b9e5bb4c89079993be0067
train
function
def get_info(): conn = connect_db() c = conn.cursor() list = [] c.execute("SELECT * FROM ADMIN.EMPLOYEE_INFO") for row in c: info = EmployeeInfo(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7]) list.append(info) # close connection conn.close() return li...
def get_info():
conn = connect_db() c = conn.cursor() list = [] c.execute("SELECT * FROM ADMIN.EMPLOYEE_INFO") for row in c: info = EmployeeInfo(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7]) list.append(info) # close connection conn.close() return list
from connection import connect_db import cx_Oracle from data.Classes.EmployeeInfo import EmployeeInfo # get all employee info def get_info():
30
64
93
4
25
GoProduction/Employee_Management_System
controllers/employee_info_controller.py
Python
get_info
get_info
6
20
6
6
6baa148443eb00feb60a03ea4957b06847449cf7
bigcode/the-stack
train
eafee87813888bcbbb2fa741
train
function
def crear_partida(cant_jug_part_actual): print("Iniciando la partida") #Mezclamos las cartas cartas_mez = mezclar_cartas(carta) print(cartas_mez) #Creamos la partida y el jugador "casa" partida_actual = Partida(1, True) casa = Jugador() casa.nombre_de_usuario = "Casa00" casa.nombre =...
def crear_partida(cant_jug_part_actual):
print("Iniciando la partida") #Mezclamos las cartas cartas_mez = mezclar_cartas(carta) print(cartas_mez) #Creamos la partida y el jugador "casa" partida_actual = Partida(1, True) casa = Jugador() casa.nombre_de_usuario = "Casa00" casa.nombre = "Casa" partida_actual.cant_j = cant_...
= list_temporal[cont_ale] list_temporal[cont_ale] = temporal return list_temporal #funcion para recibir datos #recibe un dato del cliente y lo devuelve decodificado def recibirDatos(): dato_recibido = b'' dato_recibido = connection.recv(128) return dato_recibido.decode() #funcion para enviar...
256
256
1,013
11
244
matias1405/card_game_21_v2_2021
pc_servidor/main.py
Python
crear_partida
crear_partida
47
131
47
47
39181a2a18787074ef3b4dc8160e14b0d299d401
bigcode/the-stack
train
96784242c6fa3078d91a7b87
train
function
def mezclar_cartas(carta): list_temporal = [] for x in range(len(carta)): list_temporal.append(carta[x].id) for x in range(len(carta)): cont_ale = random.randint(0,len(carta)-1) temporal = list_temporal[x] list_temporal[x] = list_temporal[cont_ale] list_temporal[cont_...
def mezclar_cartas(carta):
list_temporal = [] for x in range(len(carta)): list_temporal.append(carta[x].id) for x in range(len(carta)): cont_ale = random.randint(0,len(carta)-1) temporal = list_temporal[x] list_temporal[x] = list_temporal[cont_ale] list_temporal[cont_ale] = temporal return ...
from partida import * from jugador import * from carta import * import random import socket #funcion para mezclar las cartas def mezclar_cartas(carta):
35
64
99
8
26
matias1405/card_game_21_v2_2021
pc_servidor/main.py
Python
mezclar_cartas
mezclar_cartas
8
17
8
8
686a7973a859b51d8bc9964dbd60afb7c90d9e25
bigcode/the-stack
train
0ad2274d9fe032d9ed280c0e
train
function
def enviarDatos(dato_esperado, dato_a_enviar): dato_a_enviar = str(dato_a_enviar) dato = "" while (True): dato = recibirDatos() if(dato == dato_esperado): respuesta = "si" connection.send(respuesta.encode()) break else: respuesta = "no"...
def enviarDatos(dato_esperado, dato_a_enviar):
dato_a_enviar = str(dato_a_enviar) dato = "" while (True): dato = recibirDatos() if(dato == dato_esperado): respuesta = "si" connection.send(respuesta.encode()) break else: respuesta = "no" connection.send(respuesta.encode()...
para enviar datos #primero espera un msj del cliente solicitando un dato #se compara y se responde si es el dato esperado o no #si es la peticion esperada se envia el dato que solicito el cliente def enviarDatos(dato_esperado, dato_a_enviar):
64
64
94
14
49
matias1405/card_game_21_v2_2021
pc_servidor/main.py
Python
enviarDatos
enviarDatos
31
43
31
31
f31596da436e336898399987eb37a3d52066a29f
bigcode/the-stack
train
fab0816714780d28cfd05041
train
function
def recibirDatos(): dato_recibido = b'' dato_recibido = connection.recv(128) return dato_recibido.decode()
def recibirDatos():
dato_recibido = b'' dato_recibido = connection.recv(128) return dato_recibido.decode()
= list_temporal[x] list_temporal[x] = list_temporal[cont_ale] list_temporal[cont_ale] = temporal return list_temporal #funcion para recibir datos #recibe un dato del cliente y lo devuelve decodificado def recibirDatos():
64
64
31
4
59
matias1405/card_game_21_v2_2021
pc_servidor/main.py
Python
recibirDatos
recibirDatos
22
25
22
22
2d9e0c52b18c4c645bb7cc34f3f8b4da612142ac
bigcode/the-stack
train
af543a8a2aa7e2068d1bdac0
train
function
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the ZWave thermostats.""" if discovery_info is None or zwave.NETWORK is None: _LOGGER.debug("No discovery_info=%s or no NETWORK=%s", discovery_info, zwave.NETWORK) return node = zwave.NETWORK....
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the ZWave thermostats.""" if discovery_info is None or zwave.NETWORK is None: _LOGGER.debug("No discovery_info=%s or no NETWORK=%s", discovery_info, zwave.NETWORK) return node = zwave.NETWORK.nodes[discovery_info[zwave.const.ATTR_NODE_ID]] value = node.val...
_NAME = 'ZWave Thermostat' REMOTEC = 0x5254 REMOTEC_ZXT_120 = 0x8377 REMOTEC_ZXT_120_THERMOSTAT = (REMOTEC, REMOTEC_ZXT_120) WORKAROUND_IGNORE = 'ignore' DEVICE_MAPPINGS = { REMOTEC_ZXT_120_THERMOSTAT: WORKAROUND_IGNORE } def setup_platform(hass, config, add_devices, discovery_info=None):
105
105
351
15
90
gwendalg/home-assistant
homeassistant/components/thermostat/zwave.py
Python
setup_platform
setup_platform
29
60
29
29
28a79fc144788e9ef805f547bae9dc13a20e1055
bigcode/the-stack
train
8e72967b82dddb9a447ba118
train
class
class ZWaveThermostat(zwave.ZWaveDeviceEntity, ThermostatDevice): """Represents a HeatControl thermostat.""" def __init__(self, value): """Initialize the zwave thermostat.""" from openzwave.network import ZWaveNetwork from pydispatch import dispatcher zwave.ZWaveDeviceEntity.__i...
class ZWaveThermostat(zwave.ZWaveDeviceEntity, ThermostatDevice):
"""Represents a HeatControl thermostat.""" def __init__(self, value): """Initialize the zwave thermostat.""" from openzwave.network import ZWaveNetwork from pydispatch import dispatcher zwave.ZWaveDeviceEntity.__init__(self, value, DOMAIN) self._node = value.node ...
_id, 16), int(value.node.product_id, 16)) if specific_sensor_key in DEVICE_MAPPINGS: if DEVICE_MAPPINGS[specific_sensor_key] == WORKAROUND_IGNORE: _LOGGER.debug("Remotec ZXT-120 Zwave Thermostat, ignoring") return if not (value.node....
235
235
784
18
216
gwendalg/home-assistant
homeassistant/components/thermostat/zwave.py
Python
ZWaveThermostat
ZWaveThermostat
65
168
65
65
f2c4eb15a9ca7198e7d1993fecc61c3ac614ede3
bigcode/the-stack
train
649fd42dae7f5a67010bb19c
train
class
class Migration(migrations.Migration): dependencies = [ ('daiquiri_metadata', '0008_refactoring'), ] operations = [ migrations.RenameField( model_name='column', old_name='size', new_name='arraysize', ), ]
class Migration(migrations.Migration):
dependencies = [ ('daiquiri_metadata', '0008_refactoring'), ] operations = [ migrations.RenameField( model_name='column', old_name='size', new_name='arraysize', ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-07-25 11:02 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration):
50
64
60
7
42
agy-why/daiquiri
daiquiri/metadata/migrations/0009_arraysize.py
Python
Migration
Migration
8
20
8
9
a686e5f1b969bea6841662b8fe7906a732449be9
bigcode/the-stack
train
48cf5148a54853369b5769d4
train
function
def import_class(from_path, full_class_name): kclass = import_class_from_path(from_path, full_class_name) if kclass is None: our_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) api_dir = os.path.join(our_dir, PULSAR_API_ROOT, PULSAR_FUNCTIONS_API_ROOT) kclass = import_cla...
def import_class(from_path, full_class_name):
kclass = import_class_from_path(from_path, full_class_name) if kclass is None: our_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) api_dir = os.path.join(our_dir, PULSAR_API_ROOT, PULSAR_FUNCTIONS_API_ROOT) kclass = import_class_from_path(api_dir, full_class_name) retur...
: utf-8 -*- """util.py: Some misc utility functions """ import os import inspect import sys import log Log = log.Log PULSAR_API_ROOT = 'pulsar' PULSAR_FUNCTIONS_API_ROOT = 'functions' def import_class(from_path, full_class_name):
64
64
96
10
54
mgodave/incubator-pulsar
pulsar-functions/instance/src/main/python/util.py
Python
import_class
import_class
35
41
35
35
ba9423fd362b33ea608917fa01df9149bca83669
bigcode/the-stack
train
fb5bb94b3d930ee3fde359b0
train
function
def getFullyQualifiedFunctionName(tenant, namespace, name): return "%s/%s/%s" % (tenant, namespace, name)
def getFullyQualifiedFunctionName(tenant, namespace, name):
return "%s/%s/%s" % (tenant, namespace, name)
(mod, class_name) return retval except Exception as e: Log.info("Import failed class_name %s from path %s" % (class_name, from_path)) Log.info(e, exc_info=True) return None def getFullyQualifiedFunctionName(tenant, namespace, name):
64
64
30
13
50
mgodave/incubator-pulsar
pulsar-functions/instance/src/main/python/util.py
Python
getFullyQualifiedFunctionName
getFullyQualifiedFunctionName
69
70
69
69
61a718dca0a436beaf77ccf4b896dac9a18fa2b3
bigcode/the-stack
train
cde81d0774b480771a684bdc
train
function
def import_class_from_path(from_path, full_class_name): Log.info('Trying to import %s from path %s' % (full_class_name, from_path)) split = full_class_name.split('.') classname_path = '.'.join(split[:-1]) class_name = full_class_name.split('.')[-1] if from_path not in sys.path: Log.info("Add a new depende...
def import_class_from_path(from_path, full_class_name):
Log.info('Trying to import %s from path %s' % (full_class_name, from_path)) split = full_class_name.split('.') classname_path = '.'.join(split[:-1]) class_name = full_class_name.split('.')[-1] if from_path not in sys.path: Log.info("Add a new dependency to the path: %s" % from_path) sys.path.insert(0,...
our_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) api_dir = os.path.join(our_dir, PULSAR_API_ROOT, PULSAR_FUNCTIONS_API_ROOT) kclass = import_class_from_path(api_dir, full_class_name) return kclass def import_class_from_path(from_path, full_class_name):
75
75
253
12
62
mgodave/incubator-pulsar
pulsar-functions/instance/src/main/python/util.py
Python
import_class_from_path
import_class_from_path
43
67
43
43
910c61a48ba421684c58baf92a25b995aaa4f647
bigcode/the-stack
train
118adb5d5ba20509a1e417f3
train
function
def send_bug_mail(username, bugmessage): #admin_email_address = env.getenv('ADMIN_EMAIL_ADDRESS') nulladdr = ['\'\'', '\"\"', ''] email_from_address = settings.get('EMAIL_FROM_ADDRESS') admin_email_address = settings.get('ADMIN_EMAIL_ADDRESS') logger.info("receive bug from %s: %s" % (username, bugme...
def send_bug_mail(username, bugmessage): #admin_email_address = env.getenv('ADMIN_EMAIL_ADDRESS')
nulladdr = ['\'\'', '\"\"', ''] email_from_address = settings.get('EMAIL_FROM_ADDRESS') admin_email_address = settings.get('ADMIN_EMAIL_ADDRESS') logger.info("receive bug from %s: %s" % (username, bugmessage)) if (email_from_address in nulladdr or admin_email_address in nulladdr): return {'s...
from master.settings import settings import smtplib from utils.log import logger from utils import env from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header from datetime import datetime import json def send_bug_mail(username, bugmessage): #admin_email_a...
76
141
472
22
53
MrRobertYuan/docklet
src/master/bugreporter.py
Python
send_bug_mail
send_bug_mail
11
53
11
12
af5b0014cd762e401e67aba14ce7d7f27161a72d
bigcode/the-stack
train
2a26a7567a072c5ea9d862fb
train
function
def sugar_consumption (row): if 0 < row['meanSugarPerson'] <= 30 : return 0 # Desirable between 0 and 30 g. if 30 < row['meanSugarPerson'] <= 60 : return 1 # Raised between 30 and 60 g. if 60 < row['meanSugarPerson'] <= 90 : return 2 # Borderline high between 60 and 90 g. if 90 < row['meanSugarPe...
def sugar_consumption (row):
if 0 < row['meanSugarPerson'] <= 30 : return 0 # Desirable between 0 and 30 g. if 30 < row['meanSugarPerson'] <= 60 : return 1 # Raised between 30 and 60 g. if 60 < row['meanSugarPerson'] <= 90 : return 2 # Borderline high between 60 and 90 g. if 90 < row['meanSugarPerson'] <= 120 : return 3 # Hi...
, meanFoodPerson, meanCholesterol sub1=data[['breastCancer100th','meanSugarPerson', 'meanFoodPerson', 'meanCholesterol']] # Create the conditions to a new variable named sugar_consumption that will categorize the meanSugarPerson answers def sugar_consumption (row):
64
64
150
7
56
yan-duarte/yan-duarte.github.io
archives/assignment3.py
Python
sugar_consumption
sugar_consumption
20
25
20
20
ac811e8c1ebffeeda1ed4b405f9836f79f7f1ea0
bigcode/the-stack
train
ed3fb71d6529e67e8e946aab
train
function
def food_consumption (row): if row['meanFoodPerson'] <= food_mean : return 0 # Food consumption below the world average. if row['meanFoodPerson'] > food_mean : return 1 # Food consumption under the world average.
def food_consumption (row):
if row['meanFoodPerson'] <= food_mean : return 0 # Food consumption below the world average. if row['meanFoodPerson'] > food_mean : return 1 # Food consumption under the world average.
ption"].value_counts(sort=False,normalize=True) print(p1) #Make the average of meanFoodPerson values. food_mean = statistics.mean(data["meanFoodPerson"]) # Create the conditions to a new variable named food_consumption that will categorize the meanFoodPerson answers def food_consumption (row):
64
64
55
7
56
yan-duarte/yan-duarte.github.io
archives/assignment3.py
Python
food_consumption
food_consumption
44
46
44
44
40f50ef907cebccede09cf6d6ae68595c751ffca
bigcode/the-stack
train
d09e4d2c2d86cc7a3829dc84
train
function
def cholesterol_blood (row): if row['meanCholesterol'] <= 5.2 : return 0 # Desirable below 5.2 mmol/L if 5.2 < row['meanCholesterol'] <= 6.2 : return 1 # Borerline high between 5.2 and 6.2 mmol/L if row['meanCholesterol'] > 6.2 : return 2 # High above 6.2 mmol/L
def cholesterol_blood (row):
if row['meanCholesterol'] <= 5.2 : return 0 # Desirable below 5.2 mmol/L if 5.2 < row['meanCholesterol'] <= 6.2 : return 1 # Borerline high between 5.2 and 6.2 mmol/L if row['meanCholesterol'] > 6.2 : return 2 # High above 6.2 mmol/L
person & day) between 1961 and 2002") p2 = sub1["food_consumption"].value_counts(sort=False, normalize=True) print(p2) # Create the conditions to a new variable named cholesterol_blood that will categorize the meanCholesterol answers def cholesterol_blood (row):
64
64
108
7
56
yan-duarte/yan-duarte.github.io
archives/assignment3.py
Python
cholesterol_blood
cholesterol_blood
62
65
62
62
9df363a4bed3f8b2dca4f63b0eeefe7e8f7a750c
bigcode/the-stack
train
dcec2f89e4da0f7fc2679588
train
class
class Migration(migrations.Migration): dependencies = [ ('attachments', '0005_link'), ] operations = [ migrations.RemoveField( model_name='document', name='article', ), migrations.RemoveField( model_name='document', name='gran...
class Migration(migrations.Migration):
dependencies = [ ('attachments', '0005_link'), ] operations = [ migrations.RemoveField( model_name='document', name='article', ), migrations.RemoveField( model_name='document', name='grantee', ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-05-27 13:15 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration):
52
64
65
7
44
razortheory/who-iwg-webapp
iwg_blog/attachments/migrations/0006_auto_20160527_1315.py
Python
Migration
Migration
8
23
8
9
5df59ff76380349ec48eb9b6a3b3216f04b986f8
bigcode/the-stack
train
28b418dc964b6d3dbde7afd2
train
class
class ProteinFetcherHmdb(ProteinFetcher): def __init__(self, protein_id, extra_args={}, memory_storage=None): ProteinFetcher.__init__(self, protein_id=protein_id, memory_storage=memory_storage) self.db = 'hmdb' self.set_convergence_args(extra_args) self.protein = self.get_protein_HMD...
class ProteinFetcherHmdb(ProteinFetcher):
def __init__(self, protein_id, extra_args={}, memory_storage=None): ProteinFetcher.__init__(self, protein_id=protein_id, memory_storage=memory_storage) self.db = 'hmdb' self.set_convergence_args(extra_args) self.protein = self.get_protein_HMDB() self.add_protein() def se...
from unifuncnet.fetchers.protein_fetchers.protein_fetcher import * class ProteinFetcherHmdb(ProteinFetcher):
26
256
1,354
9
17
PedroMTQ/DRAX
unifuncnet/fetchers/protein_fetchers/protein_fetcher_hmdb.py
Python
ProteinFetcherHmdb
ProteinFetcherHmdb
4
141
4
4
dae340b5c9f5677b35ab029ffea919f548ad9bee
bigcode/the-stack
train
8371337ec3b7361969c507aa
train
class
class SplitRectsInBrickWall(AnimationGroup): def __init__(self, mobject, **kwargs): #print mobject.height, mobject.get_height() r = self.subdiv_level = mobject.subdiv_level + 1 subdivs = VGroup() x = -0.5 * mobject.get_width() anims = [] for k in range(0, ...
class SplitRectsInBrickWall(AnimationGroup):
def __init__(self, mobject, **kwargs): #print mobject.height, mobject.get_height() r = self.subdiv_level = mobject.subdiv_level + 1 subdivs = VGroup() x = -0.5 * mobject.get_width() anims = [] for k in range(0, r): proportion = float(choose(r,k)...
get_rect_widths_for_level(self, r): ret_arr = [] for k in range(0, r): proportion = float(choose(r,k)) / 2**r ret_arr.append(proportion * self.width) return ret_arr class SplitRectsInBrickWall(AnimationGroup):
64
64
191
9
54
srijan-deepsource/manim
from_3b1b/on_hold/eop/reusables/brick_row.py
Python
SplitRectsInBrickWall
SplitRectsInBrickWall
182
205
182
183
974d60ad550ed8c68d2dbf281f7d340ffd1ba3d9
bigcode/the-stack
train
6ff8c1402067158070490774
train
class
class BrickRow(VMobject): CONFIG = { "left_color" : COLOR_HEADS, "right_color" : COLOR_TAILS, "height" : 1.0, "width" : 8.0, "outcome_shrinkage_factor_x" : 0.95, "outcome_shrinkage_factor_y" : 0.94 } def __init__(self, n, **kwargs): self.subdiv_level...
class BrickRow(VMobject):
CONFIG = { "left_color" : COLOR_HEADS, "right_color" : COLOR_TAILS, "height" : 1.0, "width" : 8.0, "outcome_shrinkage_factor_x" : 0.95, "outcome_shrinkage_factor_y" : 0.94 } def __init__(self, n, **kwargs): self.subdiv_level = n self.coloring_...
from manimlib.imports import * from active_projects.eop.reusables.eop_helpers import * from active_projects.eop.reusables.eop_constants import * from active_projects.eop.reusables.upright_coins import * class BrickRow(VMobject):
56
256
1,324
7
49
srijan-deepsource/manim
from_3b1b/on_hold/eop/reusables/brick_row.py
Python
BrickRow
BrickRow
6
177
6
7
22b2de4dd2a71835b30f6b1aab4b4682411dea7f
bigcode/the-stack
train
f342d26b8e2f1d8ce8090e72
train
class
class StringFormatter(logging.Formatter): """ StringFormatter simply returns a formatted string of a log record. """ def __init__(self): super().__init__() self.datefmt = '%Y-%m-%dT%H:%M:%S' def format(self, record: logging.LogRecord) -> str: """Return formatted string of l...
class StringFormatter(logging.Formatter):
""" StringFormatter simply returns a formatted string of a log record. """ def __init__(self): super().__init__() self.datefmt = '%Y-%m-%dT%H:%M:%S' def format(self, record: logging.LogRecord) -> str: """Return formatted string of log record. Args: reco...
deque. """ return self._deque.popleft() def to_string(self) -> str: """Returns the whole deque as a string. Returns: String containing all string elements in the deque. """ return '\n'.join(list(self._deque)) class StringFormatter(logging.Formatter):
64
64
185
7
57
geomatikzh/openadms-node
core/logging.py
Python
StringFormatter
StringFormatter
78
111
78
78
5b2dfaa8c5733fcac865f7edec0c0263ea80c811
bigcode/the-stack
train
7780a2f64724fd0c3b0e518b
train
class
class RingBufferLogHandler(logging.Handler): """ RingBufferLogHandler stores a number of log messages in a `RingBuffer`. """ def __init__(self, level: int, size: int): """ Args: level: The log level. size: The size of the `RingBuffer`. """ super()...
class RingBufferLogHandler(logging.Handler):
""" RingBufferLogHandler stores a number of log messages in a `RingBuffer`. """ def __init__(self, level: int, size: int): """ Args: level: The log level. size: The size of the `RingBuffer`. """ super().__init__(level) self._size = size ...
.datefmt) try: record.message except AttributeError: record.message = record.msg s = '{} - {:>8} - {:>26} - {}'.format(record.asctime, record.levelname, record.name, ...
68
68
228
8
59
geomatikzh/openadms-node
core/logging.py
Python
RingBufferLogHandler
RingBufferLogHandler
114
154
114
114
3920eb0546760831093194060974da1bfa793a74
bigcode/the-stack
train
385b30f00589cb6bb7b4ceca
train
class
class RingBuffer: """ RingBuffer stores elements in a deque. It is a FIFO list with fixed size to cache a number of elements, like log messages. The oldest elements get removed when the number of elements is greater than the maximum length. """ def __init__(self, max_length: int): """ ...
class RingBuffer:
""" RingBuffer stores elements in a deque. It is a FIFO list with fixed size to cache a number of elements, like log messages. The oldest elements get removed when the number of elements is greater than the maximum length. """ def __init__(self, max_length: int): """ Args: ...
Python modules. """ def filter(self, record: logging.LogRecord) -> bool: """Returns whether a logging.LogRecord should be logged.""" if record.name.startswith(('asyncio', 'hbmqtt', 'passlib', ...
75
75
251
4
70
geomatikzh/openadms-node
core/logging.py
Python
RingBuffer
RingBuffer
33
75
33
33
278783d709f57b7bfe827f1d14e7f3518ee0978d
bigcode/the-stack
train
c307093320cc1a058c867699
train
class
class RootFilter(logging.Filter): """ RootFilter is a helper class to filter unwanted log messages from external Python modules. """ def filter(self, record: logging.LogRecord) -> bool: """Returns whether a logging.LogRecord should be logged.""" if record.name.startswith(('asyncio',...
class RootFilter(logging.Filter):
""" RootFilter is a helper class to filter unwanted log messages from external Python modules. """ def filter(self, record: logging.LogRecord) -> bool: """Returns whether a logging.LogRecord should be logged.""" if record.name.startswith(('asyncio', ...
, formatters, and handlers for logging.""" __author__ = 'Philipp Engel' __copyright__ = 'Copyright (c) 2017 Hochschule Neubrandenburg' __license__ = 'BSD-2-Clause' import logging from collections import deque from typing import Any class RootFilter(logging.Filter):
64
64
93
6
57
geomatikzh/openadms-node
core/logging.py
Python
RootFilter
RootFilter
15
30
15
15
be9aef4db3dfef6625f0faa54452e7d49ec220f2
bigcode/the-stack
train
10e75060a70969917e5e8ba5
train
class
class Queue(object): __lock = threading.Lock() __items = dict({}) __queue = [] __current = None def __init__(self): pass @property def current(self): mrl = backend = None with self.__lock: resource_id = self.__current if resource_id is not None: ...
class Queue(object):
__lock = threading.Lock() __items = dict({}) __queue = [] __current = None def __init__(self): pass @property def current(self): mrl = backend = None with self.__lock: resource_id = self.__current if resource_id is not None: mrl = s...
import threading class Queue(object):
7
109
365
4
2
strangedev/tinnitus
tinnitus/queue.py
Python
Queue
Queue
4
64
4
5
3e799f94b27c6745af7ba7f0099391afb470bf8c
bigcode/the-stack
train