code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from collections import defaultdict
import logging
from django.db import transaction
from django.utils import six
logger = logging.getLogger(__name__)
class Importer(object):
'''
Imports objects from source database to dest database.
It respects ForeignKey and OneToOne relationships, so it
recursively follows them and creates the related objects as well.
It fails when there is a cyclic relationship between the objects, i.e.:
A -> B -> C -> A
'''
def __init__(self, source_db, dest_db, batch_size=100):
self.source_db = source_db
self.dest_db = dest_db
self.batch_size = batch_size
def import_objects(self, querysets):
self.model_2_pks = defaultdict(set)
for qs in querysets:
pks = qs.using(self.source_db).values_list('pk', flat=True)
self.model_2_pks[qs.model] |= set(pks)
# topologically sort the models based on their relations
self.topsorted_models = []
for model in six.iterkeys(self.model_2_pks):
self._follow_model_relations(model)
# collect pks of related objects the import
for model in reversed(self.topsorted_models):
self._collect_related_pks(model)
# clean pks of already existing objects
for model, pks in six.iteritems(self.model_2_pks):
existing_pks = set(model._default_manager
.using(self.dest_db)
.filter(pk__in=pks)
.values_list('pk', flat=True))
pks -= existing_pks
# output info
for model in self.topsorted_models:
logger.debug('Importing %s new objects of %s',
len(self.model_2_pks[model]), model._meta.label)
# create objects
with transaction.atomic(using=self.dest_db):
for model in self.topsorted_models:
self._create_objects(model)
def _create_objects(self, model):
pks = list(self.model_2_pks[model])
total = len(pks)
logger.debug('Importing %s...', model._meta.label)
for start in xrange(0, total, self.batch_size):
end = min(total, start + self.batch_size)
objs = model._default_manager \
.using(self.source_db) \
.filter(pk__in=pks[start:end])
model._default_manager \
.using(self.dest_db) \
.bulk_create(objs)
def _collect_related_pks(self, model):
related_fields = [
field for field in model._meta.fields
if (field.one_to_one or field.many_to_one) and field.related_model != model]
qs = model._default_manager \
.using(self.source_db) \
.filter(pk__in=self.model_2_pks[model]) \
.values(*(field.attname for field in related_fields))
for values in qs:
for field in related_fields:
related_pk = values[field.attname]
if related_pk is not None:
self.model_2_pks[field.related_model].add(related_pk)
def _follow_model_relations(self, model, pending_models=None):
# model already processed
if model in self.topsorted_models:
return
# check circular relationship
if pending_models is None:
pending_models = []
elif model in pending_models:
raise RuntimeError('Circular relationship in models detected for models: %s -> %s!' %
(' -> '.join(pending_model._meta.label for pending_model in pending_models), model._meta.label))
pending_models.append(model)
for field in model._meta.fields:
if (field.one_to_one or field.many_to_one) and field.related_model != model:
self._follow_model_relations(field.related_model, pending_models)
pending_models.pop()
self.topsorted_models.append(model)
| [
"logging.getLogger",
"django.utils.six.iteritems",
"django.utils.six.iterkeys",
"django.db.transaction.atomic",
"collections.defaultdict"
] | [((126, 153), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (143, 153), False, 'import logging\n'), ((721, 737), 'collections.defaultdict', 'defaultdict', (['set'], {}), '(set)\n', (732, 737), False, 'from collections import defaultdict\n'), ((1012, 1042), 'django.utils.six.iterkeys', 'six.iterkeys', (['self.model_2_pks'], {}), '(self.model_2_pks)\n', (1024, 1042), False, 'from django.utils import six\n'), ((1319, 1350), 'django.utils.six.iteritems', 'six.iteritems', (['self.model_2_pks'], {}), '(self.model_2_pks)\n', (1332, 1350), False, 'from django.utils import six\n'), ((1797, 1835), 'django.db.transaction.atomic', 'transaction.atomic', ([], {'using': 'self.dest_db'}), '(using=self.dest_db)\n', (1815, 1835), False, 'from django.db import transaction\n')] |
from dataclasses import dataclass
import datetime
@dataclass
class Object:
confidence: int
@dataclass
class Dimension:
width: int
height: int
depth: int
@dataclass
class Annotation:
class_id: int
top: int
left: int
width: int
height: int
@dataclass
class BoundingBox:
image_size: [Dimension]
annotations: [Annotation]
@dataclass
class BoundingBoxMetadata:
objects: [Object]
class_map: dict
type: str = 'groundtruth/object-detection'
human_annotated: str = 'yes'
creation_date: str = str(datetime.datetime.now())
job_name: str = 'manual-conversion'
@dataclass
class GroundTruth:
source_ref: str
bounding_box: BoundingBox
bounding_box_metadata: BoundingBoxMetadata
| [
"datetime.datetime.now"
] | [((561, 584), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (582, 584), False, 'import datetime\n')] |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 23 15:57:53 2016
@author: jone0208
"""
import Body
import matplotlib.pyplot as plt
import Solver
import Simulation
def main():
skull = Body.GravBody(5,5,5)
solver = Solver.RK2(0.001)
def stop_condition(skull):
return skull.velocity > 0
sim = Simulation.TrajectorySim(stop_condition,solver,skull)
t, h = sim.get_results()
plt.plot(t,h)
plt.title("OOP Skull Toss")
plt.xlabel("Time [s]")
plt.ylabel("Height [m]")
if __name__ == "__main__": main() | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"Solver.RK2",
"Body.GravBody",
"matplotlib.pyplot.title",
"Simulation.TrajectorySim"
] | [((189, 211), 'Body.GravBody', 'Body.GravBody', (['(5)', '(5)', '(5)'], {}), '(5, 5, 5)\n', (202, 211), False, 'import Body\n'), ((223, 240), 'Solver.RK2', 'Solver.RK2', (['(0.001)'], {}), '(0.001)\n', (233, 240), False, 'import Solver\n'), ((316, 371), 'Simulation.TrajectorySim', 'Simulation.TrajectorySim', (['stop_condition', 'solver', 'skull'], {}), '(stop_condition, solver, skull)\n', (340, 371), False, 'import Simulation\n'), ((403, 417), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'h'], {}), '(t, h)\n', (411, 417), True, 'import matplotlib.pyplot as plt\n'), ((421, 448), 'matplotlib.pyplot.title', 'plt.title', (['"""OOP Skull Toss"""'], {}), "('OOP Skull Toss')\n", (430, 448), True, 'import matplotlib.pyplot as plt\n'), ((453, 475), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time [s]"""'], {}), "('Time [s]')\n", (463, 475), True, 'import matplotlib.pyplot as plt\n'), ((480, 504), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Height [m]"""'], {}), "('Height [m]')\n", (490, 504), True, 'import matplotlib.pyplot as plt\n')] |
from twilio.rest import Client
class _Notifier:
def __init__(self, twilio_account_sid, twilio_auth_token, twilio_phone_number):
self.client = Client(twilio_account_sid, twilio_auth_token)
self.phone_number = twilio_phone_number
pass
class Messenger(_Notifier):
def _send_sms(self, phone, text):
try:
self.client.api.account.messages.create(
to=phone,
from_=self.phone_number,
body=text)
except:
print('Fail on Twilio.')
pass
def welcome_message(self, user_gsm, username):
self._send_sms(user_gsm, "Welcome %s, we are happy to see you among us, let's RaiseIt together!, RaiseIt" % username)
def deposit_message(self, user_gsm, amount):
self._send_sms(user_gsm, '%s credits are just deposited to your account!, RaiseIt' % amount)
def bid_raised_message(self, user_gsm):
self._send_sms(user_gsm, "Your bid is just raised by someone else!, RaiseIt")
| [
"twilio.rest.Client"
] | [((156, 201), 'twilio.rest.Client', 'Client', (['twilio_account_sid', 'twilio_auth_token'], {}), '(twilio_account_sid, twilio_auth_token)\n', (162, 201), False, 'from twilio.rest import Client\n')] |
from typing import List, Dict, Optional
from myutils.registrar import Registrar
from myutils import dictionaries
import os, yaml
from os import path
import json
from .exceptions import FeatureConfigException
reg_plots = Registrar()
reg_features = Registrar()
KEY_SAMPLE = 'smp'
KEY_AVERAGE = 'avg'
KEY_TICKS = 'tck'
KEY_MAX_DIF = 'mdf'
KEY_COMPARE = 'cmp'
class ConfigGenerator:
CONFIG_SPEC = {
'name': {
'type': str
},
'kwargs': {
'type': dict
}
}
def __init__(self, cfg_dir: str, out_dir, reg: Registrar):
self._cfg_dir = path.abspath(path.expandvars(cfg_dir))
if not path.isdir(self._cfg_dir):
raise FeatureConfigException(f'configuration dir "{self._cfg_dir}" is not a directory')
self._out_dir = path.abspath(path.expandvars(out_dir))
if not path.isdir(self._out_dir):
raise FeatureConfigException(f'output dir "{self._out_dir}" is not a directory')
self._reg = reg
def reload(self):
_, _, filenames = next(os.walk(self._cfg_dir))
for fn in filenames:
p_in = path.join(self._cfg_dir, fn)
with open(p_in, 'r') as f:
data = f.read()
file_cfg = yaml.load(data, yaml.FullLoader)
dictionaries.validate_config(file_cfg, self.CONFIG_SPEC)
reg_nm = file_cfg['name']
reg_kwargs = file_cfg['kwargs']
ftr_cfg = self._reg[reg_nm](**reg_kwargs)
p_out = path.join(self._out_dir, fn)
with open(p_out, 'w') as f:
f.write(yaml.dump(ftr_cfg, sort_keys=False))
p_out_json = path.splitext(p_out)[0] + '.json'
with open(p_out_json, 'w') as f:
f.write(json.dumps(ftr_cfg, indent=2, sort_keys=False))
def _plot_procs_lad(ftr_key, lad_key):
"""return processors to add ladder feature of price sizes to back/lay feature"""
return [
{
'name': 'prc_ftrstodf',
'kwargs': {
'ftr_keys': {
'y': ftr_key,
'text': lad_key
}
}
}, {
'name': 'prc_dffmtps',
'kwargs': {
'df_col': 'text'
}
}, {
'name': 'prc_dftodict'
}
]
def _plot_colorscale(color_0, color_1) -> Dict:
"""`chart_args` argument to set colorscale with lines+markers"""
return {
'mode': 'lines+markers',
'line_color': 'black',
'marker': {
'colorscale': [
[0, color_0],
[1, color_1]
],
'cmid': 0,
}
}
def _ftr_smooth(sample_ms, cache_count):
"""sub-features config for sampling and then moving average"""
return {
KEY_SAMPLE: {
'name': 'RFSample',
'kwargs': {
'periodic_ms': sample_ms,
'cache_count': cache_count,
'sub_features_config': {
KEY_AVERAGE: {
'name': 'RFMvAvg'
}
}
}
}
}
def _ftr_tick(sub_features_config=None):
"""sub-feature converting parent to tick"""
return {
'name': 'RunnerFeatureSub',
'kwargs': {
'value_processors_config': [{
'name': 'value_processor_to_tick',
}],
'sub_features_config': sub_features_config,
},
}
def _ftr_tvlad(window_s, sampling_ms, cache_count):
"""traded volume `TVLad` feature sub-config for creating max/min values over window, sampling then moving avg"""
return {
'cache_secs': window_s,
'cache_insidewindow': False,
'sub_features_config': {
'dif': {
'name': 'RFTVLadDif',
'kwargs': {
'sub_features_config': {
'max': {
'name': 'RFTVLadMax',
'kwargs': {
'sub_features_config': _ftr_smooth(sampling_ms, cache_count)
}
},
'min': {
'name': 'RFTVLadMin',
'kwargs': {
'sub_features_config': _ftr_smooth(sampling_ms, cache_count)
}
}
}
}
}
}
}
@reg_features.register_element
def feature_configs_spike(
n_ladder_elements,
n_wom_ticks,
ltp_window_width_s,
ltp_window_sampling_ms,
ltp_window_sampling_count,
spread_sampling_ms,
spread_sampling_count,
) -> Dict[str, Dict]:
"""
Get a dict of default runner features, where each entry is a dictionary of:
- key: feature usage name
- value: dict of
- 'name': class name of feature
- 'kwargs': dict of constructor arguments used when creating feature
"""
def ltp_win_kwargs(sample_ms, cache_count):
d = {
'sub_features_config': {
'smp': {
'name': 'RFSample',
'kwargs': {
'periodic_ms': sample_ms,
'cache_count': cache_count,
'sub_features_config': {
'avg': {
'name': 'RFMvAvg'
}
}
}
}
}
}
return d
return {
'best back': {
'name': 'RFBck',
},
'best lay': {
'name': 'RFLay',
},
'back ladder': {
'name': 'RFLadBck',
'kwargs': {
'n_elements': n_ladder_elements,
}
},
'lay ladder': {
'name': 'RFLadLay',
'kwargs': {
'n_elements': n_ladder_elements,
}
},
'wom': {
'name': 'RFWOM',
'kwargs': {
'wom_ticks': n_wom_ticks
},
},
'tvlad': {
'name': 'RFTVLad',
'kwargs': {
'cache_secs': ltp_window_width_s,
'cache_insidewindow': False,
'sub_features_config': {
'dif': {
'name': 'RFTVLadDif',
'kwargs': {
'sub_features_config': {
'max': {
'name': 'RFTVLadMax',
'kwargs': ltp_win_kwargs(ltp_window_sampling_ms, ltp_window_sampling_count)
},
'min': {
'name': 'RFTVLadMin',
'kwargs': ltp_win_kwargs(ltp_window_sampling_ms, ltp_window_sampling_count)
},
'spread': {
'name': 'RFTVLadSpread'
}
}
}
}
}
}
},
'ltp': {
'name': 'RFLTP',
},
'tv': {
'name': 'RFTVTot',
},
'spread': {
'name': 'RFLadSprd',
'kwargs': {
'sub_features_config': {
'smp': {
'name': 'RFSample',
'kwargs': {
'periodic_ms': spread_sampling_ms,
'cache_count': spread_sampling_count,
'sub_features_config': {
'avg': {
'name': 'RFMvAvg'
}
}
}
}
}
}
}
}
@reg_plots.register_element
def plot_configs_spike(
ltp_diff_opacity,
ltp_diff_s,
tv_width_ms
):
IGNORE = [
'back ladder',
'lay ladder',
'spread',
'spread.smp',
'spread.smp.avg',
'wom',
'tvlad',
'tvlad.dif',
'tvlad.dif.max',
'tvlad.dif.max.smp',
'tvlad.dif',
'tvlad.dif.spread',
'tvlad.dif.min',
'tvlad.dif.min.smp',
]
return {
k: {
'ignore': True
} for k in IGNORE
} | {
'best back': {
'value_processors': _plot_procs_lad('best back', 'back ladder'),
},
'best lay': {
'value_processors': _plot_procs_lad('best lay', 'lay ladder')
},
'ltp': {
'chart_args': {
'mode': 'lines+markers'
},
'value_processors': [{
'name': 'prc_ftrstodf',
'kwargs': {
'ftr_keys': {
'y': 'ltp',
'text': 'tv',
}
}
}, {
'name': 'prc_dffillna'
}, {
'name': 'prc_dffmtstr',
'kwargs': {
'df_col': 'text',
'fmt_spec': 'Traded Volume: £{0:.2f}'
}
}, {
'name': 'prc_dftodict',
}],
},
'tv': {
'chart': 'Bar',
'chart_args': {
'marker': {
'colorscale': [
[0, 'rgb(250,50,50)'],
[1, 'rgb(50,250,50)']
], # default plotly colours go white, so use a green to red scale
'cmid': 0, # with grey 0 scale
},
'opacity': ltp_diff_opacity,
'width': tv_width_ms, # 1 seconds width of bars
'offset': 0, # end of bar to be aligned with timestamp
},
'trace_args': {
'secondary_y': True
},
'value_processors': [{
'name': 'prc_dfdiff'
}, {
'name': 'prc_getftr',
'keys': {
'key_out': 'key_1'
},
'kwargs': {
'ftr_key': 'wom',
}
}, {
'name': 'prc_buftodf',
'kwargs': {
'buf_cfg': {
'y': 'key_0',
'text': 'key_1'
},
}
}, {
'name': 'prc_dftypes',
'kwargs': {
'dtypes': {
'y': 'float',
'text': 'float',
}
}
}, {
'name': 'prc_resmp',
'kwargs': {
'n_seconds': tv_width_ms/1000,
'agg_function': {
'y': 'sum',
'text': 'mean',
}
}
}, {
'name': 'prc_dfcp',
'kwargs': {
'col_src': 'text',
'col_out': 'marker_color'
}
}, {
'name': 'prc_dffmtstr',
'kwargs': {
'df_col': 'text',
'fmt_spec': 'Weight of Money: £{0:.2f}'
},
}, {
'name': 'prc_dftodict'
}],
},
'tvlad.dif.max.smp.avg': {
'rename': 'ltp max'
},
'tvlad.dif.min.smp.avg': {
'rename': 'ltp min'
}
}
@reg_features.register_element
def feature_configs_smooth(
spread_sampling_ms,
spread_sampling_count,
wom_ticks,
ltp_window_width_s,
ltp_window_sampling_ms,
ltp_window_sampling_count,
ladder_sampling_ms,
ladder_sampling_count,
ltp_sampling_ms,
ltp_sampling_count,
n_ladder_elements,
diff_s,
split_sum_s,
):
def side_kwargs(diff_s, ladder_sampling_ms, ladder_sampling_count) -> Dict:
return {
'cache_secs': diff_s,
'cache_insidewindow': False,
'sub_features_config': {
KEY_TICKS: {
'name': 'RFTick',
'kwargs': {
'cache_secs': diff_s,
'cache_insidewindow': False,
'sub_features_config': {
KEY_MAX_DIF: {
'name': 'RFMaxDif'
},
KEY_SAMPLE: {
'name': 'RFSample',
'kwargs': {
'periodic_ms': ladder_sampling_ms,
'cache_count': ladder_sampling_count,
'sub_features_config': {
KEY_AVERAGE: {
'name': 'RFMvAvg',
'kwargs': {
'cache_secs': diff_s,
'sub_features_config': {
KEY_COMPARE: {
'name': 'RFDif'
}
}
}
}
}
}
}
}
}
},
KEY_SAMPLE: {
'name': 'RFSample',
'kwargs': {
'periodic_ms': ladder_sampling_ms,
'cache_count': ladder_sampling_count,
'sub_features_config': {
KEY_AVERAGE: {
'name': 'RFMvAvg'
}
}
}
}
}
}
return {
'spread': {
'name': 'RFLadSprd',
'kwargs': {
'sub_features_config': _ftr_smooth(
spread_sampling_ms,
spread_sampling_count
)
}
},
'lay': {
'name': 'RFLay',
'kwargs': side_kwargs(diff_s, ladder_sampling_ms, ladder_sampling_count)
},
'bck': {
'name': 'RFBck',
'kwargs': side_kwargs(diff_s, ladder_sampling_ms, ladder_sampling_count)
},
'ltp': {
'name': 'RFLTP',
'kwargs': {
'sub_features_config': _ftr_smooth(
ltp_sampling_ms,
ltp_sampling_count
),
}
},
'tvlad': {
'name': 'RFTVLad',
'kwargs': _ftr_tvlad(
ltp_window_width_s,
ltp_window_sampling_ms,
ltp_window_sampling_count
)
},
'bcklad': {
'name': 'RFLadBck',
'kwargs': {
'n_elements': n_ladder_elements,
}
},
'laylad': {
'name': 'RFLadLay',
'kwargs': {
'n_elements': n_ladder_elements,
}
},
'wom': {
'name': 'RFWOM',
'kwargs': {
'wom_ticks': wom_ticks
},
},
'split': {
'name': 'RFBkSplit',
'kwargs': {
'cache_secs': split_sum_s,
'cache_insidewindow': False,
'sub_features_config': {
'sum': {
'name': 'RFSum'
},
'tot': {
'name': 'RFIncSum'
}
}
}
},
'tv': {
'name': 'RFTVTot',
},
}
@reg_plots.register_element
def plot_configs_smooth(bar_width_ms, tv_opacity):
IGNORE_LIST = [
'bcklad',
'laylad',
'wom',
'spread',
'spread.smp',
'spread.smp.avg',
'tv',
'bck.smp',
'lay.smp',
'bck.tck',
'lay.tck',
'bck.tck.mdf',
'lay.tck.mdf',
'bck.tck.smp',
'lay.tck.smp',
'bck.tck.smp.avg',
'lay.tck.smp.avg',
'bck.tck.smp.avg.cmp',
'lay.tck.smp.avg.cmp',
'ltp.smp',
'tvlad',
'tvlad.dif',
'tvlad.dif.max',
'tvlad.dif.max.smp',
'tvlad.dif',
'tvlad.dif.min',
'tvlad.dif.min.smp',
]
def prcs_ltp(ltp, tv, spread, split) -> List[Dict]:
return [{
'name': 'prc_ftrstodf',
'kwargs': {
'ftr_keys': {
'y': ltp,
'tv_text': tv,
'spread_text': spread,
'split_text': split,
'marker_color': 'wom',
'wom_text': 'wom',
}
}
}, {
'name': 'prc_dffillna',
}, {
'name': 'prc_dffmtstr',
'kwargs': {
'df_col': 'spread_text',
'fmt_spec': 'Spread: {0}'
}
}, {
'name': 'prc_dffmtstr',
'kwargs': {
'df_col': 'tv_text',
'fmt_spec': 'Traded Volume: £{0:.2f}'
}
}, {
'name': 'prc_dffmtstr',
'kwargs': {
'df_col': 'split_text',
'fmt_spec': 'Book split: £{0:.2f}'
}
}, {
'name': 'prc_dffmtstr',
'kwargs': {
'df_col': 'wom_text',
'fmt_spec': 'WOM: £{0:.2f}'
}
}, {
'name': 'prc_dftxtjoin',
'kwargs': {
'dest_col': 'text',
'src_cols': [
'tv_text',
'spread_text',
'split_text',
'wom_text'
],
}
}, {
'name': 'prc_dfdrop',
'kwargs': {
'cols': [
'tv_text',
'spread_text',
'split_text',
'wom_text'
]
}
}, {
'name': 'prc_dftodict',
}]
def prcs_tvbar(tv, bar_width_ms):
return [{
'name': 'prc_getftr',
'keys': {
'key_out': 'key_tv'
},
'kwargs': {
'ftr_key': tv
}
}, {
'name': 'prc_dfdiff',
'keys': {
'key_in': 'key_tv',
'key_out': 'key_tv'
}
}, {
'name': 'prc_buftodf',
'kwargs': {
'buf_cfg': {
'y': 'key_0',
'text': 'key_tv'
}
}
}, {
'name': 'prc_resmp',
'kwargs': {
'n_seconds': int(bar_width_ms / 1000),
'agg_function': {
'y': 'sum',
'text': 'sum'
}
}
}, {
'name': 'prc_dfcp',
'kwargs': {
'col_src': 'text',
'col_out': 'marker_color'
}
}, {
'name': 'prc_dffmtstr',
'kwargs': {
'df_col': 'text',
'fmt_spec': 'Traded volume: £{0:.2f}'
}
}, {
'name': 'prc_dftodict'
}]
def smooth_value_processors(ftr_src, ftr_tks, ftr_cmp, ftr_dif) -> List[Dict]:
return [{
'name': 'prc_ftrstodf',
'kwargs': {
'ftr_keys': {
'y': ftr_src,
'marker_color': ftr_cmp,
'text_ticks': ftr_tks,
'text_tick_comp': ftr_cmp,
'text_max_diff': ftr_dif
}
},
}, {
'name': 'prc_dffillna',
}, {
'name': 'prc_dffmtstr',
'kwargs': {
'df_col': 'text_ticks',
'fmt_spec': 'Tick: {0:.2f}'
}
}, {
'name': 'prc_dffmtstr',
'kwargs': {
'df_col': 'text_tick_comp',
'fmt_spec': 'Tick difference: {0:.2f}'
}
}, {
'name': 'prc_dffmtstr',
'kwargs': {
'df_col': 'text_max_diff',
'fmt_spec': 'Max tick difference: {0:.2f}',
}
}, {
'name': 'prc_dftxtjoin',
'kwargs': {
'dest_col': 'text',
'src_cols': [
'text_ticks',
'text_tick_comp',
'text_max_diff'
],
}
}, {
'name': 'prc_dfdrop',
'kwargs': {
'cols': [
'text_ticks',
'text_tick_comp',
'text_max_diff'
]
}
}, {
'name': 'prc_dftodict',
}]
return {
f: {
'ignore': True
} for f in IGNORE_LIST
} | {
'tvlad.dif.max.smp.avg': {
'rename': 'ltp max'
},
'tvlad.dif.min.smp.avg': {
'rename': 'ltp min'
},
'bck': {
'chart_args': {
'visible': 'legendonly',
},
'value_processors': _plot_procs_lad('bck', 'bcklad'),
},
'lay': {
'chart_args': {
'visible': 'legendonly',
},
'value_processors': _plot_procs_lad('lay', 'laylad'),
},
'ltp': {
'value_processors': prcs_ltp(
ltp='ltp',
tv='tv',
spread='spread',
split='split.sum',
),
'chart_args': {
'mode': 'lines+markers',
'visible': 'legendonly',
'line_color': 'black',
'marker': {
'colorscale': [
[0, 'rgb(255,0,0)'],
[1, 'rgb(0,255,0)']
],
'cmid': 0,
}
},
},
'split': {
'chart': 'Bar',
'chart_args': {
'marker': { # default plotly colours go white, so use a green to red scale
'colorscale': [
[0, 'rgb(250,50,50)'],
[1, 'rgb(50,250,50)']
],
'cmid': 0, # with grey 0 scale
},
'opacity': tv_opacity,
'width': bar_width_ms, # 1 seconds width of bars
'offset': 0, # end of bar to be aligned with timestamp
},
'trace_args': {
'secondary_y': True
},
'value_processors': prcs_tvbar('tv', bar_width_ms),
},
'split.sum': {
'chart_args': {
'visible': 'legendonly',
},
'trace_args': {
'secondary_y': True
},
},
'split.tot': {
# 'trace_args': {
# 'secondary_y': True
# },
'ignore': True
},
'ltp.smp.avg': {
'chart_args': _plot_colorscale(
color_0='rgb(255,255,0)',
color_1='rgb(0,0,255)' # yellow to blue scale
),
'value_processors': [{
'name': 'prc_ftrstodf',
'kwargs': {
'ftr_keys': {
'y': 'ltp.smp.avg',
'text': 'split.sum',
},
},
}, {
'name': 'prc_dffillna'
}, {
'name': 'prc_dfcp',
'kwargs': {
'col_src': 'text',
'col_out': 'marker_color'
}
}, {
'name': 'prc_dffmtstr',
'kwargs': {
'df_col': 'text',
'fmt_spec': 'Book split: £{0:.2f}'
}
}, {
'name': 'prc_dftodict',
}],
'rename': 'ltp smoothed'
},
'bck.smp.avg': {
# use red to green scale
'chart_args': _plot_colorscale(
color_0='rgb(255,0,0)',
color_1='rgb(0,255,0)',
),
'value_processors': smooth_value_processors(
ftr_src='bck.smp.avg',
ftr_tks='bck.tck.smp.avg',
ftr_cmp='bck.tck.smp.avg.cmp',
ftr_dif='bck.tck.mdf',
),
'rename': 'back smoothed'
},
'lay.smp.avg': {
# use red to green scale
'chart_args': _plot_colorscale(
color_0='rgb(255,0,0)',
color_1='rgb(0,255,0)',
),
'value_processors': smooth_value_processors(
ftr_src='lay.smp.avg',
ftr_tks='lay.tck.smp.avg',
ftr_cmp='lay.tck.smp.avg.cmp',
ftr_dif='lay.tck.mdf',
),
'rename': 'lay smoothed'
},
}
| [
"myutils.registrar.Registrar",
"yaml.dump",
"os.path.expandvars",
"json.dumps",
"os.path.join",
"yaml.load",
"myutils.dictionaries.validate_config",
"os.path.splitext",
"os.path.isdir",
"os.walk"
] | [((222, 233), 'myutils.registrar.Registrar', 'Registrar', ([], {}), '()\n', (231, 233), False, 'from myutils.registrar import Registrar\n'), ((249, 260), 'myutils.registrar.Registrar', 'Registrar', ([], {}), '()\n', (258, 260), False, 'from myutils.registrar import Registrar\n'), ((619, 643), 'os.path.expandvars', 'path.expandvars', (['cfg_dir'], {}), '(cfg_dir)\n', (634, 643), False, 'from os import path\n'), ((660, 685), 'os.path.isdir', 'path.isdir', (['self._cfg_dir'], {}), '(self._cfg_dir)\n', (670, 685), False, 'from os import path\n'), ((824, 848), 'os.path.expandvars', 'path.expandvars', (['out_dir'], {}), '(out_dir)\n', (839, 848), False, 'from os import path\n'), ((865, 890), 'os.path.isdir', 'path.isdir', (['self._out_dir'], {}), '(self._out_dir)\n', (875, 890), False, 'from os import path\n'), ((1063, 1085), 'os.walk', 'os.walk', (['self._cfg_dir'], {}), '(self._cfg_dir)\n', (1070, 1085), False, 'import os, yaml\n'), ((1135, 1163), 'os.path.join', 'path.join', (['self._cfg_dir', 'fn'], {}), '(self._cfg_dir, fn)\n', (1144, 1163), False, 'from os import path\n'), ((1258, 1290), 'yaml.load', 'yaml.load', (['data', 'yaml.FullLoader'], {}), '(data, yaml.FullLoader)\n', (1267, 1290), False, 'import os, yaml\n'), ((1303, 1359), 'myutils.dictionaries.validate_config', 'dictionaries.validate_config', (['file_cfg', 'self.CONFIG_SPEC'], {}), '(file_cfg, self.CONFIG_SPEC)\n', (1331, 1359), False, 'from myutils import dictionaries\n'), ((1516, 1544), 'os.path.join', 'path.join', (['self._out_dir', 'fn'], {}), '(self._out_dir, fn)\n', (1525, 1544), False, 'from os import path\n'), ((1609, 1644), 'yaml.dump', 'yaml.dump', (['ftr_cfg'], {'sort_keys': '(False)'}), '(ftr_cfg, sort_keys=False)\n', (1618, 1644), False, 'import os, yaml\n'), ((1671, 1691), 'os.path.splitext', 'path.splitext', (['p_out'], {}), '(p_out)\n', (1684, 1691), False, 'from os import path\n'), ((1774, 1820), 'json.dumps', 'json.dumps', (['ftr_cfg'], {'indent': '(2)', 'sort_keys': '(False)'}), '(ftr_cfg, indent=2, sort_keys=False)\n', (1784, 1820), False, 'import json\n')] |
from di.container import Container
from di.dependant import Dependant, Injectable
from di.executors import SyncExecutor
class UsersRepo(Injectable, scope="app"):
pass
def endpoint(repo: UsersRepo) -> UsersRepo:
return repo
def framework():
container = Container()
solved = container.solve(
Dependant(endpoint, scope="request"), scopes=["app", "request"]
)
executor = SyncExecutor()
with container.enter_scope("app") as app_state:
with container.enter_scope("request", state=app_state) as request_state:
repo1 = container.execute_sync(
solved, executor=executor, state=request_state
)
with container.enter_scope("request"):
repo2 = container.execute_sync(
solved, executor=executor, state=request_state
)
assert repo1 is repo2
| [
"di.dependant.Dependant",
"di.container.Container",
"di.executors.SyncExecutor"
] | [((270, 281), 'di.container.Container', 'Container', ([], {}), '()\n', (279, 281), False, 'from di.container import Container\n'), ((405, 419), 'di.executors.SyncExecutor', 'SyncExecutor', ([], {}), '()\n', (417, 419), False, 'from di.executors import SyncExecutor\n'), ((320, 356), 'di.dependant.Dependant', 'Dependant', (['endpoint'], {'scope': '"""request"""'}), "(endpoint, scope='request')\n", (329, 356), False, 'from di.dependant import Dependant, Injectable\n')] |
import cv2
import numpy as np
def class_name(classid):
id_dict = {1:'Scratch', 2:'Dent', 3:'Shatter', 4:'Dislocation'}
return id_dict[classid]
def damage_cost(classid):
# cost_dict = {1: [800, 1400], 2:[1200, 3000],3:19000, 4:17000}
cost_dict = {1: 900, 2:1600, 3:19000, 4:17000}
return cost_dict[classid]
def area_ratio(image, roi, mask):
y1, x1, y2, x2 = tuple(roi)
crop_mask = mask[y1:y1+(y2-y1),x1:x1+(x2-x1)].copy()
pixels = cv2.countNonZero(np.float32(crop_mask))
image_area = image.shape[0] * image.shape[1]
area_ratio = 1 + (pixels / image_area)
return area_ratio
def costEstimate(image, rois, masks, classids):
cost_id_dict = {
"Shatter": {"Count": 0, "Cost": 0},
"Scratch": {"Count": 0, "Cost": 0},
"Dent": {"Count": 0, "Cost": 0},
"Dislocation": {"Count": 0, "Cost": 0}
}
total = 0
count = int()
cost_init = int()
for index in range(rois.shape[0]):
name = class_name(classids[index])
cost = damage_cost(classids[index])
ratio = area_ratio(image, rois[index], masks[: ,: ,index])
total = total + round(cost * ratio,2)
# unique_id = str()
# for roi in rois[index]:
# unique_id = unique_id + str(roi)
if name is 'Scratch':
count = cost_id_dict[name]['Count'] + 1
cost_init = cost_id_dict[name]['Cost'] + round(cost * ratio,2)
cost_id_dict[name]['Count'] = count
cost_id_dict[name]['Cost'] = cost_init
# cost_id_dict[name] = "Range: Rs." + str(round(cost[0] * ratio,3)) + ' - Rs.' + str(round(cost[1] * ratio, 3))
elif name is 'Dent':
count = cost_id_dict[name]['Count'] + 1
cost_init = cost_id_dict[name]['Cost'] + round(cost * ratio,2)
cost_id_dict[name]['Count'] = count
cost_id_dict[name]['Cost'] = cost_init
# cost_id_dict[name] = "Range: Rs." + str(cost[0] * ratio) + ' - Rs.' + str(cost[1] * ratio)
elif name is 'Shatter':
count = cost_id_dict[name]['Count'] + 1
cost_init = cost_id_dict[name]['Cost'] + round(cost * ratio,2)
cost_id_dict[name]['Count'] = count
cost_id_dict[name]['Cost'] = cost_init
# cost_id_dict[name] = "Cost: Rs." + str(cost)
else:
count = cost_id_dict[name]['Count'] + 1
cost_init = cost_id_dict[name]['Cost'] + round(cost * ratio,2)
cost_id_dict[name]['Count'] = count
cost_id_dict[name]['Cost'] = cost_init
# cost_id_dict[name] = "Cost: Rs." + str(cost)
for name, values in cost_id_dict.copy().items():
if values['Count'] == 0:
cost_id_dict.pop(name)
return total, cost_id_dict | [
"numpy.float32"
] | [((500, 521), 'numpy.float32', 'np.float32', (['crop_mask'], {}), '(crop_mask)\n', (510, 521), True, 'import numpy as np\n')] |
from re import findall
from json import loads
from ethereum import utils
opening_brackets = ["(", "{", "[", "<"]
closing_brackets = [")", "}", "]", ">"]
newlines_reg = r'(\r\n|\r|\n)'
newlines = ['\r\n', '\r', '\n']
def count_lines(text):
if text == "":
return 0
return 1 + len(findall(newlines_reg, text))
def get_pos_line_col(text):
return len(text), len(findall(newlines_reg, text)), min(map(lambda nwl: text[::-1].index(nwl) if nwl in text else len(text), newlines))
def get_hashes_from_abi(abi):
hashes = []
for f_interface in abi:
if "name" in f_interface:
signature = f_interface['name']
signature += "(" + ",".join([param['type'] for param in f_interface['inputs']]) + ")"
hashes.append(utils.sha3(signature)[:4].hex())
return hashes
def get_transaction_functions(contract):
functions = contract.functions
abi_hashes = get_hashes_from_abi(loads(contract.abi))
constructor_function = False
default_function = False
f_hashes = []
t_functions = []
for func in functions:
if func.isConstructor:
if not constructor_function:
constructor_function = True
t_functions.append(func)
elif len(func.name) <= 0:
if not default_function:
default_function = True
t_functions.append(func)
elif func.hash not in f_hashes:
f_hashes.append(func.hash)
if not func.constant and func.hash in abi_hashes:
t_functions.append(func)
return t_functions
def find_first_uncommented_str(code, search_str):
while len(code)>0:
line_comment, block_comment = len(code), len(code)
if "//" in code:
line_comment = code.index("//")
if "/*" in code:
line_comment = code.index("/*")
if search_str not in code:
return -1
index_search_str = code.index(search_str)
if index_search_str < line_comment and index_search_str < block_comment:
return index_search_str
if line_comment < block_comment:
code = code[line_comment:]
if "\n" in code:
code = code[code.index("\n")+1:]
else:
code = ""
elif block_comment < line_comment:
code = code[block_comment:]
code = code[code.index("*/")]
def find_matching_closed_bracket(filedata, bracket_idx):
nwl = get_newlinetype(filedata)
bracket = filedata[bracket_idx]
opening_bracket = filedata[bracket_idx] in opening_brackets
if opening_bracket:
to_search = filedata[bracket_idx:]
else:
to_search = filedata[:(bracket_idx + 1)][::-1]
matching_bracket = closing_brackets[opening_brackets.index(bracket)] if opening_bracket \
else closing_brackets[opening_brackets.index(bracket)]
idx = 0
counter = 0
while True:
if opening_bracket and to_search[idx:].startswith("//"):
idx = idx + to_search[idx:].index(nwl) + len(nwl)
if not opening_bracket and to_search[idx].startswith(nwl[::-1]):
inc_idx = 0
current_inv_line = to_search[(idx + len(nwl)):]
if nwl[::-1] in current_inv_line:
current_inv_line = current_inv_line[:current_inv_line.index(nwl[::-1])]
if "//" in current_inv_line:
inc_idx += len(nwl) + current_inv_line.index(nwl[::-1]) + len("//")
idx += inc_idx
if to_search[idx] == bracket:
counter += 1
elif to_search[idx] == matching_bracket:
counter -= 1
if counter <= 0:
break
idx += 1
return bracket_idx + (idx if opening_bracket else -idx)
def get_newlinetype(text):
nwl = "\n"
for newline in newlines:
if newline in text:
nwl = newline
break
return nwl
def current_line_contains(string, sub):
nwl = get_newlinetype(string)
string = string[(string.rfind(nwl) + len(nwl)):]
return sub in string
def is_commented_out(code, pos):
return current_line_contains(code[:pos], "//")
| [
"re.findall",
"json.loads",
"ethereum.utils.sha3"
] | [((938, 957), 'json.loads', 'loads', (['contract.abi'], {}), '(contract.abi)\n', (943, 957), False, 'from json import loads\n'), ((297, 324), 're.findall', 'findall', (['newlines_reg', 'text'], {}), '(newlines_reg, text)\n', (304, 324), False, 'from re import findall\n'), ((381, 408), 're.findall', 'findall', (['newlines_reg', 'text'], {}), '(newlines_reg, text)\n', (388, 408), False, 'from re import findall\n'), ((772, 793), 'ethereum.utils.sha3', 'utils.sha3', (['signature'], {}), '(signature)\n', (782, 793), False, 'from ethereum import utils\n')] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from nose.tools import eq_, ok_
from werkzeug.test import Client
from werkzeug.wrappers import BaseResponse
from clastic import Application
from clastic.render import JSONRender, JSONPRender, render_basic
from common import (hello_world_str,
hello_world_html,
hello_world_ctx,
complex_context)
import json
_CUR_DIR = os.path.dirname(__file__)
def test_json_render(render_json=None):
if render_json is None:
render_json = JSONRender(dev_mode=True)
app = Application([('/', hello_world_ctx, render_json),
('/<name>/', hello_world_ctx, render_json),
('/beta/<name>/', complex_context, render_json)])
yield ok_, callable(app.routes[0]._execute)
yield ok_, callable(app.routes[0]._render)
c = Client(app, BaseResponse)
resp = c.get('/')
yield eq_, resp.status_code, 200
resp_data = json.loads(resp.data)
yield eq_, resp_data['name'], 'world'
resp = c.get('/Kurt/')
yield eq_, resp.status_code, 200
resp_data = json.loads(resp.data)
yield eq_, resp_data['name'], 'Kurt'
resp = c.get('/beta/Rajkumar/')
yield eq_, resp.status_code, 200
resp_data = json.loads(resp.data)
yield eq_, resp_data['name'], 'Rajkumar'
yield ok_, resp_data['date']
yield ok_, len(resp_data) > 4
def test_jsonp_render(render_json=None):
if render_json is None:
render_json = JSONPRender(qp_name='callback', dev_mode=True)
app = Application([('/', hello_world_ctx, render_json),
('/<name>/', hello_world_ctx, render_json),
('/beta/<name>/', complex_context, render_json)])
c = Client(app, BaseResponse)
resp = c.get('/?callback=test_callback')
yield eq_, resp.status_code, 200
yield ok_, resp.data.startswith('test_callback')
yield ok_, 'world' in resp.data
resp = c.get('/?callback=test_callback')
yield eq_, resp.status_code, 200
yield ok_, resp.data.startswith('test_callback')
yield ok_, 'world' in resp.data
#def test_default_json_render():
# from clastic.render import render_json
# for t in test_json_render(render_json):
# yield t
def test_default_render():
app = Application([('/', hello_world_ctx, render_basic),
('/<name>/', hello_world_ctx, render_basic),
('/text/<name>/', hello_world_str, render_basic),
('/html/<name>/', hello_world_html, render_basic),
('/beta/<name>/', complex_context, render_basic)])
yield ok_, callable(app.routes[0]._execute)
yield ok_, callable(app.routes[0]._render)
c = Client(app, BaseResponse)
resp = c.get('/') # test simple json with endpoint default
yield eq_, resp.status_code, 200
resp_data = json.loads(resp.data)
yield eq_, resp_data['name'], 'world'
resp = c.get('/Kurt/') # test simple json with url param
yield eq_, resp.status_code, 200
resp_data = json.loads(resp.data)
yield eq_, resp_data['name'], 'Kurt'
resp = c.get('/beta/Rajkumar/') # test fancy json
yield eq_, resp.status_code, 200
resp_data = json.loads(resp.data)
yield eq_, resp_data['name'], 'Rajkumar'
yield ok_, resp_data['date']
yield ok_, len(resp_data) > 4
resp = c.get('/text/Noam/') # test text
yield eq_, resp.status_code, 200
yield eq_, resp.data, 'Hello, Noam!'
resp = c.get('/html/Asia/') # test basic html
yield eq_, resp.status_code, 200
yield ok_, 'text/html' in resp.headers['Content-Type']
| [
"json.loads",
"os.path.dirname",
"clastic.render.JSONPRender",
"werkzeug.test.Client",
"clastic.render.JSONRender",
"clastic.Application"
] | [((457, 482), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (472, 482), False, 'import os\n'), ((611, 762), 'clastic.Application', 'Application', (["[('/', hello_world_ctx, render_json), ('/<name>/', hello_world_ctx,\n render_json), ('/beta/<name>/', complex_context, render_json)]"], {}), "([('/', hello_world_ctx, render_json), ('/<name>/',\n hello_world_ctx, render_json), ('/beta/<name>/', complex_context,\n render_json)])\n", (622, 762), False, 'from clastic import Application\n'), ((905, 930), 'werkzeug.test.Client', 'Client', (['app', 'BaseResponse'], {}), '(app, BaseResponse)\n', (911, 930), False, 'from werkzeug.test import Client\n'), ((1007, 1028), 'json.loads', 'json.loads', (['resp.data'], {}), '(resp.data)\n', (1017, 1028), False, 'import json\n'), ((1152, 1173), 'json.loads', 'json.loads', (['resp.data'], {}), '(resp.data)\n', (1162, 1173), False, 'import json\n'), ((1305, 1326), 'json.loads', 'json.loads', (['resp.data'], {}), '(resp.data)\n', (1315, 1326), False, 'import json\n'), ((1589, 1740), 'clastic.Application', 'Application', (["[('/', hello_world_ctx, render_json), ('/<name>/', hello_world_ctx,\n render_json), ('/beta/<name>/', complex_context, render_json)]"], {}), "([('/', hello_world_ctx, render_json), ('/<name>/',\n hello_world_ctx, render_json), ('/beta/<name>/', complex_context,\n render_json)])\n", (1600, 1740), False, 'from clastic import Application\n'), ((1788, 1813), 'werkzeug.test.Client', 'Client', (['app', 'BaseResponse'], {}), '(app, BaseResponse)\n', (1794, 1813), False, 'from werkzeug.test import Client\n'), ((2337, 2597), 'clastic.Application', 'Application', (["[('/', hello_world_ctx, render_basic), ('/<name>/', hello_world_ctx,\n render_basic), ('/text/<name>/', hello_world_str, render_basic), (\n '/html/<name>/', hello_world_html, render_basic), ('/beta/<name>/',\n complex_context, render_basic)]"], {}), "([('/', hello_world_ctx, render_basic), ('/<name>/',\n hello_world_ctx, render_basic), ('/text/<name>/', hello_world_str,\n render_basic), ('/html/<name>/', hello_world_html, render_basic), (\n '/beta/<name>/', complex_context, render_basic)])\n", (2348, 2597), False, 'from clastic import Application\n'), ((2781, 2806), 'werkzeug.test.Client', 'Client', (['app', 'BaseResponse'], {}), '(app, BaseResponse)\n', (2787, 2806), False, 'from werkzeug.test import Client\n'), ((2925, 2946), 'json.loads', 'json.loads', (['resp.data'], {}), '(resp.data)\n', (2935, 2946), False, 'import json\n'), ((3105, 3126), 'json.loads', 'json.loads', (['resp.data'], {}), '(resp.data)\n', (3115, 3126), False, 'import json\n'), ((3277, 3298), 'json.loads', 'json.loads', (['resp.data'], {}), '(resp.data)\n', (3287, 3298), False, 'import json\n'), ((575, 600), 'clastic.render.JSONRender', 'JSONRender', ([], {'dev_mode': '(True)'}), '(dev_mode=True)\n', (585, 600), False, 'from clastic.render import JSONRender, JSONPRender, render_basic\n'), ((1532, 1578), 'clastic.render.JSONPRender', 'JSONPRender', ([], {'qp_name': '"""callback"""', 'dev_mode': '(True)'}), "(qp_name='callback', dev_mode=True)\n", (1543, 1578), False, 'from clastic.render import JSONRender, JSONPRender, render_basic\n')] |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\server_commands\inventory_commands.py
# Compiled at: 2020-07-22 20:32:56
# Size of source mod 2**32: 24662 bytes
from bucks.bucks_utils import BucksUtils
from collections import Counter
from distributor.ops import SendUIMessage
from distributor.system import Distributor
from google.protobuf import text_format
from protocolbuffers import Consts_pb2
from protocolbuffers import SimObjectAttributes_pb2
from protocolbuffers import UI_pb2
from objects.components.inventory_enums import StackScheme
from objects.system import create_object
from server_commands.argument_helpers import OptionalTargetParam, get_optional_target, RequiredTargetParam, TunableInstanceParam
from sims4.commands import CommandType
import services, sims4.commands
@sims4.commands.Command('inventory.create_in_hidden')
def create_object_in_hidden_inventory(definition_id: int, _connection=None):
lot = services.active_lot()
if lot is not None:
return lot.create_object_in_hidden_inventory(definition_id) is not None
return False
@sims4.commands.Command('inventory.list_hidden')
def list_objects_in_hidden_inventory(_connection=None):
lot = services.active_lot()
if lot is not None:
hidden_inventory = lot.get_hidden_inventory()
if hidden_inventory is not None:
for obj in hidden_inventory:
sims4.commands.output(str(obj), _connection)
return True
return False
@sims4.commands.Command('qa.objects.inventory.list', command_type=(sims4.commands.CommandType.Automation))
def automation_list_active_situations(inventory_obj_id: int=None, _connection=None):
manager = services.object_manager()
if inventory_obj_id not in manager:
sims4.commands.automation_output('ObjectInventory; Status:NoObject, ObjectId:{}'.format(inventory_obj_id), _connection)
return
else:
inventory_obj = manager.get(inventory_obj_id)
if inventory_obj.inventory_component != None:
sims4.commands.automation_output('ObjectInventory; Status:Begin, ObjectId:{}'.format(inventory_obj_id), _connection)
for obj in inventory_obj.inventory_component:
sims4.commands.automation_output('ObjectInventory; Status:Data, Id:{}, DefId:{}'.format(obj.id, obj.definition.id), _connection)
sims4.commands.automation_output('ObjectInventory; Status:End', _connection)
else:
sims4.commands.automation_output('ObjectInventory; Status:NoInventory, ObjectId:{}'.format(inventory_obj_id), _connection)
@sims4.commands.Command('inventory.purge', command_type=(sims4.commands.CommandType.Cheat))
def purge_sim_inventory(opt_target: OptionalTargetParam=None, _connection=None):
target = get_optional_target(opt_target, _connection)
if target is not None:
target.inventory_component.purge_inventory()
return False
@sims4.commands.Command('inventory.purchase_picker_response', command_type=(sims4.commands.CommandType.Live))
def purchase_picker_response(inventory_target: RequiredTargetParam, mailman_purchase: bool=False, *def_ids_and_amounts: int, _connection=None):
total_price = 0
current_purchased = 0
objects_to_buy = []
definition_manager = services.definition_manager()
for def_id, amount in zip(def_ids_and_amounts[::2], def_ids_and_amounts[1::2]):
definition = definition_manager.get(def_id)
if definition is None:
sims4.commands.output('inventory.purchase_picker_response: Definition not found with id {}'.format(def_id), _connection)
return False
purchase_price = definition.price * amount
total_price += purchase_price
objects_to_buy.append((definition, amount))
client = services.client_manager().get(_connection)
if client is None:
sims4.commands.output('inventory.purchase_picker_response: No client found to make purchase.', _connection)
return False
household = client.household
if household.funds.money < total_price:
sims4.commands.output('inventory.purchase_picker_response: Insufficient funds for household to purchase items.', _connection)
return False
if mailman_purchase:
inventory = services.active_lot().get_hidden_inventory()
else:
inventory_owner = inventory_target.get_target()
inventory = inventory_owner.inventory_component
if inventory is None:
sims4.commands.output('inventory.purchase_picker_response: Inventory not found for items to be purchased into.', _connection)
return False
for definition, amount in objects_to_buy:
obj = create_object(definition)
if obj is None:
sims4.commands.output('inventory.purchase_picker_response: Failed to create object with definition {}.'.format(definition), _connection)
continue
obj.set_stack_count(amount)
if not inventory.player_try_add_object(obj):
sims4.commands.output('inventory.purchase_picker_response: Failed to add object into inventory: {}'.format(obj), _connection)
obj.destroy(source=inventory, cause='inventory.purchase_picker_response: Failed to add object into inventory.')
continue
obj.set_household_owner_id(household.id)
obj.try_post_bb_fixup(force_fixup=True, active_household_id=(services.active_household_id()))
purchase_price = definition.price * amount
current_purchased += purchase_price
return household.funds.try_remove(current_purchased, Consts_pb2.TELEMETRY_OBJECT_BUY)
USE_DEFINITION_PRICE = -1
@sims4.commands.Command('inventory.purchase_picker_response_by_ids', command_type=(sims4.commands.CommandType.Live))
def purchase_picker_response_by_ids(inventory_target: RequiredTargetParam, inventory_source: RequiredTargetParam, currency_type: int, mailman_purchase: bool=False, object_ids_or_definition_ids: bool=False, *ids_and_amounts_and_price: int, _connection=None):
total_price = 0
current_purchased = 0
objects_to_buy = []
definition_manager = services.definition_manager()
inventory_manager = services.inventory_manager()
for def_or_obj_id, amount, price in zip(ids_and_amounts_and_price[::3], ids_and_amounts_and_price[1::3], ids_and_amounts_and_price[2::3]):
if object_ids_or_definition_ids:
obj_or_definition = inventory_manager.get(def_or_obj_id)
else:
obj_or_definition = definition_manager.get(def_or_obj_id)
if obj_or_definition is None:
sims4.commands.output('inventory.purchase_picker_response: Object or Definition not found with id {}'.format(def_or_obj_id), _connection)
return False
if price == USE_DEFINITION_PRICE:
price = obj_or_definition.definition.price
purchase_price = price * amount
total_price += purchase_price
objects_to_buy.append((obj_or_definition, price, amount))
client = services.client_manager().get(_connection)
if client is None:
sims4.commands.output('inventory.purchase_picker_response: No client found to make purchase.', _connection)
return False
household = client.household
if household.get_currency_amount(currency_type) < total_price:
sims4.commands.output('inventory.purchase_picker_response: Insufficient funds for household to purchase items.', _connection)
return False
if mailman_purchase:
to_inventory = services.active_lot().get_hidden_inventory()
else:
to_inventory_owner = inventory_target.get_target()
to_inventory = to_inventory_owner.inventory_component
if to_inventory is None:
sims4.commands.output('inventory.purchase_picker_response: Inventory not found for items to be purchased into.', _connection)
return False
if inventory_source.target_id != 0:
from_inventory_owner = inventory_source.get_target()
from_inventory = from_inventory_owner.inventory_component
else:
from_inventory_owner = None
from_inventory = None
if object_ids_or_definition_ids:
if from_inventory is None:
sims4.commands.output('inventory.purchase_picker_response: Source Inventory not found for items to be cloned from.', _connection)
return False
inventory_manager = services.inventory_manager()
obj_purchased = dict()
for obj_or_def, price, amount in objects_to_buy:
amount_left = amount
while amount_left > 0:
if object_ids_or_definition_ids:
from_inventory.try_remove_object_by_id(obj_or_def.id, obj_or_def.stack_count())
obj = obj_or_def.clone()
from_inventory.system_add_object(obj_or_def)
else:
obj = create_object(obj_or_def)
if obj is None:
sims4.commands.output('inventory.purchase_picker_response: Failed to create object with definition {}.'.format(obj_or_def), _connection)
amount_left = 0
continue
elif obj.inventoryitem_component is None or obj.inventoryitem_component.get_stack_scheme() == StackScheme.NONE:
amount_left = amount_left - 1
else:
obj.set_stack_count(amount)
amount_left = 0
obj.set_household_owner_id(household.id)
obj.try_post_bb_fixup(force_fixup=True, active_household_id=(services.active_household_id()))
if not to_inventory.player_try_add_object(obj):
sims4.commands.output('inventory.purchase_picker_response: Failed to add object into inventory: {}'.format(obj), _connection)
obj.destroy(source=to_inventory, cause='inventory.purchase_picker_response: Failed to add object into inventory.')
continue
if obj.definition.id not in obj_purchased:
obj_purchased[obj.definition.id] = {'price':0,
'amount':0}
if obj.inventoryitem_component.get_stack_scheme() == StackScheme.NONE:
purchase_price = price
obj_purchased[obj.definition.id]['amount'] += 1
else:
purchase_price = price * amount
obj_purchased[obj.definition.id]['amount'] += amount
obj_purchased[obj.definition.id]['price'] += purchase_price
current_purchased += purchase_price
return household.try_remove_currency_amount(currency_type, current_purchased, reason=(Consts_pb2.TELEMETRY_OBJECT_BUY), obj_purchased=obj_purchased)
@sims4.commands.Command('inventory.open_ui', command_type=(sims4.commands.CommandType.Live))
def open_inventory_ui(inventory_obj: RequiredTargetParam, _connection=None):
obj = inventory_obj.get_target()
if obj is None:
sims4.commands.output('Failed to get inventory_obj: {}.'.format(inventory_obj), _connection)
return False
comp = obj.inventory_component
if comp is None:
sims4.commands.output('inventory_obj does not have an inventory component: {}.'.format(inventory_obj), _connection)
return False
comp.open_ui_panel()
return True
@sims4.commands.Command('inventory.view_update', command_type=(sims4.commands.CommandType.Live))
def inventory_view_update(obj_id: int=0, _connection=None):
obj = services.current_zone().find_object(obj_id)
if obj is not None:
obj.inventory_view_update()
return True
return False
@sims4.commands.Command('inventory.sim_inventory_sell_multiple', command_type=(sims4.commands.CommandType.Live))
def sim_inventory_sell_multiple(msg: str, _connection=None):
proto = UI_pb2.InventorySellRequest()
text_format.Merge(msg, proto)
if proto is None:
return
sim_info = services.sim_info_manager().get(proto.sim_id)
if sim_info is None:
return
inventory_component = sim_info.get_sim_instance().inventory_component
if inventory_component is None:
return
sell_value = 0
objs = []
inventory_stack_items = inventory_component.get_stack_items_map(proto.stacks)
if proto.stacks is not None:
for stack_id in proto.stacks:
stack_items = inventory_stack_items.get(stack_id, None)
if stack_items is None:
continue
for item in stack_items:
if item.non_deletable_by_user:
break
sell_value += item.current_value * item.stack_count()
objs.append(item)
if proto.items is not None:
inventory_manager = services.inventory_manager()
for item_data in proto.items:
if item_data not in inventory_component:
continue
item = inventory_manager.get(item_data.id)
if item is None:
continue
if item.non_deletable_by_user:
continue
sell_value += item.current_value * item_data.count
item.update_stack_count(-item_data.count)
if item.stack_count() < 1:
objs.append(item)
else:
inventory_component.push_inventory_item_update_msg(item)
if objs:
services.active_household().add_currency_amount(proto.currency_type, sell_value, Consts_pb2.TELEMETRY_OBJECT_SELL, sim_info)
services.get_reset_and_delete_service().trigger_batch_destroy(objs)
op = SendUIMessage('InventorySellItemsComplete')
Distributor.instance().add_op_with_no_owner(op)
@sims4.commands.Command('inventory.sim_inventory_favorite_multiple', command_type=(sims4.commands.CommandType.Live))
def sim_inventory_favorite_multiple(sim_id: int=0, is_add: bool=False, *items: int, _connection=None):
sim_info = services.sim_info_manager().get(sim_id)
if sim_info is None:
return
favorites_tracker = sim_info.favorites_tracker
if favorites_tracker is None:
return
inventory_component = sim_info.get_sim_instance().inventory_component
if inventory_component is None:
return
inventory_manager = services.inventory_manager()
for item_id in items:
item = inventory_manager.get(item_id)
if is_add:
favorites_tracker.set_favorite_stack(item)
else:
favorites_tracker.unset_favorite_stack(item)
inventory_component.push_inventory_item_stack_update_msg(item)
@sims4.commands.Command('inventory.sim_inventory_census.instanced_sims', command_type=(CommandType.Automation))
def sim_inventory_census_instances_sims(_connection=None):
output = sims4.commands.CheatOutput(_connection)
for sim in services.sim_info_manager().instanced_sims_gen():
inv_comp = sim.inventory_component
output('{:50} Inventory: {:4} Shelved: {:4}'.format(inv_comp, len(inv_comp), inv_comp.get_shelved_object_count()))
@sims4.commands.Command('inventory.sim_inventory_census.save_slot', command_type=(CommandType.Automation))
def sim_inventory_census_save_slot(_connection=None):
output = sims4.commands.CheatOutput(_connection)
definition_manager = services.definition_manager()
active_household_id = services.active_household_id()
total_objs = 0
total_objs_active_house = 0
total_objs_all_player_houses = 0
counter = Counter()
stack_counter = Counter()
for sim_info in services.sim_info_manager().values():
inventory_objs = len(sim_info.inventory_data.objects)
for obj in sim_info.inventory_data.objects:
obj_def = definition_manager.get(obj.guid)
if obj_def is not None:
counter[obj_def] += 1
save_data = SimObjectAttributes_pb2.PersistenceMaster()
save_data.ParseFromString(obj.attributes)
for data in save_data.data:
if data.type == SimObjectAttributes_pb2.PersistenceMaster.PersistableData.InventoryItemComponent:
comp_data = data.Extensions[SimObjectAttributes_pb2.PersistableInventoryItemComponent.persistable_data]
stack_counter[obj_def] += comp_data.stack_count
total_objs += inventory_objs
if sim_info.is_player_sim:
total_objs_all_player_houses += inventory_objs
if sim_info.household.id == active_household_id:
total_objs_active_house += inventory_objs
dump = []
dump.append(('#inventory objs', total_objs))
dump.append(('#inventory objs active house', total_objs_active_house))
dump.append(('#inventory objs all player houses', total_objs_all_player_houses))
for name, value in dump:
output('{:50} : {}'.format(name, value))
output('{}'.format('----------------------------------------------------------------------------------------------------'))
output('{:75} : {} / {}'.format('Obj Definition', 'PlayerFacing', 'Stacks'))
for obj_def, count in stack_counter.most_common():
output('{:75} : {:4} / {:4}'.format(obj_def, count, counter.get(obj_def)))
return dump
@sims4.commands.Command('inventory.create_and_add_object_to_inventory')
def create_and_add_object_to_inventory(to_inventory_object_id: RequiredTargetParam, definition_id: int, _connection=None):
to_inventory_owner = to_inventory_object_id.get_target()
to_inventory = to_inventory_owner.inventory_component
if to_inventory is None:
sims4.commands.output('to inventory object does not have an inventory component: {}'.format(to_inventory_owner), _connection)
return False
obj = create_object(definition_id)
if not to_inventory.player_try_add_object(obj):
sims4.commands.output('object failed to be placed into inventory: {}'.format(obj), _connection)
obj.destroy(source=to_inventory, cause='object failed to be placed into inventory')
return False
sims4.commands.output('object {} placed into inventory'.format(obj), _connection)
return True
@sims4.commands.Command('qa.object_def.valid_inventory_types', command_type=(sims4.commands.CommandType.Automation))
def qa_object_def_valid_inventory_types(object_definition: TunableInstanceParam(sims4.resources.Types.OBJECT), _connection=None):
sims4.commands.automation_output('QaObjDefValidInventoryTypes; Status:Begin', _connection)
if object_definition is None:
sims4.commands.automation_output('QaObjDefValidInventoryTypes; Status:End')
return False
if object_definition.cls._components.inventory_item is not None:
valid_inventory_types = object_definition.cls._components.inventory_item._tuned_values.valid_inventory_types
if valid_inventory_types is not None:
for inventory_type in valid_inventory_types:
sims4.commands.automation_output('QaObjDefValidInventoryTypes; Status:Data, InventoryType:{}'.format(inventory_type), _connection)
sims4.commands.automation_output('QaObjDefValidInventoryTypes; Status:End', _connection) | [
"distributor.ops.SendUIMessage",
"protocolbuffers.UI_pb2.InventorySellRequest",
"protocolbuffers.SimObjectAttributes_pb2.PersistenceMaster",
"services.sim_info_manager",
"objects.system.create_object",
"distributor.system.Distributor.instance",
"services.definition_manager",
"server_commands.argument_... | [((1099, 1120), 'services.active_lot', 'services.active_lot', ([], {}), '()\n', (1118, 1120), False, 'import services, sims4.commands\n'), ((1359, 1380), 'services.active_lot', 'services.active_lot', ([], {}), '()\n', (1378, 1380), False, 'import services, sims4.commands\n'), ((1852, 1877), 'services.object_manager', 'services.object_manager', ([], {}), '()\n', (1875, 1877), False, 'import services, sims4.commands\n'), ((2938, 2982), 'server_commands.argument_helpers.get_optional_target', 'get_optional_target', (['opt_target', '_connection'], {}), '(opt_target, _connection)\n', (2957, 2982), False, 'from server_commands.argument_helpers import OptionalTargetParam, get_optional_target, RequiredTargetParam, TunableInstanceParam\n'), ((3431, 3460), 'services.definition_manager', 'services.definition_manager', ([], {}), '()\n', (3458, 3460), False, 'import services, sims4.commands\n'), ((6257, 6286), 'services.definition_manager', 'services.definition_manager', ([], {}), '()\n', (6284, 6286), False, 'import services, sims4.commands\n'), ((6311, 6339), 'services.inventory_manager', 'services.inventory_manager', ([], {}), '()\n', (6337, 6339), False, 'import services, sims4.commands\n'), ((8517, 8545), 'services.inventory_manager', 'services.inventory_manager', ([], {}), '()\n', (8543, 8545), False, 'import services, sims4.commands\n'), ((11952, 11981), 'protocolbuffers.UI_pb2.InventorySellRequest', 'UI_pb2.InventorySellRequest', ([], {}), '()\n', (11979, 11981), False, 'from protocolbuffers import UI_pb2\n'), ((11986, 12015), 'google.protobuf.text_format.Merge', 'text_format.Merge', (['msg', 'proto'], {}), '(msg, proto)\n', (12003, 12015), False, 'from google.protobuf import text_format\n'), ((13704, 13747), 'distributor.ops.SendUIMessage', 'SendUIMessage', (['"""InventorySellItemsComplete"""'], {}), "('InventorySellItemsComplete')\n", (13717, 13747), False, 'from distributor.ops import SendUIMessage\n'), ((14366, 14394), 'services.inventory_manager', 'services.inventory_manager', ([], {}), '()\n', (14392, 14394), False, 'import services, sims4.commands\n'), ((15381, 15410), 'services.definition_manager', 'services.definition_manager', ([], {}), '()\n', (15408, 15410), False, 'import services, sims4.commands\n'), ((15437, 15467), 'services.active_household_id', 'services.active_household_id', ([], {}), '()\n', (15465, 15467), False, 'import services, sims4.commands\n'), ((15570, 15579), 'collections.Counter', 'Counter', ([], {}), '()\n', (15577, 15579), False, 'from collections import Counter\n'), ((15600, 15609), 'collections.Counter', 'Counter', ([], {}), '()\n', (15607, 15609), False, 'from collections import Counter\n'), ((17799, 17827), 'objects.system.create_object', 'create_object', (['definition_id'], {}), '(definition_id)\n', (17812, 17827), False, 'from objects.system import create_object\n'), ((4829, 4854), 'objects.system.create_object', 'create_object', (['definition'], {}), '(definition)\n', (4842, 4854), False, 'from objects.system import create_object\n'), ((12869, 12897), 'services.inventory_manager', 'services.inventory_manager', ([], {}), '()\n', (12895, 12897), False, 'import services, sims4.commands\n'), ((18377, 18427), 'server_commands.argument_helpers.TunableInstanceParam', 'TunableInstanceParam', (['sims4.resources.Types.OBJECT'], {}), '(sims4.resources.Types.OBJECT)\n', (18397, 18427), False, 'from server_commands.argument_helpers import OptionalTargetParam, get_optional_target, RequiredTargetParam, TunableInstanceParam\n'), ((3941, 3966), 'services.client_manager', 'services.client_manager', ([], {}), '()\n', (3964, 3966), False, 'import services, sims4.commands\n'), ((7145, 7170), 'services.client_manager', 'services.client_manager', ([], {}), '()\n', (7168, 7170), False, 'import services, sims4.commands\n'), ((11623, 11646), 'services.current_zone', 'services.current_zone', ([], {}), '()\n', (11644, 11646), False, 'import services, sims4.commands\n'), ((12068, 12095), 'services.sim_info_manager', 'services.sim_info_manager', ([], {}), '()\n', (12093, 12095), False, 'import services, sims4.commands\n'), ((13752, 13774), 'distributor.system.Distributor.instance', 'Distributor.instance', ([], {}), '()\n', (13772, 13774), False, 'from distributor.system import Distributor\n'), ((14037, 14064), 'services.sim_info_manager', 'services.sim_info_manager', ([], {}), '()\n', (14062, 14064), False, 'import services, sims4.commands\n'), ((14924, 14951), 'services.sim_info_manager', 'services.sim_info_manager', ([], {}), '()\n', (14949, 14951), False, 'import services, sims4.commands\n'), ((15630, 15657), 'services.sim_info_manager', 'services.sim_info_manager', ([], {}), '()\n', (15655, 15657), False, 'import services, sims4.commands\n'), ((15935, 15978), 'protocolbuffers.SimObjectAttributes_pb2.PersistenceMaster', 'SimObjectAttributes_pb2.PersistenceMaster', ([], {}), '()\n', (15976, 15978), False, 'from protocolbuffers import SimObjectAttributes_pb2\n'), ((4421, 4442), 'services.active_lot', 'services.active_lot', ([], {}), '()\n', (4440, 4442), False, 'import services, sims4.commands\n'), ((5539, 5569), 'services.active_household_id', 'services.active_household_id', ([], {}), '()\n', (5567, 5569), False, 'import services, sims4.commands\n'), ((7651, 7672), 'services.active_lot', 'services.active_lot', ([], {}), '()\n', (7670, 7672), False, 'import services, sims4.commands\n'), ((8969, 8994), 'objects.system.create_object', 'create_object', (['obj_or_def'], {}), '(obj_or_def)\n', (8982, 8994), False, 'from objects.system import create_object\n'), ((13494, 13521), 'services.active_household', 'services.active_household', ([], {}), '()\n', (13519, 13521), False, 'import services, sims4.commands\n'), ((13627, 13666), 'services.get_reset_and_delete_service', 'services.get_reset_and_delete_service', ([], {}), '()\n', (13664, 13666), False, 'import services, sims4.commands\n'), ((9667, 9697), 'services.active_household_id', 'services.active_household_id', ([], {}), '()\n', (9695, 9697), False, 'import services, sims4.commands\n')] |
"""My2h JOP Transform Utility
Usage:
loco.py convert <input.lok> <output.2lok>
loco.py (-h | --help)
loco.py --version
Options:
-h --help Show this screen.
--version Show version.
"""
import os
import logging
import configparser
from docopt import docopt
#Tady je soubor specifikace hnacího vozidla MyJOP (.lok) a hJOP (.2lok), položky v MyJOP souboru jsou:
#* adresa
#* nazev
#* majitel
#* poznamka
#* trida
#* zbytek dat ignorovat
def remove_file_if_exists(fname):
'''Remove file if exists.'''
if os.path.exists(fname):
os.remove(fname)
logging.info(f'Old output file [{fname}] was removed.')
class Loco:
def __init__(self, input_fname):
with open(input_fname, encoding='cp1250') as loco_file:
line = loco_file.readline()
loco_data = line.split(';')
self.address = loco_data[0]
self.name = loco_data[1]
self.owner = loco_data[2]
self.note = loco_data[3]
self.kind = loco_data[4]
def write_2lok(self, output_fname):
global_data = {'version': '2.0'}
data = {}
if self.name:
data['nazev'] = self.name
if self.owner:
data['majitel'] = self.owner
if '.' in self.name:
data['oznaceni'] = self.name
if self.note:
data['poznamka'] = self.note
if self.kind:
data['trida'] = self.kind
config = configparser.ConfigParser()
config.optionxform = str
config['global'] = global_data
config[self.address] = data
with open(output_fname, 'w', encoding='utf8') as configfile:
config.write(configfile, space_around_delimiters=False)
logging.info(f'Loco succesfully saved in [{output_fname}].')
def __str__(self):
data = [self.address, self.name, self.owner, self.kind, self.note]
return ';'.join(data)
__repr__ = __str__
def main():
'''Entry point'''
args = docopt(__doc__, version='0.0.1')
if args['convert']:
input_file = os.path.abspath(args['<input.lok>'])
output_file = os.path.abspath(args['<output.2lok>'])
remove_file_if_exists(output_file)
loco = Loco(input_file)
loco.write_2lok(output_file)
if __name__ == '__main__':
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)
main()
| [
"logging.basicConfig",
"os.path.exists",
"configparser.ConfigParser",
"os.path.abspath",
"logging.info",
"docopt.docopt",
"os.remove"
] | [((541, 562), 'os.path.exists', 'os.path.exists', (['fname'], {}), '(fname)\n', (555, 562), False, 'import os\n'), ((2022, 2054), 'docopt.docopt', 'docopt', (['__doc__'], {'version': '"""0.0.1"""'}), "(__doc__, version='0.0.1')\n", (2028, 2054), False, 'from docopt import docopt\n'), ((2348, 2424), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(levelname)s: %(message)s"""', 'level': 'logging.INFO'}), "(format='%(levelname)s: %(message)s', level=logging.INFO)\n", (2367, 2424), False, 'import logging\n'), ((572, 588), 'os.remove', 'os.remove', (['fname'], {}), '(fname)\n', (581, 588), False, 'import os\n'), ((597, 652), 'logging.info', 'logging.info', (['f"""Old output file [{fname}] was removed."""'], {}), "(f'Old output file [{fname}] was removed.')\n", (609, 652), False, 'import logging\n'), ((1475, 1502), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (1500, 1502), False, 'import configparser\n'), ((1758, 1818), 'logging.info', 'logging.info', (['f"""Loco succesfully saved in [{output_fname}]."""'], {}), "(f'Loco succesfully saved in [{output_fname}].')\n", (1770, 1818), False, 'import logging\n'), ((2102, 2138), 'os.path.abspath', 'os.path.abspath', (["args['<input.lok>']"], {}), "(args['<input.lok>'])\n", (2117, 2138), False, 'import os\n'), ((2161, 2199), 'os.path.abspath', 'os.path.abspath', (["args['<output.2lok>']"], {}), "(args['<output.2lok>'])\n", (2176, 2199), False, 'import os\n')] |
"""
Test utilities
"""
import os
import pytest
import factory
from django.test.html import HTMLParseError, parse_html
from cms.api import add_plugin
from cms.models import Placeholder
from cms.test_utils.testcases import CMSTestCase
from cmsplugin_blocks.utils.factories import create_image_file
def get_fake_words(length=1):
"""
Shortand to build a string of fake words depending given required count of
words.
"""
words = factory.Faker("words", nb=length)
words = words.generate()
return " ".join(words)
def get_test_source(storage, *args, **kwargs):
"""
Shortcut helper to create a dummy image, save it to the FS and get its
final path from storage.
Arguments:
storage (django.core.files.storage.Storage): Storage class to use to
save file to the file system.
Keyword Arguments:
storage (django.core.files.storage.Storage): Storage class to use to
save file to the file system. This is a required argument.
destination_dir (string): relative directory path where to save file
in storage directory. Default to "pil".
*args: Any other positionnal arguments are passed to
``create_image_file``.
**kwargs: Any other Keyword arguments are passed to
``create_image_file``.
Returns:
django.core.files.File: File object with the right final file path.
"""
destination_dir = kwargs.pop("destination_dir", "pil")
image = create_image_file(*args, **kwargs)
destination = os.path.join(destination_dir, image.name)
source_filepath = storage.save(destination, image)
# Trick to update name to final destination since File object is not
# automatically updated to the final filepath during storage.
image.name = source_filepath
return image
def assert_and_parse_html(html):
"""
Shortand to use Django HTML parsing as object to use in assert
"""
dom = parse_html(html)
return dom
class FixturesTestCaseMixin(object):
"""
Mixin to inject pytest fixtures on testcase.
These fixtures will be available for every testcase tests.
"""
@pytest.fixture(autouse=True)
def inject_fixtures(self, caplog, testsettings):
self._caplog = caplog
self._testsettings = testsettings
class CMSPluginTestCase(CMSTestCase):
"""
Enriched CMS test case object to include useful stuff about plugin
rendering.
NOTE:
The CMSTestCase mixin from DjangoCMS is making queries in its "tearDown"
method which causes database transaction errors with tests that have
already generated a database error.
A workaround is to decorate such tests with
``django.db.transaction`` (or to use it as a context manager) so that
the test has its own transaction that is rolled back before the TearDown
method sends its queries to the database.
"""
def get_practical_plugin_context(self, extra_context=None):
"""
Build a template context with dummy request object and
instanciated content renderer suitable to perform full rendering of
any plugin.
NOTE:
CMSTestCase use a dummy AnonymousUser on default behavior, you can
override it with a custom user as an ``user`` attribute on your
test case object. In most cases we should in fact define this
attribute during test to use a UserFactory instead of a global
user for every tests.
Keyword Arguments:
extra_context (dict): Dictionnary to add extra variable to context.
Default to an empty dict.
Returns:
django.template.Context: Template context filled with request
object as ``request`` item and content renderer as
``cms_content_renderer`` item.
"""
context = self.get_context()
if extra_context:
context.update(extra_context)
renderer = self.get_content_renderer(request=context["request"])
# 'cms_content_renderer' is the attempted item name from CMS rendering
# machinery
context["cms_content_renderer"] = renderer
return context
def create_basic_render(self, plugin, slot_name="test", lang="en",
copy_relations_from=None, **kwargs):
"""
A shortcut to create a basic render for a plugin
"""
# Create a dummy slot if not given in arguments
placeholder = (kwargs.pop("placeholder", None)
or Placeholder.objects.create(slot=slot_name))
# Template context
context = self.get_practical_plugin_context()
# Init plugin with some content
model_instance = add_plugin(
placeholder,
plugin,
lang,
**kwargs
)
# Copy relation when asked, this is required for plugin model with
# foreign key since djangocms machinery does not perform it with API
if copy_relations_from and hasattr(model_instance, "copy_relations"):
model_instance.copy_relations(copy_relations_from)
# Render placeholder so plugin is fully rendered in real situation
html = context["cms_content_renderer"].render_placeholder(
placeholder, context=context, language=lang
)
return placeholder, model_instance, context, html
| [
"django.test.html.parse_html",
"os.path.join",
"factory.Faker",
"pytest.fixture",
"cmsplugin_blocks.utils.factories.create_image_file",
"cms.api.add_plugin",
"cms.models.Placeholder.objects.create"
] | [((449, 482), 'factory.Faker', 'factory.Faker', (['"""words"""'], {'nb': 'length'}), "('words', nb=length)\n", (462, 482), False, 'import factory\n'), ((1498, 1532), 'cmsplugin_blocks.utils.factories.create_image_file', 'create_image_file', (['*args'], {}), '(*args, **kwargs)\n', (1515, 1532), False, 'from cmsplugin_blocks.utils.factories import create_image_file\n'), ((1552, 1593), 'os.path.join', 'os.path.join', (['destination_dir', 'image.name'], {}), '(destination_dir, image.name)\n', (1564, 1593), False, 'import os\n'), ((1968, 1984), 'django.test.html.parse_html', 'parse_html', (['html'], {}), '(html)\n', (1978, 1984), False, 'from django.test.html import HTMLParseError, parse_html\n'), ((2174, 2202), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (2188, 2202), False, 'import pytest\n'), ((4796, 4843), 'cms.api.add_plugin', 'add_plugin', (['placeholder', 'plugin', 'lang'], {}), '(placeholder, plugin, lang, **kwargs)\n', (4806, 4843), False, 'from cms.api import add_plugin\n'), ((4603, 4645), 'cms.models.Placeholder.objects.create', 'Placeholder.objects.create', ([], {'slot': 'slot_name'}), '(slot=slot_name)\n', (4629, 4645), False, 'from cms.models import Placeholder\n')] |
import os
import sys
import argparse
import configparser
import random
import string
import subprocess
from godaddypy import Client, Account
def get_parser():
parser = argparse.ArgumentParser(description='Python script to generate certificate for name.suffix.domain on Godaddy', add_help=True)
parser.add_argument("-c", "--config", help="Path to the godaddy configuration file")
parser.add_argument("-n", "--name", help="Host's name. Default - random 32-character string", default=None)
parser.add_argument("-i", "--ip", help="Host's IP address")
parser.add_argument("-s", "--suffix", help="Host's suffix", default="worker")
parser.add_argument("-d", "--domain", help="Host's domain")
parser.add_argument("-o", "--output", help="Output folder. Default - ./cert", default="./cert")
return parser
def normalize_args(args, skip_list=[]):
normalized_args = {}
for key,value in args.__dict__.items():
if key not in skip_list:
normalized_args[key] = value if not value or os.path.isabs(value) else os.path.normpath(os.path.join(os.getcwd(), value))
else:
normalized_args[key]=value
return argparse.Namespace (**normalized_args)
def main(argsl=None):
if argsl is None:
argsl = sys.argv[1:]
args,_ = get_parser().parse_known_args(argsl)
args = normalize_args(args, ["name", "ip", "suffix", "domain"])
args.name = args.name.lower() if args.name else ''.join(random.choice(string.ascii_lowercase) for i in range(32))
args.suffix = args.suffix.lower()
args.domain = args.domain.lower()
name_with_suffix = ".".join([args.name, args.suffix])
full_name = ".".join([name_with_suffix, args.domain])
print("Generating certificate for", full_name)
config = configparser.ConfigParser()
config.read(args.config)
print("Creating Godaddy client")
acc = Account(api_key=config.get('godaddy', 'key'), api_secret=config.get('godaddy', 'secret'))
cli = Client(acc)
print("Getting domains")
try:
domains = cli.get_domains()
except Exception as err:
print("Failed to get domains\n", err)
return 0
if args.domain not in domains:
print("Domain", args.domain, "not found")
return 0
print("Getting records for the domain", args.domain)
records = cli.get_records(args.domain, record_type='A', name=name_with_suffix)
print("Records found\n", records)
if not records:
print("Adding new record", name_with_suffix, "to the domain", args.domain)
try:
cli.add_records(args.domain, [{"data": args.ip, "name": name_with_suffix, "ttl": 600, "type": "A"}])
except Exception as err:
print("Failed to add record", name_with_suffix, "to the domain", args.domain, "\n", err)
elif records[0]["data"] != args.ip:
print("Updating IP for the first record that corresponds search criteria:", name_with_suffix, "in the domain", args.domain)
record = records[0]
record["data"] = args.ip
try:
cli.update_record(args.domain, record)
except Exception as err:
print("Failed to update IP for the record", name_with_suffix, "in the domain", args.domain, "\n", err)
params = [ "./acme/acme.sh", "--issue", "--home", args.output, "--days", "90", "--dns", "dns_gd", "--debug", "-d", full_name ]
env = os.environ.copy()
env.update( {"GD_Key": config.get('godaddy', 'key'), "GD_Secret": config.get('godaddy', 'secret')} )
print("Running acme.sh\n", params)
try:
subprocess.run(params, env=env)
except Exception as err:
print("Failed to run acme.sh\n", params, "\n", err)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:])) | [
"random.choice",
"configparser.ConfigParser",
"argparse.ArgumentParser",
"os.path.isabs",
"subprocess.run",
"os.environ.copy",
"os.getcwd",
"argparse.Namespace",
"godaddypy.Client"
] | [((174, 308), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Python script to generate certificate for name.suffix.domain on Godaddy"""', 'add_help': '(True)'}), "(description=\n 'Python script to generate certificate for name.suffix.domain on Godaddy',\n add_help=True)\n", (197, 308), False, 'import argparse\n'), ((1177, 1214), 'argparse.Namespace', 'argparse.Namespace', ([], {}), '(**normalized_args)\n', (1195, 1214), False, 'import argparse\n'), ((1789, 1816), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (1814, 1816), False, 'import configparser\n'), ((2126, 2137), 'godaddypy.Client', 'Client', (['acc'], {}), '(acc)\n', (2132, 2137), False, 'from godaddypy import Client, Account\n'), ((3538, 3555), 'os.environ.copy', 'os.environ.copy', ([], {}), '()\n', (3553, 3555), False, 'import os\n'), ((3717, 3748), 'subprocess.run', 'subprocess.run', (['params'], {'env': 'env'}), '(params, env=env)\n', (3731, 3748), False, 'import subprocess\n'), ((1469, 1506), 'random.choice', 'random.choice', (['string.ascii_lowercase'], {}), '(string.ascii_lowercase)\n', (1482, 1506), False, 'import random\n'), ((1036, 1056), 'os.path.isabs', 'os.path.isabs', (['value'], {}), '(value)\n', (1049, 1056), False, 'import os\n'), ((1092, 1103), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1101, 1103), False, 'import os\n')] |
#!/usr/bin/env python
# Licensed under a 3-clause BSD style license - see LICENSE.rst
#
# Imports
#
import sys
from os.path import exists
#
# setuptools' sdist command ignores MANIFEST.in
#
from distutils.command.sdist import sdist as DistutilsSdist
# from ez_setup import use_setuptools
# use_setuptools()
from setuptools import setup, find_packages
setup_keywords = dict()
#
# General settings.
#
setup_keywords['name'] = 'comparator'
setup_keywords['description'] = 'Compare large data sets on geographically separated file systems.'
setup_keywords['author'] = '<NAME>'
setup_keywords['author_email'] = '<EMAIL>'
setup_keywords['license'] = 'BSD'
setup_keywords['url'] = 'https://github.com/weaverba137/comparator'
setup_keywords['keywords'] = ['backup']
setup_keywords['classifiers'] = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Science/Research',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Topic :: System :: Archiving'
]
#
# Import this module to get __doc__ and __version__.
#
try:
from importlib import import_module
product = import_module(setup_keywords['name'])
# setup_keywords['long_description'] = product.__doc__
setup_keywords['version'] = product.__version__
except ImportError:
setup_keywords['version'] = '0.0.1.dev'
#
# Try to get the long description from the README.rst file.
#
if exists('README.rst'):
with open('README.rst') as readme:
setup_keywords['long_description'] = readme.read()
else:
setup_keywords['long_description'] = ''
setup_keywords['download_url'] = '{url}/tarball/{version}'.format(**setup_keywords)
#
# Set other keywords for the setup function. These are automated, & should
# be left alone unless you are an expert.
#
setup_keywords['provides'] = [setup_keywords['name']]
setup_keywords['python_requires'] = '>=3.4'
setup_keywords['zip_safe'] = True
setup_keywords['use_2to3'] = False
setup_keywords['packages'] = find_packages()
setup_keywords['cmdclass'] = {'sdist': DistutilsSdist}
# setup_keywords['package_data'] = {'comparator': ['data/*.json',],
# 'comparator.test': ['t/*']}
#
# Autogenerate command-line scripts.
#
setup_keywords['entry_points'] = {
'console_scripts': [
'comparator = comparator.initialize:main',
]
}
#
# Test suite
#
setup_keywords['test_suite'] = '{name}.test.{name}_test_suite'.format(**setup_keywords)
#
# Run setup command.
#
setup(**setup_keywords)
| [
"os.path.exists",
"setuptools.find_packages",
"setuptools.setup",
"importlib.import_module"
] | [((1523, 1543), 'os.path.exists', 'exists', (['"""README.rst"""'], {}), "('README.rst')\n", (1529, 1543), False, 'from os.path import exists\n'), ((2095, 2110), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (2108, 2110), False, 'from setuptools import setup, find_packages\n'), ((2596, 2619), 'setuptools.setup', 'setup', ([], {}), '(**setup_keywords)\n', (2601, 2619), False, 'from setuptools import setup, find_packages\n'), ((1243, 1280), 'importlib.import_module', 'import_module', (["setup_keywords['name']"], {}), "(setup_keywords['name'])\n", (1256, 1280), False, 'from importlib import import_module\n')] |
import os
from parsers.baseline_parser import parse_baseline_file
class AddStatus:
def __init__(self, path):
self.path = path
def __call__(self, dic):
packages = dic["packages"]
baseline_path = self.path
if os.path.isfile(baseline_path):
packageStatus = parse_baseline_file(baseline_path)
for package in dic["packages"]:
status = {}
for triplet in dic["triplets"]['built-in']:
if(package["name"]+":"+triplet in packageStatus):
status[triplet] = packageStatus[package["name"]+":"+triplet]
else:
status[triplet] = "pass"
package["status"] = status
else:
# TODO: log error missing ci.baseline.txt
pass
return dic
| [
"os.path.isfile",
"parsers.baseline_parser.parse_baseline_file"
] | [((251, 280), 'os.path.isfile', 'os.path.isfile', (['baseline_path'], {}), '(baseline_path)\n', (265, 280), False, 'import os\n'), ((310, 344), 'parsers.baseline_parser.parse_baseline_file', 'parse_baseline_file', (['baseline_path'], {}), '(baseline_path)\n', (329, 344), False, 'from parsers.baseline_parser import parse_baseline_file\n')] |
from LoopStructural.utils import LoopImportError, LoopTypeError, LoopValueError
try:
from LoopProjectFile import ProjectFile
except ImportError:
raise LoopImportError("LoopProjectFile cannot be imported")
from .process_data import ProcessInputData
import numpy as np
import pandas as pd
import networkx
from LoopStructural.utils import getLogger
logger = getLogger(__name__)
class Map2LoopProcessor(ProcessInputData):
def __init__(self,projectife,use_thickness=None):
if isinstance(projectife,ProjectFile) == False:
raise LoopTypeError("projectife must be of type ProjectFile")
self.projectife = projectife
# super().__init__(
# self.projectfile.contacts,
# self.projectfile.orientations,
# stratigraphic_order,
# thicknesses=thicknesses,
# fault_orientations=fault_orientations,
# fault_locations=fault_locations,
# fault_properties=fault_properties,
# fault_edges=list(fault_graph.edges),
# colours=dict(zip(groups['code'],groups['colour'])),
# fault_stratigraphy=None,
# intrusions=None,
# use_thickness=use_thickness,
# fault_edge_properties=fault_edge_properties
# ) | [
"LoopStructural.utils.LoopImportError",
"LoopStructural.utils.getLogger",
"LoopStructural.utils.LoopTypeError"
] | [((366, 385), 'LoopStructural.utils.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (375, 385), False, 'from LoopStructural.utils import getLogger\n'), ((159, 212), 'LoopStructural.utils.LoopImportError', 'LoopImportError', (['"""LoopProjectFile cannot be imported"""'], {}), "('LoopProjectFile cannot be imported')\n", (174, 212), False, 'from LoopStructural.utils import LoopImportError, LoopTypeError, LoopValueError\n'), ((558, 613), 'LoopStructural.utils.LoopTypeError', 'LoopTypeError', (['"""projectife must be of type ProjectFile"""'], {}), "('projectife must be of type ProjectFile')\n", (571, 613), False, 'from LoopStructural.utils import LoopImportError, LoopTypeError, LoopValueError\n')] |
from PyQt5 import QtWidgets, QtCore, QtGui
class AlbumButton(QtWidgets.QFrame):
selected = QtCore.pyqtSignal(str)
def __init__(self, image, audio):
super().__init__()
self.audio = audio
self.background_image = QtGui.QPixmap(image).scaled(100, 100,
QtCore.Qt.KeepAspectRatioByExpanding)
self.background_label = QtWidgets.QLabel(self)
self.background_label.setFixedSize(100, 100)
self.background_label.setPixmap(self.background_image)
self.setFixedSize(100, 100)
self.setCursor(QtCore.Qt.PointingHandCursor)
def mouseReleaseEvent(self, event):
"""Detect click event, which is when the mouse is
released and still hovering over the item."""
mouse = self.mapToParent(event.pos())
if self.pos().x() < mouse.x() < self.pos().x() + self.width():
if self.pos().y() < mouse.y() < self.pos().y() + self.height():
self.selected.emit(self.audio)
| [
"PyQt5.QtCore.pyqtSignal",
"PyQt5.QtWidgets.QLabel",
"PyQt5.QtGui.QPixmap"
] | [((98, 120), 'PyQt5.QtCore.pyqtSignal', 'QtCore.pyqtSignal', (['str'], {}), '(str)\n', (115, 120), False, 'from PyQt5 import QtWidgets, QtCore, QtGui\n'), ((414, 436), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['self'], {}), '(self)\n', (430, 436), False, 'from PyQt5 import QtWidgets, QtCore, QtGui\n'), ((246, 266), 'PyQt5.QtGui.QPixmap', 'QtGui.QPixmap', (['image'], {}), '(image)\n', (259, 266), False, 'from PyQt5 import QtWidgets, QtCore, QtGui\n')] |
#! /bin/python
import sys
import os
import time
import glob
import simplejson as json
import subprocess
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
import config
import utils
#---------------------------------------------------------------------------------------
def main(dirlist):
StartTime = time.clock()
content = {}
for dir in dirlist:
scripts = []
src_dir = dir['src'] + '/script'
dst_dir = dir['dst'] + '/script'
print ('src: ' + src_dir)
files = []
if os.path.exists(src_dir):
files = utils.getListOfFiles(src_dir, 'nut')
if files and not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for file in files:
d = file['dir']
n = file['file']
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
name = n
name = name.split('.', 1)[0]
in_file = d + '/' + n
out_file = dst_dir + '/' + n + 't'
if utils.newerFile(in_file, out_file):
command = config.EXE_SQ + ' -c -d -o ' + utils.getWinPath(out_file).lower() + ' ' + utils.getWinPath(in_file).lower()
#command = config.EXE_SQ + ' -c -o ' + utils.getWinPath(out_file).lower() + ' ' + utils.getWinPath(in_file).lower()
utils.spawnProcess(command)
scripts.append({'name' : name, 'file': ('script/' + n + 't')});
if scripts:
with open(dst_dir + '/content.json', 'w') as f:
json.dump(scripts, f)
content['id'] = dir['id']
content['name'] = 'script'
content['file'] = 'script/content.json'
ElapsedTime = time.clock() - StartTime
print ('\nElapsed Time: %0.3fs' % (ElapsedTime))
return content
#---------------------------------------------------------------------------------------
if __name__ == "__main__":
dirlist = config.clonedDataDir();
ret = main(dirlist)
for dir in dirlist:
dst_dir = dir['dst'] + '/'
sim = '../../' + dir['id'] + '.7z'
command = config.EXE_7Z + ' u -t7z -ms=1m ' + sim + ' *'
os.chdir(dst_dir)
utils.spawnProcess(command)
sys.exit(ret)
#---------------------------------------------------------------------------------------
| [
"os.path.exists",
"config.clonedDataDir",
"time.clock",
"utils.getListOfFiles",
"utils.newerFile",
"os.makedirs",
"os.chdir",
"simplejson.dump",
"sys.exit",
"os.path.abspath",
"utils.getWinPath",
"utils.spawnProcess"
] | [((338, 350), 'time.clock', 'time.clock', ([], {}), '()\n', (348, 350), False, 'import time\n'), ((1758, 1780), 'config.clonedDataDir', 'config.clonedDataDir', ([], {}), '()\n', (1778, 1780), False, 'import config\n'), ((2011, 2024), 'sys.exit', 'sys.exit', (['ret'], {}), '(ret)\n', (2019, 2024), False, 'import sys\n'), ((530, 553), 'os.path.exists', 'os.path.exists', (['src_dir'], {}), '(src_dir)\n', (544, 553), False, 'import os\n'), ((1535, 1547), 'time.clock', 'time.clock', ([], {}), '()\n', (1545, 1547), False, 'import time\n'), ((1960, 1977), 'os.chdir', 'os.chdir', (['dst_dir'], {}), '(dst_dir)\n', (1968, 1977), False, 'import os\n'), ((1980, 2007), 'utils.spawnProcess', 'utils.spawnProcess', (['command'], {}), '(command)\n', (1998, 2007), False, 'import utils\n'), ((152, 177), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (167, 177), False, 'import os\n'), ((567, 603), 'utils.getListOfFiles', 'utils.getListOfFiles', (['src_dir', '"""nut"""'], {}), "(src_dir, 'nut')\n", (587, 603), False, 'import utils\n'), ((937, 971), 'utils.newerFile', 'utils.newerFile', (['in_file', 'out_file'], {}), '(in_file, out_file)\n', (952, 971), False, 'import utils\n'), ((660, 680), 'os.makedirs', 'os.makedirs', (['dst_dir'], {}), '(dst_dir)\n', (671, 680), False, 'import os\n'), ((763, 786), 'os.path.exists', 'os.path.exists', (['dst_dir'], {}), '(dst_dir)\n', (777, 786), False, 'import os\n'), ((792, 812), 'os.makedirs', 'os.makedirs', (['dst_dir'], {}), '(dst_dir)\n', (803, 812), False, 'import os\n'), ((1219, 1246), 'utils.spawnProcess', 'utils.spawnProcess', (['command'], {}), '(command)\n', (1237, 1246), False, 'import utils\n'), ((1389, 1410), 'simplejson.dump', 'json.dump', (['scripts', 'f'], {}), '(scripts, f)\n', (1398, 1410), True, 'import simplejson as json\n'), ((631, 654), 'os.path.exists', 'os.path.exists', (['dst_dir'], {}), '(dst_dir)\n', (645, 654), False, 'import os\n'), ((1061, 1086), 'utils.getWinPath', 'utils.getWinPath', (['in_file'], {}), '(in_file)\n', (1077, 1086), False, 'import utils\n'), ((1018, 1044), 'utils.getWinPath', 'utils.getWinPath', (['out_file'], {}), '(out_file)\n', (1034, 1044), False, 'import utils\n')] |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Wongkar and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class Rule(Document):
def validate(self):
frappe.msgprint("after_insert")
# manufacture = frappe.get_value("Rule",{"item_code": self.item_code,"type": "Manufacture"}, "item_code")
# if manufacture:
# frappe.throw("Disconut Manufature Item "+manufacture+" sudah ada !")
# dealer = frappe.get_value("Rule",{"item_code": self.item_code,"type": "Dealer"}, "item_code")
# if dealer:
# frappe.throw("Disconut Dealer Item "+dealer+" sudah ada !")
# main_dealer = frappe.get_value("Rule",{"item_code": self.item_code,"type": "Main Dealer"}, "item_code")
# if main_dealer:
# frappe.throw("Disconut Main Dealer Item "+main_dealer+" sudah ada !")
leasing = frappe.db.get_value("Rule",{"item_code": self.item_code, "besar_dp" : self.besar_dp, "tenor": self.tenor}, "item_code")
if leasing:
frappe.throw("Disconut Item "+leasing+" sudah ada !")
if self.type == "Leasing" and self.besar_dp == "":
frappe.throw("Masukkan besad DP !")
if self.type == "Leasing" and self.tenor == "":
frappe.throw("Masukkan besad Tenor !")
# biaya_penjualan_kendaraan = frappe.get_value("Rule",{"item_code": self.item_code,"type": "Biaya Penjualan Kendaraan"}, "item_code")
# if biaya_penjualan_kendaraan:
# frappe.throw("Disconut Biaya Penjualan Kendaraan Item "+biaya_penjualan_kendaraan+" sudah ada !")
| [
"frappe.throw",
"frappe.db.get_value",
"frappe.msgprint"
] | [((265, 296), 'frappe.msgprint', 'frappe.msgprint', (['"""after_insert"""'], {}), "('after_insert')\n", (280, 296), False, 'import frappe\n'), ((897, 1021), 'frappe.db.get_value', 'frappe.db.get_value', (['"""Rule"""', "{'item_code': self.item_code, 'besar_dp': self.besar_dp, 'tenor': self.tenor}", '"""item_code"""'], {}), "('Rule', {'item_code': self.item_code, 'besar_dp': self.\n besar_dp, 'tenor': self.tenor}, 'item_code')\n", (916, 1021), False, 'import frappe\n'), ((1034, 1091), 'frappe.throw', 'frappe.throw', (["('Disconut Item ' + leasing + ' sudah ada !')"], {}), "('Disconut Item ' + leasing + ' sudah ada !')\n", (1046, 1091), False, 'import frappe\n'), ((1147, 1182), 'frappe.throw', 'frappe.throw', (['"""Masukkan besad DP !"""'], {}), "('Masukkan besad DP !')\n", (1159, 1182), False, 'import frappe\n'), ((1236, 1274), 'frappe.throw', 'frappe.throw', (['"""Masukkan besad Tenor !"""'], {}), "('Masukkan besad Tenor !')\n", (1248, 1274), False, 'import frappe\n')] |
import pandas as pd
import numpy as np
from datetime import datetime
import seaborn
import matplotlib.pyplot as plt
seaborn.set_style('darkgrid')
def __to_percent1(y, position):
y = y * 100.0
return "{:.1f}%".format(y)
def plot_roc(target, predicted_proba, title, save_png=''):
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
from sklearn.metrics import roc_curve, roc_auc_score
fpr, tpr, _ = roc_curve(target, predicted_proba)
auc_plot = roc_auc_score(target, predicted_proba)
plt.figure()
plt.plot(fpr, tpr, '-', alpha=.8, color='red', lw=1.5, label= title + ' (auc = %0.3f)' % auc_plot)
plt.plot([0, 1], [0, 1], color='navy', lw=1, linestyle='--', label='Chance')
plt.xlim([0.0, 1.01])
plt.ylim([0.0, 1.01])
plt.gca().xaxis.set_major_formatter(mtick.FuncFormatter(__to_percent1))
plt.gca().yaxis.set_major_formatter(mtick.FuncFormatter(__to_percent1))
plt.xlabel('Non default cases', fontsize=15)
plt.ylabel('Default cases', fontsize=15)
plt.title("\nROC curve - {}\n".format(title), fontsize=18)
plt.legend(loc="lower right", fontsize=15)
if save_png != '':
plt.savefig(save_png, format="png")
else:
plt.show()
def plot_grade_roc(target, grade, predicted_proba, title, save_png=''):
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
from sklearn.metrics import roc_curve, roc_auc_score
fpr, tpr, _ = roc_curve(target, predicted_proba)
fpr_plot, tpr_plot, _ = roc_curve(target, grade)
raw_auc_plot = roc_auc_score(target, predicted_proba)
new_grade_auc_plot = roc_auc_score(target, grade)
plt.figure()
plt.plot(fpr, tpr, '-', color='grey', alpha=.3, label="Raw PD (auc = %0.3f)" % raw_auc_plot)
plt.plot(fpr_plot, tpr_plot, 'o-', color='red', alpha=.8, lw=1.5, label= title + ' (auc = %0.3f)' % new_grade_auc_plot)
plt.plot([0, 1], [0, 1], color='navy', lw=1, linestyle='--', label='Chance')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.gca().xaxis.set_major_formatter(mtick.FuncFormatter(__to_percent1))
plt.gca().yaxis.set_major_formatter(mtick.FuncFormatter(__to_percent1))
plt.xlabel('Non wasted policies', fontsize=15)
plt.ylabel('Wasted policies', fontsize=15)
plt.title("\nROC curve - {}\n".format(title), fontsize=18)
plt.legend(loc="lower right", fontsize=15)
bbox_props = dict(boxstyle="circle,pad=0.3", fc="white", ec="#2769a6", lw=1)
bbox_props2 = dict(boxstyle="circle,pad=0.3", fc="white", ec="red", lw=1)
bbox_props3 = dict(boxstyle="circle,pad=0.3", fc="white", ec="blue", lw=1)
for i in range(0,6):
if i >= 1 and i <= 6:
try:
plt.text(fpr_plot[i] - .01, tpr_plot[i] + .05, "%s" % (6 - i), color="red", ha="center", va="center", size=15, bbox=bbox_props2)
except:
pass
if save_png != '':
plt.savefig(save_png, format="png")
plt.show() | [
"matplotlib.pyplot.text",
"matplotlib.pyplot.savefig",
"matplotlib.ticker.FuncFormatter",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"sklearn.metrics.roc_auc_score",
"seaborn.set_style",
"matplotlib.pyplot.figure",
"sklearn.metrics.... | [((116, 145), 'seaborn.set_style', 'seaborn.set_style', (['"""darkgrid"""'], {}), "('darkgrid')\n", (133, 145), False, 'import seaborn\n'), ((454, 488), 'sklearn.metrics.roc_curve', 'roc_curve', (['target', 'predicted_proba'], {}), '(target, predicted_proba)\n', (463, 488), False, 'from sklearn.metrics import roc_curve, roc_auc_score\n'), ((508, 546), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['target', 'predicted_proba'], {}), '(target, predicted_proba)\n', (521, 546), False, 'from sklearn.metrics import roc_curve, roc_auc_score\n'), ((563, 575), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (573, 575), True, 'import matplotlib.pyplot as plt\n'), ((584, 687), 'matplotlib.pyplot.plot', 'plt.plot', (['fpr', 'tpr', '"""-"""'], {'alpha': '(0.8)', 'color': '"""red"""', 'lw': '(1.5)', 'label': "(title + ' (auc = %0.3f)' % auc_plot)"}), "(fpr, tpr, '-', alpha=0.8, color='red', lw=1.5, label=title + \n ' (auc = %0.3f)' % auc_plot)\n", (592, 687), True, 'import matplotlib.pyplot as plt\n'), ((691, 767), 'matplotlib.pyplot.plot', 'plt.plot', (['[0, 1]', '[0, 1]'], {'color': '"""navy"""', 'lw': '(1)', 'linestyle': '"""--"""', 'label': '"""Chance"""'}), "([0, 1], [0, 1], color='navy', lw=1, linestyle='--', label='Chance')\n", (699, 767), True, 'import matplotlib.pyplot as plt\n'), ((777, 798), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0.0, 1.01]'], {}), '([0.0, 1.01])\n', (785, 798), True, 'import matplotlib.pyplot as plt\n'), ((807, 828), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0.0, 1.01]'], {}), '([0.0, 1.01])\n', (815, 828), True, 'import matplotlib.pyplot as plt\n'), ((997, 1041), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Non default cases"""'], {'fontsize': '(15)'}), "('Non default cases', fontsize=15)\n", (1007, 1041), True, 'import matplotlib.pyplot as plt\n'), ((1050, 1090), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Default cases"""'], {'fontsize': '(15)'}), "('Default cases', fontsize=15)\n", (1060, 1090), True, 'import matplotlib.pyplot as plt\n'), ((1167, 1209), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""', 'fontsize': '(15)'}), "(loc='lower right', fontsize=15)\n", (1177, 1209), True, 'import matplotlib.pyplot as plt\n'), ((1594, 1628), 'sklearn.metrics.roc_curve', 'roc_curve', (['target', 'predicted_proba'], {}), '(target, predicted_proba)\n', (1603, 1628), False, 'from sklearn.metrics import roc_curve, roc_auc_score\n'), ((1661, 1685), 'sklearn.metrics.roc_curve', 'roc_curve', (['target', 'grade'], {}), '(target, grade)\n', (1670, 1685), False, 'from sklearn.metrics import roc_curve, roc_auc_score\n'), ((1709, 1747), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['target', 'predicted_proba'], {}), '(target, predicted_proba)\n', (1722, 1747), False, 'from sklearn.metrics import roc_curve, roc_auc_score\n'), ((1777, 1805), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['target', 'grade'], {}), '(target, grade)\n', (1790, 1805), False, 'from sklearn.metrics import roc_curve, roc_auc_score\n'), ((1815, 1827), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1825, 1827), True, 'import matplotlib.pyplot as plt\n'), ((1836, 1934), 'matplotlib.pyplot.plot', 'plt.plot', (['fpr', 'tpr', '"""-"""'], {'color': '"""grey"""', 'alpha': '(0.3)', 'label': "('Raw PD (auc = %0.3f)' % raw_auc_plot)"}), "(fpr, tpr, '-', color='grey', alpha=0.3, label=\n 'Raw PD (auc = %0.3f)' % raw_auc_plot)\n", (1844, 1934), True, 'import matplotlib.pyplot as plt\n'), ((1937, 2061), 'matplotlib.pyplot.plot', 'plt.plot', (['fpr_plot', 'tpr_plot', '"""o-"""'], {'color': '"""red"""', 'alpha': '(0.8)', 'lw': '(1.5)', 'label': "(title + ' (auc = %0.3f)' % new_grade_auc_plot)"}), "(fpr_plot, tpr_plot, 'o-', color='red', alpha=0.8, lw=1.5, label=\n title + ' (auc = %0.3f)' % new_grade_auc_plot)\n", (1945, 2061), True, 'import matplotlib.pyplot as plt\n'), ((2065, 2141), 'matplotlib.pyplot.plot', 'plt.plot', (['[0, 1]', '[0, 1]'], {'color': '"""navy"""', 'lw': '(1)', 'linestyle': '"""--"""', 'label': '"""Chance"""'}), "([0, 1], [0, 1], color='navy', lw=1, linestyle='--', label='Chance')\n", (2073, 2141), True, 'import matplotlib.pyplot as plt\n'), ((2151, 2171), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (2159, 2171), True, 'import matplotlib.pyplot as plt\n'), ((2180, 2201), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0.0, 1.05]'], {}), '([0.0, 1.05])\n', (2188, 2201), True, 'import matplotlib.pyplot as plt\n'), ((2370, 2416), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Non wasted policies"""'], {'fontsize': '(15)'}), "('Non wasted policies', fontsize=15)\n", (2380, 2416), True, 'import matplotlib.pyplot as plt\n'), ((2425, 2467), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Wasted policies"""'], {'fontsize': '(15)'}), "('Wasted policies', fontsize=15)\n", (2435, 2467), True, 'import matplotlib.pyplot as plt\n'), ((2544, 2586), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""', 'fontsize': '(15)'}), "(loc='lower right', fontsize=15)\n", (2554, 2586), True, 'import matplotlib.pyplot as plt\n'), ((3269, 3279), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3277, 3279), True, 'import matplotlib.pyplot as plt\n'), ((873, 907), 'matplotlib.ticker.FuncFormatter', 'mtick.FuncFormatter', (['__to_percent1'], {}), '(__to_percent1)\n', (892, 907), True, 'import matplotlib.ticker as mtick\n'), ((953, 987), 'matplotlib.ticker.FuncFormatter', 'mtick.FuncFormatter', (['__to_percent1'], {}), '(__to_percent1)\n', (972, 987), True, 'import matplotlib.ticker as mtick\n'), ((1262, 1297), 'matplotlib.pyplot.savefig', 'plt.savefig', (['save_png'], {'format': '"""png"""'}), "(save_png, format='png')\n", (1273, 1297), True, 'import matplotlib.pyplot as plt\n'), ((1328, 1338), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1336, 1338), True, 'import matplotlib.pyplot as plt\n'), ((2246, 2280), 'matplotlib.ticker.FuncFormatter', 'mtick.FuncFormatter', (['__to_percent1'], {}), '(__to_percent1)\n', (2265, 2280), True, 'import matplotlib.ticker as mtick\n'), ((2326, 2360), 'matplotlib.ticker.FuncFormatter', 'mtick.FuncFormatter', (['__to_percent1'], {}), '(__to_percent1)\n', (2345, 2360), True, 'import matplotlib.ticker as mtick\n'), ((3225, 3260), 'matplotlib.pyplot.savefig', 'plt.savefig', (['save_png'], {'format': '"""png"""'}), "(save_png, format='png')\n", (3236, 3260), True, 'import matplotlib.pyplot as plt\n'), ((837, 846), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (844, 846), True, 'import matplotlib.pyplot as plt\n'), ((917, 926), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (924, 926), True, 'import matplotlib.pyplot as plt\n'), ((2210, 2219), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2217, 2219), True, 'import matplotlib.pyplot as plt\n'), ((2290, 2299), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2297, 2299), True, 'import matplotlib.pyplot as plt\n'), ((2975, 3110), 'matplotlib.pyplot.text', 'plt.text', (['(fpr_plot[i] - 0.01)', '(tpr_plot[i] + 0.05)', "('%s' % (6 - i))"], {'color': '"""red"""', 'ha': '"""center"""', 'va': '"""center"""', 'size': '(15)', 'bbox': 'bbox_props2'}), "(fpr_plot[i] - 0.01, tpr_plot[i] + 0.05, '%s' % (6 - i), color=\n 'red', ha='center', va='center', size=15, bbox=bbox_props2)\n", (2983, 3110), True, 'import matplotlib.pyplot as plt\n')] |
#!/usr/bin/env python
import argparse, sys, math
# covalent radius to decide a bond. bond length: r1+r2
radius = {" H": 0.25,
" N": 0.65,
" C": 0.70,
" O": 0.60,
" P": 1.00,
" S": 1.00,
"NA": 1.80,
"CL": 1.00
}
elebd_radius = {" N": 1.5,
" H": 1.0,
" C": 1.7,
" O": 1.4,
" P": 1.85,
" S": 1.85,
" X": 1.85
}
vdw_parm = {" C": (2.000, 0.150),
" H": (1.000, 0.020),
" O": (1.600, 0.200),
" N": (1.750, 0.160),
" S": (2.000, 0.200),
" P": (2.000, 0.200),
" X": (2.000, 0.173)
}
sp_orbitals = [" C", " N", " O", " P", " S"]
spd_orbitals = ["FE"]
tolerance_scale = 1.3 # (r1+r2) * this scale gives the bond upper limit, value between 1.2 to 1.5 recommended
def vector_normalize(v):
vn = ()
d = math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2])
if d < 1.0e-20:
vn = (0.0, 0.0, 0.0)
else:
vn = (v[0] / d, v[1] / d, v[2] / d)
return vn
def avv(v1, v2):
v1 = vector_normalize(v1)
v2 = vector_normalize(v2)
t = v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2];
if t > 1.0:
t = 1.0
elif t < -1.0:
t = -1.0
return math.acos(t)
def dvv(v1, v2):
dx = v1[0] - v2[0]
dy = v1[1] - v2[1]
dz = v1[2] - v2[2]
d2 = dx * dx + dy * dy + dz * dz
return math.sqrt(d2)
def vector_vminusv(v1, v2):
z = (v1[0] - v2[0], v1[1] - v2[1], v1[2] - v2[2])
return z
class Atom():
def __init__(self):
self.name = ""
self.element = ""
self.orbital = ""
self.xyz = ()
self.connect = []
return
def loadline(self, line):
self.name = line[12:16]
self.element = line[76:78]
self.xyz = (float(line[30:38]), float(line[38:46]), float(line[46:54]))
return
class Pdb2ftpl:
def __init__(self, arguments):
if len(arguments.c) != 2:
print("The conformer type ID has to be 2 characters, such as 01, 02, -1, +1, DM")
return
else:
self.confid = arguments.c
self.resname = []
self.atoms = self.file2atoms(arguments.pdbfile[0])
if len(self.resname) != 1:
print("%d residue names detected. The input pdb file can only have one residue." % len(self.resname))
sys.exit()
if arguments.d:
records = self.records_from_distance()
else:
records = self.records_from_file(arguments.pdbfile[0])
if not records:
records = self.records_from_distance()
# find connected atoms
self.connect_from_records(records)
# find hybrid type from connected atoms and bond angle
self.make_bond_orbital()
return
def file2atoms(self, fname):
atoms = []
lines = open(fname).readlines()
for line in lines:
if len(line) < 54:
continue
if line[:6] == "ATOM " or line[:6] == "HETATM":
res = line[17:20]
if res not in self.resname:
self.resname.append(res)
atom = Atom()
atom.loadline(line)
atoms.append(atom)
return atoms
def records_from_file(self, fname):
connect = {}
lines = open(fname).readlines()
for line in lines:
if len(line) < 11:
continue
if line[:6] == "CONECT":
fields = line.split()
key = int(fields[1]) - 1
value = [int(x) - 1 for x in fields[2:]]
connect[key] = value
return connect
def records_from_distance(self):
connect = {}
n = len(self.atoms)
for i in range(n - 1):
for j in range(i + 1, n):
d = dvv(self.atoms[i].xyz, self.atoms[j].xyz)
bond_distance = radius[self.atoms[i].element] + radius[self.atoms[j].element]
if d < bond_distance * tolerance_scale:
if i in connect:
connect[i].append(j)
else:
connect[i] = [j]
if j in connect:
connect[j].append(i)
else:
connect[j] = [i]
return connect
def connect_from_records(self, records):
for i in range(len(self.atoms)):
atom = self.atoms[i]
if i in records.keys():
# print(i, records[i])
atom.connect = [self.atoms[k] for k in records[i]]
else:
atom.connect = []
return
def make_bond_orbital(self):
for atom in self.atoms:
if atom.element == " H":
atom.orbital = "s"
elif atom.element in sp_orbitals: # sp, sp2, sp3
if len(atom.connect) == 4: # sp3
atom.orbital = "sp3"
elif len(atom.connect) == 3 or len(atom.connect) == 2:
# bond angle: sp if 180, sp2 if 120, sp3 if 109
v1 = vector_vminusv(atom.connect[0].xyz, atom.xyz)
v2 = vector_vminusv(atom.connect[1].xyz, atom.xyz)
alpha = avv(v1, v2) / math.pi * 180
# print(atom.connect[0].name, atom.name, atom.connect[1].name, alpha)
if 104 < alpha < 115:
atom.orbital = "sp3"
elif 115 < alpha < 150:
atom.orbital = "sp2"
elif 150 < alpha < 180.1:
atom.orbital = "sp"
else:
print("%s - %s - %s bond angle = %.3f, can not interpret" % (
atom.connect[0].name, atom.name, atom.connect[1].name, alpha))
sys.exit()
elif len(atom.connect) == 1:
# doesn't matter in the sense of geometry, but O on CH3-(CO)-CH3 is sp2 instead of sp3.
atom.orbital = "sp3"
elif len(atom.connect) == 0:
atom.orbital = "ion"
else:
atom.orbital = "udf"
return
def print_conflist(self):
print("# Conformer definition")
if self.confid == "BK":
print("CONFLIST, %s: %s%s" % (self.resname[0], self.resname[0], self.confid))
else:
print("CONFLIST, %s: %sBK, %s%s" % (self.resname[0], self.resname[0], self.resname[0], self.confid))
def print_connect(self):
print("# ATOM name and bonds")
for atom in self.atoms:
connected_atoms = ",".join(["\"%s\"" % x.name for x in atom.connect])
print("CONNECT, \"%s\", %s%s: %4s, %s" % (atom.name, self.resname[0], self.confid, atom.orbital, connected_atoms))
def print_charge(self):
print("# ATOM charges")
for atom in self.atoms:
print("CHARGE, %s%s, \"%s\": to_be_filled" % (self.resname[0], self.confid, atom.name))
def print_radius(self):
print("# Atom radius, dielelctric boundary radius, VDW radius, and energy well depth")
for atom in self.atoms:
if atom.element in elebd_radius:
rbd = elebd_radius[atom.element]
else:
rbd = elebd_radius[" X"]
if atom.element in vdw_parm:
rvdw, well = vdw_parm[atom.element]
else:
rvdw, well = vdw_parm[" X"]
print("RADIUS, %s%s, \"%s\": %6.3f, %6.3f, %6.3f" % (self.resname[0], self.confid, atom.name, rbd, rvdw, well))
def print_conformer(self):
print("# Conformer parameters that appear in head3.lst: ne, Em0, nH, pKa0, rxn")
print("CONFORMER, %s%s: Em0=0.0, pKa0=0.00, ne=0, nH=0, rxn02= 0, rxn04= 0, rxn08= 0" % (self.resname[0], self.confid))
if __name__ == "__main__":
# Get the command arguments
helpmsg = "Create a ftpl template file from a cofactor PDB file. The atoms in the input files are considered as one molecule."
parser = argparse.ArgumentParser(description=helpmsg)
parser.add_argument("-d", default=False, help="Ignore CONNECT, use distance to determine bond", action="store_true")
parser.add_argument("-c", metavar="conformer type", default="01", help="Specify a 2-character conformer type ID, default 01")
parser.add_argument("pdbfile", metavar="pdbfile", nargs=1)
args = parser.parse_args()
ftpl = Pdb2ftpl(args)
ftpl.print_conflist()
print()
ftpl.print_connect()
print()
ftpl.print_charge()
print()
ftpl.print_radius()
print()
ftpl.print_conformer() | [
"sys.exit",
"math.sqrt",
"argparse.ArgumentParser",
"math.acos"
] | [((966, 1016), 'math.sqrt', 'math.sqrt', (['(v[0] * v[0] + v[1] * v[1] + v[2] * v[2])'], {}), '(v[0] * v[0] + v[1] * v[1] + v[2] * v[2])\n', (975, 1016), False, 'import argparse, sys, math\n'), ((1349, 1361), 'math.acos', 'math.acos', (['t'], {}), '(t)\n', (1358, 1361), False, 'import argparse, sys, math\n'), ((1498, 1511), 'math.sqrt', 'math.sqrt', (['d2'], {}), '(d2)\n', (1507, 1511), False, 'import argparse, sys, math\n'), ((8274, 8318), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'helpmsg'}), '(description=helpmsg)\n', (8297, 8318), False, 'import argparse, sys, math\n'), ((2479, 2489), 'sys.exit', 'sys.exit', ([], {}), '()\n', (2487, 2489), False, 'import argparse, sys, math\n'), ((6036, 6046), 'sys.exit', 'sys.exit', ([], {}), '()\n', (6044, 6046), False, 'import argparse, sys, math\n')] |
from WebsiteDescriptor import *
import googlemaps
from googlemaps import places
from tqdm import tqdm
import time
gmaps = googlemaps.Client(key='AIzaSyAFjRuP86SUl9EtuNOjjr12rY646RSp2Vo')
def find_station(browser, place_id: str) -> Website:
"""Finds a single station given a place_id and returns a website"""
info = places.place(gmaps, place_id)['result']
name = info['name']
address = info['formatted_address']
brand = info['name'] # TODO Create a map of station names to brands
location = info['geometry']['location']
rating = info['rating'] if 'rating' in info else 0
rating_count = info['user_ratings_total'] if 'user_ratings_total' in info else 0
url = info['url']
browser.get(url)
time.sleep(2)
for gas_type in browser.find_elements_by_css_selector('div.section-gas-prices-price'):
if gas_type.find_element_by_class_name('section-gas-prices-label').text == 'Regular':
price = gas_type.find_element_by_tag_name('span').text
if len(price) > 1:
price = float(price[1:])
else:
price = NaN
return Website(name, brand,
address, location['lat'], location['lng'],
price,
rating, rating_count)
def find_station_ids() -> list:
"""Finds a list of all the place ids of the stations around town"""
print("Collecting gas station data.")
stations = []
print('Collecting result data')
time.sleep(2)
search_result = places.places_nearby(gmaps, '41.977576,-91.666851', 160935, keyword='gas station')
iter = 1
while True:
stations += search_result['results']
if 'next_page_token' not in search_result:
break
else:
iter += 1
print("Collecting page {}".format(iter), end='\r')
token = search_result['next_page_token']
time.sleep(1)
while True:
try:
search_result = places.places_nearby(gmaps, '41.977576,-91.666851', 160935, keyword='gas station',
page_token=token)
break
except googlemaps.exceptions.ApiError as e:
continue
result = []
print("Filtering bad data")
for s in tqdm(stations):
info = places.place(gmaps, s['place_id'])['result']
if info is not None and info['name'] != '':
result.append(s['place_id'])
else:
print("Found a dud station entry, skipping")
return result
def find_stations(browser) -> list:
"""Finds all of the gas stations in the state of Iowa and returns them as a list"""
stations = find_station_ids()
print('\nScraping statistics:')
return [find_station(browser, s) for s in tqdm(stations)]
if __name__ == '__main__':
from selenium import webdriver
browser = webdriver.Firefox()
stations = find_stations(browser)
for s in stations:
print(str(s))
browser.close()
| [
"googlemaps.Client",
"tqdm.tqdm",
"selenium.webdriver.Firefox",
"time.sleep",
"googlemaps.places.places_nearby",
"googlemaps.places.place"
] | [((125, 189), 'googlemaps.Client', 'googlemaps.Client', ([], {'key': '"""AIzaSyAFjRuP86SUl9EtuNOjjr12rY646RSp2Vo"""'}), "(key='AIzaSyAFjRuP86SUl9EtuNOjjr12rY646RSp2Vo')\n", (142, 189), False, 'import googlemaps\n'), ((739, 752), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (749, 752), False, 'import time\n'), ((1524, 1537), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (1534, 1537), False, 'import time\n'), ((1558, 1645), 'googlemaps.places.places_nearby', 'places.places_nearby', (['gmaps', '"""41.977576,-91.666851"""', '(160935)'], {'keyword': '"""gas station"""'}), "(gmaps, '41.977576,-91.666851', 160935, keyword=\n 'gas station')\n", (1578, 1645), False, 'from googlemaps import places\n'), ((2378, 2392), 'tqdm.tqdm', 'tqdm', (['stations'], {}), '(stations)\n', (2382, 2392), False, 'from tqdm import tqdm\n'), ((2977, 2996), 'selenium.webdriver.Firefox', 'webdriver.Firefox', ([], {}), '()\n', (2994, 2996), False, 'from selenium import webdriver\n'), ((329, 358), 'googlemaps.places.place', 'places.place', (['gmaps', 'place_id'], {}), '(gmaps, place_id)\n', (341, 358), False, 'from googlemaps import places\n'), ((1948, 1961), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1958, 1961), False, 'import time\n'), ((2409, 2443), 'googlemaps.places.place', 'places.place', (['gmaps', "s['place_id']"], {}), "(gmaps, s['place_id'])\n", (2421, 2443), False, 'from googlemaps import places\n'), ((2882, 2896), 'tqdm.tqdm', 'tqdm', (['stations'], {}), '(stations)\n', (2886, 2896), False, 'from tqdm import tqdm\n'), ((2043, 2148), 'googlemaps.places.places_nearby', 'places.places_nearby', (['gmaps', '"""41.977576,-91.666851"""', '(160935)'], {'keyword': '"""gas station"""', 'page_token': 'token'}), "(gmaps, '41.977576,-91.666851', 160935, keyword=\n 'gas station', page_token=token)\n", (2063, 2148), False, 'from googlemaps import places\n')] |
from twisted.internet import reactor
from twisted.trial import unittest
from comet.utility import coerce_to_client_endpoint, coerce_to_server_endpoint
class coerce_to_client_endpoint_TestCase(unittest.TestCase):
HOST, PORT, DEFAULT_PORT = "test", 1234, 4321
def test_good_tcp_parse(self):
ep = coerce_to_client_endpoint(
reactor, f"tcp:{self.HOST}:{self.PORT}", self.DEFAULT_PORT
)
self.assertEqual(ep._host, self.HOST)
self.assertEqual(ep._port, self.PORT)
def test_good_unix_parse(self):
filename = "/dev/null"
ep = coerce_to_client_endpoint(reactor, f"unix:{filename}", self.DEFAULT_PORT)
self.assertEqual(ep._path, filename)
def test_missing_protocol(self):
ep = coerce_to_client_endpoint(
reactor, f"{self.HOST}:{self.PORT}", self.DEFAULT_PORT
)
self.assertEqual(ep._host, self.HOST)
self.assertEqual(ep._port, self.PORT)
def test_missing_port(self):
ep = coerce_to_client_endpoint(reactor, f"tcp:{self.HOST}", self.DEFAULT_PORT)
self.assertEqual(ep._host, self.HOST)
self.assertEqual(ep._port, self.DEFAULT_PORT)
def test_missing_both(self):
ep = coerce_to_client_endpoint(reactor, self.HOST, self.DEFAULT_PORT)
self.assertEqual(ep._host, self.HOST)
self.assertEqual(ep._port, self.DEFAULT_PORT)
def test_bad_parse(self):
self.assertRaises(
ValueError,
coerce_to_client_endpoint,
reactor,
"tcp:tcp:tcp",
self.DEFAULT_PORT,
)
class coerce_to_server_endpoint_TestCase(unittest.TestCase):
PORT = 1234
def test_good_tcp_parse(self):
ep = coerce_to_server_endpoint(reactor, f"tcp:{self.PORT}")
self.assertEqual(ep._port, self.PORT)
def test_good_unix_parse(self):
filename = "/dev/null"
ep = coerce_to_server_endpoint(reactor, f"unix:{filename}")
self.assertEqual(ep._address, filename)
def test_missing_protocol(self):
ep = coerce_to_server_endpoint(reactor, self.PORT)
self.assertEqual(ep._port, self.PORT)
def test_bad_parse(self):
self.assertRaises(ValueError, coerce_to_server_endpoint, reactor, "tcp:")
| [
"comet.utility.coerce_to_client_endpoint",
"comet.utility.coerce_to_server_endpoint"
] | [((314, 404), 'comet.utility.coerce_to_client_endpoint', 'coerce_to_client_endpoint', (['reactor', 'f"""tcp:{self.HOST}:{self.PORT}"""', 'self.DEFAULT_PORT'], {}), "(reactor, f'tcp:{self.HOST}:{self.PORT}', self.\n DEFAULT_PORT)\n", (339, 404), False, 'from comet.utility import coerce_to_client_endpoint, coerce_to_server_endpoint\n'), ((595, 668), 'comet.utility.coerce_to_client_endpoint', 'coerce_to_client_endpoint', (['reactor', 'f"""unix:{filename}"""', 'self.DEFAULT_PORT'], {}), "(reactor, f'unix:{filename}', self.DEFAULT_PORT)\n", (620, 668), False, 'from comet.utility import coerce_to_client_endpoint, coerce_to_server_endpoint\n'), ((765, 851), 'comet.utility.coerce_to_client_endpoint', 'coerce_to_client_endpoint', (['reactor', 'f"""{self.HOST}:{self.PORT}"""', 'self.DEFAULT_PORT'], {}), "(reactor, f'{self.HOST}:{self.PORT}', self.\n DEFAULT_PORT)\n", (790, 851), False, 'from comet.utility import coerce_to_client_endpoint, coerce_to_server_endpoint\n'), ((1008, 1081), 'comet.utility.coerce_to_client_endpoint', 'coerce_to_client_endpoint', (['reactor', 'f"""tcp:{self.HOST}"""', 'self.DEFAULT_PORT'], {}), "(reactor, f'tcp:{self.HOST}', self.DEFAULT_PORT)\n", (1033, 1081), False, 'from comet.utility import coerce_to_client_endpoint, coerce_to_server_endpoint\n'), ((1229, 1293), 'comet.utility.coerce_to_client_endpoint', 'coerce_to_client_endpoint', (['reactor', 'self.HOST', 'self.DEFAULT_PORT'], {}), '(reactor, self.HOST, self.DEFAULT_PORT)\n', (1254, 1293), False, 'from comet.utility import coerce_to_client_endpoint, coerce_to_server_endpoint\n'), ((1732, 1786), 'comet.utility.coerce_to_server_endpoint', 'coerce_to_server_endpoint', (['reactor', 'f"""tcp:{self.PORT}"""'], {}), "(reactor, f'tcp:{self.PORT}')\n", (1757, 1786), False, 'from comet.utility import coerce_to_client_endpoint, coerce_to_server_endpoint\n'), ((1914, 1968), 'comet.utility.coerce_to_server_endpoint', 'coerce_to_server_endpoint', (['reactor', 'f"""unix:{filename}"""'], {}), "(reactor, f'unix:{filename}')\n", (1939, 1968), False, 'from comet.utility import coerce_to_client_endpoint, coerce_to_server_endpoint\n'), ((2068, 2113), 'comet.utility.coerce_to_server_endpoint', 'coerce_to_server_endpoint', (['reactor', 'self.PORT'], {}), '(reactor, self.PORT)\n', (2093, 2113), False, 'from comet.utility import coerce_to_client_endpoint, coerce_to_server_endpoint\n')] |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.project_select, name='project_select'),
url(r'^project/add$', views.project_edit, name='project_add'),
url(r'^project/edit/(?P<edit_project_id>\d+)$', views.project_edit, name='project_edit'),
url(r'^project/del/(?P<del_project_id>\d+)$', views.project_del, name='project_del'),
url(r'^(?P<project_id>\d+)/$', views.main_page, name='main'),
url(r'^(?P<project_id>\d+)/result/del/(?P<del_result_id>\d+)/$', views.result_del, name='result_del'),
url(r'^(?P<project_id>\d+)/result/del/all/$', views.result_del_all, name='result_del_all'),
url(r'^(?P<project_id>\d+)/solver/$', views.solver_list, name='solver_list'),
url(r'^(?P<project_id>\d+)/solver/add$', views.solver_edit, name='solver_add'),
url(r'^(?P<project_id>\d+)/solver/edit/(?P<solver_id>\d+)/$', views.solver_edit, name='solver_edit'),
url(r'^(?P<project_id>\d+)/solver/del/(?P<solver_id>\d+)/$', views.solver_del, name='solver_del'),
url(r'^(?P<project_id>\d+)/analysis/1D$', views.analysis1D, name='analysis1D'),
url(r'^(?P<project_id>\d+)/analysis/2D$', views.analysis2D, name='analysis2D'),
]
| [
"django.conf.urls.url"
] | [((74, 128), 'django.conf.urls.url', 'url', (['"""^$"""', 'views.project_select'], {'name': '"""project_select"""'}), "('^$', views.project_select, name='project_select')\n", (77, 128), False, 'from django.conf.urls import url\n'), ((135, 195), 'django.conf.urls.url', 'url', (['"""^project/add$"""', 'views.project_edit'], {'name': '"""project_add"""'}), "('^project/add$', views.project_edit, name='project_add')\n", (138, 195), False, 'from django.conf.urls import url\n'), ((202, 295), 'django.conf.urls.url', 'url', (['"""^project/edit/(?P<edit_project_id>\\\\d+)$"""', 'views.project_edit'], {'name': '"""project_edit"""'}), "('^project/edit/(?P<edit_project_id>\\\\d+)$', views.project_edit, name=\n 'project_edit')\n", (205, 295), False, 'from django.conf.urls import url\n'), ((296, 385), 'django.conf.urls.url', 'url', (['"""^project/del/(?P<del_project_id>\\\\d+)$"""', 'views.project_del'], {'name': '"""project_del"""'}), "('^project/del/(?P<del_project_id>\\\\d+)$', views.project_del, name=\n 'project_del')\n", (299, 385), False, 'from django.conf.urls import url\n'), ((386, 446), 'django.conf.urls.url', 'url', (['"""^(?P<project_id>\\\\d+)/$"""', 'views.main_page'], {'name': '"""main"""'}), "('^(?P<project_id>\\\\d+)/$', views.main_page, name='main')\n", (389, 446), False, 'from django.conf.urls import url\n'), ((452, 559), 'django.conf.urls.url', 'url', (['"""^(?P<project_id>\\\\d+)/result/del/(?P<del_result_id>\\\\d+)/$"""', 'views.result_del'], {'name': '"""result_del"""'}), "('^(?P<project_id>\\\\d+)/result/del/(?P<del_result_id>\\\\d+)/$', views.\n result_del, name='result_del')\n", (455, 559), False, 'from django.conf.urls import url\n'), ((559, 654), 'django.conf.urls.url', 'url', (['"""^(?P<project_id>\\\\d+)/result/del/all/$"""', 'views.result_del_all'], {'name': '"""result_del_all"""'}), "('^(?P<project_id>\\\\d+)/result/del/all/$', views.result_del_all, name=\n 'result_del_all')\n", (562, 654), False, 'from django.conf.urls import url\n'), ((655, 731), 'django.conf.urls.url', 'url', (['"""^(?P<project_id>\\\\d+)/solver/$"""', 'views.solver_list'], {'name': '"""solver_list"""'}), "('^(?P<project_id>\\\\d+)/solver/$', views.solver_list, name='solver_list')\n", (658, 731), False, 'from django.conf.urls import url\n'), ((737, 815), 'django.conf.urls.url', 'url', (['"""^(?P<project_id>\\\\d+)/solver/add$"""', 'views.solver_edit'], {'name': '"""solver_add"""'}), "('^(?P<project_id>\\\\d+)/solver/add$', views.solver_edit, name='solver_add')\n", (740, 815), False, 'from django.conf.urls import url\n'), ((821, 927), 'django.conf.urls.url', 'url', (['"""^(?P<project_id>\\\\d+)/solver/edit/(?P<solver_id>\\\\d+)/$"""', 'views.solver_edit'], {'name': '"""solver_edit"""'}), "('^(?P<project_id>\\\\d+)/solver/edit/(?P<solver_id>\\\\d+)/$', views.\n solver_edit, name='solver_edit')\n", (824, 927), False, 'from django.conf.urls import url\n'), ((927, 1030), 'django.conf.urls.url', 'url', (['"""^(?P<project_id>\\\\d+)/solver/del/(?P<solver_id>\\\\d+)/$"""', 'views.solver_del'], {'name': '"""solver_del"""'}), "('^(?P<project_id>\\\\d+)/solver/del/(?P<solver_id>\\\\d+)/$', views.\n solver_del, name='solver_del')\n", (930, 1030), False, 'from django.conf.urls import url\n'), ((1030, 1108), 'django.conf.urls.url', 'url', (['"""^(?P<project_id>\\\\d+)/analysis/1D$"""', 'views.analysis1D'], {'name': '"""analysis1D"""'}), "('^(?P<project_id>\\\\d+)/analysis/1D$', views.analysis1D, name='analysis1D')\n", (1033, 1108), False, 'from django.conf.urls import url\n'), ((1114, 1192), 'django.conf.urls.url', 'url', (['"""^(?P<project_id>\\\\d+)/analysis/2D$"""', 'views.analysis2D'], {'name': '"""analysis2D"""'}), "('^(?P<project_id>\\\\d+)/analysis/2D$', views.analysis2D, name='analysis2D')\n", (1117, 1192), False, 'from django.conf.urls import url\n')] |
from ftplib import FTP
from ..config import FTP_SERVER_URL
from ..globals import globals as g
class FTPClient:
def __init__(self, host, user, passwd):
self.ftp = FTP(host)
# self.ftp.set_debuglevel(2)
self.ftp.set_pasv(True)
self.ftp.login(user, passwd)
def download(self, filename, path):
print('Downloading')
self.ftp.retrbinary('RETR ' + path, open(filename, 'wb').write)
print("Downloaded")
def upload(self, filename, path):
self.ftp.storbinary('STOR ' + path, open(filename, 'rb'), blocksize=g.ftp_upload_blocksize)
def list_server_files(self):
self.ftp.retrlines('LIST')
def close(self):
self.ftp.quit()
def get_client(username, password):
print("FTP User credentials:", FTP_SERVER_URL, username, password)
return FTPClient(host=FTP_SERVER_URL, user=username, passwd=password)
def check_credentials(username, password):
try:
FTPClient(host=FTP_SERVER_URL, user=username, passwd=password)
return True
except Exception as e:
print("Error:{}".format(str(e)))
return False | [
"ftplib.FTP"
] | [((177, 186), 'ftplib.FTP', 'FTP', (['host'], {}), '(host)\n', (180, 186), False, 'from ftplib import FTP\n')] |
import sys
import time
import requests
def send_request(keyword):
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9",
"Connection": "keep-alive",
"Content-Length": "275",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Cookie": "tvfe_boss_uuid=fdabda8ec17e137c; RK=AR0C7YpPWJ; mobileUV=1_15b4b943b61_95e4c; pgv_pvi=2738445312; pac_uid=1_978940294; eas_sid=O1R5M3q4j0z54009t3p1N6G0R2; ptcz=058154a19c221164ee78e81dc266354fe0b73cf0743d92b7ccacaccfe32727e3; pgv_pvid=297027592; o_cookie=978940294; ptui_loginuin=190064345; fy_guid=4d45ddf8-0c67-41ca-85d9-51efe63a1bdb; qtv=a3b176d483442da4; qtk=q0QMZSCt5TrX9lMHzP7T+shuoJPqF2AYpbOc0WmnK9c7RqzlJrQK3uB8o5mhzKwfIct5qOiEYj8jtrjVb41fSApRgjnje9CU1fc6IjKewErt1Iw3Z0lR7HMhFJYLX1CPf2jrFxKNZu6ZebWlBexolw==; pgv_info=ssid=s9952684092; ts_last=fanyi.qq.com/; ts_refer=www.baidu.com/link; ts_uid=7767932671; openCount=1; gr_user_id=dba8f209-b863-4452-ab75-255be17b5a84; 9c118ce09a6fa3f4_gr_session_id=98b7884d-6730-4566-9490-57f5febb6adf; grwng_uid=e17e4ad0-7514-4ed1-9643-ec6b5e576c3b; 9c118ce09a6fa3f4_gr_session_id_98b7884d-6730-4566-9490-57f5febb6adf=true",
"Host": "fanyi.qq.com",
"Origin": "https://fanyi.qq.com",
"Referer": "https://fanyi.qq.com/",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
"X-Requested-With": "XMLHttpRequest"
}
url = "https://fanyi.qq.com/api/translate"
data = {
"source": "auto",
"target": "zh",
"sourceText": keyword,
"qtv": "a3b176d483442da4",
"qtk": "q0QMZSCt5TrX9lMHzP7T+shuoJPqF2AYpbOc0WmnK9c7RqzlJrQK3uB8o5mhzKwfIct5qOiEYj8jtrjVb41fSApRgjnje9CU1fc6IjKewErt1Iw3Z0lR7HMhFJYLX1CPf2jrFxKNZu6ZebWlBexolw==",
"sessionUuid": "translate_uuid{}".format(str(int(time.time() * 1000))), # 添加时间戳(破解时间戳防盗链)
}
response = requests.post(url, data=data, headers=headers, timeout=3)
result = response.json()
print(result["translate"]["records"][0]["targetText"])
if __name__ == "__main__":
send_request(sys.argv[1]) | [
"requests.post",
"time.time"
] | [((2051, 2108), 'requests.post', 'requests.post', (['url'], {'data': 'data', 'headers': 'headers', 'timeout': '(3)'}), '(url, data=data, headers=headers, timeout=3)\n', (2064, 2108), False, 'import requests\n'), ((1988, 1999), 'time.time', 'time.time', ([], {}), '()\n', (1997, 1999), False, 'import time\n')] |
import os
import pickle
import radical.pilot as rp
import radical.utils as ru
from radical.entk import Task
from radical.entk import exceptions as ree
# ------------------------------------------------------------------------------
#
def resolve_placeholders(path, placeholders, logger):
"""
**Purpose**: Substitute placeholders in staging attributes of a Task with
actual paths to the corresponding tasks.
:arguments:
:path: string describing the staging paths, possibly
containing a placeholder
:placeholders: dictionary holding the values for placeholders
"""
try:
if isinstance(path, str):
path = str(path)
if not isinstance(path, str):
raise ree.TypeError(expected_type=str,
actual_type=type(path))
if '$' not in path:
return path
path_placeholders = []
# Extract placeholder from path
if len(path.split('>')) == 1:
path_placeholders.append(path.split('/')[0])
else:
if path.split('>')[0].strip().startswith('$'):
path_placeholders.append(path.split('>')[0].strip().split('/')[0])
if path.split('>')[1].strip().startswith('$'):
path_placeholders.append(path.split('>')[1].strip().split('/')[0])
resolved = path
for placeholder in path_placeholders:
# SHARED
if placeholder == "$SHARED":
resolved = resolved.replace(placeholder, 'pilot://')
continue
# Expected placeholder format:
# $Pipeline_{pipeline.uid}_Stage_{stage.uid}_Task_{task.uid}
elems = placeholder.split('/')[0].split('_')
if not len(elems) == 6:
expected = '$Pipeline_(pipeline_name)_' \
'Stage_(stage_name)_' \
'Task_(task_name) or $SHARED',
raise ree.ValueError(obj='placeholder', attribute='task',
expected_value=expected, actual_value=elems)
pname = elems[1]
sname = elems[3]
tname = elems[5]
is_resolved_by_uid = False
if pname in placeholders:
if sname in placeholders[pname]:
if tname in placeholders[pname][sname]:
resolved = resolved.replace(placeholder,
placeholders[pname][sname][tname]['path'])
is_resolved_by_uid = True
else:
logger.warning('%s not assigned to any task in Stage %s Pipeline %s' %
(tname, sname, pname))
else:
logger.warning('%s not assigned to any Stage in Pipeline %s' % (
sname, pname))
else:
logger.warning('%s not assigned to any Pipeline' % (pname))
if is_resolved_by_uid is False:
placeholders_by_name = placeholders["__by_name__"]
if pname in placeholders_by_name:
if sname in placeholders_by_name[pname]:
if tname in placeholders_by_name[pname][sname]:
resolved = resolved.replace(placeholder,
placeholders_by_name[pname][sname][tname]['path'])
else:
logger.warning('%s not assigned to any task in Stage %s Pipeline %s' %
(tname, sname, pname))
else:
logger.warning('%s not assigned to any Stage in Pipeline %s' % (
sname, pname))
else:
logger.warning('%s not assigned to any Pipeline' % (pname))
if not resolved:
logger.warning('No placeholder could be found for task name %s \
stage name %s and pipeline name %s. Please be sure to \
use object names and not uids in your references,i.e, \
$Pipeline_(pipeline_name)_Stage_(stage_name)_Task_(task_name)')
expected = '$Pipeline_(pipeline_name)_' \
'Stage_(stage_name)_' \
'Task_(task_name) or $SHARED'
raise ree.ValueError(obj='placeholder', attribute='task',
expected_value=expected, actual_value=elems)
return resolved
except Exception as ex:
logger.exception('Failed to resolve placeholder %s, error: %s' %
(path, ex))
raise
# ------------------------------------------------------------------------------
#
def resolve_arguments(args, placeholders, logger):
resolved_args = list()
for entry in args:
# If entry starts with $, it has a placeholder
# and needs to be resolved based after a lookup in
# the placeholders
if not isinstance(entry, str) or \
not entry.startswith('$'):
resolved_args.append(entry)
continue
placeholder = entry.split('/')[0]
if placeholder == "$SHARED":
entry = entry.replace(placeholder, '$RP_PILOT_STAGING')
elif placeholder.startswith('$Pipeline'):
elems = placeholder.split('_')
if len(elems) != 6:
expected = '$Pipeline_{pipeline.uid}_' \
'Stage_{stage.uid}_' \
'Task_{task.uid} or $SHARED'
raise ree.ValueError(obj='placeholder', attribute='length',
expected_value=expected, actual_value=elems)
pname = elems[1]
sname = elems[3]
tname = elems[5]
try:
entry = entry.replace(placeholder,
placeholders[pname][sname][tname]['path'])
except Exception:
logger.warning('Argument parsing failed. Task %s of Stage %s '
'in Pipeline %s does not exist',
tname, sname, pname)
resolved_args.append(entry)
return resolved_args
# ------------------------------------------------------------------------------
#
def resolve_tags(task, parent_pipeline_name, placeholders):
# entk only handles co_location tags. If tags are given as strings, they
# get translated into `{'colocation': '<tag>'}`. Tags passed as dictionaies
# are checked to conform with above form.
#
# In both cases, the tag string is expanded with the given placeholders.
tags = task.tags if task.tags else {'colocate': task.uid}
colo_tag = tags['colocate']
# Check self pipeline first
for sname in placeholders[parent_pipeline_name]:
if colo_tag in placeholders[parent_pipeline_name][sname]:
return {'colocate': placeholders[parent_pipeline_name][sname][colo_tag]['uid']}
for pname in placeholders:
# skip self pipeline this time
if pname == parent_pipeline_name:
continue
for sname in placeholders[pname]:
if colo_tag in placeholders[pname][sname]:
return {'colocate': placeholders[pname][sname][colo_tag]['uid']}
return {'colocate': task.uid}
# ------------------------------------------------------------------------------
#
def get_input_list_from_task(task, placeholders, logger):
"""
Purpose: Parse Task object to extract the files to be staged as the output.
Details: The extracted data is then converted into the appropriate RP
directive depending on whether the data is to be copied/downloaded.
:arguments:
:task: EnTK Task object
:placeholders: dictionary holding the values for placeholders
:return: list of RP directives for the files that need to be staged out
"""
try:
if not isinstance(task, Task):
raise ree.TypeError(expected_type=Task, actual_type=type(task))
input_data = list()
if task.link_input_data:
for path in task.link_input_data:
path = resolve_placeholders(path, placeholders, logger)
if len(path.split('>')) > 1:
temp = {
'source': path.split('>')[0].strip(),
'target': path.split('>')[1].strip(),
'action': rp.LINK
}
else:
temp = {
'source': path.split('>')[0].strip(),
'target': os.path.basename(path.split('>')[0].strip()),
'action': rp.LINK
}
input_data.append(temp)
if task.upload_input_data:
for path in task.upload_input_data:
path = resolve_placeholders(path, placeholders, logger)
if len(path.split('>')) > 1:
temp = {
'source': path.split('>')[0].strip(),
'target': path.split('>')[1].strip()
}
else:
temp = {
'source': path.split('>')[0].strip(),
'target': os.path.basename(path.split('>')[0].strip())
}
input_data.append(temp)
if task.copy_input_data:
for path in task.copy_input_data:
path = resolve_placeholders(path, placeholders, logger)
if len(path.split('>')) > 1:
temp = {
'source': path.split('>')[0].strip(),
'target': path.split('>')[1].strip(),
'action': rp.COPY
}
else:
temp = {
'source': path.split('>')[0].strip(),
'target': os.path.basename(path.split('>')[0].strip()),
'action': rp.COPY
}
input_data.append(temp)
if task.move_input_data:
for path in task.move_input_data:
path = resolve_placeholders(path, placeholders, logger)
if len(path.split('>')) > 1:
temp = {
'source': path.split('>')[0].strip(),
'target': path.split('>')[1].strip(),
'action': rp.MOVE
}
else:
temp = {
'source': path.split('>')[0].strip(),
'target': os.path.basename(path.split('>')[0].strip()),
'action': rp.MOVE
}
input_data.append(temp)
return input_data
except Exception:
logger.exception('Failed to get input list of files from task')
raise
# ------------------------------------------------------------------------------
#
def get_output_list_from_task(task, placeholders, logger):
"""
Purpose: Parse Task object to extract the files to be staged as the output.
Details: The extracted data is then converted into the appropriate RP
directive depending on whether the data is to be copied/downloaded.
:arguments:
:task: EnTK Task object
:placeholders: dictionary holding the values for placeholders
:return: list of RP directives for the files that need to be staged out
"""
try:
if not isinstance(task, Task):
raise ree.TypeError(expected_type=Task, actual_type=type(task))
output_data = list()
if task.link_output_data:
for path in task.link_output_data:
path = resolve_placeholders(path, placeholders, logger)
if len(path.split('>')) > 1:
temp = {
'source': path.split('>')[0].strip(),
'target': path.split('>')[1].strip(),
'action': rp.LINK
}
else:
temp = {
'source': path.split('>')[0].strip(),
'target': os.path.basename(path.split('>')[0].strip()),
'action': rp.LINK
}
output_data.append(temp)
if task.download_output_data:
for path in task.download_output_data:
path = resolve_placeholders(path, placeholders, logger)
if len(path.split('>')) > 1:
temp = {
'source': path.split('>')[0].strip(),
'target': path.split('>')[1].strip()
}
else:
temp = {
'source': path.split('>')[0].strip(),
'target': os.path.basename(path.split('>')[0].strip())
}
output_data.append(temp)
if task.copy_output_data:
for path in task.copy_output_data:
path = resolve_placeholders(path, placeholders, logger)
if len(path.split('>')) > 1:
temp = {
'source': path.split('>')[0].strip(),
'target': path.split('>')[1].strip(),
'action': rp.COPY
}
else:
temp = {
'source': path.split('>')[0].strip(),
'target': os.path.basename(path.split('>')[0].strip()),
'action': rp.COPY
}
output_data.append(temp)
if task.move_output_data:
for path in task.move_output_data:
path = resolve_placeholders(path, placeholders, logger)
if len(path.split('>')) > 1:
temp = {
'source': path.split('>')[0].strip(),
'target': path.split('>')[1].strip(),
'action': rp.MOVE
}
else:
temp = {
'source': path.split('>')[0].strip(),
'target': os.path.basename(path.split('>')[0].strip()),
'action': rp.MOVE
}
output_data.append(temp)
return output_data
except Exception:
logger.exception('Failed to get output list of files from task')
raise
# ------------------------------------------------------------------------------
#
def create_td_from_task(task, placeholders, task_hash_table, pkl_path, sid,
logger, prof=None):
"""
Purpose: Create an RP Task description based on the defined Task.
:arguments:
:task: EnTK Task object
:placeholders: dictionary holding the values for placeholders
:return: rp.TaskDescription
"""
try:
logger.debug('Creating Task from Task %s: %s' % (task.uid, task.sandbox))
logger.debug('Hash table state: %s' % task_hash_table)
if prof:
prof.prof('td_create', uid=task.uid)
td = rp.TaskDescription()
task_pre_uid = task_hash_table.get(task.uid, None)
if task_pre_uid is None:
td.uid = task.uid
else:
tmp_uid = ru.generate_id(prefix=task.uid, ns=sid)
td.uid = tmp_uid
task_hash_table[task.uid] = td.uid
with open(pkl_path, 'wb') as pickle_file:
pickle.dump(task_hash_table, pickle_file, pickle.HIGHEST_PROTOCOL)
logger.debug('Hash table state: %s' % task_hash_table)
td.name = '%s,%s,%s,%s,%s,%s' % (task.uid, task.name,
task.parent_stage['uid'],
task.parent_stage['name'],
task.parent_pipeline['uid'],
task.parent_pipeline['name'])
td.pre_exec = task.pre_exec
td.executable = task.executable
td.arguments = resolve_arguments(task.arguments, placeholders, logger)
td.sandbox = task.sandbox
td.post_exec = task.post_exec
td.stage_on_error = task.stage_on_error
if task.parent_pipeline['uid']:
td.tags = resolve_tags(task=task,
parent_pipeline_name=task.parent_pipeline['uid'],
placeholders=placeholders)
td.cpu_processes = task.cpu_reqs['cpu_processes']
td.cpu_threads = task.cpu_reqs['cpu_threads']
if task.cpu_reqs['cpu_process_type']:
td.cpu_process_type = task.cpu_reqs['cpu_process_type']
else:
td.cpu_process_type = rp.POSIX
if task.cpu_reqs['cpu_thread_type']:
td.cpu_thread_type = task.cpu_reqs['cpu_thread_type']
else:
td.cpu_thread_type = rp.OpenMP
td.gpu_processes = task.gpu_reqs['gpu_processes']
td.gpu_threads = task.gpu_reqs['gpu_threads']
if task.gpu_reqs['gpu_process_type']:
td.gpu_process_type = task.gpu_reqs['gpu_process_type']
else:
td.gpu_process_type = rp.POSIX
if task.gpu_reqs['gpu_thread_type']:
td.gpu_thread_type = task.gpu_reqs['gpu_thread_type']
else:
td.gpu_thread_type = rp.GPU_OpenMP
if task.lfs_per_process:
td.lfs_per_process = task.lfs_per_process
if task.stdout: td.stdout = task.stdout
if task.stderr: td.stderr = task.stderr
td.input_staging = get_input_list_from_task(task, placeholders, logger)
td.output_staging = get_output_list_from_task(task, placeholders, logger)
if prof:
prof.prof('td from task - done', uid=task.uid)
logger.debug('Task %s created from Task %s' % (td.name, task.uid))
return td
except Exception:
logger.exception('Task creation failed')
raise
# ------------------------------------------------------------------------------
#
def create_task_from_rp(rp_task, logger, prof=None):
"""
Purpose: Create a Task based on the RP Task.
Details: Currently, only the uid, parent_stage and parent_pipeline are
retrieved. The exact initial Task (that was converted to a TD)
cannot be recovered as the RP API does not provide the same
attributes for a Task as for a TD. Also, this is not required for
the most part.
:arguments:
:task: RP Task
:return: Task
"""
try:
logger.debug('Create Task from RP Task %s' % rp_task.name)
if prof:
prof.prof('task_create', uid=rp_task.name.split(',')[0].strip())
task = Task()
task.uid = rp_task.name.split(',')[0].strip()
task.name = rp_task.name.split(',')[1].strip()
task.parent_stage['uid'] = rp_task.name.split(',')[2].strip()
task.parent_stage['name'] = rp_task.name.split(',')[3].strip()
task.parent_pipeline['uid'] = rp_task.name.split(',')[4].strip()
task.parent_pipeline['name'] = rp_task.name.split(',')[5].strip()
task.rts_uid = rp_task.uid
if rp_task.state == rp.DONE : task.exit_code = 0
elif rp_task.state in [rp.FAILED, rp.CANCELED] : task.exit_code = 1
task.path = ru.Url(rp_task.sandbox).path
if prof:
prof.prof('task_created', uid=task.uid)
logger.debug('Task %s created from RP Task %s' % (task.uid, rp_task.name))
return task
except Exception:
logger.exception('Task creation from RP Task failed, error')
raise
# ------------------------------------------------------------------------------
| [
"radical.pilot.TaskDescription",
"radical.utils.Url",
"pickle.dump",
"radical.entk.exceptions.ValueError",
"radical.entk.Task",
"radical.utils.generate_id"
] | [((15614, 15634), 'radical.pilot.TaskDescription', 'rp.TaskDescription', ([], {}), '()\n', (15632, 15634), True, 'import radical.pilot as rp\n'), ((19289, 19295), 'radical.entk.Task', 'Task', ([], {}), '()\n', (19293, 19295), False, 'from radical.entk import Task\n'), ((15794, 15833), 'radical.utils.generate_id', 'ru.generate_id', ([], {'prefix': 'task.uid', 'ns': 'sid'}), '(prefix=task.uid, ns=sid)\n', (15808, 15833), True, 'import radical.utils as ru\n'), ((15968, 16034), 'pickle.dump', 'pickle.dump', (['task_hash_table', 'pickle_file', 'pickle.HIGHEST_PROTOCOL'], {}), '(task_hash_table, pickle_file, pickle.HIGHEST_PROTOCOL)\n', (15979, 16034), False, 'import pickle\n'), ((19966, 19989), 'radical.utils.Url', 'ru.Url', (['rp_task.sandbox'], {}), '(rp_task.sandbox)\n', (19972, 19989), True, 'import radical.utils as ru\n'), ((2024, 2124), 'radical.entk.exceptions.ValueError', 'ree.ValueError', ([], {'obj': '"""placeholder"""', 'attribute': '"""task"""', 'expected_value': 'expected', 'actual_value': 'elems'}), "(obj='placeholder', attribute='task', expected_value=expected,\n actual_value=elems)\n", (2038, 2124), True, 'from radical.entk import exceptions as ree\n'), ((4527, 4627), 'radical.entk.exceptions.ValueError', 'ree.ValueError', ([], {'obj': '"""placeholder"""', 'attribute': '"""task"""', 'expected_value': 'expected', 'actual_value': 'elems'}), "(obj='placeholder', attribute='task', expected_value=expected,\n actual_value=elems)\n", (4541, 4627), True, 'from radical.entk import exceptions as ree\n'), ((5776, 5879), 'radical.entk.exceptions.ValueError', 'ree.ValueError', ([], {'obj': '"""placeholder"""', 'attribute': '"""length"""', 'expected_value': 'expected', 'actual_value': 'elems'}), "(obj='placeholder', attribute='length', expected_value=\n expected, actual_value=elems)\n", (5790, 5879), True, 'from radical.entk import exceptions as ree\n')] |
import re
import numpy as np
def compounddic2atomsfraction(compounds):
def createNewDic(dic, multiplyby):
values = list(dic.values())
keys = dic.keys()
newValues = np.array(values)*multiplyby
newDic = dict(zip(keys, newValues))
return newDic
def composition2atoms(cstr):
lst = re.findall(r'([A-Z][a-z]?)(\d*\.?\d*)', cstr)
dic = {}
for i in lst:
if len(i[1]) > 0:
try:
dic[i[0]] = int(i[1])
except ValueError:
dic[i[0]] = float(i[1])
else:
dic[i[0]] = 1
return dic
dic = {}
for key in compounds.keys():
baseValue = compounds[key]
atoms = composition2atoms(key)
for a in atoms.keys():
dic[a] = dic.get(a, 0) + atoms[a]*baseValue
multiplyby = 1/np.sum(list(dic.values()))
atomsF = createNewDic(dic, multiplyby)
return atomsF
###############################################################################
# Exemplo #
###############################################################################
AvailableCompounds = ['Ag2O', 'Al2O3', 'As2O3', 'As2O5', 'B2O3', 'BaO',
'Bi2O3', 'CaO', 'CdO', 'Ce2O3', 'CeO2', 'Cl', 'Cs2O',
'Cu2O', 'CuO', 'Er2O3', 'F', 'Fe2O3', 'Fe3O4', 'FeO',
'Ga2O3', 'Gd2O3', 'GeO', 'GeO2', 'I', 'K2O', 'La2O3',
'Li2O', 'MgO', 'Mn2O3', 'Mn2O7', 'Mn3O4', 'MnO', 'MnO2',
'Mo2O3', 'Mo2O5', 'MoO', 'MoO2', 'MoO3', 'N', 'N2O5',
'NO2', 'Na2O', 'Nb2O3', 'Nb2O5', 'P2O3', 'P2O5', 'Pb3O4',
'PbO', 'PbO2', 'SO2', 'SO3', 'Sb2O3', 'Sb2O5', 'SbO2',
'SiO', 'SiO2', 'Sn2O3', 'SnO', 'SnO2', 'SrO', 'Ta2O3',
'Ta2O5', 'TeO2', 'TeO3', 'Ti2O3', 'TiO', 'TiO2', 'V2O3',
'V2O5', 'VO2', 'VO6', 'WO3', 'Y2O3', 'Yb2O3', 'ZnO',
'ZrO2']
# isto é o que o usuário pode dar de input, qualquer quantidade (numeros reais
# positivos) de um ou mais dos compostos da lista AvailableCompounds:
compostoDic = {
'Al2O3': 1,
'SiO': 0
}
atomDic = compounddic2atomsfraction(compostoDic)
print(atomDic)
# Do dicionário atomDic você tem os valores de fração atômica de cada átomo para por na rede
#ompound2atomfraction.py
#Exibindo compound2atomfraction.py. | [
"numpy.array",
"re.findall"
] | [((336, 383), 're.findall', 're.findall', (['"""([A-Z][a-z]?)(\\\\d*\\\\.?\\\\d*)"""', 'cstr'], {}), "('([A-Z][a-z]?)(\\\\d*\\\\.?\\\\d*)', cstr)\n", (346, 383), False, 'import re\n'), ((194, 210), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (202, 210), True, 'import numpy as np\n')] |
"""utilities to speedup calculations with jit
Author: <NAME>
Affiliation: TokyoTech & OSX
"""
import numpy as np
import torch
from numba import f8, jit
@jit(f8[:, :](f8[:, :]), nopython=True)
def get_normed_vec_mag(arr_vec: np.ndarray) -> np.ndarray:
"""compute
from [[x1, y1], [x2, y2], ...]
to [[normed_x1, normed_y1, mag], [normed_x2, normed_y2, mag], ...]
Args:
arr_vec (np.ndarray): un-normalized vector (2D)
Returns:
np.ndarray: normalized vector (3D)
"""
# np.linalg.norm with axis cannot be used with numba.jit
vec_mag = np.sqrt(np.sum(arr_vec ** 2, axis=1)).reshape(-1, 1)
vec_mag_avoid_zero = np.where(vec_mag == 0, 1, vec_mag)
arr_vec = arr_vec / vec_mag_avoid_zero
return np.hstack((arr_vec, vec_mag))
@jit(
f8[:, :, :](f8[:, :, :], f8[:, :], f8[:, :, :], f8[:], f8[:]),
nopython=True,
)
def get_arr_others_info(
arr_current_locs: np.ndarray,
goals: np.ndarray,
arr_prev_locs: np.ndarray,
rads: np.ndarray,
max_speeds: np.ndarray,
) -> np.ndarray:
"""get other agents relative info
Args:
arr_current_locs (np.ndarray): current locations
goals (np.ndarray): goal positions for all agents
arr_prev_locs (np.ndarray): previous locations
rads (np.ndarray): radius for all agents
max_speeds (np.ndarray): max speed for all agents
Returns:
np.ndarray:
time *
(self-agent -> other-agent) *
(current_vec, goal_vec, prev_vec, rad, speed)
Todo:
improving readability
"""
num_agents = goals.shape[0]
T = arr_current_locs.shape[0]
# get relative pos
arr_relative_pos = np.zeros((T * num_agents * num_agents * 3, 2))
for t in range(T):
for i in range(num_agents):
idx = t * (num_agents * num_agents * 3) + i * (num_agents * 3)
current_pos = arr_current_locs[t][i]
arr_relative_pos[idx + 0 * num_agents : idx + 1 * num_agents] = (
arr_current_locs[t] - current_pos
)
arr_relative_pos[idx + 1 * num_agents : idx + 2 * num_agents] = (
goals - current_pos
)
arr_relative_pos[idx + 2 * num_agents : idx + 3 * num_agents] = (
arr_prev_locs[t] - current_pos
)
arr_relative_pos = get_normed_vec_mag(arr_relative_pos)
arr_others_info = np.empty((T, num_agents * num_agents, 11))
for t in range(T):
for i in range(num_agents):
idx = t * (num_agents * num_agents * 3) + i * (num_agents * 3)
for j in range(num_agents):
k = i * num_agents + j
arr_others_info[t, k, 0:3] = arr_relative_pos[
j + 0 * num_agents + idx
]
arr_others_info[t, k, 3:6] = arr_relative_pos[
j + 1 * num_agents + idx
]
arr_others_info[t, k, 6:9] = arr_relative_pos[
j + 2 * num_agents + idx
]
arr_others_info[t, k, 9] = rads[j]
arr_others_info[t, k, 10] = max_speeds[j]
return arr_others_info
@torch.jit.script
def get_self_info(
num_agents: int, arr_others_info: torch.Tensor
) -> torch.Tensor:
"""get self-info from array of other_agents_info
Args:
num_agents (int): number of agents
arr_others_info (torch.Tensor): other agents' info
Returns:
torch.Tensor: time * agent * (goal_vec, prev_vec, rad, max_speed)
"""
T = arr_others_info.shape[0]
self_idx = torch.tensor(
[
[
t * num_agents * num_agents + num_agents * i + i
for i in range(num_agents)
]
for t in range(T)
]
).reshape(-1)
return arr_others_info.reshape(-1, arr_others_info.shape[-1])[:, 3:][
self_idx
].reshape(T, num_agents, -1)
| [
"numpy.hstack",
"numpy.where",
"numpy.sum",
"numpy.zeros",
"numpy.empty"
] | [((669, 703), 'numpy.where', 'np.where', (['(vec_mag == 0)', '(1)', 'vec_mag'], {}), '(vec_mag == 0, 1, vec_mag)\n', (677, 703), True, 'import numpy as np\n'), ((758, 787), 'numpy.hstack', 'np.hstack', (['(arr_vec, vec_mag)'], {}), '((arr_vec, vec_mag))\n', (767, 787), True, 'import numpy as np\n'), ((1706, 1752), 'numpy.zeros', 'np.zeros', (['(T * num_agents * num_agents * 3, 2)'], {}), '((T * num_agents * num_agents * 3, 2))\n', (1714, 1752), True, 'import numpy as np\n'), ((2428, 2470), 'numpy.empty', 'np.empty', (['(T, num_agents * num_agents, 11)'], {}), '((T, num_agents * num_agents, 11))\n', (2436, 2470), True, 'import numpy as np\n'), ((599, 627), 'numpy.sum', 'np.sum', (['(arr_vec ** 2)'], {'axis': '(1)'}), '(arr_vec ** 2, axis=1)\n', (605, 627), True, 'import numpy as np\n')] |
import csv
import copy
import matplotlib.pyplot as plt
def getCsv(txtFileName='twentyfourth.txt'):
with open(txtFileName) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=' ')
return list(csv_reader)
def parseLineList(csvFile):
instructionList = []
for row in csvFile:
instruction = list(row[0])
instructionEntry = []
while True:
if not instruction:
break
recentInstruction = instruction.pop(0)
if recentInstruction == 'e':
instructionEntry.append(complex(2, 0))
continue
if recentInstruction == 'w':
instructionEntry.append(complex(-2, 0))
continue
if recentInstruction == 's':
recentInstruction = instruction.pop(0)
if recentInstruction == 'e':
instructionEntry.append(complex(1, -1))
continue
if recentInstruction == 'w':
instructionEntry.append(complex(-1, -1))
continue
if recentInstruction == 'n':
recentInstruction = instruction.pop(0)
if recentInstruction == 'e':
instructionEntry.append(complex(1, 1))
continue
if recentInstruction == 'w':
instructionEntry.append(complex(-1, 1))
instructionList.append(instructionEntry)
return instructionList
def getNumberOfBlackNeighbors(recentBlackTiles, tileToCheck):
numberBlackNeighbors = 0
if tileToCheck + complex(2, 0) in recentBlackTiles:
numberBlackNeighbors += 1
if tileToCheck + complex(-2, 0) in recentBlackTiles:
numberBlackNeighbors += 1
if tileToCheck + complex(1, -1) in recentBlackTiles:
numberBlackNeighbors += 1
if tileToCheck + complex(-1, -1) in recentBlackTiles:
numberBlackNeighbors += 1
if tileToCheck + complex(1, 1) in recentBlackTiles:
numberBlackNeighbors += 1
if tileToCheck + complex(-1, 1) in recentBlackTiles:
numberBlackNeighbors += 1
return numberBlackNeighbors
def determineBlackTilesAfterDays(blackTiles, days):
recentBlackTiles = copy.deepcopy(blackTiles)
nextBlackTiles = []
for counter in range(days):
reals = [z.real for z in recentBlackTiles]
imags = [z.imag for z in recentBlackTiles]
maxRe = int(max(reals)) + 4
minRe = int(min(reals)) - 4
maxIm = int(max(imags)) + 2
minIm = int(min(imags)) - 2
for imagIndex in range(minIm, maxIm + 1):
if imagIndex % 2 == 0:
for realIndex in range(0, minRe + 1, -2):
tileToCheck = complex(realIndex, imagIndex)
numberOfBlackNeighbors = getNumberOfBlackNeighbors(recentBlackTiles, tileToCheck)
if tileToCheck in recentBlackTiles and numberOfBlackNeighbors in [1, 2]:
nextBlackTiles.append(tileToCheck)
elif tileToCheck not in recentBlackTiles and numberOfBlackNeighbors == 2:
nextBlackTiles.append(tileToCheck)
for realIndex in range(2, maxRe + 1, 2):
tileToCheck = complex(realIndex, imagIndex)
numberOfBlackNeighbors = getNumberOfBlackNeighbors(recentBlackTiles, tileToCheck)
if tileToCheck in recentBlackTiles and numberOfBlackNeighbors in [1, 2]:
nextBlackTiles.append(tileToCheck)
elif tileToCheck not in recentBlackTiles and numberOfBlackNeighbors == 2:
nextBlackTiles.append(tileToCheck)
else:
for realIndex in range(-1, minRe + 1, -2):
tileToCheck = complex(realIndex, imagIndex)
numberOfBlackNeighbors = getNumberOfBlackNeighbors(recentBlackTiles, tileToCheck)
if tileToCheck in recentBlackTiles and numberOfBlackNeighbors in [1, 2]:
nextBlackTiles.append(tileToCheck)
elif tileToCheck not in recentBlackTiles and numberOfBlackNeighbors == 2:
nextBlackTiles.append(tileToCheck)
for realIndex in range(1, maxRe + 1, 2):
tileToCheck = complex(realIndex, imagIndex)
numberOfBlackNeighbors = getNumberOfBlackNeighbors(recentBlackTiles, tileToCheck)
if tileToCheck in recentBlackTiles and numberOfBlackNeighbors in [1, 2]:
nextBlackTiles.append(tileToCheck)
elif tileToCheck not in recentBlackTiles and numberOfBlackNeighbors == 2:
nextBlackTiles.append(tileToCheck)
recentBlackTiles = nextBlackTiles[:]
nextBlackTiles =[]
return recentBlackTiles
testCase = [['nwwswee']]
testInstruction = parseLineList(testCase)
assert testInstruction[0] == [complex(-1, 1), complex(-2, 0), complex(-1, -1), complex(2, 0), complex(2, 0)]
assert sum(testInstruction[0]) == complex(0, 0)
csvFile = getCsv()
instructionList = parseLineList(csvFile)
flippedTiles = [sum(instruction) for instruction in instructionList]
blackTiles = []
for tile in flippedTiles:
if tile in blackTiles:
blackTiles.remove(tile)
else:
blackTiles.append(tile)
print(len(blackTiles))
blackTilesAfterDays = determineBlackTilesAfterDays(blackTiles, 100)
print(len(blackTilesAfterDays))
| [
"csv.reader",
"copy.deepcopy"
] | [((2272, 2297), 'copy.deepcopy', 'copy.deepcopy', (['blackTiles'], {}), '(blackTiles)\n', (2285, 2297), False, 'import copy\n'), ((162, 197), 'csv.reader', 'csv.reader', (['csv_file'], {'delimiter': '""" """'}), "(csv_file, delimiter=' ')\n", (172, 197), False, 'import csv\n')] |
import os
import os.path as op
import numpy as np
from numpy.testing import assert_almost_equal
from ..core import ShootingPoint, find_and_replace
def test_read_cv_values():
test_file_loc = op.join(op.dirname(op.abspath(__file__)),
'test_data', 'COLVAR2')
sp = ShootingPoint(name='test', input_file='.')
sp._read_cv_values(test_file_loc)
test_values = sp.cv_values
true_values = np.array([1.000000, 2.000000, 3.000000])
for test, true in zip(test_values, true_values):
assert_almost_equal(test, true)
return
def test_find_and_replace():
test_line = "abcABC123456"
test_sub = {"ABC": "EDF", "456": "789"}
test_result = find_and_replace(test_line, test_sub)
assert test_result == "abcEDF123789"
return
def test_check_if_commited():
sp = ShootingPoint(name='test', input_file='.')
test_file_loc = op.join(op.dirname(op.abspath(__file__)),
'test_data', 'commit.log')
test_result = sp.check_if_committed(test_file_loc)
assert test_result == 2, "Not getting correct basin."
test_file_loc = op.join(op.dirname(op.abspath(__file__)),
'test_data', 'no_commit.log')
test_result = sp.check_if_committed(test_file_loc)
assert not test_result, "Not reporting 'None' when it does not commit."
return
def test_log():
sp = ShootingPoint(name='test', input_file='.')
sp.name = 'test'
sp.cv_values = [1, 2, 3]
sp.result = 'accepted'
sp.log(filename="test.log")
with open("test.log", 'r') as f:
line = f.readline()
os.remove("test.log")
line = line.split(' ')
line[-1] = line[-1].rstrip()
assert line[0] == "test"
for test, true in zip(line[1:4], sp.cv_values):
assert float(test) == float(true)
# assert line[1:6] == test_CVs
assert line[-1] == "accepted"
| [
"numpy.testing.assert_almost_equal",
"numpy.array",
"os.path.abspath",
"os.remove"
] | [((432, 457), 'numpy.array', 'np.array', (['[1.0, 2.0, 3.0]'], {}), '([1.0, 2.0, 3.0])\n', (440, 457), True, 'import numpy as np\n'), ((1616, 1637), 'os.remove', 'os.remove', (['"""test.log"""'], {}), "('test.log')\n", (1625, 1637), False, 'import os\n'), ((534, 565), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['test', 'true'], {}), '(test, true)\n', (553, 565), False, 'from numpy.testing import assert_almost_equal\n'), ((217, 237), 'os.path.abspath', 'op.abspath', (['__file__'], {}), '(__file__)\n', (227, 237), True, 'import os.path as op\n'), ((914, 934), 'os.path.abspath', 'op.abspath', (['__file__'], {}), '(__file__)\n', (924, 934), True, 'import os.path as op\n'), ((1145, 1165), 'os.path.abspath', 'op.abspath', (['__file__'], {}), '(__file__)\n', (1155, 1165), True, 'import os.path as op\n')] |
import requests
import matplotlib.pyplot as plt
URL = "https://api.github.com/orgs/alibaba/repos"
repos_json = requests.get(URL).json()
star_data_repos = {}
for repo in repos_json:
star_data_repos[repo['name']] = repo['stargazers_count']
print(star_data_repos)
fig = plt.figure()
plt.bar(star_data_repos.keys(), star_data_repos.values())
plt.show() | [
"matplotlib.pyplot.figure",
"requests.get",
"matplotlib.pyplot.show"
] | [((277, 289), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (287, 289), True, 'import matplotlib.pyplot as plt\n'), ((348, 358), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (356, 358), True, 'import matplotlib.pyplot as plt\n'), ((111, 128), 'requests.get', 'requests.get', (['URL'], {}), '(URL)\n', (123, 128), False, 'import requests\n')] |
import os
def print_fonts():
"""
Prints all available font names
"""
fonts = load_fonts()
print_num = 0
# for every 5 colours printed, the next colour will go to a new line.
print('\nAvailable fonts:')
for font in fonts:
font = font.split('/')[2][:-4]
print_num += 1
if print_num != 5:
print(font + ', ', end='')
else:
print_num = 0
print(font + ', ')
def load_fonts():
"""
Loads all colours from json file to dict.
"""
fonts = []
try:
# locates the fonts in the font folder
for root, dirs, files in os.walk('../fonts'):
for file in files:
if file.endswith(".ttf"):
fonts.append('../fonts/' + file)
except FileNotFoundError:
print(f'Could not find the fonts folder!')
print(exit)
else:
return fonts
def input_fonts():
"""
Prompts the user to input a font. Also deals with error handling.
"""
fonts = load_fonts()
fonts = [font.split('/')[2][:-4] for font in fonts]
while True:
try:
print('\nIf you would like to list available fonts enter "help"')
user_input = input(f'Enter a font: ')
if user_input == 'help':
print_fonts()
continue
if user_input not in fonts:
raise KeyError
except KeyError:
print('\nThat was not a valid font!')
else:
return '../fonts/' + user_input + '.ttf'
def input_font_size():
"""
Prompts the user to input a font size. Also deals with error handling.
"""
while True:
try:
user_input = input('\nPlease enter a font size: ')
a = float(user_input)
b = int(user_input)
if a != b:
raise ValueError
except ValueError:
print('\nThat was not a valid size!')
else:
return int(user_input)
| [
"os.walk"
] | [((672, 691), 'os.walk', 'os.walk', (['"""../fonts"""'], {}), "('../fonts')\n", (679, 691), False, 'import os\n')] |
import sys
import haystack
import contentmanager
# A bit of a hack but it seems to work for my use-cases
if len(sys.argv)>1 \
and sys.argv[1] in ('clear_index', 'rebuild_index', 'update_index'):
contentmanager.autodiscover()
haystack.autodiscover()
| [
"haystack.autodiscover",
"contentmanager.autodiscover"
] | [((241, 264), 'haystack.autodiscover', 'haystack.autodiscover', ([], {}), '()\n', (262, 264), False, 'import haystack\n'), ((210, 239), 'contentmanager.autodiscover', 'contentmanager.autodiscover', ([], {}), '()\n', (237, 239), False, 'import contentmanager\n')] |
import random
from aco import SolveTSPUsingACO
## Gerando cidades aleatórias
cities_size = 15
nodes = [(random.uniform(-400, 400), random.uniform(-400, 400)) for i in range(cities_size)]
## Definindo parametros do ACO
colony_size = 10 # Número de formigas
steps = 100 # Número de interações
alpha = 1.0 # Se α = 0, só há influência da distância, assim seria algo como a busca gulosa
beta = 3.0 # Se β = 0 existe somente a dependência do feromônio, encontrando rotinas fortemente sub-ótimas
mode = 'MaxMin' # Tipo de Algoritmo. Possibilidades: ACS, Elitist, MaxMin
# Instanciando o ACO
acs = SolveTSPUsingACO(mode=mode, colony_size=colony_size, steps=steps, alpha=alpha, beta=beta, nodes=nodes)
# Rodando o ACO
acs.run()
# Plotando o ACO
acs.plot() | [
"random.uniform",
"aco.SolveTSPUsingACO"
] | [((597, 704), 'aco.SolveTSPUsingACO', 'SolveTSPUsingACO', ([], {'mode': 'mode', 'colony_size': 'colony_size', 'steps': 'steps', 'alpha': 'alpha', 'beta': 'beta', 'nodes': 'nodes'}), '(mode=mode, colony_size=colony_size, steps=steps, alpha=\n alpha, beta=beta, nodes=nodes)\n', (613, 704), False, 'from aco import SolveTSPUsingACO\n'), ((107, 132), 'random.uniform', 'random.uniform', (['(-400)', '(400)'], {}), '(-400, 400)\n', (121, 132), False, 'import random\n'), ((134, 159), 'random.uniform', 'random.uniform', (['(-400)', '(400)'], {}), '(-400, 400)\n', (148, 159), False, 'import random\n')] |
import math
import os
import pandas as pd
import numpy as np
import matplotlib as plt
def csv_to_df(csv_path, dtypes, skiprows):
df = pd.read_csv(csv_path, dtype=dtypes, skiprows=skiprows)
return df
def onehot_encode(df, dtypes):
categoricals = [column for (column, dtype) in dtypes.items() if dtype == "category"]
for column in categoricals:
df = pd.get_dummies(data=df, columns=[column])
return df
def write_csv(df, csv_path, transform_name):
out_path = "{0}_{1}.csv".format(
os.path.splitext(csv_path)[0], transform_name)
columns = df.columns.tolist()
if "ARR_DELAY" in columns:
# place target in first column for SageMaker
columns.remove("ARR_DELAY")
columns.insert(0, "ARR_DELAY")
df = df[columns]
df.to_csv(path_or_buf=out_path, index=False)
return
def csv_transform(csv_path, dtypes, drop_columns, data_config):
df = csv_to_df(csv_path, dtypes, data_config["skiprows"])
df = df.drop(columns=drop_columns)
dtypes = {key: dtypes[key] for key in dtypes if key not in drop_columns}
df = onehot_encode(df, dtypes)
write_csv(df, csv_path, data_config["transform_name"])
return
def memory_efficient():
drop_columns = ["YEAR", "TAIL_NUM", "FL_NUM", "DEST"] # skip DEST to avoid memory issues
dtypes = {
"YEAR": np.int64,
"QUARTER": "category",
"MONTH": "category",
"DAY_OF_MONTH": "category",
"DAY_OF_WEEK": "category",
"UNIQUE_CARRIER": "category",
"TAIL_NUM": "category",
"FL_NUM": "category",
"ORIGIN": "category",
"DEST": "category",
"CRS_DEP_TIME": np.int64,
"DEP_TIME": np.int64,
"DEP_DELAY": np.float64,
"DEP_DELAY_NEW": np.float64,
"DEP_DEL15": np.int64,
"DEP_DELAY_GROUP": np.int64,
"CRS_ARR_TIME": np.int64,
"ARR_DELAY": np.float64,
"CRS_ELAPSED_TIME": np.float64,
"DISTANCE": np.float64,
"DISTANCE_GROUP": "category"
}
numrows = 1114751 - 1 # minus 1 for header
training_ratio = 0.8
data_config = {
"train": {
"skiprows": range(math.floor(training_ratio * numrows) + 1, numrows + 2),
"transform_name": "training"
},
"test": {
"skiprows": range(1, math.floor(training_ratio * numrows) + 1),
"transform_name": "test"
}
}
csv_transform("data/Flights.csv", dtypes, drop_columns, data_config["train"])
csv_transform("data/Flights.csv", dtypes, drop_columns, data_config["test"])
# create dest files to be joined with other columns
drop_columns = [column for column in dtypes if column not in ["DEST"]]
data_config["train"]["transform_name"] = "training_dest"
data_config["test"]["transform_name"] = "test_dest"
csv_transform("data/Flights.csv", dtypes, drop_columns, data_config["train"])
csv_transform("data/Flights.csv", dtypes, drop_columns, data_config["test"])
def naive():
drop_columns = [["YEAR", "TAIL_NUM", "FL_NUM"],
["YEAR", "TAIL_NUM", "FL_NUM"]]
dtypes = {
"YEAR": np.int64,
"QUARTER": "category",
"MONTH": "category",
"DAY_OF_MONTH": "category",
"DAY_OF_WEEK": "category",
"UNIQUE_CARRIER": "category",
"TAIL_NUM": "category",
"FL_NUM": "category",
"ORIGIN": "category",
"DEST": "category",
"CRS_DEP_TIME": np.int64,
"DEP_TIME": np.int64,
"DEP_DELAY": np.float64,
"DEP_DELAY_NEW": np.float64,
"DEP_DEL15": np.int64,
"DEP_DELAY_GROUP": np.int64,
"CRS_ARR_TIME": np.int64,
"ARR_DELAY": np.float64,
"CRS_ELAPSED_TIME": np.float64,
"DISTANCE": np.float64,
"DISTANCE_GROUP": "category"
}
numrows = 1114751 - 1 # minus 1 for header
training_ratio = 0.8
## Better to process all at once and split at the end (if memory wasn't a concern)
data_config = {
"train": {
"skiprows": range(math.floor(training_ratio * numrows) + 1, numrows + 2),
"transform_name": "training"
},
"test": {
"skiprows": range(1, math.floor(training_ratio * numrows) + 1),
"transform_name": "test"
}
}
csv_transform("data/Flights.csv", dtypes, drop_columns, data_config["train"])
csv_transform("data/Flights.csv", dtypes, drop_columns, data_config["test"])
if __name__ == "__main__":
#naive()
memory_efficient()
| [
"pandas.get_dummies",
"os.path.splitext",
"pandas.read_csv",
"math.floor"
] | [((140, 194), 'pandas.read_csv', 'pd.read_csv', (['csv_path'], {'dtype': 'dtypes', 'skiprows': 'skiprows'}), '(csv_path, dtype=dtypes, skiprows=skiprows)\n', (151, 194), True, 'import pandas as pd\n'), ((376, 417), 'pandas.get_dummies', 'pd.get_dummies', ([], {'data': 'df', 'columns': '[column]'}), '(data=df, columns=[column])\n', (390, 417), True, 'import pandas as pd\n'), ((524, 550), 'os.path.splitext', 'os.path.splitext', (['csv_path'], {}), '(csv_path)\n', (540, 550), False, 'import os\n'), ((2170, 2206), 'math.floor', 'math.floor', (['(training_ratio * numrows)'], {}), '(training_ratio * numrows)\n', (2180, 2206), False, 'import math\n'), ((2329, 2365), 'math.floor', 'math.floor', (['(training_ratio * numrows)'], {}), '(training_ratio * numrows)\n', (2339, 2365), False, 'import math\n'), ((4059, 4095), 'math.floor', 'math.floor', (['(training_ratio * numrows)'], {}), '(training_ratio * numrows)\n', (4069, 4095), False, 'import math\n'), ((4218, 4254), 'math.floor', 'math.floor', (['(training_ratio * numrows)'], {}), '(training_ratio * numrows)\n', (4228, 4254), False, 'import math\n')] |
import sys
import versioneer
import setuptools
if sys.version_info < (3,6):
print("Soundlab requires Python 3.6 or higher please upgrade")
sys.exit(1)
long_description = \
"""
Soundlab is a python package to analyze and visualize sound data. Created
with scientific use in mind. It is in its early stages of development (alpha)
stage.
"""
setuptools.setup(
name='soundlab',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
packages=['soundlab', 'soundlab.tests'],
url='https://github.com/gbeckers/soundlab',
license='BSD-3',
author='<NAME>',
author_email='<EMAIL>',
description='Package to analyse of sound data',
long_description=long_description,
long_description_content_type="text/x-rst",
python_requires='>=3.6',
install_requires=['sounddata', 'matplotlib', 'pandas'],
data_files = [("", ["LICENSE"])],
classifiers=[
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
'Development Status :: 3 - Alpha',
'Intended Audience :: Education',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: Science/Research',
],
project_urls={ # Optional
'Source': 'https://github.com/gbeckers/soundlab',
}
)
| [
"versioneer.get_cmdclass",
"versioneer.get_version",
"sys.exit"
] | [((148, 159), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (156, 159), False, 'import sys\n'), ((405, 429), 'versioneer.get_version', 'versioneer.get_version', ([], {}), '()\n', (427, 429), False, 'import versioneer\n'), ((444, 469), 'versioneer.get_cmdclass', 'versioneer.get_cmdclass', ([], {}), '()\n', (467, 469), False, 'import versioneer\n')] |
from unittest.mock import patch
import slack
from harvey.messages import Message
@patch('harvey.messages.SLACK_CHANNEL', 'mock-channel')
@patch('harvey.messages.SLACK_BOT_TOKEN', '<PASSWORD>')
@patch('logging.Logger.debug')
@patch('slack.WebClient.chat_postMessage')
def test_send_slack_message_success(mock_slack, mock_logger):
message = 'mock message'
Message.send_slack_message(message)
mock_logger.assert_called()
mock_slack.assert_called_once_with(channel='mock-channel', text=message)
@patch('logging.Logger.error')
@patch('sys.exit')
@patch(
'slack.WebClient.chat_postMessage',
side_effect=slack.errors.SlackApiError(
message='The request to the Slack API failed.',
response={
'ok': False,
'error': 'not_authed',
},
),
)
def test_send_slack_message_exception(mock_slack, mock_sys_exit, mock_logger):
message = 'mock message'
Message.send_slack_message(message)
mock_logger.assert_called()
mock_sys_exit.assert_called_once()
| [
"slack.errors.SlackApiError",
"unittest.mock.patch",
"harvey.messages.Message.send_slack_message"
] | [((86, 140), 'unittest.mock.patch', 'patch', (['"""harvey.messages.SLACK_CHANNEL"""', '"""mock-channel"""'], {}), "('harvey.messages.SLACK_CHANNEL', 'mock-channel')\n", (91, 140), False, 'from unittest.mock import patch\n'), ((142, 196), 'unittest.mock.patch', 'patch', (['"""harvey.messages.SLACK_BOT_TOKEN"""', '"""<PASSWORD>"""'], {}), "('harvey.messages.SLACK_BOT_TOKEN', '<PASSWORD>')\n", (147, 196), False, 'from unittest.mock import patch\n'), ((198, 227), 'unittest.mock.patch', 'patch', (['"""logging.Logger.debug"""'], {}), "('logging.Logger.debug')\n", (203, 227), False, 'from unittest.mock import patch\n'), ((229, 270), 'unittest.mock.patch', 'patch', (['"""slack.WebClient.chat_postMessage"""'], {}), "('slack.WebClient.chat_postMessage')\n", (234, 270), False, 'from unittest.mock import patch\n'), ((515, 544), 'unittest.mock.patch', 'patch', (['"""logging.Logger.error"""'], {}), "('logging.Logger.error')\n", (520, 544), False, 'from unittest.mock import patch\n'), ((546, 563), 'unittest.mock.patch', 'patch', (['"""sys.exit"""'], {}), "('sys.exit')\n", (551, 563), False, 'from unittest.mock import patch\n'), ((366, 401), 'harvey.messages.Message.send_slack_message', 'Message.send_slack_message', (['message'], {}), '(message)\n', (392, 401), False, 'from harvey.messages import Message\n'), ((923, 958), 'harvey.messages.Message.send_slack_message', 'Message.send_slack_message', (['message'], {}), '(message)\n', (949, 958), False, 'from harvey.messages import Message\n'), ((628, 753), 'slack.errors.SlackApiError', 'slack.errors.SlackApiError', ([], {'message': '"""The request to the Slack API failed."""', 'response': "{'ok': False, 'error': 'not_authed'}"}), "(message='The request to the Slack API failed.',\n response={'ok': False, 'error': 'not_authed'})\n", (654, 753), False, 'import slack\n')] |
class Vertex:
def __init__(self, left = 0, right = 0):
self.sum = 0
self.left = left
self.right = right
self.left_child = None
self.right_child = None
def extend(self):
if (not self.left_child) and self.left < self.right:
mid = (self.left + self.right) // 2
self.left_child = Vertex(self.left, mid)
self.right_child = Vertex(mid + 1, self.right)
def add(self, k : int, x : int):
self.extend()
self.sum += x
if self.left_child is not None:
if k <= self.left_child.right:
self.left_child.add(k, x)
else:
self.right_child.add(k, x)
def get_sum(self, u : int, v : int):
if u <= self.left and v >= self.right:
return self.sum
if self.right < v and self.left > u:
return 0
self.extend()
sumLeft = 0
sumRight = 0
if self.left_child : sumLeft = self.left_child.get_sum(u, v)
if self.right_child : sumRight = self.right_child.get_sum(u, v)
return sumLeft + sumRight
def printNode(self):
print("range[", self.left, self.right, ']:',self.sum)
if self.left_child:
self.left_child.printNode()
self.right_child.printNode()
Ball = Vertex(0, 17)
import random
result = 0
start = tmp = random.randint(0, 17)
end = 0
while(tmp <= 17):
number = random.randint(0, 100)
result += number
Ball.add(tmp, number)
end = tmp
tmp = random.randint(tmp, 20)
print(Ball.get_sum(start, end) == result) | [
"random.randint"
] | [((1398, 1419), 'random.randint', 'random.randint', (['(0)', '(17)'], {}), '(0, 17)\n', (1412, 1419), False, 'import random\n'), ((1459, 1481), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (1473, 1481), False, 'import random\n'), ((1553, 1576), 'random.randint', 'random.randint', (['tmp', '(20)'], {}), '(tmp, 20)\n', (1567, 1576), False, 'import random\n')] |
from tqdm import tqdm
import pandas as pd
import numpy as np
from pathlib import Path
from hashlib import md5
from sklearn.feature_extraction.text import TfidfVectorizer
from scipy import sparse as sp
import argparse
def break_text(raw):
return np.array([ i for i, t in enumerate(raw) if t == '¶' ][::2])
def main(args):
if args.output.exists():
if not args.overwrite():
raise FileExistsError(f"Output directory {args.output} exists.")
print(f"Output directory {args.output} exists. It will be overwritten.")
args.output.mkdir(exist_ok=True, parents=True)
ds_path = Path(args.dataset)
raw_text = {}
break_idx = {}
for fn in tqdm(list((ds_path / "en").glob("*.txt")), desc='Parsing text'):
fid = fn.name.split("_")[2]
raw = fn.read_text()
idx = break_text(raw)
break_idx[ fid ] = np.array(idx)
for i in range(len(idx)):
t = raw[idx[i]:] if i == len(idx)-1 else raw[idx[i]:idx[i+1]]
raw_text[f"{fid}_{i}"] = t.replace('¶', '').strip()
raw_text = pd.Series(raw_text).sort_index()
rel = {}
for fn in tqdm(list((ds_path / "en").glob("*.ann")), desc='Parsing annotations'):
fid = fn.name.split("_")[2]
for annl in fn.open():
tp, bidx, eidx = annl.strip().split("\t")[1].split(" ")
if len(break_idx[fid]) == 1:
pass_id = 0
else:
pass_id = (break_idx[fid] <= int(bidx)).cumsum()[-1]-1
assert pass_id >= 0
rel[ f"{fid}_{pass_id}", tp ] = True
rel_info = pd.Series(rel).sort_index().unstack(1)\
.join(raw_text.rename('text'), how='right')\
.drop(['text', 'Other', 'Other_language'], axis=1).fillna(False)
rel_info = rel_info.rename_axis('meta_pid')\
.assign(meta_md5=rel_info.index.astype('str').map(lambda x: md5(x.encode()).hexdigest()))\
.reset_index()
assert (raw_text.index == rel_info.meta_pid).all()
X = TfidfVectorizer(sublinear_tf=True, use_idf=False).fit_transform(raw_text)
print("Saving files...")
rel_info.to_pickle( args.output / "rel_info.pkl" )
sp.save_npz( str(args.output / "X_file.npz"), X )
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', type=Path) # '/media/eugene/research/datasets/askfm-cyberbullying-data'
parser.add_argument('--output', type=Path)
parser.add_argument('--overwrite', action='store_true', default=False)
main(parser.parse_args()) | [
"pandas.Series",
"argparse.ArgumentParser",
"pathlib.Path",
"numpy.array",
"sklearn.feature_extraction.text.TfidfVectorizer"
] | [((616, 634), 'pathlib.Path', 'Path', (['args.dataset'], {}), '(args.dataset)\n', (620, 634), False, 'from pathlib import Path\n'), ((2296, 2321), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2319, 2321), False, 'import argparse\n'), ((874, 887), 'numpy.array', 'np.array', (['idx'], {}), '(idx)\n', (882, 887), True, 'import numpy as np\n'), ((1084, 1103), 'pandas.Series', 'pd.Series', (['raw_text'], {}), '(raw_text)\n', (1093, 1103), True, 'import pandas as pd\n'), ((2042, 2091), 'sklearn.feature_extraction.text.TfidfVectorizer', 'TfidfVectorizer', ([], {'sublinear_tf': '(True)', 'use_idf': '(False)'}), '(sublinear_tf=True, use_idf=False)\n', (2057, 2091), False, 'from sklearn.feature_extraction.text import TfidfVectorizer\n'), ((1607, 1621), 'pandas.Series', 'pd.Series', (['rel'], {}), '(rel)\n', (1616, 1621), True, 'import pandas as pd\n')] |
from django.shortcuts import render, get_object_or_404
from .models import Post
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import ListView
from .forms import EmailPostForm, CommentForm
from django.core.mail import send_mail
class PostListView(ListView):
queryset = Post.published.all()
context_object_name = 'posts'
paginate_by = 3
template_name = 'blog/post/list.html'
def post_list(request):
object_list = Post.published.all()
paginator = Paginator(object_list, 3, orphans=2)
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
return render(request,
'blog/post/list.html',
{'page': page,
'posts':posts})
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
comments = post.comments.filter(active=True)
new_comment = None
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()
else:
comment_form = CommentForm()
return render(request,
'blog/post/detail.html',
{'post': post,
'comments': comments,
'comment_form': comment_form,
'new_comment': new_comment})
def post_share(request, post_id):
post = get_object_or_404(Post, id=post_id, status='published')
sent = False
if request.method == 'POST':
form = EmailPostForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
post_url = request.build_absolute_uri(post.get_absolute_url())
subject = '{}({}) zachęca do przeczytania "{}"'.format(cd['name'],
cd['email'],
post.title)
message = 'Przeczytaj post "{}" na stronie {}\n\n\'s Komentarz \
dodany przez {}: {}'.format(post.title,
post_url,
cd['name'],
cd['comments'])
send_mail(subject, message, '<EMAIL>', [cd['to']])
sent = True
else:
form = EmailPostForm()
return render(request, 'blog/post/share.html', {'post': post,
'form': form,
'sent': sent})
| [
"django.shortcuts.render",
"django.shortcuts.get_object_or_404",
"django.core.mail.send_mail",
"django.core.paginator.Paginator"
] | [((524, 560), 'django.core.paginator.Paginator', 'Paginator', (['object_list', '(3)'], {'orphans': '(2)'}), '(object_list, 3, orphans=2)\n', (533, 560), False, 'from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n'), ((790, 860), 'django.shortcuts.render', 'render', (['request', '"""blog/post/list.html"""', "{'page': page, 'posts': posts}"], {}), "(request, 'blog/post/list.html', {'page': page, 'posts': posts})\n", (796, 860), False, 'from django.shortcuts import render, get_object_or_404\n'), ((976, 1094), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['Post'], {'slug': 'post', 'status': '"""published"""', 'publish__year': 'year', 'publish__month': 'month', 'publish__day': 'day'}), "(Post, slug=post, status='published', publish__year=year,\n publish__month=month, publish__day=day)\n", (993, 1094), False, 'from django.shortcuts import render, get_object_or_404\n'), ((1610, 1750), 'django.shortcuts.render', 'render', (['request', '"""blog/post/detail.html"""', "{'post': post, 'comments': comments, 'comment_form': comment_form,\n 'new_comment': new_comment}"], {}), "(request, 'blog/post/detail.html', {'post': post, 'comments':\n comments, 'comment_form': comment_form, 'new_comment': new_comment})\n", (1616, 1750), False, 'from django.shortcuts import render, get_object_or_404\n'), ((1886, 1941), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['Post'], {'id': 'post_id', 'status': '"""published"""'}), "(Post, id=post_id, status='published')\n", (1903, 1941), False, 'from django.shortcuts import render, get_object_or_404\n'), ((2838, 2925), 'django.shortcuts.render', 'render', (['request', '"""blog/post/share.html"""', "{'post': post, 'form': form, 'sent': sent}"], {}), "(request, 'blog/post/share.html', {'post': post, 'form': form, 'sent':\n sent})\n", (2844, 2925), False, 'from django.shortcuts import render, get_object_or_404\n'), ((2711, 2761), 'django.core.mail.send_mail', 'send_mail', (['subject', 'message', '"""<EMAIL>"""', "[cd['to']]"], {}), "(subject, message, '<EMAIL>', [cd['to']])\n", (2720, 2761), False, 'from django.core.mail import send_mail\n')] |
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, logout
from .forms import UserLoginForm
def home_view(request):
context = {'name': 'Dave'}
return render(request, 'home.html',context)
def login_view(request):
form = UserLoginForm(request.POST or None)
next_ = request.GET.get('next')
if form.is_valid():
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username.strip(),
password=password.strip())
login(request, user)
next_post = request.POST.get('next')
redirect_path = next_ or next_post or '/'
return redirect(redirect_path)
return render(request, 'login.html', {'form':form})
def logout_view(request):
logout(request)
return redirect('lista:home') | [
"django.shortcuts.render",
"django.shortcuts.redirect",
"django.contrib.auth.login",
"django.contrib.auth.logout"
] | [((206, 243), 'django.shortcuts.render', 'render', (['request', '"""home.html"""', 'context'], {}), "(request, 'home.html', context)\n", (212, 243), False, 'from django.shortcuts import render, redirect\n'), ((756, 801), 'django.shortcuts.render', 'render', (['request', '"""login.html"""', "{'form': form}"], {}), "(request, 'login.html', {'form': form})\n", (762, 801), False, 'from django.shortcuts import render, redirect\n'), ((832, 847), 'django.contrib.auth.logout', 'logout', (['request'], {}), '(request)\n', (838, 847), False, 'from django.contrib.auth import login, authenticate, logout\n'), ((859, 881), 'django.shortcuts.redirect', 'redirect', (['"""lista:home"""'], {}), "('lista:home')\n", (867, 881), False, 'from django.shortcuts import render, redirect\n'), ((590, 610), 'django.contrib.auth.login', 'login', (['request', 'user'], {}), '(request, user)\n', (595, 610), False, 'from django.contrib.auth import login, authenticate, logout\n'), ((721, 744), 'django.shortcuts.redirect', 'redirect', (['redirect_path'], {}), '(redirect_path)\n', (729, 744), False, 'from django.shortcuts import render, redirect\n')] |
import secrets
def getToken():
return secrets.token_urlsafe(32) | [
"secrets.token_urlsafe"
] | [((43, 68), 'secrets.token_urlsafe', 'secrets.token_urlsafe', (['(32)'], {}), '(32)\n', (64, 68), False, 'import secrets\n')] |
from rx import Observable, Observer
letters = Observable.from_(["tocho", "tochez", "tochisimo", "tochine"])
class MySubscriber(Observer):
def on_next(self, value):
print(value)
def on_completed(self):
print("done")
def on_error(self, error):
print(error)
letters.subscribe(MySubscriber())
# The same for
letters.subscribe(on_next=lambda s: print(s),
on_completed=lambda: print("done"),
on_error=lambda e: print(e)) | [
"rx.Observable.from_"
] | [((47, 108), 'rx.Observable.from_', 'Observable.from_', (["['tocho', 'tochez', 'tochisimo', 'tochine']"], {}), "(['tocho', 'tochez', 'tochisimo', 'tochine'])\n", (63, 108), False, 'from rx import Observable, Observer\n')] |
import json
import logging
import tempfile
import shapely.geometry as sgeo
import shapely.ops as ops
from pyproj.crs import CRS
from pywps import FORMATS, ComplexOutput, LiteralInput, Process
from ravenpy.utilities.analysis import dem_prop
from ravenpy.utilities.checks import boundary_check, single_file_check
from ravenpy.utilities.geo import (
generic_raster_clip,
generic_raster_warp,
generic_vector_reproject,
)
from ravenpy.utilities.io import archive_sniffer, crs_sniffer
from ..utils import gather_dem_tile
from . import wpsio as wio
LOGGER = logging.getLogger("PYWPS")
class TerrainAnalysisProcess(Process):
"""Given a file containing vector data and a DEM, analyze terrain characteristics."""
def __init__(self):
inputs = [
wio.dem_raster,
wio.shape,
LiteralInput(
"projected_crs",
"Coordinate Reference System for terrain analysis (Default: EPSG:6622, 'NAD83(CSRS) /"
" Quebec Lambert'. The CRS chosen should be projected and appropriate for the region"
" of interest.",
data_type="integer",
default=6622,
min_occurs=1,
max_occurs=1,
),
wio.select_all_touching,
]
outputs = [
ComplexOutput(
"properties",
"Feature schemas",
abstract="DEM properties (mean elevation, slope, and aspect) for each geometry.",
supported_formats=[FORMATS.JSON],
),
ComplexOutput(
"dem",
"Subsetted digital elevation model",
abstract="DEM GeoTIFF image",
as_reference=True,
supported_formats=[FORMATS.GEOTIFF, FORMATS.META4],
),
]
super(TerrainAnalysisProcess, self).__init__(
self._handler,
identifier="terrain-analysis",
title="Terrain Analysis",
version="1.0",
abstract="Return shape area in square metres based on line boundaries of a polygonal vector file.",
metadata=[],
inputs=inputs,
outputs=outputs,
status_supported=True,
store_supported=True,
)
def _handler(self, request, response):
# Process inputs
# ---------------
shape_url = request.inputs["shape"][0].file
destination_crs = request.inputs["projected_crs"][0].data
touches = request.inputs["select_all_touching"][0].data
# Checks for valid CRS and that CRS is projected
# -----------------------------------------------
projection = CRS.from_user_input(destination_crs)
if not projection.is_projected:
msg = f"Destination CRS {projection.to_epsg()} is not projected. Terrain analysis values will not be valid."
LOGGER.error(ValueError(msg))
raise ValueError(msg)
# Collect and process the shape
# -----------------------------
vectors = [".gml", ".shp", ".gpkg", ".geojson", ".json"]
vector_file = single_file_check(
archive_sniffer(shape_url, working_dir=self.workdir, extensions=vectors)
)
vec_crs = crs_sniffer(vector_file)
# Check that boundaries within 60N and 60S
boundary_check(vector_file)
if "raster" in request.inputs:
raster_url = request.inputs["raster"][0].file
rasters = [".tiff", ".tif"]
raster_file = single_file_check(
archive_sniffer(
raster_url, working_dir=self.workdir, extensions=rasters
)
)
else:
# Assuming that the shape coordinate are in WGS84
raster_file = gather_dem_tile(vector_file, self.workdir)
ras_crs = crs_sniffer(raster_file)
# Reproject raster
# ----------------
if ras_crs != projection.to_epsg():
msg = f"CRS for {raster_file} is not {projection}. Reprojecting raster..."
LOGGER.warning(msg)
warped_fn = tempfile.NamedTemporaryFile(
prefix="warped_", suffix=".tiff", delete=False, dir=self.workdir
).name
generic_raster_warp(raster_file, warped_fn, projection)
else:
warped_fn = raster_file
# Perform the terrain analysis
# ----------------------------
rpj = tempfile.NamedTemporaryFile(
prefix="reproj_", suffix=".json", delete=False, dir=self.workdir
).name
generic_vector_reproject(
vector_file, rpj, source_crs=vec_crs, target_crs=projection.to_epsg()
)
with open(rpj) as src:
geo = json.load(src)
features = [sgeo.shape(feat["geometry"]) for feat in geo["features"]]
union = ops.unary_union(features)
clipped_fn = tempfile.NamedTemporaryFile(
prefix="clipped_", suffix=".tiff", delete=False, dir=self.workdir
).name
# Ensure that values for regions outside of clip are kept
generic_raster_clip(
raster=warped_fn,
output=clipped_fn,
geometry=union,
touches=touches,
fill_with_nodata=True,
padded=True,
)
# Compute DEM properties for each feature.
properties = []
for i in range(len(features)):
properties.append(
dem_prop(clipped_fn, geom=features[i], directory=self.workdir)
)
properties.append(dem_prop(clipped_fn, directory=self.workdir))
response.outputs["properties"].data = json.dumps(properties)
response.outputs["dem"].file = clipped_fn
return response
| [
"logging.getLogger",
"pywps.LiteralInput",
"pywps.ComplexOutput",
"shapely.ops.unary_union",
"ravenpy.utilities.geo.generic_raster_clip",
"ravenpy.utilities.checks.boundary_check",
"json.dumps",
"ravenpy.utilities.geo.generic_raster_warp",
"ravenpy.utilities.io.archive_sniffer",
"json.load",
"py... | [((566, 592), 'logging.getLogger', 'logging.getLogger', (['"""PYWPS"""'], {}), "('PYWPS')\n", (583, 592), False, 'import logging\n'), ((2735, 2771), 'pyproj.crs.CRS.from_user_input', 'CRS.from_user_input', (['destination_crs'], {}), '(destination_crs)\n', (2754, 2771), False, 'from pyproj.crs import CRS\n'), ((3309, 3333), 'ravenpy.utilities.io.crs_sniffer', 'crs_sniffer', (['vector_file'], {}), '(vector_file)\n', (3320, 3333), False, 'from ravenpy.utilities.io import archive_sniffer, crs_sniffer\n'), ((3394, 3421), 'ravenpy.utilities.checks.boundary_check', 'boundary_check', (['vector_file'], {}), '(vector_file)\n', (3408, 3421), False, 'from ravenpy.utilities.checks import boundary_check, single_file_check\n'), ((3912, 3936), 'ravenpy.utilities.io.crs_sniffer', 'crs_sniffer', (['raster_file'], {}), '(raster_file)\n', (3923, 3936), False, 'from ravenpy.utilities.io import archive_sniffer, crs_sniffer\n'), ((4926, 4951), 'shapely.ops.unary_union', 'ops.unary_union', (['features'], {}), '(features)\n', (4941, 4951), True, 'import shapely.ops as ops\n'), ((5170, 5299), 'ravenpy.utilities.geo.generic_raster_clip', 'generic_raster_clip', ([], {'raster': 'warped_fn', 'output': 'clipped_fn', 'geometry': 'union', 'touches': 'touches', 'fill_with_nodata': '(True)', 'padded': '(True)'}), '(raster=warped_fn, output=clipped_fn, geometry=union,\n touches=touches, fill_with_nodata=True, padded=True)\n', (5189, 5299), False, 'from ravenpy.utilities.geo import generic_raster_clip, generic_raster_warp, generic_vector_reproject\n'), ((5737, 5759), 'json.dumps', 'json.dumps', (['properties'], {}), '(properties)\n', (5747, 5759), False, 'import json\n'), ((831, 1116), 'pywps.LiteralInput', 'LiteralInput', (['"""projected_crs"""', '"""Coordinate Reference System for terrain analysis (Default: EPSG:6622, \'NAD83(CSRS) / Quebec Lambert\'. The CRS chosen should be projected and appropriate for the region of interest."""'], {'data_type': '"""integer"""', 'default': '(6622)', 'min_occurs': '(1)', 'max_occurs': '(1)'}), '(\'projected_crs\',\n "Coordinate Reference System for terrain analysis (Default: EPSG:6622, \'NAD83(CSRS) / Quebec Lambert\'. The CRS chosen should be projected and appropriate for the region of interest."\n , data_type=\'integer\', default=6622, min_occurs=1, max_occurs=1)\n', (843, 1116), False, 'from pywps import FORMATS, ComplexOutput, LiteralInput, Process\n'), ((1338, 1509), 'pywps.ComplexOutput', 'ComplexOutput', (['"""properties"""', '"""Feature schemas"""'], {'abstract': '"""DEM properties (mean elevation, slope, and aspect) for each geometry."""', 'supported_formats': '[FORMATS.JSON]'}), "('properties', 'Feature schemas', abstract=\n 'DEM properties (mean elevation, slope, and aspect) for each geometry.',\n supported_formats=[FORMATS.JSON])\n", (1351, 1509), False, 'from pywps import FORMATS, ComplexOutput, LiteralInput, Process\n'), ((1593, 1761), 'pywps.ComplexOutput', 'ComplexOutput', (['"""dem"""', '"""Subsetted digital elevation model"""'], {'abstract': '"""DEM GeoTIFF image"""', 'as_reference': '(True)', 'supported_formats': '[FORMATS.GEOTIFF, FORMATS.META4]'}), "('dem', 'Subsetted digital elevation model', abstract=\n 'DEM GeoTIFF image', as_reference=True, supported_formats=[FORMATS.\n GEOTIFF, FORMATS.META4])\n", (1606, 1761), False, 'from pywps import FORMATS, ComplexOutput, LiteralInput, Process\n'), ((3208, 3280), 'ravenpy.utilities.io.archive_sniffer', 'archive_sniffer', (['shape_url'], {'working_dir': 'self.workdir', 'extensions': 'vectors'}), '(shape_url, working_dir=self.workdir, extensions=vectors)\n', (3223, 3280), False, 'from ravenpy.utilities.io import archive_sniffer, crs_sniffer\n'), ((4320, 4375), 'ravenpy.utilities.geo.generic_raster_warp', 'generic_raster_warp', (['raster_file', 'warped_fn', 'projection'], {}), '(raster_file, warped_fn, projection)\n', (4339, 4375), False, 'from ravenpy.utilities.geo import generic_raster_clip, generic_raster_warp, generic_vector_reproject\n'), ((4520, 4617), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'prefix': '"""reproj_"""', 'suffix': '""".json"""', 'delete': '(False)', 'dir': 'self.workdir'}), "(prefix='reproj_', suffix='.json', delete=False,\n dir=self.workdir)\n", (4547, 4617), False, 'import tempfile\n'), ((4816, 4830), 'json.load', 'json.load', (['src'], {}), '(src)\n', (4825, 4830), False, 'import json\n'), ((4852, 4880), 'shapely.geometry.shape', 'sgeo.shape', (["feat['geometry']"], {}), "(feat['geometry'])\n", (4862, 4880), True, 'import shapely.geometry as sgeo\n'), ((4974, 5072), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'prefix': '"""clipped_"""', 'suffix': '""".tiff"""', 'delete': '(False)', 'dir': 'self.workdir'}), "(prefix='clipped_', suffix='.tiff', delete=False,\n dir=self.workdir)\n", (5001, 5072), False, 'import tempfile\n'), ((5644, 5688), 'ravenpy.utilities.analysis.dem_prop', 'dem_prop', (['clipped_fn'], {'directory': 'self.workdir'}), '(clipped_fn, directory=self.workdir)\n', (5652, 5688), False, 'from ravenpy.utilities.analysis import dem_prop\n'), ((3621, 3694), 'ravenpy.utilities.io.archive_sniffer', 'archive_sniffer', (['raster_url'], {'working_dir': 'self.workdir', 'extensions': 'rasters'}), '(raster_url, working_dir=self.workdir, extensions=rasters)\n', (3636, 3694), False, 'from ravenpy.utilities.io import archive_sniffer, crs_sniffer\n'), ((4179, 4276), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'prefix': '"""warped_"""', 'suffix': '""".tiff"""', 'delete': '(False)', 'dir': 'self.workdir'}), "(prefix='warped_', suffix='.tiff', delete=False,\n dir=self.workdir)\n", (4206, 4276), False, 'import tempfile\n'), ((5541, 5603), 'ravenpy.utilities.analysis.dem_prop', 'dem_prop', (['clipped_fn'], {'geom': 'features[i]', 'directory': 'self.workdir'}), '(clipped_fn, geom=features[i], directory=self.workdir)\n', (5549, 5603), False, 'from ravenpy.utilities.analysis import dem_prop\n')] |
"""A module for testing Coding DNA DelIns tokenization."""
import unittest
from variation.tokenizers.caches import AminoAcidCache, NucleotideCache
from variation.tokenizers import CodingDNADelIns
from .tokenizer_base import TokenizerBase
class TestCodingDNADelInsTokenizer(TokenizerBase, unittest.TestCase):
"""A class for testing Coding DNA DelIns Tokenization."""
def tokenizer_instance(self):
"""Return Coding DNA DelIns instance."""
return CodingDNADelIns(AminoAcidCache(), NucleotideCache())
def token_type(self):
"""Return DNA coding delins token type."""
return "CodingDNADelIns"
def fixture_name(self):
"""Return the fixture name for DNA coding delins."""
return "coding_dna_delins"
| [
"variation.tokenizers.caches.NucleotideCache",
"variation.tokenizers.caches.AminoAcidCache"
] | [((488, 504), 'variation.tokenizers.caches.AminoAcidCache', 'AminoAcidCache', ([], {}), '()\n', (502, 504), False, 'from variation.tokenizers.caches import AminoAcidCache, NucleotideCache\n'), ((506, 523), 'variation.tokenizers.caches.NucleotideCache', 'NucleotideCache', ([], {}), '()\n', (521, 523), False, 'from variation.tokenizers.caches import AminoAcidCache, NucleotideCache\n')] |
# -*- coding: utf-8 -*-
import uuid
import unittest
import logging
from __init__ import LogTrace
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
s = [98, 127, 133, 147, 170, 197, 201, 211, 255]
class TestLogTrace(unittest.TestCase):
def test_logtrace_simple(self):
trace = LogTrace(logger, unique_id=True, verbosity='v')
trace.add("first message")
trace.add("second message")
print(trace.emit_string())
trace.emit("finally")
def test_logtrace_unique_id(self):
trace = LogTrace(logger=logger, unique_id=True, level=logging.INFO, verbosity='vvv')
trace.add("first message")
trace.add("second message")
print(trace.emit_string())
def test_function(self):
trace = LogTrace(logger=logger, level=logging.INFO)
standard_deviation(s, trace=trace)
print(trace.emit_string())
def test_function_tag(self):
trace = LogTrace(logger=logger, tag='STDDEV', level=logging.INFO, verbosity='vv')
standard_deviation(s, trace=trace)
print(trace.emit_string())
def test_logtrace_uuid(self):
trace = LogTrace(logger, unique_id=True, level=logging.INFO)
trace.add("first message")
trace.add("second message")
print(trace.get_uid())
trace.set_uid(uuid.uuid4())
trace.set_uid(str(uuid.uuid4())) # could be a string
trace.emit("finally")
def test_unicode(self):
trace = LogTrace(logger)
s = "ƀ Ɓ Ƃ ƃ Ƅ ƅ Ɔ Ƈ ƈ Ɖ Ɗ Ƌ ƌ ƍ Ǝ Ə Ɛ Ƒ ƒ Ɠ Ɣ ƕ Ɩ Ɨ Ƙ ƙ ƚ ƛ Ɯ Ɲ ƞ Ɵ Ơ ơ Ƣ ƣ Ƥ ƥ Ʀ Ƨ ƨ Ʃ ƪ ƫ Ƭ ƭ Ʈ Ư ư Ʊ Ʋ Ƴ ƴ Ƶ ƶ Ʒ Ƹ ƹ ƺ ƻ Ƽ ƽ ƾ ƿ ǀ ǁ ǂ ǃ DŽ Dž dž LJ Lj lj NJ Nj nj Ǎ ǎ Ǐ ǐ Ǒ ǒ Ǔ ǔ Ǖ ǖ Ǘ ǘ Ǚ ǚ Ǜ ǜ ǝ Ǟ ǟ Ǡ ǡ Ǣ ǣ Ǥ ǥ Ǧ ǧ Ǩ ǩ Ǫ ǫ Ǭ ǭ Ǯ ǯ ǰ DZ Dz dz Ǵ ǵ Ǻ ǻ Ǽ ǽ Ǿ ǿ Ȁ ȁ Ȃ ȃ"
trace.add(s)
print(trace.emit_string())
def test_extra(self):
trace = LogTrace(logger)
trace.emit('finish', extra={'key': 'value'})
def standard_deviation(lst, population=True, trace=None):
"""Calculates the standard deviation for a list of numbers.
Just for testing LogTrace().
"""
num_items = len(lst)
trace.add('num_items={}'.format(num_items))
mean = sum(lst) / num_items
trace.add('mean={}'.format(mean))
differences = [x - mean for x in lst]
sq_differences = [d ** 2 for d in differences]
ssd = sum(sq_differences)
trace.add('ssd={}'.format(ssd))
trace.add('population={}'.format(population))
if population:
variance = ssd / num_items
trace.add('variance={}'.format(variance))
return variance
else:
variance = ssd / (num_items - 1)
sd = sqrt(variance)
trace.add('sd={}'.format(sd))
return sd
if __name__ == '__main__':
unittest.main()
| [
"logging.basicConfig",
"logging.getLogger",
"uuid.uuid4",
"__init__.LogTrace",
"unittest.main"
] | [((98, 221), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(asctime)s %(levelname)-8s %(message)s"""', 'datefmt': '"""%Y-%m-%d %H:%M:%S"""'}), "(level=logging.INFO, format=\n '%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')\n", (117, 221), False, 'import logging\n'), ((267, 294), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (284, 294), False, 'import logging\n'), ((2911, 2926), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2924, 2926), False, 'import unittest\n'), ((467, 514), '__init__.LogTrace', 'LogTrace', (['logger'], {'unique_id': '(True)', 'verbosity': '"""v"""'}), "(logger, unique_id=True, verbosity='v')\n", (475, 514), False, 'from __init__ import LogTrace\n'), ((707, 783), '__init__.LogTrace', 'LogTrace', ([], {'logger': 'logger', 'unique_id': '(True)', 'level': 'logging.INFO', 'verbosity': '"""vvv"""'}), "(logger=logger, unique_id=True, level=logging.INFO, verbosity='vvv')\n", (715, 783), False, 'from __init__ import LogTrace\n'), ((936, 979), '__init__.LogTrace', 'LogTrace', ([], {'logger': 'logger', 'level': 'logging.INFO'}), '(logger=logger, level=logging.INFO)\n', (944, 979), False, 'from __init__ import LogTrace\n'), ((1108, 1181), '__init__.LogTrace', 'LogTrace', ([], {'logger': 'logger', 'tag': '"""STDDEV"""', 'level': 'logging.INFO', 'verbosity': '"""vv"""'}), "(logger=logger, tag='STDDEV', level=logging.INFO, verbosity='vv')\n", (1116, 1181), False, 'from __init__ import LogTrace\n'), ((1311, 1363), '__init__.LogTrace', 'LogTrace', (['logger'], {'unique_id': '(True)', 'level': 'logging.INFO'}), '(logger, unique_id=True, level=logging.INFO)\n', (1319, 1363), False, 'from __init__ import LogTrace\n'), ((1639, 1655), '__init__.LogTrace', 'LogTrace', (['logger'], {}), '(logger)\n', (1647, 1655), False, 'from __init__ import LogTrace\n'), ((2025, 2041), '__init__.LogTrace', 'LogTrace', (['logger'], {}), '(logger)\n', (2033, 2041), False, 'from __init__ import LogTrace\n'), ((1488, 1500), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (1498, 1500), False, 'import uuid\n'), ((1528, 1540), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (1538, 1540), False, 'import uuid\n')] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('silver', '0044_auto_20171115_1809'),
]
operations = [
migrations.AlterField(
model_name='customer',
name='city',
field=models.CharField(max_length=128, null=True, blank=True),
),
migrations.AlterField(
model_name='customer',
name='last_name',
field=models.CharField(help_text=b"The customer's last name.", max_length=128, null=True, blank=True),
),
migrations.AlterField(
model_name='paymentmethod',
name='payment_processor',
field=models.CharField(max_length=256, choices=[(b'manual', b'manual')]),
),
migrations.AlterField(
model_name='provider',
name='city',
field=models.CharField(max_length=128, null=True, blank=True),
),
]
| [
"django.db.models.CharField"
] | [((351, 406), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(128)', 'null': '(True)', 'blank': '(True)'}), '(max_length=128, null=True, blank=True)\n', (367, 406), False, 'from django.db import migrations, models\n'), ((533, 632), 'django.db.models.CharField', 'models.CharField', ([], {'help_text': 'b"The customer\'s last name."', 'max_length': '(128)', 'null': '(True)', 'blank': '(True)'}), '(help_text=b"The customer\'s last name.", max_length=128,\n null=True, blank=True)\n', (549, 632), False, 'from django.db import migrations, models\n'), ((768, 834), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(256)', 'choices': "[(b'manual', b'manual')]"}), "(max_length=256, choices=[(b'manual', b'manual')])\n", (784, 834), False, 'from django.db import migrations, models\n'), ((956, 1011), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(128)', 'null': '(True)', 'blank': '(True)'}), '(max_length=128, null=True, blank=True)\n', (972, 1011), False, 'from django.db import migrations, models\n')] |
import os
from plugins import gf
users_dir = os.path.join(r"users/")
def profiles(sourceText, id):
get_data = gf.loadjson(users_dir + str(id) + ".json")
own_housing = int(get_data['own_housing'])
own_car = int(get_data['own_car'])
own_yacht = int(get_data['own_yacht'])
own_air = int(get_data['own_air'])
own_helicopter = int(get_data['own_helicopter'])
own_comp = int(get_data['own_comp'])
own_smart = int(get_data['own_smart'])
own_farm = int(get_data['own_farm'])
profile = ', ваш профиль:\n\n⭐ Основное:\n⠀⠀👤 ' + '@id{}'.format(id) + '(' + str(get_data['first_name']) + ' ' + str(get_data['last_name']) + ')' + '\n⠀⠀🔎 ID: ' + str(get_data['id']) + '\n⠀⠀' + str(gf.check_group(id)) + '\n⠀⠀💰 В кошельке: ' + str(get_data['balance']) + '€\n⠀⠀🎮 Ник: ' + str(gf.check_nick(id)) + str(gf.check_own_profile(id)) + str(gf.check_own_housing(own_housing)) + str(gf.check_own_car(own_car)) + str(gf.check_own_yacht(own_yacht)) + str(gf.check_own_air(own_air)) + str(gf.check_own_helicopter(own_helicopter)) + str(gf.check_own_comp(own_comp)) + str(gf.check_own_smart(own_smart)) + str(gf.check_own_farm(own_farm)) + '\n\n Дата Регистрации: ' + str(get_data['data_reg'])
if sourceText.split()[0].lower() in ['профиль', '📒']:
return profile
else:
return None | [
"plugins.gf.check_own_profile",
"plugins.gf.check_nick",
"plugins.gf.check_own_car",
"plugins.gf.check_group",
"os.path.join",
"plugins.gf.check_own_air",
"plugins.gf.check_own_comp",
"plugins.gf.check_own_yacht",
"plugins.gf.check_own_farm",
"plugins.gf.check_own_housing",
"plugins.gf.check_own... | [((49, 71), 'os.path.join', 'os.path.join', (['"""users/"""'], {}), "('users/')\n", (61, 71), False, 'import os\n'), ((1207, 1234), 'plugins.gf.check_own_farm', 'gf.check_own_farm', (['own_farm'], {}), '(own_farm)\n', (1224, 1234), False, 'from plugins import gf\n'), ((1170, 1199), 'plugins.gf.check_own_smart', 'gf.check_own_smart', (['own_smart'], {}), '(own_smart)\n', (1188, 1199), False, 'from plugins import gf\n'), ((1135, 1162), 'plugins.gf.check_own_comp', 'gf.check_own_comp', (['own_comp'], {}), '(own_comp)\n', (1152, 1162), False, 'from plugins import gf\n'), ((1088, 1127), 'plugins.gf.check_own_helicopter', 'gf.check_own_helicopter', (['own_helicopter'], {}), '(own_helicopter)\n', (1111, 1127), False, 'from plugins import gf\n'), ((1055, 1080), 'plugins.gf.check_own_air', 'gf.check_own_air', (['own_air'], {}), '(own_air)\n', (1071, 1080), False, 'from plugins import gf\n'), ((1018, 1047), 'plugins.gf.check_own_yacht', 'gf.check_own_yacht', (['own_yacht'], {}), '(own_yacht)\n', (1036, 1047), False, 'from plugins import gf\n'), ((985, 1010), 'plugins.gf.check_own_car', 'gf.check_own_car', (['own_car'], {}), '(own_car)\n', (1001, 1010), False, 'from plugins import gf\n'), ((944, 977), 'plugins.gf.check_own_housing', 'gf.check_own_housing', (['own_housing'], {}), '(own_housing)\n', (964, 977), False, 'from plugins import gf\n'), ((912, 936), 'plugins.gf.check_own_profile', 'gf.check_own_profile', (['id'], {}), '(id)\n', (932, 936), False, 'from plugins import gf\n'), ((887, 904), 'plugins.gf.check_nick', 'gf.check_nick', (['id'], {}), '(id)\n', (900, 904), False, 'from plugins import gf\n'), ((765, 783), 'plugins.gf.check_group', 'gf.check_group', (['id'], {}), '(id)\n', (779, 783), False, 'from plugins import gf\n')] |
#!/usr/bin/env python
# encoding: utf-8
####### todo:
# reverse compliment #
### input fasta file
### input gRNA.bed, design file
### output count number for next step.
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL)
from sys import stdin, stderr
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-f1', dest='flank1', help="left flank of sgRNAseq, before rc")
parser.add_argument('-f2', dest='flank2', help="right flank of sgRNAseq, before rc")
parser.add_argument('-R', dest='rc', default="0", help="reverse compliment mode, 0: only input; 1: rc; this is useful for sgRNA2 when the input fastq files are paired reads.")
parser.add_argument('-H', dest='hasHeader', default=True, help="oligo file has header")
parser.add_argument('-i', dest='oligo', help="input oligo design file. Use the following fields as default: chrm, start, end, sgRNAid, barcode, set, sgRNA, [sgRNA2 if pair reads]; if user provides a non-conventional oligo design file, minimally it should contain sgRNAid and sgRNAseq, and -G and -B should be used to indicate which columns (the column index starts with 0) sgRNAid and sgRNAseq are in the -i input file. eg. -i 'myOligo.tsv' -G 0 -S 1")
parser.add_argument('-I', dest='sgRNAid', default="3", help="column index of sgRNAid in the input oligo design file, index starts with 0. default to 3.")
parser.add_argument('-E', dest='exact', default=True, help="if pattern resulted in exact read match.")
parser.add_argument('-S', dest='sgRNAseq', default="6", help="column index of sgRNAseq in the input oligo design file, index starts with 0. default to 6 for single reads, specified to 7 for usage of sgRNA2.")
args = parser.parse_args()
flank1 = args.flank1.upper()
flank2 = args.flank2.upper()
inFile = args.oligo
rc = str(args.rc)
idx_sgRNAid = int(args.sgRNAid)
idx_sgRNAseq = int(args.sgRNAseq)
hasHeader = bool(args.hasHeader)
exact = bool(args.exact)
###
# reverse compliment
def func_rc(seq):
string = seq.upper()
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}
return "".join([complement.get(base, base) for base in reversed(seq)])
### 1. build gRNA profile
#inFile = "gRNA.bed"
gid2bar = {}
gids = []
with open(inFile) as f:
if hasHeader:
header = f.readline()
else:
pass
for l in f.readlines():
ls = l.strip().split()
gid, sgRNAseq = ls[idx_sgRNAid], ls[idx_sgRNAseq]
gids.append(gid)
sgRNAseq = sgRNAseq.upper()
if rc == "1":
gid2bar[gid] = func_rc(sgRNAseq)
else:
gid2bar[gid] = sgRNAseq
sgRNAseqs = set(gid2bar.values())
totalSgRNA = len(sgRNAseqs)
blens = [len(sgRNAseq) for sgRNAseq in sgRNAseqs]
maxbl, minbl = max(blens), min(blens)
### 2. compile regex
import re
if rc == "0":
pattern = flank1 + "([ACGT]{" + str(minbl) + "," + str(maxbl) + "})" + flank2
if rc == "1":
pattern = func_rc(flank2) + "([ACGT]{" + str(minbl) + "," + str(maxbl) + "})" + func_rc(flank1)
stderr.write("using pattern = " + pattern + "\n")
prog = re.compile(pattern)
### 3. search for sgRNA pattern that matches
hits = []
hitc = 0
readc = 0
for seq in stdin.readlines():
readc += 1
seq = seq.upper()
hit = prog.search(seq)
# this step that act like a fuzzy match improves runtime
if hit:
#stderr.write(hit + "\n")
match = hit.group()
matchSeq = match[len(flank1):len(match)-len(flank2)]
hitc += 1
# this step checks if the sequence is actually in the original gRNA design
if exact: # very fast
if matchSeq in sgRNAseqs:
if rc == "1":
matchSeq = func_rc(matchSeq)
hits.append(matchSeq)
else: # very slow
for sgRNAseq in sgRNAseqs:
if sgRNAseq in matchSeq:
hits.append(sgRNAseq)
continue
#stderr.write(sgRNAseq + "\n")
### count
from collections import Counter
hitCounts = Counter(hits)
matchedSgRNA = len(hitCounts)
#print(hitCounts)
### print
#if rc == "1":
# for gid in gids:
# sgRNAseq = gid2bar[gid]
# if func_rc(sgRNAseq) in hitCounts:
# print("\t".join([gid, str(hitCounts[func_rc(sgRNAseq)])]))
#elif rc == "0":
# for gid in gids:
# sgRNAseq = gid2bar[gid]
# if sgRNAseq in hitCounts:
# print("\t".join([gid, str(hitCounts[sgRNAseq])]))
#else:
# print("rc mode unknown, exit")
# exit
for gid in gids:
sgRNAseq = gid2bar[gid]
if rc=="1":
sgRNAseq = func_rc(sgRNAseq)
hitVal = hitCounts.get(sgRNAseq, 0)
hitStr = str(hitVal)
print("\t".join([gid, hitStr]))
stderr.write("total read count: " + str(readc)+"\n")
stderr.write("total read match (pattern): " + str(hitc)+"\n")
stderr.write("total exact match (sgRNA): " + str(len(hits))+"\n")
stderr.write("sgRNA with matches: {} / {}".format(matchedSgRNA, totalSgRNA) + "\n")
| [
"signal.signal",
"argparse.ArgumentParser",
"re.compile",
"sys.stdin.readlines",
"collections.Counter",
"sys.stderr.write"
] | [((218, 242), 'signal.signal', 'signal', (['SIGPIPE', 'SIG_DFL'], {}), '(SIGPIPE, SIG_DFL)\n', (224, 242), False, 'from signal import signal, SIGPIPE, SIG_DFL\n'), ((297, 322), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (320, 322), False, 'import argparse\n'), ((2893, 2942), 'sys.stderr.write', 'stderr.write', (["('using pattern = ' + pattern + '\\n')"], {}), "('using pattern = ' + pattern + '\\n')\n", (2905, 2942), False, 'from sys import stdin, stderr\n'), ((2950, 2969), 're.compile', 're.compile', (['pattern'], {}), '(pattern)\n', (2960, 2969), False, 'import re\n'), ((3057, 3074), 'sys.stdin.readlines', 'stdin.readlines', ([], {}), '()\n', (3072, 3074), False, 'from sys import stdin, stderr\n'), ((3732, 3745), 'collections.Counter', 'Counter', (['hits'], {}), '(hits)\n', (3739, 3745), False, 'from collections import Counter\n')] |
from django.urls import include, path
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register("owners", views.OwnerViewSet)
router.register("accounts", views.AccountViewSet)
router.register("payments", views.PaymentViewSet)
urlpatterns = [
path("", include(router.urls)),
]
| [
"rest_framework.routers.DefaultRouter",
"django.urls.include"
] | [((106, 129), 'rest_framework.routers.DefaultRouter', 'routers.DefaultRouter', ([], {}), '()\n', (127, 129), False, 'from rest_framework import routers\n'), ((307, 327), 'django.urls.include', 'include', (['router.urls'], {}), '(router.urls)\n', (314, 327), False, 'from django.urls import include, path\n')] |
"""Test the graphical display of a CodeBlock."""
import time
from concurrent.futures import ThreadPoolExecutor
import cocos
from shimmer.programmable.code_block import (
CodeBlockDisplay,
CodeBlock,
CodeBlockDisplayDefinition,
)
from shimmer.programmable.logic.definition import Instruction
def test_code_block_display(run_gui, dummy_code_block):
"""Code block should be shown."""
layer = CodeBlockDisplay(dummy_code_block, CodeBlockDisplayDefinition())
assert run_gui(test_code_block_display, layer)
def test_code_block_display_on_loop(run_gui):
"""Code block with instructions being run sequentially should be shown."""
def wait_1():
"""An dummy instruction method that takes a while to run."""
time.sleep(0.5)
code_block = CodeBlock(instructions=[Instruction(method=wait_1) for _ in range(3)])
def loop_code_block(_code_block: CodeBlock) -> None:
"""Run the instruction repeatedly with a sleep in between."""
while not cocos.director.director.terminate_app:
_code_block.run()
time.sleep(0.5)
layer = CodeBlockDisplay(code_block, CodeBlockDisplayDefinition())
with ThreadPoolExecutor() as executor:
# Start the loop in a thread because `run_gui` blocks.
executor.submit(loop_code_block, code_block)
assert run_gui(test_code_block_display_on_loop, layer)
| [
"shimmer.programmable.code_block.CodeBlockDisplayDefinition",
"shimmer.programmable.logic.definition.Instruction",
"concurrent.futures.ThreadPoolExecutor",
"time.sleep"
] | [((448, 476), 'shimmer.programmable.code_block.CodeBlockDisplayDefinition', 'CodeBlockDisplayDefinition', ([], {}), '()\n', (474, 476), False, 'from shimmer.programmable.code_block import CodeBlockDisplay, CodeBlock, CodeBlockDisplayDefinition\n'), ((752, 767), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (762, 767), False, 'import time\n'), ((1142, 1170), 'shimmer.programmable.code_block.CodeBlockDisplayDefinition', 'CodeBlockDisplayDefinition', ([], {}), '()\n', (1168, 1170), False, 'from shimmer.programmable.code_block import CodeBlockDisplay, CodeBlock, CodeBlockDisplayDefinition\n'), ((1182, 1202), 'concurrent.futures.ThreadPoolExecutor', 'ThreadPoolExecutor', ([], {}), '()\n', (1200, 1202), False, 'from concurrent.futures import ThreadPoolExecutor\n'), ((1084, 1099), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (1094, 1099), False, 'import time\n'), ((810, 836), 'shimmer.programmable.logic.definition.Instruction', 'Instruction', ([], {'method': 'wait_1'}), '(method=wait_1)\n', (821, 836), False, 'from shimmer.programmable.logic.definition import Instruction\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File: software/utils/loop.py
# By: <NAME>
# For: Myself
# Description: This file implements the main loop for object detection with OpenCV.
IS_ARDUCAM = False
if IS_ARDUCAM:
from utils_arducam import ArducamUtils
from utils.inference import ObjectCenter
from copy import deepcopy
import cv2, time
# gstreamer_pipeline returns a GStreamer pipeline for capturing from the CSI camera
# Defaults to 1280x720 @ 60fps
# Flip the image by setting the flip_method (most common values: 0 and 2)
# display_width and display_height determine the size of the window on the screen
def gstreamer_pipeline(
capture_width=3820,
capture_height=2464,
display_width=960,
display_height=616,
framerate=21,
flip_method=0,
):
#return (
# "nvarguscamerasrc ! "
# "video/x-raw(memory:NVMM), "
# "width=(int)%d, height=(int)%d, "
# "format=(string)NV12, framerate=(fraction)%d/1 ! "
# "nvvidconv flip-method=%d ! "
# "video/x-raw, width=(int)%d, height=(int)%d, format=(string)BGRx ! "
# "videoconvert ! "
# "video/x-raw, format=(string)BGR ! appsink"
# % (
# capture_width,
# capture_height,
# framerate,
# flip_method,
# display_width,
# display_height,
# )
#return (
# #'nvarguscamerasrc ! video/x-raw(memory:NVMM), width=3280, height=2464, format=(string)NV12, framerate=21/1 ! nvvidconv flip-method=0 ! video/x-raw, width=960, height=616, format=(string)BGRx ! videoconvert ! video/x-raw, format=(string)BGR ! appsink wait-on-eos=false max-buffers=1 drop=True'
# 'nvarguscamerasrc ! video/x-raw(memory:NVMM), width=3820, height=2464, format=(string)NV12, framerate=21/1 ! nvvidconv flip-method=0 ! video/x-raw, width=960, height=616, format=(string)BGRx ! videoconvert ! video/x-raw, format=(string)BGR ! appsink wait-on-eos=false max-buffers=1 drop=True'
#)
return 'nvarguscamerasrc wbmode=3 tnr-mode=2 tnr-strength=1 ee-mode=2 ee-strength=1 ! video/x-raw(memory:NVMM), width=3264, height=2464, format=NV12, framerate=21/1 ! nvvidconv flip-method=0 ! video/x-raw, width=960, height=616, format=BGRx ! videoconvert ! video/x-raw, format=BGR ! videobalance contrast=1.5 brightness=-.2 saturation=1.2 ! appsink'
def loop(args, object_x=None, object_y=None, center_x=None, center_y=None):
"""Detection loop."""
arducam_utils = None
obj = ObjectCenter(args)
# Read input.
if args.input_type == 'image':
image = cv2.imread(args.image)
elif args.input_type == 'video':
cap = cv2.VideoCapture(args.video)
elif args.input_type == 'arducam':
# Open camera.
cap = cv2.VideoCapture(source, cv2.CAP_V4L2)
# Set pixel format.
if not cap.set(cv2.CAP_PROP_FOURCC, pixelformat):
print('Failed to set pixel format.')
arducam_utils = ArducamUtils(source)
show_info(arducam_utils)
# Turn off RGB conversion.
if arducam_utils.convert2rgb == 0:
cap.set(cv2.CAP_PROP_CONVERT_RGB, arducam_utils.convert2rgb)
# Set width.
if args.width != None:
cap.set(cv2.CAP_PROP_FRAME_WIDTH, args.width)
# Set height.
if args.height != None:
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, args.height)
elif args.input_type == 'camera':
if args.is_rpi_cam:
# To flip the image, modify the flip_method parameter (0 and 2 are the most common)
print(gstreamer_pipeline(flip_method=0))
cap = cv2.VideoCapture(gstreamer_pipeline(flip_method=0), cv2.CAP_GSTREAMER)
else:
cap = cv2.VideoCapture(0)
if not cap.isOpened():
raise SystemExit('ERROR: failed to open camera!')
# Prepare arguments early.
show = not args.no_show
(height, width) = args.image_shape
full_scrn = False
fps = 0.0
if show:
from utils.display import open_window, set_display, show_fps
open_window(args.video_name, 'Camera inference', width, height)
else:
out = cv2.VideoWriter(args.video_name, cv2.VideoWriter_fourcc(*'mp4v'), 30, (width, height))
tic = time.time()
try:
# Loop through frames.
while True:
if not (args.input_type == 'image' or cap.isOpened()):
break
# Read frame from video/camera.
if args.input_type == 'image':
frame = deepcopy(image)
elif cap.isOpened():
status, frame = cap.read()
if frame is None:
status, frame = cap.read()
if not status:
break
if frame is not None:
frame = obj.infer(frame,
object_x=object_x,
object_y=object_y,
center_x=center_x,
center_y=center_y)
if show and frame is not None:
frame = show_fps(frame, fps)
if arducam_utils is not None:
if arducam_utils.convert2rgb == 0:
w = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
frame = frame.reshape(int(h), int(w))
frame = arducam_utils.convert(frame)
if frame is not None:
# Show raw inference results.
cv2.imshow(args.video_name, frame)
else:
print('FPS:', fps)
if args.save:
# Save output.
cv2.imwrite('object_detection_result.jpg', inferred_image)
# Calculate an exponentially decaying average of FPS number.
toc = time.time()
curr_fps = 1.0 / (toc - tic)
fps = curr_fps if fps == 0.0 else (fps * 0.95 + curr_fps * 0.05)
tic = toc
# Catch keyboard input.
key = cv2.waitKey(1)
# ESC key: quit program.
if key == 27:
break
# Toggle fullscreen.
elif show and (key == ord('F') or key == ord('f')):
full_scrn = not full_scrn
set_display(args.video_name, full_scrn)
finally:
# Release resources.
if args.input_type != 'image':
cap.release()
cv2.destroyAllWindows()
| [
"utils.inference.ObjectCenter",
"cv2.imwrite",
"copy.deepcopy",
"cv2.imshow",
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.VideoWriter_fourcc",
"utils_arducam.ArducamUtils",
"utils.display.set_display",
"utils.display.show_fps",
"time.time",
"utils.display.open_window",
... | [((2502, 2520), 'utils.inference.ObjectCenter', 'ObjectCenter', (['args'], {}), '(args)\n', (2514, 2520), False, 'from utils.inference import ObjectCenter\n'), ((4262, 4273), 'time.time', 'time.time', ([], {}), '()\n', (4271, 4273), False, 'import cv2, time\n'), ((2591, 2613), 'cv2.imread', 'cv2.imread', (['args.image'], {}), '(args.image)\n', (2601, 2613), False, 'import cv2, time\n'), ((4075, 4138), 'utils.display.open_window', 'open_window', (['args.video_name', '"""Camera inference"""', 'width', 'height'], {}), "(args.video_name, 'Camera inference', width, height)\n", (4086, 4138), False, 'from utils.display import open_window, set_display, show_fps\n'), ((6541, 6564), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (6562, 6564), False, 'import cv2, time\n'), ((2666, 2694), 'cv2.VideoCapture', 'cv2.VideoCapture', (['args.video'], {}), '(args.video)\n', (2682, 2694), False, 'import cv2, time\n'), ((4197, 4228), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'mp4v'"], {}), "(*'mp4v')\n", (4219, 4228), False, 'import cv2, time\n'), ((5920, 5931), 'time.time', 'time.time', ([], {}), '()\n', (5929, 5931), False, 'import cv2, time\n'), ((6127, 6141), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (6138, 6141), False, 'import cv2, time\n'), ((2772, 2810), 'cv2.VideoCapture', 'cv2.VideoCapture', (['source', 'cv2.CAP_V4L2'], {}), '(source, cv2.CAP_V4L2)\n', (2788, 2810), False, 'import cv2, time\n'), ((2972, 2992), 'utils_arducam.ArducamUtils', 'ArducamUtils', (['source'], {}), '(source)\n', (2984, 2992), False, 'from utils_arducam import ArducamUtils\n'), ((4536, 4551), 'copy.deepcopy', 'deepcopy', (['image'], {}), '(image)\n', (4544, 4551), False, 'from copy import deepcopy\n'), ((5129, 5149), 'utils.display.show_fps', 'show_fps', (['frame', 'fps'], {}), '(frame, fps)\n', (5137, 5149), False, 'from utils.display import open_window, set_display, show_fps\n'), ((5769, 5827), 'cv2.imwrite', 'cv2.imwrite', (['"""object_detection_result.jpg"""', 'inferred_image'], {}), "('object_detection_result.jpg', inferred_image)\n", (5780, 5827), False, 'import cv2, time\n'), ((5606, 5640), 'cv2.imshow', 'cv2.imshow', (['args.video_name', 'frame'], {}), '(args.video_name, frame)\n', (5616, 5640), False, 'import cv2, time\n'), ((6384, 6423), 'utils.display.set_display', 'set_display', (['args.video_name', 'full_scrn'], {}), '(args.video_name, full_scrn)\n', (6395, 6423), False, 'from utils.display import open_window, set_display, show_fps\n'), ((3743, 3762), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (3759, 3762), False, 'import cv2, time\n')] |
from hashlib import blake2s
def hash(x):
return blake2s(x).digest()[:32]
def get_primes(givenNumber):
# Initialize a list
primes = []
for possiblePrime in range(2, givenNumber + 1):
# Assume number is prime until shown it is not.
isPrime = True
for num in range(2, int(possiblePrime ** 0.5) + 1):
if possiblePrime % num == 0:
isPrime = False
break
if isPrime:
primes.append(possiblePrime)
return(primes)
def get_B_value(base, result):
return int.from_bytes(
hash(base.to_bytes(1024, 'big') + result.to_bytes(1024, 'big')),
'big'
)
def prove_exponentiation(base, exponent, result):
B = get_B_value(base, result)
b = pow(base, exponent // B, mod)
remainder = exponent % B
return (b, remainder)
def verify_proof(base, result, b, remainder):
B = get_B_value(base, result)
return pow(b, B, mod) * pow(base, remainder, mod) % mod == result
mod = 25195908475657893494027183240048398571429282126204032027777137836043662020707595556264018525880784406918290641249515082189298559149176184502808489120072844992687392807287776735971418347270261896375014971824691165077613379859095700097330459748808428401797429100642458691817195118746121515172654632282216869987549182422433637259085141865462043576798423387184774447920739934236584823824281198163815010674810451660377306056201619676256133844143603833904414952634432190114657544454178424020924616515723350778707749817125772467962926386356373289912154831438167899885040445364023527381951378636564391212010397122822120720357
acc_values = []
g = 3
acc = g
full_exponent = 1
for v in get_primes(100):
acc_values.append(v)
full_exponent = full_exponent * v
acc = pow(acc, v, mod)
prime_to_prove = acc_values[8]
b, remainder = prove_exponentiation(g, full_exponent, acc)
print(verify_proof(g, acc, b, remainder))
| [
"hashlib.blake2s"
] | [((53, 63), 'hashlib.blake2s', 'blake2s', (['x'], {}), '(x)\n', (60, 63), False, 'from hashlib import blake2s\n')] |
#
# Author: <NAME>
# created Date: 14-11-2019
from time import sleep
from sys import exit
from cunsumer.consumerhandler import ConsumerHandler
from message_handler.messagehandler import MessageHandler
from publisher.publisher import Publisher
PAUSE = 5
class KafkaPuller:
def __init__(self, settings, client_id, timeout, auto_commit, logger):
self._settings = settings
self._logger = logger
self._consumer = ConsumerHandler(self._settings, client_id, timeout, auto_commit)
self._database_handler = MessageHandler(self._settings, self._logger)
self._publisher = Publisher(self._settings)
def listener(self, topic, timeout):
"""
Listen to new messages and notify the the DataBaseManager about it.
:param topic: the topic name
:param timeout: Maximum time to block waiting for message, event or callback
:return: error_code, error_message
"""
try:
while True:
for error_code, error_message, message in self._consumer.message_listener(topic, float(timeout)):
if error_code != 0:
self._logger(self, error_message)
else:
self._database_handler.handle_message(message, self._publisher)
sleep(PAUSE)
except KeyboardInterrupt:
print()
exit(0)
| [
"cunsumer.consumerhandler.ConsumerHandler",
"publisher.publisher.Publisher",
"time.sleep",
"message_handler.messagehandler.MessageHandler",
"sys.exit"
] | [((440, 504), 'cunsumer.consumerhandler.ConsumerHandler', 'ConsumerHandler', (['self._settings', 'client_id', 'timeout', 'auto_commit'], {}), '(self._settings, client_id, timeout, auto_commit)\n', (455, 504), False, 'from cunsumer.consumerhandler import ConsumerHandler\n'), ((538, 582), 'message_handler.messagehandler.MessageHandler', 'MessageHandler', (['self._settings', 'self._logger'], {}), '(self._settings, self._logger)\n', (552, 582), False, 'from message_handler.messagehandler import MessageHandler\n'), ((609, 634), 'publisher.publisher.Publisher', 'Publisher', (['self._settings'], {}), '(self._settings)\n', (618, 634), False, 'from publisher.publisher import Publisher\n'), ((1320, 1332), 'time.sleep', 'sleep', (['PAUSE'], {}), '(PAUSE)\n', (1325, 1332), False, 'from time import sleep\n'), ((1399, 1406), 'sys.exit', 'exit', (['(0)'], {}), '(0)\n', (1403, 1406), False, 'from sys import exit\n')] |
import magma as m
import magma.testing
def test_2d_array_from_verilog():
main = m.define_from_verilog(f"""
module transpose_buffer (
input logic clk,
output logic [2:0] index_inner,
output logic [2:0] index_outer,
input logic [3:0] input_data [63:0],
input logic [2:0] range_inner,
input logic [2:0] range_outer,
input logic rst_n,
input logic [2:0] stride
);
always_ff @(posedge clk, negedge rst_n) begin
if (~rst_n) begin
index_outer <= 3'h0;
index_inner <= 3'h0;
end
else begin
if (index_outer == (range_outer - 3'h1)) begin
index_outer <= 3'h0;
end
else index_outer <= index_outer + 3'h1;
if (index_inner == (range_inner - 3'h1)) begin
index_inner <= 3'h0;
end
else index_inner <= index_inner + 3'h1;
end
end
endmodule // transpose_buffer
""")[0]
m.compile("build/2d_array_from_verilog", main, output="verilog")
assert m.testing.check_files_equal(__file__,
f"build/2d_array_from_verilog.v",
f"gold/2d_array_from_verilog.v")
| [
"magma.compile",
"magma.define_from_verilog",
"magma.testing.check_files_equal"
] | [((833, 897), 'magma.compile', 'm.compile', (['"""build/2d_array_from_verilog"""', 'main'], {'output': '"""verilog"""'}), "('build/2d_array_from_verilog', main, output='verilog')\n", (842, 897), True, 'import magma as m\n'), ((909, 1017), 'magma.testing.check_files_equal', 'm.testing.check_files_equal', (['__file__', 'f"""build/2d_array_from_verilog.v"""', 'f"""gold/2d_array_from_verilog.v"""'], {}), "(__file__, f'build/2d_array_from_verilog.v',\n f'gold/2d_array_from_verilog.v')\n", (936, 1017), True, 'import magma as m\n'), ((86, 835), 'magma.define_from_verilog', 'm.define_from_verilog', (['f"""\nmodule transpose_buffer (\n input logic clk,\n output logic [2:0] index_inner,\n output logic [2:0] index_outer,\n input logic [3:0] input_data [63:0],\n input logic [2:0] range_inner,\n input logic [2:0] range_outer,\n input logic rst_n,\n input logic [2:0] stride\n);\n\n\nalways_ff @(posedge clk, negedge rst_n) begin\n if (~rst_n) begin\n index_outer <= 3\'h0;\n index_inner <= 3\'h0;\n end\n else begin\n if (index_outer == (range_outer - 3\'h1)) begin\n index_outer <= 3\'h0;\n end\n else index_outer <= index_outer + 3\'h1;\n if (index_inner == (range_inner - 3\'h1)) begin\n index_inner <= 3\'h0;\n end\n else index_inner <= index_inner + 3\'h1;\n end\nend\nendmodule // transpose_buffer\n"""'], {}), '(\n f"""\nmodule transpose_buffer (\n input logic clk,\n output logic [2:0] index_inner,\n output logic [2:0] index_outer,\n input logic [3:0] input_data [63:0],\n input logic [2:0] range_inner,\n input logic [2:0] range_outer,\n input logic rst_n,\n input logic [2:0] stride\n);\n\n\nalways_ff @(posedge clk, negedge rst_n) begin\n if (~rst_n) begin\n index_outer <= 3\'h0;\n index_inner <= 3\'h0;\n end\n else begin\n if (index_outer == (range_outer - 3\'h1)) begin\n index_outer <= 3\'h0;\n end\n else index_outer <= index_outer + 3\'h1;\n if (index_inner == (range_inner - 3\'h1)) begin\n index_inner <= 3\'h0;\n end\n else index_inner <= index_inner + 3\'h1;\n end\nend\nendmodule // transpose_buffer\n"""\n )\n', (107, 835), True, 'import magma as m\n')] |
import os
from .notebook import KindleNotebook
from .parser import MyHTMLParser
from .md_renderer import render_md_from_notebook
def convert_kindle_html_to_md(html_file):
if not os.path.exists(html_file):
raise ValueError("no such file: " + html_file)
note = KindleNotebook()
parser = MyHTMLParser(note)
with open(html_file, "r", encoding="utf8") as f:
try:
parser.feed(f.read())
return render_md_from_notebook(note)
except OSError as error:
print("could not open file for reading: " + error)
| [
"os.path.exists"
] | [((185, 210), 'os.path.exists', 'os.path.exists', (['html_file'], {}), '(html_file)\n', (199, 210), False, 'import os\n')] |
import torch
import os
from glob import glob
import numpy as np
from torch.nn import functional as F
import time
class Generator(object):
def __init__(self, model, exp_name, threshold = 0.1, checkpoint = None, device = torch.device("cuda")):
self.model = model.to(device)
self.model.eval()
self.device = device
self.checkpoint_path = os.path.dirname(__file__) + '/../experiments/{}/checkpoints/'.format( exp_name)
self.load_checkpoint(checkpoint)
self.threshold = threshold
def generate_point_cloud(self, data, num_steps = 10, num_points = 900000, filter_val = 0.009):
start = time.time()
inputs = data['inputs'].to(self.device)
for param in self.model.parameters():
param.requires_grad = False
sample_num = 200000
samples_cpu = np.zeros((0, 3))
samples = torch.rand(1, sample_num, 3).float().to(self.device) * 3 - 1.5
samples.requires_grad = True
encoding = self.model.encoder(inputs)
i = 0
while len(samples_cpu) < num_points:
print('iteration', i)
for j in range(num_steps):
print('refinement', j)
df_pred = torch.clamp(self.model.decoder(samples, *encoding), max=self.threshold)
df_pred.sum().backward()
gradient = samples.grad.detach()
samples = samples.detach()
df_pred = df_pred.detach()
inputs = inputs.detach()
samples = samples - F.normalize(gradient, dim=2) * df_pred.reshape(-1, 1) # better use Tensor.copy method?
samples = samples.detach()
samples.requires_grad = True
print('finished refinement')
if not i == 0:
samples_cpu = np.vstack((samples_cpu, samples[df_pred < filter_val].detach().cpu().numpy()))
samples = samples[df_pred < 0.03].unsqueeze(0)
indices = torch.randint(samples.shape[1], (1, sample_num))
samples = samples[[[0, ] * sample_num], indices]
samples += (self.threshold / 3) * torch.randn(samples.shape).to(self.device) # 3 sigma rule
samples = samples.detach()
samples.requires_grad = True
i += 1
print(samples_cpu.shape)
duration = time.time() - start
return samples_cpu, duration
def load_checkpoint(self, checkpoint):
checkpoints = glob(self.checkpoint_path + '/*')
if checkpoint is None:
if len(checkpoints) == 0:
print('No checkpoints found at {}'.format(self.checkpoint_path))
return 0, 0
checkpoints = [os.path.splitext(os.path.basename(path))[0].split('_')[-1] for path in checkpoints]
checkpoints = np.array(checkpoints, dtype=float)
checkpoints = np.sort(checkpoints)
path = self.checkpoint_path + 'checkpoint_{}h:{}m:{}s_{}.tar'.format(
*[*convertSecs(checkpoints[-1]), checkpoints[-1]])
else:
path = self.checkpoint_path + '{}.tar'.format(checkpoint)
print('Loaded checkpoint from: {}'.format(path))
checkpoint = torch.load(path)
self.model.load_state_dict(checkpoint['model_state_dict'])
epoch = checkpoint['epoch']
training_time = checkpoint['training_time']
return epoch, training_time
def convertMillis(millis):
seconds = int((millis / 1000) % 60)
minutes = int((millis / (1000 * 60)) % 60)
hours = int((millis / (1000 * 60 * 60)))
return hours, minutes, seconds
def convertSecs(sec):
seconds = int(sec % 60)
minutes = int((sec / 60) % 60)
hours = int((sec / (60 * 60)))
return hours, minutes, seconds
| [
"torch.rand",
"torch.load",
"numpy.sort",
"torch.nn.functional.normalize",
"os.path.dirname",
"numpy.zeros",
"torch.randint",
"numpy.array",
"os.path.basename",
"time.time",
"torch.randn",
"glob.glob",
"torch.device"
] | [((224, 244), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (236, 244), False, 'import torch\n'), ((645, 656), 'time.time', 'time.time', ([], {}), '()\n', (654, 656), False, 'import time\n'), ((844, 860), 'numpy.zeros', 'np.zeros', (['(0, 3)'], {}), '((0, 3))\n', (852, 860), True, 'import numpy as np\n'), ((2488, 2521), 'glob.glob', 'glob', (["(self.checkpoint_path + '/*')"], {}), "(self.checkpoint_path + '/*')\n", (2492, 2521), False, 'from glob import glob\n'), ((3231, 3247), 'torch.load', 'torch.load', (['path'], {}), '(path)\n', (3241, 3247), False, 'import torch\n'), ((371, 396), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (386, 396), False, 'import os\n'), ((1990, 2038), 'torch.randint', 'torch.randint', (['samples.shape[1]', '(1, sample_num)'], {}), '(samples.shape[1], (1, sample_num))\n', (2003, 2038), False, 'import torch\n'), ((2362, 2373), 'time.time', 'time.time', ([], {}), '()\n', (2371, 2373), False, 'import time\n'), ((2838, 2872), 'numpy.array', 'np.array', (['checkpoints'], {'dtype': 'float'}), '(checkpoints, dtype=float)\n', (2846, 2872), True, 'import numpy as np\n'), ((2899, 2919), 'numpy.sort', 'np.sort', (['checkpoints'], {}), '(checkpoints)\n', (2906, 2919), True, 'import numpy as np\n'), ((1552, 1580), 'torch.nn.functional.normalize', 'F.normalize', (['gradient'], {'dim': '(2)'}), '(gradient, dim=2)\n', (1563, 1580), True, 'from torch.nn import functional as F\n'), ((2146, 2172), 'torch.randn', 'torch.randn', (['samples.shape'], {}), '(samples.shape)\n', (2157, 2172), False, 'import torch\n'), ((879, 907), 'torch.rand', 'torch.rand', (['(1)', 'sample_num', '(3)'], {}), '(1, sample_num, 3)\n', (889, 907), False, 'import torch\n'), ((2745, 2767), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (2761, 2767), False, 'import os\n')] |
from algo import Algorithm
from lagom.experiment import Config
from lagom.experiment import BaseExperimentWorker
from lagom.experiment import BaseExperimentMaster
class ExperimentWorker(BaseExperimentWorker):
def make_algo(self):
algo = Algorithm(name='VAE on MNIST')
return algo
class ExperimentMaster(BaseExperimentMaster):
def process_algo_result(self, config, result):
assert result == None
def make_configs(self):
config = Config()
config.add_grid(name='use_ConvVAE', val=[True, False])
config.add_item(name='num_epochs', val=100)
config.add_item(name='cuda', val=True)
config.add_item(name='seed', val=1)
config.add_item(name='batch_size', val=128)
config.add_item(name='log_interval', val=100)
configs = config.make_configs()
return configs | [
"lagom.experiment.Config",
"algo.Algorithm"
] | [((252, 282), 'algo.Algorithm', 'Algorithm', ([], {'name': '"""VAE on MNIST"""'}), "(name='VAE on MNIST')\n", (261, 282), False, 'from algo import Algorithm\n'), ((498, 506), 'lagom.experiment.Config', 'Config', ([], {}), '()\n', (504, 506), False, 'from lagom.experiment import Config\n')] |
"""
Created on 2012-12-22
@author: Administrator
"""
from socket import socket
from time import ctime
HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
sock = socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(ADDR)
sock.listen(5)
while True:
print('Waiting ...')
sock_c, addr = sock.accept()
print('...connected from:', addr)
while True:
buffer = sock_c.recv(BUFSIZE)
if not buffer:
break
line = '[' + ctime() + ']' + buffer.decode('utf-8')
sock_c.send(line.encode('utf-8'))
sock_c.close()
sock.close()
| [
"time.ctime",
"socket.socket"
] | [((171, 213), 'socket.socket', 'socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (177, 213), False, 'from socket import socket\n'), ((471, 478), 'time.ctime', 'ctime', ([], {}), '()\n', (476, 478), False, 'from time import ctime\n')] |
import numpy as np
def process_actions(actions, l_action):
n_steps = len(actions)
actions_1hot = np.zeros([n_steps, l_action], dtype=int)
actions_1hot[np.arange(n_steps), actions] = 1
return actions_1hot
def get_action_others_1hot(action_all, agent_id, l_action):
action_all = list(action_all)
del action_all[agent_id]
num_others = len(action_all)
actions_1hot = np.zeros([num_others, l_action], dtype=int)
actions_1hot[np.arange(num_others), action_all] = 1
return actions_1hot.flatten()
def get_action_others_1hot_batch(list_action_all, agent_id, l_action):
n_steps = len(list_action_all)
n_agents = len(list_action_all[0])
matrix = np.stack(list_action_all) # [n_steps, n_agents]
self_removed = np.delete(matrix, agent_id, axis=1)
actions_1hot = np.zeros([n_steps, n_agents-1, l_action], dtype=np.float32)
grid = np.indices((n_steps, n_agents-1))
actions_1hot[grid[0], grid[1], self_removed] = 1
actions_1hot = np.reshape(actions_1hot, [n_steps, l_action*(n_agents-1)])
return actions_1hot
def process_rewards(rewards, gamma):
n_steps = len(rewards)
gamma_prod = np.cumprod(np.ones(n_steps) * gamma)
returns = np.cumsum((rewards * gamma_prod)[::-1])[::-1]
returns = returns / gamma_prod
return returns
| [
"numpy.reshape",
"numpy.ones",
"numpy.delete",
"numpy.indices",
"numpy.stack",
"numpy.zeros",
"numpy.cumsum",
"numpy.arange"
] | [((112, 152), 'numpy.zeros', 'np.zeros', (['[n_steps, l_action]'], {'dtype': 'int'}), '([n_steps, l_action], dtype=int)\n', (120, 152), True, 'import numpy as np\n'), ((415, 458), 'numpy.zeros', 'np.zeros', (['[num_others, l_action]'], {'dtype': 'int'}), '([num_others, l_action], dtype=int)\n', (423, 458), True, 'import numpy as np\n'), ((719, 744), 'numpy.stack', 'np.stack', (['list_action_all'], {}), '(list_action_all)\n', (727, 744), True, 'import numpy as np\n'), ((788, 823), 'numpy.delete', 'np.delete', (['matrix', 'agent_id'], {'axis': '(1)'}), '(matrix, agent_id, axis=1)\n', (797, 823), True, 'import numpy as np\n'), ((844, 905), 'numpy.zeros', 'np.zeros', (['[n_steps, n_agents - 1, l_action]'], {'dtype': 'np.float32'}), '([n_steps, n_agents - 1, l_action], dtype=np.float32)\n', (852, 905), True, 'import numpy as np\n'), ((916, 951), 'numpy.indices', 'np.indices', (['(n_steps, n_agents - 1)'], {}), '((n_steps, n_agents - 1))\n', (926, 951), True, 'import numpy as np\n'), ((1024, 1086), 'numpy.reshape', 'np.reshape', (['actions_1hot', '[n_steps, l_action * (n_agents - 1)]'], {}), '(actions_1hot, [n_steps, l_action * (n_agents - 1)])\n', (1034, 1086), True, 'import numpy as np\n'), ((1250, 1289), 'numpy.cumsum', 'np.cumsum', (['(rewards * gamma_prod)[::-1]'], {}), '((rewards * gamma_prod)[::-1])\n', (1259, 1289), True, 'import numpy as np\n'), ((171, 189), 'numpy.arange', 'np.arange', (['n_steps'], {}), '(n_steps)\n', (180, 189), True, 'import numpy as np\n'), ((477, 498), 'numpy.arange', 'np.arange', (['num_others'], {}), '(num_others)\n', (486, 498), True, 'import numpy as np\n'), ((1209, 1225), 'numpy.ones', 'np.ones', (['n_steps'], {}), '(n_steps)\n', (1216, 1225), True, 'import numpy as np\n')] |
import json, requests
from events import TickEvent
from enviro import STREAM_DOMAIN, GrabToken, GrabID
class GrabPrice(object):
def __init__(self, domain, token, ID_num, instru, event_queue):
self.domain = domain
self.token = token
self.ID_num = ID_num
self.instru = instru
self.event_queue = event_queue
def requestStream(self):
try:
s = requests.Session()
header = {'Authorization':'Bearer '+ self.token,
'Accept-Datetime-Format':'UNIX',
'Content-Type':'application/octet-stream',
'Connection':'Keep-Alive'
}
param = {'instruments':self.instru}
url = ('https://' + self.domain + '/v3/accounts/' + self.ID_num +
'/pricing/stream?')
resp = s.get(url,headers=header,params=param,stream=True)
return resp
except Exception as e:
s.close()
print('Error in requestStream func, can not connect to stream\n'+
str(e))
def streamPrices(self):
OHLC = self.requestStream()
for line in OHLC.iter_lines():
try:
decoded_line = line.decode('utf-8')
OHLC = json.loads(decoded_line)
except Exception as e:
print('Error in streamPrices func, can not parse\n'+ str(e))
else:
if OHLC['type'] == 'PRICE':
#status = OHLC['status'] # ie 'tradeable'
#can_trade = OHLC['tradeable'] #boolean value, ie True
instru = OHLC['instrument']
time = OHLC['time']
bid = OHLC['bids'][0]['price']
#bid_liq = OHLC['bids'][0]['liquidity']
#bid_close = OHLC['closeoutBid']
ask = OHLC['asks'][0]['price']
#ask_liq = OHLC['asks'][0]['liquidity']
#ask_close = OHLC['closeoutAsk']
#####print(time)
tickOHLC = TickEvent(instru, float(time), float(bid), float(ask))
self.event_queue.put(tickOHLC)
elif OHLC['type'] == 'HEARTBEAT':
time_HB = OHLC['time']
print('{} : HEARTBEAT'.format(time_HB))
"""
#testing this script with print func above (line 54)
#comment out self.event_queue and delete the parameter
#in GrabPrice self.event_queue to test script
token = GrabToken()
ID_Num = GrabID()
testGrab = GrabPrice(STREAM_DOMAIN,token,ID_Num,'EUR_USD')
testGrab.streamPrices()
"""
| [
"json.loads",
"requests.Session"
] | [((410, 428), 'requests.Session', 'requests.Session', ([], {}), '()\n', (426, 428), False, 'import json, requests\n'), ((1287, 1311), 'json.loads', 'json.loads', (['decoded_line'], {}), '(decoded_line)\n', (1297, 1311), False, 'import json, requests\n')] |
#!/usr/bin/env python3
import argparse
import configparser
import getpass
import logging
import os
import requests
import requests_toolbelt
import sys
import urllib3
from scapy.all import *
import ipaddress
import json
from scapy.layers.http import HTTPRequest # import HTTP packet
from scapy.layers.http import HTTP
CURRENT_DIRECTORY = os.path.dirname( os.path.abspath(__file__) )
SOURCE_DIRECTORY = os.path.join( CURRENT_DIRECTORY, 'src' )
sys.path.append( SOURCE_DIRECTORY )
# https://stackoverflow.com/questions/27981545/suppress-insecurerequestwarning-unverified-https-request-is-being-made-in-pythopyt
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
logging.getLogger("requests").setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
NAME = 'ourstarter'
logger = logging.getLogger( '{}'.format(NAME) )
STARTER_HOME_DIR = '.{}'.format(NAME)
OUR_CONFIGURATION_FILE = "ourstarter.ini"
DEFAULT_CONFIGURATION = """[server]
url = https://127.0.0.1
apipath = /api/v1
verify_ssl = false"""
def make_project_homedir():
if sys.platform == 'win32':
user_home_dir = os.getenv( 'HOMEDRIVE', None ) + os.getenv( 'HOMEPATH', None )
else:
user_home_dir = os.getenv( 'HOME' )
if not user_home_dir:
user_home_dir = os.getcwd()
full_path_to_project_dir = user_home_dir + os.sep + STARTER_HOME_DIR
if not os.path.exists( full_path_to_project_dir ):
os.mkdir( full_path_to_project_dir )
return full_path_to_project_dir
def read_properties( arguments, logger ):
our_configuration = None
full_path_to_project_config = arguments.homedir + os.sep + arguments.configfile
logger.info( "reading properties" )
arguments.configfile = full_path_to_project_config
logger.info( "full path to configuration file is {}".format(arguments.configfile) )
if os.path.exists(full_path_to_project_config):
our_configuration = configparser.ConfigParser()
our_configuration.read( full_path_to_project_config )
logger.debug( "all read" )
return our_configuration
else:
logger.info( "property file did not exist, save new default" )
with open( full_path_to_project_config, 'w' ) as writer:
writer.write( DEFAULT_CONFIGURATION )
logger.debug("save")
our_configuration = configparser.ConfigParser()
our_configuration.read( full_path_to_project_config )
logger.debug( "all read" )
return our_configuration
def process_packet(packet, data):
"""
This function is executed whenever a packet is sniffed
"""
if packet.haslayer(HTTPRequest):
# if this packet is an HTTP Request
# get the requested URL
url = packet[HTTPRequest].Host.decode() + packet[HTTPRequest].Path.decode()
# get the requester's IP Address
ip = packet[IP].src
# get the request method
reqmethod = packet[HTTPRequest].Method.decode()
c = {'url' : url,
'ip' : ip,
'reqmethod' :reqmethod}
data['HTTPRequests'].append(c)
def parse_arguments():
parser = argparse.ArgumentParser()
#parser.add_argument('action', metavar='ACTION', type=str, help='Specify action for {}'.format(NAME) )
parser.add_argument('-C', '--configfile', help="Specify an alternate project configuration filename. Default is ~/.{}/{}.ini".format(NAME,NAME))
parser.add_argument('-H', '--homedir', help="Specify an alternate data directory. Default is ~/.{}".format(NAME) )
parser.add_argument('-L', '--loglevel', help="Specify alternate logging level. (Default is NONE)")
parser.add_argument('-O', '--outputfile', help="Specify output location")
parser.add_argument('-p', '--pcapreader', help="Call on a specified .pcap file for analysis")
parser.add_argument('-q', '--quiet', action='store_true', help="Supress logging. Default is FALSE")
return parser.parse_args()
#This is the Entry Point
if __name__ == "__main__":
arguments = parse_arguments( )
if not arguments.configfile:
arguments.configfile = OUR_CONFIGURATION_FILE
if not arguments.homedir:
arguments.homedir = make_project_homedir( )
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=arguments.loglevel)
logger = logging.getLogger( NAME )
if arguments.quiet:
logger.propagate = False
logger.info( '{} startup'.format(NAME) )
our_properties = read_properties( arguments, logger )
#########################################################################################
#################This is the Starting point for you to work##############################
# rdpcap comes from scapy and loads in our pcap file
#packets = rdpcap('example.pcap') #>>>>> this line is leftover from https://incognitjoe.github.io/reading-pcap-with-scapy.html >>>> it is calling on a .pcap file with a very specific name. We want to call on an arugment for any .pcap file to make things more efficient.
packets = rdpcap(arguments.pcapreader)
data = {}
data['IP'] = {}
data['IP']['src.addr'] = []
data['IP']['dst.addr'] = []
data['DNSrequest'] = []
data['HTTPRequests'] = []
data['HTTPResponses'] = []
# Let's iterate through every packet
for packet in packets:
# We're only interested packets with a DNS Round Robin layer
if packet.haslayer(IP):
s = packet[IP].src
d = packet[IP].dst
so = ipaddress.ip_address(s) #so = source output
do = ipaddress.ip_address(d) #do = destination output
if not so.is_private and not so.is_multicast and not so.is_loopback: # if o.is_private != True: >>>> this works too, but it's just not as efficient
data['IP']['src.addr'].append(str(s))#, packet[IP].dst) for packet in PcapReader('file.pcap') if IP in packet)
if not do.is_private and not do.is_multicast and not so.is_loopback: # if o.is_private != True: >>>> this works too, but it's just not as efficient
data['IP']['dst.addr'].append(str(d))#, packet[IP].dst) for packet in PcapReader('file.pcap') if IP in packet)
if packet.haslayer(DNSRR): #DNSRR = scapy object for DNS
# If the an(swer) is a DNSRR, print the name it replied with.
if isinstance(packet.an, DNSRR):
data['DNSrequest'].append(str(packet.an.rrname.decode('UTF-8'))) #This saves the DNS Requests into the data[] list
elif packet.haslayer(HTTP):
process_packet(packet, data)
data['DNSrequest']=set(data['DNSrequest']) #This changes the data[] list into a "set" >>> sets DO NOT allow duplicates
data['IP']['src.addr']=set(data['IP']['src.addr']) #This changes the data[] list into a "set" >>> sets DO NOT allow duplicates
data['IP']['dst.addr']=set(data['IP']['dst.addr']) #This changes the data[] list into a "set" >>> sets DO NOT allow duplicates
# print(data['IP'])
print(data)
#print(json.dumps(data, indent=4)) | [
"logging.basicConfig",
"os.path.exists",
"logging.getLogger",
"ipaddress.ip_address",
"configparser.ConfigParser",
"argparse.ArgumentParser",
"os.getenv",
"os.path.join",
"os.getcwd",
"urllib3.disable_warnings",
"os.mkdir",
"os.path.abspath",
"sys.path.append"
] | [((402, 440), 'os.path.join', 'os.path.join', (['CURRENT_DIRECTORY', '"""src"""'], {}), "(CURRENT_DIRECTORY, 'src')\n", (414, 440), False, 'import os\n'), ((443, 476), 'sys.path.append', 'sys.path.append', (['SOURCE_DIRECTORY'], {}), '(SOURCE_DIRECTORY)\n', (458, 476), False, 'import sys\n'), ((610, 677), 'urllib3.disable_warnings', 'urllib3.disable_warnings', (['urllib3.exceptions.InsecureRequestWarning'], {}), '(urllib3.exceptions.InsecureRequestWarning)\n', (634, 677), False, 'import urllib3\n'), ((355, 380), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (370, 380), False, 'import os\n'), ((1869, 1912), 'os.path.exists', 'os.path.exists', (['full_path_to_project_config'], {}), '(full_path_to_project_config)\n', (1883, 1912), False, 'import os\n'), ((3178, 3203), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3201, 3203), False, 'import argparse\n'), ((4273, 4389), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s %(message)s"""', 'datefmt': '"""%m/%d/%Y %I:%M:%S %p"""', 'level': 'arguments.loglevel'}), "(format='%(asctime)s %(message)s', datefmt=\n '%m/%d/%Y %I:%M:%S %p', level=arguments.loglevel)\n", (4292, 4389), False, 'import logging\n'), ((4398, 4421), 'logging.getLogger', 'logging.getLogger', (['NAME'], {}), '(NAME)\n', (4415, 4421), False, 'import logging\n'), ((678, 707), 'logging.getLogger', 'logging.getLogger', (['"""requests"""'], {}), "('requests')\n", (695, 707), False, 'import logging\n'), ((734, 762), 'logging.getLogger', 'logging.getLogger', (['"""urllib3"""'], {}), "('urllib3')\n", (751, 762), False, 'import logging\n'), ((1221, 1238), 'os.getenv', 'os.getenv', (['"""HOME"""'], {}), "('HOME')\n", (1230, 1238), False, 'import os\n'), ((1292, 1303), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1301, 1303), False, 'import os\n'), ((1390, 1430), 'os.path.exists', 'os.path.exists', (['full_path_to_project_dir'], {}), '(full_path_to_project_dir)\n', (1404, 1430), False, 'import os\n'), ((1442, 1476), 'os.mkdir', 'os.mkdir', (['full_path_to_project_dir'], {}), '(full_path_to_project_dir)\n', (1450, 1476), False, 'import os\n'), ((1942, 1969), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (1967, 1969), False, 'import configparser\n'), ((2367, 2394), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (2392, 2394), False, 'import configparser\n'), ((1124, 1152), 'os.getenv', 'os.getenv', (['"""HOMEDRIVE"""', 'None'], {}), "('HOMEDRIVE', None)\n", (1133, 1152), False, 'import os\n'), ((1157, 1184), 'os.getenv', 'os.getenv', (['"""HOMEPATH"""', 'None'], {}), "('HOMEPATH', None)\n", (1166, 1184), False, 'import os\n'), ((5612, 5635), 'ipaddress.ip_address', 'ipaddress.ip_address', (['s'], {}), '(s)\n', (5632, 5635), False, 'import ipaddress\n'), ((5673, 5696), 'ipaddress.ip_address', 'ipaddress.ip_address', (['d'], {}), '(d)\n', (5693, 5696), False, 'import ipaddress\n')] |
"""
Copyright (c) 2020 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
All use of the material herein must be in accordance with the terms of
the License. All rights not expressly granted by the License are
reserved. Unless required by applicable law or agreed to separately 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.
"""
from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for
from werkzeug.security import check_password_hash
from src.auth import login_required
from src.db import get_db
from src.dnacAPI import *
from datetime import datetime
import json
import pandas
import urllib3
urllib3.disable_warnings()
bp = Blueprint('portal', __name__)
@bp.route('/', methods=('GET', 'POST'))
@login_required
def home():
"""
Home Page back-end functionality
:return:
"""
# Check for any initial errors
error = None
if 'dnac' not in session:
error = "ERROR: No DNA-Center instance configured. Please configure on the Settings page."
flash(error)
return render_template('portal/home.html', session=session)
if session['dnac']['token'] == "":
session['dnac']['token'] = dnac_get_Authorization_Token(session['dnac'])
session.modified = True
if session['dnac']['token'] == "":
error = "ERROR: No DNA-Center Token found. Please check configuration on the Settings page."
flash(error)
return render_template('portal/home.html', session=session)
# Set default state of page
db = get_db()
template_list = dnac_get_Available_Templates(session['dnac'])
session['dnac']['selectedTemplate'] = ""
# Retrieve Page Data Set
task_log = db.execute(
'SELECT t.id, ts, type, description'
' FROM tasklog t'
' ORDER BY ts DESC'
).fetchall()
# On User Action
if request.method == 'POST':
# If a User selected Refresh
if request.form.get('refresh'):
session['dnac']['token'] = dnac_get_Authorization_Token(session['dnac'])
session.modified = True
return redirect(url_for('portal.home'))
# If a DNA-Center Template is selected to view
if request.form.get('template'):
session['dnac']['selectedTemplate'] = request.form.get('template')
session.modified = True
return redirect(url_for('portal.templateDetails'))
return render_template('portal/home.html', session=session, template_list=template_list, task_log=task_log)
@bp.route('/details', methods=('GET', 'POST'))
@login_required
def templateDetails():
"""
Back-End to view Template Details
"""
error = None
template_Details_Json = dnac_get_Template(session['dnac'])
template_Details = template_Details_Json.items()
return render_template('portal/templateDetails.html', session=session, template_Details=template_Details, template_name=template_Details_Json['name'])
@bp.route('/action', methods=('GET', 'POST'))
@login_required
def templateAction():
"""
Back-End to start the Custom User Action
"""
error = None
project_list = dnac_get_Available_Projects(session['dnac'])
template_list = dnac_get_Available_Templates(session['dnac'])
device_list = dnac_get_DNAC_Network_Devices(session['dnac'])
if request.method == 'POST':
# Collect User Inputs
session['dnac']['deviceSelections'] = request.form.getlist('selectedDevice')
session['dnac']['selectedTemplate'] = request.form.get('templateSelection')
session.modified = True
return redirect(url_for('portal.templateSetAction'))
return render_template('portal/templateAction.html', session=session,
project_list=project_list, template_list=template_list, device_list=device_list['response'])
@bp.route('/actionSettings', methods=('GET', 'POST'))
@login_required
def templateSetAction():
"""
Back-End to allowing the User to set Template Params
"""
error = None
template_json = dnac_get_Template(session['dnac'])
template_parameters = template_json['templateParams']
template_name = template_json['name']
if request.method == 'POST':
# TODO: Check if user manually added parameters
# IF THE USER UPLOADED A PARAM FILE
site_Csv = request.files['file']
if site_Csv.filename == '':
print('No file uploaded...')
elif site_Csv.filename.endswith('.csv'):
site_DF = pandas.read_csv(site_Csv)
site_Params = site_DF.to_json(orient="columns")
session['templateParams'] = site_Params
print(site_Params)
session.modified = True
return redirect(url_for('portal.templateDeployAction'))
else:
error = "ERROR: File must be in CSV format!"
flash(error)
return render_template('portal/templateSetAction.html', session=session, template_name=template_name,
template_parameters=template_parameters)
@bp.route('/actionDeployment', methods=('GET', 'POST'))
@login_required
def templateDeployAction():
"""
Back-End to the Deployment of the Template to each selected device.
# NOTE: THIS IS WHERE THE DEVELOPMENT ON THE PROJECT CURRENTLY IS...
# An Update to this section will be pushed soon
"""
error = None
print("Deployment Starting...")
for device in session['dnac']['deviceSelections']:
print('Deploying to {}...'.format(device))
dnac_deploy_Template(session['dnac'], device, session['dnac']['selectedTemplate'], session['templateParams'], False)
print('Finished!')
if request.method == 'POST':
print()
return render_template('portal/templateDeployAction.html', session=session)
@bp.route('/settings', methods=('GET', 'POST'))
@login_required
def settings():
"""
Settings Page back-end functionality
:return:
"""
# Set default state of page
error = None
dnac = {}
clearPass = {}
if 'dnac' in session:
dnac = session['dnac']
if 'clearPass' in session:
clearPass = session['clearPass']
if request.method == 'POST':
update_dnac = False
update_clearPass = False
# Check for any DNA-Center inputs
if request.form.get('dnac_host') != "":
dnac["dnac_host"] = request.form.get('dnac_host')
update_dnac = True
if request.form.get('dnac_username') != "":
dnac["dnac_username"] = request.form.get('dnac_username')
update_dnac = True
if request.form.get('dnac_password') != "":
dnac["dnac_password"] = request.form.get('dnac_password')
update_dnac = True
if update_dnac:
session['dnac'] = dnac
session['dnac']['token'] = ""
session['dnac']['selectedTemplate'] = ""
# Check for any DNA-Center inputs
if request.form.get('corp_Dot1x_cluster') != "":
clearPass["corp_Dot1x_cluster"] = request.form.get('corp_Dot1x_cluster')
update_clearPass = True
if request.form.get('guest_Cluster') != "":
clearPass["guest_Cluster"] = request.form.get('guest_Cluster')
update_clearPass = True
if update_clearPass:
session['clearPass'] = clearPass
session.modified = True
return redirect(url_for('portal.home'))
return render_template('portal/settings.html', session=session)
| [
"flask.render_template",
"src.db.get_db",
"flask.flash",
"pandas.read_csv",
"flask.request.form.getlist",
"flask.request.form.get",
"flask.url_for",
"urllib3.disable_warnings",
"flask.Blueprint"
] | [((945, 971), 'urllib3.disable_warnings', 'urllib3.disable_warnings', ([], {}), '()\n', (969, 971), False, 'import urllib3\n'), ((977, 1006), 'flask.Blueprint', 'Blueprint', (['"""portal"""', '__name__'], {}), "('portal', __name__)\n", (986, 1006), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((1853, 1861), 'src.db.get_db', 'get_db', ([], {}), '()\n', (1859, 1861), False, 'from src.db import get_db\n'), ((2736, 2841), 'flask.render_template', 'render_template', (['"""portal/home.html"""'], {'session': 'session', 'template_list': 'template_list', 'task_log': 'task_log'}), "('portal/home.html', session=session, template_list=\n template_list, task_log=task_log)\n", (2751, 2841), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((3123, 3275), 'flask.render_template', 'render_template', (['"""portal/templateDetails.html"""'], {'session': 'session', 'template_Details': 'template_Details', 'template_name': "template_Details_Json['name']"}), "('portal/templateDetails.html', session=session,\n template_Details=template_Details, template_name=template_Details_Json[\n 'name'])\n", (3138, 3275), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((3962, 4127), 'flask.render_template', 'render_template', (['"""portal/templateAction.html"""'], {'session': 'session', 'project_list': 'project_list', 'template_list': 'template_list', 'device_list': "device_list['response']"}), "('portal/templateAction.html', session=session, project_list\n =project_list, template_list=template_list, device_list=device_list[\n 'response'])\n", (3977, 4127), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((5191, 5330), 'flask.render_template', 'render_template', (['"""portal/templateSetAction.html"""'], {'session': 'session', 'template_name': 'template_name', 'template_parameters': 'template_parameters'}), "('portal/templateSetAction.html', session=session,\n template_name=template_name, template_parameters=template_parameters)\n", (5206, 5330), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((6040, 6108), 'flask.render_template', 'render_template', (['"""portal/templateDeployAction.html"""'], {'session': 'session'}), "('portal/templateDeployAction.html', session=session)\n", (6055, 6108), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((7761, 7817), 'flask.render_template', 'render_template', (['"""portal/settings.html"""'], {'session': 'session'}), "('portal/settings.html', session=session)\n", (7776, 7817), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((1332, 1344), 'flask.flash', 'flash', (['error'], {}), '(error)\n', (1337, 1344), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((1360, 1412), 'flask.render_template', 'render_template', (['"""portal/home.html"""'], {'session': 'session'}), "('portal/home.html', session=session)\n", (1375, 1412), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((2248, 2275), 'flask.request.form.get', 'request.form.get', (['"""refresh"""'], {}), "('refresh')\n", (2264, 2275), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((2516, 2544), 'flask.request.form.get', 'request.form.get', (['"""template"""'], {}), "('template')\n", (2532, 2544), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((3735, 3773), 'flask.request.form.getlist', 'request.form.getlist', (['"""selectedDevice"""'], {}), "('selectedDevice')\n", (3755, 3773), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((3820, 3857), 'flask.request.form.get', 'request.form.get', (['"""templateSelection"""'], {}), "('templateSelection')\n", (3836, 3857), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((1726, 1738), 'flask.flash', 'flash', (['error'], {}), '(error)\n', (1731, 1738), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((1758, 1810), 'flask.render_template', 'render_template', (['"""portal/home.html"""'], {'session': 'session'}), "('portal/home.html', session=session)\n", (1773, 1810), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((2596, 2624), 'flask.request.form.get', 'request.form.get', (['"""template"""'], {}), "('template')\n", (2612, 2624), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((3914, 3949), 'flask.url_for', 'url_for', (['"""portal.templateSetAction"""'], {}), "('portal.templateSetAction')\n", (3921, 3949), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((6621, 6650), 'flask.request.form.get', 'request.form.get', (['"""dnac_host"""'], {}), "('dnac_host')\n", (6637, 6650), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((6690, 6719), 'flask.request.form.get', 'request.form.get', (['"""dnac_host"""'], {}), "('dnac_host')\n", (6706, 6719), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((6762, 6795), 'flask.request.form.get', 'request.form.get', (['"""dnac_username"""'], {}), "('dnac_username')\n", (6778, 6795), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((6839, 6872), 'flask.request.form.get', 'request.form.get', (['"""dnac_username"""'], {}), "('dnac_username')\n", (6855, 6872), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((6915, 6948), 'flask.request.form.get', 'request.form.get', (['"""dnac_password"""'], {}), "('dnac_password')\n", (6931, 6948), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((6992, 7025), 'flask.request.form.get', 'request.form.get', (['"""dnac_password"""'], {}), "('dnac_password')\n", (7008, 7025), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((7265, 7303), 'flask.request.form.get', 'request.form.get', (['"""corp_Dot1x_cluster"""'], {}), "('corp_Dot1x_cluster')\n", (7281, 7303), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((7357, 7395), 'flask.request.form.get', 'request.form.get', (['"""corp_Dot1x_cluster"""'], {}), "('corp_Dot1x_cluster')\n", (7373, 7395), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((7443, 7476), 'flask.request.form.get', 'request.form.get', (['"""guest_Cluster"""'], {}), "('guest_Cluster')\n", (7459, 7476), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((7525, 7558), 'flask.request.form.get', 'request.form.get', (['"""guest_Cluster"""'], {}), "('guest_Cluster')\n", (7541, 7558), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((7726, 7748), 'flask.url_for', 'url_for', (['"""portal.home"""'], {}), "('portal.home')\n", (7733, 7748), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((2426, 2448), 'flask.url_for', 'url_for', (['"""portal.home"""'], {}), "('portal.home')\n", (2433, 2448), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((2689, 2722), 'flask.url_for', 'url_for', (['"""portal.templateDetails"""'], {}), "('portal.templateDetails')\n", (2696, 2722), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((4810, 4835), 'pandas.read_csv', 'pandas.read_csv', (['site_Csv'], {}), '(site_Csv)\n', (4825, 4835), False, 'import pandas\n'), ((5166, 5178), 'flask.flash', 'flash', (['error'], {}), '(error)\n', (5171, 5178), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n'), ((5043, 5081), 'flask.url_for', 'url_for', (['"""portal.templateDeployAction"""'], {}), "('portal.templateDeployAction')\n", (5050, 5081), False, 'from flask import Blueprint, flash, g, redirect, render_template, request, Response, session, url_for\n')] |
# import the necessary packages
from imutils.video import VideoStream
from imutils import face_utils
import argparse
import imutils
import time
import dlib
import cv2
import tensorflow as tf
from tensorflow.keras.models import load_model
import numpy as np
from matplotlib import pyplot as plt
import os
# construct the argument parser and parse the arguments
#path to facial landmark predictor
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--shape-predictor", required=True,
help="path to facial landmark predictor")
#path to video or use camera
ap.add_argument("-i", "--input_method", required=True,
help="path to video or use camera")
args = vars(ap.parse_args())
# initialize dlib's face detector (HOG-based) and then load our trained shape predictor
print("[INFO] loading facial landmark predictor...")
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(args["shape_predictor"])
camera_video=int(args["input_method"])
# 0 for video camera
if camera_video is 0:
# initialize the video stream and allow the cammera sensor to warmup
print("[INFO] camera sensor warming up...")
vs = cv2.VideoCapture(0)
time.sleep(2.0)
#1 for path to video on system
elif camera_video is 1:
vs = cv2.VideoCapture("NTHU_yAWNING/16-FemaleGlasses-Yawning.avi")
#vs=cv2.VideoCapture("D:/sayus/Pictures/Camera Roll/WIN_20200716_18_36_16_Pro.mp4")
else:
print("Invalid Argument")
d=0
e=0
#load our pre-trained feature extractotr and yawn detector
feature_extractor=load_model('feature_extractor_1.h5')
yawn_detector=load_model('GRU_best_1.h5')
#set threshold values
yawn_detection_sigmoid=0.70
yawn_detection_frames=0
yawn_detection=0
input_feature_extractor=[]
count=0
start_time = time.perf_counter()
is_yawn=False
# loop over the frames from the video stream
while True:
# grab the frame from the video stream, resize it to have a
# maximum width of 400 pixels, and convert it to grayscale
grabbed,frame = vs.read()
if grabbed==False:
break
count=count+1
frame = imutils.resize(frame, width=400)
# detect faces in image
rects = detector(frame, 0)
# loop over the face detections
for rect in rects:
# convert the dlib rectangle into an OpenCV bounding box and draw a bounding box surrounding the face
#use our custom dlib shape predictor to predict the location
# of our landmark coordinates, then convert the prediction to
# an easily parsable NumPy array
shape = predictor(frame, rect)
shape = face_utils.shape_to_np(shape)
(x, y, w, h) = cv2.boundingRect(shape)
#extract mouth region
roi = frame[y-int(h/3):y + int(h), x:x + int(w)]
#resize to 50x50
roi=cv2.resize(roi,(50,50))
cv2.rectangle(frame, (x, y-int(h/3)), (x + int(w), y + int(5*h/4)), (0, 255, 0), 2)
input_feature_extractor.append(roi)
#append 32 frames together and make prediction
if len(input_feature_extractor)<32:
continue
input_feature_extractor=np.array(input_feature_extractor)
out_feature_extractor=feature_extractor.predict(input_feature_extractor)
out_feature_extractor=out_feature_extractor.reshape(1,32,256)
out_yawn_detector=yawn_detector.predict(out_feature_extractor)
#check for threshold
if out_yawn_detector > yawn_detection_sigmoid:
yawn_detection=yawn_detection+1
if yawn_detection>yawn_detection_frames:
frame = cv2.putText(frame, 'Yawning', (275,25), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 1, cv2.LINE_AA)
end_time = time.perf_counter()
u1=float("{:.2f}".format(count/(end_time-start_time)))
u="fps: "+str(u1)
#put fps on frame
cv2.putText(frame, u, (15,25), cv2.FONT_HERSHEY_SIMPLEX ,
1, (255,0,0), 1, cv2.LINE_AA)
is_yawn=True
yawn_detection=0
else:
yawn_detection=0
input_feature_extractor=[]
# show the frame
end_time = time.perf_counter()
u1=float("{:.2f}".format(count/(end_time-start_time)))
u="fps: "+str(u1)
# if is_yawn==False:
# frame = cv2.putText(frame, 'Not Yawning', (205,25), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 1, cv2.LINE_AA)
# else:
# is_yawn=False
cv2.putText(frame, u, (15,25), cv2.FONT_HERSHEY_SIMPLEX ,
1, (255,0,0), 1, cv2.LINE_AA)
cv2.imshow("Frame", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
vs.release()
| [
"argparse.ArgumentParser",
"dlib.shape_predictor",
"time.perf_counter",
"time.sleep",
"cv2.putText",
"dlib.get_frontal_face_detector",
"imutils.resize",
"cv2.imshow",
"tensorflow.keras.models.load_model",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"imutils.face_utils.shape_to_np",
"numpy.a... | [((421, 446), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (444, 446), False, 'import argparse\n'), ((863, 895), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), '()\n', (893, 895), False, 'import dlib\n'), ((909, 954), 'dlib.shape_predictor', 'dlib.shape_predictor', (["args['shape_predictor']"], {}), "(args['shape_predictor'])\n", (929, 954), False, 'import dlib\n'), ((1543, 1579), 'tensorflow.keras.models.load_model', 'load_model', (['"""feature_extractor_1.h5"""'], {}), "('feature_extractor_1.h5')\n", (1553, 1579), False, 'from tensorflow.keras.models import load_model\n'), ((1595, 1622), 'tensorflow.keras.models.load_model', 'load_model', (['"""GRU_best_1.h5"""'], {}), "('GRU_best_1.h5')\n", (1605, 1622), False, 'from tensorflow.keras.models import load_model\n'), ((1771, 1790), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (1788, 1790), False, 'import time\n'), ((4346, 4369), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (4367, 4369), False, 'import cv2\n'), ((1165, 1184), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (1181, 1184), False, 'import cv2\n'), ((1188, 1203), 'time.sleep', 'time.sleep', (['(2.0)'], {}), '(2.0)\n', (1198, 1203), False, 'import time\n'), ((2073, 2105), 'imutils.resize', 'imutils.resize', (['frame'], {'width': '(400)'}), '(frame, width=400)\n', (2087, 2105), False, 'import imutils\n'), ((3883, 3902), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (3900, 3902), False, 'import time\n'), ((4147, 4240), 'cv2.putText', 'cv2.putText', (['frame', 'u', '(15, 25)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1)', '(255, 0, 0)', '(1)', 'cv2.LINE_AA'], {}), '(frame, u, (15, 25), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 1,\n cv2.LINE_AA)\n', (4158, 4240), False, 'import cv2\n'), ((4260, 4286), 'cv2.imshow', 'cv2.imshow', (['"""Frame"""', 'frame'], {}), "('Frame', frame)\n", (4270, 4286), False, 'import cv2\n'), ((1268, 1329), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""NTHU_yAWNING/16-FemaleGlasses-Yawning.avi"""'], {}), "('NTHU_yAWNING/16-FemaleGlasses-Yawning.avi')\n", (1284, 1329), False, 'import cv2\n'), ((2533, 2562), 'imutils.face_utils.shape_to_np', 'face_utils.shape_to_np', (['shape'], {}), '(shape)\n', (2555, 2562), False, 'from imutils import face_utils\n'), ((2581, 2604), 'cv2.boundingRect', 'cv2.boundingRect', (['shape'], {}), '(shape)\n', (2597, 2604), False, 'import cv2\n'), ((2709, 2734), 'cv2.resize', 'cv2.resize', (['roi', '(50, 50)'], {}), '(roi, (50, 50))\n', (2719, 2734), False, 'import cv2\n'), ((2988, 3021), 'numpy.array', 'np.array', (['input_feature_extractor'], {}), '(input_feature_extractor)\n', (2996, 3021), True, 'import numpy as np\n'), ((4292, 4306), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (4303, 4306), False, 'import cv2\n'), ((3397, 3499), 'cv2.putText', 'cv2.putText', (['frame', '"""Yawning"""', '(275, 25)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1)', '(0, 0, 255)', '(1)', 'cv2.LINE_AA'], {}), "(frame, 'Yawning', (275, 25), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0,\n 255), 1, cv2.LINE_AA)\n", (3408, 3499), False, 'import cv2\n'), ((3509, 3528), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (3526, 3528), False, 'import time\n'), ((3640, 3733), 'cv2.putText', 'cv2.putText', (['frame', 'u', '(15, 25)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1)', '(255, 0, 0)', '(1)', 'cv2.LINE_AA'], {}), '(frame, u, (15, 25), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 1,\n cv2.LINE_AA)\n', (3651, 3733), False, 'import cv2\n')] |
"""Tests related to template reading."""
from configparser import ConfigParser
import pytest
import flatware.template_reading as reading
def test_template_splits():
"""Test that templates split in the required method."""
template = """[name]
type=str
default=<NAME>
---
Hello {{ name }}!"""
config, template = reading.parse_template_config(template)
assert template[0] == "H"
assert config.get("name", "type") == "str"
def test_template_splits_limited():
"""Test that templates are limited to splitting once."""
template = """[packages]
type=list
default="htop vim git"
---
---
This should be after the tripe dash.
"""
config, template = reading.parse_template_config(template)
assert '---\n' in template
assert config.get("packages", "type") == "list"
def test_read_incomplete_template():
"""Test the reading of incomplete templates."""
template = """[place]
type=str
default=M.I.T
"""
with pytest.raises(TypeError) as e_info:
reading.parse_template_config(template)
assert "Invalid Template" in e_info.value.args[0]
def test_create_argument_list():
"""Test the creation of argument lists from configs."""
raw_config = """[firstname]
type=str
default=rayman"""
config = ConfigParser()
config.read_string(raw_config)
results = reading.get_template_arguments(config)
assert results[0]['name'] == 'firstname'
def test_incorrect_template_argument_types():
"""Test to make sure incorrect argument types are not accepted."""
raw_config = """[place]
type=location
"""
config = ConfigParser()
config.read_string(raw_config)
with pytest.raises(TypeError) as e_info:
reading.get_template_arguments(config)
assert "not an accepted template argument" in e_info.value.args[0]
def test_string_argument_parsing():
"""Test that generated argument parsers can read strings properly."""
arguments = [
{
"name": "firstname",
"type": "str",
"default": "<NAME>",
},
]
parser = reading.build_template_argparser(arguments)
values = parser.parse_args(["--firstname", "john"])
assert values.firstname == "john"
def test_list_argument_parsing():
"""Test the parsing of list arguments."""
arguments = [
{
"name": "places",
"type": "list",
"default": None
}
]
parser = reading.build_template_argparser(arguments)
values = parser.parse_args(["--places", "hawaii", "california", "oregon"])
assert values.places == ["hawaii", "california", "oregon"]
values_with_spaces = parser.parse_args(['--places', "california",
"new mexico", "washington"])
assert values_with_spaces.places == ["california",
"new mexico",
"washington"]
def test_default_integer_argument_value():
"""Test that default arguments have the proper type."""
arguments = [
{
"name": "sum",
"type": "int",
"default": "4"
},
]
parser = reading.build_template_argparser(arguments)
values = parser.parse_args([])
assert values.sum == 4
def test_default_list_argument_value():
"""Test default arguments for lists."""
arguments = [
{
"name": "foods",
"type": "list",
"default": "pizza salad soup",
}
]
parser = reading.build_template_argparser(arguments)
values = parser.parse_args([])
assert values.foods == ["pizza", "salad", "soup"]
def test_falsy_default_argument_values():
"""Test the absence of default arguments."""
arguments = [
{
"name": "nonrequired",
"type": "str",
"default": None
},
]
parser = reading.build_template_argparser(arguments)
values = parser.parse_args([])
assert values.nonrequired == ''
def test_end_to_end_parsing():
"""Test one path through the template parsing."""
template = """[name]
type=str
---
Hello, this is my template!"""
template, parser = reading.make_argparse_from_template(template)
assert template == "Hello, this is my template!"
values = parser.parse_args(["--name", "<NAME>"])
assert values.name == "<NAME>"
| [
"configparser.ConfigParser",
"flatware.template_reading.parse_template_config",
"flatware.template_reading.build_template_argparser",
"pytest.raises",
"flatware.template_reading.make_argparse_from_template",
"flatware.template_reading.get_template_arguments"
] | [((326, 365), 'flatware.template_reading.parse_template_config', 'reading.parse_template_config', (['template'], {}), '(template)\n', (355, 365), True, 'import flatware.template_reading as reading\n'), ((676, 715), 'flatware.template_reading.parse_template_config', 'reading.parse_template_config', (['template'], {}), '(template)\n', (705, 715), True, 'import flatware.template_reading as reading\n'), ((1257, 1271), 'configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (1269, 1271), False, 'from configparser import ConfigParser\n'), ((1321, 1359), 'flatware.template_reading.get_template_arguments', 'reading.get_template_arguments', (['config'], {}), '(config)\n', (1351, 1359), True, 'import flatware.template_reading as reading\n'), ((1583, 1597), 'configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (1595, 1597), False, 'from configparser import ConfigParser\n'), ((2059, 2102), 'flatware.template_reading.build_template_argparser', 'reading.build_template_argparser', (['arguments'], {}), '(arguments)\n', (2091, 2102), True, 'import flatware.template_reading as reading\n'), ((2422, 2465), 'flatware.template_reading.build_template_argparser', 'reading.build_template_argparser', (['arguments'], {}), '(arguments)\n', (2454, 2465), True, 'import flatware.template_reading as reading\n'), ((3161, 3204), 'flatware.template_reading.build_template_argparser', 'reading.build_template_argparser', (['arguments'], {}), '(arguments)\n', (3193, 3204), True, 'import flatware.template_reading as reading\n'), ((3510, 3553), 'flatware.template_reading.build_template_argparser', 'reading.build_template_argparser', (['arguments'], {}), '(arguments)\n', (3542, 3553), True, 'import flatware.template_reading as reading\n'), ((3884, 3927), 'flatware.template_reading.build_template_argparser', 'reading.build_template_argparser', (['arguments'], {}), '(arguments)\n', (3916, 3927), True, 'import flatware.template_reading as reading\n'), ((4178, 4223), 'flatware.template_reading.make_argparse_from_template', 'reading.make_argparse_from_template', (['template'], {}), '(template)\n', (4213, 4223), True, 'import flatware.template_reading as reading\n'), ((952, 976), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (965, 976), False, 'import pytest\n'), ((996, 1035), 'flatware.template_reading.parse_template_config', 'reading.parse_template_config', (['template'], {}), '(template)\n', (1025, 1035), True, 'import flatware.template_reading as reading\n'), ((1642, 1666), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (1655, 1666), False, 'import pytest\n'), ((1686, 1724), 'flatware.template_reading.get_template_arguments', 'reading.get_template_arguments', (['config'], {}), '(config)\n', (1716, 1724), True, 'import flatware.template_reading as reading\n')] |
import pandas as pd
import os, sys
from pandas.tseries.holiday import USFederalHolidayCalendar
from pandas.tseries.offsets import CustomBusinessDay
from sklearn.utils import check_array
import numpy as np
from datetime import timedelta
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))+'/'
def mean_absolute_percentage_error(y_true, y_pred):
mask = y_true != 0
return (np.fabs(y_true - y_pred)/y_true)[mask].mean()
# function that returns a list of days not including weekends, holidays, or event day
# if pge == True will return weekdays for PG&E otherwise it will return weekdays for SCE
def get_workdays(start,end):
start = pd.to_datetime(start).date()
end = pd.to_datetime(end).date()
us_bd = CustomBusinessDay(calendar=USFederalHolidayCalendar())
workdays = pd.DatetimeIndex(start=start, end=end, freq=us_bd)
return workdays
# Returns the start and end timestamp of a single day
def get_window_of_day(date):
date = pd.to_datetime(date).date()
start, end = pd.date_range(start=date, periods=2, freq='1d', tz='US/Pacific')
start_ts = start.isoformat()
end_ts = end.isoformat()
return start_ts, end_ts
def get_closest_station(site):
stations = pd.read_csv(os.path.join(PROJECT_ROOT, 'weather_stations.csv'), index_col='site')
try:
uuid = stations.loc[site].values[0]
return uuid
except:
print("couldn't find closest weather station for %s" % site)
return None
def get_date_str(date):
date = pd.to_datetime(date).date()
return format(date)
def get_month_window(date):
end_date = pd.to_datetime(date).date() + timedelta(days=2)
start_date = end_date - timedelta(days=30)
start_ts = pd.to_datetime(start_date).tz_localize('US/Pacific').isoformat()
end_ts = pd.to_datetime(end_date).tz_localize('US/Pacific').isoformat()
return start_ts, end_ts | [
"numpy.fabs",
"pandas.tseries.holiday.USFederalHolidayCalendar",
"pandas.DatetimeIndex",
"pandas.to_datetime",
"os.path.join",
"os.path.dirname",
"datetime.timedelta",
"pandas.date_range"
] | [((800, 850), 'pandas.DatetimeIndex', 'pd.DatetimeIndex', ([], {'start': 'start', 'end': 'end', 'freq': 'us_bd'}), '(start=start, end=end, freq=us_bd)\n', (816, 850), True, 'import pandas as pd\n'), ((1011, 1075), 'pandas.date_range', 'pd.date_range', ([], {'start': 'date', 'periods': '(2)', 'freq': '"""1d"""', 'tz': '"""US/Pacific"""'}), "(start=date, periods=2, freq='1d', tz='US/Pacific')\n", (1024, 1075), True, 'import pandas as pd\n'), ((268, 293), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (283, 293), False, 'import os, sys\n'), ((1225, 1275), 'os.path.join', 'os.path.join', (['PROJECT_ROOT', '"""weather_stations.csv"""'], {}), "(PROJECT_ROOT, 'weather_stations.csv')\n", (1237, 1275), False, 'import os, sys\n'), ((1631, 1648), 'datetime.timedelta', 'timedelta', ([], {'days': '(2)'}), '(days=2)\n', (1640, 1648), False, 'from datetime import timedelta\n'), ((1677, 1695), 'datetime.timedelta', 'timedelta', ([], {'days': '(30)'}), '(days=30)\n', (1686, 1695), False, 'from datetime import timedelta\n'), ((652, 673), 'pandas.to_datetime', 'pd.to_datetime', (['start'], {}), '(start)\n', (666, 673), True, 'import pandas as pd\n'), ((691, 710), 'pandas.to_datetime', 'pd.to_datetime', (['end'], {}), '(end)\n', (705, 710), True, 'import pandas as pd\n'), ((757, 783), 'pandas.tseries.holiday.USFederalHolidayCalendar', 'USFederalHolidayCalendar', ([], {}), '()\n', (781, 783), False, 'from pandas.tseries.holiday import USFederalHolidayCalendar\n'), ((966, 986), 'pandas.to_datetime', 'pd.to_datetime', (['date'], {}), '(date)\n', (980, 986), True, 'import pandas as pd\n'), ((1505, 1525), 'pandas.to_datetime', 'pd.to_datetime', (['date'], {}), '(date)\n', (1519, 1525), True, 'import pandas as pd\n'), ((1601, 1621), 'pandas.to_datetime', 'pd.to_datetime', (['date'], {}), '(date)\n', (1615, 1621), True, 'import pandas as pd\n'), ((388, 412), 'numpy.fabs', 'np.fabs', (['(y_true - y_pred)'], {}), '(y_true - y_pred)\n', (395, 412), True, 'import numpy as np\n'), ((1711, 1737), 'pandas.to_datetime', 'pd.to_datetime', (['start_date'], {}), '(start_date)\n', (1725, 1737), True, 'import pandas as pd\n'), ((1789, 1813), 'pandas.to_datetime', 'pd.to_datetime', (['end_date'], {}), '(end_date)\n', (1803, 1813), True, 'import pandas as pd\n')] |
"""
UKPDS
See:
"""
import numpy as np
from cvdm.score import BaseRisk
from cvdm.score import clean_age, clean_hba1c, clean_bp, clean_tchdl
# coefficients for survival
BETA = np.array([ 1.059, # age at diagnosis of diabetes
0.525, # risk for females
0.390, # Afro-Carribean ethnicity
1.350, # smoking
1.183, # HBA1c
1.088, # 10mmHg increase in systolic blood pressure
3.845 # unit increase in log of lipid ratio
])
Q_0 = 0.0112 # intercept
D = 1.078 # risk ratio for each year increase in duration of diagnosed diabetes
def ukpds(ageDiab, age, female, ac, smoking, hba1c, sbp, tchdl, tYear=10):
"""
Calculate the number of years to forecast the risk.
"""
xFeat = np.array([clean_age(age)-55,
female,
ac,
bool(smoking),
clean_hba1c(hba1c)-6.72,
(clean_bp(sbp) - 135.7)/10,
np.log(clean_tchdl(tchdl))-1.59])
q = Q_0 * np.prod(np.power(BETA, xFeat))
uscore = 1 - np.exp(-q * D**(age-ageDiab)* (1-D**tYear)/ (1 - D))
return max(uscore, 0.0)
class Ukpds(BaseRisk):
tYear = None
features = ["diab_age",
"index_age",
"female",
"AC",
"cur_smoke",
"hba1c",
"sbp"]
feat_key = features + ["tchdl"]
def __init__(self, tYear=10):
self.tYear = tYear
def score(self, row):
return ukpds(row["diab_age"],
row["index_age"],
row["female"],
row["AC"],
row["cur_smoke"],
row["hba1c"],
row["sbp"],
row["tchdl"],
tYear=self.tYear)
def get_features(self, row):
feat_dict = super().get_features(row)
feat_dict["tchdl_log"] = np.log(row["tchdl"])
return feat_dict
| [
"numpy.power",
"cvdm.score.clean_age",
"numpy.log",
"numpy.exp",
"numpy.array",
"cvdm.score.clean_hba1c",
"cvdm.score.clean_tchdl",
"cvdm.score.clean_bp"
] | [((179, 236), 'numpy.array', 'np.array', (['[1.059, 0.525, 0.39, 1.35, 1.183, 1.088, 3.845]'], {}), '([1.059, 0.525, 0.39, 1.35, 1.183, 1.088, 3.845])\n', (187, 236), True, 'import numpy as np\n'), ((1134, 1196), 'numpy.exp', 'np.exp', (['(-q * D ** (age - ageDiab) * (1 - D ** tYear) / (1 - D))'], {}), '(-q * D ** (age - ageDiab) * (1 - D ** tYear) / (1 - D))\n', (1140, 1196), True, 'import numpy as np\n'), ((2003, 2023), 'numpy.log', 'np.log', (["row['tchdl']"], {}), "(row['tchdl'])\n", (2009, 2023), True, 'import numpy as np\n'), ((1094, 1115), 'numpy.power', 'np.power', (['BETA', 'xFeat'], {}), '(BETA, xFeat)\n', (1102, 1115), True, 'import numpy as np\n'), ((807, 821), 'cvdm.score.clean_age', 'clean_age', (['age'], {}), '(age)\n', (816, 821), False, 'from cvdm.score import clean_age, clean_hba1c, clean_bp, clean_tchdl\n'), ((941, 959), 'cvdm.score.clean_hba1c', 'clean_hba1c', (['hba1c'], {}), '(hba1c)\n', (952, 959), False, 'from cvdm.score import clean_age, clean_hba1c, clean_bp, clean_tchdl\n'), ((989, 1002), 'cvdm.score.clean_bp', 'clean_bp', (['sbp'], {}), '(sbp)\n', (997, 1002), False, 'from cvdm.score import clean_age, clean_hba1c, clean_bp, clean_tchdl\n'), ((1045, 1063), 'cvdm.score.clean_tchdl', 'clean_tchdl', (['tchdl'], {}), '(tchdl)\n', (1056, 1063), False, 'from cvdm.score import clean_age, clean_hba1c, clean_bp, clean_tchdl\n')] |
import numpy as np
import pandas as pd
from shapely.geometry import Point
import folium
import geopandas as gpd
from shapely.wkt import loads
from math import isnan
import gspread
from oauth2client.service_account import ServiceAccountCredentials
wgs84 = {'init': 'epsg:4326'}
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('gsheets.json', scope)
gc = gspread.authorize(credentials)
wks_laws = gc.open("environmental-laws").sheet1
val_laws = wks_laws.get_all_values()
laws = pd.DataFrame(val_laws[1:], columns=val_laws[0])
laws = laws.astype({'lat': int, 'long':int})
laws_geom = [Point(xy) for xy in zip(laws['lat'], laws['long'])]
laws = gpd.GeoDataFrame(laws, crs=wgs84, geometry=laws_geom)
wks_states = gc.open("states-folium").sheet1
val_states = wks_states.get_all_values()
states = pd.DataFrame(val_states[1:], columns=val_states[0])
states = states.astype({'Code': str, 'Name': str, 'Summary': str, 'State': str, 'Local': str})
states = gpd.GeoDataFrame(states, crs=wgs84)
states['geometry'] = states['geometry'].apply(lambda x: loads(x))
states_dict = {}
for index, row in states.iterrows():
states_dict[row['Name']] = {'geom':states['geometry'][index:index+1],
'summary': row['Summary'],
'state': row['State'],
'local': row['Local']}
m = folium.Map([40, -100], zoom_start=4, control_scale=True, tiles='cartodbpositron')
for index, row in laws.iterrows():
category = row['category']
location = row['location']
level = row['level']
folium.Marker(
location=[row['lat'], row['long']],
popup=f'<h3>Category</h3>{category}<h3>Location</h3>{location}<h3>Government level</h3>{level}',
icon=folium.Icon(color='red', icon='info-sign')
).add_to(m)
def style_function(feature):
return {
'fillColor': '#99d8c9',
'color': '#2ca25f',
'weight': 1.5
}
def highlight_function(feature):
return {
'fillColor': '#2ca25f',
'color': 'green',
'weight': 3
}
for key, value in states_dict.items():
if len(value['summary']) > 0:
c = folium.GeoJson(
value['geom'],
style_function=style_function,
highlight_function=highlight_function)
summary = value['summary']
state = value['state']
local = value['local']
popup=f'<h3>Summary</h3>{summary}<h3>State laws</h3>{state}<h3>Local laws</h3>{local}'
folium.Popup(popup).add_to(c)
c.add_to(m)
m.save('folium-gspread.html')
| [
"gspread.authorize",
"folium.GeoJson",
"folium.Icon",
"shapely.wkt.loads",
"folium.Map",
"shapely.geometry.Point",
"oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name",
"folium.Popup",
"pandas.DataFrame",
"geopandas.GeoDataFrame"
] | [((393, 464), 'oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name', 'ServiceAccountCredentials.from_json_keyfile_name', (['"""gsheets.json"""', 'scope'], {}), "('gsheets.json', scope)\n", (441, 464), False, 'from oauth2client.service_account import ServiceAccountCredentials\n'), ((470, 500), 'gspread.authorize', 'gspread.authorize', (['credentials'], {}), '(credentials)\n', (487, 500), False, 'import gspread\n'), ((594, 641), 'pandas.DataFrame', 'pd.DataFrame', (['val_laws[1:]'], {'columns': 'val_laws[0]'}), '(val_laws[1:], columns=val_laws[0])\n', (606, 641), True, 'import pandas as pd\n'), ((760, 813), 'geopandas.GeoDataFrame', 'gpd.GeoDataFrame', (['laws'], {'crs': 'wgs84', 'geometry': 'laws_geom'}), '(laws, crs=wgs84, geometry=laws_geom)\n', (776, 813), True, 'import geopandas as gpd\n'), ((910, 961), 'pandas.DataFrame', 'pd.DataFrame', (['val_states[1:]'], {'columns': 'val_states[0]'}), '(val_states[1:], columns=val_states[0])\n', (922, 961), True, 'import pandas as pd\n'), ((1067, 1102), 'geopandas.GeoDataFrame', 'gpd.GeoDataFrame', (['states'], {'crs': 'wgs84'}), '(states, crs=wgs84)\n', (1083, 1102), True, 'import geopandas as gpd\n'), ((1472, 1558), 'folium.Map', 'folium.Map', (['[40, -100]'], {'zoom_start': '(4)', 'control_scale': '(True)', 'tiles': '"""cartodbpositron"""'}), "([40, -100], zoom_start=4, control_scale=True, tiles=\n 'cartodbpositron')\n", (1482, 1558), False, 'import folium\n'), ((701, 710), 'shapely.geometry.Point', 'Point', (['xy'], {}), '(xy)\n', (706, 710), False, 'from shapely.geometry import Point\n'), ((1159, 1167), 'shapely.wkt.loads', 'loads', (['x'], {}), '(x)\n', (1164, 1167), False, 'from shapely.wkt import loads\n'), ((2270, 2373), 'folium.GeoJson', 'folium.GeoJson', (["value['geom']"], {'style_function': 'style_function', 'highlight_function': 'highlight_function'}), "(value['geom'], style_function=style_function,\n highlight_function=highlight_function)\n", (2284, 2373), False, 'import folium\n'), ((2625, 2644), 'folium.Popup', 'folium.Popup', (['popup'], {}), '(popup)\n', (2637, 2644), False, 'import folium\n'), ((1858, 1900), 'folium.Icon', 'folium.Icon', ([], {'color': '"""red"""', 'icon': '"""info-sign"""'}), "(color='red', icon='info-sign')\n", (1869, 1900), False, 'import folium\n')] |
"""
Simple socket helper to handle large data frames and
ensure complete data frames are received.
"""
import struct
def send_msg(sock, msg):
"""
sock: socket
msg: byte string
send data packet with length prefix
"""
# Prefix each message with a 4-byte length (network byte order)
msg = struct.pack('>I', len(msg)) + msg
# sendall is a high-level Python-only method that sends the entire buffer
sock.sendall(msg)
def recv_msg(sock):
"""
sock: socket
receive data packet with length prefix
:return: bytearray
"""
# Read message length and unpack it into an integer
# message lenght is 4 bytes as message prefix
raw_msglen = recvall(sock, 4)
if not raw_msglen:
return None
msglen = struct.unpack('>I', raw_msglen)[0]
# Read the message data
return recvall(sock, msglen)
def recvall(sock, n):
"""
sock: socket
n: integer, data amount
receive n-amount of data from socket
:return: bytearray
"""
data = bytearray()
while len(data) < n:
packet = sock.recv(n - len(data))
if not packet:
return None
data.extend(packet)
return data
| [
"struct.unpack"
] | [((769, 800), 'struct.unpack', 'struct.unpack', (['""">I"""', 'raw_msglen'], {}), "('>I', raw_msglen)\n", (782, 800), False, 'import struct\n')] |
#!/usr/bin/env python
import webapp2
from google.appengine.api import app_identity
from google.appengine.api import mail
from conference import ConferenceApi
from google.appengine.api import app_identity
from google.appengine.api import mail
from google.appengine.api import memcache
from google.appengine.ext import ndb
from models import Session
# Handlers for taskqueues
class SendConfirmationEmailHandler(webapp2.RequestHandler):
def post(self):
"""Send email confirming Conference creation."""
mail.send_mail(
'<EMAIL>' % (
app_identity.get_application_id()), # from
self.request.get('email'), # to
'You created a new Conference!', # subj
'Hi, you have created a following ' # body
'conference:\r\n\r\n%s' % self.request.get(
'conferenceInfo')
)
class SetAnnouncementHandler(webapp2.RequestHandler):
def get(self):
"""Set Announcement in Memcache."""
ConferenceApi._cacheAnnouncement()
# If the speaker hosts at least one other session in this conference,
# set them as the new featured speaker. This is called when a new
# session is added to the conference.
class SetFeaturedSpeaker(webapp2.RequestHandler):
def get(self):
conf = ndb.Key(urlsafe=self.request.get('websafeConferenceKey'))
sessions = Session.query(ancestor=conf)
speaker_sessions = sessions.filter(Session.speaker == self.request.get('speaker'))
speaker_session_names = [self.request.get('speaker')]
for sess in speaker_sessions:
speaker_session_names.append(sess.name)
if len(speaker_session_names) > 2:
memcache.set(key='featured_speaker_sessions', value=speaker_session_names)
# Set URL's for each handler
app = webapp2.WSGIApplication([
('/crons/set_announcement', SetAnnouncementHandler),
('/tasks/send_confirmation_email', SendConfirmationEmailHandler),
('/tasks/set_featured_speaker', SetFeaturedSpeaker),
], debug=True) | [
"models.Session.query",
"google.appengine.api.memcache.set",
"webapp2.WSGIApplication",
"conference.ConferenceApi._cacheAnnouncement",
"google.appengine.api.app_identity.get_application_id"
] | [((1858, 2077), 'webapp2.WSGIApplication', 'webapp2.WSGIApplication', (["[('/crons/set_announcement', SetAnnouncementHandler), (\n '/tasks/send_confirmation_email', SendConfirmationEmailHandler), (\n '/tasks/set_featured_speaker', SetFeaturedSpeaker)]"], {'debug': '(True)'}), "([('/crons/set_announcement', SetAnnouncementHandler\n ), ('/tasks/send_confirmation_email', SendConfirmationEmailHandler), (\n '/tasks/set_featured_speaker', SetFeaturedSpeaker)], debug=True)\n", (1881, 2077), False, 'import webapp2\n'), ((1046, 1080), 'conference.ConferenceApi._cacheAnnouncement', 'ConferenceApi._cacheAnnouncement', ([], {}), '()\n', (1078, 1080), False, 'from conference import ConferenceApi\n'), ((1420, 1448), 'models.Session.query', 'Session.query', ([], {'ancestor': 'conf'}), '(ancestor=conf)\n', (1433, 1448), False, 'from models import Session\n'), ((1747, 1821), 'google.appengine.api.memcache.set', 'memcache.set', ([], {'key': '"""featured_speaker_sessions"""', 'value': 'speaker_session_names'}), "(key='featured_speaker_sessions', value=speaker_session_names)\n", (1759, 1821), False, 'from google.appengine.api import memcache\n'), ((579, 612), 'google.appengine.api.app_identity.get_application_id', 'app_identity.get_application_id', ([], {}), '()\n', (610, 612), False, 'from google.appengine.api import app_identity\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
# 根目录配置
# 要求将浏览的文件目录挂载到statics/mountfile目录,没有对任意位置的目录做兼容性测试,因为我准备使用docker容器运行程序,正好是挂载方式。
# 使用normpath对windows和linux的路径分隔符做兼容
baseroot = os.path.normpath(os.path.join(os.path.dirname(__file__), 'statics/mountfile'))
def root():
return baseroot
# 数据库配置
dbconfig={
'DBHost': '10.0.0.24',
'DBPort': '3306',
'User': 'root',
'Pwd': '<PASSWORD>',
'Database': 'zyimg'
}
def mysqlconfig():
return dbconfig
| [
"os.path.dirname"
] | [((223, 248), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (238, 248), False, 'import os\n')] |
"""
Module contenant les classes utiles à la modélisation sous forme de graphe :
Sommet, Arc, Graphe
auteur : cmarichal
"""
from typing import Tuple, List
from math import floor
import numpy as np
from classes_traitement_plan import CouleurSpeciale, Plan
class Sommet:
"""Sommet ayant une position et un numéro"""
def __init__(self, numero: int, pos: Tuple[int, int], majeur: bool = False):
self.pos = pos
self.numero = numero
self.majeur = majeur
class Arc:
"""Arc comportant 2 sommets, une longueur et une route"""
def __init__(self, sommet_depart: Sommet, sommet_arrive: Sommet, longueur: int):
self.sommets = (sommet_depart, sommet_arrive)
self.longueur = longueur
class Graphe:
"""Graphe mathématique comportant la liste des sommets et la matrice d'adjacence"""
def __init__(self):
self.matrice_adjacence = np.array([])
self.liste_sommets = []
@staticmethod
def graphe_from_plan(plan: Plan):
"""retourne le graphe associé à une image prétraitée"""
nouveau_graphe = Graphe()
sommets, coefprop = Graphe.cherche_sommets(plan)
nouveau_graphe.liste_sommets = sommets
Gr = []
for i in range(len(sommets)): # crée une matrice de zéros d'une taille adaptée
Gr.append([0] * len(sommets))
for i in range(len(sommets) - 1):
for k in range(i + 1, len(sommets)):
if plan.verifLignePaint(sommets[i].pos, sommets[k].pos): # vérifie que 2 sommets sont reliés par un arc
x = sommets[i].pos[0] - sommets[k].pos[0]
y = sommets[i].pos[1] - sommets[k].pos[1]
Gr[i][k] = floor(coefprop * np.sqrt(x ** 2 + y ** 2)) # distance entre les sommets
Gr[k][i] = Gr[i][k] # matrice symetrique
else:
Gr[i][k] = -1 # sommet inaccessible
Gr[k][i] = -1
nouveau_graphe.matrice_adjacence = np.array(Gr)
return nouveau_graphe
@staticmethod
def cherche_sommets(plan: Plan) -> Tuple[List[Sommet], float]:
"""repère les sommets/pixels rouges"""
sommets = []
echelle = []
for i in range(len(plan.image_255)):
for j in range(len(plan.image_255[0])):
code_pixel = list(plan.image_255[i][j])
if code_pixel == CouleurSpeciale.ROUGE.value:
sommets.append(Sommet(numero=len(sommets), pos=(i, j)))
elif code_pixel == CouleurSpeciale.ROSE.value:
sommets.append(Sommet(numero=len(sommets), pos=(i, j), majeur=True))
elif code_pixel == CouleurSpeciale.VIOLET.value:
echelle.append((i, j))
coefprop = plan.echelle / (echelle[1][1] - echelle[0][1]) # coefficient de propotionnalité pixels/metres
return sommets, coefprop
def get_liste_arcs_graphe(self) -> List[Tuple[int, int]]:
"""renvoie la liste de tous les arcs"""
L = []
for i in range(len(self.matrice_adjacence)):
for j in range(len(self.matrice_adjacence[0])):
if self.matrice_adjacence[i][j] != 0 and self.matrice_adjacence[i][j] != -1:
L.append((i, j))
return L
def get_liste_sommets_majeurs(self) -> List[Sommet]:
"""Renvoie la liste des sommets majeurs"""
sommets_majeurs = []
for sommet in self.liste_sommets:
if sommet.majeur:
sommets_majeurs.append(sommet)
return sommets_majeurs
| [
"numpy.array",
"numpy.sqrt"
] | [((895, 907), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (903, 907), True, 'import numpy as np\n'), ((2004, 2016), 'numpy.array', 'np.array', (['Gr'], {}), '(Gr)\n', (2012, 2016), True, 'import numpy as np\n'), ((1730, 1754), 'numpy.sqrt', 'np.sqrt', (['(x ** 2 + y ** 2)'], {}), '(x ** 2 + y ** 2)\n', (1737, 1754), True, 'import numpy as np\n')] |
import os
import sys
import json
import datetime
import numpy as np
import skimage.draw
from mrcnn.visualize import display_images
import mrcnn.model as modellib
from mrcnn.model import log
from config.fashion_config import FashionConfig
from config.dataset import FashionDataset
# Path to trained weights file
COCO_WEIGHTS_PATH = os.path.join("", "weight/mask_rcnn_coco.h5")
# Path to Datasets
DEFAULT_DATASETS_DIR = os.path.join("", "datasets")
# through the command line argument --logs
DEFAULT_LOGS_DIR = os.path.join("", "logs")
def train(model):
"""Train the model."""
# Training dataset.
dataset_train = FashionDataset()
dataset_train.load_data(args.dataset+"/train.json", args.dataset+"/train")
dataset_train.prepare()
# Validation dataset
dataset_val = FashionDataset()
dataset_val.load_data(args.dataset+"/validation.json", args.dataset+"/val")
dataset_val.prepare()
# *** This training schedule is an example. Update to your needs ***
# Since we're using a very small dataset, and starting from
# COCO trained weights, we don't need to train too long. Also,
# no need to train all layers, just the heads should do it.
print("Training network heads")
model.train(dataset_train, dataset_val,
learning_rate=config.LEARNING_RATE,
epochs=15 ,
layers='heads')
model.train(dataset_train, dataset_val,
learning_rate=config.LEARNING_RATE / 10,
epochs=30,
layers="all")
if __name__ == '__main__':
import argparse
# Parse command line arguments
parser = argparse.ArgumentParser(
description='Train Mask R-CNN to detect fashion.')
parser.add_argument('--dataset', required=False,
default=DEFAULT_DATASETS_DIR,
help='Directory of the fashion dataset')
parser.add_argument('--weights', required=False,
default=COCO_WEIGHTS_PATH,
help="Path to weights .h5 file or 'coco'")
parser.add_argument('--logs', required=False,
default=DEFAULT_LOGS_DIR,
metavar="/path/to/logs/",
help='Logs and checkpoints directory (default=logs/)')
args = parser.parse_args()
print("Weights: ", args.weights)
print("Dataset: ", args.dataset)
print("Logs: ", args.logs)
# Configurations
config = FashionConfig()
config.display()
# Create model
model = modellib.MaskRCNN(mode="training", config=config,
model_dir=args.logs)
# Select weights file to load
weights_path = COCO_WEIGHTS_PATH
print("Loading weights ", weights_path)
# Exclude the last layers because they require a matching
# number of classes
model.load_weights(weights_path, by_name=True, exclude=[
"mrcnn_class_logits", "mrcnn_bbox_fc",
"mrcnn_bbox", "mrcnn_mask"])
# Train
train(model)
| [
"mrcnn.model.MaskRCNN",
"argparse.ArgumentParser",
"config.fashion_config.FashionConfig",
"os.path.join",
"config.dataset.FashionDataset"
] | [((334, 378), 'os.path.join', 'os.path.join', (['""""""', '"""weight/mask_rcnn_coco.h5"""'], {}), "('', 'weight/mask_rcnn_coco.h5')\n", (346, 378), False, 'import os\n'), ((422, 450), 'os.path.join', 'os.path.join', (['""""""', '"""datasets"""'], {}), "('', 'datasets')\n", (434, 450), False, 'import os\n'), ((514, 538), 'os.path.join', 'os.path.join', (['""""""', '"""logs"""'], {}), "('', 'logs')\n", (526, 538), False, 'import os\n'), ((629, 645), 'config.dataset.FashionDataset', 'FashionDataset', ([], {}), '()\n', (643, 645), False, 'from config.dataset import FashionDataset\n'), ((797, 813), 'config.dataset.FashionDataset', 'FashionDataset', ([], {}), '()\n', (811, 813), False, 'from config.dataset import FashionDataset\n'), ((1627, 1701), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Train Mask R-CNN to detect fashion."""'}), "(description='Train Mask R-CNN to detect fashion.')\n", (1650, 1701), False, 'import argparse\n'), ((2478, 2493), 'config.fashion_config.FashionConfig', 'FashionConfig', ([], {}), '()\n', (2491, 2493), False, 'from config.fashion_config import FashionConfig\n'), ((2551, 2621), 'mrcnn.model.MaskRCNN', 'modellib.MaskRCNN', ([], {'mode': '"""training"""', 'config': 'config', 'model_dir': 'args.logs'}), "(mode='training', config=config, model_dir=args.logs)\n", (2568, 2621), True, 'import mrcnn.model as modellib\n')] |
# Simple hangman game using Python --- <NAME>
# Import getpass function from getpass module
from getpass import getpass
# Function that returns the current hangman board
def hangmanStages(attempts):
display = ['''
-------
| |
| O
| /|\\
| / \\
|
----- ''','''
-------
| |
| O
| /|\\
| /
|
----- ''','''
-------
| |
| O
| /|\\
|
|
----- ''','''
-------
| |
| O
| /|
|
|
----- ''','''
-------
| |
| O
| |
|
|
----- ''','''
-------
| |
| O
|
|
|
----- ''','''
-------
| |
|
|
|
|
----- ''']
return display[attempts];
# Function to display the hangman board and guesses
def display(attempts, blanks):
print(hangmanStages(attempts))
for i in range (0,len(blanks),1):
print(blanks[i], end=" ")
print("\n")
# Function to play hangman with user chosen word
def playGame(word):
attempts = 6
blanks = '_' * len(word)
alreadyGuessed = []
wordGuessed = False
display(attempts,blanks)
# Loops until player 2 is out of attempts or word is guessed
while wordGuessed == False and attempts != 0:
guess = input("Player 2, guess a letter or the word: ").upper()
# Make sure guess consists of only letters
if guess.isalpha() == True:
# Ends game if player 2 correctly guesses the word
if guess == word:
print("Congrats, you guessed the word correctly!")
wordGuessed = True
# Checks if word or letter has already been guessed
elif guess in alreadyGuessed:
print("You already guessed " + guess)
display(attempts,blanks)
# Checks if guess is a letter
elif len(guess) == 1:
# Checks if letter guessed is in the word
if guess in word:
print("Good guess, " + guess + " is in the word!")
alreadyGuessed.append(guess)
# Replaces blank with correctly guessed letter
listOfBlanks = list(blanks)
indices = [i for i, letter in enumerate(word) if letter == guess]
for index in indices:
listOfBlanks[index] = guess
blanks = "".join(listOfBlanks)
display(attempts,blanks)
# Word has been guessed
if "_" not in blanks:
print("Congrats, you guessed the word correctly!")
wordGuessed = True
# The letter guessed was not in the word
else:
print(guess + " is not in the word.")
attempts -= 1
alreadyGuessed.append(guess)
display(attempts,blanks)
# If word player 2 guessed is not the correct word, attempts left decreases by 1
else:
print(guess + " is not the correct word.")
attempts -= 1
alreadyGuessed.append(guess)
display(attempts,blanks)
# Guess contains non-letter characters
else:
print("Invalid guess...")
display(attempts,blanks)
# Player 2 ran out of attempts and did not guess the word
if wordGuessed == False:
print("You've run out of attempts...")
print("The correct word was " + word)
# Main function
def main():
flag = True
print("Welcome to Hangman!")
print("Player 1 enter a word for player 2 to guess...")
# Loops until player 1 enters a valid word
while flag == True:
# Hides word from player 2 using imported getpass function
word = getpass("Your word will be hidden: ")
if word.isalpha() == False :
print("Sorry, invalid word.")
print("Please enter a different word...")
else:
flag = False
# Changes word to uppercase and calls playGame function
word = word.upper()
playGame(word)
# Loops game, allowing users to play again
while input("Would you like to play again? (Y/N) ").upper() == 'Y':
flag = True
print("Player 1 enter a word for player 2 to guess...")
while flag == True:
word = getpass("Your word will be hidden: ")
if word.isalpha() == False :
print("Sorry, invalid word.")
print("Please enter a different word...")
else:
flag = False
word = word.upper()
playGame(word)
print("Thanks for playing!")
# Runs main function
if __name__ == "__main__":
main()
| [
"getpass.getpass"
] | [((3441, 3478), 'getpass.getpass', 'getpass', (['"""Your word will be hidden: """'], {}), "('Your word will be hidden: ')\n", (3448, 3478), False, 'from getpass import getpass\n'), ((3966, 4003), 'getpass.getpass', 'getpass', (['"""Your word will be hidden: """'], {}), "('Your word will be hidden: ')\n", (3973, 4003), False, 'from getpass import getpass\n')] |
import bourgeon
import ragnarok_client as client
from bourgeon import ui
from ragnarok_client import Mode
class BasicInfoWindow:
def __init__(self, name: str) -> None:
self._hp_text = ui.Text("--")
self._sp_text = ui.Text("--")
self.window = ui.Window(name, [[
ui.Text("HP"),
self._hp_text,
ui.Text("| SP"),
self._sp_text,
]], 0)
def open(self) -> None:
ui.register_window(self.window)
def close(self) -> None:
ui.unregister_window(self.window)
def update(self, hp: int, max_hp: int, sp: int, max_sp: int) -> None:
self._hp_text.set_text(f"{hp} / {max_hp}")
self._sp_text.set_text(f"{sp} / {max_sp}")
basic_info_window = None
def on_tick() -> None:
"""
OnTick callback.
"""
global basic_info_window
if basic_info_window:
basic_info_window.update(client.get_hp(), client.get_max_hp(),
client.get_sp(), client.get_max_sp())
def on_mode_switch(mode_type: Mode, _map_name: str) -> None:
"""
OnModeSwitch callback.
"""
global basic_info_window
if mode_type == Mode.Game:
basic_info_window = BasicInfoWindow(client.get_char_name())
basic_info_window.open()
elif mode_type == Mode.Login:
if basic_info_window:
basic_info_window.close()
bourgeon.register_callback("OnTick", on_tick)
bourgeon.register_callback("OnModeSwitch", on_mode_switch)
| [
"ragnarok_client.get_max_hp",
"ragnarok_client.get_max_sp",
"bourgeon.register_callback",
"ragnarok_client.get_hp",
"bourgeon.ui.unregister_window",
"ragnarok_client.get_sp",
"bourgeon.ui.register_window",
"ragnarok_client.get_char_name",
"bourgeon.ui.Text"
] | [((1379, 1424), 'bourgeon.register_callback', 'bourgeon.register_callback', (['"""OnTick"""', 'on_tick'], {}), "('OnTick', on_tick)\n", (1405, 1424), False, 'import bourgeon\n'), ((1425, 1483), 'bourgeon.register_callback', 'bourgeon.register_callback', (['"""OnModeSwitch"""', 'on_mode_switch'], {}), "('OnModeSwitch', on_mode_switch)\n", (1451, 1483), False, 'import bourgeon\n'), ((198, 211), 'bourgeon.ui.Text', 'ui.Text', (['"""--"""'], {}), "('--')\n", (205, 211), False, 'from bourgeon import ui\n'), ((236, 249), 'bourgeon.ui.Text', 'ui.Text', (['"""--"""'], {}), "('--')\n", (243, 249), False, 'from bourgeon import ui\n'), ((453, 484), 'bourgeon.ui.register_window', 'ui.register_window', (['self.window'], {}), '(self.window)\n', (471, 484), False, 'from bourgeon import ui\n'), ((523, 556), 'bourgeon.ui.unregister_window', 'ui.unregister_window', (['self.window'], {}), '(self.window)\n', (543, 556), False, 'from bourgeon import ui\n'), ((905, 920), 'ragnarok_client.get_hp', 'client.get_hp', ([], {}), '()\n', (918, 920), True, 'import ragnarok_client as client\n'), ((922, 941), 'ragnarok_client.get_max_hp', 'client.get_max_hp', ([], {}), '()\n', (939, 941), True, 'import ragnarok_client as client\n'), ((976, 991), 'ragnarok_client.get_sp', 'client.get_sp', ([], {}), '()\n', (989, 991), True, 'import ragnarok_client as client\n'), ((993, 1012), 'ragnarok_client.get_max_sp', 'client.get_max_sp', ([], {}), '()\n', (1010, 1012), True, 'import ragnarok_client as client\n'), ((1218, 1240), 'ragnarok_client.get_char_name', 'client.get_char_name', ([], {}), '()\n', (1238, 1240), True, 'import ragnarok_client as client\n'), ((303, 316), 'bourgeon.ui.Text', 'ui.Text', (['"""HP"""'], {}), "('HP')\n", (310, 316), False, 'from bourgeon import ui\n'), ((357, 372), 'bourgeon.ui.Text', 'ui.Text', (['"""| SP"""'], {}), "('| SP')\n", (364, 372), False, 'from bourgeon import ui\n')] |
from dnn_schedules.per_layer.hwcf_schedule import HWCFSchedule
# from dnn_schedules.cfhw.cfhw_eyeriss import run_tangram
from attrdict import AttrDict
class FCHWScheduleCFHWTangram2(HWCFSchedule):
def __init__(self, net, model_name, result_dir, verbose, hardware_yaml=None, hardware_dict=None):
super().__init__(net, model_name, result_dir, verbose, hardware_yaml, hardware_dict)
def __str__(self):
return 'fchw_cfhw_schedule'
def run_model(self):
items = list(self.net.layers.items())
idx = 0
while idx < len(items):
current_layer = items[idx][1]
if idx + 1 < len(items):
next_layer = items[idx+1][1]
if current_layer.type == 'Conv2d' and next_layer.type == 'Conv2d':
# if (current_layer.attr_type == 'DW' or current_layer.attr_type == 'PW') \
# and (next_layer.attr_type == 'DW' or next_layer.attr_type == 'PW') :
self.conv_conv(items[idx][1], items[idx+1][1])
idx += 2
continue
if current_layer.type == 'Conv2d':
# if (current_layer.attr_type == 'DW' or current_layer.attr_type == 'PW'):
per_layer_hw_params = self.load_hw_params_conv(True, False, config=3)
per_layer_hw_params['hxx'] = current_layer.Hin
per_layer_hw_params['wxx'] = current_layer.Win
self.conv2d_pw(current_layer, per_layer_hw_params)
self.layer_names.append(current_layer.name)
self.debug_message('===================================================')
self.debug_message(' LAYER NAME: {} LAYER IDX: {}'.format(current_layer.name, current_layer.layer_idx))
idx += 1
def conv_conv(self, first_layer, second_layer):
first_layer_hw_params = self.load_hw_params_conv(True, False, config=3)
first_layer_hw_params['hxx'] = first_layer.Hin
first_layer_hw_params['wxx'] = first_layer.Win
# --- Pointwise 1 stats
self.debug_message('cin= {} cout= {}'.format(first_layer.Cin, first_layer.Cout))
self.debug_message('{} {} {}'.format(first_layer.layer_idx, first_layer.name, first_layer.attr_type))
first_num_macs_w_units = first_layer_hw_params.mac_wxx * (first_layer_hw_params.mac_wxx_type ** 2)
first_layer_mac_units = first_layer_hw_params.mac_cxx * first_num_macs_w_units * first_layer_hw_params.mac_fx
first_layer_padd_units = first_layer_hw_params.mac_wxx * (first_layer_hw_params.mac_wxx_type **2) * first_layer_hw_params.mac_fx
self.insert_max_stats('mac_units_available', first_layer.layer_idx, first_layer_mac_units)
self.insert_max_stats('padd_units_available', first_layer.layer_idx, first_layer_padd_units)
# --- Pointwise 2 stats
second_layer_hw_params = self.load_hw_params_conv(False, False, config=3)
second_layer_hw_params['hxx'] = second_layer.Hin
second_layer_hw_params['wxx'] = second_layer.Win
self.debug_message('{} {} {}'.format(second_layer.layer_idx, second_layer.name, second_layer.attr_type))
second_num_macs_w_units = second_layer_hw_params.mac_wxx * second_layer_hw_params.mac_wxx_type * second_layer_hw_params.mac_wxx_type
second_layer_mac_units = second_layer_hw_params.mac_cxx * second_num_macs_w_units * second_layer_hw_params.mac_fx
self.insert_max_stats('mac_units_available', second_layer.layer_idx, second_layer_mac_units)
second_layer_padd_units = second_layer_hw_params.mac_wxx * second_layer_hw_params.mac_wxx_type * second_layer_hw_params.mac_wxx_type * second_layer_hw_params.mac_fx
self.insert_max_stats('padd_units_available', second_layer.layer_idx, second_layer_padd_units)
# adding mac units
total_mac_units = first_layer_mac_units + second_layer_mac_units
self.insert_max_stats('total_mac_units', first_layer.layer_idx, total_mac_units)
self.insert_max_stats('total_mac_units', second_layer.layer_idx, total_mac_units)
# print('total mac units: {} 1: {} 3: {}'.format(total_mac_units, first_layer_mac_units, second_layer_mac_units))
self.insert_max_stats('total_padd_units', first_layer.layer_idx, first_layer_padd_units)
self.insert_max_stats('total_padd_units', second_layer.layer_idx, second_layer_padd_units)
# -- schedule loop --
if first_layer.attr_type == 'DW':
start_f = 0
end_f = 1
f_tile = first_layer_hw_params.fx
else:
start_f = 0
end_f = first_layer.Cout
f_tile = first_layer_hw_params.fx
batch_cycles_1 = {}
batch_cycles_2 = {}
time_idx_1 = 0
time_idx_2 = 0
for f in range(start_f, end_f, f_tile):
# Note: layer1 in F|C i.e F -> will run Fx idx only
# However, if 'cout'=0 'cout_end'= layer_attr.Cout, it becomes C|F again
end_cout_idx = min(f + first_layer_hw_params.fx, first_layer.Cout) - 1
# num_cout = end_cout_idx - f + 1
for cin in range(0, first_layer.Cin, first_layer_hw_params.cxx):
end_cin_idx = min(cin + first_layer_hw_params.cxx, first_layer.Cin) - 1
self.debug_message('=== Layer 1: PW/DW/CONV ===')
pw_block_start_indices_1 = AttrDict({'orig_hin': 0, 'end_hin': first_layer.Hin,
'orig_win': 0, 'end_win': first_layer.Win,
'orig_cin': cin, 'end_cin': end_cin_idx + 1,
'hout': 0, 'wout': 0,
'cout': f, 'cout_end': end_cout_idx + 1})
if first_layer.attr_type == 'DW':
pw_block_start_indices_1['cout'] = cin
pw_block_start_indices_1['cout_end'] = cin + first_layer.Depth_multiplier
cycles_1 = self.conv2d_pw_block(pw_block_start_indices_1, first_layer,
first_layer_hw_params,
num_cross_layers=3,
layer_position_idx=0)
if time_idx_1 in batch_cycles_1:
batch_cycles_1[time_idx_1] += cycles_1
else:
batch_cycles_1[time_idx_1] = cycles_1
# end cin
time_idx_2 = time_idx_1+1
# --------------------------------------------------------------------------------------------------
# -- start of CONV/PW/DW 2 convolution
# --------------------------------------------------------------------------------------------------
cin_start_2 = f
cin_end_2_idx = end_cout_idx
self.debug_message(' --second layer (hwc) input_act[{}:{}][{}:{}][{}:{}]'.format(
0, second_layer.Hin-1,
0, second_layer.Win-1,
cin_start_2, cin_end_2_idx
))
# Stage 3 PW2 - executes all filters.
# Runs in C|F for all filters of Layer 2
self.debug_message('=== Layer 3: PW ===')
pw2_start_indices = AttrDict({'hin': 0, 'win': 0, 'cin': cin_start_2,
'hout': 0, 'wout': 0, 'cout': 0,
'end_hin': second_layer.Hin,
'end_win': second_layer.Win,
'end_cin': cin_end_2_idx+1,
'end_cout': second_layer.Cout
})
cycles_2 = self.conv2d_pw(second_layer, second_layer_hw_params, pw2_start_indices,
num_cross_layers=3, layer_position_idx=2)
if time_idx_2 in batch_cycles_2:
batch_cycles_2[time_idx_2] += cycles_2
else:
batch_cycles_2[time_idx_2] = cycles_2
time_idx_1 += 1
# end f
assert time_idx_1 == time_idx_2, 'For two layers both times should match'
cross_layer_cycles, cycles_layer1, cycles_layer2 = self.get_global_cycles_two_layer(batch_cycles_1, batch_cycles_2, time_idx_2)
# Add cross_layer_cycles to 'global_cycles'
# Note: Since, the global cycles will be added across layers to get total cycles
# Only add cycles to last of the cross layers
self.insert_max_stats('global_cycles', first_layer.layer_idx, 0)
self.insert_max_stats('global_cycles', second_layer.layer_idx, cross_layer_cycles)
self.insert_max_stats('timing_cycles', first_layer.layer_idx, cycles_layer1)
self.insert_max_stats('timing_cycles', second_layer.layer_idx, cycles_layer2)
return
| [
"attrdict.AttrDict"
] | [((7312, 7522), 'attrdict.AttrDict', 'AttrDict', (["{'hin': 0, 'win': 0, 'cin': cin_start_2, 'hout': 0, 'wout': 0, 'cout': 0,\n 'end_hin': second_layer.Hin, 'end_win': second_layer.Win, 'end_cin': \n cin_end_2_idx + 1, 'end_cout': second_layer.Cout}"], {}), "({'hin': 0, 'win': 0, 'cin': cin_start_2, 'hout': 0, 'wout': 0,\n 'cout': 0, 'end_hin': second_layer.Hin, 'end_win': second_layer.Win,\n 'end_cin': cin_end_2_idx + 1, 'end_cout': second_layer.Cout})\n", (7320, 7522), False, 'from attrdict import AttrDict\n'), ((5411, 5623), 'attrdict.AttrDict', 'AttrDict', (["{'orig_hin': 0, 'end_hin': first_layer.Hin, 'orig_win': 0, 'end_win':\n first_layer.Win, 'orig_cin': cin, 'end_cin': end_cin_idx + 1, 'hout': 0,\n 'wout': 0, 'cout': f, 'cout_end': end_cout_idx + 1}"], {}), "({'orig_hin': 0, 'end_hin': first_layer.Hin, 'orig_win': 0,\n 'end_win': first_layer.Win, 'orig_cin': cin, 'end_cin': end_cin_idx + 1,\n 'hout': 0, 'wout': 0, 'cout': f, 'cout_end': end_cout_idx + 1})\n", (5419, 5623), False, 'from attrdict import AttrDict\n')] |
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
"""Contains functionality used to submit experiments and manage experiment history in Azure Machine Learning."""
import logging
import os
from collections import OrderedDict
from functools import wraps
from azureml._logging import ChainedIdentity
from azureml._project import _commands
from azureml._base_sdk_common.common import check_valid_resource_name
from azureml._restclient.workspace_client import WorkspaceClient
from azureml.core.runconfig import DEFAULT_GPU_IMAGE
from azureml.core._experiment_method import get_experiment_submit, check_for_lock_file
from azureml.core._portal import HasExperimentPortal
from azureml.core._docs import get_docs_url
from azureml.exceptions import UserErrorException
from azureml._html.utilities import to_html, make_link
module_logger = logging.getLogger(__name__)
def _check_for_experiment_id(func):
@wraps(func)
def wrapped(self, *args, **kwargs):
if self._id is None:
raise UserErrorException("{} doesn't have an id set therefore, the {} cannot "
"modify the experiment. Please call the Experiment "
"constructor by setting _create_in_cloud to True".format(
self, self.__class__.__name__))
return func(self, *args, **kwargs)
return wrapped
class ViewType(object):
"""Defines how to filter out or include archived experiments when listing experiments.
Use ViewType in the :meth:`azureml.core.experiment.Experiment.list` method.
Attributes:
ActiveOnly: Show only active experiments.
All: Show all experiments.
ArchivedOnly: Show only archived experiments.
"""
ActiveOnly = "ActiveOnly"
All = "All"
ArchivedOnly = "ArchivedOnly"
class Experiment(ChainedIdentity, HasExperimentPortal):
"""Represents the main entry point for creating and working with experiments in Azure Machine Learning.
An Experiment is a container of *trials* that represent multiple model runs.
.. remarks::
An Azure Machine Learning *experiment* represent the collection of *trials* used to validate a
user's *hypothesis*.
In Azure Machine Learning, an experiment is represented by the :class:`azureml.core.Experiment`
class and a trial is represented by the :class:`azureml.core.Run` class.
To get or create an experiment from a workspace, you request the experiment using the experiment name.
Experiment name must be 3-36 characters, start with a letter or a number, and can only contain letters,
numbers, underscores, and dashes.
.. code-block:: python
experiment = Experiment(workspace, "MyExperiment")
If the experiment is not found in the workspace, a new experiment is created.
There are two ways to execute an experiment trial. If you are interactively experimenting in a
Jupyter notebook, use :func:`start_logging` If you are submitting an experiment from source code
or some other type of configured trial, use :func:`submit`
Both mechanisms create a :class:`azureml.core.Run` object. In interactive scenarios, use logging methods
such as :func:`azureml.core.Run.log` to add measurements and metrics to the trial record. In configured
scenarios use status methods such as :func:`azureml.core.Run.get_status` to retrieve information about the
run.
In both cases you can use query methods like :func:`azureml.core.Run.get_metrics` to retrieve the current
values, if any, of any trial measurements and metrics.
:param workspace: The workspace object containing the experiment.
:type workspace: azureml.core.workspace.Workspace
:param name: The experiment name.
:type name: str
:param kwargs: A dictionary of keyword args.
:type kwargs: dict
"""
def __init__(self,
workspace,
name,
_skip_name_validation=False,
_id=None,
_archived_time=None,
_create_in_cloud=True,
_experiment_dto=None,
**kwargs):
"""Experiment constructor.
:param workspace: The workspace object containing the experiment.
:type workspace: azureml.core.workspace.Workspace
:param name: The experiment name.
:type name: str
:param kwargs: A dictionary of keyword args.
:type kwargs: dict
"""
self._workspace = workspace
self._name = name
self._workspace_client = WorkspaceClient(workspace.service_context)
_ident = kwargs.pop("_ident", ChainedIdentity.DELIM.join([self.__class__.__name__, self._name]))
if not _skip_name_validation:
check_valid_resource_name(name, "Experiment")
# Get or create the experiment from the workspace
if _create_in_cloud:
experiment = self._workspace_client.get_or_create_experiment(experiment_name=name)
self._id = experiment.experiment_id
self._archived_time = experiment.archived_time
self._extract_from_dto(experiment)
else:
self._id = _id
self._archived_time = _archived_time
self._extract_from_dto(_experiment_dto)
super(Experiment, self).__init__(experiment=self, _ident=_ident, **kwargs)
def submit(self, config, tags=None, **kwargs):
r"""Submit an experiment and return the active created run.
.. remarks::
Submit is an asynchronous call to the Azure Machine Learning platform to execute a trial on local
or remote hardware. Depending on the configuration, submit will automatically prepare
your execution environments, execute your code, and capture your source code and results
into the experiment's run history.
To submit an experiment you first need to create a configuration object describing
how the experiment is to be run. The configuration depends on the type of trial required.
An example of how to submit an experiment from your local machine is as follows:
.. code-block:: python
from azureml.core import ScriptRunConfig
# run a trial from the train.py code in your current directory
config = ScriptRunConfig(source_directory='.', script='train.py',
run_config=RunConfiguration())
run = experiment.submit(config)
# get the url to view the progress of the experiment and then wait
# until the trial is complete
print(run.get_portal_url())
run.wait_for_completion()
For details on how to configure a run, see the configuration type details.
* :class:`azureml.core.ScriptRunConfig`
* :class:`azureml.train.automl.automlconfig.AutoMLConfig`
* :class:`azureml.pipeline.core.Pipeline`
* :class:`azureml.pipeline.core.PublishedPipeline`
* :class:`azureml.pipeline.core.PipelineEndpoint`
.. note::
When you submit the training run, a snapshot of the directory that contains your training scripts \
is created and sent to the compute target. It is also stored as part of the experiment in your \
workspace. If you change files and submit the run again, only the changed files will be uploaded.
To prevent files from being included in the snapshot, create a
`.gitignore <https://git-scm.com/docs/gitignore>`_ or `.amlignore` file in the directory and add the
files to it. The `.amlignore` file uses the same syntax and patterns as the .gitignore file. If both
files exist, the `.amlignore` file takes precedence.
For more information, see `Snapshots
<https://docs.microsoft.com/azure/machine-learning/concept-azure-machine-learning-architecture#snapshots>`_.
:param config: The config to be submitted.
:type config: object
:param tags: Tags to be added to the submitted run, {"tag": "value"}.
:type tags: dict
:param kwargs: Additional parameters used in submit function for configurations.
:type kwargs: dict
:return: A run.
:rtype: azureml.core.Run
"""
# Warn user if trying to run GPU image on a local machine
try:
runconfig = config.run_config
if (runconfig.environment.docker.base_image == DEFAULT_GPU_IMAGE and runconfig.target == "local"):
print("Note: The GPU base image must be used on Microsoft Azure Services only. See LICENSE.txt file.")
except AttributeError: # Not all configuration options have run_configs that specify base images
pass
# Warn user if conda lock files haven't been removed for non-Docker run
try:
runconfig = config.run_config
if not runconfig.environment.docker.enabled:
check_for_lock_file()
except AttributeError: # Not all configuration options have run_configs that specify environments
pass
submit_func = get_experiment_submit(config)
with self._log_context("submit config {}".format(config.__class__.__name__)):
run = submit_func(config, self.workspace, self.name, **kwargs)
if tags is not None:
run.set_tags(tags)
return run
def start_logging(self, *args, **kwargs):
"""Start an interactive logging session and create an interactive run in the specified experiment.
.. remarks::
**start_logging** creates an interactive run for use in scenarios such as Jupyter notebooks.
Any metrics that are logged during the session are added to the run record in the experiment.
If an output directory is specified, the contents of that directory is uploaded as run
artifacts upon run completion.
.. code-block:: python
experiment = Experiment(workspace, "My Experiment")
run = experiment.start_logging(outputs=None, snapshot_directory=".")
...
run.log_metric("Accuracy", accuracy)
run.complete()
.. note::
**run_id** is automatically generated for each run and is unique within the experiment.
:param experiment: The experiment.
:type experiment: azureml.core.Experiment
:param outputs: Optional outputs directory to track.
:type outputs: str
:param snapshot_directory: Optional directory to take snapshot of. Setting to None will take no snapshot.
:type snapshot_directory: str
:param args:
:type args: builtin.list
:param kwargs:
:type kwargs: dict
:return: Return a started run.
:rtype: azureml.core.Run
"""
from azureml.core.run import Run
return Run._start_logging(self, *args, _parent_logger=self._logger, **kwargs)
@_check_for_experiment_id
def archive(self):
"""Archive an experiment.
.. remarks::
After archival, the experiment will not be listed by default.
Attempting to write to an archived experiment will create a new active experiment with the same
name.
An archived experiment can be restored by calling :func:`azureml.core.Experiment.reactivate` as long as
there is not another
active experiment with the same name.
"""
updated_experiment = self._workspace_client.archive_experiment(experiment_id=self._id)
self._archived_time = updated_experiment.archived_time
@_check_for_experiment_id
def reactivate(self, new_name=None):
"""Reactivates an archived experiment.
.. remarks::
An archived experiment can only be reactivated if there is not another active experiment with
the same name.
:param new_name: Not supported anymore
:type new_name: str
"""
if new_name is not None:
raise UserErrorException("Cannot rename an experiment. If the archived experiment name conflicts"
" with an active experiment name, you can delete the active experiment"
" before unarchiving this experiment.")
updated_experiment = self._workspace_client.reactivate_experiment(experiment_id=self._id)
self._archived_time = updated_experiment.archived_time
self._name = updated_experiment.name
@_check_for_experiment_id
def tag(self, key, value=None):
"""Tag the experiment with a string key and optional string value.
.. remarks::
Tags on an experiment are stored in a dictionary with string keys and string values.
Tags can be set, updated and deleted.
Tags are user-facing and generally contain meaning information for the consumers of the experiment.
.. code-block:: python
experiment.tag('')
experiment.tag('DeploymentCandidate')
experiment.tag('modifiedBy', 'Master CI')
experiment.tag('modifiedBy', 'release pipeline') # Careful, tags are mutable
:param key: The tag key
:type key: str
:param value: An optional value for the tag
:type value: str
"""
self.set_tags({key: value})
@_check_for_experiment_id
def set_tags(self, tags):
"""Add or modify a set of tags on the experiment. Tags not passed in the dictionary are left untouched.
:param tags: The tags stored in the experiment object
:type tags: dict[str]
"""
self._workspace_client.set_tags(experiment_id=self._id, tags=tags)
@_check_for_experiment_id
def remove_tags(self, tags):
"""Delete the specified tags from the experiment.
:param tags: The tag keys that will get removed
:type tags: [str]
"""
self._workspace_client.delete_experiment_tags(experiment_id=self._id, tags=tags)
@_check_for_experiment_id
def refresh(self):
"""Return the most recent version of the experiment from the cloud."""
experiment = self._workspace_client.get_experiment_by_id(self._id)
self._archived_time = experiment.archived_time
self._extract_from_dto(experiment)
@staticmethod
def from_directory(path, auth=None):
"""(Deprecated) Load an experiment from the specified path.
:param path: Directory containing the experiment configuration files.
:type path: str
:param auth: The auth object.
If None the default Azure CLI credentials will be used or the API will prompt for credentials.
:type auth: azureml.core.authentication.ServicePrincipalAuthentication or
azureml.core.authentication.InteractiveLoginAuthentication
:return: Returns the Experiment
:rtype: azureml.core.Experiment
"""
from azureml.core.workspace import Workspace
info_dict = _commands.get_project_info(auth, path)
# TODO: Fix this
subscription = info_dict[_commands.SUBSCRIPTION_KEY]
resource_group_name = info_dict[_commands.RESOURCE_GROUP_KEY]
workspace_name = info_dict[_commands.WORKSPACE_KEY]
experiment_name = info_dict[_commands.PROJECT_KEY]
workspace = Workspace(
subscription_id=subscription, resource_group=resource_group_name, workspace_name=workspace_name, auth=auth
)
return Experiment(workspace=workspace, name=experiment_name)
@staticmethod
def list(workspace, experiment_name=None, view_type=ViewType.ActiveOnly, tags=None):
"""Return the list of experiments in the workspace.
:param workspace: The workspace from which to list the experiments.
:type workspace: azureml.core.workspace.Workspace
:param experiment_name: Optional name to filter experiments.
:type experiment_name: str
:param view_type: Optional enum value to filter or include archived experiments.
:type view_type: azureml.core.experiment.ViewType
:param tags: Optional tag key or dictionary of tag key-value pairs to filter experiments on.
:type tag: str or dict[str]
:return: A list of experiment objects.
:rtype: builtin.list[azureml.core.Experiment]
"""
workspace_client = WorkspaceClient(workspace.service_context)
experiments = workspace_client.list_experiments(experiment_name=experiment_name,
view_type=view_type, tags=tags)
return [Experiment(workspace,
experiment.name,
_id=experiment.experiment_id,
_archived_time=experiment.archived_time,
_create_in_cloud=False,
_skip_name_validation=True,
_experiment_dto=experiment) for experiment in experiments]
@staticmethod
def delete(workspace, experiment_id):
"""Delete an experiment in the workspace.
:param workspace: The workspace which the experiment belongs to.
:type workspace: azureml.core.workspace.Workspace
:param experiment_id: The experiment id of the experiment to be deleted.
:type experiment_name: str
"""
workspace_client = WorkspaceClient(workspace.service_context)
delete_experiment_timeout_seconds = int(os.getenv('AZUREML_DELETE_EXPERIMENT_TIMEOUT_SECONDS', 240))
workspace_client.delete_experiment(experiment_id, timeout_seconds=delete_experiment_timeout_seconds)
@property
def workspace(self):
"""Return the workspace containing the experiment.
:return: Returns the workspace object.
:rtype: azureml.core.workspace.Workspace
"""
return self._workspace
@property
def workspace_object(self):
"""(Deprecated) Return the workspace containing the experiment.
Use the :attr:`azureml.core.experiment.Experiment.workspace` attribute.
:return: The workspace object.
:rtype: azureml.core.workspace.Workspace
"""
self._logger.warning("Deprecated, use experiment.workspace")
return self.workspace
@property
def name(self):
"""Return name of the experiment.
:return: The name of the experiment.
:rtype: str
"""
return self._name
@property
def id(self):
"""Return id of the experiment.
:return: The id of the experiment.
:rtype: str
"""
return self._id
@property
def archived_time(self):
"""Return the archived time for the experiment. Value should be None for an active experiment.
:return: The archived time of the experiment.
:rtype: str
"""
return self._archived_time
@property
def tags(self):
"""Return the mutable set of tags on the experiment.
:return: The tags on an experiment.
:rtype: dict[str]
"""
return self._tags
def get_runs(self, type=None, tags=None, properties=None, include_children=False):
"""Return a generator of the runs for this experiment, in reverse chronological order.
:param type: Filter the returned generator of runs by the provided type. See
:func:`azureml.core.Run.add_type_provider` for creating run types.
:type type: string
:param tags: Filter runs by "tag" or {"tag": "value"}.
:type tags: string or dict
:param properties: Filter runs by "property" or {"property": "value"}
:type properties: string or dict
:param include_children: By default, fetch only top-level runs. Set to true to list all runs.
:type include_children: bool
:return: The list of runs matching supplied filters.
:rtype: builtin.list[azureml.core.Run]
"""
from azureml.core.run import Run
return Run.list(self, type=type, tags=tags, properties=properties, include_children=include_children)
def _serialize_to_dict(self):
"""Serialize the Experiment object details into a dictionary.
:return: experiment details
:rtype: dict
"""
output_dict = {"Experiment name": self.name,
"Subscription id": self.workspace.subscription_id,
"Resource group": self.workspace.resource_group,
"Workspace name": self.workspace.name}
return output_dict
def _get_base_info_dict(self):
"""Return base info dictionary.
:return:
:rtype: OrderedDict
"""
return OrderedDict([
('Name', self._name),
('Workspace', self._workspace.name)
])
@classmethod
def get_docs_url(cls):
"""Url to the documentation for this class.
:return: url
:rtype: str
"""
return get_docs_url(cls)
def __str__(self):
"""Format Experiment data into a string.
:return:
:rtype: str
"""
info = self._get_base_info_dict()
formatted_info = ',\n'.join(["{}: {}".format(k, v) for k, v in info.items()])
return "Experiment({0})".format(formatted_info)
def __repr__(self):
"""Representation of the object.
:return: Return the string form of the experiment object
:rtype: str
"""
return self.__str__()
def _repr_html_(self):
"""Html representation of the object.
:return: Return an html table representing this experiment
:rtype: str
"""
info = self._get_base_info_dict()
info.update([
('Report Page', make_link(self.get_portal_url(), "Link to Azure Machine Learning studio")),
('Docs Page', make_link(self.get_docs_url(), "Link to Documentation"))
])
return to_html(info)
def _extract_from_dto(self, experiment_dto):
if experiment_dto is None:
self._experiment_dto = experiment_dto
self._tags = None
else:
self._experiment_dto = experiment_dto
self._tags = experiment_dto.tags
| [
"logging.getLogger",
"azureml.exceptions.UserErrorException",
"collections.OrderedDict",
"os.getenv",
"azureml.core._experiment_method.check_for_lock_file",
"azureml._logging.ChainedIdentity.DELIM.join",
"azureml._html.utilities.to_html",
"functools.wraps",
"azureml._base_sdk_common.common.check_val... | [((987, 1014), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1004, 1014), False, 'import logging\n'), ((1062, 1073), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (1067, 1073), False, 'from functools import wraps\n'), ((4917, 4959), 'azureml._restclient.workspace_client.WorkspaceClient', 'WorkspaceClient', (['workspace.service_context'], {}), '(workspace.service_context)\n', (4932, 4959), False, 'from azureml._restclient.workspace_client import WorkspaceClient\n'), ((9702, 9731), 'azureml.core._experiment_method.get_experiment_submit', 'get_experiment_submit', (['config'], {}), '(config)\n', (9723, 9731), False, 'from azureml.core._experiment_method import get_experiment_submit, check_for_lock_file\n'), ((11545, 11615), 'azureml.core.run.Run._start_logging', 'Run._start_logging', (['self', '*args'], {'_parent_logger': 'self._logger'}), '(self, *args, _parent_logger=self._logger, **kwargs)\n', (11563, 11615), False, 'from azureml.core.run import Run\n'), ((15840, 15878), 'azureml._project._commands.get_project_info', '_commands.get_project_info', (['auth', 'path'], {}), '(auth, path)\n', (15866, 15878), False, 'from azureml._project import _commands\n'), ((16184, 16305), 'azureml.core.workspace.Workspace', 'Workspace', ([], {'subscription_id': 'subscription', 'resource_group': 'resource_group_name', 'workspace_name': 'workspace_name', 'auth': 'auth'}), '(subscription_id=subscription, resource_group=resource_group_name,\n workspace_name=workspace_name, auth=auth)\n', (16193, 16305), False, 'from azureml.core.workspace import Workspace\n'), ((17244, 17286), 'azureml._restclient.workspace_client.WorkspaceClient', 'WorkspaceClient', (['workspace.service_context'], {}), '(workspace.service_context)\n', (17259, 17286), False, 'from azureml._restclient.workspace_client import WorkspaceClient\n'), ((18281, 18323), 'azureml._restclient.workspace_client.WorkspaceClient', 'WorkspaceClient', (['workspace.service_context'], {}), '(workspace.service_context)\n', (18296, 18323), False, 'from azureml._restclient.workspace_client import WorkspaceClient\n'), ((20993, 21091), 'azureml.core.run.Run.list', 'Run.list', (['self'], {'type': 'type', 'tags': 'tags', 'properties': 'properties', 'include_children': 'include_children'}), '(self, type=type, tags=tags, properties=properties,\n include_children=include_children)\n', (21001, 21091), False, 'from azureml.core.run import Run\n'), ((21720, 21792), 'collections.OrderedDict', 'OrderedDict', (["[('Name', self._name), ('Workspace', self._workspace.name)]"], {}), "([('Name', self._name), ('Workspace', self._workspace.name)])\n", (21731, 21792), False, 'from collections import OrderedDict\n'), ((22005, 22022), 'azureml.core._docs.get_docs_url', 'get_docs_url', (['cls'], {}), '(cls)\n', (22017, 22022), False, 'from azureml.core._docs import get_docs_url\n'), ((23006, 23019), 'azureml._html.utilities.to_html', 'to_html', (['info'], {}), '(info)\n', (23013, 23019), False, 'from azureml._html.utilities import to_html, make_link\n'), ((5001, 5066), 'azureml._logging.ChainedIdentity.DELIM.join', 'ChainedIdentity.DELIM.join', (['[self.__class__.__name__, self._name]'], {}), '([self.__class__.__name__, self._name])\n', (5027, 5066), False, 'from azureml._logging import ChainedIdentity\n'), ((5122, 5167), 'azureml._base_sdk_common.common.check_valid_resource_name', 'check_valid_resource_name', (['name', '"""Experiment"""'], {}), "(name, 'Experiment')\n", (5147, 5167), False, 'from azureml._base_sdk_common.common import check_valid_resource_name\n'), ((12741, 12948), 'azureml.exceptions.UserErrorException', 'UserErrorException', (['"""Cannot rename an experiment. If the archived experiment name conflicts with an active experiment name, you can delete the active experiment before unarchiving this experiment."""'], {}), "(\n 'Cannot rename an experiment. If the archived experiment name conflicts with an active experiment name, you can delete the active experiment before unarchiving this experiment.'\n )\n", (12759, 12948), False, 'from azureml.exceptions import UserErrorException\n'), ((18373, 18432), 'os.getenv', 'os.getenv', (['"""AZUREML_DELETE_EXPERIMENT_TIMEOUT_SECONDS"""', '(240)'], {}), "('AZUREML_DELETE_EXPERIMENT_TIMEOUT_SECONDS', 240)\n", (18382, 18432), False, 'import os\n'), ((9529, 9550), 'azureml.core._experiment_method.check_for_lock_file', 'check_for_lock_file', ([], {}), '()\n', (9548, 9550), False, 'from azureml.core._experiment_method import get_experiment_submit, check_for_lock_file\n')] |
# Copyright 2018 <NAME>
#
# 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.
import getpass
import itertools
import logging
import os
import pathlib
import pendulum
import qtoml
from . import events, utils
log = logging.getLogger(__name__)
CONFIG_NAME = '.zeitig'
SOURCE_NAME = 'source'
GROUPS_NAME = 'groups'
LAST_NAME = 'last'
DEFAULT_CONFIG_PATHS = [pathlib.Path(p).expanduser() for p in (
'~/.local/share/zeitig',
'~/.config/zeitig',
)]
CONFIG_STORE_ENV_NAME = 'ZEITIG_STORE'
class LastPathNotSetException(Exception):
pass
def find_config_store(cwd=None):
"""Find the config store base directory."""
config_path = os.environ.get(CONFIG_STORE_ENV_NAME)
config_path_override = [pathlib.Path(config_path).expanduser()]\
if config_path else []
if cwd is None:
cwd = pathlib.Path.cwd()
else:
cwd = pathlib.Path(cwd).resolve()
for config_path in itertools.chain(
config_path_override,
map(lambda p: p.joinpath(CONFIG_NAME),
itertools.chain((cwd,), cwd.parents)),
DEFAULT_CONFIG_PATHS
):
try:
if config_path.resolve().is_dir():
return config_path
except FileNotFoundError:
pass
else:
# create default
config_path.mkdir()
return config_path
class Link:
def __init__(self):
self.previous = None
self.next = None
def before(self):
if self.previous:
yield self.previous
yield from self.previous.before()
def after(self):
if self.next:
yield self.next
yield from self.next.after()
def __iter__(self):
return iter(self.after())
@property
def head(self):
"""Find the last element."""
current = self
while current.next:
current = current.next
return current
@property
def root(self):
"""Find the first element."""
current = self
while current.previous:
current = current.previous
return current
def insert(self, next):
"""Insert a next chain after this link."""
if self.next is not None:
self.next.previous, next.next = next, self.next
next.previous, self.next = self, next
@classmethod
def from_sequence(cls, seq):
previous = None
for item in seq:
src = cls(item)
if previous:
previous.insert(src)
yield src
previous = src
class EventSource(Link):
def __init__(self, name):
super().__init__()
self.name = name
@utils.reify
def when(self):
when = pendulum.parse(self.name).in_tz('UTC')
return when
def __repr__(self):
return f'<{self.__class__.__name__} {self.when}>'
class Store:
"""Handle persisting and loading of event sources.
The default lookup precedence for the store is::
- ./.zeitig
- ~/.config/zeitig
- ~/.local/share/zeitig
The user has to explicitelly create the local store `./.zeitig` to be used.
If a local store is found in the parent directories that one is used.
"""
user = getpass.getuser()
def __init__(self, store_path=None, group=None):
self.store_path = store_path if store_path else find_config_store()
self.group = group
def __repr__(self):
return f'{self.__class__.__name__}: {self.store_path} [{self.group}]'
def iter_names_created(self):
"""The list of event paths sorted after creation time."""
paths = sorted(((x, x.stat()) for x in self.source_path.iterdir()),
key=lambda x: (x[1].st_ctime, x[1].st_mtime, x[0].name))
return paths
def iter_names(self):
"""Create a double linked list of all event dates."""
paths = sorted(map(lambda x: x.name, self.source_path.iterdir()))
return EventSource.from_sequence(paths)
@utils.reify
def user_path(self):
user_path = self.store_path.joinpath(self.user)
if not user_path.is_dir():
user_path.mkdir(parents=True)
return user_path
@utils.reify
def group_path(self):
if not self.group and not self.last_path.is_symlink():
raise LastPathNotSetException(
f'You need to link {self.last_path} to a group'
)
group_path = self.user_path.joinpath(GROUPS_NAME,
self.group)\
if self.group else self.last_group_path
if not group_path.is_dir():
group_path.mkdir(parents=True)
return group_path
@utils.reify
def source_path(self):
source_path = self.group_path.joinpath(SOURCE_NAME)
if not source_path.is_dir():
source_path.mkdir(parents=True)
return source_path
@utils.reify
def last_path(self):
last_path = self.user_path.joinpath(LAST_NAME)
return last_path
@utils.reify
def last_group(self):
try:
return self.last_group_path.name
except LastPathNotSetException:
pass
@utils.reify
def last_source(self):
try:
last_path = self.last_path.resolve()
except FileNotFoundError:
pass
else:
if last_path.exists():
last_name = last_path.name
return EventSource(last_name)
@utils.reify
def groups(self):
group_base_path = self.user_path.joinpath(GROUPS_NAME)
if not group_base_path.is_dir():
group_base_path.mkdir(parents=True)
groups = [dir.name for dir in group_base_path.iterdir()
if dir.is_dir()]
return groups
def persist(self, event):
"""Store the event."""
event_path = self.source_path.joinpath(
str(event.when)
)
source = dict(event.source())
with event_path.open('w') as event_file:
qtoml.dump(source, event_file)
log.info('Persisted event: %s', source)
self.link_last_path()
def link_last_path(self):
"""Point last path to the actual group path."""
if self.last_group != self.group:
if self.last_path.exists():
self.last_path.unlink()
self.last_path.symlink_to(self.group_path.relative_to(self.user_path))
@utils.reify
def last_group_path(self):
if not self.last_path.is_symlink():
raise LastPathNotSetException(
f'You need to link {self.last_path} to a group')
resolved_last_path = self.last_path.resolve()
# this fixes old last paths, which point to an event and not to a group
# since we may find the last event easily by sorting timestamps
# it is mor maintable to point to the last group only
if resolved_last_path.is_file():
group_path = resolved_last_path.parent.parent
else:
group_path = resolved_last_path
return group_path
def load(self, filename):
event_path = self.source_path.joinpath(filename)
with event_path.open('r') as event_file:
event = events.Event(**qtoml.load(event_file))
return event
| [
"logging.getLogger",
"itertools.chain",
"qtoml.load",
"pathlib.Path",
"pathlib.Path.cwd",
"os.environ.get",
"pendulum.parse",
"getpass.getuser",
"qtoml.dump"
] | [((707, 734), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (724, 734), False, 'import logging\n'), ((1138, 1175), 'os.environ.get', 'os.environ.get', (['CONFIG_STORE_ENV_NAME'], {}), '(CONFIG_STORE_ENV_NAME)\n', (1152, 1175), False, 'import os\n'), ((3747, 3764), 'getpass.getuser', 'getpass.getuser', ([], {}), '()\n', (3762, 3764), False, 'import getpass\n'), ((1311, 1329), 'pathlib.Path.cwd', 'pathlib.Path.cwd', ([], {}), '()\n', (1327, 1329), False, 'import pathlib\n'), ((849, 864), 'pathlib.Path', 'pathlib.Path', (['p'], {}), '(p)\n', (861, 864), False, 'import pathlib\n'), ((1524, 1560), 'itertools.chain', 'itertools.chain', (['(cwd,)', 'cwd.parents'], {}), '((cwd,), cwd.parents)\n', (1539, 1560), False, 'import itertools\n'), ((6567, 6597), 'qtoml.dump', 'qtoml.dump', (['source', 'event_file'], {}), '(source, event_file)\n', (6577, 6597), False, 'import qtoml\n'), ((1354, 1371), 'pathlib.Path', 'pathlib.Path', (['cwd'], {}), '(cwd)\n', (1366, 1371), False, 'import pathlib\n'), ((3222, 3247), 'pendulum.parse', 'pendulum.parse', (['self.name'], {}), '(self.name)\n', (3236, 3247), False, 'import pendulum\n'), ((1204, 1229), 'pathlib.Path', 'pathlib.Path', (['config_path'], {}), '(config_path)\n', (1216, 1229), False, 'import pathlib\n'), ((7792, 7814), 'qtoml.load', 'qtoml.load', (['event_file'], {}), '(event_file)\n', (7802, 7814), False, 'import qtoml\n')] |
#! /usr/bin/env python3
#
# power_wrangler.py -- Copyright (C) 2016-2017 <NAME>
#
import os, sys, platform, daemon, time, minimalmodbus
from datetime import datetime
if len(sys.argv) != 2:
print()
print('USAGE: %s [serial-device - e.g.: /dev/ttyACM0]' % (sys.argv[0]))
print()
exit(1)
dev = sys.argv[1]
working_dir = '/RAE'
data_dir = working_dir + '/raw'
meter_count = 8
meters = []
with daemon.DaemonContext():
for i in range(meter_count):
meters.append(minimalmodbus.Instrument(dev, i + 1))
meters[i].serial.baudrate = 115200
meters[i].read_registers(4021, 4)
ts = int(time.time())
while True:
while ts == int(time.time()):
time.sleep(0.01)
ts = int(time.time())
dt = datetime.fromtimestamp(ts)
log_name = '%s/SUB_%04d-%02d-%02d.csv' % (data_dir, dt.year, dt.month, dt.day)
f = open(log_name, 'a')
for i in range(meter_count):
raw = meters[i].read_registers(4021, 43)
raw = [ts, chr(ord('A') + i)] + raw
f.write(','.join([str(v) for v in raw]) + '\n')
f.close()
| [
"datetime.datetime.fromtimestamp",
"minimalmodbus.Instrument",
"time.sleep",
"time.time",
"daemon.DaemonContext"
] | [((415, 437), 'daemon.DaemonContext', 'daemon.DaemonContext', ([], {}), '()\n', (435, 437), False, 'import os, sys, platform, daemon, time, minimalmodbus\n'), ((631, 642), 'time.time', 'time.time', ([], {}), '()\n', (640, 642), False, 'import os, sys, platform, daemon, time, minimalmodbus\n'), ((771, 797), 'datetime.datetime.fromtimestamp', 'datetime.fromtimestamp', (['ts'], {}), '(ts)\n', (793, 797), False, 'from datetime import datetime\n'), ((494, 530), 'minimalmodbus.Instrument', 'minimalmodbus.Instrument', (['dev', '(i + 1)'], {}), '(dev, i + 1)\n', (518, 530), False, 'import os, sys, platform, daemon, time, minimalmodbus\n'), ((711, 727), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (721, 727), False, 'import os, sys, platform, daemon, time, minimalmodbus\n'), ((745, 756), 'time.time', 'time.time', ([], {}), '()\n', (754, 756), False, 'import os, sys, platform, daemon, time, minimalmodbus\n'), ((685, 696), 'time.time', 'time.time', ([], {}), '()\n', (694, 696), False, 'import os, sys, platform, daemon, time, minimalmodbus\n')] |
"""Support routines for the qdyn_prop_gate utility"""
import re
import numpy as np
from .units import UnitFloat
def _isqrt(n):
"""Integer square root of n > 0
>>> _isqrt(1024**2)
1024
>>> _isqrt(10)
3
"""
assert n >= 0
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x
def get_prop_gate_of_t(gates_file, with_t=False):
r"""Yield gates in `gates_file`, where `gates_file` is in the format
written by the ``qdyn_prop_gate`` utility's ``--write-gate`` option. That
is, each row in `gates_files` has $2 n^2 + 1$ columns. The first column is
a time stamp, the remaining columns are the real and imaginary part for
each entry in the $n \times n$ gate (vectorized in column-major format). If
`with_t` is False (default), yield only the gates, otherwise yield both the
gates and the time stamp for each gate
Returns:
* If ``with_t=False``, iterator over gates, where each gate is a
complex $n \times n$ numpy matrix, or a Gate2Q instance for a $4
\times 4$ gate
* If ``with_t=True``, iterator of tuples ``(gate, t)``, where ``t`` is
a float or an instance of UnitFloat if the time unit can be derived
from the header of `gates_file`
"""
with open(gates_file) as in_fh:
time_unit = None
for line in in_fh:
if line.startswith('#'):
try:
time_unit = re.search(r't\s*\[(\w+)\]', line).group(1)
except AttributeError:
pass
else:
vals = np.array([float(v) for v in line.split()])
n = _isqrt((len(vals) - 1) // 2)
assert 2 * n * n + 1 == len(vals)
shape = (n, n)
gate = np.reshape(
vals[1::2], shape, order='F'
) + 1j * np.reshape(vals[2::2], shape, order='F')
if with_t:
if time_unit is not None:
yield gate, UnitFloat(vals[0], time_unit)
else:
yield gate, vals[0]
else:
yield gate
| [
"numpy.reshape",
"re.search"
] | [((1834, 1874), 'numpy.reshape', 'np.reshape', (['vals[1::2]', 'shape'], {'order': '"""F"""'}), "(vals[1::2], shape, order='F')\n", (1844, 1874), True, 'import numpy as np\n'), ((1920, 1960), 'numpy.reshape', 'np.reshape', (['vals[2::2]', 'shape'], {'order': '"""F"""'}), "(vals[2::2], shape, order='F')\n", (1930, 1960), True, 'import numpy as np\n'), ((1490, 1526), 're.search', 're.search', (['"""t\\\\s*\\\\[(\\\\w+)\\\\]"""', 'line'], {}), "('t\\\\s*\\\\[(\\\\w+)\\\\]', line)\n", (1499, 1526), False, 'import re\n')] |
import os
import types
class Config:
"""
Dictionary-like class for holding configuration values.
Normalizes all keys to lowercase, and allows you to use `config.foo` just
like you would `config['foo']`.
"""
def __init__(self, data=None):
super().__setattr__("_data", {}) # avoid recursion in __setattr__
if data:
self.update(data)
def get(self, key, default=None):
if key in self:
return self[key]
return default
def setdefault(self, key, value):
if key not in self:
self[key] = value
def update(self, *args, **kwargs):
for arg in args:
kwargs.update(arg)
for key, value in kwargs.items():
self[key] = value
def update_from_env(self, prefix="FJELL_"):
prefix_len = len(prefix)
for key, value in os.environ.items():
if key.startswith(prefix):
key = key[prefix_len:]
self[key] = value
def update_from_file(self, path):
if path.endswith(".json"):
import json
with open(path) as f:
self.update(json.load(f))
elif path.endswith((".yml", ".yaml")):
import yaml
with open(path) as f:
self.update(yaml.load(f.read()))
elif path.endswith(".toml"):
import toml
self.update(toml.load(path))
elif path.endswith(".py"):
obj = types.ModuleType("config")
obj.__file__ = path
with open(path, "rb") as config_file:
exec(compile(config_file.read(), path, "exec"), obj.__dict__)
self.update_from_object(obj)
else:
raise ValueError("unknown file type: %s" % path)
def update_from_object(self, obj):
for key in dir(obj):
if not key.startswith("_"):
self[key] = getattr(obj, key)
def __getitem__(self, key):
return self._data[key.lower()]
__getattr__ = __getitem__
def __setitem__(self, key, value):
if isinstance(value, dict):
value = Config(value)
self._data[key.lower()] = value
__setattr__ = __setitem__
def __delitem__(self, key):
del self._data[key.lower()]
__delattr__ = __delitem__
def __contains__(self, key):
return key.lower() in self._data
| [
"os.environ.items",
"json.load",
"types.ModuleType",
"toml.load"
] | [((876, 894), 'os.environ.items', 'os.environ.items', ([], {}), '()\n', (892, 894), False, 'import os\n'), ((1169, 1181), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1178, 1181), False, 'import json\n'), ((1424, 1439), 'toml.load', 'toml.load', (['path'], {}), '(path)\n', (1433, 1439), False, 'import toml\n'), ((1494, 1520), 'types.ModuleType', 'types.ModuleType', (['"""config"""'], {}), "('config')\n", (1510, 1520), False, 'import types\n')] |
# -*- coding: utf-8 -*-
# @Time : 2017/7/27 13:47
# @Author : play4fun
# @File : HoughCircles_camera.py
# @Software: PyCharm
"""
HoughCircles_camera.py:
用围棋-棋子来测试
"""
import cv2
import numpy as np
from skimage.measure import compare_mse as mse
import string, random
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
cap = cv2.VideoCapture(0)
# ret = cap.set(3, 640)
# ret = cap.set(4, 480)
# margin = 60
margin = 30
def draw_line_rectangle(frame, margin):
rows, cols, ch = frame.shape # (720, 1280, 3)
half = int(cols / 2)
# 中间
cv2.line(frame, (half, 0), (half, rows), (0, 0, 255), 2)
# margin = 40
# 左边
up_left1 = (margin, margin) # 左上点
down_right1 = (cols - margin, rows - margin) # 右下点
# print(up_left, down_right)
cv2.rectangle(frame, up_left1, down_right1, (0, 255, 0), 3)
ret, temp = cap.read()
tm = 0
while cap.isOpened():
key = cv2.waitKey(1)
if key == ord("q"):
break
if key == ord('s'):
cv2.imwrite(id_generator() + '.jpg', frame2)
# Capture frame-by-frame
ret, frame = cap.read()
m = mse(cv2.cvtColor(temp, cv2.COLOR_BGR2GRAY), cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY))
print('mse', m, '----\n')
if abs(m - tm) < 2: # 静止画面,不用重复计算
continue
else:
temp = frame.copy()
tm = m
#
# print(margin,frame.shape[0] - margin, margin,frame.shape[1] - margin)#40 680 40 1240
frame2 = frame[margin:frame.shape[0] - margin, margin:frame.shape[1] - margin] # .copy()
# cv2.imshow('frame2', frame2)
gray = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
# edges = cv2.Canny(gray, 50, 150, apertureSize=3)
# HoughCircles(image, method, dp, minDist, circles=None, param1=None, param2=None, minRadius=None, maxRadius=None)
# circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=100, param2=30, minRadius=10, maxRadius=40)
# circles = circles1[0, :, :] # 提取为二维
# circles = np.uint16(np.around(circles1))
print(circles)
cimg = frame2
if circles is not None:
for i in circles[0, :]:
# for i in circles[:]:
# draw the outer circle
cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)
# draw the center of the circle
cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)
# cv2.imshow('detected circles', cimg)
draw_line_rectangle(frame, margin)
cv2.imshow("houghlines", frame)
# cv2.imwrite('frame3.jpg', frame[margin:frame.shape[0] - margin, margin:frame.shape[1] - margin])
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
| [
"cv2.rectangle",
"random.choice",
"cv2.line",
"cv2.HoughCircles",
"cv2.imshow",
"cv2.circle",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.cvtColor",
"cv2.waitKey"
] | [((420, 439), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (436, 439), False, 'import cv2\n'), ((2804, 2827), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (2825, 2827), False, 'import cv2\n'), ((647, 703), 'cv2.line', 'cv2.line', (['frame', '(half, 0)', '(half, rows)', '(0, 0, 255)', '(2)'], {}), '(frame, (half, 0), (half, rows), (0, 0, 255), 2)\n', (655, 703), False, 'import cv2\n'), ((864, 923), 'cv2.rectangle', 'cv2.rectangle', (['frame', 'up_left1', 'down_right1', '(0, 255, 0)', '(3)'], {}), '(frame, up_left1, down_right1, (0, 255, 0), 3)\n', (877, 923), False, 'import cv2\n'), ((988, 1002), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (999, 1002), False, 'import cv2\n'), ((1646, 1686), 'cv2.cvtColor', 'cv2.cvtColor', (['frame2', 'cv2.COLOR_BGR2GRAY'], {}), '(frame2, cv2.COLOR_BGR2GRAY)\n', (1658, 1686), False, 'import cv2\n'), ((1990, 2094), 'cv2.HoughCircles', 'cv2.HoughCircles', (['gray', 'cv2.HOUGH_GRADIENT', '(1)', '(20)'], {'param1': '(100)', 'param2': '(30)', 'minRadius': '(10)', 'maxRadius': '(40)'}), '(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=100, param2=30,\n minRadius=10, maxRadius=40)\n', (2006, 2094), False, 'import cv2\n'), ((2610, 2641), 'cv2.imshow', 'cv2.imshow', (['"""houghlines"""', 'frame'], {}), "('houghlines', frame)\n", (2620, 2641), False, 'import cv2\n'), ((1188, 1226), 'cv2.cvtColor', 'cv2.cvtColor', (['temp', 'cv2.COLOR_BGR2GRAY'], {}), '(temp, cv2.COLOR_BGR2GRAY)\n', (1200, 1226), False, 'import cv2\n'), ((1228, 1267), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (1240, 1267), False, 'import cv2\n'), ((369, 389), 'random.choice', 'random.choice', (['chars'], {}), '(chars)\n', (382, 389), False, 'import string, random\n'), ((2363, 2415), 'cv2.circle', 'cv2.circle', (['cimg', '(i[0], i[1])', 'i[2]', '(0, 255, 0)', '(2)'], {}), '(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)\n', (2373, 2415), False, 'import cv2\n'), ((2472, 2521), 'cv2.circle', 'cv2.circle', (['cimg', '(i[0], i[1])', '(2)', '(0, 0, 255)', '(3)'], {}), '(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)\n', (2482, 2521), False, 'import cv2\n')] |
"""This script is used for doing off-line meta testing."""
from metaworld.benchmarks import ML45WithPinnedGoal
from metarl.experiment.meta_test_helper import MetaTestHelper
if __name__ == "__main__":
MetaTestHelper.read_cmd(ML45WithPinnedGoal.get_test_tasks)
| [
"metarl.experiment.meta_test_helper.MetaTestHelper.read_cmd"
] | [((206, 264), 'metarl.experiment.meta_test_helper.MetaTestHelper.read_cmd', 'MetaTestHelper.read_cmd', (['ML45WithPinnedGoal.get_test_tasks'], {}), '(ML45WithPinnedGoal.get_test_tasks)\n', (229, 264), False, 'from metarl.experiment.meta_test_helper import MetaTestHelper\n')] |
import os
from typing import List, Dict
from collections import namedtuple, deque
Vec = namedtuple('Vec', 'x, y')
class Cart:
"""
Represents a single cart using a position vector and a direction vector
"""
def __init__(self, pos: Vec, dir_: Vec) -> None:
self.pos = pos
self.dir = dir_
self.crashed = False
"""
A fixed-size deque makes it trivial to keep track of which direction
the cart will turn at the next intersection as you can simply call
deque.rotate(-1) whenever an intersection is encountered and it will
rotate to the next direction.
"""
self.next_intersection = deque(('left', 'straight', 'right'))
def update(self, segment: str):
"""
Updates the cart to its next position according to the part of track
it is on. Direction is also updated accordingly.
"""
if not self.crashed:
if segment == '/':
self.dir = Vec(-self.dir.y, -self.dir.x)
elif segment == '\\':
self.dir = Vec(self.dir.y, self.dir.x)
elif segment == '+':
if self.next_intersection[0] == 'left':
if self.dir.y == 0:
self.dir = Vec(0, -self.dir.x)
else:
self.dir = Vec(self.dir.y, 0)
elif self.next_intersection[0] == 'right':
if self.dir.y == 0:
self.dir = Vec(0, self.dir.x)
else:
self.dir = Vec(-self.dir.y, 0)
elif self.next_intersection[0] == 'straight':
pass
self.next_intersection.rotate(-1)
self.pos = Vec(self.pos.x + self.dir.x, self.pos.y + self.dir.y)
def create_track(track_rows: List[str]) -> List[List[str]]:
"""
Parses the track and returns it as a graph / list of lists. Cart markers
are ignored and replaced with correct track segments.
"""
track: List[List[str]] = []
for y in range(len(track_rows)):
segments = []
for segment in track_rows[y]:
if segment == '^':
segment = '|'
elif segment == '>':
segment = '-'
elif segment == '<':
segment = '-'
elif segment == 'v':
segment = '|'
segments.append(segment)
track.append(segments)
return track
def create_carts(track_rows: List[str]) -> List[Cart]:
"""
Parses the track and returns a list of Carts.
"""
carts: List[Cart] = []
for y in range(len(track_rows)):
for x, segment in enumerate(track_rows[y]):
if segment in ('^', 'v', '<', '>'):
if segment == '^':
direction = Vec(0, -1)
elif segment == '>':
direction = Vec(1, 0)
elif segment == '<':
direction = Vec(-1, 0)
else:
direction = Vec(0, 1)
position = Vec(x, y)
carts.append(Cart(position, direction))
return carts
def find_crashes(carts: List[Cart]) -> List[Vec]:
"""
Checks carts for crashes and returns coordinates for any crashes. As a
side-effect if a cart is found to have crashed it is flagged as crashed.
"""
cart_at: Dict[Vec, Cart] = {}
crashes: List[Vec] = []
for cart in carts:
if not cart.crashed:
if cart.pos in cart_at:
crashes.append(cart.pos)
cart.crashed = True
cart_at[cart.pos].crashed = True
else:
cart_at[cart.pos] = cart
return crashes
if __name__ == '__main__':
"""
The first half of the puzzle can be solved by constructing a graph of the
track and then running a simulation of the carts on the graph.
"""
with open(os.path.join('inputs', 'day13.in')) as f:
original_track = f.read().splitlines()
carts = create_carts(original_track)
crashes: List[Vec] = []
while not crashes:
for cart in sorted(carts, key=lambda cart: cart.pos):
cart.update(original_track[cart.pos.y][cart.pos.x])
crashes = find_crashes(carts)
if crashes:
break
assert crashes[0] == Vec(116, 10)
"""
The second half of the puzzle is essentially the same thing but the exit
condition is that only one cart is left so loop until only one cart is
left.
"""
carts = create_carts(original_track)
crashes = []
while len([cart for cart in carts if not cart.crashed]) > 1:
for cart in sorted(carts, key=lambda cart: cart.pos):
cart.update(original_track[cart.pos.y][cart.pos.x])
_ = find_crashes(carts)
# Get the last cart still riding around
cart = [cart for cart in carts if not cart.crashed][0]
assert cart.pos == Vec(116, 25)
| [
"os.path.join",
"collections.namedtuple",
"collections.deque"
] | [((91, 116), 'collections.namedtuple', 'namedtuple', (['"""Vec"""', '"""x, y"""'], {}), "('Vec', 'x, y')\n", (101, 116), False, 'from collections import namedtuple, deque\n'), ((676, 712), 'collections.deque', 'deque', (["('left', 'straight', 'right')"], {}), "(('left', 'straight', 'right'))\n", (681, 712), False, 'from collections import namedtuple, deque\n'), ((3984, 4018), 'os.path.join', 'os.path.join', (['"""inputs"""', '"""day13.in"""'], {}), "('inputs', 'day13.in')\n", (3996, 4018), False, 'import os\n')] |
import tcp
import random
class ServerData(object):
def __init__(self):
self._data = ""
def receive(self, data):
print("input data = {}".format(data))
self._data = data
def send(self):
data = self._data + "{}".format(random.randint(0, 10))
print("make data = {}".format(data))
return data
server_data = ServerData()
server = tcp.TcpServer("localhost", 999,
server_data.receive,
server_data.send,
send_first=False
)
server.daemon = True
server.start()
import time
time.sleep(100)
server.exit() | [
"tcp.TcpServer",
"random.randint",
"time.sleep"
] | [((390, 482), 'tcp.TcpServer', 'tcp.TcpServer', (['"""localhost"""', '(999)', 'server_data.receive', 'server_data.send'], {'send_first': '(False)'}), "('localhost', 999, server_data.receive, server_data.send,\n send_first=False)\n", (403, 482), False, 'import tcp\n'), ((623, 638), 'time.sleep', 'time.sleep', (['(100)'], {}), '(100)\n', (633, 638), False, 'import time\n'), ((264, 285), 'random.randint', 'random.randint', (['(0)', '(10)'], {}), '(0, 10)\n', (278, 285), False, 'import random\n')] |
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import autograd.numpy as np
from lifelines.fitters import KnownModelParametericUnivariateFitter
class WeibullFitter(KnownModelParametericUnivariateFitter):
r"""
This class implements a Weibull model for univariate data. The model has parameterized
form:
.. math:: S(t) = \exp\left(-\left(\frac{t}{\lambda}\right)^\rho\right), \lambda > 0, \rho > 0,
which implies the cumulative hazard rate is
.. math:: H(t) = \left(\frac{t}{\lambda}\right)^\rho,
and the hazard rate is:
.. math:: h(t) = \frac{\rho}{\lambda}(t/\lambda )^{\rho-1}
After calling the `.fit` method, you have access to properties like: ``cumulative_hazard_``, ``survival_function_``, ``lambda_`` and ``rho_``.
A summary of the fit is available with the method ``print_summary()``.
Important
----------
The parameterization of this model changed in lifelines 0.19.0. Previously, the cumulative hazard looked like
:math:`(\lambda t)^\rho`. The parameterization is now the recipricol of :math:`\lambda`.
Examples
--------
>>> from lifelines import WeibullFitter
>>> from lifelines.datasets import load_waltons
>>> waltons = load_waltons()
>>> wbf = WeibullFitter()
>>> wbf.fit(waltons['T'], waltons['E'])
>>> wbf.plot()
>>> print(wbf.lambda_)
"""
_fitted_parameter_names = ["lambda_", "rho_"]
def _cumulative_hazard(self, params, times):
lambda_, rho_ = params
return (times / lambda_) ** rho_
@property
def median_(self):
return self.lambda_ * (np.log(2) ** (1.0 / self.rho_))
| [
"autograd.numpy.log"
] | [((1637, 1646), 'autograd.numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (1643, 1646), True, 'import autograd.numpy as np\n')] |
# import the necessary packages
from tensorflow.keras.applications import imagenet_utils
import imutils
def sliding_window(image, step, ws):
# slide a window across the image
for y in range(0, image.shape[0] - ws[1], step):
for x in range(0, image.shape[1] - ws[0], step):
# yield the current window
yield (x, y, image[y:y + ws[1], x:x + ws[0]])
def image_pyramid(image, scale=1.5, minSize=(224, 224)):
# yield the original image
yield image
# keep looping over the image pyramid
while True:
# compute the dimensions of the next image in the pyramid
w = int(image.shape[1] / scale)
image = imutils.resize(image, width=w)
# if the resized image does not meet the supplied minimum
# size, then stop constructing the pyramid
if image.shape[0] < minSize[1] or image.shape[1] < minSize[0]:
break
# yield the next image in the pyramid
yield image
def classify_batch(model, batchROIs, batchLocs, labels, minProb=0.5,
top=10, dims=(224, 224)):
# pass our batch ROIs through our network and decode the
# predictions
preds = model.predict(batchROIs)
P = imagenet_utils.decode_predictions(preds, top=top)
# loop over the decoded predictions
for i in range(0, len(P)):
for (_, label, prob) in P[i]:
# filter out weak detections by ensuring the
# predicted probability is greater than the minimum
# probability
if prob > minProb:
# grab the coordinates of the sliding window for
# the prediction and construct the bounding box
(pX, pY) = batchLocs[i]
box = (pX, pY, pX + dims[0], pY + dims[1])
# grab the list of predictions for the label and
# add the bounding box + probability to the list
L = labels.get(label, [])
L.append((box, prob))
labels[label] = L
# return the labels dictionary
return labels | [
"tensorflow.keras.applications.imagenet_utils.decode_predictions",
"imutils.resize"
] | [((1088, 1137), 'tensorflow.keras.applications.imagenet_utils.decode_predictions', 'imagenet_utils.decode_predictions', (['preds'], {'top': 'top'}), '(preds, top=top)\n', (1121, 1137), False, 'from tensorflow.keras.applications import imagenet_utils\n'), ((613, 643), 'imutils.resize', 'imutils.resize', (['image'], {'width': 'w'}), '(image, width=w)\n', (627, 643), False, 'import imutils\n')] |
# Generated by Django 3.0.4 on 2020-03-15 20:15
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('books', '0008_auto_20200312_2222'),
]
operations = [
migrations.AlterField(
model_name='book',
name='ISBN_Data',
field=models.CharField(max_length=50, null=True),
),
migrations.AlterField(
model_name='book',
name='ISBN_Image',
field=models.FileField(null=True, upload_to='', verbose_name='ISBN_Image'),
),
migrations.AlterField(
model_name='book',
name='current_user',
field=models.CharField(max_length=50, null=True),
),
migrations.AlterField(
model_name='book',
name='deadline_date',
field=models.DateTimeField(default=datetime.datetime(2020, 3, 22, 23, 15, 9, 384270), null=True),
),
migrations.AlterField(
model_name='book',
name='detail',
field=models.CharField(max_length=500, null=True),
),
migrations.AlterField(
model_name='book',
name='upload_date',
field=models.DateTimeField(default=datetime.datetime(2020, 3, 15, 23, 15, 9, 384365)),
),
]
| [
"datetime.datetime",
"django.db.models.FileField",
"django.db.models.CharField"
] | [((351, 393), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)', 'null': '(True)'}), '(max_length=50, null=True)\n', (367, 393), False, 'from django.db import migrations, models\n'), ((517, 585), 'django.db.models.FileField', 'models.FileField', ([], {'null': '(True)', 'upload_to': '""""""', 'verbose_name': '"""ISBN_Image"""'}), "(null=True, upload_to='', verbose_name='ISBN_Image')\n", (533, 585), False, 'from django.db import migrations, models\n'), ((711, 753), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)', 'null': '(True)'}), '(max_length=50, null=True)\n', (727, 753), False, 'from django.db import migrations, models\n'), ((1090, 1133), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(500)', 'null': '(True)'}), '(max_length=500, null=True)\n', (1106, 1133), False, 'from django.db import migrations, models\n'), ((909, 958), 'datetime.datetime', 'datetime.datetime', (['(2020)', '(3)', '(22)', '(23)', '(15)', '(9)', '(384270)'], {}), '(2020, 3, 22, 23, 15, 9, 384270)\n', (926, 958), False, 'import datetime\n'), ((1287, 1336), 'datetime.datetime', 'datetime.datetime', (['(2020)', '(3)', '(15)', '(23)', '(15)', '(9)', '(384365)'], {}), '(2020, 3, 15, 23, 15, 9, 384365)\n', (1304, 1336), False, 'import datetime\n')] |
import os
import ssl
import socket
from tempfile import NamedTemporaryFile
try:
from httplib import HTTPSConnection
except ImportError:
from http.client import HTTPSConnection
class ValidatedHTTPSConnection(HTTPSConnection):
CA_ROOT_CERT_FALLBACK = '''
DigiCert Global Root G2
-----BEGIN CERTIFICATE-----
MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBh
MQ<KEY>
<KEY>Q
q2EGnI/yuum06ZIya7XzV+hdG82MHauVBJVJ8zUtluNJbd134/tJS7SsVQepj5Wz
tCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyMUNGPHgm+F6HmIcr9g+UQ
vIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQABo0IwQDAP
BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV
5uNu5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY
1Yl9PMWLSn/pvtsrF9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4
NeF22d+mQrvHRAiGfzZ0JFrabA0UWTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NG
Fdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBHQRFXGU7Aj64GxJUTFy8bJZ91
8rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/iyK5S9kJRaTe
pLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl
MrY=
-----END CERTIFICATE-----
'''
def get_ca_cert_bundle(self):
via_env = os.getenv('SSL_CERT_FILE')
if via_env is not None and os.path.exists(via_env):
return via_env
probe_paths = [
"/etc/ssl/certs/ca-certificates.crt",
"/etc/ssl/certs/ca-bundle.crt",
"/etc/pki/tls/certs/ca-bundle.crt",
]
for path in probe_paths:
if os.path.exists(path):
return path
return None
def connect(self):
sock = socket.create_connection((self.host, self.port),
self.timeout,
self.source_address)
bundle = cafile = self.get_ca_cert_bundle()
if bundle is None:
ca_certs = NamedTemporaryFile()
ca_certs.write('\n'.join(
map(str.strip, self.CA_ROOT_CERT_FALLBACK.splitlines())
).encode('ascii'))
ca_certs.flush()
cafile = ca_certs.name
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=cafile)
if bundle is None:
ca_certs.close()
| [
"socket.create_connection",
"os.path.exists",
"os.getenv",
"ssl.wrap_socket",
"tempfile.NamedTemporaryFile"
] | [((1279, 1305), 'os.getenv', 'os.getenv', (['"""SSL_CERT_FILE"""'], {}), "('SSL_CERT_FILE')\n", (1288, 1305), False, 'import os\n'), ((1726, 1814), 'socket.create_connection', 'socket.create_connection', (['(self.host, self.port)', 'self.timeout', 'self.source_address'], {}), '((self.host, self.port), self.timeout, self.\n source_address)\n', (1750, 1814), False, 'import socket\n'), ((2238, 2341), 'ssl.wrap_socket', 'ssl.wrap_socket', (['sock', 'self.key_file', 'self.cert_file'], {'cert_reqs': 'ssl.CERT_REQUIRED', 'ca_certs': 'cafile'}), '(sock, self.key_file, self.cert_file, cert_reqs=ssl.\n CERT_REQUIRED, ca_certs=cafile)\n', (2253, 2341), False, 'import ssl\n'), ((1341, 1364), 'os.path.exists', 'os.path.exists', (['via_env'], {}), '(via_env)\n', (1355, 1364), False, 'import os\n'), ((1617, 1637), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (1631, 1637), False, 'import os\n'), ((1992, 2012), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ([], {}), '()\n', (2010, 2012), False, 'from tempfile import NamedTemporaryFile\n')] |
import os
import code
from flask_script import Manager
from flask_migrate import MigrateCommand
from whitebearbake import create_app
port = int(os.environ.get('PORT', 5000))
app = create_app()
def run():
app.run(host='0.0.0.0', port=port)
def cli():
""" Interactive CLI session entrypoint """
with app.app_context():
code.interact(local=locals())
def manage():
from whitebearbake import migrate
manager = Manager(app)
manager.add_command('db', MigrateCommand)
manager.run()
# Run entrypoint
if __name__ == '__main__':
run() | [
"flask_script.Manager",
"os.environ.get",
"whitebearbake.create_app"
] | [((183, 195), 'whitebearbake.create_app', 'create_app', ([], {}), '()\n', (193, 195), False, 'from whitebearbake import create_app\n'), ((147, 175), 'os.environ.get', 'os.environ.get', (['"""PORT"""', '(5000)'], {}), "('PORT', 5000)\n", (161, 175), False, 'import os\n'), ((447, 459), 'flask_script.Manager', 'Manager', (['app'], {}), '(app)\n', (454, 459), False, 'from flask_script import Manager\n')] |
import logging
import numpy as np
from collections import Counter
from imblearn.base import SamplerMixin
from imblearn.utils import check_target_type, hash_X_y
from sklearn.utils import check_X_y, check_random_state, safe_indexing
__all__ = ['RandomUnderSampler']
def check_ratio(ratio, y):
"""check and returns actual and valid ratio"""
target_stats = Counter(y)
diff_target = set(ratio.keys()) - set(target_stats.keys())
# check to ensure all keys in ratio are also in y
# and the ratio are all positive
if diff_target:
raise ValueError(
'The {} target class is/are not present in the data.'.format(diff_target))
if any(n_samples < 0 for n_samples in ratio.values()):
raise ValueError(
'The proportion of samples in a class cannot be negative. '
'Input ratio contains some negative value: {}'.format(ratio))
checked_ratio = {}
for target, n_samples in ratio.items():
target_samples = target_stats[target]
# if it's a float then assume it's asking for a
# proportion of the targeted sample
if isinstance(n_samples, float):
n_samples = int(n_samples * target_samples)
if n_samples > target_samples:
raise ValueError(
'With under-sampling methods, the number of '
'samples in a class should be less or equal '
'to the original number of samples. '
'Originally, there is {} samples and {} '
'samples are asked.'.format(target_samples, n_samples))
checked_ratio[target] = n_samples
return checked_ratio
class BaseSampler(SamplerMixin):
"""
Base class for sampling algorithms.
Warning: This class should not be used directly.
Use the derive classes instead.
"""
def __init__(self, ratio):
self.ratio = ratio
self.logger = logging.getLogger(__name__)
def fit(self, X, y):
"""
Find the classes statistics to perform sampling.
Parameters
----------
X : 2d ndarray or scipy sparse matrix, shape [n_samples, n_features]
Matrix containing the data which have to be sampled.
y : 1d ndarray, shape [n_samples]
Corresponding label for each sample in X.
Returns
-------
self
"""
X, y = check_X_y(X, y, accept_sparse = ['csr', 'csc'])
y = check_target_type(y)
self.X_hash_, self.y_hash_ = hash_X_y(X, y)
self.ratio_ = check_ratio(self.ratio, y)
return self
class RandomUnderSampler(BaseSampler):
"""
Class to perform random under-sampling.
Under-sample the majority class(es) by randomly picking samples
with or without replacement.
This is an "improvement" of imbalance learn's RandomUnderSampler [1]_
by only accepting a dictionary for the ratio argument and supports
float value indicating the proportional sampling.
Parameters
----------
ratio : dict[(int, int/float)]
Ratio to use for resampling the data set.
Keys correspond to the targeted classes and the values
correspond to the desired number/proportion of samples.
e.g. {0: 1.0, 1: 0.5} becauses the values are float, this
is read as we'll keep all samples from class label 0 and
keep only 50 percent of class label 1, note that in this
case {1: 0.5} will also work. We could also specify integer
value for the values in the dictionary to indicate the
actual number of samples to retain.
replacement : bool, default False
Whether the sample is with or without replacement.
random_state : int, RandomState instance or None, default None
If int, ``random_state`` is the seed used by the random number
generator; If ``RandomState`` instance, random_state is the random
number generator; If ``None``, the random number generator is the
``RandomState`` instance used by ``np.random``.
Attributes
----------
ratio_ : dict[(int, int)]
The actual ratio that was used for resampling the data set,
where the class label is the key and the number of samples is the value
X_hash_/y_hash_ : str
Hash identifier of the input X and y. This is used for ensuring
the X and y that was used for fitting is identical to sampling
(resampling is only meant for the same "training" set)
References
----------
.. [1] `imbalanced-learn RandomUnderSampler
<http://contrib.scikit-learn.org/imbalanced-learn/stable/generated/imblearn.under_sampling.RandomUnderSampler.html>`_
"""
def __init__(self, ratio, replacement = False, random_state = None):
super().__init__(ratio = ratio)
self.replacement = replacement
self.random_state = random_state
def _sample(self, X, y):
"""resample the dataset"""
random_state = check_random_state(self.random_state)
sample_indices = []
targets = np.unique(y)
for target in targets:
target_indices = np.flatnonzero(y == target)
if target in self.ratio_:
n_samples = self.ratio_[target]
target_indices = random_state.choice(
target_indices, size = n_samples, replace = self.replacement)
sample_indices.append(target_indices)
sample_indices = np.hstack(sample_indices)
return safe_indexing(X, sample_indices), safe_indexing(y, sample_indices)
| [
"logging.getLogger",
"sklearn.utils.check_random_state",
"numpy.unique",
"sklearn.utils.check_X_y",
"numpy.hstack",
"numpy.flatnonzero",
"sklearn.utils.safe_indexing",
"collections.Counter",
"imblearn.utils.check_target_type",
"imblearn.utils.hash_X_y"
] | [((365, 375), 'collections.Counter', 'Counter', (['y'], {}), '(y)\n', (372, 375), False, 'from collections import Counter\n'), ((1916, 1943), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1933, 1943), False, 'import logging\n'), ((2390, 2435), 'sklearn.utils.check_X_y', 'check_X_y', (['X', 'y'], {'accept_sparse': "['csr', 'csc']"}), "(X, y, accept_sparse=['csr', 'csc'])\n", (2399, 2435), False, 'from sklearn.utils import check_X_y, check_random_state, safe_indexing\n'), ((2450, 2470), 'imblearn.utils.check_target_type', 'check_target_type', (['y'], {}), '(y)\n', (2467, 2470), False, 'from imblearn.utils import check_target_type, hash_X_y\n'), ((2508, 2522), 'imblearn.utils.hash_X_y', 'hash_X_y', (['X', 'y'], {}), '(X, y)\n', (2516, 2522), False, 'from imblearn.utils import check_target_type, hash_X_y\n'), ((4983, 5020), 'sklearn.utils.check_random_state', 'check_random_state', (['self.random_state'], {}), '(self.random_state)\n', (5001, 5020), False, 'from sklearn.utils import check_X_y, check_random_state, safe_indexing\n'), ((5068, 5080), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (5077, 5080), True, 'import numpy as np\n'), ((5468, 5493), 'numpy.hstack', 'np.hstack', (['sample_indices'], {}), '(sample_indices)\n', (5477, 5493), True, 'import numpy as np\n'), ((5141, 5168), 'numpy.flatnonzero', 'np.flatnonzero', (['(y == target)'], {}), '(y == target)\n', (5155, 5168), True, 'import numpy as np\n'), ((5509, 5541), 'sklearn.utils.safe_indexing', 'safe_indexing', (['X', 'sample_indices'], {}), '(X, sample_indices)\n', (5522, 5541), False, 'from sklearn.utils import check_X_y, check_random_state, safe_indexing\n'), ((5543, 5575), 'sklearn.utils.safe_indexing', 'safe_indexing', (['y', 'sample_indices'], {}), '(y, sample_indices)\n', (5556, 5575), False, 'from sklearn.utils import check_X_y, check_random_state, safe_indexing\n')] |
# Copyright 2021 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.
import os
import tempfile
from unittest import mock
import numpy as np
import pandas as pd
import pytest
import tensorflow as tf
import create_datasets
import data_utils
import predict
import trainer
def test_validated_missing_field() -> None:
tensor_dict = {}
values_spec = {"x": tf.TensorSpec(shape=(3,), dtype=tf.float32)}
with pytest.raises(KeyError):
trainer.validated(tensor_dict, values_spec)
def test_validated_incompatible_type() -> None:
tensor_dict = {"x": tf.constant(["a", "b", "c"])}
values_spec = {"x": tf.TensorSpec(shape=(3,), dtype=tf.float32)}
with pytest.raises(TypeError):
trainer.validated(tensor_dict, values_spec)
def test_validated_incompatible_shape() -> None:
tensor_dict = {"x": tf.constant([1.0])}
values_spec = {"x": tf.TensorSpec(shape=(3,), dtype=tf.float32)}
with pytest.raises(ValueError):
trainer.validated(tensor_dict, values_spec)
def test_validated_ok() -> None:
tensor_dict = {"x": tf.constant([1.0, 2.0, 3.0])}
values_spec = {"x": tf.TensorSpec(shape=(3,), dtype=tf.float32)}
trainer.validated(tensor_dict, values_spec)
tensor_dict = {"x": tf.constant([[1.0], [2.0], [3.0]])}
values_spec = {"x": tf.TensorSpec(shape=(None, 1), dtype=tf.float32)}
trainer.validated(tensor_dict, values_spec)
def test_serialize_deserialize() -> None:
unlabeled_data = data_utils.read_data("test_data/56980685061237.npz")
labels = data_utils.read_labels("test_data/labels.csv")
data = data_utils.label_data(unlabeled_data, labels)
for training_point in data_utils.generate_training_points(data):
serialized = trainer.serialize(training_point)
inputs, outputs = trainer.deserialize(serialized)
assert set(inputs.keys()) == set(trainer.INPUTS_SPEC.keys())
assert set(outputs.keys()) == set(trainer.OUTPUTS_SPEC.keys())
@mock.patch.object(trainer, "PADDING", 2)
def test_e2e_local() -> None:
with tempfile.TemporaryDirectory() as temp_dir:
train_data_dir = os.path.join(temp_dir, "datasets", "train")
eval_data_dir = os.path.join(temp_dir, "datasets", "eval")
model_dir = os.path.join(temp_dir, "model")
tensorboard_dir = os.path.join(temp_dir, "tensorboard")
checkpoint_dir = os.path.join(temp_dir, "checkpoints")
# Create the dataset TFRecord files.
create_datasets.run(
raw_data_dir="test_data",
raw_labels_dir="test_data",
train_data_dir=train_data_dir,
eval_data_dir=eval_data_dir,
train_eval_split=[80, 20],
)
assert os.listdir(train_data_dir), "no training files found"
assert os.listdir(eval_data_dir), "no evaluation files found"
# Train the model and save it.
trainer.run(
train_data_dir=train_data_dir,
eval_data_dir=eval_data_dir,
model_dir=model_dir,
tensorboard_dir=tensorboard_dir,
checkpoint_dir=checkpoint_dir,
train_epochs=10,
batch_size=32,
)
assert os.listdir(model_dir), "no model files found"
assert os.listdir(tensorboard_dir), "no tensorboard files found"
assert os.listdir(checkpoint_dir), "no checkpoint files found"
# Load the trained model and make a prediction.
with open("test_data/56980685061237.npz", "rb") as f:
input_data = pd.DataFrame(np.load(f)["x"])
predictions = predict.run(model_dir, input_data.to_dict("list"))
# Check that we get non-empty predictions.
assert "is_fishing" in predictions
assert len(predictions["is_fishing"]) > 0
| [
"data_utils.generate_training_points",
"data_utils.read_data",
"trainer.validated",
"trainer.OUTPUTS_SPEC.keys",
"os.listdir",
"data_utils.read_labels",
"trainer.deserialize",
"tensorflow.TensorSpec",
"pytest.raises",
"trainer.run",
"tempfile.TemporaryDirectory",
"trainer.INPUTS_SPEC.keys",
... | [((2461, 2501), 'unittest.mock.patch.object', 'mock.patch.object', (['trainer', '"""PADDING"""', '(2)'], {}), "(trainer, 'PADDING', 2)\n", (2478, 2501), False, 'from unittest import mock\n'), ((1674, 1717), 'trainer.validated', 'trainer.validated', (['tensor_dict', 'values_spec'], {}), '(tensor_dict, values_spec)\n', (1691, 1717), False, 'import trainer\n'), ((1857, 1900), 'trainer.validated', 'trainer.validated', (['tensor_dict', 'values_spec'], {}), '(tensor_dict, values_spec)\n', (1874, 1900), False, 'import trainer\n'), ((1966, 2018), 'data_utils.read_data', 'data_utils.read_data', (['"""test_data/56980685061237.npz"""'], {}), "('test_data/56980685061237.npz')\n", (1986, 2018), False, 'import data_utils\n'), ((2032, 2078), 'data_utils.read_labels', 'data_utils.read_labels', (['"""test_data/labels.csv"""'], {}), "('test_data/labels.csv')\n", (2054, 2078), False, 'import data_utils\n'), ((2090, 2135), 'data_utils.label_data', 'data_utils.label_data', (['unlabeled_data', 'labels'], {}), '(unlabeled_data, labels)\n', (2111, 2135), False, 'import data_utils\n'), ((2162, 2203), 'data_utils.generate_training_points', 'data_utils.generate_training_points', (['data'], {}), '(data)\n', (2197, 2203), False, 'import data_utils\n'), ((869, 912), 'tensorflow.TensorSpec', 'tf.TensorSpec', ([], {'shape': '(3,)', 'dtype': 'tf.float32'}), '(shape=(3,), dtype=tf.float32)\n', (882, 912), True, 'import tensorflow as tf\n'), ((923, 946), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (936, 946), False, 'import pytest\n'), ((956, 999), 'trainer.validated', 'trainer.validated', (['tensor_dict', 'values_spec'], {}), '(tensor_dict, values_spec)\n', (973, 999), False, 'import trainer\n'), ((1074, 1102), 'tensorflow.constant', 'tf.constant', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (1085, 1102), True, 'import tensorflow as tf\n'), ((1128, 1171), 'tensorflow.TensorSpec', 'tf.TensorSpec', ([], {'shape': '(3,)', 'dtype': 'tf.float32'}), '(shape=(3,), dtype=tf.float32)\n', (1141, 1171), True, 'import tensorflow as tf\n'), ((1182, 1206), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (1195, 1206), False, 'import pytest\n'), ((1216, 1259), 'trainer.validated', 'trainer.validated', (['tensor_dict', 'values_spec'], {}), '(tensor_dict, values_spec)\n', (1233, 1259), False, 'import trainer\n'), ((1335, 1353), 'tensorflow.constant', 'tf.constant', (['[1.0]'], {}), '([1.0])\n', (1346, 1353), True, 'import tensorflow as tf\n'), ((1379, 1422), 'tensorflow.TensorSpec', 'tf.TensorSpec', ([], {'shape': '(3,)', 'dtype': 'tf.float32'}), '(shape=(3,), dtype=tf.float32)\n', (1392, 1422), True, 'import tensorflow as tf\n'), ((1433, 1458), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1446, 1458), False, 'import pytest\n'), ((1468, 1511), 'trainer.validated', 'trainer.validated', (['tensor_dict', 'values_spec'], {}), '(tensor_dict, values_spec)\n', (1485, 1511), False, 'import trainer\n'), ((1571, 1599), 'tensorflow.constant', 'tf.constant', (['[1.0, 2.0, 3.0]'], {}), '([1.0, 2.0, 3.0])\n', (1582, 1599), True, 'import tensorflow as tf\n'), ((1625, 1668), 'tensorflow.TensorSpec', 'tf.TensorSpec', ([], {'shape': '(3,)', 'dtype': 'tf.float32'}), '(shape=(3,), dtype=tf.float32)\n', (1638, 1668), True, 'import tensorflow as tf\n'), ((1743, 1777), 'tensorflow.constant', 'tf.constant', (['[[1.0], [2.0], [3.0]]'], {}), '([[1.0], [2.0], [3.0]])\n', (1754, 1777), True, 'import tensorflow as tf\n'), ((1803, 1851), 'tensorflow.TensorSpec', 'tf.TensorSpec', ([], {'shape': '(None, 1)', 'dtype': 'tf.float32'}), '(shape=(None, 1), dtype=tf.float32)\n', (1816, 1851), True, 'import tensorflow as tf\n'), ((2226, 2259), 'trainer.serialize', 'trainer.serialize', (['training_point'], {}), '(training_point)\n', (2243, 2259), False, 'import trainer\n'), ((2286, 2317), 'trainer.deserialize', 'trainer.deserialize', (['serialized'], {}), '(serialized)\n', (2305, 2317), False, 'import trainer\n'), ((2541, 2570), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (2568, 2570), False, 'import tempfile\n'), ((2609, 2652), 'os.path.join', 'os.path.join', (['temp_dir', '"""datasets"""', '"""train"""'], {}), "(temp_dir, 'datasets', 'train')\n", (2621, 2652), False, 'import os\n'), ((2677, 2719), 'os.path.join', 'os.path.join', (['temp_dir', '"""datasets"""', '"""eval"""'], {}), "(temp_dir, 'datasets', 'eval')\n", (2689, 2719), False, 'import os\n'), ((2740, 2771), 'os.path.join', 'os.path.join', (['temp_dir', '"""model"""'], {}), "(temp_dir, 'model')\n", (2752, 2771), False, 'import os\n'), ((2798, 2835), 'os.path.join', 'os.path.join', (['temp_dir', '"""tensorboard"""'], {}), "(temp_dir, 'tensorboard')\n", (2810, 2835), False, 'import os\n'), ((2861, 2898), 'os.path.join', 'os.path.join', (['temp_dir', '"""checkpoints"""'], {}), "(temp_dir, 'checkpoints')\n", (2873, 2898), False, 'import os\n'), ((2953, 3121), 'create_datasets.run', 'create_datasets.run', ([], {'raw_data_dir': '"""test_data"""', 'raw_labels_dir': '"""test_data"""', 'train_data_dir': 'train_data_dir', 'eval_data_dir': 'eval_data_dir', 'train_eval_split': '[80, 20]'}), "(raw_data_dir='test_data', raw_labels_dir='test_data',\n train_data_dir=train_data_dir, eval_data_dir=eval_data_dir,\n train_eval_split=[80, 20])\n", (2972, 3121), False, 'import create_datasets\n'), ((3200, 3226), 'os.listdir', 'os.listdir', (['train_data_dir'], {}), '(train_data_dir)\n', (3210, 3226), False, 'import os\n'), ((3269, 3294), 'os.listdir', 'os.listdir', (['eval_data_dir'], {}), '(eval_data_dir)\n', (3279, 3294), False, 'import os\n'), ((3372, 3569), 'trainer.run', 'trainer.run', ([], {'train_data_dir': 'train_data_dir', 'eval_data_dir': 'eval_data_dir', 'model_dir': 'model_dir', 'tensorboard_dir': 'tensorboard_dir', 'checkpoint_dir': 'checkpoint_dir', 'train_epochs': '(10)', 'batch_size': '(32)'}), '(train_data_dir=train_data_dir, eval_data_dir=eval_data_dir,\n model_dir=model_dir, tensorboard_dir=tensorboard_dir, checkpoint_dir=\n checkpoint_dir, train_epochs=10, batch_size=32)\n', (3383, 3569), False, 'import trainer\n'), ((3671, 3692), 'os.listdir', 'os.listdir', (['model_dir'], {}), '(model_dir)\n', (3681, 3692), False, 'import os\n'), ((3732, 3759), 'os.listdir', 'os.listdir', (['tensorboard_dir'], {}), '(tensorboard_dir)\n', (3742, 3759), False, 'import os\n'), ((3805, 3831), 'os.listdir', 'os.listdir', (['checkpoint_dir'], {}), '(checkpoint_dir)\n', (3815, 3831), False, 'import os\n'), ((2359, 2385), 'trainer.INPUTS_SPEC.keys', 'trainer.INPUTS_SPEC.keys', ([], {}), '()\n', (2383, 2385), False, 'import trainer\n'), ((2429, 2456), 'trainer.OUTPUTS_SPEC.keys', 'trainer.OUTPUTS_SPEC.keys', ([], {}), '()\n', (2454, 2456), False, 'import trainer\n'), ((4018, 4028), 'numpy.load', 'np.load', (['f'], {}), '(f)\n', (4025, 4028), True, 'import numpy as np\n')] |
import copy as _copy
import json as _json
import os
import sys as _sys
import coinstac_computation.utils as _ut
import datetime as _dt
import multiprocessing as _mp
class COINSTACPyNode:
_VALID_MODES_ = [_ut.MODE_LOCAL, _ut.MODE_REMOTE]
def __init__(self, mode: str, debug=False):
self.cache = {}
self.input = None
self.state = None
self.mode = mode.upper()
self.debug = debug
self._logs = {}
self._pipeline_ = _ut.PhasePipeline(self.mode, self.cache)
self.pool = None
assert self.mode in COINSTACPyNode._VALID_MODES_, \
f"Invalid mode : {self.mode}, Use one of: {COINSTACPyNode._VALID_MODES_}"
def add_phase(self, phase_cls, local_only: bool = False, multi_iterations: bool = False):
"""
:param phase_cls: Custom implementation of ComputationPhase class
:type phase_cls: ComputationPhase
:param local_only: This phase will run only locally right after the previous phase is done.
:type local_only: bool
:param multi_iterations: Specifies if it is a multiple iterations phase.
:type multi_iterations: bool
Note: It is assumed that a normal(default) computation phase will run one round of local-remote.
"""
self._pipeline_.add_phase(phase_cls, local_only, multi_iterations)
def _save_logs(self, state):
date_time = _dt.datetime.now().strftime("%H:%M:%S %m/%d/%Y")
with open(
state['outputDirectory'] + os.sep + f"{self.mode}_{state['clientId']}_logs.txt", 'a'
) as log:
for k, v in self._logs.items():
print(f"[{k.upper()}] {date_time} ", file=log)
for k1, v1 in v.items():
print(f" {k1}{v1}", file=log)
print('', file=log)
def _initialize(self):
self.cache['input_args'] = _ut.FrozenDict(_copy.deepcopy(self.input))
self.pool = _mp.Pool(self.cache.setdefault('num_workers', 2))
def compute(self, data):
self.input = data['input']
self.state = data['state']
if not self.cache.get(self.mode):
self._initialize()
self.cache[self.mode] = True
if self.debug:
self._logs['input'] = {}
self._logs['input']['->'] = _copy.deepcopy(self.input)
self._logs['cache'] = {}
self._logs['cache']['->'] = _copy.deepcopy(self.cache)
phase_key = self.cache.setdefault('next_phase', self._pipeline_.phase_ids[0])
if self.mode == _ut.MODE_LOCAL and self.input.get('jump_to_next'):
phase_key = self._pipeline_.next_phase(self.input['jump_to_next'])
phase_out = self._pipeline_.phases[phase_key](phase_key, self).compute()
if not isinstance(phase_out, dict):
phase_out = {}
node_output = {"output": phase_out}
jump_to_next = phase_out.get('jump_to_next', False)
if self.mode == _ut.MODE_REMOTE:
jump_to_next = jump_to_next or _ut.check(all, 'jump_to_next', True, self.input)
node_output['success'] = phase_out.get('success', False)
self.cache['next_phase'] = self._pipeline_.next_phase(jump_to_next)
if self._pipeline_.local_only.get(self.cache['next_phase']):
node_output = self.compute(data)
if self.debug:
self._logs['cache']['<-'] = _copy.deepcopy(self.cache)
self._logs['output'] = {'<-': _copy.deepcopy(node_output)}
self._save_logs(self.state)
return node_output
def __call__(self, *args, **kwargs):
return self.compute(*args, **kwargs)
def to_stdout(self):
"""
Backward compatibility for the old library. Deprecated now.
"""
data = _json.loads(_sys.stdin.read())
if data.get('cache') and len(data['cache']) > 0:
self.cache = data['cache']
self._pipeline_.cache = self.cache
output = self.compute(data)
output['cache'] = self.cache
_sys.stdout.write(_json.dumps(output))
| [
"json.dumps",
"coinstac_computation.utils.PhasePipeline",
"datetime.datetime.now",
"copy.deepcopy",
"sys.stdin.read",
"coinstac_computation.utils.check"
] | [((481, 521), 'coinstac_computation.utils.PhasePipeline', '_ut.PhasePipeline', (['self.mode', 'self.cache'], {}), '(self.mode, self.cache)\n', (498, 521), True, 'import coinstac_computation.utils as _ut\n'), ((1909, 1935), 'copy.deepcopy', '_copy.deepcopy', (['self.input'], {}), '(self.input)\n', (1923, 1935), True, 'import copy as _copy\n'), ((2323, 2349), 'copy.deepcopy', '_copy.deepcopy', (['self.input'], {}), '(self.input)\n', (2337, 2349), True, 'import copy as _copy\n'), ((2427, 2453), 'copy.deepcopy', '_copy.deepcopy', (['self.cache'], {}), '(self.cache)\n', (2441, 2453), True, 'import copy as _copy\n'), ((3412, 3438), 'copy.deepcopy', '_copy.deepcopy', (['self.cache'], {}), '(self.cache)\n', (3426, 3438), True, 'import copy as _copy\n'), ((3810, 3827), 'sys.stdin.read', '_sys.stdin.read', ([], {}), '()\n', (3825, 3827), True, 'import sys as _sys\n'), ((4073, 4092), 'json.dumps', '_json.dumps', (['output'], {}), '(output)\n', (4084, 4092), True, 'import json as _json\n'), ((1412, 1430), 'datetime.datetime.now', '_dt.datetime.now', ([], {}), '()\n', (1428, 1430), True, 'import datetime as _dt\n'), ((3038, 3086), 'coinstac_computation.utils.check', '_ut.check', (['all', '"""jump_to_next"""', '(True)', 'self.input'], {}), "(all, 'jump_to_next', True, self.input)\n", (3047, 3086), True, 'import coinstac_computation.utils as _ut\n'), ((3481, 3508), 'copy.deepcopy', '_copy.deepcopy', (['node_output'], {}), '(node_output)\n', (3495, 3508), True, 'import copy as _copy\n')] |
'''
<NAME>
simple ray trace - tools and classes to specify and instantiate rays
'''
import numpy as np
from srt_modules.useful_math import euler1232C
class Ray:
def __init__(self, pos=None, dirs=None):
self.X = pos # 3 x N position vectors of rays
self.d = dirs # direction vectors of rays in same frame
return
def set_pos(self, ray_starts):
self.X = ray_starts
return
def set_dir(self, ray_dirs):
self.d = ray_dirs
return
class AngledCircleRayDef:
# definition/inputs to make a light source which is a set of rays in concentric circles
# for a less naive generation of concentric circles of rays, vary the number of rays with sqrt(radius) of each ring.
def __init__(self):
self.rad = 0.5 # [m] radius of largest circle of rays
self.angles = [0.] # [arc sec] angle of rays measure wrt the instrument primary axis. providing a list will generate
# multiple sets of rays to be used in multiple runs of the experiment.
self.num_circ = 15 # number of concentric circles
self.per_circ = 150 # number of rays per circle
def make_angled_circle_rays(inputs):
rad_inc = inputs.rad / inputs.num_circ # radius increment
theta_inc = np.pi * 2 / inputs.per_circ # angle increment
ray_set_list = [] # set of sets of start points
for angle in inputs.angles:
rays = []
angle = angle / 3600. * np.pi / 180. # convert from arc sec to radians
for i in range(inputs.num_circ):
r = rad_inc * i
for j in range(inputs.per_circ):
# note x = 0 always. We assume the rays start at the y-z plane in the lab frame.
x, y, z = 0., r * np.cos(theta_inc * j), r * np.sin(theta_inc * j)
rays.append(np.array([x, y, z]))
rays = np.array(rays).transpose()
ray_dirs = np.array([np.array([1, 0, 0])] * np.shape(rays)[1]).transpose() # rays initialize down x-axis
DCM = euler1232C([0., 0., angle]).transpose()
ray_dirs = np.dot(DCM, ray_dirs) # rays rotated by given angle
ray_set_list.append(Ray(rays, ray_dirs))
return ray_set_list # here we have a list of ray sets. one set per angle given. many rays per set
def make_one_edge_ray(rad, angle):
# rad is radius of primary
# angle is the desired angle of the ray relative to primary centerline
# make one ray, starts at the edge of the generating circle at a specified angle. For checking secondary diameter
x, y, z = 0., rad, 0.,
L_X = np.array([x,y,z]).reshape([3, 1])
angle = angle/3600. * np.pi/180.
dir = np.array([np.cos(angle), -np.sin(angle), 0]).reshape([3, 1])
return Ray(L_X, dir) | [
"numpy.array",
"numpy.dot",
"numpy.cos",
"numpy.sin",
"srt_modules.useful_math.euler1232C",
"numpy.shape"
] | [((2083, 2104), 'numpy.dot', 'np.dot', (['DCM', 'ray_dirs'], {}), '(DCM, ray_dirs)\n', (2089, 2104), True, 'import numpy as np\n'), ((2585, 2604), 'numpy.array', 'np.array', (['[x, y, z]'], {}), '([x, y, z])\n', (2593, 2604), True, 'import numpy as np\n'), ((1869, 1883), 'numpy.array', 'np.array', (['rays'], {}), '(rays)\n', (1877, 1883), True, 'import numpy as np\n'), ((2024, 2053), 'srt_modules.useful_math.euler1232C', 'euler1232C', (['[0.0, 0.0, angle]'], {}), '([0.0, 0.0, angle])\n', (2034, 2053), False, 'from srt_modules.useful_math import euler1232C\n'), ((1833, 1852), 'numpy.array', 'np.array', (['[x, y, z]'], {}), '([x, y, z])\n', (1841, 1852), True, 'import numpy as np\n'), ((2676, 2689), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (2682, 2689), True, 'import numpy as np\n'), ((1756, 1777), 'numpy.cos', 'np.cos', (['(theta_inc * j)'], {}), '(theta_inc * j)\n', (1762, 1777), True, 'import numpy as np\n'), ((1783, 1804), 'numpy.sin', 'np.sin', (['(theta_inc * j)'], {}), '(theta_inc * j)\n', (1789, 1804), True, 'import numpy as np\n'), ((2692, 2705), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (2698, 2705), True, 'import numpy as np\n'), ((1925, 1944), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (1933, 1944), True, 'import numpy as np\n'), ((1948, 1962), 'numpy.shape', 'np.shape', (['rays'], {}), '(rays)\n', (1956, 1962), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
This script copies the examples under tests to
the standard example directory and processes
certain setting variables. Under the tests, the
examples do not plot and save data. In examples
directory they do.
"""
import os
from shutil import copyfile
def get_example_files(loc):
"""Returns files containing examples
"""
onlyfiles = [f for f in os.listdir(loc)
if os.path.isfile(os.path.join(loc, f))]
return onlyfiles
def get_prefix(file):
"""Returns the prefix of the file
"""
parts = file.split(sep="_")
return parts[0]
def get_number(file):
"""Returns the number part of the file name
"""
parts = file.split(sep="_")
return parts[1]
def get_root(file):
"""Returns the root part of the filename
"""
parts = file.split(sep="_")
ret = ""
for k in range(len(parts)):
part = parts[k]
if k > 1:
ret += "_"+part
return ret
def copy_file(from_loc, file, to, as_file, fltr=None):
"""Copies the file into "examples" directory
"""
if fltr is None:
src = os.path.join(from_loc, file)
dst = os.path.join(to, as_file)
copyfile(src, dst)
def fltr_fce(text):
"""Changes predefined variables in examples
"""
pass
exloc = os.path.join("..", "quantarhei", "wizard", "examples")
files = get_example_files(exloc)
print("Copying example files from ", exloc)
for file in files:
pref = get_prefix(file)
if pref == "ex":
nr = get_number(file)
root = get_root(file)
demo_file = "demo_"+nr+root
print(file,"-->", demo_file)
copy_file(from_loc=exloc, file=file,
to=".", as_file=demo_file) #, fltr=fltr_fce)
if pref == "data":
nr = get_number(file)
root = get_root(file)
data_file = "data_"+nr+root
print(file,"-->", data_file)
copy_file(from_loc=exloc, file=file,
to=".", as_file=data_file)
| [
"shutil.copyfile",
"os.listdir",
"os.path.join"
] | [((1378, 1432), 'os.path.join', 'os.path.join', (['""".."""', '"""quantarhei"""', '"""wizard"""', '"""examples"""'], {}), "('..', 'quantarhei', 'wizard', 'examples')\n", (1390, 1432), False, 'import os\n'), ((1172, 1200), 'os.path.join', 'os.path.join', (['from_loc', 'file'], {}), '(from_loc, file)\n', (1184, 1200), False, 'import os\n'), ((1215, 1240), 'os.path.join', 'os.path.join', (['to', 'as_file'], {}), '(to, as_file)\n', (1227, 1240), False, 'import os\n'), ((1249, 1267), 'shutil.copyfile', 'copyfile', (['src', 'dst'], {}), '(src, dst)\n', (1257, 1267), False, 'from shutil import copyfile\n'), ((410, 425), 'os.listdir', 'os.listdir', (['loc'], {}), '(loc)\n', (420, 425), False, 'import os\n'), ((462, 482), 'os.path.join', 'os.path.join', (['loc', 'f'], {}), '(loc, f)\n', (474, 482), False, 'import os\n')] |
import time
import dgl
import numpy as np
import torch
from se3_transformer_pytorch import SE3Transformer
from se3_transformer_pytorch.irr_repr import rot
from project.lit_egnn import LitEGNN
from project.lit_set import LitSET
# Instantiate different models to be compared
original_se3_transformer = LitSET(num_layers=3,
atom_feature_size=16,
num_channels=16,
num_degrees=2,
edge_dim=3)
new_se3_transformer = SE3Transformer(dim=16,
depth=2,
attend_self=True,
num_degrees=2,
output_degrees=1,
fourier_encode_dist=True)
open_source_egnn = LitEGNN(node_feat=16,
pos_feat=3,
coord_feat=3,
edge_feat=0,
fourier_feat=0,
num_nearest_neighbors=0,
num_layers=3)
# Establish common variables
device = 'cuda:0'
original_se3_transformer.to(device)
new_se3_transformer.to(device)
open_source_egnn.to(device)
feats = torch.randn(1, 32, 16).to(device)
coors = torch.randn(1, 32, 3).to(device)
mask = torch.ones(1, 32).bool().to(device)
R = rot(15, 0, 45).to(device)
edge_f = torch.randn(1, 32 * 32, 3).to(device)
# Create mock graphs
src_ids = np.repeat(range(32), 32)
dst_ids = np.tile(range(32), 32)
g = dgl.graph((src_ids, dst_ids), idtype=torch.long, device=device)
g.ndata['x'] = coors[0, :, :]
g.ndata['f'] = feats[0, :, :].view(32, 16, 1)
g.edata['d'] = g.ndata['x'][g.edges()[0]] - g.ndata['x'][g.edges()[1]]
g.edata['w'] = edge_f[0, :, :]
output1 = None
h_output1 = None
num_steps = 10
# Test original SE(3)-Transformer (by <NAME> et al.)
t1 = time.time()
for i in range(num_steps):
output1 = original_se3_transformer(g)
t2 = time.time()
g.ndata['x'] = g.ndata['x'] @ R
output2 = original_se3_transformer(g)
diff = (output1 - output2).max()
print(
f'The original SE(3)-Transformer, with an equivariance error of {str(diff)}, takes {str(t2 - t1)} seconds to perform {num_steps} forward passes.')
# Test new SE(3)-Transformer (by lucidrains et al.)
edge_f = edge_f.view(32, 32, 3)
t1 = time.time()
for i in range(num_steps):
output1 = new_se3_transformer(feats, coors, mask, return_type=1)
t2 = time.time()
output2 = new_se3_transformer(feats, coors @ R, mask, return_type=1)
diff = (output1 - output2).max()
print(
f'The new SE(3)-Transformer, with an equivariance error of {str(diff)}, takes {str(t2 - t1)} seconds to perform {num_steps} forward passes.')
# Test the open-source EGNN (by lucidrains et al.)
edge_f = edge_f.view(32, 32, 3)
t1 = time.time()
for i in range(num_steps):
h_output1, x_output1 = open_source_egnn(feats, coors)
t2 = time.time()
h_output2, x_output2 = open_source_egnn(feats, coors @ R)
diff = (h_output1 - h_output2).max()
print(
f'The open-source EGNN, with an equivariance error of {str(diff)}, takes {str(t2 - t1)} seconds to perform {num_steps} forward passes.')
| [
"dgl.graph",
"project.lit_egnn.LitEGNN",
"se3_transformer_pytorch.SE3Transformer",
"se3_transformer_pytorch.irr_repr.rot",
"project.lit_set.LitSET",
"time.time",
"torch.randn",
"torch.ones"
] | [((303, 393), 'project.lit_set.LitSET', 'LitSET', ([], {'num_layers': '(3)', 'atom_feature_size': '(16)', 'num_channels': '(16)', 'num_degrees': '(2)', 'edge_dim': '(3)'}), '(num_layers=3, atom_feature_size=16, num_channels=16, num_degrees=2,\n edge_dim=3)\n', (309, 393), False, 'from project.lit_set import LitSET\n'), ((548, 660), 'se3_transformer_pytorch.SE3Transformer', 'SE3Transformer', ([], {'dim': '(16)', 'depth': '(2)', 'attend_self': '(True)', 'num_degrees': '(2)', 'output_degrees': '(1)', 'fourier_encode_dist': '(True)'}), '(dim=16, depth=2, attend_self=True, num_degrees=2,\n output_degrees=1, fourier_encode_dist=True)\n', (562, 660), False, 'from se3_transformer_pytorch import SE3Transformer\n'), ((861, 980), 'project.lit_egnn.LitEGNN', 'LitEGNN', ([], {'node_feat': '(16)', 'pos_feat': '(3)', 'coord_feat': '(3)', 'edge_feat': '(0)', 'fourier_feat': '(0)', 'num_nearest_neighbors': '(0)', 'num_layers': '(3)'}), '(node_feat=16, pos_feat=3, coord_feat=3, edge_feat=0, fourier_feat=0,\n num_nearest_neighbors=0, num_layers=3)\n', (868, 980), False, 'from project.lit_egnn import LitEGNN\n'), ((1580, 1643), 'dgl.graph', 'dgl.graph', (['(src_ids, dst_ids)'], {'idtype': 'torch.long', 'device': 'device'}), '((src_ids, dst_ids), idtype=torch.long, device=device)\n', (1589, 1643), False, 'import dgl\n'), ((1928, 1939), 'time.time', 'time.time', ([], {}), '()\n', (1937, 1939), False, 'import time\n'), ((2015, 2026), 'time.time', 'time.time', ([], {}), '()\n', (2024, 2026), False, 'import time\n'), ((2378, 2389), 'time.time', 'time.time', ([], {}), '()\n', (2387, 2389), False, 'import time\n'), ((2492, 2503), 'time.time', 'time.time', ([], {}), '()\n', (2501, 2503), False, 'import time\n'), ((2848, 2859), 'time.time', 'time.time', ([], {}), '()\n', (2857, 2859), False, 'import time\n'), ((2950, 2961), 'time.time', 'time.time', ([], {}), '()\n', (2959, 2961), False, 'import time\n'), ((1291, 1313), 'torch.randn', 'torch.randn', (['(1)', '(32)', '(16)'], {}), '(1, 32, 16)\n', (1302, 1313), False, 'import torch\n'), ((1333, 1354), 'torch.randn', 'torch.randn', (['(1)', '(32)', '(3)'], {}), '(1, 32, 3)\n', (1344, 1354), False, 'import torch\n'), ((1413, 1427), 'se3_transformer_pytorch.irr_repr.rot', 'rot', (['(15)', '(0)', '(45)'], {}), '(15, 0, 45)\n', (1416, 1427), False, 'from se3_transformer_pytorch.irr_repr import rot\n'), ((1448, 1474), 'torch.randn', 'torch.randn', (['(1)', '(32 * 32)', '(3)'], {}), '(1, 32 * 32, 3)\n', (1459, 1474), False, 'import torch\n'), ((1373, 1390), 'torch.ones', 'torch.ones', (['(1)', '(32)'], {}), '(1, 32)\n', (1383, 1390), False, 'import torch\n')] |
from pygame import *
from GameSprite import GameSprite
from Player import Player
def game():
back = (200, 255, 255)
win_width = 600
win_height = 500
window = display.set_mode((win_width, win_height))
window.fill(back)
run = True
finish = True
clock = time.Clock()
FPS = 60
racket1 = Player('racket.png', 30, 200, 4, 50, 150)
racket2 = Player('racket.png', 520, 200, 4, 50, 150)
while run:
for e in event.get():
if e.type == QUIT:
run = False
display.update()
clock.tick(FPS)
if __name__ == '__main__':
game() | [
"Player.Player"
] | [((344, 385), 'Player.Player', 'Player', (['"""racket.png"""', '(30)', '(200)', '(4)', '(50)', '(150)'], {}), "('racket.png', 30, 200, 4, 50, 150)\n", (350, 385), False, 'from Player import Player\n'), ((401, 443), 'Player.Player', 'Player', (['"""racket.png"""', '(520)', '(200)', '(4)', '(50)', '(150)'], {}), "('racket.png', 520, 200, 4, 50, 150)\n", (407, 443), False, 'from Player import Player\n')] |
# -*- coding: utf-8 -*-
from jinja2 import Environment, FileSystemLoader
import yaml
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('index_template.html')
heading_list = ['research', 'engineering', 'illustration']
with open('research_pub.yml') as f:
research_pub_list = yaml.load(f)
with open('research_conf.yml') as f:
research_conf_list = yaml.load(f)
with open('research_gakkai.yml') as f:
research_gakkai_list = yaml.load(f)
with open('eng_products.yml') as f:
eng_products_list = yaml.load(f)
with open('design_products.yml') as f:
design_products_list = yaml.load(f)
with open('links.yml') as f:
link_list = yaml.load(f)
output = template.render(heading_list=heading_list, research_pub_list=research_pub_list, research_conf_list=research_conf_list, research_gakkai_list=research_gakkai_list, eng_products_list=eng_products_list, design_products_list=design_products_list, link_list=link_list)
with open('./index.html', mode='w') as f:
f.write(output)
| [
"jinja2.FileSystemLoader",
"yaml.load"
] | [((306, 318), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (315, 318), False, 'import yaml\n'), ((381, 393), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (390, 393), False, 'import yaml\n'), ((460, 472), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (469, 472), False, 'import yaml\n'), ((533, 545), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (542, 545), False, 'import yaml\n'), ((612, 624), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (621, 624), False, 'import yaml\n'), ((670, 682), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (679, 682), False, 'import yaml\n'), ((111, 132), 'jinja2.FileSystemLoader', 'FileSystemLoader', (['"""."""'], {}), "('.')\n", (127, 132), False, 'from jinja2 import Environment, FileSystemLoader\n')] |
# ------------------------------------------------------------------------
# GroupFromer
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Modified from DETR (https://github.com/facebookresearch/detr) and Routing Transformers (https://arxiv.org/pdf/2003.05997.pdf)
# ------------------------------------------------------------------------
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from inspect import isfunction
from operator import mul
from functools import partial, reduce, wraps
import torch.distributed as dist
# constants
TOKEN_SELF_ATTN_VALUE = -5e4
KMEAN_INIT_ITERS = 10
# helper functions
def default(x, d):
if x is None:
return d if not isfunction(d) else d()
return x
def cast_tuple(x):
return x if isinstance(x, tuple) else (x,)
def cache_fn(f):
cache = None
@wraps(f)
def cached_fn(*args, **kwargs):
nonlocal cache
if cache is not None:
return cache
cache = f(*args, **kwargs)
return cache
return cached_fn
def to(t):
return {'device': t.device, 'dtype': t.dtype}
def find_modules(nn_module, type):
return [module for module in nn_module.modules() if isinstance(module, type)]
def is_empty(t):
return t.nelement() == 0
def max_neg_value(tensor):
return -torch.finfo(tensor.dtype).max
def batched_index_select(values, indices):
last_dim = values.shape[-1]
return values.gather(2, expand_dim(indices, -1, last_dim))
def merge_dims(ind_from, ind_to, tensor):
shape = list(tensor.shape)
arr_slice = slice(ind_from, ind_to + 1)
shape[arr_slice] = [reduce(mul, shape[arr_slice])]
return tensor.reshape(*shape)
def expand_dim(t, dim, k):
t = t.unsqueeze(dim)
expand_shape = [-1] * len(t.shape)
expand_shape[dim] = k
return t.expand(*expand_shape)
def scatter_mean(src, t, index, dim, eps = 1e-5):
numer = src.scatter_add(dim, index, t)
denom = src.scatter_add(dim, index, torch.ones_like(t))
return numer / (denom + eps)
def split_at_index(dim, index, t):
pre_slices = (slice(None),) * dim
l = (*pre_slices, slice(None, index))
r = (*pre_slices, slice(index, None))
return t[l], t[r]
def reshape_dim(t, dim, split_dims):
shape = list(t.shape)
num_dims = len(shape)
dim = (dim + num_dims) % num_dims
shape[dim:dim+1] = split_dims
return t.reshape(shape)
def ema(old, new, decay):
if old is None:
return new
return old * decay + new * (1 - decay)
# kmeans related function and class
def update_kmeans_on_backwards(module):
module.kmean_modules = find_modules(module, Kmeans)
def hook(_, grad_in, grad_out):
for m in module.kmean_modules:
m.update()
return module.register_backward_hook(hook)
def similarity(x, means):
return torch.einsum('bhld,hcd->bhlc', x, means)
def dists_and_buckets(x, means):
dists = similarity(x, means)
_, buckets = torch.max(dists, dim=-1)
return dists, buckets
def batched_bincount(index, num_classes, dim=-1):
shape = list(index.shape)
shape[dim] = num_classes
out = index.new_zeros(shape)
out.scatter_add_(dim, index, torch.ones_like(index, dtype=index.dtype))
return out
def kmeans_iter(x, means, buckets = None):
b, h, l, d, dtype, num_clusters = *x.shape, x.dtype, means.shape[1]
if buckets is None:
_, buckets = dists_and_buckets(x, means)
bins = batched_bincount(buckets, num_clusters).sum(0, keepdim=True)
zero_mask = bins.long() == 0
means_ = buckets.new_zeros(b, h, num_clusters, d, dtype=dtype)
means_.scatter_add_(-2, expand_dim(buckets, -1, d), x)
means_ = F.normalize(means_.sum(0, keepdim=True), dim=-1).type(dtype)
means = torch.where(zero_mask.unsqueeze(-1), means, means_)
means = means.squeeze(0)
return means
def distribution(dists, window_size):
_, topk_indices = dists.topk(k=window_size, dim=-2)
indices = topk_indices.transpose(-2, -1)
return indices.reshape(*indices.size()[:2], -1)
class Kmeans(nn.Module):
def __init__(self, num_heads, head_dim, num_clusters, ema_decay = 0.999, commitment = 1e-4):
super().__init__()
self.commitment = commitment
self.ema_decay = ema_decay
self.register_buffer('means', torch.randn(num_heads, num_clusters, head_dim))
#self.register_buffer('initted', torch.tensor(False))
self.initted=False
self.num_new_means = 0
self.new_means = None
@torch.no_grad()
def init(self, x):
if self.initted:
return
_, h, _, d, device, dtype = *x.shape, x.device, x.dtype
num_clusters = self.means.shape[1]
#h,c,d
means = x.transpose(0, 1).contiguous().view(h, -1, d)
num_samples = means.shape[1]
if num_samples >= num_clusters:
indices = torch.randperm(num_samples, device=device)[:num_clusters]
else:
indices = torch.randint(0, num_samples, (num_clusters,), device=device)
means = means[:, indices]
for _ in range(KMEAN_INIT_ITERS):
means = kmeans_iter(x, means)
self.num_new_means = 0
self.means.data.copy_(means)
#self.initted.data.copy_(torch.tensor(True))
self.initted=True
@torch.no_grad()
def update(self, new_means = None):
new_means = default(new_means, self.new_means)
assert new_means is not None, 'new kmeans has not been supplied'
ema_inplace(self.means, new_means, self.ema_decay)
del self.new_means
self.new_means = None
self.num_new_means = 0
def forward(self, x, update_means = False):
self.init(x)
self.world_size = dist.get_world_size()
b, dtype = x.shape[0], x.dtype
means = self.means.type(dtype)
x = F.normalize(x, 2, dim=-1).type(dtype)
with torch.no_grad():
dists, buckets = dists_and_buckets(x, means)
routed_means = batched_index_select(expand_dim(means, 0, b), buckets)
loss = F.mse_loss(x, routed_means)/self.world_size #* self.commitment
if update_means:
with torch.no_grad():
means = kmeans_iter(x, means, buckets)
self.new_means = ema(self.new_means, means, self.num_new_means / (self.num_new_means + 1))
self.num_new_means += 1
return dists, loss
# kmeans attention class
class KmeansAttention(nn.Module):
def __init__(self, num_clusters, window_size, num_heads, head_dim, causal = False, dropout = 0., ema_decay = 0.999, commitment = 1e-4, context_window_size = None, receives_context = False, num_mem_kv = 0, shared_qk = False):
super().__init__()
self.num_heads = num_heads
self.num_clusters = num_clusters
self.head_dim = head_dim
self.window_size = window_size
self.context_window_size = default(context_window_size, window_size)
self.causal = causal
self.shared_qk = shared_qk
self.receives_context = receives_context
self.kmeans = Kmeans(num_heads, head_dim, num_clusters, ema_decay, commitment)
self.dropout = nn.Dropout(dropout)
self.num_mem_kv = max(num_mem_kv, 1 if causal and not shared_qk else 0)
self.mem_key = nn.Parameter(torch.randn(num_heads, num_clusters, self.num_mem_kv, head_dim))
self.mem_value = nn.Parameter(torch.randn(num_heads, num_clusters, self.num_mem_kv, head_dim))
def forward(self, q, k, v, query_mask = None, key_mask = None, **kwargs):
b, h, t, d, kv_t, wsz, c_wsz, nc, device, dtype = *q.shape, k.shape[2], self.window_size, self.context_window_size, self.num_clusters, q.device, q.dtype
is_reverse = kwargs.pop('_reverse', False)
out = torch.zeros_like(q, dtype=dtype)
update_kmeans = self.training and not is_reverse
key_mask = default(key_mask, query_mask) if not self.receives_context else key_mask
kv_wsz = wsz if not self.receives_context else c_wsz
wsz = min(wsz, t)
kv_wsz = min(kv_wsz, kv_t)
if not self.shared_qk or self.receives_context:
dists, aux_loss = self.kmeans(torch.cat((q, k), dim=2), update_kmeans)
q_dists, k_dists = split_at_index(2, t, dists)
indices = distribution(q_dists, wsz)
kv_indices = distribution(k_dists, kv_wsz)
else:
dists, aux_loss = self.kmeans(q, update_kmeans)
k = F.normalize(k, dim=-1).to(q)
indices = distribution(dists, wsz)
kv_indices = indices
q = batched_index_select(q, indices)
k = batched_index_select(k, kv_indices)
v = batched_index_select(v, kv_indices)
reshape_with_window = lambda x: x.reshape(b, h, nc, -1, d)
q, k, v = map(reshape_with_window, (q, k, v))
m_k, m_v = map(lambda x: expand_dim(x, 0, b).to(q), (self.mem_key, self.mem_value))
k, v = map(lambda x: torch.cat(x, dim=3), ((m_k, k), (m_v, v)))
dots = torch.einsum('bhnid,bhnjd->bhnij', q, k) * (d ** -0.5)
mask_value = max_neg_value(dots)
if query_mask is not None or key_mask is not None:
query_mask = default(query_mask, lambda: torch.ones((b, t), device=device).bool())
key_mask = default(key_mask, lambda: torch.ones((b, kv_t), device=device).bool())
q_mask = expand_dim(query_mask, 1, h).gather(2, indices)
kv_mask = expand_dim(key_mask, 1, h).gather(2, kv_indices)
q_mask, kv_mask = map(lambda t: t.reshape(b, h, nc, -1), (q_mask, kv_mask))
mask = q_mask[:, :, :, :, None] * kv_mask[:, :, :, None, :]
mask = F.pad(mask, (self.num_mem_kv, 0), value=True)
dots.masked_fill_(~mask, mask_value)
del mask
if self.causal:
q_mask, kv_mask = map(lambda t: t.reshape(b, h, nc, -1), (indices, kv_indices))
mask = q_mask[:, :, :, :, None] >= kv_mask[:, :, :, None, :]
mask = F.pad(mask, (self.num_mem_kv, 0), value=True)
dots.masked_fill_(~mask, mask_value)
del mask
if self.shared_qk:
q_mask, kv_mask = map(lambda t: t.reshape(b, h, nc, -1), (indices, kv_indices))
mask = q_mask[:, :, :, :, None] == kv_mask[:, :, :, None, :]
mask = F.pad(mask, (self.num_mem_kv, 0), value=False)
dots.masked_fill_(mask, TOKEN_SELF_ATTN_VALUE)
del mask
dots = dots.softmax(dim=-1)
dots = self.dropout(dots)
bo = torch.einsum('bhcij,bhcjd->bhcid', dots, v)
so = torch.reshape(bo, (b, h, -1, bo.shape[-1])).type(dtype)
out = scatter_mean(out, so, indices.unsqueeze(-1).expand_as(so), -2)
return out, aux_loss
# self attention
class SelfAttention(nn.Module):
def __init__(self, dim, max_seq_len, heads, window_size,num_clusters=None,causal = False, attn_dropout = 0., dropout = 0., kmeans_ema_decay = 0.999, commitment_factor = 1e-4, receives_context = False, num_mem_kv = 0, shared_qk = False):
super().__init__()
assert dim % heads == 0, 'hidden dimension must be divisible by number of heads'
assert (max_seq_len % window_size) == 0, 'maximum sequence length must be divisible by the target window size'
assert not (receives_context and causal), 'contextual attention layer cannot be causal'
self.shared_qk = shared_qk
self.receives_context = receives_context
self.heads = heads
self.global_attn_heads = heads
self.window_size = window_size
dim_head = dim // heads
dim_heads = dim_head * heads
self.dim_head = dim_head
if num_clusters ==None:
num_clusters = max_seq_len // window_size
else:
window_size=max_seq_len//num_clusters
# global
global_dim_heads = dim_head * self.global_attn_heads
if self.global_attn_heads > 0:
self.global_attn = KmeansAttention(num_clusters, window_size, self.global_attn_heads, dim_head, causal = causal, dropout = attn_dropout, ema_decay = kmeans_ema_decay, commitment = commitment_factor, receives_context = receives_context, num_mem_kv = num_mem_kv, shared_qk = shared_qk)
self.to_q = nn.Linear(dim, global_dim_heads, bias = False)
self.to_v = nn.Linear(dim, global_dim_heads, bias = False)
if not self.shared_qk:
self.to_k = nn.Linear(dim, global_dim_heads, bias = False)
# out
self.to_out = nn.Linear(dim_heads, dim, bias = False)
self.dropout = nn.Dropout(dropout)
def forward(self, x, context = None, input_mask = None, context_mask = None, **kwargs):
assert not (self.receives_context and context is None), 'context must be passed if self attention is set to receive context'
#x.shape=b,t,e
x=x.transpose(0,1)
b, t, e, h, dh = *x.shape, self.heads, self.dim_head
split_heads = lambda v: reshape_dim(v, -1, (-1, dh)).transpose(1, 2).contiguous()
kv_input = x if not self.receives_context else context
q, v = self.to_q(x), self.to_v(kv_input)
if not self.shared_qk:
k = self.to_k(kv_input)
else:
k = self.to_q(kv_input) if self.receives_context else q
q, k, v = map(split_heads, (q, k, v))
out = []
total_loss = torch.tensor(0., requires_grad=True, **to(x))
global_out, loss = self.global_attn(q, k, v, query_mask = input_mask, key_mask = context_mask)
total_loss = total_loss + loss
out.append(global_out)
out = torch.cat(out, dim=1)
out = out.reshape(b, h, t, -1).transpose(1, 2).reshape(b, t, -1)
out = self.to_out(out)
out=out.transpose(0,1)
return self.dropout(out), total_loss
class ClusteringTransformer(nn.Module):
def __init__(self, dim, max_seq_len, heads = 8, window_size = 64,num_clusters=None, causal = False, attn_dropout = 0., attn_layer_dropout = 0., kmeans_ema_decay = 0.999, commitment_factor = 1e-4, _register_kmeans_update = False, rel_pos_emb = True, num_mem_kv = 0, shared_qk = None):
super().__init__()
shared_qk = default(shared_qk, causal) # default to shared qk when causal, due to experimental results
self.get_attn =SelfAttention(dim, max_seq_len, heads, window_size,num_clusters=num_clusters, causal = causal, attn_dropout = attn_dropout, dropout = attn_layer_dropout, kmeans_ema_decay = kmeans_ema_decay, commitment_factor = commitment_factor, num_mem_kv = num_mem_kv, shared_qk = shared_qk)
self._handle = None
if _register_kmeans_update:
self.register_kmeans_update()
def cancel_kmeans_update(self):
if self._handle is None:
return
self._handle.remove()
self._handle = None
def register_kmeans_update(self):
self._handle = update_kmeans_on_backwards(self)
def forward(self, x, **kwargs):
x, loss = self.get_attn(x)
return x, loss
| [
"torch.nn.Dropout",
"torch.randperm",
"torch.max",
"torch.nn.functional.pad",
"functools.wraps",
"torch.randint",
"torch.finfo",
"torch.zeros_like",
"torch.randn",
"torch.distributed.get_world_size",
"torch.ones_like",
"torch.nn.functional.mse_loss",
"functools.reduce",
"torch.nn.functiona... | [((996, 1004), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (1001, 1004), False, 'from functools import partial, reduce, wraps\n'), ((2976, 3016), 'torch.einsum', 'torch.einsum', (['"""bhld,hcd->bhlc"""', 'x', 'means'], {}), "('bhld,hcd->bhlc', x, means)\n", (2988, 3016), False, 'import torch\n'), ((3101, 3125), 'torch.max', 'torch.max', (['dists'], {'dim': '(-1)'}), '(dists, dim=-1)\n', (3110, 3125), False, 'import torch\n'), ((4651, 4666), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4664, 4666), False, 'import torch\n'), ((5448, 5463), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5461, 5463), False, 'import torch\n'), ((1774, 1803), 'functools.reduce', 'reduce', (['mul', 'shape[arr_slice]'], {}), '(mul, shape[arr_slice])\n', (1780, 1803), False, 'from functools import partial, reduce, wraps\n'), ((2126, 2144), 'torch.ones_like', 'torch.ones_like', (['t'], {}), '(t)\n', (2141, 2144), False, 'import torch\n'), ((3328, 3369), 'torch.ones_like', 'torch.ones_like', (['index'], {'dtype': 'index.dtype'}), '(index, dtype=index.dtype)\n', (3343, 3369), False, 'import torch\n'), ((5876, 5897), 'torch.distributed.get_world_size', 'dist.get_world_size', ([], {}), '()\n', (5895, 5897), True, 'import torch.distributed as dist\n'), ((7320, 7339), 'torch.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(dropout)\n', (7330, 7339), True, 'import torch.nn as nn\n'), ((7931, 7963), 'torch.zeros_like', 'torch.zeros_like', (['q'], {'dtype': 'dtype'}), '(q, dtype=dtype)\n', (7947, 7963), False, 'import torch\n'), ((10736, 10779), 'torch.einsum', 'torch.einsum', (['"""bhcij,bhcjd->bhcid"""', 'dots', 'v'], {}), "('bhcij,bhcjd->bhcid', dots, v)\n", (10748, 10779), False, 'import torch\n'), ((12465, 12509), 'torch.nn.Linear', 'nn.Linear', (['dim', 'global_dim_heads'], {'bias': '(False)'}), '(dim, global_dim_heads, bias=False)\n', (12474, 12509), True, 'import torch.nn as nn\n'), ((12532, 12576), 'torch.nn.Linear', 'nn.Linear', (['dim', 'global_dim_heads'], {'bias': '(False)'}), '(dim, global_dim_heads, bias=False)\n', (12541, 12576), True, 'import torch.nn as nn\n'), ((12720, 12757), 'torch.nn.Linear', 'nn.Linear', (['dim_heads', 'dim'], {'bias': '(False)'}), '(dim_heads, dim, bias=False)\n', (12729, 12757), True, 'import torch.nn as nn\n'), ((12783, 12802), 'torch.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(dropout)\n', (12793, 12802), True, 'import torch.nn as nn\n'), ((13818, 13839), 'torch.cat', 'torch.cat', (['out'], {'dim': '(1)'}), '(out, dim=1)\n', (13827, 13839), False, 'import torch\n'), ((1463, 1488), 'torch.finfo', 'torch.finfo', (['tensor.dtype'], {}), '(tensor.dtype)\n', (1474, 1488), False, 'import torch\n'), ((4447, 4493), 'torch.randn', 'torch.randn', (['num_heads', 'num_clusters', 'head_dim'], {}), '(num_heads, num_clusters, head_dim)\n', (4458, 4493), False, 'import torch\n'), ((5113, 5174), 'torch.randint', 'torch.randint', (['(0)', 'num_samples', '(num_clusters,)'], {'device': 'device'}), '(0, num_samples, (num_clusters,), device=device)\n', (5126, 5174), False, 'import torch\n'), ((6040, 6055), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6053, 6055), False, 'import torch\n'), ((6208, 6235), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['x', 'routed_means'], {}), '(x, routed_means)\n', (6218, 6235), True, 'import torch.nn.functional as F\n'), ((7457, 7520), 'torch.randn', 'torch.randn', (['num_heads', 'num_clusters', 'self.num_mem_kv', 'head_dim'], {}), '(num_heads, num_clusters, self.num_mem_kv, head_dim)\n', (7468, 7520), False, 'import torch\n'), ((7560, 7623), 'torch.randn', 'torch.randn', (['num_heads', 'num_clusters', 'self.num_mem_kv', 'head_dim'], {}), '(num_heads, num_clusters, self.num_mem_kv, head_dim)\n', (7571, 7623), False, 'import torch\n'), ((9193, 9233), 'torch.einsum', 'torch.einsum', (['"""bhnid,bhnjd->bhnij"""', 'q', 'k'], {}), "('bhnid,bhnjd->bhnij', q, k)\n", (9205, 9233), False, 'import torch\n'), ((9859, 9904), 'torch.nn.functional.pad', 'F.pad', (['mask', '(self.num_mem_kv, 0)'], {'value': '(True)'}), '(mask, (self.num_mem_kv, 0), value=True)\n', (9864, 9904), True, 'import torch.nn.functional as F\n'), ((10184, 10229), 'torch.nn.functional.pad', 'F.pad', (['mask', '(self.num_mem_kv, 0)'], {'value': '(True)'}), '(mask, (self.num_mem_kv, 0), value=True)\n', (10189, 10229), True, 'import torch.nn.functional as F\n'), ((10524, 10570), 'torch.nn.functional.pad', 'F.pad', (['mask', '(self.num_mem_kv, 0)'], {'value': '(False)'}), '(mask, (self.num_mem_kv, 0), value=False)\n', (10529, 10570), True, 'import torch.nn.functional as F\n'), ((12635, 12679), 'torch.nn.Linear', 'nn.Linear', (['dim', 'global_dim_heads'], {'bias': '(False)'}), '(dim, global_dim_heads, bias=False)\n', (12644, 12679), True, 'import torch.nn as nn\n'), ((853, 866), 'inspect.isfunction', 'isfunction', (['d'], {}), '(d)\n', (863, 866), False, 'from inspect import isfunction\n'), ((5019, 5061), 'torch.randperm', 'torch.randperm', (['num_samples'], {'device': 'device'}), '(num_samples, device=device)\n', (5033, 5061), False, 'import torch\n'), ((5988, 6013), 'torch.nn.functional.normalize', 'F.normalize', (['x', '(2)'], {'dim': '(-1)'}), '(x, 2, dim=-1)\n', (5999, 6013), True, 'import torch.nn.functional as F\n'), ((6314, 6329), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6327, 6329), False, 'import torch\n'), ((8345, 8369), 'torch.cat', 'torch.cat', (['(q, k)'], {'dim': '(2)'}), '((q, k), dim=2)\n', (8354, 8369), False, 'import torch\n'), ((9134, 9153), 'torch.cat', 'torch.cat', (['x'], {'dim': '(3)'}), '(x, dim=3)\n', (9143, 9153), False, 'import torch\n'), ((10793, 10836), 'torch.reshape', 'torch.reshape', (['bo', '(b, h, -1, bo.shape[-1])'], {}), '(bo, (b, h, -1, bo.shape[-1]))\n', (10806, 10836), False, 'import torch\n'), ((8639, 8661), 'torch.nn.functional.normalize', 'F.normalize', (['k'], {'dim': '(-1)'}), '(k, dim=-1)\n', (8650, 8661), True, 'import torch.nn.functional as F\n'), ((9403, 9436), 'torch.ones', 'torch.ones', (['(b, t)'], {'device': 'device'}), '((b, t), device=device)\n', (9413, 9436), False, 'import torch\n'), ((9494, 9530), 'torch.ones', 'torch.ones', (['(b, kv_t)'], {'device': 'device'}), '((b, kv_t), device=device)\n', (9504, 9530), False, 'import torch\n')] |