hexsha
stringlengths 40
40
| size
int64 5
2.06M
| ext
stringclasses 10
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 3
248
| max_stars_repo_name
stringlengths 5
125
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
191k
โ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
โ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
โ | max_issues_repo_path
stringlengths 3
248
| max_issues_repo_name
stringlengths 5
125
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
67k
โ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
โ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
โ | max_forks_repo_path
stringlengths 3
248
| max_forks_repo_name
stringlengths 5
125
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
โ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
โ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
โ | content
stringlengths 5
2.06M
| avg_line_length
float64 1
1.02M
| max_line_length
int64 3
1.03M
| alphanum_fraction
float64 0
1
| count_classes
int64 0
1.6M
| score_classes
float64 0
1
| count_generators
int64 0
651k
| score_generators
float64 0
1
| count_decorators
int64 0
990k
| score_decorators
float64 0
1
| count_async_functions
int64 0
235k
| score_async_functions
float64 0
1
| count_documentation
int64 0
1.04M
| score_documentation
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
08e511f1a5de576d29d0f24338c61be5e0fb82ee | 2,250 | py | Python | multiband_melgan/dataset.py | AppleHolic/multiband_melgan | e0864d0fc205c3bdf5e19c77753e105e29a2641b | [
"MIT"
]
| 41 | 2020-06-24T08:07:23.000Z | 2022-01-24T16:39:54.000Z | multiband_melgan/dataset.py | AppleHolic/multiband_melgan | e0864d0fc205c3bdf5e19c77753e105e29a2641b | [
"MIT"
]
| 2 | 2020-06-24T08:02:15.000Z | 2020-11-23T02:56:42.000Z | multiband_melgan/dataset.py | AppleHolic/multiband_melgan | e0864d0fc205c3bdf5e19c77753e105e29a2641b | [
"MIT"
]
| 5 | 2020-07-03T04:00:50.000Z | 2020-11-04T03:24:48.000Z | import numpy as np
import librosa
import os
from pytorch_sound.data.meta.ljspeech import LJSpeechMeta
from torch.utils.data import Dataset, DataLoader
from typing import Tuple
class AudioDataset(Dataset):
def __init__(self, meta_frame, crop_length: int, seed: int = 1234):
self.meta_frame = meta_frame
self.column_name = 'audio_filename'
self.crop_length = crop_length
self.seed = seed
np.random.seed(seed)
def __getitem__(self, idx):
# get selected file path
file_path = self.meta_frame.iloc[idx][self.column_name]
# load audio
wav, _ = librosa.load(file_path, sr=None)
# wav = librosa.effects.trim(wav)[0]
# random crop
if self.crop_length:
rand_start = np.random.randint(0, (len(wav) - self.crop_length))
cropped_wav = wav[rand_start:rand_start + self.crop_length]
# crop on voiced part
while np.abs(cropped_wav).max() < 0.05 and np.random.randint(5):
rand = np.random.randint(0, max(len(wav) - 1 - self.crop_length, 1))
cropped_wav = wav[rand:rand + self.crop_length]
wav = cropped_wav
# make mask
wav_mask = np.ones_like(wav)
return wav, wav_mask
def __len__(self):
return len(self.meta_frame)
def get_datasets(meta_dir: str, batch_size: int, num_workers: int, crop_length: int, random_seed: int
) -> Tuple[DataLoader, DataLoader]:
assert os.path.isdir(meta_dir), '{} is not valid directory path!'
train_file, valid_file = LJSpeechMeta.frame_file_names[1:]
# load meta file
train_meta = LJSpeechMeta(os.path.join(meta_dir, train_file))
valid_meta = LJSpeechMeta(os.path.join(meta_dir, valid_file))
# create dataset
train_dataset = AudioDataset(train_meta, crop_length=crop_length, seed=random_seed)
valid_dataset = AudioDataset(valid_meta, crop_length=crop_length, seed=random_seed)
# create data loader
train_loader = DataLoader(train_dataset, batch_size=batch_size, num_workers=num_workers, shuffle=True)
valid_loader = DataLoader(valid_dataset, batch_size=batch_size, num_workers=num_workers)
return train_loader, valid_loader
| 34.090909 | 106 | 0.679111 | 1,163 | 0.516889 | 0 | 0 | 0 | 0 | 0 | 0 | 218 | 0.096889 |
08e85c7f00798390cfd21fa3cd1b2758063f698c | 3,830 | py | Python | yasmss/sparkmapper/sparkmapper.py | AshirwadPradhan/yasmss | 8b8b7108a3a437f0c757f19225a0c2082dbbd488 | [
"MIT"
]
| null | null | null | yasmss/sparkmapper/sparkmapper.py | AshirwadPradhan/yasmss | 8b8b7108a3a437f0c757f19225a0c2082dbbd488 | [
"MIT"
]
| 2 | 2019-09-22T03:27:20.000Z | 2019-09-22T13:56:35.000Z | yasmss/sparkmapper/sparkmapper.py | AshirwadPradhan/yasmss | 8b8b7108a3a437f0c757f19225a0c2082dbbd488 | [
"MIT"
]
| 2 | 2019-09-15T13:10:41.000Z | 2019-10-29T11:20:10.000Z | """Get the parsed query from the driver and apply transformation and action based on the
query template
"""
import time
import pyspark.sql.functions as f
from pyspark.sql import SparkSession
from pyspark.sql.types import IntegerType, StringType, StructField, StructType
import yaml
from schema import schema
with open("config.yaml", 'r') as file:
data = yaml.load(file, Loader=yaml.FullLoader)
baseURI = data['pathconfig']['host_ip_port'] + \
'/' + data['pathconfig']['input_dir']
table_format = '.csv'
class SparkJob:
"""Start a spark job based on the query template provided by the user
"""
def __init__(self):
self.queryresult = None
self.trans_actions = None
self.exectime = None
self.classType = None
def _prepareEnv(self):
spark = SparkSession.builder.master(
'local').appName('master_job').getOrCreate()
return spark
def _getKeyType(self, keyType):
if keyType == 'IntegerType':
return IntegerType()
elif keyType == 'StringType':
return StringType()
else:
raise TypeError(keyType+' is not supported')
def _getdata(self, table):
"""Read from csv using sprak.read.csv with schema
Make a YAML file to specify schema and get StructType
"""
spark = self._prepareEnv()
table_schema_dict = schema.Schema().getSchemaDict(table=table)
table_schema_structlist = []
for key, value in table_schema_dict.items():
table_schema_structlist.append(
StructField(key, self._getKeyType(value), True))
table_schema = StructType(table_schema_structlist)
table_data = spark.read.csv(
baseURI+table+table_format, schema=table_schema)
return table_data
def _computeaggr(self, df_fromtable, queryset):
df_tempg = df_fromtable.groupBy(queryset.groupcolumns)
df_tempga = df_tempg.agg({str(queryset.aggcol): str(queryset.aggfunc)})
return df_tempga
def startjob(self, queryset, classType):
self.classType = classType
if classType == 'QuerySetJoin':
start_time = time.time()
df_fromtabledata = self._getdata(queryset.fromtable)
df_jointabledata = self._getdata(queryset.jointable)
on_l = queryset.onlval.split('.')
on_r = queryset.onrval.split('.')
if on_l[1] != on_r[1]:
raise AttributeError(
'Lval and Rval of "On" condition does not match')
df_innerjoin = df_fromtabledata.join(
df_jointabledata, on=on_l[1], how='inner').orderBy(on_l[1], ascending=True)
wherecol = queryset.wherelval.split('.')[1]
try:
con_whererval = int(queryset.whererval)
filter_cond = wherecol+queryset.whereop+queryset.whererval
except ValueError:
filter_cond = wherecol+queryset.whereop+'"'+queryset.whererval+'"'
df_finalres = df_innerjoin.where(filter_cond)
self.exectime = (time.time() - start_time)
self.queryresult = df_finalres
self.trans_actions = ['join', 'where']
return self
elif classType == 'QuerySetGroupBy':
start_time = time.time()
df_fromtable = self._getdata(queryset.fromtable)
df_agg_groupby = self._computeaggr(df_fromtable, queryset)
df_finalres = df_agg_groupby.where(queryset.havcond)
self.exectime = (time.time() - start_time)
self.queryresult = df_finalres
self.trans_actions = ['groupby', 'agg', 'where']
return self
else:
raise TypeError('Unidentified Class Type')
return None
| 33.304348 | 91 | 0.621671 | 3,308 | 0.863708 | 0 | 0 | 0 | 0 | 0 | 0 | 613 | 0.160052 |
08ea5997bb021488c38f1e74924d799e82ac53bd | 17,456 | py | Python | src/rangeen/_emotes.py | khera-shanu/Rangeen | 0a7f7699c0030d28fd42211c1fb33c89ced3e857 | [
"MIT"
]
| null | null | null | src/rangeen/_emotes.py | khera-shanu/Rangeen | 0a7f7699c0030d28fd42211c1fb33c89ced3e857 | [
"MIT"
]
| null | null | null | src/rangeen/_emotes.py | khera-shanu/Rangeen | 0a7f7699c0030d28fd42211c1fb33c89ced3e857 | [
"MIT"
]
| null | null | null | class Emote:
smile = u"๐"
satisfied = u"๐"
blush = u"๐"
smiley = u"๐"
relaxed = u"โบ๏ธ"
smirk = u"๐"
heart_eyes = u"๐"
kissing_heart = u"๐"
kissing_closed_eyes = u"๐"
flushed = u"๐ณ"
relieved = u"๐"
grin = u"๐"
wink = u"๐"
stuck_out_tongue_winking_eye = u"๐"
stuck_out_tongue_closed_eyes = u"๐"
grinning = u"๐"
kissing = u"๐"
kissing_smiling_eyes = u"๐"
stuck_out_tongue = u"๐"
sleeping = u"๐ด"
worried = u"๐"
frowning = u"๐ฆ"
anguished = u"๐ง"
open_mouth = u"๐ฎ"
grimacing = u"๐ฌ"
confused = u"๐"
hushed = u"๐ฏ"
expressionless = u"๐"
unamused = u"๐"
sweat_smile = u"๐
"
sweat = u"๐"
disappointed_relieved = u"๐ฅ"
weary = u"๐ฉ"
pensive = u"๐"
disappointed = u"๐"
confounded = u"๐"
fearful = u"๐จ"
cold_sweat = u"๐ฐ"
persevere = u"๐ฃ"
cry = u"๐ข"
sob = u"๐ญ"
joy = u"๐"
astonished = u"๐ฒ"
scream = u"๐ฑ"
tired_face = u"๐ซ"
angry = u"๐ "
rage = u"๐ก"
triumph = u"๐ค"
sleepy = u"๐ช"
yum = u"๐"
mask = u"๐ท"
sunglasses = u"๐"
dizzy_face = u"๐ต"
imp = u"๐ฟ"
smiling_imp = u"๐"
neutral_face = u"๐"
no_mouth = u"๐ถ"
innocent = u"๐"
alien = u"๐ฝ"
yellow_heart = u"๐"
blue_heart = u"๐"
purple_heart = u"๐"
heart = u"โค๏ธ"
green_heart = u"๐"
broken_heart = u"๐"
heartbeat = u"๐"
heartpulse = u"๐"
two_hearts = u"๐"
revolving_hearts = u"๐"
cupid = u"๐"
sparkling_heart = u"๐"
sparkles = u"โจ"
star = u"โญ๏ธ"
star2 = u"๐"
dizzy = u"๐ซ"
collision = u"๐ฅ"
anger = u"๐ข"
heavy_exclamation_mark = u"โ๏ธ"
question = u"โ"
grey_exclamation = u"โ"
grey_question = u"โ"
zzz = u"๐ค"
dash = u"๐จ"
sweat_drops = u"๐ฆ"
notes = u"๐ถ"
musical_note = u"๐ต"
fire = u"๐ฅ"
shit = u"๐ฉ"
thumbsup = u"๐"
thumbsdown = u"๐"
ok_hand = u"๐"
facepunch = u"๐"
fist = u"โ"
v = u"โ๏ธ"
wave = u"๐"
raised_hand = u"โ"
open_hands = u"๐"
point_up = u"โ๏ธ"
point_down = u"๐"
point_left = u"๐"
point_right = u"๐"
raised_hands = u"๐"
pray = u"๐"
point_up_2 = u"๐"
clap = u"๐"
muscle = u"๐ช"
metal = u"๐ค"
fu = u"๐"
walking = u"๐ถ"
running = u"๐"
couple = u"๐ซ"
family = u"๐ช"
two_men_holding_hands = u"๐ฌ"
two_women_holding_hands = u"๐ญ"
dancer = u"๐"
dancers = u"๐ฏ"
ok_woman = u"๐"
no_good = u"๐
"
information_desk_person = u"๐"
raising_hand = u"๐"
bride_with_veil = u"๐ฐ"
person_with_pouting_face = u"๐"
person_frowning = u"๐"
bow = u"๐"
couple_with_heart = u"๐"
massage = u"๐"
haircut = u"๐"
nail_care = u"๐
"
boy = u"๐ฆ"
girl = u"๐ง"
woman = u"๐ฉ"
man = u"๐จ"
baby = u"๐ถ"
older_woman = u"๐ต"
older_man = u"๐ด"
person_with_blond_hair = u"๐ฑ"
man_with_gua_pi_mao = u"๐ฒ"
man_with_turban = u"๐ณ"
construction_worker = u"๐ท"
cop = u"๐ฎ"
angel = u"๐ผ"
princess = u"๐ธ"
smiley_cat = u"๐บ"
smile_cat = u"๐ธ"
heart_eyes_cat = u"๐ป"
kissing_cat = u"๐ฝ"
smirk_cat = u"๐ผ"
scream_cat = u"๐"
crying_cat_face = u"๐ฟ"
joy_cat = u"๐น"
pouting_cat = u"๐พ"
japanese_ogre = u"๐น"
japanese_goblin = u"๐บ"
see_no_evil = u"๐"
hear_no_evil = u"๐"
speak_no_evil = u"๐"
guardsman = u"๐"
skull = u"๐"
paw_prints = u"๐พ"
lips = u"๐"
kiss = u"๐"
droplet = u"๐ง"
ear = u"๐"
eyes = u"๐"
nose = u"๐"
tongue = u"๐
"
love_letter = u"๐"
bust_in_silhouette = u"๐ค"
busts_in_silhouette = u"๐ฅ"
speech_balloon = u"๐ฌ"
thought_balloon = u"๐ญ"
sunny = u"โ๏ธ"
umbrella = u"โ๏ธ"
cloud = u"โ๏ธ"
snowflake = u"โ๏ธ"
snowman = u"โ๏ธ"
zap = u"โก๏ธ"
cyclone = u"๐"
foggy = u"๐"
ocean = u"๐"
cat = u"๐ฑ"
dog = u"๐ถ"
mouse = u"๐ญ"
hamster = u"๐น"
rabbit = u"๐ฐ"
wolf = u"๐บ"
frog = u"๐ธ"
tiger = u"๐ฏ"
koala = u"๐จ"
bear = u"๐ป"
pig = u"๐ท"
pig_nose = u"๐ฝ"
cow = u"๐ฎ"
boar = u"๐"
monkey_face = u"๐ต"
monkey = u"๐"
horse = u"๐ด"
racehorse = u"๐"
camel = u"๐ซ"
sheep = u"๐"
elephant = u"๐"
panda_face = u"๐ผ"
snake = u"๐"
bird = u"๐ฆ"
baby_chick = u"๐ค"
hatched_chick = u"๐ฅ"
hatching_chick = u"๐ฃ"
chicken = u"๐"
penguin = u"๐ง"
turtle = u"๐ข"
bug = u"๐"
honeybee = u"๐"
ant = u"๐"
beetle = u"๐"
snail = u"๐"
octopus = u"๐"
tropical_fish = u"๐ "
fish = u"๐"
whale = u"๐ณ"
whale2 = u"๐"
dolphin = u"๐ฌ"
cow2 = u"๐"
ram = u"๐"
rat = u"๐"
water_buffalo = u"๐"
tiger2 = u"๐
"
rabbit2 = u"๐"
dragon = u"๐"
goat = u"๐"
rooster = u"๐"
dog2 = u"๐"
pig2 = u"๐"
mouse2 = u"๐"
ox = u"๐"
dragon_face = u"๐ฒ"
blowfish = u"๐ก"
crocodile = u"๐"
dromedary_camel = u"๐ช"
leopard = u"๐"
cat2 = u"๐"
poodle = u"๐ฉ"
bouquet = u"๐"
cherry_blossom = u"๐ธ"
tulip = u"๐ท"
four_leaf_clover = u"๐"
rose = u"๐น"
sunflower = u"๐ป"
hibiscus = u"๐บ"
maple_leaf = u"๐"
leaves = u"๐"
fallen_leaf = u"๐"
herb = u"๐ฟ"
mushroom = u"๐"
cactus = u"๐ต"
palm_tree = u"๐ด"
evergreen_tree = u"๐ฒ"
deciduous_tree = u"๐ณ"
chestnut = u"๐ฐ"
seedling = u"๐ฑ"
blossom = u"๐ผ"
ear_of_rice = u"๐พ"
shell = u"๐"
globe_with_meridians = u"๐"
sun_with_face = u"๐"
full_moon_with_face = u"๐"
new_moon_with_face = u"๐"
new_moon = u"๐"
waxing_crescent_moon = u"๐"
first_quarter_moon = u"๐"
moon = u"๐"
full_moon = u"๐"
waning_gibbous_moon = u"๐"
last_quarter_moon = u"๐"
waning_crescent_moon = u"๐"
last_quarter_moon_with_face = u"๐"
first_quarter_moon_with_face = u"๐"
earth_africa = u"๐"
earth_americas = u"๐"
earth_asia = u"๐"
volcano = u"๐"
milky_way = u"๐"
partly_sunny = u"โ
๏ธ"
bamboo = u"๐"
gift_heart = u"๐"
dolls = u"๐"
school_satchel = u"๐"
mortar_board = u"๐"
flags = u"๐"
fireworks = u"๐"
sparkler = u"๐"
wind_chime = u"๐"
rice_scene = u"๐"
jack_o_lantern = u"๐"
ghost = u"๐ป"
santa = u"๐
"
christmas_tree = u"๐"
gift = u"๐"
bell = u"๐"
no_bell = u"๐"
tanabata_tree = u"๐"
tada = u"๐"
confetti_ball = u"๐"
balloon = u"๐"
crystal_ball = u"๐ฎ"
cd = u"๐ฟ"
dvd = u"๐"
floppy_disk = u"๐พ"
camera = u"๐ท"
video_camera = u"๐น"
movie_camera = u"๐ฅ"
computer = u"๐ป"
tv = u"๐บ"
iphone = u"๐ฑ"
telephone = u"โ๏ธ"
telephone_receiver = u"๐"
pager = u"๐"
fax = u"๐ "
minidisc = u"๐ฝ"
vhs = u"๐ผ"
sound = u"๐"
speaker = u"๐"
mute = u"๐"
loudspeaker = u"๐ข"
mega = u"๐ฃ"
hourglass = u"โ๏ธ"
hourglass_flowing_sand = u"โณ"
alarm_clock = u"โฐ"
watch = u"โ๏ธ"
radio = u"๐ป"
satellite = u"๐ก"
loop = u"โฟ"
mag = u"๐"
mag_right = u"๐"
unlock = u"๐"
lock = u"๐"
lock_with_ink_pen = u"๐"
closed_lock_with_key = u"๐"
key = u"๐"
bulb = u"๐ก"
flashlight = u"๐ฆ"
high_brightness = u"๐"
low_brightness = u"๐
"
electric_plug = u"๐"
battery = u"๐"
calling = u"๐ฒ"
envelope = u"โ๏ธ"
mailbox = u"๐ซ"
postbox = u"๐ฎ"
bath = u"๐"
bathtub = u"๐"
shower = u"๐ฟ"
toilet = u"๐ฝ"
wrench = u"๐ง"
nut_and_bolt = u"๐ฉ"
hammer = u"๐จ"
seat = u"๐บ"
moneybag = u"๐ฐ"
yen = u"๐ด"
dollar = u"๐ต"
pound = u"๐ท"
euro = u"๐ถ"
credit_card = u"๐ณ"
money_with_wings = u"๐ธ"
e_mail = u"๐ง"
inbox_tray = u"๐ฅ"
outbox_tray = u"๐ค"
incoming_envelope = u"๐จ"
postal_horn = u"๐ฏ"
mailbox_closed = u"๐ช"
mailbox_with_mail = u"๐ฌ"
mailbox_with_no_mail = u"๐ญ"
door = u"๐ช"
smoking = u"๐ฌ"
bomb = u"๐ฃ"
gun = u"๐ซ"
hocho = u"๐ช"
pill = u"๐"
syringe = u"๐"
page_facing_up = u"๐"
page_with_curl = u"๐"
bookmark_tabs = u"๐"
bar_chart = u"๐"
chart_with_upwards_trend = u"๐"
chart_with_downwards_trend = u"๐"
scroll = u"๐"
clipboard = u"๐"
calendar = u"๐"
date = u"๐
"
card_index = u"๐"
file_folder = u"๐"
open_file_folder = u"๐"
scissors = u"โ๏ธ"
pushpin = u"๐"
paperclip = u"๐"
black_nib = u"โ๏ธ"
pencil2 = u"โ๏ธ"
straight_ruler = u"๐"
triangular_ruler = u"๐"
closed_book = u"๐"
green_book = u"๐"
blue_book = u"๐"
orange_book = u"๐"
notebook = u"๐"
notebook_with_decorative_cover = u"๐"
ledger = u"๐"
books = u"๐"
bookmark = u"๐"
name_badge = u"๐"
microscope = u"๐ฌ"
telescope = u"๐ญ"
newspaper = u"๐ฐ"
football = u"๐"
basketball = u"๐"
soccer = u"โฝ๏ธ"
baseball = u"โพ๏ธ"
tennis = u"๐พ"
_8ball = u"๐ฑ"
rugby_football = u"๐"
bowling = u"๐ณ"
golf = u"โณ๏ธ"
mountain_bicyclist = u"๐ต"
bicyclist = u"๐ด"
horse_racing = u"๐"
snowboarder = u"๐"
swimmer = u"๐"
surfer = u"๐"
ski = u"๐ฟ"
spades = u"โ ๏ธ"
hearts = u"โฅ๏ธ"
clubs = u"โฃ๏ธ"
diamonds = u"โฆ๏ธ"
gem = u"๐"
ring = u"๐"
trophy = u"๐"
musical_score = u"๐ผ"
musical_keyboard = u"๐น"
violin = u"๐ป"
space_invader = u"๐พ"
video_game = u"๐ฎ"
black_joker = u"๐"
flower_playing_cards = u"๐ด"
game_die = u"๐ฒ"
dart = u"๐ฏ"
mahjong = u"๐๏ธ"
clapper = u"๐ฌ"
pencil = u"๐"
book = u"๐"
art = u"๐จ"
microphone = u"๐ค"
headphones = u"๐ง"
trumpet = u"๐บ"
saxophone = u"๐ท"
guitar = u"๐ธ"
mans_shoe = u"๐"
sandal = u"๐ก"
high_heel = u"๐ "
lipstick = u"๐"
boot = u"๐ข"
tshirt = u"๐"
necktie = u"๐"
womans_clothes = u"๐"
dress = u"๐"
running_shirt_with_sash = u"๐ฝ"
jeans = u"๐"
kimono = u"๐"
bikini = u"๐"
ribbon = u"๐"
tophat = u"๐ฉ"
crown = u"๐"
womans_hat = u"๐"
closed_umbrella = u"๐"
briefcase = u"๐ผ"
handbag = u"๐"
pouch = u"๐"
purse = u"๐"
eyeglasses = u"๐"
fishing_pole_and_fish = u"๐ฃ"
coffee = u"โ๏ธ"
tea = u"๐ต"
sake = u"๐ถ"
baby_bottle = u"๐ผ"
beer = u"๐บ"
beers = u"๐ป"
cocktail = u"๐ธ"
tropical_drink = u"๐น"
wine_glass = u"๐ท"
fork_and_knife = u"๐ด"
pizza = u"๐"
hamburger = u"๐"
fries = u"๐"
poultry_leg = u"๐"
meat_on_bone = u"๐"
spaghetti = u"๐"
curry = u"๐"
fried_shrimp = u"๐ค"
bento = u"๐ฑ"
sushi = u"๐ฃ"
fish_cake = u"๐ฅ"
rice_ball = u"๐"
rice_cracker = u"๐"
rice = u"๐"
ramen = u"๐"
stew = u"๐ฒ"
oden = u"๐ข"
dango = u"๐ก"
egg = u"๐ฅ"
bread = u"๐"
doughnut = u"๐ฉ"
custard = u"๐ฎ"
icecream = u"๐ฆ"
ice_cream = u"๐จ"
shaved_ice = u"๐ง"
birthday = u"๐"
cake = u"๐ฐ"
cookie = u"๐ช"
chocolate_bar = u"๐ซ"
candy = u"๐ฌ"
lollipop = u"๐ญ"
honey_pot = u"๐ฏ"
apple = u"๐"
green_apple = u"๐"
tangerine = u"๐"
lemon = u"๐"
cherries = u"๐"
grapes = u"๐"
watermelon = u"๐"
strawberry = u"๐"
peach = u"๐"
melon = u"๐"
banana = u"๐"
pear = u"๐"
pineapple = u"๐"
sweet_potato = u"๐ "
eggplant = u"๐"
tomato = u"๐
"
corn = u"๐ฝ"
house = u"๐ "
house_with_garden = u"๐ก"
school = u"๐ซ"
office = u"๐ข"
post_office = u"๐ฃ"
hospital = u"๐ฅ"
bank = u"๐ฆ"
convenience_store = u"๐ช"
love_hotel = u"๐ฉ"
hotel = u"๐จ"
wedding = u"๐"
church = u"โช๏ธ"
department_store = u"๐ฌ"
european_post_office = u"๐ค"
city_sunrise = u"๐"
city_sunset = u"๐"
japanese_castle = u"๐ฏ"
european_castle = u"๐ฐ"
tent = u"โบ๏ธ"
factory = u"๐ญ"
tokyo_tower = u"๐ผ"
japan = u"๐พ"
mount_fuji = u"๐ป"
sunrise_over_mountains = u"๐"
sunrise = u"๐
"
stars = u"๐ "
statue_of_liberty = u"๐ฝ"
bridge_at_night = u"๐"
carousel_horse = u"๐ "
rainbow = u"๐"
ferris_wheel = u"๐ก"
fountain = u"โฒ๏ธ"
roller_coaster = u"๐ข"
ship = u"๐ข"
speedboat = u"๐ค"
sailboat = u"โต๏ธ"
rowboat = u"๐ฃ"
anchor = u"โ๏ธ"
rocket = u"๐"
airplane = u"โ๏ธ"
helicopter = u"๐"
steam_locomotive = u"๐"
tram = u"๐"
mountain_railway = u"๐"
bike = u"๐ฒ"
aerial_tramway = u"๐ก"
suspension_railway = u"๐"
mountain_cableway = u"๐ "
tractor = u"๐"
blue_car = u"๐"
oncoming_automobile = u"๐"
red_car = u"๐"
taxi = u"๐"
oncoming_taxi = u"๐"
articulated_lorry = u"๐"
bus = u"๐"
oncoming_bus = u"๐"
rotating_light = u"๐จ"
police_car = u"๐"
oncoming_police_car = u"๐"
fire_engine = u"๐"
ambulance = u"๐"
minibus = u"๐"
truck = u"๐"
train = u"๐"
station = u"๐"
train2 = u"๐"
bullettrain_front = u"๐
"
bullettrain_side = u"๐"
light_rail = u"๐"
monorail = u"๐"
railway_car = u"๐"
trolleybus = u"๐"
ticket = u"๐ซ"
fuelpump = u"โฝ๏ธ"
vertical_traffic_light = u"๐ฆ"
traffic_light = u"๐ฅ"
warning = u"โ ๏ธ"
construction = u"๐ง"
beginner = u"๐ฐ"
atm = u"๐ง"
slot_machine = u"๐ฐ"
busstop = u"๐"
barber = u"๐"
hotsprings = u"โจ๏ธ"
checkered_flag = u"๐"
crossed_flags = u"๐"
izakaya_lantern = u"๐ฎ"
moyai = u"๐ฟ"
circus_tent = u"๐ช"
performing_arts = u"๐ญ"
round_pushpin = u"๐"
triangular_flag_on_post = u"๐ฉ"
one = u"1๏ธโฃ"
two = u"2๏ธโฃ"
three = u"3๏ธโฃ"
four = u"4๏ธโฃ"
five = u"5๏ธโฃ"
six = u"6๏ธโฃ"
seven = u"7๏ธโฃ"
eight = u"8๏ธโฃ"
nine = u"9๏ธโฃ"
keycap_ten = u"๐"
_1234 = u"๐ข"
zero = u"0๏ธโฃ"
hash = u"#๏ธโฃ"
symbols = u"๐ฃ"
arrow_backward = u"โ๏ธ"
arrow_down = u"โฌ๏ธ"
arrow_forward = u"โถ๏ธ"
arrow_left = u"โฌ
๏ธ"
capital_abcd = u"๐ "
abcd = u"๐ก"
abc = u"๐ค"
arrow_lower_left = u"โ๏ธ"
arrow_lower_right = u"โ๏ธ"
arrow_right = u"โก๏ธ"
arrow_up = u"โฌ๏ธ"
arrow_upper_left = u"โ๏ธ"
arrow_upper_right = u"โ๏ธ"
arrow_double_down = u"โฌ"
arrow_double_up = u"โซ"
arrow_down_small = u"๐ฝ"
arrow_heading_down = u"โคต๏ธ"
arrow_heading_up = u"โคด๏ธ"
leftwards_arrow_with_hook = u"โฉ๏ธ"
arrow_right_hook = u"โช๏ธ"
left_right_arrow = u"โ๏ธ"
arrow_up_down = u"โ๏ธ"
arrow_up_small = u"๐ผ"
arrows_clockwise = u"๐"
arrows_counterclockwise = u"๐"
rewind = u"โช"
fast_forward = u"โฉ"
information_source = u"โน๏ธ"
ok = u"๐"
twisted_rightwards_arrows = u"๐"
repeat = u"๐"
repeat_one = u"๐"
new = u"๐"
top = u"๐"
up = u"๐"
cool = u"๐"
free = u"๐"
ng = u"๐"
cinema = u"๐ฆ"
koko = u"๐"
signal_strength = u"๐ถ"
u5272 = u"๐น"
u5408 = u"๐ด"
u55b6 = u"๐บ"
u6307 = u"๐ฏ๏ธ"
u6708 = u"๐ท๏ธ"
u6709 = u"๐ถ"
u6e80 = u"๐ต"
u7121 = u"๐๏ธ"
u7533 = u"๐ธ"
u7a7a = u"๐ณ"
u7981 = u"๐ฒ"
sa = u"๐๏ธ"
restroom = u"๐ป"
mens = u"๐น"
womens = u"๐บ"
baby_symbol = u"๐ผ"
no_smoking = u"๐ญ"
parking = u"๐
ฟ๏ธ"
wheelchair = u"โฟ๏ธ"
metro = u"๐"
baggage_claim = u"๐"
accept = u"๐"
wc = u"๐พ"
potable_water = u"๐ฐ"
put_litter_in_its_place = u"๐ฎ"
secret = u"ใ๏ธ"
congratulations = u"ใ๏ธ"
m = u"โ๏ธ"
passport_control = u"๐"
left_luggage = u"๐
"
customs = u"๐"
ideograph_advantage = u"๐"
cl = u"๐"
sos = u"๐"
id = u"๐"
no_entry_sign = u"๐ซ"
underage = u"๐"
no_mobile_phones = u"๐ต"
do_not_litter = u"๐ฏ"
non_potable_water = u"๐ฑ"
no_bicycles = u"๐ณ"
no_pedestrians = u"๐ท"
children_crossing = u"๐ธ"
no_entry = u"โ๏ธ"
eight_spoked_asterisk = u"โณ๏ธ"
eight_pointed_black_star = u"โด๏ธ"
heart_decoration = u"๐"
vs = u"๐"
vibration_mode = u"๐ณ"
mobile_phone_off = u"๐ด"
chart = u"๐น"
currency_exchange = u"๐ฑ"
aries = u"โ๏ธ"
taurus = u"โ๏ธ"
gemini = u"โ๏ธ"
cancer = u"โ๏ธ"
leo = u"โ๏ธ"
virgo = u"โ๏ธ"
libra = u"โ๏ธ"
scorpius = u"โ๏ธ"
sagittarius = u"โ๏ธ"
capricorn = u"โ๏ธ"
aquarius = u"โ๏ธ"
pisces = u"โ๏ธ"
ophiuchus = u"โ"
six_pointed_star = u"๐ฏ"
negative_squared_cross_mark = u"โ"
a = u"๐
ฐ๏ธ"
b = u"๐
ฑ๏ธ"
ab = u"๐"
o2 = u"๐
พ๏ธ"
diamond_shape_with_a_dot_inside = u"๐ "
recycle = u"โป๏ธ"
end = u"๐"
on = u"๐"
soon = u"๐"
clock1 = u"๐"
clock130 = u"๐"
clock10 = u"๐"
clock1030 = u"๐ฅ"
clock11 = u"๐"
clock1130 = u"๐ฆ"
clock12 = u"๐"
clock1230 = u"๐ง"
clock2 = u"๐"
clock230 = u"๐"
clock3 = u"๐"
clock330 = u"๐"
clock4 = u"๐"
clock430 = u"๐"
clock5 = u"๐"
clock530 = u"๐ "
clock6 = u"๐"
clock630 = u"๐ก"
clock7 = u"๐"
clock730 = u"๐ข"
clock8 = u"๐"
clock830 = u"๐ฃ"
clock9 = u"๐"
clock930 = u"๐ค"
heavy_dollar_sign = u"๐ฒ"
copyright = u"ยฉ๏ธ"
registered = u"ยฎ๏ธ"
tm = u"โข๏ธ"
x = u"โ"
bangbang = u"โผ๏ธ"
interrobang = u"โ๏ธ"
o = u"โญ๏ธ"
heavy_multiplication_x = u"โ๏ธ"
heavy_plus_sign = u"โ"
heavy_minus_sign = u"โ"
heavy_division_sign = u"โ"
white_flower = u"๐ฎ"
_100 = u"๐ฏ"
heavy_check_mark = u"โ๏ธ"
ballot_box_with_check = u"โ๏ธ"
radio_button = u"๐"
link = u"๐"
curly_loop = u"โฐ"
wavy_dash = u"ใฐ๏ธ"
part_alternation_mark = u"ใฝ๏ธ"
trident = u"๐ฑ"
white_check_mark = u"โ
"
black_square_button = u"๐ฒ"
white_square_button = u"๐ณ"
black_circle = u"โซ๏ธ"
white_circle = u"โช๏ธ"
red_circle = u"๐ด"
large_blue_circle = u"๐ต"
large_blue_diamond = u"๐ท"
large_orange_diamond = u"๐ถ"
small_blue_diamond = u"๐น"
small_orange_diamond = u"๐ธ"
small_red_triangle = u"๐บ"
small_red_triangle_down = u"๐ป"
| 21.261876 | 42 | 0.477601 | 20,005 | 0.99995 | 0 | 0 | 0 | 0 | 0 | 0 | 5,944 | 0.297111 |
08ee02203bdf0fc6105effa49f09100d9294242e | 8,412 | py | Python | main_gui.py | vedymin/All_IPG_Move | b8b079fd471709731a7550cec3a5add3db409b81 | [
"MIT"
]
| null | null | null | main_gui.py | vedymin/All_IPG_Move | b8b079fd471709731a7550cec3a5add3db409b81 | [
"MIT"
]
| null | null | null | main_gui.py | vedymin/All_IPG_Move | b8b079fd471709731a7550cec3a5add3db409b81 | [
"MIT"
]
| null | null | null | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main_gui.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(400, 250)
MainWindow.setMinimumSize(QtCore.QSize(400, 250))
MainWindow.setMaximumSize(QtCore.QSize(400, 250))
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.new_hd_check = QtWidgets.QCheckBox(self.centralwidget)
font = QtGui.QFont()
font.setPointSize(14)
self.new_hd_check.setFont(font)
self.new_hd_check.setObjectName("new_hd_check")
self.horizontalLayout.addWidget(self.new_hd_check)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem1)
self.location_label = QtWidgets.QLabel(self.centralwidget)
font = QtGui.QFont()
font.setPointSize(14)
self.location_label.setFont(font)
self.location_label.setObjectName("location_label")
self.horizontalLayout.addWidget(self.location_label)
self.location_line_edit = QtWidgets.QLineEdit(self.centralwidget)
self.location_line_edit.setObjectName("location_line_edit")
self.horizontalLayout.addWidget(self.location_line_edit)
self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 1)
self.to_layout = QtWidgets.QHBoxLayout()
self.to_layout.setObjectName("to_layout")
self.to_label = QtWidgets.QLabel(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(4)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.to_label.sizePolicy().hasHeightForWidth())
self.to_label.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(17)
self.to_label.setFont(font)
self.to_label.setAlignment(QtCore.Qt.AlignCenter)
self.to_label.setObjectName("to_label")
self.to_layout.addWidget(self.to_label)
self.to_line_edit = QtWidgets.QLineEdit(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(8)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.to_line_edit.sizePolicy().hasHeightForWidth())
self.to_line_edit.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(15)
self.to_line_edit.setFont(font)
self.to_line_edit.setObjectName("to_line_edit")
self.to_layout.addWidget(self.to_line_edit)
self.gridLayout.addLayout(self.to_layout, 5, 0, 1, 1)
self.start_button = QtWidgets.QPushButton(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.start_button.sizePolicy().hasHeightForWidth())
self.start_button.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(17)
self.start_button.setFont(font)
self.start_button.setObjectName("start_button")
self.gridLayout.addWidget(self.start_button, 6, 0, 1, 1)
self.from_layout = QtWidgets.QHBoxLayout()
self.from_layout.setObjectName("from_layout")
self.from_label = QtWidgets.QLabel(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(4)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.from_label.sizePolicy().hasHeightForWidth())
self.from_label.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(17)
self.from_label.setFont(font)
self.from_label.setAlignment(QtCore.Qt.AlignCenter)
self.from_label.setObjectName("from_label")
self.from_layout.addWidget(self.from_label)
self.from_line_edit = QtWidgets.QLineEdit(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(8)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.from_line_edit.sizePolicy().hasHeightForWidth())
self.from_line_edit.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(15)
self.from_line_edit.setFont(font)
self.from_line_edit.setInputMask("")
self.from_line_edit.setObjectName("from_line_edit")
self.from_layout.addWidget(self.from_line_edit)
self.gridLayout.addLayout(self.from_layout, 4, 0, 1, 1)
self.session_layout = QtWidgets.QHBoxLayout()
self.session_layout.setObjectName("session_layout")
self.choose_session_label = QtWidgets.QLabel(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.choose_session_label.sizePolicy().hasHeightForWidth())
self.choose_session_label.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(11)
self.choose_session_label.setFont(font)
self.choose_session_label.setToolTipDuration(-1)
self.choose_session_label.setAlignment(QtCore.Qt.AlignCenter)
self.choose_session_label.setObjectName("choose_session_label")
self.session_layout.addWidget(self.choose_session_label)
self.choose_session_combo = QtWidgets.QComboBox(self.centralwidget)
self.choose_session_combo.setObjectName("choose_session_combo")
self.session_layout.addWidget(self.choose_session_combo)
self.refresh_session_button = QtWidgets.QPushButton(self.centralwidget)
self.refresh_session_button.setObjectName("refresh_session_button")
self.session_layout.addWidget(self.refresh_session_button)
self.gridLayout.addLayout(self.session_layout, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 400, 21))
self.menubar.setObjectName("menubar")
self.menuVersion = QtWidgets.QMenu(self.menubar)
self.menuVersion.setObjectName("menuVersion")
MainWindow.setMenuBar(self.menubar)
self.menubar.addAction(self.menuVersion.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "HD-HD Move"))
self.new_hd_check.setText(_translate("MainWindow", "New HD"))
self.location_label.setText(_translate("MainWindow", "Location:"))
self.to_label.setText(_translate("MainWindow", "To HD:"))
self.start_button.setText(_translate("MainWindow", "Start"))
self.from_label.setText(_translate("MainWindow", "From HD:"))
self.choose_session_label.setText(_translate("MainWindow", "Choose session:"))
self.refresh_session_button.setText(_translate("MainWindow", "Refresh list"))
self.menuVersion.setTitle(_translate("MainWindow", "Version"))
| 54.980392 | 116 | 0.714812 | 8,158 | 0.969805 | 0 | 0 | 0 | 0 | 0 | 0 | 703 | 0.083571 |
08f00026b0a8d4a6cccad1a88563ce7a5b83f749 | 1,522 | py | Python | src/config.py | DQiaole/ZITS | 5f7a060167790789d5e29a3d14d3c2ef8a34e765 | [
"Apache-2.0"
]
| 40 | 2022-03-02T06:12:43.000Z | 2022-03-30T02:17:02.000Z | src/config.py | DQiaole/ZITS | 5f7a060167790789d5e29a3d14d3c2ef8a34e765 | [
"Apache-2.0"
]
| 6 | 2022-03-06T03:53:14.000Z | 2022-03-31T06:36:34.000Z | src/config.py | DQiaole/ZITS | 5f7a060167790789d5e29a3d14d3c2ef8a34e765 | [
"Apache-2.0"
]
| 5 | 2022-03-04T06:39:44.000Z | 2022-03-28T04:58:32.000Z | import os
import yaml
class Config(dict):
def __init__(self, config_path):
with open(config_path, 'r') as f:
self._yaml = f.read()
self._dict = yaml.load(self._yaml, Loader=yaml.FullLoader)
self._dict['PATH'] = os.path.dirname(config_path)
def __getattr__(self, name):
if self._dict.get(name) is not None:
return self._dict[name]
if DEFAULT_CONFIG.get(name) is not None:
return DEFAULT_CONFIG[name]
return None
def print(self):
print('Model configurations:')
print('---------------------------------')
print(self._yaml)
print('')
print('---------------------------------')
print('')
DEFAULT_CONFIG = {
'SEED': 10, # random seed
'BATCH_SIZE': 8, # input batch size for training
'INPUT_SIZE': 256, # input image size for training 0 for original size
'MAX_ITERS': 1e6, # maximum number of iterations to train the model
'SAVE_INTERVAL': 1000, # how many iterations to wait before saving model (0: never)
'SAMPLE_INTERVAL': 1000, # how many iterations to wait before sampling (0: never)
'SAMPLE_SIZE': 12, # number of images to sample
'EVAL_INTERVAL': 0, # how many iterations to wait before model evaluation (0: never)
'LOG_INTERVAL': 10, # how many iterations to wait before logging training status (0: never)
}
| 35.395349 | 107 | 0.557819 | 716 | 0.470434 | 0 | 0 | 0 | 0 | 0 | 0 | 644 | 0.423127 |
08f0432c93f8f390bd7d7a71479785cb462167ba | 8,786 | py | Python | examples/acados_python/test/generate_c_code.py | besticka/acados | 32767a19aed01a15b5e7b83ebc6ddbd669a47954 | [
"BSD-2-Clause"
]
| null | null | null | examples/acados_python/test/generate_c_code.py | besticka/acados | 32767a19aed01a15b5e7b83ebc6ddbd669a47954 | [
"BSD-2-Clause"
]
| null | null | null | examples/acados_python/test/generate_c_code.py | besticka/acados | 32767a19aed01a15b5e7b83ebc6ddbd669a47954 | [
"BSD-2-Clause"
]
| null | null | null | #
# Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren,
# Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor,
# Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan,
# Jonas Koenemann, Yutao Chen, Tobias Schรถls, Jonas Schlagenhauf, Moritz Diehl
#
# This file is part of acados.
#
# The 2-Clause BSD License
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.;
#
from acados_template import *
import acados_template as at
from export_ode_model import *
import numpy as np
import scipy.linalg
from ctypes import *
import json
import argparse
# set to 'True' to generate test data
GENERATE_DATA = False
LOCAL_TEST = False
TEST_TOL = 1e-8
if LOCAL_TEST is True:
FORMULATION = 'LS'
SOLVER_TYPE = 'SQP_RTI'
QP_SOLVER = 'FULL_CONDENSING_QPOASES'
INTEGRATOR_TYPE = 'IRK'
else:
parser = argparse.ArgumentParser(description='test Python interface on pendulum example.')
parser.add_argument('--FORMULATION', dest='FORMULATION',
default='LS',
help='FORMULATION: linear least-squares (LS) or nonlinear \
least-squares (NLS) (default: LS)')
parser.add_argument('--QP_SOLVER', dest='QP_SOLVER',
default='PARTIAL_CONDENSING_HPIPM',
help='QP_SOLVER: PARTIAL_CONDENSING_HPIPM, FULL_CONDENSING_HPIPM, ' \
'FULL_CONDENSING_HPIPM (default: PARTIAL_CONDENSING_HPIPM)')
parser.add_argument('--INTEGRATOR_TYPE', dest='INTEGRATOR_TYPE',
default='ERK',
help='INTEGRATOR_TYPE: explicit (ERK) or implicit (IRK) ' \
' Runge-Kutta (default: ERK)')
parser.add_argument('--SOLVER_TYPE', dest='SOLVER_TYPE',
default='SQP_RTI',
help='SOLVER_TYPE: (full step) sequential quadratic programming (SQP) or ' \
' real-time iteration (SQP-RTI) (default: SQP-RTI)')
args = parser.parse_args()
FORMULATION = args.FORMULATION
FORMULATION_values = ['LS', 'NLS']
if FORMULATION not in FORMULATION_values:
raise Exception('Invalid unit test value {} for parameter FORMULATION. Possible values are' \
' {}. Exiting.'.format(FORMULATION, FORMULATION_values))
QP_SOLVER = args.QP_SOLVER
QP_SOLVER_values = ['PARTIAL_CONDENSING_HPIPM', 'FULL_CONDENSING_HPIPM', 'FULL_CONDENSING_QPOASES']
if QP_SOLVER not in QP_SOLVER_values:
raise Exception('Invalid unit test value {} for parameter QP_SOLVER. Possible values are' \
' {}. Exiting.'.format(QP_SOLVER, QP_SOLVER_values))
INTEGRATOR_TYPE = args.INTEGRATOR_TYPE
INTEGRATOR_TYPE_values = ['ERK', 'IRK']
if INTEGRATOR_TYPE not in INTEGRATOR_TYPE:
raise Exception('Invalid unit test value {} for parameter INTEGRATOR_TYPE. Possible values are' \
' {}. Exiting.'.format(INTEGRATOR_TYPE, INTEGRATOR_TYPE_values))
SOLVER_TYPE = args.SOLVER_TYPE
SOLVER_TYPE_values = ['SQP', 'SQP-RTI']
if SOLVER_TYPE not in SOLVER_TYPE:
raise Exception('Invalid unit test value {} for parameter SOLVER_TYPE. Possible values are' \
' {}. Exiting.'.format(SOLVER_TYPE, SOLVER_TYPE_values))
# print test setting
print("Running test with:\n\tformulation:", FORMULATION, "\n\tqp solver: ", QP_SOLVER,\
"\n\tintergrator: ", INTEGRATOR_TYPE, "\n\tsolver: ", SOLVER_TYPE)
# create render arguments
ocp = acados_ocp_nlp()
# export model
model = export_ode_model()
# set model_name
ocp.model = model
Tf = 2.0
nx = model.x.size()[0]
nu = model.u.size()[0]
ny = nx + nu
ny_e = nx
N = 50
# set ocp_nlp_dimensions
nlp_dims = ocp.dims
nlp_dims.nx = nx
nlp_dims.ny = ny
nlp_dims.ny_e = ny_e
nlp_dims.nbx = 0
nlp_dims.nbu = nu
nlp_dims.nu = model.u.size()[0]
nlp_dims.N = N
# set weighting matrices
nlp_cost = ocp.cost
if FORMULATION == 'LS':
nlp_cost.cost_type = 'LINEAR_LS'
nlp_cost.cost_type_e = 'LINEAR_LS'
elif FORMULATION == 'NLS':
nlp_cost.cost_type = 'NONLINEAR_LS'
nlp_cost.cost_type_e = 'NONLINEAR_LS'
else:
raise Exception('Unknown FORMULATION. Possible values are \'LS\' and \'NLS\'.')
Q = np.eye(4)
Q[0,0] = 1e0
Q[1,1] = 1e2
Q[2,2] = 1e-3
Q[3,3] = 1e-2
R = np.eye(1)
R[0,0] = 1e0
unscale = N/Tf
Q = Q * unscale
R = R * unscale
if FORMULATION == 'NLS':
nlp_cost.W = scipy.linalg.block_diag(R, Q)
else:
nlp_cost.W = scipy.linalg.block_diag(Q, R)
nlp_cost.W_e = Q/unscale
Vx = np.zeros((ny, nx))
Vx[0,0] = 1.0
Vx[1,1] = 1.0
Vx[2,2] = 1.0
Vx[3,3] = 1.0
nlp_cost.Vx = Vx
Vu = np.zeros((ny, nu))
Vu[4,0] = 1.0
nlp_cost.Vu = Vu
Vx_e = np.zeros((ny_e, nx))
Vx_e[0,0] = 1.0
Vx_e[1,1] = 1.0
Vx_e[2,2] = 1.0
Vx_e[3,3] = 1.0
nlp_cost.Vx_e = Vx_e
if FORMULATION == 'NLS':
x = SX.sym('x', 4, 1)
u = SX.sym('u', 1, 1)
ocp.cost_r.expr = vertcat(u, x)
ocp.cost_r.x = x
ocp.cost_r.u = u
ocp.cost_r.name = 'lin_res'
ocp.cost_r.ny = nx + nu
ocp.cost_r_e.expr = x
ocp.cost_r_e.x = x
ocp.cost_r_e.name = 'lin_res'
ocp.cost_r_e.ny = nx
nlp_cost.yref = np.zeros((ny, ))
nlp_cost.yref_e = np.zeros((ny_e, ))
# setting bounds
Fmax = 2.0
nlp_con = ocp.constraints
nlp_con.lbu = np.array([-Fmax])
nlp_con.ubu = np.array([+Fmax])
nlp_con.x0 = np.array([0.0, 3.14, 0.0, 0.0])
nlp_con.idxbu = np.array([0])
# set QP solver
ocp.solver_options.qp_solver = QP_SOLVER
ocp.solver_options.hessian_approx = 'GAUSS_NEWTON'
ocp.solver_options.integrator_type = INTEGRATOR_TYPE
ocp.solver_options.sim_method_num_stages = 2
ocp.solver_options.sim_method_num_steps = 5
# set prediction horizon
ocp.solver_options.tf = Tf
ocp.solver_options.nlp_solver_type = SOLVER_TYPE
# set header path
ocp.acados_include_path = '../../../../include'
ocp.acados_lib_path = '../../../../lib'
acados_solver = generate_solver(ocp, json_file = 'acados_ocp.json')
Nsim = 100
simX = np.ndarray((Nsim, nx))
simU = np.ndarray((Nsim, nu))
for i in range(Nsim):
status = acados_solver.solve()
if status !=0:
print("acados failure! Exiting. \n")
sys.exit(status)
# get solution
x0 = acados_solver.get(0, "x")
u0 = acados_solver.get(0, "u")
for j in range(nx):
simX[i,j] = x0[j]
for j in range(nu):
simU[i,j] = u0[j]
# update initial condition
x0 = acados_solver.get(1, "x")
acados_solver.set(0, "lbx", x0)
acados_solver.set(0, "ubx", x0)
# update reference
for j in range(N):
acados_solver.set(j, "yref", np.array([0, 0, 0, 0, 0]))
acados_solver.set(N, "yref", np.array([0, 0, 0, 0]))
# dump result to JSON file for unit testing
test_file_name = 'test_data/generate_c_code_out_' + FORMULATION + '_' + QP_SOLVER + '_' + \
INTEGRATOR_TYPE + '_' + SOLVER_TYPE + '.json'
if GENERATE_DATA:
with open(test_file_name, 'w') as f:
json.dump({"simX": simX.tolist(), "simU": simU.tolist()}, f, indent=4, sort_keys=True)
else:
with open(test_file_name, 'r') as f:
test_data = json.load(f)
simX_error = np.linalg.norm(test_data['simX'] - simX)
simU_error = np.linalg.norm(test_data['simU'] - simU)
if simX_error > TEST_TOL or simU_error > TEST_TOL:
raise Exception("Python acados test failure with accuracies {:.2E} and {:.2E} ({:.2E} required) on pendulum example! Exiting.\n".format(simX_error, simU_error, TEST_TOL))
else:
print('Python test passed with accuracy {:.2E}'.format(max(simU_error, simX_error)))
| 31.604317 | 178 | 0.669019 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,694 | 0.420394 |
08f05b58d9116c10d8df8fa1c928dc1cf428e826 | 2,820 | py | Python | collectors/cpustats.py | vijayanant/kunai | 0dfe169731eaceb1bba66e12715b3968d2a3de20 | [
"MIT"
]
| 1 | 2020-04-12T21:05:46.000Z | 2020-04-12T21:05:46.000Z | collectors/cpustats.py | vijayanant/kunai | 0dfe169731eaceb1bba66e12715b3968d2a3de20 | [
"MIT"
]
| null | null | null | collectors/cpustats.py | vijayanant/kunai | 0dfe169731eaceb1bba66e12715b3968d2a3de20 | [
"MIT"
]
| null | null | null | import httplib # Used only for handling httplib.HTTPException (case #26701)
import os
import sys
import platform
import re
import urllib
import urllib2
import traceback
import time
from StringIO import StringIO
from multiprocessing import subprocess
from kunai.log import logger
from kunai.collector import Collector
class CpuStats(Collector):
def launch(self):
logger.debug('getCPUStats: start')
cpuStats = {}
if sys.platform == 'linux2':
logger.debug('getCPUStats: linux2')
headerRegexp = re.compile(r'.*?([%][a-zA-Z0-9]+)[\s+]?')
itemRegexp = re.compile(r'.*?\s+(\d+)[\s+]?')
valueRegexp = re.compile(r'\d+\.\d+')
proc = None
try:
proc = subprocess.Popen(['mpstat', '-P', 'ALL', '1', '1'], stdout=subprocess.PIPE, close_fds=True)
stats = proc.communicate()[0]
if int(self.pythonVersion[1]) >= 6:
try:
proc.kill()
except Exception, e:
logger.debug('Process already terminated')
stats = stats.split('\n')
header = stats[2]
headerNames = re.findall(headerRegexp, header)
device = None
for statsIndex in range(4, len(stats)): # skip "all"
row = stats[statsIndex]
if not row: # skip the averages
break
deviceMatch = re.match(itemRegexp, row)
if deviceMatch is not None:
device = 'CPU%s' % deviceMatch.groups()[0]
values = re.findall(valueRegexp, row.replace(',', '.'))
cpuStats[device] = {}
for headerIndex in range(0, len(headerNames)):
headerName = headerNames[headerIndex]
cpuStats[device][headerName] = values[headerIndex]
except OSError, ex:
# we dont have it installed return nothing
return False
except Exception, ex:
if int(self.pythonVersion[1]) >= 6:
try:
if proc:
proc.kill()
except UnboundLocalError, e:
logger.debug('Process already terminated')
except Exception, e:
logger.debug('Process already terminated')
logger.error('getCPUStats: exception = %s', traceback.format_exc())
return False
else:
logger.debug('getCPUStats: unsupported platform')
return False
logger.debug('getCPUStats: completed, returning')
return cpuStats
| 32.790698 | 114 | 0.510638 | 2,498 | 0.885816 | 0 | 0 | 0 | 0 | 0 | 0 | 465 | 0.164894 |
08f3eae9e91dde600e2781b52aa83909fff87587 | 1,560 | py | Python | prob_h.py | ShinjiKatoA16/icpc2017ucsy | de1954620036e8025b7b4c1b469e6b8c57af212e | [
"MIT"
]
| null | null | null | prob_h.py | ShinjiKatoA16/icpc2017ucsy | de1954620036e8025b7b4c1b469e6b8c57af212e | [
"MIT"
]
| null | null | null | prob_h.py | ShinjiKatoA16/icpc2017ucsy | de1954620036e8025b7b4c1b469e6b8c57af212e | [
"MIT"
]
| null | null | null | #!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
2017 ICPC at UCSY
Problem-H: Sum Square
'''
import sys
class TestCase():
pass
def parse_tc(tc):
'''
Input: Test Case
Update:
Return: None
'''
x = list(map(int,tc.infile.readline().split()))
tc.dataset = x[0]
tc.max_num = x[1]
tc.base = x[2]
tc.a0 = x[3]
return
def ssd(b, n):
val = 0
while n > 0:
val += (n % b) ** 2
n //= b
# print(b, n, val)
return val
def prt_list(_list):
while len(_list) >= 20:
s = ' '.join(map(str,_list[:20]))
print(s)
_list = _list[20:]
if len(_list):
s = ' '.join(map(str, _list))
print(s)
return
def solve(tc):
'''
Input: Test Case
Return: None
'''
parse_tc(tc)
ak = tc.a0
ssd_list = [ak]
for i in range(tc.max_num):
ssd_val = ssd(tc.base, ak)
if ssd_val in ssd_list:
index_k = ssd_list.index(ssd_val)
print(tc.dataset, len(ssd_list)+1, len(ssd_list)-index_k)
ssd_list.append(ssd_val)
prt_list(ssd_list[index_k:])
break
ssd_list.append(ssd_val)
ak = ssd_val
else:
print(tc.dataset, tc.max_num, 0)
print(ak)
return
##
## Main routine
##
if __name__ == '__main__':
tc = TestCase()
tc.infile = sys.stdin
tc.t = int(tc.infile.readline())
for i in range(tc.t):
solve(tc)
if tc.infile != sys.stdin:
tc.infile.close()
| 16.956522 | 69 | 0.501923 | 26 | 0.016667 | 0 | 0 | 0 | 0 | 0 | 0 | 281 | 0.180128 |
08f52305d640784da8d8fb26cf618726da107b3a | 2,357 | py | Python | spark_mapinput.py | pw2393/spark-bitcoin-parser | 320eb30ffcc462b0607655d2f4002a82590fd120 | [
"MIT"
]
| 11 | 2017-09-29T05:37:57.000Z | 2022-02-04T06:34:17.000Z | spark_mapinput.py | pw2393/spark-bitcoin-parser | 320eb30ffcc462b0607655d2f4002a82590fd120 | [
"MIT"
]
| 2 | 2018-07-03T12:19:50.000Z | 2019-10-19T21:24:53.000Z | spark_mapinput.py | pw2393/spark-bitcoin-parser | 320eb30ffcc462b0607655d2f4002a82590fd120 | [
"MIT"
]
| 3 | 2019-11-09T13:01:07.000Z | 2021-12-03T04:20:29.000Z | """
Author: Peng Wu
License: MIT
"""
# Initialize Spark Context: local multi-threads
from pyspark import SparkConf, SparkContext
output_folder = './csv/'
def main():
# Initialize Spark Context: local multi-threads
conf = SparkConf().setAppName("BTC-InputMapper")
sc = SparkContext(conf=conf)
# Loading files
def parse_outputs(line):
"""
schema:
txhash, nid, value, addr
:param line:
:return (key, value):
"""
fields = line.split(',')
return (fields[0], fields[1]), (fields[2], fields[3])
def parse_inputsmapping(line):
"""
schema:
txhash, mid, prev_txhash, nid
:param line:
:return (key, value):
"""
fields = line.split(',')
return (fields[2], fields[3]), (fields[0], fields[1], fields[4])
outputs = sc.textFile(output_folder+'outputs.csv').map(parse_outputs)
inputs = sc.textFile(output_folder+'inputs_mapping.csv').map(parse_inputsmapping)
# Transformations and/or Actions
# op: transformation + action
metafinal = inputs.join(outputs).persist()
final = metafinal.values()
# op: transformation
# UTXOs = outputs.subtractByKey(inputs)
# can be then reduced on address thus to obtain the total value for an UTXO address
# final.map(lambda x:(x[0][0],x[0][1],x[1][0],x[1][1])).saveAsTextFile("input_final")
with open(output_folder+'inputs.csv', 'w') as f:
pass
def formatted_print(keyValue):
with open(output_folder+'inputs.csv', 'a') as f:
f.write('{},{},{},{}\n'.format(keyValue[0][0], keyValue[0][1], keyValue[1][0], keyValue[1][1]))
final.foreach(formatted_print)
# with open(output_folder+'viz_txedge.csv', 'w') as f:
# pass
# def formatted_print_2(keyValue):
# with open(output_folder+'viz_txedge.csv', 'a') as f:
# f.write('{},{},{},{}\n'.format(keyValue[0][0], keyValue[1][1][0], keyValue[1][0][0], keyValue[1][0][2]))
# metafinal.foreach(formatted_print_2)
# #print metafinal.first()
if __name__ == "__main__":
import sys
if len(sys.argv) != 1:
print "\n\tUSAGE:\n\t\tspark-submit spark_mapinput.py"
sys.exit()
import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time)) | 28.39759 | 117 | 0.602036 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,218 | 0.516759 |
08f5c575bcbcd0ee74f875b6fd32a403f396576c | 6,819 | py | Python | neuralpredictors/layers/readouts/factorized.py | kellirestivo/neuralpredictors | 57205a90d2e3daa5f8746c6ef6170be9e35cb5f5 | [
"MIT"
]
| 9 | 2020-11-26T18:22:32.000Z | 2022-01-22T15:51:52.000Z | neuralpredictors/layers/readouts/factorized.py | kellirestivo/neuralpredictors | 57205a90d2e3daa5f8746c6ef6170be9e35cb5f5 | [
"MIT"
]
| 60 | 2020-10-21T15:32:28.000Z | 2022-02-25T10:38:16.000Z | neuralpredictors/layers/readouts/factorized.py | mohammadbashiri/neuralpredictors | 8e60c9ce91f83e3dcaa1b3dbe4422e1509ccbd5f | [
"MIT"
]
| 21 | 2020-10-21T09:29:17.000Z | 2022-02-07T10:04:46.000Z | import torch
from torch import nn as nn
import numpy as np
from .base import Readout
class FullFactorized2d(Readout):
"""
Factorized fully connected layer. Weights are a sum of outer products between a spatial filter and a feature vector.
"""
def __init__(
self,
in_shape,
outdims,
bias,
normalize=True,
init_noise=1e-3,
constrain_pos=False,
positive_weights=False,
shared_features=None,
mean_activity=None,
spatial_and_feature_reg_weight=1.0,
gamma_readout=None, # depricated, use feature_reg_weight instead
**kwargs,
):
super().__init__()
c, w, h = in_shape
self.in_shape = in_shape
self.outdims = outdims
self.positive_weights = positive_weights
self.constrain_pos = constrain_pos
self.init_noise = init_noise
self.normalize = normalize
self.mean_activity = mean_activity
self.spatial_and_feature_reg_weight = self.resolve_deprecated_gamma_readout(
spatial_and_feature_reg_weight, gamma_readout
)
self._original_features = True
self.initialize_features(**(shared_features or {}))
self.spatial = nn.Parameter(torch.Tensor(self.outdims, w, h))
if bias:
bias = nn.Parameter(torch.Tensor(outdims))
self.register_parameter("bias", bias)
else:
self.register_parameter("bias", None)
self.initialize(mean_activity)
@property
def shared_features(self):
return self._features
@property
def features(self):
if self._shared_features:
return self.scales * self._features[self.feature_sharing_index, ...]
else:
return self._features
@property
def weight(self):
if self.positive_weights:
self.features.data.clamp_min_(0)
n = self.outdims
c, w, h = self.in_shape
return self.normalized_spatial.view(n, 1, w, h) * self.features.view(n, c, 1, 1)
@property
def normalized_spatial(self):
"""
Normalize the spatial mask
"""
if self.normalize:
norm = self.spatial.pow(2).sum(dim=1, keepdim=True)
norm = norm.sum(dim=2, keepdim=True).sqrt().expand_as(self.spatial) + 1e-6
weight = self.spatial / norm
else:
weight = self.spatial
if self.constrain_pos:
weight.data.clamp_min_(0)
return weight
def regularizer(self, reduction="sum", average=None):
return self.l1(reduction=reduction, average=average) * self.spatial_and_feature_reg_weight
def l1(self, reduction="sum", average=None):
reduction = self.resolve_reduction_method(reduction=reduction, average=average)
if reduction is None:
raise ValueError("Reduction of None is not supported in this regularizer")
n = self.outdims
c, w, h = self.in_shape
ret = (
self.normalized_spatial.view(self.outdims, -1).abs().sum(dim=1, keepdim=True)
* self.features.view(self.outdims, -1).abs().sum(dim=1)
).sum()
if reduction == "mean":
ret = ret / (n * c * w * h)
return ret
def initialize(self, mean_activity=None):
"""
Initializes the mean, and sigma of the Gaussian readout along with the features weights
"""
if mean_activity is None:
mean_activity = self.mean_activity
self.spatial.data.normal_(0, self.init_noise)
self._features.data.normal_(0, self.init_noise)
if self._shared_features:
self.scales.data.fill_(1.0)
if self.bias is not None:
self.initialize_bias(mean_activity=mean_activity)
def initialize_features(self, match_ids=None, shared_features=None):
"""
The internal attribute `_original_features` in this function denotes whether this instance of the FullGuassian2d
learns the original features (True) or if it uses a copy of the features from another instance of FullGaussian2d
via the `shared_features` (False). If it uses a copy, the feature_l1 regularizer for this copy will return 0
"""
c, w, h = self.in_shape
if match_ids is not None:
assert self.outdims == len(match_ids)
n_match_ids = len(np.unique(match_ids))
if shared_features is not None:
assert shared_features.shape == (
n_match_ids,
c,
), f"shared features need to have shape ({n_match_ids}, {c})"
self._features = shared_features
self._original_features = False
else:
self._features = nn.Parameter(
torch.Tensor(n_match_ids, c)
) # feature weights for each channel of the core
self.scales = nn.Parameter(torch.Tensor(self.outdims, 1)) # feature weights for each channel of the core
_, sharing_idx = np.unique(match_ids, return_inverse=True)
self.register_buffer("feature_sharing_index", torch.from_numpy(sharing_idx))
self._shared_features = True
else:
self._features = nn.Parameter(torch.Tensor(self.outdims, c)) # feature weights for each channel of the core
self._shared_features = False
def forward(self, x, shift=None):
if shift is not None:
raise NotImplementedError("shift is not implemented for this readout")
if self.constrain_pos:
self.features.data.clamp_min_(0)
N, c, w, h = x.size()
c_in, w_in, h_in = self.in_shape
if (c_in, w_in, h_in) != (c, w, h):
raise ValueError("the specified feature map dimension is not the readout's expected input dimension")
y = torch.einsum("ncwh,owh->nco", x, self.normalized_spatial)
y = torch.einsum("nco,oc->no", y, self.features)
if self.bias is not None:
y = y + self.bias
return y
def __repr__(self):
c, w, h = self.in_shape
r = self.__class__.__name__ + " (" + "{} x {} x {}".format(c, w, h) + " -> " + str(self.outdims) + ")"
if self.bias is not None:
r += " with bias"
if self._shared_features:
r += ", with {} features".format("original" if self._original_features else "shared")
if self.normalize:
r += ", normalized"
else:
r += ", unnormalized"
for ch in self.children():
r += " -> " + ch.__repr__() + "\n"
return r
# Classes for backwards compatibility
class SpatialXFeatureLinear(FullFactorized2d):
pass
class FullSXF(FullFactorized2d):
pass
| 35.889474 | 120 | 0.60698 | 6,686 | 0.980496 | 0 | 0 | 982 | 0.144009 | 0 | 0 | 1,322 | 0.19387 |
08f7015d2835dcc1e926fd4acbcfff51249816e9 | 1,186 | py | Python | app/main/views.py | josphat-otieno/news-app | e6ff307230bd2cab787489fca4850004cd9bdbd0 | [
"MIT"
]
| null | null | null | app/main/views.py | josphat-otieno/news-app | e6ff307230bd2cab787489fca4850004cd9bdbd0 | [
"MIT"
]
| null | null | null | app/main/views.py | josphat-otieno/news-app | e6ff307230bd2cab787489fca4850004cd9bdbd0 | [
"MIT"
]
| 1 | 2022-02-28T22:33:33.000Z | 2022-02-28T22:33:33.000Z | from flask import render_template,request, redirect, url_for
from . import main
from ..requests import get_articles, get_news_sources,get_top_headlines, get_news_category
@main.route('/')
def index():
'''
view root function that returns the idex page and its data
'''
title="Welcome to your favorite news app"
message='Read your favorite news here'
news_sources=get_news_sources('sources')
top_headlines = get_top_headlines()
return render_template('index.html', title=title, message=message, sources=news_sources,top_headlines=top_headlines)
@main.route('/article/<id>')
def articles(id):
'''function to dsiplay articls page and its data
'''
articles = get_articles(id)
title = 'trending articles'
return render_template('article.html' ,articles=articles, title = title)
@main.route('/categories/<category_name>')
def category(category_name):
'''
function to return the categories.html page and its content
'''
category = get_news_category(category_name)
title = f'{category_name}'
cat = category_name
return render_template('categories.html',title = title,category = category, category_name=cat) | 34.882353 | 120 | 0.729342 | 0 | 0 | 0 | 0 | 1,010 | 0.851602 | 0 | 0 | 406 | 0.342327 |
08f715599ebdccb7db7f9153cc150737106850d8 | 6,904 | py | Python | fabric_cf/actor/core/util/resource_count.py | fabric-testbed/ActorBase | 3c7dd040ee79fef0759e66996c93eeec57c790b2 | [
"MIT"
]
| null | null | null | fabric_cf/actor/core/util/resource_count.py | fabric-testbed/ActorBase | 3c7dd040ee79fef0759e66996c93eeec57c790b2 | [
"MIT"
]
| 67 | 2020-12-21T15:39:49.000Z | 2022-02-27T17:55:00.000Z | fabric_cf/actor/core/util/resource_count.py | fabric-testbed/ControlFramework | 95ab745e32f15c993bc7a017aa97a5a0f67f210f | [
"MIT"
]
| null | null | null | #!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020 FABRIC Testbed
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# 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, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
#
# Author: Komal Thareja ([email protected])
from fabric_cf.actor.core.util.resource_type import ResourceType
class CountsPerType:
"""
Inner class representing counts for a given resource type.
"""
def __init__(self, *, resource_type: ResourceType):
self.resource_type = resource_type
self.active = 0
self.pending = 0
self.expired = 0
self.failed = 0
self.closed = 0
class ResourceCount:
"""
ResourceCount is a utility class used to count reservations in a ReservationSet based on the reservation
state and resource type. An instance of this class is used as an argument to the "tally" methods in ReservationSet.
Note: no internal locking.
"""
def __init__(self):
# Counts per resource type. <String, CountsPerType>
self.map = {}
def get_counts(self, *, resource_type: ResourceType) -> CountsPerType:
"""
Returns the count entry for the given resource type.
Args:
resource_type: resource type
Returns:
count entry for the given resource type
"""
return self.map.get(resource_type.get_type(), None)
def get_or_create_counts(self, *, resource_type: ResourceType) -> CountsPerType:
"""
Returns or creates a new count entry for the given resource type.
Args:
resource_type: resource type
Returns:
count entry for the given resource type
"""
result = self.map.get(resource_type.get_type(), None)
if result is None:
result = CountsPerType(resource_type=resource_type)
self.map[resource_type.get_type()] = result
return result
def count_active(self, *, resource_type: ResourceType) -> int:
"""
Returns the number of active units from the given resource type.
Args:
resource_type: resource type
Returns:
number of active units
"""
counts = self.get_counts(resource_type=resource_type)
if counts is not None:
return counts.active
else:
return 0
def count_close(self, *, resource_type: ResourceType) -> int:
"""
Returns the number of closed units from the given resource type.
Args:
resource_type: resource type
Returns:
number of closed units
"""
counts = self.get_counts(resource_type=resource_type)
if counts is not None:
return counts.closed
else:
return 0
def count_expired(self, *, resource_type: ResourceType) -> int:
"""
Returns the number of expired units from the given resource type.
Args:
resource_type: resource type
Returns:
number of expired units
"""
counts = self.get_counts(resource_type=resource_type)
if counts is not None:
return counts.expired
else:
return 0
def count_failed(self, *, resource_type: ResourceType) -> int:
"""
Returns the number of failed units from the given resource type.
Args:
resource_type: resource type
Returns:
number of failed units
"""
counts = self.get_counts(resource_type=resource_type)
if counts is not None:
return counts.failed
else:
return 0
def count_pending(self, *, resource_type: ResourceType) -> int:
"""
Returns the number of pending units from the given resource type.
Args:
resource_type: resource type
Returns:
number of pending units
"""
counts = self.get_counts(resource_type=resource_type)
if counts is not None:
return counts.pending
else:
return 0
def tally_active(self, *, resource_type: ResourceType, count: int):
"""
Increments with count the internal counter for active units of the specified type.
Args:
resource_type: resource type
count: count
"""
counts = self.get_or_create_counts(resource_type=resource_type)
counts.active += count
def tally_close(self, *, resource_type: ResourceType, count: int):
"""
Increments with count the internal counter for closed units of the specified type.
Args:
resource_type: resource type
count: count
"""
counts = self.get_or_create_counts(resource_type=resource_type)
counts.closed += count
def tally_expired(self, *, resource_type: ResourceType, count: int):
"""
Increments with count the internal counter for expired units of the specified type.
Args:
resource_type: resource type
count: count
"""
counts = self.get_or_create_counts(resource_type=resource_type)
counts.expired += count
def tally_failed(self, *, resource_type: ResourceType, count: int):
"""
Increments with count the internal counter for failed units of the specified type.
Args:
resource_type: resource type
count: count
"""
counts = self.get_or_create_counts(resource_type=resource_type)
counts.failed += count
def tally_pending(self, *, resource_type: ResourceType, count: int):
"""
Increments with count the internal counter for pending units of the specified type.
Args:
resource_type: resource type
count: count
"""
counts = self.get_or_create_counts(resource_type=resource_type)
counts.pending += count
| 33.033493 | 119 | 0.637167 | 5,652 | 0.818656 | 0 | 0 | 0 | 0 | 0 | 0 | 3,888 | 0.563152 |
08f958d96728940d01ac948489adc3f2710db6d4 | 114 | py | Python | unweaver/graphs/digraphgpkg/nodes/__init__.py | jsbeckwith/unweaver | a4ba9e4e288c75e93bf7f9d67bc11680f09c3da0 | [
"Apache-2.0"
]
| 4 | 2019-04-24T16:38:57.000Z | 2021-12-28T20:38:08.000Z | unweaver/graphs/digraphgpkg/nodes/__init__.py | jsbeckwith/unweaver | a4ba9e4e288c75e93bf7f9d67bc11680f09c3da0 | [
"Apache-2.0"
]
| 3 | 2021-06-02T04:06:33.000Z | 2021-11-02T01:47:20.000Z | unweaver/graphs/digraphgpkg/nodes/__init__.py | jsbeckwith/unweaver | a4ba9e4e288c75e93bf7f9d67bc11680f09c3da0 | [
"Apache-2.0"
]
| 1 | 2020-08-13T04:42:05.000Z | 2020-08-13T04:42:05.000Z | from .node_view import NodeView
from .node import Node
from .nodes_view import NodesView
from .nodes import Nodes
| 22.8 | 33 | 0.824561 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
08f98d32f073c8a759a51d5a1b5fc9a27ec1c07c | 1,927 | py | Python | python/http_request.py | MrVallentin/http_request | b21cb23ead1e3bc7176f09804f9cc9287b9f0168 | [
"MIT"
]
| null | null | null | python/http_request.py | MrVallentin/http_request | b21cb23ead1e3bc7176f09804f9cc9287b9f0168 | [
"MIT"
]
| null | null | null | python/http_request.py | MrVallentin/http_request | b21cb23ead1e3bc7176f09804f9cc9287b9f0168 | [
"MIT"
]
| null | null | null | #!/usr/bin/env python
# Author: Christian Vallentin <[email protected]>
# Website: http://vallentinsource.com
# Repository: https://github.com/MrVallentin/http_request
#
# Date Created: February 28, 2016
# Last Modified: February 29, 2016
#
# Developed and tested using Python 3.5.1
import http.client, urllib.parse
def http_request(url, data = None, method = "GET", headers = {}):
parsed = urllib.parse.urlparse(url)
scheme, netloc, path = parsed.scheme, parsed.netloc, parsed.path
if not method:
method = "GET"
method = method.upper()
if not headers:
headers = {}
if data:
data = urllib.parse.urlencode(data)
#data = data.encode("utf-8")
if method == "GET":
if data:
path += "?" + data
data = None
if not headers:
headers = {}
if data:
headers["Content-Length"] = len(data)
headers["Content-Type"] = "application/x-www-form-urlencoded"
conn = None
if scheme and scheme == "https":
conn = http.client.HTTPSConnection(netloc)
else:
conn = http.client.HTTPConnection(netloc)
conn.request(method, path, data, headers)
res = conn.getresponse()
res_status, res_reason = res.status, res.reason
res_body = res.read()
res_headers = res.getheaders()
conn.close()
res_body = res_body.decode("utf-8")
return res_body, res_status, res_reason, res_headers
def http_head(url, data = None, headers = None):
return http_request(url, data, "HEAD", headers)
def http_get(url, data = None, headers = None):
return http_request(url, data, "GET", headers)
def http_post(url, data = None, headers = None):
return http_request(url, data, "POST", headers)
def http_delete(url, data = None, headers = None):
return http_request(url, data, "DELETE", headers)
def http_put(url, data = None, headers = None):
return http_request(url, data, "PUT", headers)
def http_patch(url, data = None, headers = None):
return http_request(url, data, "PATCH", headers)
| 23.790123 | 65 | 0.694862 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 444 | 0.23041 |
3e92c270410556137345bdc66663f957e85d9d78 | 937 | py | Python | notebook/pypdf2_merge_page.py | vhn0912/python-snippets | 80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038 | [
"MIT"
]
| 174 | 2018-05-30T21:14:50.000Z | 2022-03-25T07:59:37.000Z | notebook/pypdf2_merge_page.py | vhn0912/python-snippets | 80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038 | [
"MIT"
]
| 5 | 2019-08-10T03:22:02.000Z | 2021-07-12T20:31:17.000Z | notebook/pypdf2_merge_page.py | vhn0912/python-snippets | 80b2e1d6b2b8f12ae30d6dbe86d25bb2b3a02038 | [
"MIT"
]
| 53 | 2018-04-27T05:26:35.000Z | 2022-03-25T07:59:37.000Z | import PyPDF2
merger = PyPDF2.PdfFileMerger()
merger.append('data/src/pdf/sample1.pdf', pages=(0, 1))
merger.append('data/src/pdf/sample2.pdf', pages=(2, 4))
merger.merge(2, 'data/src/pdf/sample3.pdf', pages=(0, 3, 2))
merger.write('data/temp/sample_merge_page.pdf')
merger.close()
merger = PyPDF2.PdfFileMerger()
merger.append('data/src/pdf/sample1.pdf', pages=PyPDF2.pagerange.PageRange('-1'))
merger.append('data/src/pdf/sample2.pdf', pages=PyPDF2.pagerange.PageRange('2:'))
merger.merge(2, 'data/src/pdf/sample3.pdf', pages=PyPDF2.pagerange.PageRange('::-1'))
merger.write('data/temp/sample_merge_pagerange.pdf')
merger.close()
reader1 = PyPDF2.PdfFileReader('data/src/pdf/sample1.pdf')
reader2 = PyPDF2.PdfFileReader('data/src/pdf/sample2.pdf')
writer = PyPDF2.PdfFileWriter()
writer.addPage(reader1.getPage(0))
writer.addPage(reader2.getPage(2))
with open('data/temp/sample_merge_wr.pdf', 'wb') as f:
writer.write(f)
| 30.225806 | 85 | 0.741729 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 328 | 0.350053 |
3e93e3456bdf96692c3deeb42d3cc140eb248959 | 1,983 | py | Python | examples/nlp/bert_squad_pytorch/data.py | gh-determined-ai/determined | 9a1ab33a3a356b69681b3351629fef4ab98ddb56 | [
"Apache-2.0"
]
| 1,729 | 2020-04-27T17:36:40.000Z | 2022-03-31T05:48:39.000Z | examples/nlp/bert_squad_pytorch/data.py | ChrisW09/determined | 5c37bfe9cfcc69174ba29a3f1a115c3e9e3632e0 | [
"Apache-2.0"
]
| 1,940 | 2020-04-27T17:34:14.000Z | 2022-03-31T23:02:28.000Z | examples/nlp/bert_squad_pytorch/data.py | ChrisW09/determined | 5c37bfe9cfcc69174ba29a3f1a115c3e9e3632e0 | [
"Apache-2.0"
]
| 214 | 2020-04-27T19:57:28.000Z | 2022-03-29T08:17:16.000Z | from transformers.data.processors.squad import SquadV1Processor, SquadV2Processor
from transformers import squad_convert_examples_to_features
import urllib.request
import os
def load_and_cache_examples(data_dir: str, tokenizer, task, max_seq_length, doc_stride, max_query_length, evaluate=False):
if (task == "SQuAD1.1"):
train_url = "https://rajpurkar.github.io/SQuAD-explorer/dataset/train-v1.1.json"
validation_url = "https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v1.1.json"
train_file = "train-v1.1.json"
validation_file = "dev-v1.1.json"
processor = SquadV1Processor()
elif (task == "SQuAD2.0"):
train_url = "https://rajpurkar.github.io/SQuAD-explorer/dataset/train-v2.0.json"
validation_url = "https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v2.0.json"
train_file = "train-v2.0.json"
validation_file = "dev-v2.0.json"
processor = SquadV2Processor()
else:
raise NameError("Incompatible dataset detected")
if not os.path.exists(data_dir):
os.makedirs(data_dir)
if evaluate:
with urllib.request.urlopen(validation_url) as url:
with open(data_dir + "/" + validation_file, 'w') as f:
f.write(url.read().decode())
examples = processor.get_dev_examples(data_dir, filename=validation_file)
else:
with urllib.request.urlopen(train_url) as url:
with open(data_dir + "/" + train_file, 'w') as f:
f.write(url.read().decode())
examples = processor.get_train_examples(data_dir, filename=train_file)
features, dataset = squad_convert_examples_to_features(
examples=examples,
tokenizer=tokenizer,
max_seq_length=max_seq_length,
doc_stride=doc_stride,
max_query_length=max_query_length,
is_training=not evaluate,
return_dataset="pt",
)
return dataset, examples, features
| 44.066667 | 122 | 0.670701 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 399 | 0.20121 |
3e946fdc0458e3cc6d05239b37f7f11a04a0d076 | 898 | py | Python | test_simplebuy.py | caoxuwen/bitgym | 0a6796a039290122430ebc13c8d7ad9ff741921a | [
"MIT"
]
| 1 | 2018-09-07T10:10:29.000Z | 2018-09-07T10:10:29.000Z | test_simplebuy.py | caoxuwen/bitgym | 0a6796a039290122430ebc13c8d7ad9ff741921a | [
"MIT"
]
| null | null | null | test_simplebuy.py | caoxuwen/bitgym | 0a6796a039290122430ebc13c8d7ad9ff741921a | [
"MIT"
]
| null | null | null | import random
import numpy as np
import pandas as pd
import trading_env
# np.set_printoptions(threshold=np.nan)
#df = pd.read_hdf('dataset/SGXTW.h5', 'STW')
#df = pd.read_hdf('dataset/SGXTWsample.h5', 'STW')
df = pd.read_csv('dataset/btc_indexed2.csv')
print(df.describe())
env = trading_env.make(env_id='training_v1', obs_data_len=1, step_len=1,
df=df, fee=0.0, max_position=5, deal_col_name='close',
sample_days=1,
feature_names=['low', 'high',
'open', 'close',
'volume', 'datetime'])
env.reset()
env.render()
state, reward, done, info = env.step(1)
print state
# randow choice action and show the transaction detail
while True:
state, reward, done, info = env.step(0)
env.render()
if done:
print state, reward
break
| 27.212121 | 77 | 0.587973 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 275 | 0.306236 |
3e9679307c3b46578c6f09f3d9606e2140ef17b5 | 1,253 | py | Python | sandbox/images/reseau_serveur_utile.py | chiesax/sandbox | 3b628e0068c6f7116c3a98d481299158a8bf5de3 | [
"MIT"
]
| null | null | null | sandbox/images/reseau_serveur_utile.py | chiesax/sandbox | 3b628e0068c6f7116c3a98d481299158a8bf5de3 | [
"MIT"
]
| 1 | 2015-12-29T09:38:21.000Z | 2015-12-30T16:16:19.000Z | sandbox/images/reseau_serveur_utile.py | chiesax/sandbox | 3b628e0068c6f7116c3a98d481299158a8bf5de3 | [
"MIT"
]
| null | null | null | #!/usr/bin/python3.4
# -*-coding:utf-8 -*
"""
https://openclassrooms.com/courses/apprenez-a-programmer-en-python/le-reseau
ร LA FIN LE TERMINAL QUITTE PYTHON :
DONC CE PROGRAMME NE MARCHE PAS !!
"""
# Les deux lignes prรฉcรฉdentes serviraient si je rendais ce fichier
# directement exรฉcutable
import socket
# Construire notre socket : LE SERVEUR
# socket.AF_INET : la famille d'adresses, ici ce sont des adresses Internet ;
#
# socket.SOCK_STREAM : le type du socket, SOCK_STREAM pour le protocole TCP.
connexion_principale = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print("connexion_principale :\n",connexion_principale)
# Connecter le socket
# le nom de l'hรดte sera vide et le port sera celui que vous voulez, entre 1024 et 65535.
connexion_principale.bind(("",12800)) # l'argument unique de bind est un tuple !!
print("bind :\n",connexion_principale.bind)
# Faire รฉcouter notre socket
connexion_principale.listen(5)
print("listen :\n",connexion_principale.listen)
print("salute")
# +++ Il y a donc deux ports dans notre histoire +++
#
# mais celui qu'utilise le client
# pour ouvrir sa connexion ne va pas nous intรฉresser.
connexion_avec_client,infos_connexion = connexion_principale.accept()
| 27.844444 | 89 | 0.739824 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 900 | 0.714286 |
3e9b7d58a68d506fe7a43a816c3f565b193865ec | 10,030 | py | Python | crawler_shopee.py | HariWu1995/ecommerce_crawlers | 578957dbbce2914f8af16c5f21c6529591a9f1d4 | [
"CC0-1.0"
]
| null | null | null | crawler_shopee.py | HariWu1995/ecommerce_crawlers | 578957dbbce2914f8af16c5f21c6529591a9f1d4 | [
"CC0-1.0"
]
| null | null | null | crawler_shopee.py | HariWu1995/ecommerce_crawlers | 578957dbbce2914f8af16c5f21c6529591a9f1d4 | [
"CC0-1.0"
]
| null | null | null | import os
import sys
import time
from tqdm import tqdm as print_progress
import csv
import json
import logging
import numpy as np
import pandas as pd
import random
import cv2
from PIL import Image
from matplotlib import pyplot as plt
import re
import requests
from io import BytesIO
from bs4 import BeautifulSoup as BS
from urllib import request, response
from selenium import webdriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.common.proxy import *
from selenium.common.exceptions import *
import sqlite3 as sqllib
from sql_commands import *
from driver_utils import *
from utils import *
working_dir = os.path.dirname(__file__)
# Define global variables
page_url = 'https://www.shopee.vn'
data_source = 'shopee'
def crawl_all_categories(driver, first_time: bool=False):
driver.get(page_url)
# Scroll down to load all page
simulate_scroll(driver, 5, 1)
# Crawl
categories = []
categories_groups = driver.find_elements_by_css_selector('[class="home-category-list__group"]')
for cat_group in categories_groups:
categories_raw = cat_group.find_elements_by_css_selector('[class="home-category-list__category-grid"]')
for cat_raw in categories_raw:
cat_title = cat_raw.find_element_by_css_selector('[class="vvKCN3"]')
category_info = [
cat_title.get_attribute("innerHTML").replace('&', '&'),
cat_raw.get_attribute('href'),
data_source
]
if first_time:
insert_new_category(category_info)
categories.append(category_info)
return categories
def crawl_single_category(driver, category_url: str, category_id: int):
print(f"\n\n\nLoading\n\t{category_url}")
driver.get(category_url)
# Scroll down to load all page
simulate_scroll(driver, 11, 0, 0.69, 1.96)
random_sleep()
category_url += '/?page={}'
all_products = []
page_id, max_pages = 1, 49
while page_id <= max_pages:
product_css = '[class="col-xs-2-4 shopee-search-item-result__item"]'
try:
print(f"\n\n\nCrawling page {page_id} ...")
# Get the review details
WebDriverWait(driver, timeout=random.randint(6,9)).until(
method=expected_conditions.visibility_of_all_elements_located(
locator=(By.CSS_SELECTOR, product_css)
)
)
except Exception:
print("Can't find any item!")
break
# Get product info
products_raw = driver.find_elements_by_css_selector(product_css)
for product_raw in products_raw:
try:
product_url = product_raw.find_element_by_css_selector('[data-sqe="link"]').get_attribute('href').split('?', 1)[0]
product_title = product_raw.find_element_by_css_selector('[data-sqe="name"]').find_element_by_tag_name('div').text
if not (product_title != '' or product_title.strip()):
continue
product_info = [product_title, product_url, category_id]
insert_new_product(product_info)
all_products.append(product_info)
except Exception:
print("Cannot crawl product")
continue
# open new tab
current_tab = driver.current_window_handle
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[-1])
# crawl products' reviews per category
product_title = product_info[0].replace('"', "'")
query = f'SELECT id FROM products WHERE title = "{product_title}" AND category_id = "{category_id}"'
execute_sql(query)
product_id = db_cursor.fetchone()[0]
try:
crawl_single_product(driver, product_info[1], product_id)
except Exception as e:
# print("Error while crawl\n\t", product_info[1])
# print(e)
pass
# close tab
driver.close()
driver.switch_to.window(current_tab)
# Go to next page
driver.get(category_url.format(page_id))
simulate_scroll(driver, 11, 0, 0.69, 1.96)
page_id += 1
def crawl_single_product(driver, product_url: str, product_id: int):
print(f"\n\n\nLoading\n\t{product_url}")
driver.get(product_url)
# Scroll down to load all page
simulate_scroll(driver)
page_id, max_pages = 1, 49
while page_id <= max_pages:
simulate_scroll(driver, 5, 1, 0.69, 0.96)
review_css = '[class="shopee-product-rating"]'
try:
print(f"\n\t\tCrawling page {page_id} ...")
# Get the review details
WebDriverWait(driver, timeout=random.randint(6,9)).until(
method=expected_conditions.visibility_of_all_elements_located(
locator=(By.CSS_SELECTOR, review_css)
)
)
except Exception:
print("Can't find any review!")
break
# Get product reviews
all_reviews = driver.find_elements_by_css_selector(review_css)
for raw_review in all_reviews:
try:
crawl_single_review(raw_review, product_id)
except Exception as e:
print("Error while crawling comment\n\t")
try:
page_buttons_css = '[class="shopee-button-no-outline"]'
page_buttons = driver.find_elements_by_css_selector(page_buttons_css)
if len(page_buttons) < 1:
print("\n\t\tOnly 1 page")
break
for page_button in page_buttons:
page_button_id = page_button.get_attribute("innerHTML")
if page_button_id == '':
continue
if int(page_button_id) > page_id:
page_button.click()
random_sleep()
page_id += 1
break
except Exception as e:
# print("\n\t\tOut-of-page Error: ", e)
break
def crawl_single_review(raw_review, product_id):
content = raw_review.find_element_by_css_selector("[class='shopee-product-rating__main']")
# Read review content
review = content.find_element_by_css_selector("[class='shopee-product-rating__content']").text
# Filter-out non-text reviews
if not (review != '' or review.strip()):
return 'Review is empty'
review = review.replace('\n', ' . ').replace('\t', ' . ')
# Read number of likes for this review
try:
n_likes = content.find_element_by_css_selector("[class='shopee-product-rating__like-count']")\
.get_attribute("innerHTML")
n_likes = re.sub('[^0-9]', '', n_likes)
if n_likes == '':
n_likes = 0
else:
n_likes = int(n_likes)
except Exception:
n_likes = -1
# Read rating
try:
rating = 5
stars = content.find_element_by_css_selector('div.shopee-product-rating__rating')\
.find_elements_by_tag_name("svg")
for star in stars:
star_color = star.find_element_by_tag_name('polygon')
try:
star_empty = star_color.get_attribute('fill')
if star_empty == 'none':
rating -= 1
except Exception:
pass
except Exception:
rating = -1
# Read verification
is_verified = 'ฤรฃ xรกc thแปฑc' if n_likes > 0 else 'chฦฐa xรกc thแปฑc'
insert_new_review([review, is_verified, n_likes, rating, product_id])
# print('\t\t\t', review, is_verified, n_likes, rating)
def main(driver, first_time: bool):
# Step 1: Get all categories in main page
all_categories = crawl_all_categories(driver, first_time)
db_cursor.execute("SELECT category_id FROM products;")
crawled_category_ids = list(set(
np.array(db_cursor.fetchall()).flatten().tolist()
))
print(f"Categories crawled: {crawled_category_ids}")
random_sleep()
# Step 2: Get products per categories page-by-page, then crawl their info & reviews
main_page = driver.current_window_handle
random.shuffle(all_categories)
for category_info in all_categories:
# open new tab
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[-1])
random_sleep()
# crawl products' reviews per category
query = f'SELECT id FROM categories WHERE url = "{category_info[1]}" AND source = "{data_source}"'
execute_sql(query)
category_id = db_cursor.fetchone()[0]
if category_id not in crawled_category_ids:
crawl_single_category(driver, category_info[1], category_id)
random_sleep()
print(f'Finish crawling {category_info[1]} at {data_source}')
# close current tab
driver.close()
driver.switch_to.window(main_page)
if __name__ == "__main__":
initialize_db()
first_time = True
while True:
# Step 0: Initialize
browser = random.choice(['chrome', 'firefox', 'edge'])
driver = initialize_driver(browser)
try:
main(driver, first_time)
except Exception as e:
print("\n\n\nCrash ... Please wait a few seconds!!!")
for t in print_progress(range(69)):
time.sleep(1)
first_time = False
driver.quit()
db_connector.close()
| 34.826389 | 131 | 0.598006 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,145 | 0.213667 |
3e9c99bd9c44f5d31431b1d6a56ba33cddb063ae | 6,584 | py | Python | tests/inferbeddings/regularizers/test_regularizers.py | issca/inferbeddings | 80492a7aebcdcac21e758514c8af403d77e8594a | [
"MIT"
]
| 33 | 2017-07-25T14:31:00.000Z | 2019-03-06T09:18:00.000Z | tests/inferbeddings/regularizers/test_regularizers.py | issca/inferbeddings | 80492a7aebcdcac21e758514c8af403d77e8594a | [
"MIT"
]
| 1 | 2017-08-22T13:49:30.000Z | 2017-08-22T13:49:30.000Z | tests/inferbeddings/regularizers/test_regularizers.py | issca/inferbeddings | 80492a7aebcdcac21e758514c8af403d77e8594a | [
"MIT"
]
| 9 | 2017-10-05T08:50:45.000Z | 2019-04-18T12:40:56.000Z | # -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf
from inferbeddings.regularizers import TransEEquivalentPredicateRegularizer
from inferbeddings.regularizers import DistMultEquivalentPredicateRegularizer
from inferbeddings.regularizers import ComplExEquivalentPredicateRegularizer
from inferbeddings.regularizers import BilinearEquivalentPredicateRegularizer
import pytest
def l2sqr(x):
return np.sum(np.square(x), axis=-1)
def complex_conjugate(x):
x_re, x_im = np.split(x, indices_or_sections=2, axis=-1)
return np.concatenate((x_re, - x_im), axis=-1)
@pytest.mark.light
def test_translations():
rs = np.random.RandomState(0)
pe = rs.rand(1024, 10)
var = tf.Variable(pe, name='predicate_embedding')
init_op = tf.global_variables_initializer()
with tf.Session() as session:
session.run(init_op)
loss = TransEEquivalentPredicateRegularizer(x1=var[0, :], x2=var[0, :])()
np.testing.assert_almost_equal(session.run(loss), 0.0)
loss = TransEEquivalentPredicateRegularizer(x1=var[0, :], x2=var[1, :])()
np.testing.assert_almost_equal(session.run(loss), l2sqr(pe[0, :] - pe[1, :]))
loss = TransEEquivalentPredicateRegularizer(x1=var[0:4, :], x2=var[0:4, :])()
np.testing.assert_almost_equal(session.run(loss), [0.0] * 4)
loss = TransEEquivalentPredicateRegularizer(x1=var[0, :], x2=var[1, :], is_inverse=True)()
np.testing.assert_almost_equal(session.run(loss), l2sqr(pe[0, :] + pe[1, :]))
loss = TransEEquivalentPredicateRegularizer(x1=var[0:4, :], x2=var[1:5, :])()
np.testing.assert_almost_equal(session.run(loss), l2sqr(pe[0:4, :] - pe[1:5, :]))
loss = TransEEquivalentPredicateRegularizer(x1=var[0:4, :], x2=var[1:5, :], is_inverse=True)()
np.testing.assert_almost_equal(session.run(loss), l2sqr(pe[0:4, :] + pe[1:5, :]))
tf.reset_default_graph()
@pytest.mark.light
def test_scaling():
rs = np.random.RandomState(0)
pe = rs.rand(1024, 10)
var = tf.Variable(pe, name='predicate_embedding')
init_op = tf.global_variables_initializer()
with tf.Session() as session:
session.run(init_op)
loss = DistMultEquivalentPredicateRegularizer(x1=var[0, :], x2=var[0, :])()
np.testing.assert_almost_equal(session.run(loss), 0.0)
loss = DistMultEquivalentPredicateRegularizer(x1=var[0, :], x2=var[1, :])()
np.testing.assert_almost_equal(session.run(loss), l2sqr(pe[0, :] - pe[1, :]))
loss = DistMultEquivalentPredicateRegularizer(x1=var[0:4, :], x2=var[0:4, :])()
np.testing.assert_almost_equal(session.run(loss), [0.0] * 4)
loss = DistMultEquivalentPredicateRegularizer(x1=var[0, :], x2=var[1, :], is_inverse=True)()
np.testing.assert_almost_equal(session.run(loss), l2sqr(pe[0, :] - pe[1, :]))
loss = DistMultEquivalentPredicateRegularizer(x1=var[0:4, :], x2=var[1:5, :])()
np.testing.assert_almost_equal(session.run(loss), l2sqr(pe[0:4, :] - pe[1:5, :]))
loss = DistMultEquivalentPredicateRegularizer(x1=var[0:4, :], x2=var[1:5, :], is_inverse=True)()
np.testing.assert_almost_equal(session.run(loss), l2sqr(pe[0:4, :] - pe[1:5, :]))
tf.reset_default_graph()
@pytest.mark.light
def test_complex():
rs = np.random.RandomState(0)
pe = rs.rand(1024, 10)
var = tf.Variable(pe, name='predicate_embedding')
init_op = tf.global_variables_initializer()
with tf.Session() as session:
session.run(init_op)
loss = ComplExEquivalentPredicateRegularizer(x1=var[0, :], x2=var[0, :])()
np.testing.assert_almost_equal(session.run(loss), 0.0)
loss = ComplExEquivalentPredicateRegularizer(x1=var[0, :], x2=var[1, :])()
np.testing.assert_almost_equal(session.run(loss), l2sqr(pe[0, :] - pe[1, :]))
loss = ComplExEquivalentPredicateRegularizer(x1=var[0:4, :], x2=var[0:4, :])()
np.testing.assert_almost_equal(session.run(loss), [0.0] * 4)
loss = ComplExEquivalentPredicateRegularizer(x1=var[0, :], x2=var[1, :], is_inverse=True)()
np.testing.assert_almost_equal(session.run(loss), l2sqr(pe[0, :] - complex_conjugate(pe[1, :])))
loss = ComplExEquivalentPredicateRegularizer(x1=var[0:4, :], x2=var[1:5, :])()
np.testing.assert_almost_equal(session.run(loss), l2sqr(pe[0:4, :] - pe[1:5, :]))
loss = ComplExEquivalentPredicateRegularizer(x1=var[0:4, :], x2=var[1:5, :], is_inverse=True)()
np.testing.assert_almost_equal(session.run(loss), l2sqr(pe[0:4, :] - complex_conjugate(pe[1:5, :])))
tf.reset_default_graph()
@pytest.mark.light
def test_bilinear():
rs = np.random.RandomState(0)
pe = rs.rand(1024, 16)
var = tf.Variable(pe, name='predicate_embedding')
kwargs = {'entity_embedding_size': 4}
init_op = tf.global_variables_initializer()
with tf.Session() as session:
session.run(init_op)
loss = BilinearEquivalentPredicateRegularizer(x1=var[0, :], x2=var[0, :], **kwargs)()
np.testing.assert_almost_equal(session.run(loss), 0.0)
var3 = tf.reshape(var, [-1, 4, 4])
s_var = tf.reshape(var3 + tf.transpose(var3, [0, 2, 1]), [-1, 16])
loss = BilinearEquivalentPredicateRegularizer(x1=s_var[0, :], x2=s_var[0, :], is_inverse=True, **kwargs)()
np.testing.assert_almost_equal(session.run(loss), 0.0)
def invert(emb):
predicate = emb
predicate_matrix = tf.reshape(predicate, [-1, 4, 4])
predicate_matrix_transposed = tf.transpose(predicate_matrix, [0, 2, 1])
predicate_inverse = tf.reshape(predicate_matrix_transposed, [-1, 16])
return predicate_inverse
for i in range(32):
loss = BilinearEquivalentPredicateRegularizer(x1=var[i, :], x2=var[i, :], is_inverse=False, **kwargs)()
np.testing.assert_almost_equal(session.run(loss), 0.0)
loss = BilinearEquivalentPredicateRegularizer(x1=var[i, :], x2=invert(var[i, :]), is_inverse=True, **kwargs)()
np.testing.assert_almost_equal(session.run(loss), 0.0)
loss = BilinearEquivalentPredicateRegularizer(x1=var[0:32, :], x2=var[0:32, :], is_inverse=False, **kwargs)()
np.testing.assert_almost_equal(session.run(loss), 0.0)
loss = BilinearEquivalentPredicateRegularizer(x1=var[0:32, :], x2=invert(var[0:32, :]), is_inverse=True, **kwargs)()
np.testing.assert_almost_equal(session.run(loss), 0.0)
tf.reset_default_graph()
if __name__ == '__main__':
pytest.main([__file__])
| 39.662651 | 124 | 0.659326 | 0 | 0 | 0 | 0 | 5,925 | 0.899909 | 0 | 0 | 140 | 0.021264 |
3e9de159f87129c1ecdbf87d9939fc63a59cd88b | 1,360 | py | Python | Chapter 08/8.11_chaos_game.py | ACsBlack/Tkinter-GUI-Application-Development-Blueprints-Second-Edition | c6a045fbf5ba3ece5e8a02bbe33ac13bb57b2b8e | [
"MIT"
]
| 120 | 2018-03-04T07:17:00.000Z | 2022-01-25T08:09:57.000Z | Chapter 08/8.11_chaos_game.py | ACsBlack/Tkinter-GUI-Application-Development-Blueprints-Second-Edition | c6a045fbf5ba3ece5e8a02bbe33ac13bb57b2b8e | [
"MIT"
]
| 3 | 2019-03-24T09:32:43.000Z | 2020-07-28T07:35:49.000Z | Chapter 08/8.11_chaos_game.py | ACsBlack/Tkinter-GUI-Application-Development-Blueprints-Second-Edition | c6a045fbf5ba3ece5e8a02bbe33ac13bb57b2b8e | [
"MIT"
]
| 81 | 2018-04-18T06:51:46.000Z | 2022-03-30T01:31:35.000Z | """
Code illustration: 8.11
Chaos Game
Tkinter GUI Application Development Blueprints
"""
import random
from tkinter import Tk, Canvas
import math
WIDTH = 800
HEIGHT = 500
v1 = (float(WIDTH/2), 0.0)
v2 = (0.00, float(HEIGHT))
v3 = (float(WIDTH), float(HEIGHT))
last_point = None
root = Tk()
canvas = Canvas(root, background="#660099", width = WIDTH, height = HEIGHT)
canvas.pack()
def midway_point(p1, p2):
x = p1[0] + (p2[0] - p1[0]) //2
y = p1[1] + (p2[1] - p1[1]) //2
return (x,y)
def random_point_inside_triangle(v1, v2, v3):
a = random.random()
b = random.random()
if a + b > 1:
a = 1-a
b = 1-b
c = 1 - a -b
x = (a*v1[0])+(b*v2[0])+(c*v3[0]);
y = (a*v1[1])+(b*v2[1])+(c*v3[1]);
return (x,y)
last_point = random_point_inside_triangle(v1, v2, v3)
def get_next_point():
global last_point
roll = random.choice(range(6))+1
mid_point = None
if roll == 1 or roll == 2:
mid_point = midway_point(last_point, v1)
elif roll == 3 or roll == 4:
mid_point = midway_point(last_point, v2)
elif roll == 5 or roll == 6:
mid_point = midway_point(last_point, v3)
last_point = mid_point
return mid_point
def update():
x,y = get_next_point()
canvas.create_rectangle(x, y, x, y, outline="#FFFF33")
root.after(1, update)
update()
root.mainloop()
| 21.25 | 75 | 0.605147 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 111 | 0.081618 |
3e9e105d1fe756d9759cec38597f51f376c2fdd7 | 1,129 | py | Python | home/migrations/0010_auto_20150916_1146.py | taedori81/gentlecoffee | 62de8ff17c934afdfde188ecc6b9dbfb400d0682 | [
"BSD-3-Clause"
]
| null | null | null | home/migrations/0010_auto_20150916_1146.py | taedori81/gentlecoffee | 62de8ff17c934afdfde188ecc6b9dbfb400d0682 | [
"BSD-3-Clause"
]
| null | null | null | home/migrations/0010_auto_20150916_1146.py | taedori81/gentlecoffee | 62de8ff17c934afdfde188ecc6b9dbfb400d0682 | [
"BSD-3-Clause"
]
| null | null | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import wagtail.wagtailcore.fields
import wagtail.wagtailcore.blocks
import datetime
import wagtail.wagtailimages.blocks
class Migration(migrations.Migration):
dependencies = [
('home', '0009_subscribepage'),
]
operations = [
migrations.AddField(
model_name='blogpage',
name='author',
field=models.CharField(max_length=255, default='Gentle Coffee'),
),
migrations.AddField(
model_name='blogpage',
name='body',
field=wagtail.wagtailcore.fields.StreamField((('heading', wagtail.wagtailcore.blocks.CharBlock(classname='full title')), ('paragraph', wagtail.wagtailcore.blocks.RichTextBlock()), ('image', wagtail.wagtailimages.blocks.ImageChooserBlock())), blank=True),
),
migrations.AddField(
model_name='blogpage',
name='date',
field=models.DateField(verbose_name='Post Date', default=datetime.datetime(2015, 9, 16, 11, 46, 26, 479699)),
),
]
| 33.205882 | 266 | 0.648361 | 900 | 0.797166 | 0 | 0 | 0 | 0 | 0 | 0 | 164 | 0.145261 |
3e9f295d7038dec0577aca1bae6bbad75edf434c | 2,083 | py | Python | src/hard/multi_search.py | JadielTeofilo/General-Algorithms | dfcf86c6ecd727573079f8971187c47bdb7a37bb | [
"MIT"
]
| null | null | null | src/hard/multi_search.py | JadielTeofilo/General-Algorithms | dfcf86c6ecd727573079f8971187c47bdb7a37bb | [
"MIT"
]
| null | null | null | src/hard/multi_search.py | JadielTeofilo/General-Algorithms | dfcf86c6ecd727573079f8971187c47bdb7a37bb | [
"MIT"
]
| null | null | null | """
17.17 Multi Search: Given a string b and an array of smaller strings T, design a method to search b for
each small string in T.
In - text: str, words: List[str]
Out - List[str]
lgget`s go to the party tonight?
['go', 'test', 'jump']
return ['go']
O(k^2 + n*t) time complexity, where k is the size of text, n is the size of words, and t is the size of the biggest word
O(k^2) space complexity
"""
from typing import Dict, Any, List
TrieNode = Dict[str, Any]
class Trie:
def __init__(self) -> None:
self.trie: TrieNode = {'children': {}}
def insert(self, word: str) -> None:
if not word:
return
self._insert_helper(word, self.trie)
def _insert_helper(self, word: str, node: TrieNode) -> None:
if not word:
return
target_char: str = word[0]
if target_char not in node['children']:
node['children'][target_char] = {'children': {}}
return self._insert_helper(
word[1:],
node['children'][target_char],
)
def search(self, word: str) -> bool:
if not word:
raise ValueError('Empty input')
return self._search_helper(word, self.trie)
def _search_helper(self, word: str, node: TrieNode) -> bool:
if not word:
return True
target_char: str = word[0]
if target_char not in node['children']:
return False
return self._search_helper(
word[1:],
node['children'][target_char],
)
def multi_search(text: str, words: List[str]) -> List[str]:
# TODO validate input
trie: Trie = build_trie(text)
result: List[str] = []
for word in words:
if trie.search(word):
result.append(word)
return result
def build_trie(text: str) -> Trie:
"""
Inserts all possible substrings on the trie
"""
trie: Trie = Trie()
for i in range(len(text)):
trie.insert(text[i:])
return trie
print(multi_search('lgget`s go to the party tonight?', ['go', 'test', 'jump']))
| 24.797619 | 120 | 0.586174 | 1,070 | 0.513682 | 0 | 0 | 0 | 0 | 0 | 0 | 623 | 0.299088 |
3e9f73be09a575abe5d0c2f48b7beb177bd85283 | 793 | py | Python | setup.py | yoarch/replace | 5255810c019141f7de03b96c26a9b732d2218597 | [
"MIT"
]
| null | null | null | setup.py | yoarch/replace | 5255810c019141f7de03b96c26a9b732d2218597 | [
"MIT"
]
| null | null | null | setup.py | yoarch/replace | 5255810c019141f7de03b96c26a9b732d2218597 | [
"MIT"
]
| null | null | null | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="replacefs",
version="1.2.0",
python_requires='>=3',
author="yoarch",
author_email="[email protected]",
description="Search and replace CLI tool for strings on the all system",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/yoarch/replace",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
entry_points={
"console_scripts": [
"replacefs = replacefs.__main__:main",
"rp = replacefs.__main__:main"
]
})
| 28.321429 | 76 | 0.659521 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 377 | 0.47541 |
3e9f9ed5bec5e5e254a0bf74367dcc5d5151767d | 26 | py | Python | tests/unit/test_modulegraph/__init__.py | hawkhai/pyinstaller | 016a24479b34de161792c72dde455a81ad4c78ae | [
"Apache-2.0"
]
| 9,267 | 2015-01-01T04:08:45.000Z | 2022-03-31T11:42:38.000Z | tests/unit/test_modulegraph/__init__.py | jeremysanders/pyinstaller | 321b24f9a9a5978337735816b36ca6b4a90a2fb4 | [
"Apache-2.0"
]
| 5,150 | 2015-01-01T12:09:56.000Z | 2022-03-31T18:06:12.000Z | tests/unit/test_modulegraph/__init__.py | jeremysanders/pyinstaller | 321b24f9a9a5978337735816b36ca6b4a90a2fb4 | [
"Apache-2.0"
]
| 2,101 | 2015-01-03T10:25:27.000Z | 2022-03-30T11:04:42.000Z | """ modulegraph tests """
| 13 | 25 | 0.615385 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 0.961538 |
3ea0a1cb7ee908d792303d9bcee0623c9c0029ae | 774 | py | Python | ZD2.py | Novomlinov/Lab5 | bd86f277be60173472202329a86790ca08549c26 | [
"MIT"
]
| null | null | null | ZD2.py | Novomlinov/Lab5 | bd86f277be60173472202329a86790ca08549c26 | [
"MIT"
]
| null | null | null | ZD2.py | Novomlinov/Lab5 | bd86f277be60173472202329a86790ca08549c26 | [
"MIT"
]
| null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
if __name__ == '__main__':
A = list(map(int, input().split()))
if len(A) != 10:
print("ะะตะฒะตัะฝัะน ัะฐะทะผะตั ัะฟะธัะบะฐ", file=sys.stderr)
exit(1)
s = 0
for item in A:
if not ((item % 2) == 0):
s += item
x0 = 0 # ะะพะทะธัะธั ะฟะตัะฒะพะณะพ ะพััะธัะฐัะตะปัะฝะพะณะพ ัะปะตะผะตะฝัะฐ
x1 = 0 # ะะพะทะธัะธั ะฟะพัะปะตะดะฝะตะณะพ ะพััะธัะฐัะตะปัะฝะพะณะพ ัะปะตะผะตะฝัะฐ
for i, a in enumerate(A):
if a < 0:
x0 = i
break
for i, a in enumerate(A[::-1]):
if a < 0:
x1 = len(A) - 1 - i
break
print(s)
print(sum(A[x0 + 1:x1]))
snew=list(filter(lambda x: abs(x)>1, A))
for _ in range(len(A)-len(snew)): snew.append(0)
print(snew) | 25.8 | 57 | 0.5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 263 | 0.302647 |
3ea4ef2ff77ddb776dc4b7390350caad1477ed17 | 687 | py | Python | elements/requesting.py | pughlab/GENIE-FMI-converter | 62009d419ac9ada8bfea2432412e0304724ae842 | [
"MIT"
]
| null | null | null | elements/requesting.py | pughlab/GENIE-FMI-converter | 62009d419ac9ada8bfea2432412e0304724ae842 | [
"MIT"
]
| 1 | 2019-11-19T16:49:21.000Z | 2019-11-19T16:49:21.000Z | elements/requesting.py | pughlab/GENIE-FMI-converter | 62009d419ac9ada8bfea2432412e0304724ae842 | [
"MIT"
]
| 1 | 2019-12-12T04:27:29.000Z | 2019-12-12T04:27:29.000Z | import requests
import re
import sys
xml = re.compile(r'<.+>|\n')
# queries using closed intervals [x,y], 1-based
def get_segment(url, chrom, coords):
r = requests.get(url, params={'segment': "{}:{},{}".format(chrom, *coords)})
if r.status_code == requests.codes.ok:
return re.sub(xml, '', r.text).upper()
else:
print("Bad request")
return None
# queries using half-open intervals [x,y), 0-based
def get_segment_local(d, chrom, coords):
try:
return str(d[chrom][coords[0] - 1: coords[1]]).upper()
except:
print("No record for {}:{}-{} in fasta".format(chrom, coords[0] - 1, coords[1]), file=sys.stderr)
return None
| 28.625 | 105 | 0.611354 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 174 | 0.253275 |
3ea642dd21695e59f25c2f55930176a71d62c99c | 82 | py | Python | python-analysers/src/test/resources/org/jetbrains/research/lupa/pythonAnalysis/imports/analysis/psi/importStatementsData/in_3_several_imports.py | JetBrains-Research/Lupa | c105487621564c60cae17395bf32eb40868ceb89 | [
"Apache-2.0"
]
| 16 | 2022-01-11T00:32:20.000Z | 2022-03-25T21:40:52.000Z | python-analysers/src/test/resources/org/jetbrains/research/lupa/pythonAnalysis/imports/analysis/psi/importStatementsData/in_3_several_imports.py | nbirillo/Kotlin-Analysis | 73c3b8a59bf40ed932bb512f30b0ff31f251af40 | [
"Apache-2.0"
]
| 12 | 2021-07-05T11:42:01.000Z | 2021-12-23T07:57:54.000Z | python-analysers/src/test/resources/org/jetbrains/research/lupa/pythonAnalysis/imports/analysis/psi/importStatementsData/in_3_several_imports.py | nbirillo/Kotlin-Analysis | 73c3b8a59bf40ed932bb512f30b0ff31f251af40 | [
"Apache-2.0"
]
| 3 | 2021-09-10T13:21:54.000Z | 2021-11-23T11:37:55.000Z | import cmath
import math
import logging
import random
import plotly
import pandas
| 11.714286 | 14 | 0.853659 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
3ea72258a32209376e761138207efecbaefac54c | 6,916 | py | Python | tf_agents/policies/categorical_q_policy.py | gregorgebhardt/agents | b6aeae5e0ed68dd4e4ec2ca73ef971254d3208f3 | [
"Apache-2.0"
]
| null | null | null | tf_agents/policies/categorical_q_policy.py | gregorgebhardt/agents | b6aeae5e0ed68dd4e4ec2ca73ef971254d3208f3 | [
"Apache-2.0"
]
| null | null | null | tf_agents/policies/categorical_q_policy.py | gregorgebhardt/agents | b6aeae5e0ed68dd4e4ec2ca73ef971254d3208f3 | [
"Apache-2.0"
]
| 3 | 2019-09-08T22:05:56.000Z | 2020-05-27T08:27:15.000Z | # coding=utf-8
# Copyright 2018 The TF-Agents Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required 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 language governing permissions and
# limitations under the License.
"""Simple Categorical Q-Policy for Q-Learning with Categorical DQN."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gin
import tensorflow as tf
import tensorflow_probability as tfp
from tf_agents.policies import tf_policy
from tf_agents.specs import tensor_spec
from tf_agents.trajectories import policy_step
from tf_agents.trajectories import time_step as ts
from tf_agents.utils import common
from tf_agents.utils import nest_utils
@gin.configurable()
class CategoricalQPolicy(tf_policy.Base):
"""Class to build categorical Q-policies."""
def __init__(self,
min_q_value,
max_q_value,
q_network,
action_spec,
temperature=1.0):
"""Builds a categorical Q-policy given a categorical Q-network.
Args:
min_q_value: A float specifying the minimum Q-value, used for setting up
the support.
max_q_value: A float specifying the maximum Q-value, used for setting up
the support.
q_network: A network.Network to use for our policy.
action_spec: A `BoundedTensorSpec` representing the actions.
temperature: temperature for sampling, when close to 0.0 is arg_max.
Raises:
ValueError: if `q_network` does not have property `num_atoms`.
TypeError: if `action_spec` is not a `BoundedTensorSpec`.
"""
num_atoms = getattr(q_network, 'num_atoms', None)
if num_atoms is None:
raise ValueError('Expected q_network to have property `num_atoms`, but '
'it doesn\'t. Network is: %s' % q_network)
time_step_spec = ts.time_step_spec(q_network.input_tensor_spec)
super(CategoricalQPolicy, self).__init__(
time_step_spec, action_spec, q_network.state_spec)
if not isinstance(action_spec, tensor_spec.BoundedTensorSpec):
raise TypeError('action_spec must be a BoundedTensorSpec. Got: %s' % (
action_spec,))
self._temperature = tf.convert_to_tensor(temperature, dtype=tf.float32)
self._min_q_value = min_q_value
self._max_q_value = max_q_value
self._num_atoms = q_network.num_atoms
self._q_network = q_network
self._support = tf.linspace(min_q_value, max_q_value, self._num_atoms)
self._action_dtype = action_spec.dtype
def _variables(self):
return self._q_network.variables
@gin.configurable(module='CategoricalQPolicy')
def _action(self, time_step, policy_state, seed=None):
"""Generates next action given the time_step and optional policy_state.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: A Tensor, or a nested dict, list or tuple of
Tensors representing the previous policy_state.
seed: Seed to use if action performs sampling (optional).
Returns:
An action Tensor, or a nested dict, list or tuple of Tensors,
matching the `action_spec()`.
A policy_state Tensor, or a nested dict, list or tuple of Tensors,
representing the new policy state.
"""
batched_time_step = nest_utils.batch_nested_tensors(time_step,
self.time_step_spec)
q_logits, policy_state = self._q_network(batched_time_step.observation,
batched_time_step.step_type,
policy_state)
q_logits.shape.assert_has_rank(3)
q_values = common.convert_q_logits_to_values(q_logits, self._support)
actions = tf.argmax(q_values, -1)
actions = tf.cast(actions, self._action_dtype, name='action')
actions = tf.nest.pack_sequence_as(self._action_spec, [actions])
return policy_step.PolicyStep(actions, policy_state)
@gin.configurable(module='CategoricalQPolicy')
def step(self, time_step, policy_state=(), num_samples=1):
"""Generates a random action given the time_step and policy_state.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: A Tensor, or a nested dict, list or tuple of
Tensors representing the previous policy_state.
num_samples: Integer, number of samples per time_step.
Returns:
An action Tensor, or a nested dict, list or tuple of Tensors,
matching the `action_spec()`.
A policy_state Tensor, or a nested dict, list or tuple of Tensors,
representing the new policy state.
"""
batched_time_step = nest_utils.batch_nested_tensors(time_step,
self.time_step_spec)
q_logits, policy_state = self._q_network(batched_time_step.observation,
batched_time_step.step_type,
policy_state)
q_logits.shape.assert_has_rank(3)
q_values = common.convert_q_logits_to_values(q_logits, self._support)
logits = q_values / self._temperature
actions = tf.random.categorical(logits, num_samples)
if num_samples == 1:
actions = tf.squeeze(actions, [-1])
actions = tf.cast(actions, self._action_dtype, name='step')
actions = tf.nest.pack_sequence_as(self._action_spec, [actions])
return actions, policy_state
def _distribution(self, time_step, policy_state):
"""Generates the distribution over next actions given the time_step.
Args:
time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.
policy_state: A Tensor, or a nested dict, list or tuple of
Tensors representing the previous policy_state.
Returns:
A tfp.distributions.Categorical capturing the distribution of next
actions.
A policy_state Tensor, or a nested dict, list or tuple of Tensors,
representing the new policy state.
"""
q_logits, policy_state = self._q_network(time_step.observation,
time_step.step_type,
policy_state)
q_logits.shape.assert_has_rank(3)
q_values = common.convert_q_logits_to_values(q_logits, self._support)
return policy_step.PolicyStep(
tfp.distributions.Categorical(logits=q_values,
dtype=self.action_spec.dtype),
policy_state)
| 41.915152 | 78 | 0.686669 | 5,783 | 0.836177 | 0 | 0 | 5,803 | 0.839069 | 0 | 0 | 3,189 | 0.461105 |
3ea75b500ba52b9dd243fdb83d052c734dde9d13 | 477 | py | Python | invenio_oarepo_oai_pmh_harvester/rules/uk/creator.py | Semtexcz/invenio-oarepo-oai-pmh-harvester | 2866c7d7355f6885b4f443ee1e82baa24502b36e | [
"MIT"
]
| null | null | null | invenio_oarepo_oai_pmh_harvester/rules/uk/creator.py | Semtexcz/invenio-oarepo-oai-pmh-harvester | 2866c7d7355f6885b4f443ee1e82baa24502b36e | [
"MIT"
]
| null | null | null | invenio_oarepo_oai_pmh_harvester/rules/uk/creator.py | Semtexcz/invenio-oarepo-oai-pmh-harvester | 2866c7d7355f6885b4f443ee1e82baa24502b36e | [
"MIT"
]
| null | null | null | from invenio_oarepo_oai_pmh_harvester.register import Decorators
from invenio_oarepo_oai_pmh_harvester.rules.utils import iter_array
from invenio_oarepo_oai_pmh_harvester.transformer import OAITransformer
@Decorators.rule("xoai")
@Decorators.pre_rule("/dc/creator")
def transform_creator(paths, el, results, phase, **kwargs):
results[-1]["creator"] = [
{
"name": x
} for x in iter_array(el["value"])
]
return OAITransformer.PROCESSED
| 29.8125 | 71 | 0.735849 | 0 | 0 | 0 | 0 | 269 | 0.563941 | 0 | 0 | 41 | 0.085954 |
3ea87068d5cb5b9e7405c8d14e13c79ddfb0503e | 639 | py | Python | tests/test_queries.py | guillaumevincent/rangevoting | a8a1d5c7aabf2ea30fd89453e7bdec53d981ca36 | [
"MIT"
]
| 4 | 2015-03-23T09:48:32.000Z | 2020-08-25T13:19:08.000Z | tests/test_queries.py | guillaumevincent/rangevoting | a8a1d5c7aabf2ea30fd89453e7bdec53d981ca36 | [
"MIT"
]
| 4 | 2015-04-27T23:50:28.000Z | 2015-09-23T07:05:25.000Z | tests/test_queries.py | guillaumevincent/rangevoting | a8a1d5c7aabf2ea30fd89453e7bdec53d981ca36 | [
"MIT"
]
| 2 | 2015-09-21T08:58:25.000Z | 2020-08-25T13:19:14.000Z | import unittest
import queries
class QueriesTestCase(unittest.TestCase):
def test_get_rangevote_query(self):
uuid = 1
get_rangevote_query = queries.GetRangeVoteQuery(uuid)
self.assertEqual(uuid, get_rangevote_query.uuid)
def test_get_rangevote_results_query(self):
uuid = 1
get_rangevote_results_query = queries.GetRangeVoteResultsQuery(uuid)
self.assertEqual(uuid, get_rangevote_results_query.uuid)
def test_get_rangevotes_query(self):
get_rangevote_results_query = queries.GetRangeVotesQuery()
self.assertEqual(20, get_rangevote_results_query.count)
| 24.576923 | 76 | 0.746479 | 604 | 0.945227 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
3ea985da6ab078979759098314b0008ca7d1ea59 | 1,490 | py | Python | cgatpipelines/tools/pipeline_docs/pipeline_windows/trackers/GenomicContext.py | kevinrue/cgat-flow | 02b5a1867253c2f6fd6b4f3763e0299115378913 | [
"MIT"
]
| 49 | 2015-04-13T16:49:25.000Z | 2022-03-29T10:29:14.000Z | cgatpipelines/tools/pipeline_docs/pipeline_windows/trackers/GenomicContext.py | kevinrue/cgat-flow | 02b5a1867253c2f6fd6b4f3763e0299115378913 | [
"MIT"
]
| 252 | 2015-04-08T13:23:34.000Z | 2019-03-18T21:51:29.000Z | cgatpipelines/tools/pipeline_docs/pipeline_windows/trackers/GenomicContext.py | kevinrue/cgat-flow | 02b5a1867253c2f6fd6b4f3763e0299115378913 | [
"MIT"
]
| 22 | 2015-05-21T00:37:52.000Z | 2019-09-25T05:04:27.000Z | from MedipReport import ProjectTracker
from CGATReport.Tracker import SingleTableTrackerRows, \
SingleTableTrackerEdgeList
class ContextSummary(ProjectTracker, SingleTableTrackerRows):
table = "context_stats"
class GatFold(ProjectTracker, SingleTableTrackerEdgeList):
'''fold change matrix.'''
row = "sample"
column = "track"
value = "fold"
where = "pvalue < 0.05"
class GatLogFold(ProjectTracker):
'''logfold - colour is signficance'''
fdr = 0.05
as_tables = True
def __call__(self, track):
return self.getDict("""SELECT track, l2fold,
CASE WHEN qvalue < %(fdr)f THEN 'red' ELSE 'gray' END AS colour
FROM %(track)s ORDER BY fold""")
class GatResults(ProjectTracker):
as_tables = True
def __call__(self, track):
return self.getAll("SELECT * FROM %(track)s")
class GatSignificantResults(ProjectTracker):
as_tables = True
fdr = 0.05
def __call__(self, track):
return self.getAll("SELECT * FROM %(track)s WHERE qvalue < %(fdr)f")
class GatTableContext:
pattern = "(.*)_context_gat$"
_gat_analysis = {"Results": GatResults,
"SignificantResults": GatSignificantResults,
"Fold": GatLogFold,
"LogFold": GatLogFold}
_gat_sets = {"Context": GatTableContext}
for a, aa in list(_gat_analysis.items()):
for b, bb in list(_gat_sets.items()):
n = "Gat%s%s" % (a, b)
globals()[n] = type(n, (bb, aa), {})
| 24.032258 | 76 | 0.642953 | 960 | 0.644295 | 0 | 0 | 0 | 0 | 0 | 0 | 403 | 0.27047 |
3ead938794e4c6cd2d0971d9e594b96ceaee54b7 | 6,852 | py | Python | interfaces/withdrawal_gui.py | firminoneto11/terceiro-projeto-curso-python | 685a0e6fafdc07a28a4e7589ac40db0de61737c0 | [
"MIT"
]
| 1 | 2021-04-07T00:28:41.000Z | 2021-04-07T00:28:41.000Z | interfaces/withdrawal_gui.py | firminoneto11/terceiro-projeto-curso-python | 685a0e6fafdc07a28a4e7589ac40db0de61737c0 | [
"MIT"
]
| null | null | null | interfaces/withdrawal_gui.py | firminoneto11/terceiro-projeto-curso-python | 685a0e6fafdc07a28a4e7589ac40db0de61737c0 | [
"MIT"
]
| null | null | null | from tkinter import *
from interfaces.functions import centralize
from tkinter import messagebox
from interfaces.functions import update_session_data_csv, update_clients_csv, get_current_balance
class WithdrawalGUI:
def __init__(self, frame, label):
"""
This __init__ method initializes the sub window for the withdrawal area.
:param frame: This is the self.buttons_frame from GUISession class. It's going to be used to update the new
balance after a successfully withdrawal.
:param label: This is the self.buttons_frame from GUISession class. It's going to be used to update the new
balance after a successfully withdrawal.
"""
# Saving frame and label in order to update them after the withdrawal
self.frame = frame
self.label = label
# Creating another window for the 'withdrawal' section
self.withdrawal_gui = Toplevel()
self.withdrawal_gui.configure(background='#393e46')
self.withdrawal_gui.iconbitmap(r'.\valware.ico')
self.withdrawal_gui.resizable(False, False)
self.withdrawal_gui.title("Saque")
centralize(width=900, height=500, element=self.withdrawal_gui)
# State of the system
self.state_label = Label(self.withdrawal_gui, text='Sacar', bg='#393e46', fg='#eeeeee',
font=('Helvetica', 24))
# Main frame
self.main_frame = LabelFrame(self.withdrawal_gui, text='Dados do saque', fg='#00adb5', bg='#393e46',
font=('Helvetica', 14))
# Data
self.withdrawal_amount_label = Label(self.main_frame, text='Insira o valor do saque - ',
font=('Helvetica', 14), bg='#393e46', fg='#eeeeee')
self.withdrawal_amount = Entry(self.main_frame, font=('Helvetica', 14), borderwidth=3)
# Buttons
self.withdrawal_button = Button(self.main_frame, text="Sacar", width=20, font=('Helvetica', 14),
bg='#00adb5', fg='#eeeeee', borderwidth=3, command=self.__withdrawing)
self.cancel_button = Button(self.main_frame, text="Cancelar", width=20, font=('Helvetica', 14), bg='#222831',
fg='#eeeeee', borderwidth=3, command=self.withdrawal_gui.destroy)
# Inserting the elements onto the screen
self.state_label.pack(pady=50)
self.main_frame.pack()
self.withdrawal_amount_label.grid(row=0, column=0, pady=10, sticky=E)
self.withdrawal_amount.grid(row=0, column=1, pady=10)
self.withdrawal_button.grid(row=1, column=0, padx=10, pady=50)
self.cancel_button.grid(row=1, column=1, padx=10, pady=50)
def __withdrawing(self):
"""
This method does the whole withdrawal logic into the current client's session.
:return: None
"""
# Storing the gathered data into a variable
withdrawal = self.withdrawal_amount.get()
# Collecting the current balance
current_balance = get_current_balance()
# Checking if the withdrawal amount is valid
if len(withdrawal) == 0:
self.withdrawal_amount.delete(0, END)
error = messagebox.showerror("Campo vazio", "O valor para o saque estรก vazio!")
if error == 'ok':
self.withdrawal_gui.destroy()
return None
elif ',' in withdrawal:
withdrawal = withdrawal.replace(',', '.')
# Checking inserted values
try:
withdrawal = float(withdrawal)
# Taking care of possible exceptions
except ValueError:
self.withdrawal_amount.delete(0, END)
error = messagebox.showerror("Valor invรกlido", "O valor informado para saque รฉ invรกlido. Insira apenas "
"os dรญgitos/nรบmeros para o saque.")
if error == 'ok':
self.withdrawal_gui.destroy()
return None
# Validating the withdrawal amount that is going to be subtracted from the current balance.
new_balance_amount = round((current_balance - withdrawal), 2)
if new_balance_amount < 0:
self.withdrawal_amount.delete(0, END)
error = messagebox.showerror("Saldo insuficiente", "O valor informado para o saque รฉ insuficiente, pois o "
"seu saldo atual รฉ menor do que a quantia solicitada.")
if error == 'ok':
self.withdrawal_gui.destroy()
return None
# This part will only be executed if it passes all the previous verifications
else:
# Cleaning the typed data from the input entry
self.withdrawal_amount.delete(0, END)
# Before updating stuff, i need to get a confirmation from the user
response = messagebox.askyesno("Confirmar saque", f"Deseja efetuar o saque no valor de R${withdrawal} "
f"da sua conta?")
# If response is 'Yes' or True
if response:
# Updating the current balance in the session_gui class
self.__update_balance_after_withdrawal(balance=new_balance_amount)
# Updating session_data.csv and clients.csv
updated_data = update_session_data_csv(new_balance=new_balance_amount)
update_clients_csv(updated_data=updated_data)
# Informing to the user that its deposit has been successfully made
success = messagebox.showinfo("Saque feito com sucesso", f"Parabรฉns! Seu saque foi efetuado com "
f"sucesso no valor de R${withdrawal}. "
f"Seu novo saldo รฉ de R${new_balance_amount}.")
if success == 'ok':
self.withdrawal_gui.destroy()
return None
# If response is 'No' or False
else:
self.withdrawal_gui.destroy()
return None
def __update_balance_after_withdrawal(self, balance):
"""
This method updates the balance label from the GUISession class that was previously passed to the __init__
method. It will only be called after a successfully withdrawal.
:param balance: The new overall balance from the user. Previous balance minus the withdrawal.
:return: None
"""
self.label.destroy()
self.label = Label(self.frame, text=f"Saldo - R${balance}", font=('Helvetica', 14), bg='#393e46', fg='#eeeeee')
self.label.grid(row=1, column=0, pady=10)
| 48.253521 | 120 | 0.597052 | 6,664 | 0.971145 | 0 | 0 | 0 | 0 | 0 | 0 | 2,636 | 0.384145 |
3eaea2f364b0232cd2155f284fa3e784667552cf | 321 | py | Python | card_collector_db/urls.py | tyhunt99/card-collector-db | 932bd829eb46f9492e6a25326140823629161bab | [
"MIT"
]
| null | null | null | card_collector_db/urls.py | tyhunt99/card-collector-db | 932bd829eb46f9492e6a25326140823629161bab | [
"MIT"
]
| 4 | 2020-06-05T20:53:52.000Z | 2022-02-10T08:32:51.000Z | card_collector_db/urls.py | tyhunt99/card-collector-db | 932bd829eb46f9492e6a25326140823629161bab | [
"MIT"
]
| null | null | null | '''
cardcollectordb URL Configuration
'''
from django.contrib import admin
from django.urls import include, path
from account.views import SignUp
urlpatterns = [
path('admin/', admin.site.urls),
path('account/', include('account.urls'), name='account'),
path('signup/', SignUp.as_view(), name='signup'),
]
| 21.4 | 62 | 0.697819 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 99 | 0.308411 |
3eaf7ae8895d39770420351b1a65c6dd69d2f75e | 1,829 | py | Python | sdk/python/kfp/v2/components/utils.py | ryansteakley/pipelines | 98677b2190fb327be68e4bb0d00c520593707f21 | [
"Apache-2.0"
]
| 1 | 2021-10-23T00:39:47.000Z | 2021-10-23T00:39:47.000Z | sdk/python/kfp/v2/components/utils.py | ryansteakley/pipelines | 98677b2190fb327be68e4bb0d00c520593707f21 | [
"Apache-2.0"
]
| null | null | null | sdk/python/kfp/v2/components/utils.py | ryansteakley/pipelines | 98677b2190fb327be68e4bb0d00c520593707f21 | [
"Apache-2.0"
]
| null | null | null | # Copyright 2021 The Kubeflow Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required 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 language governing permissions and
# limitations under the License.
"""Definitions of utils methods."""
import importlib
import os
import re
import sys
import types
def load_module(module_name: str, module_directory: str) -> types.ModuleType:
"""Dynamically imports the Python module with the given name and package
path.
E.g., Assuming there is a file called `my_module.py` under
`/some/directory/my_module`, we can use::
load_module('my_module', '/some/directory')
to effectively `import mymodule`.
Args:
module_name: The name of the module.
package_path: The package under which the specified module resides.
"""
module_spec = importlib.util.spec_from_file_location(
name=module_name,
location=os.path.join(module_directory, f'{module_name}.py'))
module = importlib.util.module_from_spec(module_spec)
sys.modules[module_spec.name] = module
module_spec.loader.exec_module(module)
return module
def maybe_rename_for_k8s(name: str) -> str:
"""Cleans and converts a name to be k8s compatible.
Args:
name: The original name.
Returns:
A sanitized name.
"""
return re.sub('-+', '-', re.sub('[^-0-9a-z]+', '-',
name.lower())).lstrip('-').rstrip('-')
| 31.534483 | 77 | 0.689995 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,218 | 0.665938 |
3eafedfb7f7bd2c80bdda6855f91326da49ebb9e | 3,068 | py | Python | backend/test/notification_tests/notification_rest_tests.py | raphaelrpl/portal | 9e84e52a73500390187d3fc7c4871cf8a3620231 | [
"MIT"
]
| null | null | null | backend/test/notification_tests/notification_rest_tests.py | raphaelrpl/portal | 9e84e52a73500390187d3fc7c4871cf8a3620231 | [
"MIT"
]
| null | null | null | backend/test/notification_tests/notification_rest_tests.py | raphaelrpl/portal | 9e84e52a73500390187d3fc7c4871cf8a3620231 | [
"MIT"
]
| null | null | null | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from datetime import datetime, date
from decimal import Decimal
from base import GAETestCase
from notification_app.notification_model import Notification
from routes.notifications import rest
from gaegraph.model import Node
from mock import Mock
from mommygae import mommy
class IndexTests(GAETestCase):
def test_success(self):
mommy.save_one(Notification)
mommy.save_one(Notification)
json_response = rest.index()
context = json_response.context
self.assertEqual(2, len(context))
notification_dct = context[0]
self.assertSetEqual(set(['id', 'creation', 'message']), set(notification_dct.iterkeys()))
self.assert_can_serialize_as_json(json_response)
class NewTests(GAETestCase):
def test_success(self):
self.assertIsNone(Notification.query().get())
json_response = rest.new(None, message='message_string')
db_notification = Notification.query().get()
self.assertIsNotNone(db_notification)
self.assertEquals('message_string', db_notification.message)
self.assert_can_serialize_as_json(json_response)
def test_error(self):
resp = Mock()
json_response = rest.new(resp)
errors = json_response.context
self.assertEqual(500, resp.status_code)
self.assertSetEqual(set(['message']), set(errors.keys()))
self.assert_can_serialize_as_json(json_response)
class EditTests(GAETestCase):
def test_success(self):
notification = mommy.save_one(Notification)
old_properties = notification.to_dict()
json_response = rest.edit(None, notification.key.id(), message='message_string')
db_notification = notification.key.get()
self.assertEquals('message_string', db_notification.message)
self.assertNotEqual(old_properties, db_notification.to_dict())
self.assert_can_serialize_as_json(json_response)
def test_error(self):
notification = mommy.save_one(Notification)
old_properties = notification.to_dict()
resp = Mock()
json_response = rest.edit(resp, notification.key.id())
errors = json_response.context
self.assertEqual(500, resp.status_code)
self.assertSetEqual(set(['message']), set(errors.keys()))
self.assertEqual(old_properties, notification.key.get().to_dict())
self.assert_can_serialize_as_json(json_response)
class DeleteTests(GAETestCase):
def test_success(self):
notification = mommy.save_one(Notification)
rest.delete(None, notification.key.id())
self.assertIsNone(notification.key.get())
def test_non_notification_deletion(self):
non_notification = mommy.save_one(Node)
response = Mock()
json_response = rest.delete(response, non_notification.key.id())
self.assertIsNotNone(non_notification.key.get())
self.assertEqual(500, response.status_code)
self.assert_can_serialize_as_json(json_response)
| 38.835443 | 97 | 0.712842 | 2,701 | 0.880378 | 0 | 0 | 0 | 0 | 0 | 0 | 128 | 0.041721 |
3eb1886d18a07c578c32647296635bbe0ed29b6d | 285 | py | Python | yamlcfg/__init__.py | RiskIQ/pyyamlcfg | 93affb9dfdbae7deebd60b50b23b7036682866e4 | [
"BSD-2-Clause"
]
| 2 | 2016-05-25T13:50:14.000Z | 2017-08-08T18:24:04.000Z | yamlcfg/__init__.py | RiskIQ/pyyamlcfg | 93affb9dfdbae7deebd60b50b23b7036682866e4 | [
"BSD-2-Clause"
]
| 2 | 2015-09-13T12:48:50.000Z | 2019-04-25T10:26:00.000Z | yamlcfg/__init__.py | RiskIQ/pyyamlcfg | 93affb9dfdbae7deebd60b50b23b7036682866e4 | [
"BSD-2-Clause"
]
| 3 | 2016-04-29T07:12:44.000Z | 2019-04-08T07:52:14.000Z | #!/usr/bin/env python
''' yamlcfg
Bring in Configs into namespace
'''
from yamlcfg.conf import Config as BaseConfig
from yamlcfg.yml import YAMLConfig
YMLConfig = YAMLConfig
YamlConfig = YAMLConfig
from yamlcfg.util import normalize, validate_ext
from yamlcfg.env import check_env
| 19 | 48 | 0.8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 69 | 0.242105 |
3eb1b1746b5ee00b2b35cef5dad3b395d8706a08 | 294 | py | Python | www/bigghosthead/bigghosthead/items.py | baijiege9/BigGhostHead | 1ffa0bf390bad707e4fc902f9af98a4c73eea554 | [
"BSD-3-Clause"
]
| null | null | null | www/bigghosthead/bigghosthead/items.py | baijiege9/BigGhostHead | 1ffa0bf390bad707e4fc902f9af98a4c73eea554 | [
"BSD-3-Clause"
]
| null | null | null | www/bigghosthead/bigghosthead/items.py | baijiege9/BigGhostHead | 1ffa0bf390bad707e4fc902f9af98a4c73eea554 | [
"BSD-3-Clause"
]
| null | null | null | # -*- coding: utf-8 -*-
from scrapy.item import Item, Field
class BigghostheadItem(Item):
# ็ตๅ็ฝ็ซ็fields
productId = Field()
title = Field()# ๅๅ
store = Field()# ๅบ้บ
#ๆฐ้ปๅๅฎข็fields
text = Field()# ๆๆฌ
keywords = Field()# ๅ
ณ้ฎ่ฏ
comment = Field()
productId = Field() | 22.615385 | 35 | 0.602041 | 271 | 0.816265 | 0 | 0 | 0 | 0 | 0 | 0 | 103 | 0.310241 |
3eb626e1df9d6b1845d27917297cdbee245c41fb | 5,008 | py | Python | protos/gen/python/protos/public/modeldb/Lineage_pb2_grpc.py | CaptEmulation/modeldb | 78b10aca553e386554f9740db63466b1cf013a1a | [
"Apache-2.0"
]
| 835 | 2017-02-08T20:14:24.000Z | 2020-03-12T17:37:49.000Z | protos/gen/python/protos/public/modeldb/Lineage_pb2_grpc.py | CaptEmulation/modeldb | 78b10aca553e386554f9740db63466b1cf013a1a | [
"Apache-2.0"
]
| 651 | 2019-04-18T12:55:07.000Z | 2022-03-31T23:45:09.000Z | protos/gen/python/protos/public/modeldb/Lineage_pb2_grpc.py | CaptEmulation/modeldb | 78b10aca553e386554f9740db63466b1cf013a1a | [
"Apache-2.0"
]
| 170 | 2017-02-13T14:49:22.000Z | 2020-02-19T17:59:12.000Z | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from ..modeldb import Lineage_pb2 as modeldb_dot_Lineage__pb2
class LineageServiceStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.addLineage = channel.unary_unary(
'/ai.verta.modeldb.LineageService/addLineage',
request_serializer=modeldb_dot_Lineage__pb2.AddLineage.SerializeToString,
response_deserializer=modeldb_dot_Lineage__pb2.AddLineage.Response.FromString,
)
self.deleteLineage = channel.unary_unary(
'/ai.verta.modeldb.LineageService/deleteLineage',
request_serializer=modeldb_dot_Lineage__pb2.DeleteLineage.SerializeToString,
response_deserializer=modeldb_dot_Lineage__pb2.DeleteLineage.Response.FromString,
)
self.findAllInputs = channel.unary_unary(
'/ai.verta.modeldb.LineageService/findAllInputs',
request_serializer=modeldb_dot_Lineage__pb2.FindAllInputs.SerializeToString,
response_deserializer=modeldb_dot_Lineage__pb2.FindAllInputs.Response.FromString,
)
self.findAllOutputs = channel.unary_unary(
'/ai.verta.modeldb.LineageService/findAllOutputs',
request_serializer=modeldb_dot_Lineage__pb2.FindAllOutputs.SerializeToString,
response_deserializer=modeldb_dot_Lineage__pb2.FindAllOutputs.Response.FromString,
)
self.findAllInputsOutputs = channel.unary_unary(
'/ai.verta.modeldb.LineageService/findAllInputsOutputs',
request_serializer=modeldb_dot_Lineage__pb2.FindAllInputsOutputs.SerializeToString,
response_deserializer=modeldb_dot_Lineage__pb2.FindAllInputsOutputs.Response.FromString,
)
class LineageServiceServicer(object):
# missing associated documentation comment in .proto file
pass
def addLineage(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def deleteLineage(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def findAllInputs(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def findAllOutputs(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def findAllInputsOutputs(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_LineageServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'addLineage': grpc.unary_unary_rpc_method_handler(
servicer.addLineage,
request_deserializer=modeldb_dot_Lineage__pb2.AddLineage.FromString,
response_serializer=modeldb_dot_Lineage__pb2.AddLineage.Response.SerializeToString,
),
'deleteLineage': grpc.unary_unary_rpc_method_handler(
servicer.deleteLineage,
request_deserializer=modeldb_dot_Lineage__pb2.DeleteLineage.FromString,
response_serializer=modeldb_dot_Lineage__pb2.DeleteLineage.Response.SerializeToString,
),
'findAllInputs': grpc.unary_unary_rpc_method_handler(
servicer.findAllInputs,
request_deserializer=modeldb_dot_Lineage__pb2.FindAllInputs.FromString,
response_serializer=modeldb_dot_Lineage__pb2.FindAllInputs.Response.SerializeToString,
),
'findAllOutputs': grpc.unary_unary_rpc_method_handler(
servicer.findAllOutputs,
request_deserializer=modeldb_dot_Lineage__pb2.FindAllOutputs.FromString,
response_serializer=modeldb_dot_Lineage__pb2.FindAllOutputs.Response.SerializeToString,
),
'findAllInputsOutputs': grpc.unary_unary_rpc_method_handler(
servicer.findAllInputsOutputs,
request_deserializer=modeldb_dot_Lineage__pb2.FindAllInputsOutputs.FromString,
response_serializer=modeldb_dot_Lineage__pb2.FindAllInputsOutputs.Response.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'ai.verta.modeldb.LineageService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
| 43.547826 | 103 | 0.76877 | 3,161 | 0.63119 | 0 | 0 | 0 | 0 | 0 | 0 | 1,141 | 0.227835 |
3ebb613990f10c469e7937a90350ba7e43ef9d8e | 10,709 | py | Python | src/sparnn/layers/basic/conv_lstm_layer.py | JoeinChina/DeepWeather | 2677edc16d9865ec98401aaf121aaabd24974aaf | [
"MIT"
]
| 1 | 2020-07-23T04:13:02.000Z | 2020-07-23T04:13:02.000Z | src/sparnn/layers/basic/conv_lstm_layer.py | JoeBuzh/DeepWeather | 2677edc16d9865ec98401aaf121aaabd24974aaf | [
"MIT"
]
| null | null | null | src/sparnn/layers/basic/conv_lstm_layer.py | JoeBuzh/DeepWeather | 2677edc16d9865ec98401aaf121aaabd24974aaf | [
"MIT"
]
| null | null | null |
import numpy
import logging
import theano
import theano.tensor as TT
from theano.gradient import grad_clip
from sparnn.utils import *
from sparnn.layers import Layer
logger = logging.getLogger(__name__)
class ConvLSTMLayer(Layer):
def __init__(self, layer_param):
super(ConvLSTMLayer, self).__init__(layer_param)
if self.input is not None:
assert 5 == self.input.ndim
else:
assert ("init_hidden_state" in layer_param or "init_cell_state" in layer_param)
self.input_receptive_field = layer_param['input_receptive_field']
self.transition_receptive_field = layer_param['transition_receptive_field']
self.gate_activation = layer_param.get('gate_activation', 'sigmoid')
self.modular_activation = layer_param.get('modular_activation', 'tanh')
self.hidden_activation = layer_param.get('hidden_activation', 'tanh')
self.init_hidden_state = layer_param.get("init_hidden_state", quick_theano_zero((self.minibatch_size,) + self.dim_out))
self.init_cell_state = layer_param.get("init_cell_state", quick_theano_zero((self.minibatch_size,) + self.dim_out))
self.init_hidden_state = TT.unbroadcast(self.init_hidden_state, *range(self.init_hidden_state.ndim))
self.init_cell_state = TT.unbroadcast(self.init_cell_state, *range(self.init_cell_state.ndim))
self.learn_padding = layer_param.get('learn_padding', False)
self.input_padding = layer_param.get('input_padding', None)
if self.input is None:
assert 'n_steps' in layer_param
self.n_steps = layer_param['n_steps']
else:
self.n_steps = layer_param.get('n_steps', self.input.shape[0])
self.kernel_size = (self.feature_out, self.feature_in,
self.input_receptive_field[0], self.input_receptive_field[1])
self.transition_mat_size = (self.feature_out, self.feature_out,
self.transition_receptive_field[0], self.transition_receptive_field[1])
#print('ConvLSTMLayer', self.kernel_size, self.transition_mat_size)
self.W_hi = quick_init_xavier(self.rng, self.transition_mat_size, self._s("W_hi"))
self.W_hf = quick_init_xavier(self.rng, self.transition_mat_size, self._s("W_hf"))
self.W_ho = quick_init_xavier(self.rng, self.transition_mat_size, self._s("W_ho"))
self.W_hc = quick_init_xavier(self.rng, self.transition_mat_size, self._s("W_hc"))
if self.input is not None:
self.W_xi = quick_init_xavier(self.rng, self.kernel_size, self._s("W_xi"))
self.W_xf = quick_init_xavier(self.rng, self.kernel_size, self._s("W_xf"))
self.W_xo = quick_init_xavier(self.rng, self.kernel_size, self._s("W_xo"))
self.W_xc = quick_init_xavier(self.rng, self.kernel_size, self._s("W_xc"))
if self.learn_padding:
self.hidden_padding = quick_zero((self.feature_out, ), self._s("hidden_padding"))
else:
self.hidden_padding = None
self.b_i = quick_zero((self.feature_out, ), self._s("b_i"))
self.b_f = quick_zero((self.feature_out, ), self._s("b_f"))
self.b_o = quick_zero((self.feature_out, ), self._s("b_o"))
self.b_c = quick_zero((self.feature_out, ), self._s("b_c"))
self.W_ci = quick_zero((self.feature_out, ), self._s("W_ci"))
self.W_cf = quick_zero((self.feature_out, ), self._s("W_cf"))
self.W_co = quick_zero((self.feature_out, ), self._s("W_co"))
if self.input is not None:
self.param = [self.W_xi, self.W_hi, self.W_ci, self.b_i,
self.W_xf, self.W_hf, self.W_cf, self.b_f,
self.W_xo, self.W_ho, self.W_co, self.b_o,
self.W_xc, self.W_hc, self.b_c]
if self.learn_padding:
self.param.append(self.hidden_padding)
else:
self.param = [self.W_hi, self.W_ci, self.b_i,
self.W_hf, self.W_cf, self.b_f,
self.W_ho, self.W_co, self.b_o,
self.W_hc, self.b_c]
if self.learn_padding:
self.param.append(self.hidden_padding)
self.is_recurrent = True
self.fprop()
def set_name(self):
self.name = "ConvLSTMLayer-" + str(self.id)
def step_fprop(self, x_t, mask_t, h_tm1, c_tm1):
#print('step fprop in conv lstm layer:', self.dim_in, self.kernel_size)
if x_t is not None:
# input_gate = x_t*W + h_t*W + c_t W
input_gate = quick_activation(conv2d_same(x_t, self.W_xi, (None, ) + self.dim_in,
self.kernel_size, self.input_padding)
+ conv2d_same(h_tm1, self.W_hi, (None, ) + self.dim_out,
self.transition_mat_size, self.hidden_padding)
+ c_tm1 * self.W_ci.dimshuffle('x', 0, 'x', 'x')
+ self.b_i.dimshuffle('x', 0, 'x', 'x'), "sigmoid")
forget_gate = quick_activation(conv2d_same(x_t, self.W_xf, (None, ) + self.dim_in,
self.kernel_size, self.input_padding)
+ conv2d_same(h_tm1, self.W_hf, (None, ) + self.dim_out,
self.transition_mat_size, self.hidden_padding)
+ c_tm1 * self.W_cf.dimshuffle('x', 0, 'x', 'x')
+ self.b_f.dimshuffle('x', 0, 'x', 'x'), "sigmoid")
c_t = forget_gate * c_tm1 \
+ input_gate * quick_activation(conv2d_same(x_t, self.W_xc, (None, ) + self.dim_in,
self.kernel_size, self.input_padding)
+ conv2d_same(h_tm1, self.W_hc, (None, ) + self.dim_out,
self.transition_mat_size, self.hidden_padding)
+ self.b_c.dimshuffle('x', 0, 'x', 'x'), "tanh")
output_gate = quick_activation(conv2d_same(x_t, self.W_xo, (None, ) + self.dim_in,
self.kernel_size, self.input_padding)
+ conv2d_same(h_tm1, self.W_ho, (None, ) + self.dim_out,
self.transition_mat_size, self.hidden_padding)
+ c_t * self.W_co.dimshuffle('x', 0, 'x', 'x')
+ self.b_o.dimshuffle('x', 0, 'x', 'x'), "sigmoid")
h_t = output_gate * quick_activation(c_t, "tanh")
else:
#input_gate = h_t * W
input_gate = quick_activation(
conv2d_same(h_tm1, self.W_hi, (None, ) + self.dim_out, self.transition_mat_size, self.hidden_padding)
+ c_tm1 * self.W_ci.dimshuffle('x', 0, 'x', 'x')
+ self.b_i.dimshuffle('x', 0, 'x', 'x'), "sigmoid")
forget_gate = quick_activation(conv2d_same(h_tm1, self.W_hf, (None, ) + self.dim_out,
self.transition_mat_size, self.hidden_padding)
+ c_tm1 * self.W_cf.dimshuffle('x', 0, 'x', 'x')
+ self.b_f.dimshuffle('x', 0, 'x', 'x'), "sigmoid")
c_t = forget_gate * c_tm1 \
+ input_gate * quick_activation(conv2d_same(h_tm1, self.W_hc, (None, ) + self.dim_out,
self.transition_mat_size, self.hidden_padding)
+ self.b_c.dimshuffle('x', 0, 'x', 'x'), "tanh")
output_gate = quick_activation(conv2d_same(h_tm1, self.W_ho, (None, ) + self.dim_out,
self.transition_mat_size, self.hidden_padding)
+ c_t * self.W_co.dimshuffle('x', 0, 'x', 'x')
+ self.b_o.dimshuffle('x', 0, 'x', 'x'), "sigmoid")
h_t = output_gate * quick_activation(c_t, "tanh")
if mask_t is not None:
h_t = mask_t * h_t + (1 - mask_t) * h_tm1
c_t = mask_t * c_t + (1 - mask_t) * c_tm1
#print h_t.ndim, c_t.ndim
#h_t = quick_aggregate_pooling(h_t, "max", mask=None)
#c_t = quick_aggregate_pooling(c_t, "max", mask=None)
return h_t, c_t
def init_states(self):
return self.init_hidden_state, self.init_cell_state
def fprop(self):
# The dimension of self.mask is (Timestep, Minibatch).
# We need to pad it to (Timestep, Minibatch, FeatureDim, Row, Col)
# and keep the last three added dimensions broadcastable. TT.shape_padright
# function is thus a good choice
if self.mask is None:
if self.input is not None:
scan_input = [self.input]
scan_fn = lambda x_t, h_tm1, c_tm1: self.step_fprop(x_t, None, h_tm1, c_tm1)
else:
scan_input = None
scan_fn = lambda h_tm1, c_tm1: self.step_fprop(None, None, h_tm1, c_tm1)
else:
if self.input is not None:
scan_input = [self.input, TT.shape_padright(self.mask, 3)]
scan_fn = lambda x_t, mask_t, h_tm1, c_tm1: self.step_fprop(x_t, mask_t, h_tm1, c_tm1)
else:
scan_input = [TT.shape_padright(self.mask, 3)]
scan_fn = lambda mask_t, h_tm1, c_tm1: self.step_fprop(None, mask_t, h_tm1, c_tm1)
#print('conv lstm output:', scan_fn, self.init_cell_state, scan_input, self.n_steps)
[self.output, self.cell_output], self.output_update = quick_scan(fn=scan_fn,
outputs_info=[self.init_hidden_state,
self.init_cell_state],
sequences=scan_input,
name=self._s("lstm_output_func"),
n_steps=self.n_steps
)
| 59.494444 | 127 | 0.530488 | 10,500 | 0.980484 | 0 | 0 | 0 | 0 | 0 | 0 | 1,234 | 0.11523 |
3ebbdc540dc8fa6d2e3f28778c968adced8e307f | 779 | py | Python | build_script.py | lammda/mercari-solution | e6e216d33d19b62fdd4fb2a906bd904ede9c5aaa | [
"MIT"
]
| 249 | 2018-03-31T13:08:55.000Z | 2022-02-23T16:13:16.000Z | build_script.py | arita37/mercari-solution | 374301ad1c32cbc93dcc40313d5d7bb9c5503746 | [
"MIT"
]
| 1 | 2018-10-24T00:49:12.000Z | 2019-08-28T17:37:00.000Z | build_script.py | arita37/mercari-solution | 374301ad1c32cbc93dcc40313d5d7bb9c5503746 | [
"MIT"
]
| 84 | 2018-03-31T20:32:10.000Z | 2022-03-06T10:56:58.000Z | import base64
import glob
import gzip
def build_script(submission_name):
script_template = open('script_template.tmpl')
script = open('script/script_{name}.py'.format(name=submission_name), 'wt')
file_data = {}
for fn in glob.glob('mercari/*.py') + glob.glob('mercari/*.pyx'):
content = open(fn).read()
compressed = gzip.compress(content.encode('utf-8'), compresslevel=9)
encoded = base64.b64encode(compressed).decode('utf-8')
name = fn.split('/')[1]
file_data[name] = encoded
script.write(script_template.read().replace('{file_data}', str(file_data)).replace('{name}', submission_name))
script.close()
if __name__ == '__main__':
for submission_name in ['tf', 'mx']:
build_script(submission_name)
| 31.16 | 114 | 0.661104 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 136 | 0.174583 |
3ebc05f1d094795c30a0aca20105e5ff7a3813fa | 596 | py | Python | data_visualization_gui/src/interactive.py | bbueno5000/DataGUI | 940fcd0fb8dbde22350eacd538a8a1c244eb28ea | [
"MIT"
]
| null | null | null | data_visualization_gui/src/interactive.py | bbueno5000/DataGUI | 940fcd0fb8dbde22350eacd538a8a1c244eb28ea | [
"MIT"
]
| 2 | 2021-03-31T19:46:50.000Z | 2021-12-13T20:37:15.000Z | data_visualization_gui/src/interactive.py | bbueno5000/DataGUI | 940fcd0fb8dbde22350eacd538a8a1c244eb28ea | [
"MIT"
]
| null | null | null | """
DOCSTRING
"""
import dash
import dash.dependencies as dependencies
import dash_core_components.Graph as Graph
import dash_core_components.Input as Input
import dash_html_components.Div as Div
import dash_html_components.H1 as H1
app = dash.Dash()
app.layout = Div(children=[Input(id='input', value='blank', type='text'), Div(id='output')])
@app.callback(Output(component_id='output', component_property='children'),
[Input(component_id='input', component_property='value')])
def update_value(input_data):
return 'Input: "{}"'.format(input_data)
app.run_server(debug=True) | 35.058824 | 92 | 0.753356 | 0 | 0 | 0 | 0 | 224 | 0.375839 | 0 | 0 | 90 | 0.151007 |
3ebc6bb0c418253d021814396ba94a1161d06814 | 18,106 | py | Python | pidlearningscript.py | mtw30/ml_accumualtor_controller | d80d62ac66ccea9e6f089d9deebf796678fa818b | [
"Apache-2.0"
]
| null | null | null | pidlearningscript.py | mtw30/ml_accumualtor_controller | d80d62ac66ccea9e6f089d9deebf796678fa818b | [
"Apache-2.0"
]
| null | null | null | pidlearningscript.py | mtw30/ml_accumualtor_controller | d80d62ac66ccea9e6f089d9deebf796678fa818b | [
"Apache-2.0"
]
| null | null | null | # My script to process the generated data
# The temperature we want to aim for
aimTemperature = float(30 + 273)
# To halt the script
import sys
# Numpy matrices
import numpy as np
#Used to get the epoch time to calculate the time difference dt
import datetime
import time
#Regular expressions
import re
# Generate random numbers for the epsilon greedy
import random
# Math functions
import math
# Allows deep copies to be made
import copy
### variables
# Q = mcDeltaT for li-ion batteries
specHeatCap = 795.0 # Specific heat capacity (in seconds)
Tamb = float(25 + 273) # Ambient (initial) temperature (kelin)
battMass = 80.0 # Mass of the battery in kg
# Conversion factors
mphTomps = 0.44704
# Fan infomation
maxFanDraw = 36.0 # 36W, based on 2.8W power consumption and 12 fans on the TBRe car
fanVoltage = 12.0 # 12V DC
# Fan current is the power divided by the voltage
fanCurrent = maxFanDraw / fanVoltage
coolingFloor = 285 # Min temperature the fans can physically get the batteries, 12oC
# Battery infomation
currDraw = 240.0 # 240A, continous current draw of 30A with 8 cells in parallel
battCapacity = 18.7 # 180Ah total capcity of the battery, note unit of hours!
battVoltageNom = 388.0 # 388V nominal voltage
battResistance = 0.2304 # 0.2304ohm, 108 in series, 6 in parallel, 12.8E-3 per cell
regenEfficiency = 0.55 # 55% Efficiecny of the velocity converted to regen power, and this power used for recharging
maxAllowTemp = 307 # Kelvin, 35oC
minAllowTemp = 288 # Kevlin, 15oC
# GA variables
generationCount = 5
populationCount = 50
mutationRate = 0.01
# Some variables to do with the traniing of the controller
reqSigFig = 4 # Number of signiicant figures we need to variables to
maxkp = 2.0
maxki = 2.0
maxkd = 2.0
# Chromosomes length
chromKPlen = math.ceil(math.log(((maxkp - 0) * 10 ** reqSigFig), 2))
chromKIlen = math.ceil(math.log(((maxki - 0) * 10 ** reqSigFig), 2))
chromKDlen = math.ceil(math.log(((maxkd - 0) * 10 ** reqSigFig), 2))
# Generate a random binary string of input length
def generateBinaryString(chromosomeLength):
returnString = ''
for i in range(1, chromosomeLength):
if random.random() < 0.5:
returnString += '0'
else:
returnString += '1'
return returnString
# Decode chromosome
# Decodes the chromoesome string to the float digit
def decodeChromosome(chromosome, chromoesomeMaxVal):
decode = 0.0 + float(int(chromosome, 2)) * (float(chromoesomeMaxVal) - 0.0) / (2.0 ** len(chromosome) - 1)
return decode
#Calculated the time difference in milliseconds
#Regex on each filepath to get the time variables
#Create an object to get the epoch time
#Differene in epoch time is the dt (in seconds)
def calculateDt(prev, current):
#Calculate the epoch of the prev tick
#File last value is millisconds so convert to microseconds in datetime constructor
p = re.search(r'.+center_(\d+)_(\d+)_(\d+)_(\d+)_(\d+)_(\d+)_(\d+).jpg', prev)
prevTime = datetime.datetime(int(p.groups(1)[0]), int(p.groups(1)[1]), int(p.groups(1)[2]),
int(p.groups(1)[3]), int(p.groups(1)[4]), int(p.groups(1)[5]), (int(p.groups(1)[6]) * 1000))
prevEpoch = time.mktime(prevTime.timetuple())+(prevTime.microsecond/1000000.)
#Calculate the epoch of the current tick
#File last value is millisconds so convert to microseconds in datetime constructor
c = re.search(r'.+center_(\d+)_(\d+)_(\d+)_(\d+)_(\d+)_(\d+)_(\d+).jpg', current)
currTime = datetime.datetime(int(c.groups(1)[0]), int(c.groups(1)[1]), int(c.groups(1)[2]),
int(c.groups(1)[3]), int(c.groups(1)[4]), int(c.groups(1)[5]), (int(c.groups(1)[6]) * 1000))
currEpoch = time.mktime(currTime.timetuple())+(currTime.microsecond/1000000.)
dt = (currEpoch - prevEpoch)
if dt > 1:
if False:
print("Warning : dt over 1, so setting to 1, from pictures:")
print(prev)
print(current)
dt = 1
return dt
# Take an action to change the fan speed
# Fan speed can only be changed up to 20% per dt, as per the main script
def actionFanSpeed(actionIndex, dt, coolingThrottle):
fanSettings = (0.0, 0.2, 0.4, 0.6, 0.8, 1.0)
setThrottle = fanSettings[actionIndex]
if setThrottle == coolingThrottle:
#Dont need to calculate anything
return setThrottle
elif setThrottle > coolingThrottle:
#Need to calculate an increase
#Increase is not able to be more than 10% per 0.2 seconds
#Caulculate the maximum increase for the dt
#Get the current x value (time)
t = coolingThrottle * 2.0
#Get the highest speed possible with the dt
x = t + dt
maxThrottle = x / 2.0
#If the attempted fan speed to set is more than that maximum allowable for the dt
#Just set it to the maximum allowable
newThrottle = maxThrottle if (maxThrottle < setThrottle) else setThrottle
else:
#Need to calculate a decrease
#Not able to decrease more than 10% every 1/3 seconds
t = coolingThrottle * 2.0
x = t - dt
minThrottle = x / 2.0
newThrottle = minThrottle if (minThrottle > setThrottle) else setThrottle
return newThrottle
#Calculate the cooling which occurs, depending on the vehicle speed
#In m/s, and the accumulator
#Uses fluid dynamics of dry air, with flow across a tube bank
def calculateCooling(coolingThrottle, dt):
#Make sure the cooling throttle is between 0 and 1
coolingThrottle = 1 if (coolingThrottle > 1) else coolingThrottle
coolingThrottle = 0 if (coolingThrottle < 0) else coolingThrottle
#Work out the air speed, max 10m/s
coolAirSpeed = float(coolingThrottle) * 4.0
#Caulcate Vmax, the max velocity of the air through the staggered tube bank arrangement
St = 25.0 * (10.0 ** -3.0)
D = 18.65 * (10.0 ** -3.0)
Vmax = (St * coolAirSpeed) / (St - D)
#Properties of dry air
density = 1.177
dynamVis = 1.846 * (10.0 ** -5.0)
criticalDimension = 0.01865
#Calculate value of Re, pre computed values for desnity, cell size and dynamic viscosity
#dt cancells out, but in the equations for clairty
Re = (density * criticalDimension) / (dynamVis) * Vmax
#Calculate the prandtl number, which is based on the Tfilm temperature
#Tfilm is the average of the Tamb and the heat of the object
Pr = 0.706
Prs = 0.708
#Calculate the nusselt number, using the Re and the prandtl number
#St and Sl are the dimensions of the staggered battery arangement
St = 24.0 * (10.0 ** -3)
Sl = 22.0 * (10.0 ** -3)
Nu = (0.35 * ((St / Sl) ** (0.2)) * (Re ** 0.6) * (Pr ** 0.36) * ((Pr / Prs) ** 0.25))
#Calculate the value of h,
h = ((2.624 * (10.0 ** -2.0) * Nu) / 0.01865)
#Calculate the heat loss Q
Q = h * 0.0044 * (maxAllowTemp - Tamb)
#6 sub packs, 108 in series and 6 in parallel 636 total. However, with the depth the air cooling tends towards
# to decrease, so only have the 6 sub packs with the 6 in the string being cooled in the model
cellCount = 6.0 * 6.0
#Calculate the cooling value over the cells, but multiplied by dt, and the number of sub packs
coolingValue = Q * dt * cellCount
return coolingValue
# Calcualte the drain on the batteriries
# Drain from running the fan
# Drain is very large approximation with a linear drain on the batteries!!
def calculateBatteryDrain(thisBattCapacity, coolingThrottle, drivingPower, dt):
#Use the fan throttle to scale the instanteous current draw of the fans
cellCurrentDraw = fanCurrent * coolingThrottle
#Current is the flow per second, so also need to scale by dt
cellCurrentDraw *= dt
# Add the current that is drawn by the motor, by dividing the driving power by the nominal battery voltage
# This power is already instantaneous in dt
cellCurrentDraw += drivingPower / battVoltageNom
if False:
print("Instantaneous current " + str(cellCurrentDraw) + "A")
print("dt : " + str(dt) + "s")
#No power is consumed if the cellCurrentDraw is 0
if cellCurrentDraw == 0:
return thisBattCapacity
#Remove this consumed power from the battery capacity
#Work out how many seconds are left when this draw happens
timeLeftHours = thisBattCapacity / cellCurrentDraw
timeLeftSeconds = timeLeftHours * 3600.0
#We are working in time units of dt, we are drawing for dt seconds
timeLeftSeconds -= dt
#Work in reverse to get the capacity after drawing the power
timeLeftHours = timeLeftSeconds / 3600.0
thisBattCapacity = timeLeftHours * cellCurrentDraw
return thisBattCapacity
class pidcontroller:
'This is a pid controller '
def __init__(self, kp, ki, kd):
# Temperature setpoint for the contoller
self.aimTemperature = 273.0 + 30
# Gains built from the ML model
self.kp = kp
self.ki = ki
self.kd = kd
print("Gains loaded for the PID controller:- kp : " + str(self.kp)
+ ", ki : " + str(self.ki) + ", kd : " + str(self.kd))
# Values to normalise the nominal controller value between
self.contLow = -5.0
self.contHig = 5.0
# Initial state of the intergrator
self.uiPrev = 1.0
# Previous error value
self.ePrev = 1.0
# Take an action to change the fan speed
# Fan speed can only be changed up to 20% per dt, as per the main script
def __actionFanSpeed(self, setThrottle, dt, coolingThrottle):
if setThrottle == coolingThrottle:
#Dont need to calculate anything
return setThrottle
elif setThrottle > coolingThrottle:
#Need to calculate an increase
#Increase is not able to be more than 10% per 0.2 seconds
#Caulculate the maximum increase for the dt
#Get the current x value (time)
t = coolingThrottle * 2.0
#Get the highest speed possible with the dt
x = t + dt
maxThrottle = x / 2.0
#If the attempted fan speed to set is more than that maximum allowable for the dt
#Just set it to the maximum allowable
newThrottle = maxThrottle if (maxThrottle < setThrottle) else setThrottle
else:
#Need to calculate a decrease
#Not able to decrease more than 10% every 1/3 seconds
t = coolingThrottle * 2.0
x = t - dt
minThrottle = x / 2.0
newThrottle = minThrottle if (minThrottle > setThrottle) else setThrottle
return newThrottle
#THis is the same function stucture that every controller requires
#Implemented differently by every controller
#Returns a new fan value
def runController(self, dt, fanSpeed, temperature):
# Implement PID
# Error values are swapped as we want the controller on when the temperature is higher
e = temperature - self.aimTemperature
print('-----------------------')
print(temperature)
print(e)
ui = self.uiPrev + (1/self.ki) * dt * e
ud = (1/self.kd) + (e - self.ePrev) / dt
# Save the previous values
self.uiPrev = ui
self.ePrev = e
# Generate the control effort
u = self.kp * e + ud
print(u)
un = 2 * (u - self.contLow) / (self.contHig - self.contLow) - 1
throttleValue = un if un >= 0 else 0
print(throttleValue)
return throttleValue
class geneticLearner:
'An individual in the society'
def __init__(self, chromKP, chromKI, chromKD, initialTemp):
self.chromKP = chromKP
self.chromKI = chromKI
self.chromKD = chromKD
self.temperature = copy.deepcopy(initialTemp)
KP = decodeChromosome(chromKP, maxkp)
KI = decodeChromosome(chromKI, maxki)
KD = decodeChromosome(chromKD, maxkd)
self.controller = pidcontroller(KP, KI, KD)
# Setup some values such as the fan speed
self.fanspeed = 0.0
# Set to true of the temperature every goes out of bounds
self.failStatus = False
# Just need to track the charge just to display it on a chart
self.thisBattCap = copy.deepcopy(battCapacity)
# Finally, reset the fitness value
self.fitness = 0.0
self.fitnessBounds = 1.0 #+- 1 Kelvin
self.beginTracking = False # Begins false as we start far away from the temperature
# Runs the genetic controller, just the normal kind of control things taking place
# Keep track of fitness though
def runController(self, dt, generatedHeat):
newThrottle = self.controller.runController(dt, self.fanspeed, self.temperature)
#This is the number of watts of heat taken away per dt from the airflow
coolingPower = calculateCooling(coolingThrottle, dt)
#The instantaneous power generated in the cells is the driving power minues the cooling power
instantaneousPower = abs(generatedHeat) - coolingPower
#Temperature cannot go lower than coolingFloor
instantaneousPower = 0 if (temp < coolingFloor and instantaneousPower < 0) else instantaneousPower
#Using q=m*c*Delta
dTemp = float(instantaneousPower) / (float(battMass) * float(specHeatCap) * dt)
# Change the current temperature by the temperature change calculated
self.temperature += dTemp
self.thisBattCapacity = calculateBatteryDrain(dt, newThrottle, 0.0, self.thisBattCapacity)
if self.temp < minAllowTemp or temp > maxAllowTemp:
print("Failure, battery temperature at " + str(temp - 273))
self.fitness = 0.0
self.failStatus = True
else:
# Carry on looping though all the data
if self.beginTracking:
if (self.temperature <= self.aimTemperature + self.fitnessBounds and
self.temperature >= self.aimTemperature - self.fitnessBounds):
print("Hello")
#Process the input file to work out the power at each point
#Print it to a file
def processFile(filePath):
#open this new file and get all the lines
with open(filePath) as f:
processLine = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
processLine = [x.strip() for x in processLine]
# Bin off the first line as it just contains all the titles
processLine.pop(0)
# Set up learning variables
epochs = generationCount # Run the learn 1000 times per simulation
print(datetime.datetime.now().strftime("%a, %d %B %Y %I:%M:%S"))
# Initialise the generation
generationGroup = []
for count in range(populationCount):
chromKP = generateBinaryString(chromKPlen)
chromKI = generateBinaryString(chromKPlen)
chromKD = generateBinaryString(chromKPlen)
cont = geneticLearner(chromKP, chromKI, chromKD, Tamb)
generationGroup.append(cont)
for i in range(epochs):
# Set up the training run
readLines = copy.deepcopy(processLine)
# First thing to do is initialise the state
# Keep the state as dynamic arrays so can be popped and appended
# Trim the lines that were sent to the state creation
battTemp = copy.deepcopy(Tamb)
battCharge = 100.0
fanSpeed = 0.0
isRunning = True
thisBattCapacity = copy.deepcopy(battCapacity)
lineCounter = 0
prevLine = readLines.pop(0).split(',')
while isRunning:
# Run the simulation
currLine = readLines.pop(0).split(',')
# Work out the dt
dt = calculateDt(prevLine[0], currLine[0])
if len(readLines) > 1:
prevLine = currLine
else:
isRunning = False
# Every 10 % of the way print the current time, and the percentage
if ((i + 1) % (epochs / 10.0)) == 0:
print("---------------------------------------------")
print(str(((i + 1) / epochs) * 100) + "% completed...")
print(datetime.datetime.now().strftime("%a, %d %B %Y %I:%M:%S"))
# Print some things at the end of each game to see how close we are to targets :)
print("---------------------------------------------")
print("Completed game " + str(i + 1) + "/" + str(epochs))
#print("End temperature : " + str(battTemp))
#batteryPercentage = (thisBattCapacity / battCapacity) * 100.0
##Get this as a string with two decimal places (cut, not rounded)
#wholePercentage = str(batteryPercentage).split('.')[0]
#decimPercentage = str(batteryPercentage).split('.')[1]
#batteryRemaining = str(wholePercentage + "." + decimPercentage[0:2])
#print("End capacity : " + str(batteryRemaining))
# Simulation finished, print model to JSON file
print("---------------------------------------------")
print("Model saved to disk...")
# File with the list of files to process
masterFile = "/Users/Matt/google_drive/documents/uni/year_3/EE30147_40148_GDBP_MEng/individual/scripts/traindatatoprocess"
#Open the list of files to go through,
try:
with open(masterFile) as f:
processFilePaths = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
processFilePaths = [x.strip() for x in processFilePaths]
except IOError:
print("Error, unable to find list file : " + filePath)
#Remove first item from processFilePaths as this is just the file header
processFilePaths.pop(0)
#For every required file
for row in processFilePaths:
#Try to process this file
try:
print("Processing file : " + row)
processFile(row)
except IOError:
print("Error, unable to find list file : " + row)
| 37.486542 | 122 | 0.643378 | 5,426 | 0.29968 | 0 | 0 | 0 | 0 | 0 | 0 | 8,099 | 0.44731 |
3ebd20504757b6e90b9dac2cead03c7e3e9835fc | 2,188 | py | Python | graphjson.py | suprfanz/flask-fb-neo4j-alchemy | 8ee5692bdbddc94342b38144d299e9d1a1b0b68d | [
"MIT"
]
| 2 | 2018-03-09T03:10:49.000Z | 2020-10-22T10:28:03.000Z | graphjson.py | suprfanz/flask-fb-neo4j-alchemy | 8ee5692bdbddc94342b38144d299e9d1a1b0b68d | [
"MIT"
]
| null | null | null | graphjson.py | suprfanz/flask-fb-neo4j-alchemy | 8ee5692bdbddc94342b38144d299e9d1a1b0b68d | [
"MIT"
]
| null | null | null | """
graphjson module pull an event from neo4j and creates
graphjson formated file to be used with AlchemyJS
Written by Ray Bernard [email protected]
"""
import json
from neo4j.v1 import GraphDatabase, basic_auth
from config import neo4j_dbip, neo4j_admin, neo4j_password
session = GraphDatabase.driver("bolt://{}:7687".format(neo4j_dbip),
auth=basic_auth("{}".format(neo4j_admin), "{}".format(neo4j_password))).session()
def create_guest_node():
# fetches the guest nodes from neo4j
insert_query_guest = '''
MATCH (a:fb_guest)
WITH collect({name: a.fb_guest_name, nodeType:'guest', id:a.fb_usr_id}) AS nodes RETURN nodes
'''
result = session.run(insert_query_guest)
for record in result:
guest_node = json.dumps(dict(record))
return guest_node
def create_guest_edge():
# fetches the guest-event edges from neo4j
insert_query_guest = '''
MATCH (a:fb_guest)-[r:RSVP]->(b:fb_event)
WITH collect({source: a.fb_usr_id,target: b.fb_event_id, rsvp:r.rsvp_status}) AS edges RETURN edges
'''
result = session.run(insert_query_guest)
for record in result:
return json.dumps(dict(record))
def create_event_node():
# fetches the event nodes from neo4j
insert_query_guest = '''
MATCH (b:fb_event)
WITH collect ({name: b.event_name, nodeType:'event', id:b.fb_event_id}) AS nodes RETURN nodes
'''
result = session.run(insert_query_guest)
for record in result:
return json.dumps(record['nodes'])
def main():
# puts the data together in graphjson format
comment = '{"comment":" This is a test",'
guest_nodes = str(create_guest_node())[1:][:-2]
guest_edges = str(create_guest_edge())[1:]
event_node = str((create_event_node())) + ']'
graphjson = str(comment) + str(guest_nodes) + ', ' + str(event_node) + ',' + str(guest_edges)
print(graphjson)
# put your file path to json data here
with open(
"C:\\Users\\yourname\\Documents\\path\\to\\alchemy\\app\\static\\data\\fb_events.json",
"w") as f:
f.write(graphjson)
return graphjson
if __name__ == '__main__':
main()
| 29.173333 | 112 | 0.664534 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 944 | 0.431444 |
3ebd492c672da94f9dbeb381a25939527becda92 | 2,507 | py | Python | dataset.py | kisom/aipnd-classifier | a361fc5f25402bbdfb23ddc08ad1b071fff50210 | [
"MIT"
]
| null | null | null | dataset.py | kisom/aipnd-classifier | a361fc5f25402bbdfb23ddc08ad1b071fff50210 | [
"MIT"
]
| null | null | null | dataset.py | kisom/aipnd-classifier | a361fc5f25402bbdfb23ddc08ad1b071fff50210 | [
"MIT"
]
| null | null | null | """
dataset.py defines a container for a training dataset.
"""
import os
import torch
from torchvision import datasets, transforms
class Dataset:
"""
Dataset encapsulations training, validation, and testing datasets
from a single top-level directory.
"""
def __init__(self, data_dir, batchsize):
test_transforms = [
transforms.Resize(255),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]
train_transforms = [
transforms.RandomRotation(45),
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]
validate_transforms = [
transforms.Resize(255),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]
self.batchsize = batchsize
self.datadir = data_dir
train_dir = os.path.join(data_dir, "train")
valid_dir = os.path.join(data_dir, "valid")
test_dir = os.path.join(data_dir, "test")
dataset_training = datasets.ImageFolder(
train_dir, transforms.Compose(train_transforms)
)
dataset_validation = datasets.ImageFolder(
valid_dir, transforms.Compose(validate_transforms)
)
dataset_testing = datasets.ImageFolder(
test_dir, transforms.Compose(test_transforms)
)
self.class_to_idx = dataset_training.class_to_idx
self.training = torch.utils.data.DataLoader(
dataset_training, batchsize * 2, shuffle=True
)
self.validation = torch.utils.data.DataLoader(
dataset_validation, batchsize, shuffle=True
)
self.testing = torch.utils.data.DataLoader(
dataset_testing, batchsize, shuffle=True
)
def __repr__(self):
return "dataset(data_dir={}, batchsize={})".format(self.datadir, self.batchsize)
def training_set(self):
"Returns the training dataset."
return self.training
def validation_set(self):
"Returns the validation dataset."
return self.validation
def testing_set(self):
"Returns the testing dataset."
return self.testing
| 32.986842 | 88 | 0.618668 | 2,373 | 0.94655 | 0 | 0 | 0 | 0 | 0 | 0 | 332 | 0.132429 |
3ebef9e4fbaf39a788a4ad55fc4f3d9f0f5242a4 | 3,659 | py | Python | site-packages/cinderclient/tests/unit/v2/test_cgsnapshots.py | hariza17/freezer_libraries | e0bd890eba5e7438976fb3b4d66c41c128bab790 | [
"PSF-2.0"
]
| null | null | null | site-packages/cinderclient/tests/unit/v2/test_cgsnapshots.py | hariza17/freezer_libraries | e0bd890eba5e7438976fb3b4d66c41c128bab790 | [
"PSF-2.0"
]
| 1 | 2018-09-10T23:44:02.000Z | 2018-09-12T16:28:07.000Z | site-packages/cinderclient/tests/unit/v2/test_cgsnapshots.py | hariza17/freezer_libraries | e0bd890eba5e7438976fb3b4d66c41c128bab790 | [
"PSF-2.0"
]
| 2 | 2018-09-07T23:17:23.000Z | 2019-01-11T16:10:08.000Z | # Copyright (C) 2012 - 2014 EMC Corporation.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required 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 language governing permissions and limitations
# under the License.
from cinderclient.tests.unit import utils
from cinderclient.tests.unit.v2 import fakes
cs = fakes.FakeClient()
class cgsnapshotsTest(utils.TestCase):
def test_delete_cgsnapshot(self):
v = cs.cgsnapshots.list()[0]
vol = v.delete()
self._assert_request_id(vol)
cs.assert_called('DELETE', '/cgsnapshots/1234')
vol = cs.cgsnapshots.delete('1234')
cs.assert_called('DELETE', '/cgsnapshots/1234')
self._assert_request_id(vol)
vol = cs.cgsnapshots.delete(v)
cs.assert_called('DELETE', '/cgsnapshots/1234')
self._assert_request_id(vol)
def test_create_cgsnapshot(self):
vol = cs.cgsnapshots.create('cgsnap')
cs.assert_called('POST', '/cgsnapshots')
self._assert_request_id(vol)
def test_create_cgsnapshot_with_cg_id(self):
vol = cs.cgsnapshots.create('1234')
expected = {'cgsnapshot': {'status': 'creating',
'description': None,
'user_id': None,
'name': None,
'consistencygroup_id': '1234',
'project_id': None}}
cs.assert_called('POST', '/cgsnapshots', body=expected)
self._assert_request_id(vol)
def test_update_cgsnapshot(self):
v = cs.cgsnapshots.list()[0]
expected = {'cgsnapshot': {'name': 'cgs2'}}
vol = v.update(name='cgs2')
cs.assert_called('PUT', '/cgsnapshots/1234', body=expected)
self._assert_request_id(vol)
vol = cs.cgsnapshots.update('1234', name='cgs2')
cs.assert_called('PUT', '/cgsnapshots/1234', body=expected)
self._assert_request_id(vol)
vol = cs.cgsnapshots.update(v, name='cgs2')
cs.assert_called('PUT', '/cgsnapshots/1234', body=expected)
self._assert_request_id(vol)
def test_update_cgsnapshot_no_props(self):
cs.cgsnapshots.update('1234')
def test_list_cgsnapshot(self):
lst = cs.cgsnapshots.list()
cs.assert_called('GET', '/cgsnapshots/detail')
self._assert_request_id(lst)
def test_list_cgsnapshot_detailed_false(self):
lst = cs.cgsnapshots.list(detailed=False)
cs.assert_called('GET', '/cgsnapshots')
self._assert_request_id(lst)
def test_list_cgsnapshot_with_search_opts(self):
lst = cs.cgsnapshots.list(search_opts={'foo': 'bar'})
cs.assert_called('GET', '/cgsnapshots/detail?foo=bar')
self._assert_request_id(lst)
def test_list_cgsnapshot_with_empty_search_opt(self):
lst = cs.cgsnapshots.list(search_opts={'foo': 'bar', '123': None})
cs.assert_called('GET', '/cgsnapshots/detail?foo=bar')
self._assert_request_id(lst)
def test_get_cgsnapshot(self):
cgsnapshot_id = '1234'
vol = cs.cgsnapshots.get(cgsnapshot_id)
cs.assert_called('GET', '/cgsnapshots/%s' % cgsnapshot_id)
self._assert_request_id(vol)
| 38.515789 | 78 | 0.639519 | 2,898 | 0.79202 | 0 | 0 | 0 | 0 | 0 | 0 | 1,159 | 0.316753 |
3ebf6af93d750f46cb0ac8a35e125abd85daa7b2 | 710 | py | Python | mlps/core/data/cnvrtr/functions/IPTransferDivide.py | seculayer/automl-mlps | 80569909ec1c25db1ceafbb85b27d069d1a66aa3 | [
"Apache-2.0"
]
| null | null | null | mlps/core/data/cnvrtr/functions/IPTransferDivide.py | seculayer/automl-mlps | 80569909ec1c25db1ceafbb85b27d069d1a66aa3 | [
"Apache-2.0"
]
| 2 | 2022-03-31T07:39:59.000Z | 2022-03-31T07:40:18.000Z | mlps/core/data/cnvrtr/functions/IPTransferDivide.py | seculayer/AutoAPE-mlps | 80569909ec1c25db1ceafbb85b27d069d1a66aa3 | [
"Apache-2.0"
]
| 1 | 2021-11-03T09:09:07.000Z | 2021-11-03T09:09:07.000Z | # -*- coding: utf-8 -*-
# Author : Manki Baek
# e-mail : [email protected]
# Powered by Seculayer ยฉ 2021 Service Model Team
from mlps.core.data.cnvrtr.ConvertAbstract import ConvertAbstract
class IPTransferDivide(ConvertAbstract):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.num_feat = 4
# ํ ํฌ๋์ด์ง ํ๋๊ณณ
def apply(self, data):
try:
row = data.split(".")
except Exception as e:
# self.LOGGER.error(e)
row = ["0", "0", "0", "0"]
return row
if __name__ == "__main__":
payload = "192.168.1.110"
tokenizer = IPTransferDivide(stat_dict=None, arg_list=None)
print(tokenizer.apply(payload))
| 24.482759 | 65 | 0.612676 | 367 | 0.504814 | 0 | 0 | 0 | 0 | 0 | 0 | 216 | 0.297111 |
3ec23576c70ac623990dae2bb8e27678909b68f6 | 2,327 | py | Python | dataAnalytics/roomAnalytics.py | PeterJWei/EnergyFootprinting | 0396efba7d4e6863452e322f9f7561c6cd756478 | [
"MIT"
]
| null | null | null | dataAnalytics/roomAnalytics.py | PeterJWei/EnergyFootprinting | 0396efba7d4e6863452e322f9f7561c6cd756478 | [
"MIT"
]
| null | null | null | dataAnalytics/roomAnalytics.py | PeterJWei/EnergyFootprinting | 0396efba7d4e6863452e322f9f7561c6cd756478 | [
"MIT"
]
| null | null | null | import DBScrape
import calendar
import datetime
import time
import csv
import sys
import os
days = 30
class roomAnalytics:
energyDictionary = {}
energyCounts = {}
def backspace(self):
print '\r',
def roomData(self):
databaseScrape = DBScrape.DBScrape()
t = (2017, 5, 1, 0, 0, 0, 0, 0, 0)
beginTime = calendar.timegm(datetime.datetime.utcfromtimestamp(time.mktime(t)).utctimetuple())
for i in range(0, days):
s = str(round(float(i)/days*100.0)) + '%'
print s,
sys.stdout.flush()
self.backspace()
start = beginTime + i*24*60*60
end = beginTime + (i+1)*24*60*60
shots = databaseScrape.snapshots_col_appliances(start, end)
for snapshot in shots:
timestamp = snapshot["timestamp"]
timestamp = calendar.timegm(timestamp.utctimetuple())
b = int(timestamp-beginTime)/900
day = b/96
binNumber = b%96
data = snapshot["data"]
for appliance in data:
params = data[appliance]
if (type(params) == type(150)):
continue
energy = params["value"]
rooms = params["rooms"]
l = len(rooms)
for room in rooms:
if room not in self.energyDictionary:
self.energyDictionary[room] = [[0]*96 for index in range(days)]
self.energyCounts[room] = [[0]*96 for index in range(days)]
if (day >= days or binNumber >= 96):
print((binNumber, day))
continue
self.energyDictionary[room][day][binNumber] += energy
for room in self.energyDictionary:
self.energyCounts[room][day][binNumber] += 1
def saveData(self):
try:
os.remove('savedData.csv')
except OSError:
pass
with open('savedData.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for room in self.energyDictionary:
# if (room != "nwc1003b_a"):
# continue
# print("Found Room")
arr = self.energyDictionary[room]
arrCount = self.energyCounts[room]
savedArray = [0]*96
for i in range(96):
for j in range(days):
if (arrCount[j][i] > 1):
savedArray[i] += arr[j][i]/arrCount[j][i]
else:
savedArray[i] += arr[j][i]
for k in range(96):
savedArray[k] = savedArray[k]/days
spamwriter.writerow(room)
spamwriter.writerow(savedArray)
R = roomAnalytics()
R.roomData()
R.saveData() | 25.021505 | 96 | 0.638161 | 2,169 | 0.932101 | 0 | 0 | 0 | 0 | 0 | 0 | 147 | 0.063171 |
3ec715aa850089a5f7b7b582922c73d2960606c8 | 778 | py | Python | tests/test_kubernetes_master.py | damoxc/charm-kubernetes-master | 624095b278e9f235a03d061132e9fdf029d45b71 | [
"Apache-2.0"
]
| null | null | null | tests/test_kubernetes_master.py | damoxc/charm-kubernetes-master | 624095b278e9f235a03d061132e9fdf029d45b71 | [
"Apache-2.0"
]
| null | null | null | tests/test_kubernetes_master.py | damoxc/charm-kubernetes-master | 624095b278e9f235a03d061132e9fdf029d45b71 | [
"Apache-2.0"
]
| null | null | null | import pytest
from unittest import mock
from reactive import kubernetes_master
from charms.reactive import endpoint_from_flag, remove_state
from charmhelpers.core import hookenv
def patch_fixture(patch_target):
@pytest.fixture()
def _fixture():
with mock.patch(patch_target) as m:
yield m
return _fixture
def test_send_default_cni():
hookenv.config.return_value = 'test-default-cni'
kubernetes_master.send_default_cni()
kube_control = endpoint_from_flag('kube-control.connected')
kube_control.set_default_cni.assert_called_once_with('test-default-cni')
def test_default_cni_changed():
kubernetes_master.default_cni_changed()
remove_state.assert_called_once_with(
'kubernetes-master.components.started'
)
| 27.785714 | 76 | 0.767352 | 0 | 0 | 158 | 0.203085 | 101 | 0.12982 | 0 | 0 | 98 | 0.125964 |
3ec94f77c122b98fdf7c96a211b8a9024dac0bae | 57,058 | py | Python | pysnmp-with-texts/HH3C-DOT3-EFM-EPON-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
]
| 8 | 2019-05-09T17:04:00.000Z | 2021-06-09T06:50:51.000Z | pysnmp-with-texts/HH3C-DOT3-EFM-EPON-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
]
| 4 | 2019-05-31T16:42:59.000Z | 2020-01-31T21:57:17.000Z | pysnmp-with-texts/HH3C-DOT3-EFM-EPON-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
]
| 10 | 2019-04-30T05:51:36.000Z | 2022-02-16T03:33:41.000Z | #
# PySNMP MIB module HH3C-DOT3-EFM-EPON-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-DOT3-EFM-EPON-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:26:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint")
hh3cEpon, = mibBuilder.importSymbols("HH3C-OID-MIB", "hh3cEpon")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup")
Unsigned32, ObjectIdentity, IpAddress, TimeTicks, Integer32, mib_2, Gauge32, iso, Counter64, Counter32, ModuleIdentity, NotificationType, MibIdentifier, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "ObjectIdentity", "IpAddress", "TimeTicks", "Integer32", "mib-2", "Gauge32", "iso", "Counter64", "Counter32", "ModuleIdentity", "NotificationType", "MibIdentifier", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
TextualConvention, MacAddress, DisplayString, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "MacAddress", "DisplayString", "TruthValue")
hh3cDot3EfmeponMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2))
hh3cDot3EfmeponMIB.setRevisions(('2004-09-21 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: hh3cDot3EfmeponMIB.setRevisionsDescriptions(('Initial version, published as RFC XXXX.',))
if mibBuilder.loadTexts: hh3cDot3EfmeponMIB.setLastUpdated('200409210000Z')
if mibBuilder.loadTexts: hh3cDot3EfmeponMIB.setOrganization('Hangzhou H3C Tech. Co., Ltd.')
if mibBuilder.loadTexts: hh3cDot3EfmeponMIB.setContactInfo('Platform Team Hangzhou H3C Tech. Co., Ltd. Hai-Dian District Beijing P.R. China http://www.h3c.com Zip:100085 ')
if mibBuilder.loadTexts: hh3cDot3EfmeponMIB.setDescription("The objects in this MIB module are used to manage the Ethernet in the First Mile (EFM) Multi Point Control Protocol (MPCP) Interfaces as defined in IEEE Draft P802.3ah/D3.0 clause 64,65. The following reference is used throughout this MIB module: [802.3ah] refers to: IEEE Draft P802.3ah/D3.3: 'Draft amendment to - Information technology - Telecommunications and information exchange between systems - Local and metropolitan area networks - Specific requirements - Part 3: Carrier sense multiple access with collision detection (CSMA/CD) access method and physical layer specifications - Media Access Control Parameters, Physical Layers and Management Parameters for subscriber access networks', 22 April 2004. Of particular interest are Clause 64(MPCP) 65(P2MP RS) and 60 (PON PMDs). Clause 30, 'Management', and Clause 45, 'Management Data Input/Output (MDIO) Interface'. Copyright (C) The Internet Society (2004). This version of this MIB module is part of XXXX see the RFC itself for full legal notices.")
hh3cDot3MpcpMIB = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1))
hh3cDot3MpcpObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1))
hh3cDot3MpcpConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 2))
hh3cDot3MpcpTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 1), )
if mibBuilder.loadTexts: hh3cDot3MpcpTable.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpTable.setDescription('Table for dot3 Multi-Point Control Protocol (MPCP) MIB modules.')
hh3cDot3MpcpEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: hh3cDot3MpcpEntry.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpEntry.setDescription('An entry in the dot3 MPCP MIB modules table.')
hh3cDot3MpcpID = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpID.setReference('[802.3ah], 30.3.5.1.1.')
if mibBuilder.loadTexts: hh3cDot3MpcpID.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpID.setDescription('This variable is assigned so as to uniquely identify the Multi-Point MAC Control (MPCP) entity, as defined in [802.3ah] clause 64, among the subordinate managed objects of the containing object. This attribute is relevant for an OLT and an ONU.')
hh3cDot3MpcpOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 1, 1, 2), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpOperStatus.setReference('[802.3ah], 30.3.5.1.2.')
if mibBuilder.loadTexts: hh3cDot3MpcpOperStatus.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpOperStatus.setDescription('This variable can be used to define the operational state of the Multi-Point MAC Control sublayer as defined in [802.3ah] clause 64. Selecting admin for an interface with Multi-Point MAC Control sublayer. When the attribute is True the the interface will act as if Multi-point control protocol is enabled. When the attribute is False the interface will act as if it does not have the Multi-point control protocol. The operational state can be changed using the hh3cDot3MpcpAdminState attribute. This attribute is relevant for an OLT and an ONU.')
hh3cDot3MpcpMode = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("olt", 1), ("onu", 2))).clone(1)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hh3cDot3MpcpMode.setReference('[802.3ah], 30.3.5.1.3.')
if mibBuilder.loadTexts: hh3cDot3MpcpMode.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpMode.setDescription('This variable can be used to identify the operational state of the Multi-Point MAC Control sublayer as defined in [802.3ah] clause 64. Selecting olt(1) for an OLT (server) mode and onu(2) for an ONU (client) mode. Writing can be done during only during initialization, when hh3cDot3MpcpOperStatus indicates Flase. This attribute is relevant for an OLT and an ONU.')
hh3cDot3MpcpLinkID = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 1, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpLinkID.setReference('[802.3ah], 30.3.5.1.4.')
if mibBuilder.loadTexts: hh3cDot3MpcpLinkID.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpLinkID.setDescription('A read-only value that identifies the Logical Link identity (LLID) associated with the MAC port as specified in [802.3ah] clause 65.1.3.2.2. This attribute is relevant for an OLT and an ONU.')
hh3cDot3MpcpRemoteMACAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 1, 1, 5), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpRemoteMACAddress.setReference('[802.3ah], 30.3.5.1.5.')
if mibBuilder.loadTexts: hh3cDot3MpcpRemoteMACAddress.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpRemoteMACAddress.setDescription('A read-only value that identifies the source_address parameter of the last MPCPDUs passed to the MAC Control. This value is updated on reception of a valid frame with (1) a destination Field equal to the reserved multicast address for MAC Control specified in [802.3ah] Annex 31A, (2) lengthOrType field value equal to the reserved Type for MAC Control as specified in [802.3ah] Annex 31A. (3) an MPCP subtype value equal to the subtype reserved for MPCP as specified in [802.3ah] Annex 31A. This attribute is relevant for an OLT and an ONU.')
hh3cDot3MpcpRegistrationState = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("unregistered", 1), ("registering", 2), ("registered", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpRegistrationState.setReference('[802.3ah], 30.3.5.1.6.')
if mibBuilder.loadTexts: hh3cDot3MpcpRegistrationState.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpRegistrationState.setDescription('A read-only value that identifies the operational state of the Multi-Point MAC Control sublayer as defined in [802.3ah] clause 64. When this attribute has the enumeration unregistered(1) the interface may be used for registering a link partner. When this attribute has the enumeration registering(2) the interface is in the process of registering a link-partner. When this attribute has the enumeration registered(3) the interface has an established link-partner. This attribute is relevant for an OLT and an ONU. For the OLT it provides an indication per LLID.')
hh3cDot3MpcpTransmitElapsed = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 1, 1, 7), Integer32()).setUnits('TQ (16nsec)').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpTransmitElapsed.setReference('[802.3ah], 30.3.5.1.19.')
if mibBuilder.loadTexts: hh3cDot3MpcpTransmitElapsed.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpTransmitElapsed.setDescription('A read-only value that reports the interval from last MPCP frame transmission in increments of Time Quanta (TQ) 16ns. The value returned shall be (interval from last MPCP frame transmission in ns)/16. If this value exceeds (2^32-1) the value (2^32-1) shall be returned. This attribute is relevant for an OLT and an ONU.')
hh3cDot3MpcpReceiveElapsed = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 1, 1, 8), Integer32()).setUnits('TQ (16nsec)').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpReceiveElapsed.setReference('[802.3ah], 30.3.5.1.20.')
if mibBuilder.loadTexts: hh3cDot3MpcpReceiveElapsed.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpReceiveElapsed.setDescription('A read-only value that reports the interval from last MPCP frame reception in increments of Time Quanta (TQ) 16ns. The value returned shall be (interval from last MPCP last MPCP frame reception in ns)/16. If this value exceeds (2^32-1) the value (2^32-1) shall be returned. This attribute is relevant for an OLT and an ONU.')
hh3cDot3MpcpRoundTripTime = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 1, 1, 9), Integer32()).setUnits('TQ (16nsec)').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpRoundTripTime.setReference('[802.3ah], 30.3.5.1.21.')
if mibBuilder.loadTexts: hh3cDot3MpcpRoundTripTime.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpRoundTripTime.setDescription('A read-only value that reports the MPCP round trip time in increments of Time Quanta (TQ) 16ns. The value returned shall be (round trip time in ns)/16. If this value exceeds (2^16-1) the value (2^16-1) shall be returned. This attribute is relevant for an OLT and an ONU. For the OLT there is a value per LLID')
hh3cDot3MpcpMaximumPendingGrants = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpMaximumPendingGrants.setReference('[802.3ah], 30.3.5.1.24.')
if mibBuilder.loadTexts: hh3cDot3MpcpMaximumPendingGrants.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpMaximumPendingGrants.setDescription('A read-only value that indicates the maximum number of grants an ONU can store. The maximum number of grants an ONU can store has a range of 0 to 255. This attribute is relevant for an OLT and an ONU. For the OLT there is a value per LLID')
hh3cDot3MpcpAdminState = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 1, 1, 11), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hh3cDot3MpcpAdminState.setReference('[802.3ah], 30.3.5.2.1.')
if mibBuilder.loadTexts: hh3cDot3MpcpAdminState.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpAdminState.setDescription('This variable can be used to define the operational state of the Multi-Point MAC Control sublayer as defined in [802.3ah] clause 64. Selecting admin for an interface with Multi-Point MAC Control sublayer. When selecting the value as True the interface Multi-Point control protocol is enabled. When selecting the value as False the interface acts as if the Multi-point Control protocol does not exist. Reading reflects the state of the attribute and the operation of the Multi-point control protocol mode of the interface. Writing can be done all the time. This attribute is relevant for an OLT and an ONU.')
hh3cDot3MpcpOnTime = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 1, 1, 12), Integer32()).setUnits('TQ (16nsec)').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpOnTime.setReference('[802.3ah], 64.3.5.1.')
if mibBuilder.loadTexts: hh3cDot3MpcpOnTime.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpOnTime.setDescription('A read-only value that reports the -on time- for a grant burst in increments of Time Quanta (TQ) 16ns as defined in [802.3ah] 60,64. The value returned shall be (on time ns)/16. If this value exceeds (2^32-1) the value (2^32-1) shall be returned. This attribute is relevant for an OLT and an ONU.')
hh3cDot3MpcpOffTime = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 1, 1, 13), Integer32()).setUnits('TQ (16nsec)').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpOffTime.setReference('[802.3ah], 64.3.5.1.')
if mibBuilder.loadTexts: hh3cDot3MpcpOffTime.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpOffTime.setDescription('A read-only value that reports the -off time- for a grant burst in increments of Time Quanta (TQ) 16ns as defined in [802.3ah] 60,64. The value returned shall be (off time ns)/16. If this value exceeds (2^32-1) the value (2^32-1) shall be returned. This attribute is relevant for an OLT and an ONU.')
hh3cDot3MpcpSyncTime = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 1, 1, 14), Integer32()).setUnits('TQ (16nsec)').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpSyncTime.setReference('[802.3ah], 64.3.3.2.')
if mibBuilder.loadTexts: hh3cDot3MpcpSyncTime.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpSyncTime.setDescription('A read-only value that reports the -sync lock time- for an OLT receiver in increments of Time Quanta (TQ) 16ns as defined in [802.3ah] 60,64,65. The value returned shall be (sync lock time ns)/16. If this value exceeds (2^32-1) the value (2^32-1) shall be returned. This attribute is relevant for an OLT and an ONU.')
hh3cDot3MpcpStatTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 2), )
if mibBuilder.loadTexts: hh3cDot3MpcpStatTable.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpStatTable.setDescription('This table defines the list of statistics counters of [802.3ah] clause 64 MPCP interface.')
hh3cDot3MpcpStatEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: hh3cDot3MpcpStatEntry.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpStatEntry.setDescription('Table entries for table of statistics counters of [802.3ah] clause 64 MPCP interface.')
hh3cDot3MpcpMACCtrlFramesTransmitted = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 2, 1, 1), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpMACCtrlFramesTransmitted.setReference('[802.3ah], 30.3.5.1.7.')
if mibBuilder.loadTexts: hh3cDot3MpcpMACCtrlFramesTransmitted.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpMACCtrlFramesTransmitted.setDescription('A count of MPCP frames passed to the MAC sublayer for transmission. This counter is incremented when a MA_CONTROL.request service primitive is generated within the MAC control sublayer with an opcode indicating a MPCP frame. This attribute is relevant for an OLT and an ONU.')
hh3cDot3MpcpMACCtrlFramesReceived = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 2, 1, 2), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpMACCtrlFramesReceived.setReference('[802.3ah], 30.3.5.1.8.')
if mibBuilder.loadTexts: hh3cDot3MpcpMACCtrlFramesReceived.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpMACCtrlFramesReceived.setDescription('A count of MPCP frames passed by the MAC sublayer to the MAC Control sublayer. This counter is incremented when a ReceiveFrame function call returns a valid frame with: (1) a lengthOrType field value equal to the reserved Type for 802.3_MAC_Control as specified in 31.4.1.3, and (2) an opcode indicating a MPCP frame. This attribute is relevant for an OLT and an ONU.')
hh3cDot3MpcpDiscoveryWindowsSent = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 2, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpDiscoveryWindowsSent.setReference('[802.3ah], 30.3.5.1.22.')
if mibBuilder.loadTexts: hh3cDot3MpcpDiscoveryWindowsSent.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpDiscoveryWindowsSent.setDescription('A count of discovery windows generated. The counter is incremented by one for each generated discovery window. This attribute is relevant for an OLT and an ONU. At the ONU value should be zero.')
hh3cDot3MpcpDiscoveryTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 2, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpDiscoveryTimeout.setReference('[802.3ah], 30.3.5.1.23.')
if mibBuilder.loadTexts: hh3cDot3MpcpDiscoveryTimeout.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpDiscoveryTimeout.setDescription('A count of the number of times a discovery timeout occurs. Increment the counter by one for each discovery processing state-machine reset resulting from timeout waiting for message arrival. This attribute is relevant for an OLT and an ONU.')
hh3cDot3MpcpTxRegRequest = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 2, 1, 5), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpTxRegRequest.setReference('[802.3ah], 30.3.5.1.12.')
if mibBuilder.loadTexts: hh3cDot3MpcpTxRegRequest.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpTxRegRequest.setDescription('A count of the number of times a REGISTER_REQ MPCP frames transmission occurs. Increment the counter by one for each REGISTER_REQ MPCP frame transmitted as defined in [802.3ah] clause 64. This counter is mandatory for an ONU. This attribute is relevant for an OLT and an ONU. At the OLT value should be zero.')
hh3cDot3MpcpRxRegRequest = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 2, 1, 6), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpRxRegRequest.setReference('[802.3ah], 30.3.5.1.17.')
if mibBuilder.loadTexts: hh3cDot3MpcpRxRegRequest.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpRxRegRequest.setDescription('A count of the number of times a REGISTER_REQ MPCP frames reception occurs. A single counter at the ONU and a set of counters, one for each LLID, at the OLT. Increment the counter by one for each REGISTER_REQ MPCP frame received for each LLID as defined in [802.3ah] clause 64. This counter is mandatory for an ONU and for an OLT. At the ONU value should be zero.')
hh3cDot3MpcpTxRegAck = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 2, 1, 7), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpTxRegAck.setReference('[802.3ah], 30.3.5.1.10.')
if mibBuilder.loadTexts: hh3cDot3MpcpTxRegAck.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpTxRegAck.setDescription('A count of the number of times a REGISTER_ACK MPCP frames transmission occurs. Increment the counter by one for each REGISTER_ACK MPCP frame transmitted as defined in [802.3ah] clause 64. This counter is mandatory for an ONU. This attribute is relevant for an OLT and an ONU. At the OLT the value should be zero.')
hh3cDot3MpcpRxRegAck = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 2, 1, 8), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpRxRegAck.setReference('[802.3ah], 30.3.5.1.15.')
if mibBuilder.loadTexts: hh3cDot3MpcpRxRegAck.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpRxRegAck.setDescription('A count of the number of times a REGISTER_ACK MPCP frames reception occurs. A single counter at the ONU and a set of counters, one for each LLID, at the OLT. Increment the counter by one for each REGISTER_ACK MPCP frame received for each LLID, as defined in [802.3ah] clause 64. This counter is mandatory for an ONU and for an OLT. At the ONU the value should be zero.')
hh3cDot3MpcpTxReport = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 2, 1, 9), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpTxReport.setReference('[802.3ah], 30.3.5.1.13.')
if mibBuilder.loadTexts: hh3cDot3MpcpTxReport.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpTxReport.setDescription('A count of the number of times a REPORT MPCP frames transmission occurs. Increment the counter by one for each REPORT MPCP frame transmitted as defined in [802.3ah] clause 64. This counter is mandatory for an ONU. This attribute is relevant for an OLT and an ONU. At the OLT value should be zero.')
hh3cDot3MpcpRxReport = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 2, 1, 10), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpRxReport.setReference('[802.3ah], 30.3.5.1.18.')
if mibBuilder.loadTexts: hh3cDot3MpcpRxReport.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpRxReport.setDescription('A count of the number of times a REPORT MPCP frames reception occurs. A single counter at the ONU and a set of counters, one for each LLID, at the OLT. Increment the counter by one for each REPORT MPCP frame received for each LLID, as defined in [802.3ah] clause 64. This counter is mandatory for an ONU and for an OLT. At the ONU value should be zero.')
hh3cDot3MpcpTxGate = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 2, 1, 11), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpTxGate.setReference('[802.3ah], 30.3.5.1.9.')
if mibBuilder.loadTexts: hh3cDot3MpcpTxGate.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpTxGate.setDescription('A count of the number of times a GATE MPCP frames transmission occurs. A set of counters, one for each LLID, at the OLT. Increment the counter by one for each GATE MPCP frame transmitted, for each LLID, as defined in [802.3ah] clause 64. This counter is mandatory for an OLT. This attribute is relevant for an OLT and an ONU. At the ONU the value should be zero.')
hh3cDot3MpcpRxGate = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 2, 1, 12), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpRxGate.setReference('[802.3ah], 30.3.5.1.14.')
if mibBuilder.loadTexts: hh3cDot3MpcpRxGate.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpRxGate.setDescription('A count of the number of times a GATE MPCP frames reception occurs. A single counter at the ONU and a set of counters, one for each LLID ,at the OLT. Increment the counter by one for each GATE MPCP frame received, for each LLID, as defined in [802.3ah] clause 64. This counter is mandatory for an ONU and for an OLT. At the OLT the value should be zero.')
hh3cDot3MpcpTxRegister = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 2, 1, 13), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpTxRegister.setReference('[802.3ah], 30.3.5.1.11.')
if mibBuilder.loadTexts: hh3cDot3MpcpTxRegister.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpTxRegister.setDescription('A count of the number of times a REGISTER MPCP frames transmission occurs. A set of counters, one for each LLID, at the OLT. Increment the counter by one for each REGISTER MPCP frame transmitted, for each LLID, as defined in [802.3ah] clause 64. This counter is mandatory for an OLT. This attribute is relevant for an OLT and an ONU. At the ONU the value should be zero.')
hh3cDot3MpcpRxRegister = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 2, 1, 14), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpRxRegister.setReference('[802.3ah], 30.3.5.1.16.')
if mibBuilder.loadTexts: hh3cDot3MpcpRxRegister.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpRxRegister.setDescription('A count of the number of times a REGISTER MPCP frames reception occurs. A single counter at the ONU and a set of counters, one for each LLID, at the OLT. Increment the counter by one for each REGISTER MPCP frame received, for each LLID, as defined in [802.3ah] clause 64. This counter is mandatory for an ONU and for an OLT. at the OLT the value should be zero.')
hh3cDot3MpcpRxNotSupportedMPCP = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 1, 2, 1, 15), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3MpcpRxNotSupportedMPCP.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpRxNotSupportedMPCP.setDescription('A count of the number of times a non-supported MPCP frames reception occurs. A single counter at the ONU and a set of counters, one for each LLID, at the OLT. Increment the counter by one for each non-supported MPCP frame received, for each LLID, as defined in [802.3ah] clause 64. This counter is mandatory for an ONU and for an OLT.')
hh3cDot3MpcpGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 2, 1))
hh3cDot3MpcpGroupBase = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 2, 1, 1)).setObjects(("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpID"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpOperStatus"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpMode"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpLinkID"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpRemoteMACAddress"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpRegistrationState"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpMaximumPendingGrants"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpAdminState"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cDot3MpcpGroupBase = hh3cDot3MpcpGroupBase.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpGroupBase.setDescription('A collection of objects of dot3 Mpcp Basic entity state definition.')
hh3cDot3MpcpGroupParam = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 2, 1, 2)).setObjects(("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpTransmitElapsed"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpReceiveElapsed"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpRoundTripTime"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpOnTime"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpOffTime"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpSyncTime"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cDot3MpcpGroupParam = hh3cDot3MpcpGroupParam.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpGroupParam.setDescription('A collection of objects of dot3 Mpcp for P2MP parameters.')
hh3cDot3MpcpGroupStat = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 2, 1, 3)).setObjects(("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpMACCtrlFramesTransmitted"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpMACCtrlFramesReceived"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpDiscoveryWindowsSent"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpDiscoveryTimeout"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpTxRegRequest"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpRxRegRequest"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpTxRegAck"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpRxRegAck"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpTxReport"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpRxReport"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpTxGate"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpRxGate"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpTxRegister"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpRxRegister"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpRxNotSupportedMPCP"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cDot3MpcpGroupStat = hh3cDot3MpcpGroupStat.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpGroupStat.setDescription('A collection of objects of dot3 Mpcp Statistics')
hh3cDot3MpcpCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 2, 2))
hh3cDot3MpcpCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 1, 2, 2, 1)).setObjects(("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpGroupBase"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpGroupParam"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3MpcpGroupStat"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cDot3MpcpCompliance = hh3cDot3MpcpCompliance.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3MpcpCompliance.setDescription('The compliance statement for Multi-point control protocol interfaces.')
hh3cDot3OmpEmulationMIB = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2))
hh3cDot3OmpEmulationObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 1))
hh3cDot3OmpeConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 2))
hh3cDot3OmpEmulationTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 1, 1), )
if mibBuilder.loadTexts: hh3cDot3OmpEmulationTable.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationTable.setDescription('Table for dot3 OmpEmulation MIB modules.')
hh3cDot3OmpEmulationEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 1, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: hh3cDot3OmpEmulationEntry.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationEntry.setDescription('An entry in the dot3 OmpEmulation MIB modules table.')
hh3cDot3OmpEmulationID = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3OmpEmulationID.setReference('[802.3ah], 30.3.7.1.1.')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationID.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationID.setDescription('The value of hh3cDot3OmpEmulationID is assigned so as to uniquely identify a OMPEmulation entity among the subordinate managed objects of the containing object. The value is mandated for an ONU.')
hh3cDot3OmpEmulationType = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("unknown", 1), ("olt", 2), ("onu", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3OmpEmulationType.setReference('[802.3ah], 30.3.7.1.2.')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationType.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationType.setDescription('A read-only value that indicates that mode of operation of the Reconciliation Sublayer for Point to Point Emulation (see [802.3ah] clause 65.1). unknown(1) value is assigned in initializing, true state or type not yet known. olt(2) value is assigned when Sublayer operating in OLT mode. onu(3) value is assigned when Sublayer operating in ONU mode.')
hh3cDot3OmpEmulationStatTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 1, 2), )
if mibBuilder.loadTexts: hh3cDot3OmpEmulationStatTable.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationStatTable.setDescription('This table defines the list of statistics counters of [802.3ah] clause 65 OMP interface.')
hh3cDot3OmpEmulationStatEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 1, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: hh3cDot3OmpEmulationStatEntry.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationStatEntry.setDescription('Table entries for Table of statistics counters of [802.3ah] clause 65 OMP interface.')
hh3cDot3OmpEmulationSLDErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 1, 2, 1, 1), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3OmpEmulationSLDErrors.setReference('[802.3ah], 30.3.7.1.3.')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationSLDErrors.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationSLDErrors.setDescription('A count of frames received that do not contain a valid SLD field as defined in [802.3ah] clause 65.1.3.3.1. This attribute is mandatory for an OLT and optional for an ONU.')
hh3cDot3OmpEmulationCRC8Errors = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 1, 2, 1, 2), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3OmpEmulationCRC8Errors.setReference('[802.3ah], 30.3.7.1.4.')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationCRC8Errors.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationCRC8Errors.setDescription('A count of frames received that contain a valid SLD field, as defined in [802.3ah] clause 65.1.3.3.1, but do not pass the CRC-8 check as defined in [802.3ah] clause 65.1.3.3.3. This attribute is mandatory for an OLT and for an ONU.')
hh3cDot3OmpEmulationBadLLID = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 1, 2, 1, 3), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3OmpEmulationBadLLID.setReference('[802.3ah], 30.3.7.1.8.')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationBadLLID.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationBadLLID.setDescription('A count of frames received that contain a valid SLD field, as defined in [802.3ah] clause 65.1.3.3.1, and pass the CRC-8 check, as defined in [802.3ah] clause 65.1.3.3.3, but are discarded due to the LLID check as defined in [802.3ah] clause 65.1.3.3.2. This attribute is relevant for an OLT and an ONU.')
hh3cDot3OmpEmulationGoodLLID = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 1, 2, 1, 4), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3OmpEmulationGoodLLID.setReference('[802.3ah], 30.3.7.1.5.')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationGoodLLID.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationGoodLLID.setDescription('A count of frames received that contain a valid SLD field, as defined in [802.3ah] clause 65.1.3.3.1, and pass the CRC-8 check, as defined in [802.3ah] clause 65.1.3.3.3. This attribute is relevant for an OLT and an ONU.')
hh3cDot3OmpEmulationOnuPonCastLLID = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 1, 2, 1, 5), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3OmpEmulationOnuPonCastLLID.setReference('[802.3ah], 30.3.7.1.6.')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationOnuPonCastLLID.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationOnuPonCastLLID.setDescription('A count of frames received that contain a valid SLD field in an ONU, as defined in [802.3ah] 65.1.3.3.1, passes the CRC-8 check, as defined in [802.3ah] 65.1.3.3.3, and the frame meets the rule for acceptance defined in [802.3ah] 65.1.3.3.2.')
hh3cDot3OmpEmulationOltPonCastLLID = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 1, 2, 1, 6), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3OmpEmulationOltPonCastLLID.setReference('[802.3ah], 30.3.7.1.7.')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationOltPonCastLLID.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationOltPonCastLLID.setDescription('A count of frames received that contain a valid SLD field in an OLT, as defined in [802.3ah] 65.1.3.3.1, passes the CRC-8 check, as defined in [802.3ah] 65.1.3.3.3, and the frame meets the rule for acceptance defined in [802.3ah] 65.1.3.3.2.')
hh3cDot3OmpEmulationBroadcastLLIDNotOnuID = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 1, 2, 1, 7), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3OmpEmulationBroadcastLLIDNotOnuID.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationBroadcastLLIDNotOnuID.setDescription('A count of frames received that contain a valid SLD field in a OLT, as defined in [802.3ah] clause 65.1.3.3.1, and pass the CRC-8 check, as defined in [802.3ah] clause 65.1.3.3.3, and contain broadcast LLID as defined in [802.3ah] clause 65. This attribute is mandatory for an OLT and for an ONU.')
hh3cDot3OmpEmulationOnuLLIDNotBroadcast = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 1, 2, 1, 8), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3OmpEmulationOnuLLIDNotBroadcast.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationOnuLLIDNotBroadcast.setDescription("A count of frames received that contain a valid SLD field in a OLT, as defined in [802.3ah] clause 65.1.3.3.1, and pass the CRC-8 check, as defined in [802.3ah] clause 65.1.3.3.3, and contain the ONU's LLID as defined in [802.3ah] clause 65. This attribute is mandatory for an ONU and mandatory for an OLT (a counter per LLID).")
hh3cDot3OmpEmulationBroadcastLLIDPlusOnuId = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 1, 2, 1, 9), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3OmpEmulationBroadcastLLIDPlusOnuId.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationBroadcastLLIDPlusOnuId.setDescription("A count of frames received that contain a valid SLD field in a OLT, as defined in [802.3ah] clause 65.1.3.3.1, and pass the CRC-8 check, as defined in [802.3ah] clause 65.1.3.3.3, and contain the broadcast LLID plus ONU's LLID (frame reflected) as defined in [802.3ah] clause 65. This attribute is mandatory for an ONU and mandatory for an OLT (a counter per LLID).")
hh3cDot3OmpEmulationNotBroadcastLLIDNotOnuId = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 1, 2, 1, 10), Counter32()).setUnits('frames').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3OmpEmulationNotBroadcastLLIDNotOnuId.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpEmulationNotBroadcastLLIDNotOnuId.setDescription("A count of frames received that contain a valid SLD field in a OLT, as defined in [802.3ah] clause 65.1.3.3.1, and pass the CRC-8 check, as defined in [802.3ah] clause 65.1.3.3.3, and does not contain the ONU's LLID as defined in [802.3ah] clause 65. This attribute is mandatory for an ONU")
hh3cDot3OmpeGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 2, 1))
hh3cDot3OmpeGroupID = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 2, 1, 1)).setObjects(("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3OmpEmulationID"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3OmpEmulationType"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cDot3OmpeGroupID = hh3cDot3OmpeGroupID.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpeGroupID.setDescription('A collection of objects of dot3 OMP emulation ID entity state definition.')
hh3cDot3OmpeGroupStat = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 2, 1, 2)).setObjects(("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3OmpEmulationSLDErrors"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3OmpEmulationCRC8Errors"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3OmpEmulationBadLLID"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3OmpEmulationGoodLLID"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3OmpEmulationOnuPonCastLLID"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3OmpEmulationOltPonCastLLID"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3OmpEmulationBroadcastLLIDNotOnuID"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3OmpEmulationOnuLLIDNotBroadcast"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3OmpEmulationBroadcastLLIDPlusOnuId"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3OmpEmulationNotBroadcastLLIDNotOnuId"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cDot3OmpeGroupStat = hh3cDot3OmpeGroupStat.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpeGroupStat.setDescription('A collection of objects of dot3 OMP emulation Statistics')
hh3cDot3OmpeCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 2, 2))
hh3cDot3OmpeCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 2, 2, 2, 1)).setObjects(("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3OmpeGroupID"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3OmpeGroupStat"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cDot3OmpeCompliance = hh3cDot3OmpeCompliance.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3OmpeCompliance.setDescription('The compliance statement for OMPEmulation interfaces.')
hh3cDot3EponMauMIB = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3))
hh3cDot3EponMauObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 1))
hh3cDot3EponMauConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 2))
hh3cDot3EponMauTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 1, 1), )
if mibBuilder.loadTexts: hh3cDot3EponMauTable.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3EponMauTable.setDescription('Table for dot3 MAU EPON MIB modules.')
hh3cDot3EponMauEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 1, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: hh3cDot3EponMauEntry.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3EponMauEntry.setDescription('An entry in the dot3 MAU EPON MIB modules table.')
hh3cDot3EponMauPCSCodingViolation = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 1, 1, 1, 1), Counter32()).setUnits('octets').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3EponMauPCSCodingViolation.setReference('[802.3ah], 30.5.1.1.12.')
if mibBuilder.loadTexts: hh3cDot3EponMauPCSCodingViolation.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3EponMauPCSCodingViolation.setDescription('For 100 Mb/ s operation it is a count of the number of times an invalid code-group is received, other than the /H/ code-group. For 1000 Mb/ s operation it is a count of the number of times an invalid codegroup is received, other than the /V/ code-group.')
hh3cDot3EponMauFecAbility = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("unknown", 1), ("nonsupported", 2), ("supported", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3EponMauFecAbility.setReference('[802.3ah], 30.5.1.1.13.')
if mibBuilder.loadTexts: hh3cDot3EponMauFecAbility.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3EponMauFecAbility.setDescription('A read-only value that indicates the support of operation of the 1000BASE-PX PHY optional FEC Sublayer for Forward error correction see [802.3ah] clause 65.2). unknown(1) value is assigned in initializing, for non FEC support state or type not yet known. nonsupported(2) value is assigned when Sublayer is not support. supported(3) value is assigned when Sublayer is supported.')
hh3cDot3EponMauFecMode = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("unknown", 1), ("disabled", 2), ("enabled", 3))).clone(1)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hh3cDot3EponMauFecMode.setReference('[802.3ah], 30.5.1.1.14.')
if mibBuilder.loadTexts: hh3cDot3EponMauFecMode.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3EponMauFecMode.setDescription('A read-write value that indicates the mode of operation of the 1000BASE-PX PHY optional FEC Sublayer for Forward error correction see [802.3ah] clause 65.2). A GET operation returns the current mode of operation the PHY. A SET operation changes the mode of operation of the PHY to the indicated value. unknown(1) value is assigned in initializing, for non FEC support state or type not yet known. disabled(2) value is assigned when Sublayer operating in disabled mode. enabled(3) value is assigned when Sublayer operating in FEC mode. writing can be done all the time.')
hh3cDot3EponMauFECCorrectedBlocks = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 1, 1, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3EponMauFECCorrectedBlocks.setReference('[802.3ah], 30.5.1.1.15.')
if mibBuilder.loadTexts: hh3cDot3EponMauFECCorrectedBlocks.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3EponMauFECCorrectedBlocks.setDescription('For 10PASS-TS, 2BASE-TL and 1000BASE-PX PHYs, a count of corrected FEC blocks. This counter will not increment for other PHY Types. Increment the counter by one for each received block that is corrected by the FEC function in the PHY.')
hh3cDot3EponMauFECUncorrectableBlocks = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 1, 1, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3EponMauFECUncorrectableBlocks.setReference('[802.3ah], 30.5.1.1.16.')
if mibBuilder.loadTexts: hh3cDot3EponMauFECUncorrectableBlocks.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3EponMauFECUncorrectableBlocks.setDescription('For 10PASS-TS, 2BASE-TL and 1000BASE-PX PHYs, a count of uncorrectable FEC blocks. This counter will not increment for other PHY Types. Increment the counter by one for each FEC block that is determined to be uncorrectable by the FEC function in the PHY.')
hh3cDot3EponMauBufferHeadCodingViolation = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 1, 1, 1, 6), Counter32()).setUnits('octets').setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cDot3EponMauBufferHeadCodingViolation.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3EponMauBufferHeadCodingViolation.setDescription('For 1000 Mbps operation it is a counts of the number of invalid code-group received directly from the link.')
hh3cDot3EponMauType = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 3))
hh3cEponMauType1000BasePXOLT = ObjectIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 3, 1))
if mibBuilder.loadTexts: hh3cEponMauType1000BasePXOLT.setStatus('current')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePXOLT.setDescription('Multipoint MAC Control (per 802.3 section 64,65) OLT (master), unknown PMD')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePXOLT.setReference('[802.3ah], 30.5.1.1.2.')
hh3cEponMauType1000BasePXONU = ObjectIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 3, 2))
if mibBuilder.loadTexts: hh3cEponMauType1000BasePXONU.setStatus('current')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePXONU.setDescription('Multipoint MAC Control (per 802.3 section 64,65),ONU (slave), unknown PMD')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePXONU.setReference('[802.3ah], 30.5.1.1.2.')
hh3cEponMauType1000BasePX10DOLT = ObjectIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 3, 3))
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX10DOLT.setStatus('current')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX10DOLT.setDescription('EPON over 10K link, downlink (per 802.3 section 60), OLT side')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX10DOLT.setReference('[802.3ah], 30.5.1.1.2.')
hh3cEponMauType1000BasePX10DONU = ObjectIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 3, 4))
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX10DONU.setStatus('current')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX10DONU.setDescription('EPON over 10K link, downlink (per 802.3 section 60), ONU side')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX10DONU.setReference('[802.3ah], 30.5.1.1.2.')
hh3cEponMauType1000BasePX10UOLT = ObjectIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 3, 5))
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX10UOLT.setStatus('current')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX10UOLT.setDescription('EPON over 10K link, uplink (per 802.3 section 60), OLT side')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX10UOLT.setReference('[802.3ah], 30.5.1.1.2.')
hh3cEponMauType1000BasePX10UONU = ObjectIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 3, 6))
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX10UONU.setStatus('current')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX10UONU.setDescription('EPON over 10K link, uplink (per 802.3 section 60), ONU side')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX10UONU.setReference('[802.3ah], 30.5.1.1.2.')
hh3cEponMauType1000BasePX20DOLT = ObjectIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 3, 7))
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX20DOLT.setStatus('current')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX20DOLT.setDescription('EPON over 20K link, downlink (per 802.3 section 60), OLT side')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX20DOLT.setReference('[802.3ah], 30.5.1.1.2.')
hh3cEponMauType1000BasePX20DONU = ObjectIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 3, 8))
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX20DONU.setStatus('current')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX20DONU.setDescription('EPON over 20K link, downlink (per 802.3 section 60), ONU side')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX20DONU.setReference('[802.3ah], 30.5.1.1.2.')
hh3cEponMauType1000BasePX20UOLT = ObjectIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 3, 9))
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX20UOLT.setStatus('current')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX20UOLT.setDescription('EPON over 20K link, uplink (per 802.3 section 60), OLT side')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX20UOLT.setReference('[802.3ah], 30.5.1.1.2.')
hh3cEponMauType1000BasePX20UONU = ObjectIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 3, 10))
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX20UONU.setStatus('current')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX20UONU.setDescription('EPON over 20K link, uplink (per 802.3 section 60), ONU side')
if mibBuilder.loadTexts: hh3cEponMauType1000BasePX20UONU.setReference('[802.3ah], 30.5.1.1.2.')
hh3cDot3EponMauGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 2, 1))
hh3cDot3EponMauGroupAll = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 2, 1, 1)).setObjects(("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3EponMauPCSCodingViolation"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cDot3EponMauGroupAll = hh3cDot3EponMauGroupAll.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3EponMauGroupAll.setDescription('A collection of objects of dot3 MAU definition.')
hh3cDot3EponMauGroupFEC = ObjectGroup((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 2, 1, 2)).setObjects(("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3EponMauFecAbility"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3EponMauFecMode"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3EponMauFECCorrectedBlocks"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3EponMauFECUncorrectableBlocks"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3EponMauBufferHeadCodingViolation"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cDot3EponMauGroupFEC = hh3cDot3EponMauGroupFEC.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3EponMauGroupFEC.setDescription('A collection of objects of FEC group definition.')
hh3cDot3EponMauCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 2, 2))
hh3cDot3EponMauCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 25506, 2, 42, 2, 3, 2, 2, 1)).setObjects(("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3EponMauGroupAll"), ("HH3C-DOT3-EFM-EPON-MIB", "hh3cDot3EponMauGroupFEC"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hh3cDot3EponMauCompliance = hh3cDot3EponMauCompliance.setStatus('current')
if mibBuilder.loadTexts: hh3cDot3EponMauCompliance.setDescription('The compliance statement for MAU EPON interfaces.')
mibBuilder.exportSymbols("HH3C-DOT3-EFM-EPON-MIB", hh3cDot3MpcpRxNotSupportedMPCP=hh3cDot3MpcpRxNotSupportedMPCP, hh3cEponMauType1000BasePXONU=hh3cEponMauType1000BasePXONU, hh3cDot3OmpEmulationGoodLLID=hh3cDot3OmpEmulationGoodLLID, hh3cDot3MpcpCompliances=hh3cDot3MpcpCompliances, hh3cEponMauType1000BasePX10UOLT=hh3cEponMauType1000BasePX10UOLT, hh3cDot3OmpeGroupStat=hh3cDot3OmpeGroupStat, hh3cDot3OmpeConformance=hh3cDot3OmpeConformance, hh3cEponMauType1000BasePX10UONU=hh3cEponMauType1000BasePX10UONU, hh3cEponMauType1000BasePX20DONU=hh3cEponMauType1000BasePX20DONU, hh3cDot3OmpEmulationStatEntry=hh3cDot3OmpEmulationStatEntry, hh3cDot3OmpEmulationType=hh3cDot3OmpEmulationType, hh3cDot3MpcpRxGate=hh3cDot3MpcpRxGate, hh3cEponMauType1000BasePX10DONU=hh3cEponMauType1000BasePX10DONU, hh3cDot3EponMauPCSCodingViolation=hh3cDot3EponMauPCSCodingViolation, hh3cEponMauType1000BasePX20UONU=hh3cEponMauType1000BasePX20UONU, hh3cDot3MpcpTxRegister=hh3cDot3MpcpTxRegister, hh3cDot3MpcpDiscoveryWindowsSent=hh3cDot3MpcpDiscoveryWindowsSent, hh3cDot3OmpEmulationMIB=hh3cDot3OmpEmulationMIB, hh3cDot3MpcpMACCtrlFramesReceived=hh3cDot3MpcpMACCtrlFramesReceived, hh3cDot3MpcpConformance=hh3cDot3MpcpConformance, hh3cDot3MpcpMACCtrlFramesTransmitted=hh3cDot3MpcpMACCtrlFramesTransmitted, hh3cDot3OmpEmulationCRC8Errors=hh3cDot3OmpEmulationCRC8Errors, PYSNMP_MODULE_ID=hh3cDot3EfmeponMIB, hh3cDot3OmpEmulationBadLLID=hh3cDot3OmpEmulationBadLLID, hh3cDot3MpcpObjects=hh3cDot3MpcpObjects, hh3cDot3EponMauGroupFEC=hh3cDot3EponMauGroupFEC, hh3cDot3MpcpAdminState=hh3cDot3MpcpAdminState, hh3cDot3EponMauGroups=hh3cDot3EponMauGroups, hh3cDot3MpcpGroups=hh3cDot3MpcpGroups, hh3cDot3EponMauType=hh3cDot3EponMauType, hh3cDot3MpcpStatTable=hh3cDot3MpcpStatTable, hh3cDot3MpcpOnTime=hh3cDot3MpcpOnTime, hh3cDot3OmpEmulationStatTable=hh3cDot3OmpEmulationStatTable, hh3cDot3EponMauBufferHeadCodingViolation=hh3cDot3EponMauBufferHeadCodingViolation, hh3cDot3MpcpGroupParam=hh3cDot3MpcpGroupParam, hh3cDot3OmpEmulationBroadcastLLIDNotOnuID=hh3cDot3OmpEmulationBroadcastLLIDNotOnuID, hh3cDot3MpcpCompliance=hh3cDot3MpcpCompliance, hh3cDot3EponMauFECUncorrectableBlocks=hh3cDot3EponMauFECUncorrectableBlocks, hh3cDot3MpcpRxReport=hh3cDot3MpcpRxReport, hh3cEponMauType1000BasePX10DOLT=hh3cEponMauType1000BasePX10DOLT, hh3cDot3OmpEmulationSLDErrors=hh3cDot3OmpEmulationSLDErrors, hh3cDot3EponMauCompliances=hh3cDot3EponMauCompliances, hh3cDot3MpcpRemoteMACAddress=hh3cDot3MpcpRemoteMACAddress, hh3cDot3MpcpMaximumPendingGrants=hh3cDot3MpcpMaximumPendingGrants, hh3cDot3MpcpTable=hh3cDot3MpcpTable, hh3cDot3EponMauEntry=hh3cDot3EponMauEntry, hh3cDot3OmpEmulationOnuPonCastLLID=hh3cDot3OmpEmulationOnuPonCastLLID, hh3cDot3EponMauTable=hh3cDot3EponMauTable, hh3cDot3OmpEmulationEntry=hh3cDot3OmpEmulationEntry, hh3cDot3MpcpRxRegRequest=hh3cDot3MpcpRxRegRequest, hh3cDot3EponMauFecAbility=hh3cDot3EponMauFecAbility, hh3cDot3EponMauMIB=hh3cDot3EponMauMIB, hh3cDot3MpcpTxRegRequest=hh3cDot3MpcpTxRegRequest, hh3cDot3MpcpEntry=hh3cDot3MpcpEntry, hh3cDot3MpcpStatEntry=hh3cDot3MpcpStatEntry, hh3cDot3OmpEmulationObjects=hh3cDot3OmpEmulationObjects, hh3cDot3MpcpMode=hh3cDot3MpcpMode, hh3cDot3OmpEmulationNotBroadcastLLIDNotOnuId=hh3cDot3OmpEmulationNotBroadcastLLIDNotOnuId, hh3cDot3EponMauCompliance=hh3cDot3EponMauCompliance, hh3cDot3MpcpReceiveElapsed=hh3cDot3MpcpReceiveElapsed, hh3cDot3MpcpOperStatus=hh3cDot3MpcpOperStatus, hh3cDot3MpcpOffTime=hh3cDot3MpcpOffTime, hh3cDot3OmpEmulationBroadcastLLIDPlusOnuId=hh3cDot3OmpEmulationBroadcastLLIDPlusOnuId, hh3cDot3MpcpMIB=hh3cDot3MpcpMIB, hh3cDot3MpcpGroupBase=hh3cDot3MpcpGroupBase, hh3cDot3MpcpGroupStat=hh3cDot3MpcpGroupStat, hh3cDot3OmpeGroups=hh3cDot3OmpeGroups, hh3cDot3OmpEmulationTable=hh3cDot3OmpEmulationTable, hh3cDot3OmpEmulationID=hh3cDot3OmpEmulationID, hh3cDot3MpcpTransmitElapsed=hh3cDot3MpcpTransmitElapsed, hh3cDot3EponMauObjects=hh3cDot3EponMauObjects, hh3cDot3EponMauFecMode=hh3cDot3EponMauFecMode, hh3cDot3MpcpTxReport=hh3cDot3MpcpTxReport, hh3cDot3EponMauFECCorrectedBlocks=hh3cDot3EponMauFECCorrectedBlocks, hh3cDot3OmpeCompliance=hh3cDot3OmpeCompliance, hh3cDot3EponMauGroupAll=hh3cDot3EponMauGroupAll, hh3cEponMauType1000BasePX20UOLT=hh3cEponMauType1000BasePX20UOLT, hh3cDot3OmpEmulationOnuLLIDNotBroadcast=hh3cDot3OmpEmulationOnuLLIDNotBroadcast, hh3cDot3MpcpTxRegAck=hh3cDot3MpcpTxRegAck, hh3cDot3MpcpRegistrationState=hh3cDot3MpcpRegistrationState, hh3cDot3MpcpRoundTripTime=hh3cDot3MpcpRoundTripTime, hh3cDot3EfmeponMIB=hh3cDot3EfmeponMIB, hh3cDot3MpcpRxRegAck=hh3cDot3MpcpRxRegAck, hh3cDot3MpcpDiscoveryTimeout=hh3cDot3MpcpDiscoveryTimeout, hh3cEponMauType1000BasePX20DOLT=hh3cEponMauType1000BasePX20DOLT, hh3cDot3MpcpLinkID=hh3cDot3MpcpLinkID, hh3cDot3MpcpRxRegister=hh3cDot3MpcpRxRegister, hh3cDot3MpcpID=hh3cDot3MpcpID, hh3cEponMauType1000BasePXOLT=hh3cEponMauType1000BasePXOLT, hh3cDot3EponMauConformance=hh3cDot3EponMauConformance, hh3cDot3OmpeCompliances=hh3cDot3OmpeCompliances, hh3cDot3OmpEmulationOltPonCastLLID=hh3cDot3OmpEmulationOltPonCastLLID, hh3cDot3OmpeGroupID=hh3cDot3OmpeGroupID, hh3cDot3MpcpTxGate=hh3cDot3MpcpTxGate, hh3cDot3MpcpSyncTime=hh3cDot3MpcpSyncTime)
| 169.311573 | 5,121 | 0.783483 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 25,010 | 0.438326 |
3ecbd115bcfdc5ce591f196d4fe1390310b89ddc | 576 | py | Python | example/runscripts/nhilton/run_batch_job.py | weegreenblobbie/pith-tool | 25708bd2354cc5d97eb0c0a0046ca4704e4ced0a | [
"MIT"
]
| 2 | 2016-03-04T19:25:29.000Z | 2016-03-10T02:22:36.000Z | example/runscripts/nhilton/run_batch_job.py | weegreenblobbie/pith-tool | 25708bd2354cc5d97eb0c0a0046ca4704e4ced0a | [
"MIT"
]
| 10 | 2016-03-01T03:23:17.000Z | 2017-04-27T00:37:09.000Z | example/runscripts/nhilton/run_batch_job.py | weegreenblobbie/pith-tool | 25708bd2354cc5d97eb0c0a0046ca4704e4ced0a | [
"MIT"
]
| null | null | null | import argparse
from module_a.fun_1 import fun_1
from module_c.fun_4 import fun_4
from external_a.extra_fun import extra_fun
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'input_txt_file',
help = 'Some input file',
)
args = parser.parse_args()
print('Running batch job ...')
with open(args.input_txt_file, 'r') as fd:
text = fd.read()
print('Read "%s" from file' % repr(text))
fun_1()
fun_4()
extra_fun()
print('batch job complete!')
if __name__ == "__main__":
main()
| 16 | 46 | 0.626736 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 111 | 0.192708 |
3eccd3d6d89a4b4cb5aaf3d2889bce0836f4e413 | 395 | py | Python | DFS BFS/Leetcode 1436. Destination City.py | kaizhengny/LeetCode | 67d64536ab80f4966699fe7460d165f2a98d6a82 | [
"MIT"
]
| 31 | 2020-06-23T00:40:04.000Z | 2022-01-08T11:06:24.000Z | DFS BFS/Leetcode 1436. Destination City.py | kaizhengny/LeetCode | 67d64536ab80f4966699fe7460d165f2a98d6a82 | [
"MIT"
]
| null | null | null | DFS BFS/Leetcode 1436. Destination City.py | kaizhengny/LeetCode | 67d64536ab80f4966699fe7460d165f2a98d6a82 | [
"MIT"
]
| 7 | 2020-04-30T08:46:03.000Z | 2021-08-28T16:25:54.000Z | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
dic = collections.defaultdict(list)
for [x,y] in paths:
dic[x].append(y)
res = set()
stack = []
stack.append(paths[0][0])
while stack:
while dic[stack[-1]]:
stack.append(dic[stack[-1]].pop())
return stack[-1] | 30.384615 | 54 | 0.473418 | 395 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
3eccf323bfafeef7616f6d78bb34226073a6758e | 3,039 | py | Python | i18n/listeners/proxyContainer/ListShouldContainSubListProxy.py | Rexmen/i18n | b615f2d1e06b58f4647f1b269fc37d7921bc5c4b | [
"MIT"
]
| null | null | null | i18n/listeners/proxyContainer/ListShouldContainSubListProxy.py | Rexmen/i18n | b615f2d1e06b58f4647f1b269fc37d7921bc5c4b | [
"MIT"
]
| null | null | null | i18n/listeners/proxyContainer/ListShouldContainSubListProxy.py | Rexmen/i18n | b615f2d1e06b58f4647f1b269fc37d7921bc5c4b | [
"MIT"
]
| null | null | null | from .Proxy import Proxy
from robot.libraries.BuiltIn import BuiltIn
import sys
from robot.libraries.Screenshot import Screenshot
from robot.api import logger
import I18nListener as i18n
import ManyTranslations as ui
from robot.utils import unic
class ListShouldContainSubListProxy(Proxy):
def __init__(self, arg_format):
arg_format[repr(['list1', 'list2', 'msg=None', 'values=True'])] = self
def i18n_Proxy(self, func):
def proxy(self, list1, list2, msg=None, values=True):
full_args = [str(list1), str(list2)]
list1_trans = i18n.I18nListener.MAP.values(list1, full_args)
list2_trans = i18n.I18nListener.MAP.values(list2, full_args)
list1_have_multi_trans = False
for lt in list1_trans:
if len(lt) >1:
list1_have_multi_trans = True
break
list2_have_multi_trans = False
for lt in list2_trans:
if len(lt) >1:
list2_have_multi_trans = True
break
if list1_have_multi_trans or list2_have_multi_trans:
ListShouldContainSubListProxy.show_warning(self, list1, list2, full_args)
diffs = ', '.join(unic(item) for item in list2 if item not in list1)
if not diffs:
i18n.I18nListener.Is_Multi_Trans = True
for i, lt in enumerate(list1_trans):
if len(lt)>1 and str(full_args)+list1[i] not in ui.UI.unique_log:
multi_trans_word = [list1[i]]
ui.UI.origin_xpaths_or_arguments.append(full_args)
ui.UI.add_trans_info(self, multi_trans_word, lt, full_args, func.__name__)
for i, lt in enumerate(list2_trans):
if len(lt)>1 and str(full_args)+list2[i] not in ui.UI.unique_log:
multi_trans_word = [list2[i]]
ui.UI.origin_xpaths_or_arguments.append(full_args)
ui.UI.add_trans_info(self, multi_trans_word, lt, full_args, func.__name__)
return func(self, list1_trans, list2_trans, msg, values)
return proxy
def show_warning(self, list1, list2, full_args):
language = 'i18n in %s:\n ' %i18n.I18nListener.LOCALE
test_name = ('Test Name: %s') %BuiltIn().get_variable_value("${TEST NAME}") + '=> Exist multiple translations of the word' + '\n'
message_for_list1 = Proxy().deal_warning_message_for_list(list1, full_args, 'LIST1')
message_for_list2 = Proxy().deal_warning_message_for_list(list2, full_args, 'LIST2')
if message_for_list1 or message_for_list2:
message = language + test_name + message_for_list1 + '\n' + message_for_list2 + '\n'\
'You should verify translation is correct!'
logger.warn(message) | 50.65 | 137 | 0.58901 | 2,792 | 0.918723 | 0 | 0 | 0 | 0 | 0 | 0 | 199 | 0.065482 |
3ecdb050826a3f9850819307adc5e13bc204f458 | 3,218 | py | Python | dl_bounds/src/experiments/exp_bad_minima_branchout.py | google/dl_bounds | b38fbd73f30d2fd8d1b57ad8706c07a223689365 | [
"Apache-2.0"
]
| 12 | 2018-02-23T11:57:26.000Z | 2021-04-20T20:38:16.000Z | dl_bounds/src/experiments/exp_bad_minima_branchout.py | google/dl_bounds | b38fbd73f30d2fd8d1b57ad8706c07a223689365 | [
"Apache-2.0"
]
| null | null | null | dl_bounds/src/experiments/exp_bad_minima_branchout.py | google/dl_bounds | b38fbd73f30d2fd8d1b57ad8706c07a223689365 | [
"Apache-2.0"
]
| 7 | 2018-06-28T04:10:45.000Z | 2021-10-14T01:18:59.000Z | # coding=utf-8
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required 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 language governing permissions and
# limitations under the License.
"""Implements experimental logic."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from copy import copy
from dl_bounds.src.data import LocalDatasetProvider
from dl_bounds.src.exp_helpers import aggregate_dicts
from dl_bounds.src.experiments.exp_base import Experiment
import numpy as np
from scipy.stats import truncnorm
import tensorflow as tf
class BadMinimaBranchoutExperiment(Experiment):
"""Runs the branchout version of "bad minima" experiment."""
def __init__(self, conf, subexp_factory):
super(BadMinimaBranchoutExperiment, self).__init__(conf)
self.subexp_factory = subexp_factory
def run(self):
"""Runs experiment."""
tf.logging.info("Pre-training network with 50% labels flipped...")
conf = copy(self.conf)
conf.flip_labels = 0.5
conf.split_n = -1
conf.log2_snapshots = True
exp = Experiment(conf)
(x_train, y_train, _, _, _) = exp.get_data()
noisy_dataset = LocalDatasetProvider(
x_train, y_train, shuffle_seed=self.conf.data_shuffle_seed)
all_rs = []
bad_min_weight_snapshots = []
# Training model on the dataset with 50% labels randomly flipped, while
# keeping intermediate weights
for (p, model) in exp.train(noisy_dataset):
init_weights = model.weights.eval()
bad_min_weight_snapshots.append(init_weights)
# Training & evaluating models initialized from intermediate weights
for (p, init_weights) in enumerate(bad_min_weight_snapshots):
tf.logging.info(
"""Initializing weights and running actual experiment from
weights of noisy experiment at pass %d.""",
p)
exp = self.subexp_factory(self.conf)
exp.is_persistent_experiment = False
exp.init_weights = init_weights
rs = exp.run()
rs["bad_min_branchout_pass"] = p
all_rs.append(rs)
aggregated_rs = aggregate_dicts(all_rs)
self.save(aggregated_rs)
w_l2_norm_at_bad_min = np.linalg.norm(bad_min_weight_snapshots[-1])
dim = len(bad_min_weight_snapshots[-1])
new_init_w = truncnorm(
a=-2 / self.conf.init_stddev,
b=2 / self.conf.init_stddev,
scale=self.conf.init_stddev).rvs(size=dim).astype(np.float32)
new_init_w = (
new_init_w / np.linalg.norm(new_init_w)) * w_l2_norm_at_bad_min
conf = copy(self.conf)
exp = self.subexp_factory(conf)
exp.is_persistent_experiment = False
exp.init_weights = new_init_w
rs = exp.run()
rs["blown_up_stddev"] = True
self.conf.result_filename += "_blown_up_stddev"
self.save(rs)
return aggregated_rs
| 32.836735 | 75 | 0.724984 | 2,215 | 0.688316 | 0 | 0 | 0 | 0 | 0 | 0 | 1,071 | 0.332815 |
3ecdb707d9b5224c78e8710bc0080bbb309fdaf0 | 279 | py | Python | config.py | DiagnoSkin/diagnoskin-server | e1cae10423323cc681d6acf6cc5d1511e6e2cae5 | [
"Apache-2.0"
]
| null | null | null | config.py | DiagnoSkin/diagnoskin-server | e1cae10423323cc681d6acf6cc5d1511e6e2cae5 | [
"Apache-2.0"
]
| 4 | 2021-06-08T20:42:49.000Z | 2022-03-12T00:08:54.000Z | config.py | DiagnoSkin/diagnoskin-server | e1cae10423323cc681d6acf6cc5d1511e6e2cae5 | [
"Apache-2.0"
]
| null | null | null | import json
class Config:
def __init__(self, configPath):
with open(configPath) as configFile:
configFileContent = json.load(configFile)
self.imageHeight = configFileContent['imageHeight']
self.imageWidth = configFileContent['imageWidth'] | 34.875 | 59 | 0.698925 | 266 | 0.953405 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 0.089606 |
3ece59f5395837726a33f7c182a3a996e31afa97 | 699 | py | Python | World 1/If...Else/ex029 - Eletronic Radar.py | MiguelChichorro/PythonExercises | 3b2726e7d9ef92c1eb6b977088692c42a2a7b86e | [
"MIT"
]
| 2 | 2021-04-23T19:18:06.000Z | 2021-05-15T17:45:21.000Z | World 1/If...Else/ex029 - Eletronic Radar.py | MiguelChichorro/PythonExercises | 3b2726e7d9ef92c1eb6b977088692c42a2a7b86e | [
"MIT"
]
| 1 | 2021-05-14T00:29:23.000Z | 2021-05-14T00:29:23.000Z | World 1/If...Else/ex029 - Eletronic Radar.py | MiguelChichorro/PythonExercises | 3b2726e7d9ef92c1eb6b977088692c42a2a7b86e | [
"MIT"
]
| 1 | 2021-05-14T00:19:33.000Z | 2021-05-14T00:19:33.000Z | from time import sleep
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
v = float(input("Enter the car speed was: "))
tic = (v - 80) * 7
print("{}Loading...{}".format(colors["green"], colors["clean"]))
sleep(2)
if v > 80:
print("{}You were very fast, your speed was {} km{}".format(colors["red"], v, colors["clean"]))
print("{}Now you need to pay {} $US because of that{}".format(colors["red"], tic, colors["clean"]))
else:
print("{}You were in the right speed, you can move on{}".format(colors["green"], colors["clean"]))
| 38.833333 | 103 | 0.546495 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 354 | 0.506438 |
3ece62c6129ee74730b7e33194559a50dbbdff89 | 1,913 | py | Python | 687.longest-univalue-path.py | Lonitch/hackerRank | 84991b8340e725422bc47eec664532cc84a3447e | [
"MIT"
]
| null | null | null | 687.longest-univalue-path.py | Lonitch/hackerRank | 84991b8340e725422bc47eec664532cc84a3447e | [
"MIT"
]
| null | null | null | 687.longest-univalue-path.py | Lonitch/hackerRank | 84991b8340e725422bc47eec664532cc84a3447e | [
"MIT"
]
| null | null | null | #
# @lc app=leetcode id=687 lang=python3
#
# [687] Longest Univalue Path
#
# https://leetcode.com/problems/longest-univalue-path/description/
#
# algorithms
# Easy (34.69%)
# Likes: 1312
# Dislikes: 351
# Total Accepted: 76.5K
# Total Submissions: 218.3K
# Testcase Example: '[5,4,5,1,1,5]'
#
# Given a binary tree, find the length of the longest path where each node in
# the path has the same value. This path may or may not pass through the root.
#
# The length of path between two nodes is represented by the number of edges
# between them.
#
#
#
# Example 1:
#
# Input:
#
#
# โ 5
# โ / \
# โ 4 5
# โ / \ \
# โ 1 1 5
#
#
# Output:ย 2
#
#
#
# Example 2:
#
# Input:
#
#
# โ 1
# โ / \
# โ 4 5
# โ / \ \
# โ 4 4 5
#
#
# Output:ย 2
#
#
#
# Note: The given binary tree has not more than 10000 nodes. The height of the
# tree is not more than 1000.
#
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.ans = 0
def longestUnivaluePath(self, root: TreeNode) -> int:
def util(node,cur,l):
if node is None:
return l
else:
if node.val==cur:
left=util(node.left,cur,l+1)
right=util(node.right,cur,l+1)
self.ans = max(self.ans,left+right-2*l-2)
return max(left,right)
else:
left=util(node.left,node.val,0)
right=util(node.right,node.val,0)
self.ans = max(self.ans,left+right)
return l
util(root,2**31,0)
return self.ans
# @lc code=end
| 21.021978 | 78 | 0.504966 | 723 | 0.373643 | 0 | 0 | 0 | 0 | 0 | 0 | 1,141 | 0.589664 |
3ecfb19dcb608f2b63fc8fd0aece69c83033985f | 6,085 | py | Python | scripts/wordnet.py | WladimirSidorenko/SentimentLexicon | 0d7203b7b7e3ca5d11759fdad656f775fa5d6e95 | [
"MIT"
]
| 13 | 2016-08-03T18:46:02.000Z | 2022-02-22T22:30:19.000Z | scripts/wordnet.py | WladimirSidorenko/SentimentLexicon | 0d7203b7b7e3ca5d11759fdad656f775fa5d6e95 | [
"MIT"
]
| 2 | 2019-10-22T13:03:48.000Z | 2019-12-05T21:41:36.000Z | scripts/wordnet.py | WladimirSidorenko/SentimentLexicon | 0d7203b7b7e3ca5d11759fdad656f775fa5d6e95 | [
"MIT"
]
| 5 | 2019-12-25T13:53:18.000Z | 2020-06-05T20:47:31.000Z | #!/usr/bin/env python2.7
# -*- coding: utf-8; mode: python; -*-
"""
Module for reading and processing GemaNet files.
Constants:
POS - list of parts-of-speech present in GermaNet
RELTYPES - types of GermaNet relations
Classes:
Germanet - main class for processing GermaNet files
"""
##################################################################
# Imports
from __future__ import unicode_literals, print_function
from itertools import chain
from collections import defaultdict
import argparse
import codecs
import glob
import os
import re
import sys
import xml.etree.ElementTree as ET
##################################################################
# Variables and Constants
SKIP_RE = re.compile(r"\s+[1-9]")
ENCODING = "utf-8"
POS = [".adj", ".adv", ".noun", ".verb"]
RELSYM2NAME = {
"~": "Hyponym",
"~i": "Instance Hyponym",
"!": "Antonym",
"#m": "Member holonym",
"#p": "Part holonym",
"#s": "Substance holonym",
"$": "Verb Group",
"%m": "Member meronym",
"%p": "Part meronym",
"%s": "Substance meronym",
"&": "Similar to",
"*": "Entailment",
"+": "Derivationally related form",
"-c": "Member of this domain - TOPIC",
"-r": "Member of this domain - REGION",
"-u": "Member of this domain - USAGE",
";c": "Domain of synset - TOPIC",
";r": "Domain of synset - REGION",
";u": "Domain of synset - USAGE",
"<": "Participle of verb",
"=": "Attribute",
">": "Cause",
"@": "Hypernym",
"@i": "Instance Hypernym",
"\\": "Derived from adjective",
"^": "Also see"
}
##################################################################
# Class
class Wordnet(object):
"""
Class for reading and pocessing GermaNet files
Instance variables:
lexid2lex - mapping from lexeme IDs to lexemes
lex2lexid - mapping from lexemes to lexeme IDs
lexid2synids - mapping from lexeme IDs to synset IDs
synid2lexids - mapping from synset IDs to lexemes
synid2defexmp - mapping from synset IDs to synset definitions and examples
con_relations - adjacency lists of relations between synsets
lex_relations - adjacency lists of relations between lexemes
"""
def __init__(self, a_dir=os.getcwd()):
"""Class constructor.
@param a_dir - directory containing GermaNet files
"""
if not os.path.isdir(a_dir) or not os.access(a_dir, os.R_OK):
raise RuntimeError("Can't read from directory: {:s}".format(a_dir))
## mapping from synset IDs to synset definitions and examples
self.synid2defexmp = dict()
## mapping from synset IDs to part-of-speech categories
self.synid2pos = dict()
## mapping from synset IDs to lexemes
self.synid2lexemes = defaultdict(set)
## mapping from lexeme IDs to lexemes
self.lexeme2synids = defaultdict(set)
## adjacency lists of relations between synsets
self.relations = defaultdict(set)
# parse synsets
for ifile in chain.from_iterable(
glob.iglob(os.path.join(a_dir, "data" + ipos))
for ipos in POS):
self._parse_synsets(ifile)
assert self.lexeme2synids, \
"No synset files found in directory {:s}".format(a_dir)
def _parse_synsets(self, a_fname):
"""Parse GemaNet XML file
@param a_fname - name of input file
@return \c void
"""
ptr_sym = ""
i = w_cnt = rel_cnt = 0
ilex = toks = syn_id = pos = trg_id = trg_synid = trg_pos = None
with codecs.open(a_fname, 'r', ENCODING) as ifile:
for iline in ifile:
iline = iline.rstrip()
if SKIP_RE.match(iline):
continue
# print("iline = ", repr(iline), file=sys.stderr)
toks = iline.split()
syn_id, pos = toks[0], toks[2]
syn_id = (syn_id, pos)
self.synid2pos[syn_id] = pos
# print("syn_id =", repr(syn_id), file=sys.stderr)
# print("pos =", repr(pos), file=sys.stderr)
w_cnt = int(toks[3], 16)
# print("w_cnt =", repr(w_cnt), file=sys.stderr)
# read lexemes
for j in xrange(4, 4 + w_cnt * 2, 2):
ilex = toks[j]
self.synid2lexemes[syn_id].add(ilex)
self.lexeme2synids[ilex].add(syn_id)
# print("self.synid2lexemes[syn_id] =",
# repr(self.synid2lexemes[syn_id]), file=sys.stderr)
# print("self.lexeme2synids[ilex] =",
# repr(self.lexeme2synids[ilex]), file=sys.stderr)
# read relations
i = 4 + w_cnt * 2
rel_cnt = int(toks[i])
i += 1
# print("rel_cnt =",
# repr(rel_cnt), file=sys.stderr)
# print("i =", repr(i), file=sys.stderr)
for j in xrange(i, i + rel_cnt * 4, 4):
ptr_sym, trg_synid, trg_pos, _ = toks[j:j+4]
# print("ptr_sym =",
# repr(ptr_sym), file=sys.stderr)
# print("trg_synid =",
# repr(trg_synid), file=sys.stderr)
# print("trg_pos =",
# repr(trg_pos), file=sys.stderr)
trg_id = (trg_synid, trg_pos)
self.relations[syn_id].add((trg_id, RELSYM2NAME[ptr_sym]))
i += rel_cnt * 4
# print("i =", repr(i), file=sys.stderr)
if pos == 'v':
f_cnt = int(toks[i])
i += f_cnt * 3 + 1
assert toks[i] == '|', \
"Invalid line format '{:s}' token {:d} expected" \
" to be '|', but it is '{:s}' ".format(repr(iline), i,
repr(toks[i]))
self.synid2defexmp[syn_id] = ' '.join(toks[i + 1:])
| 35.794118 | 79 | 0.517173 | 4,434 | 0.728677 | 0 | 0 | 0 | 0 | 0 | 0 | 2,999 | 0.492851 |
3ed5304c84ec79c59f7ad03780e20d83636a1751 | 493 | py | Python | exec_ops/python/run.py | orm011/skyhookml | 0cec9011ffbece3348cf56275f027c4b5b31b4d4 | [
"MIT"
]
| null | null | null | exec_ops/python/run.py | orm011/skyhookml | 0cec9011ffbece3348cf56275f027c4b5b31b4d4 | [
"MIT"
]
| null | null | null | exec_ops/python/run.py | orm011/skyhookml | 0cec9011ffbece3348cf56275f027c4b5b31b4d4 | [
"MIT"
]
| null | null | null | import sys
sys.path.append('./python')
import skyhook.common as lib
import io
import json
import math
import numpy
import os
import os.path
import skimage.io
import struct
user_func = None
# user_func will be defined by the exec call in meta_func
def callback(*args):
return user_func(*args)
def meta_func(meta):
global user_func
# code should define a function "f"
locals = {}
exec(meta['Code'], None, locals)
user_func = locals['f']
lib.run(callback, meta_func)
| 17.607143 | 57 | 0.720081 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 111 | 0.225152 |
3ed7524764506c9bf8a8c074a4bfe30279004c01 | 36 | py | Python | example_package/model_eval.py | aaronengland/example_package | 1e45fccc27af57b9d2bb58e16e58ef57d81b656e | [
"MIT"
]
| null | null | null | example_package/model_eval.py | aaronengland/example_package | 1e45fccc27af57b9d2bb58e16e58ef57d81b656e | [
"MIT"
]
| null | null | null | example_package/model_eval.py | aaronengland/example_package | 1e45fccc27af57b9d2bb58e16e58ef57d81b656e | [
"MIT"
]
| null | null | null | # model eval
def roc_curve():
pass | 9 | 16 | 0.694444 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 12 | 0.333333 |
3ed921fc020d2c520c2bb21c3fba179cbc45d373 | 2,836 | py | Python | ducky/asm/lexer.py | happz/ducky | 1c6a875ca5a7a9cc71836bad5b7e45cc398d42ad | [
"MIT"
]
| 3 | 2015-04-25T18:25:37.000Z | 2017-08-31T20:52:29.000Z | ducky/asm/lexer.py | happz/ducky-legacy | 1c6a875ca5a7a9cc71836bad5b7e45cc398d42ad | [
"MIT"
]
| 27 | 2015-01-06T21:59:22.000Z | 2016-11-12T07:31:39.000Z | ducky/asm/lexer.py | happz/ducky-legacy | 1c6a875ca5a7a9cc71836bad5b7e45cc398d42ad | [
"MIT"
]
| 1 | 2017-05-14T18:52:34.000Z | 2017-05-14T18:52:34.000Z | import ply.lex
#
# Lexer setup
#
instructions = (
'NOP', 'INT', 'IPI', 'RETINT', 'CALL', 'RET', 'CLI', 'STI', 'HLT', 'RST', 'IDLE',
'PUSH', 'POP', 'INC', 'DEC', 'ADD', 'SUB', 'CMP', 'J', 'AND', 'OR', 'XOR', 'NOT',
'SHL', 'SHR', 'SHRS', 'LW', 'LS', 'LB', 'LI', 'LIU', 'LA', 'STW', 'STS', 'STB',
'MOV', 'SWP', 'MUL', 'UDIV', 'MOD', 'CMPU', 'CAS', 'SIS', 'DIV',
'BE', 'BNE', 'BS', 'BNS', 'BZ', 'BNZ', 'BO', 'BNO', "BL", "BLE", "BGE", "BG",
'SETE', 'SETNE', 'SETZ', 'SETNZ', 'SETO', 'SETNO', 'SETS', 'SETNS', "SETL", "SETLE", "SETGE", "SETG",
'SELE', 'SELNE', 'SELZ', 'SELNZ', 'SELS', 'SELNS', 'SELO', 'SELNO', "SELL", "SELLE", "SELGE", "SELG",
'LPM', 'CTR', 'CTW', 'FPTC'
)
math_instructions = (
'PUSHW', 'SAVEW', 'POPW', 'LOADW', 'POPUW', 'LOADUW', 'SAVE', 'LOAD',
'INCL', 'DECL', 'ADDL', 'MULL', 'DIVL', 'MODL', 'UDIVL', 'UMODL',
'DUP', 'DUP2', 'SWPL', 'DROP', 'SYMDIVL', 'SYMMODL',
'PUSHL', 'POPL'
)
directives = (
'data', 'text',
'type', 'global',
'ascii', 'byte', 'short', 'space', 'string', 'word',
'section',
'align', 'file',
'set'
)
# Construct list of tokens, and map of reserved words
tokens = instructions + math_instructions + (
'COMMA', 'COLON', 'HASH', 'LBRAC', 'RBRAC', 'DOT', 'PLUS',
'SCONST', 'ICONST',
'ID', 'REGISTER'
)
reserved_map = {
# Special registers
'sp': 'REGISTER',
'fp': 'REGISTER',
# Special instructions
'shiftl': 'SHL',
'shiftr': 'SHR',
'shiftrs': 'SHRS'
}
reserved_map.update({i.lower(): i for i in instructions})
reserved_map.update({i.lower(): i for i in math_instructions})
tokens = tokens + tuple([i.upper() for i in directives])
reserved_map.update({'.' + i: i.upper() for i in directives})
reserved_map.update({i: i.upper() for i in directives})
reserved_map.update({'r%d' % i: 'REGISTER' for i in range(0, 32)})
# Newlines
def t_NEWLINE(t):
r'\n+'
t.lexer.lineno += t.value.count('\n')
# Tokens
t_COMMA = r','
t_COLON = r':'
t_HASH = r'\#'
t_LBRAC = r'\['
t_RBRAC = r'\]'
t_DOT = r'\.'
t_PLUS = r'\+'
t_SCONST = r'\"([^\\\n]|(\\.))*?\"'
t_ICONST = r'-?(?:(?:0x[0-9a-fA-F][0-9a-fA-F]*)|(?:[0-9][0-9]*))'
def t_ID(t):
r'[a-zA-Z_\.][a-zA-Z0-9_\.]*'
t.type = reserved_map.get(t.value, 'ID')
return t
t_ignore = " \t"
def t_error(t):
from ..errors import AssemblyIllegalCharError
loc = t.lexer.location.copy()
loc.lineno = t.lineno - loc.lineno
loc.column = t.lexer.parser.lexpos_to_lineno(t.lexpos)
raise AssemblyIllegalCharError(c = t.value[0], location = loc, line = t.lexer.parser.lineno_to_line(t.lineno))
class AssemblyLexer(object):
def __init__(self):
self._lexer = ply.lex.lex()
def token(self, *args, **kwargs):
return self._lexer.token(*args, **kwargs)
def input(self, *args, **kwargs):
return self._lexer.input(*args, **kwargs)
| 27.269231 | 112 | 0.563822 | 248 | 0.087447 | 0 | 0 | 0 | 0 | 0 | 0 | 1,152 | 0.406206 |
3ed9543d76f8e0c91108d623c8ce3f5c3c426593 | 3,965 | py | Python | MyUser/api/tests/allauth_login.py | mrvafa/blog-api | cef0773b3199bfb785126ce82567fd7fc78e6c89 | [
"MIT"
]
| null | null | null | MyUser/api/tests/allauth_login.py | mrvafa/blog-api | cef0773b3199bfb785126ce82567fd7fc78e6c89 | [
"MIT"
]
| null | null | null | MyUser/api/tests/allauth_login.py | mrvafa/blog-api | cef0773b3199bfb785126ce82567fd7fc78e6c89 | [
"MIT"
]
| null | null | null | from django.test import TestCase, override_settings
from django.urls import reverse
from rest_framework.test import APIClient
from MyUser.models import User
@override_settings(ACCOUNT_EMAIL_VERIFICATION='none')
class TestAllAuthLogin(TestCase):
def setUp(self):
self.client = APIClient()
self.user_1 = {
'username': 'user1',
'email': '[email protected]',
'password1': 'm2^CexxBmsNrBx\'+',
'password2': 'm2^CexxBmsNrBx\'+'
}
self.user_2 = User.objects.create(username='user2', email='[email protected]')
self.user_2.set_password('!jX+2#~:SvX@mMz:')
self.user_2.save()
self.user_3 = User.objects.create(username='user3', email='[email protected]')
def test_ok_login(self):
res = self.client.post(reverse('rest_login'), data={'username': 'user2', 'password': '!jX+2#~:SvX@mMz:'})
self.assertEqual(200, res.status_code)
def test_ok_get_profile(self):
user_data = {'username': 'user2', 'password': '!jX+2#~:SvX@mMz:'}
token = self.client.post(reverse('rest_login'), data=user_data).json()
self.client.credentials(HTTP_AUTHORIZATION=f'Token {token["key"]}')
res = self.client.get(reverse('rest_user_details'))
self.assertEqual(200, res.status_code)
def test_ok_get_profile_check_details(self):
user_data = {'username': 'user2', 'password': '!jX+2#~:SvX@mMz:'}
token = self.client.post(reverse('rest_login'), data=user_data).json()
self.client.credentials(HTTP_AUTHORIZATION=f'Token {token["key"]}')
res = self.client.get(reverse('rest_user_details'))
result = res.json()
self.assertEqual('', result['first_name'])
self.assertEqual('', result['last_name'])
self.assertEqual('user2', result['username'])
self.assertFalse('password' in result)
def test_edit_get_profile_first_name(self):
user_data = {'username': 'user2', 'password': '!jX+2#~:SvX@mMz:'}
token = self.client.post(reverse('rest_login'), data=user_data).json()
self.client.credentials(HTTP_AUTHORIZATION=f'Token {token["key"]}')
res = self.client.patch(reverse('rest_user_details'), data={'first_name': 'Ali', 'username': 'user2'})
result = res.json()
self.assertEqual('Ali', result['first_name'])
self.assertEqual('', result['last_name'])
self.assertEqual('user2', result['username'])
def test_edit_get_profile_last_name(self):
user_data = {'username': 'user2', 'password': '!jX+2#~:SvX@mMz:'}
token = self.client.post(reverse('rest_login'), data=user_data).json()
self.client.credentials(HTTP_AUTHORIZATION=f'Token {token["key"]}')
res = self.client.patch(reverse('rest_user_details'), data={'last_name': 'last_name', 'username': 'user2'})
result = res.json()
self.assertEqual('', result['first_name'])
self.assertEqual('last_name', result['last_name'])
self.assertEqual('user2', result['username'])
def test_check_editable_email(self):
user_data = {'username': 'user2', 'password': '!jX+2#~:SvX@mMz:'}
token = self.client.post(reverse('rest_login'), data=user_data).json()
self.client.credentials(HTTP_AUTHORIZATION=f'Token {token["key"]}')
res = self.client.patch(reverse('rest_user_details'), data={'email': '[email protected]', 'username': 'user2'})
result = res.json()
self.assertEqual(User.objects.get(username='user2').email, result['email'])
def test_check_change_username_taken(self):
user_data = {'username': 'user2', 'password': '!jX+2#~:SvX@mMz:'}
token = self.client.post(reverse('rest_login'), data=user_data).json()
self.client.credentials(HTTP_AUTHORIZATION=f'Token {token["key"]}')
res = self.client.patch(reverse('rest_user_details'), data={'username': 'user3'})
self.assertEqual(400, res.status_code)
| 50.189873 | 118 | 0.64691 | 3,750 | 0.945776 | 0 | 0 | 3,804 | 0.959395 | 0 | 0 | 1,129 | 0.284741 |
3ed9a5ed8b96c7fface62084d850daafe13c098c | 1,478 | py | Python | flashcards/commands/sets.py | zergov/flashcards | 4d1b1c277585b95517ed6c00ceff7555c8c131eb | [
"MIT"
]
| 21 | 2016-06-13T00:51:49.000Z | 2021-03-20T05:04:23.000Z | flashcards/commands/sets.py | zergov/flashcards | 4d1b1c277585b95517ed6c00ceff7555c8c131eb | [
"MIT"
]
| 11 | 2016-06-10T10:17:57.000Z | 2020-01-30T15:14:35.000Z | flashcards/commands/sets.py | zergov/flashcards | 4d1b1c277585b95517ed6c00ceff7555c8c131eb | [
"MIT"
]
| 4 | 2017-01-02T13:26:21.000Z | 2021-07-07T04:20:00.000Z | """
flashcards.commands.sets
~~~~~~~~~~~~~~~~~~~
Contains the commands and subcommands related to the sets resource.
"""
import os
import click
from flashcards import sets
from flashcards import storage
@click.group('sets')
def sets_group():
"""Command related to the StudySet object """
pass
@click.command('new')
@click.option('--title', prompt='Title of the study set')
@click.option('--desc', prompt='Description for the study set (optional)')
def new(title, desc):
"""
Create a new study set.
User supplies a title and a description.
If this study set does not exist, it is created.
"""
study_set = sets.StudySet(title, desc)
filepath = storage.create_studyset_file(study_set)
# automatically select this studyset
storage.link_selected_studyset(filepath)
click.echo('Study set created !')
@click.command('select')
@click.argument('studyset')
def select(studyset):
"""
Select a studyset.
Focus on a studyset, every new added cards are going to be put directly in
this studyset.
"""
studyset_path = os.path.join(storage.studyset_storage_path(), studyset)
storage.link_selected_studyset(studyset_path)
studyset_obj = storage.load_studyset(studyset_path).load()
click.echo('Selected studyset: %s' % studyset_obj.title)
click.echo('Next created cards will be automatically added '
'to this studyset.')
sets_group.add_command(new)
sets_group.add_command(select)
| 25.482759 | 78 | 0.703654 | 0 | 0 | 0 | 0 | 1,202 | 0.813261 | 0 | 0 | 697 | 0.471583 |
3ed9dea01e0c68f96f2ada5e7ccd8ced87c473be | 329 | py | Python | legiti_challenge/feature_store_pipelines/user/__init__.py | rafaelleinio/legiti-challenge | 5f15cb759d13e23292dffd103bc63583c934bf8b | [
"MIT"
]
| 1 | 2021-04-01T19:55:51.000Z | 2021-04-01T19:55:51.000Z | legiti_challenge/feature_store_pipelines/user/__init__.py | rafaelleinio/legiti-challenge | 5f15cb759d13e23292dffd103bc63583c934bf8b | [
"MIT"
]
| null | null | null | legiti_challenge/feature_store_pipelines/user/__init__.py | rafaelleinio/legiti-challenge | 5f15cb759d13e23292dffd103bc63583c934bf8b | [
"MIT"
]
| null | null | null | """Module containing imports for user entity feature set pipelines."""
from legiti_challenge.feature_store_pipelines.user.user_chargebacks import (
UserChargebacksPipeline,
)
from legiti_challenge.feature_store_pipelines.user.user_orders import UserOrdersPipeline
__all__ = ["UserChargebacksPipeline", "UserOrdersPipeline"]
| 41.125 | 88 | 0.841945 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 115 | 0.349544 |
3eda7f92aad073987eebca83a079837bb3553721 | 5,908 | py | Python | sdf/step.py | pschou/py-sdf | 0a269ed155d026e29429d76666fb63c95d2b4b2c | [
"MIT"
]
| null | null | null | sdf/step.py | pschou/py-sdf | 0a269ed155d026e29429d76666fb63c95d2b4b2c | [
"MIT"
]
| null | null | null | sdf/step.py | pschou/py-sdf | 0a269ed155d026e29429d76666fb63c95d2b4b2c | [
"MIT"
]
| null | null | null | import numpy as np
import struct
import getpass
import struct
from datetime import datetime
edge_curve = {}
def _make_edge_curve(i,a,b,fp,v0,v1,s01):
a_str = struct.pack('<fff',a[0],a[1],a[2])
b_str = struct.pack('<fff',b[0],b[1],b[2])
f_val = a_str+b_str
r_val = b_str+a_str
if f_val in edge_curve:
n = edge_curve[f_val]
ec_dir = ".T."
elif r_val in edge_curve:
n = edge_curve[r_val]
ec_dir = ".F."
else:
fp.write("#{} = EDGE_CURVE('', #{}, #{}, #{},.T.);\n".format(i,v0,v1,s01)); n=i; i+=1
edge_curve[f_val] = n
ec_dir = ".T."
return i, n, ec_dir
def write_step(path, points, tol=0):
n = len(points) // 3
points = np.array(points, dtype='float32').reshape((-1, 3, 3))
normals = np.cross(points[:,1] - points[:,0], points[:,2] - points[:,0])
normals_len = np.linalg.norm(normals, axis=1).reshape((-1, 1))
normals /= normals_len
vec01 = points[:,1] - points[:,0]
vec01_len = np.linalg.norm(vec01, axis=1).reshape((-1, 1))
vec01 /= vec01_len
vec12 = points[:,2] - points[:,1]
vec12_len = np.linalg.norm(vec12, axis=1).reshape((-1, 1))
vec12 /= vec12_len
vec20 = points[:,0] - points[:,2]
vec20_len= np.linalg.norm(vec20, axis=1).reshape((-1, 1))
vec20 /= vec20_len
OPEN_SHELL = []
with open(path, 'w') as fp:
fp.write("ISO-10303-21;\n")
fp.write("HEADER;\n")
fp.write("FILE_DESCRIPTION(('STP203'),'2;1');\n")
fp.write("FILE_NAME('{}','{}',('{}'),('PythonSDF'),' ','pschou/py-sdf',' ');\n".format(path,datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),getpass.getuser()))
fp.write("FILE_SCHEMA(('CONFIG_CONTROL_DESIGN'));\n")
fp.write("ENDSEC;\n")
fp.write("DATA;\n")
fp.write("#1 = CARTESIAN_POINT('', (0,0,0));\n")
fp.write("#2 = DIRECTION('', (0, 0, 1));\n")
fp.write("#3 = DIRECTION('', (1, 0, 0));\n")
fp.write("#4 = AXIS2_PLACEMENT_3D('',#1,#2,#3);\n")
i = 5
for j in range(n):
if any([vec01_len[j] < tol, vec12_len[j] < tol, vec20_len[j] < tol, normals_len[j] < tol]):
continue
#fp.write("#{} ".format(i))
fp.write("#{} = CARTESIAN_POINT('', ({},{},{}));\n".format(i,points[j,0,0],points[j,0,1],points[j,0,2])); p0=i;i+=1
fp.write("#{} = VERTEX_POINT('', #{});\n".format(i,p0)); v0=i;i+=1
fp.write("#{} = CARTESIAN_POINT('', ({},{},{}));\n".format(i,points[j,1,0],points[j,1,1],points[j,1,2])); p1=i;i+=1
fp.write("#{} = VERTEX_POINT('', #{});\n".format(i,p1)); v1=i;i+=1
fp.write("#{} = CARTESIAN_POINT('', ({},{},{}));\n".format(i,points[j,2,0],points[j,2,1],points[j,2,2])); p2=i;i+=1
fp.write("#{} = VERTEX_POINT('', #{});\n".format(i,p2)); v2=i;i+=1
#fp.write("#{} = CARTESIAN_POINT('', ({},{},{}));\n".format(i,points[j,0,0],points[j,0,1],points[j,0,2])); i+=1
#fp.write("#{} = DIRECTION('', ({}, {}, {}));\n".format(i, normals[j,0],normals[j,1],normals[j,2]); i+=1
fp.write("#{} = DIRECTION('', ({}, {}, {}));\n".format(i, vec01[j,0],vec01[j,1],vec01[j,2])); d01=i; i+=1
fp.write("#{} = VECTOR('',#{},1);\n".format(i,d01)); v01=i; i+=1
fp.write("#{} = LINE('',#{}, #{});\n".format(i,p0,v01)); L01=i; i+=1
fp.write("#{} = SURFACE_CURVE('', #{});\n".format(i,L01)); s01=i; i+=1
i, ec01, ec_dir01 = _make_edge_curve(i,points[j,0,:],points[j,1,:],fp,v0,v1,s01)
fp.write("#{} = DIRECTION('', ({}, {}, {}));\n".format(i, vec12[j,0],vec12[j,1],vec12[j,2])); d12=i; i+=1
fp.write("#{} = VECTOR('',#{},1);\n".format(i,d12)); v12=i; i+=1
fp.write("#{} = LINE('',#{}, #{});\n".format(i,p1,v12)); L12=i; i+=1
fp.write("#{} = SURFACE_CURVE('', #{});\n".format(i,L12)); s12=i; i+=1
#fp.write("#{} = EDGE_CURVE('', #{}, #{}, #{},.T.);\n".format(i,v1,v2,s12)); ec12=i; i+=1
i, ec12, ec_dir12 = _make_edge_curve(i,points[j,1,:],points[j,2,:],fp,v1,v2,s12)
fp.write("#{} = DIRECTION('', ({}, {}, {}));\n".format(i, vec20[j,0],vec20[j,1],vec20[j,2])); d20=i; i+=1
fp.write("#{} = VECTOR('',#{},1);\n".format(i,d20)); v20=i; i+=1
fp.write("#{} = LINE('',#{}, #{});\n".format(i,p2,v20)); L20=i; i+=1
fp.write("#{} = SURFACE_CURVE('', #{});\n".format(i,L20)); s20=i; i+=1
#fp.write("#{} = EDGE_CURVE('', #{}, #{}, #{},.T.);\n".format(i,v2,v0,s20)); ec20=i; i+=1
i, ec20, ec_dir20 = _make_edge_curve(i,points[j,2,:],points[j,0,:],fp,v2,v0,s20)
fp.write("#{} = ORIENTED_EDGE('',*,*,#{},{});\n".format(i,ec01,ec_dir01)); oe01=i; i+=1
fp.write("#{} = ORIENTED_EDGE('',*,*,#{},{});\n".format(i,ec12,ec_dir12)); oe12=i; i+=1
fp.write("#{} = ORIENTED_EDGE('',*,*,#{},{});\n".format(i,ec20,ec_dir20)); oe20=i; i+=1
fp.write("#{} = DIRECTION('', ({}, {}, {}));\n".format(i, normals[j,0],normals[j,1],normals[j,2])); n=i; i+=1
fp.write("#{} = AXIS2_PLACEMENT_3D('',#{},#{},#{});\n".format(i,p0,n,d01)); ap=i; i+=1
fp.write("#{} = PLANE('',#{});\n".format(i,ap)); plane=i; i+=1
fp.write("#{} = EDGE_LOOP('', (#{},#{},#{}));\n".format(i,oe01,oe12,oe20)); eL=i; i+=1
fp.write("#{} = FACE_BOUND('', #{},.T.);\n".format(i,eL)); fb=i; i+=1
fp.write("#{} = ADVANCED_FACE('', (#{}),#{},.T.);\n".format(i,fb,plane)); OPEN_SHELL.append(i); i+=1
fp.write("#{} = OPEN_SHELL('',(#{}));\n".format(i,",#".join([str(i) for i in OPEN_SHELL]))); osh=i; i+=1
fp.write("#{} = SHELL_BASED_SURFACE_MODEL('', (#{}));\n".format(i,osh)); sm=i; i+=1
fp.write("#{} = MANIFOLD_SURFACE_SHAPE_REPRESENTATION('', (#4, #{}));\n".format(i,sm)); i+=1
fp.write("ENDSEC;\n")
fp.write("END-ISO-10303-21;\n")
| 52.283186 | 164 | 0.488659 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,986 | 0.336154 |
3edaa008a2ee781cad3cfd27460bbf4776c643ad | 209 | py | Python | djmail/apps.py | CuriousLearner/djmail | da4cd3d4749f116b714f5f509cadc0a5d2cfb9c4 | [
"BSD-3-Clause"
]
| 53 | 2015-06-22T11:24:00.000Z | 2021-08-30T21:00:08.000Z | djmail/apps.py | CuriousLearner/djmail | da4cd3d4749f116b714f5f509cadc0a5d2cfb9c4 | [
"BSD-3-Clause"
]
| 28 | 2015-11-04T16:11:00.000Z | 2021-02-24T17:48:14.000Z | djmail/apps.py | CuriousLearner/djmail | da4cd3d4749f116b714f5f509cadc0a5d2cfb9c4 | [
"BSD-3-Clause"
]
| 22 | 2015-07-29T15:53:53.000Z | 2020-12-21T04:32:26.000Z | from django.apps import AppConfig
class DjMailConfig(AppConfig):
name = 'djmail'
verbose_name = "DjMail"
def ready(self):
from . import signals
super(DjMailConfig, self).ready()
| 19 | 41 | 0.660287 | 172 | 0.822967 | 0 | 0 | 0 | 0 | 0 | 0 | 16 | 0.076555 |
3edffdae907a0e7657c6b259ab845792ce337f54 | 349 | py | Python | flask-api/schema/change_password.py | PapamichMarios/Intranet | 65cd98d08a1a550d70e1afa4859a0b105c049817 | [
"MIT"
]
| 1 | 2021-12-21T19:13:37.000Z | 2021-12-21T19:13:37.000Z | flask-api/schema/change_password.py | PapamichMarios/Intranet | 65cd98d08a1a550d70e1afa4859a0b105c049817 | [
"MIT"
]
| null | null | null | flask-api/schema/change_password.py | PapamichMarios/Intranet | 65cd98d08a1a550d70e1afa4859a0b105c049817 | [
"MIT"
]
| null | null | null | from marshmallow import Schema, fields, validate
class ChangePasswordSchema(Schema):
id = fields.Number(attribute="id")
oldPassword = fields.String(attribute="old_password", validate=validate.Length(min=8, max=256), required=True)
password = fields.String(attribute="password", validate=validate.Length(min=8, max=256), required=True)
| 43.625 | 114 | 0.762178 | 297 | 0.851003 | 0 | 0 | 0 | 0 | 0 | 0 | 28 | 0.080229 |
3ee1169f26e39df8113aa1b6b00e7646bd86f543 | 6,100 | py | Python | ros/src/tl_detector/light_classification/tl_classifier.py | jkoloda/CarND-Capstone | 79ccd31930f5aab307a16db7b6c799a2ea54dc41 | [
"MIT"
]
| null | null | null | ros/src/tl_detector/light_classification/tl_classifier.py | jkoloda/CarND-Capstone | 79ccd31930f5aab307a16db7b6c799a2ea54dc41 | [
"MIT"
]
| null | null | null | ros/src/tl_detector/light_classification/tl_classifier.py | jkoloda/CarND-Capstone | 79ccd31930f5aab307a16db7b6c799a2ea54dc41 | [
"MIT"
]
| null | null | null | from styx_msgs.msg import TrafficLight
import tensorflow as tf
import numpy as np
import rospy
import cv2
import os
MAX_IMAGE_WIDTH = 300
MAX_IMAGE_HEIGHT = 300
class TLClassifier(object):
"""Traffic light classifier based on a tensorflow model."""
def __init__(self, is_site=True):
"""Build, load and prepare traffic light classifier object.
Loads classifier trained on simulator or real data, depending on the
is_site flag coming from the configuration file.
"""
self.session = None
self.detection_graph = None
self.classes = {1: TrafficLight.RED,
2: TrafficLight.YELLOW,
3: TrafficLight.GREEN,
4: TrafficLight.UNKNOWN}
self.light_labels = ['RED', 'YELLOW', 'GREEN', 'UNKNOWN']
temp = os.path.dirname(os.path.realpath(__file__))
temp = temp.replace(
'ros/src/tl_detector/light_classification',
'models',
)
if is_site is False:
self.model_path = os.path.join(temp,
'frozen_inference_graph_sim.pb')
else:
self.model_path = os.path.join(temp,
'frozen_inference_graph_real.pb')
self.load_model(model_path=self.model_path)
def get_classification(self, image):
"""Determine the color of the traffic light in the image.
Args
----
image (cv::Mat): image containing the traffic light
Returns
-------
int: ID of traffic light color
(specified in styx_msgs/TrafficLight)
"""
class_idx, confidence = self.predict(image)
return class_idx
def load_model(self, model_path):
"""Load classifier (graph and session)."""
self.detection_graph = tf.Graph()
with tf.Session(graph=self.detection_graph) as sess:
self.session = sess
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(model_path, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
def predict(self, image_np, min_score_thresh=0.5):
"""Predict traffic light state from image.
Parameters
----------
image_np : ndarray
Input image.
min_score_threshold : float
Confidence threshold for traffic light classification.
Returns
-------
light : TrafficLight
Light color of traffic light detected on input image.
score : float
Classification confidence score.
"""
image_tensor = self.detection_graph.\
get_tensor_by_name('image_tensor:0')
detection_boxes = self.detection_graph.\
get_tensor_by_name('detection_boxes:0')
detection_scores = self.detection_graph.\
get_tensor_by_name('detection_scores:0')
detection_classes = self.detection_graph.\
get_tensor_by_name('detection_classes:0')
num_detections = self.detection_graph.\
get_tensor_by_name('num_detections:0')
image_np = self.process_image(image_np)
input = [detection_boxes, detection_scores, detection_classes]
(boxes, scores, classes) = self.session.run(
input,
feed_dict={image_tensor: np.expand_dims(image_np, axis=0)})
scores = np.squeeze(scores)
classes = np.squeeze(classes)
boxes = np.squeeze(boxes)
# Traffic light state decision
# In case mutliple traffic lights are detected (as e.g. is the case of
# the simulator) we select the light with the highest accumulated score
accumulated_scores = np.zeros(len(self.classes))
accumulated_classes = np.zeros(len(self.classes))
for ii, score in enumerate(scores):
if score > min_score_thresh:
# light_class = self.classes[classes[ii]]
# return light_class, score
rospy.loginfo(self.light_labels[int(classes[ii] - 1)])
accumulated_scores[classes[ii] - 1] += score
accumulated_classes[classes[ii] - 1] += 1
if np.sum(accumulated_scores) > 0:
light_class_idx = np.argmax(accumulated_scores) + 1
confidence = accumulated_scores[light_class_idx - 1] / \
float(accumulated_classes[light_class_idx - 1])
return self.classes[light_class_idx], confidence
else:
return None, None
def process_image(self, img):
"""Pre-process imae so it can be passed directly to classifier.
Pre-processing consists of shrinkng the image to default maximum size
and converting in to RGB format (assuming that input is BGR).
Parameters
----------
img : ndarray
Input image to be processed.
Returns
-------
img : ndarray
Processed image.
"""
img = cv2.resize(img, (MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT))
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return img
def shrink_image(self, img):
"""Shrink image if bigger than default maximum dimensions.
Aspect ratio is kept. If the image is smaller it is return as it is.
Parameters
----------
img : ndarray
Input image to be shrinked if necessary.
Returns
-------
img : ndarray
Shrinked image.
"""
height, width = img.shape[:2]
if MAX_IMAGE_HEIGHT < height or MAX_IMAGE_WIDTH < width:
scaling_factor = np.min(MAX_IMAGE_HEIGHT / float(height),
MAX_IMAGE_WIDTH / float(width))
img = cv2.resize(img, None, fx=scaling_factor,
fy=scaling_factor, interpolation=cv2.INTER_AREA)
return img
| 32.972973 | 79 | 0.587869 | 5,934 | 0.972787 | 0 | 0 | 0 | 0 | 0 | 0 | 2,284 | 0.374426 |
3ee194cecfeab3512df97384ab2ebd0feb3a1a32 | 3,554 | py | Python | esp.py | dries007/MicroPythonUtils | fba10989713f85ce4afa598c550737720df24648 | [
"MIT"
]
| null | null | null | esp.py | dries007/MicroPythonUtils | fba10989713f85ce4afa598c550737720df24648 | [
"MIT"
]
| null | null | null | esp.py | dries007/MicroPythonUtils | fba10989713f85ce4afa598c550737720df24648 | [
"MIT"
]
| null | null | null | import os
import serial
import time
import binascii
import textwrap
import re
from wifi import WIFI_SSID, WIFI_PASS
def ctrl(key):
# Thank you https://github.com/zeevro/esp_file_sender/
return chr(ord(key.upper()) - ord('A') + 1)
class Esp:
def __init__(self, port, baudrate):
super().__init__()
# self.raw = serial.Serial(port, baudrate)
# if not self.raw.is_open:
# raise RuntimeError("Port {} won't open.".format(port))
def __del__(self):
self.reset()
def kill(self):
self.send(ctrl('C'), 2)
def reset(self):
# self.send(ctrl('D'), 5)
pass
def send(self, data, wait=0.100):
print(data.replace('\r\n', ''))
# self.raw.write(data.encode('ascii'))
# time.sleep(wait)
# out = self.raw.read_all()
# print(out.decode('ascii'), end="")
# return out
def settings(self, data=None, app=None):
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'boot.py'), 'rb') as f:
text = f.read().decode('ascii')
if data is None:
data = {}
data.setdefault('WIFI_SSID', WIFI_SSID)
data.setdefault('WIFI_PASS', WIFI_PASS)
for k, v in data.items():
text += '{} = {!r}\r\n'.format(k, v)
self.save_file('boot.py', text.encode('ascii'))
if app is not None:
app = app.replace('.py', '')
text = 'from boot import *\r\n'
text += "if machine.reset_cause() == SLEEP_RESET or not wait_for(timeout=5, message='To abort booting \"{}\", press GPIO0'):\r\n".format(app)
text += '\timport {}\r\n'.format(app)
text += '\t{}.main()\r\n'.format(app)
self.save_file('main.py', text.encode('ascii'))
def save_file(self, filename, text):
# self.send(ctrl('E'))
self.send('import os\r\n')
# self.send('import ubinascii\r\n')
self.send('import gc\r\n')
self.send('gc.collect()\r\n')
# self.send('os.remove("{}")\r\n'.format(filename))
self.send('f = open("{}", "wb")\r\n'.format(filename))
# for part in re.findall('.{1,100}', text.decode('ascii'), re.DOTALL):
# self.send('f.write(ubinascii.a2b_base64("{}"))\r\n'.format(binascii.b2a_base64(part.encode('ascii')).decode('ascii')[:-1]))
for part in re.findall('.{1,1000}', text.decode('ascii'), re.DOTALL):
self.send('f.write({!r})\r\n'.format(part))
# self.send('f.write({!r})\r\n'.format(text))
self.send('f.close()\r\n')
self.send('del f\r\n')
self.send('gc.collect()\r\n')
# self.send(ctrl('D'))
def delete(self, *params):
self.send('import os\r\n')
for param in params:
self.send('os.remove({!r})\r\n'.format(param))
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('port', help='Serial port')
parser.add_argument('-b', '--baudrate', help='Serial baudrate', type=int, default=115200)
parser.add_argument('app', help='Input file')
parser.add_argument('drivers', help='Extra driver files', nargs='*')
args = parser.parse_args()
esp = Esp(args.port, args.baudrate)
esp.settings(app=args.app)
with open('apps/' + args.app, 'rb') as in_f:
esp.save_file(args.app, in_f.read())
for file in args.drivers:
with open('drivers/' + file, 'rb') as in_f:
esp.save_file(file, in_f.read())
if __name__ == '__main__':
main()
| 32.018018 | 153 | 0.565841 | 2,599 | 0.731289 | 0 | 0 | 0 | 0 | 0 | 0 | 1,328 | 0.373663 |
3ee1be975102fb088be8688d19317a0aa2d3e773 | 3,909 | py | Python | dev/tools/leveleditor/pandac/libpandaodeModules.py | CrankySupertoon01/Toontown-2 | 60893d104528a8e7eb4aced5d0015f22e203466d | [
"MIT"
]
| 1 | 2021-02-13T22:40:50.000Z | 2021-02-13T22:40:50.000Z | dev/tools/leveleditor/pandac/libpandaodeModules.py | CrankySupertoonArchive/Toontown-2 | 60893d104528a8e7eb4aced5d0015f22e203466d | [
"MIT"
]
| 1 | 2018-07-28T20:07:04.000Z | 2018-07-30T18:28:34.000Z | dev/tools/leveleditor/pandac/libpandaodeModules.py | CrankySupertoonArchive/Toontown-2 | 60893d104528a8e7eb4aced5d0015f22e203466d | [
"MIT"
]
| 2 | 2019-12-02T01:39:10.000Z | 2021-02-13T22:41:00.000Z | from extension_native_helpers import *
Dtool_PreloadDLL('libpandaode')
from libpandaode import *
from extension_native_helpers import *
Dtool_PreloadDLL('libpanda')
from libpanda import *
def convert(self):
if self.getClass() == OdeGeom.GCSphere:
return self.convertToSphere()
elif self.getClass() == OdeGeom.GCBox:
return self.convertToBox()
elif self.getClass() == OdeGeom.GCCappedCylinder:
return self.convertToCappedCylinder()
elif self.getClass() == OdeGeom.GCPlane:
return self.convertToPlane()
elif self.getClass() == OdeGeom.GCRay:
return self.convertToRay()
elif self.getClass() == OdeGeom.GCTriMesh:
return self.convertToTriMesh()
elif self.getClass() == OdeGeom.GCSimpleSpace:
return self.convertToSimpleSpace()
elif self.getClass() == OdeGeom.GCHashSpace:
return self.convertToHashSpace()
elif self.getClass() == OdeGeom.GCQuadTreeSpace:
return self.convertToQuadTreeSpace()
Dtool_funcToMethod(convert, OdeGeom)
del convert
def getConvertedSpace(self):
return self.getSpace().convert()
Dtool_funcToMethod(getConvertedSpace, OdeGeom)
del getConvertedSpace
def getAABounds(self):
min = Point3()
max = Point3()
self.getAABB(min, max)
return (min, max)
Dtool_funcToMethod(getAABounds, OdeGeom)
del getAABounds
from extension_native_helpers import *
Dtool_PreloadDLL('libpanda')
from libpanda import *
def convert(self):
if self.getClass() == OdeGeom.GCSimpleSpace:
return self.convertToSimpleSpace()
elif self.getClass() == OdeGeom.GCHashSpace:
return self.convertToHashSpace()
elif self.getClass() == OdeGeom.GCQuadTreeSpace:
return self.convertToQuadTreeSpace()
Dtool_funcToMethod(convert, OdeSpace)
del convert
def getConvertedGeom(self, index):
return self.getGeom(index).convert()
Dtool_funcToMethod(getConvertedGeom, OdeSpace)
del getConvertedGeom
def getConvertedSpace(self):
return self.getSpace().convert()
Dtool_funcToMethod(getConvertedSpace, OdeSpace)
del getConvertedSpace
def getAABounds(self):
min = Point3()
max = Point3()
self.getAABB(min, max)
return (min, max)
Dtool_funcToMethod(getAABounds, OdeSpace)
del getAABounds
from extension_native_helpers import *
Dtool_PreloadDLL('libpanda')
from libpanda import *
def attach(self, body1, body2):
if body1 and body2:
self.attachBodies(body1, body2)
elif body1 and not body2:
self.attachBody(body1, 0)
elif not body1 and body2:
self.attachBody(body2, 1)
Dtool_funcToMethod(attach, OdeJoint)
del attach
def convert(self):
if self.getJointType() == OdeJoint.JTBall:
return self.convertToBall()
elif self.getJointType() == OdeJoint.JTHinge:
return self.convertToHinge()
elif self.getJointType() == OdeJoint.JTSlider:
return self.convertToSlider()
elif self.getJointType() == OdeJoint.JTContact:
return self.convertToContact()
elif self.getJointType() == OdeJoint.JTUniversal:
return self.convertToUniversal()
elif self.getJointType() == OdeJoint.JTHinge2:
return self.convertToHinge2()
elif self.getJointType() == OdeJoint.JTFixed:
return self.convertToFixed()
elif self.getJointType() == OdeJoint.JTNull:
return self.convertToNull()
elif self.getJointType() == OdeJoint.JTAMotor:
return self.convertToAMotor()
elif self.getJointType() == OdeJoint.JTLMotor:
return self.convertToLMotor()
elif self.getJointType() == OdeJoint.JTPlane2d:
return self.convertToPlane2d()
Dtool_funcToMethod(convert, OdeJoint)
del convert
from extension_native_helpers import *
Dtool_PreloadDLL('libpanda')
from libpanda import *
def getConvertedJoint(self, index):
return self.getJoint(index).convert()
Dtool_funcToMethod(getConvertedJoint, OdeBody)
del getConvertedJoint
| 27.921429 | 53 | 0.724738 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 53 | 0.013558 |
3ee350f95efe4a8c2344a53f97be58f2e3f0dcc2 | 1,087 | py | Python | view_note.py | pushkar-anand/make-a-note | ca129dd1df1b62faad0c451e0818742bb1b1bc08 | [
"Apache-2.0"
]
| 1 | 2018-10-02T07:09:29.000Z | 2018-10-02T07:09:29.000Z | view_note.py | pushkar-anand/make-a-note | ca129dd1df1b62faad0c451e0818742bb1b1bc08 | [
"Apache-2.0"
]
| 3 | 2018-10-01T13:40:13.000Z | 2019-05-02T23:17:52.000Z | view_note.py | pushkar-anand/make-a-note | ca129dd1df1b62faad0c451e0818742bb1b1bc08 | [
"Apache-2.0"
]
| 6 | 2018-10-02T07:09:30.000Z | 2019-06-09T17:09:49.000Z | import gi
import json
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class NewNoteWindow(Gtk.Window):
def __init__(self, nid):
Gtk.Window.__init__(self, title="Note")
with open('notes.json') as data_file:
data = json.load(data_file)
notes = data["notes"]
#Looping through all the notes to check which note is being viewed
for note in notes:
print(note)
if note["note-id"] == nid:
self.title = note["note-title"]
self.note_text = note["note-text"]
self.cat = note["note-category"]
break
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=3)
self.add(box)
self.label = Gtk.Label()
self.label.set_markup("<big><b>"+self.title+"</b></big>")
box.pack_start(self.label, True, True, 0)
self.label = Gtk.Label(self.note_text)
self.label.set_line_wrap(True)
self.label.set_justify(Gtk.Justification.FILL)
box.pack_start(self.label, True, True, 0)
| 30.194444 | 74 | 0.589696 | 998 | 0.918123 | 0 | 0 | 0 | 0 | 0 | 0 | 170 | 0.156394 |
3ee37804938d5d76c8a9bfe4608d76c629788f81 | 4,588 | py | Python | homeserver/voice_control/voice_controller.py | miikama/home-server | 07a9dbb9438e3c316c37cb52ca3c709d0b059af1 | [
"MIT"
]
| null | null | null | homeserver/voice_control/voice_controller.py | miikama/home-server | 07a9dbb9438e3c316c37cb52ca3c709d0b059af1 | [
"MIT"
]
| 1 | 2019-11-30T10:59:28.000Z | 2019-11-30T10:59:28.000Z | homeserver/voice_control/voice_controller.py | miikama/home-server | 07a9dbb9438e3c316c37cb52ca3c709d0b059af1 | [
"MIT"
]
| null | null | null |
from homeserver.voice_control.google_speech import GoogleVoiceRecognition
from homeserver.voice_control.snowboy.snowboydecoder import HotwordDetector, play_audio_file
#make the voicecontrol follow the device interface structure for control
from homeserver.interface import DeviceInterface, DeviceTarget
# import the DeviceCommand
from homeserver.command_handler import DeviceCommand
from homeserver import app, logger, device_handler
import datetime
import threading
class VoiceThread(threading.Thread):
def __init__(self, parent=None, **kvargs):
self.parent = parent
super(VoiceThread, self).__init__(**kvargs)
class VoiceController(DeviceInterface):
def __init__(self, start=True):
#### variables for the DeviceInterface ###
self.name="Voice Control"
self.connected = False
self.is_on = False
self.running = False
self._devices = []
self.targets = set('voice_control')
self.commands = [DeviceTarget(self.targets, "toggle", self.toggle_detection)]
self.dev_id = 200000 #TODO: read this from some config or smth
### ############# ###
self.google_recognizer = GoogleVoiceRecognition(app.config['GOOGLE_CREDENTIALS'])
#a list of strings to help google speect to text
self.google_keyphrases = device_handler.get_voice_keys()
self.interrupted = False
#some parameters, seem okay for two word command
self.silent_count_threshold = 2
self.recording_timeout = 10
# param to the snowboy detector
self.sensitivity = 0.5
self.model = app.config['SNOWBOY_MODEL']
self.recording_path = app.config['AUDIO_PATH_AFTER_DETECTION']
# the keyword detector is initialized in the start detector
self.detector = None
self.vthread = None
self.voice_callbacks = {}
if start:
self.start_detector()
def initialize_detector(self):
logger.info("model path: {}".format(self.model))
self.detector = HotwordDetector(self.model, sensitivity=self.sensitivity)
#set the path of the audio file saved
self.detector.set_recording_filepath(self.recording_path)
#the voicethread
self.vthread = VoiceThread(target=self._start_detection, parent=self)
def start_detector(self):
"""
Method to be called outside the VoiceController class to start
the detection.
"""
self.initialize_detector()
self.vthread.start()
self.is_on = True
self.connected = True
self.running = True
logger.info('Keyword detector started')
def _start_detection(self):
# main loop
self.detector.start(detected_callback=self.detection_callback,
interrupt_check=self.interrupt_callback,
sleep_time=0.03,
audio_recorder_callback=self.audio_recorded_callback,
silent_count_threshold=self.silent_count_threshold,
recording_timeout=self.recording_timeout)
def detection_callback(self):
"""This is called when the hot word is detected, this just logs the time
keyword is detected. The actual handling is done after audio is recorder
in audio detection callback
"""
logger.debug("Keyword detected at {}".format(datetime.datetime.now().isoformat() ) )
def audio_recorded_callback(self, fname):
"""
Called when after detecting keyword an audioclip has done recorded and saved
recognizes what was said and then acts on the interpreted audio
"""
command_string = self.google_recognizer.interpret_command(fname,
keyphrases=self.google_keyphrases)
logger.debug("command_string: {}".format(command_string))
if command_string:
command = DeviceCommand.command_from_string(command_string)
logger.debug("sending command to device_handler: {}".format(command))
device_handler.handle_voice_command(command)
def toggle_detection(self):
if self.running:
self.stop_detection()
else:
self.start_detector()
def stop_detection(self):
logger.info("Stopping voice detection")
self.interrupted = True
self.vthread.join()
self.running = False
self.is_on = False
logger.info("Voice detection halted")
def interrupt_callback(self):
return self.interrupted
def command_subjects(self,command, *args):
"""Base methods, common error checking for all base classes implemented here"""
super().command_subjects(command)
#parse command
if len(command.arguments) < 1:
return
action = command.arguments[0]
func = None
# match the action in the command to the commands of this class
for command in self.commands:
if action == command.action:
func = command.action_func
break
if func is not None:
func()
| 24.275132 | 92 | 0.735833 | 4,101 | 0.893854 | 0 | 0 | 0 | 0 | 0 | 0 | 1,322 | 0.288143 |
3ee3d2c54d6989f6ad2059cbf79a527aa7c5bc22 | 451 | py | Python | main.py | CSULB-RMC/testing-repo | f0f82f43dadd91c2e6b968cb6ed13b50df4505c2 | [
"Unlicense"
]
| null | null | null | main.py | CSULB-RMC/testing-repo | f0f82f43dadd91c2e6b968cb6ed13b50df4505c2 | [
"Unlicense"
]
| null | null | null | main.py | CSULB-RMC/testing-repo | f0f82f43dadd91c2e6b968cb6ed13b50df4505c2 | [
"Unlicense"
]
| null | null | null | # Name: HELLO WORLD
# Author: Fenteale
#
# Notes:
# This is just a tiny program meant to showcase what
# a repository will look like when downloaded through
# github.
print("Hello World!")
print("This is just meant to be a tiny program to show off what a repo looks like.")
inp = input("Type something here: ")
print("You typed:", inp)
print("Ok this is another test.")
print("This is a change from the testing branch. Here is even more info.")
| 23.736842 | 84 | 0.716186 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 380 | 0.842572 |
3ee5a364faab5171c5ce76299e1bdd425fb0f34b | 188 | py | Python | arduinowithpyFirmata.py | xfzlun/WinUIAutomation | 0f94388671cf0aacbc8499293b7dd31ddfa205fa | [
"MIT"
]
| null | null | null | arduinowithpyFirmata.py | xfzlun/WinUIAutomation | 0f94388671cf0aacbc8499293b7dd31ddfa205fa | [
"MIT"
]
| null | null | null | arduinowithpyFirmata.py | xfzlun/WinUIAutomation | 0f94388671cf0aacbc8499293b7dd31ddfa205fa | [
"MIT"
]
| null | null | null | from pyfirmata import Arduino, util
import time
board = Arduino('/dev/ttyACM0')
while 1:
board.digital[13].write(0)
time.sleep(1)
board.digital[13].write(1)
time.sleep(1)
| 18.8 | 35 | 0.680851 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 14 | 0.074468 |
3ee683dea81950011c4a8893e44e207f0c0558cc | 275 | py | Python | 2016/Day5/tests.py | dh256/adventofcode | 428eec13f4cbf153333a0e359bcff23070ef6d27 | [
"MIT"
]
| null | null | null | 2016/Day5/tests.py | dh256/adventofcode | 428eec13f4cbf153333a0e359bcff23070ef6d27 | [
"MIT"
]
| null | null | null | 2016/Day5/tests.py | dh256/adventofcode | 428eec13f4cbf153333a0e359bcff23070ef6d27 | [
"MIT"
]
| null | null | null | import pytest
from Door import Door
def test_find_password():
door_id = "abc"
door = Door(door_id)
assert(door.find_password() == "18f47a30")
def test_find_password2():
door_id = "abc"
door = Door(door_id)
assert(door.find_password2() == "05ace8e3") | 22.916667 | 47 | 0.676364 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 30 | 0.109091 |
3ee8fa63da0e0bfe5eb55277fd9f507afe7bfefe | 1,528 | py | Python | CondTools/SiPixel/test/SiPixelCPEGenericErrorParmReader_cfg.py | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
]
| 13 | 2015-11-30T15:49:45.000Z | 2022-02-08T16:11:30.000Z | CondTools/SiPixel/test/SiPixelCPEGenericErrorParmReader_cfg.py | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
]
| 640 | 2015-02-11T18:55:47.000Z | 2022-03-31T14:12:23.000Z | CondTools/SiPixel/test/SiPixelCPEGenericErrorParmReader_cfg.py | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
]
| 51 | 2015-08-11T21:01:40.000Z | 2022-03-30T07:31:34.000Z | import FWCore.ParameterSet.Config as cms
process = cms.Process("SiPixelCPEGenericErrorParmReaderTest")
process.load("CondCore.DBCommon.CondDBSetup_cfi")
process.load("FWCore.MessageService.MessageLogger_cfi")
process.source = cms.Source("EmptySource")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(1)
)
#Uncomment these two lines to get from the global tag
#process.load('Configuration/StandardSequences/FrontierConditions_GlobalTag_cff')
#process.GlobalTag.globaltag = 'IDEAL_30X::All'
process.PoolDBESSource = cms.ESSource("PoolDBESSource",
process.CondDBSetup,
loadAll = cms.bool(True),
toGet = cms.VPSet(cms.PSet(
record = cms.string('SiPixelCPEGenericErrorParmRcd'),
tag = cms.string('SiPixelCPEGenericErrorParm')
)),
DBParameters = cms.PSet(
messageLevel = cms.untracked.int32(0),
authenticationPath = cms.untracked.string('.')
),
catalog = cms.untracked.string('file:PoolFileCatalog.xml'),
timetype = cms.string('runnumber'),
connect = cms.string('sqlite_file:siPixelCPEGenericErrorParm.db')
)
process.reader = cms.EDAnalyzer("SiPixelCPEGenericErrorParmReader")
process.myprint = cms.OutputModule("AsciiOutputModule")
process.p = cms.Path(process.reader)
| 40.210526 | 103 | 0.620419 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 519 | 0.33966 |
3eea8ad1e4ebfd2294a6137803d28554a3bc0130 | 5,621 | py | Python | tools/perf/benchmarks/smoothness.py | justremotephone/android_external_chromium_org | 246856e61da7acf5494076c74198f2aea894a721 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
]
| 2 | 2020-01-25T10:18:18.000Z | 2021-01-23T15:29:56.000Z | tools/perf/benchmarks/smoothness.py | justremotephone/android_external_chromium_org | 246856e61da7acf5494076c74198f2aea894a721 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
]
| null | null | null | tools/perf/benchmarks/smoothness.py | justremotephone/android_external_chromium_org | 246856e61da7acf5494076c74198f2aea894a721 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
]
| 1 | 2020-11-04T07:24:13.000Z | 2020-11-04T07:24:13.000Z | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry import test
from benchmarks import silk_flags
from measurements import smoothness
import page_sets
@test.Disabled # crbug.com/368767
class SmoothnessTop25(test.Test):
"""Measures rendering statistics while scrolling down the top 25 web pages.
http://www.chromium.org/developers/design-documents/rendering-benchmarks"""
test = smoothness.Smoothness
page_set = page_sets.Top25PageSet
@test.Disabled('linux', 'mac', 'win') # crbug.com/368767
class SmoothnessToughCanvasCases(test.Test):
test = smoothness.Smoothness
page_set = page_sets.ToughCanvasCasesPageSet
@test.Disabled # crbug.com/373812
class SmoothnessToughWebGLCases(test.Test):
test = smoothness.Smoothness
page_set = page_sets.ToughWebglCasesPageSet
class SmoothnessMaps(test.Test):
test = smoothness.Smoothness
page_set = page_sets.MapsPageSet
class SmoothnessKeyMobileSites(test.Test):
"""Measures rendering statistics while scrolling down the key mobile sites.
http://www.chromium.org/developers/design-documents/rendering-benchmarks"""
test = smoothness.Smoothness
page_set = page_sets.KeyMobileSitesPageSet
@test.Disabled('android', 'mac') # crbug.com/350692, crbug.com/368767
class SmoothnessToughAnimationCases(test.Test):
test = smoothness.Smoothness
page_set = page_sets.ToughAnimationCasesPageSet
class SmoothnessKeySilkCases(test.Test):
"""Measures rendering statistics for the key silk cases without GPU
rasterization
"""
test = smoothness.Smoothness
page_set = page_sets.KeySilkCasesPageSet
class SmoothnessFastPathKeySilkCases(test.Test):
"""Measures rendering statistics for the key silk cases without GPU
rasterization using bleeding edge rendering fast paths.
"""
tag = 'fast_path'
test = smoothness.Smoothness
page_set = page_sets.KeySilkCasesPageSet
def CustomizeBrowserOptions(self, options):
silk_flags.CustomizeBrowserOptionsForFastPath(options)
@test.Disabled('android') # crbug.com/363783
class SmoothnessGpuRasterizationTop25(test.Test):
"""Measures rendering statistics for the top 25 with GPU rasterization
"""
tag = 'gpu_rasterization'
test = smoothness.Smoothness
page_set = page_sets.Top25PageSet
def CustomizeBrowserOptions(self, options):
silk_flags.CustomizeBrowserOptionsForGpuRasterization(options)
@test.Disabled('android') # crbug.com/363783
class SmoothnessGpuRasterizationKeyMobileSites(test.Test):
"""Measures rendering statistics for the key mobile sites with GPU
rasterization
"""
tag = 'gpu_rasterization'
test = smoothness.Smoothness
page_set = page_sets.KeyMobileSitesPageSet
def CustomizeBrowserOptions(self, options):
silk_flags.CustomizeBrowserOptionsForGpuRasterization(options)
class SmoothnessGpuRasterizationKeySilkCases(test.Test):
"""Measures rendering statistics for the key silk cases with GPU rasterization
"""
tag = 'gpu_rasterization'
test = smoothness.Smoothness
page_set = page_sets.KeySilkCasesPageSet
def CustomizeBrowserOptions(self, options):
silk_flags.CustomizeBrowserOptionsForGpuRasterization(options)
class SmoothnessFastPathGpuRasterizationKeySilkCases(
SmoothnessGpuRasterizationKeySilkCases):
"""Measures rendering statistics for the key silk cases with GPU rasterization
using bleeding edge rendering fast paths.
"""
tag = 'fast_path_gpu_rasterization'
test = smoothness.Smoothness
page_set = page_sets.KeySilkCasesPageSet
def CustomizeBrowserOptions(self, options):
super(SmoothnessFastPathGpuRasterizationKeySilkCases, self). \
CustomizeBrowserOptions(options)
silk_flags.CustomizeBrowserOptionsForFastPath(options)
@test.Enabled('android')
class SmoothnessToughPinchZoomCases(test.Test):
"""Measures rendering statistics for pinch-zooming into the tough pinch zoom
cases
"""
test = smoothness.Smoothness
page_set = page_sets.ToughPinchZoomCasesPageSet
@test.Disabled # crbug.com/370725
class SmoothnessPolymer(test.Test):
"""Measures rendering statistics for Polymer cases.
"""
test = smoothness.Smoothness
page_set = page_sets.PolymerPageSet
@test.Disabled # crbug.com/370725
class SmoothnessFastPathPolymer(test.Test):
"""Measures rendering statistics for the Polymer cases without GPU
rasterization using bleeding edge rendering fast paths.
"""
tag = 'fast_path'
test = smoothness.Smoothness
page_set = page_sets.PolymerPageSet
def CustomizeBrowserOptions(self, options):
silk_flags.CustomizeBrowserOptionsForFastPath(options)
@test.Disabled # crbug.com/370725
class SmoothnessGpuRasterizationPolymer(test.Test):
"""Measures rendering statistics for the Polymer cases with GPU rasterization
"""
tag = 'gpu_rasterization'
test = smoothness.Smoothness
page_set = page_sets.PolymerPageSet
def CustomizeBrowserOptions(self, options):
silk_flags.CustomizeBrowserOptionsForGpuRasterization(options)
@test.Disabled # crbug.com/370725
class SmoothnessFastPathGpuRasterizationPolymer(
SmoothnessGpuRasterizationPolymer):
"""Measures rendering statistics for the Polymer cases with GPU rasterization
using bleeding edge rendering fast paths.
"""
tag = 'fast_path_gpu_rasterization'
test = smoothness.Smoothness
page_set = page_sets.PolymerPageSet
def CustomizeBrowserOptions(self, options):
super(SmoothnessFastPathGpuRasterizationPolymer, self). \
CustomizeBrowserOptions(options)
silk_flags.CustomizeBrowserOptionsForFastPath(options)
| 32.871345 | 80 | 0.794698 | 4,836 | 0.860345 | 0 | 0 | 3,420 | 0.608433 | 0 | 0 | 1,962 | 0.349048 |
3eeacd092135bae68f848fe55ada198c37b80c48 | 315 | py | Python | setup.py | igorccouto/robot | 67019ee1f52d5474ce36734c1e56725046471cd9 | [
"MIT"
]
| null | null | null | setup.py | igorccouto/robot | 67019ee1f52d5474ce36734c1e56725046471cd9 | [
"MIT"
]
| null | null | null | setup.py | igorccouto/robot | 67019ee1f52d5474ce36734c1e56725046471cd9 | [
"MIT"
]
| null | null | null | from setuptools import setup, find_packages
setup(name='robot',
version='1.0',
author='Igor Couto',
author_email='[email protected]',
description='A project to execute a robot that performs several actions on the browser.',
packages=find_packages(),
license='MIT'
)
| 28.636364 | 96 | 0.660317 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 126 | 0.4 |
3eec09187c14d47ed9948ca3461f050626849937 | 31,103 | py | Python | carcassonne.py | pierre-dejoue/carcassonne | 046c39fd61f17072e6d75a48ef65afa7be82a973 | [
"MIT"
]
| null | null | null | carcassonne.py | pierre-dejoue/carcassonne | 046c39fd61f17072e6d75a48ef65afa7be82a973 | [
"MIT"
]
| null | null | null | carcassonne.py | pierre-dejoue/carcassonne | 046c39fd61f17072e6d75a48ef65afa7be82a973 | [
"MIT"
]
| null | null | null | #!/usr/bin/env python
import argparse
import boundary
import functools
import graphics
import itertools
import json
import operator
import os.path
import random
import re
import secrets
import sys
import traceback
from boundary import Boundary
from boundary import Domain
from boundary import Orientation
from boundary import Vect
from collections import deque
from enum import Enum, auto
DEBUG_PRINTOUT = False
DEFAULT_TILE_SIZE = 100
SCREENSHOT_PATH = './screenshot.jpg'
DUMP_PATH = './dump.bmp'
class RiverPlacement(Enum):
USE_T = auto()
EXCLUDE_T = auto()
SHORT_RIVER = auto()
LONG_RIVER = auto()
RIVER_PLACEMENT_DEFAULT_T_POLICY = RiverPlacement.USE_T
RIVER_PLACEMENT_DEFAULT_LENGTH_POLICY = RiverPlacement.SHORT_RIVER
def warn(msg):
print('Warning: ' + msg)
def error(msg):
print('Error: ' + msg, file = sys.stderr)
exit(-1)
def override(f):
# Eye-candy decorator
return f
def handle_assertion_error():
_, _, tb = sys.exc_info()
tb_info = traceback.extract_tb(tb)
filename, line, func, text = tb_info[-1]
warn('An error occurred in file {} line {} in statement "{}"'.format(filename, line, text))
class Tile:
"""A tile (usually a game tile) defined by the description of its four sides (desc), its cardinality (max_nb) and optionally a graphical representation (img)"""
def __init__(self, desc = [None, None, None, None], max_nb = 1, img_path = '', tags = []):
self.desc = desc
self.max_nb = max_nb
self.img_path = img_path
self.img = None
self.tags = tags
def __repr__(self):
return 'Tile({})'.format(self.desc)
@classmethod
def from_json_description(cls, json_obj, basedir):
assert 'description' in json_obj.keys()
desc = json_obj['description']
max_nb = json_obj['cardinality'] if 'cardinality' in json_obj.keys() else 1
img_path = os.path.join(basedir, json_obj['img']) if 'img' in json_obj.keys() and json_obj['img'] else ''
tags = []
for id in range(10):
key = 'tag' + str(id)
if key in json_obj.keys():
tags.append(json_obj[key])
return cls(desc, max_nb, img_path, tags)
@classmethod
def from_uniform_color(cls, color, size, tag = ''):
tile = cls()
tile.img = graphics.draw_uniform_tile(color, size)
tile.tags.append(tag)
assert tile.get_size() == size
return tile
def load_image(self):
try:
self.img = graphics.load_image(self.img_path)
except Exception as e:
warn('Could not load image: {} (message: {})'.format(self.img_path, e))
self.img = None
def draw_image(self, size):
assert self.img is None
self.img = graphics.draw_game_tile(self.desc, size)
assert self.get_size() == size
def get_size(self):
if self.img is not None:
assert self.img.height() == self.img.width()
return self.img.width()
else:
return 0
def parse_tileset_description_file(json_file):
fp = None
cumul = 0
try:
fp = open(json_file, 'r')
tileset_json = json.load(fp)
assert 'tiles' in tileset_json.keys()
for tile_json in tileset_json['tiles']:
tile = Tile.from_json_description(tile_json, os.path.dirname(json_file))
assert tile.max_nb >= 0
if tile.max_nb > 0:
if 'start' in tile.tags:
assert tile.max_nb == 1
cumul += tile.max_nb
yield tile
except FileNotFoundError:
warn('Could not load file {}'.format(json_file))
except AssertionError:
handle_assertion_error()
except Exception:
warn('Error parsing file {}'.format(json_file))
raise
finally:
if fp is not None:
fp.close()
if cumul > 0:
print('Loaded {} tiles from file {}'.format(cumul, json_file))
def load_or_draw_tile_images(tileset, draw_all = False):
assert graphics.is_init()
tile_size = 0
if not draw_all:
for tile in tileset:
tile.load_image()
if tile.get_size() != 0:
if tile_size == 0:
tile_size = tile.get_size()
elif tile.get_size() != tile_size:
error('Image size of file {} ({}) does not match the previous size ({})'.format(tile.img_path, tile.get_size(), tile_size))
if tile_size == 0:
tile_size = DEFAULT_TILE_SIZE
for tile in tileset:
if tile.img is None:
tile.draw_image(tile_size)
assert tile.img is not None
return tile_size
class PositionedTile:
"""Declare a position on the grid where a tile could be placed"""
def __init__(self, pos, segments = []):
assert isinstance(pos, Vect)
self.pos = pos
if len(segments) == 1:
self.segment = segments[0] # Common segment between the current map boundary and this tile
else:
self.segment = None # Use None if unknown, or to indicate a forbidden position
@classmethod
def from_boundary_edge(cls, border, point, edge, domain = Domain.EXTERIOR):
assert isinstance(border, Boundary)
assert isinstance(point, Vect)
assert isinstance(edge, Vect)
tile_border = boundary.from_edge(point, edge, Orientation.COUNTERCLOCKWISE, domain)
pos = tile_border.bottom_left()
tile_border.rotate_to_start_with(pos)
return cls(pos, border.common_segments(tile_border))
def __repr__(self):
return 'PositionedTile(pos = {}, segment = {})'.format(self.pos, self.segment)
def get_l1_distance(self):
return self.pos.l1_distance()
def get_segment(self):
return self.segment if self.segment is not None else (0, 0, 0)
def get_segment_length(self):
(_, _, L) = self.get_segment()
return L
def iter_segment(self):
(_, j, L) = self.get_segment()
return self.get_boundary().iter_slice(j, j + L)
def iter_complement_segment(self):
(_, j, L) = self.get_segment()
tile_border = self.get_boundary()
if L == 0:
return tile_border.iter_all(j)
else:
return tile_border.iter_slice(j + L, j)
def get_boundary(self, desc = [None, None, None, None]):
return boundary.get_tile(self.pos, desc)
class PlacedTile(PositionedTile):
"""Declares a Tile placed on the grid, with its position and orientation (r)"""
def __init__(self, tile, pos, r, segment = None):
assert isinstance(tile, Tile)
PositionedTile.__init__(self, pos, [] if segment is None else [segment])
self.tile = tile
self.r = r
@override
def __repr__(self):
return 'PlacedTile(pos = {}, r = {}, segment = {}, tile = {})'.format(self.pos, self.r, self.segment, self.tile)
@classmethod
def from_positioned_tile(cls, pos_tile, tile, r):
assert isinstance(pos_tile, PositionedTile)
assert isinstance(tile, Tile)
return cls(tile, pos_tile.pos, r, pos_tile.segment)
def draw(self, display):
assert isinstance(display, graphics.GridDisplay)
assert self.tile.img is not None
display.set_tile(self.tile.img, self.pos.x, self.pos.y, self.r)
@override
def get_boundary(self):
desc = deque(self.tile.desc)
desc.rotate(self.r)
return PositionedTile.get_boundary(self, desc)
class CompositeTile:
"""A super-tile made of several unit tiles (e.g. the city of Carcasonne)"""
class Elt:
def __init__(self, tile, offset):
assert isinstance(tile, Tile)
assert isinstance(offset, Vect)
self.tile = tile
self.offset = offset
vect_re = re.compile(r'[Vv]ect_(\d+)_(\d+)')
def __init__(self):
self.elts = []
def append(self, tile):
offset = None
for tag in tile.tags:
result = self.vect_re.match(tag)
if result:
offset = Vect(int(result.group(1)), int(result.group(2)))
if offset:
self.elts.append(CompositeTile.Elt(tile, offset))
else:
warn('Could not find the offset pattern in the tags for tile {}. Tags = {}.'.format(tile, tile.tags))
def __reduce(self, fun, initializer = None):
self.elts.sort(key=operator.attrgetter('offset'))
return functools.reduce(fun, self.elts, initializer)
def draw(self, display, pos, r = 0):
assert isinstance(pos, Vect)
assert isinstance(display, graphics.GridDisplay)
def draw_elt(_, elt):
PlacedTile(elt.tile, pos + elt.offset.rotate(r), r).draw(display)
return None
self.__reduce(draw_elt)
def get_boundary(self, pos, r = 0):
assert isinstance(pos, Vect)
def merge_boundary(border, elt):
border.merge(PlacedTile(elt.tile, pos + elt.offset.rotate(r), r).get_boundary())
return border
return self.__reduce(merge_boundary, Boundary())
class TileSubset:
def __init__(self, predicate, shuffle = True, output_n = -1):
self.predicate = predicate
self.shuffle = shuffle # Shuffle result
self.output_n = output_n # If < 0, output all
def partition_iter(self, tileset_iter):
it0, it1 = itertools.tee(tileset_iter)
selection = list(filter(self.predicate, it0))
if self.shuffle:
selection = random.sample(selection, len(selection))
if self.output_n >= 0:
selection = selection[:self.output_n]
return selection, itertools.filterfalse(self.predicate, it1)
def partition(self, tileset_iter):
part1, part2_iter = self.partition_iter(tileset_iter)
return part1, list(part2_iter)
@staticmethod
def regular_start():
def pred_regular_start(tile):
return 'start' in tile.tags and 'river' not in tile.tags
return TileSubset(pred_regular_start, output_n = 1)
@staticmethod
def carcassonne_city():
def pred_city(tile):
return 'carcassonne_city' in tile.tags
return TileSubset(pred_city, shuffle = False)
@staticmethod
def river():
def pred_river(tile):
return 'river' in tile.tags
return TileSubset(pred_river, shuffle = False)
@staticmethod
def river_source(n = -1):
def pred_river_source(tile):
return 'river' in tile.tags and 'source' in tile.tags
return TileSubset(pred_river_source, output_n = n)
@staticmethod
def river_exclude_t_shaped():
def pred_river_t_shaped(tile):
return 'river' in tile.tags and list(tile.desc).count('R') == 3
return TileSubset(pred_river_t_shaped, output_n = 0)
@staticmethod
def river_not_source_nor_sink():
def pred_river_others(tile):
return 'river' in tile.tags and 'source' not in tile.tags and 'lake' not in tile.tags
return TileSubset(pred_river_others)
@staticmethod
def river_sink(n = -1):
def pred_river_sink(tile):
return 'river' in tile.tags and 'lake' in tile.tags
return TileSubset(pred_river_sink, output_n = n)
@staticmethod
def shuffle_remaining():
return TileSubset(lambda _: True)
@staticmethod
def exclude_remaining(warn_on_excluded = True):
def pred_exclude_remaining(tile):
if warn_on_excluded:
warn('Excluded tile: {}'.format(tile))
return True
return TileSubset(pred_exclude_remaining, output_n = 0)
def iterate_tile_predicates(tile_predicates, tileset_iter):
remaining = tileset_iter
for predicate in tile_predicates:
tile_subset, remaining = predicate.partition_iter(remaining)
yield tile_subset
TileSubset.exclude_remaining().partition_iter(remaining)
def iterate_tilesets(river_tileset, regular_tileset, river_tileset_period = 0, infinite = False):
river_flag = len(river_tileset) > 0
first = True
while True:
if river_flag:
if river_tileset_period == 0:
# Single use of the river tileset
if first:
yield river_tileset
else:
# Reuse the river tileset periodically
yield river_tileset
for _ in range(max(1, river_tileset_period)):
yield regular_tileset
else:
yield regular_tileset
if not infinite:
break
first = False
def shuffle_tileset(tileset, first_tileset_flag, river_placement_policies = []):
river_flag = any('river' in tile.tags for tile in tileset)
all_tiles = itertools.chain.from_iterable(itertools.repeat(tile, tile.max_nb) for tile in tileset)
if river_flag:
river_long = RiverPlacement.LONG_RIVER in river_placement_policies
river_exclude_t_shaped = RiverPlacement.EXCLUDE_T in river_placement_policies
# River sources
if river_long and not first_tileset_flag:
nb_of_sources = 0
else:
nb_of_sources = 1
# River sinks
if river_exclude_t_shaped:
nb_of_sinks = 1
else:
nb_of_sinks = 2
if river_long:
nb_of_sinks = nb_of_sinks - 1
# Predicates
tile_predicates = [
TileSubset.river_source(nb_of_sources)
]
if river_exclude_t_shaped:
tile_predicates += [
TileSubset.river_exclude_t_shaped()
]
tile_predicates += [
TileSubset.river_not_source_nor_sink(),
TileSubset.river_sink(nb_of_sinks),
]
elif first_tileset_flag:
tile_predicates = [
TileSubset.regular_start(),
TileSubset.shuffle_remaining()
]
else:
tile_predicates = [
TileSubset.shuffle_remaining()
]
return iterate_tile_predicates(tile_predicates, all_tiles)
class CandidateTiles:
def __init__(self, on_update = None, on_delete = None):
assert not on_update or callable(on_update)
assert not on_delete or callable(on_delete)
self.sorted_positions = [] # List of positions
self.tiles = dict() # Dict of position -> PositionedTile
self.nb_to_be_deleted = 0
self.on_update = on_update
self.on_delete = on_delete
def __len__(self):
return len(self.tiles)
def allocated(self):
return len(self.sorted_positions)
@staticmethod
def to_be_deleted(pos_tile):
# Ad hoc criteria to identify a tile to be deleted
return pos_tile.get_segment_length() == 0
def iterate(self):
for pos in self.sorted_positions:
if pos in self.tiles:
yield self.tiles[pos]
def update(self, pos_tile):
assert isinstance(pos_tile, PositionedTile)
if self.on_update:
self.on_update(pos_tile)
if self.to_be_deleted(pos_tile):
self.delete(pos_tile.pos)
else:
if pos_tile.pos not in self.tiles:
if pos_tile.pos not in self.sorted_positions:
self.sorted_positions.append(pos_tile.pos)
else:
# We are restoring a deleted entry
assert self.nb_to_be_deleted > 0
self.nb_to_be_deleted -= 1
self.tiles[pos_tile.pos] = pos_tile
def delete(self, pos):
assert isinstance(pos, Vect)
if self.on_delete:
self.on_delete(pos)
if pos in self.tiles:
self.nb_to_be_deleted += 1
del self.tiles[pos]
def __resize(self):
assert self.allocated() == len(self) + self.nb_to_be_deleted
assert all(self.sorted_positions[idx] not in self.tiles for idx in range(len(self), self.allocated()))
del self.sorted_positions[len(self):]
self.nb_to_be_deleted = 0
assert self.allocated() == len(self) + self.nb_to_be_deleted
def force_resize(self):
self.sorted_positions.sort(key = lambda pos: 0 if pos in self.tiles else 1)
self.__resize()
def __sort_key(self, key_on_positioned_tile, reverse, pos):
if pos not in self.tiles:
return -sys.maxsize if reverse else sys.maxsize
else:
return key_on_positioned_tile(self.tiles[pos])
def __sort(self, key_on_positioned_tile, reverse):
self.sorted_positions.sort(key = lambda pos: self.__sort_key(key_on_positioned_tile, reverse, pos), reverse = reverse)
def sort(self, key, reverse = False):
self.__sort(key, reverse)
# Resize if the nb of tiles marked for deletion is passed a certain threshold
if len(self) > 0 and (self.allocated() / len(self)) > 1.333:
self.__resize()
def debug_printout(self):
print('Candidates: (used/total: {}/{})'.format(len(self.tiles), len(self.sorted_positions)))
for pos in self.sorted_positions:
if pos in self.tiles:
print('nb_contact_sides={}, pos={}'.format(self.tiles[pos].get_segment_length(), pos))
else:
print('to_be_deleted, pos={}'.format(pos))
def validate_tile_placement(placed_tile, border):
# Trivial except for river tiles
if 'R' in Boundary.label_getter(placed_tile.iter_segment()):
test_border = border.copy()
test_border.merge(placed_tile.get_boundary())
for (point, edge, label) in placed_tile.iter_complement_segment():
if label == 'R':
test_tile_border = boundary.from_edge(point, edge, Orientation.COUNTERCLOCKWISE, Domain.EXTERIOR)
common_segments = test_border.common_segments(test_tile_border)
if len(common_segments) != 1:
return False
(_, _, L) = common_segments[0]
if L != 1:
return False
return True
def update_border_and_candidate_tiles(placed_tile, border, candidate_tiles):
"""
This function updates the map boundary and the candidate tile placements
Arguments:
placed_tile The tile being added to the map boundary
border The current map boundary
candidate_tiles The list of candidate tiles along the map boundary
Notes:
A candidate tile placement is an unoccupied tile adjacent to the map boundary.
In order to prioritize a tile placement among other candidates, the following parameters are used:
- The length of the segment in contact with the map boundary
- The L1 distance of the tile to the center of the map
"""
assert isinstance(placed_tile, PlacedTile)
assert isinstance(border, Boundary)
assert isinstance(candidate_tiles, CandidateTiles)
# Merge the newly placed tile to the map boundary
border.merge(placed_tile.get_boundary())
# Account for the change in the map boundary in candidate_tiles
candidate_tiles.delete(placed_tile.pos)
neighbor_edges = [(point, edge) for (point, edge, _) in placed_tile.iter_complement_segment()]
neighbor_edges.extend([(point + edge, edge) for (point, edge) in neighbor_edges[:-1]])
tiles_to_update = [PositionedTile.from_boundary_edge(border, point, edge) for (point, edge) in neighbor_edges]
for pos_tile in tiles_to_update:
candidate_tiles.update(pos_tile)
# Sort the updated list of candidates
candidate_tiles.sort(key=PlacedTile.get_l1_distance)
candidate_tiles.sort(key=PlacedTile.get_segment_length, reverse=True)
if DEBUG_PRINTOUT:
candidate_tiles.debug_printout()
return placed_tile
def select_tile_placement(candidate_placements):
assert isinstance(candidate_placements, list) # NB: A list of PlacedTile
assert len(candidate_placements) > 0
# Nothing fancy
return candidate_placements[0]
def find_candidate_placements(tile, border, candidate_tiles, max_candidates = -1, force_edge_label = None):
assert isinstance(tile, Tile)
assert isinstance(border, Boundary)
assert len(border) > 0
assert isinstance(candidate_tiles, CandidateTiles)
assert len(candidate_tiles) > 0
candidate_placements = []
for pos_tile in candidate_tiles.iterate():
(i0, j0, L0) = pos_tile.get_segment()
assert L0 > 0
tile_border = pos_tile.get_boundary(list(tile.desc))
# Recompute PositionedTile because the common segment's 'i' index will not match
pos_tile = PositionedTile(pos_tile.pos, border.common_segments(tile_border))
(i1, j1, L1) = pos_tile.get_segment()
if (j0, L0) != (j1, L1):
warn('Incoherent common segments for tile at {} in candidate_tiles: {} and computed against the current border: {}'.format(pos_tile.pos, (i0, j0, L0), (i1, j1, L1)))
continue
if force_edge_label is not None and force_edge_label not in Boundary.label_getter(border.iter_slice(i1, i1 + L1)):
continue
for r in border.find_matching_rotations(tile_border, pos_tile.get_segment()):
placed_tile = PlacedTile.from_positioned_tile(pos_tile, tile, r)
if validate_tile_placement(placed_tile, border):
candidate_placements.append(placed_tile)
if max_candidates > 0 and len(candidate_placements) >= max_candidates:
break
return candidate_placements
def place_carcassonne_city(tileset, candidate_tiles, display, z, pos, r = 0):
assert len(tileset) > 0
assert isinstance(pos, Vect)
if len(tileset) != 12:
warn('Expected 12 tiles for the city of Carcassonne')
composite_tile = CompositeTile()
for tile in tileset:
assert 'carcassonne_city' in tile.tags
composite_tile.append(tile)
composite_tile.draw(display, pos, r)
display.update(z)
border = composite_tile.get_boundary(pos, r)
neighbor_tiles = [PositionedTile.from_boundary_edge(border, point, edge) for (point, edge, _) in border.iter_all()]
for pos_tile in neighbor_tiles:
candidate_tiles.update(pos_tile)
return border
def parse_river_placement_policies(policies):
result = []
# Policy: T-shaped tile
if RiverPlacement.USE_T in policies:
result.append(RiverPlacement.USE_T)
elif RiverPlacement.EXCLUDE_T in policies:
result.append(RiverPlacement.EXCLUDE_T)
else:
result.append(RIVER_PLACEMENT_DEFAULT_T_POLICY)
# Policy: River length
if RiverPlacement.SHORT_RIVER in policies:
result.append(RiverPlacement.SHORT_RIVER)
elif RiverPlacement.LONG_RIVER in policies:
result.append(RiverPlacement.LONG_RIVER)
else:
result.append(RIVER_PLACEMENT_DEFAULT_LENGTH_POLICY)
assert len(result) == 2
return result
def main():
parser = argparse.ArgumentParser(description='Display a randomized Carcassonne map')
parser.add_argument('files', metavar='FILE', nargs='*', help='Tile description file (JSON format)')
parser.add_argument('-d', '--debug', dest='debug_mode', action='store_true', help='Display non-game tiles, etc.')
parser.add_argument('-n', metavar='N', type=int, dest='max_tiles', default = 0, help='Number of tiles to display (Default: The whole tileset)')
parser.add_argument('-z', '--zoom-factor', metavar='Z', type=float, dest='zoom_factor', default = 1.0, help='Initial zoom factor (Default: 1.0)')
parser.add_argument('--draw-all', dest='draw_all', action='store_true', help='Draw all tiles')
parser.add_argument('-f', '--full-screen', dest='full_screen', action='store_true', help='Full screen')
parser.add_argument('-s', '--screenshot', dest='take_screenshot', action='store_true', help='Take a screenshot of the final display')
parser.add_argument('--dump', dest='dump_to_img', action='store_true', help='Dump the final grid to an image')
parser.add_argument('--river-policy', type=str, dest='river_policy', choices=[policy.name for policy in RiverPlacement], action='append', default=[], help='Placement policies for the river tileset. Can be used multiple times')
parser.add_argument('--river-period', metavar='P', type=int, dest='river_period', default=1, help='Period of repetition of the river tileset. Set to zero for a single use of the river tileset')
parser.add_argument('--seed', metavar='INT', type=int, dest='seed', default = 0, help='A seed for the random generator (Default: Use a system generated seed)')
args = parser.parse_args()
# Set random seed
rng_seed = args.seed
if rng_seed == 0:
rng_seed = secrets.randbits(64)
print('Random seed: {}'.format(rng_seed))
random.seed(rng_seed)
# Load tileset (JSON files)
tileset = list(itertools.chain.from_iterable(parse_tileset_description_file(json_file) for json_file in args.files))
if len(tileset) == 0:
error('No tiles loaded')
# River tiles placement policy and period
river_placement_policies = parse_river_placement_policies([RiverPlacement[policy] for policy in args.river_policy])
river_tileset_period = args.river_period if args.river_period >= 0 else 0
if args.debug_mode and any('river' in tile.tags for tile in tileset):
print('river_placement_policies: {}'.format([policy.name for policy in river_placement_policies]))
print('river_tileset_period: {}'.format(river_tileset_period))
try:
# Load tile images, and draw missing ones
graphics.init()
tile_size = load_or_draw_tile_images(tileset, args.draw_all)
carcassonne_city_tileset, tileset = TileSubset.carcassonne_city().partition_iter(tileset)
city_start_flag = len(carcassonne_city_tileset) > 0
river_tileset, regular_tileset = TileSubset.river().partition(tileset)
del tileset
# Non-game tiles
riverside_tile = Tile.from_uniform_color((217, 236, 255), tile_size, 'riverside')
forbidden_tile = Tile.from_uniform_color((100, 20, 20), tile_size, 'forbidden')
segment_length_tiles = {
0: forbidden_tile,
1: Tile.from_uniform_color((10, 60, 10), tile_size, 'one_side'),
2: Tile.from_uniform_color((40, 120, 40), tile_size, 'two_sides'),
3: Tile.from_uniform_color((70, 180, 70), tile_size, 'three_sides')
}
# Open display
(w, h) = (0, 0) if args.full_screen else (1280, 720)
display = graphics.GridDisplay(w, h, tile_size)
print('Press ESCAPE in the graphics window to quit', flush = True)
# Place random tiles. The map must grow!
candidate_tiles = CandidateTiles(
on_update = lambda pos_tile: display.set_tile(segment_length_tiles[pos_tile.get_segment_length()].img, pos_tile.pos.x, pos_tile.pos.y) if args.debug_mode else None,
on_delete = None)
z = args.zoom_factor
border = place_carcassonne_city(carcassonne_city_tileset, candidate_tiles, display, z, Vect(-2, -1)) if city_start_flag else Boundary()
total_nb_tiles_placed = 0
total_nb_tiles_not_placed = 0
first_tileset_flag = not city_start_flag
all_done_flag = False
for tileset in iterate_tilesets(river_tileset, regular_tileset, river_tileset_period, infinite = (args.max_tiles > 0)):
for tiles_to_place in shuffle_tileset(tileset, first_tileset_flag, river_placement_policies):
local_nb_tiles_placed = 0
while len(tiles_to_place) > 0:
tiles_not_placed = []
for tile in tiles_to_place:
if args.max_tiles > 0 and total_nb_tiles_placed >= args.max_tiles:
all_done_flag = True
break
if len(border) == 0:
# The first tile of the map is placed at the center
placed_tile = PlacedTile(tile, Vect(0, 0), r = 0)
else:
forced_segment = 'R' if 'river' in tile.tags and 'source' not in tile.tags else None
max_candidates = 1
candidate_placements = find_candidate_placements(tile, border, candidate_tiles, max_candidates, forced_segment)
placed_tile = select_tile_placement(candidate_placements) if len(candidate_placements) > 0 else None
if placed_tile:
update_border_and_candidate_tiles(placed_tile, border, candidate_tiles)
placed_tile.draw(display)
total_nb_tiles_placed += 1
local_nb_tiles_placed += 1
# z = 0.995 * z
# display.update(z, 100)
else:
tiles_not_placed.append(tile)
if all_done_flag:
break
if len(tiles_not_placed) == len(tiles_to_place):
# making no progress, stop there
total_nb_tiles_not_placed += len(tiles_not_placed)
for tile in tiles_not_placed:
warn('Could not place tile: {}'.format(tile))
break
assert len(tiles_not_placed) < len(tiles_to_place)
tiles_to_place = tiles_not_placed
# Done with the current tiles subset
if DEBUG_PRINTOUT or args.debug_mode:
print('total_nb_tiles_placed: {} (+{})'.format(total_nb_tiles_placed, local_nb_tiles_placed))
if all_done_flag:
break
# Done with the current tileset
if all_done_flag:
break
first_tileset_flag = False
display.update(z)
# Completely done!
display.update(z)
print('Done!')
print('total_nb_tiles_not_placed: {}'.format(total_nb_tiles_not_placed))
print('total_nb_tiles_placed: {}'.format(total_nb_tiles_placed))
sys.stdout.flush()
# Wait until the user quits
while True:
display.check_event_queue(200)
except graphics.MustQuit:
pass
finally:
if args.debug_mode and 'display' in locals():
print(display.get_debug_info())
if (args.take_screenshot or args.debug_mode) and 'display' in locals():
display.take_screenshot(SCREENSHOT_PATH)
print('Screenshot saved in {}'.format(SCREENSHOT_PATH))
if args.dump_to_img and 'display' in locals():
display.dump_to_img(DUMP_PATH, args.zoom_factor)
print('Dump grid to {}'.format(DUMP_PATH))
graphics.quit()
return 0
if __name__ == "__main__":
main()
| 36.764775 | 230 | 0.635051 | 12,324 | 0.396232 | 2,024 | 0.065074 | 3,692 | 0.118702 | 0 | 0 | 4,594 | 0.147703 |
3eec12f5620398b980058505bc6d6b26e01d13f2 | 11,029 | py | Python | business_card/mainpage.py | AshxStudio/PyLearning | 4ae42f9ef0c1b0e6bf3ff415f98687ba1058636e | [
"MIT"
]
| null | null | null | business_card/mainpage.py | AshxStudio/PyLearning | 4ae42f9ef0c1b0e6bf3ff415f98687ba1058636e | [
"MIT"
]
| null | null | null | business_card/mainpage.py | AshxStudio/PyLearning | 4ae42f9ef0c1b0e6bf3ff415f98687ba1058636e | [
"MIT"
]
| null | null | null | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainpage.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import *
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(1224, 725)
font = QtGui.QFont()
font.setFamily("Arial")
font.setKerning(False)
Form.setFont(font)
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(25, 25, 45, 45))
self.label.setCursor(QtGui.QCursor(QtCore.Qt.UpArrowCursor))
# self.label.setStyleSheet("background-color: rgb(10, 46, 255);")
self.label.setText("")
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(80, 30, 331, 41))
font = QtGui.QFont()
font.setPointSize(30)
font.setBold(True)
font.setItalic(False)
font.setUnderline(False)
font.setWeight(75)
font.setStrikeOut(False)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setGeometry(QtCore.QRect(450, 40, 291, 31))
self.lineEdit.setText("")
self.lineEdit.setObjectName("lineEdit")
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(680, 40, 61, 31))
self.pushButton.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgb(0, 170, 255);")
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(Form)
self.pushButton_2.setGeometry(QtCore.QRect(750, 40, 81, 31))
self.pushButton_2.setStyleSheet("background-color: rgb(0, 170, 255);\n"
"color: rgb(255, 255, 255);")
self.pushButton_2.setObjectName("pushButton_2")
self.scrollArea = QtWidgets.QScrollArea(Form)
self.scrollArea.setGeometry(QtCore.QRect(10, 140, 1200, 571))
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 1198, 569))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.gridLayoutWidget = QtWidgets.QWidget(self.scrollAreaWidgetContents)
self.gridLayoutWidget.setGeometry(QtCore.QRect(0, 0, 1201, 571))
self.gridLayoutWidget.setObjectName("gridLayoutWidget")
self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.layoutWidget = QtWidgets.QWidget(Form)
self.layoutWidget.setGeometry(QtCore.QRect(12, 90, 1191, 41))
self.layoutWidget.setObjectName("layoutWidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.layoutWidget)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setObjectName("horizontalLayout")
self.pushButton_3 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_3.setObjectName("pushButton_3")
self.horizontalLayout.addWidget(self.pushButton_3)
self.pushButton_4 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_4.setObjectName("pushButton_4")
self.horizontalLayout.addWidget(self.pushButton_4)
self.pushButton_6 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_6.setObjectName("pushButton_6")
self.horizontalLayout.addWidget(self.pushButton_6)
self.pushButton_5 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_5.setObjectName("pushButton_5")
self.horizontalLayout.addWidget(self.pushButton_5)
self.pushButton_7 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_7.setObjectName("pushButton_7")
self.horizontalLayout.addWidget(self.pushButton_7)
self.pushButton_8 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_8.setObjectName("pushButton_8")
self.horizontalLayout.addWidget(self.pushButton_8)
self.pushButton_9 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_9.setObjectName("pushButton_9")
self.horizontalLayout.addWidget(self.pushButton_9)
self.pushButton_10 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_10.setObjectName("pushButton_10")
self.horizontalLayout.addWidget(self.pushButton_10)
self.pushButton_11 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_11.setObjectName("pushButton_11")
self.horizontalLayout.addWidget(self.pushButton_11)
self.pushButton_12 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_12.setObjectName("pushButton_12")
self.horizontalLayout.addWidget(self.pushButton_12)
self.pushButton_13 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_13.setObjectName("pushButton_13")
self.horizontalLayout.addWidget(self.pushButton_13)
self.pushButton_14 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_14.setObjectName("pushButton_14")
self.horizontalLayout.addWidget(self.pushButton_14)
self.pushButton_15 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_15.setObjectName("pushButton_15")
self.horizontalLayout.addWidget(self.pushButton_15)
self.pushButton_16 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_16.setObjectName("pushButton_16")
self.horizontalLayout.addWidget(self.pushButton_16)
self.pushButton_17 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_17.setObjectName("pushButton_17")
self.horizontalLayout.addWidget(self.pushButton_17)
self.pushButton_18 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_18.setObjectName("pushButton_18")
self.horizontalLayout.addWidget(self.pushButton_18)
self.pushButton_19 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_19.setObjectName("pushButton_19")
self.horizontalLayout.addWidget(self.pushButton_19)
self.pushButton_20 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_20.setObjectName("pushButton_20")
self.horizontalLayout.addWidget(self.pushButton_20)
self.pushButton_21 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_21.setObjectName("pushButton_21")
self.horizontalLayout.addWidget(self.pushButton_21)
self.pushButton_22 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_22.setObjectName("pushButton_22")
self.horizontalLayout.addWidget(self.pushButton_22)
self.pushButton_23 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_23.setObjectName("pushButton_23")
self.horizontalLayout.addWidget(self.pushButton_23)
self.pushButton_24 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_24.setObjectName("pushButton_24")
self.horizontalLayout.addWidget(self.pushButton_24)
self.pushButton_25 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_25.setObjectName("pushButton_25")
self.horizontalLayout.addWidget(self.pushButton_25)
self.pushButton_26 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_26.setObjectName("pushButton_26")
self.horizontalLayout.addWidget(self.pushButton_26)
self.pushButton_27 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_27.setObjectName("pushButton_27")
self.horizontalLayout.addWidget(self.pushButton_27)
self.pushButton_28 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_28.setObjectName("pushButton_28")
self.horizontalLayout.addWidget(self.pushButton_28)
self.pushButton_29 = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton_29.setObjectName("pushButton_29")
self.horizontalLayout.addWidget(self.pushButton_29)
self.pushButton_30 = QtWidgets.QPushButton(Form)
self.pushButton_30.setGeometry(QtCore.QRect(1100, 40, 91, 31))
self.pushButton_30.setStyleSheet("background-color: rgb(0, 170, 255);\n"
"color: rgb(255, 255, 255);")
self.pushButton_30.setObjectName("pushButton_30")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "AIๆบ่ฝ่็ณปไบบ็ฎก็"))
# ่ฎพ็ฝฎ็ชไฝๅพๆ
Form.setWindowIcon(QIcon('res/img/ic_launcher.png'))
self.label_2.setText(_translate("Form", "AIๆบ่ฝ่็ณปไบบ็ฎก็"))
self.lineEdit.setPlaceholderText(_translate("Form", "่พๅ
ฅๆ็ดขๅ
ๅฎน"))
self.pushButton.setText(_translate("Form", "ๆ็ดข"))
self.pushButton_2.setText(_translate("Form", "ๆทปๅ "))
self.pushButton_3.setText(_translate("Form", "All"))
self.pushButton_4.setText(_translate("Form", "A"))
self.pushButton_6.setText(_translate("Form", "B"))
self.pushButton_5.setText(_translate("Form", "C"))
self.pushButton_7.setText(_translate("Form", "D"))
self.pushButton_8.setText(_translate("Form", "E"))
self.pushButton_9.setText(_translate("Form", "F"))
self.pushButton_10.setText(_translate("Form", "G"))
self.pushButton_11.setText(_translate("Form", "H"))
self.pushButton_12.setText(_translate("Form", "I"))
self.pushButton_13.setText(_translate("Form", "J"))
self.pushButton_14.setText(_translate("Form", "K"))
self.pushButton_15.setText(_translate("Form", "L"))
self.pushButton_16.setText(_translate("Form", "M"))
self.pushButton_17.setText(_translate("Form", "N"))
self.pushButton_18.setText(_translate("Form", "O"))
self.pushButton_19.setText(_translate("Form", "P"))
self.pushButton_20.setText(_translate("Form", "Q"))
self.pushButton_21.setText(_translate("Form", "R"))
self.pushButton_22.setText(_translate("Form", "S"))
self.pushButton_23.setText(_translate("Form", "T"))
self.pushButton_24.setText(_translate("Form", "U"))
self.pushButton_25.setText(_translate("Form", "V"))
self.pushButton_26.setText(_translate("Form", "W"))
self.pushButton_27.setText(_translate("Form", "X"))
self.pushButton_28.setText(_translate("Form", "Y"))
self.pushButton_29.setText(_translate("Form", "Z"))
self.pushButton_30.setText(_translate("Form", "ๆฅ็่็ณปไบบๅๅธ"))
# ่ฎพ็ฝฎ่ฆๆพ็คบ็ๅพ็
self.label.setPixmap(QPixmap('res/img/ic_launcher.png'))
# ๅพ็ๆพ็คบๆนๅผ ่ฎฉๅพ็้ๅบQLabel็ๅคงๅฐ
self.label.setScaledContents(True)
| 54.59901 | 80 | 0.710581 | 10,880 | 0.976047 | 0 | 0 | 0 | 0 | 0 | 0 | 1,573 | 0.141114 |
3eecad1535b44d09acd50ef4de76145c633066a1 | 2,890 | py | Python | project/classification/posture_classification/ops/data_processor.py | jh-lau/solid_ai_waddle | b966f2c6e8b6b48c62064d58461692231aa2116b | [
"MIT"
]
| null | null | null | project/classification/posture_classification/ops/data_processor.py | jh-lau/solid_ai_waddle | b966f2c6e8b6b48c62064d58461692231aa2116b | [
"MIT"
]
| null | null | null | project/classification/posture_classification/ops/data_processor.py | jh-lau/solid_ai_waddle | b966f2c6e8b6b48c62064d58461692231aa2116b | [
"MIT"
]
| null | null | null | """
@Author : liujianhan
@Date : 2018/6/2 ไธๅ11:59
@Project : posture_classification
@FileName : data_processor.py
@Description : Placeholder
"""
import os
from typing import Tuple
import pandas as pd
from keras.applications.resnet50 import preprocess_input
from keras.preprocessing.image import ImageDataGenerator
from sklearn.utils import shuffle
import numpy as np
def data_generator_flow(_train_dir: str,
_valid_dir: str,
_test_dir: str,
batch_size: int = 32,
target_size: Tuple = (256, 256),
multi_output_mode: bool = False) -> Tuple:
"""
ๆฐๆฎ็ๆๅจๅฝๆฐ
@param _train_dir: ่ฎญ็ปๆฐๆฎๆไปถ่ทฏๅพ
@param _valid_dir: ้ช่ฏๆฐๆฎๆไปถ่ทฏๅพ
@param _test_dir: ๆต่ฏๆฐๆฎๆไปถ่ทฏๅพ
@param batch_size: ๆน้ๅๆฐ
@param target_size: ็ฎๆ ่ฝฌๆขๅฝข็ถ
@param multi_output_mode: ๅค่พๅบๆจกๅผ
@return: ็ๆๅจๅ
็ป
"""
train_df = pd.read_csv(os.path.join(_train_dir, 'train.csv'))
valid_df = pd.read_csv(os.path.join(_valid_dir, 'valid.csv'))
test_df = pd.read_csv(os.path.join(_test_dir, 'test.csv'))
if not multi_output_mode:
train_df.label = train_df.label.astype('str')
valid_df.label = valid_df.label.astype('str')
test_df.label = test_df.label.astype('str')
train_data_gen = ImageDataGenerator(
preprocessing_function=preprocess_input,
width_shift_range=.2,
height_shift_range=.2,
shear_range=.2,
zoom_range=.2,
channel_shift_range=np.random.choice(100),
horizontal_flip=True,
)
train_data_flow = train_data_gen.flow_from_dataframe(
dataframe=train_df,
target_size=target_size,
directory=_train_dir,
batch_size=batch_size,
class_mode='multi_output' if multi_output_mode else 'binary',
x_col='filename',
y_col=['label', 'score'] if multi_output_mode else 'label',
)
# ้ช่ฏ้ไธ่ฆๅๆฐๆฎๅขๅผบ
valid_data_gen = ImageDataGenerator(preprocessing_function=preprocess_input)
valid_data_flow = valid_data_gen.flow_from_dataframe(
dataframe=valid_df,
target_size=target_size,
directory=_valid_dir,
batch_size=batch_size,
class_mode='multi_output' if multi_output_mode else 'binary',
x_col='filename',
y_col=['label', 'score'] if multi_output_mode else 'label',
)
test_data_gen = ImageDataGenerator(preprocessing_function=preprocess_input)
test_data_flow = test_data_gen.flow_from_dataframe(
dataframe=test_df,
target_size=target_size,
directory=_test_dir,
batch_size=batch_size,
class_mode='multi_output' if multi_output_mode else 'binary',
x_col='filename',
y_col=['label', 'score'] if multi_output_mode else 'label',
)
return train_data_flow, valid_data_flow, test_data_flow
| 34.404762 | 80 | 0.664014 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 754 | 0.25 |
3eecb6e97ffd929b50cc81c0b14af95a02561e17 | 150 | py | Python | 1015.py | gabzin/beecrowd | 177bdf3f87bacfd924bd031a973b8db877379fe5 | [
"MIT"
]
| 3 | 2021-12-15T20:27:14.000Z | 2022-03-01T12:30:08.000Z | 1015.py | gabzin/uri | 177bdf3f87bacfd924bd031a973b8db877379fe5 | [
"MIT"
]
| null | null | null | 1015.py | gabzin/uri | 177bdf3f87bacfd924bd031a973b8db877379fe5 | [
"MIT"
]
| null | null | null | from math import sqrt
x1,y1=map(float,input().split())
x2,y2=map(float,input().split())
p1=x2-x1
p2=y2-y1
res=sqrt((p1*p1)+(p2*p2))
print("%.4f"%res)
| 18.75 | 32 | 0.66 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | 0.04 |
3eed4a648db7f6b58a8270deb65a534840398278 | 43 | py | Python | modules/pointer_network/__init__.py | matthew-z/pytorch_rnet | 670f3796cd01595903ef781ec7eb0e55c020e77b | [
"MIT"
]
| 227 | 2017-09-20T08:17:07.000Z | 2022-02-16T23:48:04.000Z | modules/pointer_network/__init__.py | matthew-z/R-Net | 670f3796cd01595903ef781ec7eb0e55c020e77b | [
"MIT"
]
| 18 | 2017-10-25T14:42:56.000Z | 2020-04-14T18:50:48.000Z | modules/pointer_network/__init__.py | matthew-z/R-Net | 670f3796cd01595903ef781ec7eb0e55c020e77b | [
"MIT"
]
| 59 | 2017-10-02T15:25:27.000Z | 2021-05-28T07:57:39.000Z | from .pointer_network import PointerNetwork | 43 | 43 | 0.906977 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
3eedf65adf2ccf1a08d61e0dec0f3caf4fa9559f | 985 | py | Python | twitch_the_universim_chat/views.py | gaelfargeas/twitch_universim_streamer_chat | 4773bf30e6aab3d9f950ba027e7aa3e51278428c | [
"BSD-3-Clause"
]
| null | null | null | twitch_the_universim_chat/views.py | gaelfargeas/twitch_universim_streamer_chat | 4773bf30e6aab3d9f950ba027e7aa3e51278428c | [
"BSD-3-Clause"
]
| null | null | null | twitch_the_universim_chat/views.py | gaelfargeas/twitch_universim_streamer_chat | 4773bf30e6aab3d9f950ba027e7aa3e51278428c | [
"BSD-3-Clause"
]
| null | null | null | from django.shortcuts import render, redirect
from django.utils.datastructures import MultiValueDictKeyError
def index(request):
return render(request, "chat.html", {})
def logged(request):
try :
bot_name = request.POST["bot_name"]
streamer_name = request.POST["streamer_name"]
stream_token = request.POST["stream_token"]
return render(
request,
"chat_logged.html",
{
"streamer_name": streamer_name,
"stream_token": stream_token,
"bot_name": bot_name,
},
)
except MultiValueDictKeyError :
return redirect("/")
def redirect_style_css(request):
response = redirect("/static/css/styles.css")
print("redirect to /static/css/styles.css")
return response
def redirect_favicon(request):
response = redirect("/static/images/favicon.ico")
print("redirect to /static/images/favicon.ico")
return response | 27.361111 | 62 | 0.631472 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 238 | 0.241624 |
3eef9508412716c264b3b444bb752f75ff044dba | 1,480 | py | Python | numba/exttypes/tests/test_extension_attributes.py | liuzhenhai/numba | 855a2b262ae3d82bd6ac1c3e1c0acb36ee2e2acf | [
"BSD-2-Clause"
]
| 1 | 2015-01-29T06:52:36.000Z | 2015-01-29T06:52:36.000Z | numba/exttypes/tests/test_extension_attributes.py | shiquanwang/numba | a41c85fdd7d6abf8ea1ebe9116939ddc2217193b | [
"BSD-2-Clause"
]
| null | null | null | numba/exttypes/tests/test_extension_attributes.py | shiquanwang/numba | a41c85fdd7d6abf8ea1ebe9116939ddc2217193b | [
"BSD-2-Clause"
]
| null | null | null | """
Test class attributes.
"""
import numba
from numba import *
from numba.testing.test_support import parametrize, main
def make_base(compiler):
@compiler
class Base(object):
value1 = double
value2 = int_
@void(int_, double)
def __init__(self, value1, value2):
self.value1 = value1
self.value2 = value2
@void(int_)
def setvalue(self, value):
self.value1 = value
@double()
def getvalue1(self):
return self.value1
return Base
def make_derived(compiler):
Base = make_base(compiler)
@compiler
class Derived(Base):
value3 = float_
@void(int_)
def setvalue(self, value):
self.value3 = value
return Base, Derived
#------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------
@parametrize(jit, autojit)
def test_baseclass_attrs(compiler):
Base = make_base(compiler)
assert Base(10, 11.0).value1 == 10.0
assert Base(10, 11.0).value2 == 11
obj = Base(10, 11.0)
obj.setvalue(12)
assert obj.getvalue1() == 12.0
@parametrize(jit) #, autojit)
def test_derivedclass_attrs(compiler):
Base, Derived = make_derived(compiler)
obj = Derived(10, 11.0)
obj.setvalue(9)
assert obj.value3 == 9.0
if __name__ == '__main__':
# test_derivedclass_attrs(autojit)
main()
| 20.555556 | 73 | 0.551351 | 505 | 0.341216 | 0 | 0 | 978 | 0.660811 | 0 | 0 | 238 | 0.160811 |
3ef2102b67623964df7f8e5b43fb31855632c83c | 1,386 | py | Python | tests/plugins/pull/test_poll.py | HazardDede/pnp | 469ca17254dcca1a4eefe0dc5ac574692a9ab38e | [
"MIT"
]
| 4 | 2018-10-07T11:32:00.000Z | 2019-04-23T09:34:23.000Z | tests/plugins/pull/test_poll.py | HazardDede/pnp | 469ca17254dcca1a4eefe0dc5ac574692a9ab38e | [
"MIT"
]
| null | null | null | tests/plugins/pull/test_poll.py | HazardDede/pnp | 469ca17254dcca1a4eefe0dc5ac574692a9ab38e | [
"MIT"
]
| 1 | 2019-08-12T19:56:10.000Z | 2019-08-12T19:56:10.000Z | import time
from datetime import datetime
import pytest
from pnp.plugins.pull import StopPollingError
from pnp.plugins.pull.simple import CustomPolling
from . import make_runner, start_runner
@pytest.mark.asyncio
async def test_poll():
events = []
def callback(plugin, payload):
events.append(payload)
def poll():
return datetime.now()
dut = CustomPolling(name='pytest', interval="1s", scheduled_callable=poll)
assert not dut.is_cron
assert dut._poll_interval == 1
runner = await make_runner(dut, callback)
async with start_runner(runner):
time.sleep(3)
assert len(events) >= 2
@pytest.mark.asyncio
async def test_poll_for_aborting():
events = []
def callback(plugin, payload):
events.append(payload)
def poll():
raise StopPollingError()
runner = await make_runner(CustomPolling(name='pytest', interval="1s", scheduled_callable=poll), callback)
async with start_runner(runner):
time.sleep(1)
assert len(events) == 0
def test_poll_with_cron_expression():
from cronex import CronExpression
def poll():
pass
dut = CustomPolling(name='pytest', interval="*/1 * * * *", scheduled_callable=poll)
assert dut.is_cron
assert isinstance(dut._cron_interval, CronExpression)
assert dut._cron_interval.string_tab == ['*/1', '*', '*', '*', '*']
| 24.75 | 110 | 0.683983 | 0 | 0 | 0 | 0 | 836 | 0.603175 | 794 | 0.572872 | 62 | 0.044733 |
3ef267c5d2fee953bb87ccf05e6b6f25d5d276e4 | 3,632 | py | Python | motorisedcameratracking/Cameras.py | wDove1/motorisedcameratracking | 97ae1722978fc99faf37c0ab7e3c8f39e3e2355d | [
"Apache-2.0"
]
| null | null | null | motorisedcameratracking/Cameras.py | wDove1/motorisedcameratracking | 97ae1722978fc99faf37c0ab7e3c8f39e3e2355d | [
"Apache-2.0"
]
| null | null | null | motorisedcameratracking/Cameras.py | wDove1/motorisedcameratracking | 97ae1722978fc99faf37c0ab7e3c8f39e3e2355d | [
"Apache-2.0"
]
| null | null | null | from picamera import PiCamera
from time import *
from cv2 import *
import numpy as np
import os
from PIL import Image
from .errors import *
class RPICam:
"""A class for the raspberry pi camera
Attributes:
modelDetails: A dictionary containing details of the Camera
imagePath: The path where the image will be stored and found
orientation: The orientation of the image
"""
modelDetails={'name':'rPi_NoIRv2','width':3280,'height':2464}
imagePath: str = None
orientation: float = None
def __init__(self,imagePath: str,orientation: str):
"""sets the values of imagePath and orientation
Args:
imagePath: the path to the image
orientation: the orientation of the camera
"""
self.imagePath=imagePath
self.orientation=orientation
def getImage(self,resolution: list = [1280,720]):
"""Gets the image from the camera
Args:
resolution: The resolution the camera will capture at
"""
camera=PiCamera()#creates a camera object
camera.resolution=(resolution[0],resolution[1])#sets the resolution
camera.capture(self.imagePath)#captures the image
camera.close()#closes the camera to prevent errros
def postProcessing(self):
"""loads the image and converts it to a numPy array
Returns:
img: A numPy array containing the image
"""
img=cv2.imread(self.imagePath,1)#convert image to a colour array
os.remove(self.imagePath)#removes the image from the location it was saved
return img
def orientationCorrection(self):
"""Corrects the orientation of the image
Runs on the image before it is opened so may need replacing
"""
img = Image.open(self.imagePath)#opens the image
img = img.rotate(-self.orientation)#rotates the image
img = img.save(self.imagePath)#saves the image to the same location
def capture(self,resolution: list =[1280,720]):
"""The outward facing method to capture an image
returns:
numPy array: contains the image
"""
self.getImage(resolution)#gets the image
self.orientationCorrection()#corrects the orientation
return self.postProcessing()#returns the image as a numPy array
def getData(self):
return self.modelDetails[self.model]
def getModel(self):
return self.model
def getImagePath(self):
return self.imagePath
def getModelDetails(self):
return self.modelDetails
class GenericCamera:
"""A generic camera using openCV"""
camera=cv2.VideoCapture(1)
def __init__(self):
pass
def capture(self):
x,frame = camera.read()
return frame
class VirtualCamera:
"""A virtual camera primarily for testing as it has no practical purpose other than this"""
images=[]
#images.append(np.array())
def __init__(self):
pass
def capture(self):
raise FeatureNotImplementedError()#raise an error as this is not implemented
#return None
| 35.262136 | 99 | 0.566079 | 3,487 | 0.960077 | 0 | 0 | 0 | 0 | 0 | 0 | 1,641 | 0.451817 |
3ef53bdde39e3c5144f18bd2ee63f39dd48f0058 | 1,568 | py | Python | simdigree/dummy.py | aryakaul/simdigree | 403e0130771c400b7687179363c7eba5ed9feeb2 | [
"MIT"
]
| 1 | 2018-11-12T19:41:14.000Z | 2018-11-12T19:41:14.000Z | simdigree/dummy.py | aryakaul/simdigree | 403e0130771c400b7687179363c7eba5ed9feeb2 | [
"MIT"
]
| null | null | null | simdigree/dummy.py | aryakaul/simdigree | 403e0130771c400b7687179363c7eba5ed9feeb2 | [
"MIT"
]
| null | null | null | class Dummy:
"""
Class for use when given a pedigree to model.
I create a 'dummy' for each individual with key information about that
individual
"""
def __init__(self, parents, founder, children=[]):
self.parents = parents
self.founder = founder
self.children = children
def __str__(self):
return("Parents: %s\nFounder?: %s\n Children: %s\n" % (self.get_parents(), self.is_founder(), self.get_children()))
def is_founder(self):
return self.founder
def get_parents(self):
return self.parents
def get_children(self):
return self.children
def add_child(self, child):
copy = list(self.children)
copy.append(child)
self.children = copy
class DummyPair:
"""
Class for use when given a pedigree to model.
I create a 'DummyPair' for each married pair found in the original
pedigree
"""
def __init__(self, parents, children=[]):
self.pair = parents
self.children = children
def __eq__(self, other):
if self.pair == other.pair:
return True
return False
def __str__(self):
return("Pair: %s\tNo.Children: %s" % (self.get_pair(), self.get_num_children()))
def get_num_children(self):
return len(self.get_children())
def get_children(self):
return self.children
def add_child(self, child):
copy = list(self.children)
copy.append(child)
self.children = copy
def get_pair(self):
return self.pair
| 24.5 | 123 | 0.616071 | 1,565 | 0.998087 | 0 | 0 | 0 | 0 | 0 | 0 | 367 | 0.234056 |
3ef554160c1a186dae9bd51e974deb08ac86e468 | 1,226 | py | Python | setup.py | Superbuy-Team/sbcnab240 | fe32ffa1efc3f07f8e1be607d4bf110f5134720a | [
"MIT"
]
| 5 | 2017-12-19T17:50:56.000Z | 2019-02-12T03:19:50.000Z | setup.py | Superbuy-Team/sbcnab240 | fe32ffa1efc3f07f8e1be607d4bf110f5134720a | [
"MIT"
]
| null | null | null | setup.py | Superbuy-Team/sbcnab240 | fe32ffa1efc3f07f8e1be607d4bf110f5134720a | [
"MIT"
]
| null | null | null | from setuptools import setup, find_packages
"""
Uma biblioteca para leitura de arquivos CNAB 240.
"""
setup(
name='sbcnab240',
version='0.1.0',
url='https://github.com/Superbuy-Team/sbcnab240/',
license='MIT',
author='SuperBuy Team',
author_email='[email protected]',
description='Uma biblioteca para leitura de arquivos CNAB 240',
long_description=__doc__,
keywords='cnab cnab240 boleto',
#packages=['sbcnab240'],
packages=find_packages(exclude=['contrib', 'docs', 'tests*']),
package_data={
'bancos': ['sbcnab240/bancos/santander.json'],
},
include_package_data=True,
zip_safe=False,
python_requires='~=2.6',
platforms='any',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Natural Language :: Portuguese (Brazilian)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| 31.435897 | 70 | 0.630506 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 725 | 0.591354 |
3ef60e720154164bc72b950006e65765140586cd | 860 | py | Python | mlib/web/shadow_lib.py | mgroth0/mlib | 0442ed51eab417b6972f885605afd351892a3a9a | [
"MIT"
]
| 1 | 2020-06-16T17:26:45.000Z | 2020-06-16T17:26:45.000Z | mlib/web/shadow_lib.py | mgroth0/mlib | 0442ed51eab417b6972f885605afd351892a3a9a | [
"MIT"
]
| null | null | null | mlib/web/shadow_lib.py | mgroth0/mlib | 0442ed51eab417b6972f885605afd351892a3a9a | [
"MIT"
]
| null | null | null | from mlib.proj.struct import Project
from mlib.web.html import HTMLPage, Hyperlink, HTMLImage
SKIPPED_SOURCE = [
'@log_invokation',
'global DOC',
'@staticmethod'
]
def scipy_doc_url(funname): return f'https://docs.scipy.org/doc/scipy/reference/generated/{funname}.html'
FUN_LINKS = {
'bilinear': 'https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.bilinear.html'
}
FUN_LINKS.update(
{fun.split('.')[-1]: scipy_doc_url(fun) for fun in [
'scipy.signal.filtfilt',
'scipy.signal.lfilter',
'scipy.signal.butter'
]}
)
def ShadowIndex(*pages):
return HTMLPage(
'index',
*[Hyperlink(page.rootpath, f"{page.rootpath}/{page.name}.html") for page in pages],
HTMLImage(Project.PYCALL_FILE, fix_abs_path=True),
HTMLImage(Project.PYDEPS_OUTPUT, fix_abs_path=True)
)
| 27.741935 | 105 | 0.676744 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 316 | 0.367442 |
3efa82e7a5854f87ab9bf7282fade9ac7afa8bff | 3,607 | py | Python | markdown-journal.py | fire-wally/markdown-notebook | 8fe22f645d6aca65f5f02cf4a67993e809795396 | [
"Apache-2.0"
]
| null | null | null | markdown-journal.py | fire-wally/markdown-notebook | 8fe22f645d6aca65f5f02cf4a67993e809795396 | [
"Apache-2.0"
]
| null | null | null | markdown-journal.py | fire-wally/markdown-notebook | 8fe22f645d6aca65f5f02cf4a67993e809795396 | [
"Apache-2.0"
]
| null | null | null | #!/usr/local/bin/python3
import sys
import os
import shutil
import markdown
class Page(object):
def __init__(self, filename, mtime):
self.file_name = filename
self.modified_at = mtime
def main(argv):
if len(argv) != 3:
print("USAGE: markdown-journal.py source-dir output-dir")
return
source = argv[1]
dest = argv[2]
if not (os.path.isdir(source)):
print(source+ " is not a directory!")
return
if not (os.path.isdir(dest)):
print(dest + " is not a directory!")
return
print("Source directory is " + argv[1])
print("Output directory is " + argv[2])
clean_output(dest)
generate_output(source, dest)
def clean_output(dest):
print("Cleaning Output Directory")
for root, dirs, files in os.walk(dest, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
def generate_output(source, dest):
files_written=[]
print("Creating .html Files in Output Directory")
for root, dirs, files in os.walk(source):
for name in files:
print(os.path.join(dest,name))
##Transform Markdown files to HTML. Copy all other files as-is
if (name.endswith(".md")):
file_path = os.path.join(root, name)
new_file_name = generate_markdown(file_path, dest)
new_file = Page(new_file_name, os.path.getmtime(file_path))
files_written.append(new_file)
else:
shutil.copy(os.path.join(root, name), dest)
for name in dirs:
os.mkdir(os.path.join(dest, name))
#Now generate the index file
generate_index(files_written, dest)
def generate_index(files, dest_dir):
html = generate_index_html(files)
index_path = os.path.join(dest_dir, "index.html")
with open(index_path, "w+") as opened_file:
opened_file.write(html)
def generate_markdown(source_file, dest_dir):
'''generates a new html file in the dest directory, returns the name of the
newly-created file'''
md = ""
with open(source_file, 'r') as opened_file:
md = opened_file.read()
html = content_to_html(md)
new_name = os.path.split(source_file)[1].replace("md", "html")
new_path = os.path.join(dest_dir, new_name)
with open(new_path, "w+") as opened_file:
opened_file.write(html)
return new_name
def generate_index_html(pages):
with open("index-template.html") as template_file:
html_template = template_file.read()
alpha_page_list = "<ul>"
for page in pages:
alpha_page_list += "\n<li><a href='http://localhost/notes/{0}'>{0}</a></li>".format(page.file_name)
alpha_page_list += '\n</ul>'
recent_page_list = "<ul>"
for page in sorted(pages, key=lambda p: p.modified_at, reverse=True):
recent_page_list += "\n<li><a href='http://localhost/notes/{0}'>{0}</a></li>".format(page.file_name)
recent_page_list += "</ul>"
html_page = html_template.replace("{{PAGE_LIST_RECENT}}", recent_page_list) \
.replace("{{PAGE_LIST_ALPHA}}", alpha_page_list)
return html_page
def content_to_html(source_string):
with open("page-template.html") as template_file: #Assume in same directory as code
html_template = template_file.read()
page_fragment = markdown.markdown(source_string)
html_page = html_template.replace("{{PAGE_GOES_HERE}}", page_fragment)
return html_page
if __name__ == "__main__":
main(sys.argv) | 33.71028 | 108 | 0.640144 | 127 | 0.035209 | 0 | 0 | 0 | 0 | 0 | 0 | 752 | 0.208484 |
3efbe3ec6f7235b59b283ab4d9dd8c0d9a53ffcd | 1,090 | py | Python | plugins/modules/set_java_trusted_sites_facts.py | c2platform/ansible-collection-core | 40c4e86349cda170c406c9af2b74d7760dcf5c86 | [
"MIT"
]
| null | null | null | plugins/modules/set_java_trusted_sites_facts.py | c2platform/ansible-collection-core | 40c4e86349cda170c406c9af2b74d7760dcf5c86 | [
"MIT"
]
| null | null | null | plugins/modules/set_java_trusted_sites_facts.py | c2platform/ansible-collection-core | 40c4e86349cda170c406c9af2b74d7760dcf5c86 | [
"MIT"
]
| null | null | null | #!/usr/bin/python
from ansible.module_utils.basic import *
def site_result(site, trusted_sites_download):
rs = trusted_sites_download['results']
for r in rs:
if r['site'] == site:
return r
msg = "Result for site {} not found in {}".format(site, rs)
raise Exception(msg)
def set_java_trusted_sites_facts(data):
facts = {}
facts['java_trusted_sites'] = {}
facts['java_trusted_sites']['certs'] = {}
for site in data['trusted_sites']['certs']:
facts['java_trusted_sites']['certs'][site] = {}
r = site_result(site, data['trusted_sites_download'])
facts['java_trusted_sites']['certs'][site]['cert'] = r['stdout']
return (False, facts)
def main():
fields = {"trusted_sites": {"required": True, "type": "dict"},
"trusted_sites_download": {"required": True, "type": "dict"}}
module = AnsibleModule(argument_spec=fields)
has_changed, fcts = set_java_trusted_sites_facts(module.params)
module.exit_json(changed=has_changed, ansible_facts=fcts)
if __name__ == '__main__':
main()
| 30.277778 | 75 | 0.647706 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 322 | 0.295413 |
3efc5fe15cf4eeb421dcf698ef2f0aa33c8d45db | 53 | py | Python | src/signal_backtester/schemas/__init__.py | xibalbas/signal_backtester | 8eaa52ecad22419b29b0e0e34eaadfea83f4e4b9 | [
"MIT"
]
| 14 | 2022-03-04T20:23:45.000Z | 2022-03-30T11:04:40.000Z | src/signal_backtester/schemas/__init__.py | xibalbas/signal_backtester | 8eaa52ecad22419b29b0e0e34eaadfea83f4e4b9 | [
"MIT"
]
| null | null | null | src/signal_backtester/schemas/__init__.py | xibalbas/signal_backtester | 8eaa52ecad22419b29b0e0e34eaadfea83f4e4b9 | [
"MIT"
]
| 2 | 2022-03-05T10:18:19.000Z | 2022-03-06T12:51:49.000Z | """Schemas
Schemas Package
more description
"""
| 10.6 | 20 | 0.679245 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 52 | 0.981132 |
3efdff5f0d2a7d90af9b5f718370bdc45e63e120 | 5,829 | py | Python | py/src/api_custo.py | Ennoriel/veille-pedagogique | 63f368ad1faee2f6fca86fff68ccccc7ac89f81b | [
"FSFAP"
]
| null | null | null | py/src/api_custo.py | Ennoriel/veille-pedagogique | 63f368ad1faee2f6fca86fff68ccccc7ac89f81b | [
"FSFAP"
]
| null | null | null | py/src/api_custo.py | Ennoriel/veille-pedagogique | 63f368ad1faee2f6fca86fff68ccccc7ac89f81b | [
"FSFAP"
]
| null | null | null | from itertools import chain, combinations
from re import search
from urllib.parse import urlparse
from pymongo.errors import BulkWriteError
from tweepy import OAuthHandler, API
from yaml import load as yaml_load, BaseLoader
from objects.article import Article
from objects.hashtag import Hashtag
from objects.tweet import Tweet
from mongo.article_mongo import ArticleMongo
from mongo.hashtag_mongo import HashtagMongo
from mongo.theme_mongo import ThemeMongo
from mongo.tweet_mongo import TweetMongo
from utils.log_utils import dir_log
from utils.url_utils import unshorten
class ApiCusto:
def __init__(self):
conf = yaml_load(open("./../resources/credentials.yaml"), Loader=BaseLoader)["twitter_api"]
consumer_key = conf["consumer_key"]
consumer_secret = conf["consumer_secret"]
access_token = conf["access_token"]
access_token_secret = conf["access_token_secret"]
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
self.api = API(auth)
self.article_mongo = ArticleMongo()
self.tweet_mongo = TweetMongo()
self.hashtag_mongo = HashtagMongo()
self.theme_mongo = ThemeMongo()
self.articles = []
def fetch(self, fetch_local=True):
"""
fetch remote or local if time is remote fetch limit is not reached
:param fetch_local: if true, retrieve tweets id from a file, otherwise from a hashtag on twitter
:return: tweets
"""
return self.fetch_local() if fetch_local else self.fetch_remote()
def fetch_remote(self):
"""
Fetch to Twitter API tweets by their hashtags
:return:
"""
return self.api.search(q='#pedagogie', result_type='recent', tweet_mode='extended', lang='fr', count=20)
def fetch_local(self):
"""
Fetch to Twitter API local saved tweet ids
:return:
"""
tweet_ids_to_fetch = Tweet.get_saved_tweet_ids()
if tweet_ids_to_fetch:
return self.api.statuses_lookup(tweet_ids_to_fetch, tweet_mode='extended')
else:
return []
def parse(self, fetch_local):
"""
Gets statuses from Twitter, make an article out of links and dowload article content
:param fetch_local: if true, retrieve tweets id from a file, otherwise from a hashtag on twitter
"""
statuses = self.fetch(fetch_local)
for index_status, status in enumerate(statuses):
dir_log(0, index_status + 1, len(statuses))
# Suppression des tweets non francophones
if status.__getattribute__("lang") != 'fr':
continue
# Suppression des tweets dรฉjร enregistrรฉs
if self.tweet_mongo.exists(status.__getattribute__("_json")["id"]):
continue
article_courants = []
_json = status.__getattribute__("_json")
urls = status.entities["urls"]
# variable counting url already indexed as an article, in order to save the tweet eventhoug all its urls
# are already referenced. If the tweet as at least one url not indexed as an article, it will be saved later
# TODO vรฉrifier l'utilitรฉ de ce truc car comme le tweet est ajoutรฉ ร un article, il devrait รชtre enregistrรฉ
count_url_already_indexed = 0
for index_article, url in enumerate(urls):
dir_log(1, index_article + 1, len(urls))
print(' ' + str(_json["id"]))
unshorten_url = unshorten(url["expanded_url"])
# Suppression des url en double dans un tweet
if unshorten_url in [a.url for a in article_courants]:
continue
# Suppression des url qui sont des liens vers d'autres status Twitter
if search("^https://twitter.com/\\w+/status/\\d{19}", unshorten_url):
continue
# Suppression des url qui sont des urls de sites et non d'articles
url_path = urlparse(unshorten_url).path
if url_path == '' or url_path == '/':
continue
# Si l'url pointe vers un article dรฉjร rรฉfรฉrencรฉ, on le mets ร jour et on passe ร l'url suivante
if Article.update_article_if_exists(self.article_mongo, unshorten_url, _json["id"]):
count_url_already_indexed += 1
continue
# Si article dรฉjร rรฉfรฉrencรฉ, on le met ร jour localement
if unshorten_url in [article.url for article in self.articles]:
for article in self.articles:
if article.url == unshorten_url:
article.add_tweet(status)
break
continue
article_courant = Article.get_article_content(unshorten_url, status)
if not article_courant:
continue
article_courants.append(article_courant)
if count_url_already_indexed == len(urls):
self.tweet_mongo.saves_one(Tweet(status).get())
self.articles.extend(article_courants)
def save(self):
"""
Save articles, tweets, hashtags and updates themes
"""
if self.articles:
for article in self.articles:
print(str(article.get()))
# save articles
try:
self.article_mongo.saves_many([article.get() for article in self.articles])
except BulkWriteError as e:
print(e.details)
raise
# save tweets
tweets = list(chain.from_iterable([article.tweets for article in self.articles]))
self.tweet_mongo.saves_many([tweet.get() for tweet in tweets])
# save hashtags
hashtags = []
for article in self.articles:
hashtags.extend([theme for theme in article.not_indexed_theme_entries])
# clean duplicates
hashtags = list(dict.fromkeys(hashtags))
hashtags = [Hashtag(hashtag).get() for hashtag in hashtags]
if len(hashtags):
self.hashtag_mongo.saves_many(hashtags)
# update themes
for article in self.articles:
for [themeA, themeB] in combinations(article.indexed_theme_entries, 2):
self.theme_mongo.update_weight(themeA, themeB)
self.theme_mongo.update_weight(themeB, themeA)
def fetch_and_parse(self, fetch_local):
"""
fetch statuses, parse them to articles and saves articles
:param fetch_local: if true, retrieve tweets id from a file, otherwise from a hashtag on twitter
"""
self.parse(fetch_local)
self.save() | 31.33871 | 111 | 0.731515 | 5,273 | 0.901213 | 0 | 0 | 0 | 0 | 0 | 0 | 1,859 | 0.317723 |
3eff530062f79f81142b5bbce7a5802437435e1c | 3,985 | py | Python | ensemble_compilation/physical_db.py | LumingSun/deepdb-public | 39cf21b3145c3255f15eb40df606b02a53323e86 | [
"MIT"
]
| 48 | 2020-02-21T10:19:18.000Z | 2022-03-29T20:59:20.000Z | ensemble_compilation/physical_db.py | LumingSun/deepdb-public | 39cf21b3145c3255f15eb40df606b02a53323e86 | [
"MIT"
]
| 7 | 2020-04-29T15:13:05.000Z | 2021-06-08T13:33:53.000Z | ensemble_compilation/physical_db.py | jschj/deepdb-public | 655ada13a043a4226a239b0c0a65bcdefef87a02 | [
"MIT"
]
| 18 | 2020-02-21T13:11:49.000Z | 2022-03-07T23:27:05.000Z | import psycopg2
import pandas as pd
from ensemble_compilation.utils import gen_full_join_query, print_conditions
class DBConnection:
def __init__(self, db_user="postgres", db_password="postgres", db_host="localhost", db_port="5432", db="shopdb"):
self.db_user = db_user
self.db_password = db_password
self.db_host = db_host
self.db_port = db_port
self.db = db
def vacuum(self):
connection = psycopg2.connect(user=self.db_user,
password=self.db_password,
host=self.db_host,
port=self.db_port,
database=self.db)
old_isolation_level = connection.isolation_level
connection.set_isolation_level(0)
query = "VACUUM"
cursor = connection.cursor()
cursor.execute(query)
connection.commit()
connection.set_isolation_level(old_isolation_level)
def get_dataframe(self, sql):
connection = psycopg2.connect(user=self.db_user,
password=self.db_password,
host=self.db_host,
port=self.db_port,
database=self.db)
return pd.read_sql(sql, connection)
def submit_query(self, sql):
"""Submits query and ignores result."""
connection = psycopg2.connect(user=self.db_user,
password=self.db_password,
host=self.db_host,
port=self.db_port,
database=self.db)
cursor = connection.cursor()
cursor.execute(sql)
connection.commit()
def get_result(self, sql):
"""Fetches exactly one row of result set."""
connection = psycopg2.connect(user=self.db_user,
password=self.db_password,
host=self.db_host,
port=self.db_port,
database=self.db)
cursor = connection.cursor()
cursor.execute(sql)
record = cursor.fetchone()
result = record[0]
if connection:
cursor.close()
connection.close()
return result
def get_result_set(self, sql, return_columns=False):
"""Fetches all rows of result set."""
connection = psycopg2.connect(user=self.db_user,
password=self.db_password,
host=self.db_host,
port=self.db_port,
database=self.db)
cursor = connection.cursor()
cursor.execute(sql)
rows = cursor.fetchall()
columns = [desc[0] for desc in cursor.description]
if connection:
cursor.close()
connection.close()
if return_columns:
return rows, columns
return rows
class TrueCardinalityEstimator:
"""Queries the database to return true cardinalities."""
def __init__(self, schema_graph, db_connection):
self.schema_graph = schema_graph
self.db_connection = db_connection
def true_cardinality(self, query):
full_join_query = gen_full_join_query(self.schema_graph, query.relationship_set, query.table_set, "JOIN")
where_cond = print_conditions(query.conditions, seperator='AND')
if where_cond != "":
where_cond = "WHERE " + where_cond
sql_query = full_join_query.format("COUNT(*)", where_cond)
cardinality = self.db_connection.get_result(sql_query)
return sql_query, cardinality
| 36.227273 | 118 | 0.524969 | 3,855 | 0.967378 | 0 | 0 | 0 | 0 | 0 | 0 | 260 | 0.065245 |
4103275c6f48564c6ff1fad5fb0a8944ab60a436 | 137,967 | py | Python | release/stubs/Autodesk/AutoCAD/EditorInput.py | paoloemilioserra/ironpython-stubs | 49d92db7f28f25ccd3654c5f6ae83daa0c401fa1 | [
"MIT"
]
| null | null | null | release/stubs/Autodesk/AutoCAD/EditorInput.py | paoloemilioserra/ironpython-stubs | 49d92db7f28f25ccd3654c5f6ae83daa0c401fa1 | [
"MIT"
]
| null | null | null | release/stubs/Autodesk/AutoCAD/EditorInput.py | paoloemilioserra/ironpython-stubs | 49d92db7f28f25ccd3654c5f6ae83daa0c401fa1 | [
"MIT"
]
| null | null | null | # encoding: utf-8
# module Autodesk.AutoCAD.EditorInput calls itself EditorInput
# from Acmgd, Version=24.0.0.0, Culture=neutral, PublicKeyToken=null, accoremgd, Version=24.0.0.0, Culture=neutral, PublicKeyToken=null
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class AddedKeywords(Enum):
""" enum AddedKeywords, values: All (4), CrossingCPolygon (32), Fence (64), Group (1024), Last (128), LastAllPrevious (1), Multiple (16), PickImplied (2), Previous (256), WindowCrossingBoxWPolygonCPolygon (8), WindowWPolygon (512) """
All = None
CrossingCPolygon = None
Fence = None
Group = None
Last = None
LastAllPrevious = None
Multiple = None
PickImplied = None
Previous = None
value__ = None
WindowCrossingBoxWPolygonCPolygon = None
WindowWPolygon = None
class Camera(Entity):
# no doc
def Dispose(self):
""" Dispose(self: DBObject, A_0: bool) """
pass
BackClipDistance = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: BackClipDistance(self: Camera) -> float
"""
BackClipEnabled = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: BackClipEnabled(self: Camera) -> bool
"""
FieldOfView = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: FieldOfView(self: Camera) -> float
"""
FrontClipDistance = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: FrontClipDistance(self: Camera) -> float
"""
FrontClipEnabled = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: FrontClipEnabled(self: Camera) -> bool
"""
IsCameraPlottable = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: IsCameraPlottable(self: Camera) -> bool
"""
LensLength = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: LensLength(self: Camera) -> float
"""
Position = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Position(self: Camera) -> Point3d
"""
Target = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Target(self: Camera) -> Point3d
"""
ViewId = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ViewId(self: Camera) -> ObjectId
"""
ViewTwist = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ViewTwist(self: Camera) -> float
"""
class ConstraintUtilities(object):
""" ConstraintUtilities() """
@staticmethod
def ShowConstraintBar(subentityPaths, bToShow):
""" ShowConstraintBar(subentityPaths: Array[FullSubentityPath], bToShow: bool) -> bool """
pass
class SelectedObject(object):
"""
SelectedObject(id: ObjectId, subSelections: Array[SelectedSubObject])
SelectedObject(id: ObjectId, method: SelectionMethod, gsMarker: IntPtr)
SelectedObject(id: ObjectId, method: SelectionMethod, gsMarker: Int64)
"""
def GetSubentities(self):
""" GetSubentities(self: SelectedObject) -> Array[SelectedSubObject] """
pass
def ToString(self, provider=None):
"""
ToString(self: SelectedObject, provider: IFormatProvider) -> str
ToString(self: SelectedObject) -> str
"""
pass
@staticmethod # known case of __new__
def __new__(self, id, *__args):
"""
__new__(cls: type, id: ObjectId, subSelections: Array[SelectedSubObject])
__new__(cls: type, id: ObjectId, method: SelectionMethod, gsMarker: IntPtr)
__new__(cls: type, id: ObjectId, method: SelectionMethod, gsMarker: Int64)
"""
pass
GraphicsSystemMarker = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GraphicsSystemMarker(self: SelectedObject) -> Int64
"""
GraphicsSystemMarkerPtr = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GraphicsSystemMarkerPtr(self: SelectedObject) -> IntPtr
"""
ObjectId = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ObjectId(self: SelectedObject) -> ObjectId
"""
OptionalDetails = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: OptionalDetails(self: SelectedObject) -> SelectionDetails
"""
SelectionMethod = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SelectionMethod(self: SelectedObject) -> SelectionMethod
"""
class CrossingOrWindowSelectedObject(SelectedObject):
"""
CrossingOrWindowSelectedObject(id: ObjectId, method: SelectionMethod, gsMarker: IntPtr)
CrossingOrWindowSelectedObject(id: ObjectId, method: SelectionMethod, gsMarker: Int64)
"""
def GetPickPoints(self):
""" GetPickPoints(self: CrossingOrWindowSelectedObject) -> Array[PickPointDescriptor] """
pass
def ToString(self, provider=None):
"""
ToString(self: CrossingOrWindowSelectedObject, provider: IFormatProvider) -> str
ToString(self: CrossingOrWindowSelectedObject) -> str
"""
pass
@staticmethod # known case of __new__
def __new__(self, id, method, gsMarker):
"""
__new__(cls: type, id: ObjectId, method: SelectionMethod, gsMarker: IntPtr)
__new__(cls: type, id: ObjectId, method: SelectionMethod, gsMarker: Int64)
"""
pass
class SelectedSubObject(object):
"""
SelectedSubObject(path: FullSubentityPath, method: SelectionMethod, gsMarker: IntPtr)
SelectedSubObject(path: FullSubentityPath, method: SelectionMethod, gsMarker: Int64)
"""
def ToString(self, provider=None):
"""
ToString(self: SelectedSubObject, provider: IFormatProvider) -> str
ToString(self: SelectedSubObject) -> str
"""
pass
@staticmethod # known case of __new__
def __new__(self, path, method, gsMarker):
"""
__new__(cls: type, path: FullSubentityPath, method: SelectionMethod, gsMarker: IntPtr)
__new__(cls: type, path: FullSubentityPath, method: SelectionMethod, gsMarker: Int64)
"""
pass
FullSubentityPath = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: FullSubentityPath(self: SelectedSubObject) -> FullSubentityPath
"""
GraphicsSystemMarker = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GraphicsSystemMarker(self: SelectedSubObject) -> Int64
"""
GraphicsSystemMarkerPtr = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GraphicsSystemMarkerPtr(self: SelectedSubObject) -> IntPtr
"""
OptionalDetails = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: OptionalDetails(self: SelectedSubObject) -> SelectionDetails
"""
SelectionMethod = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SelectionMethod(self: SelectedSubObject) -> SelectionMethod
"""
class CrossingOrWindowSelectedSubObject(SelectedSubObject):
"""
CrossingOrWindowSelectedSubObject(path: FullSubentityPath, method: SelectionMethod, gsMarker: IntPtr)
CrossingOrWindowSelectedSubObject(path: FullSubentityPath, method: SelectionMethod, gsMarker: Int64)
"""
def GetPickPoints(self):
""" GetPickPoints(self: CrossingOrWindowSelectedSubObject) -> Array[PickPointDescriptor] """
pass
def ToString(self, provider=None):
"""
ToString(self: CrossingOrWindowSelectedSubObject, provider: IFormatProvider) -> str
ToString(self: CrossingOrWindowSelectedSubObject) -> str
"""
pass
@staticmethod # known case of __new__
def __new__(self, path, method, gsMarker):
"""
__new__(cls: type, path: FullSubentityPath, method: SelectionMethod, gsMarker: IntPtr)
__new__(cls: type, path: FullSubentityPath, method: SelectionMethod, gsMarker: Int64)
"""
pass
class CursorBadgeUtilities(object):
""" CursorBadgeUtilities() """
def AddSupplementalCursorImage(self, cursorImage, priority):
""" AddSupplementalCursorImage(self: CursorBadgeUtilities, cursorImage: ImageBGRA32, priority: int) -> bool """
pass
def GetSupplementalCursorOffset(self, x, y):
""" GetSupplementalCursorOffset(self: CursorBadgeUtilities, x: int, y: int) -> (int, int) """
pass
def HasSupplementalCursorImage(self):
""" HasSupplementalCursorImage(self: CursorBadgeUtilities) -> bool """
pass
def RemoveSupplementalCursorImage(self, cursorImage):
""" RemoveSupplementalCursorImage(self: CursorBadgeUtilities, cursorImage: ImageBGRA32) -> bool """
pass
def SetSupplementalCursorOffset(self, x, y):
""" SetSupplementalCursorOffset(self: CursorBadgeUtilities, x: int, y: int) """
pass
class CursorType(Enum):
""" enum CursorType, values: Crosshair (0), CrosshairNoRotate (6), EntitySelect (8), EntitySelectNoPerspective (10), Invisible (7), NoSpecialCursor (-1), NotRotated (3), Parallelogram (9), PickfirstOrGrips (11), RectangularCursor (1), RotatedCrosshair (5), RubberBand (2), TargetBox (4) """
Crosshair = None
CrosshairNoRotate = None
EntitySelect = None
EntitySelectNoPerspective = None
Invisible = None
NoSpecialCursor = None
NotRotated = None
Parallelogram = None
PickfirstOrGrips = None
RectangularCursor = None
RotatedCrosshair = None
RubberBand = None
TargetBox = None
value__ = None
class DeviceInputEventArgs(EventArgs):
# no doc
GraphicsSystemMarker = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GraphicsSystemMarker(self: DeviceInputEventArgs) -> IntPtr
"""
Handled = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Handled(self: DeviceInputEventArgs) -> bool
Set: Handled(self: DeviceInputEventArgs) = value
"""
LParam = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: LParam(self: DeviceInputEventArgs) -> IntPtr
"""
Message = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Message(self: DeviceInputEventArgs) -> int
"""
WParam = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: WParam(self: DeviceInputEventArgs) -> IntPtr
"""
class DeviceInputEventHandler(MulticastDelegate):
""" DeviceInputEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: DeviceInputEventHandler, sender: object, e: DeviceInputEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: DeviceInputEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: DeviceInputEventHandler, sender: object, e: DeviceInputEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class DisposableSelectionSet(object):
""" DisposableSelectionSet(selectionSet: SelectionSetDelayMarshalled) """
def Dispose(self):
""" Dispose(self: DisposableSelectionSet) """
pass
def __enter__(self, *args): #cannot find CLR method
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args): #cannot find CLR method
""" __exit__(self: IDisposable, exc_type: object, exc_value: object, exc_back: object) """
pass
@staticmethod # known case of __new__
def __new__(self, selectionSet):
""" __new__(cls: type, selectionSet: SelectionSetDelayMarshalled) """
pass
class DragCallback(MulticastDelegate):
""" DragCallback(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, current, xform, callback, obj):
""" BeginInvoke(self: DragCallback, current: Point3d, callback: AsyncCallback, obj: object) -> (IAsyncResult, Matrix3d) """
pass
def EndInvoke(self, result):
""" EndInvoke(self: DragCallback, result: IAsyncResult) -> SamplerStatus """
pass
def Invoke(self, current, xform):
""" Invoke(self: DragCallback, current: Point3d) -> (SamplerStatus, Matrix3d) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class DragCursor(Enum):
""" enum DragCursor, values: None (1), Normal (0), Selection (2) """
None = None
Normal = None
Selection = None
value__ = None
class DraggingEndedEventArgs(EventArgs):
# no doc
Offset = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Offset(self: DraggingEndedEventArgs) -> Vector3d
"""
PickPoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: PickPoint(self: DraggingEndedEventArgs) -> Point3d
"""
Status = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Status(self: DraggingEndedEventArgs) -> PromptStatus
"""
class DraggingEndedEventHandler(MulticastDelegate):
""" DraggingEndedEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: DraggingEndedEventHandler, sender: object, e: DraggingEndedEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: DraggingEndedEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: DraggingEndedEventHandler, sender: object, e: DraggingEndedEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class DraggingEventArgs(EventArgs):
""" DraggingEventArgs(prompt: str) """
@staticmethod # known case of __new__
def __new__(self, prompt):
""" __new__(cls: type, prompt: str) """
pass
Prompt = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Prompt(self: DraggingEventArgs) -> str
"""
class DraggingEventHandler(MulticastDelegate):
""" DraggingEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: DraggingEventHandler, sender: object, e: DraggingEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: DraggingEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: DraggingEventHandler, sender: object, e: DraggingEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class Jig(object):
# no doc
def GetDynamicDimensionData(self, *args): #cannot find CLR method
""" GetDynamicDimensionData(self: Jig, dimScale: float) -> DynamicDimensionDataCollection """
pass
def OnDimensionValueChanged(self, *args): #cannot find CLR method
""" OnDimensionValueChanged(self: Jig, e: DynamicDimensionChangedEventArgs) """
pass
def Sampler(self, *args): #cannot find CLR method
""" Sampler(self: Jig, prompts: JigPrompts) -> SamplerStatus """
pass
class DrawJig(Jig):
# no doc
def ViewportDraw(self, *args): #cannot find CLR method
""" ViewportDraw(self: DrawJig, draw: ViewportDraw) """
pass
def WorldDraw(self, *args): #cannot find CLR method
""" WorldDraw(self: DrawJig, draw: WorldDraw) -> bool """
pass
class Editor(MarshalByRefObject):
# no doc
def ApplyCurDwgLayerTableChanges(self):
""" ApplyCurDwgLayerTableChanges(self: Editor) """
pass
def Command(self, parameter):
""" Command(self: Editor, *parameter: Array[object]) """
pass
def CommandAsync(self, parameter):
""" CommandAsync(self: Editor, *parameter: Array[object]) -> CommandResult """
pass
def DoPrompt(self, opt):
""" DoPrompt(self: Editor, opt: PromptOptions) -> PromptResult """
pass
def Drag(self, *__args):
"""
Drag(self: Editor, jig: Jig) -> PromptResult
Drag(self: Editor, selection: SelectionSet, message: str, callback: DragCallback) -> PromptPointResult
Drag(self: Editor, options: PromptDragOptions) -> PromptPointResult
"""
pass
def DrawVector(self, from, to, color, drawHighlighted):
""" DrawVector(self: Editor, from: Point3d, to: Point3d, color: int, drawHighlighted: bool) """
pass
def DrawVectors(self, rb, transform):
""" DrawVectors(self: Editor, rb: ResultBuffer, transform: Matrix3d) """
pass
def GetAngle(self, *__args):
"""
GetAngle(self: Editor, message: str) -> PromptDoubleResult
GetAngle(self: Editor, options: PromptAngleOptions) -> PromptDoubleResult
"""
pass
def GetCommandVersion(self):
""" GetCommandVersion(self: Editor) -> int """
pass
def GetCorner(self, *__args):
"""
GetCorner(self: Editor, message: str, basePoint: Point3d) -> PromptPointResult
GetCorner(self: Editor, options: PromptCornerOptions) -> PromptPointResult
"""
pass
def GetCurrentView(self):
""" GetCurrentView(self: Editor) -> ViewTableRecord """
pass
def GetDistance(self, *__args):
"""
GetDistance(self: Editor, message: str) -> PromptDoubleResult
GetDistance(self: Editor, options: PromptDistanceOptions) -> PromptDoubleResult
"""
pass
def GetDouble(self, *__args):
"""
GetDouble(self: Editor, message: str) -> PromptDoubleResult
GetDouble(self: Editor, options: PromptDoubleOptions) -> PromptDoubleResult
"""
pass
def GetEntity(self, *__args):
"""
GetEntity(self: Editor, message: str) -> PromptEntityResult
GetEntity(self: Editor, options: PromptEntityOptions) -> PromptEntityResult
"""
pass
def GetFileNameForOpen(self, *__args):
"""
GetFileNameForOpen(self: Editor, message: str) -> PromptFileNameResult
GetFileNameForOpen(self: Editor, options: PromptOpenFileOptions) -> PromptFileNameResult
"""
pass
def GetFileNameForSave(self, *__args):
"""
GetFileNameForSave(self: Editor, message: str) -> PromptFileNameResult
GetFileNameForSave(self: Editor, options: PromptSaveFileOptions) -> PromptFileNameResult
"""
pass
def GetInteger(self, *__args):
"""
GetInteger(self: Editor, message: str) -> PromptIntegerResult
GetInteger(self: Editor, options: PromptIntegerOptions) -> PromptIntegerResult
"""
pass
def GetKeywords(self, *__args):
"""
GetKeywords(self: Editor, message: str, *globalKeywords: Array[str]) -> PromptResult
GetKeywords(self: Editor, options: PromptKeywordOptions) -> PromptResult
"""
pass
def GetNestedEntity(self, *__args):
"""
GetNestedEntity(self: Editor, message: str) -> PromptNestedEntityResult
GetNestedEntity(self: Editor, options: PromptNestedEntityOptions) -> PromptNestedEntityResult
"""
pass
def GetPoint(self, *__args):
"""
GetPoint(self: Editor, message: str) -> PromptPointResult
GetPoint(self: Editor, options: PromptPointOptions) -> PromptPointResult
"""
pass
def GetSelection(self, *__args):
"""
GetSelection(self: Editor, filter: SelectionFilter) -> PromptSelectionResult
GetSelection(self: Editor) -> PromptSelectionResult
GetSelection(self: Editor, options: PromptSelectionOptions, filter: SelectionFilter) -> PromptSelectionResult
GetSelection(self: Editor, options: PromptSelectionOptions) -> PromptSelectionResult
"""
pass
def GetString(self, *__args):
"""
GetString(self: Editor, message: str) -> PromptResult
GetString(self: Editor, options: PromptStringOptions) -> PromptResult
"""
pass
def GetViewportNumber(self, point):
""" GetViewportNumber(self: Editor, point: Point) -> int """
pass
def InitCommandVersion(self, nVersion):
""" InitCommandVersion(self: Editor, nVersion: int) -> int """
pass
def PointToScreen(self, pt, viewportNumber):
""" PointToScreen(self: Editor, pt: Point3d, viewportNumber: int) -> Point """
pass
def PointToWorld(self, pt, viewportNumber=None):
"""
PointToWorld(self: Editor, pt: Point) -> Point3d
PointToWorld(self: Editor, pt: Point, viewportNumber: int) -> Point3d
"""
pass
def PostCommandPrompt(self):
""" PostCommandPrompt(self: Editor) """
pass
def Regen(self):
""" Regen(self: Editor) """
pass
def SelectAll(self, filter=None):
"""
SelectAll(self: Editor) -> PromptSelectionResult
SelectAll(self: Editor, filter: SelectionFilter) -> PromptSelectionResult
"""
pass
def SelectCrossingPolygon(self, polygon, filter=None):
"""
SelectCrossingPolygon(self: Editor, polygon: Point3dCollection) -> PromptSelectionResult
SelectCrossingPolygon(self: Editor, polygon: Point3dCollection, filter: SelectionFilter) -> PromptSelectionResult
"""
pass
def SelectCrossingWindow(self, pt1, pt2, filter=None, forceSubEntitySelection=None):
"""
SelectCrossingWindow(self: Editor, pt1: Point3d, pt2: Point3d) -> PromptSelectionResult
SelectCrossingWindow(self: Editor, pt1: Point3d, pt2: Point3d, filter: SelectionFilter) -> PromptSelectionResult
SelectCrossingWindow(self: Editor, pt1: Point3d, pt2: Point3d, filter: SelectionFilter, forceSubEntitySelection: bool) -> PromptSelectionResult
"""
pass
def SelectFence(self, fence, filter=None):
"""
SelectFence(self: Editor, fence: Point3dCollection) -> PromptSelectionResult
SelectFence(self: Editor, fence: Point3dCollection, filter: SelectionFilter) -> PromptSelectionResult
"""
pass
def SelectImplied(self):
""" SelectImplied(self: Editor) -> PromptSelectionResult """
pass
def SelectLast(self):
""" SelectLast(self: Editor) -> PromptSelectionResult """
pass
def SelectPrevious(self):
""" SelectPrevious(self: Editor) -> PromptSelectionResult """
pass
def SelectWindow(self, pt1, pt2, filter=None):
"""
SelectWindow(self: Editor, pt1: Point3d, pt2: Point3d) -> PromptSelectionResult
SelectWindow(self: Editor, pt1: Point3d, pt2: Point3d, filter: SelectionFilter) -> PromptSelectionResult
"""
pass
def SelectWindowPolygon(self, polygon, filter=None):
"""
SelectWindowPolygon(self: Editor, polygon: Point3dCollection) -> PromptSelectionResult
SelectWindowPolygon(self: Editor, polygon: Point3dCollection, filter: SelectionFilter) -> PromptSelectionResult
"""
pass
def SetCurrentView(self, value):
""" SetCurrentView(self: Editor, value: ViewTableRecord) """
pass
def SetImpliedSelection(self, *__args):
""" SetImpliedSelection(self: Editor, selectedObjects: Array[ObjectId])SetImpliedSelection(self: Editor, selectionSet: SelectionSet) """
pass
def Snap(self, snapMode, input):
""" Snap(self: Editor, snapMode: str, input: Point3d) -> Point3d """
pass
def StartUserInteraction(self, *__args):
"""
StartUserInteraction(self: Editor, window: Window) -> EditorUserInteraction
StartUserInteraction(self: Editor, hwnd: IntPtr) -> EditorUserInteraction
"""
pass
def SwitchToModelSpace(self):
""" SwitchToModelSpace(self: Editor) """
pass
def SwitchToPaperSpace(self):
""" SwitchToPaperSpace(self: Editor) """
pass
def TraceBoundary(self, seedPoint, detectIslands):
""" TraceBoundary(self: Editor, seedPoint: Point3d, detectIslands: bool) -> DBObjectCollection """
pass
def TurnForcedPickOff(self):
""" TurnForcedPickOff(self: Editor) -> int """
pass
def TurnForcedPickOn(self):
""" TurnForcedPickOn(self: Editor) -> int """
pass
def TurnSubentityWindowSelectionOff(self):
""" TurnSubentityWindowSelectionOff(self: Editor) """
pass
def TurnSubentityWindowSelectionOn(self):
""" TurnSubentityWindowSelectionOn(self: Editor) """
pass
def UpdateScreen(self):
""" UpdateScreen(self: Editor) """
pass
def UpdateTiledViewportsFromDatabase(self):
""" UpdateTiledViewportsFromDatabase(self: Editor) """
pass
def UpdateTiledViewportsInDatabase(self):
""" UpdateTiledViewportsInDatabase(self: Editor) """
pass
def ViewportIdFromNumber(self, viewportNumber):
""" ViewportIdFromNumber(self: Editor, viewportNumber: int) -> ObjectId """
pass
def WriteMessage(self, message, parameter=None):
""" WriteMessage(self: Editor, message: str)WriteMessage(self: Editor, message: str, *parameter: Array[object]) """
pass
ActiveViewportId = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ActiveViewportId(self: Editor) -> ObjectId
"""
CurrentUserCoordinateSystem = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CurrentUserCoordinateSystem(self: Editor) -> Matrix3d
Set: CurrentUserCoordinateSystem(self: Editor) = value
"""
CurrentViewportObjectId = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CurrentViewportObjectId(self: Editor) -> ObjectId
"""
Document = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Document(self: Editor) -> Document
"""
IsDragging = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: IsDragging(self: Editor) -> bool
"""
IsQuiescent = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: IsQuiescent(self: Editor) -> bool
"""
IsQuiescentForTransparentCommand = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: IsQuiescentForTransparentCommand(self: Editor) -> bool
"""
MouseHasMoved = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: MouseHasMoved(self: Editor) -> bool
"""
UseCommandLineInterface = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UseCommandLineInterface(self: Editor) -> bool
"""
CommandResult = None
Dragging = None
DraggingEnded = None
EnteringQuiescentState = None
LeavingQuiescentState = None
PauseToken = '\\'
PointFilter = None
PointMonitor = None
PromptedForAngle = None
PromptedForCorner = None
PromptedForDistance = None
PromptedForDouble = None
PromptedForEntity = None
PromptedForInteger = None
PromptedForKeyword = None
PromptedForNestedEntity = None
PromptedForPoint = None
PromptedForSelection = None
PromptedForString = None
PromptForEntityEnding = None
PromptForSelectionEnding = None
PromptingForAngle = None
PromptingForCorner = None
PromptingForDistance = None
PromptingForDouble = None
PromptingForEntity = None
PromptingForInteger = None
PromptingForKeyword = None
PromptingForNestedEntity = None
PromptingForPoint = None
PromptingForSelection = None
PromptingForString = None
Rollover = None
SelectionAdded = None
SelectionRemoved = None
class EditorExtension(object):
# no doc
@staticmethod
def GetViewportNumber(editor, point):
""" GetViewportNumber(editor: Editor, point: Point) -> int """
pass
@staticmethod
def PointToScreen(editor, pt, viewportNumber):
""" PointToScreen(editor: Editor, pt: Point3d, viewportNumber: int) -> Point """
pass
@staticmethod
def PointToWorld(editor, pt, viewportNumber=None):
"""
PointToWorld(editor: Editor, pt: Point) -> Point3d
PointToWorld(editor: Editor, pt: Point, viewportNumber: int) -> Point3d
"""
pass
@staticmethod
def StartUserInteraction(editor, modalForm):
""" StartUserInteraction(editor: Editor, modalForm: Control) -> EditorUserInteraction """
pass
__all__ = [
'GetViewportNumber',
'PointToScreen',
'PointToWorld',
'StartUserInteraction',
]
class EditorUserInteraction(object):
# no doc
def Dispose(self):
""" Dispose(self: EditorUserInteraction) """
pass
def End(self):
""" End(self: EditorUserInteraction) """
pass
def __enter__(self, *args): #cannot find CLR method
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args): #cannot find CLR method
""" __exit__(self: IDisposable, exc_type: object, exc_value: object, exc_back: object) """
pass
class EditorVisualStyle(object):
""" EditorVisualStyle() """
@staticmethod
def setCvpVS2d():
""" setCvpVS2d() """
pass
IsVS2dType = True
IsVS3dType = False
class EntityJig(Jig):
# no doc
def Update(self, *args): #cannot find CLR method
""" Update(self: EntityJig) -> bool """
pass
@staticmethod # known case of __new__
def __new__(self, *args): #cannot find CLR constructor
""" __new__(cls: type, entity: Entity) """
pass
Entity = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
class FenceSelectedObject(SelectedObject):
"""
FenceSelectedObject(id: ObjectId, method: SelectionMethod, gsMarker: IntPtr, descriptors: Array[PickPointDescriptor])
FenceSelectedObject(id: ObjectId, method: SelectionMethod, gsMarker: Int64, descriptors: Array[PickPointDescriptor])
"""
def GetIntersectionPoints(self):
""" GetIntersectionPoints(self: FenceSelectedObject) -> Array[PickPointDescriptor] """
pass
def ToString(self, provider=None):
"""
ToString(self: FenceSelectedObject, provider: IFormatProvider) -> str
ToString(self: FenceSelectedObject) -> str
"""
pass
@staticmethod # known case of __new__
def __new__(self, id, method, gsMarker, descriptors):
"""
__new__(cls: type, id: ObjectId, method: SelectionMethod, gsMarker: IntPtr, descriptors: Array[PickPointDescriptor])
__new__(cls: type, id: ObjectId, method: SelectionMethod, gsMarker: Int64, descriptors: Array[PickPointDescriptor])
"""
pass
class FenceSelectedSubObject(SelectedSubObject):
"""
FenceSelectedSubObject(path: FullSubentityPath, method: SelectionMethod, gsMarker: IntPtr, descriptors: Array[PickPointDescriptor])
FenceSelectedSubObject(path: FullSubentityPath, method: SelectionMethod, gsMarker: Int64, descriptors: Array[PickPointDescriptor])
"""
def GetIntersectionPoints(self):
""" GetIntersectionPoints(self: FenceSelectedSubObject) -> Array[PickPointDescriptor] """
pass
def ToString(self, provider=None):
"""
ToString(self: FenceSelectedSubObject, provider: IFormatProvider) -> str
ToString(self: FenceSelectedSubObject) -> str
"""
pass
@staticmethod # known case of __new__
def __new__(self, path, method, gsMarker, descriptors):
"""
__new__(cls: type, path: FullSubentityPath, method: SelectionMethod, gsMarker: IntPtr, descriptors: Array[PickPointDescriptor])
__new__(cls: type, path: FullSubentityPath, method: SelectionMethod, gsMarker: Int64, descriptors: Array[PickPointDescriptor])
"""
pass
class InputPointContext(object):
# no doc
def Dispose(self):
""" Dispose(self: InputPointContext) """
pass
def GetAlignmentPaths(self):
""" GetAlignmentPaths(self: InputPointContext) -> Array[Curve3d] """
pass
def GetCustomObjectSnapModes(self):
""" GetCustomObjectSnapModes(self: InputPointContext) -> Array[CustomObjectSnapMode] """
pass
def GetCustomObjectSnapOverrides(self):
""" GetCustomObjectSnapOverrides(self: InputPointContext) -> Array[CustomObjectSnapMode] """
pass
def GetKeyPointEntities(self):
""" GetKeyPointEntities(self: InputPointContext) -> Array[FullSubentityPath] """
pass
def GetPickedEntities(self):
""" GetPickedEntities(self: InputPointContext) -> Array[FullSubentityPath] """
pass
def __enter__(self, *args): #cannot find CLR method
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args): #cannot find CLR method
""" __exit__(self: IDisposable, exc_type: object, exc_value: object, exc_back: object) """
pass
CartesianSnappedPoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CartesianSnappedPoint(self: InputPointContext) -> Point3d
"""
ComputedPoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ComputedPoint(self: InputPointContext) -> Point3d
"""
Document = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Document(self: InputPointContext) -> Document
"""
DrawContext = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DrawContext(self: InputPointContext) -> ViewportDraw
"""
GrippedPoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GrippedPoint(self: InputPointContext) -> Point3d
"""
History = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: History(self: InputPointContext) -> PointHistoryBits
"""
LastPoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: LastPoint(self: InputPointContext) -> Point3d
"""
ObjectSnapMask = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ObjectSnapMask(self: InputPointContext) -> ObjectSnapMasks
"""
ObjectSnapOverrides = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ObjectSnapOverrides(self: InputPointContext) -> ObjectSnapMasks
"""
ObjectSnappedPoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ObjectSnappedPoint(self: InputPointContext) -> Point3d
"""
PointComputed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: PointComputed(self: InputPointContext) -> bool
"""
RawPoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: RawPoint(self: InputPointContext) -> Point3d
"""
ToolTipText = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ToolTipText(self: InputPointContext) -> str
"""
class PromptOptions(object):
# no doc
def DoIt(self, *args): #cannot find CLR method
""" DoIt(self: PromptOptions) -> PromptResult """
pass
def FormatPrompt(self, *args): #cannot find CLR method
""" FormatPrompt(self: PromptOptions) -> str """
pass
def GetDefaultValueString(self, *args): #cannot find CLR method
""" GetDefaultValueString(self: PromptOptions) -> str """
pass
def SetMessageAndKeywords(self, messageAndKeywords, globalKeywords):
""" SetMessageAndKeywords(self: PromptOptions, messageAndKeywords: str, globalKeywords: str) """
pass
@staticmethod # known case of __new__
def __new__(self, *args): #cannot find CLR constructor
"""
__new__(cls: type, messageAndKeywords: str, globalKeywords: str)
__new__(cls: type, message: str)
"""
pass
AppendKeywordsToMessage = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AppendKeywordsToMessage(self: PromptOptions) -> bool
Set: AppendKeywordsToMessage(self: PromptOptions) = value
"""
IsReadOnly = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: IsReadOnly(self: PromptOptions) -> bool
"""
Keywords = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Keywords(self: PromptOptions) -> KeywordCollection
"""
Message = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Message(self: PromptOptions) -> str
Set: Message(self: PromptOptions) = value
"""
class JigPromptOptions(PromptOptions):
# no doc
def CalculateResult(self, *args): #cannot find CLR method
""" CalculateResult(self: JigPromptOptions, status: DragStatus, result: PromptResult) """
pass
def CommonInit(self, *args): #cannot find CLR method
""" CommonInit(self: JigPromptOptions) """
pass
@staticmethod # known case of __new__
def __new__(self, *args): #cannot find CLR constructor
"""
__new__(cls: type, messageAndKeywords: str, globalKeywords: str)
__new__(cls: type, message: str)
__new__(cls: type)
"""
pass
Cursor = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Cursor(self: JigPromptOptions) -> CursorType
Set: Cursor(self: JigPromptOptions) = value
"""
UserInputControls = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UserInputControls(self: JigPromptOptions) -> UserInputControls
Set: UserInputControls(self: JigPromptOptions) = value
"""
class JigPromptGeometryOptions(JigPromptOptions):
"""
JigPromptGeometryOptions(messageAndKeywords: str, globalKeywords: str)
JigPromptGeometryOptions(message: str)
JigPromptGeometryOptions()
"""
@staticmethod # known case of __new__
def __new__(self, *__args):
"""
__new__(cls: type, messageAndKeywords: str, globalKeywords: str)
__new__(cls: type, message: str)
__new__(cls: type)
"""
pass
BasePoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: BasePoint(self: JigPromptGeometryOptions) -> Point3d
Set: BasePoint(self: JigPromptGeometryOptions) = value
"""
UseBasePoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UseBasePoint(self: JigPromptGeometryOptions) -> bool
Set: UseBasePoint(self: JigPromptGeometryOptions) = value
"""
class JigPromptAngleOptions(JigPromptGeometryOptions):
"""
JigPromptAngleOptions(messageAndKeywords: str, globalKeywords: str)
JigPromptAngleOptions(message: str)
JigPromptAngleOptions()
"""
@staticmethod # known case of __new__
def __new__(self, *__args):
"""
__new__(cls: type, messageAndKeywords: str, globalKeywords: str)
__new__(cls: type, message: str)
__new__(cls: type)
"""
pass
DefaultValue = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DefaultValue(self: JigPromptAngleOptions) -> float
Set: DefaultValue(self: JigPromptAngleOptions) = value
"""
class JigPromptDistanceOptions(JigPromptGeometryOptions):
"""
JigPromptDistanceOptions(messageAndKeywords: str, globalKeywords: str)
JigPromptDistanceOptions(message: str)
JigPromptDistanceOptions()
"""
@staticmethod # known case of __new__
def __new__(self, *__args):
"""
__new__(cls: type, messageAndKeywords: str, globalKeywords: str)
__new__(cls: type, message: str)
__new__(cls: type)
"""
pass
DefaultValue = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DefaultValue(self: JigPromptDistanceOptions) -> float
Set: DefaultValue(self: JigPromptDistanceOptions) = value
"""
class JigPromptPointOptions(JigPromptGeometryOptions):
"""
JigPromptPointOptions(messageAndKeywords: str, globalKeywords: str)
JigPromptPointOptions(message: str)
JigPromptPointOptions()
"""
@staticmethod # known case of __new__
def __new__(self, *__args):
"""
__new__(cls: type, messageAndKeywords: str, globalKeywords: str)
__new__(cls: type, message: str)
__new__(cls: type)
"""
pass
DefaultValue = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DefaultValue(self: JigPromptPointOptions) -> Point3d
Set: DefaultValue(self: JigPromptPointOptions) = value
"""
class JigPrompts(object):
# no doc
def AcquireAngle(self, *__args):
"""
AcquireAngle(self: JigPrompts) -> PromptDoubleResult
AcquireAngle(self: JigPrompts, options: JigPromptAngleOptions) -> PromptDoubleResult
AcquireAngle(self: JigPrompts, messageAndKeywords: str, globalKeywords: str) -> PromptDoubleResult
AcquireAngle(self: JigPrompts, message: str) -> PromptDoubleResult
"""
pass
def AcquireDistance(self, *__args):
"""
AcquireDistance(self: JigPrompts) -> PromptDoubleResult
AcquireDistance(self: JigPrompts, options: JigPromptDistanceOptions) -> PromptDoubleResult
AcquireDistance(self: JigPrompts, messageAndKeywords: str, globalKeywords: str) -> PromptDoubleResult
AcquireDistance(self: JigPrompts, message: str) -> PromptDoubleResult
"""
pass
def AcquirePoint(self, *__args):
"""
AcquirePoint(self: JigPrompts) -> PromptPointResult
AcquirePoint(self: JigPrompts, options: JigPromptPointOptions) -> PromptPointResult
AcquirePoint(self: JigPrompts, messageAndKeywords: str, globalKeywords: str) -> PromptPointResult
AcquirePoint(self: JigPrompts, message: str) -> PromptPointResult
"""
pass
def AcquireString(self, *__args):
"""
AcquireString(self: JigPrompts) -> PromptResult
AcquireString(self: JigPrompts, options: JigPromptStringOptions) -> PromptResult
AcquireString(self: JigPrompts, messageAndKeywords: str, globalKeywords: str) -> PromptResult
AcquireString(self: JigPrompts, message: str) -> PromptResult
"""
pass
class JigPromptStringOptions(JigPromptOptions):
"""
JigPromptStringOptions(messageAndKeywords: str, globalKeywords: str)
JigPromptStringOptions(message: str)
JigPromptStringOptions()
"""
@staticmethod # known case of __new__
def __new__(self, *__args):
"""
__new__(cls: type, messageAndKeywords: str, globalKeywords: str)
__new__(cls: type, message: str)
__new__(cls: type)
"""
pass
DefaultValue = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DefaultValue(self: JigPromptStringOptions) -> str
Set: DefaultValue(self: JigPromptStringOptions) = value
"""
class Keyword(object):
# no doc
DisplayName = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DisplayName(self: Keyword) -> str
Set: DisplayName(self: Keyword) = value
"""
Enabled = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Enabled(self: Keyword) -> bool
Set: Enabled(self: Keyword) = value
"""
GlobalName = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GlobalName(self: Keyword) -> str
Set: GlobalName(self: Keyword) = value
"""
IsReadOnly = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: IsReadOnly(self: Keyword) -> bool
"""
LocalName = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: LocalName(self: Keyword) -> str
Set: LocalName(self: Keyword) = value
"""
Visible = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Visible(self: Keyword) -> bool
Set: Visible(self: Keyword) = value
"""
class KeywordCollection(object):
""" KeywordCollection() """
def Add(self, globalName, localName=None, displayName=None, visible=None, enabled=None):
""" Add(self: KeywordCollection, globalName: str, localName: str, displayName: str)Add(self: KeywordCollection, globalName: str, localName: str, displayName: str, visible: bool, enabled: bool)Add(self: KeywordCollection, globalName: str)Add(self: KeywordCollection, globalName: str, localName: str) """
pass
def Clear(self):
""" Clear(self: KeywordCollection) """
pass
def CopyTo(self, array, index):
""" CopyTo(self: KeywordCollection, array: Array[Keyword], index: int) """
pass
def GetDisplayString(self, showNoDefault):
""" GetDisplayString(self: KeywordCollection, showNoDefault: bool) -> str """
pass
def GetEnumerator(self):
""" GetEnumerator(self: KeywordCollection) -> IEnumerator """
pass
def __add__(self, *args): #cannot find CLR method
""" x.__add__(y) <==> x+yx.__add__(y) <==> x+yx.__add__(y) <==> x+yx.__add__(y) <==> x+y """
pass
def __getitem__(self, *args): #cannot find CLR method
""" x.__getitem__(y) <==> x[y] """
pass
def __iter__(self, *args): #cannot find CLR method
""" __iter__(self: IEnumerable) -> object """
pass
def __len__(self, *args): #cannot find CLR method
""" x.__len__() <==> len(x) """
pass
Count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Count(self: KeywordCollection) -> int
"""
Default = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Default(self: KeywordCollection) -> str
Set: Default(self: KeywordCollection) = value
"""
IsReadOnly = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: IsReadOnly(self: KeywordCollection) -> bool
"""
class LivePreview(DisposableWrapper):
"""
LivePreview()
LivePreview(doc: Document)
LivePreview(doc: Document, startPending: bool)
"""
def AbortAll(self):
""" AbortAll(self: LivePreview) """
pass
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
def EndPreview(self, *__args):
""" EndPreview(self: LivePreview, delayTime: int)EndPreview(self: LivePreview)EndPreview(self: LivePreview, delayTime: int, bRegen: bool)EndPreview(self: LivePreview, bRegen: bool) """
pass
def EndRecording(self):
""" EndRecording(self: LivePreview) """
pass
@staticmethod
def IsPreviewRecording(doc=None):
"""
IsPreviewRecording(doc: Document) -> bool
IsPreviewRecording() -> bool
"""
pass
@staticmethod
def IsPreviewStarted(doc=None):
"""
IsPreviewStarted(doc: Document) -> bool
IsPreviewStarted() -> bool
"""
pass
def QueueAction(self, action, delayTime=None):
""" QueueAction(self: LivePreview, action: LivePreviewActionBase)QueueAction(self: LivePreview, action: LivePreviewActionBase, delayTime: int) """
pass
def StartRecording(self):
""" StartRecording(self: LivePreview) """
pass
@staticmethod # known case of __new__
def __new__(self, doc=None, startPending=None):
"""
__new__(cls: type)
__new__(cls: type, doc: Document)
__new__(cls: type, doc: Document, startPending: bool)
"""
pass
PreviewEnded = None
Previewing = None
PreviewStarted = None
PreviewWillEnd = None
PreviewWillStart = None
RecordingEnded = None
RecordingStarted = None
RecordingWillEnd = None
RecordingWillStart = None
class LivePreviewActionBase(object):
# no doc
def Execute(self):
""" Execute(self: LivePreviewActionBase) """
pass
def OnAborted(self):
""" OnAborted(self: LivePreviewActionBase) """
pass
class LivePreviewAction(LivePreviewActionBase):
""" LivePreviewAction(method: Delegate, *args: Array[object]) """
def Execute(self):
""" Execute(self: LivePreviewAction) """
pass
@staticmethod # known case of __new__
def __new__(self, method, args):
""" __new__(cls: type, method: Delegate, *args: Array[object]) """
pass
class LivePreviewCallback(MulticastDelegate):
""" LivePreviewCallback(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, callback, obj):
""" BeginInvoke(self: LivePreviewCallback, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: LivePreviewCallback, result: IAsyncResult) """
pass
def Invoke(self):
""" Invoke(self: LivePreviewCallback) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class LivePreviewCommand(LivePreviewActionBase):
""" LivePreviewCommand(cmd: str) """
def Execute(self):
""" Execute(self: LivePreviewCommand) """
pass
@staticmethod # known case of __new__
def __new__(self, cmd):
""" __new__(cls: type, cmd: str) """
pass
class LivePreviewContextCallback(MulticastDelegate):
""" LivePreviewContextCallback(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, contextName, contextVal, callback, obj):
""" BeginInvoke(self: LivePreviewContextCallback, contextName: str, contextVal: object, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: LivePreviewContextCallback, result: IAsyncResult) """
pass
def Invoke(self, contextName, contextVal):
""" Invoke(self: LivePreviewContextCallback, contextName: str, contextVal: object) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class LivePreviewContextParameter(object):
# no doc
LivePreview = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: LivePreview(self: LivePreviewContextParameter) -> LivePreview
"""
Type = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Type(self: LivePreviewContextParameter) -> LivePreviewContextType
"""
Value = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Value(self: LivePreviewContextParameter) -> object
"""
class LivePreviewContextProxy(object):
""" LivePreviewContextProxy(contexName: str, callback: Delegate, *parameters: Array[object]) """
def Dispose(self):
""" Dispose(self: LivePreviewContextProxy) """
pass
def __enter__(self, *args): #cannot find CLR method
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args): #cannot find CLR method
""" __exit__(self: IDisposable, exc_type: object, exc_value: object, exc_back: object) """
pass
@staticmethod # known case of __new__
def __new__(self, contexName, callback, parameters):
""" __new__(cls: type, contexName: str, callback: Delegate, *parameters: Array[object]) """
pass
class LivePreviewContextType(Enum):
""" enum LivePreviewContextType, values: EndPreview (0), UpdatePreview (1) """
EndPreview = None
UpdatePreview = None
value__ = None
class LivePreviewDelegate(LivePreviewActionBase):
"""
LivePreviewDelegate(actCallback: LivePreviewCallback, abortedCallback: LivePreviewCallback)
LivePreviewDelegate(actCallback: LivePreviewCallback)
"""
def Execute(self):
""" Execute(self: LivePreviewDelegate) """
pass
def OnAborted(self):
""" OnAborted(self: LivePreviewDelegate) """
pass
@staticmethod # known case of __new__
def __new__(self, actCallback, abortedCallback=None):
"""
__new__(cls: type, actCallback: LivePreviewCallback, abortedCallback: LivePreviewCallback)
__new__(cls: type, actCallback: LivePreviewCallback)
"""
pass
class LivePreviewEventArgs(EventArgs):
"""
LivePreviewEventArgs(*parameters: Array[object])
LivePreviewEventArgs(document: Document, *parameters: Array[object])
LivePreviewEventArgs()
"""
def LockDocument(self):
""" LockDocument(self: LivePreviewEventArgs) -> IDisposable """
pass
@staticmethod # known case of __new__
def __new__(self, *__args):
"""
__new__(cls: type, *parameters: Array[object])
__new__(cls: type, document: Document, *parameters: Array[object])
__new__(cls: type)
"""
pass
AbortPreview = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AbortPreview(self: LivePreviewEventArgs) -> bool
Set: AbortPreview(self: LivePreviewEventArgs) = value
"""
CommandParameter = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CommandParameter(self: LivePreviewEventArgs) -> object
"""
Document = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Document(self: LivePreviewEventArgs) -> Document
"""
Parameters = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Parameters(self: LivePreviewEventArgs) -> Array[object]
"""
class LivePreviewPropertySetting(LivePreviewActionBase):
""" LivePreviewPropertySetting(prop: PropertyDescriptor, component: object, value: object) """
def Execute(self):
""" Execute(self: LivePreviewPropertySetting) """
pass
@staticmethod # known case of __new__
def __new__(self, prop, component, value):
""" __new__(cls: type, prop: PropertyDescriptor, component: object, value: object) """
pass
class ObjectSnapMasks(Enum):
""" enum (flags) ObjectSnapMasks, values: AllowTangent (131072), ApparentIntersection (2048), Center (4), DisablePerpendicular (262144), End (1), Immediate (65536), Insertion (64), Intersection (32), Middle (2), Near (512), Node (8), NoneOverride (2097152), Perpendicular (128), Quadrant (16), Quick (1024), RelativeCartesian (524288), RelativePolar (1048576), Tangent (256) """
AllowTangent = None
ApparentIntersection = None
Center = None
DisablePerpendicular = None
End = None
Immediate = None
Insertion = None
Intersection = None
Middle = None
Near = None
Node = None
NoneOverride = None
Perpendicular = None
Quadrant = None
Quick = None
RelativeCartesian = None
RelativePolar = None
Tangent = None
value__ = None
class PickPointDescriptor(object):
""" PickPointDescriptor(kind: PickPointKind, pointOnLine: Point3d, direction: Vector3d) """
def Equals(self, obj):
""" Equals(self: PickPointDescriptor, obj: object) -> bool """
pass
def GetHashCode(self):
""" GetHashCode(self: PickPointDescriptor) -> int """
pass
def IsEqualTo(self, a, tolerance=None):
"""
IsEqualTo(self: PickPointDescriptor, a: PickPointDescriptor, tolerance: Tolerance) -> bool
IsEqualTo(self: PickPointDescriptor, a: PickPointDescriptor) -> bool
"""
pass
def ToString(self, provider=None):
"""
ToString(self: PickPointDescriptor, provider: IFormatProvider) -> str
ToString(self: PickPointDescriptor) -> str
"""
pass
def __eq__(self, *args): #cannot find CLR method
""" x.__eq__(y) <==> x==y """
pass
@staticmethod # known case of __new__
def __new__(self, kind, pointOnLine, direction):
"""
__new__[PickPointDescriptor]() -> PickPointDescriptor
__new__(cls: type, kind: PickPointKind, pointOnLine: Point3d, direction: Vector3d)
"""
pass
def __ne__(self, *args): #cannot find CLR method
pass
Direction = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Direction(self: PickPointDescriptor) -> Vector3d
"""
Kind = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Kind(self: PickPointDescriptor) -> PickPointKind
"""
PointOnLine = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: PointOnLine(self: PickPointDescriptor) -> Point3d
"""
class PickPointKind(Enum):
""" enum PickPointKind, values: InfiniteLine (0), LineSegment (2), Ray (1) """
InfiniteLine = None
LineSegment = None
Ray = None
value__ = None
class PickPointSelectedObject(SelectedObject):
"""
PickPointSelectedObject(id: ObjectId, method: SelectionMethod, gsMarker: IntPtr, descriptor: PickPointDescriptor)
PickPointSelectedObject(id: ObjectId, method: SelectionMethod, gsMarker: Int64, descriptor: PickPointDescriptor)
"""
def ToString(self, provider=None):
"""
ToString(self: PickPointSelectedObject, provider: IFormatProvider) -> str
ToString(self: PickPointSelectedObject) -> str
"""
pass
@staticmethod # known case of __new__
def __new__(self, id, method, gsMarker, descriptor):
"""
__new__(cls: type, id: ObjectId, method: SelectionMethod, gsMarker: IntPtr, descriptor: PickPointDescriptor)
__new__(cls: type, id: ObjectId, method: SelectionMethod, gsMarker: Int64, descriptor: PickPointDescriptor)
"""
pass
PickPoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: PickPoint(self: PickPointSelectedObject) -> PickPointDescriptor
"""
class PickPointSelectedSubObject(SelectedSubObject):
"""
PickPointSelectedSubObject(path: FullSubentityPath, method: SelectionMethod, gsMarker: IntPtr, descriptor: PickPointDescriptor)
PickPointSelectedSubObject(path: FullSubentityPath, method: SelectionMethod, gsMarker: Int64, descriptor: PickPointDescriptor)
"""
def ToString(self, provider=None):
"""
ToString(self: PickPointSelectedSubObject, provider: IFormatProvider) -> str
ToString(self: PickPointSelectedSubObject) -> str
"""
pass
@staticmethod # known case of __new__
def __new__(self, path, method, gsMarker, descriptor):
"""
__new__(cls: type, path: FullSubentityPath, method: SelectionMethod, gsMarker: IntPtr, descriptor: PickPointDescriptor)
__new__(cls: type, path: FullSubentityPath, method: SelectionMethod, gsMarker: Int64, descriptor: PickPointDescriptor)
"""
pass
PickPoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: PickPoint(self: PickPointSelectedSubObject) -> PickPointDescriptor
"""
class PointFilterEventArgs(EventArgs):
# no doc
def Dispose(self):
""" Dispose(self: PointFilterEventArgs) """
pass
def __enter__(self, *args): #cannot find CLR method
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args): #cannot find CLR method
""" __exit__(self: IDisposable, exc_type: object, exc_value: object, exc_back: object) """
pass
CallNext = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CallNext(self: PointFilterEventArgs) -> bool
Set: CallNext(self: PointFilterEventArgs) = value
"""
Context = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Context(self: PointFilterEventArgs) -> InputPointContext
"""
Result = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Result(self: PointFilterEventArgs) -> PointFilterResult
"""
class PointFilterEventHandler(MulticastDelegate):
""" PointFilterEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PointFilterEventHandler, sender: object, e: PointFilterEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PointFilterEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PointFilterEventHandler, sender: object, e: PointFilterEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PointFilterResult(object):
# no doc
def Dispose(self):
""" Dispose(self: PointFilterResult) """
pass
def __enter__(self, *args): #cannot find CLR method
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args): #cannot find CLR method
""" __exit__(self: IDisposable, exc_type: object, exc_value: object, exc_back: object) """
pass
DisplayObjectSnapGlyph = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DisplayObjectSnapGlyph(self: PointFilterResult) -> bool
Set: DisplayObjectSnapGlyph(self: PointFilterResult) = value
"""
NewPoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NewPoint(self: PointFilterResult) -> Point3d
Set: NewPoint(self: PointFilterResult) = value
"""
Retry = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Retry(self: PointFilterResult) -> bool
Set: Retry(self: PointFilterResult) = value
"""
ToolTipText = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ToolTipText(self: PointFilterResult) -> str
Set: ToolTipText(self: PointFilterResult) = value
"""
class PointHistoryBits(Enum):
""" enum (flags) PointHistoryBits, values: Aligned (1024), AppFiltered (2048), CartSnapped (16), CoordinatePending (458752), CyclingPoint (64), DidNotPick (0), ForcedPick (4096), FromKeyboard (524288), Gripped (8), LastPoint (4), NotDigitizer (2), NotInteractive (1048576), ObjectSnapped (128), Ortho (32), PickAborted (32768), PickMask (57344), PolarAngle (256), Tablet (1), UsedObjectSnapBox (16384), UsedPickBox (8192), XPending (65536), YPending (131072), ZPending (262144) """
Aligned = None
AppFiltered = None
CartSnapped = None
CoordinatePending = None
CyclingPoint = None
DidNotPick = None
ForcedPick = None
FromKeyboard = None
Gripped = None
LastPoint = None
NotDigitizer = None
NotInteractive = None
ObjectSnapped = None
Ortho = None
PickAborted = None
PickMask = None
PolarAngle = None
Tablet = None
UsedObjectSnapBox = None
UsedPickBox = None
value__ = None
XPending = None
YPending = None
ZPending = None
class PointInputEventArgs(EventArgs):
# no doc
Context = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Context(self: PointInputEventArgs) -> InputPointContext
"""
GraphicsSystemMarker = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GraphicsSystemMarker(self: PointInputEventArgs) -> IntPtr
"""
Handled = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Handled(self: PointInputEventArgs) -> bool
Set: Handled(self: PointInputEventArgs) = value
"""
Result = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Result(self: PointInputEventArgs) -> PointFilterResult
"""
class PointInputEventHandler(MulticastDelegate):
""" PointInputEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PointInputEventHandler, sender: object, e: PointInputEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PointInputEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PointInputEventHandler, sender: object, e: PointInputEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PointMonitorEventArgs(EventArgs):
# no doc
def AppendToolTipText(self, value):
""" AppendToolTipText(self: PointMonitorEventArgs, value: str) """
pass
def Dispose(self):
""" Dispose(self: PointMonitorEventArgs) """
pass
def __enter__(self, *args): #cannot find CLR method
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args): #cannot find CLR method
""" __exit__(self: IDisposable, exc_type: object, exc_value: object, exc_back: object) """
pass
Context = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Context(self: PointMonitorEventArgs) -> InputPointContext
"""
class PointMonitorEventHandler(MulticastDelegate):
""" PointMonitorEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PointMonitorEventHandler, sender: object, e: PointMonitorEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PointMonitorEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PointMonitorEventHandler, sender: object, e: PointMonitorEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptEditorOptions(PromptOptions):
# no doc
@staticmethod # known case of __new__
def __new__(self, *args): #cannot find CLR constructor
"""
__new__(cls: type, messageAndKeywords: str, globalKeywords: str)
__new__(cls: type, message: str)
"""
pass
class PromptAngleOptions(PromptEditorOptions):
"""
PromptAngleOptions(messageAndKeywords: str, globalKeywords: str)
PromptAngleOptions(message: str)
"""
@staticmethod # known case of __new__
def __new__(self, *__args):
"""
__new__(cls: type, messageAndKeywords: str, globalKeywords: str)
__new__(cls: type, message: str)
"""
pass
AllowArbitraryInput = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowArbitraryInput(self: PromptAngleOptions) -> bool
Set: AllowArbitraryInput(self: PromptAngleOptions) = value
"""
AllowNone = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowNone(self: PromptAngleOptions) -> bool
Set: AllowNone(self: PromptAngleOptions) = value
"""
AllowZero = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowZero(self: PromptAngleOptions) -> bool
Set: AllowZero(self: PromptAngleOptions) = value
"""
BasePoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: BasePoint(self: PromptAngleOptions) -> Point3d
Set: BasePoint(self: PromptAngleOptions) = value
"""
DefaultValue = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DefaultValue(self: PromptAngleOptions) -> float
Set: DefaultValue(self: PromptAngleOptions) = value
"""
UseAngleBase = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UseAngleBase(self: PromptAngleOptions) -> bool
Set: UseAngleBase(self: PromptAngleOptions) = value
"""
UseBasePoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UseBasePoint(self: PromptAngleOptions) -> bool
Set: UseBasePoint(self: PromptAngleOptions) = value
"""
UseDashedLine = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UseDashedLine(self: PromptAngleOptions) -> bool
Set: UseDashedLine(self: PromptAngleOptions) = value
"""
UseDefaultValue = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UseDefaultValue(self: PromptAngleOptions) -> bool
Set: UseDefaultValue(self: PromptAngleOptions) = value
"""
class PromptAngleOptionsEventArgs(EventArgs):
# no doc
Options = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Options(self: PromptAngleOptionsEventArgs) -> PromptAngleOptions
"""
class PromptAngleOptionsEventHandler(MulticastDelegate):
""" PromptAngleOptionsEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptAngleOptionsEventHandler, sender: object, e: PromptAngleOptionsEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptAngleOptionsEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptAngleOptionsEventHandler, sender: object, e: PromptAngleOptionsEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptCornerOptions(PromptEditorOptions):
"""
PromptCornerOptions(messageAndKeywords: str, globalKeywords: str, basePoint: Point3d)
PromptCornerOptions(message: str, basePoint: Point3d)
"""
@staticmethod # known case of __new__
def __new__(self, *__args):
"""
__new__(cls: type, messageAndKeywords: str, globalKeywords: str, basePoint: Point3d)
__new__(cls: type, message: str, basePoint: Point3d)
"""
pass
AllowArbitraryInput = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowArbitraryInput(self: PromptCornerOptions) -> bool
Set: AllowArbitraryInput(self: PromptCornerOptions) = value
"""
AllowNone = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowNone(self: PromptCornerOptions) -> bool
Set: AllowNone(self: PromptCornerOptions) = value
"""
BasePoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: BasePoint(self: PromptCornerOptions) -> Point3d
Set: BasePoint(self: PromptCornerOptions) = value
"""
LimitsChecked = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: LimitsChecked(self: PromptCornerOptions) -> bool
Set: LimitsChecked(self: PromptCornerOptions) = value
"""
UseDashedLine = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UseDashedLine(self: PromptCornerOptions) -> bool
Set: UseDashedLine(self: PromptCornerOptions) = value
"""
class PromptNumericalOptions(PromptEditorOptions):
# no doc
AllowArbitraryInput = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowArbitraryInput(self: PromptNumericalOptions) -> bool
Set: AllowArbitraryInput(self: PromptNumericalOptions) = value
"""
AllowNegative = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowNegative(self: PromptNumericalOptions) -> bool
Set: AllowNegative(self: PromptNumericalOptions) = value
"""
AllowNone = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowNone(self: PromptNumericalOptions) -> bool
Set: AllowNone(self: PromptNumericalOptions) = value
"""
AllowZero = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowZero(self: PromptNumericalOptions) -> bool
Set: AllowZero(self: PromptNumericalOptions) = value
"""
UseDefaultValue = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UseDefaultValue(self: PromptNumericalOptions) -> bool
Set: UseDefaultValue(self: PromptNumericalOptions) = value
"""
class PromptDistanceOptions(PromptNumericalOptions):
"""
PromptDistanceOptions(messageAndKeywords: str, globalKeywords: str)
PromptDistanceOptions(message: str)
"""
@staticmethod # known case of __new__
def __new__(self, *__args):
"""
__new__(cls: type, messageAndKeywords: str, globalKeywords: str)
__new__(cls: type, message: str)
"""
pass
BasePoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: BasePoint(self: PromptDistanceOptions) -> Point3d
Set: BasePoint(self: PromptDistanceOptions) = value
"""
DefaultValue = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DefaultValue(self: PromptDistanceOptions) -> float
Set: DefaultValue(self: PromptDistanceOptions) = value
"""
Only2d = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Only2d(self: PromptDistanceOptions) -> bool
Set: Only2d(self: PromptDistanceOptions) = value
"""
UseBasePoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UseBasePoint(self: PromptDistanceOptions) -> bool
Set: UseBasePoint(self: PromptDistanceOptions) = value
"""
UseDashedLine = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UseDashedLine(self: PromptDistanceOptions) -> bool
Set: UseDashedLine(self: PromptDistanceOptions) = value
"""
class PromptDistanceOptionsEventArgs(EventArgs):
# no doc
Options = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Options(self: PromptDistanceOptionsEventArgs) -> PromptDistanceOptions
"""
class PromptDistanceOptionsEventHandler(MulticastDelegate):
""" PromptDistanceOptionsEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptDistanceOptionsEventHandler, sender: object, e: PromptDistanceOptionsEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptDistanceOptionsEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptDistanceOptionsEventHandler, sender: object, e: PromptDistanceOptionsEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptDoubleOptions(PromptNumericalOptions):
"""
PromptDoubleOptions(messageAndKeywords: str, globalKeywords: str)
PromptDoubleOptions(message: str)
"""
@staticmethod # known case of __new__
def __new__(self, *__args):
"""
__new__(cls: type, messageAndKeywords: str, globalKeywords: str)
__new__(cls: type, message: str)
"""
pass
DefaultValue = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DefaultValue(self: PromptDoubleOptions) -> float
Set: DefaultValue(self: PromptDoubleOptions) = value
"""
class PromptDoubleOptionsEventArgs(EventArgs):
# no doc
Options = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Options(self: PromptDoubleOptionsEventArgs) -> PromptDoubleOptions
"""
class PromptDoubleOptionsEventHandler(MulticastDelegate):
""" PromptDoubleOptionsEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptDoubleOptionsEventHandler, sender: object, e: PromptDoubleOptionsEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptDoubleOptionsEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptDoubleOptionsEventHandler, sender: object, e: PromptDoubleOptionsEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptResult(object):
# no doc
def ToString(self, provider=None):
"""
ToString(self: PromptResult, provider: IFormatProvider) -> str
ToString(self: PromptResult) -> str
"""
pass
Status = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Status(self: PromptResult) -> PromptStatus
"""
StringResult = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: StringResult(self: PromptResult) -> str
"""
class PromptDoubleResult(PromptResult):
# no doc
def ToString(self, provider=None):
"""
ToString(self: PromptDoubleResult, provider: IFormatProvider) -> str
ToString(self: PromptDoubleResult) -> str
"""
pass
Value = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Value(self: PromptDoubleResult) -> float
"""
class PromptDoubleResultEventArgs(EventArgs):
# no doc
Result = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Result(self: PromptDoubleResultEventArgs) -> PromptDoubleResult
"""
class PromptDoubleResultEventHandler(MulticastDelegate):
""" PromptDoubleResultEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptDoubleResultEventHandler, sender: object, e: PromptDoubleResultEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptDoubleResultEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptDoubleResultEventHandler, sender: object, e: PromptDoubleResultEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptDragOptions(PromptEditorOptions):
"""
PromptDragOptions(selection: SelectionSet, messageAndKeywords: str, globalKeywords: str, callback: DragCallback)
PromptDragOptions(selection: SelectionSet, message: str, callback: DragCallback)
"""
@staticmethod # known case of __new__
def __new__(self, selection, *__args):
"""
__new__(cls: type, selection: SelectionSet, messageAndKeywords: str, globalKeywords: str, callback: DragCallback)
__new__(cls: type, selection: SelectionSet, message: str, callback: DragCallback)
"""
pass
AllowArbitraryInput = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowArbitraryInput(self: PromptDragOptions) -> bool
Set: AllowArbitraryInput(self: PromptDragOptions) = value
"""
AllowNone = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowNone(self: PromptDragOptions) -> bool
Set: AllowNone(self: PromptDragOptions) = value
"""
Callback = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Callback(self: PromptDragOptions) -> DragCallback
Set: Callback(self: PromptDragOptions) = value
"""
Cursor = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Cursor(self: PromptDragOptions) -> DragCursor
Set: Cursor(self: PromptDragOptions) = value
"""
Selection = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Selection(self: PromptDragOptions) -> SelectionSet
"""
class PromptEntityOptions(PromptEditorOptions):
"""
PromptEntityOptions(messageAndKeywords: str, globalKeywords: str)
PromptEntityOptions(message: str)
"""
def AddAllowedClass(self, type, exactMatch):
""" AddAllowedClass(self: PromptEntityOptions, type: Type, exactMatch: bool) """
pass
def RemoveAllowedClass(self, type):
""" RemoveAllowedClass(self: PromptEntityOptions, type: Type) """
pass
def SetRejectMessage(self, message):
""" SetRejectMessage(self: PromptEntityOptions, message: str) """
pass
@staticmethod # known case of __new__
def __new__(self, *__args):
"""
__new__(cls: type, messageAndKeywords: str, globalKeywords: str)
__new__(cls: type, message: str)
"""
pass
AllowNone = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowNone(self: PromptEntityOptions) -> bool
Set: AllowNone(self: PromptEntityOptions) = value
"""
AllowObjectOnLockedLayer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowObjectOnLockedLayer(self: PromptEntityOptions) -> bool
Set: AllowObjectOnLockedLayer(self: PromptEntityOptions) = value
"""
class PromptEntityOptionsEventArgs(EventArgs):
# no doc
Options = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Options(self: PromptEntityOptionsEventArgs) -> PromptEntityOptions
"""
class PromptEntityOptionsEventHandler(MulticastDelegate):
""" PromptEntityOptionsEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptEntityOptionsEventHandler, sender: object, e: PromptEntityOptionsEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptEntityOptionsEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptEntityOptionsEventHandler, sender: object, e: PromptEntityOptionsEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptEntityResult(PromptResult):
# no doc
def ToString(self, provider=None):
"""
ToString(self: PromptEntityResult, provider: IFormatProvider) -> str
ToString(self: PromptEntityResult) -> str
"""
pass
ObjectId = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ObjectId(self: PromptEntityResult) -> ObjectId
"""
PickedPoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: PickedPoint(self: PromptEntityResult) -> Point3d
"""
class PromptEntityResultEventArgs(EventArgs):
# no doc
Result = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Result(self: PromptEntityResultEventArgs) -> PromptEntityResult
"""
class PromptEntityResultEventHandler(MulticastDelegate):
""" PromptEntityResultEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptEntityResultEventHandler, sender: object, e: PromptEntityResultEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptEntityResultEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptEntityResultEventHandler, sender: object, e: PromptEntityResultEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptFileNameResult(PromptResult):
# no doc
def ToString(self, provider=None):
"""
ToString(self: PromptFileNameResult) -> str
ToString(self: PromptFileNameResult, provider: IFormatProvider) -> str
"""
pass
ReadOnly = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ReadOnly(self: PromptFileNameResult) -> bool
"""
class PromptFileOptions(object):
# no doc
AllowUrls = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowUrls(self: PromptFileOptions) -> bool
Set: AllowUrls(self: PromptFileOptions) = value
"""
DialogCaption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DialogCaption(self: PromptFileOptions) -> str
Set: DialogCaption(self: PromptFileOptions) = value
"""
DialogName = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DialogName(self: PromptFileOptions) -> str
Set: DialogName(self: PromptFileOptions) = value
"""
Filter = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Filter(self: PromptFileOptions) -> str
Set: Filter(self: PromptFileOptions) = value
"""
FilterIndex = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: FilterIndex(self: PromptFileOptions) -> int
Set: FilterIndex(self: PromptFileOptions) = value
"""
InitialDirectory = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: InitialDirectory(self: PromptFileOptions) -> str
Set: InitialDirectory(self: PromptFileOptions) = value
"""
InitialFileName = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: InitialFileName(self: PromptFileOptions) -> str
Set: InitialFileName(self: PromptFileOptions) = value
"""
Message = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Message(self: PromptFileOptions) -> str
Set: Message(self: PromptFileOptions) = value
"""
PreferCommandLine = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: PreferCommandLine(self: PromptFileOptions) -> bool
Set: PreferCommandLine(self: PromptFileOptions) = value
"""
class PromptForEntityEndingEventArgs(EventArgs):
# no doc
def Dispose(self):
""" Dispose(self: PromptForEntityEndingEventArgs) """
pass
def RemoveSelectedObject(self):
""" RemoveSelectedObject(self: PromptForEntityEndingEventArgs) """
pass
def ReplaceSelectedObject(self, newValue):
""" ReplaceSelectedObject(self: PromptForEntityEndingEventArgs, newValue: SelectedObject) """
pass
def __enter__(self, *args): #cannot find CLR method
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args): #cannot find CLR method
""" __exit__(self: IDisposable, exc_type: object, exc_value: object, exc_back: object) """
pass
Result = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Result(self: PromptForEntityEndingEventArgs) -> PromptEntityResult
"""
class PromptForEntityEndingEventHandler(MulticastDelegate):
""" PromptForEntityEndingEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptForEntityEndingEventHandler, sender: object, e: PromptForEntityEndingEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptForEntityEndingEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptForEntityEndingEventHandler, sender: object, e: PromptForEntityEndingEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptForSelectionEndingEventArgs(EventArgs):
# no doc
def Add(self, value):
""" Add(self: PromptForSelectionEndingEventArgs, value: SelectedObject) """
pass
def AddSubEntity(self, value):
""" AddSubEntity(self: PromptForSelectionEndingEventArgs, value: SelectedSubObject) """
pass
def Dispose(self):
""" Dispose(self: PromptForSelectionEndingEventArgs) """
pass
def Remove(self, index):
""" Remove(self: PromptForSelectionEndingEventArgs, index: int) """
pass
def RemoveSubEntity(self, entityIndex, subEntityIndex):
""" RemoveSubEntity(self: PromptForSelectionEndingEventArgs, entityIndex: int, subEntityIndex: int) """
pass
def __add__(self, *args): #cannot find CLR method
""" x.__add__(y) <==> x+y """
pass
def __enter__(self, *args): #cannot find CLR method
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args): #cannot find CLR method
""" __exit__(self: IDisposable, exc_type: object, exc_value: object, exc_back: object) """
pass
Flags = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Flags(self: PromptForSelectionEndingEventArgs) -> SelectionFlags
"""
Selection = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Selection(self: PromptForSelectionEndingEventArgs) -> SelectionSet
"""
class PromptForSelectionEndingEventHandler(MulticastDelegate):
""" PromptForSelectionEndingEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptForSelectionEndingEventHandler, sender: object, e: PromptForSelectionEndingEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptForSelectionEndingEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptForSelectionEndingEventHandler, sender: object, e: PromptForSelectionEndingEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptIntegerOptions(PromptNumericalOptions):
"""
PromptIntegerOptions(messageAndKeywords: str, globalKeywords: str, lowerLimit: int, upperLimit: int)
PromptIntegerOptions(messageAndKeywords: str, globalKeywords: str)
PromptIntegerOptions(message: str)
"""
@staticmethod # known case of __new__
def __new__(self, *__args):
"""
__new__(cls: type, messageAndKeywords: str, globalKeywords: str, lowerLimit: int, upperLimit: int)
__new__(cls: type, messageAndKeywords: str, globalKeywords: str)
__new__(cls: type, message: str)
"""
pass
DefaultValue = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DefaultValue(self: PromptIntegerOptions) -> int
Set: DefaultValue(self: PromptIntegerOptions) = value
"""
LowerLimit = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: LowerLimit(self: PromptIntegerOptions) -> int
Set: LowerLimit(self: PromptIntegerOptions) = value
"""
UpperLimit = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UpperLimit(self: PromptIntegerOptions) -> int
Set: UpperLimit(self: PromptIntegerOptions) = value
"""
class PromptIntegerOptionsEventArgs(EventArgs):
# no doc
Options = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Options(self: PromptIntegerOptionsEventArgs) -> PromptIntegerOptions
"""
class PromptIntegerOptionsEventHandler(MulticastDelegate):
""" PromptIntegerOptionsEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptIntegerOptionsEventHandler, sender: object, e: PromptIntegerOptionsEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptIntegerOptionsEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptIntegerOptionsEventHandler, sender: object, e: PromptIntegerOptionsEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptIntegerResult(PromptResult):
# no doc
def ToString(self, provider=None):
"""
ToString(self: PromptIntegerResult, provider: IFormatProvider) -> str
ToString(self: PromptIntegerResult) -> str
"""
pass
Value = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Value(self: PromptIntegerResult) -> int
"""
class PromptIntegerResultEventArgs(EventArgs):
# no doc
Result = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Result(self: PromptIntegerResultEventArgs) -> PromptIntegerResult
"""
class PromptIntegerResultEventHandler(MulticastDelegate):
""" PromptIntegerResultEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptIntegerResultEventHandler, sender: object, e: PromptIntegerResultEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptIntegerResultEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptIntegerResultEventHandler, sender: object, e: PromptIntegerResultEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptKeywordOptions(PromptEditorOptions):
"""
PromptKeywordOptions(messageAndKeywords: str, globalKeywords: str)
PromptKeywordOptions(message: str)
"""
@staticmethod # known case of __new__
def __new__(self, *__args):
"""
__new__(cls: type, messageAndKeywords: str, globalKeywords: str)
__new__(cls: type, message: str)
"""
pass
AllowArbitraryInput = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowArbitraryInput(self: PromptKeywordOptions) -> bool
Set: AllowArbitraryInput(self: PromptKeywordOptions) = value
"""
AllowNone = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowNone(self: PromptKeywordOptions) -> bool
Set: AllowNone(self: PromptKeywordOptions) = value
"""
class PromptKeywordOptionsEventArgs(EventArgs):
# no doc
Options = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Options(self: PromptKeywordOptionsEventArgs) -> PromptKeywordOptions
"""
class PromptKeywordOptionsEventHandler(MulticastDelegate):
""" PromptKeywordOptionsEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptKeywordOptionsEventHandler, sender: object, e: PromptKeywordOptionsEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptKeywordOptionsEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptKeywordOptionsEventHandler, sender: object, e: PromptKeywordOptionsEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptNestedEntityOptions(PromptEditorOptions):
"""
PromptNestedEntityOptions(messageAndKeywords: str, globalKeywords: str)
PromptNestedEntityOptions(message: str)
"""
@staticmethod # known case of __new__
def __new__(self, *__args):
"""
__new__(cls: type, messageAndKeywords: str, globalKeywords: str)
__new__(cls: type, message: str)
"""
pass
AllowNone = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowNone(self: PromptNestedEntityOptions) -> bool
Set: AllowNone(self: PromptNestedEntityOptions) = value
"""
NonInteractivePickPoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NonInteractivePickPoint(self: PromptNestedEntityOptions) -> Point3d
Set: NonInteractivePickPoint(self: PromptNestedEntityOptions) = value
"""
UseNonInteractivePickPoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UseNonInteractivePickPoint(self: PromptNestedEntityOptions) -> bool
Set: UseNonInteractivePickPoint(self: PromptNestedEntityOptions) = value
"""
class PromptNestedEntityOptionsEventArgs(EventArgs):
# no doc
Options = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Options(self: PromptNestedEntityOptionsEventArgs) -> PromptNestedEntityOptions
"""
class PromptNestedEntityOptionsEventHandler(MulticastDelegate):
""" PromptNestedEntityOptionsEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptNestedEntityOptionsEventHandler, sender: object, e: PromptNestedEntityOptionsEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptNestedEntityOptionsEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptNestedEntityOptionsEventHandler, sender: object, e: PromptNestedEntityOptionsEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptNestedEntityResult(PromptEntityResult):
# no doc
def GetContainers(self):
""" GetContainers(self: PromptNestedEntityResult) -> Array[ObjectId] """
pass
def ToString(self, provider=None):
"""
ToString(self: PromptNestedEntityResult, provider: IFormatProvider) -> str
ToString(self: PromptNestedEntityResult) -> str
"""
pass
Transform = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Transform(self: PromptNestedEntityResult) -> Matrix3d
"""
class PromptNestedEntityResultEventArgs(EventArgs):
# no doc
Result = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Result(self: PromptNestedEntityResultEventArgs) -> PromptNestedEntityResult
"""
class PromptNestedEntityResultEventHandler(MulticastDelegate):
""" PromptNestedEntityResultEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptNestedEntityResultEventHandler, sender: object, e: PromptNestedEntityResultEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptNestedEntityResultEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptNestedEntityResultEventHandler, sender: object, e: PromptNestedEntityResultEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptOpenFileOptions(PromptFileOptions):
""" PromptOpenFileOptions(message: str) """
@staticmethod # known case of __new__
def __new__(self, message):
""" __new__(cls: type, message: str) """
pass
SearchPath = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SearchPath(self: PromptOpenFileOptions) -> bool
Set: SearchPath(self: PromptOpenFileOptions) = value
"""
TransferRemoteFiles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TransferRemoteFiles(self: PromptOpenFileOptions) -> bool
Set: TransferRemoteFiles(self: PromptOpenFileOptions) = value
"""
class PromptPointOptions(PromptCornerOptions):
"""
PromptPointOptions(messageAndKeywords: str, globalKeywords: str)
PromptPointOptions(message: str)
"""
@staticmethod # known case of __new__
def __new__(self, *__args):
"""
__new__(cls: type, messageAndKeywords: str, globalKeywords: str)
__new__(cls: type, message: str)
"""
pass
UseBasePoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UseBasePoint(self: PromptPointOptions) -> bool
Set: UseBasePoint(self: PromptPointOptions) = value
"""
class PromptPointOptionsEventArgs(EventArgs):
# no doc
Options = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Options(self: PromptPointOptionsEventArgs) -> PromptPointOptions
"""
class PromptPointOptionsEventHandler(MulticastDelegate):
""" PromptPointOptionsEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptPointOptionsEventHandler, sender: object, e: PromptPointOptionsEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptPointOptionsEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptPointOptionsEventHandler, sender: object, e: PromptPointOptionsEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptPointResult(PromptResult):
# no doc
def ToString(self, provider=None):
"""
ToString(self: PromptPointResult, provider: IFormatProvider) -> str
ToString(self: PromptPointResult) -> str
"""
pass
Value = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Value(self: PromptPointResult) -> Point3d
"""
class PromptPointResultEventArgs(EventArgs):
# no doc
Result = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Result(self: PromptPointResultEventArgs) -> PromptPointResult
"""
class PromptPointResultEventHandler(MulticastDelegate):
""" PromptPointResultEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptPointResultEventHandler, sender: object, e: PromptPointResultEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptPointResultEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptPointResultEventHandler, sender: object, e: PromptPointResultEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptSaveFileOptions(PromptFileOptions):
""" PromptSaveFileOptions(message: str) """
@staticmethod # known case of __new__
def __new__(self, message):
""" __new__(cls: type, message: str) """
pass
DeriveInitialFilenameFromDrawingName = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DeriveInitialFilenameFromDrawingName(self: PromptSaveFileOptions) -> bool
Set: DeriveInitialFilenameFromDrawingName(self: PromptSaveFileOptions) = value
"""
DisplaySaveOptionsMenuItem = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DisplaySaveOptionsMenuItem(self: PromptSaveFileOptions) -> bool
Set: DisplaySaveOptionsMenuItem(self: PromptSaveFileOptions) = value
"""
ForceOverwriteWarningForScriptsAndLisp = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ForceOverwriteWarningForScriptsAndLisp(self: PromptSaveFileOptions) -> bool
Set: ForceOverwriteWarningForScriptsAndLisp(self: PromptSaveFileOptions) = value
"""
class PromptSelectionOptions(object):
""" PromptSelectionOptions() """
def AddKeywordsToMinimalList(self, kwds):
""" AddKeywordsToMinimalList(self: PromptSelectionOptions, kwds: AddedKeywords) """
pass
def RemoveKeywordsFromFullList(self, kwds):
""" RemoveKeywordsFromFullList(self: PromptSelectionOptions, kwds: SubtractedKeywords) """
pass
def SetKeywords(self, keywords, globalKeywords):
""" SetKeywords(self: PromptSelectionOptions, keywords: str, globalKeywords: str) """
pass
AllowDuplicates = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowDuplicates(self: PromptSelectionOptions) -> bool
Set: AllowDuplicates(self: PromptSelectionOptions) = value
"""
AllowSubSelections = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowSubSelections(self: PromptSelectionOptions) -> bool
Set: AllowSubSelections(self: PromptSelectionOptions) = value
"""
ForceSubSelections = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ForceSubSelections(self: PromptSelectionOptions) -> bool
Set: ForceSubSelections(self: PromptSelectionOptions) = value
"""
Keywords = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Keywords(self: PromptSelectionOptions) -> KeywordCollection
"""
MessageForAdding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: MessageForAdding(self: PromptSelectionOptions) -> str
Set: MessageForAdding(self: PromptSelectionOptions) = value
"""
MessageForRemoval = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: MessageForRemoval(self: PromptSelectionOptions) -> str
Set: MessageForRemoval(self: PromptSelectionOptions) = value
"""
PrepareOptionalDetails = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: PrepareOptionalDetails(self: PromptSelectionOptions) -> bool
Set: PrepareOptionalDetails(self: PromptSelectionOptions) = value
"""
RejectObjectsFromNonCurrentSpace = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: RejectObjectsFromNonCurrentSpace(self: PromptSelectionOptions) -> bool
Set: RejectObjectsFromNonCurrentSpace(self: PromptSelectionOptions) = value
"""
RejectObjectsOnLockedLayers = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: RejectObjectsOnLockedLayers(self: PromptSelectionOptions) -> bool
Set: RejectObjectsOnLockedLayers(self: PromptSelectionOptions) = value
"""
RejectPaperspaceViewport = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: RejectPaperspaceViewport(self: PromptSelectionOptions) -> bool
Set: RejectPaperspaceViewport(self: PromptSelectionOptions) = value
"""
SelectEverythingInAperture = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SelectEverythingInAperture(self: PromptSelectionOptions) -> bool
Set: SelectEverythingInAperture(self: PromptSelectionOptions) = value
"""
SingleOnly = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SingleOnly(self: PromptSelectionOptions) -> bool
Set: SingleOnly(self: PromptSelectionOptions) = value
"""
SinglePickInSpace = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SinglePickInSpace(self: PromptSelectionOptions) -> bool
Set: SinglePickInSpace(self: PromptSelectionOptions) = value
"""
KeywordInput = None
UnknownInput = None
class PromptSelectionOptionsEventArgs(EventArgs):
# no doc
def GetPoints(self):
""" GetPoints(self: PromptSelectionOptionsEventArgs) -> Array[Point3d] """
pass
Filter = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Filter(self: PromptSelectionOptionsEventArgs) -> SelectionFilter
"""
Options = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Options(self: PromptSelectionOptionsEventArgs) -> PromptSelectionOptions
"""
class PromptSelectionOptionsEventHandler(MulticastDelegate):
""" PromptSelectionOptionsEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptSelectionOptionsEventHandler, sender: object, e: PromptSelectionOptionsEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptSelectionOptionsEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptSelectionOptionsEventHandler, sender: object, e: PromptSelectionOptionsEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptSelectionResult(object):
# no doc
def ToString(self, provider=None):
"""
ToString(self: PromptSelectionResult, provider: IFormatProvider) -> str
ToString(self: PromptSelectionResult) -> str
"""
pass
Status = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Status(self: PromptSelectionResult) -> PromptStatus
"""
Value = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Value(self: PromptSelectionResult) -> SelectionSet
"""
class PromptSelectionResultEventArgs(EventArgs):
# no doc
Result = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Result(self: PromptSelectionResultEventArgs) -> PromptSelectionResult
"""
class PromptSelectionResultEventHandler(MulticastDelegate):
""" PromptSelectionResultEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptSelectionResultEventHandler, sender: object, e: PromptSelectionResultEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptSelectionResultEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptSelectionResultEventHandler, sender: object, e: PromptSelectionResultEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptStatus(Enum):
""" enum PromptStatus, values: Cancel (-5002), Error (-5001), Keyword (-5005), Modeless (5027), None (5000), OK (5100), Other (5028) """
Cancel = None
Error = None
Keyword = None
Modeless = None
None = None
OK = None
Other = None
value__ = None
class PromptStringOptions(PromptEditorOptions):
""" PromptStringOptions(message: str) """
@staticmethod # known case of __new__
def __new__(self, message):
""" __new__(cls: type, message: str) """
pass
AllowSpaces = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AllowSpaces(self: PromptStringOptions) -> bool
Set: AllowSpaces(self: PromptStringOptions) = value
"""
DefaultValue = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DefaultValue(self: PromptStringOptions) -> str
Set: DefaultValue(self: PromptStringOptions) = value
"""
UseDefaultValue = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UseDefaultValue(self: PromptStringOptions) -> bool
Set: UseDefaultValue(self: PromptStringOptions) = value
"""
class PromptStringOptionsEventArgs(EventArgs):
# no doc
Options = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Options(self: PromptStringOptionsEventArgs) -> PromptStringOptions
"""
class PromptStringOptionsEventHandler(MulticastDelegate):
""" PromptStringOptionsEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptStringOptionsEventHandler, sender: object, e: PromptStringOptionsEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptStringOptionsEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptStringOptionsEventHandler, sender: object, e: PromptStringOptionsEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class PromptStringResultEventArgs(EventArgs):
# no doc
Result = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Result(self: PromptStringResultEventArgs) -> PromptResult
"""
class PromptStringResultEventHandler(MulticastDelegate):
""" PromptStringResultEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: PromptStringResultEventHandler, sender: object, e: PromptStringResultEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: PromptStringResultEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: PromptStringResultEventHandler, sender: object, e: PromptStringResultEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class RolloverEventArgs(EventArgs):
# no doc
Highlighted = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Highlighted(self: RolloverEventArgs) -> FullSubentityPath
Set: Highlighted(self: RolloverEventArgs) = value
"""
Picked = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Picked(self: RolloverEventArgs) -> FullSubentityPath
"""
class RolloverEventHandler(MulticastDelegate):
""" RolloverEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: RolloverEventHandler, sender: object, e: RolloverEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: RolloverEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: RolloverEventHandler, sender: object, e: RolloverEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class SamplerStatus(Enum):
""" enum SamplerStatus, values: Cancel (2), NoChange (1), OK (0) """
Cancel = None
NoChange = None
OK = None
value__ = None
class SelectionAddedEventArgs(EventArgs):
# no doc
def Add(self, value):
""" Add(self: SelectionAddedEventArgs, value: SelectedObject) """
pass
def AddSubEntity(self, value):
""" AddSubEntity(self: SelectionAddedEventArgs, value: SelectedSubObject) """
pass
def Dispose(self):
""" Dispose(self: SelectionAddedEventArgs) """
pass
def Highlight(self, subSelectionIndex, path):
""" Highlight(self: SelectionAddedEventArgs, subSelectionIndex: int, path: FullSubentityPath) """
pass
def Remove(self, index):
""" Remove(self: SelectionAddedEventArgs, index: int) """
pass
def RemoveSubEntity(self, entityIndex, subEntityIndex):
""" RemoveSubEntity(self: SelectionAddedEventArgs, entityIndex: int, subEntityIndex: int) """
pass
def __add__(self, *args): #cannot find CLR method
""" x.__add__(y) <==> x+y """
pass
def __enter__(self, *args): #cannot find CLR method
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args): #cannot find CLR method
""" __exit__(self: IDisposable, exc_type: object, exc_value: object, exc_back: object) """
pass
AddedObjects = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AddedObjects(self: SelectionAddedEventArgs) -> SelectionSet
"""
Flags = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Flags(self: SelectionAddedEventArgs) -> SelectionFlags
"""
Selection = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Selection(self: SelectionAddedEventArgs) -> SelectionSet
"""
class SelectionAddedEventHandler(MulticastDelegate):
""" SelectionAddedEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: SelectionAddedEventHandler, sender: object, e: SelectionAddedEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: SelectionAddedEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: SelectionAddedEventHandler, sender: object, e: SelectionAddedEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class SelectionDetails(object):
# no doc
def GetContainers(self):
""" GetContainers(self: SelectionDetails) -> Array[ObjectId] """
pass
def ToString(self, provider=None):
"""
ToString(self: SelectionDetails, provider: IFormatProvider) -> str
ToString(self: SelectionDetails) -> str
"""
pass
Transform = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Transform(self: SelectionDetails) -> Matrix3d
"""
class SelectionFilter(object):
""" SelectionFilter(value: Array[TypedValue]) """
def GetFilter(self):
""" GetFilter(self: SelectionFilter) -> Array[TypedValue] """
pass
@staticmethod # known case of __new__
def __new__(self, value):
""" __new__(cls: type, value: Array[TypedValue]) """
pass
class SelectionFlags(Enum):
""" enum (flags) SelectionFlags, values: Duplicates (2), FailedPickAuto (512), NestedEntities (4), Normal (0), PickfirstSet (32), PickPoints (1), PreviousSet (64), SinglePick (16), SubEntities (8), SubSelection (128), Undo (256) """
Duplicates = None
FailedPickAuto = None
NestedEntities = None
Normal = None
PickfirstSet = None
PickPoints = None
PreviousSet = None
SinglePick = None
SubEntities = None
SubSelection = None
Undo = None
value__ = None
class SelectionMethod(Enum):
""" enum SelectionMethod, values: Crossing (3), Fence (4), NonGraphical (0), PickPoint (1), SubEntity (5), Unavailable (-1), Window (2) """
Crossing = None
Fence = None
NonGraphical = None
PickPoint = None
SubEntity = None
Unavailable = None
value__ = None
Window = None
class SelectionMode(Enum):
""" enum SelectionMode, values: All (6), Box (3), Crossing (2), CrossingPolygon (8), Entity (5), Every (11), Extents (12), FencePolyline (7), Group (13), Last (4), Multiple (15), Pick (10), Previous (14), Window (1), WindowPolygon (9) """
All = None
Box = None
Crossing = None
CrossingPolygon = None
Entity = None
Every = None
Extents = None
FencePolyline = None
Group = None
Last = None
Multiple = None
Pick = None
Previous = None
value__ = None
Window = None
WindowPolygon = None
class SelectionRemovedEventArgs(EventArgs):
# no doc
def Dispose(self):
""" Dispose(self: SelectionRemovedEventArgs) """
pass
def Remove(self, index):
""" Remove(self: SelectionRemovedEventArgs, index: int) """
pass
def RemoveSubentity(self, index, subentityIndex):
""" RemoveSubentity(self: SelectionRemovedEventArgs, index: int, subentityIndex: int) """
pass
def __enter__(self, *args): #cannot find CLR method
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args): #cannot find CLR method
""" __exit__(self: IDisposable, exc_type: object, exc_value: object, exc_back: object) """
pass
Flags = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Flags(self: SelectionRemovedEventArgs) -> SelectionFlags
"""
RemovedObjects = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: RemovedObjects(self: SelectionRemovedEventArgs) -> SelectionSet
"""
Selection = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Selection(self: SelectionRemovedEventArgs) -> SelectionSet
"""
class SelectionRemovedEventHandler(MulticastDelegate):
""" SelectionRemovedEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: SelectionRemovedEventHandler, sender: object, e: SelectionRemovedEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: SelectionRemovedEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: SelectionRemovedEventHandler, sender: object, e: SelectionRemovedEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class SelectionSet(object):
# no doc
def CopyTo(self, array, index):
""" CopyTo(self: SelectionSet, array: Array[SelectedObject], index: int) """
pass
def Dispose(self):
""" Dispose(self: SelectionSet) """
pass
@staticmethod
def FromObjectIds(ids):
""" FromObjectIds(ids: Array[ObjectId]) -> SelectionSet """
pass
def GetEnumerator(self):
""" GetEnumerator(self: SelectionSet) -> IEnumerator """
pass
def GetObjectIds(self):
""" GetObjectIds(self: SelectionSet) -> Array[ObjectId] """
pass
def ToString(self, provider=None):
"""
ToString(self: SelectionSet, provider: IFormatProvider) -> str
ToString(self: SelectionSet) -> str
"""
pass
def __enter__(self, *args): #cannot find CLR method
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args): #cannot find CLR method
""" __exit__(self: IDisposable, exc_type: object, exc_value: object, exc_back: object) """
pass
def __getitem__(self, *args): #cannot find CLR method
""" x.__getitem__(y) <==> x[y] """
pass
def __iter__(self, *args): #cannot find CLR method
""" __iter__(self: IEnumerable) -> object """
pass
def __len__(self, *args): #cannot find CLR method
""" x.__len__() <==> len(x) """
pass
Count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Count(self: SelectionSet) -> int
"""
IsSynchronized = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: IsSynchronized(self: SelectionSet) -> bool
"""
SyncRoot = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SyncRoot(self: SelectionSet) -> object
"""
class SelectionSetDelayMarshalled(SelectionSet):
# no doc
def Dispose(self):
""" Dispose(self: SelectionSetDelayMarshalled, A_0: bool) """
pass
def GetEnumerator(self):
""" GetEnumerator(self: SelectionSetDelayMarshalled) -> IEnumerator """
pass
def GetObjectIds(self):
""" GetObjectIds(self: SelectionSetDelayMarshalled) -> Array[ObjectId] """
pass
Count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Count(self: SelectionSetDelayMarshalled) -> int
"""
Name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Name(self: SelectionSetDelayMarshalled) -> AdsName
"""
class SelectionTextInputEventArgs(EventArgs):
# no doc
def AddObjects(self, ids):
""" AddObjects(self: SelectionTextInputEventArgs, ids: Array[ObjectId]) """
pass
def SetErrorMessage(self, errorMessage):
""" SetErrorMessage(self: SelectionTextInputEventArgs, errorMessage: str) """
pass
Input = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Input(self: SelectionTextInputEventArgs) -> str
"""
class SelectionTextInputEventHandler(MulticastDelegate):
""" SelectionTextInputEventHandler(A_0: object, A_1: IntPtr) """
def BeginInvoke(self, sender, e, callback, obj):
""" BeginInvoke(self: SelectionTextInputEventHandler, sender: object, e: SelectionTextInputEventArgs, callback: AsyncCallback, obj: object) -> IAsyncResult """
pass
def EndInvoke(self, result):
""" EndInvoke(self: SelectionTextInputEventHandler, result: IAsyncResult) """
pass
def Invoke(self, sender, e):
""" Invoke(self: SelectionTextInputEventHandler, sender: object, e: SelectionTextInputEventArgs) """
pass
@staticmethod # known case of __new__
def __new__(self, A_0, A_1):
""" __new__(cls: type, A_0: object, A_1: IntPtr) """
pass
class SubtractedKeywords(Enum):
""" enum SubtractedKeywords, values: AddRemove (2048), All (4), BoxAuto (8), CrossingCPolygon (32), Fence (64), Group (1024), Last (128), LastAllGroupPrevious (1), Multiple (16), PickImplied (2), Previous (256), WindowWPolygon (512) """
AddRemove = None
All = None
BoxAuto = None
CrossingCPolygon = None
Fence = None
Group = None
Last = None
LastAllGroupPrevious = None
Multiple = None
PickImplied = None
Previous = None
value__ = None
WindowWPolygon = None
class Transient(Drawable):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
def OnCaptured(self, *args): #cannot find CLR method
""" OnCaptured(self: Transient, e: EventArgs) """
pass
def OnCaptureReleased(self, *args): #cannot find CLR method
""" OnCaptureReleased(self: Transient, e: EventArgs) """
pass
def OnDeviceInput(self, *args): #cannot find CLR method
""" OnDeviceInput(self: Transient, e: DeviceInputEventArgs) """
pass
def OnPointInput(self, *args): #cannot find CLR method
""" OnPointInput(self: Transient, e: PointInputEventArgs) """
pass
def raise_Captured(self, *args): #cannot find CLR method
""" raise_Captured(self: Transient, value0: object, value1: EventArgs) """
pass
def raise_CaptureReleased(self, *args): #cannot find CLR method
""" raise_CaptureReleased(self: Transient, value0: object, value1: EventArgs) """
pass
def raise_DeviceInput(self, *args): #cannot find CLR method
""" raise_DeviceInput(self: Transient, value0: object, value1: DeviceInputEventArgs) """
pass
def raise_PointInput(self, *args): #cannot find CLR method
""" raise_PointInput(self: Transient, value0: object, value1: PointInputEventArgs) """
pass
Id = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Id(self: Transient) -> ObjectId
"""
IsPersistent = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: IsPersistent(self: Transient) -> bool
"""
Captured = None
CapturedDrawable = None
CaptureReleased = None
DeviceInput = None
PointInput = None
class UserInputControls(Enum):
""" enum (flags) UserInputControls, values: Accept3dCoordinates (128), AcceptMouseUpAsPoint (256), AcceptOtherInputString (2048), AnyBlankTerminatesInput (512), DoNotEchoCancelForCtrlC (4), DoNotUpdateLastPoint (8), GovernedByOrthoMode (1), GovernedByUCSDetect (4096), InitialBlankTerminatesInput (1024), NoDwgLimitsChecking (16), NoNegativeResponseAccepted (64), NoZDirectionOrtho (8192), NoZeroResponseAccepted (32), NullResponseAccepted (2), UseBasePointElevation (32768) """
Accept3dCoordinates = None
AcceptMouseUpAsPoint = None
AcceptOtherInputString = None
AnyBlankTerminatesInput = None
DoNotEchoCancelForCtrlC = None
DoNotUpdateLastPoint = None
GovernedByOrthoMode = None
GovernedByUCSDetect = None
InitialBlankTerminatesInput = None
NoDwgLimitsChecking = None
NoNegativeResponseAccepted = None
NoZDirectionOrtho = None
NoZeroResponseAccepted = None
NullResponseAccepted = None
UseBasePointElevation = None
value__ = None
| 34.972624 | 486 | 0.648677 | 136,645 | 0.990418 | 0 | 0 | 16,485 | 0.119485 | 0 | 0 | 75,948 | 0.550479 |
4104d25dc6796ebc87ccaf0dca4400cb888e648b | 169 | py | Python | AutotestWebD/all_models_for_mock/models/__init__.py | yangjourney/sosotest | 2e88099a829749910ca325253c9b1a2e368d21a0 | [
"MIT"
]
| 422 | 2019-08-18T05:04:20.000Z | 2022-03-31T06:49:19.000Z | AutotestWebD/all_models_for_mock/models/__init__.py | LinSongJian1985/sosotest | 091863dee531b5726650bb63efd6f169267cbeb4 | [
"MIT"
]
| 10 | 2019-10-24T09:55:38.000Z | 2021-09-29T17:28:43.000Z | AutotestWebD/all_models_for_mock/models/__init__.py | LinSongJian1985/sosotest | 091863dee531b5726650bb63efd6f169267cbeb4 | [
"MIT"
]
| 202 | 2019-08-18T05:04:27.000Z | 2022-03-30T05:57:18.000Z | from all_models_for_mock.models.M0001_mock import *
from all_models_for_mock.models.M0002_keywords import *
from all_models_for_mock.models.M0003_statisic_task import *
| 42.25 | 60 | 0.87574 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
41067ed6db1ed6b79ce07e5f1ba003d3a292c73c | 151 | py | Python | chpt8/Reverse.py | GDG-Buea/learn-python | 9dfe8caa4b57489cf4249bf7e64856062a0b93c2 | [
"Apache-2.0"
]
| null | null | null | chpt8/Reverse.py | GDG-Buea/learn-python | 9dfe8caa4b57489cf4249bf7e64856062a0b93c2 | [
"Apache-2.0"
]
| 2 | 2018-05-21T09:39:00.000Z | 2018-05-27T15:59:15.000Z | chpt8/Reverse.py | GDG-Buea/learn-python | 9dfe8caa4b57489cf4249bf7e64856062a0b93c2 | [
"Apache-2.0"
]
| 2 | 2018-05-19T14:59:56.000Z | 2018-05-19T15:25:48.000Z | # This program reverses a given string
def reverse():
user_string = input("Enter a string: ")
s = user_string[::-1]
print(s)
reverse()
| 13.727273 | 43 | 0.629139 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 56 | 0.370861 |
4108814557aaf45fa9bd2469a548f631f9648812 | 29,383 | py | Python | pauxy/walkers/thermal.py | pauxy-qmc/pauxy | 1da80284284769b59361c73cfa3c2d914c74a73f | [
"Apache-2.0"
]
| 16 | 2020-08-05T17:17:17.000Z | 2022-03-18T04:06:18.000Z | pauxy/walkers/thermal.py | pauxy-qmc/pauxy | 1da80284284769b59361c73cfa3c2d914c74a73f | [
"Apache-2.0"
]
| 4 | 2020-05-17T21:28:20.000Z | 2021-04-22T18:05:50.000Z | pauxy/walkers/thermal.py | pauxy-qmc/pauxy | 1da80284284769b59361c73cfa3c2d914c74a73f | [
"Apache-2.0"
]
| 5 | 2020-05-18T01:03:18.000Z | 2021-04-13T15:36:29.000Z | import copy
import cmath
import numpy
import scipy.linalg
from pauxy.estimators.thermal import greens_function, one_rdm_from_G, particle_number
from pauxy.estimators.mixed import local_energy
from pauxy.walkers.stack import PropagatorStack
from pauxy.walkers.walker import Walker
from pauxy.utils.linalg import regularise_matrix_inverse
from pauxy.utils.misc import update_stack, get_numeric_names
class ThermalWalker(Walker):
def __init__(self, system, trial, walker_opts={}, verbose=False):
Walker.__init__(self, system, trial, walker_opts=walker_opts)
self.num_slices = trial.num_slices
dtype = numpy.complex128
self.G = numpy.zeros(trial.dmat.shape, dtype=dtype)
self.nbasis = trial.dmat[0].shape[0]
self.stack_size = walker_opts.get('stack_size', None)
max_diff_diag = numpy.linalg.norm((numpy.diag(trial.dmat[0].diagonal())-trial.dmat[0]))
if max_diff_diag < 1e-10:
self.diagonal_trial = True
if verbose:
print("# Trial density matrix is diagonal.")
else:
self.diagonal_trial = False
if verbose:
print("# Trial density matrix is not diagonal.")
if self.stack_size == None:
self.stack_size = trial.stack_size
if (self.num_slices//self.stack_size)*self.stack_size != self.num_slices:
if verbose:
print("# Input stack size does not divide number of slices.")
self.stack_size = update_stack(self.stack_size, self.num_slices, verbose)
if self.stack_size > trial.stack_size:
if verbose:
print("# Walker stack size differs from that estimated from "
"trial density matrix.")
print("# Be careful. cond(BT)**stack_size: %10.3e."
%(trial.cond**self.stack_size))
self.stack_length = self.num_slices // self.stack_size
if verbose:
print("# Walker stack size: {}".format(self.stack_size))
self.lowrank = walker_opts.get('low_rank', False)
self.lowrank_thresh = walker_opts.get('low_rank_thresh', 1e-6)
if verbose:
print("# Using low rank trick: {}".format(self.lowrank))
self.stack = PropagatorStack(self.stack_size, trial.num_slices,
trial.dmat.shape[-1], dtype,
trial.dmat, trial.dmat_inv,
diagonal=self.diagonal_trial,
lowrank=self.lowrank,
thresh=self.lowrank_thresh)
# Initialise all propagators to the trial density matrix.
self.stack.set_all(trial.dmat)
self.greens_function_qr_strat(trial)
self.stack.G = self.G
self.M0 = numpy.array([scipy.linalg.det(self.G[0], check_finite=False),
scipy.linalg.det(self.G[1], check_finite=False)])
self.stack.ovlp = numpy.array([1.0/self.M0[0], 1.0/self.M0[1]])
# # temporary storage for stacks...
I = numpy.identity(system.nbasis, dtype=dtype)
One = numpy.ones(system.nbasis, dtype=dtype)
self.Tl = numpy.array([I, I])
self.Ql = numpy.array([I, I])
self.Dl = numpy.array([One, One])
self.Tr = numpy.array([I, I])
self.Qr = numpy.array([I, I])
self.Dr = numpy.array([One, One])
self.hybrid_energy = 0.0
if verbose:
eloc = self.local_energy(system)
P = one_rdm_from_G(self.G)
nav = particle_number(P)
print("# Initial walker energy: {} {} {}".format(*eloc))
print("# Initial walker electron number: {}".format(nav))
# self.buff_names = ['weight', 'G', 'unscaled_weight', 'phase', 'Tl',
# 'Ql', 'Dl', 'Tr', 'Qr', 'Dr', 'M0']
self.buff_names, self.buff_size = get_numeric_names(self.__dict__)
# self.buff_size = (self.G.size+3+self.Tl.size+2+
# self.Ql.size+self.Dl.size+self.Tr.size+self.Qr.size
# +self.Dr.size)
def greens_function(self, trial, slice_ix=None, inplace=True):
if self.lowrank:
return self.stack.G
else:
return self.greens_function_qr_strat(trial, slice_ix=slice_ix,
inplace=inplace)
def greens_function_svd(self, trial, slice_ix=None, inplace=True):
if slice_ix == None:
slice_ix = self.stack.time_slice
bin_ix = slice_ix // self.stack.stack_size
# For final time slice want first block to be the rightmost (for energy
# evaluation).
if bin_ix == self.stack.nbins:
bin_ix = -1
if inplace:
G = None
else:
G = numpy.zeros(self.G.shape, self.G.dtype)
for spin in [0, 1]:
# Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1}
# in stable way. Iteratively construct SVD decompositions starting
# from the rightmost (product of) propagator(s).
B = self.stack.get((bin_ix+1)%self.stack.nbins)
(U1, S1, V1) = scipy.linalg.svd(B[spin])
for i in range(2, self.stack.nbins+1):
ix = (bin_ix + i) % self.stack.nbins
B = self.stack.get(ix)
T1 = numpy.dot(B[spin], U1)
# todo optimise
T2 = numpy.dot(T1, numpy.diag(S1))
(U1, S1, V) = scipy.linalg.svd(T2)
V1 = numpy.dot(V, V1)
A = numpy.dot(U1.dot(numpy.diag(S1)), V1)
# Final SVD decomposition to construct G(l) = [I + A(l)]^{-1}.
# Care needs to be taken when adding the identity matrix.
T3 = numpy.dot(U1.conj().T, V1.conj().T) + numpy.diag(S1)
(U2, S2, V2) = scipy.linalg.svd(T3)
U3 = numpy.dot(U1, U2)
D3 = numpy.diag(1.0/S2)
V3 = numpy.dot(V2, V1)
# G(l) = (U3 S2 V3)^{-1}
# = V3^{\dagger} D3 U3^{\dagger}
if inplace:
# self.G[spin] = (V3inv).dot(U3.conj().T)
self.G[spin] = (V3.conj().T).dot(D3).dot(U3.conj().T)
else:
# G[spin] = (V3inv).dot(U3.conj().T)
G[spin] = (V3.conj().T).dot(D3).dot(U3.conj().T)
return G
def greens_function_qr(self, trial, slice_ix=None, inplace=True):
if (slice_ix == None):
slice_ix = self.stack.time_slice
bin_ix = slice_ix // self.stack.stack_size
# For final time slice want first block to be the rightmost (for energy
# evaluation).
if bin_ix == self.stack.nbins:
bin_ix = -1
if not inplace:
G = numpy.zeros(self.G.shape, self.G.dtype)
else:
G = None
for spin in [0, 1]:
# Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1}
# in stable way. Iteratively construct SVD decompositions starting
# from the rightmost (product of) propagator(s).
B = self.stack.get((bin_ix+1)%self.stack.nbins)
(U1, V1) = scipy.linalg.qr(B[spin], pivoting=False, check_finite=False)
for i in range(2, self.stack.nbins+1):
ix = (bin_ix + i) % self.stack.nbins
B = self.stack.get(ix)
T1 = numpy.dot(B[spin], U1)
(U1, V) = scipy.linalg.qr(T1, pivoting=False, check_finite=False)
V1 = numpy.dot(V, V1)
# Final SVD decomposition to construct G(l) = [I + A(l)]^{-1}.
# Care needs to be taken when adding the identity matrix.
V1inv = scipy.linalg.solve_triangular(V1, numpy.identity(V1.shape[0]))
T3 = numpy.dot(U1.conj().T, V1inv) + numpy.identity(V1.shape[0])
(U2, V2) = scipy.linalg.qr(T3, pivoting=False, check_finite=False)
U3 = numpy.dot(U1, U2)
V3 = numpy.dot(V2, V1)
V3inv = scipy.linalg.solve_triangular(V3, numpy.identity(V3.shape[0]))
# G(l) = (U3 S2 V3)^{-1}
# = V3^{\dagger} D3 U3^{\dagger}
if inplace:
self.G[spin] = (V3inv).dot(U3.conj().T)
else:
G[spin] = (V3inv).dot(U3.conj().T)
return G
def compute_left_right(self, center_ix):
# Use Stratification method (DOI 10.1109/IPDPS.2012.37)
# B(L) .... B(1)
for spin in [0, 1]:
# right bit
# B(right) ... B(1)
if (center_ix > 0):
# print ("center_ix > 0")
B = self.stack.get(0)
(self.Qr[spin], R1, P1) = scipy.linalg.qr(B[spin], pivoting=True, check_finite=False)
# Form D matrices
self.Dr[spin] = (R1.diagonal())
D1inv = (1.0/R1.diagonal())
self.Tr[spin] = numpy.einsum('i,ij->ij',D1inv, R1)
# now permute them
self.Tr[spin][:,P1] = self.Tr[spin] [:,range(self.nbasis)]
for ix in range(1, center_ix):
B = self.stack.get(ix)
C2 = numpy.einsum('ij,j->ij',
numpy.dot(B[spin], self.Qr[spin]),
self.Dr[spin])
(self.Qr[spin], R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False)
# Compute D matrices
D1inv = (1.0/R1.diagonal())
self.Dr[spin] = (R1.diagonal())
# smarter permutation
# D^{-1} * R
tmp = numpy.einsum('i,ij->ij',D1inv, R1)
# D^{-1} * R * P^T
tmp[:,P1] = tmp[:,range(self.nbasis)]
# D^{-1} * R * P^T * T
self.Tr[spin] = numpy.dot(tmp, self.Tr[spin])
# left bit
# B(l) ... B(left)
if (center_ix < self.stack.nbins-1):
# print("center_ix < self.stack.nbins-1 first")
# We will assume that B matrices are all diagonal for left....
B = self.stack.get(center_ix+1)
self.Dl[spin] = (B[spin].diagonal())
D1inv = (1.0/B[spin].diagonal())
self.Ql[spin] = numpy.identity(B[spin].shape[0])
self.Tl[spin] = numpy.identity(B[spin].shape[0])
for ix in range(center_ix+2, self.stack.nbins):
# print("center_ix < self.stack.nbins-1 first inner loop")
B = self.stack.get(ix)
C2 = (numpy.einsum('ii,i->i',B[spin],self.Dl[spin]))
self.Dl[spin] = C2
def compute_right(self, center_ix):
# Use Stratification method (DOI 10.1109/IPDPS.2012.37)
# B(L) .... B(1)
for spin in [0, 1]:
# right bit
# B(right) ... B(1)
if (center_ix > 0):
# print ("center_ix > 0")
B = self.stack.get(0)
(self.Qr[spin], R1, P1) = scipy.linalg.qr(B[spin], pivoting=True, check_finite=False)
# Form D matrices
self.Dr[spin] = (R1.diagonal())
D1inv = (1.0/R1.diagonal())
self.Tr[spin] = numpy.einsum('i,ij->ij',D1inv, R1)
# now permute them
self.Tr[spin][:,P1] = self.Tr[spin] [:,range(self.nbasis)]
for ix in range(1, center_ix):
B = self.stack.get(ix)
C2 = numpy.einsum('ij,j->ij',
numpy.dot(B[spin], self.Qr[spin]),
self.Dr[spin])
(self.Qr[spin], R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False)
# Compute D matrices
D1inv = (1.0/R1.diagonal())
self.Dr[spin] = (R1.diagonal())
# smarter permutation
# D^{-1} * R
tmp = numpy.einsum('i,ij->ij',D1inv, R1)
# D^{-1} * R * P^T
tmp[:,P1] = tmp[:,range(self.nbasis)]
# D^{-1} * R * P^T * T
self.Tr[spin] = numpy.dot(tmp, self.Tr[spin])
def compute_left(self, center_ix):
# Use Stratification method (DOI 10.1109/IPDPS.2012.37)
# B(L) .... B(1)
for spin in [0, 1]:
# left bit
# B(l) ... B(left)
if (center_ix < self.stack.nbins-1):
# print("center_ix < self.stack.nbins-1 first")
# We will assume that B matrices are all diagonal for left....
B = self.stack.get(center_ix+1)
self.Dl[spin] = (B[spin].diagonal())
self.Ql[spin] = numpy.identity(B[spin].shape[0])
self.Tl[spin] = numpy.identity(B[spin].shape[0])
for ix in range(center_ix+2, self.stack.nbins):
# print("center_ix < self.stack.nbins-1 first inner loop")
B = self.stack.get(ix)
C2 = (numpy.einsum('ii,i->i',B[spin],self.Dl[spin]))
self.Dl[spin] = C2.diagonal()
def greens_function_left_right(self, center_ix, inplace=False, thresh = 1e-6):
assert(self.diagonal_trial)
if not inplace:
G = numpy.zeros(self.G.shape, self.G.dtype)
else:
G = None
mL = self.G.shape[1]
mR = self.G.shape[1]
mT = self.G.shape[1]
Bc = self.stack.get(center_ix)
nbsf = Bc.shape[1]
# It goes to right to left and we sample (I + L*B*R) in the end
for spin in [0,1]:
if (center_ix > 0): # there exists right bit
mR = len(self.Dr[spin][numpy.abs(self.Dr[spin])>thresh])
Ccr = numpy.einsum('ij,j->ij',
numpy.dot(Bc[spin],self.Qr[spin][:,:mR]),
self.Dr[spin][:mR]) # N x mR
(Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Ccr, pivoting=True, check_finite=False)
Dlcr = Rlcr[:mR,:mR].diagonal() # mR
Dinv = 1.0/Dlcr # mR
tmp = numpy.einsum('i,ij->ij',Dinv[:mR], Rlcr[:mR,:mR]) # mR, mR x mR -> mR x mR
tmp[:,Plcr] = tmp[:,range(mR)]
Tlcr = numpy.dot(tmp, self.Tr[spin][:mR,:]) # mR x N
else:
(Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Bc[spin], pivoting=True, check_finite=False)
# Form D matrices
Dlcr = Rlcr.diagonal()
mR = len(Dlcr[numpy.abs(Dlcr) > thresh])
Dinv = 1.0/Rlcr.diagonal()
Tlcr = numpy.einsum('i,ij->ij',Dinv[:mR], Rlcr[:mR,:]) # mR x N
Tlcr[:,Plcr] = Tlcr[:,range(self.nbasis)] # mR x N
if (center_ix < self.stack.nbins-1): # there exists left bit
# assume left stack is all diagonal (i.e., QDT = diagonal -> Q and T are identity)
Clcr = numpy.einsum('i,ij->ij',
self.Dl[spin],
numpy.einsum('ij,j->ij',Qlcr[:,:mR], Dlcr[:mR])) # N x mR
(Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Clcr, pivoting=True, check_finite=False) # N x N, mR x mR
Dlcr = Rlcr.diagonal()
Dinv = 1.0/Dlcr
mT = len(Dlcr[numpy.abs(Dlcr) > thresh])
tmp = numpy.einsum('i,ij->ij',Dinv[:mT], Rlcr[:mT,:])
tmp[:,Plcr] = tmp[:,range(mR)] # mT x mR
Tlcr = numpy.dot(tmp, Tlcr) # mT x N
else:
mT = mR
# D = Ds Db^{-1}
Db = numpy.zeros(mT, Bc[spin].dtype)
Ds = numpy.zeros(mT, Bc[spin].dtype)
for i in range(mT):
absDlcr = abs(Dlcr[i])
if absDlcr > 1.0:
Db[i] = 1.0 / absDlcr
Ds[i] = numpy.sign(Dlcr[i])
else:
Db[i] = 1.0
Ds[i] = Dlcr[i]
if (mT == nbsf): # No need for Woodbury
T1inv = scipy.linalg.inv(Tlcr, check_finite=False)
# C = (Db Q^{-1}T^{-1}+Ds)
C = numpy.dot(
numpy.einsum('i,ij->ij',Db, Qlcr.conj().T),
T1inv) + numpy.diag(Ds)
Cinv = scipy.linalg.inv(C, check_finite = False)
# Then G = T^{-1} C^{-1} Db Q^{-1}
# Q is unitary.
if inplace:
self.G[spin] = numpy.dot(numpy.dot(T1inv, Cinv),
numpy.einsum('i,ij->ij',Db, Qlcr.conj().T))
# return # This seems to change the answer WHY??
else:
G[spin] = numpy.dot(numpy.dot(T1inv, Cinv),
numpy.einsum('i,ij->ij',Db, Qlcr.conj().T))
else: # Use Woodbury
TQ = Tlcr.dot(Qlcr[:,:mT])
TQinv = scipy.linalg.inv(TQ, check_finite=False)
tmp = scipy.linalg.inv(numpy.einsum('ij,j->ij',TQinv, Db) + numpy.diag(Ds), check_finite=False)
A = numpy.einsum("i,ij->ij", Db, tmp.dot(TQinv))
if inplace:
self.G[spin] = numpy.eye(nbsf, dtype=Bc[spin].dtype) - Qlcr[:,:mT].dot(numpy.diag(Dlcr[:mT])).dot(A).dot(Tlcr)
else:
G[spin] = numpy.eye(nbsf, dtype=Bc[spin].dtype) - Qlcr[:,:mT].dot(numpy.diag(Dlcr[:mT])).dot(A).dot(Tlcr)
# print(mR,mT,nbsf)
# print("ref: mL, mR, mT = {}, {}, {}".format(mL, mR, mT))
return G
def greens_function_left_right_no_truncation(self, center_ix, inplace=False):
if not inplace:
G = numpy.zeros(self.G.shape, self.G.dtype)
else:
G = None
Bc = self.stack.get(center_ix)
for spin in [0,1]:
if (center_ix > 0): # there exists right bit
# print("center_ix > 0 second")
Ccr = numpy.einsum('ij,j->ij',
numpy.dot(Bc[spin],self.Qr[spin]),
self.Dr[spin])
(Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Ccr, pivoting=True, check_finite=False)
Dlcr = Rlcr.diagonal()
Dinv = 1.0/Rlcr.diagonal()
tmp = numpy.einsum('i,ij->ij',Dinv, Rlcr)
tmp[:,Plcr] = tmp[:,range(self.nbasis)]
Tlcr = numpy.dot(tmp, self.Tr[spin])
else:
# print("center_ix > 0 else second")
(Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Bc[spin], pivoting=True, check_finite=False)
# Form D matrices
Dlcr = Rlcr.diagonal()
Dinv = 1.0/Rlcr.diagonal()
Tlcr = numpy.einsum('i,ij->ij',Dinv, Rlcr)
Tlcr[:,Plcr] = Tlcr[:,range(self.nbasis)]
if (center_ix < self.stack.nbins-1): # there exists left bit
# print("center_ix < self.stack.nbins-1 second")
# assume left stack is all diagonal
Clcr = numpy.einsum('i,ij->ij',
self.Dl[spin],
numpy.einsum('ij,j->ij',Qlcr, Dlcr))
(Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Clcr, pivoting=True, check_finite=False)
Dlcr = Rlcr.diagonal()
Dinv = 1.0/Rlcr.diagonal()
tmp = numpy.einsum('i,ij->ij',Dinv, Rlcr)
tmp[:,Plcr] = tmp[:,range(self.nbasis)]
Tlcr = numpy.dot(tmp, Tlcr)
# print("Dlcr = {}".format(Dlcr))
# G^{-1} = 1+A = 1+QDT = Q (Q^{-1}T^{-1}+D) T
# Write D = Db^{-1} Ds
# Then G^{-1} = Q Db^{-1}(Db Q^{-1}T^{-1}+Ds) T
Db = numpy.zeros(Bc[spin].shape[-1], Bc[spin].dtype)
Ds = numpy.zeros(Bc[spin].shape[-1], Bc[spin].dtype)
for i in range(Db.shape[0]):
absDlcr = abs(Dlcr[i])
if (absDlcr > 1.0):
Db[i] = 1.0 / absDlcr
Ds[i] = numpy.sign(Dlcr[i])
else:
Db[i] = 1.0
Ds[i] = Dlcr[i]
T1inv = scipy.linalg.inv(Tlcr, check_finite=False)
# C = (Db Q^{-1}T^{-1}+Ds)
C = numpy.dot(
numpy.einsum('i,ij->ij',Db, Qlcr.conj().T),
T1inv) + numpy.diag(Ds)
Cinv = scipy.linalg.inv(C, check_finite = False)
# Then G = T^{-1} C^{-1} Db Q^{-1}
# Q is unitary.
if inplace:
self.G[spin] = numpy.dot(numpy.dot(T1inv, Cinv),
numpy.einsum('i,ij->ij',Db, Qlcr.conj().T))
else:
G[spin] = numpy.dot(numpy.dot(T1inv, Cinv),
numpy.einsum('i,ij->ij',Db, Qlcr.conj().T))
return G
def greens_function_qr_strat(self, trial, slice_ix=None, inplace=True):
# Use Stratification method (DOI 10.1109/IPDPS.2012.37)
if (slice_ix == None):
slice_ix = self.stack.time_slice
bin_ix = slice_ix // self.stack.stack_size
# For final time slice want first block to be the rightmost (for energy
# evaluation).
if bin_ix == self.stack.nbins:
bin_ix = -1
if not inplace:
G = numpy.zeros(self.G.shape, self.G.dtype)
else:
G = None
for spin in [0, 1]:
# Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} in
# stable way. Iteratively construct column pivoted QR decompositions
# (A = QDT) starting from the rightmost (product of) propagator(s).
B = self.stack.get((bin_ix+1)%self.stack.nbins)
(Q1, R1, P1) = scipy.linalg.qr(B[spin], pivoting=True,
check_finite=False)
# Form D matrices
D1 = numpy.diag(R1.diagonal())
D1inv = numpy.diag(1.0/R1.diagonal())
T1 = numpy.einsum('ii,ij->ij', D1inv, R1)
# permute them
T1[:,P1] = T1 [:, range(self.nbasis)]
for i in range(2, self.stack.nbins+1):
ix = (bin_ix + i) % self.stack.nbins
B = self.stack.get(ix)
C2 = numpy.dot(numpy.dot(B[spin], Q1), D1)
(Q1, R1, P1) = scipy.linalg.qr(C2, pivoting=True,
check_finite=False)
# Compute D matrices
D1inv = numpy.diag(1.0/R1.diagonal())
D1 = numpy.diag(R1.diagonal())
tmp = numpy.einsum('ii,ij->ij',D1inv, R1)
tmp[:,P1] = tmp[:,range(self.nbasis)]
T1 = numpy.dot(tmp, T1)
# G^{-1} = 1+A = 1+QDT = Q (Q^{-1}T^{-1}+D) T
# Write D = Db^{-1} Ds
# Then G^{-1} = Q Db^{-1}(Db Q^{-1}T^{-1}+Ds) T
Db = numpy.zeros(B[spin].shape, B[spin].dtype)
Ds = numpy.zeros(B[spin].shape, B[spin].dtype)
for i in range(Db.shape[0]):
absDlcr = abs(Db[i,i])
if absDlcr > 1.0:
Db[i,i] = 1.0 / absDlcr
Ds[i,i] = numpy.sign(D1[i,i])
else:
Db[i,i] = 1.0
Ds[i,i] = D1[i,i]
T1inv = scipy.linalg.inv(T1, check_finite = False)
# C = (Db Q^{-1}T^{-1}+Ds)
C = numpy.dot(numpy.einsum('ii,ij->ij',Db, Q1.conj().T), T1inv) + Ds
Cinv = scipy.linalg.inv(C, check_finite=False)
# Then G = T^{-1} C^{-1} Db Q^{-1}
# Q is unitary.
if inplace:
self.G[spin] = numpy.dot(numpy.dot(T1inv, Cinv),
numpy.einsum('ii,ij->ij', Db, Q1.conj().T))
else:
G[spin] = numpy.dot(numpy.dot(T1inv, Cinv),
numpy.einsum('ii,ij->ij', Db, Q1.conj().T))
return G
def local_energy(self, system, two_rdm=None):
rdm = one_rdm_from_G(self.G)
return local_energy(system, rdm, two_rdm=two_rdm)
def unit_test():
from pauxy.systems.ueg import UEG
from pauxy.trial_density_matrices.onebody import OneBody
from pauxy.thermal_propagation.planewave import PlaneWave
from pauxy.qmc.options import QMCOpts
inputs = {'nup':1,
'ndown':1,
'rs':1.0,
'ecut':0.5,
"name": "one_body",
"mu":1.94046021,
"beta":0.5,
"dt": 0.05,
"optimised": True
}
beta = inputs ['beta']
dt = inputs['dt']
system = UEG(inputs, verbose = False)
qmc = QMCOpts(inputs, system, True)
trial = OneBody(inputs, system, beta, dt, system.H1, verbose=False)
walker = ThermalWalker(inputs, system, trial, True)
# walker.greens_function(trial)
E, T, V = walker.local_energy(system)
numpy.random.seed(0)
inputs['optimised'] = False
propagator = PlaneWave(inputs, qmc, system, trial, verbose=False)
propagator.propagate_walker_free(system, walker, trial, False)
Gold = walker.G[0].copy()
system = UEG(inputs, verbose=False)
qmc = QMCOpts(inputs, system, verbose=False)
trial = OneBody(inputs, system, beta, dt, system.H1, verbose=False)
propagator = PlaneWave(inputs, qmc, system, trial, True)
walker = ThermalWalker(inputs, system, trial, verbose=False)
# walker.greens_function(trial)
E, T, V = walker.local_energy(system)
numpy.random.seed(0)
inputs['optimised'] = True
propagator = PlaneWave(inputs, qmc, system, trial, verbose=False)
propagator.propagate_walker_free(system, walker, trial, False)
Gnew = walker.G[0].copy()
assert(scipy.linalg.norm(Gold[:,0] - Gnew[:,0]) < 1e-10)
inputs['stack_size'] = 1
walker = ThermalWalker(inputs, system, trial, verbose=False)
numpy.random.seed(0)
propagator = PlaneWave(inputs, qmc, system, trial, verbose=False)
for i in range(0,5):
propagator.propagate_walker(system, walker, trial)
Gs1 = walker.G[0].copy()
for ts in range(walker.stack_length):
walker.greens_function(trial, slice_ix=ts*walker.stack_size)
E, T, V = walker.local_energy(system)
# print(E)
inputs['stack_size'] = 5
walker = ThermalWalker(inputs, system, trial, verbose=False)
numpy.random.seed(0)
propagator = PlaneWave(inputs, qmc, system, trial, verbose=False)
for i in range(0,5):
propagator.propagate_walker(system, walker, trial)
Gs5 = walker.G[0].copy()
for ts in range(walker.stack_length):
walker.greens_function(trial, slice_ix=ts*walker.stack_size)
E, T, V = walker.local_energy(system)
# print(E)
assert(numpy.linalg.norm(Gs1-Gs5) < 1e-10)
N = 5
A = numpy.random.rand(N,N)
Q, R, P = scipy.linalg.qr(A, pivoting=True)
#### test permutation start
# Pmat = numpy.zeros((N,N))
# for i in range (N):
# Pmat[P[i],i] = 1
# print(P)
# tmp = Q.dot(R)#.dot(Pmat.T)
# print(tmp)
# print("==================")
# tmp2 = tmp.dot(Pmat.T)
# print(tmp2)
# print("==================")
# tmp[:,P] = tmp [:,range(N)]
# print(tmp)
#### test permutation end
B = numpy.random.rand(N,N)
(Q1, R1, P1) = scipy.linalg.qr(B, pivoting=True, check_finite = False)
# Form permutation matrix
P1mat = numpy.zeros(B.shape, B.dtype)
P1mat[P1,range(len(P1))] = 1.0
# Form D matrices
D1 = numpy.diag(R1.diagonal())
D1inv = numpy.diag(1.0/R1.diagonal())
T1 = numpy.dot(numpy.dot(D1inv, R1), P1mat.T)
assert(numpy.linalg.norm(B - numpy.einsum('ij,jj->ij',Q1,D1).dot(T1)) < 1e-10)
# tmp[:,:] = tmp[:,P]
# print(A - tmp)
# print(Q * Q.T)
# print(R)
# Test walker green's function.
from pauxy.systems.hubbard import Hubbard
from pauxy.estimators.thermal import greens_function, one_rdm_from_G
from pauxy.estimators.hubbard import local_energy_hubbard
sys_dict = {'name': 'Hubbard', 'nx': 4, 'ny': 4,
'nup': 7, 'ndown': 7, 'U': 4, 't': 1}
system = Hubbard(sys_dict)
beta = 4
mu = 1
trial = OneBody({"mu": mu}, system, beta, dt, verbose=True)
dt = 0.05
num_slices = int(beta/dt)
eref = 0
for ek in system.eks:
eref += 2 * ek * 1.0 / (numpy.exp(beta*(ek-mu))+1)
walker = ThermalWalker({"stack_size": 1}, system, trial)
Gs1 = walker.G[0].copy()
rdm = one_rdm_from_G(walker.G)
ekin = local_energy_hubbard(system, rdm)[1]
try:
assert(abs(eref-ekin) < 1e-8)
except AssertionError:
print("Error in kinetic energy check. Ref: %13.8e Calc:%13.8e"%(eref, ekin))
walker = ThermalWalker({"stack_size": 10}, system, trial)
rdm = one_rdm_from_G(walker.G)
ekin = local_energy_hubbard(system, rdm)[1]
try:
assert(abs(eref-ekin) < 1e-8)
except AssertionError:
print("Error in kinetic energy check. Ref: %13.10e Calc: %13.10e"
" Error: %13.8e"%(eref.real, ekin.real, abs(eref-ekin)))
for ts in range(walker.stack_length):
walker.greens_function(trial, slice_ix=ts*walker.stack_size)
assert(numpy.linalg.norm(Gs1-walker.G[0]) < 1e-10)
if __name__=="__main__":
unit_test()
| 41.678014 | 130 | 0.510499 | 23,871 | 0.812409 | 0 | 0 | 0 | 0 | 0 | 0 | 5,476 | 0.186366 |
4108de14460ec5d4d27312f76596c4d68c7d284a | 1,607 | py | Python | schedules_tools/batches/utils.py | RedHat-Eng-PGM/python-schedules-tools | 6166cdd0e5f7c08fba1c50f113ae6a6103460f9b | [
"MIT"
]
| 1 | 2019-05-06T21:10:35.000Z | 2019-05-06T21:10:35.000Z | schedules_tools/batches/utils.py | RedHat-Eng-PGM/schedules-tools | fd96a9e1df4e53b8da3048c013af0cd2c290f9b5 | [
"MIT"
]
| 5 | 2019-05-06T21:25:38.000Z | 2021-02-05T20:54:30.000Z | schedules_tools/batches/utils.py | RedHat-Eng-PGM/schedules-tools | fd96a9e1df4e53b8da3048c013af0cd2c290f9b5 | [
"MIT"
]
| 1 | 2019-10-31T01:51:41.000Z | 2019-10-31T01:51:41.000Z | from collections import OrderedDict
import os
import re
from schedules_tools.schedule_handlers.smart_sheet import ScheduleHandler_smartsheet
import yaml
DEFAULT_TEMPLATE_DIR = os.path.join(os.path.dirname(__file__), 'templates')
DEPENDENCY_REGEX = re.compile(r'^{(?P<to>predecessor|\d+)}(?P<type>[F|S]+)?'
r'( ?(?P<lag_sign>[+|-])?(?P<lag_amount>\d+)'
r'(?P<lag_type>[d|w]))?$')
def load_template(template_name):
template_dir = os.getenv('BATCHES_TEMPLATE_DIR', DEFAULT_TEMPLATE_DIR)
template_path = os.path.join(template_dir, '%s.yml' % template_name)
if not os.path.exists(template_path):
raise ValueError('Template "%s" now found.', template_name)
with open(template_path, 'r') as f:
template = yaml.safe_load(f)
tasks = OrderedDict()
for task in template['tasks']:
task_id = task.pop('id')
if 'dependency' in task:
dependency_match = DEPENDENCY_REGEX.match(task['dependency'])
if not dependency_match:
raise ValueError('Incorrect dependency format: %s' % task['dependency'])
else:
task['dependency'] = dependency_match.groupdict()
tasks[task_id] = task
template['tasks'] = tasks
return template
def initialize_ss_handler(handle):
api_token = os.getenv('SMARTSHEET_TOKEN')
if not api_token:
raise ValueError('SMARTSHEET_TOKEN required')
handler = ScheduleHandler_smartsheet(
handle=handle,
options={'smartsheet_token': api_token}
)
return handler
| 31.509804 | 88 | 0.645924 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 348 | 0.216553 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.