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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b3df01458b1234255ab7578b | train | function | def get_pg(cloud_name: Optional[str] = None,
components: Optional[Sequence[pulumi.InputType['GetPgComponentArgs']]] = None,
maintenance_window_dow: Optional[str] = None,
maintenance_window_time: Optional[str] = None,
pg: Optional[pulumi.InputType['GetPgPgArgs']] = None,
... | def get_pg(cloud_name: Optional[str] = None,
components: Optional[Sequence[pulumi.InputType['GetPgComponentArgs']]] = None,
maintenance_window_dow: Optional[str] = None,
maintenance_window_time: Optional[str] = None,
pg: Optional[pulumi.InputType['GetPgPgArgs']] = None,
... | """
## # PG Data Source
The PG data source provides information about the existing Aiven PostgreSQL service.
## Example Usage
```python
import pulumi
import pulumi_aiven as aiven
pg = aiven.get_pg(project=data["aiven_project"]["pr1"]["project"],
service_name="my-pg1")
```... | def get_pg(cloud_name: Optional[str] = None,
components: Optional[Sequence[pulumi.InputType['GetPgComponentArgs']]] = None,
maintenance_window_dow: Optional[str] = None,
maintenance_window_time: Optional[str] = None,
pg: Optional[pulumi.InputType['GetPgPgArgs']] = None,
... | 262 | 256 | 1,671 | 262 | 0 | pulumi/pulumi-aiven | sdk/python/pulumi_aiven/get_pg.py | Python | get_pg | get_pg | 284 | 411 | 284 | 303 | 79d6a4c107d4245db9d86022c2a8f4968ff3f6aa | bigcode/the-stack | train |
ce592f41bc9c1e5b8b57dfb5 | train | class | @pulumi.output_type
class GetPgResult:
"""
A collection of values returned by getPg.
"""
def __init__(__self__, cloud_name=None, components=None, id=None, maintenance_window_dow=None, maintenance_window_time=None, pg=None, pg_user_config=None, plan=None, project=None, project_vpc_id=None, service_host=N... | @pulumi.output_type
class GetPgResult:
| """
A collection of values returned by getPg.
"""
def __init__(__self__, cloud_name=None, components=None, id=None, maintenance_window_dow=None, maintenance_window_time=None, pg=None, pg_user_config=None, plan=None, project=None, project_vpc_id=None, service_host=None, service_integrations=None, service... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... | 126 | 256 | 2,367 | 11 | 115 | pulumi/pulumi-aiven | sdk/python/pulumi_aiven/get_pg.py | Python | GetPgResult | GetPgResult | 19 | 253 | 19 | 20 | c3f7d5dcd4213482c9234a88581238d556f25c47 | bigcode/the-stack | train |
57e3b3ec68c79a8a7d32a2a5 | train | class | class _TypeDBTransactionExtended(TypeDBTransaction, ABC):
@abstractmethod
def execute(self, request: transaction_proto.Transaction.Req) -> transaction_proto.Transaction.Res:
pass
@abstractmethod
def run_query(self, request: transaction_proto.Transaction.Req) -> QueryFuture[transaction_proto.Tr... | class _TypeDBTransactionExtended(TypeDBTransaction, ABC):
@abstractmethod
| def execute(self, request: transaction_proto.Transaction.Req) -> transaction_proto.Transaction.Res:
pass
@abstractmethod
def run_query(self, request: transaction_proto.Transaction.Req) -> QueryFuture[transaction_proto.Transaction.Res]:
pass
@abstractmethod
def stream(self, request:... | (self) -> None:
pass
@abstractmethod
def __enter__(self):
pass
@abstractmethod
def __exit__(self, exc_type, exc_val, exc_tb):
pass
class _TypeDBTransactionExtended(TypeDBTransaction, ABC):
@abstractmethod
| 64 | 64 | 100 | 17 | 46 | rpatil524/client-python | typedb/api/connection/transaction.py | Python | _TypeDBTransactionExtended | _TypeDBTransactionExtended | 96 | 108 | 96 | 98 | f862c27af0f886f75c97a70e3350b2396820b49d | bigcode/the-stack | train |
be9a2f83e56bfaed50cac184 | train | class | class TransactionType(enum.Enum):
READ = 0
WRITE = 1
def is_read(self):
return self is TransactionType.READ
def is_write(self):
return self is TransactionType.WRITE
def proto(self):
return transaction_proto.Transaction.Type.Value(self.name)
| class TransactionType(enum.Enum):
| READ = 0
WRITE = 1
def is_read(self):
return self is TransactionType.READ
def is_write(self):
return self is TransactionType.WRITE
def proto(self):
return transaction_proto.Transaction.Type.Value(self.name)
| _proto
from typedb.api.concept.concept_manager import ConceptManager
from typedb.api.logic.logic_manager import LogicManager
from typedb.api.connection.options import TypeDBOptions
from typedb.api.query.future import QueryFuture
from typedb.api.query.query_manager import QueryManager
class TransactionType(enum.Enum):
| 64 | 64 | 61 | 6 | 57 | rpatil524/client-python | typedb/api/connection/transaction.py | Python | TransactionType | TransactionType | 35 | 46 | 35 | 35 | 8825d3f81d8dbe13510b02e09435abb2ad798c62 | bigcode/the-stack | train |
d9ae50f86ed5f3b7c2cb33f7 | train | class | class TypeDBTransaction(ABC):
@abstractmethod
def is_open(self) -> bool:
pass
@abstractmethod
def transaction_type(self) -> TransactionType:
pass
@abstractmethod
def options(self) -> TypeDBOptions:
pass
@abstractmethod
def concepts(self) -> ConceptManager:
... | class TypeDBTransaction(ABC):
@abstractmethod
| def is_open(self) -> bool:
pass
@abstractmethod
def transaction_type(self) -> TransactionType:
pass
@abstractmethod
def options(self) -> TypeDBOptions:
pass
@abstractmethod
def concepts(self) -> ConceptManager:
pass
@abstractmethod
def logic(self) ... | 0
WRITE = 1
def is_read(self):
return self is TransactionType.READ
def is_write(self):
return self is TransactionType.WRITE
def proto(self):
return transaction_proto.Transaction.Type.Value(self.name)
class TypeDBTransaction(ABC):
@abstractmethod
| 64 | 64 | 198 | 12 | 52 | rpatil524/client-python | typedb/api/connection/transaction.py | Python | TypeDBTransaction | TypeDBTransaction | 49 | 93 | 49 | 51 | 83bedf23e9b5d43f5a37cea86f4d9cea8a838340 | bigcode/the-stack | train |
09b5e0adcf335f96c170ea23 | train | function | def edge(city, **place):
print(f"Край: {city}")
for place, name in place.items():
sorted(place)
print(f"{place}: {name}")
| def edge(city, **place):
| print(f"Край: {city}")
for place, name in place.items():
sorted(place)
print(f"{place}: {name}")
| # !/usr/bin/env python3
# -*- coding: utf-8 -*-
def edge(city, **place):
| 24 | 64 | 39 | 7 | 17 | LazarevaDarya/work13 | PyCharm/zad3.py | Python | edge | edge | 5 | 9 | 5 | 5 | 91dd70553ed850c3c64845a6bd7c7215fa39ade6 | bigcode/the-stack | train |
cffd976d9f065359a9b53614 | train | class | class TridiagonalMulOpTest(test.TestCase):
def _testAllFormats(self,
superdiag,
maindiag,
subdiag,
rhs,
expected,
dtype=dtypes.float64):
superdiag_extended = np.pad(superdiag, [0, 1... | class TridiagonalMulOpTest(test.TestCase):
| def _testAllFormats(self,
superdiag,
maindiag,
subdiag,
rhs,
expected,
dtype=dtypes.float64):
superdiag_extended = np.pad(superdiag, [0, 1], 'constant')
subdiag_extended = np.pad... | you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES ... | 256 | 256 | 2,334 | 11 | 244 | PaulWang1905/tensorflow | tensorflow/python/kernel_tests/tridiagonal_matmul_op_test.py | Python | TridiagonalMulOpTest | TridiagonalMulOpTest | 38 | 242 | 38 | 39 | 0f60aa97c4dc76b3ed6783e563afe91397935b92 | bigcode/the-stack | train |
cd62e005fd018cd6eef676f6 | train | function | def determine_speedup(muxProb, NB, Nds, patCount):
'''
runs the simulation for a multiplexing probability of
mux_prob, Nds multiplexed data streams with a pattern count
of pat_count.
'''
# Generate single data streams
dsVec = []
dsProbVec = []
for j in range(Nds):
dsType = ra... | def determine_speedup(muxProb, NB, Nds, patCount):
| '''
runs the simulation for a multiplexing probability of
mux_prob, Nds multiplexed data streams with a pattern count
of pat_count.
'''
# Generate single data streams
dsVec = []
dsProbVec = []
for j in range(Nds):
dsType = random.randint(1, 3)
if dsType == 1:
... | #!/usr/bin/python3
'''
This script is used to evaluate how fast our high-level
approach is compared to a bit-level approach
'''
from interconnect import data
import random
import timeit
import numpy as np
def determine_speedup(muxProb, NB, Nds, patCount):
| 64 | 150 | 501 | 16 | 47 | Joern-Noeller/ratatoskr | power/src/sim_res/evaluate_speedup.py | Python | determine_speedup | determine_speedup | 12 | 58 | 12 | 12 | a561a3f865d7154dab89fe5d7bead087b4e921bf | bigcode/the-stack | train |
9b9ea9bf481a288ba49efc04 | train | class | class CardinalFst(GraphFst):
"""
Finite state transducer for verbalizing cardinal
e.g. tokens { cardinal { integer: "23" negative: "-" } } -> -23
"""
def __init__(self):
super().__init__(name="cardinal", kind="verbalize")
optional_sign = pynini.closure(
pynutil.delet... | class CardinalFst(GraphFst):
| """
Finite state transducer for verbalizing cardinal
e.g. tokens { cardinal { integer: "23" negative: "-" } } -> -23
"""
def __init__(self):
super().__init__(name="cardinal", kind="verbalize")
optional_sign = pynini.closure(
pynutil.delete("negative:")
+ ... | NEMO_NOT_QUOTE, GraphFst, delete_space
try:
import pynini
from pynini.lib import pynutil
PYNINI_AVAILABLE = True
except (ModuleNotFoundError, ImportError):
PYNINI_AVAILABLE = False
class CardinalFst(GraphFst):
| 64 | 64 | 208 | 8 | 55 | yashiagar1999/indict_punc | src/inverse_text_normalization/asm/verbalizers/cardinal.py | Python | CardinalFst | CardinalFst | 27 | 55 | 27 | 27 | ce9d454e9d16c50317ae857711467f4d22b90820 | bigcode/the-stack | train |
dfcd22b806ee75525028f0cf | train | class | class MagentaTest(test_util.TFLiteModelTest):
def __init__(self, *args, **kwargs):
super(MagentaTest, self).__init__(model_path, *args, **kwargs)
def compare_results(self, iree_results, tflite_results, details):
super(MagentaTest, self).compare_results(iree_results, tflite_results, details)
self.assert... | class MagentaTest(test_util.TFLiteModelTest):
| def __init__(self, *args, **kwargs):
super(MagentaTest, self).__init__(model_path, *args, **kwargs)
def compare_results(self, iree_results, tflite_results, details):
super(MagentaTest, self).compare_results(iree_results, tflite_results, details)
self.assertTrue(numpy.isclose(iree_results[0], tflite_res... | import absl.testing
import numpy
import test_util
model_path = "https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/prediction/1?lite-format=tflite"
class MagentaTest(test_util.TFLiteModelTest):
| 64 | 64 | 131 | 12 | 52 | not-jenni/iree-samples | tflitehub/magenta_test.py | Python | MagentaTest | MagentaTest | 9 | 18 | 9 | 9 | 42cc3db64ace2e36f7b207d4f710f11e045718f1 | bigcode/the-stack | train |
70698f0d33e6e140a78b4b3f | train | function | @app.callback(
Output('fullReport', 'children'),
[Input('submit-button', 'n_clicks')],
[State('hash-box', 'value')],
)
def render_report(n_clicks, hash_value):
if hash_value == None:
return [html.Div([
html.Div([
html.Div([
dcc.... | @app.callback(
Output('fullReport', 'children'),
[Input('submit-button', 'n_clicks')],
[State('hash-box', 'value')],
)
def render_report(n_clicks, hash_value):
| if hash_value == None:
return [html.Div([
html.Div([
html.Div([
dcc.Input(id='hash-box', type='text', className="form no-print", style={'position': "absolute", 'top': '-38.3', 'width':'50%', 'right': '50%'}),
], className = "six cloumns"),
... | ': '50%'}),
], className = "six cloumns"),
html.Div([
html.Button('Submit', className="btn btn-primary btn-sm no-print", id='submit-button', style={'position': "absolute", 'top': '-38.3', 'right': '30%'}),
], className = "three columns"),
html.Div(... | 159 | 159 | 532 | 46 | 113 | MenheraMikumo/Mnemosyne | Reporter/dash_deploy.py | Python | render_report | render_report | 34 | 87 | 34 | 39 | 5c5e91573f8ad1f8e365426f7c2d4d43a10b47c4 | bigcode/the-stack | train |
fd63f17e41ade37929f38ce2 | train | function | def main():
""" Main method """
window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
window.setup()
arcade.run()
| def main():
| """ Main method """
window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
window.setup()
arcade.run()
| , modifiers):
"""Called when the user releases a key. """
if key == arcade.key.UP or key == arcade.key.DOWN:
self.player_sprite.speed = 0
elif key == arcade.key.LEFT or key == arcade.key.RIGHT:
self.player_sprite.change_angle = 0
def main():
| 64 | 64 | 31 | 3 | 60 | KommentatorForAll/arcade | arcade/examples/sprite_move_angle.py | Python | main | main | 132 | 136 | 132 | 132 | cdfd052198447cecfcf03578877a94f0b69ba5b3 | bigcode/the-stack | train |
0198d863db192ade84f38d2b | train | class | class Player(arcade.Sprite):
""" Player class """
def __init__(self, image, scale):
""" Set up the player """
# Call the parent init
super().__init__(image, scale)
# Create a variable to hold our speed. 'angle' is created by the parent
self.speed = 0
def update(se... | class Player(arcade.Sprite):
| """ Player class """
def __init__(self, image, scale):
""" Set up the player """
# Call the parent init
super().__init__(image, scale)
# Create a variable to hold our speed. 'angle' is created by the parent
self.speed = 0
def update(self):
# Convert angle ... |
"""
import arcade
import os
import math
SPRITE_SCALING = 0.5
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "Move Sprite by Angle Example"
MOVEMENT_SPEED = 5
ANGLE_SPEED = 5
class Player(arcade.Sprite):
| 64 | 64 | 152 | 7 | 56 | KommentatorForAll/arcade | arcade/examples/sprite_move_angle.py | Python | Player | Player | 25 | 46 | 25 | 25 | 4b9b0b11de96193bffa6e29675f92b017823bf38 | bigcode/the-stack | train |
55abb66ce99b1fefd4c834d1 | train | class | class MyGame(arcade.Window):
"""
Main application class.
"""
def __init__(self, width, height, title):
"""
Initializer
"""
# Call the parent class initializer
super().__init__(width, height, title)
# Set the working directory (where we expect to find fi... | class MyGame(arcade.Window):
| """
Main application class.
"""
def __init__(self, width, height, title):
"""
Initializer
"""
# Call the parent class initializer
super().__init__(width, height, title)
# Set the working directory (where we expect to find files) to the same
# di... | ANGLE_SPEED = 5
class Player(arcade.Sprite):
""" Player class """
def __init__(self, image, scale):
""" Set up the player """
# Call the parent init
super().__init__(image, scale)
# Create a variable to hold our speed. 'angle' is created by the parent
self.speed = 0
... | 166 | 166 | 556 | 8 | 158 | KommentatorForAll/arcade | arcade/examples/sprite_move_angle.py | Python | MyGame | MyGame | 49 | 129 | 49 | 49 | 2b4d14a1f0e7f18a48555b44db4bde6792024527 | bigcode/the-stack | train |
3c4c4c2d7a9b9f044e488249 | train | class | class latoken(Exchange):
def describe(self):
return self.deep_extend(super(latoken, self).describe(), {
'id': 'latoken',
'name': 'Latoken',
'countries': ['KY'], # Cayman Islands
'version': 'v1',
'rateLimit': 2000,
'certified': False,
... | class latoken(Exchange):
| def describe(self):
return self.deep_extend(super(latoken, self).describe(), {
'id': 'latoken',
'name': 'Latoken',
'countries': ['KY'], # Cayman Islands
'version': 'v1',
'rateLimit': 2000,
'certified': False,
'userAgent': s... | # -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import A... | 158 | 256 | 6,910 | 6 | 151 | seanjsong/ccxt | python/ccxt/async_support/latoken.py | Python | latoken | latoken | 19 | 829 | 19 | 20 | 2fc6a61ac5439dea02f8374d515a5be87c0d1b8d | bigcode/the-stack | train |
6746f31bcf81c2050ab4f695 | train | function | def MakeNofz_fits(input_files,outputfileName,OneBin_nofzFileName,neff=[],single_bin=True,type='lowerEdge',suffix='SAMPLE'):
nBins=len(input_files)
print('I got '+str(nBins)+' files from input. Type is set to '+type)
cols=[]
for bin1 in range(nBins):
file= open(input_files[bin1])
nofZ=np.loadtxt(file,comments='#... | def MakeNofz_fits(input_files,outputfileName,OneBin_nofzFileName,neff=[],single_bin=True,type='lowerEdge',suffix='SAMPLE'):
| nBins=len(input_files)
print('I got '+str(nBins)+' files from input. Type is set to '+type)
cols=[]
for bin1 in range(nBins):
file= open(input_files[bin1])
nofZ=np.loadtxt(file,comments='#')
if(bin1==0):
if(single_bin):
z_vec=nofZ[:,1]*neff[bin1]
DeltaZ=nofZ[1,0]-nofZ[0,0]
if(type=='lowerEdge'):
... | value for the lower end of each redshift histogram bin
#Z_MID 8-byte real // Real, the z value for a middle point of each redshift histogram bin
#Z_HIGH 8-byte real // Real, the z value for the upper end of each redshift histogram bin
#BIN1 8-byte real // Real, the n(z) value for this histogram bin for the fi... | 248 | 249 | 830 | 38 | 210 | KiDS-WL/Cat_to_Obs_K1000_P1 | data/kids/nofz/MakeNofZForCosmosis_function.py | Python | MakeNofz_fits | MakeNofz_fits | 29 | 94 | 29 | 29 | 95aab1f72b73352d6b4bf8d7d561cfaac090c02f | bigcode/the-stack | train |
eb51074a1c255ba2dfbd8f2e | train | function | def wrap( x ):
return run( *x )
| def wrap( x ):
| return run( *x )
| -q -r bilinear -overwrite -t_srs EPSG:3338 -tr 1000 1000 -srcnodata -9999 -dstnodata -9999 -co COMPRESS=LZW {} {}'.format( fn, out_fn ) )
return out_fn
def wrap( x ):
| 64 | 64 | 11 | 5 | 58 | ua-snap/downscale | snap_scripts/old_scripts/tem_iem_older_scripts_april2018/tem_inputs_v2/resample_to_1km.py | Python | wrap | wrap | 14 | 15 | 14 | 14 | dacd9a60f567686dd549f9385feec2872d662238 | bigcode/the-stack | train |
da018572ffe97d152458ab46 | train | function | def run( fn, out_fn ):
import os
dirname = os.path.dirname( out_fn )
try:
if not os.path.exists( dirname ):
os.makedirs( dirname )
except:
pass
os.system( 'gdalwarp -q -r bilinear -overwrite -t_srs EPSG:3338 -tr 1000 1000 -srcnodata -9999 -dstnodata -9999 -co COMPRESS=LZW {} {}'.format( fn, out_fn ) )
ret... | def run( fn, out_fn ):
| import os
dirname = os.path.dirname( out_fn )
try:
if not os.path.exists( dirname ):
os.makedirs( dirname )
except:
pass
os.system( 'gdalwarp -q -r bilinear -overwrite -t_srs EPSG:3338 -tr 1000 1000 -srcnodata -9999 -dstnodata -9999 -co COMPRESS=LZW {} {}'.format( fn, out_fn ) )
return out_fn
| # resample to 1km
def run( fn, out_fn ):
| 16 | 64 | 109 | 8 | 7 | ua-snap/downscale | snap_scripts/old_scripts/tem_iem_older_scripts_april2018/tem_inputs_v2/resample_to_1km.py | Python | run | run | 2 | 12 | 2 | 2 | d975f87fd890b59c4b6fbb47476ddfd05607b5cf | bigcode/the-stack | train |
01fe74e47a761cc0d6560355 | train | class | class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="color", parent_name="ohlc.hoverlabel.font", **kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.... | class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
| def __init__(
self, plotly_name="color", parent_name="ohlc.hoverlabel.font", **kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop("array_ok", True),
edit_type=kwargs.pop("edit_type"... | import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
| 20 | 64 | 96 | 12 | 7 | andresgreen-byte/Laboratorio-1--Inversion-de-Capital | env/Lib/site-packages/plotly/validators/ohlc/hoverlabel/font/_color.py | Python | ColorValidator | ColorValidator | 4 | 14 | 4 | 4 | 6074cc9d3ec22e77b86aef240228a28c5fe4d28f | bigcode/the-stack | train |
0a80ef6c0bff8a49ccf25ec3 | train | function | def warningregistry(func):
def wrapper(*args, **kws):
missing = []
saved = getattr(warnings, '__warningregistry__', missing).copy()
try:
return func(*args, **kws)
finally:
if saved is missing:
try:
del warnings.__warningregi... | def warningregistry(func):
| def wrapper(*args, **kws):
missing = []
saved = getattr(warnings, '__warningregistry__', missing).copy()
try:
return func(*args, **kws)
finally:
if saved is missing:
try:
del warnings.__warningregistry__
exce... | import functools
import sys
import types
import warnings
import unittest
# Decorator used in the deprecation tests to reset the warning registry for
# test isolation and reproducibility.
def warningregistry(func):
| 43 | 64 | 91 | 5 | 38 | finefoot/cpython | Lib/unittest/test/test_loader.py | Python | warningregistry | warningregistry | 10 | 24 | 10 | 10 | 46bc07a78980e377a11dd4cd88be11778547c3d0 | bigcode/the-stack | train |
a0e598dabd3a52683d3336c9 | train | class | class Test_TestLoader(unittest.TestCase):
### Basic object tests
################################################################
def test___init__(self):
loader = unittest.TestLoader()
self.assertEqual([], loader.errors)
### Tests for TestLoader.loadTestsFromTestCase
############... | class Test_TestLoader(unittest.TestCase):
### Basic object tests
################################################################
| def test___init__(self):
loader = unittest.TestLoader()
self.assertEqual([], loader.errors)
### Tests for TestLoader.loadTestsFromTestCase
################################################################
# "Return a suite of all test cases contained in the TestCase-derived
# class ... | import functools
import sys
import types
import warnings
import unittest
# Decorator used in the deprecation tests to reset the warning registry for
# test isolation and reproducibility.
def warningregistry(func):
def wrapper(*args, **kws):
missing = []
saved = getattr(warnings, '__warningregistry... | 146 | 256 | 13,987 | 17 | 128 | finefoot/cpython | Lib/unittest/test/test_loader.py | Python | Test_TestLoader | Test_TestLoader | 27 | 1,591 | 27 | 31 | a7ac5960a72436f6395a9fa6854b55070a4f7442 | bigcode/the-stack | train |
a72cd0d07f210e4454b20b2f | train | class | class TestObsoleteFunctions(unittest.TestCase):
class MyTestSuite(unittest.TestSuite):
pass
class MyTestCase(unittest.TestCase):
def check_1(self): pass
def check_2(self): pass
def test(self): pass
@staticmethod
def reverse_three_way_cmp(a, b):
return unittest.u... | class TestObsoleteFunctions(unittest.TestCase):
| class MyTestSuite(unittest.TestSuite):
pass
class MyTestCase(unittest.TestCase):
def check_1(self): pass
def check_2(self): pass
def test(self): pass
@staticmethod
def reverse_three_way_cmp(a, b):
return unittest.util.three_way_cmp(b, a)
def test_getTestCas... | tests)
# "The default value is the TestSuite class"
def test_suiteClass__default_value(self):
loader = unittest.TestLoader()
self.assertIs(loader.suiteClass, unittest.TestSuite)
def test_partial_functions(self):
def noop(arg):
pass
class Foo(unittest.TestCase... | 124 | 124 | 414 | 9 | 115 | finefoot/cpython | Lib/unittest/test/test_loader.py | Python | TestObsoleteFunctions | TestObsoleteFunctions | 1,594 | 1,638 | 1,594 | 1,594 | ffe4e5ecedea2fc82dad4ae386141e6764cdd5e0 | bigcode/the-stack | train |
9b0f2c42c715d70a6e80170c | train | class | class Series(base.IndexOpsMixin, generic.NDFrame):
"""
One-dimensional ndarray with axis labels (including time series).
Labels need not be unique but must be a hashable type. The object
supports both integer- and label-based indexing and provides a host of
methods for performing operations involvi... | class Series(base.IndexOpsMixin, generic.NDFrame):
| """
One-dimensional ndarray with axis labels (including time series).
Labels need not be unique but must be a hashable type. The object
supports both integer- and label-based indexing and provides a host of
methods for performing operations involving the index. Statistical
methods from ndarray ... | import pandas.plotting
if TYPE_CHECKING:
from pandas.core.frame import DataFrame
from pandas.core.groupby.generic import SeriesGroupBy
__all__ = ["Series"]
_shared_doc_kwargs = dict(
axes="index",
klass="Series",
axes_single_arg="{0 or 'index'}",
axis="""axis : {0 or 'index'}
Paramete... | 256 | 256 | 31,744 | 12 | 243 | dannyhyunkim/pandas | pandas/core/series.py | Python | Series | Series | 140 | 4,577 | 140 | 140 | 817c041d315e5ae954b08af75554c1ee43215d91 | bigcode/the-stack | train |
a70a87f34016e9249f36d205 | train | function | def _coerce_method(converter):
"""
Install the scalar coercion methods.
"""
def wrapper(self):
if len(self) == 1:
return converter(self.iloc[0])
raise TypeError(f"cannot convert the series to {converter}")
wrapper.__name__ = f"__{converter.__name__}__"
return wrappe... | def _coerce_method(converter):
| """
Install the scalar coercion methods.
"""
def wrapper(self):
if len(self) == 1:
return converter(self.iloc[0])
raise TypeError(f"cannot convert the series to {converter}")
wrapper.__name__ = f"__{converter.__name__}__"
return wrapper
| returns None.""",
unique="np.ndarray",
duplicated="Series",
optional_by="",
optional_mapper="",
optional_labels="",
optional_axis="",
versionadded_to_excel="\n .. versionadded:: 0.20.0\n",
)
def _coerce_method(converter):
| 64 | 64 | 77 | 8 | 56 | dannyhyunkim/pandas | pandas/core/series.py | Python | _coerce_method | _coerce_method | 122 | 133 | 122 | 122 | 0e60574191fb0e15e1a25159b51a7721ffeb4dfc | bigcode/the-stack | train |
5921f2274e51635094f2f78e | train | class | class TestIntegration:
"""Test that the program loader integrates properly with PennyLane."""
def test_load_program_via_entry_point(self):
"""Test that a pyquil Program instance can be loaded via the load entrypoint."""
program = pyquil.Program()
program += g.H(0)
program += g.... | class TestIntegration:
| """Test that the program loader integrates properly with PennyLane."""
def test_load_program_via_entry_point(self):
"""Test that a pyquil Program instance can be loaded via the load entrypoint."""
program = pyquil.Program()
program += g.H(0)
program += g.RZ(0.34, 1)
pro... | , 3, 7]
def test_str(self):
"""Test that the string representation of ProgramLoader is correct."""
quil_str = textwrap.dedent(
"""
DECLARE alpha REAL[1]
DECLARE beta REAL[1]
DECLARE gamma REAL[1]
DEFGATE SQRT-X:
0.5+0.5i, 0... | 256 | 256 | 2,146 | 4 | 252 | thisac/pennylane-forest | tests/test_converter.py | Python | TestIntegration | TestIntegration | 1,033 | 1,266 | 1,033 | 1,033 | cbcca89f76dca7a527980c9cad3b1f72315d02b1 | bigcode/the-stack | train |
4d4436c83bfe9dd218afc813 | train | class | class TestQuilConverter:
"""Test that quil instances passed as string are properly converted."""
def test_convert_simple_program(self):
"""Test that a simple program is properly converted."""
quil_str = textwrap.dedent(
"""
H 0
RZ(0.34) 1
CNOT 0 3... | class TestQuilConverter:
| """Test that quil instances passed as string are properly converted."""
def test_convert_simple_program(self):
"""Test that a simple program is properly converted."""
quil_str = textwrap.dedent(
"""
H 0
RZ(0.34) 1
CNOT 0 3
H 2
... | expected_queue = [
qml.CNOT(wires=[0, 1]),
qml.QubitUnitary(expected_controlled_matrix, wires=[2, 0, 1]),
qml.QubitUnitary(expected_controlled_matrix, wires=[0, 1, 2]),
qml.CNOT(wires=[0, 1]),
]
for converted, expected in zip(rec.queue, expected_queue):
... | 256 | 256 | 2,238 | 6 | 250 | thisac/pennylane-forest | tests/test_converter.py | Python | TestQuilConverter | TestQuilConverter | 646 | 921 | 646 | 646 | 033a4c93288c2552c9033349199ae080146c4861 | bigcode/the-stack | train |
ae48438a90adf16ef98f83d7 | train | class | class TestQuilFileConverter:
"""Test that quil files are properly converted."""
def test_convert_simple_program(self):
"""Test that a simple program in a quil file is properly converted."""
cur_dir = os.path.dirname(os.path.abspath(__file__))
with OperationRecorder() as rec:
... | class TestQuilFileConverter:
| """Test that quil files are properly converted."""
def test_convert_simple_program(self):
"""Test that a simple program in a quil file is properly converted."""
cur_dir = os.path.dirname(os.path.abspath(__file__))
with OperationRecorder() as rec:
load_quil_from_file(os.path... | qml.Hadamard(1),
qml.QubitUnitary(c_sqrt_x, wires=[0, 1]),
]
for converted, expected in zip(rec.queue, expected_queue):
assert converted.name == expected.name
assert converted.wires == expected.wires
assert np.array_equal(converted.params, expected.param... | 79 | 79 | 265 | 7 | 72 | thisac/pennylane-forest | tests/test_converter.py | Python | TestQuilFileConverter | TestQuilFileConverter | 924 | 952 | 924 | 924 | 578b88b0839a076c2fc4d8f543f92aacb274e582 | bigcode/the-stack | train |
37a2244f747cc45595786da7 | train | class | class TestInspectionProperties:
"""Test that the inspection properties of ProgramLoader return the expected values."""
def test_inspection(self):
"""Test the combined inspection properties."""
quil_str = textwrap.dedent(
"""
DECLARE alpha REAL[1]
DECLARE beta... | class TestInspectionProperties:
| """Test that the inspection properties of ProgramLoader return the expected values."""
def test_inspection(self):
"""Test the combined inspection properties."""
quil_str = textwrap.dedent(
"""
DECLARE alpha REAL[1]
DECLARE beta REAL[1]
DECLARE gam... | .join(cur_dir, "simple_program.quil"))(wires=range(5))
# The wires should be assigned as
# 0 1 2 3 7
# 0 1 2 3 4
expected_queue = [
qml.Hadamard(0),
qml.RZ(0.34, wires=[1]),
qml.CNOT(wires=[0, 3]),
qml.Hadamard(2),
qml... | 200 | 200 | 668 | 5 | 194 | thisac/pennylane-forest | tests/test_converter.py | Python | TestInspectionProperties | TestInspectionProperties | 955 | 1,030 | 955 | 955 | 1947026334c56ab6c216661ef2945af21f4c2272 | bigcode/the-stack | train |
1503804c4fd0fa297bce22a3 | train | class | class TestProgramConverter:
"""Test that PyQuil Program instances are properly converted."""
@pytest.mark.parametrize(
"pyquil_operation,expected_pl_operation",
[
(g.I(0), qml.Identity(wires=[0])),
(g.H(0), qml.Hadamard(0)),
(g.H(0).dagger(), qml.Hadamard(0).... | class TestProgramConverter:
| """Test that PyQuil Program instances are properly converted."""
@pytest.mark.parametrize(
"pyquil_operation,expected_pl_operation",
[
(g.I(0), qml.Identity(wires=[0])),
(g.H(0), qml.Hadamard(0)),
(g.H(0).dagger(), qml.Hadamard(0).inv()),
(g.H(0).... | import os
import textwrap
import numpy as np
import pennylane as qml
import pyquil
import pyquil.gates as g
import pytest
from pennylane.utils import OperationRecorder
from pennylane_forest.converter import *
class TestProgramConverter:
| 58 | 256 | 8,096 | 5 | 53 | thisac/pennylane-forest | tests/test_converter.py | Python | TestProgramConverter | TestProgramConverter | 13 | 643 | 13 | 13 | 8b66fa8618a76b4ab5312dc8ae0e35de2531b044 | bigcode/the-stack | train |
7a8026f035b8d0742b3cefef | train | function | def search_around_poly(binary_warped, state):
"""
Lane detection methods. Searches in a area arounf the last lane lines for line pixels and fits a new line through
those pixels. If successful, lines are added to state.
:param binary_warped: Input image.
:param state: State, type State()
:return:... | def search_around_poly(binary_warped, state):
| """
Lane detection methods. Searches in a area arounf the last lane lines for line pixels and fits a new line through
those pixels. If successful, lines are added to state.
:param binary_warped: Input image.
:param state: State, type State()
:return: True if lines were found, False otherwise
... |
right_fit = np.polyfit(righty, rightx, 2)
# Left line with found poly and detection method=sliding window
right_line = Line('right', right_fit, 1, line_pixels={"x": rightx, "y": righty})
# Check if lines are valid
last_lines = state.get_last_lines()
if ... | 211 | 211 | 706 | 12 | 198 | akrost/CarND-AdvancedLaneFinding | AdvancedLaneLines.py | Python | search_around_poly | search_around_poly | 608 | 672 | 608 | 608 | 5a9d1e6fe862e3b961de5e0fc87a82a0008d6571 | bigcode/the-stack | train |
f9a05c3fabbfa49c4c4596ee | train | function | def get_hist(binary_img):
"""
This function splits the given image into an upper and a lower half.
The lower half is used to calculate a histogram an.
:param binary_img: Binary input image
:return: Histogram of lower half of input image.
"""
return np.sum(binary_img[binary_img.shape[0]//2:, ... | def get_hist(binary_img):
| """
This function splits the given image into an upper and a lower half.
The lower half is used to calculate a histogram an.
:param binary_img: Binary input image
:return: Histogram of lower half of input image.
"""
return np.sum(binary_img[binary_img.shape[0]//2:, :], axis=0)
| max position, right side max position (tuple)
"""
midpoint = np.int(hist.shape[0]//2)
left_max = np.argmax(hist[:midpoint])
right_max = np.argmax(hist[midpoint:])+midpoint
return left_max, right_max
def get_hist(binary_img):
| 64 | 64 | 81 | 6 | 57 | akrost/CarND-AdvancedLaneFinding | AdvancedLaneLines.py | Python | get_hist | get_hist | 405 | 412 | 405 | 405 | c687c8bd161eedb1d3749bbabda304d8532781db | bigcode/the-stack | train |
703fb81330c070b5752d8a70 | train | function | def check_lines_valid(left_line, right_line, last_left_line=None, last_right_line=None):
"""
Checks validity of two given lines based on there geometry and optionally based on the deviation to the previous
detected lines. Also calculates the Mean Absolute error and the Mean Squared Error of the x values bet... | def check_lines_valid(left_line, right_line, last_left_line=None, last_right_line=None):
| """
Checks validity of two given lines based on there geometry and optionally based on the deviation to the previous
detected lines. Also calculates the Mean Absolute error and the Mean Squared Error of the x values between the
two current lines.
:param left_line: Left line, Line() object
:param... | absolute):
"""
Compare two values with respect to a relative and an absolute deviation.
:param value1: First value
:param value2: Second value
:param relative: Relative deviation (0..1)
:param absolute: Absolute deviation (e.g. 1, -5.7, 100)
:return: True is value1 is within valid deviation... | 159 | 159 | 533 | 20 | 138 | akrost/CarND-AdvancedLaneFinding | AdvancedLaneLines.py | Python | check_lines_valid | check_lines_valid | 433 | 468 | 433 | 433 | e3cac5980d258770206d451e87fb6ed642ec4350 | bigcode/the-stack | train |
d0a2cd6af43725ae1fc2579e | train | class | class Line:
"""
Holds all relevant information to describe a line.
"""
def __init__(self, side, poly_params, detection_method, line_pixels=None):
# Side on which the line is
# 'left'
# 'right'
self.side = side
# Parameters of the 2nd order polynomial of the li... | class Line:
| """
Holds all relevant information to describe a line.
"""
def __init__(self, side, poly_params, detection_method, line_pixels=None):
# Side on which the line is
# 'left'
# 'right'
self.side = side
# Parameters of the 2nd order polynomial of the line (a * y² +... | import cv2
import numpy as np
import pickle
import argparse
from moviepy.editor import VideoFileClip
IMAGE_WIDTH = 1280
IMAGE_HEIGHT = 720
class Line:
| 40 | 67 | 224 | 3 | 36 | akrost/CarND-AdvancedLaneFinding | AdvancedLaneLines.py | Python | Line | Line | 12 | 35 | 12 | 12 | abd3f9c5045bfcbd7fc49f83855180bfb2f548d7 | bigcode/the-stack | train |
48a1ddaaf4b6394c7202653f | train | function | def undistort(img, mtx, dist):
"""
This function undistorts a given image
:param img: Input image
:param mtx: Camera matrix
:param dist: Distortion coefficients
:return: Undistorted image
"""
return cv2.undistort(img, mtx, dist, None, mtx)
| def undistort(img, mtx, dist):
| """
This function undistorts a given image
:param img: Input image
:param mtx: Camera matrix
:param dist: Distortion coefficients
:return: Undistorted image
"""
return cv2.undistort(img, mtx, dist, None, mtx)
| Returns last n lines saved in state.
:param n: Number of last lines to return
:return: Array of dict of lines [['left': Line(), 'right': Line()}, ...]
"""
return self.last_lines[-n:]
def undistort(img, mtx, dist):
| 63 | 64 | 80 | 11 | 52 | akrost/CarND-AdvancedLaneFinding | AdvancedLaneLines.py | Python | undistort | undistort | 198 | 206 | 198 | 198 | 489e22dc7a361dab8fd2f54df6666c321f00bf8e | bigcode/the-stack | train |
4d5fbf9cdc706557e76496ac | train | function | def hist_peaks(hist):
"""
This functions finds two peaks in a histogram. For this the image is split
into a left and a right part. In each part the max histogram value is searched.
The position of the max histogram value is returned.
:param hist: Histogram
:return: left side max position, right ... | def hist_peaks(hist):
| """
This functions finds two peaks in a histogram. For this the image is split
into a left and a right part. In each part the max histogram value is searched.
The position of the max histogram value is returned.
:param hist: Histogram
:return: left side max position, right side max position (tup... | # Undistort image
dst = undistort(img, mtx, dist)
# Apply perpective transfomation
warped = warp(dst)
# Apply color space operations
binary = cvt_color_space(warped)
return binary
def hist_peaks(hist):
| 64 | 64 | 126 | 6 | 57 | akrost/CarND-AdvancedLaneFinding | AdvancedLaneLines.py | Python | hist_peaks | hist_peaks | 391 | 402 | 391 | 391 | 59a744dae63fb75eb6e18ca2cb706c70e652af06 | bigcode/the-stack | train |
8fa7d6e8dd0a0b46cc80cd61 | train | function | def compare_values(value1, value2, relative, absolute):
"""
Compare two values with respect to a relative and an absolute deviation.
:param value1: First value
:param value2: Second value
:param relative: Relative deviation (0..1)
:param absolute: Absolute deviation (e.g. 1, -5.7, 100)
:retu... | def compare_values(value1, value2, relative, absolute):
| """
Compare two values with respect to a relative and an absolute deviation.
:param value1: First value
:param value2: Second value
:param relative: Relative deviation (0..1)
:param absolute: Absolute deviation (e.g. 1, -5.7, 100)
:return: True is value1 is within valid deviation of value2, ... | calculate a histogram an.
:param binary_img: Binary input image
:return: Histogram of lower half of input image.
"""
return np.sum(binary_img[binary_img.shape[0]//2:, :], axis=0)
def compare_values(value1, value2, relative, absolute):
| 64 | 64 | 150 | 13 | 51 | akrost/CarND-AdvancedLaneFinding | AdvancedLaneLines.py | Python | compare_values | compare_values | 415 | 430 | 415 | 415 | 8bf2ccc41d1d65c588d92981623222032bc64428 | bigcode/the-stack | train |
107e8e2ebcda857b71bbcb8c | train | function | def channel_thresh(img, channel='h', thresh=(90, 255)):
"""
This function extracts a given channel from an image and applies a threshold to it.
The output image is a binary image with the same shape of the input image.
:param img: Input image (BGR)
:param channel: The channel that the threshold is a... | def channel_thresh(img, channel='h', thresh=(90, 255)):
| """
This function extracts a given channel from an image and applies a threshold to it.
The output image is a binary image with the same shape of the input image.
:param img: Input image (BGR)
:param channel: The channel that the threshold is applied to
:param thresh: Threshold to apply. Tuple (... | [img_size[0]//4, 0]])
# Compute perspective transform matrix
if not reverse:
m = cv2.getPerspectiveTransform(src, dst)
else:
m = cv2.getPerspectiveTransform(dst, src)
# Warp image
warped = cv2.warpPerspective(img, m, img_size, flags=cv2.INTER_LINEAR)
return warped
def ... | 99 | 99 | 330 | 16 | 82 | akrost/CarND-AdvancedLaneFinding | AdvancedLaneLines.py | Python | channel_thresh | channel_thresh | 252 | 284 | 252 | 252 | e194dac9d21b290383e7d58e2dd3e0c63737f995 | bigcode/the-stack | train |
fe5784da90ea9d94ba68fe85 | train | class | class State:
"""
Holds the current state of the lane line detection.
"""
def __init__(self, num_last_saved=5, copy_limit=10):
# CONSTANTS
self.IMG_WIDTH = 1280
self.IMG_HEIGHT = 720
self.LANE_WIDTH_METERS = 3 # Used to calculate the pixel resolution in x direction
... | class State:
| """
Holds the current state of the lane line detection.
"""
def __init__(self, num_last_saved=5, copy_limit=10):
# CONSTANTS
self.IMG_WIDTH = 1280
self.IMG_HEIGHT = 720
self.LANE_WIDTH_METERS = 3 # Used to calculate the pixel resolution in x direction
# Number ... |
import pickle
import argparse
from moviepy.editor import VideoFileClip
IMAGE_WIDTH = 1280
IMAGE_HEIGHT = 720
class Line:
"""
Holds all relevant information to describe a line.
"""
def __init__(self, side, poly_params, detection_method, line_pixels=None):
# Side on which the line is
... | 256 | 256 | 1,631 | 3 | 252 | akrost/CarND-AdvancedLaneFinding | AdvancedLaneLines.py | Python | State | State | 38 | 195 | 38 | 38 | 4a987206c967c47c44ecb443f4c3f4a23a426de4 | bigcode/the-stack | train |
a5b3074b78ef3eb5d72c0137 | train | function | def visualize_from_state(img, state, line_color=(255, 0, 0), lane_color=(0, 255, 0), warped=True):
"""
Generate an output image based on an input image and a state (type State()).
:param img: Input image
:param state: State, type State()
:param line_color: Color of the detected lines. Default (255, ... | def visualize_from_state(img, state, line_color=(255, 0, 0), lane_color=(0, 255, 0), warped=True):
| """
Generate an output image based on an input image and a state (type State()).
:param img: Input image
:param state: State, type State()
:param line_color: Color of the detected lines. Default (255, 0, 0)
:param lane_color: Color of the detected lane (polygon between two lanes). Default (0, 25... | Lines will be added to state.
:param state: State, type State()
:return: True if copying work, False otherwise.
"""
# Check if number of maximum copies was not exceeded
if state.num_copied_lines < state.copy_limit:
try:
# Get all saved last lines
last_lines = state.g... | 256 | 256 | 1,056 | 33 | 222 | akrost/CarND-AdvancedLaneFinding | AdvancedLaneLines.py | Python | visualize_from_state | visualize_from_state | 710 | 791 | 710 | 710 | e29869d676baab4ba6b043070ba2ecbe5a077f59 | bigcode/the-stack | train |
99e9876967ff168e7600908c | train | function | def cvt_color_space(img):
"""
This function extracts the R- and S-channel of the image. Since the S-channel is quite noisy
a sobel in x-direction is used to filter the noise (bitwise_and). Also both, the filtered S- and the R-channel
are not working that well for detection yellow lines. Therefor a yello... | def cvt_color_space(img):
| """
This function extracts the R- and S-channel of the image. Since the S-channel is quite noisy
a sobel in x-direction is used to filter the noise (bitwise_and). Also both, the filtered S- and the R-channel
are not working that well for detection yellow lines. Therefor a yellow color mask is added (bit... | the scaled gradient magnitude
binary_output = np.zeros_like(scaled_sobel)
binary_output[(scaled_sobel >= thresh_min) & (scaled_sobel <= thresh_max)] = 1
# 6) [Optional] Apply erosion
if erosion:
binary_output = cv2.erode(binary_output, er_kernel)
# 7) [Optional] Apply dilation... | 114 | 114 | 383 | 7 | 106 | akrost/CarND-AdvancedLaneFinding | AdvancedLaneLines.py | Python | cvt_color_space | cvt_color_space | 332 | 365 | 332 | 332 | 49f28cb4ca25cd5ad9547455be6026fa776824fa | bigcode/the-stack | train |
8602d9a6ea2ab09fc86533b9 | train | function | def take_last_lines(state):
"""
Lane detection methods. Return last detected lines if the maximum number of copied lines was not exceeded already.
Lines will be added to state.
:param state: State, type State()
:return: True if copying work, False otherwise.
"""
# Check if number of maximum ... | def take_last_lines(state):
| """
Lane detection methods. Return last detected lines if the maximum number of copied lines was not exceeded already.
Lines will be added to state.
:param state: State, type State()
:return: True if copying work, False otherwise.
"""
# Check if number of maximum copies was not exceeded
... | :
_, _, valid = check_lines_valid(left_line, right_line)
if valid:
# Add found lines to state
state.add_lines({'left': left_line,
'right': right_line})
return True
else:
return False
except:
... | 75 | 75 | 253 | 6 | 68 | akrost/CarND-AdvancedLaneFinding | AdvancedLaneLines.py | Python | take_last_lines | take_last_lines | 675 | 707 | 675 | 675 | 0614aac59a4307a51526365d612fda3fd7709ece | bigcode/the-stack | train |
8909c27df18d8a32fc7216fd | train | function | def sliding_window(binary_warped, state, leftx_base=None, rightx_base=None):
"""
Lane detection method. Starting from the left and right base the method searched for line pixels using a sliding
window approach. Left and right base can either be given or are determined by a histogram (see
"_find_lane_pix... | def sliding_window(binary_warped, state, leftx_base=None, rightx_base=None):
| """
Lane detection method. Starting from the left and right base the method searched for line pixels using a sliding
window approach. Left and right base can either be given or are determined by a histogram (see
"_find_lane_pixels()" for details). If succesful, lines are added to state.
:param binar... | This ensures that the lines have a minimum (and maximum) distance
if (mae < 150) or (mae > 750):
valid = False
# Check if params have changed too much from the last frame
if last_left_line is not None:
last_frame_comparison = compare_values(left_line.poly_params[0], last_left_line.poly_par... | 256 | 256 | 1,458 | 20 | 235 | akrost/CarND-AdvancedLaneFinding | AdvancedLaneLines.py | Python | sliding_window | sliding_window | 471 | 605 | 471 | 471 | cc60e0cab6b52940276dd96bf605922579c8692f | bigcode/the-stack | train |
5d8527d32072b7c574b77ff0 | train | function | def process_image(img):
"""
Main function to process video frames. Image will be pre-processed with the image pre-processing pipeline. The
binary output of the pipeline will then be searched for lane lines. To do that, three different approaches are used.
1) Sliding window
2) Search around poly
... | def process_image(img):
| """
Main function to process video frames. Image will be pre-processed with the image pre-processing pipeline. The
binary output of the pipeline will then be searched for lane lines. To do that, three different approaches are used.
1) Sliding window
2) Search around poly
3) Take last line (if no... | , 0)
# Add "radius" and "off center" to image if a valid lane was detected
if last_lines:
text = 'Lane radius: {0:.3f} m'.format(state.lane_radius)
cv2.putText(result, text, (20, 70), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 255, 255), thickness=2)
text = 'Off center: {0:.3f} m'.format(sta... | 164 | 164 | 547 | 5 | 158 | akrost/CarND-AdvancedLaneFinding | AdvancedLaneLines.py | Python | process_image | process_image | 794 | 843 | 794 | 794 | bcd4b65ec32db18b6e7cebb3cb0c6349574c7880 | bigcode/the-stack | train |
82bfc1ff65260e6ef03219c6 | train | function | def pipeline(img, mtx, dist):
"""
The pipeline applies all image pre-processing steps to the image (or video frame).
1) Undistort the image using the given camera matrix and the distortion coefficients
2) Warp the image to a bird's-eye view
3) Apply color space conversion
:param img: Input image... | def pipeline(img, mtx, dist):
| """
The pipeline applies all image pre-processing steps to the image (or video frame).
1) Undistort the image using the given camera matrix and the distortion coefficients
2) Warp the image to a bird's-eye view
3) Apply color space conversion
:param img: Input image (BGR)
:param mtx: Camera ... | .inRange(hsv, yellow_low, yellow_high)//255
yellow = cv2.bitwise_or(filtered_s, yellow_mask)
# combine R and filtered S channel
bin_img = cv2.bitwise_or(bin_r, yellow)
return bin_img
def pipeline(img, mtx, dist):
| 64 | 64 | 180 | 9 | 54 | akrost/CarND-AdvancedLaneFinding | AdvancedLaneLines.py | Python | pipeline | pipeline | 368 | 388 | 368 | 368 | 9c049d5b40d42deff35caeca3247e80ecc7e7a64 | bigcode/the-stack | train |
eb94dc6b8702c0d1bdc1380b | train | function | def abs_sobel_thresh(img, orient='x', thresh_min=0, thresh_max=255, erosion=False, dilation=False,
er_kernel=np.ones((9, 9), np.uint8), dil_kernel=np.ones((15, 15), np.uint8)):
"""
This function calculates the sobel for an image and applies a
binary threshold
:param img: input image... | def abs_sobel_thresh(img, orient='x', thresh_min=0, thresh_max=255, erosion=False, dilation=False,
er_kernel=np.ones((9, 9), np.uint8), dil_kernel=np.ones((15, 15), np.uint8)):
| """
This function calculates the sobel for an image and applies a
binary threshold
:param img: input image
:param orient: orientation, can be 'x' or 'y'
:param thresh_min: minimum binary threshold
:param thresh_max: maximum binary threshold
:param erosion: If True, erosion will be applie... | img[:, :, 1]
elif channel == 'r':
c = img[:, :, 2]
else:
raise Exception('Channel {} is not recognized. Possible values are: h, l, s, r, g, b'.format(channel))
# use threshold to generate binary image
binary = np.zeros_like(c)
binary[(c > thresh[0]) & (c <= thresh[1])] = 1
... | 153 | 153 | 511 | 56 | 96 | akrost/CarND-AdvancedLaneFinding | AdvancedLaneLines.py | Python | abs_sobel_thresh | abs_sobel_thresh | 287 | 329 | 287 | 288 | c7cd2516202c46039346b14eb4cfd8564fb13e8a | bigcode/the-stack | train |
381836a72c36362744faf493 | train | function | def warp(img, pers_margin=425, margin_bottom=50, margin_top=450, margin_sides=150, reverse=False):
"""
This function warps an image. For the transformation a src polygon and a destination
polygon are used. The source polygon is calculated by the image shape and the margins
given. The destination polygon... | def warp(img, pers_margin=425, margin_bottom=50, margin_top=450, margin_sides=150, reverse=False):
| """
This function warps an image. For the transformation a src polygon and a destination
polygon are used. The source polygon is calculated by the image shape and the margins
given. The destination polygon is calculated solely on the image shape.
:param img: Input image
:param pers_margin: This ... | of lines [['left': Line(), 'right': Line()}, ...]
"""
return self.last_lines[-n:]
def undistort(img, mtx, dist):
"""
This function undistorts a given image
:param img: Input image
:param mtx: Camera matrix
:param dist: Distortion coefficients
:return: Undistorted image
"""... | 133 | 133 | 444 | 28 | 105 | akrost/CarND-AdvancedLaneFinding | AdvancedLaneLines.py | Python | warp | warp | 209 | 249 | 209 | 209 | 9a7fc92f448f1de025c8b5044a6abdf123088b7a | bigcode/the-stack | train |
dd7cf1f083b9b0b57daaec2d | train | class | class LivePyDevd(protocol.Daemon):
@classmethod
def parse_source(cls, source):
kind, sep, name = source.partition(':')
if kind == 'file':
return name, None, False
elif kind == 'module':
parts = (name).split('.')
filename = os.path.join(*parts) + '.py'... | class LivePyDevd(protocol.Daemon):
@classmethod
| def parse_source(cls, source):
kind, sep, name = source.partition(':')
if kind == 'file':
return name, None, False
elif kind == 'module':
parts = (name).split('.')
filename = os.path.join(*parts) + '.py'
return filename, name, False
els... | if not acquire_with_timeout(self._lock, timeout=3):
# This shouldn't happen since the timeout on event waiting
# is this long.
warnings.warn('timeout out waiting for "done"')
return self._closeondone
def done(self, close=True):
self._closeondone = close
... | 88 | 88 | 294 | 14 | 74 | rozuur/ptvsd | tests/helpers/pydevd/_live.py | Python | LivePyDevd | LivePyDevd | 57 | 94 | 57 | 59 | ddc807406acd8400bab278ed0cdc63298562e59d | bigcode/the-stack | train |
a6ccdd1fd24517f2f32313e7 | train | class | class Binder(BinderBase):
def __init__(self, filename, module, singlesession=True, **kwargs):
super(Binder, self).__init__(
singlesession=singlesession,
**kwargs
)
self.filename = filename
self.module = module
self._lock = threading.Lock()
sel... | class Binder(BinderBase):
| def __init__(self, filename, module, singlesession=True, **kwargs):
super(Binder, self).__init__(
singlesession=singlesession,
**kwargs
)
self.filename = filename
self.module = module
self._lock = threading.Lock()
self._lock.acquire()
s... | import os
import os.path
import threading
import warnings
import ptvsd._local
from tests.helpers import protocol
from tests.helpers.threading import acquire_with_timeout
from ._binder import BinderBase
class Binder(BinderBase):
| 50 | 88 | 296 | 6 | 43 | rozuur/ptvsd | tests/helpers/pydevd/_live.py | Python | Binder | Binder | 12 | 54 | 12 | 13 | 591a78bb9b3faa421339f9ed7d7f7114eb1e158a | bigcode/the-stack | train |
ce61529e0340a71a61b9f6e1 | train | class | class Solution2(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n < 0 and n != -n:
return 1.0 / self.myPow(x, -n)
if n == 0:
return 1
v = self.myPow(x, n / 2)
if n % 2 == 0:
... | class Solution2(object):
| def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n < 0 and n != -n:
return 1.0 / self.myPow(x, -n)
if n == 0:
return 1
v = self.myPow(x, n / 2)
if n % 2 == 0:
return v * v
e... | """
result = 1
abs_n = abs(n)
while abs_n:
if abs_n & 1:
result *= x
abs_n >>= 1
x *= x
return 1 / result if n < 0 else result
class Solution2(object):
| 64 | 64 | 118 | 5 | 58 | paperfactory/LeetCode-Solution | Python/powx-n.py | Python | Solution2 | Solution2 | 22 | 37 | 22 | 22 | a860810629592bbeff29048d7f6a105997159ded | bigcode/the-stack | train |
882f135461e8efaf8454c8dd | train | class | class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
result = 1
abs_n = abs(n)
while abs_n:
if abs_n & 1:
result *= x
abs_n >>= 1
x *= x
return 1 /... | class Solution(object):
| def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
result = 1
abs_n = abs(n)
while abs_n:
if abs_n & 1:
result *= x
abs_n >>= 1
x *= x
return 1 / result if n < 0 else re... | from __future__ import print_function
# Time: O(logn) = O(1)
# Space: O(1)
class Solution(object):
| 32 | 64 | 95 | 4 | 28 | paperfactory/LeetCode-Solution | Python/powx-n.py | Python | Solution | Solution | 5 | 20 | 5 | 5 | 35011c02454554fb578c33358e9a292a31af6d58 | bigcode/the-stack | train |
f874fc061fd0eb94277b5bc2 | train | class | class IsptAdmin(admin.ModelAdmin):
list_display = ('id', 'fecha_final', 'fecha_inicial', 'tipo_tabla', 'limite_inferior', 'limite_superior', 'cuota_fija', 'excedente', 'bruto')
list_filter = ('fecha_final',)
date_hierarchy = 'fecha_final'
ordering = ('-fecha_final',)
save_on_top = True
search_fi... | class IsptAdmin(admin.ModelAdmin):
| list_display = ('id', 'fecha_final', 'fecha_inicial', 'tipo_tabla', 'limite_inferior', 'limite_superior', 'cuota_fija', 'excedente', 'bruto')
list_filter = ('fecha_final',)
date_hierarchy = 'fecha_final'
ordering = ('-fecha_final',)
save_on_top = True
search_fields = ('tipo_tabla',)
| 'rango', 'sueldo', 'compensacion')
list_filter = ('fecha_final',)
date_hierarchy = 'fecha_final'
ordering = ('-fecha_final',)
save_on_top = True
search_fields = ('nivel',)
class IsptAdmin(admin.ModelAdmin):
| 64 | 64 | 101 | 8 | 56 | apfnomina/app-nomina | main/admin.py | Python | IsptAdmin | IsptAdmin | 14 | 20 | 14 | 14 | 00bd8a1d22c346786334009357cad34fe9e1a539 | bigcode/the-stack | train |
8949a2e8795a7f9f7a3a8c6a | train | class | class TabuladorAdmin(admin.ModelAdmin):
list_display = ('id', 'fecha_final', 'fecha_inicial', 'nivel', 'zona_economica', 'rango', 'sueldo', 'compensacion')
list_filter = ('fecha_final',)
date_hierarchy = 'fecha_final'
ordering = ('-fecha_final',)
save_on_top = True
search_fields = ('nivel',)
| class TabuladorAdmin(admin.ModelAdmin):
| list_display = ('id', 'fecha_final', 'fecha_inicial', 'nivel', 'zona_economica', 'rango', 'sueldo', 'compensacion')
list_filter = ('fecha_final',)
date_hierarchy = 'fecha_final'
ordering = ('-fecha_final',)
save_on_top = True
search_fields = ('nivel',)
| from django.contrib import admin
# Register your models here.
from main.models import Tabulador, Ispt
class TabuladorAdmin(admin.ModelAdmin):
| 32 | 64 | 90 | 9 | 22 | apfnomina/app-nomina | main/admin.py | Python | TabuladorAdmin | TabuladorAdmin | 6 | 12 | 6 | 6 | 42313c4c7b31252dc2e32938c0c5569852ac333e | bigcode/the-stack | train |
13afd3f6acd91b3924918a62 | train | class | class SimulationManager(ABC):
"""
Control interaction between Trainer and AgentBasedSimulation.
A Manager implmenents the reset and step API, by which it calls the AgentBasedSimulation
API, using the getters within reset and step to accomplish the desired control
flow.
Attributes:
sim:... | class SimulationManager(ABC):
| """
Control interaction between Trainer and AgentBasedSimulation.
A Manager implmenents the reset and step API, by which it calls the AgentBasedSimulation
API, using the getters within reset and step to accomplish the desired control
flow.
Attributes:
sim: The AgentBasedSimulation.
... | from abc import ABC, abstractmethod
from abmarl.sim import AgentBasedSimulation
class SimulationManager(ABC):
| 24 | 89 | 299 | 6 | 17 | Leonardo767/Abmarl | abmarl/managers/simulation_manager.py | Python | SimulationManager | SimulationManager | 6 | 54 | 6 | 6 | f1b9850c87df1d06fe8d07bb6d71dff45726a21c | bigcode/the-stack | train |
3db330fb9ca4e88c436a635b | train | class | class TestCheckFilters(unittest.TestCase):
def create_check(self, attrs):
ret = RegressionTest()
for k, v in attrs.items():
setattr(ret, k, v)
return ret
def setUp(self):
self.checks = [
self.create_check({
'name': 'check1',
... | class TestCheckFilters(unittest.TestCase):
| def create_check(self, attrs):
ret = RegressionTest()
for k, v in attrs.items():
setattr(ret, k, v)
return ret
def setUp(self):
self.checks = [
self.create_check({
'name': 'check1',
'tags': {'a', 'b', 'c', 'd'},
... | # Copyright 2016-2020 Swiss National Supercomputing Centre (CSCS/ETH Zurich)
# ReFrame Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
import pytest
import unittest
import reframe.core.runtime as rt
import reframe.frontend.check_filters as filters
import refra... | 116 | 256 | 854 | 8 | 107 | mboisson/reframe | unittests/test_check_filters.py | Python | TestCheckFilters | TestCheckFilters | 17 | 103 | 17 | 17 | c71445c0998e59ecd6d03c39f148788e67bed01c | bigcode/the-stack | train |
8779e81f7b47336e04db28e0 | train | function | def draw(history, epochs, title, x_range, t_name, v_name):
""" """
pyplot.clf()
pyplot.grid(True)
t_values = history[t_name]
v_values = history[v_name]
pyplot.plot(x_range, t_values, 'b-o', label='Test set')
pyplot.plot(x_range, v_values, 'g-s', label='Validation set')
pyplot.xlabel(... | def draw(history, epochs, title, x_range, t_name, v_name):
| """ """
pyplot.clf()
pyplot.grid(True)
t_values = history[t_name]
v_values = history[v_name]
pyplot.plot(x_range, t_values, 'b-o', label='Test set')
pyplot.plot(x_range, v_values, 'g-s', label='Validation set')
pyplot.xlabel('Epoch')
pyplot.ylabel('Value')
pyplot.title(title)... | a loss/accuracy plot.
"""
import io
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as pyplot
from matplotlib.ticker import MaxNLocator
def initialize():
""" Defines graph style. """
pyplot.style.use('classic')
def draw(history, epochs, title, x_range, t_name, v_name):
| 69 | 70 | 235 | 17 | 52 | EEvangelisti/amfinder | amf/amfinder_plot.py | Python | draw | draw | 52 | 90 | 52 | 52 | d89f53a30e00757d8fbdda25f38501932725d244 | bigcode/the-stack | train |
65199ca2dbf787acd053622b | train | function | def initialize():
""" Defines graph style. """
pyplot.style.use('classic')
| def initialize():
| """ Defines graph style. """
pyplot.style.use('classic')
| THE SOFTWARE.
"""
Plots accuracy and loss after training.
Functions
-----------
:function initialize: Defines plot style.
:function draw: draws a loss/accuracy plot.
"""
import io
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as pyplot
from matplotlib.ticker import MaxNLocator
def initialize(... | 64 | 64 | 17 | 3 | 60 | EEvangelisti/amfinder | amf/amfinder_plot.py | Python | initialize | initialize | 45 | 48 | 45 | 45 | 70e40b47f9aa48b7435485e7c1f4411cebe9676d | bigcode/the-stack | train |
ca28d3e826aa6a1eab9b00af | train | function | def test__threepoints():
# init with file
v1 = ppp.ThreePoints("test/data/v1.survey")
v2 = ppp.ThreePoints("test/data/v2.survey")
# init with dict
with open("test/data/v1.survey", 'r') as fl:
dict_survey = json.load(fl)
_ = ppp.ThreePoints(dict_survey)
# test wrong version
dict_s... | def test__threepoints():
# init with file
| v1 = ppp.ThreePoints("test/data/v1.survey")
v2 = ppp.ThreePoints("test/data/v2.survey")
# init with dict
with open("test/data/v1.survey", 'r') as fl:
dict_survey = json.load(fl)
_ = ppp.ThreePoints(dict_survey)
# test wrong version
dict_survey.pop('inline')
with pytest.raises(Inv... | # -*- coding: utf-8 -*-
"""
Test
Created on Feb. 22nd 2018
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
__author__ = "yuhao"
import json
import pytest
import pygeopressure as ppp
from pygeopressure.basic.threepoints import (
Invalid_threepoints... | 111 | 139 | 466 | 12 | 99 | antineutrino2/pyGeoPressure | test/basic/test_threepoints.py | Python | test__threepoints | test__threepoints | 22 | 60 | 22 | 23 | 64c5602b539cb7d87d6f027da08d6104a199cfba | bigcode/the-stack | train |
202433ed8c2ecd75b2a610f6 | train | class | class ThumbnailEvents(BaseEvent):
settings_key = "thumbnail_updates"
def launch(self, session, event):
"""Updates thumbnails of entities from new AssetVersion."""
filtered_entities = self.filter_entities(event)
if not filtered_entities:
return
for project_id, entiti... | class ThumbnailEvents(BaseEvent):
| settings_key = "thumbnail_updates"
def launch(self, session, event):
"""Updates thumbnails of entities from new AssetVersion."""
filtered_entities = self.filter_entities(event)
if not filtered_entities:
return
for project_id, entities_info in filtered_entities.items... | import collections
from pype.modules.ftrack.lib import BaseEvent
class ThumbnailEvents(BaseEvent):
| 20 | 256 | 994 | 6 | 13 | simonebarbieri/pype | pype/modules/ftrack/event_handlers_server/event_thumbnail_updates.py | Python | ThumbnailEvents | ThumbnailEvents | 5 | 151 | 5 | 5 | 43fd50bdd4742aed2a928bc256b65327653b2641 | bigcode/the-stack | train |
6203f95b6ddaf030b0cf2f9f | train | function | def register(session):
ThumbnailEvents(session).register()
| def register(session):
| ThumbnailEvents(session).register()
| Get project id from entity info
project_id = entity_info["parents"][-1]["entityId"]
if project_id not in filtered_entities_info:
filtered_entities_info[project_id] = []
filtered_entities_info[project_id].append(entity_info)
return filtered_entities_info
def r... | 64 | 64 | 11 | 4 | 59 | simonebarbieri/pype | pype/modules/ftrack/event_handlers_server/event_thumbnail_updates.py | Python | register | register | 154 | 155 | 154 | 154 | 333f90289ae43c880b50b80cf5d7036cf3516a54 | bigcode/the-stack | train |
47edc1e293a433a827b968d5 | train | function | def add_tenhou_game_to_pantheon(log_link: str):
data = {
"jsonrpc": "2.0",
"method": "addOnlineReplay",
"params": {"eventId": settings.PANTHEON_EVENT_ID, "link": log_link},
"id": make_random_letters_and_digit_string(),
}
return requests.post(settings.PANTHEON_URL, json=data)
| def add_tenhou_game_to_pantheon(log_link: str):
| data = {
"jsonrpc": "2.0",
"method": "addOnlineReplay",
"params": {"eventId": settings.PANTHEON_EVENT_ID, "link": log_link},
"id": make_random_letters_and_digit_string(),
}
return requests.post(settings.PANTHEON_URL, json=data)
| heon 500.")
return []
content = response.json()
if content.get("error"):
logger.error("Make sortition. Pantheon error. {}".format(content.get("error")))
return []
return content["result"]
def add_tenhou_game_to_pantheon(log_link: str):
| 63 | 64 | 87 | 15 | 48 | Jesterboxboy/mahjong-portal | server/utils/pantheon.py | Python | add_tenhou_game_to_pantheon | add_tenhou_game_to_pantheon | 101 | 108 | 101 | 101 | 72b303adad108eead2b41e90eccb470497f5c78e | bigcode/the-stack | train |
b6906efc5d379ba1003c79e8 | train | function | def get_pantheon_swiss_sortition():
data = {
"jsonrpc": "2.0",
"method": "generateSwissSeating",
"params": {"eventId": settings.PANTHEON_EVENT_ID},
"id": make_random_letters_and_digit_string(),
}
headers = {"X-Auth-Token": settings.PANTHEON_ADMIN_TOKEN}
response = reque... | def get_pantheon_swiss_sortition():
| data = {
"jsonrpc": "2.0",
"method": "generateSwissSeating",
"params": {"eventId": settings.PANTHEON_EVENT_ID},
"id": make_random_letters_and_digit_string(),
}
headers = {"X-Auth-Token": settings.PANTHEON_ADMIN_TOKEN}
response = requests.post(settings.PANTHEON_URL, json... | player. 500 response")
content = response.json()
if content.get("error"):
return HttpResponse("Register player. Pantheon error: {}".format(content.get("error")))
record.added_to_pantheon = True
record.save()
def get_pantheon_swiss_sortition():
| 64 | 64 | 165 | 10 | 54 | Jesterboxboy/mahjong-portal | server/utils/pantheon.py | Python | get_pantheon_swiss_sortition | get_pantheon_swiss_sortition | 78 | 98 | 78 | 78 | eb80213cfb2c4b6d96aa5ce97dc2e91e63e102d5 | bigcode/the-stack | train |
855605f743dfdb6fff51bcdf | train | function | def add_user_to_pantheon(record: TournamentPlayers):
if not record.pantheon_id:
return
headers = {"X-Auth-Token": settings.PANTHEON_ADMIN_TOKEN}
# The first step is update player tenhou nickname
data = {
"jsonrpc": "2.0",
"method": "updatePlayer",
"params": {
... | def add_user_to_pantheon(record: TournamentPlayers):
| if not record.pantheon_id:
return
headers = {"X-Auth-Token": settings.PANTHEON_ADMIN_TOKEN}
# The first step is update player tenhou nickname
data = {
"jsonrpc": "2.0",
"method": "updatePlayer",
"params": {
"id": record.pantheon_id,
"ident": "",
... | import logging
import requests
from django.conf import settings
from django.http import HttpResponse
from online.models import TournamentPlayers
from utils.general import make_random_letters_and_digit_string
logger = logging.getLogger()
def add_user_to_pantheon(record: TournamentPlayers):
| 55 | 153 | 513 | 12 | 43 | Jesterboxboy/mahjong-portal | server/utils/pantheon.py | Python | add_user_to_pantheon | add_user_to_pantheon | 13 | 75 | 13 | 13 | 442c26ae75ba5e08a79053f613ba697e2a35a107 | bigcode/the-stack | train |
d25160d3739706b73fda2b56 | train | function | def fp2int_test(num, name, should_fail):
try:
x = int(num)
passed = ~should_fail
except:
passed = should_fail
print('%s: %s' % (name, passed and 'passed' or 'failed'))
| def fp2int_test(num, name, should_fail):
| try:
x = int(num)
passed = ~should_fail
except:
passed = should_fail
print('%s: %s' % (name, passed and 'passed' or 'failed'))
| print('fail: 10**%u was %u digits long' % (i, digcnt));
testpass = False
print("power of 10 test: %s" % (testpass and 'passed' or 'failed'))
def fp2int_test(num, name, should_fail):
| 64 | 64 | 58 | 12 | 52 | learnforpractice/micropython-cpp | tests/float/float2int_doubleprec_intbig.py | Python | fp2int_test | fp2int_test | 61 | 67 | 61 | 61 | e6972dfe457f6352850016e45b4d9f2a01c68002 | bigcode/the-stack | train |
647dae1ef02c5ddf0490a2e1 | train | function | def banner():
clear()
print(Fore.RED+"")
print('''
__________________________________
|WHO Am I you ask? or what is this|
|---------------------------------|
\
\
.--.
|o_o |
|:_/ |
// \ \
(| | )
/'\_ _/`\
\___)=(___/
''')
| def banner():
| clear()
print(Fore.RED+"")
print('''
__________________________________
|WHO Am I you ask? or what is this|
|---------------------------------|
\
\
.--.
|o_o |
|:_/ |
// \ \
(| | )
/'\_ _/`\
\___)=(___/
''')
| 500 average ports for scanning and
probing website ports. while also being
extremely fast when probing and outputting
unlike python3 where i made evil scanner a slow
but efficent program this is still one that can
be way faster and more useful
''')
def banner():
| 64 | 64 | 89 | 3 | 61 | ArkAngeL43/Rube-Ster | readme.py | Python | banner | banner | 105 | 122 | 105 | 105 | 8b0b4a7918e555676525dff335f64190dc6103a9 | bigcode/the-stack | train |
c1fcfac49bff864eb1eadb62 | train | function | def cs(X):
t.sleep(X)
if sys.platform == 'linux':
os.system('clear')
if sys.platform == 'win-32':
os.system('cls')
if sys.platform == 'win-64':
os.system('cls')
| def cs(X):
| t.sleep(X)
if sys.platform == 'linux':
os.system('clear')
if sys.platform == 'win-32':
os.system('cls')
if sys.platform == 'win-64':
os.system('cls')
| import os
import colorama
import time as t
from colorama import init
from colorama import Fore
import sys
init()
def cs(X):
| 33 | 64 | 55 | 4 | 29 | ArkAngeL43/Rube-Ster | readme.py | Python | cs | cs | 11 | 18 | 11 | 11 | f8be923f21f2cc238e888a37b2b9cffc25f81562 | bigcode/the-stack | train |
4d83ce06c22914b5fdaa5626 | train | function | def cls():
oscheck()
| def cls():
| oscheck()
| print(" hello 1 ")
if sys.platform == 'win-32':
def cs(X):
t.sleep(X)
os.system('cls')
if sys.platform == 'win-64':
def cs(X): ... | 63 | 64 | 7 | 3 | 60 | ArkAngeL43/Rube-Ster | readme.py | Python | cls | cls | 34 | 35 | 34 | 34 | 30e3eb460c4a0637a5827a20269f2d2b5fc5f28c | bigcode/the-stack | train |
9710094094230b9f0b1f583c | train | function | def menue():
t.sleep(5)
print('''
______________________ABOUT___________________________
well for one let m,e introduce you to Rube-rabbit
or rubster as i like to call this framework, well
Rube-Rabbit is a penetration testing scanner and recon
framework written mainly from ruby. with ruby ... | def menue():
| t.sleep(5)
print('''
______________________ABOUT___________________________
well for one let m,e introduce you to Rube-rabbit
or rubster as i like to call this framework, well
Rube-Rabbit is a penetration testing scanner and recon
framework written mainly from ruby. with ruby being its
... | `* #=ooO=========Ooo=#")
print(Fore.YELLOW+" /(o o)\ :(o o): . (o o) !! | | 8(o o)(_)Ooo - (o o) - (o o) # \\ (o o) // #")
print(Fore.YELLOW+"ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo------------------ooO-(_)---Ooo----ooO--(_)--Ooo-ooO--(_)--Ooo---------(_)-------- ... | 173 | 174 | 580 | 4 | 169 | ArkAngeL43/Rube-Ster | readme.py | Python | menue | menue | 52 | 102 | 52 | 52 | f9c5daf3338735d70c776b9e2b55f8ee30a64efd | bigcode/the-stack | train |
06a838b11ca722e1f4358462 | train | function | def banner1():
oscheck()
print(Fore.YELLOW+" ")
print(Fore.YELLOW+" . . _ _ ___ ... o ___ # #")
print(Fore.YELLOW+" ,,,,, . .:::. '\\-//` < - - - - -()_ \ o,*,(o o) ` /_\ ' /_\ `* #=o... | def banner1():
| oscheck()
print(Fore.YELLOW+" ")
print(Fore.YELLOW+" . . _ _ ___ ... o ___ # #")
print(Fore.YELLOW+" ,,,,, . .:::. '\\-//` < - - - - -()_ \ o,*,(o o) ` /_\ ' /_\ `* #=ooO=========Ooo=... | if sys.platform == 'win-32':
def cs(X):
t.sleep(X)
os.system('cls')
if sys.platform == 'win-64':
def cs(X): ... | 66 | 66 | 221 | 4 | 62 | ArkAngeL43/Rube-Ster | readme.py | Python | banner1 | banner1 | 37 | 43 | 37 | 37 | 8c663db6af3a459f21d1ad3c2467f5519b69229b | bigcode/the-stack | train |
499511c58b80291414197e14 | train | function | def oscheck():
if sys.platform == 'linux':
print(" hello 1 ")
if sys.platform == 'win-32':
def cs(X):
t.sleep(X)
os.system('cls')
if sys.platform == 'win-64':
... | def oscheck():
| if sys.platform == 'linux':
print(" hello 1 ")
if sys.platform == 'win-32':
def cs(X):
t.sleep(X)
os.system('cls')
if sys.platform == 'win-64':
... | import sys
init()
def cs(X):
t.sleep(X)
if sys.platform == 'linux':
os.system('clear')
if sys.platform == 'win-32':
os.system('cls')
if sys.platform == 'win-64':
os.system('cls')
def oscheck():
| 64 | 64 | 73 | 4 | 60 | ArkAngeL43/Rube-Ster | readme.py | Python | oscheck | oscheck | 21 | 31 | 21 | 21 | 1ee45728105e8b628f1257cb74efba92806169a7 | bigcode/the-stack | train |
5690d80a2421a71f0b08ac1c | train | function | def clear():
os.system(' clear ')
| def clear():
| os.system(' clear ')
| --(_)--Ooo------------------ooO-(_)---Ooo----ooO--(_)--Ooo-ooO--(_)--Ooo---------(_)-------- ")
if sys.platform == 'win32':
os.system('cls')
if sys.platform == 'linux':
os.system('clear')
def clear():
| 64 | 64 | 9 | 3 | 61 | ArkAngeL43/Rube-Ster | readme.py | Python | clear | clear | 49 | 50 | 49 | 49 | a1856b9f170607c409232d7c3ec08b7cc6f12a1b | bigcode/the-stack | train |
ab13f8fc41b43b9777a664ef | train | function | @pytest.mark.parametrize(
"rows_per_chunk, cols_per_chunk", [
(1, 2),
(len(df.index), len(df.columns)) # single chunk
])
def test_set_td_classes_chunked(rows_per_chunk, cols_per_chunk):
create_and_assert_patched_styler(
df,
lambda styler: styler.set_td_classes(classes),
... | @pytest.mark.parametrize(
"rows_per_chunk, cols_per_chunk", [
(1, 2),
(len(df.index), len(df.columns)) # single chunk
])
def test_set_td_classes_chunked(rows_per_chunk, cols_per_chunk):
| create_and_assert_patched_styler(
df,
lambda styler: styler.set_td_classes(classes),
rows_per_chunk,
cols_per_chunk
)
| "]
], index=df.index, columns=df.columns)
@pytest.mark.parametrize(
"rows_per_chunk, cols_per_chunk", [
(1, 2),
(len(df.index), len(df.columns)) # single chunk
])
def test_set_td_classes_chunked(rows_per_chunk, cols_per_chunk):
| 64 | 64 | 91 | 54 | 10 | rendner/py-plugin-dataframe-viewer | projects/python_plugin_code/pandas_1.3_code/tests/test_set_td_classes.py | Python | test_set_td_classes_chunked | test_set_td_classes_chunked | 36 | 47 | 36 | 41 | 1776c2fe47ad1b4bb81338ab1a2999e8f47081ff | bigcode/the-stack | train |
f53b07e11552a16fae1d98db | train | class | class SavedAppMapSearchGroup(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_... | class SavedAppMapSearchGroup(object):
| """NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
... | # coding: utf-8
"""
Wavefront REST API Documentation
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the W... | 175 | 256 | 1,886 | 8 | 166 | httpsgithu/python-client | wavefront_api_client/models/saved_app_map_search_group.py | Python | SavedAppMapSearchGroup | SavedAppMapSearchGroup | 22 | 282 | 22 | 22 | 74ff37416ee23f45c46db398613c427a503c81dc | bigcode/the-stack | train |
cba746ec18215367ce0cdbaf | train | function | def jacchiaFuncVel(t, a1, a2, a3, a4):
""" Predict the velocity from time using the Jacchia exponential function. """
return a2 - np.abs(a3*a4)*np.exp(np.abs(a4)*t)
| def jacchiaFuncVel(t, a1, a2, a3, a4):
| """ Predict the velocity from time using the Jacchia exponential function. """
return a2 - np.abs(a3*a4)*np.exp(np.abs(a4)*t)
| , a3, a4):
""" Predict the length from time using the Jacchia exponential function. """
return a1 + a2*t - np.abs(a3)*np.exp(np.abs(a4)*t)
def jacchiaFuncVel(t, a1, a2, a3, a4):
| 64 | 64 | 55 | 19 | 45 | markmac99/WesternMeteorPyLib | wmpl/Utils/PecinaCeplechaFunction.py | Python | jacchiaFuncVel | jacchiaFuncVel | 254 | 257 | 254 | 254 | f9644ad29ca4bd1e1fd1287e0ae5eeeaca9db0e7 | bigcode/the-stack | train |
a40b3c35cdf5dcf05d1f91d0 | train | function | def jacchiaFuncLen(t, a1, a2, a3, a4):
""" Predict the length from time using the Jacchia exponential function. """
return a1 + a2*t - np.abs(a3)*np.exp(np.abs(a4)*t)
| def jacchiaFuncLen(t, a1, a2, a3, a4):
| """ Predict the length from time using the Jacchia exponential function. """
return a1 + a2*t - np.abs(a3)*np.exp(np.abs(a4)*t)
| .integrate.quad(inv_vel_interp, l0, l)[0]
# Compute the final time
t = t0 + vel_integ
time_arr.append(t)
return np.array(time_arr)
def jacchiaFuncLen(t, a1, a2, a3, a4):
| 64 | 64 | 57 | 19 | 45 | markmac99/WesternMeteorPyLib | wmpl/Utils/PecinaCeplechaFunction.py | Python | jacchiaFuncLen | jacchiaFuncLen | 249 | 252 | 249 | 249 | 099e0624b7aafce89cb0212e6d0a3606464709b8 | bigcode/the-stack | train |
1a1f5946aed7b1bfe53102f0 | train | function | def htFromLen(l, c, zr):
""" Compute the height from the length, constant c, and the zenith angle zr.
Arguments:
l: [float] Length (km).
c: [float] Height-length constant (km).
zr: [float] Zenith angle (radians).
Return:
h: [float] Height in km.
"""
return (c... | def htFromLen(l, c, zr):
| """ Compute the height from the length, constant c, and the zenith angle zr.
Arguments:
l: [float] Length (km).
c: [float] Height-length constant (km).
zr: [float] Zenith angle (radians).
Return:
h: [float] Height in km.
"""
return (c - l)*np.cos(zr)
| , ht_data, len_target):
""" Residual function usef for finding the constant c and the zenith angle. """
c, zr = params
return np.sum((len_target - lenFromHt(ht_data, c, zr))**2)
def htFromLen(l, c, zr):
| 64 | 64 | 94 | 10 | 54 | markmac99/WesternMeteorPyLib | wmpl/Utils/PecinaCeplechaFunction.py | Python | htFromLen | htFromLen | 43 | 56 | 43 | 43 | 0543e8d469101aa9d2c6285e845dba80a4528926 | bigcode/the-stack | train |
03ecf5e1133962b00ab4b1f3 | train | function | def velFromHt(ht_arr, h0, v0, v_inf, sigma, c, zr, dens_interp):
""" Compute the velocity given the height and parameters as defined by Pecina & Ceplecha (1984) model.
Arugments:
ht_arr: [ndarray] Height in km.
h0: [float] Height of the reference point (seconds).
v0: [float] Veloci... | def velFromHt(ht_arr, h0, v0, v_inf, sigma, c, zr, dens_interp):
| """ Compute the velocity given the height and parameters as defined by Pecina & Ceplecha (1984) model.
Arugments:
ht_arr: [ndarray] Height in km.
h0: [float] Height of the reference point (seconds).
v0: [float] Velocity at the reference point (km/s).
v_inf: [float] Velocity... | _inf
v_bounds = [(0.1, 80)]
res = scipy.optimize.minimize(_diff, v_first_guess, args=(sigma, eiv_term), bounds=v_bounds)
# print()
# print("HT:", ht)
# print("Air integ:", air_dens_integ)
# print("E_vinf:", scipy.special.expi((sigma*v_inf**2)/6))
# print("EIV:",... | 173 | 173 | 578 | 25 | 148 | markmac99/WesternMeteorPyLib | wmpl/Utils/PecinaCeplechaFunction.py | Python | velFromHt | velFromHt | 133 | 194 | 133 | 133 | 17b51f9ddceb694e66b6442aaf282b4ac46db858 | bigcode/the-stack | train |
341be17af91d22023a50952a | train | function | def timeFromLen(len_arr, t0, l0, v0, v_inf, sigma, c, zr, dens_interp):
""" Compute the time given the length of a Pecina & Ceplecha (1984) model.
Arugments:
len_arr: [ndarray] Length in km.
t0: [float] Time of the reference point (seconds).
l0: [float] Length of the reference point (km... | def timeFromLen(len_arr, t0, l0, v0, v_inf, sigma, c, zr, dens_interp):
| """ Compute the time given the length of a Pecina & Ceplecha (1984) model.
Arugments:
len_arr: [ndarray] Length in km.
t0: [float] Time of the reference point (seconds).
l0: [float] Length of the reference point (km).
v0: [float] Velocity at the reference point (km/s).
v... | )
# Compute the square residual
return (eiv_target - eiv_guess)**2
v_first_guess = v_inf
v_bounds = [(0.1, 80)]
res = scipy.optimize.minimize(_diff, v_first_guess, args=(sigma, eiv_term), bounds=v_bounds)
vel = res.x[0]
###
# Store the velo... | 130 | 130 | 436 | 28 | 102 | markmac99/WesternMeteorPyLib | wmpl/Utils/PecinaCeplechaFunction.py | Python | timeFromLen | timeFromLen | 198 | 245 | 198 | 198 | 95c6313a67418ddc8c19707d219855a619839744 | bigcode/the-stack | train |
9601bd880b397865864eba52 | train | function | def lenFromHt(h, c, zr):
""" Compute the length from the height, constant c, and the zenith angle zr.
Arguments:
h: [float] Height in km.
c: [float] Height-length constant (km).
zr: [float] Zenith angle (radians).
Return:
l: [float] Length (km).
"""
l = c - h... | def lenFromHt(h, c, zr):
| """ Compute the length from the height, constant c, and the zenith angle zr.
Arguments:
h: [float] Height in km.
c: [float] Height-length constant (km).
zr: [float] Zenith angle (radians).
Return:
l: [float] Length (km).
"""
l = c - h/np.cos(zr)
return l... | scipy.integrate
import scipy.interpolate
from wmpl.Utils.AtmosphereDensity import atmDensPoly, fitAtmPoly
# Define the ceiling height (assumed to be h_inf in terms of the air density)
HT_CEILING = 180
def lenFromHt(h, c, zr):
| 64 | 64 | 98 | 10 | 53 | markmac99/WesternMeteorPyLib | wmpl/Utils/PecinaCeplechaFunction.py | Python | lenFromHt | lenFromHt | 16 | 31 | 16 | 16 | 9a3761aa7eaca89acf2452e0dc42b5ab0bad9548 | bigcode/the-stack | train |
ef41859018b02b6c2512b1aa | train | function | def velFromHtPhysicalParams(ht_arr, v_inf, m_inf, sigma, zr, K, dens_interp):
""" For the given height as meteoroid parameters, compute the velocity.
Arguments:
ht_arr: [ndarray] Height in meters.
v_inf: [float] Initial velocity in m/s.
m_inf: [float] Mass in kg.
sigma: [fl... | def velFromHtPhysicalParams(ht_arr, v_inf, m_inf, sigma, zr, K, dens_interp):
| """ For the given height as meteoroid parameters, compute the velocity.
Arguments:
ht_arr: [ndarray] Height in meters.
v_inf: [float] Initial velocity in m/s.
m_inf: [float] Mass in kg.
sigma: [float] Ablation coefficient in m^2/s^2.
zr: [float] Zenith angle (radian... | return l
def _lenFromHtResidual(params, ht_data, len_target):
""" Residual function usef for finding the constant c and the zenith angle. """
c, zr = params
return np.sum((len_target - lenFromHt(ht_data, c, zr))**2)
def htFromLen(l, c, zr):
""" Compute the height from the length, constant c, ... | 183 | 183 | 610 | 24 | 159 | markmac99/WesternMeteorPyLib | wmpl/Utils/PecinaCeplechaFunction.py | Python | velFromHtPhysicalParams | velFromHtPhysicalParams | 60 | 129 | 60 | 60 | a4a0193a8ec8a8ca138c891a661a9c93a9affbe7 | bigcode/the-stack | train |
51cb056434176ca8b6517728 | train | function | def fitPecinaCeplecha84Model(lat, lon, jd, time_data, ht_data, len_data, dens_interp=None, sigma_initial=0.03):
""" Fit the Pecina & Ceplecha (1984) model to the given data.
Arguments:
lat: [float] Latitude (radians).
Lon: [float] Longitude (radians).
jd: [float] Julian date of the... | def fitPecinaCeplecha84Model(lat, lon, jd, time_data, ht_data, len_data, dens_interp=None, sigma_initial=0.03):
| """ Fit the Pecina & Ceplecha (1984) model to the given data.
Arguments:
lat: [float] Latitude (radians).
Lon: [float] Longitude (radians).
jd: [float] Julian date of the event.
time_data: [ndarray] Relative time (seconds).
ht_data: [ndarray] Height (km).
le... | zip(len_arr, vel_arr):
# Interpolate the inverse velocity over length
inv_vel_interp = scipy.interpolate.CubicSpline(len_arr, 1.0/vel_arr)
# Integrate the velocity^-1 over length to compute the relative time from t0
vel_integ = scipy.integrate.quad(inv_vel_interp, l0, l)[0]
... | 256 | 256 | 1,707 | 36 | 220 | markmac99/WesternMeteorPyLib | wmpl/Utils/PecinaCeplechaFunction.py | Python | fitPecinaCeplecha84Model | fitPecinaCeplecha84Model | 261 | 429 | 261 | 261 | 3c198010d2085314d17df5cf20b9698244327cb6 | bigcode/the-stack | train |
266c433b0a6908e8c398ff1f | train | function | def _lenFromHtResidual(params, ht_data, len_target):
""" Residual function usef for finding the constant c and the zenith angle. """
c, zr = params
return np.sum((len_target - lenFromHt(ht_data, c, zr))**2)
| def _lenFromHtResidual(params, ht_data, len_target):
| """ Residual function usef for finding the constant c and the zenith angle. """
c, zr = params
return np.sum((len_target - lenFromHt(ht_data, c, zr))**2)
| ] Height-length constant (km).
zr: [float] Zenith angle (radians).
Return:
l: [float] Length (km).
"""
l = c - h/np.cos(zr)
return l
def _lenFromHtResidual(params, ht_data, len_target):
| 64 | 64 | 61 | 14 | 49 | markmac99/WesternMeteorPyLib | wmpl/Utils/PecinaCeplechaFunction.py | Python | _lenFromHtResidual | _lenFromHtResidual | 34 | 39 | 34 | 34 | 4633196cb9573bc8ebc17c0fc7a0c6df7634b584 | bigcode/the-stack | train |
ae3f276e4af406ec7df732ba | train | class | class Extraction:
def __init__(self, feature_dict = {}):
"""
parameters
-----------------------
feature_dict: dict parameters for the corresponding fingerprint type, say: {'AtomPairFP':{'nBits':2048}}
"""
if feature_dict == {}:
factory = mapk... | class Extraction:
| def __init__(self, feature_dict = {}):
"""
parameters
-----------------------
feature_dict: dict parameters for the corresponding fingerprint type, say: {'AtomPairFP':{'nBits':2048}}
"""
if feature_dict == {}:
factory = mapkey
self.fla... | PharmacoPFP',
GetPubChemFPs:'PubChemFP',
GetMHFP6:'MHFP6',
GetMAP4:'MAP4',
}
mapkey = dict(map(reversed, mapfunc.items()))
colors = sns.palettes.color_palette('hsv', n_colors=len(mapkey)).as_hex()
# sns.palplot(colors)
fps = ['MorganFP','RDkitFP', 'AtomPairFP','TorsionFP'... | 167 | 169 | 564 | 4 | 163 | riversdark/bidd-molmap | molmap/feature/fingerprint/__init__.py | Python | Extraction | Extraction | 49 | 124 | 49 | 50 | a51648a5039fd2e950344c9ceb3999a3423c94cd | bigcode/the-stack | train |
f766984b9122b0b566a484c8 | train | function | def read(*rnames):
with open(os.path.join(os.path.dirname(__file__), *rnames)) as f:
return f.read()
| def read(*rnames):
| with open(os.path.join(os.path.dirname(__file__), *rnames)) as f:
return f.read()
| docs.zope.org/zopetoolkit
# When developing and releasing this package, please follow the documented
# Zope Toolkit policies as described by this documentation.
##############################################################################
"""Setup for zope.app.rotterdam package."""
import os
from setuptools import set... | 64 | 64 | 30 | 6 | 57 | zopefoundation/zope.app.rotterdam | setup.py | Python | read | read | 24 | 26 | 24 | 24 | f71710ced4392bab76a8e726dfe7f02f242598a4 | bigcode/the-stack | train |
471d898e94197c7e43d06bdb | train | function | def main(*args):
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
@param args: command line arguments
@type args: str
"""
gen = None
xmlFilename = None
HTTPignore = []
# Process global args and prepare generator args parser
loc... | def main(*args):
| """
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
@param args: command line arguments
@type args: str
"""
gen = None
xmlFilename = None
HTTPignore = []
# Process global args and prepare generator args parser
local_args = pywikib... | ):
for ignoreR in ignorelist:
if ignoreR.match(url):
break
else:
# Each thread will check one page, then die.
thread = LinkCheckThread(page, url, self.history,
self.HTTPignore, self.day)
... | 225 | 225 | 751 | 5 | 219 | ModelTemplate/WarframeWikiBot | scripts/weblinkchecker.py | Python | main | main | 628 | 724 | 628 | 628 | a6d4b63c2fe675840d7d4f0cb6fbd74e7f76f0dc | bigcode/the-stack | train |
8e04ca70846d8a7717fc5504 | train | function | def get_archive_url(url):
"""Get archive URL."""
try:
archive = _get_closest_memento_url(
url,
timegate_uri='http://web.archive.org/web/')
except Exception:
archive = _get_closest_memento_url(
url,
timegate_uri='http://timetravel.mementoweb.org... | def get_archive_url(url):
| """Get archive URL."""
try:
archive = _get_closest_memento_url(
url,
timegate_uri='http://web.archive.org/web/')
except Exception:
archive = _get_closest_memento_url(
url,
timegate_uri='http://timetravel.mementoweb.org/webcite/timegate/')
... | timegate_uri))
if 'uri' not in mementos['closest']:
raise Exception(
'closest memento uri not found for {0} via {1}'.format(
url, timegate_uri))
return mementos['closest']['uri'][0]
def get_archive_url(url):
| 64 | 64 | 131 | 6 | 58 | ModelTemplate/WarframeWikiBot | scripts/weblinkchecker.py | Python | get_archive_url | get_archive_url | 211 | 225 | 211 | 211 | d9544d34ea4c46b48d09ea75bb3322aae8ffb375 | bigcode/the-stack | train |
7b44bcaf4625665e2d647c85 | train | function | def _get_closest_memento_url(url, when=None, timegate_uri=None):
"""Get most recent memento for url."""
if isinstance(memento_client, ImportError):
raise memento_client
if not when:
when = datetime.datetime.now()
mc = memento_client.MementoClient()
if timegate_uri:
mc.timeg... | def _get_closest_memento_url(url, when=None, timegate_uri=None):
| """Get most recent memento for url."""
if isinstance(memento_client, ImportError):
raise memento_client
if not when:
when = datetime.datetime.now()
mc = memento_client.MementoClient()
if timegate_uri:
mc.timegate_uri = timegate_uri
retry_count = 0
while retry_count... | Z]]
# bot can't handle their redirects:
# bot rejected on the site, already archived
re.compile(r'.*[\./@]web\.archive\.org(/.*)?'),
# Ignore links containing * in domain name
# as they are intentionally fake
re.compile(r'https?\:\/\/\*(/.*)?'),
]
def _get_closest_memento_url(url, when=None, t... | 90 | 90 | 303 | 18 | 72 | ModelTemplate/WarframeWikiBot | scripts/weblinkchecker.py | Python | _get_closest_memento_url | _get_closest_memento_url | 172 | 208 | 172 | 172 | 8e018c0abcd09aacc651165dc8b05c387da4ed19 | bigcode/the-stack | train |
0dd7aa43298cb1f08b77e087 | train | class | class NotAnURLError(BaseException):
"""The link is not an URL."""
| class NotAnURLError(BaseException):
| """The link is not an URL."""
| m in linkR.finditer(text):
if m.group('url'):
yield m.group('url')
else:
yield m.group('urlb')
XmlDumpPageGenerator = partial(
_XMLDumpPageGenerator, text_predicate=weblinksIn)
class NotAnURLError(BaseException):
| 64 | 64 | 17 | 8 | 56 | ModelTemplate/WarframeWikiBot | scripts/weblinkchecker.py | Python | NotAnURLError | NotAnURLError | 274 | 276 | 274 | 275 | fab54817278ab89a963ee747cf2af00720775174 | bigcode/the-stack | train |
2bff67ba72effcf843bcbf8e | train | class | class LinkCheckThread(threading.Thread):
"""A thread responsible for checking one URL.
After checking the page, it will die.
"""
def __init__(self, page, url, history, HTTPignore, day):
"""Initializer."""
super().__init__()
self.page = page
self.url = url
self.... | class LinkCheckThread(threading.Thread):
| """A thread responsible for checking one URL.
After checking the page, it will die.
"""
def __init__(self, page, url, history, HTTPignore, day):
"""Initializer."""
super().__init__()
self.page = page
self.url = url
self.history = history
self.header = {
... | would not be correct
text = text.replace('}}', ' }}')
# Remove HTML comments in URLs as well as URLs in HTML comments.
# Also remove text inside nowiki links etc.
text = textlib.removeDisabledParts(text)
linkR = textlib.compileLinkR(withoutBracketed, onlyBracketed)
for m in linkR.finditer(text... | 153 | 154 | 514 | 8 | 145 | ModelTemplate/WarframeWikiBot | scripts/weblinkchecker.py | Python | LinkCheckThread | LinkCheckThread | 279 | 335 | 279 | 280 | 61d5e45104fbd30e2b8e8d30eb46562547d78fe6 | bigcode/the-stack | train |
5a5702de809b55275024759d | train | function | def RepeatPageGenerator():
"""Generator for pages in History."""
history = History(None)
pageTitles = set()
for value in history.historyDict.values():
for entry in value:
pageTitles.add(entry[0])
for pageTitle in sorted(pageTitles):
page = pywikibot.Page(pywikibot.Site(),... | def RepeatPageGenerator():
| """Generator for pages in History."""
history = History(None)
pageTitles = set()
for value in history.historyDict.values():
for entry in value:
pageTitles.add(entry[0])
for pageTitle in sorted(pageTitles):
page = pywikibot.Page(pywikibot.Site(), pageTitle)
yield p... |
else:
# Each thread will check one page, then die.
thread = LinkCheckThread(page, url, self.history,
self.HTTPignore, self.day)
# thread dies when program terminates
thread.setDaemon(True)
... | 64 | 64 | 79 | 5 | 59 | ModelTemplate/WarframeWikiBot | scripts/weblinkchecker.py | Python | RepeatPageGenerator | RepeatPageGenerator | 603 | 612 | 603 | 603 | b23c1119328f62c866512b5d2bac71486a8254e5 | bigcode/the-stack | train |
ff92ad4f553f00c33998a8e0 | train | class | class History:
"""
Store previously found dead links.
The URLs are dictionary keys, and
values are lists of tuples where each tuple represents one time the URL was
found dead. Tuples have the form (title, date, error) where title is the
wiki page where the URL was found, date is an instance of... | class History:
| """
Store previously found dead links.
The URLs are dictionary keys, and
values are lists of tuples where each tuple represents one time the URL was
found dead. Tuples have the form (title, date, error) where title is the
wiki page where the URL was found, date is an instance of time, and error... | weblinkchecker', False)
self.day = day
def run(self):
"""Run the bot."""
try:
header = self.header
r = comms.http.fetch(
self.url, headers=header,
use_fake_user_agent=self._use_fake_user_agent)
except requests.exceptions.Invali... | 255 | 256 | 1,103 | 3 | 252 | ModelTemplate/WarframeWikiBot | scripts/weblinkchecker.py | Python | History | History | 338 | 457 | 338 | 339 | 1ad74fbdbc1215b7bf0341a8c544c05d557ee52a | bigcode/the-stack | train |
88468a7d68f683c9e7bb5fd9 | train | class | class DeadLinkReportThread(threading.Thread):
"""
A Thread that is responsible for posting error reports on talk pages.
There is only one DeadLinkReportThread, and it is using a semaphore to make
sure that two LinkCheckerThreads can not access the queue at the same time.
"""
def __init__(self... | class DeadLinkReportThread(threading.Thread):
| """
A Thread that is responsible for posting error reports on talk pages.
There is only one DeadLinkReportThread, and it is using a semaphore to make
sure that two LinkCheckerThreads can not access the queue at the same time.
"""
def __init__(self):
"""Initializer."""
super()._... | # search for archived page
try:
archiveURL = get_archive_url(url)
except Exception as e:
pywikibot.warning(
'get_closest_memento_url({0}) failed: {1}'.format(
... | 228 | 228 | 760 | 9 | 219 | ModelTemplate/WarframeWikiBot | scripts/weblinkchecker.py | Python | DeadLinkReportThread | DeadLinkReportThread | 460 | 556 | 460 | 461 | c26b49d68b1926e333c3948d13a14440b9527e73 | bigcode/the-stack | train |
9544756105c02386cb2707d5 | train | function | def countLinkCheckThreads() -> int:
"""
Count LinkCheckThread threads.
@return: number of LinkCheckThread threads
"""
i = 0
for thread in threading.enumerate():
if isinstance(thread, LinkCheckThread):
i += 1
return i
| def countLinkCheckThreads() -> int:
| """
Count LinkCheckThread threads.
@return: number of LinkCheckThread threads
"""
i = 0
for thread in threading.enumerate():
if isinstance(thread, LinkCheckThread):
i += 1
return i
| ()
for value in history.historyDict.values():
for entry in value:
pageTitles.add(entry[0])
for pageTitle in sorted(pageTitles):
page = pywikibot.Page(pywikibot.Site(), pageTitle)
yield page
def countLinkCheckThreads() -> int:
| 64 | 64 | 64 | 9 | 54 | ModelTemplate/WarframeWikiBot | scripts/weblinkchecker.py | Python | countLinkCheckThreads | countLinkCheckThreads | 615 | 625 | 615 | 615 | 3753741ec67c9276d97fd116d6c42f714fd29f3f | bigcode/the-stack | train |
5dd7b89426d42b3667ceabb5 | train | class | class WeblinkCheckerRobot(SingleSiteBot, ExistingPageBot):
"""
Bot which will search for dead weblinks.
It uses several LinkCheckThreads at once to process pages from generator.
"""
def __init__(self, generator, HTTPignore=None, day=7, site=True):
"""Initializer."""
super().__init... | class WeblinkCheckerRobot(SingleSiteBot, ExistingPageBot):
| """
Bot which will search for dead weblinks.
It uses several LinkCheckThreads at once to process pages from generator.
"""
def __init__(self, generator, HTTPignore=None, day=7, site=True):
"""Initializer."""
super().__init__(generator=generator, site=site)
if config.report... | ainingPage.site,
'weblinkchecker-summary'))
try:
talkPage.put(content, comment)
except pywikibot.SpamblacklistError as error:
pywikibot.output(color_format(
'{lightaqua}** SpamblacklistEr... | 92 | 92 | 309 | 14 | 78 | ModelTemplate/WarframeWikiBot | scripts/weblinkchecker.py | Python | WeblinkCheckerRobot | WeblinkCheckerRobot | 559 | 600 | 559 | 560 | de65204c31dad1ae9774a827dce04c23eaf3d635 | bigcode/the-stack | train |
f247351cb5f718e3bca5ab74 | train | function | def weblinksIn(text, withoutBracketed=False, onlyBracketed=False):
"""
Yield web links from text.
TODO: move to textlib
"""
text = textlib.removeDisabledParts(text)
# Ignore links in fullurl template
text = re.sub(r'{{\s?fullurl:.[^}]*}}', '', text)
# MediaWiki parses templates before... | def weblinksIn(text, withoutBracketed=False, onlyBracketed=False):
| """
Yield web links from text.
TODO: move to textlib
"""
text = textlib.removeDisabledParts(text)
# Ignore links in fullurl template
text = re.sub(r'{{\s?fullurl:.[^}]*}}', '', text)
# MediaWiki parses templates before parsing external links. Thus, there
# might be a | or a } dire... | timegate_uri='http://web.archive.org/web/')
except Exception:
archive = _get_closest_memento_url(
url,
timegate_uri='http://timetravel.mementoweb.org/webcite/timegate/')
# FIXME: Hack for T167463: Use https instead of http for archive.org links
if archive.startsw... | 119 | 119 | 398 | 17 | 101 | ModelTemplate/WarframeWikiBot | scripts/weblinkchecker.py | Python | weblinksIn | weblinksIn | 228 | 267 | 228 | 228 | 69cfe2d8f8d8972873506d650d5ad39f332f0f3c | bigcode/the-stack | train |
14db0b3f41a6d35d581202cc | train | class | class ComplexCLI(click.MultiCommand):
def list_commands(self, ctx):
rv = []
for filename in os.listdir(cmd_folder):
if filename.endswith(".py") and filename.startswith("cmd_"):
rv.append(filename[4:-3])
rv.sort()
return rv
def get_command(self, ctx, n... | class ComplexCLI(click.MultiCommand):
| def list_commands(self, ctx):
rv = []
for filename in os.listdir(cmd_folder):
if filename.endswith(".py") and filename.startswith("cmd_"):
rv.append(filename[4:-3])
rv.sort()
return rv
def get_command(self, ctx, name):
try:
mod = _... | """Logs a message to stderr only if verbose is enabled."""
if self.verbose:
self.log(msg, *args)
pass_environment = click.make_pass_decorator(Environment, ensure=True)
cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), "commands"))
class ComplexCLI(click.MultiCommand):
| 63 | 64 | 106 | 7 | 56 | M-o-a-T/trio-click | examples/complex/complex/cli.py | Python | ComplexCLI | ComplexCLI | 31 | 45 | 31 | 31 | de61f51e4f94e411555095a2bd2c1d5420791fac | bigcode/the-stack | train |
58f773008e904b79058e2019 | train | function | @click.command(cls=ComplexCLI, context_settings=CONTEXT_SETTINGS)
@click.option(
"--home",
type=click.Path(exists=True, file_okay=False, resolve_path=True),
help="Changes the folder to operate on.",
)
@click.option("-v", "--verbose", is_flag=True, help="Enables verbose mode.")
@pass_environment
def cli(ctx,... | @click.command(cls=ComplexCLI, context_settings=CONTEXT_SETTINGS)
@click.option(
"--home",
type=click.Path(exists=True, file_okay=False, resolve_path=True),
help="Changes the folder to operate on.",
)
@click.option("-v", "--verbose", is_flag=True, help="Enables verbose mode.")
@pass_environment
def cli(ctx,... | """A complex command line interface."""
ctx.verbose = verbose
if home is not None:
ctx.home = home
| @click.command(cls=ComplexCLI, context_settings=CONTEXT_SETTINGS)
@click.option(
"--home",
type=click.Path(exists=True, file_okay=False, resolve_path=True),
help="Changes the folder to operate on.",
)
@click.option("-v", "--verbose", is_flag=True, help="Enables verbose mode.")
@pass_environment
def cli(ctx,... | 81 | 64 | 108 | 81 | 0 | M-o-a-T/trio-click | examples/complex/complex/cli.py | Python | cli | cli | 48 | 60 | 48 | 56 | c4b97b8c5ce0751223c6c702af7d957eae6a4596 | bigcode/the-stack | train |
d69d3d2315046fab489e2d3d | train | class | class Environment:
def __init__(self):
self.verbose = False
self.home = os.getcwd()
def log(self, msg, *args):
"""Logs a message to stderr."""
if args:
msg %= args
click.echo(msg, file=sys.stderr)
def vlog(self, msg, *args):
"""Logs a message to ... | class Environment:
| def __init__(self):
self.verbose = False
self.home = os.getcwd()
def log(self, msg, *args):
"""Logs a message to stderr."""
if args:
msg %= args
click.echo(msg, file=sys.stderr)
def vlog(self, msg, *args):
"""Logs a message to stderr only if verb... | import os
import sys
import asyncclick as click
CONTEXT_SETTINGS = dict(auto_envvar_prefix="COMPLEX")
class Environment:
| 31 | 64 | 95 | 3 | 28 | M-o-a-T/trio-click | examples/complex/complex/cli.py | Python | Environment | Environment | 10 | 24 | 10 | 10 | 98d97bf5091cdd430daf3bb01a9c02f30e6bd435 | bigcode/the-stack | train |
e0e75ef5c8c470b35a109df6 | train | class | class TestFlexbox_Flex0NNShrink(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'flexbox_flex-0-N-N-shrink'))
| class TestFlexbox_Flex0NNShrink(W3CTestCase):
| vars().update(W3CTestCase.find_tests(__file__, 'flexbox_flex-0-N-N-shrink'))
| from tests.utils import W3CTestCase
class TestFlexbox_Flex0NNShrink(W3CTestCase):
| 25 | 64 | 41 | 16 | 8 | fletchgraham/colosseum | tests/web_platform/css_flexbox_1/test_flexbox_flex_0_N_N_shrink.py | Python | TestFlexbox_Flex0NNShrink | TestFlexbox_Flex0NNShrink | 3 | 4 | 3 | 3 | 410d659984bf0f1e2b5120118d8f61186c0e9421 | bigcode/the-stack | train |
2a3bb2f6755dd442fe3dd2ff | train | function | def main():
"""Testing 'jedi' package"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-v",
"--verbosity",
dest="verbosity",
action="count",
default=0,
help="set verbosity level",
)
args = parser.parse_args()
if args.verbosity == 1:
... | def main():
| """Testing 'jedi' package"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-v",
"--verbosity",
dest="verbosity",
action="count",
default=0,
help="set verbosity level",
)
args = parser.parse_args()
if args.verbosity == 1:
logging... | BMS®"
# - "This product includes parts of foxBMS®"
# - "This product is derived from foxBMS®"
"""Testing 'jedi' package"""
import logging
import argparse
# package to test
import jedi # pylint: disable=unused-import
def main():
| 64 | 64 | 108 | 3 | 60 | patkan/foxbms-2 | tests/env/packages/env_test_jedi.py | Python | main | main | 50 | 68 | 50 | 50 | c1c88c70b7669ad55ee7ff06868a2221e487db0b | bigcode/the-stack | train |
f1f09b6fabad199257cca397 | train | function | @pytest.mark.version('>=2.5')
def test_1(act_1: Action, temp_db_1: Path):
test_script = f"""
set sql dialect 1;
create database 'localhost:{str(temp_db_1)}' page_size 4096 default character set win1251 collation win1251;
set list on;
select mon$sql_dialect as x from mon$database;
"""
act_1.expec... | @pytest.mark.version('>=2.5')
def test_1(act_1: Action, temp_db_1: Path):
| test_script = f"""
set sql dialect 1;
create database 'localhost:{str(temp_db_1)}' page_size 4096 default character set win1251 collation win1251;
set list on;
select mon$sql_dialect as x from mon$database;
"""
act_1.expected_stdout = expected_stdout_1
act_1.isql(switches=[], input=test_scri... | ', substitutions=substitutions_1)
expected_stdout_1 = """
X 1
"""
temp_db_1 = temp_file('tmp_4067_1.fdb')
@pytest.mark.version('>=2.5')
def test_1(act_1: Action, temp_db_1: Path):
| 64 | 64 | 133 | 26 | 38 | FirebirdSQL/firebird-qa | tests/bugs/core_4067_test.py | Python | test_1 | test_1 | 72 | 82 | 72 | 73 | fcaf861913beb8fec8b52358bc0cf4acf4f4c61b | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.