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
53aa7e976445c4408b97a00c
train
function
@websocket_api.websocket_command( {vol.Required("type"): "mqtt/device/debug_info", vol.Required("device_id"): str} ) @websocket_api.async_response async def websocket_mqtt_info(hass, connection, msg): """Get MQTT debug info for device.""" device_id = msg["device_id"] mqtt_info = await debug_info.info_fo...
@websocket_api.websocket_command( {vol.Required("type"): "mqtt/device/debug_info", vol.Required("device_id"): str} ) @websocket_api.async_response async def websocket_mqtt_info(hass, connection, msg):
"""Get MQTT debug info for device.""" device_id = msg["device_id"] mqtt_info = await debug_info.info_for_device(hass, device_id) connection.send_result(msg["id"], mqtt_info)
return lambda topic: next(matcher.iter_match(topic), False) @websocket_api.websocket_command( {vol.Required("type"): "mqtt/device/debug_info", vol.Required("device_id"): str} ) @websocket_api.async_response async def websocket_mqtt_info(hass, connection, msg):
64
64
94
49
15
mikan-megane/core
homeassistant/components/mqtt/__init__.py
Python
websocket_mqtt_info
websocket_mqtt_info
977
986
977
981
740252911395742543b60f18ad3bd9934c41ff9a
bigcode/the-stack
train
ee154838126e38dbd9fceaf4
train
function
def _merge_config(entry, conf): """Merge configuration.yaml config with config entry.""" return {**conf, **entry.data}
def _merge_config(entry, conf):
"""Merge configuration.yaml config with config entry.""" return {**conf, **entry.data}
Only import if we haven't before. if not hass.config_entries.async_entries(DOMAIN): hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data={} ) ) return True def _merge_config(entry, co...
64
64
28
8
55
mikan-megane/core
homeassistant/components/mqtt/__init__.py
Python
_merge_config
_merge_config
422
424
422
422
92de4d90d7af755a94204fac2ff236a968b35c21
bigcode/the-stack
train
58fc22ff7c7df52df81f0ed3
train
function
def embedded_broker_deprecated(value): """Warn user that embedded MQTT broker is deprecated.""" _LOGGER.warning( "The embedded MQTT broker has been deprecated and will stop working" "after June 5th, 2019. Use an external broker instead. For" "instructions, see https://www.home-assistant....
def embedded_broker_deprecated(value):
"""Warn user that embedded MQTT broker is deprecated.""" _LOGGER.warning( "The embedded MQTT broker has been deprecated and will stop working" "after June 5th, 2019. Use an external broker instead. For" "instructions, see https://www.home-assistant.io/docs/mqtt/broker" ) return v...
(ATTR_PAYLOAD, "topic_payload"): cv.string, vol.Optional(ATTR_QOS, default=DEFAULT_QOS): _VALID_QOS_SCHEMA, vol.Optional(ATTR_RETAIN, default=DEFAULT_RETAIN): cv.boolean, }, required=True, ) def embedded_broker_deprecated(value):
64
64
82
8
56
mikan-megane/core
homeassistant/components/mqtt/__init__.py
Python
embedded_broker_deprecated
embedded_broker_deprecated
148
155
148
148
391e665091fcc625b48c3ff307bed3d3dc7c2cfc
bigcode/the-stack
train
92ec616c835b5623ca536bc5
train
function
async def _async_setup_discovery( hass: HomeAssistant, conf: ConfigType, config_entry ) -> bool: """Try to start the discovery of MQTT devices. This method is a coroutine. """ success: bool = await discovery.async_start( hass, conf[CONF_DISCOVERY_PREFIX], config_entry ) return succ...
async def _async_setup_discovery( hass: HomeAssistant, conf: ConfigType, config_entry ) -> bool:
"""Try to start the discovery of MQTT devices. This method is a coroutine. """ success: bool = await discovery.async_start( hass, conf[CONF_DISCOVERY_PREFIX], config_entry ) return success
, encoding), hass.loop ).result() def remove(): """Remove listener convert.""" run_callback_threadsafe(hass.loop, async_remove).result() return remove async def _async_setup_discovery( hass: HomeAssistant, conf: ConfigType, config_entry ) -> bool:
64
64
75
26
37
mikan-megane/core
homeassistant/components/mqtt/__init__.py
Python
_async_setup_discovery
_async_setup_discovery
380
391
380
382
657e39abbed5496fadf07ce56ec375fcbae3d146
bigcode/the-stack
train
407856b9f408002f827bfccb
train
class
@attr.s(slots=True, frozen=True) class Subscription: """Class to hold data about an active subscription.""" topic: str = attr.ib() matcher: Any = attr.ib() job: HassJob = attr.ib() qos: int = attr.ib(default=0) encoding: str = attr.ib(default="utf-8")
@attr.s(slots=True, frozen=True) class Subscription:
"""Class to hold data about an active subscription.""" topic: str = attr.ib() matcher: Any = attr.ib() job: HassJob = attr.ib() qos: int = attr.ib(default=0) encoding: str = attr.ib(default="utf-8")
"): valid_subscribe_topic, vol.Optional("duration", default=5): int, } ), ) if conf.get(CONF_DISCOVERY): await _async_setup_discovery(hass, conf, entry) return True @attr.s(slots=True, frozen=True) class Subscription:
64
64
73
13
50
mikan-megane/core
homeassistant/components/mqtt/__init__.py
Python
Subscription
Subscription
535
543
535
536
718ee5b3831d10dda44cdc06cdb201f5359a5363
bigcode/the-stack
train
bc48d1e267aa6ef1492ee8ce
train
function
def setup(bot): bot.add_cog(Audio(bot))
def setup(bot):
bot.add_cog(Audio(bot))
None: await self.play_clip(introclip, after.channel) await self.play_clip("tts:" + text, after.channel) except UserError as e: logger.error(f"Bad voice channel connection to ({channel_id}) from on_voice_state_update: {e.message}") def setup(bot):
63
64
12
4
59
uncledu/MangoByte
cogs/audio.py
Python
setup
setup
696
697
696
696
f803caa77b69dba9f43c599bbe5639ad5392c804
bigcode/the-stack
train
93ee2d7e398a8218908b78ea
train
function
def remove_if_temp(mp3name): if os.path.isfile(mp3name): if os.path.dirname(mp3name) == settings.resource("temp"): os.remove(mp3name) logger.info("removed temp file " + mp3name)
def remove_if_temp(mp3name):
if os.path.isfile(mp3name): if os.path.dirname(mp3name) == settings.resource("temp"): os.remove(mp3name) logger.info("removed temp file " + mp3name)
tsChannelError(Exception): def __init__(self, error): self.message = "Errored in the tts channel" self.original = error class AudioPlayerNotFoundError(UserError): def __init__(self, message): super().__init__(message) def remove_if_temp(mp3name):
64
64
51
8
56
uncledu/MangoByte
cogs/audio.py
Python
remove_if_temp
remove_if_temp
37
41
37
37
db787af5ac0a82dd14f349e73766f8f603d8ce13
bigcode/the-stack
train
d22a556d990969fb6002d6d0
train
class
class AudioPlayerNotFoundError(UserError): def __init__(self, message): super().__init__(message)
class AudioPlayerNotFoundError(UserError):
def __init__(self, message): super().__init__(message)
24 * 4 means after 4 days of inactivity, mango will disconnect from the voice channel class TtsChannelError(Exception): def __init__(self, error): self.message = "Errored in the tts channel" self.original = error class AudioPlayerNotFoundError(UserError):
64
64
24
9
54
uncledu/MangoByte
cogs/audio.py
Python
AudioPlayerNotFoundError
AudioPlayerNotFoundError
33
35
33
33
09eceb842163f194cc6f576d2cf7ec294418b696
bigcode/the-stack
train
e300dd5def6d290317b97f5e
train
class
class Audio(MangoCog): """For playing audio in a voice channel The mangobyte audio system uses things called 'clips'. For more info on these, check out `/docs Clips`""" def __init__(self, bot): MangoCog.__init__(self, bot) self.start_time = datetime.datetime.now() self.last_played_audio = {} # dict of the la...
class Audio(MangoCog):
"""For playing audio in a voice channel The mangobyte audio system uses things called 'clips'. For more info on these, check out `/docs Clips`""" def __init__(self, bot): MangoCog.__init__(self, bot) self.start_time = datetime.datetime.now() self.last_played_audio = {} # dict of the last time audio was playe...
play_next_clip(self): clip = self.next_clip() try: self.voice.play(disnake.FFmpegPCMAudio(clip.audiopath), after=self.done_talking) except disnake.errors.ClientException as e: if str(e) == "Not connected to voice.": raise UserError("Error playing clip. Try doing `?resummon`.") else: raise se...
256
256
5,155
6
250
uncledu/MangoByte
cogs/audio.py
Python
Audio
Audio
148
693
148
148
ed6b6e99582857bb3ec98ff68c8daf55b5f8fc99
bigcode/the-stack
train
4b1a380eb5ccccfd58a85a33
train
class
class AudioPlayer: """The guild-specific objects used for mangobyte's audio output""" def __init__(self, bot, guild): self.bot = bot self.guild_id = guild.id self.guild = guild self.player = None self.clipqueue = queue.Queue() self.last_clip = None @property def voice(self): return self.guild.voice_c...
class AudioPlayer:
"""The guild-specific objects used for mangobyte's audio output""" def __init__(self, bot, guild): self.bot = bot self.guild_id = guild.id self.guild = guild self.player = None self.clipqueue = queue.Queue() self.last_clip = None @property def voice(self): return self.guild.voice_client @property ...
import report_error from cogs.mangocog import * CLIPS_ITEMS_PER_PAGE = 20 URL_CLIP_ERROR_MESSAGE = "Unfortunatley I'm removing the url clip feature for now. I've got plans to eventually implement some custom clips that will be even more flexible than this, but I'm not sure when that feature will arrive." intro_outr...
227
227
759
4
223
uncledu/MangoByte
cogs/audio.py
Python
AudioPlayer
AudioPlayer
44
144
44
44
02f720b43a3570fc03a1b25ebf604c95e0493b20
bigcode/the-stack
train
de0cd92c942604b7eabddc9e
train
class
class TtsChannelError(Exception): def __init__(self, error): self.message = "Errored in the tts channel" self.original = error
class TtsChannelError(Exception):
def __init__(self, error): self.message = "Errored in the tts channel" self.original = error
than this, but I'm not sure when that feature will arrive." intro_outro_length = 4.5 voice_channel_culling_timeout_hours = 24 * 4 # 24 * 4 means after 4 days of inactivity, mango will disconnect from the voice channel class TtsChannelError(Exception):
64
64
34
7
56
uncledu/MangoByte
cogs/audio.py
Python
TtsChannelError
TtsChannelError
28
31
28
28
7ed0fdccae4733ca65ae9882f089543ce8e660c7
bigcode/the-stack
train
f50ae66e3a7e75b17ec347e7
train
function
def walk(): """Performs one cycle in the pipeline""" # 1. Fetch most recent record for the intended user (which is also the paper-to-read) print(f'Fetching paper-to-read for {USER_EMAIL}') paper_to_read = mongo_obj.get_recent(USER_EMAIL) paper_id = paper_to_read['paper_id'] print(f'Found pa...
def walk():
"""Performs one cycle in the pipeline""" # 1. Fetch most recent record for the intended user (which is also the paper-to-read) print(f'Fetching paper-to-read for {USER_EMAIL}') paper_to_read = mongo_obj.get_recent(USER_EMAIL) paper_id = paper_to_read['paper_id'] print(f'Found paper_id {pape...
) import information_extraction from mongo_utils import MongoUtils from dotenv import load_dotenv; load_dotenv() from mail_sender import send_mail from utils import get_current_time, sample_next_paper, compose_paper_url, get_binary_img # Loading environment variables USER_EMAIL = os.getenv('USER_EMAIL') # Initializi...
86
86
288
3
83
harshit158/paper-dots
src/paper_walk.py
Python
walk
walk
29
59
29
29
9fdf9b8e046bef0658c316b850b27ac843c2a314
bigcode/the-stack
train
6ecb6b64a51b5c13c7671468
train
function
def lumiDataFromDB(sourceschema,sourcelumidataid): ''' select nominalegev,ncollidingbunches,starttime,stoptime,nls from lumidata where DATA_ID=:dataid select lumilsnum,cmslsnum,beamstatus,beamenergy,numorbit,startorbit,instlumi,cmsbxindexblob,beamintensityblob_1,beamintensityblob_2,bxlumivalue_occ1,bxlumiva...
def lumiDataFromDB(sourceschema,sourcelumidataid):
''' select nominalegev,ncollidingbunches,starttime,stoptime,nls from lumidata where DATA_ID=:dataid select lumilsnum,cmslsnum,beamstatus,beamenergy,numorbit,startorbit,instlumi,cmsbxindexblob,beamintensityblob_1,beamintensityblob_2,bxlumivalue_occ1,bxlumivalue_occ2,bxlumivalue_et,bxlumierror_occ1,bxlumierro...
optime perlsresult={}#{lumilsnum:instlumiub} ''' perrunresult=[]#source,starttime,stoptime perlsresult={}#{lumilsnum:instlumiub} csv_data=open(filename) csvreader=csv.reader(csv_data,delimiter=',') idx=0 ts=[] for row in csvreader: if idx==0: idx=1 ...
256
256
2,379
15
241
bisnupriyasahu/cmssw
RecoLuminosity/LumiDB/test/patchkit/csvLumiLoader.py
Python
lumiDataFromDB
lumiDataFromDB
119
273
119
119
1ea4e07a5591e739edb44837cc80c4bd7e851cf4
bigcode/the-stack
train
9fd31d14709107bc74d8cad1
train
function
def lumiDataFromfile(filename): ''' input:bcm1f lumi csv file output:(perrunresult,perlsresult) perrunresult=[]#source,starttime,stoptime perlsresult={}#{lumilsnum:instlumiub} ''' perrunresult=[]#source,starttime,stoptime perlsresult={}#{lumilsnum:instlumiub} csv_data...
def lumiDataFromfile(filename):
''' input:bcm1f lumi csv file output:(perrunresult,perlsresult) perrunresult=[]#source,starttime,stoptime perlsresult={}#{lumilsnum:instlumiub} ''' perrunresult=[]#source,starttime,stoptime perlsresult={}#{lumilsnum:instlumiub} csv_data=open(filename) csvread...
blob_1,beamintensityblob_2,bxlumivalue_occ1,bxlumierror_occ1,bxlumiquality_occ1,bxlumivalue_occ2,bxlumierror_occ2,bxlumiquality_occ2,bxlumivalue_et,bxlumierror_et,bxlumiquality_et] return (lumirundata,lumilsdata) def lumiDataFromfile(filename):
84
84
282
7
77
bisnupriyasahu/cmssw
RecoLuminosity/LumiDB/test/patchkit/csvLumiLoader.py
Python
lumiDataFromfile
lumiDataFromfile
85
117
85
85
cade11ad1cbc4d3f085ff7c426239fe752add393
bigcode/the-stack
train
86e5f75439734fe58343f341
train
function
def generateLumidata(lumirundatafromfile,lsdatafromfile,rundatafromdb,lsdatafromdb,replacelsMin,replacelsMax): ''' input: perrunresultfromfile=[]#source,starttime,stoptime,nls perlsresultfromfile={} #{lumilsnum:instlumiub} lumirundatafromdb=[] #[source,nominalegev,ncollidingbunches,starttime,st...
def generateLumidata(lumirundatafromfile,lsdatafromfile,rundatafromdb,lsdatafromdb,replacelsMin,replacelsMax):
''' input: perrunresultfromfile=[]#source,starttime,stoptime,nls perlsresultfromfile={} #{lumilsnum:instlumiub} lumirundatafromdb=[] #[source,nominalegev,ncollidingbunches,starttime,stoptime,nls] lumilsdatafromdb={}#{lumilsnum:[cmslsnum(0),instlumi(1),instlumierror(2),instlumiquality(3),be...
#!/usr/bin/env python from __future__ import print_function from builtins import range import os,os.path,sys,time,csv,array,coral from RecoLuminosity.LumiDB import sessionManager,argparse,nameDealer,revisionDML,dataDML,lumiParameters,CommonUtil,lumiTime def generateLumidata(lumirundatafromfile,lsdatafromfile,rundatafro...
103
256
1,248
35
67
bisnupriyasahu/cmssw
RecoLuminosity/LumiDB/test/patchkit/csvLumiLoader.py
Python
generateLumidata
generateLumidata
8
83
8
8
e8e6247e767e662c713c0d9942317588b8202519
bigcode/the-stack
train
d871bec46529cc065feb5e85
train
function
def assign_values(): module = sys.modules[__name__] for key, value in VALUES.items(): module.__dict__[key] = value
def assign_values():
module = sys.modules[__name__] for key, value in VALUES.items(): module.__dict__[key] = value
load_args(): for key, value in zip(sys.argv[1:-1], sys.argv[2:]): if key.startswith('--'): key = key[2:] if key in VALUES: create_value = type(VALUES[key]) VALUES[key] = create_value(value) def assign_values():
64
64
33
4
60
yrapop01/fable
fable/config.py
Python
assign_values
assign_values
40
43
40
40
8ef7e7a2678e185d97ac773ae5e3baf5debfc27a
bigcode/the-stack
train
22a90870e3e249fe42e0a5ab
train
function
def load_args(): for key, value in zip(sys.argv[1:-1], sys.argv[2:]): if key.startswith('--'): key = key[2:] if key in VALUES: create_value = type(VALUES[key]) VALUES[key] = create_value(value)
def load_args():
for key, value in zip(sys.argv[1:-1], sys.argv[2:]): if key.startswith('--'): key = key[2:] if key in VALUES: create_value = type(VALUES[key]) VALUES[key] = create_value(value)
with open(path) as f: conf = json.load(f) for key in conf: if key in VALUES: VALUES[key] = conf[key] else: print('Unrecognized configuration key', key, flush=True) except FileNotFoundError: pass def load_args():
64
64
61
4
59
yrapop01/fable
fable/config.py
Python
load_args
load_args
32
38
32
32
657976938d71f30276f94b68d5b19d138dbda0bb
bigcode/the-stack
train
1dd511c23a45b5e2e768644e
train
function
def load_config(path): try: with open(path) as f: conf = json.load(f) for key in conf: if key in VALUES: VALUES[key] = conf[key] else: print('Unrecognized configuration key', key, flush=True) except FileNotFoundError: pa...
def load_config(path):
try: with open(path) as f: conf = json.load(f) for key in conf: if key in VALUES: VALUES[key] = conf[key] else: print('Unrecognized configuration key', key, flush=True) except FileNotFoundError: pass
'conf.json') VALUES = { 'port': 4891, 'host': '127.0.0.1', 'home': os.getcwd(), 'exec': 'xelatex', 'bibl': '', 'args': '-shell-escape' } def load_config(path):
64
64
69
5
59
yrapop01/fable
fable/config.py
Python
load_config
load_config
20
30
20
20
cf270203588ae45a5b281829bb950a79c52f0c42
bigcode/the-stack
train
1d09b29fd29c86d624372629
train
function
def _check_spark_version(sc, report_warn): version_info = _get_bigdl_verion_conf() (c_major, c_feature, c_maintenance) = _split_full_version(version_info['spark_version']) (r_major, r_feature, r_maintenance) = _split_full_version(sc.version) error_message = \ """ The compile time spark v...
def _check_spark_version(sc, report_warn):
version_info = _get_bigdl_verion_conf() (c_major, c_feature, c_maintenance) = _split_full_version(version_info['spark_version']) (r_major, r_feature, r_maintenance) = _split_full_version(sc.version) error_message = \ """ The compile time spark version is not compatible with the spark run...
.analytics.zoo.versionCheck.warning", "False").lower() == "true" _check_spark_version(sc, report_warn) def _split_full_version(version): parts = version.split(".") major = parts[0] feature = parts[1] maintenance = parts[2] return (major, feature, maintenance) def _check_spark_version(sc, r...
82
82
276
11
71
SteNicholas/analytics-zoo
pyzoo/zoo/common/nncontext.py
Python
_check_spark_version
_check_spark_version
242
264
242
242
0f33791ce2205b645cc99242d9ec0abb5de18308
bigcode/the-stack
train
43a05784ed0b4e82aa91c0ba
train
function
def init_spark_on_local(cores=2, conf=None, python_location=None, spark_log_level="WARN", redirect_spark_log=True): """ Create a SparkContext with Zoo configuration in local machine. :param cores: The default value is 2 and you can also set it to * meaning all of the available c...
def init_spark_on_local(cores=2, conf=None, python_location=None, spark_log_level="WARN", redirect_spark_log=True):
""" Create a SparkContext with Zoo configuration in local machine. :param cores: The default value is 2 and you can also set it to * meaning all of the available cores. i.e `init_on_local(cores="*")` :param conf: A key value dictionary appended to SparkConf. :param python_location: The path to ...
the License for the specific language governing permissions and # limitations under the License. # from bigdl.util.common import * import warnings import multiprocessing import os def init_spark_on_local(cores=2, conf=None, python_location=None, spark_log_level="WARN", redirect_spark_log=True)...
64
64
210
31
32
SteNicholas/analytics-zoo
pyzoo/zoo/common/nncontext.py
Python
init_spark_on_local
init_spark_on_local
23
39
23
24
e0ff833e3f1e678a3c689df356523eff777ecf0b
bigcode/the-stack
train
020e374d0b4679b120644dd5
train
function
def init_nncontext(conf=None, redirect_spark_log=True): """ Creates or gets a SparkContext with optimized configuration for BigDL performance. The method will also initialize the BigDL engine. Note: if you use spark-shell or Jupyter notebook, as the Spark context is created before your code, you ha...
def init_nncontext(conf=None, redirect_spark_log=True):
""" Creates or gets a SparkContext with optimized configuration for BigDL performance. The method will also initialize the BigDL engine. Note: if you use spark-shell or Jupyter notebook, as the Spark context is created before your code, you have to set Spark conf values through command line options...
=extra_python_lib, penv_archive=penv_archive, hadoop_user_name=hadoop_user_name, spark_yarn_archive=spark_yarn_archive, jars=jars, spark_conf=spark_conf) return sc def init_nncontext(conf=None, redirect_spark_log=True):
64
64
175
13
50
SteNicholas/analytics-zoo
pyzoo/zoo/common/nncontext.py
Python
init_nncontext
init_nncontext
104
124
104
104
3cc8bcca26e48293cb8be74c66536e299c1629a3
bigcode/the-stack
train
287bc2076eb0960206687eee
train
function
def load_conf(conf_str, split_char=None): return dict(line.split(split_char) for line in conf_str.split("\n") if "#" not in line and line.strip())
def load_conf(conf_str, split_char=None):
return dict(line.split(split_char) for line in conf_str.split("\n") if "#" not in line and line.strip())
RuntimeError("Error while locating file zoo-version-info.properties, " + "please make sure the mvn generate-resources phase" + " is executed and a zoo-version-info.properties file" + " is located in zoo/target/extra-resources") def load_conf(conf_str...
64
64
38
10
54
SteNicholas/analytics-zoo
pyzoo/zoo/common/nncontext.py
Python
load_conf
load_conf
289
291
289
289
669b8010f853e64d3444b9a3286ac34632f6807f
bigcode/the-stack
train
d53dec45bcbaa38e98b98054
train
function
def init_spark_conf(conf=None): spark_conf = SparkConf() if conf: spark_conf.setAll(conf.items()) init_env(spark_conf) zoo_conf = get_analytics_zoo_conf() # Set bigDL and TF conf spark_conf.setAll(zoo_conf.items()) if os.environ.get("BIGDL_JARS", None) and not is_spark_below_2_2(): ...
def init_spark_conf(conf=None):
spark_conf = SparkConf() if conf: spark_conf.setAll(conf.items()) init_env(spark_conf) zoo_conf = get_analytics_zoo_conf() # Set bigDL and TF conf spark_conf.setAll(zoo_conf.items()) if os.environ.get("BIGDL_JARS", None) and not is_spark_below_2_2(): for jar in os.environ["B...
omp_num_threads) os.environ["KMP_AFFINITY"] = kmp_affinity os.environ["KMP_SETTINGS"] = kmp_settings os.environ["OMP_NUM_THREADS"] = omp_num_threads os.environ["KMP_BLOCKTIME"] = kmp_blocktime def init_spark_conf(conf=None):
70
70
236
8
61
SteNicholas/analytics-zoo
pyzoo/zoo/common/nncontext.py
Python
init_spark_conf
init_spark_conf
198
222
198
198
47236130a5413bd08538464a7443aadf45c889ea
bigcode/the-stack
train
5224be08c169c9753d4f6656
train
function
def get_analytics_zoo_conf(): zoo_conf_file = "spark-analytics-zoo.conf" zoo_python_wrapper = "python-api.zip" for p in sys.path: if zoo_conf_file in p and os.path.isfile(p): with open(p) if sys.version_info < (3,) else open(p, encoding='latin-1') as conf_file: return lo...
def get_analytics_zoo_conf():
zoo_conf_file = "spark-analytics-zoo.conf" zoo_python_wrapper = "python-api.zip" for p in sys.path: if zoo_conf_file in p and os.path.isfile(p): with open(p) if sys.version_info < (3,) else open(p, encoding='latin-1') as conf_file: return load_conf(conf_file.read()) ...
_context is None: spark_conf = init_spark_conf() if conf is None else conf if appName: spark_conf.setAppName(appName) return SparkContext.getOrCreate(spark_conf) else: return SparkContext.getOrCreate() def get_analytics_zoo_conf():
64
64
172
8
56
SteNicholas/analytics-zoo
pyzoo/zoo/common/nncontext.py
Python
get_analytics_zoo_conf
get_analytics_zoo_conf
143
159
143
143
16b17204f9c5d151fd95418ccf56a1e1827ae1fb
bigcode/the-stack
train
04a8cb782b6376e71df57cf4
train
function
def init_env(conf): # Default env kmp_affinity = "granularity=fine,compact,1,0" kmp_settings = "1" omp_num_threads = "1" kmp_blocktime = "0" # Check env and override if necessary # Currently, focused on ZOO_NUM_MKLTHREADS, # OMP_NUM_THREADS, KMP_BLOCKTIME, KMP_AFFINITY # and KMP_SET...
def init_env(conf): # Default env
kmp_affinity = "granularity=fine,compact,1,0" kmp_settings = "1" omp_num_threads = "1" kmp_blocktime = "0" # Check env and override if necessary # Currently, focused on ZOO_NUM_MKLTHREADS, # OMP_NUM_THREADS, KMP_BLOCKTIME, KMP_AFFINITY # and KMP_SETTINGS if "KMP_AFFINITY" in os.envi...
(3,) else open(p, encoding='latin-1') as conf_file: return load_conf(conf_file.read()) if zoo_python_wrapper in p and os.path.isfile(p): import zipfile with zipfile.ZipFile(p, 'r') as zip_conf: if zoo_conf_file in zip_conf.namelist(): ...
121
122
407
10
111
SteNicholas/analytics-zoo
pyzoo/zoo/common/nncontext.py
Python
init_env
init_env
162
195
162
163
3decfbf6a2d1c034478497fea15a140b8ab79125
bigcode/the-stack
train
23721f856c0cd1515255cf35
train
function
def init_spark_on_yarn(hadoop_conf, conda_name, num_executor, executor_cores, executor_memory="2g", driver_memory="1g", driver_cores=4, extra_executor_memory_f...
def init_spark_on_yarn(hadoop_conf, conda_name, num_executor, executor_cores, executor_memory="2g", driver_memory="1g", driver_cores=4, extra_executor_memory_f...
""" Create a SparkContext with Zoo configuration on Yarn cluster on "Yarn-client" mode. You should create a conda env and install the python dependencies in that env. Conda env and the python dependencies only need to be installed in the driver machine. It's not necessary create and install those on...
_spark_log: Redirect the Spark log to local file or not. :return: """ from zoo.util.spark import SparkRunner sparkrunner = SparkRunner(spark_log_level=spark_log_level, redirect_spark_log=redirect_spark_log) return sparkrunner.init_spark_on_local(cores=cores, conf=conf, ...
186
186
623
104
82
SteNicholas/analytics-zoo
pyzoo/zoo/common/nncontext.py
Python
init_spark_on_yarn
init_spark_on_yarn
42
101
42
57
681f1f69b7f62e21b0514e7f4690495789d52b57
bigcode/the-stack
train
d85fd5b694f3bc7e48b6d1b4
train
function
def check_version(): sc = getOrCreateSparkContext() conf = sc._conf if conf.get("spark.analytics.zoo.versionCheck", "False").lower() == "true": report_warn = conf.get( "spark.analytics.zoo.versionCheck.warning", "False").lower() == "true" _check_spark_version(sc, report_warn)
def check_version():
sc = getOrCreateSparkContext() conf = sc._conf if conf.get("spark.analytics.zoo.versionCheck", "False").lower() == "true": report_warn = conf.get( "spark.analytics.zoo.versionCheck.warning", "False").lower() == "true" _check_spark_version(sc, report_warn)
.pyFiles") if existing_py_files: spark_conf.set(key="spark.submit.pyFiles", value="%s,%s" % (python_lib, existing_py_files)) else: spark_conf.set(key="spark.submit.pyFiles", value=python_lib) return spark_conf def check_version():
64
64
78
4
59
SteNicholas/analytics-zoo
pyzoo/zoo/common/nncontext.py
Python
check_version
check_version
225
231
225
225
fa1a7f4cd0b2dcbcfd9050199186619cec1608d7
bigcode/the-stack
train
910c39357a9ced6ea3d611de
train
function
def _get_bigdl_verion_conf(): bigdl_build_file = "zoo-version-info.properties" bigdl_python_wrapper = "python-api.zip" for p in sys.path: if bigdl_build_file in p and os.path.isfile(p): with open(p) if sys.version_info < (3,) else open(p, encoding='latin-1') as conf_file: ...
def _get_bigdl_verion_conf():
bigdl_build_file = "zoo-version-info.properties" bigdl_python_wrapper = "python-api.zip" for p in sys.path: if bigdl_build_file in p and os.path.isfile(p): with open(p) if sys.version_info < (3,) else open(p, encoding='latin-1') as conf_file: return load_conf(conf_file.r...
and c_feature == r_feature): warnings.warn("The compile time spark version may not compatible with " + "the Spark runtime version. " + "Compile time version is %s, " % version_info['spark_version'] + "runtime version is %s" % sc.version) def _ge...
70
70
234
9
61
SteNicholas/analytics-zoo
pyzoo/zoo/common/nncontext.py
Python
_get_bigdl_verion_conf
_get_bigdl_verion_conf
267
286
267
267
dd789f869061e9cff1aa1bd3667bf972184c46b8
bigcode/the-stack
train
a6e2320519445aeb436fdc0a
train
function
def _split_full_version(version): parts = version.split(".") major = parts[0] feature = parts[1] maintenance = parts[2] return (major, feature, maintenance)
def _split_full_version(version):
parts = version.split(".") major = parts[0] feature = parts[1] maintenance = parts[2] return (major, feature, maintenance)
if conf.get("spark.analytics.zoo.versionCheck", "False").lower() == "true": report_warn = conf.get( "spark.analytics.zoo.versionCheck.warning", "False").lower() == "true" _check_spark_version(sc, report_warn) def _split_full_version(version):
64
64
44
7
57
SteNicholas/analytics-zoo
pyzoo/zoo/common/nncontext.py
Python
_split_full_version
_split_full_version
234
239
234
234
dd8006feb51ab33653ca27f5017a81c9d054ce13
bigcode/the-stack
train
af02e86a6fe7c2e8a21e0271
train
function
def getOrCreateSparkContext(conf=None, appName=None): """ Get the current active spark context and create one if no active instance :param conf: combining bigdl configs into spark conf :return: SparkContext """ with SparkContext._lock: if SparkContext._active_spark_context is None: ...
def getOrCreateSparkContext(conf=None, appName=None):
""" Get the current active spark context and create one if no active instance :param conf: combining bigdl configs into spark conf :return: SparkContext """ with SparkContext._lock: if SparkContext._active_spark_context is None: spark_conf = init_spark_conf() if conf is None ...
=conf) else: sc = getOrCreateSparkContext(conf=conf) check_version() if redirect_spark_log: redire_spark_logs() show_bigdl_info_logs() init_engine() return sc def getOrCreateSparkContext(conf=None, appName=None):
64
64
123
13
50
SteNicholas/analytics-zoo
pyzoo/zoo/common/nncontext.py
Python
getOrCreateSparkContext
getOrCreateSparkContext
127
140
127
127
939c7b6ffb3e8d1918057fc1c940893893146dea
bigcode/the-stack
train
725f6281f2d6cfd5c5ee62a1
train
class
class HoursSinceLoginService(BaseTimeSinceLoginService): keys = ["hours"] postfix = "h" next_handler_class = MinutesSinceLoginService
class HoursSinceLoginService(BaseTimeSinceLoginService):
keys = ["hours"] postfix = "h" next_handler_class = MinutesSinceLoginService
> 0 for key in self.keys]): return self.get_message() return self.next() class MinutesSinceLoginService(BaseTimeSinceLoginService): keys = ["minutes"] postfix = "m" def next(self): return _("moment") class HoursSinceLoginService(BaseTimeSinceLoginService):
64
64
33
11
53
dkusy/dan-auth
apps/users/services.py
Python
HoursSinceLoginService
HoursSinceLoginService
44
47
44
44
b7f35a14eb7dccdda78c1730c618bfe81063a92b
bigcode/the-stack
train
7b4926f878a589985d870eae
train
class
class DaysSinceLoginService(BaseTimeSinceLoginService): keys = ["days"] postfix = "d" next_handler_class = HoursSinceLoginService
class DaysSinceLoginService(BaseTimeSinceLoginService):
keys = ["days"] postfix = "d" next_handler_class = HoursSinceLoginService
= ["minutes"] postfix = "m" def next(self): return _("moment") class HoursSinceLoginService(BaseTimeSinceLoginService): keys = ["hours"] postfix = "h" next_handler_class = MinutesSinceLoginService class DaysSinceLoginService(BaseTimeSinceLoginService):
64
64
33
11
52
dkusy/dan-auth
apps/users/services.py
Python
DaysSinceLoginService
DaysSinceLoginService
50
53
50
50
dfd8237475a0d152ef1b3a9f5439646bb892123b
bigcode/the-stack
train
45dbc3ebc89244e70f4d5835
train
class
class MinutesSinceLoginService(BaseTimeSinceLoginService): keys = ["minutes"] postfix = "m" def next(self): return _("moment")
class MinutesSinceLoginService(BaseTimeSinceLoginService):
keys = ["minutes"] postfix = "m" def next(self): return _("moment")
): return self.next_handler_class(self.last_login, self.time).get_last_login() def get_last_login(self): if any([self.time[key] > 0 for key in self.keys]): return self.get_message() return self.next() class MinutesSinceLoginService(BaseTimeSinceLoginService):
64
64
33
11
53
dkusy/dan-auth
apps/users/services.py
Python
MinutesSinceLoginService
MinutesSinceLoginService
36
41
36
36
d93caac19d59a1b8c979a30fcc8f896e11279901
bigcode/the-stack
train
fa58f21fb47c72f098a14913
train
class
class TimeSinceLoginService(BaseTimeSinceLoginService): keys = ["years", "weeks"] next_handler_class = DaysSinceLoginService def get_message(self): return self.last_login.strftime("%d %B %Y")
class TimeSinceLoginService(BaseTimeSinceLoginService):
keys = ["years", "weeks"] next_handler_class = DaysSinceLoginService def get_message(self): return self.last_login.strftime("%d %B %Y")
= ["hours"] postfix = "h" next_handler_class = MinutesSinceLoginService class DaysSinceLoginService(BaseTimeSinceLoginService): keys = ["days"] postfix = "d" next_handler_class = HoursSinceLoginService class TimeSinceLoginService(BaseTimeSinceLoginService):
64
64
49
11
52
dkusy/dan-auth
apps/users/services.py
Python
TimeSinceLoginService
TimeSinceLoginService
56
61
56
56
d8446786465979cb9231ab14066d6fa0c6eaba25
bigcode/the-stack
train
e7c7c1e5e251f136e83e5569
train
class
class BaseTimeSinceLoginService(abc.ABC): keys = [] postfix = "" next_handler_class = None def __init__(self, last_login: datetime, time: datetime): self.last_login = last_login self.time = time def get_message(self): value = self.time[self.keys[0]] return f"{value}...
class BaseTimeSinceLoginService(abc.ABC):
keys = [] postfix = "" next_handler_class = None def __init__(self, last_login: datetime, time: datetime): self.last_login = last_login self.time = time def get_message(self): value = self.time[self.keys[0]] return f"{value}{self.postfix}" def next(self): ...
from django.conf import settings from django.dispatch import receiver from django.template.loader import render_to_string from django.utils.translation import gettext_lazy as _ from django_rest_passwordreset.signals import reset_password_token_created from apps.users.api_services import MailingApiService class BaseTim...
64
64
139
11
52
dkusy/dan-auth
apps/users/services.py
Python
BaseTimeSinceLoginService
BaseTimeSinceLoginService
14
33
14
14
8460d8a63e52625e7d6112671b513facb5416a78
bigcode/the-stack
train
d226f0b94dda78deab9359cb
train
class
class ResetPasswordService: @staticmethod @receiver(reset_password_token_created) def send_email_on_token_creation( sender, instance, reset_password_token, *args, **kwargs ): """ Handles password reset tokens When a token is created, an e-mail needs to be sent to the user...
class ResetPasswordService: @staticmethod @receiver(reset_password_token_created)
def send_email_on_token_creation( sender, instance, reset_password_token, *args, **kwargs ): """ Handles password reset tokens When a token is created, an e-mail needs to be sent to the user :param sender: View Class that sent the signal :param instance: View Inst...
SinceLoginService(BaseTimeSinceLoginService): keys = ["years", "weeks"] next_handler_class = DaysSinceLoginService def get_message(self): return self.last_login.strftime("%d %B %Y") class ResetPasswordService: @staticmethod @receiver(reset_password_token_created)
64
64
192
17
47
dkusy/dan-auth
apps/users/services.py
Python
ResetPasswordService
ResetPasswordService
64
87
64
66
68cbe02943e6f80b245544d9b66a38dd19e190a7
bigcode/the-stack
train
c8e68b1e8cf20197cd9377bd
train
function
def pp_symbols(labels, drop_unvoiced_vowels=True): PP = [] accent = [] N = len(labels) for n in range(len(labels)): lab_curr = labels[n] p3 = re.search(r"\-(.*?)\+", lab_curr).group(1) if drop_unvoiced_vowels and p3 in "AEIOU": p3 = p3.lower() if p3 == 's...
def pp_symbols(labels, drop_unvoiced_vowels=True):
PP = [] accent = [] N = len(labels) for n in range(len(labels)): lab_curr = labels[n] p3 = re.search(r"\-(.*?)\+", lab_curr).group(1) if drop_unvoiced_vowels and p3 in "AEIOU": p3 = p3.lower() if p3 == 'sil': assert n== 0 or n == N-1 ...
from pathlib import Path import re from tqdm import tqdm # full context label to accent label from ttslearn def numeric_feature_by_regex(regex, s): match = re.search(regex, s) if match is None: return -50 return int(match.group(1)) def pp_symbols(labels, drop_unvoiced_vowels=True):
75
136
455
13
62
ndkgit339/FastSpeech2-filled_pause_speech_synthesis
predict_utils/prepare_tg_accent.py
Python
pp_symbols
pp_symbols
12
60
12
12
68e1a928daf42c635322c10f32923a7fdd1a7d55
bigcode/the-stack
train
6be8b8cee37b6d2816b8a271
train
function
def numeric_feature_by_regex(regex, s): match = re.search(regex, s) if match is None: return -50 return int(match.group(1))
def numeric_feature_by_regex(regex, s):
match = re.search(regex, s) if match is None: return -50 return int(match.group(1))
from pathlib import Path import re from tqdm import tqdm # full context label to accent label from ttslearn def numeric_feature_by_regex(regex, s):
34
64
37
9
24
ndkgit339/FastSpeech2-filled_pause_speech_synthesis
predict_utils/prepare_tg_accent.py
Python
numeric_feature_by_regex
numeric_feature_by_regex
6
10
6
6
68451fcb7cbd8da02ff95f008dfcdc20abf897c2
bigcode/the-stack
train
d8db16f1e09b818b073b6e69
train
function
def prepare_accent(data_dir): data_dir = Path(data_dir) lab_files = (data_dir / "fullcontext_lab").glob("*.lab") # create output directory ac_dir = data_dir / 'accent' if not ac_dir.exists(): ac_dir.mkdir() # iter through lab files for lab_file in tqdm(lab_files): accent =...
def prepare_accent(data_dir):
data_dir = Path(data_dir) lab_files = (data_dir / "fullcontext_lab").glob("*.lab") # create output directory ac_dir = data_dir / 'accent' if not ac_dir.exists(): ac_dir.mkdir() # iter through lab files for lab_file in tqdm(lab_files): accent = [] with open(lab_file...
a2 != f1: accent.append("]") # ピッチの立ち上がり elif a2 == 1 and a2_next == 2: accent.append("[") else: accent.append('0') return PP, accent def prepare_accent(data_dir):
64
64
140
7
56
ndkgit339/FastSpeech2-filled_pause_speech_synthesis
predict_utils/prepare_tg_accent.py
Python
prepare_accent
prepare_accent
62
79
62
62
e520482dcf04d62ab8e3b32fd419cb046d82737b
bigcode/the-stack
train
0de3e571ee0bf8f65e471d96
train
class
class ScrollingGroup(Group): def __init__(self, *buttons: Keyboard, id: str, width: Optional[int] = None, height: int = 0, when: WhenCondition = None, on_page_changed: Union[OnStateChanged, WidgetEventProcessor, None] = None): super().__init__(*buttons, id=id, width=width, ...
class ScrollingGroup(Group):
def __init__(self, *buttons: Keyboard, id: str, width: Optional[int] = None, height: int = 0, when: WhenCondition = None, on_page_changed: Union[OnStateChanged, WidgetEventProcessor, None] = None): super().__init__(*buttons, id=id, width=width, when=when) self.heigh...
from typing import List, Dict, Optional, Callable, Awaitable, Union from aiogram.types import InlineKeyboardButton, CallbackQuery from aiogram_dialog.deprecation_utils import manager_deprecated from aiogram_dialog.dialog import Dialog, ChatEvent from aiogram_dialog.manager.protocols import DialogManager from aiogram_...
136
165
550
6
130
AlessandrIT/aiogram_dialog
aiogram_dialog/widgets/kbd/scrolling_group.py
Python
ScrollingGroup
ScrollingGroup
20
65
20
20
649b054bd1a08062e85cef537376f8f471be4593
bigcode/the-stack
train
1d2873079707410e4d963bda
train
class
class ManagedScrollingGroupAdapter(ManagedWidgetAdapter[ScrollingGroup]): def get_page(self, manager: Optional[DialogManager] = None) -> int: manager_deprecated(manager) return self.widget.get_page(self.manager) async def set_page(self, event: ChatEvent, page: int, manage...
class ManagedScrollingGroupAdapter(ManagedWidgetAdapter[ScrollingGroup]):
def get_page(self, manager: Optional[DialogManager] = None) -> int: manager_deprecated(manager) return self.widget.get_page(self.manager) async def set_page(self, event: ChatEvent, page: int, manager: Optional[DialogManager] = None) -> None: manager_deprecated(man...
().widget_data[self.widget_id] = page await self.on_page_changed.process_event( event, self.managed(manager), manager, ) def managed(self, manager: DialogManager): return ManagedScrollingGroupAdapter(self, manager) class ManagedScrollingGroupAdapter(ManagedWidgetAdapter[Scrollin...
64
64
101
13
51
AlessandrIT/aiogram_dialog
aiogram_dialog/widgets/kbd/scrolling_group.py
Python
ManagedScrollingGroupAdapter
ManagedScrollingGroupAdapter
68
78
68
68
f870487c498e5c90a44f89a446f7f0f8f9bbd981
bigcode/the-stack
train
f4d2e2b9656f0b626b28aab7
train
function
def gen_demonstrated_funcs_str(example_config_path: Path) -> str: """Generate a list of the demonstrated functionality based on the config. """ env = os.environ env['MNE_BIDS_STUDY_CONFIG'] = str(example_config_path.expanduser()) # Set one of the various tasks for ERP CORE, as we currently raise if...
def gen_demonstrated_funcs_str(example_config_path: Path) -> str:
"""Generate a list of the demonstrated functionality based on the config. """ env = os.environ env['MNE_BIDS_STUDY_CONFIG'] = str(example_config_path.expanduser()) # Set one of the various tasks for ERP CORE, as we currently raise if none # was provided if example_config_path.name == 'confi...
import os import shutil from pathlib import Path import runpy from typing import Union, Iterable dataset_opts_path = Path('tests/datasets.py') run_tests_path = Path('tests/run_tests.py') dataset_options = runpy.run_path(dataset_opts_path)['DATASET_OPTIONS'] test_options = runpy.run_path(run_tests_path)['TEST_SUITE']...
90
146
489
16
74
dengemann/mne-bids-pipeline
docs/source/examples/gen_examples.py
Python
gen_demonstrated_funcs_str
gen_demonstrated_funcs_str
15
59
15
15
3283ef0677be1e7ba72ca6d6558b3d7140e0ef0a
bigcode/the-stack
train
7d3f3cb6b046ef332705863e
train
class
class IonToJSONEncoder(JSONExtendedEncoder): """JSON Encoder for Ion value types. Used in the json.dumps method as the cls parameter to support JSON encoding of Python Ion types: json.dumps(obj, cls=IonToJSONEncoder) Notes: The json_encoder module is not supported for use with PyPy. """ de...
class IonToJSONEncoder(JSONExtendedEncoder):
"""JSON Encoder for Ion value types. Used in the json.dumps method as the cls parameter to support JSON encoding of Python Ion types: json.dumps(obj, cls=IonToJSONEncoder) Notes: The json_encoder module is not supported for use with PyPy. """ def isinstance(self, obj, cls): if (not...
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS # OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the # License. from .core import IonType from .simple_types import IonPyList, IonPyDict, IonPyNull, IonPyBool, IonPyInt, IonPyFloat, IonP...
163
163
545
9
153
jeff-wishnie/ion-python
amazon/ion/json_encoder.py
Python
IonToJSONEncoder
IonToJSONEncoder
26
69
26
26
f1ffc0cc5bd57c11d81fa02441aa2dd715a09b37
bigcode/the-stack
train
c0e2a63459778be122d90553
train
function
def latent_heat_lambda(air_temperature): """ Function to calculate the latent heat of vapourisation, lambda, from air temperature. Source: J. Bringfelt. Test of a forest evapotranspiration model. Meteorology and Climatology Reports 52, SMHI, Norrkopping, Sweden, 1986. Input: - air_tempe...
def latent_heat_lambda(air_temperature):
""" Function to calculate the latent heat of vapourisation, lambda, from air temperature. Source: J. Bringfelt. Test of a forest evapotranspiration model. Meteorology and Climatology Reports 52, SMHI, Norrkopping, Sweden, 1986. Input: - air_temperature: (array of) air temperature [Celsi...
ndarray, float] : Vapour pressure deficit [Pa] """ # Calculate saturation vapour pressures es = es_calc(air_temperature) eact = ea_calc(air_temperature, relative_humidity) # Calculate vapour pressure deficit return es - eact # in Pa def latent_heat_lambda(air_temperature):
73
73
245
8
64
OpenAgriTech/opencroplib
opencroplib/atmophere.py
Python
latent_heat_lambda
latent_heat_lambda
225
255
225
225
d5429c5519970ec17a184bf8826e44ab3755cddf
bigcode/the-stack
train
e4df1edb73e54229e31fdc35
train
function
def es_buck(air_temperature): """ Parameters ---------- air_temperature : Union[array, float] Moist air temperature [Celsius]. Note: assumes air temperature > 0C Returns ------- Union[array, float] : saturated vapour pressure [Pa] """ return 611.21*np.exp((18.678-air_tempe...
def es_buck(air_temperature):
""" Parameters ---------- air_temperature : Union[array, float] Moist air temperature [Celsius]. Note: assumes air temperature > 0C Returns ------- Union[array, float] : saturated vapour pressure [Pa] """ return 611.21*np.exp((18.678-air_temperature/234.5)*(air_temperature...
es[np.array(air_temperature >= 0, dtype=bool)] = np.power(10, log_pw[np.array(air_temperature >= 0, dtype=bool)]) # Convert from hPa to Pa es *= 100.0 return es def es_buck(air_temperature):
64
64
92
8
55
OpenAgriTech/opencroplib
opencroplib/atmophere.py
Python
es_buck
es_buck
115
128
115
115
4bc8e158bddffca8755b8e14411c92c3497359a9
bigcode/the-stack
train
a32c42fa5ec4c12b38daa828
train
function
def vpd_calc(air_temperature, relative_humidity): """ Function to calculate vapour pressure deficit. Examples: >>> vpd_calc(30,60) >>> 1697.0903978626527 >>> T=[20,25] >>> RH=[50,100] >>> vpd_calc(T,RH) >>> array([ 1168.540099, 0. ]) Parameters --...
def vpd_calc(air_temperature, relative_humidity):
""" Function to calculate vapour pressure deficit. Examples: >>> vpd_calc(30,60) >>> 1697.0903978626527 >>> T=[20,25] >>> RH=[50,100] >>> vpd_calc(T,RH) >>> array([ 1168.540099, 0. ]) Parameters ---------- air_temperature : Union[ndarray, floa...
] """ # Calculate saturation vapour pressures es = es_calc(air_temperature) # Calculate actual vapour pressure eact = relative_humidity / 100.0 * es return eact # in Pa def vpd_calc(air_temperature, relative_humidity):
64
64
202
12
51
OpenAgriTech/opencroplib
opencroplib/atmophere.py
Python
vpd_calc
vpd_calc
193
222
193
193
e109e9d92089fe23dab537320a79d886518c287d
bigcode/the-stack
train
f6c0d52e848c69dacbd92a56
train
function
def rho_cp_moist(air_temperature, relative_humidity, air_pressure): """ Parameters ---------- air_temperature relative_humidity air_pressure Returns ------- """ rho = air_density_rho(air_temperature, relative_humidity, air_pressure) return rho * specific_heat_cp(air_temper...
def rho_cp_moist(air_temperature, relative_humidity, air_pressure):
""" Parameters ---------- air_temperature relative_humidity air_pressure Returns ------- """ rho = air_density_rho(air_temperature, relative_humidity, air_pressure) return rho * specific_heat_cp(air_temperature, relative_humidity, air_pressure)
.07 * (air_temperature + 273.15)) return rho * (1002.5 + 275e-6 * np.power(air_temperature + 273.15 - 200.0, 2)) def rho_cp_moist(air_temperature, relative_humidity, air_pressure):
64
64
81
17
47
OpenAgriTech/opencroplib
opencroplib/atmophere.py
Python
rho_cp_moist
rho_cp_moist
445
459
445
445
9d5d2fbc5bc178845fb8ade563e5c24481643d77
bigcode/the-stack
train
69a65b3b4508fdeec1ce5276
train
function
def rho_cp_dry(air_temperature, air_pressure): """ Parameters ---------- air_temperature air_pressure Returns ------- """ rho = air_temperature / (287.07 * (air_temperature + 273.15)) return rho * (1002.5 + 275e-6 * np.power(air_temperature + 273.15 - 200.0, 2))
def rho_cp_dry(air_temperature, air_pressure):
""" Parameters ---------- air_temperature air_pressure Returns ------- """ rho = air_temperature / (287.07 * (air_temperature + 273.15)) return rho * (1002.5 + 275e-6 * np.power(air_temperature + 273.15 - 200.0, 2))
if we can use gamma function instead gamma = a1 * air_temperature / (b1 + air_temperature) + np.log(relative_humidity / 100.0) dew = b * gamma / (a - gamma) return dew def rho_cp_dry(air_temperature, air_pressure):
64
64
90
12
51
OpenAgriTech/opencroplib
opencroplib/atmophere.py
Python
rho_cp_dry
rho_cp_dry
429
442
429
429
8901f15589dce2f370e7502bef431d6ccf05ead4
bigcode/the-stack
train
8d9523a66813b125dfbdb00a
train
function
def es_calc(air_temperature): """ Function to calculate saturated vapour pressure from temperature. For T<0 C: Saturation vapour pressure equation for ice: Goff, J.A.,and S. Gratch, Low-pressure properties of water from \-160 to 212 F. Transactions of the American society of heating and ventila...
def es_calc(air_temperature):
""" Function to calculate saturated vapour pressure from temperature. For T<0 C: Saturation vapour pressure equation for ice: Goff, J.A.,and S. Gratch, Low-pressure properties of water from \-160 to 212 F. Transactions of the American society of heating and ventilating engineers, pp 95-122, pre...
2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an...
256
256
1,064
7
249
OpenAgriTech/opencroplib
opencroplib/atmophere.py
Python
es_calc
es_calc
36
112
36
36
45d397c7da9b3792f4f200c9d4cc2a23abe01a10
bigcode/the-stack
train
a5c369dc468cab99879fe55d
train
function
def ea_calc(air_temperature, relative_humidity): """ Function to calculate actual saturation vapour pressure. Examples: >>> ea_calc(25, 60) >>> 1900.0946514729308 Parameters ---------- air_temperature : Union[ndarray, float] Air temperature [Celsius] relative_humid...
def ea_calc(air_temperature, relative_humidity):
""" Function to calculate actual saturation vapour pressure. Examples: >>> ea_calc(25, 60) >>> 1900.0946514729308 Parameters ---------- air_temperature : Union[ndarray, float] Air temperature [Celsius] relative_humidity : Union[ndarray, float] Relative humi...
kPa es /= 1000.0 # Calculate Delta Delta = es * 4098.0 / np.power((air_temperature + 237.3), 2) * 1000.0 return Delta def ea_calc(air_temperature, relative_humidity):
64
64
160
11
52
OpenAgriTech/opencroplib
opencroplib/atmophere.py
Python
ea_calc
ea_calc
164
190
164
164
6175b33eb835ba7c398e9d0fa876d42c49f5d2c9
bigcode/the-stack
train
11c06535eb6b92e269b42ba2
train
function
def delta_calc(air_temperature): """ Function to calculate the slope of the temperature - vapour pressure curve (Delta) from air temperatures. Source: Technical regulations 49, World Meteorological Organisation, 1984. Appendix A. 1-Ap-A-3. Examples: >>> delta_calc(30.0) >>> 243.343...
def delta_calc(air_temperature):
""" Function to calculate the slope of the temperature - vapour pressure curve (Delta) from air temperatures. Source: Technical regulations 49, World Meteorological Organisation, 1984. Appendix A. 1-Ap-A-3. Examples: >>> delta_calc(30.0) >>> 243.34309166827097 >>> x = [20, ...
]. Note: assumes air temperature > 0C Returns ------- Union[array, float] : saturated vapour pressure [Pa] """ return 611.21*np.exp((18.678-air_temperature/234.5)*(air_temperature/(257.14+air_temperature))) def delta_calc(air_temperature):
68
68
229
7
61
OpenAgriTech/opencroplib
opencroplib/atmophere.py
Python
delta_calc
delta_calc
130
161
130
130
4d10eef8474159b3382644ce03d585e11844749f
bigcode/the-stack
train
87790fa8a05a3e2e83fa0bde
train
function
def specific_heat_cp(air_temperature, relative_humidity, air_pressure): """ Function to calculate the specific heat of air, c_p, from air temperatures, relative humidity and air pressure. Examples: >>> specific_heat_cp(25,60,101300) 1014.0749457208065 >>> t=[10, 20, 30] >>> ...
def specific_heat_cp(air_temperature, relative_humidity, air_pressure):
""" Function to calculate the specific heat of air, c_p, from air temperatures, relative humidity and air pressure. Examples: >>> specific_heat_cp(25,60,101300) 1014.0749457208065 >>> t=[10, 20, 30] >>> rh=[10, 20, 30] >>> air_pressure=[100000, 101000, 102000] ...
2452718.3817125, 2429049.3792125]) Parameters ---------- air_temperature Returns ------- ndarray """ # Calculate lambda return 4185.5 * (751.78 - 0.5655 * (air_temperature + 273.15)) # in J/kg def specific_heat_cp(air_temperature, relative_humidity, air_pressure):
91
91
305
15
75
OpenAgriTech/opencroplib
opencroplib/atmophere.py
Python
specific_heat_cp
specific_heat_cp
258
290
258
258
ea874a748b52ebb8b7ebf7f5bc4275d35a4b1ce4
bigcode/the-stack
train
9e561fcb3d4fac6eeb1e134e
train
function
def psychrometric_gamma(air_temperature, relative_humidity, air_pressure): """ Function to calculate the psychrometric constant gamma. Source: J. Bringfelt. Test of a forest evapotranspiration model. Meteorology and Climatology Reports 52, SMHI, Norrköpping, Sweden, 1986. Examples: >>> ...
def psychrometric_gamma(air_temperature, relative_humidity, air_pressure):
""" Function to calculate the psychrometric constant gamma. Source: J. Bringfelt. Test of a forest evapotranspiration model. Meteorology and Climatology Reports 52, SMHI, Norrköpping, Sweden, 1986. Examples: >>> psychrometric_gamma(10,50,101300) 66.263433186572274 >>> t=...
/kg/K] """ # calculate vapour pressures eact = ea_calc(air_temperature, relative_humidity) # Calculate cp cp = 0.24 * 4185.5 * (1 + 0.8 * (0.622 * eact / (air_pressure - eact))) return cp # in J/kg/K def psychrometric_gamma(air_temperature, relative_humidity, air_pressure):
94
94
314
16
77
OpenAgriTech/opencroplib
opencroplib/atmophere.py
Python
psychrometric_gamma
psychrometric_gamma
293
328
293
293
49e04d72b2e7c693800695fbdf0192340e3ea6b2
bigcode/the-stack
train
5595ea7cf79e2030b2d638fe
train
function
def dew_point(air_temperature, relative_humidity): """ Calculates dew point from air temperature and relative humidity Reference: TODO Parameters ---------- relative_humidity : ndarray Relative humidity [%] air_temperature: ndarray Dry bulb air temperature [Celsius] Ret...
def dew_point(air_temperature, relative_humidity):
""" Calculates dew point from air temperature and relative humidity Reference: TODO Parameters ---------- relative_humidity : ndarray Relative humidity [%] air_temperature: ndarray Dry bulb air temperature [Celsius] Returns ------- ndarray: dew point [Celsius] ...
_humidity, air_pressure) theta = (air_temperature + 273.15) * np.power((100000.0 / air_pressure), (287.0 / cp)) - 273.15 return theta # in degrees celsius def dew_point(air_temperature, relative_humidity):
64
64
168
11
52
OpenAgriTech/opencroplib
opencroplib/atmophere.py
Python
dew_point
dew_point
402
426
402
402
5da53ae6aa29103a32f392a1c224754044f063e7
bigcode/the-stack
train
0088c7199eedef369199726b
train
function
def air_density_rho(air_temperature, relative_humidity, air_pressure): """ Function to calculate the density of air, rho, from air temperatures, relative humidity and air pressure. Examples: >>> t=[10, 20, 30] >>> rh=[10, 20, 30] >>> air_pressure=[100000, 101000, 102000] ...
def air_density_rho(air_temperature, relative_humidity, air_pressure):
""" Function to calculate the density of air, rho, from air temperatures, relative humidity and air pressure. Examples: >>> t=[10, 20, 30] >>> rh=[10, 20, 30] >>> air_pressure=[100000, 101000, 102000] >>> air_density_rho(t,rh,air_pressure) array([ 1.22948419, 1...
[ndarray, float] : psychrometric constant gamma [Pa/K] """ cp = specific_heat_cp(air_temperature, relative_humidity, air_pressure) lamb = latent_heat_lambda(air_temperature) # Calculate gamma gamma = cp * air_pressure / (0.622 * lamb) return gamma # in Pa/K def air_density_rho(air_temperature...
90
90
302
16
73
OpenAgriTech/opencroplib
opencroplib/atmophere.py
Python
air_density_rho
air_density_rho
331
363
331
331
72d75df98d4ffc7c0e724b03d962396cc2d3c770
bigcode/the-stack
train
5e935f6b57b562b129428c09
train
function
def potential_temperature_theta(air_temperature, relative_humidity, air_pressure): """ Function to calculate the potential temperature air, theta, from air temperatures, relative humidity and air pressure. Reference pressure 1000 hPa. Examples: >>> t=[5, 10, 20] >>> rh=[45, 65, 89] ...
def potential_temperature_theta(air_temperature, relative_humidity, air_pressure):
""" Function to calculate the potential temperature air, theta, from air temperatures, relative humidity and air pressure. Reference pressure 1000 hPa. Examples: >>> t=[5, 10, 20] >>> rh=[45, 65, 89] >>> air_pressure=[101300, 102000, 99800] >>> potential_temperature_...
kg/m3] """ eact = ea_calc(air_temperature, relative_humidity) rho = 1.201 * (290.0 * (air_pressure - 0.378 * eact)) / (1000.0 * (air_temperature + 273.15)) / 100.0 return rho # in kg/m3 def potential_temperature_theta(air_temperature, relative_humidity, air_pressure):
92
92
307
15
76
OpenAgriTech/opencroplib
opencroplib/atmophere.py
Python
potential_temperature_theta
potential_temperature_theta
366
399
366
366
3f49d21e38f11a4ffaf7814eab47be29510655fd
bigcode/the-stack
train
0c8f37e2e1957c356b3e7251
train
function
def Usage(): print('ogrupdate.py -src name -dst name [-srclayer name] [-dstlayer name] [-matchfield name] [-update_only | -append_new_only]') print(' [-compare_before_update] [-preserve_fid] [-select field_list] [-dry_run] [-progress] [-skip_failures] [-quiet]') print('') print('Update a tar...
def Usage():
print('ogrupdate.py -src name -dst name [-srclayer name] [-dstlayer name] [-matchfield name] [-update_only | -append_new_only]') print(' [-compare_before_update] [-preserve_fid] [-select field_list] [-dry_run] [-progress] [-skip_failures] [-quiet]') print('') print('Update a target datasourc...
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHET...
141
141
470
3
138
HongqiangWei/gdal
gdal/swig/python/samples/ogrupdate.py
Python
Usage
Usage
42
68
42
42
fb620bda8bc45e29576c4d2697ca2d052f68e4d5
bigcode/the-stack
train
cf44cb71066fcf5a95211da1
train
function
def AreFeaturesEqual(src_feat, dst_feat): for i in range(src_feat.GetFieldCount()): src_val = src_feat.GetField(i) dst_val = dst_feat.GetField(i) if src_val != dst_val: return False src_geom = src_feat.GetGeometryRef() dst_geom = dst_feat.GetGeometryRef() if src_geom ...
def AreFeaturesEqual(src_feat, dst_feat):
for i in range(src_feat.GetFieldCount()): src_val = src_feat.GetField(i) dst_val = dst_feat.GetField(i) if src_val != dst_val: return False src_geom = src_feat.GetGeometryRef() dst_geom = dst_feat.GetGeometryRef() if src_geom is None and dst_geom is not None: ...
[0]) if inserted_failed[0] != 0: print('Failed inserts : %d' % inserted_failed[0]) src_ds = None dst_ds = None return ret ############################################################### # AreFeaturesEqual() def AreFeaturesEqual(src_feat, dst_feat):
64
64
136
10
54
HongqiangWei/gdal
gdal/swig/python/samples/ogrupdate.py
Python
AreFeaturesEqual
AreFeaturesEqual
254
269
254
254
b84368ca6cdddfaebb4dee9db0608c25fe28457b
bigcode/the-stack
train
4eaa9ceb73128fbc115758b2
train
function
def ogrupdate_analyse_args(argv, progress = None, progress_arg = None): src_filename = None dst_filename = None src_layername = None dst_layername = None matchfieldname = None # in case there's no existing matching feature in the target datasource # should we try to create a new feature ? ...
def ogrupdate_analyse_args(argv, progress = None, progress_arg = None):
src_filename = None dst_filename = None src_layername = None dst_layername = None matchfieldname = None # in case there's no existing matching feature in the target datasource # should we try to create a new feature ? update_only = False # in case there's no existing matching feat...
source feature has no match in the target layer.') print('-append_new_only: do *not update* features of the target layer that match features from the source layer;') print(' *append* new features from the source layer that do not match any feature from the target layer.') print('') pri...
256
256
1,465
17
239
HongqiangWei/gdal
gdal/swig/python/samples/ogrupdate.py
Python
ogrupdate_analyse_args
ogrupdate_analyse_args
73
249
73
74
72fb15a1a38c0f3adaba4a9ce78e02e12d23a680
bigcode/the-stack
train
660a2fb0f4b8585867fc8354
train
function
def ogrupdate_process(src_layer, dst_layer, matchfieldname = None, update_mode = DEFAULT, \ preserve_fid = False, compare_before_update = False, \ papszSelFields = None, dry_run = False, skip_failures = False, \ updated_count_out = None, updated_failed_o...
def ogrupdate_process(src_layer, dst_layer, matchfieldname = None, update_mode = DEFAULT, \ preserve_fid = False, compare_before_update = False, \ papszSelFields = None, dry_run = False, skip_failures = False, \ updated_count_out = None, updated_failed_o...
src_layer_defn = src_layer.GetLayerDefn() dst_layer_defn = dst_layer.GetLayerDefn() if matchfieldname is not None: src_idx = src_layer.GetLayerDefn().GetFieldIndex(matchfieldname) if src_idx < 0: print('Cannot find field to match in source layer') return 1 sr...
dst_ds = None return ret ############################################################### # AreFeaturesEqual() def AreFeaturesEqual(src_feat, dst_feat): for i in range(src_feat.GetFieldCount()): src_val = src_feat.GetField(i) dst_val = dst_feat.GetField(i) if src_val != dst_val: ...
256
256
1,666
93
163
HongqiangWei/gdal
gdal/swig/python/samples/ogrupdate.py
Python
ogrupdate_process
ogrupdate_process
274
458
274
279
a94ea2e1ae263ba167b217bc846ce329089ca0c9
bigcode/the-stack
train
31682b1925179eb19db0e1e2
train
class
class TestAppsV1beta1DeploymentCondition(unittest.TestCase): """ AppsV1beta1DeploymentCondition unit test stubs """ def setUp(self): pass def tearDown(self): pass def testAppsV1beta1DeploymentCondition(self): """ Test AppsV1beta1DeploymentCondition """ ...
class TestAppsV1beta1DeploymentCondition(unittest.TestCase):
""" AppsV1beta1DeploymentCondition unit test stubs """ def setUp(self): pass def tearDown(self): pass def testAppsV1beta1DeploymentCondition(self): """ Test AppsV1beta1DeploymentCondition """ # FIXME: construct object with mandatory attributes with exam...
gen.git """ from __future__ import absolute_import import os import sys import unittest import client from client.rest import ApiException from client.models.apps_v1beta1_deployment_condition import AppsV1beta1DeploymentCondition class TestAppsV1beta1DeploymentCondition(unittest.TestCase):
64
64
110
13
50
craigtracey/python
kubernetes/test/test_apps_v1beta1_deployment_condition.py
Python
TestAppsV1beta1DeploymentCondition
TestAppsV1beta1DeploymentCondition
25
40
25
25
bc1a5a2741e49034bf978be732d79e5cac798c11
bigcode/the-stack
train
754da60d53eddd8e20914a80
train
class
class Jobs(object): pass
class Jobs(object):
pass
send_task` which sends task by name. task = current_app.tasks.get(task_id) if current_app.AsyncResult(task_id).state == 'PENDING': backend = task.backend if task else current_app.backend backend.store_result(task_id, None, 'ACCEPTED') class Jobs(object):
64
64
7
4
60
shalomb/terrestrial
worker/tasks.py
Python
Jobs
Jobs
35
36
35
35
9f74aeac9d6ccb6782267ec3ca19c8830fb89dc9
bigcode/the-stack
train
cc9f93758f0a8511d9005c46
train
function
def setup_celery(app_name, tasks, config=None): celery = Celery(app_name, include=[tasks]) if config: celery.config_from_object(config) return celery
def setup_celery(app_name, tasks, config=None):
celery = Celery(app_name, include=[tasks]) if config: celery.config_from_object(config) return celery
celery.utils.log import get_task_logger from celery.signals import after_task_publish from celery.exceptions import SoftTimeLimitExceeded # TODO # Loggers # http://docs.celeryproject.org/en/latest/userguide/tasks.html def setup_celery(app_name, tasks, config=None):
64
64
40
13
50
shalomb/terrestrial
worker/tasks.py
Python
setup_celery
setup_celery
15
19
15
15
9b3c27ee491882a1ce7d3b93399ac77362f05dd5
bigcode/the-stack
train
d8785bd6da14613fb335d278
train
function
@after_task_publish.connect def set_task_default_state(sender=None, headers=None, body=None, **kwargs): ''' Set the default status of a task to ACCEPTED instead of PENDING. This is so we can discern non-existent when looking them up by id. https://stackoverflow.com/a/10089358/742600 ''' task_id = headers['i...
@after_task_publish.connect def set_task_default_state(sender=None, headers=None, body=None, **kwargs):
''' Set the default status of a task to ACCEPTED instead of PENDING. This is so we can discern non-existent when looking them up by id. https://stackoverflow.com/a/10089358/742600 ''' task_id = headers['id'] # the task may not exist if sent using `send_task` which sends task by name. task = current_app....
def setup_celery(app_name, tasks, config=None): celery = Celery(app_name, include=[tasks]) if config: celery.config_from_object(config) return celery @after_task_publish.connect def set_task_default_state(sender=None, headers=None, body=None, **kwargs):
64
64
152
23
40
shalomb/terrestrial
worker/tasks.py
Python
set_task_default_state
set_task_default_state
21
33
21
22
38bdbe2a467b06dec31c40409ff9d254e9341343
bigcode/the-stack
train
4691a65d62cb626acb492b37
train
class
@pulumi.input_type class RegexPatternSetArgs: def __init__(__self__, *, scope: pulumi.Input[str], description: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, regular_expressions: Optional[pulumi.Input[Sequence[pulumi....
@pulumi.input_type class RegexPatternSetArgs:
def __init__(__self__, *, scope: pulumi.Input[str], description: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, regular_expressions: Optional[pulumi.Input[Sequence[pulumi.Input['RegexPatternSetRegularExpressionArgs']]...
# 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...
117
256
1,005
12
105
chivandikwa/pulumi-aws
sdk/python/pulumi_aws/wafv2/regex_pattern_set.py
Python
RegexPatternSetArgs
RegexPatternSetArgs
15
99
15
16
30b32884154ecb35077ff77168df25d8f183add6
bigcode/the-stack
train
f3909d761dc355b1f264d030
train
class
@pulumi.input_type class _RegexPatternSetState: def __init__(__self__, *, arn: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, lock_token: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = ...
@pulumi.input_type class _RegexPatternSetState:
def __init__(__self__, *, arn: Optional[pulumi.Input[str]] = None, description: Optional[pulumi.Input[str]] = None, lock_token: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, regular_expressions: Opti...
umi.Input['RegexPatternSetRegularExpressionArgs']]]]: """ One or more blocks of regular expression patterns that you want AWS WAF to search for, such as `B[a@]dB[o0]t`. See Regular Expression below for details. """ return pulumi.get(self, "regular_expressions") @regular_expressions....
256
256
1,459
13
243
chivandikwa/pulumi-aws
sdk/python/pulumi_aws/wafv2/regex_pattern_set.py
Python
_RegexPatternSetState
_RegexPatternSetState
102
231
102
103
853fa38b7a68656267bcd001c4d7360edf975549
bigcode/the-stack
train
acdbba4dad01a609258e7ecd
train
class
class RegexPatternSet(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, description: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, ...
class RegexPatternSet(pulumi.CustomResource): @overload
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, description: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, regular_expressions: Optional[pulumi.Input[Sequenc...
"scope", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: """ An array of key:value pairs to associate with the resource. .If configured with a provider `default_tags` configuration block present, tags with matching keys will overwr...
256
256
2,655
15
241
chivandikwa/pulumi-aws
sdk/python/pulumi_aws/wafv2/regex_pattern_set.py
Python
RegexPatternSet
RegexPatternSet
234
475
234
235
6a6cc7687e22844246e607926722d5e5958f5b62
bigcode/the-stack
train
2df0fbfb3961ecd1aca85ad8
train
function
def circle_to_polygon(center, radius): n = 32 coords = [] for x in range(n): coords.append(_offset(center, radius, 2 * pi * x / n)) return coords
def circle_to_polygon(center, radius):
n = 32 coords = [] for x in range(n): coords.append(_offset(center, radius, 2 * pi * x / n)) return coords
R) * cos(bearing)) lon = lon1 + atan2(sin(bearing) * sin(dByR) * cos(lat1), cos(dByR) - sin(lat1) * sin(lat)) return [degrees(lat), degrees(lon)] def circle_to_polygon(center, radius):
63
64
47
8
55
ignaloidas/savetheplanet-backend
utils.py
Python
circle_to_polygon
circle_to_polygon
60
66
60
60
2b451478a7339024616c32fe646b0bd14b7f8f8c
bigcode/the-stack
train
03886da63564b4c68d877a51
train
function
def _offset(c, distance, bearing): lat1 = radians(c[0]) lon1 = radians(c[1]) dByR = distance / 6378137 lat = asin(sin(lat1) * cos(dByR) + cos(lat1) * sin(dByR) * cos(bearing)) lon = lon1 + atan2(sin(bearing) * sin(dByR) * cos(lat1), cos(dByR) - sin(lat1) * sin(lat)) return [degrees(lat), degrees...
def _offset(c, distance, bearing):
lat1 = radians(c[0]) lon1 = radians(c[1]) dByR = distance / 6378137 lat = asin(sin(lat1) * cos(dByR) + cos(lat1) * sin(dByR) * cos(bearing)) lon = lon1 + atan2(sin(bearing) * sin(dByR) * cos(lat1), cos(dByR) - sin(lat1) * sin(lat)) return [degrees(lat), degrees(lon)]
) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = R * c return distance def _offset(c, distance, bearing):
64
64
118
9
54
ignaloidas/savetheplanet-backend
utils.py
Python
_offset
_offset
51
57
51
51
b89f66c3528b054747288b8cb4ae2ffecbac84ed
bigcode/the-stack
train
48de138bd51d8bfa1b002c3e
train
function
def chunks(iter, size): for i in range(0, len(iter), size): yield iter[i : i + size]
def chunks(iter, size):
for i in range(0, len(iter), size): yield iter[i : i + size]
) is not None: return func(user) else: abort(403, "Unauthorized") return decorator def generate_random_string(stringLength): letters = string.ascii_lowercase return "".join(random.choice(letters) for i in range(stringLength)) def chunks(iter, size):
64
64
28
6
58
ignaloidas/savetheplanet-backend
utils.py
Python
chunks
chunks
32
34
32
32
c1446e144ed3b0eeaede967ff9a3a6524fb5acd5
bigcode/the-stack
train
e551b84d8460bc4b7d41fd3c
train
function
def require_authentication(func): @wraps(func) def decorator(): if current_user.is_authenticated: return func(current_user) if (auth := request.headers.get("Authentication")) is not None and ( user := User.query.filter(User.token == auth).one_or_none() ) is not No...
def require_authentication(func): @wraps(func)
def decorator(): if current_user.is_authenticated: return func(current_user) if (auth := request.headers.get("Authentication")) is not None and ( user := User.query.filter(User.token == auth).one_or_none() ) is not None: return func(user) else: ...
import random import string from functools import wraps from math import atan2, cos, radians, sin, sqrt, asin, degrees, pi from flask import request, abort from flask_login import current_user from models import User def require_authentication(func): @wraps(func)
62
64
86
12
49
ignaloidas/savetheplanet-backend
utils.py
Python
require_authentication
require_authentication
12
24
12
13
e6d991cef90ef8bfe814628c7b44b9aa2f1f263c
bigcode/the-stack
train
fec727b347c97c7f9c79335e
train
function
def distance_between_points(lon1, lon2, lat1, lat2): lon1 = radians(lon1) lon1 = radians(lon2) lat1 = radians(lat1) lat2 = radians(lat2) R = 6373.0 dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2 c = 2 * atan2(sqrt(a), sqrt(1 ...
def distance_between_points(lon1, lon2, lat1, lat2):
lon1 = radians(lon1) lon1 = radians(lon2) lat1 = radians(lat1) lat2 = radians(lat2) R = 6373.0 dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = R * c return distance
_lowercase return "".join(random.choice(letters) for i in range(stringLength)) def chunks(iter, size): for i in range(0, len(iter), size): yield iter[i : i + size] def distance_between_points(lon1, lon2, lat1, lat2):
64
64
144
17
47
ignaloidas/savetheplanet-backend
utils.py
Python
distance_between_points
distance_between_points
37
48
37
37
b923b15910658822a7c41f90c0b59a17bd0b6366
bigcode/the-stack
train
9563431c44b35256ec1cf962
train
function
def generate_random_string(stringLength): letters = string.ascii_lowercase return "".join(random.choice(letters) for i in range(stringLength))
def generate_random_string(stringLength):
letters = string.ascii_lowercase return "".join(random.choice(letters) for i in range(stringLength))
if (auth := request.headers.get("Authentication")) is not None and ( user := User.query.filter(User.token == auth).one_or_none() ) is not None: return func(user) else: abort(403, "Unauthorized") return decorator def generate_random_string(stringLength):
64
64
32
7
56
ignaloidas/savetheplanet-backend
utils.py
Python
generate_random_string
generate_random_string
27
29
27
27
2b87eb45cfac8fb2bd831b9d5d95b1270baaa1cf
bigcode/the-stack
train
9e6eaaa0aed8356de2561428
train
function
def case_decorator(func): '''Decorator to enforce commmon behavior for cases''' def wrapboi(*args, **kwargs): clear_screen() retobj = func(*args, **kwargs) time.sleep(ccng.CASE_EXIT_WAIT_TIME) return retobj # "Inherit docstring" wrapboi.__doc__ = func.__doc__ ...
def case_decorator(func):
'''Decorator to enforce commmon behavior for cases''' def wrapboi(*args, **kwargs): clear_screen() retobj = func(*args, **kwargs) time.sleep(ccng.CASE_EXIT_WAIT_TIME) return retobj # "Inherit docstring" wrapboi.__doc__ = func.__doc__ return wrapboi
space*countlen) sys.stdout.flush() time.sleep(blink_interval) sys.stdout.write(f'\r{space*basemsglen}\r') sys.stdout.write('All threads done!') [worker.join() for worker in threads] return def case_decorator(func):
64
64
86
6
57
Napam/Stockybocky
old_code/common.py
Python
case_decorator
case_decorator
53
63
53
53
6beab01e57b97c65439c2d81dc6d671c4058ae31
bigcode/the-stack
train
8b39c797247b095d3211ef07
train
function
def join_threads(threads: list, verbose: bool = False, blink_interval: int = cng.BLINK_INTERVAL): ''' Join ongoing threads from threading module, has a verbose functionality showing the number of active threads. ''' if verbose: space = ' ' backspace = '\b' basemsg = "...
def join_threads(threads: list, verbose: bool = False, blink_interval: int = cng.BLINK_INTERVAL):
''' Join ongoing threads from threading module, has a verbose functionality showing the number of active threads. ''' if verbose: space = ' ' backspace = '\b' basemsg = "Active threads: " basemsglen = len(basemsg) sys.stdout.write(basemsg) ...
print html containers returned by beautifulsoup4''' try: strhtml = str(html_test.prettify()) except: strhtml = str(html_test) print(strhtml) return strhtml def join_threads(threads: list, verbose: bool = False, blink_interval: int = cng.BLINK_INTERVAL):
70
70
235
25
44
Napam/Stockybocky
old_code/common.py
Python
join_threads
join_threads
21
51
21
21
73471b1ca47750165c7749fd99aba0e01829c523
bigcode/the-stack
train
9cefb91cf90ab31d30a53184
train
function
def print_html(html_test): '''To print html containers returned by beautifulsoup4''' try: strhtml = str(html_test.prettify()) except: strhtml = str(html_test) print(strhtml) return strhtml
def print_html(html_test):
'''To print html containers returned by beautifulsoup4''' try: strhtml = str(html_test.prettify()) except: strhtml = str(html_test) print(strhtml) return strhtml
from bs4 import BeautifulSoup as bs import threading import time import numpy as np import sys from io import StringIO import scrapeconfig as cng import consoleconfig as ccng import os def print_html(html_test):
52
64
54
6
45
Napam/Stockybocky
old_code/common.py
Python
print_html
print_html
11
19
11
11
c8cda7570b5ed4908c891934f9aec1d8bcd40f3c
bigcode/the-stack
train
8097b7d4521d349df4f402a6
train
class
class DVTVIE(InfoExtractor): IE_NAME = 'dvtv' IE_DESC = 'http://video.aktualne.cz/' _VALID_URL = r'https?://video\.aktualne\.cz/(?:[^/]+/)+r~(?P<id>[0-9a-f]{32})' _TESTS = [{ 'url': 'http://video.aktualne.cz/dvtv/vondra-o-ceskem-stoleti-pri-pohledu-na-havla-mi-bylo-trapne/r~e5efe9ca855511e4833a0...
class DVTVIE(InfoExtractor):
IE_NAME = 'dvtv' IE_DESC = 'http://video.aktualne.cz/' _VALID_URL = r'https?://video\.aktualne\.cz/(?:[^/]+/)+r~(?P<id>[0-9a-f]{32})' _TESTS = [{ 'url': 'http://video.aktualne.cz/dvtv/vondra-o-ceskem-stoleti-pri-pohledu-na-havla-mi-bylo-trapne/r~e5efe9ca855511e4833a0025900fea04/', 'md5':...
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( determine_ext, ExtractorError, int_or_none, js_to_json, mimetype2ext, try_get, unescapeHTML, parse_iso8601, ) class DVTVIE(InfoExtractor):
79
256
2,098
8
71
hackarada/youtube-dl
youtube_dl/extractor/dvtv.py
Python
DVTVIE
DVTVIE
19
184
19
19
8d7051de8de6e0a578e4596063fd88462311682b
bigcode/the-stack
train
a9007dd6d9fa3ab1938cde64
train
function
def play_loop(): global play_game play_game = input("Do You want to play again? y = yes, n = no \n") while play_game not in ["y", "n","Y","N"]: play_game = input("Do You want to play again? y = yes, n = no \n") if play_game == "y": main() elif play_game == "n": print("Thanks ...
def play_loop():
global play_game play_game = input("Do You want to play again? y = yes, n = no \n") while play_game not in ["y", "n","Y","N"]: play_game = input("Do You want to play again? y = yes, n = no \n") if play_game == "y": main() elif play_game == "n": print("Thanks For Playing! We e...
","King","kazi"] word = random.choice(words_to_guess) length = len(word) count = 0 display = '_' * length already_guessed = [] play_game = "" # A loop to re-execute the game when the first round ends: def play_loop():
64
64
106
4
60
mk-knight23/mk-pack
mk-pack.py
Python
play_loop
play_loop
37
46
37
37
290dac2161d128d8bd24149b6591e1002c5a04c7
bigcode/the-stack
train
451235b5e5e114bde72ddfd0
train
function
def main(): global count global display global word global already_guessed global length global play_game words_to_guess = ["film","King","kazi"] word = random.choice(words_to_guess) length = len(word) count = 0 display = '_' * length already_guessed = [] play_game = ...
def main():
global count global display global word global already_guessed global length global play_game words_to_guess = ["film","King","kazi"] word = random.choice(words_to_guess) length = len(word) count = 0 display = '_' * length already_guessed = [] play_game = ""
kazi \n") name = input("Enter your name: ") print("Hello " + name + "! Best of Luck!") time.sleep(2) print("The game is about to start!\n Let's play Hangman!") time.sleep(3) # The parameters we require to execute the game: def main():
64
64
82
3
61
mk-knight23/mk-pack
mk-pack.py
Python
main
main
20
33
20
20
0729affda43d08eecbcbc84e7004ef7306dc2441
bigcode/the-stack
train
7b47112cdc8975cc3e48d5a6
train
function
def hangman(): global count global display global word global already_guessed global play_game limit = 5 guess = input("This is the Hangman Word: " + display + " Enter your guess: \n") guess = guess.strip() if len(guess.strip()) == 0 or len(guess.strip()) >= 2 or guess <= "9": ...
def hangman():
global count global display global word global already_guessed global play_game limit = 5 guess = input("This is the Hangman Word: " + display + " Enter your guess: \n") guess = guess.strip() if len(guess.strip()) == 0 or len(guess.strip()) >= 2 or guess <= "9": print("Invali...
main(): global count global display global word global already_guessed global length global play_game words_to_guess = ["film","King","kazi"] word = random.choice(words_to_guess) length = len(word) count = 0 display = '_' * length already_guessed = [] play_game = "" ...
217
217
725
4
213
mk-knight23/mk-pack
mk-pack.py
Python
hangman
hangman
49
143
49
49
b0591a900dc8ad1dfc47b02d6383936975b2e1b2
bigcode/the-stack
train
0a61cef260608b2c105d98c9
train
class
class Migration(migrations.Migration): dependencies = [ ('client', '0027_remove_client_datedenaissance'), ] operations = [ migrations.AddField( model_name='client', name='DateDeNaissance', field=models.DateField(default=django.utils.timezone.now), ...
class Migration(migrations.Migration):
dependencies = [ ('client', '0027_remove_client_datedenaissance'), ] operations = [ migrations.AddField( model_name='client', name='DateDeNaissance', field=models.DateField(default=django.utils.timezone.now), preserve_default=False, ),...
# Generated by Django 3.2.8 on 2021-10-08 16:47 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration):
44
64
71
7
36
HakoKabar/ApiRest
client/migrations/0028_client_datedenaissance.py
Python
Migration
Migration
7
20
7
8
e762d2d0b8885d1644d888032ad992fc696c3b51
bigcode/the-stack
train
6753add243517396a7df521e
train
class
class EndPointsClient(rest_client.RestClient): api_version = "v3" def list_endpoints(self, **params): """List endpoints. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3/#list-endpoints "...
class EndPointsClient(rest_client.RestClient):
api_version = "v3" def list_endpoints(self, **params): """List endpoints. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3/#list-endpoints """ url = 'endpoints' if params:...
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific la...
143
143
478
9
133
cityofships/tempest
tempest/lib/services/identity/v3/endpoints_client.py
Python
EndPointsClient
EndPointsClient
27
82
27
27
06de4d0a5b8eecf8f25bf7ef88127b65acc3079e
bigcode/the-stack
train
0db0769c2e7d74eff87583c2
train
function
def create_configparser(): if sys.version_info > (3, 0): return configparser.RawConfigParser(strict=True) else: return configparser.RawConfigParser()
def create_configparser():
if sys.version_info > (3, 0): return configparser.RawConfigParser(strict=True) else: return configparser.RawConfigParser()
""" A set of compatibility methods """ import sys from six.moves import configparser def create_configparser():
23
64
38
5
17
toumorokoshi/sprinter
sprinter/next/compat.py
Python
create_configparser
create_configparser
8
12
8
8
14865293327f626efc880160c5699225b26ce316
bigcode/the-stack
train
1cb518f308b52d0c9a4d2921
train
function
def p_test_or_starred_expr(s): if s.sy == '*': return p_starred_expr(s) else: return p_test(s)
def p_test_or_starred_expr(s):
if s.sy == '*': return p_starred_expr(s) else: return p_test(s)
) n1 = ExprNodes.PrimaryCmpNode(pos, operator = op, operand1 = n1, operand2 = n2) if s.sy in comparison_ops: n1.cascade = p_cascaded_cmp(s) return n1 def p_test_or_starred_expr(s):
64
64
33
9
54
0101011/cython
Cython/Compiler/Parsing.py
Python
p_test_or_starred_expr
p_test_or_starred_expr
206
210
206
206
001702e0b0df8307e3a347e3f7ec77a435f140e7
bigcode/the-stack
train
cbe6e668d2ef30159da39938
train
function
def p_arith_expr(s): return p_binop_expr(s, ('+', '-'), p_term)
def p_arith_expr(s):
return p_binop_expr(s, ('+', '-'), p_term)
shift_expr: arith_expr (('<<'|'>>') arith_expr)* def p_shift_expr(s): return p_binop_expr(s, ('<<', '>>'), p_arith_expr) #arith_expr: term (('+'|'-') term)* def p_arith_expr(s):
64
64
22
7
56
0101011/cython
Cython/Compiler/Parsing.py
Python
p_arith_expr
p_arith_expr
280
281
280
280
ad7129e59e939f56958eb7321122ce37371baf8f
bigcode/the-stack
train
e5f7e3621a4d5c251ccf547d
train
function
def p_assert_statement(s): # s.sy == 'assert' pos = s.position() s.next() cond = p_test(s) if s.sy == ',': s.next() value = p_test(s) else: value = None return Nodes.AssertStatNode(pos, cond = cond, value = value)
def p_assert_statement(s): # s.sy == 'assert'
pos = s.position() s.next() cond = p_test(s) if s.sy == ',': s.next() value = p_test(s) else: value = None return Nodes.AssertStatNode(pos, cond = cond, value = value)
ustring(u'.'.join(names)), as_name) def p_as_name(s): if s.sy == 'IDENT' and s.systring == 'as': s.next() return p_ident(s) else: return None def p_assert_statement(s): # s.sy == 'assert'
64
64
73
14
49
0101011/cython
Cython/Compiler/Parsing.py
Python
p_assert_statement
p_assert_statement
1,807
1,817
1,807
1,808
20362ffb979b6ba71d49493ff7484ea8f5eafedd
bigcode/the-stack
train
9850ce5b0cef8a740281f1de
train
function
def p_import_statement(s): # s.sy in ('import', 'cimport') pos = s.position() kind = s.sy s.next() items = [p_dotted_name(s, as_allowed=1)] while s.sy == ',': s.next() items.append(p_dotted_name(s, as_allowed=1)) stats = [] is_absolute = Future.absolute_import in s.contex...
def p_import_statement(s): # s.sy in ('import', 'cimport')
pos = s.position() kind = s.sy s.next() items = [p_dotted_name(s, as_allowed=1)] while s.sy == ',': s.next() items.append(p_dotted_name(s, as_allowed=1)) stats = [] is_absolute = Future.absolute_import in s.context.future_directives for pos, target_name, dotted_name, as_n...
exc_type or exc_value or exc_tb: return Nodes.RaiseStatNode(pos, exc_type = exc_type, exc_value = exc_value, exc_tb = exc_tb, cause = cause) else: return Nodes.ReraiseStatNode(pos) def p_import_statement(s): # s.sy in ('import', 'cimport')
75
75
253
18
57
0101011/cython
Cython/Compiler/Parsing.py
Python
p_import_statement
p_import_statement
1,660
1,689
1,660
1,661
24e980dcb71d253b9564487c20eb30289588c78f
bigcode/the-stack
train
5d3bb3d98dc5959864d5a990
train
function
def p_struct_enum(s, pos, ctx): if s.systring == 'enum': return p_c_enum_definition(s, pos, ctx) else: return p_c_struct_or_union_definition(s, pos, ctx)
def p_struct_enum(s, pos, ctx):
if s.systring == 'enum': return p_c_enum_definition(s, pos, ctx) else: return p_c_struct_or_union_definition(s, pos, ctx)
=1)) else: s.next() s.expect_newline() s.expect_dedent() if not types: error(pos, "Need at least one type") return Nodes.FusedTypeNode(pos, name=name, types=types) def p_struct_enum(s, pos, ctx):
64
64
48
10
54
0101011/cython
Cython/Compiler/Parsing.py
Python
p_struct_enum
p_struct_enum
3,249
3,253
3,249
3,249
4b4f2c02a80f1c283322390197497dfc81562594
bigcode/the-stack
train
4bd5ee4f33afe23e83b53c4c
train
function
def p_index(s, base): # s.sy == '[' pos = s.position() s.next() subscripts, is_single_value = p_subscript_list(s) if is_single_value and len(subscripts[0]) == 2: start, stop = subscripts[0] result = ExprNodes.SliceIndexNode(pos, base = base, start = start, stop = stop) ...
def p_index(s, base): # s.sy == '['
pos = s.position() s.next() subscripts, is_single_value = p_subscript_list(s) if is_single_value and len(subscripts[0]) == 2: start, stop = subscripts[0] result = ExprNodes.SliceIndexNode(pos, base = base, start = start, stop = stop) else: indexes = make_slice_nod...
( pos, function=function, positional_args=arg_tuple, keyword_args=keyword_dict) #lambdef: 'lambda' [varargslist] ':' test #subscriptlist: subscript (',' subscript)* [','] def p_index(s, base): # s.sy == '['
64
64
158
14
50
0101011/cython
Cython/Compiler/Parsing.py
Python
p_index
p_index
571
589
571
572
f1a7b24743f50b911934d26e4ac04b75034be2af
bigcode/the-stack
train
9bc9dbd032944a00639016cd
train
function
def p_c_simple_base_type(s, self_flag, nonempty, templates = None): #print "p_c_simple_base_type: self_flag =", self_flag, nonempty is_basic = 0 signed = 1 longness = 0 complex = 0 module_path = [] pos = s.position() # Handle const/volatile is_const = is_volatile = 0 while s.sy ...
def p_c_simple_base_type(s, self_flag, nonempty, templates = None): #print "p_c_simple_base_type: self_flag =", self_flag, nonempty
is_basic = 0 signed = 1 longness = 0 complex = 0 module_path = [] pos = s.position() # Handle const/volatile is_const = is_volatile = 0 while s.sy == 'IDENT': if s.systring == 'const': if is_const: error(pos, "Duplicate 'const'") is_const = 1 ...
base_type = p_c_base_type(s, templates=templates) declarator = p_c_declarator(s, empty=True) type_node = Nodes.CComplexBaseTypeNode( pos, base_type=base_type, declarator=declarator) if s.sy == ',': components = [type_node] while s.sy == ',': s.next() if s.sy ...
256
256
879
37
218
0101011/cython
Cython/Compiler/Parsing.py
Python
p_c_simple_base_type
p_c_simple_base_type
2,477
2,571
2,477
2,478
6f4ff64422e51a0b76dc480b422e2ebcf699a254
bigcode/the-stack
train
f47ebbe18a3dd595d7571c95
train
function
def make_slice_node(pos, start, stop = None, step = None): if not start: start = ExprNodes.NoneNode(pos) if not stop: stop = ExprNodes.NoneNode(pos) if not step: step = ExprNodes.NoneNode(pos) return ExprNodes.SliceNode(pos, start = start, stop = stop, step = step)
def make_slice_node(pos, start, stop = None, step = None):
if not start: start = ExprNodes.NoneNode(pos) if not stop: stop = ExprNodes.NoneNode(pos) if not step: step = ExprNodes.NoneNode(pos) return ExprNodes.SliceNode(pos, start = start, stop = stop, step = step)
result = [] for subscript in subscripts: if len(subscript) == 1: result.append(subscript[0]) else: result.append(make_slice_node(pos, *subscript)) return result def make_slice_node(pos, start, stop = None, step = None):
64
64
80
16
47
0101011/cython
Cython/Compiler/Parsing.py
Python
make_slice_node
make_slice_node
646
654
646
646
231de6284951160d7be2580cd625e3a43248a3a6
bigcode/the-stack
train
914dc9b1dbb8a479c3d6c58b
train
function
def looking_at_call(s): "See if we're looking at a.b.c(" # Don't mess up the original position, so save and restore it. # Unfortunately there's no good way to handle this, as a subsequent call # to next() will not advance the position until it reads a new token. position = s.start_line, s.start_col ...
def looking_at_call(s):
"See if we're looking at a.b.c(" # Don't mess up the original position, so save and restore it. # Unfortunately there's no good way to handle this, as a subsequent call # to next() will not advance the position until it reads a new token. position = s.start_line, s.start_col result = looking_at_...
_words def looking_at_dotted_name(s): if s.sy == 'IDENT': name = s.systring s.next() result = s.sy == '.' s.put_back('IDENT', name) return result else: return 0 def looking_at_call(s):
64
64
109
6
57
0101011/cython
Cython/Compiler/Parsing.py
Python
looking_at_call
looking_at_call
2,713
2,722
2,713
2,713
2683c117af588693dc9b06646e7a50b84b8d8d08
bigcode/the-stack
train
9324193ee0f70a942b62709f
train
function
def p_continue_statement(s): # s.sy == 'continue' pos = s.position() s.next() return Nodes.ContinueStatNode(pos)
def p_continue_statement(s): # s.sy == 'continue'
pos = s.position() s.next() return Nodes.ContinueStatNode(pos)
Expected a newline", ignore_semicolon=True) return Nodes.PassStatNode(pos) def p_break_statement(s): # s.sy == 'break' pos = s.position() s.next() return Nodes.BreakStatNode(pos) def p_continue_statement(s): # s.sy == 'continue'
64
64
33
14
50
0101011/cython
Cython/Compiler/Parsing.py
Python
p_continue_statement
p_continue_statement
1,615
1,619
1,615
1,616
fc324b9be230841964794a8af869c5c350b50eb1
bigcode/the-stack
train
d72a0e3b8a088b5de339ed55
train
function
def p_test_nocond(s): if s.sy == 'lambda': return p_lambdef_nocond(s) else: return p_or_test(s)
def p_test_nocond(s):
if s.sy == 'lambda': return p_lambdef_nocond(s) else: return p_or_test(s)
.expect('else') other = p_test(s) return ExprNodes.CondExprNode(pos, test=test, true_val=expr, false_val=other) else: return expr #test_nocond: or_test | lambdef_nocond def p_test_nocond(s):
64
64
37
8
55
0101011/cython
Cython/Compiler/Parsing.py
Python
p_test_nocond
p_test_nocond
154
158
154
154
50db20408e84b082985b8dee944cc7e25fb3ce79
bigcode/the-stack
train
914b2e0296b187006e56424a
train
function
def p_bit_expr(s): return p_binop_expr(s, ('|',), p_xor_expr)
def p_bit_expr(s):
return p_binop_expr(s, ('|',), p_xor_expr)
'!=' return op comparison_ops = cython.declare(set, set([ '<', '>', '==', '>=', '<=', '<>', '!=', 'in', 'is', 'not' ])) #expr: xor_expr ('|' xor_expr)* def p_bit_expr(s):
64
64
23
6
57
0101011/cython
Cython/Compiler/Parsing.py
Python
p_bit_expr
p_bit_expr
260
261
260
260
813507a256b3506b95c4da307f3affc220c2c3e3
bigcode/the-stack
train
5a1362e1f785b0cd08431703
train
function
def p_lambdef_nocond(s): return p_lambdef(s, allow_conditional=False)
def p_lambdef_nocond(s):
return p_lambdef(s, allow_conditional=False)
.LambdaNode( pos, args = args, star_arg = star_arg, starstar_arg = starstar_arg, result_expr = expr) #lambdef_nocond: 'lambda' [varargslist] ':' test_nocond def p_lambdef_nocond(s):
64
64
23
10
53
0101011/cython
Cython/Compiler/Parsing.py
Python
p_lambdef_nocond
p_lambdef_nocond
133
134
133
133
1e812a97cf99e917414ed4047f2227c0da698d11
bigcode/the-stack
train
157e03daa8a435f9caa45892
train
function
def p_def_statement(s, decorators=None, is_async_def=False): # s.sy == 'def' pos = decorators[0].pos if decorators else s.position() # PEP 492 switches the async/await keywords on in "async def" functions if is_async_def: s.enter_async() s.next() name = _reject_cdef_modifier_in_py(s, p_i...
def p_def_statement(s, decorators=None, is_async_def=False): # s.sy == 'def'
pos = decorators[0].pos if decorators else s.position() # PEP 492 switches the async/await keywords on in "async def" functions if is_async_def: s.enter_async() s.next() name = _reject_cdef_modifier_in_py(s, p_ident(s)) s.expect( '(', "Expected '(', found '%s'. Did you us...
and name in _CDEF_MODIFIERS: # Special enough to provide a good error message. s.error("Cannot use cdef modifier '%s' in Python function signature. Use a decorator instead." % name, fatal=False) return p_ident(s) # Keep going, in case there are other errors. return name def p_def_statement...
93
93
312
22
70
0101011/cython
Cython/Compiler/Parsing.py
Python
p_def_statement
p_def_statement
3,390
3,419
3,390
3,391
136c9c5e227125d8cdc6c55c7f38d083553b6599
bigcode/the-stack
train
19785d0d1eb7756dceb5deb0
train
function
def _extract_docstring(node): """ Extract a docstring from a statement or from the first statement in a list. Remove the statement if found. Return a tuple (plain-docstring or None, node). """ doc_node = None if node is None: pass elif isinstance(node, Nodes.ExprStatNode): ...
def _extract_docstring(node):
""" Extract a docstring from a statement or from the first statement in a list. Remove the statement if found. Return a tuple (plain-docstring or None, node). """ doc_node = None if node is None: pass elif isinstance(node, Nodes.ExprStatNode): if node.expr.is_string_lit...
bytes_result, unicode_result = p_cat_string_literal(s) s.expect_newline("Syntax error in doc string", ignore_semicolon=True) if kind in ('u', ''): return unicode_result warning(pos, "Python 3 requires docstrings to be unicode strings") return bytes_result else: r...
78
78
261
7
70
0101011/cython
Cython/Compiler/Parsing.py
Python
_extract_docstring
_extract_docstring
3,613
3,645
3,613
3,613
31aa6c15b8a0e386deeeeecb285428f923a2a409
bigcode/the-stack
train
b2c6265fbb6117ef0781b1d9
train
function
def p_typecast(s): # s.sy == "<" pos = s.position() s.next() base_type = p_c_base_type(s) is_memslice = isinstance(base_type, Nodes.MemoryViewSliceTypeNode) is_template = isinstance(base_type, Nodes.TemplatedTypeNode) is_const_volatile = isinstance(base_type, Nodes.CConstOrVolatileTypeNode) ...
def p_typecast(s): # s.sy == "<"
pos = s.position() s.next() base_type = p_c_base_type(s) is_memslice = isinstance(base_type, Nodes.MemoryViewSliceTypeNode) is_template = isinstance(base_type, Nodes.TemplatedTypeNode) is_const_volatile = isinstance(base_type, Nodes.CConstOrVolatileTypeNode) if not is_memslice and not is_tem...
) return ExprNodes.AmpersandNode(pos, operand = arg) elif sy == "<": return p_typecast(s) elif sy == 'IDENT' and s.systring == "sizeof": return p_sizeof(s) return p_power(s) def p_typecast(s): # s.sy == "<"
70
70
234
13
57
0101011/cython
Cython/Compiler/Parsing.py
Python
p_typecast
p_typecast
313
338
313
314
3da06d45cfa66d8342419731b7b6a596231a8b6c
bigcode/the-stack
train
3987a79320576a2f40adc396
train
function
def p_code(s, level=None, ctx=Ctx): body = p_statement_list(s, ctx(level = level), first_statement = 1) if s.sy != 'EOF': s.error("Syntax error in statement [%s,%s]" % ( repr(s.sy), repr(s.systring))) return body
def p_code(s, level=None, ctx=Ctx):
body = p_statement_list(s, ctx(level = level), first_statement = 1) if s.sy != 'EOF': s.error("Syntax error in statement [%s,%s]" % ( repr(s.sy), repr(s.systring))) return body
_node.value elif isinstance(doc_node, ExprNodes.StringNode): doc = doc_node.unicode_value if doc is None: doc = doc_node.value else: doc = doc_node.value return doc, node def p_code(s, level=None, ctx=Ctx):
64
64
68
12
51
0101011/cython
Cython/Compiler/Parsing.py
Python
p_code
p_code
3,648
3,653
3,648
3,648
0bf1496d42e4328a5539336fd04fd556d36c9981
bigcode/the-stack
train