hexsha stringlengths 40 40 | size int64 5 2.06M | ext stringclasses 10 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 248 | max_stars_repo_name stringlengths 5 125 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 248 | max_issues_repo_name stringlengths 5 125 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 248 | max_forks_repo_name stringlengths 5 125 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 2.06M | avg_line_length float64 1 1.02M | max_line_length int64 3 1.03M | alphanum_fraction float64 0 1 | count_classes int64 0 1.6M | score_classes float64 0 1 | count_generators int64 0 651k | score_generators float64 0 1 | count_decorators int64 0 990k | score_decorators float64 0 1 | count_async_functions int64 0 235k | score_async_functions float64 0 1 | count_documentation int64 0 1.04M | score_documentation float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d52dbcb5f5f927e8beee568c91222838c4d49f6e | 11,606 | py | Python | cross_correlation.py | sbargy/cross-correlation | ee6f991758dbe6715d8cbf3ec03b07407f2acdf1 | [
"MIT"
] | null | null | null | cross_correlation.py | sbargy/cross-correlation | ee6f991758dbe6715d8cbf3ec03b07407f2acdf1 | [
"MIT"
] | null | null | null | cross_correlation.py | sbargy/cross-correlation | ee6f991758dbe6715d8cbf3ec03b07407f2acdf1 | [
"MIT"
] | 1 | 2020-06-23T21:06:33.000Z | 2020-06-23T21:06:33.000Z | #!/usr/bin/env python3
# system imports
import argparse
import sys
# obspy imports
from obspy.clients.fdsn import Client
from obspy import read, read_inventory, UTCDateTime
from scipy import signal
from obspy.signal.cross_correlation import correlate, xcorr_max
from obspy.clients.fdsn.header import FDSNNoDataException
from obspy.core.stream import Stream
# other imports
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import pickle
################################################################################
def main():
parser = argparse.ArgumentParser(description="Cross correlate sensor streams", formatter_class=SmartFormatter)
parser.add_argument("net",
help="Network code (e.g. II)",
action="store")
parser.add_argument("sta",
help="Station Code (e.g. MSEY or WRAB)",
action="store")
parser.add_argument("chan",
help="channel (e.g. BHZ or BH0",
action="store")
parser.add_argument("startdate",
help="R|start date (YYYY-JJJ OR\n"
"YYYY-MM-DD), UTC is assumed",
action="store")
parser.add_argument("enddate",
help="R|end date (YYYY-JJJ OR\n"
"YYYY-MM-DD), UTC is assumed",
action="store")
parser.add_argument("-d", "--duration",
help="the duration in seconds of the sample",
action="store",
type=int)
parser.add_argument("-i", "--interval",
help="interval in minutes to skip between segments",
action="store",
default="14400",
type=int)
parser.add_argument("-k", "--keepresponse",
help="don't use the remove_response call",
action="store_true")
parser.add_argument("-o", "--outfilename",
help="the filename for the plot output file",
action="store",
type=str)
parser.add_argument("-r", "--responsefilepath",
help="the path to the response file location, the filename is generated in code",
action="store",
type=str)
parser.add_argument("-v", "--verbose",
help="extra output for debugging",
action="store_true",
default=False)
args = parser.parse_args()
# upper case the stations and channels
args.sta = args.sta.upper()
args.chan = args.chan.upper()
doCorrelation(args.net, args.sta, args.chan, args.startdate, args.enddate, args.duration, \
args.interval, args.keepresponse, args.outfilename, args.responsefilepath, args.verbose)
################################################################################
def doCorrelation(net, sta, chan, start, end, duration, interval,
keep_response, outfilename, resp_filepath, be_verbose):
stime = UTCDateTime(start)
etime = UTCDateTime(end)
ctime = stime
skiptime = 24*60*60*10 # 10 days in seconds. Override with --interval <minutes> option
skiptime = interval*60 #
# location constants
LOC00 = '00'
LOC10 = '10'
# True to calculate values, False to read them from a pickle file
# this might be desirable when debugging the plotting code piece
calc = True
print(net, sta, LOC00, LOC10, duration, interval, stime, etime, keep_response, resp_filepath)
if calc:
times, shifts, vals = [],[], []
while ctime < etime:
cnt = 1
attach_response = True
if resp_filepath:
inv00 = read_inventory(f'{resp_filepath}/RESP.{net}.{sta}.{LOC00}.{chan}', 'RESP')
inv10 = read_inventory(f'{resp_filepath}/RESP.{net}.{sta}.{LOC10}.{chan}', 'RESP')
attach_response = False
st00 = getStream(net, sta, LOC00, chan, ctime, duration, be_verbose, attach_response)
st10 = getStream(net, sta, LOC10, chan, ctime, duration, be_verbose, attach_response)
if len(st00) == 0:
if be_verbose:
print("no traces returned for {} {} {} {} {}".format(net, sta, LOC00, chan, ctime), file=sys.stderr)
ctime += skiptime
continue
if len(st10) == 0:
if be_verbose:
print("no traces returned for {} {} {} {} {}".format(net, sta, LOC10, chan, ctime), file=sys.stderr)
ctime += skiptime
continue
if len(st00) > 1:
if be_verbose:
print("gap(s) found in segment for {} {} {} {} {}".format(net, sta, LOC00, chan, ctime), file=sys.stderr)
ctime += skiptime
continue
if len(st10) > 1:
if be_verbose:
print("gap(s) found in segment for {} {} {} {} {}".format(net, sta, LOC10, chan, ctime), file=sys.stderr)
ctime += skiptime
continue
if ((st00[0].stats.endtime - st00[0].stats.starttime) < (duration - 1.0/st00[0].stats.sampling_rate)):
if be_verbose:
print("skipping short segment in {} {} {} {} {}".format(net, sta, LOC00, chan, ctime), file=sys.stderr)
ctime += skiptime
continue
if ((st10[0].stats.endtime - st10[0].stats.starttime) < (duration - 1.0/st10[0].stats.sampling_rate)):
if be_verbose:
print("skipping short segment in {} {} {} {} {}".format(net, sta, LOC10, chan, ctime), file=sys.stderr)
ctime += skiptime
continue
if not attach_response:
st00.attach_response(inv00)
st10.attach_response(inv10)
if not keep_response:
st00.remove_response()
st10.remove_response()
# apply a bandpass filter and merge before resampling
st00.filter('bandpass', freqmax=1/4., freqmin=1./8., zerophase=True)
st00.resample(1000)
st10.filter('bandpass', freqmax=1/4., freqmin=1./8., zerophase=True)
st10.resample(1000)
# get the traces from the stream for each location
try:
tr1 = st00.select(location=LOC00)[0]
except Exception as err:
print(err, file=sys.stderr)
try:
tr2 = st10.select(location=LOC10)[0]
except Exception as err:
print(err, file=sys.stderr)
# trim sample to start and end at the same times
trace_start = max(tr1.stats.starttime, tr2.stats.starttime)
trace_end = min(tr1.stats.endtime, tr2.stats.endtime)
# debug
if be_verbose:
print("Before trim", file=sys.stderr)
print("tr1 start: {} tr2 start: {}".format(tr1.stats.starttime, tr2.stats.starttime), file=sys.stderr)
print("tr1 end: {} tr2 end: {}".format(tr1.stats.endtime, tr2.stats.endtime), file=sys.stderr)
print("max trace_start: {} min trace_end {}".format(trace_start, trace_end), file=sys.stderr)
tr1.trim(trace_start, trace_end)
tr2.trim(trace_start, trace_end)
# debug
if be_verbose:
print("After trim", file=sys.stderr)
print("tr1 start: {} tr2 start: {}".format(tr1.stats.starttime, tr2.stats.starttime), file=sys.stderr)
print("tr1 end: {} tr2 end: {}".format(tr1.stats.endtime, tr2.stats.endtime), file=sys.stderr)
# calculate time offset
time_offset = tr1.stats.starttime - tr2.stats.starttime
cc = correlate(tr1.data, tr2.data, 500)
# xcorr_max returns the shift and value of the maximum of the cross-correlation function
shift, val = xcorr_max(cc)
# append to lists for plotting
shifts.append(shift)
vals.append(val)
times.append(ctime.year + ctime.julday/365.25)
print("duration: {} to {} offset: {}\tshift: {} value: {}".format(ctime, ctime+duration, time_offset, shift, val))
# skip 10 days for next loop
if be_verbose:
print("ctime: {}".format(ctime), file=sys.stderr)
ctime += skiptime
# persist the data in a pickle file
if outfilename:
with open(outfilename + '.pickle', 'wb') as f:
pickle.dump([shifts, vals, times], f)
else:
with open(net + '_' + sta + '_' + net + '_' + sta + '.pickle', 'wb') as f:
pickle.dump([shifts, vals, times], f)
else:
# retrieve the data from the pickle file
if outfilename:
with open(outfilename + '.pickle', 'rb') as f:
shifts, vals, times = pickle.load(f)
else:
with open(net + '_' + sta + '_' + net + '_' + sta + '.pickle', 'rb') as f:
shifts, vals, times = pickle.load(f)
mpl.rc('font',serif='Times')
mpl.rc('font',size=16)
fig = plt.figure(1, figsize=(10,10))
plt.subplot(2,1,1)
plt.title(net + ' ' + sta + ' ' + LOC00 + ' compared to ' + net + ' ' + sta + ' ' + LOC10)
plt.plot(times, shifts,'.')
plt.ylabel('Time Shift (ms)')
plt.subplot(2,1,2)
plt.plot(times, vals, '.')
#plt.ylim((0.8, 1.0))
plt.ylim((0, 1.0))
plt.xlabel('Time (year)')
plt.ylabel('Correlation')
if outfilename:
plt.savefig(outfilename + '.PDF', format='PDF')
else:
plt.savefig(net + '_' + sta + '_' + net + '_' + sta + '.PDF', format='PDF')
################################################################################
def getStream(net, sta, loc, chan, ctime, duration, be_verbose, attach_response):
cnt = 1
client = Client()
st = Stream()
while cnt <= 4:
try:
# get_waveforms gets 'duration' seconds of activity for the channel/date/location
# only attach response if we're not using a response file
if attach_response:
st = client.get_waveforms(net, sta, loc, chan, ctime, ctime + duration, attach_response=True)
else:
st = client.get_waveforms(net, sta, loc, chan, ctime, ctime + duration)
break
except KeyboardInterrupt:
sys.exit()
except FDSNNoDataException:
if be_verbose:
print(f"No data available for {net}.{sta}.{loc}.{chan} {ctime} to {ctime+duration}", file=sys.stderr)
except Exception as err:
print(err, file=sys.stderr)
finally:
cnt += 1
return st
################################################################################
class SmartFormatter(argparse.HelpFormatter):
def _split_lines(self, text, width):
if text.startswith('R|'):
return text[2:].splitlines()
# this is the RawTextHelpFormatter._split_lines
return argparse.HelpFormatter._split_lines(self, text, width)
################################################################################
if __name__ == '__main__':
main()
| 41.45 | 126 | 0.525418 | 287 | 0.024729 | 0 | 0 | 0 | 0 | 0 | 0 | 2,978 | 0.256591 |
d52e9d0960091a82d4473fa8f90e1a3e2e15884d | 32,810 | py | Python | djcloudbridge/serializers.py | almahmoud/djcloudbridge | 0a00ccefb217cc3962315019405dd176956c1830 | [
"MIT"
] | null | null | null | djcloudbridge/serializers.py | almahmoud/djcloudbridge | 0a00ccefb217cc3962315019405dd176956c1830 | [
"MIT"
] | null | null | null | djcloudbridge/serializers.py | almahmoud/djcloudbridge | 0a00ccefb217cc3962315019405dd176956c1830 | [
"MIT"
] | null | null | null | import urllib
from cloudbridge.cloud.interfaces.resources import TrafficDirection
from rest_auth.serializers import UserDetailsSerializer
from rest_framework import serializers
from rest_framework.reverse import reverse
from . import models
from . import view_helpers
from .drf_helpers import CustomHyperlinkedIdentityField
from .drf_helpers import PlacementZonePKRelatedField
from .drf_helpers import ProviderPKRelatedField
class ZoneSerializer(serializers.Serializer):
id = serializers.CharField(read_only=True)
name = serializers.CharField(read_only=True)
class RegionSerializer(serializers.Serializer):
id = serializers.CharField(read_only=True)
url = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:region-detail',
lookup_field='id',
lookup_url_kwarg='pk',
parent_url_kwargs=['cloud_pk'])
name = serializers.CharField(read_only=True)
zones = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:zone-list',
lookup_field='id',
lookup_url_kwarg='region_pk',
parent_url_kwargs=['cloud_pk'])
class MachineImageSerializer(serializers.Serializer):
id = serializers.CharField(read_only=True)
url = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:machine_image-detail',
lookup_field='id',
lookup_url_kwarg='pk',
parent_url_kwargs=['cloud_pk'])
name = serializers.CharField(read_only=True)
label = serializers.CharField()
description = serializers.CharField()
class KeyPairSerializer(serializers.Serializer):
id = serializers.CharField(read_only=True)
url = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:keypair-detail',
lookup_field='id',
lookup_url_kwarg='pk',
parent_url_kwargs=['cloud_pk'])
name = serializers.CharField(required=True)
material = serializers.CharField(read_only=True)
def create(self, validated_data):
provider = view_helpers.get_cloud_provider(self.context.get('view'))
return provider.security.key_pairs.create(validated_data.get('name'))
class VMFirewallRuleSerializer(serializers.Serializer):
protocol = serializers.CharField(allow_blank=True)
from_port = serializers.CharField(allow_blank=True)
to_port = serializers.CharField(allow_blank=True)
cidr = serializers.CharField(label="CIDR", allow_blank=True)
firewall = ProviderPKRelatedField(
label="VM Firewall",
queryset='security.vm_firewalls',
display_fields=['name', 'id'],
display_format="{0} (ID: {1})",
required=False,
allow_null=True)
url = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:vm_firewall_rule-detail',
lookup_field='id',
lookup_url_kwarg='pk',
parent_url_kwargs=['cloud_pk', 'vm_firewall_pk'])
def validate(self, data):
"""Cursory data check."""
if data.get('protocol').lower() not in ['tcp', 'udp', 'icmp']:
raise serializers.ValidationError(
'Protocol must be one of: tcp, udp, icmp.')
try:
if not (1 < int(data['from_port']) <= 65535):
raise serializers.ValidationError(
'From port must be an integer between 1 and 65535.')
elif not (1 < int(data['to_port']) <= 65535):
raise serializers.ValidationError(
'To port must be an integer between 1 and 65535.')
except ValueError:
raise serializers.ValidationError(
'To/from ports must be integers.')
return data
def create(self, validated_data):
view = self.context.get('view')
provider = view_helpers.get_cloud_provider(view)
vmf_pk = view.kwargs.get('vm_firewall_pk')
if vmf_pk:
vmf = provider.security.vm_firewalls.get(vmf_pk)
if vmf and validated_data.get('firewall'):
return vmf.rules.create(
TrafficDirection.INBOUND,
validated_data.get('protocol'),
int(validated_data.get('from_port')),
int(validated_data.get('to_port')),
src_dest_fw=validated_data.get('firewall'))
elif vmf:
return vmf.rules.create(TrafficDirection.INBOUND,
validated_data.get('protocol'),
int(validated_data.get('from_port')),
int(validated_data.get('to_port')),
validated_data.get('cidr'))
return None
class VMFirewallSerializer(serializers.Serializer):
id = serializers.CharField(read_only=True)
url = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:vm_firewall-detail',
lookup_field='id',
lookup_url_kwarg='pk',
parent_url_kwargs=['cloud_pk'])
name = serializers.CharField(read_only=True)
label = serializers.CharField(required=True)
# Technically, the description is required but when wanting to reuse an
# existing VM firewall with a different resource (eg, creating an
# instance), we need to be able to call this serializer w/o it.
description = serializers.CharField(required=False)
network_id = ProviderPKRelatedField(
queryset='networking.networks',
display_fields=['id', 'label'],
display_format="{1} ({0})")
rules = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:vm_firewall_rule-list',
lookup_field='id',
lookup_url_kwarg='vm_firewall_pk',
parent_url_kwargs=['cloud_pk'])
def create(self, validated_data):
provider = view_helpers.get_cloud_provider(self.context.get('view'))
return provider.security.vm_firewalls.create(
label=validated_data.get('label'),
network_id=validated_data.get('network_id').id,
description=validated_data.get('description'))
class NetworkingSerializer(serializers.Serializer):
networks = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:network-list',
parent_url_kwargs=['cloud_pk'])
routers = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:router-list',
parent_url_kwargs=['cloud_pk'])
class NetworkSerializer(serializers.Serializer):
id = serializers.CharField(read_only=True)
url = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:network-detail',
lookup_field='id',
lookup_url_kwarg='pk',
parent_url_kwargs=['cloud_pk'])
name = serializers.CharField(read_only=True)
label = serializers.CharField(required=True)
state = serializers.CharField(read_only=True)
cidr_block = serializers.CharField()
subnets = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:subnet-list',
lookup_field='id',
lookup_url_kwarg='network_pk',
parent_url_kwargs=['cloud_pk'])
gateways = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:gateway-list',
lookup_field='id',
lookup_url_kwarg='network_pk',
parent_url_kwargs=['cloud_pk'])
def create(self, validated_data):
provider = view_helpers.get_cloud_provider(self.context.get('view'))
return provider.networking.networks.create(
label=validated_data.get('label'),
cidr_block=validated_data.get('cidr_block', '10.0.0.0/16'))
def update(self, instance, validated_data):
# We do not allow the cidr_block to be edited so the value is ignored
# and only the name is updated.
try:
if instance.label != validated_data.get('label'):
instance.label = validated_data.get('label')
return instance
except Exception as e:
raise serializers.ValidationError("{0}".format(e))
class SubnetSerializer(serializers.Serializer):
id = serializers.CharField(read_only=True)
url = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:subnet-detail',
lookup_field='id',
lookup_url_kwarg='pk',
parent_url_kwargs=['cloud_pk', 'network_pk'])
name = serializers.CharField(read_only=True)
label = serializers.CharField(required=True)
cidr_block = serializers.CharField()
network_id = serializers.CharField(read_only=True)
zone = PlacementZonePKRelatedField(
label="Zone",
queryset='non_empty_value',
display_fields=['id'],
display_format="{0}",
required=True)
def create(self, validated_data):
provider = view_helpers.get_cloud_provider(self.context.get('view'))
net_id = self.context.get('view').kwargs.get('network_pk')
return provider.networking.subnets.create(
label=validated_data.get('label'), network=net_id,
cidr_block=validated_data.get('cidr_block'),
zone=validated_data.get('zone'))
class SubnetSerializerUpdate(SubnetSerializer):
cidr_block = serializers.CharField(read_only=True)
def update(self, instance, validated_data):
try:
if instance.label != validated_data.get('label'):
instance.label = validated_data.get('label')
return instance
except Exception as e:
raise serializers.ValidationError("{0}".format(e))
class RouterSerializer(serializers.Serializer):
id = serializers.CharField(read_only=True)
url = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:router-detail',
lookup_field='id',
lookup_url_kwarg='pk',
parent_url_kwargs=['cloud_pk'])
name = serializers.CharField(read_only=True)
label = serializers.CharField(required=True)
state = serializers.CharField(read_only=True)
network_id = ProviderPKRelatedField(
queryset='networking.networks',
display_fields=['id', 'name'],
display_format="{1} ({0})")
def create(self, validated_data):
provider = view_helpers.get_cloud_provider(self.context.get('view'))
return provider.networking.routers.create(
label=validated_data.get('label'),
network=validated_data.get('network_id').id)
def update(self, instance, validated_data):
try:
if instance.label != validated_data.get('label'):
instance.label = validated_data.get('label')
return instance
except Exception as e:
raise serializers.ValidationError("{0}".format(e))
class GatewaySerializer(serializers.Serializer):
id = serializers.CharField(read_only=True)
url = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:gateway-detail',
lookup_field='id',
lookup_url_kwarg='pk',
parent_url_kwargs=['cloud_pk', 'network_pk'])
name = serializers.CharField()
state = serializers.CharField(read_only=True)
network_id = serializers.CharField(read_only=True)
floating_ips = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:floating_ip-list',
lookup_field='id',
lookup_url_kwarg='gateway_pk',
parent_url_kwargs=['cloud_pk', 'network_pk'])
def create(self, validated_data):
provider = view_helpers.get_cloud_provider(self.context.get('view'))
net_id = self.context.get('view').kwargs.get('network_pk')
net = provider.networking.networks.get(net_id)
return net.gateways.get_or_create_inet_gateway(
name=validated_data.get('name'))
class FloatingIPSerializer(serializers.Serializer):
id = serializers.CharField(read_only=True)
ip = serializers.CharField(read_only=True)
state = serializers.CharField(read_only=True)
class VMTypeSerializer(serializers.Serializer):
id = serializers.CharField(read_only=True)
url = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:vm_type-detail',
lookup_field='pk',
parent_url_kwargs=['cloud_pk'])
name = serializers.CharField()
family = serializers.CharField()
vcpus = serializers.CharField()
ram = serializers.CharField()
size_root_disk = serializers.CharField()
size_ephemeral_disks = serializers.CharField()
num_ephemeral_disks = serializers.CharField()
size_total_disk = serializers.CharField()
extra_data = serializers.DictField(serializers.CharField())
class AttachmentInfoSerializer(serializers.Serializer):
device = serializers.CharField(read_only=True)
instance_id = ProviderPKRelatedField(
label="Instance ID",
queryset='compute.instances',
display_fields=['name', 'id'],
display_format="{0} (ID: {1})",
required=False,
allow_null=True)
instance = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:instance-detail',
lookup_field='instance_id',
lookup_url_kwarg='pk',
parent_url_kwargs=['cloud_pk'])
class VolumeSerializer(serializers.Serializer):
id = serializers.CharField(read_only=True)
url = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:volume-detail',
lookup_field='id',
lookup_url_kwarg='pk',
parent_url_kwargs=['cloud_pk'])
name = serializers.CharField(read_only=True)
label = serializers.CharField(required=True)
description = serializers.CharField(allow_blank=True)
size = serializers.IntegerField(min_value=0)
create_time = serializers.CharField(read_only=True)
zone_id = PlacementZonePKRelatedField(
label="Zone",
queryset='non_empty_value',
display_fields=['id'],
display_format="{0}",
required=True)
state = serializers.CharField(read_only=True)
snapshot_id = ProviderPKRelatedField(
label="Snapshot ID",
queryset='storage.snapshots',
display_fields=['label', 'id', 'size'],
display_format="{0} (ID: {1}, Size: {2} GB)",
write_only=True,
required=False,
allow_null=True)
attachments = AttachmentInfoSerializer()
def create(self, validated_data):
provider = view_helpers.get_cloud_provider(self.context.get('view'))
try:
return provider.storage.volumes.create(
validated_data.get('label'),
validated_data.get('size'),
validated_data.get('zone_id'),
description=validated_data.get('description'),
snapshot=validated_data.get('snapshot_id'))
except Exception as e:
raise serializers.ValidationError("{0}".format(e))
def update(self, instance, validated_data):
try:
if instance.label != validated_data.get('label'):
instance.label = validated_data.get('label')
if instance.description != validated_data.get('description'):
instance.description = validated_data.get('description')
return instance
except Exception as e:
raise serializers.ValidationError("{0}".format(e))
class SnapshotSerializer(serializers.Serializer):
id = serializers.CharField(read_only=True)
url = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:snapshot-detail',
lookup_field='id',
lookup_url_kwarg='pk',
parent_url_kwargs=['cloud_pk'])
name = serializers.CharField(read_only=True)
label = serializers.CharField(required=True)
description = serializers.CharField()
state = serializers.CharField(read_only=True)
volume_id = ProviderPKRelatedField(
label="Volume ID",
queryset='storage.volumes',
display_fields=['label', 'id', 'size'],
display_format="{0} (ID: {1}, Size: {2} GB)",
required=True)
create_time = serializers.CharField(read_only=True)
size = serializers.IntegerField(min_value=0, read_only=True)
def create(self, validated_data):
provider = view_helpers.get_cloud_provider(self.context.get('view'))
try:
return provider.storage.snapshots.create(
validated_data.get('label'),
validated_data.get('volume_id'),
description=validated_data.get('description'))
except Exception as e:
raise serializers.ValidationError("{0}".format(e))
def update(self, instance, validated_data):
try:
if instance.label != validated_data.get('label'):
instance.label = validated_data.get('label')
if instance.description != validated_data.get('description'):
instance.description = validated_data.get('description')
return instance
except Exception as e:
raise serializers.ValidationError("{0}".format(e))
class InstanceSerializer(serializers.Serializer):
id = serializers.CharField(read_only=True)
url = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:instance-detail',
lookup_field='id',
lookup_url_kwarg='pk',
parent_url_kwargs=['cloud_pk'])
name = serializers.CharField(read_only=True)
label = serializers.CharField(required=True)
public_ips = serializers.ListField(serializers.IPAddressField())
private_ips = serializers.ListField(serializers.IPAddressField())
vm_type_id = ProviderPKRelatedField(
label="Instance Type",
queryset='compute.vm_types',
display_fields=['name'],
display_format="{0}",
required=True)
vm_type_url = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:vm_type-detail',
lookup_field='vm_type_id',
lookup_url_kwarg='pk',
parent_url_kwargs=['cloud_pk'])
image_id = ProviderPKRelatedField(
label="Image",
queryset='compute.images',
display_fields=['name', 'id', 'label'],
display_format="{0} (ID: {1}, Label: {2})",
required=True)
image_id_url = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:machine_image-detail',
lookup_field='image_id',
lookup_url_kwarg='pk',
parent_url_kwargs=['cloud_pk'])
key_pair_id = ProviderPKRelatedField(
label="Keypair",
queryset='security.key_pairs',
display_fields=['id'],
display_format="{0}",
required=True)
subnet_id = ProviderPKRelatedField(
label="Subnet",
queryset='networking.subnets',
display_fields=['id', 'label'],
display_format="{1} ({0})")
zone_id = PlacementZonePKRelatedField(
label="Placement Zone",
queryset='non_empty_value',
display_fields=['id'],
display_format="{0}",
required=True)
vm_firewall_ids = ProviderPKRelatedField(
label="VM Firewalls",
queryset='security.vm_firewalls',
display_fields=['name', 'id', 'label'],
display_format="{0} (ID: {1}, Label: {2})",
many=True)
user_data = serializers.CharField(write_only=True, allow_blank=True,
style={'base_template': 'textarea.html'})
def create(self, validated_data):
provider = view_helpers.get_cloud_provider(self.context.get('view'))
label = validated_data.get('label')
image_id = validated_data.get('image_id')
vm_type = validated_data.get('vm_type_id')
kp_name = validated_data.get('key_pair_name')
zone_id = validated_data.get('zone_id')
vm_firewall_ids = validated_data.get('vm_firewall_ids')
subnet_id = validated_data.get('subnet_id')
user_data = validated_data.get('user_data')
try:
return provider.compute.instances.create(
label, image_id, vm_type, subnet_id, zone_id,
key_pair=kp_name, vm_firewalls=vm_firewall_ids,
user_data=user_data)
except Exception as e:
raise serializers.ValidationError("{0}".format(e))
def update(self, instance, validated_data):
try:
if instance.label != validated_data.get('label'):
instance.label = validated_data.get('label')
return instance
except Exception as e:
raise serializers.ValidationError("{0}".format(e))
class BucketSerializer(serializers.Serializer):
id = serializers.CharField(read_only=True)
url = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:bucket-detail',
lookup_field='id',
lookup_url_kwarg='pk',
parent_url_kwargs=['cloud_pk'])
name = serializers.CharField()
objects = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:bucketobject-list',
lookup_field='id',
lookup_url_kwarg='bucket_pk',
parent_url_kwargs=['cloud_pk'])
def create(self, validated_data):
provider = view_helpers.get_cloud_provider(self.context.get('view'))
try:
return provider.storage.buckets.create(validated_data.get('name'))
except Exception as e:
raise serializers.ValidationError("{0}".format(e))
class BucketObjectSerializer(serializers.Serializer):
id = serializers.CharField(read_only=True)
name = serializers.CharField(allow_blank=True)
size = serializers.IntegerField(read_only=True)
last_modified = serializers.CharField(read_only=True)
url = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:bucketobject-detail',
lookup_field='id',
lookup_url_kwarg='pk',
parent_url_kwargs=['cloud_pk', 'bucket_pk'])
download_url = serializers.SerializerMethodField()
upload_content = serializers.FileField(write_only=True)
def get_download_url(self, obj):
"""Create a URL for accessing a single instance."""
kwargs = self.context['view'].kwargs.copy()
kwargs.update({'pk': obj.id})
obj_url = reverse('djcloudbridge:bucketobject-detail',
kwargs=kwargs,
request=self.context['request'])
return urllib.parse.urljoin(obj_url, '?format=binary')
def create(self, validated_data):
provider = view_helpers.get_cloud_provider(self.context.get('view'))
bucket_id = self.context.get('view').kwargs.get('bucket_pk')
bucket = provider.storage.buckets.get(bucket_id)
try:
name = validated_data.get('name')
content = validated_data.get('upload_content')
if name:
obj = bucket.objects.create(name)
else:
obj = bucket.objects.create(content.name)
if content:
obj.upload(content.file.getvalue())
return obj
except Exception as e:
raise serializers.ValidationError("{0}".format(e))
def update(self, instance, validated_data):
try:
instance.upload(
validated_data.get('upload_content').file.getvalue())
return instance
except Exception as e:
raise serializers.ValidationError("{0}".format(e))
class CloudSerializer(serializers.ModelSerializer):
slug = serializers.CharField(read_only=True)
compute = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:compute-list',
lookup_field='slug',
lookup_url_kwarg='cloud_pk')
security = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:security-list',
lookup_field='slug',
lookup_url_kwarg='cloud_pk')
storage = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:storage-list',
lookup_field='slug',
lookup_url_kwarg='cloud_pk')
networking = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:networking-list',
lookup_field='slug',
lookup_url_kwarg='cloud_pk')
region_name = serializers.SerializerMethodField()
cloud_type = serializers.SerializerMethodField()
extra_data = serializers.SerializerMethodField()
def get_region_name(self, obj):
if hasattr(obj, 'aws'):
return obj.aws.region_name
elif hasattr(obj, 'openstack'):
return obj.openstack.region_name
elif hasattr(obj, 'azure'):
return obj.azure.region_name
elif hasattr(obj, 'gcp'):
return obj.gcp.region_name
else:
return "Cloud provider not recognized"
def get_cloud_type(self, obj):
if hasattr(obj, 'aws'):
return 'aws'
elif hasattr(obj, 'openstack'):
return 'openstack'
elif hasattr(obj, 'azure'):
return 'azure'
elif hasattr(obj, 'gcp'):
return 'gcp'
else:
return 'unknown'
def get_extra_data(self, obj):
if hasattr(obj, 'aws'):
aws = obj.aws
return {'region_name': aws.region_name,
'ec2_endpoint_url': aws.ec2_endpoint_url,
'ec2_is_secure': aws.ec2_is_secure,
'ec2_validate_certs': aws.ec2_validate_certs,
's3_endpoint_url': aws.s3_endpoint_url,
's3_is_secure': aws.s3_is_secure,
's3_validate_certs': aws.s3_validate_certs
}
elif hasattr(obj, 'openstack'):
os = obj.openstack
return {'auth_url': os.auth_url,
'region_name': os.region_name,
'identity_api_version': os.identity_api_version
}
elif hasattr(obj, 'azure'):
azure = obj.azure
return {'region_name': azure.region_name}
elif hasattr(obj, 'gcp'):
gcp = obj.gcp
return {'region_name': gcp.region_name,
'zone_name': gcp.zone_name
}
else:
return {}
class Meta:
model = models.Cloud
exclude = ('kind',)
class ComputeSerializer(serializers.Serializer):
instances = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:instance-list',
parent_url_kwargs=['cloud_pk'])
machine_images = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:machine_image-list',
parent_url_kwargs=['cloud_pk'])
regions = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:region-list',
parent_url_kwargs=['cloud_pk'])
vm_types = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:vm_type-list',
parent_url_kwargs=['cloud_pk'])
class SecuritySerializer(serializers.Serializer):
keypairs = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:keypair-list',
parent_url_kwargs=['cloud_pk'])
vm_firewalls = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:vm_firewall-list',
parent_url_kwargs=['cloud_pk'])
class StorageSerializer(serializers.Serializer):
volumes = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:volume-list',
parent_url_kwargs=['cloud_pk'])
snapshots = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:snapshot-list',
parent_url_kwargs=['cloud_pk'])
buckets = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:bucket-list',
parent_url_kwargs=['cloud_pk'])
"""
User Profile and Credentials related serializers
"""
class CredentialsSerializer(serializers.Serializer):
aws = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:awscredentials-list')
openstack = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:openstackcredentials-list')
azure = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:azurecredentials-list')
gcp = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:gcpcredentials-list')
class AWSCredsSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(read_only=True)
secret_key = serializers.CharField(
style={'input_type': 'password'},
write_only=True,
required=False
)
cloud_id = serializers.CharField(write_only=True)
cloud = CloudSerializer(read_only=True)
class Meta:
model = models.AWSCredentials
exclude = ('user_profile',)
class OpenstackCredsSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(read_only=True)
password = serializers.CharField(
style={'input_type': 'password'},
write_only=True,
required=False
)
cloud_id = serializers.CharField(write_only=True)
cloud = CloudSerializer(read_only=True)
class Meta:
model = models.OpenStackCredentials
exclude = ('user_profile',)
class AzureCredsSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(read_only=True)
secret = serializers.CharField(
style={'input_type': 'password'},
write_only=True,
required=False
)
cloud_id = serializers.CharField(write_only=True)
cloud = CloudSerializer(read_only=True)
class Meta:
model = models.AzureCredentials
exclude = ('user_profile',)
class GCPCredsSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(read_only=True)
credentials = serializers.CharField(
write_only=True,
style={'base_template': 'textarea.html', 'rows': 20},
)
cloud_id = serializers.CharField(write_only=True)
cloud = CloudSerializer(read_only=True)
class Meta:
model = models.GCPCredentials
exclude = ('user_profile',)
class CloudConnectionAuthSerializer(serializers.Serializer):
aws_creds = AWSCredsSerializer(write_only=True, required=False)
openstack_creds = OpenstackCredsSerializer(write_only=True, required=False)
azure_creds = AzureCredsSerializer(write_only=True, required=False)
gcp_creds = GCPCredsSerializer(write_only=True, required=False)
result = serializers.CharField(read_only=True)
details = serializers.CharField(read_only=True)
def create(self, validated_data):
provider = view_helpers.get_cloud_provider(self.context.get('view'))
try:
provider.authenticate()
return {'result': 'SUCCESS'}
except Exception as e:
return {'result': 'FAILURE', 'details': str(e)}
class UserSerializer(UserDetailsSerializer):
credentials = CustomHyperlinkedIdentityField(
view_name='djcloudbridge:credentialsroute-list', lookup_field=None)
aws_creds = serializers.SerializerMethodField()
openstack_creds = serializers.SerializerMethodField()
azure_creds = serializers.SerializerMethodField()
gcp_creds = serializers.SerializerMethodField()
def get_aws_creds(self, obj):
"""
Include a URL for listing this bucket's contents
"""
try:
creds = obj.userprofile.credentials.filter(
awscredentials__isnull=False).select_subclasses()
return AWSCredsSerializer(instance=creds, many=True,
context=self.context).data
except models.UserProfile.DoesNotExist:
return ""
def get_openstack_creds(self, obj):
"""
Include a URL for listing this bucket's contents
"""
try:
creds = obj.userprofile.credentials.filter(
openstackcredentials__isnull=False).select_subclasses()
return OpenstackCredsSerializer(instance=creds, many=True,
context=self.context).data
except models.UserProfile.DoesNotExist:
return ""
def get_azure_creds(self, obj):
"""
Include a URL for listing this bucket's contents
"""
try:
creds = obj.userprofile.credentials.filter(
azurecredentials__isnull=False).select_subclasses()
return AzureCredsSerializer(instance=creds, many=True,
context=self.context).data
except models.UserProfile.DoesNotExist:
return ""
def get_gcp_creds(self, obj):
"""
Include a URL for listing this bucket's contents
"""
try:
creds = obj.userprofile.credentials.filter(
gcpcredentials__isnull=False).select_subclasses()
return GCPCredsSerializer(instance=creds, many=True,
context=self.context).data
except models.UserProfile.DoesNotExist:
return ""
class Meta(UserDetailsSerializer.Meta):
fields = UserDetailsSerializer.Meta.fields + \
('aws_creds', 'openstack_creds', 'azure_creds', 'gcp_creds',
'credentials')
| 38.6 | 79 | 0.65666 | 32,229 | 0.982292 | 0 | 0 | 0 | 0 | 0 | 0 | 5,286 | 0.161109 |
d52fc94190a48ed5868310e2aad92eeeb9feb60b | 866 | py | Python | what_apps/mooncalendar/admin.py | SlashRoot/WHAT | 69e78d01065142446234e77ea7c8c31e3482af29 | [
"MIT"
] | null | null | null | what_apps/mooncalendar/admin.py | SlashRoot/WHAT | 69e78d01065142446234e77ea7c8c31e3482af29 | [
"MIT"
] | null | null | null | what_apps/mooncalendar/admin.py | SlashRoot/WHAT | 69e78d01065142446234e77ea7c8c31e3482af29 | [
"MIT"
] | null | null | null | from what_apps.mooncalendar.models import Event
from what_apps.mooncalendar.models import Moon
from django.contrib import admin
class EventAdmin(admin.ModelAdmin):
list_display = 'name',
fieldsets = [
(None, {'fields': ['name']}),
('description', {'fields':['description']}),
('Date information', {'fields':['event_date']}),
]
class MoonAdmin(admin.ModelAdmin):
list_display = ('name', 'new', 'full', 'length_as_string' )
def length_as_string(self, obj):
return str(obj.length())
fieldsets = [
('name', {'fields':['name']}),
('new', {'fields':['new']}),
('waxing', {'fields':['waxing']}),
('full', {'fields':['full']}),
('waning', {'fields':['waning']}),
]
admin.site.register(Event, EventAdmin)
admin.site.register(Moon, MoonAdmin) | 30.928571 | 63 | 0.575058 | 646 | 0.745958 | 0 | 0 | 0 | 0 | 0 | 0 | 233 | 0.269053 |
d53250d431f3b7786477248a4bd086c3905e3d46 | 4,019 | py | Python | kvdbclient/bigtable/utils.py | seung-lab/KVDbClient | 4b82ded0c19b89cc9887ed60998583989a086506 | [
"MIT"
] | null | null | null | kvdbclient/bigtable/utils.py | seung-lab/KVDbClient | 4b82ded0c19b89cc9887ed60998583989a086506 | [
"MIT"
] | null | null | null | kvdbclient/bigtable/utils.py | seung-lab/KVDbClient | 4b82ded0c19b89cc9887ed60998583989a086506 | [
"MIT"
] | null | null | null | from typing import Dict
from typing import Union
from typing import Iterable
from typing import Optional
from datetime import datetime
from datetime import timedelta
import numpy as np
from google.cloud.bigtable.row_data import PartialRowData
from google.cloud.bigtable.row_filters import RowFilter
from . import attributes
def _from_key(family_id: str, key: bytes):
try:
return attributes.Attribute._attributes[(family_id, key)]
except KeyError:
# FIXME: Look if the key matches a columnarray pattern and
# remove loop initialization in _AttributeArray.__init__()
raise KeyError(f"Unknown key {family_id}:{key.decode()}")
def partial_row_data_to_column_dict(
partial_row_data: PartialRowData,
) -> Dict[attributes.Attribute, PartialRowData]:
new_column_dict = {}
for family_id, column_dict in partial_row_data._cells.items():
for column_key, column_values in column_dict.items():
try:
column = _from_key(family_id, column_key)
except KeyError:
continue
new_column_dict[column] = column_values
return new_column_dict
def _get_google_compatible_time_stamp(
time_stamp: datetime, round_up: bool = False
) -> datetime:
"""
Makes a datetime time stamp compatible with googles' services.
Google restricts the accuracy of time stamps to milliseconds. Hence, the
microseconds are cut of. By default, time stamps are rounded to the lower
number.
"""
micro_s_gap = timedelta(microseconds=time_stamp.microsecond % 1000)
if micro_s_gap == 0:
return time_stamp
if round_up:
time_stamp += timedelta(microseconds=1000) - micro_s_gap
else:
time_stamp -= micro_s_gap
return time_stamp
def _get_column_filter(
columns: Union[Iterable[attributes.Attribute], attributes.Attribute] = None
) -> RowFilter:
"""Generates a RowFilter that accepts the specified columns."""
from google.cloud.bigtable.row_filters import RowFilterUnion
from google.cloud.bigtable.row_filters import ColumnRangeFilter
if isinstance(columns, attributes.Attribute):
return ColumnRangeFilter(
columns.family_id, start_column=columns.key, end_column=columns.key
)
elif len(columns) == 1:
return ColumnRangeFilter(
columns[0].family_id, start_column=columns[0].key, end_column=columns[0].key
)
return RowFilterUnion(
[
ColumnRangeFilter(col.family_id, start_column=col.key, end_column=col.key)
for col in columns
]
)
def _get_time_range_filter(
start_time: Optional[datetime] = None,
end_time: Optional[datetime] = None,
end_inclusive: bool = True,
) -> RowFilter:
"""Generates a TimeStampRangeFilter which is inclusive for start and (optionally) end."""
from google.cloud.bigtable.row_filters import TimestampRange
from google.cloud.bigtable.row_filters import TimestampRangeFilter
# Comply to resolution of BigTables TimeRange
if start_time is not None:
start_time = _get_google_compatible_time_stamp(start_time, round_up=False)
if end_time is not None:
end_time = _get_google_compatible_time_stamp(end_time, round_up=end_inclusive)
return TimestampRangeFilter(TimestampRange(start=start_time, end=end_time))
def get_time_range_and_column_filter(
columns: Optional[
Union[Iterable[attributes.Attribute], attributes.Attribute]
] = None,
start_time: Optional[datetime] = None,
end_time: Optional[datetime] = None,
end_inclusive: bool = False,
) -> RowFilter:
from google.cloud.bigtable.row_filters import RowFilterChain
time_filter = _get_time_range_filter(
start_time=start_time, end_time=end_time, end_inclusive=end_inclusive
)
if columns is not None:
column_filter = _get_column_filter(columns)
return RowFilterChain([column_filter, time_filter])
else:
return time_filter
| 34.646552 | 93 | 0.718089 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 606 | 0.150784 |
d5341906de628d8bd34733d0c157d31c4b909dfe | 551 | py | Python | Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_LightSensor_cpx.py | joewalk102/Adafruit_Learning_System_Guides | 2bda607f8c433c661a2d9d40b4db4fd132334c9a | [
"MIT"
] | 665 | 2017-09-27T21:20:14.000Z | 2022-03-31T09:09:25.000Z | Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_LightSensor_cpx.py | joewalk102/Adafruit_Learning_System_Guides | 2bda607f8c433c661a2d9d40b4db4fd132334c9a | [
"MIT"
] | 641 | 2017-10-03T19:46:37.000Z | 2022-03-30T18:28:46.000Z | Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_LightSensor_cpx.py | joewalk102/Adafruit_Learning_System_Guides | 2bda607f8c433c661a2d9d40b4db4fd132334c9a | [
"MIT"
] | 734 | 2017-10-02T22:47:38.000Z | 2022-03-30T14:03:51.000Z | # CircuitPlaygroundExpress_LightSensor
# reads the on-board light sensor and graphs the brighness with NeoPixels
import time
from adafruit_circuitplayground.express import cpx
from simpleio import map_range
cpx.pixels.brightness = 0.05
while True:
# light value remaped to pixel position
peak = map_range(cpx.light, 10, 325, 0, 9)
print(cpx.light)
print(int(peak))
for i in range(0, 9, 1):
if i <= peak:
cpx.pixels[i] = (0, 255, 0)
else:
cpx.pixels[i] = (0, 0, 0)
time.sleep(0.01)
| 22.958333 | 73 | 0.653358 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 150 | 0.272232 |
d534b5964680d262bdbcff4ab014dca342de302c | 3,258 | py | Python | mpc.py | clovaai/subword-qac | df7a9a557a594712f757adccf86fdaf365bff601 | [
"MIT"
] | 65 | 2019-09-04T01:53:31.000Z | 2022-03-13T09:39:47.000Z | mpc.py | naver-ai/subword-qac | df7a9a557a594712f757adccf86fdaf365bff601 | [
"MIT"
] | 3 | 2020-10-09T14:24:54.000Z | 2021-08-24T06:23:09.000Z | mpc.py | naver-ai/subword-qac | df7a9a557a594712f757adccf86fdaf365bff601 | [
"MIT"
] | 13 | 2019-09-09T11:19:43.000Z | 2021-08-30T23:10:06.000Z | """
Copyright (c) 2019-present NAVER Corp.
MIT License
"""
import os
import sys
import json
import logging
import argparse
import pickle
from tqdm import tqdm
from dataset import read_data, PrefixDataset
from trie import Trie
from metric import calc_rank, calc_partial_rank, mrr_summary, mrl_summary
logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO)
logger = logging.getLogger(__name__)
def get_args():
parser = argparse.ArgumentParser(description="Most Popular Completion")
parser.add_argument('--data_dir', default="data/aol/full")
parser.add_argument('--min_len', type=int, default=3)
parser.add_argument('--min_prefix_len', type=int, default=2)
parser.add_argument('--min_suffix_len', type=int, default=1)
parser.add_argument('--n_candidates', type=int, default=10)
parser.add_argument('--min_freq', type=int, default=1)
parser.add_argument('--train', action='store_true')
parser.add_argument('--model_path', default="models/mpc/trie.pkl")
args = parser.parse_args()
return args
def main(args):
logger.info(f"Args: {json.dumps(args.__dict__, indent=2, sort_keys=True)}")
logger.info("Reading train dataset")
train_data = read_data(os.path.join(args.data_dir, f"train.query.txt"), min_len=args.min_len)
logger.info(f" Number of train data: {len(train_data):8d}")
seen_set = set(train_data)
if not args.train and os.path.isfile(args.model_path):
logger.info(f"Loading trie at {args.model_path}")
trie = pickle.load(open(args.model_path, 'rb'))
else:
logger.info("Making trie")
trie = Trie(train_data)
os.makedirs(os.path.dirname(args.model_path), exist_ok=True)
logger.info(f"Saving trie at {args.model_path}")
sys.setrecursionlimit(100000)
pickle.dump(trie, open(args.model_path, 'wb'))
logger.info("Reading test dataset")
test_data = read_data(os.path.join(args.data_dir, f"test.query.txt"), min_len=args.min_len)
logger.info(f" Number of test data: {len(test_data):8d}")
logger.info("Evaluating MPC")
test_dataset = PrefixDataset(test_data, args.min_prefix_len, args.min_suffix_len)
seens = []
ranks = []
pranks = []
rls = []
for query, prefix in tqdm(test_dataset):
seen = int(query in seen_set)
completions = trie.get_mpc(prefix, n_candidates=args.n_candidates, min_freq=args.min_freq)
rank = calc_rank(query, completions)
prank = calc_partial_rank(query, completions)
rl = [0 for _ in range(args.n_candidates + 1)]
if seen:
for i in range(1, len(query) + 1):
r = calc_rank(query, trie.get_mpc(query[:-i]))
if r == 0:
break
else:
for j in range(r, args.n_candidates + 1):
rl[j] += 1
seens.append(seen)
ranks.append(rank)
pranks.append(prank)
rls.append(rl)
mrr_logs = mrr_summary(ranks, pranks, seens, args.n_candidates)
mrl_logs = mrl_summary(rls, seens, args.n_candidates)
for log in mrr_logs + mrl_logs:
logger.info(log)
if __name__ == "__main__":
main(get_args())
| 33.244898 | 105 | 0.656845 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 641 | 0.196746 |
d534d824de326bc7eb62d09547d2ef9f6480689c | 813 | py | Python | old_source_code/Experiment 4 Extended Game Convergency/plotHistory.py | prasoonpatidar/multiagentRL-resource-sharing | e63ba7fc3c7ab019e9fd109cd45b739e3322152f | [
"MIT"
] | null | null | null | old_source_code/Experiment 4 Extended Game Convergency/plotHistory.py | prasoonpatidar/multiagentRL-resource-sharing | e63ba7fc3c7ab019e9fd109cd45b739e3322152f | [
"MIT"
] | null | null | null | old_source_code/Experiment 4 Extended Game Convergency/plotHistory.py | prasoonpatidar/multiagentRL-resource-sharing | e63ba7fc3c7ab019e9fd109cd45b739e3322152f | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 16 18:18:29 2020
@author: xuhuiying
"""
import numpy as np
import matplotlib.pyplot as plt
def plotHistory(history,times,xLabelText,yLabelText,legendText):#画出每个history plot each history
history = np.array(history) #history是二维数组 history is a 2D array
history = history.T
iteration = range(0,times)
# plt.figure()
for j in range(0,history.shape[0]):
plt.plot(iteration,history[j],label = "%s %d"%(legendText,j + 1))
# plt.legend(loc='upper left',prop = {'size': 10},handlelength = 1)
plt.xlabel(xLabelText,fontsize = 8)
plt.ylabel(yLabelText,fontsize = 8)
plt.tick_params(labelsize=8)
# plt.savefig('%sWith%dSellersAnd%dBuyer.jpg'%(fileNamePre,N,M), dpi=300,bbox_inches = 'tight')
# plt.show()
| 32.52 | 98 | 0.682657 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 398 | 0.478941 |
d535465b4cadf1f4ee90d4f52f137ea35dc5bc11 | 56 | py | Python | dominion/cards/__init__.py | billletson/dominion | ad430e20aa1615758091df1ca39a5fc7313e921e | [
"MIT"
] | null | null | null | dominion/cards/__init__.py | billletson/dominion | ad430e20aa1615758091df1ca39a5fc7313e921e | [
"MIT"
] | null | null | null | dominion/cards/__init__.py | billletson/dominion | ad430e20aa1615758091df1ca39a5fc7313e921e | [
"MIT"
] | null | null | null | from .constants import *
from .actions import ACTIONS
| 18.666667 | 29 | 0.767857 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
d535a3e83f35b85829a2417b8b9cf8c664d410a0 | 1,497 | py | Python | VMTranslator.py | Nismirno/n2tVMTranslator | 0274f5a51a5e3209e3536c1de5b4ff8b3824a116 | [
"MIT"
] | null | null | null | VMTranslator.py | Nismirno/n2tVMTranslator | 0274f5a51a5e3209e3536c1de5b4ff8b3824a116 | [
"MIT"
] | null | null | null | VMTranslator.py | Nismirno/n2tVMTranslator | 0274f5a51a5e3209e3536c1de5b4ff8b3824a116 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
from VMParser import Parser
from VMCodewriter import CodeWriter
from pathlib import Path
import sys
def processDirectory(inputPath):
fileName = str(inputPath.stem)
myWriter = CodeWriter(fileName)
lines = myWriter.initHeader()
for f in inputPath.glob("*.vm"):
lines += processFile(f)
return lines
def processFile(inputPath):
myParser = Parser(inputPath)
fileName = str(inputPath.stem)
parsedProg = [line for line in myParser.parse()]
myWriter = CodeWriter(fileName)
return myWriter.writeCode(parsedProg)
def main():
if (len(sys.argv) < 2):
print("Enter VM file name or directory")
print("Example:")
print("{0} path_to_file.vm".format(sys.argv[0]))
print("{0} path_to_dir".format(sys.argv[0]))
input("Press Enter to exit...")
inputPath = Path(sys.argv[1])
realPath = Path.resolve(inputPath)
isDir = realPath.is_dir()
if (isDir):
outName = str(realPath / realPath.name)
outFile = open("{0}.asm".format(outName), 'w')
output = processDirectory(realPath)
outFile.write('\n'.join(output))
elif (realPath.suffix == ".vm"):
outName = str(realPath.parent / realPath.stem)
outFile = open("{0}.asm".format(outName), 'w')
output = processFile(realPath)
outFile.write('\n'.join(output))
else:
print("Input file must be of .vm extension")
return None
if __name__ == "__main__":
main()
| 28.788462 | 56 | 0.637275 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 216 | 0.144289 |
d535db0b037e93b7fd2d6697df93c4c6ea03dea8 | 19,343 | py | Python | python/package/solution.py | pchtsp/ROADEF2018 | 442dfe919a41fa993155226b601625917e632577 | [
"MIT"
] | null | null | null | python/package/solution.py | pchtsp/ROADEF2018 | 442dfe919a41fa993155226b601625917e632577 | [
"MIT"
] | null | null | null | python/package/solution.py | pchtsp/ROADEF2018 | 442dfe919a41fa993155226b601625917e632577 | [
"MIT"
] | null | null | null | import package.data_input as di
import ete3
import math
import package.instance as inst
import package.params as pm
import numpy as np
import matplotlib
try:
import tkinter
except:
matplotlib.use('Qt5Agg', warn=False, force=True)
import matplotlib.pyplot as plt
import palettable as pal
import pprint as pp
import pandas as pd
import package.auxiliar as aux
import os
import package.superdict as sd
import package.tuplist as tl
import package.nodes as nd
import package.nodes_checks as nc
import package.geometry as geom
class Solution(inst.Instance):
def __init__(self, input_data, solution_data):
super().__init__(input_data)
# self.sol_data = solution_data
if len(solution_data) == 0:
self.trees = []
return
self.trees = []
defects = input_data['defects']
data_byPlate = solution_data.index_by_property('PLATE_ID', get_list=True)
for pos, plate in enumerate(data_byPlate):
tree = self.get_tree_from_solution_data(plate)
tree.add_feature('DEFECTS', defects.get(pos, []))
self.trees.append(tree)
self.order_all_children()
@staticmethod
def get_tree_from_solution_data(solution_data):
parent_child = [(int(v['PARENT']), int(k), 1) for k, v in solution_data.items()
if not math.isnan(v['PARENT'])]
for p, c, d in parent_child:
if p == c:
raise ValueError('parent cannot be the same node!')
if len(parent_child) == 0:
# this means we have a one-node tree:
name = [*solution_data.keys()][0]
tree = ete3.Tree(name=name)
else:
tree = ete3.Tree.from_parent_child_table(parent_child)
# add info about each node
for node in tree.traverse():
for k, v in solution_data[node.name].items():
if math.isnan(v):
node.add_feature(k, v)
else:
node.add_feature(k, int(v))
return tree
def draw(self, pos=0, *attributes):
node = self.trees[pos]
nd.draw(node, *attributes)
return
def draw_interactive(self, pos=0):
return self.trees[pos].show()
@staticmethod
def search_case_in_options(path):
try:
options = di.load_data(path + 'options.json')
except FileNotFoundError:
return None
else:
return options.get('case_name', None)
@classmethod
def from_io_files(cls, case_name=None, path=pm.PATHS['checker_data'], solutionfile="solution"):
if case_name is None:
case_name = cls.search_case_in_options(path)
if case_name is None:
raise ImportError('case_name is None and options.json is not available')
input_data = di.get_model_data(case_name, path)
solution = di.get_model_solution(case_name, path, filename=solutionfile)
return cls(input_data, solution)
@classmethod
def from_input_files(cls, case_name=None, path=pm.PATHS['data'], **kwargs):
if case_name is None:
case_name = cls.search_case_in_options(path)
if case_name is None:
raise ImportError('case_name is None and options.json is not available')
return cls(di.get_model_data(case_name, path), **kwargs)
def get_cuts(self):
# for each node, we get the cut that made it.
# there's always one of the children that has no cut
# each cut wll have as property the first and second piece
pass
def order_all_children(self):
for tree in self.trees:
nd.order_children(tree)
def get_pieces_by_type(self, solution, by_plate=False, pos=None, min_type=0):
"""
Gets the solution pieces indexed by the TYPE.
:param by_plate: when active it returns a dictionary indexed
by the plates. So it's {PLATE_0: {0: leaf0, 1: leaf1}, PLATE_1: {}}
:param pos: get an individual plate marked by pos
:param filter_type: if True: gets only demanded items. If not: returns all plates
:param solution: if given it's evaluated instead of self.trees
:return: {0: leaf0, 1: leaf1}
"""
if pos is None:
leaves = [leaf for tree in solution
for leaf in nd.get_node_leaves(tree, min_type)]
else:
leaves = [leaf for leaf in nd.get_node_leaves(solution[pos], min_type)]
if not by_plate:
return {int(leaf.TYPE): leaf for leaf in leaves}
leaves_by_plate = sd.SuperDict({tree.PLATE_ID: {} for tree in solution})
for leaf in leaves:
leaves_by_plate[leaf.PLATE_ID][int(leaf.TYPE)] = leaf
if pos is None:
return leaves_by_plate
return leaves_by_plate[pos]
def get_plate_production(self):
return [(leaf.WIDTH, leaf.HEIGHT) for tree in self.trees for leaf in tree.get_leaves()]
def count_errors(self):
checks = self.check_all()
return len([i for k, v in checks.items() for i in v])
def check_all(self):
func_list = {
'overlapping': self.check_overlapping
, 'sequence': self.check_sequence
, 'defects': self.check_defects
, 'demand': self.check_demand_satisfied
, 'ch_size': self.check_nodes_fit
, 'inside': self.check_parent_of_children
, 'cuts': self.check_cuts_number
, 'max_cut': self.check_max_cut
, 'position': self.check_nodes_inside_jumbo
, 'types': self.check_wrong_type
, 'ch_order': self.check_children_order
, 'node_size': self.check_sizes
, 'waste_size': self.check_waste_size
}
result = {k: v() for k, v in func_list.items()}
return {k: v for k, v in result.items() if len(v) > 0}
def check_consistency(self):
func_list = {
'ch_size': self.check_nodes_fit
, 'inside': self.check_parent_of_children
, 'cuts': self.check_cuts_number
, 'types': self.check_wrong_type
, 'ch_order': self.check_children_order
, 'node_size': self.check_sizes
, 'only_child': self.check_only_child
}
result = {k: v() for k, v in func_list.items()}
return {k: v for k, v in result.items() if len(v) > 0}
def check_only_child(self):
return [a for t in self.trees for a in nc.check_only_child(t)]
def check_overlapping(self):
solution = self.trees
plate_leaves = self.get_pieces_by_type(by_plate=True, solution=solution)
overlapped = []
for plate, leaves in plate_leaves.items():
for k1, leaf1 in leaves.items():
point1 = {'X': leaf1.X, 'Y': leaf1.Y}
point2 = {'X': leaf1.X + leaf1.WIDTH, 'Y': leaf1.Y + leaf1.HEIGHT}
for k2, leaf2 in leaves.items():
square = nd.node_to_square(leaf2)
if geom.point_in_square(point1, square) or \
geom.point_in_square(point2, square):
overlapped.append((leaf1, leaf2))
return overlapped
def get_previous_nodes(self, solution=None, type_node_dict=None):
"""
:param solution: forest: a list of trees.
:return:
"""
if type_node_dict is None or solution is not None:
if solution is None:
solution = self.trees
type_node_dict = self.get_pieces_by_type(solution=solution)
prev_items = self.get_previous_items()
prev_nodes = {}
for k, v in prev_items.items():
prev_nodes[type_node_dict[k]] = []
for i in v:
prev_nodes[type_node_dict[k]].append(type_node_dict[i])
return sd.SuperDict(prev_nodes)
def check_sequence(self, solution=None, type_node_dict=None):
wrong_order = []
n_prec = self.get_previous_nodes(solution=solution, type_node_dict=type_node_dict)
for node, prec_nodes in n_prec.items():
for prec_node in prec_nodes:
# prec is in a previous plate: correct
if node.PLATE_ID > prec_node.PLATE_ID:
continue
# if prec is in the next plate: very incorrect
if node.PLATE_ID < prec_node.PLATE_ID:
wrong_order.append((node, prec_node))
continue
# if we're here, they are in the same plate/ tree.
# we find the common ancestor and check which node's
# ancestors appear first
if nd.check_node_order(node, prec_node):
wrong_order.append((node, prec_node))
return tl.TupList(wrong_order)
def check_defects(self, solution=None):
"""
:return: [(node, defect), ()]
"""
node_defect = self.get_nodes_defects(solution)
return [(node, defect) for node, defect in node_defect if node.TYPE >= 0]
def get_nodes_defects(self, solution=None):
# A defect can be in more than one node/
if solution is None:
solution = self.trees
defect_node = []
defects_by_plate = self.get_defects_per_plate()
# if solution is None:
# a = 1
# pass
for tree in solution:
if tree.PLATE_ID not in defects_by_plate:
continue
for defect in defects_by_plate[tree.PLATE_ID]:
nodes = nd.search_nodes_of_defect(tree, defect)
assert nodes is not None, 'defect {} doesnt have node'.format(defect)
defect_node.extend((node, defect) for node in nodes)
return defect_node
def check_waste_size(self, solution=None):
min_waste = self.get_param('minWaste')
if solution is None:
solution = self.trees
bad_wastes = []
for tree in solution:
wastes = nd.get_node_leaves(tree, type_options=[-1, -3])
bad_wastes.extend([w for w in wastes if 0 < w.WIDTH < min_waste or 0 < w.HEIGHT < min_waste])
return bad_wastes
def check_space_usage(self, solution=None):
# if solution is None:
# solution = self.trees
return self.calculate_objective(solution, discard_empty_trees=True)
# return sum(self.calculate_residual_plate(tree)*(pos+1)**4 for pos, tree in enumerate(solution)) / \
# (self.get_param('widthPlates') * len(solution)**4)
# sum(nd.get_node_position_cost(n, self.get_param('widthPlates')) for tree in solution
# for n in nd.get_node_leaves(tree, type_options=[-1, -3])) / \
# ((self.get_param('widthPlates') * len(solution))**2 *self.get_param('widthPlates')*self.get_param('heightPlates'))
def calculate_residual_plate(self, node):
waste = nd.find_waste(node, child=True)
if waste is None:
return 0
return waste.WIDTH
def check_nodes_inside_jumbo(self):
w, h = self.get_param('widthPlates'), self.get_param('heightPlates')
plate_square = {'DL': {'X': 0, 'Y': 0}, 'UR': {'X': w, 'Y': h}}
bad_position = []
for tree in self.trees:
for node in tree.iter_leaves():
square = nd.node_to_square(node)
if geom.square_inside_square(square, plate_square, both_sides=False):
continue
bad_position.append(node)
return bad_position
def check_cuts_number(self):
"""
This checks if the CUT property of each node really corresponds with
the node's level.
:return:
"""
return [a for t in self.trees for a in nc.check_cuts_number(t)]
def check_max_cut(self):
"""
check that the maximum achieved level is 4
:return:
"""
levels = {}
for tree in self.trees:
levels.update(nd.assign_cut_numbers(tree, update=False))
return [(node, level) for node, level in levels.items() if level > 4 or\
(level == 4 and len(node.get_sisters()) > 1)]
def check_wrong_type(self):
return [a for t in self.trees for a in nc.check_wrong_type(t)]
def check_nodes_fit(self):
return [a for t in self.trees for a in nc.check_nodes_fit(t)]
def check_children_order(self):
# This checks that the order of the children
# follows the positions.
# meaining: if children A is before B
# it is lower or more to the left
return [a for t in self.trees for a in nc.check_children_order(t)]
def check_sizes(self):
return [a for t in self.trees for a in nc.check_sizes(t)]
def check_parent_of_children(self):
"""
We want to check if each node is inside its parent.
:return:
"""
return [a for t in self.trees for a in nc.check_parent_of_children(t)]
def check_demand_satisfied(self):
demand = self.get_batch()
produced = []
pieces = self.get_pieces_by_type(solution=self.trees)
for k, leaf in pieces.items():
item = demand.get(k, None)
# there's no demand for this item code
if item is None:
continue
plate1 = item['WIDTH_ITEM'], item['LENGTH_ITEM']
plate2 = leaf.WIDTH, leaf.HEIGHT
if geom.plate_inside_plate(plate1, plate2):
produced.append(k)
return np.setdiff1d([*demand], produced)
def calculate_objective(self, solution=None, discard_empty_trees=False):
if solution is None:
solution = self.trees
if not solution:
return None
height, width = self.get_param('heightPlates'), self.get_param('widthPlates')
items_area = self.get_items_area()
last_tree = len(solution) - 1
if discard_empty_trees:
while last_tree >= 0 and not len(nd.get_node_leaves(solution[last_tree])):
last_tree -= 1
last_tree_children = solution[last_tree].get_children()
last_waste_width = 0
if last_tree_children and nd.is_waste(last_tree_children[-1]):
last_waste_width = last_tree_children[-1].WIDTH
return (last_tree+1) * height * width - last_waste_width * height - items_area
def graph_solution(self, path="", name="rect", show=False, pos=None, dpi=50, fontsize=30, solution=None):
if solution is None:
solution = self.trees
batch_data = self.get_batch()
stack = batch_data.get_property('STACK')
sequence = batch_data.get_property('SEQUENCE')
colors = pal.colorbrewer.qualitative.Set3_5.hex_colors
width, height = self.get_param('widthPlates'), self.get_param('heightPlates')
pieces_by_type = self.get_pieces_by_type(by_plate=True, solution=solution)
if pos is not None:
pieces_by_type = pieces_by_type.filter([pos])
for plate, leafs in pieces_by_type.items():
fig1 = plt.figure(figsize=(width/100, height/100))
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.set_xlim([0, width])
ax1.set_ylim([0, height])
ax1.tick_params(axis='both', which='major', labelsize=50)
# graph items
for pos, leaf in enumerate(leafs.values()):
nc.draw_leaf(ax1, leaf, stack, sequence, colors, fontsize)
# graph wastes:
wastes = nd.get_node_leaves(solution[plate], type_options=[-1, -3])
for waste in wastes:
nc.draw_leaf(ax1, waste, stack, sequence, colors, fontsize)
# graph defects
for defect in self.get_defects_plate(plate):
nc.draw_defect(ax1, defect)
fig_path = os.path.join(path, '{}_{}.png'.format(name, plate))
fig1.savefig(fig_path, dpi=dpi, bbox_inches='tight')
if not show:
plt.close(fig1)
def correct_plate_node_ids(self, solution=None, features=None, edit_features=True):
if features is None:
features = nd.default_features()
if solution is None:
solution = self.trees
result = {}
order = 0
for pos, tree in enumerate(solution):
for v in tree.traverse("preorder"):
# rename the NODE_IDs and PLATE_ID
if edit_features:
v.add_features(PLATE_ID=pos, NODE_ID=order)
v.name = v.NODE_ID
# correct all wastes to -1 by default
if 'TYPE' in features:
if v.TYPE == -3:
v.TYPE = -1
d = nd.get_features(v, features)
v.add_features(PARENT=d['PARENT'])
result[int(v.NODE_ID)] = d
order += 1
if 'TYPE' in features and edit_features:
if result[order-1]['TYPE'] == -1 and result[order-1]['CUT'] == 1:
result[order - 1]['TYPE'] = -3
return result
def export_solution(self, path=pm.PATHS['results'] + aux.get_timestamp(), prefix='',
name='solution.csv', solution=None, correct_naming=True):
"""
When creating the output forest:
– The trees must be given in the correct sequence of plates, i.e. first
the nodes of plate 0, then nodes of plate 1....
– For each plate, the root (node with CUT=0) should be given first.
– The children of a node should be given from left to right (as repre-
sented on the cutting pattern).
– The nodes of trees should be given in depth first search.
– If the last 1-cut of the forest in the last cutting pattern is a waste, it
must be declared as a residual.
:param path:
:param prefix: usually the case.
:param name: name after prefix. Without extension.
:return:
"""
if solution is None:
solution = self.trees
if not os.path.exists(path):
os.mkdir(path)
result = self.correct_plate_node_ids(solution, edit_features=correct_naming)
table = pd.DataFrame.from_dict(result, orient='index')
col_order = ['PLATE_ID', 'NODE_ID', 'X', 'Y', 'WIDTH', 'HEIGHT', 'TYPE', 'CUT', 'PARENT']
table = table[col_order]
table.to_csv(path + '{}{}'.format(prefix, name), index=False, sep=';')
return True
def clean_last_trees(self, solution):
sol = solution[:]
while True:
if not nd.get_node_leaves(sol[-1]):
sol.pop()
else:
break
return sol
if __name__ == "__main__":
input_data = di.get_model_data('A0', path=pm.PATHS['checker_data'])
solution_data = di.get_model_solution('A0')
solution_data_byPlate = solution_data.index_by_property('PLATE_ID', get_list=True)
self = Solution(input_data, solution_data)
self.graph_solution()
self.draw()
# pp.pprint(self.sol_data)
# self.trees = []
# Useful functions:
# tree.search_nodes(name=0)[0]
# tree & 0
# help(tree)
# print(tree)
# tree.show()
| 39.964876 | 132 | 0.596133 | 18,313 | 0.946262 | 0 | 0 | 1,981 | 0.102361 | 0 | 0 | 3,955 | 0.204361 |
d535e635e6b66ba70c20fb56aebb09ef9c95a99d | 2,435 | py | Python | tests/engine/training/test_fingerprinting.py | fintzd/rasa | 6359be5509c7d87cd29c2ab5149bc45e843fea85 | [
"Apache-2.0"
] | 9,701 | 2019-04-16T15:46:27.000Z | 2022-03-31T11:52:18.000Z | tests/engine/training/test_fingerprinting.py | fintzd/rasa | 6359be5509c7d87cd29c2ab5149bc45e843fea85 | [
"Apache-2.0"
] | 6,420 | 2019-04-16T15:58:22.000Z | 2022-03-31T17:54:35.000Z | tests/engine/training/test_fingerprinting.py | fintzd/rasa | 6359be5509c7d87cd29c2ab5149bc45e843fea85 | [
"Apache-2.0"
] | 3,063 | 2019-04-16T15:23:52.000Z | 2022-03-31T00:01:12.000Z | import inspect
from unittest.mock import Mock
from _pytest.monkeypatch import MonkeyPatch
from rasa.core.policies.ted_policy import TEDPolicy
from rasa.engine.training import fingerprinting
from rasa.nlu.classifiers.diet_classifier import DIETClassifier
from rasa.nlu.selectors.response_selector import ResponseSelector
from tests.engine.training.test_components import FingerprintableText
def test_fingerprint_stays_same():
key1 = fingerprinting.calculate_fingerprint_key(
TEDPolicy, TEDPolicy.get_default_config(), {"input": FingerprintableText("Hi")},
)
key2 = fingerprinting.calculate_fingerprint_key(
TEDPolicy, TEDPolicy.get_default_config(), {"input": FingerprintableText("Hi")},
)
assert key1 == key2
def test_fingerprint_changes_due_to_class():
key1 = fingerprinting.calculate_fingerprint_key(
DIETClassifier,
TEDPolicy.get_default_config(),
{"input": FingerprintableText("Hi")},
)
key2 = fingerprinting.calculate_fingerprint_key(
ResponseSelector,
TEDPolicy.get_default_config(),
{"input": FingerprintableText("Hi")},
)
assert key1 != key2
def test_fingerprint_changes_due_to_config():
key1 = fingerprinting.calculate_fingerprint_key(
TEDPolicy, {}, {"input": FingerprintableText("Hi")},
)
key2 = fingerprinting.calculate_fingerprint_key(
ResponseSelector,
TEDPolicy.get_default_config(),
{"input": FingerprintableText("Hi")},
)
assert key1 != key2
def test_fingerprint_changes_due_to_inputs():
key1 = fingerprinting.calculate_fingerprint_key(
TEDPolicy, {}, {"input": FingerprintableText("Hi")},
)
key2 = fingerprinting.calculate_fingerprint_key(
ResponseSelector,
TEDPolicy.get_default_config(),
{"input": FingerprintableText("bye")},
)
assert key1 != key2
def test_fingerprint_changes_due_to_changed_source(monkeypatch: MonkeyPatch):
key1 = fingerprinting.calculate_fingerprint_key(
TEDPolicy, {}, {"input": FingerprintableText("Hi")},
)
get_source_mock = Mock(return_value="other implementation")
monkeypatch.setattr(inspect, inspect.getsource.__name__, get_source_mock)
key2 = fingerprinting.calculate_fingerprint_key(
TEDPolicy, {}, {"input": FingerprintableText("Hi")},
)
assert key1 != key2
get_source_mock.assert_called_once_with(TEDPolicy)
| 30.822785 | 88 | 0.725667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 133 | 0.05462 |
d535fc7f00accf0db8f763c0a2459c7d2e6f66c8 | 10,068 | py | Python | smarty/cli_smirky.py | openforcefield/smarty | 882d54b6d6d0fada748c71789964b07be2210a6a | [
"MIT"
] | 10 | 2018-03-29T15:31:50.000Z | 2022-02-17T14:04:37.000Z | smarty/cli_smirky.py | openforcefield/smarty | 882d54b6d6d0fada748c71789964b07be2210a6a | [
"MIT"
] | 14 | 2017-11-22T21:27:25.000Z | 2019-01-24T04:50:42.000Z | smarty/cli_smirky.py | openforcefield/smarty | 882d54b6d6d0fada748c71789964b07be2210a6a | [
"MIT"
] | 2 | 2019-03-05T22:52:26.000Z | 2022-02-17T14:05:06.000Z | """
Command-line driver example for SMIRKY.
"""
import sys
import string
import time
from optparse import OptionParser # For parsing of command line arguments
import smarty
from openforcefield.utils import utils
import os
import math
import copy
import re
import numpy
from numpy import random
def main():
# Create command-line argument options.
usage_string = """\
Sample over fragment types (atoms, bonds, angles, torsions, or impropers)
optionally attempting to match created types to an established SMIRFF.
For all files left blank, they will be taken from this module's
data/odds_files/ subdirectory.
usage %prog --molecules molfile --typetag fragmentType
[--atomORbases AtomORbaseFile --atomORdecors AtomORdecorFile
--atomANDdecors AtomANDdecorFile --bondORbase BondORbaseFile
--bondANDdecors BondANDdecorFile --atomIndexOdds AtomIndexFile
--bondIndexOdds BondIndexFile --replacements substitutions
--initialtypes initialFragmentsFile --SMIRFF referenceSMIRFF
--temperature float --verbose verbose
--iterations iterations --output outputFile]
example:
smirky --molecules AlkEthOH_test_filt1_ff.mol2 --typetag Angle
"""
version_string = "%prog %__version__"
parser = OptionParser(usage=usage_string, version=version_string)
parser.add_option("-m", "--molecules", metavar='MOLECULES',
action="store", type="string", dest='molecules_filename', default=None,
help="Small molecule set (in any OpenEye compatible file format) containing 'dG(exp)' fields with experimental hydration free energies. This filename can also be an option in this module's data/molecules sub-directory")
#TODO: ask about the the dG(exp) fields?
parser.add_option("-T", "--typetag", metavar='TYPETAG',
action = "store", type="choice", dest='typetag',
default=None, choices = ['VdW', 'Bond', 'Angle', 'Torsion', 'Improper'],
help="type of fragment being sampled, options are 'VdW', 'Bond', 'Angle', 'Torsion', 'Improper'")
parser.add_option('-e', '--atomORbases', metavar="DECORATORS",
action='store', type='string', dest='atom_OR_bases',
default = 'odds_files/atom_OR_bases.smarts',
help="Filename defining atom OR bases and associated probabilities. These are combined with atom OR decorators in SMIRKS, for example in '[#6X4,#7X3;R2:2]' '#6' and '#7' are atom OR bases. (OPTIONAL)")
parser.add_option("-O", "--atomORdecors", metavar="DECORATORS",
action='store', type='string', dest='atom_OR_decorators',
default = 'odds_files/atom_decorators.smarts',
help="Filename defining atom OR decorators and associated probabilities. These are combined with atom bases in SMIRKS, for example in '[#6X4,#7X3;R2:2]' 'X4' and 'X3' are ORdecorators. (OPTIONAL)")
parser.add_option('-A', '--atomANDdecors', metavar="DECORATORS",
action='store', type='string', dest='atom_AND_decorators',
default='odds_files/atom_decorators.smarts',
help="Filename defining atom AND decorators and associated probabilities. These are added to the end of an atom's SMIRKS, for example in '[#6X4,#7X3;R2:2]' 'R2' is an AND decorator. (OPTIONAL)")
parser.add_option('-o', '--bondORbase', metavar="DECORATORS",
action='store', type='string', dest='bond_OR_bases',
default='odds_files/bond_OR_bases.smarts',
help="Filename defining bond OR bases and their associated probabilities. These are OR'd together to describe a bond, for example in '[#6]-,=;@[#6]' '-' and '=' are OR bases. (OPTIONAL)")
parser.add_option('-a', '--bondANDdecors', metavar="DECORATORS",
action="store", type='string', dest='bond_AND_decorators',
default='odds_files/bond_AND_decorators.smarts',
help="Filename defining bond AND decorators and their associated probabilities. These are AND'd to the end of a bond, for example in '[#6]-,=;@[#7]' '@' is an AND decorator.(OPTIONAL)")
parser.add_option('-D', '--atomOddsFile', metavar="ODDSFILE",
action="store", type="string", dest="atom_odds",
default='odds_files/atom_index_odds.smarts',
help="Filename defining atom descriptors and probabilities with making changes to that kind of atom. Options for descriptors are integers corresponding to that indexed atom, 'Indexed', 'Unindexed', 'Alpha', 'Beta', 'All'. (OPTIONAL)")
parser.add_option('-d', '--bondOddsFile', metavar="ODDSFILE",
action="store", type="string", dest="bond_odds",
default='odds_files/bond_index_odds.smarts',
help="Filename defining bond descriptors and probabilities with making changes to that kind of bond. Options for descriptors are integers corresponding to that indexed bond, 'Indexed', 'Unindexed', 'Alpha', 'Beta', 'All'. (OPTIONAL)")
parser.add_option("-s", "--substitutions", metavar="SUBSTITUTIONS",
action="store", type="string", dest='substitutions_filename',
default=None,
help="Filename defining substitution definitions for SMARTS atom matches. (OPTIONAL).")
parser.add_option("-f", "--initialtypes", metavar='INITIALTYPES',
action="store", type="string", dest='initialtypes_filename',
default=None,
help="Filename defining initial fragment types. The file is formatted with two columns: 'SMIRKS typename'. For the default the initial type will be a generic form of the given fragment, for example '[*:1]~[*:2]' for a bond (OPTIONAL)")
parser.add_option('-r', '--smirff', metavar='REFERENCE',
action='store', type='string', dest='SMIRFF',
default=None,
help="Filename defining a SMIRFF force fielce used to determine reference fragment types in provided set of molecules. It may be an absolute file path, a path relative to the current working directory, or a path relative to this module's data subdirectory (for built in force fields). (OPTIONAL)")
parser.add_option("-i", "--iterations", metavar='ITERATIONS',
action="store", type="int", dest='iterations',
default=150,
help="MCMC iterations.")
parser.add_option("-t", "--temperature", metavar='TEMPERATURE',
action="store", type="float", dest='temperature',
default=0.1,
help="Effective temperature for Monte Carlo acceptance, indicating fractional tolerance of mismatched atoms (default: 0.1). If 0 is specified, will behave in a greedy manner.")
parser.add_option("-p", "--output", metavar='OUTPUT',
action="store", type="string", dest='outputfile',
default=None,
help="Filename base for output information. This same base will be used for all output files created. If None provided then it is set to 'typetag_temperature' (OPTIONAL).")
parser.add_option('-v', '--verbose', metavar='VERBOSE',
action='store', type='choice', dest='verbose',
default=False, choices = ['True', 'False'],
help="If True prints minimal information to the commandline during iterations. (OPTIONAL)")
# Parse command-line arguments.
(option,args) = parser.parse_args()
# Molecules are required
if option.molecules_filename is None:
parser.print_help()
parser.error("Molecules input files must be specified.")
verbose = option.verbose == 'True'
# Load and type all molecules in the specified dataset.
molecules = utils.read_molecules(option.molecules_filename, verbose=verbose)
# Parse input odds files
atom_OR_bases = smarty.parse_odds_file(option.atom_OR_bases, verbose)
atom_OR_decorators = smarty.parse_odds_file(option.atom_OR_decorators, verbose)
atom_AND_decorators = smarty.parse_odds_file(option.atom_AND_decorators, verbose)
bond_OR_bases = smarty.parse_odds_file(option.bond_OR_bases, verbose)
bond_AND_decorators = smarty.parse_odds_file(option.bond_AND_decorators, verbose)
atom_odds = smarty.parse_odds_file(option.atom_odds, verbose)
bond_odds = smarty.parse_odds_file(option.bond_odds, verbose)
# get initial types if provided, otherwise none
if option.initialtypes_filename is None:
initialtypes = None
else:
initialtypes = smarty.AtomTyper.read_typelist(option.initialtypes_filename)
output = option.outputfile
if output is None:
output = "%s_%.2e" % ( option.typetag, option.temperature)
# get replacements
if option.substitutions_filename is None:
sub_file = smarty.get_data_filename('odds_files/substitutions.smarts')
else:
sub_file = option.substitutions_filename
replacements = smarty.AtomTyper.read_typelist(sub_file)
replacements = [ (short, smarts) for (smarts, short) in replacements]
start_sampler = time.time()
fragment_sampler = smarty.FragmentSampler(
molecules, option.typetag, atom_OR_bases, atom_OR_decorators,
atom_AND_decorators, bond_OR_bases, bond_AND_decorators,
atom_odds, bond_odds, replacements, initialtypes,
option.SMIRFF, option.temperature, output)
# report time
finish_sampler = time.time()
elapsed = finish_sampler - start_sampler
if verbose: print("Creating %s sampler took %.3f s" % (option.typetag, elapsed))
# Make iterations
frac_found = fragment_sampler.run(option.iterations, verbose)
results = fragment_sampler.write_results_smarts_file()
finished = time.time()
elapsed = finished - finish_sampler
per_it = elapsed / float(option.iterations)
if verbose: print("%i iterations took %.3f s (%.3f s / iteration)" % (option.iterations, elapsed, per_it))
if verbose: print("Final score was %.3f %%" % (frac_found*100.0))
# plot results
plot_file = "%s.pdf" % output
traj = "%s.csv" % output
smarty.score_utils.create_plot_file(traj, plot_file, False, verbose)
| 53.839572 | 309 | 0.689114 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5,509 | 0.547179 |
d53653c57078f22dc6820daf96fa072146e66f13 | 100 | py | Python | zim/plugins/zimclip/tests/__init__.py | stiles69/bin | a327326ae22933e44c7ee2268f973dcedf7c8b3c | [
"MIT"
] | null | null | null | zim/plugins/zimclip/tests/__init__.py | stiles69/bin | a327326ae22933e44c7ee2268f973dcedf7c8b3c | [
"MIT"
] | null | null | null | zim/plugins/zimclip/tests/__init__.py | stiles69/bin | a327326ae22933e44c7ee2268f973dcedf7c8b3c | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import logging
import os
import sys
import unittest
# FIXME Do some tests
| 11.111111 | 23 | 0.7 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 44 | 0.44 |
d536849becbcd8fd7d2759bd7a26ed03c8235dce | 9,800 | py | Python | fastai/classifyAllSnippets.py | jtbr/tv-news-quality | 0aa57a67ff3f3207e5cdf4129d58ea967e698e90 | [
"MIT"
] | null | null | null | fastai/classifyAllSnippets.py | jtbr/tv-news-quality | 0aa57a67ff3f3207e5cdf4129d58ea967e698e90 | [
"MIT"
] | null | null | null | fastai/classifyAllSnippets.py | jtbr/tv-news-quality | 0aa57a67ff3f3207e5cdf4129d58ea967e698e90 | [
"MIT"
] | null | null | null | from collections import defaultdict, deque
from datetime import datetime
import pandas as pd
import random
import numpy as np
import sys
sys.path.append("..") # Adds higher directory to python modules path.
from common import Label_DbFields, Synthetic_Category_Group_Names, Other_Synthetic_Group_Names, MultiLabel_Group_Name, Labels, Stations
random.seed(42)
from fastai.text import *
bs = 256 #224 # size of minibatch
# written with fastai v1.0.48
classifiers_to_run = ['label_category', 'label_usforeign', 'factinvestigative', 'label_tone', 'label_emotion']
# this contains the labels for each classifier
label_set = Labels.copy()
label_set['factinvestigative'] = ['investigative', 'noninvestigative', 'opinion', 'other']
# contains the labels for which a classifier is relevant
relevant_col_names = {}
relevant_col_names['factinvestigative'] = ['elections_hard', 'elections_soft', 'business_economics', 'government', 'current_events', 'cultural']
relevant_col_names['label_usforeign'] = ['business_economics', 'government', 'current_events', 'sports', 'cultural']
relevant_col_names['label_tone'] = ['elections_hard', 'elections_soft', 'business_economics', 'science_tech', 'government', 'entertainment', 'sports', 'products', 'anecdotes', 'current_events', 'cultural']
relevant_col_names['label_emotion'] = ['elections_hard', 'elections_soft', 'business_economics', 'science_tech', 'government', 'entertainment', 'anecdotes', 'current_events', 'cultural']
def getIndices(names, nameMap):
return tensor(sorted([nameMap.index(name) for name in names]))
modeldir = '/data/fastai-models/selected' # the second best auto-trained model among folds
# write headers for each output file
# (only needed the first time we run, in case this gets aborted midway)
for clas_name in classifiers_to_run:
with open(clas_name + '_stats.csv', 'w') as stats_f:
header = ["quarter_begin_date"]
for station in ['overall'] + Stations:
header += [station+'-'+label for label in (['total'] + label_set[clas_name])]
# if clas_name in ['label_category', 'station']:
for station in ['overall'] + Stations:
header += [station+'-'+cn+'-top_k' for cn in (['sum'] + label_set[clas_name])]
stats_f.write(",".join(header) + "\n")
dataset_rows = {}
quarters = []
for year in range(2010,2017):
for month in ["01", "04", "07", "10"]:
quarter = str(year) + '-' + month + "-01"
quarters += [quarter]
for quarter in quarters:
print('\n\n', str(datetime.now()), 'Reading in snippets for', quarter)
# read in full population of (truecased, preprocessed) snippets for this quarter
df = pd.read_csv('/data/' + quarter + '_snippets.tsv', sep='\t')
dataset_rows = {} # what rows are relevant for a particular classifier (apart from label_category)
for clas_name in classifiers_to_run:
print('Processing', clas_name)
# take subset of rows that are relevant for this classifier; both from the dataset and the original dataframe
if clas_name == 'label_category':
train_df = df
else:
train_df = df.iloc[dataset_rows[clas_name],:]
print(' - loading databunch of size', len(train_df))
learn = load_learner(modeldir, fname=clas_name + '_clas_fine_tuned.pkl',
test= TextList.from_df(train_df, cols='snippet'))
# if clas_name == 'label_category':
# learn = load_learner(modeldir, fname=clas_name + '_clas_fine_tuned.pkl',
# test= TextList.from_df(train_df, cols='snippet'))
# learn.data.save('quarter_temp_data') # need to save rather than leave in memory
# df = df.drop('snippet', axis=1) # remove no-longer-needed column to save memory
# train_df = train_df.drop('snippet', axis=1)
# else:
# learn = load_learner(modeldir, fname=clas_name + '_clas_fine_tuned.pkl')
# loaded_data = load_data(modeldir, 'quarter_temp_data', bs=bs)
# learn.data.test_dl = loaded_data.test_dl
# loaded_data.test_dl = None; loaded_data = None
# learn.data.test_ds.x.filter_subset(dataset_rows[clas_name])
# learn.data.test_ds.y.filter_subset(dataset_rows[clas_name])
# del dataset_rows[clas_name]
# gc.collect()
print(' - running classifier')
preds, _ = learn.get_preds(ds_type=DatasetType.Test, ordered=True) # second return value would be true label (if this weren't a test set)
print(' - analyzing and saving results')
yhat = np.argmax(preds.numpy(), axis=1)
labelcounts = [defaultdict(int) for s in ['overall'] + Stations]
for i, station in enumerate(Stations):
station_yhat = yhat[train_df['station'] == station]
for label in station_yhat:
labelcounts[i+1][label] += 1 # leave index 0 for the overall counts to calculate next
print(" ", preds[:5])
# print(labelcounts[0])
# add 'overall' counts:
for label_idx, _ in enumerate(learn.data.train_ds.classes):
labelcounts[0][label_idx] = sum([labelcounts[i+1][label_idx] for i, __ in enumerate(Stations)])
# translate from NN class index into class name, and make a full list of counts
all_counts_ordered = []
for i, station in enumerate(['overall'] + Stations):
namedlabelcounts = defaultdict(int)
total = 0
for k,v in labelcounts[i].items():
namedlabelcounts[learn.data.train_ds.classes[k]] = v
total += v
print(" ", station, namedlabelcounts)
# label counts in order
counts_ordered = [str(total)] + [("0" if total == 0 else str(float(namedlabelcounts[cn])/total)) for cn in label_set[clas_name]]
all_counts_ordered += counts_ordered
all_summed_likelihoods_ordered = []
# if clas_name in ['label_category', 'station']:
# tbd: how to handle binary classifiers: ads, transitions, nonsense, investigative (currently not being run)
# calculate categories using top-k precision
k = 3 if clas_name in ['label_category', 'station', 'supergroups'] else 2
likelihoods, posns = preds.topk(k, dim=-1, sorted=False)
# scale predictions so that top 3 likelihoods sum to 1
norm_factors = 1. / likelihoods.sum(dim=-1)
likelihoods = norm_factors * likelihoods.transpose(-1,0)
likelihoods.transpose_(-1,0)
overalllabelsums = defaultdict(float)
overall_sum = 0.0
for station in Stations:
# allocate their normalized likelihoods to the 3 categories for each snippet
likelihoods_sums = defaultdict(float)
station_row_idxs = tensor((train_df['station'] == station).to_numpy().nonzero()[0])
station_likelihood_rows = likelihoods.index_select(0, station_row_idxs)
station_posns_rows = posns.index_select(0, station_row_idxs)
for (snippet_lhs, snippet_posns) in zip(station_likelihood_rows, station_posns_rows): #python 3: zip is an iterator (py2 use itertools.izip)
for lh, posn in zip(snippet_lhs.tolist(), snippet_posns.tolist()):
likelihoods_sums[posn] += lh
# order the likelihoods for reporting, and sum up overall totals
namedlabelsums = defaultdict(float)
for k,v in likelihoods_sums.items():
namedlabelsums[learn.data.train_ds.classes[k]] = v
overalllabelsums[learn.data.train_ds.classes[k]] += v
station_sum = sum([namedlabelsums[cn] for cn in label_set[clas_name]])
overall_sum += station_sum
summed_likelihoods_ordered = [("0.0" if station_sum == 0. else str(namedlabelsums[cn]/station_sum)) for cn in label_set[clas_name]]
all_summed_likelihoods_ordered += [str(station_sum)] + summed_likelihoods_ordered
# prepend the overall total likelihoods (in order) before the station totals
overall_summed_likelihoods_ordered = [str(overall_sum)] + [str(overalllabelsums[cn]/overall_sum) for cn in label_set[clas_name]]
all_summed_likelihoods_ordered = overall_summed_likelihoods_ordered + all_summed_likelihoods_ordered
# append one line with counts for this learner in this quarter
with open(clas_name + '_stats.csv', 'a') as stats_f:
stats_f.write(",".join([quarter] + all_counts_ordered + all_summed_likelihoods_ordered) + "\n")
# if this is the first classifier (label_category), save the subsets of df for other classifiers to run on
if clas_name == 'label_category':
# get the column indices in this learner for the classes for which subsequent classifiers are relevant
relevant_col_idxes = {}
for clas, col_list in relevant_col_names.items():
relevant_col_idxes[clas] = getIndices(col_list, learn.data.train_ds.classes)
# save rows to be classified for the remaining classifiers
for clas, cols in relevant_col_idxes.items():
relevant_scores = preds.index_select(1, cols)
# indexes of rows (snippets) positive for relevant cols (having >0.5 probability among relevant scores)
dataset_rows[clas] = (relevant_scores.sum(dim=-1) > 0.5).nonzero().squeeze(1).numpy()
del relevant_col_idxes; del relevant_scores
del learn; del yhat; del preds; del likelihoods; del station_likelihood_rows; del posns; del _
gc.collect()
#torch.cuda.empty_cache()
| 52.12766 | 205 | 0.655612 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4,013 | 0.40949 |
d536b7482bc290966d04a1055fdea35f0784a032 | 3,385 | py | Python | LDDMM_Python/lddmm_python/modules/io/anim3D.py | tt6746690/lddmm-ot | 98e45d44969221b0fc8206560d9b7a655ef7e137 | [
"MIT"
] | 48 | 2017-08-04T03:30:22.000Z | 2022-03-09T03:24:11.000Z | LDDMM_Python/lddmm_python/modules/io/anim3D.py | hushunbo/lddmm-ot | 5af26fe32ae440c598ed403ce2876e98d6e1c692 | [
"MIT"
] | null | null | null | LDDMM_Python/lddmm_python/modules/io/anim3D.py | hushunbo/lddmm-ot | 5af26fe32ae440c598ed403ce2876e98d6e1c692 | [
"MIT"
] | 15 | 2017-09-30T18:55:48.000Z | 2021-04-27T18:27:55.000Z | # We use a slightly hacked version of the plot.ly js/python library
lddmm_python = __import__(__name__.split('.')[0])
print(lddmm_python)
import lddmm_python.lib.plotly as plotly
import re
from pylab import *
from IPython.html.widgets import interact
from IPython.display import HTML, display
from pprint import pprint
import json
from plotly.tools import FigureFactory as FF
from plotly import utils, graph_objs
from .my_iplot import my_iplot
from .read_vtk import ReadVTK
class Anim3d :
def __init__(self, filenames):
self.frames = list(ReadVTK(f) for f in filenames)
self.current_frame = list(range(len(self.frames)))
print(self.current_frame)
def get_frame(self, w) :
points = array(self.frames[w][0])
"""update = dict(
x = [points[:,2]],
y = [points[:,0]],
z = [points[:,1]]
)"""
update1 = dict(
visible = False
)
update2 = dict(
visible = True
)
list1 = str(self.current_frame)
self.current_frame = [w]
list2 = str(self.current_frame)
return ([update1, update2], [list1, list2])
def show(self, title):
figs = []
for ind_f in range(len(self.frames)) :
(points, triangles, signals) = self.frames[ind_f]
points = array(points)
triangles = array(triangles)
signals = array(signals)
signals_per_triangle = list( (signals[triangles[i,0]] + signals[triangles[i,1]] + signals[triangles[i,2]]) / 3
for i in range(triangles.shape[0]) )
signals_per_triangle[0] += 0.001
# Validate colormap
my_colormap = FF._validate_colors("Portland", 'tuple')
newdata = FF._trisurf(x=points[:,2], y=points[:,0], z=points[:,1],
colormap=my_colormap,
simplices=triangles,
color_func = signals_per_triangle,
plot_edges=False,
edges_color = 'rgb(50, 50, 50)',
show_colorbar = False,
data_list = True)
figs += newdata
axis = dict(
showbackground=True,
backgroundcolor='rgb(230, 230, 230)',
gridcolor='rgb(255, 255, 255)',
zerolinecolor='rgb(255, 255, 255)'
)
xaxis = axis.copy()
xaxis['range'] = [-0.08,0.09]
yaxis = axis.copy()
yaxis['range'] = [-0.11,0.05]
zaxis = axis.copy()
zaxis['range'] = [0.02,0.18]
aspectratio=dict(x=1, y=1, z=1)
layout = graph_objs.Layout(
title=title,
width='100%',
height= 800,
scene=graph_objs.Scene(
xaxis=graph_objs.XAxis(xaxis),
yaxis=graph_objs.YAxis(yaxis),
zaxis=graph_objs.ZAxis(zaxis),
aspectratio=dict(
x=aspectratio['x'],
y=aspectratio['y'],
z=aspectratio['z']),
)
)
return my_iplot(graph_objs.Figure( data = figs, layout=layout))
def slider(self, div_id) :
#div_id = self.show(*args, **kwargs)
def change_frame(w) :
(updates, indices) = self.get_frame(w-1)
script = ''
for i in range(len(updates)) :
jupdate = json.dumps(updates[i], cls=utils.PlotlyJSONEncoder)
#pprint(jupdate)
script = script \
+ 'Plotly.restyle("{id}", {update}, [{index}]);'.format(
id=div_id,
update=jupdate, index = indices[i][1:-1])
#print(script)
update_str = (
''
'<script type="text/javascript">' +
'window.PLOTLYENV=window.PLOTLYENV || {{}};'
'window.PLOTLYENV.BASE_URL="' + 'https://plot.ly' + '";'
'{script}' +
'</script>'
'').format(script=script)
display(HTML(update_str))
interact((lambda frame : change_frame(frame)), frame=(1,len(self.frames)))
| 28.686441 | 113 | 0.644313 | 2,898 | 0.85613 | 0 | 0 | 0 | 0 | 0 | 0 | 575 | 0.169867 |
d537bbba3a9ba3ab580ea135450c563c974dfe24 | 3,180 | py | Python | driftbase/api/users.py | directivegames/drift-base | 5fc7d4686c56e93fc22178f3b1bb49239d7eee45 | [
"MIT"
] | 1 | 2021-09-04T01:45:44.000Z | 2021-09-04T01:45:44.000Z | driftbase/api/users.py | directivegames/drift-base | 5fc7d4686c56e93fc22178f3b1bb49239d7eee45 | [
"MIT"
] | 30 | 2020-12-09T04:10:26.000Z | 2022-03-02T02:34:49.000Z | driftbase/api/users.py | directivegames/drift-base | 5fc7d4686c56e93fc22178f3b1bb49239d7eee45 | [
"MIT"
] | null | null | null | import logging
import http.client as http_client
from flask import url_for, g
from flask.views import MethodView
import marshmallow as ma
from flask_smorest import Blueprint, abort
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
from drift.core.extensions.urlregistry import Endpoints
from driftbase.models.db import User, CorePlayer, UserIdentity
log = logging.getLogger(__name__)
endpoints = Endpoints()
bp = Blueprint('users', __name__, url_prefix='/users', description='User management')
class UserPlayerSchema(SQLAlchemyAutoSchema):
class Meta:
load_instance = True
include_relationships = True
model = CorePlayer
exclude = ('num_logons', )
strict = True
player_url = ma.fields.Str(metadata=dict(description="Hello"))
class UserIdentitySchema(SQLAlchemyAutoSchema):
class Meta:
load_instance = True
include_relationships = True
model = UserIdentity
strict = True
class UserSchema(SQLAlchemyAutoSchema):
class Meta:
load_instance = True
include_relationships = True
model = User
strict = True
user_url = ma.fields.Str(metadata=dict(description="Hello"))
client_url = ma.fields.Str()
user_url = ma.fields.Str()
players = ma.fields.List(ma.fields.Nested(UserPlayerSchema))
class UserRequestSchema(ma.Schema):
class Meta:
strict = True
ordered = True
def drift_init_extension(app, api, **kwargs):
endpoints.init_app(app)
api.register_blueprint(bp)
#@bp.route('', endpoint='users')
@bp.route('', endpoint='list')
class UsersListAPI(MethodView):
@bp.response(http_client.OK, UserSchema(many=True))
def get(self):
"""List Users
Return users, just the most recent 10 records with no paging or anything I'm afraid.
"""
ret = []
users = g.db.query(User).order_by(-User.user_id).limit(10)
for row in users:
user = {
"user_id": row.user_id,
"user_url": url_for('users.entry', user_id=row.user_id, _external=True)
}
ret.append(user)
return ret
#@bp.route('/<int:user_id>', endpoint='user')
@bp.route('/<int:user_id>', endpoint='entry')
class UsersAPI(MethodView):
"""
"""
@bp.response(http_client.OK, UserSchema(many=False))
def get(self, user_id):
"""Single user
Return a user by ID
"""
user = g.db.query(User).filter(User.user_id == user_id).first()
if not user:
abort(http_client.NOT_FOUND)
data = user.as_dict()
data["client_url"] = None
players = g.db.query(CorePlayer).filter(CorePlayer.user_id == user_id)
data["players"] = players
identities = g.db.query(UserIdentity).filter(UserIdentity.user_id == user_id)
data["identities"] = identities
return data
@endpoints.register
def endpoint_info(current_user):
ret = {"users": url_for("users.list", _external=True), }
ret["my_user"] = None
if current_user:
ret["my_user"] = url_for("users.entry", user_id=current_user["user_id"], _external=True)
return ret
| 27.894737 | 96 | 0.654403 | 2,119 | 0.666352 | 0 | 0 | 1,556 | 0.489308 | 0 | 0 | 476 | 0.149686 |
d539894b90e242423be7b5a80d8dab14133e7cdc | 1,342 | py | Python | xlsx2x.py | KhanShaheb34/xlsx2pdf | 2ed6c687ac1ae664fb0599c8b9138a3bdc0cd828 | [
"MIT"
] | null | null | null | xlsx2x.py | KhanShaheb34/xlsx2pdf | 2ed6c687ac1ae664fb0599c8b9138a3bdc0cd828 | [
"MIT"
] | null | null | null | xlsx2x.py | KhanShaheb34/xlsx2pdf | 2ed6c687ac1ae664fb0599c8b9138a3bdc0cd828 | [
"MIT"
] | null | null | null | import os
import cv2
import jpype
import shutil
import weasyprint
from bs4 import BeautifulSoup
jpype.startJVM()
from asposecells.api import *
def generatePDF(XLSXPath, OutPath):
workbook = Workbook(XLSXPath)
workbook.save(f"sheet.html", SaveFormat.HTML)
with open(f'./sheet_files/sheet001.htm') as f:
htmlDoc = f.read()
soup = BeautifulSoup(htmlDoc, 'html.parser')
table = soup.find_all('table')[0]
with open(f'./sheet_files/stylesheet.css') as f:
styles = f.read()
with open(f'out.html', 'w') as f:
f.write(f'''
<style>
{styles}
@page {{size: A4; margin:0;}}
table {{margin:auto; margin-top: 5mm;}}
table, tr, td {{border: 1px solid #000 !important;}}
</style>
''')
f.write(str(table.prettify()))
weasyprint.HTML('out.html').write_pdf(OutPath)
def cleanPDF(OutPath):
shutil.rmtree('./sheet_files')
os.remove('./out.html')
os.remove('./sheet.html')
os.remove(OutPath)
def generatePNG(XLSXPath, OutPath):
workbook = Workbook(XLSXPath)
workbook.save(f"sheet.png", SaveFormat.PNG)
img = cv2.imread("sheet.png")
cropped = img[20:-100]
cv2.imwrite(OutPath, cropped)
def cleanPNG(OutPath):
os.remove('./sheet.png')
os.remove(OutPath) | 25.807692 | 68 | 0.612519 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 447 | 0.333085 |
d53a3a12bcf8b7a3bf6b3520d6ff05036c95f9f7 | 6,912 | py | Python | test/test_one.py | hellhound/pyejdb | cdb8285eef5417cd1fcaf84ecdfa2f2cb0fa6a18 | [
"Python-2.0",
"OLDAP-2.3"
] | null | null | null | test/test_one.py | hellhound/pyejdb | cdb8285eef5417cd1fcaf84ecdfa2f2cb0fa6a18 | [
"Python-2.0",
"OLDAP-2.3"
] | null | null | null | test/test_one.py | hellhound/pyejdb | cdb8285eef5417cd1fcaf84ecdfa2f2cb0fa6a18 | [
"Python-2.0",
"OLDAP-2.3"
] | 2 | 2015-08-11T17:00:17.000Z | 2021-01-04T08:34:47.000Z | #-*- coding: utf8 -*-
# *************************************************************************************************
# Python API for EJDB database library http://ejdb.org
# Copyright (C) 2012-2013 Softmotions Ltd.
#
# This file is part of EJDB.
# EJDB is free software; you can redistribute it and/or modify it under the terms of
# the GNU Lesser General Public License as published by the Free Software Foundation; either
# version 2.1 of the License or any later version. EJDB is distributed in the hope
# that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
# License for more details.
# You should have received a copy of the GNU Lesser General Public License along with EJDB;
# if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
# Boston, MA 02111-1307 USA.
# *************************************************************************************************
from __future__ import with_statement
from __future__ import division
from __future__ import print_function
from datetime import datetime
import sys
PY3 = sys.version_info[0] == 3
import unittest
from pyejdb import bson
import pyejdb
if PY3:
from io import StringIO as strio
else:
from io import BytesIO as strio
class TestOne(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestOne, self).__init__(*args, **kwargs)
#super().__init__(*args, **kwargs)
_ejdb = None
@classmethod
def setUpClass(cls):
print("pyejdb version: %s" % pyejdb.version)
print("libejdb_version: %s" % pyejdb.libejdb_version)
cls._ejdb = pyejdb.EJDB("testdb", pyejdb.DEFAULT_OPEN_MODE | pyejdb.JBOTRUNC)
def test(self):
ejdb = TestOne._ejdb
self.assertEqual(ejdb.isopen, True)
doc = {"foo": "bar", "foo2": 2}
ejdb.save("foocoll", doc)
self.assertEqual(type(doc["_id"]).__name__, "str" if PY3 else "unicode")
ldoc = ejdb.load("foocoll", doc["_id"])
self.assertIsInstance(ldoc, dict)
self.assertEqual(doc["_id"], ldoc["_id"])
self.assertEqual(doc["foo"], ldoc["foo"])
self.assertEqual(doc["foo2"], ldoc["foo2"])
cur = ejdb.find("foocoll", {"foo": "bar"}, hints={"$fields": {"foo2": 0}})
self.assertEqual(len(cur), 1)
d = cur[0]
self.assertTrue(d is not None)
self.assertEqual(d["_id"], ldoc["_id"])
with ejdb.find("foocoll") as cur2:
d = cur2[0]
self.assertTrue(d is not None)
self.assertEqual(d["_id"], ldoc["_id"])
self.assertEqual(ejdb.findOne("foocoll")["foo"], "bar")
self.assertTrue(ejdb.findOne("foocoll2") is None)
self.assertEqual(ejdb.count("foocoll"), 1)
self.assertEqual(ejdb.count("foocoll2"), 0)
ejdb.ensureStringIndex("foocoll", "foo")
cur = ejdb.find("foocoll", {"foo": "bar"}, hints={"$fields": {"foo2": 0}})
self.assertEqual(len(cur), 1)
ejdb.remove("foocoll", doc["_id"])
ldoc = ejdb.load("foocoll", doc["_id"])
self.assertTrue(ldoc is None)
ejdb.sync()
ejdb.ensureCollection("ecoll1", records=90000, large=False)
ejdb.dropCollection("ecoll1", prune=True)
def test2(self):
ejdb = TestOne._ejdb
self.assertEqual(ejdb.isopen, True)
parrot1 = {
"name": "Grenny",
"type": "African Grey",
"male": True,
"age": 1,
"birthdate": datetime.utcnow(),
"likes": ["green color", "night", "toys"],
"extra1": None
}
parrot2 = {
"name": "Bounty",
"type": "Cockatoo",
"male": False,
"age": 15,
"birthdate": datetime.utcnow(),
"likes": ["sugar cane"],
"extra1": None
}
ejdb.save("parrots", *[parrot1, None, parrot2])
self.assertEqual(type(parrot1["_id"]).__name__, "str" if PY3 else "unicode")
self.assertEqual(type(parrot2["_id"]).__name__, "str" if PY3 else "unicode")
p2 = ejdb.load("parrots", parrot2["_id"])
self.assertEqual(p2["_id"], parrot2["_id"])
cur = ejdb.find("parrots")
self.assertEqual(len(cur), 2)
self.assertEqual(len(cur[1:]), 1)
self.assertEqual(len(cur[2:]), 0)
cur = ejdb.find("parrots",
{"name": bson.BSON_Regex(("(grenny|bounty)", "i"))},
hints={"$orderby": [("name", 1)]})
self.assertEqual(len(cur), 2)
self.assertEqual(cur[0]["name"], "Bounty")
self.assertEqual(cur[0]["age"], 15)
cur = ejdb.find("parrots", {}, {"name": "Grenny"}, {"name": "Bounty"},
hints={"$orderby": [("name", 1)]})
self.assertEqual(len(cur), 2)
cur = ejdb.find("parrots", {}, {"name": "Grenny"},
hints={"$orderby": [("name", 1)]})
self.assertEqual(len(cur), 1)
sally = {
"name": "Sally",
"mood": "Angry",
}
molly = {
"name": "Molly",
"mood": "Very angry",
"secret": None
}
ejdb.save("birds", *[sally, molly])
logbuf = strio()
ejdb.find("birds", {"name": "Molly"}, log=logbuf)
#print("LB=%s" % logbuf.getvalue())
self.assertTrue(logbuf.getvalue().find("RUN FULLSCAN") != -1)
ejdb.ensureStringIndex("birds", "name")
logbuf = strio()
ejdb.find("birds", {"name": "Molly"}, log=logbuf)
self.assertTrue(logbuf.getvalue().find("MAIN IDX: 'sname'") != -1)
self.assertTrue(logbuf.getvalue().find("RUN FULLSCAN") == -1)
##print("dbmeta=%s" % ejdb.dbmeta())
bar = {
"foo": "bar"
}
self.assertEqual(ejdb.isactivetx("bars"), False)
ejdb.begintx("bars")
self.assertEqual(ejdb.isactivetx("bars"), True)
ejdb.save("bars", bar)
self.assertTrue(bar["_id"] is not None)
ejdb.abortx("bars")
self.assertTrue(ejdb.load("bars", bar["_id"]) is None)
ejdb.begintx("bars")
ejdb.save("bars", bar)
self.assertTrue(ejdb.load("bars", bar["_id"]) is not None)
self.assertEqual(ejdb.isactivetx("bars"), True)
ejdb.commitx("bars")
self.assertEqual(ejdb.isactivetx("bars"), False)
self.assertTrue(ejdb.load("bars", bar["_id"]) is not None)
ejdb.update("upsertcoll",
{"foo": "bar", "$upsert": {"foo": "bar"}})
self.assertTrue(ejdb.findOne("upsertcoll", {"foo": "bar"}) is not None)
@classmethod
def tearDownClass(cls):
if cls._ejdb:
cls._ejdb.close()
cls._ejdb = None
if __name__ == '__main__':
unittest.main()
| 34.38806 | 99 | 0.552228 | 5,494 | 0.79485 | 0 | 0 | 359 | 0.051939 | 0 | 0 | 2,238 | 0.323785 |
d53acbe8d2fd10ef53b5cd93c9f759efa5b93c91 | 242 | py | Python | accounts/urls.py | bekzod-fayzikuloff/djChat | d58e882c26d461b110c8b3277998108214d72fd5 | [
"MIT"
] | null | null | null | accounts/urls.py | bekzod-fayzikuloff/djChat | d58e882c26d461b110c8b3277998108214d72fd5 | [
"MIT"
] | null | null | null | accounts/urls.py | bekzod-fayzikuloff/djChat | d58e882c26d461b110c8b3277998108214d72fd5 | [
"MIT"
] | null | null | null | from django.urls import path
from . import views
app_name = 'users'
urlpatterns = [
path('<int:pk>/', views.user_profile, name='user_profile'),
path('messages/<int:pk>/', views.PrivateMessageView.as_view(), name='private_message')
] | 26.888889 | 90 | 0.706612 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 69 | 0.285124 |
d53b07a8a498ac3b78d4cd3571eb5f9210cc5922 | 2,029 | py | Python | vkmz/__main__.py | HegemanLab/VKMZ | 5876c24913a3b778980b6d1d4046f4c481222005 | [
"MIT"
] | 1 | 2022-01-12T15:41:00.000Z | 2022-01-12T15:41:00.000Z | vkmz/__main__.py | HegemanLab/VanKrevelin_galaxy_wrapper | 5876c24913a3b778980b6d1d4046f4c481222005 | [
"MIT"
] | 2 | 2021-06-09T14:41:47.000Z | 2021-06-09T17:56:30.000Z | vkmz/__main__.py | HegemanLab/VanKrevelin_galaxy_wrapper | 5876c24913a3b778980b6d1d4046f4c481222005 | [
"MIT"
] | 2 | 2018-07-26T21:55:17.000Z | 2018-08-01T17:59:00.000Z | #!/usr/bin/env python
def main():
"""Main flow control of vkmz
Read input data into feature objects. Results in dictionaries for samples
and features.
Then, make predictions for features. Features without predictions are removed
by default.
Finally, write results.
"""
from vkmz.arguments import args, JSON, METADATA, MODE, SQL
from vkmz.read import (
tabular as readTabular,
xcmsTabular as readXcmsTabular,
formulas as readFormulas,
)
from vkmz.predict import predict
import vkmz.write as write
# read input
if MODE == "tabular":
# read arguments here in case "input" is undeclared
tabular_f = getattr(args, "input")
samples, features = readTabular(tabular_f)
elif MODE == "w4m-xcms":
sample_f = getattr(args, "sample_metadata")
variable_f = getattr(args, "variable_metadata")
matrix_f = getattr(args, "data_matrix")
samples, features = readXcmsTabular(sample_f, variable_f, matrix_f)
else: # MODE == "formula"
formula_f = getattr(args, "input")
samples, features = readFormulas(formula_f)
if MODE == "tabular" or MODE == "w4m-xcms":
# make predictions for all features
features = {k: predict(v) for k, v in features.items()}
# remove features without a prediction
features = {k: v for k, v in features.items() if v is not None}
# remove sample feature intensities without a feature
for s in samples.values():
s.sfis = [x for x in s.sfis if len(x.feature.predictions) > 0]
# remove samples without a sample feature intensity
samples = {k: v for k, v in samples.items() if len(v.sfis) > 0}
# write results
write.tabular(samples)
j_objs = write.generateJson(samples)
if JSON:
write.json_write(j_objs)
write.html(j_objs)
if SQL:
write.sql(samples, features)
if METADATA:
write.metadata()
if __name__ == "__main__":
main()
| 32.206349 | 81 | 0.638245 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 669 | 0.329719 |
d53da663fdb9651c945c63d8d3b450c89e7a3a5a | 1,076 | py | Python | python/problem-080.py | mbuhot/mbuhot-euler-solutions | 30066543cfd2d84976beb0605839750b64f4b8ef | [
"MIT"
] | 1 | 2015-12-18T13:25:41.000Z | 2015-12-18T13:25:41.000Z | python/problem-080.py | mbuhot/mbuhot-euler-solutions | 30066543cfd2d84976beb0605839750b64f4b8ef | [
"MIT"
] | null | null | null | python/problem-080.py | mbuhot/mbuhot-euler-solutions | 30066543cfd2d84976beb0605839750b64f4b8ef | [
"MIT"
] | null | null | null | #! /usr/bin/env python3
from math import sqrt
from decimal import getcontext, Decimal
description = '''
Square root digital expansion
Problem 80
It is well known that if the square root of a natural number is not an integer, then it is irrational. The decimal expansion of such square roots is infinite without any repeating pattern at all.
The square root of two is 1.41421356237309504880..., and the digital sum of the first one hundred decimal digits is 475.
For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits for all the irrational square roots.
'''
# set the decimal precision slightly above the required 100, so there isn't any rounding in the last digit
getcontext().prec = 110
# sum the digits, excluding '.'
def decimalSum(d):
digits = str(d)[:101]
return sum(int(c) for c in digits if c != '.')
assert(decimalSum(Decimal(2).sqrt()) == 475)
def isSquare(n):
return sqrt(n).is_integer()
total = sum(decimalSum(Decimal(n).sqrt()) for n in range(1, 101) if not isSquare(n))
print(total)
| 34.709677 | 195 | 0.746283 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 685 | 0.636617 |
d53df78809e1584483410583a6ebc437b5a2b0ef | 36 | py | Python | indra/assemblers/tsv/__init__.py | zebulon2/indra | 7727ddcab52ad8012eb6592635bfa114e904bd48 | [
"BSD-2-Clause"
] | 136 | 2016-02-11T22:06:37.000Z | 2022-03-31T17:26:20.000Z | indra/assemblers/tsv/__init__.py | zebulon2/indra | 7727ddcab52ad8012eb6592635bfa114e904bd48 | [
"BSD-2-Clause"
] | 748 | 2016-02-03T16:27:56.000Z | 2022-03-09T14:27:54.000Z | indra/assemblers/tsv/__init__.py | zebulon2/indra | 7727ddcab52ad8012eb6592635bfa114e904bd48 | [
"BSD-2-Clause"
] | 56 | 2015-08-28T14:03:44.000Z | 2022-02-04T06:15:55.000Z | from .assembler import TsvAssembler
| 18 | 35 | 0.861111 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
d53e507f1e8d5bf59c86b10b14c714438e608427 | 971 | py | Python | binary_classifiers/KerasLogReg.py | zcikojevic/toxic-language-detection | 32e0e83fbc5d341dbb77bfa677f78dce82960861 | [
"MIT"
] | 1 | 2019-07-02T08:12:21.000Z | 2019-07-02T08:12:21.000Z | binary_classifiers/KerasLogReg.py | zcikojevic/toxic-language-detection | 32e0e83fbc5d341dbb77bfa677f78dce82960861 | [
"MIT"
] | null | null | null | binary_classifiers/KerasLogReg.py | zcikojevic/toxic-language-detection | 32e0e83fbc5d341dbb77bfa677f78dce82960861 | [
"MIT"
] | null | null | null | from keras.layers import Dense
from keras.models import Sequential
from keras.wrappers.scikit_learn import KerasClassifier
from run_binary_classifier import run
from keras import regularizers
def keras_logreg_model():
model = Sequential()
model.add(Dense(units=1,
input_shape=(2,),
kernel_initializer='normal',
kernel_regularizer=regularizers.l2(1.),
activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
param_grid = {
'bag_of_words__stop_words': ['english'],
'bag_of_words__ngram_range': [(1, 2)],
'bag_of_words__max_features': [500],
#'dim_reduct__n_components': [300],
'normalizer__norm': ['l2']
#'classifier__C': [5., 10.]
}
estimator = KerasClassifier(build_fn=keras_logreg_model, epochs=1, batch_size=5, verbose=1)
run(param_grid, estimator)
| 31.322581 | 91 | 0.658084 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 228 | 0.234809 |
d53f500a66c4a9814996ed105b5158ad59abc0ad | 1,910 | py | Python | phantomapp/migrations/0009_order_orderproduct.py | t7hm1/My-django-project | cf1a86a5134a86af510f9392a748f129954d1c76 | [
"MIT"
] | 5 | 2018-09-21T13:56:19.000Z | 2019-10-23T23:48:20.000Z | phantomapp/migrations/0009_order_orderproduct.py | mach1el/My-django-project | cf1a86a5134a86af510f9392a748f129954d1c76 | [
"MIT"
] | null | null | null | phantomapp/migrations/0009_order_orderproduct.py | mach1el/My-django-project | cf1a86a5134a86af510f9392a748f129954d1c76 | [
"MIT"
] | 1 | 2019-01-11T10:41:55.000Z | 2019-01-11T10:41:55.000Z | # Generated by Django 2.1 on 2018-09-06 02:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('phantomapp', '0008_auto_20180904_2102'),
]
operations = [
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('username', models.CharField(blank=True, max_length=255)),
('email', models.CharField(max_length=255)),
('first_name', models.CharField(max_length=255)),
('last_name', models.CharField(max_length=255)),
('company', models.CharField(max_length=255)),
('country', models.CharField(max_length=255)),
('state', models.CharField(max_length=255)),
('address', models.CharField(max_length=255)),
('telephone', models.CharField(max_length=255)),
('created', models.DateTimeField(auto_now=True)),
('updated', models.DateTimeField(auto_now=True)),
('paid', models.BooleanField(default=False)),
],
options={
'ordering': ('-created',),
},
),
migrations.CreateModel(
name='OrderProduct',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('price', models.IntegerField()),
('product', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='products', to='phantomapp.ShopProduct')),
('purchase', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='products', to='phantomapp.Order')),
],
),
]
| 42.444444 | 146 | 0.575916 | 1,786 | 0.935079 | 0 | 0 | 0 | 0 | 0 | 0 | 336 | 0.175916 |
d53f7a92ad96592864829c170139b3f620bcb9e7 | 109 | py | Python | aiohttp_devtools/start/__init__.py | antonmyronyuk/aiohttp-devtools | be06d295a8911a43f7ad582a88a3d64d6482b6e8 | [
"MIT"
] | 2 | 2018-11-13T06:34:17.000Z | 2019-01-08T14:33:09.000Z | aiohttp_devtools/start/__init__.py | theruziev/aiohttp-devtools | 8ab8a621964c8af0021c62e7971eea8c04f534e8 | [
"MIT"
] | 1 | 2021-02-27T14:13:58.000Z | 2021-02-27T14:13:58.000Z | aiohttp_devtools/start/__init__.py | theruziev/aiohttp-devtools | 8ab8a621964c8af0021c62e7971eea8c04f534e8 | [
"MIT"
] | null | null | null | # flake8: noqa
from .main import DatabaseChoice, ExampleChoice, SessionChoices, StartProject, TemplateChoice
| 36.333333 | 93 | 0.834862 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 14 | 0.12844 |
d540205fcfb3b4dcc91f1525818782cb26364ac5 | 178 | py | Python | epmclib/getPMID.py | tarrow/epmclib | aea429d640b0e4a7375db4bd90ce04693c940340 | [
"MIT"
] | 2 | 2015-12-07T17:56:25.000Z | 2016-01-28T16:47:21.000Z | epmclib/getPMID.py | tarrow/epmclib | aea429d640b0e4a7375db4bd90ce04693c940340 | [
"MIT"
] | 8 | 2015-12-03T17:57:54.000Z | 2016-01-21T10:22:10.000Z | epmclib/getPMID.py | tarrow/epmclib | aea429d640b0e4a7375db4bd90ce04693c940340 | [
"MIT"
] | null | null | null | from . getID import getID
class getPMID(getID):
"""Add the correct query string to only search for PMIDs"""
def __init__(self, id):
self.query = 'ext_id:' + id + ' src:med'
| 25.428571 | 60 | 0.679775 | 150 | 0.842697 | 0 | 0 | 0 | 0 | 0 | 0 | 78 | 0.438202 |
d5410810359ac36bb644e7de8c9340cf0988d530 | 560 | py | Python | test/test_levelsymmetric.py | camminady/sphericalquadpy | 0646547cc69e27de7ce36f4b519d4f420ef443e7 | [
"MIT"
] | 1 | 2020-11-15T23:47:48.000Z | 2020-11-15T23:47:48.000Z | test/test_levelsymmetric.py | camminady/sphericalquadpy | 0646547cc69e27de7ce36f4b519d4f420ef443e7 | [
"MIT"
] | 1 | 2019-04-09T08:38:21.000Z | 2019-04-09T08:38:21.000Z | test/test_levelsymmetric.py | camminady/sphericalquadpy | 0646547cc69e27de7ce36f4b519d4f420ef443e7 | [
"MIT"
] | 1 | 2020-12-19T21:12:59.000Z | 2020-12-19T21:12:59.000Z | from sphericalquadpy.levelsymmetric.levelsymmetric import Levelsymmetric
import pytest
def test_levelsymmetric():
Q = Levelsymmetric(order=4)
assert Q.name() == "Levelsymmetric Quadrature"
assert Q.getmaximalorder() == 20
with pytest.raises(Exception):
_ = Levelsymmetric(order=-10)
Q = Levelsymmetric(nq=30)
def test_invalid():
Q = Levelsymmetric(order=4)
with pytest.raises(Exception):
_ = Q.computequadpoints(234234234234)
with pytest.raises(Exception):
_ = Q.computequadweights(234234234234)
| 23.333333 | 72 | 0.707143 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 27 | 0.048214 |
d541c05f38e8c5156b01666be9ab4d4d64d8249a | 2,202 | py | Python | skinport/enums.py | PaxxPatriot/skinport.py | 37cf131aa468a3218a6bb694c5fead0353c32623 | [
"MIT"
] | null | null | null | skinport/enums.py | PaxxPatriot/skinport.py | 37cf131aa468a3218a6bb694c5fead0353c32623 | [
"MIT"
] | 1 | 2022-02-23T19:17:16.000Z | 2022-02-23T19:17:16.000Z | skinport/enums.py | PaxxPatriot/skinport.py | 37cf131aa468a3218a6bb694c5fead0353c32623 | [
"MIT"
] | null | null | null | """
MIT License
Copyright (c) 2022 PaxxPatriot
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from enum import Enum, IntEnum
__all__ = (
"Currency",
"AppID",
"Locale",
"SaleType",
"Exterior",
)
class Currency(Enum):
aud = "AUD"
brl = "BRL"
cad = "CAD"
chf = "CHF"
cny = "CNY"
czk = "CZK"
dkk = "DKK"
eur = "EUR"
gbp = "GBP"
hrk = "HRK"
nok = "NOK"
pln = "PLN"
rub = "RUB"
sek = "SEK"
try_ = "TRY"
usd = "USD"
def __str__(self) -> str:
return self.value
class AppID(IntEnum):
csgo = 730
dota2 = 570
rust = 252490
tf2 = 440
class Locale(Enum):
en = "en"
de = "de"
ru = "ru"
fr = "fr"
zh = "zh"
nl = "nl"
fi = "fi"
es = "es"
tr = "tr"
def __str__(self) -> str:
return self.value
class SaleType(Enum):
public = "public"
private = "private"
def __str__(self) -> str:
return self.value
class Exterior(Enum):
factory_new = "Factory New"
minimal_wear = "Minimal Wear"
field_tested = "Field-Tested"
well_worn = "Well-Worn"
battle_scarred = "Battle-Scarred"
def __str__(self) -> str:
return self.value
| 22.701031 | 78 | 0.653951 | 989 | 0.449137 | 0 | 0 | 0 | 0 | 0 | 0 | 1,321 | 0.599909 |
d5434f4d2e70af5a0a1a114b544845f6ac8dde26 | 387 | py | Python | lib/mcapi.py | RalphORama/MCPerms | 099d9169b1c7992b7d1c9b72003b846366eb78f7 | [
"MIT"
] | 3 | 2017-12-01T09:39:36.000Z | 2021-07-27T23:52:11.000Z | lib/mcapi.py | RalphORama/MCPerms | 099d9169b1c7992b7d1c9b72003b846366eb78f7 | [
"MIT"
] | null | null | null | lib/mcapi.py | RalphORama/MCPerms | 099d9169b1c7992b7d1c9b72003b846366eb78f7 | [
"MIT"
] | 2 | 2019-02-25T19:05:05.000Z | 2020-02-12T13:17:01.000Z | from requests import get
from json import loads
from time import time
from uuid import UUID
def username_to_uuid(username, when=int(time())):
url = 'https://api.mojang.com/users/profiles/minecraft/{}?at={}'
r = get(url.format(username, when))
if r.status_code == 200:
data = loads(r.text)
uuid = UUID(data['id'])
return str(uuid)
return None
| 21.5 | 68 | 0.648579 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 62 | 0.160207 |
d543530f4df09080f53a3a25090b0d0f7018de42 | 329 | py | Python | src/dictionaries/generic_subjects.py | FNClassificator/FNC-classificators | c159a04dff9edb714f69b323f6c46a15de63c278 | [
"Apache-2.0"
] | null | null | null | src/dictionaries/generic_subjects.py | FNClassificator/FNC-classificators | c159a04dff9edb714f69b323f6c46a15de63c278 | [
"Apache-2.0"
] | null | null | null | src/dictionaries/generic_subjects.py | FNClassificator/FNC-classificators | c159a04dff9edb714f69b323f6c46a15de63c278 | [
"Apache-2.0"
] | null | null | null | GENERIC = [
'Half of US adults have had family jailed',
'Judge stopped me winning election',
'Stock markets stabilise after earlier sell-off'
]
NON_GENERIC = [
'Leicester helicopter rotor controls failed',
'Pizza Express founder Peter Boizot dies aged 89',
'Senior Tory suggests vote could be delayed'
] | 27.416667 | 54 | 0.711246 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 262 | 0.796353 |
d543615e9951c7852a85d6e69de555518f2e11f8 | 604 | py | Python | tests/testPublishedServices.py | mapledyne/skytap | c7fb43e7d2b3e97c619948a9e5b3f03472b5cd45 | [
"MIT"
] | 3 | 2019-04-17T13:07:30.000Z | 2021-09-09T22:01:14.000Z | tests/testPublishedServices.py | FulcrumIT/skytap | c7fb43e7d2b3e97c619948a9e5b3f03472b5cd45 | [
"MIT"
] | 10 | 2016-11-02T20:48:38.000Z | 2021-09-15T15:29:34.000Z | tests/testPublishedServices.py | FulcrumIT/skytap | c7fb43e7d2b3e97c619948a9e5b3f03472b5cd45 | [
"MIT"
] | 3 | 2016-03-03T07:25:13.000Z | 2016-08-30T15:33:03.000Z | """Test Skytap published services API access."""
import json
import os
import time
import sys
sys.path.append('..')
from skytap.Environments import Environments # noqa
from skytap.framework.ApiClient import ApiClient # noqa
environments = Environments()
def test_ps_values():
"""Ensure published service capabilities are functioning."""
e = environments.first()
for v in e.vms:
for i in v.interfaces:
for s in i.services:
assert s.id
assert s.internal_port
assert s.external_ip
assert s.external_port
| 24.16 | 64 | 0.650662 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 124 | 0.205298 |
d543b90b04fcf2474056db6ca2936d01a704158e | 396 | py | Python | Python3/0828-Count-Unique-Characters-of-All-Substrings-of-a-Given-String/soln-1.py | wyaadarsh/LeetCode-Solutions | 3719f5cb059eefd66b83eb8ae990652f4b7fd124 | [
"MIT"
] | 5 | 2020-07-24T17:48:59.000Z | 2020-12-21T05:56:00.000Z | Python3/0828-Count-Unique-Characters-of-All-Substrings-of-a-Given-String/soln-1.py | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | null | null | null | Python3/0828-Count-Unique-Characters-of-All-Substrings-of-a-Given-String/soln-1.py | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | 2 | 2020-07-24T17:49:01.000Z | 2020-08-31T19:57:35.000Z | class Solution:
def uniqueLetterString(self, S: str) -> int:
idxes = {ch : (-1, -1) for ch in string.ascii_uppercase}
ans = 0
for idx, ch in enumerate(S):
i, j = idxes[ch]
ans += (j - i) * (idx - j)
idxes[ch] = j, idx
for i, j in idxes.values():
ans += (j - i) * (len(S) - j)
return ans % (int(1e9) + 7)
| 33 | 64 | 0.45202 | 395 | 0.997475 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
d5495231e3d431fe1e3c8b0e5b54558d71f22bf7 | 411 | py | Python | pythonDesafios/desafio031.py | mateusdev7/desafios-python | 6160ddc84548c7af7f5775f9acabe58238f83008 | [
"MIT"
] | null | null | null | pythonDesafios/desafio031.py | mateusdev7/desafios-python | 6160ddc84548c7af7f5775f9acabe58238f83008 | [
"MIT"
] | null | null | null | pythonDesafios/desafio031.py | mateusdev7/desafios-python | 6160ddc84548c7af7f5775f9acabe58238f83008 | [
"MIT"
] | null | null | null | from time import sleep
print('-=-' * 15)
print('Iremos calcular o preço da sua viagem (R$)')
print('-=-' * 15)
distancia = float(input('Qual a distância da viagem?\n>'))
print('CALCULANDO...')
sleep(2)
if distancia <= 200:
preco = distancia * 0.50
print(f'O preço da sua viagem vai custar R${preco:.2f}')
else:
preco = distancia * 0.45
print(f'O preço da sua viagem vai custar R${preco:.2f}')
| 25.6875 | 60 | 0.644769 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 203 | 0.489157 |
d54a0002af3d3a00d396f68eb323f46a1f109f28 | 357 | py | Python | backend/saas_framework/sharing/views.py | snarayanank2/django-workspaces | 46ef92a4caa95eee617a24ead284e533422afca0 | [
"MIT"
] | 1 | 2021-01-27T17:51:58.000Z | 2021-01-27T17:51:58.000Z | backend/saas_framework/sharing/views.py | snarayanank2/django-workspaces | 46ef92a4caa95eee617a24ead284e533422afca0 | [
"MIT"
] | 6 | 2021-03-30T13:51:35.000Z | 2022-03-02T09:24:07.000Z | backend/saas_framework/sharing/views.py | snarayanank2/django-workspaces | 46ef92a4caa95eee617a24ead284e533422afca0 | [
"MIT"
] | 1 | 2022-03-18T08:43:17.000Z | 2022-03-18T08:43:17.000Z | import logging
from rest_framework import viewsets
from saas_framework.sharing.models import Sharing
from saas_framework.sharing.serializers import SharingSerializer
logger = logging.getLogger(__name__)
class SharingViewSet(viewsets.ModelViewSet):
queryset = Sharing.objects.all()
serializer_class = SharingSerializer
ordering = 'created_at'
| 27.461538 | 64 | 0.820728 | 150 | 0.420168 | 0 | 0 | 0 | 0 | 0 | 0 | 12 | 0.033613 |
d54ab457563a7da1ea0a8ea69694b17e69f12c37 | 228 | py | Python | meridian/acupoints/yifeng41.py | sinotradition/meridian | 8c6c1762b204b72346be4bbfb74dedd792ae3024 | [
"Apache-2.0"
] | 5 | 2015-12-14T15:14:23.000Z | 2022-02-09T10:15:33.000Z | meridian/acupoints/yifeng41.py | sinotradition/meridian | 8c6c1762b204b72346be4bbfb74dedd792ae3024 | [
"Apache-2.0"
] | null | null | null | meridian/acupoints/yifeng41.py | sinotradition/meridian | 8c6c1762b204b72346be4bbfb74dedd792ae3024 | [
"Apache-2.0"
] | 3 | 2015-11-27T05:23:49.000Z | 2020-11-28T09:01:56.000Z | #!/usr/bin/python
#coding=utf-8
'''
@author: sheng
@license:
'''
SPELL=u'yìfēng'
CN=u'翳风'
NAME=u'yifeng41'
CHANNEL='sanjiao'
CHANNEL_FULLNAME='SanjiaoChannelofHand-Shaoyang'
SEQ='SJ17'
if __name__ == '__main__':
pass
| 10.857143 | 48 | 0.688596 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 150 | 0.641026 |
d54b09c1f95475f540ec4196ed5f07e9af5e2f80 | 2,090 | py | Python | Entities/ImageAnotation.py | mylenefarias/360RAT | e6b6037c0e4f90a79f0e4a9e7afee887af2b1a82 | [
"MIT"
] | null | null | null | Entities/ImageAnotation.py | mylenefarias/360RAT | e6b6037c0e4f90a79f0e4a9e7afee887af2b1a82 | [
"MIT"
] | null | null | null | Entities/ImageAnotation.py | mylenefarias/360RAT | e6b6037c0e4f90a79f0e4a9e7afee887af2b1a82 | [
"MIT"
] | 2 | 2022-02-25T02:33:28.000Z | 2022-02-25T10:10:21.000Z | class Image_Anotation:
def __init__(self, id, image, path_image):
self.id = id
self.FOV = [0.30,0.60]
self.image = image
self.list_roi=[]
self.list_compose_ROI=[]
self.id_roi=0
self.path_image = path_image
def set_image(self, image):
self.image = image
def get_image(self):
return self.image
def get_id(self):
return self.id
def get_path(self):
return self.path_image
def get_list_roi(self):
return self.list_roi
def add_ROI(self, roi):
self.id_roi += 1
roi.set_id(self.id_roi)
self.list_roi.append(roi)
#return roi to get the id
return roi
def delet_ROI(self, id):
for element in self.list_roi:
if element.get_id() == id:
self.list_roi.remove(element)
self.id_roi -= 1
break
for element in self.list_roi:
if element.get_id() > id:
new_id = element.get_id() - 1
element.set_id(new_id)
def edit_roi(self, roi):
self.list_roi[(roi.get_id()-1)] = roi
def delet_list_roi(self):
self.list_roi.clear()
def add_compose_ROI(self, compose_ROI):
self.list_compose_ROI.append(compose_ROI)
def get_list_compose_ROI(self):
return self.list_compose_ROI
def get_compose_ROI(self, id):
for roi in self.list_compose_ROI:
if roi.get_id() == id:
return roi
return None
def delete_compose_ROI(self, id):
for element in self.list_compose_ROI:
if element.get_id() == id:
self.list_compose_ROI.remove(element)
break
for element in self.list_compose_ROI:
if element.get_id() > id:
new_id = element.get_id() - 1
element.set_id(new_id)
def modify_compose_ROI(self, id, compose_ROI):
self.list_compose_ROI[id]= compose_ROI
| 24.880952 | 53 | 0.552153 | 2,067 | 0.988995 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 0.011962 |
d54b25a37b893cdc466d3bbbe69d97e87c53a99c | 106 | py | Python | qubeInfraSight/projectoffice/apps.py | debaleena2019/QubInfraInsight | 70b0b2654f6589e65283bd6fc779b13be32512ab | [
"Apache-2.0"
] | 1 | 2019-06-17T06:06:11.000Z | 2019-06-17T06:06:11.000Z | qubeInfraSight/projectoffice/apps.py | debaleena2019/QubInfraInsight | 70b0b2654f6589e65283bd6fc779b13be32512ab | [
"Apache-2.0"
] | null | null | null | qubeInfraSight/projectoffice/apps.py | debaleena2019/QubInfraInsight | 70b0b2654f6589e65283bd6fc779b13be32512ab | [
"Apache-2.0"
] | null | null | null | from django.apps import AppConfig
class ProjectofficeConfig(AppConfig):
name = 'projectoffice'
| 17.666667 | 38 | 0.745283 | 65 | 0.613208 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 0.141509 |
d54c2dcbd7cf59b2c57685116f1d61c741d7e2cb | 2,874 | py | Python | object_detection/realtime_detection.py | pcrete/humanet | a956c0903d4a6ebff987da723ce8e80ada692585 | [
"Apache-2.0"
] | 7 | 2019-10-25T12:35:02.000Z | 2022-03-24T02:14:43.000Z | object_detection/realtime_detection.py | pcrete/humanet | a956c0903d4a6ebff987da723ce8e80ada692585 | [
"Apache-2.0"
] | null | null | null | object_detection/realtime_detection.py | pcrete/humanet | a956c0903d4a6ebff987da723ce8e80ada692585 | [
"Apache-2.0"
] | 2 | 2019-11-30T03:22:37.000Z | 2020-10-06T07:17:36.000Z | import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
import cv2
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
sys.path.insert(0, os.path.abspath(".."))
from utils import label_map_util
from utils import visualization_utils as vis_util
# MODEL_NAME = 'ssd_mobilenet_v1_coco_11_06_2017'
# MODEL_NAME = 'faster_rcnn_inception_resnet_v2_atrous_coco_11_06_2017'
MODEL_NAME = 'faster_rcnn_resnet101_coco_11_06_2017'
PATH_TO_CKPT = os.path.join(MODEL_NAME,'frozen_inference_graph.pb')
PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')
NUM_CLASSES = 90
PATH_TO_VIDEO = '../dataset/videos'
print ('loading model..')
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)
def load_image_into_numpy_array(image):
im_width, im_height = image.size
return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)
with detection_graph.as_default():
with tf.Session(graph=detection_graph) as sess:
skip = 1
cap = cv2.VideoCapture(os.path.join(PATH_TO_VIDEO, 'PETS09_0.mp4'))
points_objs = {}
id_frame = 1;
id_center = 1;
first = True
while(True):
ret, frame = cap.read()
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if(skip == 1):
skip = 0
image_np = np.array(frame)
if(image_np.shape == ()): break
image_np_expanded = np.expand_dims(image_np, axis=0)
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
scores = detection_graph.get_tensor_by_name('detection_scores:0')
classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')
(boxes, scores, classes, num_detections) = sess.run([boxes, scores, classes, num_detections],
feed_dict={image_tensor: image_np_expanded})
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
np.squeeze(boxes),
np.squeeze(classes).astype(np.int32),
np.squeeze(scores),
category_index,
use_normalized_coordinates=True,
line_thickness=3,
max_boxes_to_draw=None,
min_score_thresh=0.4)
cv2.imshow('frame', image_np)
id_frame += 1
skip+=1
cap.release()
cv2.destroyAllWindows() | 29.326531 | 122 | 0.753653 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 380 | 0.13222 |
d54c9a0268801c4210ca35761a0c8999bcb5ec81 | 1,832 | py | Python | stupidV2.py | Devansh-ops/HashCode2021 | c1450a0bd81fff5a8d6b402188576024727587d9 | [
"MIT"
] | null | null | null | stupidV2.py | Devansh-ops/HashCode2021 | c1450a0bd81fff5a8d6b402188576024727587d9 | [
"MIT"
] | null | null | null | stupidV2.py | Devansh-ops/HashCode2021 | c1450a0bd81fff5a8d6b402188576024727587d9 | [
"MIT"
] | null | null | null | # Hashcode 2021
# Team Depresso
# Problem - Traffic Signaling
## Data Containers
class Street:
def __init__(self,start,end,name,L):
self.start = start
self.end = end
self.name = name
self.time = L
def show(self):
print(self.start,self.end,self.name,self.time)
class Car:
def __init__(self,P, path):
self.P = P # the number of streets that the car wants to travel
self.path = path # names of the streets
# the car starts at the end of first street
def show(self):
print(self.P, self.path)
#Just getting data
with open('c.txt') as f:
D, I, S, V, F = list(map(int, f.readline()[:-1].split(" ")))
'''
l1 = f.readline()[:-1].split(' ')
D = int(l1[0]) # Duration of simulation 1 <D<10^4
I = int(l1[1]) # The number of intersections 2 ≤ I ≤ 10^5
S = int(l1[2]) # The number of streets 2 ≤ S ≤ 10 5
V = int(l1[3]) # The number of cars 1 ≤ V ≤ 10 3
F = int(l1[4]) # The bonus points for each car that reaches
# its destination before time D1 ≤ F ≤ 10 3
'''
# B, E, streets_descriptions = [], [], []
streets = [0]*S
for i in range(S):
line = f.readline()[:-1].split(' ')
street = Street(int(line[0]), int(line[1]), line[2], int(line[3]))
streets[i] = street
#street.show()
cars = [0]*V
for i in range(V):
line = f.readline()[:-1].split(' ')
car = Car(int(line[0]), line[1:])
cars[i] = car
#car.show()
o= open("c-output-try-stupid-v2.txt","w+")
o.write(str(I)+'\n')
for i in range(I):
o.write(str(i)+'\n')
num_roads_ending = 0
str_ending = []
for j in range(S):
if streets[j].end == i:
num_roads_ending += 1
str_ending.append(streets[j].name)
o.write(str(num_roads_ending)+'\n')
for k in range(num_roads_ending):
o.write(str_ending[k]+" "+ str(1)+'\n') | 24.756757 | 70 | 0.581332 | 475 | 0.257035 | 0 | 0 | 0 | 0 | 0 | 0 | 742 | 0.401515 |
d54d660e19d06efe546719fe102b385e9d155b60 | 3,178 | py | Python | notebooks/uplifts/dea_383.py | NHSDigital/medicines-text-mining-tool | bea1efddd832b614fdb00ae8df5f8dc206ba81b0 | [
"MIT"
] | 1 | 2022-03-31T13:04:05.000Z | 2022-03-31T13:04:05.000Z | notebooks/uplifts/dea_383.py | NHSDigital/medicines-text-mining-tool | bea1efddd832b614fdb00ae8df5f8dc206ba81b0 | [
"MIT"
] | null | null | null | notebooks/uplifts/dea_383.py | NHSDigital/medicines-text-mining-tool | bea1efddd832b614fdb00ae8df5f8dc206ba81b0 | [
"MIT"
] | null | null | null | # Databricks notebook source
# MAGIC %run ../_modules/epma_global/functions
# COMMAND ----------
# MAGIC %run ../_modules/epma_global/test_helpers
# COMMAND ----------
from pyspark.sql import functions as F
# COMMAND ----------
dbutils.widgets.text('db', '', 'db')
DB = dbutils.widgets.get('db')
assert DB
dbutils.widgets.text('unmappable_table_name', 'unmappable', 'unmappable_table_name')
UNMAPPABLE_TABLE_NAME = dbutils.widgets.get('unmappable_table_name')
assert UNMAPPABLE_TABLE_NAME
dbutils.widgets.text('match_lookup_final_name', 'match_lookup_final', 'match_lookup_final_name')
MATCH_LOOKUP_FINAL_TABLE_NAME = dbutils.widgets.get('match_lookup_final_name')
assert MATCH_LOOKUP_FINAL_TABLE_NAME
dbutils.widgets.text('processed_descriptions_table_name', 'processed_epma_descriptions', 'processed_descriptions_table_name')
PROCESSED_DESCRIPTIONS_TABLE_NAME = dbutils.widgets.get('processed_descriptions_table_name')
assert PROCESSED_DESCRIPTIONS_TABLE_NAME
# COMMAND ----------
def add_form_in_text_col_to_match_lookup_final_table(db: str, table: str) -> None:
if not table_exists(db, table):
return
df = spark.table(f'{db}.{table}')
if 'form_in_text' not in df.columns:
with TemporaryTable(df, db, create=True) as tmp_table:
df_tmp_table = spark.table(f'{db}.{tmp_table.name}').withColumn('form_in_text', F.lit(' '))
df_tmp_table = df_tmp_table.select('original_epma_description', 'form_in_text', 'match_id',
'match_term', 'id_level', 'match_level', 'match_datetime',
'version_id', 'run_id')
create_table(df_tmp_table, db, table=table, overwrite=True)
# COMMAND ----------
def add_form_in_text_col_to_unmappable_table(db: str, table: str) -> None:
if not table_exists(db, table):
return
df = spark.table(f'{db}.{table}')
if 'form_in_text' not in df.columns:
with TemporaryTable(df, db, create=True) as tmp_table:
df_tmp_table = spark.table(f'{db}.{tmp_table.name}').withColumn('form_in_text', F.lit(' '))
df_tmp_table = df_tmp_table.select('original_epma_description', 'form_in_text', 'reason',
'match_datetime', 'run_id')
create_table(df_tmp_table, db, table=table, overwrite=True)
# COMMAND ----------
def add_form_in_text_col_to_processed_descriptions_table(db: str, table: str) -> None:
if not table_exists(db, table):
return
df = spark.table(f'{db}.{table}')
if 'form_in_text' not in df.columns:
with TemporaryTable(df, db, create=True) as tmp_table:
df_tmp_table = spark.table(f'{db}.{tmp_table.name}').withColumn('form_in_text', F.lit(' '))
df_tmp_table = df_tmp_table.select('original_epma_description', 'form_in_text', 'matched')
create_table(df_tmp_table, db, table=table, overwrite=True)
# COMMAND ----------
add_form_in_text_col_to_match_lookup_final_table(DB, MATCH_LOOKUP_FINAL_TABLE_NAME)
add_form_in_text_col_to_unmappable_table(DB, UNMAPPABLE_TABLE_NAME)
add_form_in_text_col_to_processed_descriptions_table(DB, PROCESSED_DESCRIPTIONS_TABLE_NAME) | 36.113636 | 125 | 0.704216 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,042 | 0.327879 |
d54e3560503b5dd94b9ef2b1f63b8e1ccc96eeee | 164 | py | Python | allauth/socialaccount/providers/stripe/urls.py | mina-gaid/scp | 38e1cd303d4728a987df117f666ce194e241ed1a | [
"MIT"
] | 1 | 2018-04-06T21:36:59.000Z | 2018-04-06T21:36:59.000Z | allauth/socialaccount/providers/stripe/urls.py | mina-gaid/scp | 38e1cd303d4728a987df117f666ce194e241ed1a | [
"MIT"
] | 6 | 2020-06-05T18:44:19.000Z | 2022-01-13T00:48:56.000Z | allauth/socialaccount/providers/stripe/urls.py | mina-gaid/scp | 38e1cd303d4728a987df117f666ce194e241ed1a | [
"MIT"
] | 1 | 2022-02-01T17:19:28.000Z | 2022-02-01T17:19:28.000Z | from allauth.socialaccount.providers.oauth2.urls import default_urlpatterns
from .provider import StripeProvider
urlpatterns = default_urlpatterns(StripeProvider)
| 32.8 | 75 | 0.878049 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
d54e772528672c15b49db9bb963f2e75f766bb4b | 1,491 | py | Python | state-change-localization-classification/slowFast-perceiver/models/frameselection_models.py | EGO4D/hands-and-objects | 76d6ce6af1a9db4007ea24eb315f3f0eaea26bc2 | [
"MIT"
] | 24 | 2021-10-15T20:17:38.000Z | 2022-03-30T18:54:55.000Z | state-change-localization-classification/slowFast-perceiver/models/frameselection_models.py | EGO4D/hands-and-objects | 76d6ce6af1a9db4007ea24eb315f3f0eaea26bc2 | [
"MIT"
] | 1 | 2022-03-09T03:35:42.000Z | 2022-03-10T20:50:24.000Z | state-change-localization-classification/slowFast-perceiver/models/frameselection_models.py | EGO4D/hands-and-objects | 76d6ce6af1a9db4007ea24eb315f3f0eaea26bc2 | [
"MIT"
] | 4 | 2021-11-18T19:22:16.000Z | 2022-03-21T02:51:35.000Z | import torch
import torch.nn as nn
import torchvision.models as models
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from .build import MODEL_REGISTRY
@MODEL_REGISTRY.register()
class CNNRNN(nn.Module):
def __init__(self, cfg):
super().__init__()
input_dim = 512
hidden_dim = 128
num_layers = 1
self.cnn = models.resnet50(pretrained=True)
out_features = self.cnn.fc.in_features
self.fc1 = nn.Linear(out_features, input_dim)
self.fc2 = nn.Linear(hidden_dim, 1)
self.rnn = nn.RNN(input_dim, hidden_dim, num_layers, batch_first=True)
def forward(self, vid, lengths):
B, T, *a = vid.shape
vid = vid.permute(0, 1, 4, 2, 3)
outs = []
def hook(module, input, output):
outs.append(input)
self.cnn.fc.register_forward_hook(hook)
for t in range(T):
# print(t)
frame = vid[:, t, :, :, :]
out = self.cnn(frame)
if outs[0][0].ndim == 2:
outs = [ten[0].unsqueeze(0) for ten in outs]
else:
outs = [ten[0] for ten in outs]
outs = torch.cat(outs, dim=1)
outs = self.fc1(outs)
packed_seq = pack_padded_sequence(outs, lengths, batch_first=True, enforce_sorted=False)
out, hn = self.rnn(packed_seq)
padded_seq, lengths = pad_packed_sequence(out, batch_first=True)
out = self.fc2(padded_seq)
return out
| 29.82 | 96 | 0.602951 | 1,282 | 0.859826 | 0 | 0 | 1,309 | 0.877934 | 0 | 0 | 10 | 0.006707 |
d54fb479ac6c0ddd4d66b98b5bfa4aea9b2fd454 | 5,829 | py | Python | azurelinuxagent/daemon/resourcedisk/openwrt.py | koifans/WALinuxAgent | 236c6c12d89757589411651ae015640d371251a4 | [
"Apache-2.0"
] | 1 | 2020-11-23T10:48:28.000Z | 2020-11-23T10:48:28.000Z | azurelinuxagent/daemon/resourcedisk/openwrt.py | koifans/WALinuxAgent | 236c6c12d89757589411651ae015640d371251a4 | [
"Apache-2.0"
] | 1 | 2019-06-06T13:24:55.000Z | 2019-06-06T13:24:55.000Z | azurelinuxagent/daemon/resourcedisk/openwrt.py | koifans/WALinuxAgent | 236c6c12d89757589411651ae015640d371251a4 | [
"Apache-2.0"
] | null | null | null | # Microsoft Azure Linux Agent
#
# Copyright 2018 Microsoft Corporation
# Copyright 2018 Sonus Networks, Inc. (d.b.a. Ribbon Communications Operating Company)
#
# 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.
#
# Requires Python 2.6+ and Openssl 1.0+
#
import os
import errno as errno
import azurelinuxagent.common.logger as logger
import azurelinuxagent.common.utils.fileutil as fileutil
import azurelinuxagent.common.utils.shellutil as shellutil
import azurelinuxagent.common.conf as conf
from azurelinuxagent.common.exception import ResourceDiskError
from azurelinuxagent.daemon.resourcedisk.default import ResourceDiskHandler
class OpenWRTResourceDiskHandler(ResourceDiskHandler):
def __init__(self):
super(OpenWRTResourceDiskHandler, self).__init__()
# Fase File System (FFS) is UFS
if self.fs == 'ufs' or self.fs == 'ufs2':
self.fs = 'ffs'
def reread_partition_table(self, device):
ret, output = shellutil.run_get_output("hdparm -z {0}".format(device), chk_err=False)
if ret != 0:
logger.warn("Failed refresh the partition table.")
def mount_resource_disk(self, mount_point):
device = self.osutil.device_for_ide_port(1)
if device is None:
raise ResourceDiskError("unable to detect disk topology")
logger.info('Resource disk device {0} found.', device)
# 2. Get partition
device = "/dev/{0}".format(device)
partition = device + "1"
logger.info('Resource disk partition {0} found.', partition)
# 3. Mount partition
mount_list = shellutil.run_get_output("mount")[1]
existing = self.osutil.get_mount_point(mount_list, device)
if existing:
logger.info("Resource disk [{0}] is already mounted [{1}]",
partition,
existing)
return existing
try:
fileutil.mkdir(mount_point, mode=0o755)
except OSError as ose:
msg = "Failed to create mount point " \
"directory [{0}]: {1}".format(mount_point, ose)
logger.error(msg)
raise ResourceDiskError(msg=msg, inner=ose)
force_option = 'F'
if self.fs == 'xfs':
force_option = 'f'
mkfs_string = "mkfs.{0} -{2} {1}".format(self.fs, partition, force_option)
# Compare to the Default mount_resource_disk, we don't check for GPT that is not supported on OpenWRT
ret = self.change_partition_type(suppress_message=True, option_str="{0} 1 -n".format(device))
ptype = ret[1].strip()
if ptype == "7" and self.fs != "ntfs":
logger.info("The partition is formatted with ntfs, updating "
"partition type to 83")
self.change_partition_type(suppress_message=False, option_str="{0} 1 83".format(device))
self.reread_partition_table(device)
logger.info("Format partition [{0}]", mkfs_string)
shellutil.run(mkfs_string)
else:
logger.info("The partition type is {0}", ptype)
mount_options = conf.get_resourcedisk_mountoptions()
mount_string = self.get_mount_string(mount_options,
partition,
mount_point)
attempts = 5
while not os.path.exists(partition) and attempts > 0:
logger.info("Waiting for partition [{0}], {1} attempts remaining",
partition,
attempts)
sleep(5)
attempts -= 1
if not os.path.exists(partition):
raise ResourceDiskError("Partition was not created [{0}]".format(partition))
if os.path.ismount(mount_point):
logger.warn("Disk is already mounted on {0}", mount_point)
else:
# Some kernels seem to issue an async partition re-read after a
# command invocation. This causes mount to fail if the
# partition re-read is not complete by the time mount is
# attempted. Seen in CentOS 7.2. Force a sequential re-read of
# the partition and try mounting.
logger.info("Mounting after re-reading partition info.")
self.reread_partition_table(device)
logger.info("Mount resource disk [{0}]", mount_string)
ret, output = shellutil.run_get_output(mount_string)
if ret:
logger.warn("Failed to mount resource disk. "
"Attempting to format and retry mount. [{0}]",
output)
shellutil.run(mkfs_string)
ret, output = shellutil.run_get_output(mount_string)
if ret:
raise ResourceDiskError("Could not mount {0} "
"after syncing partition table: "
"[{1}] {2}".format(partition,
ret,
output))
logger.info("Resource disk {0} is mounted at {1} with {2}",
device,
mount_point,
self.fs)
return mount_point
| 42.860294 | 109 | 0.593927 | 4,701 | 0.806485 | 0 | 0 | 0 | 0 | 0 | 0 | 2,014 | 0.345514 |
d5519eaf2867f48a79c81e7d904b4b74a968d747 | 1,828 | py | Python | lib/stacks/publish_to_social/lambda/send_report.py | shaftoe/api-l3x-in | 06426f62708051b570e8839398562982d770903f | [
"Apache-2.0"
] | 11 | 2020-03-01T15:24:09.000Z | 2022-01-06T08:31:31.000Z | lib/stacks/publish_to_social/lambda/send_report.py | sierrezinal/api-l3x-in | 0c5122a29ecd8f94cb9b99909499c330969d26ee | [
"Apache-2.0"
] | 1 | 2020-08-28T15:25:39.000Z | 2020-08-30T07:35:59.000Z | lib/stacks/publish_to_social/lambda/send_report.py | sierrezinal/api-l3x-in | 0c5122a29ecd8f94cb9b99909499c330969d26ee | [
"Apache-2.0"
] | 5 | 2020-10-15T03:06:37.000Z | 2021-09-29T07:07:18.000Z | from os import environ as env
import json
import utils
import utils.aws as aws
import utils.handlers as handlers
def put_record_to_logstream(event: utils.LambdaEvent) -> str:
"""Put a record of source Lambda execution in LogWatch Logs."""
log_group_name = env["REPORT_LOG_GROUP_NAME"]
utils.Log.info("Fetching requestPayload and responsePayload")
req, res = event["requestPayload"], event["responsePayload"]
utils.Log.info("Fetching requestPayload content")
sns_payload = req["Records"][0]["Sns"]
message_id = sns_payload["MessageId"]
message = json.loads(sns_payload["Message"])
url, title = message["url"], message["title"]
try:
body = json.loads(res["body"])
except json.JSONDecodeError as error:
raise utils.HandledError("Failed decoding payload: %s" % error)
name, timestamp = body["name"], body["timestamp"]
if res["statusCode"] != 200:
raise utils.HandledError("Source lambda '%s' failed with status code %d, "
"ignoring report" % (name, res["statusCode"]))
return aws.send_event_to_logstream(log_group=log_group_name,
log_stream=name,
message={
"url": url,
"MessageId": message_id,
"title": title,
"timestamp": timestamp,
})
def handler(event, context) -> utils.Response:
"""Lambda entry point."""
return handlers.EventHandler(
name="send_report",
event=utils.LambdaEvent(event),
context=utils.LambdaContext(context),
action=put_record_to_logstream,
).response
| 34.490566 | 82 | 0.571116 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 457 | 0.25 |
d551aabe726e69db8b462ea2ce644c9f926174ad | 2,999 | py | Python | RAMLFlask/Server.py | nm-wu/RAMLFlask | 003ceb0f0b68d0d80d8fb8fcd6d5b329a1608dd0 | [
"BSD-3-Clause"
] | 4 | 2017-11-30T10:23:12.000Z | 2020-06-07T01:05:12.000Z | RAMLFlask/Server.py | nm-wu/RAMLFlask | 003ceb0f0b68d0d80d8fb8fcd6d5b329a1608dd0 | [
"BSD-3-Clause"
] | null | null | null | RAMLFlask/Server.py | nm-wu/RAMLFlask | 003ceb0f0b68d0d80d8fb8fcd6d5b329a1608dd0 | [
"BSD-3-Clause"
] | 1 | 2017-12-14T17:11:05.000Z | 2017-12-14T17:11:05.000Z | import os
from importlib import import_module
from flask import Flask
import ConfigParser
import Printer
class Server:
def __init__(self, generator, comparison, config_file='config.ini'):
# Generator class
self.gen = generator
# Comparison class
self.comp = comparison
cparse = ConfigParser.ConfigParser()
cparse.read(config_file)
self.generated_dir = os.path.join('generated')
self.routes_dir = os.path.join('routes')
self.delegates_dir = os.path.join('delegates')
if cparse.has_section('DIRECTORIES'):
if cparse.has_option('DIRECTORIES', 'generated'):
self.gen.generated_directory = cparse.get('DIRECTORIES', 'generated')
self.comp.generated_directory = cparse.get('DIRECTORIES', 'generated')
if cparse.has_option('DIRECTORIES', 'routes'):
self.gen.routes_directory = cparse.get('DIRECTORIES', 'routes')
self.comp.routes_directory = cparse.get('DIRECTORIES', 'routes')
if cparse.has_option('DIRECTORIES', 'delegates'):
self.gen.delegates_directory = cparse.get('DIRECTORIES', 'delegates')
self.comp.delegates_directory = cparse.get('DIRECTORIES', 'delegates')
def generate(self, generate=True, bind=True):
if generate == True:
self.gen.generate_code()
if bind == True:
self.gen.bind_routes()
def compare(self, p_v=True, p_r=True, p_t=True, static_validations=None, static_rtypes=None, test_in=[]):
self.comp.current_version = self.gen.current_file_name
self.comp.test_res = self.gen.test_res
self.comp.new_v_file = self.gen.new_v_file
self.comp.new_r_file = self.gen.new_r_file
if p_v == True:
out = self.comp.static_valid_analysis(static_validations)
for i in out:
Printer.info_print(i)
if p_r == True:
out = self.comp.static_rtypes_analysis(static_rtypes)
for i in out:
Printer.info_print(i)
if p_t == True:
out = self.comp.test_analysis()
for i in out:
if i[0] == 'INFO':
Printer.info_print(i[1])
else:
Printer.warn_print(i[1])
def start_server(self):
# Creates the basic Flask app
self.app = Flask(__name__)
self.app = Flask(__name__)
folder = self.gen.generated_directory.replace('/', '.').replace('\\', '.') + '.'
while folder[0] == '.':
folder = folder[1:]
while folder[-1] == '.':
folder = folder[:-1]
module = import_module(folder + '.route_mappings', 'route_imports')
self.app.register_blueprint(module.route_imports, url_prefix='')
self.app.run()
def exec_all(self):
self.generate(True, True)
self.compare(True, True, True)
self.start_server() | 34.872093 | 109 | 0.596199 | 2,893 | 0.964655 | 0 | 0 | 0 | 0 | 0 | 0 | 388 | 0.129376 |
d551c440a4a93ff739f21c92c784dfb223859c3d | 416 | py | Python | native/public/urls.py | Andrew-Chen-Wang/django-3.0-private-messaging | d7c02c42dfd077cd234df3ed08d7ed692dc2b4c7 | [
"BSD-3-Clause"
] | 1 | 2020-05-21T03:17:29.000Z | 2020-05-21T03:17:29.000Z | native/public/urls.py | Andrew-Chen-Wang/django-3.0-private-messaging | d7c02c42dfd077cd234df3ed08d7ed692dc2b4c7 | [
"BSD-3-Clause"
] | 7 | 2021-03-30T12:48:24.000Z | 2021-06-10T18:35:08.000Z | native/public/urls.py | Andrew-Chen-Wang/django-3.0-private-messaging | d7c02c42dfd077cd234df3ed08d7ed692dc2b4c7 | [
"BSD-3-Clause"
] | 1 | 2020-05-05T08:31:16.000Z | 2020-05-05T08:31:16.000Z | from django.urls import path, include
from . import views
urlpatterns = [
path("", views.index, name="index"),
# Authentication
path("accounts/", include("django.contrib.auth.urls")),
path("accounts/register/", views.register, name="register"),
# Test URLs
path("test/wsconn", views.wsconn, name="wsconntest"),
# Chat URL
path("chat/<int:thread>", views.open_chat, name="chat")
]
| 24.470588 | 64 | 0.653846 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 163 | 0.391827 |
d5537a673b3a26aa0f21d11d643794a306a0cc11 | 4,337 | py | Python | drex-atari/train.py | abalakrishna123/CoRL2019-DREX | b80b3308559261f7144d173ee293eb3c5b4a0502 | [
"MIT"
] | 36 | 2019-11-02T02:48:47.000Z | 2022-03-04T19:10:28.000Z | drex-atari/train.py | abalakrishna123/CoRL2019-DREX | b80b3308559261f7144d173ee293eb3c5b4a0502 | [
"MIT"
] | 16 | 2019-10-31T16:19:34.000Z | 2022-03-12T00:02:27.000Z | drex-atari/train.py | abalakrishna123/CoRL2019-DREX | b80b3308559261f7144d173ee293eb3c5b4a0502 | [
"MIT"
] | 13 | 2019-11-06T08:32:06.000Z | 2022-02-28T06:56:10.000Z | import os
from bc import Imitator
import numpy as np
from dataset import Example, Dataset
import utils
#from ale_wrapper import ALEInterfaceWrapper
from evaluator import Evaluator
from pdb import set_trace
import matplotlib.pyplot as plt
#try bmh
plt.style.use('bmh')
def smooth(losses, run=10):
new_losses = []
for i in range(len(losses)):
new_losses.append(np.mean(losses[max(0, i - 10):i+1]))
return new_losses
def plot(losses, checkpoint_dir, env_name):
print("Plotting losses to ", os.path.join(checkpoint_dir, env_name + "_loss.png"))
p=plt.plot(smooth(losses, 25))
plt.xlabel("Update")
plt.ylabel("Loss")
plt.legend(loc='lower center')
plt.savefig(os.path.join(checkpoint_dir, env_name + "loss.png"))
def train(env_name,
minimal_action_set,
learning_rate,
alpha,
l2_penalty,
minibatch_size,
hist_len,
discount,
checkpoint_dir,
updates,
dataset,
validation_dataset,
num_eval_episodes,
epsilon_greedy,
extra_info):
import tracemalloc
# create DQN agent
agent = Imitator(list(minimal_action_set),
learning_rate,
alpha,
checkpoint_dir,
hist_len,
l2_penalty)
print("Beginning training...")
log_frequency = 500
log_num = log_frequency
update = 1
running_loss = 0.
best_v_loss = np.float('inf')
count = 0
while update < updates:
# snapshot = tracemalloc.take_snapshot()
# top_stats = snapshot.statistics('lineno')
# import gc
# for obj in gc.get_objects():
# try:
# if torch.is_tensor(obj) or (hasattr(obj, 'data') and torch.is_tensor(obj.data)):
# print(type(obj), obj.size())
# except:
# pass
#
# print("[ Top 10 ]")
# for stat in top_stats[:10]:
# print(stat)
if update > log_num:
print(str(update) + " updates completed. Loss {}".format(running_loss / log_frequency))
log_num += log_frequency
running_loss = 0
#run validation loss test
v_loss = agent.validate(validation_dataset, 10)
print("Validation accuracy = {}".format(v_loss / validation_dataset.size))
if v_loss > best_v_loss:
count += 1
if count > 5:
print("validation not improing for {} steps. Stopping to prevent overfitting".format(count))
break
else:
best_v_loss = v_loss
print("updating best vloss", best_v_loss)
count = 0
l = agent.train(dataset, minibatch_size)
running_loss += l
update += 1
print("Training completed.")
agent.checkpoint_network(env_name, extra_info)
#Plot losses
#Evaluation
print("beginning evaluation")
evaluator = Evaluator(env_name, num_eval_episodes, checkpoint_dir, epsilon_greedy)
evaluator.evaluate(agent)
return agent
def train_transitions(env_name,
minimal_action_set,
learning_rate,
alpha,
l2_penalty,
minibatch_size,
hist_len,
discount,
checkpoint_dir,
updates,
dataset,
num_eval_episodes):
# create DQN agent
agent = Imitator(list(minimal_action_set),
learning_rate,
alpha,
checkpoint_dir,
hist_len,
l2_penalty)
print("Beginning training...")
log_frequency = 1000
log_num = log_frequency
update = 1
running_loss = 0.
while update < updates:
if update > log_num:
print(str(update) + " updates completed. Loss {}".format(running_loss / log_frequency))
log_num += log_frequency
running_loss = 0
l = agent.train(dataset, minibatch_size)
running_loss += l
update += 1
print("Training completed.")
agent.checkpoint_network(env_name + "_transitions")
#calculate accuacy
#Evaluation
#evaluator = Evaluator(env_name, num_eval_episodes)
#evaluator.evaluate(agent)
return agent
if __name__ == '__main__':
train()
| 29.107383 | 111 | 0.587733 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 993 | 0.22896 |
d5539201acc74777191577d0a77d4057f6de4e8d | 153 | py | Python | graphgallery/utils/ipynb.py | EdisonLeeeee/GraphGallery | 4eec9c5136bda14809bd22584b26cc346cdb633b | [
"MIT"
] | 300 | 2020-08-09T04:27:41.000Z | 2022-03-30T07:43:41.000Z | graphgallery/utils/ipynb.py | EdisonLeeeee/GraphGallery | 4eec9c5136bda14809bd22584b26cc346cdb633b | [
"MIT"
] | 5 | 2020-11-05T06:16:50.000Z | 2021-12-11T05:05:22.000Z | graphgallery/utils/ipynb.py | EdisonLeeeee/GraphGallery | 4eec9c5136bda14809bd22584b26cc346cdb633b | [
"MIT"
] | 51 | 2020-09-23T15:37:12.000Z | 2022-03-05T01:28:56.000Z | from IPython import get_ipython
from IPython.display import display
def is_ipynb():
return type(get_ipython()).__module__.startswith('ipykernel.')
| 21.857143 | 66 | 0.784314 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 12 | 0.078431 |
d55427688a084bec0e9255b152935a5e5812cfae | 8,526 | py | Python | monitoring/prober/scd/test_subscription_queries.py | rpai1/dss | 79d8110c336851b155a6e5417692ec68b70c0c07 | [
"Apache-2.0"
] | 1 | 2021-03-06T19:31:04.000Z | 2021-03-06T19:31:04.000Z | monitoring/prober/scd/test_subscription_queries.py | rpai1/dss | 79d8110c336851b155a6e5417692ec68b70c0c07 | [
"Apache-2.0"
] | null | null | null | monitoring/prober/scd/test_subscription_queries.py | rpai1/dss | 79d8110c336851b155a6e5417692ec68b70c0c07 | [
"Apache-2.0"
] | 1 | 2020-09-20T22:15:36.000Z | 2020-09-20T22:15:36.000Z | """Strategic conflict detection Subscription query tests:
- add a few Subscriptions spaced in time and footprints
- query with various combinations of arguments
"""
import datetime
from monitoring.monitorlib.infrastructure import default_scope
from monitoring.monitorlib import scd
from monitoring.monitorlib.scd import SCOPE_SC
SUB1_ID = '00000088-b268-481c-a32d-6be442000000'
SUB2_ID = '00000017-a3fe-42d6-9f3b-83dec2000000'
SUB3_ID = '0000001b-9c8a-475e-a82d-d81922000000'
LAT0 = 23
LNG0 = 56
# This value should be large enough to ensure areas separated by this distance
# will lie in separate grid cells.
FOOTPRINT_SPACING_M = 10000
def _make_sub1_req():
time_start = datetime.datetime.utcnow()
time_end = time_start + datetime.timedelta(minutes=60)
lat = LAT0 - scd.latitude_degrees(FOOTPRINT_SPACING_M)
return {
"extents": scd.make_vol4(None, time_end, 0, 300, scd.make_circle(lat, LNG0, 100)),
"old_version": 0,
"uss_base_url": "https://example.com/foo",
"notify_for_operations": True,
"notify_for_constraints": False
}
def _make_sub2_req():
time_start = datetime.datetime.utcnow() + datetime.timedelta(hours=2)
time_end = time_start + datetime.timedelta(minutes=60)
return {
"extents": scd.make_vol4(time_start, time_end, 350, 650, scd.make_circle(LAT0, LNG0, 100)),
"old_version": 0,
"uss_base_url": "https://example.com/foo",
"notify_for_operations": True,
"notify_for_constraints": False
}
def _make_sub3_req():
time_start = datetime.datetime.utcnow() + datetime.timedelta(hours=4)
time_end = time_start + datetime.timedelta(minutes=60)
lat = LAT0 + scd.latitude_degrees(FOOTPRINT_SPACING_M)
return {
"extents": scd.make_vol4(time_start, time_end, 700, 1000, scd.make_circle(lat, LNG0, 100)),
"old_version": 0,
"uss_base_url": "https://example.com/foo",
"notify_for_operations": True,
"notify_for_constraints": False
}
def test_ensure_clean_workspace(scd_session):
for sub_id in (SUB1_ID, SUB2_ID, SUB3_ID):
resp = scd_session.get('/subscriptions/{}'.format(sub_id), scope=SCOPE_SC)
if resp.status_code == 200:
resp = scd_session.delete('/subscriptions/{}'.format(sub_id), scope=SCOPE_SC)
assert resp.status_code == 200, resp.content
elif resp.status_code == 404:
# As expected.
pass
else:
assert False, resp.content
# Preconditions: No named Subscriptions exist
# Mutations: None
@default_scope(SCOPE_SC)
def test_subs_do_not_exist_get(scd_session):
for sub_id in (SUB1_ID, SUB2_ID, SUB3_ID):
resp = scd_session.get('/subscriptions/{}'.format(sub_id))
assert resp.status_code == 404, resp.content
# Preconditions: No named Subscriptions exist
# Mutations: None
@default_scope(SCOPE_SC)
def test_subs_do_not_exist_query(scd_session):
resp = scd_session.post('/subscriptions/query', json={
'area_of_interest': scd.make_vol4(None, None, 0, 5000, scd.make_circle(LAT0, LNG0, FOOTPRINT_SPACING_M))
})
assert resp.status_code == 200, resp.content
result_ids = [x['id'] for x in resp.json()['subscriptions']]
for sub_id in (SUB1_ID, SUB2_ID, SUB3_ID):
assert sub_id not in result_ids
# Preconditions: No named Subscriptions exist
# Mutations: Subscriptions 1, 2, and 3 created
@default_scope(SCOPE_SC)
def test_create_subs(scd_session):
resp = scd_session.put('/subscriptions/{}'.format(SUB1_ID), json=_make_sub1_req())
assert resp.status_code == 200, resp.content
resp = scd_session.put('/subscriptions/{}'.format(SUB2_ID), json=_make_sub2_req())
assert resp.status_code == 200, resp.content
resp = scd_session.put('/subscriptions/{}'.format(SUB3_ID), json=_make_sub3_req())
assert resp.status_code == 200, resp.content
# Preconditions: Subscriptions 1, 2, and 3 created
# Mutations: None
@default_scope(SCOPE_SC)
def test_search_find_all_subs(scd_session):
resp = scd_session.post(
'/subscriptions/query',
json={
"area_of_interest": scd.make_vol4(None, None, 0, 3000,
scd.make_circle(LAT0, LNG0, FOOTPRINT_SPACING_M))
})
assert resp.status_code == 200, resp.content
result_ids = [x['id'] for x in resp.json()['subscriptions']]
for sub_id in (SUB1_ID, SUB2_ID, SUB3_ID):
assert sub_id in result_ids
# Preconditions: Subscriptions 1, 2, and 3 created
# Mutations: None
@default_scope(SCOPE_SC)
def test_search_footprint(scd_session):
lat = LAT0 - scd.latitude_degrees(FOOTPRINT_SPACING_M)
print(lat)
resp = scd_session.post(
'/subscriptions/query',
json={
"area_of_interest": scd.make_vol4(None, None, 0, 3000,
scd.make_circle(lat, LNG0, 50))
})
assert resp.status_code == 200, resp.content
result_ids = [x['id'] for x in resp.json()['subscriptions']]
assert SUB1_ID in result_ids
assert SUB2_ID not in result_ids
assert SUB3_ID not in result_ids
resp = scd_session.post(
'/subscriptions/query',
json={
"area_of_interest": scd.make_vol4(None, None, 0, 3000,
scd.make_circle(LAT0, LNG0, 50))
})
assert resp.status_code == 200, resp.content
result_ids = [x['id'] for x in resp.json()['subscriptions']]
assert SUB1_ID not in result_ids
assert SUB2_ID in result_ids
assert SUB3_ID not in result_ids
# Preconditions: Subscriptions 1, 2, and 3 created
# Mutations: None
@default_scope(SCOPE_SC)
def test_search_time(scd_session):
time_start = datetime.datetime.utcnow()
time_end = time_start + datetime.timedelta(minutes=1)
resp = scd_session.post(
'/subscriptions/query',
json={
"area_of_interest": scd.make_vol4(time_start, time_end, 0, 3000,
scd.make_circle(LAT0, LNG0, FOOTPRINT_SPACING_M))
})
assert resp.status_code == 200, resp.content
result_ids = [x['id'] for x in resp.json()['subscriptions']]
assert SUB1_ID in result_ids
assert SUB2_ID not in result_ids
assert SUB3_ID not in result_ids
resp = scd_session.post(
'/subscriptions/query',
json={
"area_of_interest": scd.make_vol4(None, time_end, 0, 3000,
scd.make_circle(LAT0, LNG0, FOOTPRINT_SPACING_M))
})
assert resp.status_code == 200, resp.content
result_ids = [x['id'] for x in resp.json()['subscriptions']]
assert SUB1_ID in result_ids
assert SUB2_ID not in result_ids
assert SUB3_ID not in result_ids
time_start = datetime.datetime.utcnow() + datetime.timedelta(hours=4)
time_end = time_start + datetime.timedelta(minutes=1)
resp = scd_session.post(
'/subscriptions/query',
json={
"area_of_interest": scd.make_vol4(time_start, time_end, 0, 3000,
scd.make_circle(LAT0, LNG0, FOOTPRINT_SPACING_M))
})
assert resp.status_code == 200, resp.content
result_ids = [x['id'] for x in resp.json()['subscriptions']]
assert SUB1_ID not in result_ids
assert SUB2_ID not in result_ids
assert SUB3_ID in result_ids
resp = scd_session.post(
'/subscriptions/query',
json={
"area_of_interest": scd.make_vol4(time_start, None, 0, 3000,
scd.make_circle(LAT0, LNG0, FOOTPRINT_SPACING_M))
})
assert resp.status_code == 200, resp.content
result_ids = [x['id'] for x in resp.json()['subscriptions']]
assert SUB1_ID not in result_ids
assert SUB2_ID not in result_ids
assert SUB3_ID in result_ids
# Preconditions: Subscriptions 1, 2, and 3 created
# Mutations: None
@default_scope(SCOPE_SC)
def test_search_time_footprint(scd_session):
time_start = datetime.datetime.utcnow()
time_end = time_start + datetime.timedelta(hours=2.5)
lat = LAT0 + scd.latitude_degrees(FOOTPRINT_SPACING_M)
resp = scd_session.post(
'/subscriptions/query',
json={
"area_of_interest": scd.make_vol4(time_start, time_end, 0, 3000,
scd.make_circle(lat, LNG0, FOOTPRINT_SPACING_M))
})
assert resp.status_code == 200, resp.content
result_ids = [x['id'] for x in resp.json()['subscriptions']]
assert SUB1_ID not in result_ids
assert SUB2_ID in result_ids
assert SUB3_ID not in result_ids
# Preconditions: Subscriptions 1, 2, and 3 created
# Mutations: Subscriptions 1, 2, and 3 deleted
@default_scope(SCOPE_SC)
def test_delete_subs(scd_session):
for sub_id in (SUB1_ID, SUB2_ID, SUB3_ID):
resp = scd_session.delete('/subscriptions/{}'.format(sub_id))
assert resp.status_code == 200, resp.content
| 34.518219 | 108 | 0.700563 | 0 | 0 | 0 | 0 | 5,522 | 0.647666 | 0 | 0 | 1,976 | 0.231762 |
d55558bb3f6a8ea15ddbd66ee162839cfc0d523b | 516 | py | Python | backend/mp/apps/questionnarie/migrations/0002_auto_20200327_1422.py | shidashui/mymp | 75d81906908395ece1c8d12249d6afc4bd2d0704 | [
"MIT"
] | 1 | 2020-03-14T12:33:24.000Z | 2020-03-14T12:33:24.000Z | backend/mp/apps/questionnarie/migrations/0002_auto_20200327_1422.py | shidashui/mymp | 75d81906908395ece1c8d12249d6afc4bd2d0704 | [
"MIT"
] | 8 | 2021-03-19T00:59:11.000Z | 2022-03-12T00:19:38.000Z | backend/mp/apps/questionnarie/migrations/0002_auto_20200327_1422.py | shidashui/mymp | 75d81906908395ece1c8d12249d6afc4bd2d0704 | [
"MIT"
] | null | null | null | # Generated by Django 3.0.4 on 2020-03-27 14:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('questionnarie', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='questionnaire',
name='email',
),
migrations.AddField(
model_name='questionnaire',
name='user_id',
field=models.IntegerField(default=0, verbose_name='用户id'),
),
]
| 22.434783 | 70 | 0.581395 | 427 | 0.821154 | 0 | 0 | 0 | 0 | 0 | 0 | 132 | 0.253846 |
d55583a4f654b4e383a9599f22b9a53cb07d00f4 | 2,250 | py | Python | engine/scene.py | amirgeva/retroupy | 1ee19b36a72c5f592cce150d1d0382a00ccdc4a0 | [
"BSD-3-Clause"
] | null | null | null | engine/scene.py | amirgeva/retroupy | 1ee19b36a72c5f592cce150d1d0382a00ccdc4a0 | [
"BSD-3-Clause"
] | null | null | null | engine/scene.py | amirgeva/retroupy | 1ee19b36a72c5f592cce150d1d0382a00ccdc4a0 | [
"BSD-3-Clause"
] | null | null | null | from .rtree import RTree
from .utils import Point
# EXPORT
class Scene(object):
def __init__(self):
self.entities = {}
self.dynamics = set()
self.statics = set()
self.rtree = RTree()
def add(self, entity):
eid = entity.get_id()
self.entities[eid] = entity
if entity.is_dynamic:
self.dynamics.add(eid)
else:
self.statics.add(eid)
r = entity.get_rect()
# self.rtree.add(eid, r)
def advance(self, dt):
ids = set(self.dynamics) # Copy to allow deletions
for eid in ids:
e = self.entities.get(eid)
before = e.get_rect()
if not e.advance(dt):
# self.rtree.remove(eid)
self.dynamics.remove(eid)
del self.entities[eid]
else:
after = e.get_rect()
if before != after:
self.check_collisions(e, after)
after = e.get_rect()
# self.rtree.move(e.get_id(), after)
def draw(self, view):
# visible = self.rtree.search(view.get_rect())
# vis_id = [v[0] for v in visible]
# ids = [eid for eid in vis_id if eid in self.statics]
# ids.extend([eid for eid in vis_id if eid not in self.statics])
ids = list(self.statics) + list(self.dynamics)
for eid in ids:
e = self.entities.get(eid)
if e:
e.draw(view)
def check_collisions(self, entity, rect):
return
eid = entity.get_id()
spr1 = entity.anim.get_current_sprite()
cands = self.rtree.search(rect)
for (cand_id, cand_rect) in cands:
if cand_id != eid:
cand = self.entities.get(cand_id)
spr2 = cand.anim.get_current_sprite()
offset = cand.get_position() - entity.get_position()
ox = int(offset.x)
oy = int(offset.y)
pt = spr1.mask.overlap(spr2.mask, Point(ox, oy))
if pt:
dx, dy = pt.x, pt.y
entity.collision(cand, Point(dx, dy))
cand.collision(entity, Point(dx - ox, dy - oy))
| 33.58209 | 72 | 0.509333 | 2,188 | 0.972444 | 0 | 0 | 0 | 0 | 0 | 0 | 315 | 0.14 |
d555ba2edd936b2db086f718b541516f58f3e05b | 1,192 | py | Python | tests/test_pages/test_views.py | wilfredinni/merken | f15f168f58e9391fcafeeda7ad17232fffab2a14 | [
"MIT"
] | 5 | 2020-05-06T03:34:07.000Z | 2022-03-25T10:05:30.000Z | tests/test_pages/test_views.py | MaxCodeXTC/merken | 040515e43dcc9bdcf23f51ea15b49b4d2af64964 | [
"MIT"
] | 17 | 2019-08-28T22:10:47.000Z | 2021-06-09T18:19:00.000Z | tests/test_pages/test_views.py | MaxCodeXTC/merken | 040515e43dcc9bdcf23f51ea15b49b4d2af64964 | [
"MIT"
] | 1 | 2020-06-15T08:34:16.000Z | 2020-06-15T08:34:16.000Z | from django.test import TestCase, Client
from django.urls import reverse
from apps.pages.models import Page
class TestPageView(TestCase):
def setUp(self):
self.client = Client()
Page.objects.create(slug="test_slug")
def test_page_GET(self):
url = reverse("page_app:page", args=["test_slug"])
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "merken/pages/page.html")
def test_page_404(self):
url = reverse("page_app:page", args=["wrong_page"])
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
class TestIndexView(TestCase):
def setUp(self):
self.client = Client()
def test_index_GET(self):
Page.objects.create(slug="index")
url = reverse("page_app:index")
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "merken/pages/index.html")
def test_index_404(self):
url = reverse("page_app:index")
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
| 30.564103 | 68 | 0.666946 | 1,077 | 0.903523 | 0 | 0 | 0 | 0 | 0 | 0 | 152 | 0.127517 |
d556e06f516793a26ef5cbe49151f9799ff8daf6 | 1,148 | py | Python | sequal/mass_spectrometry.py | bschulzlab/glypniro | 383429932cda2f6cc8b70be57a954de9b9c0f6d4 | [
"MIT"
] | 1 | 2021-03-08T13:29:17.000Z | 2021-03-08T13:29:17.000Z | sequal/mass_spectrometry.py | bschulzlab/glypniro | 383429932cda2f6cc8b70be57a954de9b9c0f6d4 | [
"MIT"
] | null | null | null | sequal/mass_spectrometry.py | bschulzlab/glypniro | 383429932cda2f6cc8b70be57a954de9b9c0f6d4 | [
"MIT"
] | null | null | null | from sequal.ion import Ion
ax = "ax"
by = "by"
cz = "cz"
# calculate non-labile modifications and yield associated transition
# For example "by" would yield a tuple of "b" and "y" transitions.
def fragment_non_labile(sequence, fragment_type):
for i in range(1, sequence.seq_length, 1):
left = Ion(sequence[:i], fragment_number=i, ion_type=fragment_type[0])
right = Ion(sequence[i:], fragment_number=sequence.seq_length-i, ion_type=fragment_type[1])
yield left, right
# calculate all labile modification variants for the sequence and its associated labile modifications
def fragment_labile(sequence):
fragment_number = 0
for p in sequence.mods:
for i in sequence.mods[p]:
if i.labile:
fragment_number += i.labile_number
return Ion(sequence, fragment_number=fragment_number, ion_type="Y")
class FragmentFactory:
def __init__(self, fragment_type, ignore=None):
self.fragment_type = fragment_type
if ignore:
self.ignore = ignore
else:
self.ignore = []
def set_ignore(self, ignore):
self.ignore = ignore
| 30.210526 | 101 | 0.678571 | 276 | 0.240418 | 301 | 0.262195 | 0 | 0 | 0 | 0 | 250 | 0.21777 |
d55772963e28794e8a087234f1d656d1c4c7b7a0 | 444 | py | Python | scapula/transform/encoded_rt_to_r9.py | fengjixuchui/scapula | 0ca411d8571622a6f7411bf423c3b662030e550b | [
"MIT"
] | 7 | 2019-10-11T17:35:00.000Z | 2020-04-06T00:51:18.000Z | scapula/transform/encoded_rt_to_r9.py | fengjixuchui/scapula | 0ca411d8571622a6f7411bf423c3b662030e550b | [
"MIT"
] | null | null | null | scapula/transform/encoded_rt_to_r9.py | fengjixuchui/scapula | 0ca411d8571622a6f7411bf423c3b662030e550b | [
"MIT"
] | 3 | 2019-10-12T01:51:20.000Z | 2019-11-12T15:15:37.000Z | import shoulder
class EncodedRtToR9(shoulder.transform.abstract_transform.AbstractTransform):
@property
def description(self):
d = "changing src/dest register for encoded accessors from r0 to r9"
return d
def do_transform(self, reg):
for am in reg.access_mechanisms["mrs_register"]:
am.rt = 9
for am in reg.access_mechanisms["msr_register"]:
am.rt = 9
return reg
| 24.666667 | 77 | 0.650901 | 425 | 0.957207 | 0 | 0 | 130 | 0.292793 | 0 | 0 | 92 | 0.207207 |
d557f1cb2328fe8b59c23cb0bcb3af7a0541259f | 1,642 | py | Python | model/user.py | fi-ksi/dashboard-alpha | aaa800d02f78f198a95faf27af2bc8afeca4b867 | [
"MIT"
] | null | null | null | model/user.py | fi-ksi/dashboard-alpha | aaa800d02f78f198a95faf27af2bc8afeca4b867 | [
"MIT"
] | 24 | 2019-05-14T19:13:38.000Z | 2022-03-14T10:51:55.000Z | model/user.py | fi-ksi/dashboard-alpha | aaa800d02f78f198a95faf27af2bc8afeca4b867 | [
"MIT"
] | null | null | null | import datetime
from sqlalchemy import Column, Integer, String, Boolean, Enum, Text, text
from sqlalchemy.types import TIMESTAMP
from sqlalchemy.orm import relationship
from sqlalchemy.ext.hybrid import hybrid_property
from . import Base
class User(Base):
__tablename__ = 'users'
__table_args__ = {
'mysql_engine': 'InnoDB',
'mysql_charset': 'utf8mb4'
}
id = Column(Integer, primary_key=True)
email = Column(String(50), nullable=False, unique=True)
phone = Column(String(15))
first_name = Column(String(50), nullable=False)
nick_name = Column(String(50))
last_name = Column(String(50), nullable=False)
sex = Column(Enum('male', 'female'), nullable=False)
password = Column(String(255), nullable=False)
short_info = Column(Text, nullable=False)
profile_picture = Column(String(255))
role = Column(
Enum('admin', 'org', 'participant', 'participant_hidden', 'tester'),
nullable=False, default='participant', server_default='participant')
enabled = Column(Boolean, nullable=False, default=True, server_default='1')
registered = Column(TIMESTAMP, nullable=False,
default=datetime.datetime.utcnow,
server_default=text('CURRENT_TIMESTAMP'))
@hybrid_property
def name(self):
return self.first_name + ' ' + self.last_name
tasks = relationship('Task', primaryjoin='User.id == Task.author')
evaluations = relationship('Evaluation',
primaryjoin='User.id == Evaluation.user')
def __str__(self):
return self.name
__repr__ = __str__
| 34.208333 | 79 | 0.665043 | 1,399 | 0.85201 | 0 | 0 | 90 | 0.054811 | 0 | 0 | 241 | 0.146772 |
d55801396ba40004f6ae580dd0df2cf475baa674 | 4,999 | py | Python | order.py | bogdanmagometa/logistics-system | 8c69c29f23354c37dddec299eaa7031092430daf | [
"MIT"
] | null | null | null | order.py | bogdanmagometa/logistics-system | 8c69c29f23354c37dddec299eaa7031092430daf | [
"MIT"
] | null | null | null | order.py | bogdanmagometa/logistics-system | 8c69c29f23354c37dddec299eaa7031092430daf | [
"MIT"
] | null | null | null | """
order.py
This module contains classes needed for emulating logistics system. In particular, the following
classes are here:
Item
Vehicle
Order
Location
"""
import copy
from typing import List
class Item:
"""A class used to represent an item for logistics system.
Attributes
----------
name : str
a name of the item, e.g. book, letter, TV, cookie
price : float
the price of an item in UAH
"""
def __init__(self, name: str, price: float) -> None:
"""Initialize Item with name and price (in UAH).
>>> item = Item("phone", 5123.4567)
>>> item.name
'phone'
>>> item.price
5123.4567
"""
self.name = name
self.price = price
def __str__(self) -> str:
"""Return human-readable representation of the order.
>>> item = Item("shoes", 240)
>>> print(item)
shoes
"""
return self.name
class Vehicle:
"""A class user to represent Vehicles for logistics system.
Attributes
----------
vehicle_no : int
number of vehicle
is_available : bool
tells if a vehicle is available for delivering
"""
def __init__(self, vehicle_no: int) -> None:
"""Initialize Vehicle with vehicle number."""
self.vehicle_no = vehicle_no
self.is_available = True
class Order:
"""A class used to represent an order in logistics system.
Attributes
----------
user_name : str
the name of the user who created the order
city : str
the city of destination
postoffice : int
the postoffice number of Ukrposhta in the city
items : list of items
items listed in the order
location : Location
location of destination point
vehicle : Vehicle
vehicle for delivery of the item
"""
num_orders_created = 0
def __init__(self, user_name: str, city: str, postoffice: int, items: List[Item]) -> None:
"""Initialize order with name of user, delivery city, postoffice, and items to deliver.
>>> order = Order("Bohdan", "Stryi", 2,
... [Item('Arduino',120), Item("ESP32-CAM",200), Item("Raspberri Pi Zero",1100)])
Your order number is 0.
>>> isinstance(order.location, Location)
True
>>> order.vehicle
>>> order.user_name
'Bohdan'
>>> order.location.city
'Stryi'
>>> order.location.postoffice
2
>>> all(map(lambda x: isinstance(x, Item), order.items))
True
"""
self.order_id = Order.num_orders_created
self.user_name = user_name
self.location = Location(city, postoffice)
self.items = copy.copy(items)
self.vehicle = None
Order.num_orders_created += 1
print(f"Your order number is {self.order_id}.")
def __str__(self) -> str:
"""Return human-readable represenation of an order.
>>> order = Order("Ivan", "Kyiv", "42", ['computer'])
Your order number is 1.
>>> print(order)
The order #1 by Ivan to city Kyiv, postoffice 42. The item is computer.
"""
text = f"The order #{self.order_id} by {self.user_name} to city {self.location.city}, post\
office {self.location.postoffice}."
if self.items:
text += " The item"
if len(self.items) == 1:
return text + f" is {self.items[0]}."
return text + f"s are {', '.join(map(str, self.items))}."
return text
def calculate_amount(self) -> float:
"""Return total cost of each Item (in UAH).
>>> order = Order("Bohdan", "Stryi", "2",
... [Item('Arduino',120), Item("ESP32-CAM",200),
... Item("Raspberri Pi Zero",1100)]) #doctest: +ELLIPSIS
Your order number is ....
>>> order.calculate_amount()
1420
"""
return sum(item.price for item in self.items)
def assign_vehicle(self, vehicle: Vehicle) -> None:
"""Assign a vehicle to an order.
>>> order = Order("Oksana", "Zhytomyr", 5, [Item("cap", 100)]) #doctest: +ELLIPSIS
Your order number is ....
>>> vehicle = Vehicle(213)
>>> order.assign_vehicle(vehicle)
>>> order.vehicle.vehicle_no
213
"""
self.vehicle = vehicle
class Location:
"""A class used to represent a location in logistics system.
Attributes
----------
city : str
city of the location
postoffice : int
number of postoffice of Ukrposhta in city
"""
def __init__(self, city: str, postoffice: int) -> None:
"""Initialize location with delivery city and postoffice.
>>> location = Location("Nezhukhiv", 1)
>>> location.city
'Nezhukhiv'
>>> location.postoffice
1
"""
self.city = city
self.postoffice = postoffice
if __name__ == "__main__":
import doctest
doctest.testmod()
| 27.927374 | 99 | 0.576715 | 4,719 | 0.943989 | 0 | 0 | 0 | 0 | 0 | 0 | 3,570 | 0.714143 |
d55a7d09487a4d342d812df22a9da92debc35a70 | 28 | py | Python | homeassistant/components/ripple/__init__.py | domwillcode/home-assistant | f170c80bea70c939c098b5c88320a1c789858958 | [
"Apache-2.0"
] | 30,023 | 2016-04-13T10:17:53.000Z | 2020-03-02T12:56:31.000Z | homeassistant/components/ripple/__init__.py | jagadeeshvenkatesh/core | 1bd982668449815fee2105478569f8e4b5670add | [
"Apache-2.0"
] | 31,101 | 2020-03-02T13:00:16.000Z | 2022-03-31T23:57:36.000Z | homeassistant/components/ripple/__init__.py | jagadeeshvenkatesh/core | 1bd982668449815fee2105478569f8e4b5670add | [
"Apache-2.0"
] | 11,956 | 2016-04-13T18:42:31.000Z | 2020-03-02T09:32:12.000Z | """The ripple component."""
| 14 | 27 | 0.642857 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 27 | 0.964286 |
d55a7fec2efd8d806f3e68ef5a593dad286e8eeb | 8,362 | py | Python | synapse/cmds/hive.py | ackroute/synapse | 51197f89ab372d2e357bcd054358352ecca66840 | [
"Apache-2.0"
] | 216 | 2017-01-17T18:52:50.000Z | 2022-03-31T18:44:49.000Z | synapse/cmds/hive.py | ackroute/synapse | 51197f89ab372d2e357bcd054358352ecca66840 | [
"Apache-2.0"
] | 2,189 | 2017-01-17T22:31:48.000Z | 2022-03-31T20:41:45.000Z | synapse/cmds/hive.py | ackroute/synapse | 51197f89ab372d2e357bcd054358352ecca66840 | [
"Apache-2.0"
] | 44 | 2017-01-17T16:50:57.000Z | 2022-03-16T18:35:52.000Z | import os
import json
import shlex
import pprint
import asyncio
import tempfile
import functools
import subprocess
import synapse.exc as s_exc
import synapse.common as s_common
import synapse.lib.cmd as s_cmd
import synapse.lib.cli as s_cli
ListHelp = '''
Lists all the keys underneath a particular key in the hive.
Syntax:
hive ls|list [path]
Notes:
If path is not specified, the root is listed.
'''
GetHelp = '''
Display or save to file the contents of a key in the hive.
Syntax:
hive get [--file] [--json] {path}
'''
DelHelp = '''
Deletes a key in the cell's hive.
Syntax:
hive rm|del {path}
Notes:
Delete will recursively delete all subkeys underneath path if they exist.
'''
EditHelp = '''
Edits or creates a key in the cell's hive.
Syntax:
hive edit|mod {path} [--string] ({value} | --editor | -f {filename})
Notes:
One may specify the value directly on the command line, from a file, or use an editor. For the --editor option,
the environment variable VISUAL or EDITOR must be set.
'''
class HiveCmd(s_cli.Cmd):
'''
Manipulates values in a cell's Hive.
A Hive is a hierarchy persistent storage mechanism typically used for configuration data.
'''
_cmd_name = 'hive'
_cmd_syntax = (
('line', {'type': 'glob'}), # type: ignore
)
def _make_argparser(self):
parser = s_cmd.Parser(prog='hive', outp=self, description=self.__doc__)
subparsers = parser.add_subparsers(title='subcommands', required=True, dest='cmd',
parser_class=functools.partial(s_cmd.Parser, outp=self))
parser_ls = subparsers.add_parser('list', aliases=['ls'], help="List entries in the hive", usage=ListHelp)
parser_ls.add_argument('path', nargs='?', help='Hive path')
parser_get = subparsers.add_parser('get', help="Get any entry in the hive", usage=GetHelp)
parser_get.add_argument('path', help='Hive path')
parser_get.add_argument('-f', '--file', default=False, action='store',
help='Save the data to a file.')
parser_get.add_argument('--json', default=False, action='store_true', help='Emit output as json')
parser_rm = subparsers.add_parser('del', aliases=['rm'], help='Delete a key in the hive', usage=DelHelp)
parser_rm.add_argument('path', help='Hive path')
parser_edit = subparsers.add_parser('edit', aliases=['mod'], help='Sets/creates a key', usage=EditHelp)
parser_edit.add_argument('--string', action='store_true', help="Edit value as a single string")
parser_edit.add_argument('path', help='Hive path')
group = parser_edit.add_mutually_exclusive_group(required=True)
group.add_argument('value', nargs='?', help='Value to set')
group.add_argument('--editor', default=False, action='store_true',
help='Opens an editor to set the value')
group.add_argument('--file', '-f', help='Copies the contents of the file to the path')
return parser
async def runCmdOpts(self, opts):
line = opts.get('line')
if line is None:
self.printf(self.__doc__)
return
core = self.getCmdItem()
try:
opts = self._make_argparser().parse_args(shlex.split(line))
except s_exc.ParserExit:
return
handlers = {
'list': self._handle_ls,
'ls': self._handle_ls,
'del': self._handle_rm,
'rm': self._handle_rm,
'get': self._handle_get,
'edit': self._handle_edit,
'mod': self._handle_edit,
}
await handlers[opts.cmd](core, opts)
@staticmethod
def parsepath(path):
''' Turn a slash-delimited path into a list that hive takes '''
return path.split('/')
async def _handle_ls(self, core, opts):
path = self.parsepath(opts.path) if opts.path is not None else None
keys = await core.listHiveKey(path=path)
if keys is None:
self.printf('Path not found')
return
for key in keys:
self.printf(key)
async def _handle_get(self, core, opts):
path = self.parsepath(opts.path)
valu = await core.getHiveKey(path)
if valu is None:
self.printf(f'{opts.path} not present')
return
if opts.json:
prend = json.dumps(valu, indent=4, sort_keys=True)
rend = prend.encode()
elif isinstance(valu, str):
rend = valu.encode()
prend = valu
elif isinstance(valu, bytes):
rend = valu
prend = pprint.pformat(valu)
else:
rend = json.dumps(valu, indent=4, sort_keys=True).encode()
prend = pprint.pformat(valu)
if opts.file:
with s_common.genfile(opts.file) as fd:
fd.truncate(0)
fd.write(rend)
self.printf(f'Saved the hive entry [{opts.path}] to {opts.file}')
return
self.printf(f'{opts.path}:\n{prend}')
async def _handle_rm(self, core, opts):
path = self.parsepath(opts.path)
await core.popHiveKey(path)
async def _handle_edit(self, core, opts):
path = self.parsepath(opts.path)
if opts.value is not None:
if opts.value[0] not in '([{"':
data = opts.value
else:
data = json.loads(opts.value)
await core.setHiveKey(path, data)
return
elif opts.file is not None:
with open(opts.file) as fh:
s = fh.read()
if len(s) == 0:
self.printf('Empty file. Not writing key.')
return
data = s if opts.string else json.loads(s)
await core.setHiveKey(path, data)
return
editor = os.getenv('VISUAL', (os.getenv('EDITOR', None)))
if editor is None or editor == '':
self.printf('Environment variable VISUAL or EDITOR must be set for --editor')
return
tnam = None
try:
with tempfile.NamedTemporaryFile(mode='w', delete=False) as fh:
old_valu = await core.getHiveKey(path)
if old_valu is not None:
if opts.string:
if not isinstance(old_valu, str):
self.printf('Existing value is not a string, therefore not editable as a string')
return
data = old_valu
else:
try:
data = json.dumps(old_valu, indent=4, sort_keys=True)
except (ValueError, TypeError):
self.printf('Value is not JSON-encodable, therefore not editable.')
return
fh.write(data)
tnam = fh.name
while True:
retn = subprocess.call(f'{editor} {tnam}', shell=True)
if retn != 0: # pragma: no cover
self.printf('Editor failed with non-zero code. Aborting.')
return
with open(tnam) as fh:
rawval = fh.read()
if len(rawval) == 0: # pragma: no cover
self.printf('Empty file. Not writing key.')
return
try:
valu = rawval if opts.string else json.loads(rawval)
except json.JSONDecodeError as e: # pragma: no cover
self.printf(f'JSON decode failure: [{e}]. Reopening.')
await asyncio.sleep(1)
continue
# We lose the tuple/list distinction in the telepath round trip, so tuplify everything to compare
if (opts.string and valu == old_valu) or (not opts.string and s_common.tuplify(valu) == old_valu):
self.printf('Valu not changed. Not writing key.')
return
await core.setHiveKey(path, valu)
break
finally:
if tnam is not None:
os.unlink(tnam)
| 35.2827 | 118 | 0.556565 | 7,321 | 0.875508 | 0 | 0 | 141 | 0.016862 | 5,132 | 0.613729 | 2,218 | 0.265248 |
d55b66f29d249e5be6c857b36e678994e5a67ff0 | 1,888 | py | Python | bfmplot/colortools.py | benmaier/bfmplot | e5af40c8a90862cdb443438f0bd343bb8de5f44c | [
"MIT"
] | 3 | 2020-07-17T15:19:48.000Z | 2020-08-08T23:35:48.000Z | bfmplot/colortools.py | benmaier/bfmplot | e5af40c8a90862cdb443438f0bd343bb8de5f44c | [
"MIT"
] | null | null | null | bfmplot/colortools.py | benmaier/bfmplot | e5af40c8a90862cdb443438f0bd343bb8de5f44c | [
"MIT"
] | 1 | 2020-10-22T12:59:58.000Z | 2020-10-22T12:59:58.000Z | """
Contains methods to convert hex colors to rgb colors
and to brighten/darken colors.
"""
import numpy as np
def h2r(_hex):
"""
Convert a hex string to an RGB-tuple.
"""
if _hex.startswith('#'):
l = _hex[1:]
else:
l = _hex
return [ a/255. for a in bytes.fromhex(l) ]
def r2h(rgb):
"""
Convert an RGB-tuple to a hex string.
"""
return '#%02x%02x%02x' % tuple([ int(a*255) for a in rgb ])
def tohex(color):
"""
Convert any color to its hex string.
"""
if type(color) == str:
if len(color) in (6, 7):
try:
h2r(color)
return color
except:
pass
try:
return hex_colors[color]
except KeyError as e:
raise ValueError("unknown color: '" + color +"'")
elif type(color) in (list, tuple, np.ndarray) and len(color) == 3:
return r2h(color)
else:
raise ValueError("Don't know how to interpret color " + str(color))
def torgb(color):
"""
Convert any color to an rgb tuple.
"""
if type(color) == str:
if len(color) in (6, 7):
try:
return h2r(color)
except:
pass
try:
return colors[color]
except KeyError as e:
raise ValueError("unknown color: '" + str(color) +"'")
elif type(color) in (list, tuple, np.ndarray) and len(color) == 3:
return color
else:
raise ValueError("Don't know how to interpret color " + str(color))
def brighter(rgb,base=2):
"""
Make the color (rgb-tuple) a tad brighter.
"""
_rgb = tuple([ a**(1/base) for a in torgb(rgb) ])
return _rgb
def darker(rgb,base=2):
"""
Make the color (rgb-tuple) a tad darker.
"""
_rgb = tuple([ (a)**base for a in torgb(rgb) ])
return _rgb
| 23.6 | 75 | 0.528072 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 545 | 0.288665 |
d55ba82230322a219b1f4cd74baae15cd90185fa | 13,815 | py | Python | newscout_web/news_site/migrations/0002_auto_20190819_1230.py | rsqwerty/newscout_web | 8be095cc3e1a95d6ccf5cd8c43d3f13746b263f2 | [
"Apache-2.0"
] | 3 | 2019-10-30T07:15:59.000Z | 2021-12-26T20:59:05.000Z | newscout_web/news_site/migrations/0002_auto_20190819_1230.py | rsqwerty/newscout_web | 8be095cc3e1a95d6ccf5cd8c43d3f13746b263f2 | [
"Apache-2.0"
] | 322 | 2019-10-30T07:12:36.000Z | 2022-02-10T10:55:32.000Z | newscout_web/news_site/migrations/0002_auto_20190819_1230.py | rsqwerty/newscout_web | 8be095cc3e1a95d6ccf5cd8c43d3f13746b263f2 | [
"Apache-2.0"
] | 7 | 2019-10-30T13:34:54.000Z | 2021-12-27T12:08:07.000Z | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2019-08-19 12:30
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.auth.validators
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('news_site', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='AdGroup',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Created At')),
('modified_at', models.DateTimeField(auto_now=True, verbose_name='Last Modified At')),
('is_active', models.BooleanField(default=True)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='AdType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Created At')),
('modified_at', models.DateTimeField(auto_now=True, verbose_name='Last Modified At')),
('type', models.CharField(max_length=100)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Advertisement',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Created At')),
('modified_at', models.DateTimeField(auto_now=True, verbose_name='Last Modified At')),
('ad_text', models.CharField(max_length=160)),
('ad_url', models.URLField()),
('media', models.ImageField(blank=True, null=True, upload_to='')),
('is_active', models.BooleanField(default=True)),
('impsn_limit', models.IntegerField(default=0)),
('delivered', models.IntegerField(default=0)),
('click_count', models.IntegerField(default=0)),
('ad_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='news_site.AdType')),
('adgroup', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='news_site.AdGroup')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Campaign',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Created At')),
('modified_at', models.DateTimeField(auto_now=True, verbose_name='Last Modified At')),
('name', models.CharField(max_length=160)),
('is_active', models.BooleanField(default=True)),
('daily_budget', models.DecimalField(blank=True, decimal_places=2, max_digits=8, null=True)),
('max_bid', models.DecimalField(blank=True, decimal_places=2, max_digits=8, null=True)),
('start_date', models.DateTimeField()),
('end_date', models.DateTimeField()),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='CategoryAssociation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('child_cat', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='child_category', to='news_site.Category')),
('parent_cat', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='parent_category', to='news_site.Category')),
],
),
migrations.CreateModel(
name='CategoryDefaultImage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('default_image_url', models.URLField()),
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='news_site.Category')),
],
),
migrations.CreateModel(
name='DailyDigest',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Created At')),
('modified_at', models.DateTimeField(auto_now=True, verbose_name='Last Modified At')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Devices',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('device_name', models.CharField(blank=True, max_length=255, null=True)),
('device_id', models.CharField(blank=True, max_length=255, null=True)),
],
),
migrations.CreateModel(
name='Menu',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='news_site.Category')),
],
),
migrations.CreateModel(
name='Notification',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('breaking_news', models.BooleanField(default=False)),
('daily_edition', models.BooleanField(default=False)),
('personalized', models.BooleanField(default=False)),
('device', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='news_site.Devices')),
],
),
migrations.CreateModel(
name='ScoutedItem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('url', models.URLField(default='http://nowhe.re')),
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='news_site.Category')),
],
),
migrations.CreateModel(
name='ScoutFrontier',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('url', models.URLField(default='http://nowhe.re')),
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='news_site.Category')),
],
),
migrations.CreateModel(
name='SocialAccount',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('provider', models.CharField(max_length=200)),
('social_account_id', models.CharField(max_length=200)),
('image_url', models.CharField(blank=True, max_length=250, null=True)),
],
options={
'verbose_name_plural': 'Social Accounts',
},
),
migrations.CreateModel(
name='SubMenu',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('hash_tags', models.ManyToManyField(to='news_site.HashTag')),
('name', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='news_site.Category')),
],
),
migrations.CreateModel(
name='TrendingArticle',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Created At')),
('modified_at', models.DateTimeField(auto_now=True, verbose_name='Last Modified At')),
('active', models.BooleanField(default=True)),
('score', models.FloatField(default=0.0)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='TrendingHashTag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
],
),
migrations.RemoveField(
model_name='subcategory',
name='category',
),
migrations.RemoveField(
model_name='article',
name='industry',
),
migrations.RemoveField(
model_name='article',
name='sub_category',
),
migrations.AddField(
model_name='article',
name='edited_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='article',
name='edited_on',
field=models.DateTimeField(auto_now=True),
),
migrations.AddField(
model_name='article',
name='indexed_on',
field=models.DateTimeField(default=django.utils.timezone.now),
),
migrations.AddField(
model_name='article',
name='manually_edit',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='article',
name='spam',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='articlemedia',
name='video_url',
field=models.TextField(blank=True, null=True, validators=[django.core.validators.URLValidator()]),
),
migrations.AlterField(
model_name='article',
name='category',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='news_site.Category'),
),
migrations.AlterField(
model_name='article',
name='cover_image',
field=models.TextField(validators=[django.core.validators.URLValidator()]),
),
migrations.AlterField(
model_name='article',
name='source_url',
field=models.TextField(validators=[django.core.validators.URLValidator()]),
),
migrations.AlterField(
model_name='articlemedia',
name='url',
field=models.TextField(blank=True, null=True, validators=[django.core.validators.URLValidator()]),
),
migrations.AlterField(
model_name='userprofile',
name='passion',
field=models.ManyToManyField(blank=True, to='news_site.HashTag'),
),
migrations.AlterField(
model_name='userprofile',
name='username',
field=models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username'),
),
migrations.DeleteModel(
name='Industry',
),
migrations.DeleteModel(
name='SubCategory',
),
migrations.AddField(
model_name='trendingarticle',
name='articles',
field=models.ManyToManyField(to='news_site.Article'),
),
migrations.AddField(
model_name='socialaccount',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='menu',
name='submenu',
field=models.ManyToManyField(to='news_site.SubMenu'),
),
migrations.AddField(
model_name='devices',
name='user',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='dailydigest',
name='articles',
field=models.ManyToManyField(to='news_site.Article'),
),
migrations.AddField(
model_name='dailydigest',
name='device',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='news_site.Devices'),
),
migrations.AddField(
model_name='adgroup',
name='campaign',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='news_site.Campaign'),
),
migrations.AddField(
model_name='adgroup',
name='category',
field=models.ManyToManyField(to='news_site.Category'),
),
]
| 44.708738 | 317 | 0.573941 | 13,494 | 0.976764 | 0 | 0 | 0 | 0 | 0 | 0 | 2,354 | 0.170394 |
d55c43761228c894fc64e5f30843f83b9761d7c9 | 658 | py | Python | Redeye(1.1).py | AkshayraviC09YC47/R3DEY3 | 05c2e47740263b22b5fb0fcc4cff89566a950209 | [
"Apache-2.0"
] | 1 | 2020-07-07T16:18:47.000Z | 2020-07-07T16:18:47.000Z | Redeye(1.1).py | AkshayraviC09YC47/R3DEY3 | 05c2e47740263b22b5fb0fcc4cff89566a950209 | [
"Apache-2.0"
] | null | null | null | Redeye(1.1).py | AkshayraviC09YC47/R3DEY3 | 05c2e47740263b22b5fb0fcc4cff89566a950209 | [
"Apache-2.0"
] | null | null | null | #!usr/bin/env python3
import os
import requests
os.system("clear")
print("""
▒█▀▀█ █▀▀█ ▒█▀▀▄ ░░ ▒█▀▀▀ ▒█░░▒█ █▀▀█
▒█▄▄▀ ░░▀▄ ▒█░▒█ ▀▀ ▒█▀▀▀ ▒█▄▄▄█ ░░▀▄
▒█░▒█ █▄▄█ ▒█▄▄▀ ░░ ▒█▄▄▄ ░░▒█░░ █▄▄█""")
print("<---------Coded By Copycat---------->")
print("")
url = input("[+] Site Name: ")
shell_name = input("[+] Shell Name: ")
while True:
try:
cmd_shell= "?a="
cmd = input("$ ")
payload = (url + "/" +shell_name + cmd_shell + cmd)
r = requests.get(payload)
r.raise_for_status()
print(r.text)
if cmd =="exit":
exit()
except:
print("[!] Something Went Wrong!!")
exit()
| 21.933333 | 59 | 0.416413 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 456 | 0.540284 |
d55cda12da93006ace57b91df18f253f81460e74 | 460 | py | Python | organization/job_urls.py | opendream/asip | 20583aca6393102d425401d55ea32ac6b78be048 | [
"MIT"
] | null | null | null | organization/job_urls.py | opendream/asip | 20583aca6393102d425401d55ea32ac6b78be048 | [
"MIT"
] | 8 | 2020-03-24T17:11:49.000Z | 2022-01-13T01:18:11.000Z | organization/job_urls.py | opendream/asip | 20583aca6393102d425401d55ea32ac6b78be048 | [
"MIT"
] | null | null | null | from django.conf.urls import url, patterns
urlpatterns = patterns('organization.views',
url(r'^organization/(?P<organization_id>\d+)/job/create/$', 'job_create', name='job_create'),
url(r'^job/create/$', 'job_create_standalone', name='job_create_standalone'),
url(r'^job/(?P<job_id>\d+)/edit/$', 'job_edit', name='job_edit'),
url(r'^job/(?P<job_id>\d+)/$', 'job_detail', name='job_detail'),
url(r'^job/$', 'job_list', name='job_list'),
) | 41.818182 | 97 | 0.654348 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 288 | 0.626087 |
d55d9b1686825eb1a58575cb08bd3504ed4c5ca6 | 337 | py | Python | awards/tasks.py | fgmacedo/django-awards | a5307a96f8d39abdd466eb854049dd0f7b13eaee | [
"MIT"
] | null | null | null | awards/tasks.py | fgmacedo/django-awards | a5307a96f8d39abdd466eb854049dd0f7b13eaee | [
"MIT"
] | 305 | 2017-05-16T17:45:58.000Z | 2022-03-18T07:20:22.000Z | awards/tasks.py | fgmacedo/django-awards | a5307a96f8d39abdd466eb854049dd0f7b13eaee | [
"MIT"
] | null | null | null | from celery.task import Task
from ..notifications.contextmanagers import BatchNotifications
class AsyncBadgeAward(Task):
ignore_result = True
def run(self, badge, state, **kwargs):
# from celery.contrib import rdb; rdb.set_trace()
with BatchNotifications():
badge.actually_possibly_award(**state)
| 25.923077 | 62 | 0.712166 | 241 | 0.715134 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 0.145401 |
d55e1d50fdcd5b0ae9b87802278f9d5ea632048b | 5,128 | py | Python | py/desispec/pipeline/tasks/psfnight.py | echaussidon/desispec | 8a8bd59653861509dd630ffc8e1cd6c67f6cdd51 | [
"BSD-3-Clause"
] | 24 | 2015-09-29T06:06:29.000Z | 2022-01-14T07:31:45.000Z | py/desispec/pipeline/tasks/psfnight.py | echaussidon/desispec | 8a8bd59653861509dd630ffc8e1cd6c67f6cdd51 | [
"BSD-3-Clause"
] | 1,452 | 2015-02-26T00:14:23.000Z | 2022-03-31T23:35:10.000Z | py/desispec/pipeline/tasks/psfnight.py | echaussidon/desispec | 8a8bd59653861509dd630ffc8e1cd6c67f6cdd51 | [
"BSD-3-Clause"
] | 25 | 2015-02-06T21:39:13.000Z | 2022-02-22T14:16:31.000Z | #
# See top-level LICENSE.rst file for Copyright information
#
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from collections import OrderedDict
from ..defs import (task_name_sep, task_state_to_int, task_int_to_state)
from ...util import option_list
from ...io import findfile
from .base import (BaseTask, task_classes)
from desiutil.log import get_logger
import sys,re,os,glob
import numpy as np
# NOTE: only one class in this file should have a name that starts with "Task".
class TaskPSFNight(BaseTask):
"""Class containing the properties of one PSF combined night task.
"""
def __init__(self):
super(TaskPSFNight, self).__init__()
# then put int the specifics of this class
# _cols must have a state
self._type = "psfnight"
self._cols = [
"night",
"band",
"spec",
"state"
]
self._coltypes = [
"integer",
"text",
"integer",
"integer"
]
# _name_fields must also be in _cols
self._name_fields = ["night","band","spec"]
self._name_formats = ["08d","s","d"]
def _paths(self, name):
"""See BaseTask.paths.
"""
props = self.name_split(name)
camera = "{}{}".format(props["band"], props["spec"])
return [ findfile("psfnight", night=props["night"],
camera=camera, groupname=None, nside=None, band=props["band"],
spectrograph=props["spec"]) ]
def _deps(self, name, db, inputs):
"""See BaseTask.deps.
"""
return dict()
def _run_max_procs(self):
# This is a serial task.
return 1
def _run_time(self, name, procs, db):
# Run time on one proc on machine with scale factor == 1.0
return 2.0
def _run_defaults(self):
"""See BaseTask.run_defaults.
"""
return {}
def _option_dict(self, name, opts):
"""Build the full list of options.
This includes appending the filenames and incorporating runtime
options.
"""
from .base import task_classes, task_type
options = OrderedDict()
options["output"] = self.paths(name)[0]
# look for psf for this night on disk
options["input"] = []
props = self.name_split(name)
camera = "{}{}".format(props["band"], props["spec"])
dummy_expid = 99999999
template_input = findfile("psf", night=props["night"], expid=dummy_expid,
camera=camera,
band=props["band"],
spectrograph=props["spec"])
template_input = template_input.replace("{:08d}".format(dummy_expid),"????????")
options["input"] = glob.glob(template_input)
return options
def _option_list(self, name, opts):
"""Build the full list of options.
This includes appending the filenames and incorporating runtime
options.
"""
return option_list(self._option_dict(name,opts))
def _run_cli(self, name, opts, procs, db):
"""See BaseTask.run_cli.
"""
optlist = self._option_list(name, opts)
com = "# command line for psfnight not implemented"
return com
def _run(self, name, opts, comm, db):
"""See BaseTask.run.
"""
from ...scripts import specex
optdict = self._option_dict(name, opts)
specex.mean_psf(optdict["input"], optdict["output"])
return
def getready(self, db, name, cur):
"""Checks whether dependencies are ready"""
log = get_logger()
# look for the state of psf with same night,band,spectro
props = self.name_split(name)
cmd = "select state from psf where night={} and band='{}' and spec={}".format(props["night"],props["band"],props["spec"])
cur.execute(cmd)
states = np.array([ x for (x,) in cur.fetchall() ])
log.debug("states={}".format(states))
# psfnight ready if all psf from the night have been processed, and at least one is done (failures are allowed)
n_done = np.sum(states==task_state_to_int["done"])
n_failed = np.sum(states==task_state_to_int["failed"])
ready = (n_done > 0) & ( (n_done + n_failed) == states.size )
if ready :
self.state_set(db=db,name=name,state="ready",cur=cur)
def postprocessing(self, db, name, cur):
"""For successful runs, postprocessing on DB"""
# run getready for all extraction with same night,band,spec
props = self.name_split(name)
log = get_logger()
tt = "traceshift"
cmd = "select name from {} where night={} and band='{}' and spec={} and state=0".format(tt,props["night"],props["band"],props["spec"])
cur.execute(cmd)
tasks = [ x for (x,) in cur.fetchall() ]
log.debug("checking {}".format(tasks))
for task in tasks :
task_classes[tt].getready( db=db,name=task,cur=cur)
| 32.66242 | 142 | 0.582878 | 4,596 | 0.896256 | 0 | 0 | 0 | 0 | 0 | 0 | 1,743 | 0.339899 |
d55eab7fd5f16ed25a0e81651ee54d23764c963e | 150 | py | Python | octopus/config/NEO_EXPLORER.py | ZarvisD/octopus | 3e238721fccfec69a69a1635b8a0dc485e525e69 | [
"MIT"
] | 2 | 2019-01-19T07:12:02.000Z | 2021-08-14T13:23:37.000Z | octopus/config/NEO_EXPLORER.py | ZarvisD/octopus | 3e238721fccfec69a69a1635b8a0dc485e525e69 | [
"MIT"
] | null | null | null | octopus/config/NEO_EXPLORER.py | ZarvisD/octopus | 3e238721fccfec69a69a1635b8a0dc485e525e69 | [
"MIT"
] | 1 | 2019-01-19T07:12:05.000Z | 2019-01-19T07:12:05.000Z | NEO_HOST = "seed3.neo.org"
MAINNET_HTTP_RPC_PORT = 10332
MAINNET_HTTPS_RPC_PORT = 10331
TESTNET_HTTP_RPC_PORT = 20332
TESTNET_HTTPS_RPC_PORT = 20331
| 21.428571 | 30 | 0.833333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 0.1 |
d55ecdd36992a28fb470a18a8005d9df4ba25380 | 1,141 | py | Python | Project_Euler/10_sum_primes_2000000/find_sum.py | perlygatekeeper/glowing-robot | 7ef5eb089f552a1de309092606c95e805e6723a0 | [
"Artistic-2.0"
] | 2 | 2015-06-05T15:40:06.000Z | 2020-03-19T17:08:37.000Z | Project_Euler/10_sum_primes_2000000/find_sum.py | perlygatekeeper/glowing-robot | 7ef5eb089f552a1de309092606c95e805e6723a0 | [
"Artistic-2.0"
] | null | null | null | Project_Euler/10_sum_primes_2000000/find_sum.py | perlygatekeeper/glowing-robot | 7ef5eb089f552a1de309092606c95e805e6723a0 | [
"Artistic-2.0"
] | null | null | null | #!/opt/local/bin/python
import timeit
import time
import sys
def sieveOfSundaram(n=1000):
# this version returns a dictionary for quick lookup of primes <= n
# this version returns a list for easy identification of nth prime
k = int(( n - 2 ) / 2 )
a = [0] * ( k + 1 )
# primes = {}
primes = []
the_sum = 0
for i in range( 1, k + 1):
# if i%1000000 == 0:
# print("one million processed")
j = i
while(( i + j + 2 * i * j ) <= k):
a[ i + j + 2 * i * j ] = 1
j+=1
sequence = 0
if n > 2:
# primes[2] = sequence
primes.append(2)
the_sum += 2
for i in range(1, k + 1):
if a[i] == 0:
sequence += 1
# primes[2+i+1] = sequence
primes.append( (2*i + 1 ))
the_sum += (2*i + 1)
return ( the_sum, primes )
limit = 2000000
print("Finding sum of primes below %d" % (limit))
start_time = timeit.default_timer()
(the_sum, primes) = sieveOfSundaram(limit)
print("the sum is %d" % ( the_sum ) ) # primes list indexed starting with 0
print(timeit.default_timer() - start_time)
| 27.166667 | 75 | 0.534619 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 387 | 0.339176 |
d561a4358751853a43b858854e0ddacafff4f534 | 1,895 | py | Python | public/images/articles/automate-your-style/graph.py | twolfson/twolfson.com | f7a76784f97e1bac3fe2e09815f2b5d76dda3239 | [
"MIT"
] | 10 | 2015-01-08T15:36:18.000Z | 2020-09-26T13:46:32.000Z | public/images/articles/automate-your-style/graph.py | twolfson/twolfson.com | f7a76784f97e1bac3fe2e09815f2b5d76dda3239 | [
"MIT"
] | 14 | 2015-09-28T08:25:07.000Z | 2016-11-02T06:21:34.000Z | public/images/articles/automate-your-style/graph.py | twolfson/twolfson.com | f7a76784f97e1bac3fe2e09815f2b5d76dda3239 | [
"MIT"
] | 3 | 2016-01-16T15:56:20.000Z | 2017-07-23T12:58:39.000Z | # Load in our dependencies
# Forking from http://matplotlib.org/xkcd/examples/showcase/xkcd.html
from matplotlib import pyplot
import numpy
"""
Comments on PRs about style
20 | --------\
| |
| |
| |
| |
1 | \--\
0 | -------
-----------------------
|
Introduction of `jscs`
Time
"""
def main():
"""Generate and save an image as per the docstring above"""
# Define our style as XKCD
pyplot.xkcd()
# Start a new graph
dpi = 72
fig = pyplot.figure(1, figsize=(600 / dpi, 400 / dpi))
# Add labels and a title
pyplot.xlabel('Time')
pyplot.title('Comments on PRs about style')
# Define our axes and limits
# http://matplotlib.org/xkcd/api/pyplot_api.html#matplotlib.pyplot.subplot
ax = fig.add_subplot(1, 1, 1) # cols, rows, plot number
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
pyplot.xticks([])
pyplot.yticks([0, 20])
ax.set_ylim([-1, 25])
# Hide right side of ticks
# http://stackoverflow.com/questions/9051494/customizing-just-one-side-of-tick-marks-in-matplotlib-using-spines
# http://matplotlib.org/api/axis_api.html
ax.yaxis.set_ticks_position('none')
# Generate 100 nodes for our graph and draw them
# http://wiki.scipy.org/Numpy_Example_List#fill
data = numpy.zeros(100)
data.fill(20)
inflection_point = 50
data[inflection_point:inflection_point+10] = numpy.arange(20, 0, -2)
data[inflection_point+10:] = numpy.zeros(100 - (inflection_point + 10))
pyplot.plot(data)
# Add our annotation
pyplot.annotate(
'Introduction of `jscs`',
xy=(inflection_point, 20), arrowprops=dict(arrowstyle='->'), xytext=(10, 15))
# Save the image
pyplot.savefig('graph.png', dpi=dpi)
if __name__ == '__main__':
main()
| 27.071429 | 115 | 0.608443 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,017 | 0.536675 |
d56289df74f4674cf5abeb1309158e1e0a013342 | 457 | py | Python | class1/class_1_yaml.py | daveg999/Automation_class | d23652ecae56b790684971dda6e85a1d2367e22b | [
"Apache-2.0"
] | null | null | null | class1/class_1_yaml.py | daveg999/Automation_class | d23652ecae56b790684971dda6e85a1d2367e22b | [
"Apache-2.0"
] | null | null | null | class1/class_1_yaml.py | daveg999/Automation_class | d23652ecae56b790684971dda6e85a1d2367e22b | [
"Apache-2.0"
] | null | null | null | import yaml
import json
yaml_list = range(5)
yaml_list.append('string1')
yaml_list.append('string2')
yaml_list.append({})
yaml_list[-1]
{}
yaml_list[-1]['critter1'] = 'hedgehog'
yaml_list[-1]['critter2'] = 'bunny'
yaml_list[-1]['dungeon_levels'] = range(5)
yaml_list.append('list_end')
with open("class1_list.yml", "w") as f:
f.write(yaml.dump(yaml_list, default_flow_style=False))
with open("class1_list.json", "w") as f:
json.dump(yaml_list, f)
| 21.761905 | 57 | 0.706783 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 122 | 0.266958 |
d564cb51b33bc55213dfe9dbf9c99c0386c1608f | 402 | py | Python | ch05/first.n.squares.manual.method.py | ibiscum/Learn-Python-Programming-Third-Edition | c8e0061e97b16c9b55250cc720a8bc7613cb6cca | [
"MIT"
] | null | null | null | ch05/first.n.squares.manual.method.py | ibiscum/Learn-Python-Programming-Third-Edition | c8e0061e97b16c9b55250cc720a8bc7613cb6cca | [
"MIT"
] | null | null | null | ch05/first.n.squares.manual.method.py | ibiscum/Learn-Python-Programming-Third-Edition | c8e0061e97b16c9b55250cc720a8bc7613cb6cca | [
"MIT"
] | null | null | null | # first.n.squares.manual.method.py
def get_squares_gen(n):
for x in range(n):
yield x ** 2
squares = get_squares_gen(3)
print(squares.__next__()) # prints: 0
print(squares.__next__()) # prints: 1
print(squares.__next__()) # prints: 4
# the following raises StopIteration, the generator is exhausted,
# any further call to next will keep raising StopIteration
print(squares.__next__())
| 28.714286 | 65 | 0.723881 | 0 | 0 | 67 | 0.166667 | 0 | 0 | 0 | 0 | 190 | 0.472637 |
d5675b3789a7238a94e6d0ec1c781776af8848b8 | 3,737 | py | Python | products/admin.py | silver-whale-enterprises-llc/amzproduzer | 25e63f64b0ef09241475c72af9a710dcb7d9e926 | [
"Apache-2.0"
] | 1 | 2019-07-22T14:03:11.000Z | 2019-07-22T14:03:11.000Z | products/admin.py | silver-whale-enterprises-llc/amzproduzer | 25e63f64b0ef09241475c72af9a710dcb7d9e926 | [
"Apache-2.0"
] | null | null | null | products/admin.py | silver-whale-enterprises-llc/amzproduzer | 25e63f64b0ef09241475c72af9a710dcb7d9e926 | [
"Apache-2.0"
] | null | null | null | import csv
from django.contrib import admin
from django.forms import ModelForm
from django.http import HttpRequest
from products.models import AmazonCategory, AmazonProductListing
from products.tasks import process_inventory_upload
from products.utils import find_price_col_index, save_status, find_identifier_col_index, create_or_update_product
from .models import Supplier, Product, InventoryUpload
class InventoryUploadAdmin(admin.ModelAdmin):
list_display = ('id', 'file', 'supplier', 'total_products', 'progress', 'status', 'failed_analysis_reason')
fieldsets = [
(None, {'fields': ['supplier', 'file']}),
('File Info', {'fields': ['price_col', 'identifier_col', 'identifier_type']}),
]
def progress(self, instance: InventoryUpload):
return instance.progress
def save_model(self, request: HttpRequest, obj: InventoryUpload, form: ModelForm, change: bool):
super().save_model(request, obj, form, change)
if change:
return
try:
with open(obj.file.name, "r") as read_file:
reader = csv.reader(read_file, delimiter=',')
header = next(reader)
price_col = find_price_col_index(obj, header)
if price_col < 0 or price_col >= len(header):
save_status(obj, InventoryUpload.FAILED,
f'Price column value "{obj.price_col}" not found in file!')
return
identifier_col = find_identifier_col_index(obj, header)
if identifier_col < 0 or identifier_col >= len(header):
save_status(obj, InventoryUpload.FAILED,
f'Identifier column value "{obj.identifier_col}" not found in file!')
return
for line_no, line in enumerate(list(reader)):
if line_no == 0:
pass # skip header
create_or_update_product(obj, line, price_col, identifier_col)
obj.total_products = obj.products.all().count()
if obj.total_products <= 1:
save_status(obj, InventoryUpload.FAILED, 'File is empty. No products found!')
else:
obj.save()
except Exception as e:
save_status(obj, InventoryUpload.FAILED, str(e))
process_inventory_upload.delay(obj.id)
class ProductAdmin(admin.ModelAdmin):
list_display = (
'upc',
'name',
'supplier',
'status',
'failed_analysis_reason'
)
list_filter = ('supplier__name', 'status')
class AmazonProductListingAdmin(admin.ModelAdmin):
list_display = (
'asin',
'name',
'profit',
'roi',
'three_month_supply_cost',
'three_month_supply_amount',
'sales_estimate_current',
'review_count',
'sold_by_amazon',
'total_cost',
'buy_box',
'buy_box_avg90',
'buy_box_min',
'buy_box_max',
'fba_sellers_count',
'review_count_last30',
'review_count_avg90',
'sales_rank',
'sales_rank_avg90',
'root_category',
)
list_filter = ('sold_by_amazon',)
class AmazonCategoryAdmin(admin.ModelAdmin):
list_display = (
'name',
'category_id',
'products_count',
'highest_rank',
)
list_filter = ('sales_rank__name',)
admin.site.register(Supplier)
admin.site.register(Product, ProductAdmin)
admin.site.register(InventoryUpload, InventoryUploadAdmin)
admin.site.register(AmazonCategory, AmazonCategoryAdmin)
admin.site.register(AmazonProductListing, AmazonProductListingAdmin)
| 32.780702 | 113 | 0.613059 | 3,062 | 0.819374 | 0 | 0 | 0 | 0 | 0 | 0 | 803 | 0.214878 |
d56a6b6cc928e92831ff43c629863b6b344a0193 | 614 | py | Python | examples/bintree.py | jdrprod/Pym-s | e68dfb840bd36fe60cda02de3b96762e9138071a | [
"MIT"
] | 3 | 2019-08-16T20:54:09.000Z | 2020-04-26T02:43:57.000Z | examples/bintree.py | jdrprod/Pym-s | e68dfb840bd36fe60cda02de3b96762e9138071a | [
"MIT"
] | null | null | null | examples/bintree.py | jdrprod/Pym-s | e68dfb840bd36fe60cda02de3b96762e9138071a | [
"MIT"
] | null | null | null | class binary_tree:
def __init__(self):
pass
class Node(binary_tree):
__field_0 : int
__field_1 : binary_tree
__field_2 : binary_tree
def __init__(self, arg_0 : int , arg_1 : binary_tree , arg_2 : binary_tree ):
self.__field_0 = arg_0
self.__field_1 = arg_1
self.__field_2 = arg_2
def __iter__(self):
yield self.__field_0
yield self.__field_1
yield self.__field_2
class Leaf(binary_tree):
__field_0 : int
def __init__(self, arg_0 : int ):
self.__field_0 = arg_0
def __iter__(self):
yield self.__field_0
| 24.56 | 81 | 0.636808 | 608 | 0.990228 | 154 | 0.250814 | 0 | 0 | 0 | 0 | 0 | 0 |
d56af4bb09c9819923a740a48a9336b6c5056a35 | 42 | py | Python | python_module/sirius/utils/exceptions.py | mtaillefumier/SIRIUS | 50ec1c202c019113c5660f1966b170dec9dfd4d4 | [
"BSD-2-Clause"
] | 77 | 2016-03-18T08:38:30.000Z | 2022-03-11T14:06:25.000Z | python_module/sirius/utils/exceptions.py | simonpintarelli/SIRIUS | f4b5c4810af2a3ea1e67992d65750535227da84b | [
"BSD-2-Clause"
] | 240 | 2016-04-12T16:39:11.000Z | 2022-03-31T08:46:12.000Z | python_module/sirius/utils/exceptions.py | simonpintarelli/SIRIUS | f4b5c4810af2a3ea1e67992d65750535227da84b | [
"BSD-2-Clause"
] | 43 | 2016-03-18T17:45:07.000Z | 2022-02-28T05:27:59.000Z | class NotEnoughBands(Exception):
pass
| 14 | 32 | 0.761905 | 41 | 0.97619 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
d56fd836050b26c8b6384555a79574597fcc5e6a | 197 | py | Python | pyCLI/main.py | tillstud/spotirss | 407dbdcc1e625527fec041bd07a19bf4ac456817 | [
"MIT"
] | null | null | null | pyCLI/main.py | tillstud/spotirss | 407dbdcc1e625527fec041bd07a19bf4ac456817 | [
"MIT"
] | null | null | null | pyCLI/main.py | tillstud/spotirss | 407dbdcc1e625527fec041bd07a19bf4ac456817 | [
"MIT"
] | null | null | null | from pyCLI.config import Config
from pyCLI.logging import logger
def main(config: Config):
print(config.pycli_message)
logger.debug("If you enter 'pyCLI -v', you will see this message!")
| 24.625 | 71 | 0.741117 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 53 | 0.269036 |
d572ea68caef2b7338a29025f406b9ba5ae03a5f | 3,164 | py | Python | tests/Output/__init__.py | FreekDS/git-ci-analyzer | 33e179ea2e569a9df3aefee40b96e5ff6d70da1f | [
"MIT"
] | 1 | 2022-01-16T16:18:59.000Z | 2022-01-16T16:18:59.000Z | tests/Output/__init__.py | FreekDS/git-ci-analyzer | 33e179ea2e569a9df3aefee40b96e5ff6d70da1f | [
"MIT"
] | null | null | null | tests/Output/__init__.py | FreekDS/git-ci-analyzer | 33e179ea2e569a9df3aefee40b96e5ff6d70da1f | [
"MIT"
] | null | null | null | import pytest
from analyzer.config import LATE_MERGING, SKIP_FAILING_TESTS, SLOW_BUILD, BROKEN_RELEASE
@pytest.fixture(scope='module')
def antipattern_data_hd():
"""
Happy day antipattern data
:return: happy day antipattern data
"""
return {
LATE_MERGING: {},
SKIP_FAILING_TESTS: {},
SLOW_BUILD: {},
BROKEN_RELEASE: {}
}
@pytest.fixture(scope='module')
def late_merging_data_hd(antipattern_data_hd):
antipattern_data_hd[LATE_MERGING] = {
'missed activity': {
'branch1': 0,
'branch2': 58748,
'branch3': -1,
'branch4': 1,
'branch5': -20
},
'branch deviation': {
'branch1': 0,
'branch2': 20,
'branch3': 30,
'branch4': 5,
'branch5': 1000
},
'unsynced activity': {
'branch1': 0,
'branch2': 20,
'branch3': 30,
'branch4': 5,
'branch5': 1000
},
'classification': {
'missed activity': {
'medium_severity': ['branch5'],
'high_severity': ['branch2']
},
'branch deviation': {
'medium_severity': ['branch5'],
'high_severity': ['branch2']
},
'unsynced activity': {
'medium_severity': ['branch5'],
'high_severity': ['branch2']
}
}
}
return antipattern_data_hd
@pytest.fixture(scope='module')
def slow_build_hd(antipattern_data_hd):
antipattern_data_hd[SLOW_BUILD] = {
'wf1': {
'data': {
"2021-03-17T20:05:17Z": 54879.0,
"2022-03-17T20:05:17Z": 17.0,
None: -1
},
'tool': "some_tool",
'total avg': 50
},
'wf2': {
'data': {
"2021-03-17T20:05:17Z": 54879.0,
"2022-03-17T20:05:17Z": 17.0,
},
'tool': "some_other_tool",
'total avg': 50
}
}
return antipattern_data_hd
@pytest.fixture(scope='module')
def broken_release_hd(antipattern_data_hd):
antipattern_data_hd[BROKEN_RELEASE] = {
'wf1': {
'data': [
{
'started_at': "2021-03-17T20:05:17Z"
},
{
'started_at': "2021-03-17T20:05:45Z"
}
],
'tool': 'some_tool'
},
'wf2': {
'data': [
{
'started_at': "2021-03-17T20:05:17Z"
},
{
'started_at': "2021-03-17T20:05:45Z"
}
],
'tool': 'some_tool'
},
'wf3': {'not-correct': True}
}
return antipattern_data_hd
@pytest.fixture(scope='module')
def late_merging_data_some_missing(late_merging_data_hd):
del late_merging_data_hd[LATE_MERGING]['classification']
del late_merging_data_hd[LATE_MERGING]['branch deviation']
return late_merging_data_hd
| 26.366667 | 88 | 0.469343 | 0 | 0 | 0 | 0 | 3,046 | 0.962705 | 0 | 0 | 947 | 0.299305 |
d574fc52182f76e129c8ec44d9cbcfde16ecf130 | 513 | py | Python | app/apps/taskker/migrations/0013_auto_20200703_1530.py | calinbule/taskker | 0dbe5a238c9ca231abd7c9a78931fd0c6523453d | [
"MIT"
] | null | null | null | app/apps/taskker/migrations/0013_auto_20200703_1530.py | calinbule/taskker | 0dbe5a238c9ca231abd7c9a78931fd0c6523453d | [
"MIT"
] | 3 | 2021-06-04T23:32:25.000Z | 2021-09-22T19:21:20.000Z | app/apps/taskker/migrations/0013_auto_20200703_1530.py | calinbule/taskker | 0dbe5a238c9ca231abd7c9a78931fd0c6523453d | [
"MIT"
] | null | null | null | # Generated by Django 3.0.7 on 2020-07-03 15:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('taskker', '0012_auto_20200703_1529'),
]
operations = [
migrations.AlterField(
model_name='task',
name='priority',
field=models.TextField(choices=[('danger-dark', 'p1'), ('warning-dark', 'p2'), ('info-dark', 'p3'), ('black', 'no priority')], default='no priority', max_length=20),
),
]
| 27 | 177 | 0.594542 | 420 | 0.818713 | 0 | 0 | 0 | 0 | 0 | 0 | 180 | 0.350877 |
d57698c6c78a214bdc3e21206cf0cac8e0f389e4 | 21,498 | py | Python | fhir/resources/specimendefinition.py | chgl/fhir.resources | 35b22314642640c0b25960ab5b2855e7c51749ef | [
"BSD-3-Clause"
] | null | null | null | fhir/resources/specimendefinition.py | chgl/fhir.resources | 35b22314642640c0b25960ab5b2855e7c51749ef | [
"BSD-3-Clause"
] | null | null | null | fhir/resources/specimendefinition.py | chgl/fhir.resources | 35b22314642640c0b25960ab5b2855e7c51749ef | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Profile: http://hl7.org/fhir/StructureDefinition/SpecimenDefinition
Release: R4
Version: 4.0.1
Build ID: 9346c8cc45
Last updated: 2019-11-01T09:29:23.356+11:00
"""
import typing
from pydantic import Field, root_validator
from pydantic.error_wrappers import ErrorWrapper, ValidationError
from pydantic.errors import MissingError, NoneIsNotAllowedError
from . import backboneelement, domainresource, fhirtypes
class SpecimenDefinition(domainresource.DomainResource):
"""Disclaimer: Any field name ends with ``__ext`` does't part of
Resource StructureDefinition, instead used to enable Extensibility feature
for FHIR Primitive Data Types.
Kind of specimen.
A kind of specimen with associated set of requirements.
"""
resource_type = Field("SpecimenDefinition", const=True)
collection: typing.List[fhirtypes.CodeableConceptType] = Field(
None,
alias="collection",
title="Specimen collection procedure",
description="The action to be performed for collecting the specimen.",
# if property is element of this resource.
element_property=True,
)
identifier: fhirtypes.IdentifierType = Field(
None,
alias="identifier",
title="Business identifier of a kind of specimen",
description="A business identifier associated with the kind of specimen.",
# if property is element of this resource.
element_property=True,
)
patientPreparation: typing.List[fhirtypes.CodeableConceptType] = Field(
None,
alias="patientPreparation",
title="Patient preparation for collection",
description="Preparation of the patient for specimen collection.",
# if property is element of this resource.
element_property=True,
)
timeAspect: fhirtypes.String = Field(
None,
alias="timeAspect",
title="Time aspect for collection",
description="Time aspect of specimen collection (duration or offset).",
# if property is element of this resource.
element_property=True,
)
timeAspect__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
None, alias="_timeAspect", title="Extension field for ``timeAspect``."
)
typeCollected: fhirtypes.CodeableConceptType = Field(
None,
alias="typeCollected",
title="Kind of material to collect",
description="The kind of material to be collected.",
# if property is element of this resource.
element_property=True,
)
typeTested: typing.List[fhirtypes.SpecimenDefinitionTypeTestedType] = Field(
None,
alias="typeTested",
title="Specimen in container intended for testing by lab",
description=(
"Specimen conditioned in a container as expected by the testing "
"laboratory."
),
# if property is element of this resource.
element_property=True,
)
class SpecimenDefinitionTypeTested(backboneelement.BackboneElement):
"""Disclaimer: Any field name ends with ``__ext`` does't part of
Resource StructureDefinition, instead used to enable Extensibility feature
for FHIR Primitive Data Types.
Specimen in container intended for testing by lab.
Specimen conditioned in a container as expected by the testing laboratory.
"""
resource_type = Field("SpecimenDefinitionTypeTested", const=True)
container: fhirtypes.SpecimenDefinitionTypeTestedContainerType = Field(
None,
alias="container",
title="The specimen's container",
description=None,
# if property is element of this resource.
element_property=True,
)
handling: typing.List[fhirtypes.SpecimenDefinitionTypeTestedHandlingType] = Field(
None,
alias="handling",
title="Specimen handling before testing",
description=(
"Set of instructions for preservation/transport of the specimen at a "
"defined temperature interval, prior the testing process."
),
# if property is element of this resource.
element_property=True,
)
isDerived: bool = Field(
None,
alias="isDerived",
title="Primary or secondary specimen",
description="Primary of secondary specimen.",
# if property is element of this resource.
element_property=True,
)
isDerived__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
None, alias="_isDerived", title="Extension field for ``isDerived``."
)
preference: fhirtypes.Code = Field(
None,
alias="preference",
title="preferred | alternate",
description="The preference for this type of conditioned specimen.",
# if property is element of this resource.
element_property=True,
element_required=True,
# note: Enum values can be used in validation,
# but use in your own responsibilities, read official FHIR documentation.
enum_values=["preferred", "alternate"],
)
preference__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
None, alias="_preference", title="Extension field for ``preference``."
)
rejectionCriterion: typing.List[fhirtypes.CodeableConceptType] = Field(
None,
alias="rejectionCriterion",
title="Rejection criterion",
description=(
"Criterion for rejection of the specimen in its container by the "
"laboratory."
),
# if property is element of this resource.
element_property=True,
)
requirement: fhirtypes.String = Field(
None,
alias="requirement",
title="Specimen requirements",
description=(
"Requirements for delivery and special handling of this kind of "
"conditioned specimen."
),
# if property is element of this resource.
element_property=True,
)
requirement__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
None, alias="_requirement", title="Extension field for ``requirement``."
)
retentionTime: fhirtypes.DurationType = Field(
None,
alias="retentionTime",
title="Specimen retention time",
description=(
"The usual time that a specimen of this kind is retained after the "
"ordered tests are completed, for the purpose of additional testing."
),
# if property is element of this resource.
element_property=True,
)
type: fhirtypes.CodeableConceptType = Field(
None,
alias="type",
title="Type of intended specimen",
description="The kind of specimen conditioned for testing expected by lab.",
# if property is element of this resource.
element_property=True,
)
@root_validator(pre=True, allow_reuse=True)
def validate_required_primitive_elements_3071(
cls, values: typing.Dict[str, typing.Any]
) -> typing.Dict[str, typing.Any]:
"""https://www.hl7.org/fhir/extensibility.html#Special-Case
In some cases, implementers might find that they do not have appropriate data for
an element with minimum cardinality = 1. In this case, the element must be present,
but unless the resource or a profile on it has made the actual value of the primitive
data type mandatory, it is possible to provide an extension that explains why
the primitive value is not present.
"""
required_fields = [("preference", "preference__ext")]
_missing = object()
def _fallback():
return ""
errors: typing.List["ErrorWrapper"] = []
for name, ext in required_fields:
field = cls.__fields__[name]
ext_field = cls.__fields__[ext]
value = values.get(field.alias, _missing)
if value not in (_missing, None):
continue
ext_value = values.get(ext_field.alias, _missing)
missing_ext = True
if ext_value not in (_missing, None):
if isinstance(ext_value, dict):
missing_ext = len(ext_value.get("extension", [])) == 0
elif (
getattr(ext_value.__class__, "get_resource_type", _fallback)()
== "FHIRPrimitiveExtension"
):
if ext_value.extension and len(ext_value.extension) > 0:
missing_ext = False
else:
validate_pass = True
for validator in ext_field.type_.__get_validators__():
try:
ext_value = validator(v=ext_value)
except ValidationError as exc:
errors.append(ErrorWrapper(exc, loc=ext_field.alias))
validate_pass = False
if not validate_pass:
continue
if ext_value.extension and len(ext_value.extension) > 0:
missing_ext = False
if missing_ext:
if value is _missing:
errors.append(ErrorWrapper(MissingError(), loc=field.alias))
else:
errors.append(
ErrorWrapper(NoneIsNotAllowedError(), loc=field.alias)
)
if len(errors) > 0:
raise ValidationError(errors, cls) # type: ignore
return values
class SpecimenDefinitionTypeTestedContainer(backboneelement.BackboneElement):
"""Disclaimer: Any field name ends with ``__ext`` does't part of
Resource StructureDefinition, instead used to enable Extensibility feature
for FHIR Primitive Data Types.
The specimen's container.
"""
resource_type = Field("SpecimenDefinitionTypeTestedContainer", const=True)
additive: typing.List[
fhirtypes.SpecimenDefinitionTypeTestedContainerAdditiveType
] = Field(
None,
alias="additive",
title="Additive associated with container",
description=(
"Substance introduced in the kind of container to preserve, maintain or"
" enhance the specimen. Examples: Formalin, Citrate, EDTA."
),
# if property is element of this resource.
element_property=True,
)
cap: fhirtypes.CodeableConceptType = Field(
None,
alias="cap",
title="Color of container cap",
description=None,
# if property is element of this resource.
element_property=True,
)
capacity: fhirtypes.QuantityType = Field(
None,
alias="capacity",
title="Container capacity",
description="The capacity (volume or other measure) of this kind of container.",
# if property is element of this resource.
element_property=True,
)
description: fhirtypes.String = Field(
None,
alias="description",
title="Container description",
description="The textual description of the kind of container.",
# if property is element of this resource.
element_property=True,
)
description__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
None, alias="_description", title="Extension field for ``description``."
)
material: fhirtypes.CodeableConceptType = Field(
None,
alias="material",
title="Container material",
description="The type of material of the container.",
# if property is element of this resource.
element_property=True,
)
minimumVolumeQuantity: fhirtypes.QuantityType = Field(
None,
alias="minimumVolumeQuantity",
title="Minimum volume",
description="The minimum volume to be conditioned in the container.",
# if property is element of this resource.
element_property=True,
# Choice of Data Types. i.e minimumVolume[x]
one_of_many="minimumVolume",
one_of_many_required=False,
)
minimumVolumeString: fhirtypes.String = Field(
None,
alias="minimumVolumeString",
title="Minimum volume",
description="The minimum volume to be conditioned in the container.",
# if property is element of this resource.
element_property=True,
# Choice of Data Types. i.e minimumVolume[x]
one_of_many="minimumVolume",
one_of_many_required=False,
)
minimumVolumeString__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
None,
alias="_minimumVolumeString",
title="Extension field for ``minimumVolumeString``.",
)
preparation: fhirtypes.String = Field(
None,
alias="preparation",
title="Specimen container preparation",
description=(
"Special processing that should be applied to the container for this "
"kind of specimen."
),
# if property is element of this resource.
element_property=True,
)
preparation__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
None, alias="_preparation", title="Extension field for ``preparation``."
)
type: fhirtypes.CodeableConceptType = Field(
None,
alias="type",
title="Kind of container associated with the kind of specimen",
description="The type of container used to contain this kind of specimen.",
# if property is element of this resource.
element_property=True,
)
@root_validator(pre=True, allow_reuse=True)
def validate_one_of_many_4016(
cls, values: typing.Dict[str, typing.Any]
) -> typing.Dict[str, typing.Any]:
"""https://www.hl7.org/fhir/formats.html#choice
A few elements have a choice of more than one data type for their content.
All such elements have a name that takes the form nnn[x].
The "nnn" part of the name is constant, and the "[x]" is replaced with
the title-cased name of the type that is actually used.
The table view shows each of these names explicitly.
Elements that have a choice of data type cannot repeat - they must have a
maximum cardinality of 1. When constructing an instance of an element with a
choice of types, the authoring system must create a single element with a
data type chosen from among the list of permitted data types.
"""
one_of_many_fields = {
"minimumVolume": ["minimumVolumeQuantity", "minimumVolumeString"]
}
for prefix, fields in one_of_many_fields.items():
assert cls.__fields__[fields[0]].field_info.extra["one_of_many"] == prefix
required = (
cls.__fields__[fields[0]].field_info.extra["one_of_many_required"]
is True
)
found = False
for field in fields:
if field in values and values[field] is not None:
if found is True:
raise ValueError(
"Any of one field value is expected from "
f"this list {fields}, but got multiple!"
)
else:
found = True
if required is True and found is False:
raise ValueError(f"Expect any of field value from this list {fields}.")
return values
class SpecimenDefinitionTypeTestedContainerAdditive(backboneelement.BackboneElement):
"""Disclaimer: Any field name ends with ``__ext`` does't part of
Resource StructureDefinition, instead used to enable Extensibility feature
for FHIR Primitive Data Types.
Additive associated with container.
Substance introduced in the kind of container to preserve, maintain or
enhance the specimen. Examples: Formalin, Citrate, EDTA.
"""
resource_type = Field("SpecimenDefinitionTypeTestedContainerAdditive", const=True)
additiveCodeableConcept: fhirtypes.CodeableConceptType = Field(
None,
alias="additiveCodeableConcept",
title="Additive associated with container",
description=(
"Substance introduced in the kind of container to preserve, maintain or"
" enhance the specimen. Examples: Formalin, Citrate, EDTA."
),
# if property is element of this resource.
element_property=True,
# Choice of Data Types. i.e additive[x]
one_of_many="additive",
one_of_many_required=True,
)
additiveReference: fhirtypes.ReferenceType = Field(
None,
alias="additiveReference",
title="Additive associated with container",
description=(
"Substance introduced in the kind of container to preserve, maintain or"
" enhance the specimen. Examples: Formalin, Citrate, EDTA."
),
# if property is element of this resource.
element_property=True,
# Choice of Data Types. i.e additive[x]
one_of_many="additive",
one_of_many_required=True,
# note: Listed Resource Type(s) should be allowed as Reference.
enum_reference_types=["Substance"],
)
@root_validator(pre=True, allow_reuse=True)
def validate_one_of_many_4813(
cls, values: typing.Dict[str, typing.Any]
) -> typing.Dict[str, typing.Any]:
"""https://www.hl7.org/fhir/formats.html#choice
A few elements have a choice of more than one data type for their content.
All such elements have a name that takes the form nnn[x].
The "nnn" part of the name is constant, and the "[x]" is replaced with
the title-cased name of the type that is actually used.
The table view shows each of these names explicitly.
Elements that have a choice of data type cannot repeat - they must have a
maximum cardinality of 1. When constructing an instance of an element with a
choice of types, the authoring system must create a single element with a
data type chosen from among the list of permitted data types.
"""
one_of_many_fields = {
"additive": ["additiveCodeableConcept", "additiveReference"]
}
for prefix, fields in one_of_many_fields.items():
assert cls.__fields__[fields[0]].field_info.extra["one_of_many"] == prefix
required = (
cls.__fields__[fields[0]].field_info.extra["one_of_many_required"]
is True
)
found = False
for field in fields:
if field in values and values[field] is not None:
if found is True:
raise ValueError(
"Any of one field value is expected from "
f"this list {fields}, but got multiple!"
)
else:
found = True
if required is True and found is False:
raise ValueError(f"Expect any of field value from this list {fields}.")
return values
class SpecimenDefinitionTypeTestedHandling(backboneelement.BackboneElement):
"""Disclaimer: Any field name ends with ``__ext`` does't part of
Resource StructureDefinition, instead used to enable Extensibility feature
for FHIR Primitive Data Types.
Specimen handling before testing.
Set of instructions for preservation/transport of the specimen at a defined
temperature interval, prior the testing process.
"""
resource_type = Field("SpecimenDefinitionTypeTestedHandling", const=True)
instruction: fhirtypes.String = Field(
None,
alias="instruction",
title="Preservation instruction",
description=(
"Additional textual instructions for the preservation or transport of "
"the specimen. For instance, 'Protect from light exposure'."
),
# if property is element of this resource.
element_property=True,
)
instruction__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
None, alias="_instruction", title="Extension field for ``instruction``."
)
maxDuration: fhirtypes.DurationType = Field(
None,
alias="maxDuration",
title="Maximum preservation time",
description=(
"The maximum time interval of preservation of the specimen with these "
"conditions."
),
# if property is element of this resource.
element_property=True,
)
temperatureQualifier: fhirtypes.CodeableConceptType = Field(
None,
alias="temperatureQualifier",
title="Temperature qualifier",
description=(
"It qualifies the interval of temperature, which characterizes an "
"occurrence of handling. Conditions that are not related to temperature"
" may be handled in the instruction element."
),
# if property is element of this resource.
element_property=True,
)
temperatureRange: fhirtypes.RangeType = Field(
None,
alias="temperatureRange",
title="Temperature range",
description="The temperature interval for this set of handling instructions.",
# if property is element of this resource.
element_property=True,
)
| 38.389286 | 93 | 0.634199 | 21,045 | 0.978928 | 0 | 0 | 6,526 | 0.303563 | 0 | 0 | 9,918 | 0.461345 |
d576c12c0ca80e35e6f43cee787a2cfd1e8bfe55 | 8,415 | py | Python | binlin/model/syn/sympairs_newenc.py | UKPLab/inlg2019-revisiting-binlin | 250196403ee4050cac78c547add90087ea04243f | [
"Apache-2.0"
] | 1 | 2021-12-15T08:44:35.000Z | 2021-12-15T08:44:35.000Z | binlin/model/syn/sympairs_newenc.py | UKPLab/inlg2019-revisiting-binlin | 250196403ee4050cac78c547add90087ea04243f | [
"Apache-2.0"
] | 3 | 2021-03-19T04:07:44.000Z | 2022-01-13T01:40:50.000Z | binlin/model/syn/sympairs_newenc.py | UKPLab/inlg2019-revisiting-binlin | 250196403ee4050cac78c547add90087ea04243f | [
"Apache-2.0"
] | null | null | null | import logging
from typing import Dict, List, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from networkx import DiGraph
from torch import Tensor, nn as nn
from torch.autograd.variable import Variable
from binlin.data.ud import index_data
from binlin.model.nn_utils import get_embed_matrix, pad_seq
from binlin.model.syn.sympairs import SymModel
from binlin.model.syn.utils.bintree import BinTreeBase
from binlin.utils.combinatorics import flatten_nested_lists
from binlin.utils.constants import VocabSymbols
logger = logging.getLogger('main')
class SymGraphEncModel(SymModel):
@property
def _data_fields(self):
return ['LEMMA', 'UPOS', 'XPOS', 'DEPREL']
@property
def _num_embedding_feats(self):
# todo: need to avoid hard-coding
# 6 = 2 * 3
# 2 because we consider two nodes at a time,
# 3 because for a node we consider itself + its context
# consisting of its parent and a random child
return 2 * 3 * self._data_fields_num
def _init_weights(self):
self._dim_emb = self.config["embedding_dim"]
self._mat_emb = get_embed_matrix(len(self._id2tok), self._dim_emb, padding_idx=self.PAD_ID)
self._dim_emb_proj_in = self._num_embedding_feats * self._dim_emb
self._dim_emb_proj_out = self._num_embedding_feats * self.config['embedding_proj_dim']
self._mat_emb_proj = nn.Linear(self._dim_emb_proj_in, self._dim_emb_proj_out)
self._dim_dense_out = self.config["dense_dim"]
self._mat_dense = nn.Linear(self._dim_emb_proj_out, self._dim_dense_out)
self._mat_attn = nn.Linear(self._dim_emb, 1)
self._dim_concat_in = self._dim_dense_out + self._dim_emb
self._dim_concat_out = self._dim_dense_out
self._mat_concat = nn.Linear(self._dim_concat_in, self._dim_concat_out)
self._dim_out = 1
self._mat_out = nn.Linear(self._dim_dense_out, self._dim_out)
def forward(self, batch_data: Tuple[Tensor, Tensor, Union[Tensor, None]]) -> Dict:
other_nodes_var, head_child_var, _ = batch_data
# head-child pair is encoded using an MLP
x_head_child = self._mat_emb(head_child_var).view(-1,
self._dim_emb_proj_in) # size(num_node_pairs, self.emb_proj_in)
x_head_child = F.leaky_relu(self._mat_emb_proj(x_head_child)) # size (num_node_pairs, self.emb_proj_out)
x_head_child = F.leaky_relu(self._mat_dense(x_head_child)) # size (num_node_pairs, self.dense1_dim)
# x_head_child = F.leaky_relu(x_head_child) # size (num_node_pairs, self.dense1_dim)
# graph nodes are encoded using embedding lookup --> summing
node_number = other_nodes_var.shape[-1]
x_graph = self._mat_emb(other_nodes_var) # size (max_num_nodes, batch_size, self.emb_dim)
# variant1: sum over all vecs
# x_graph = torch.sum(x_graph, dim=[0], keepdim=True).view(-1, self._dim_emb) # size (batch_size, emb_dim)
# variant2: use attn scores
attn_unnorm_scores = self._mat_attn(x_graph.view(-1, self._dim_emb)) # num_edges x 1
attn_weights = F.leaky_relu(attn_unnorm_scores).view(-1, 1, node_number)
# TODO: find a simpler way to do it w/o squeezing and unsqueezing?
# apply attention weights to the graph vectors to get weighted average
# size (1, dense)
x_graph = torch.bmm(attn_weights, x_graph).squeeze(1) # size: (bsize, emb_size)
# Concat head, child and graph representations
x_combined = torch.cat((x_head_child, x_graph), 1) # size (bs, emb_dim + self.dense1_dim)
# size (batch_size, self.dense1_dim)
x_combined = self._mat_concat(x_combined)
x_combined = F.leaky_relu(x_combined)
x_combined = self._mat_out(x_combined)
logits = torch.sigmoid(x_combined)
return {'logits': logits}
def extract_features(self, bt, new_node_nxid, dg, feats_d):
# pair-level features
head_nxid = bt.nxid
head_deptree_feats = feats_d[head_nxid]
child_deptree_feats = feats_d[new_node_nxid]
x_pair_ids_l = head_deptree_feats + child_deptree_feats
# extracting graph-level features
graph_ids_l = self.extract_graph_level_feats(dg, new_node_nxid, bt, feats_d)
return (graph_ids_l, x_pair_ids_l)
def extract_graph_level_feats(self, dg, new_node_nxid, bt, feats_d):
head_sbl = dg.node[bt.nxid]['sbl']
if head_sbl is None:
head_sbl_feats_l = self._dummy_node_feats_vec
else:
head_sbl_feats_l = flatten_nested_lists([feats_d[ch] for ch in head_sbl])
child_sbl = dg.node[new_node_nxid]['sbl']
if child_sbl is None:
ch_sbl_feats_l = self._dummy_node_feats_vec
else:
ch_sbl_feats_l = flatten_nested_lists([feats_d[ch] for ch in child_sbl])
child_children = dg[new_node_nxid]
if len(child_children) == 0:
ch_ch_feats_l = self._dummy_node_feats_vec
else:
ch_ch_feats_l = flatten_nested_lists([feats_d[ch] for ch in child_children])
graph_ids_l = head_sbl_feats_l + ch_sbl_feats_l + ch_ch_feats_l
return graph_ids_l
def init_data_containers(self):
return {'X': [],
'Y': [],
'Xg': []}
def add_xy_pairs(self, data_containers: Dict, y: int, model_inputs: Tuple[List[int], List[int]]):
x_graph, x_head_child = model_inputs
data_containers['X'].append(x_head_child)
data_containers['Xg'].append(x_graph)
data_containers['Y'].append(y)
def _batchify(self, data_containers: Dict, batch_size: int):
# sort according to the lemma length
sorted_data = sorted(zip(*(data_containers['Xg'],
data_containers['X'],
data_containers['Y'])), key=lambda p: len(p[0]), reverse=True)
data_size = len(sorted_data)
num_batches = data_size // batch_size
data_indices = index_data(data_size, mode='no_shuffling')
batch_pairs = []
for bi in range(num_batches + 1): # including the last (smaller) batch
batch_x_pair_feats = []
batch_x_graph_feats = []
batch_x_lens = []
batch_y = []
curr_batch_indices = data_indices[bi * batch_size: (bi + 1) * batch_size]
if len(curr_batch_indices) == 0:
break
for idx in curr_batch_indices:
graph_f_ids, node_pairs_f_ids, y_ids = sorted_data[idx]
batch_x_graph_feats.append(graph_f_ids)
batch_x_lens.append(len(graph_f_ids))
batch_x_pair_feats.append(node_pairs_f_ids)
batch_y.append(y_ids)
max_graph_f_len = max(batch_x_lens)
batch_x_graph_feats_padded = [pad_seq(x, max_graph_f_len, pad_id=self.PAD_ID) for x in batch_x_graph_feats]
# size: (num_nodes, batch_size)
batch_x_graph_feats_var = Variable(torch.LongTensor(batch_x_graph_feats_padded)).to(self.device)
# size: (batch_size, 2 * num_node_feats)
batch_x_pair_feats_var = Variable(torch.LongTensor(batch_x_pair_feats)).to(self.device)
# size: (batch_size, 1)
batch_y_var = Variable(torch.FloatTensor(batch_y)).unsqueeze(1).to(self.device)
batch_pairs.append((batch_x_graph_feats_var, batch_x_pair_feats_var, batch_y_var))
return batch_pairs
def make_decision(self,
bt: BinTreeBase,
new_node_nxid: str,
dg: DiGraph,
feats_d: Dict, *other_inputs) -> int:
x_graph_ids_l, x_ids_l = self.extract_features(bt, new_node_nxid, dg, feats_d)
x_ids_np = np.asarray(x_ids_l)
x_graph_ids_l = np.asarray([x_graph_ids_l])
outputs = self.__call__(
(
torch.from_numpy(x_graph_ids_l).to(self.device),
torch.from_numpy(x_ids_np).to(self.device),
None)
)
logit_val = outputs['logits'].cpu().data[0].numpy()
if logit_val >= 0.5:
decision = VocabSymbols.RIGHT
else:
decision = VocabSymbols.LEFT
return decision
component = SymGraphEncModel
| 40.456731 | 122 | 0.651337 | 7,803 | 0.927273 | 0 | 0 | 411 | 0.048841 | 0 | 0 | 1,387 | 0.164825 |
d576c1660c434219aa62d4d9116e13d2df8e9624 | 1,563 | py | Python | mazeChallenge/nicolovescera_tommasoromani_nicoloposta/data_analyzer.py | NicoloPosta/pybootcamp-challenges | c20a44df413a6adc6e18c7052cf55bdbf760838c | [
"Apache-2.0"
] | null | null | null | mazeChallenge/nicolovescera_tommasoromani_nicoloposta/data_analyzer.py | NicoloPosta/pybootcamp-challenges | c20a44df413a6adc6e18c7052cf55bdbf760838c | [
"Apache-2.0"
] | null | null | null | mazeChallenge/nicolovescera_tommasoromani_nicoloposta/data_analyzer.py | NicoloPosta/pybootcamp-challenges | c20a44df413a6adc6e18c7052cf55bdbf760838c | [
"Apache-2.0"
] | null | null | null | from plotter import load_data
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Stampa il dataframe passatogli come istogramma
def plot_coordinata(data: pd.DataFrame, coordinata: str, alpha_value=1.0, title="Grafico 1"):
data = data[[coordinata,'color']]
rosse = data[data['color'] == 'red'].groupby(coordinata).count()
blu = data[data['color'] == 'blue'].groupby(coordinata).count()
verdi = data[data['color'] == 'green'].groupby(coordinata).count()
ax = pd.concat([rosse,verdi,blu], axis = 1).plot(kind = 'bar', color = ['r','g','b'])
ax.legend(["R", "G", "B"])
ax.set_title(title)
# Conta il totale delle celle e il colore
def cell_stats(data: pd.DataFrame):
colors = data['color'].value_counts()
print(f"\nIl totale delle celle nel labirinto è di {data['color'].count()}.\n")
# Tolgo le celle bianche
colors.drop('white', inplace=True)
for color, value in colors.iteritems():
print(f"{color}:\t{value}")
# Stampa a video gli istogrammi, se invocata con True confronta le due distribuzioni nei relativi istogrammi
def plot_stats(confronto=False):
data = load_data("data.csv")
if confronto:
data2 = load_data("data2.csv")
if not confronto:
cell_stats(data)
plot_coordinata(data, 'x')
if confronto:
plot_coordinata(data2, 'x', alpha_value=0.5, title="Grafico 2")
plot_coordinata(data, 'y')
if confronto:
plot_coordinata(data2, 'y', alpha_value=0.5, title="Grafico 2")
plt.show()
| 30.057692 | 108 | 0.651951 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 463 | 0.296036 |
d57d0a31e680bead64fbb6304d9ea92f18b64649 | 1,281 | py | Python | complex_data_structure/7_map_filter_reduce.py | hardikid/learn-python | 6b3684c9d459dc10ed41e3328daf49313a34b375 | [
"MIT"
] | 1 | 2019-11-19T11:42:50.000Z | 2019-11-19T11:42:50.000Z | complex_data_structure/7_map_filter_reduce.py | hardikid/learn-python | 6b3684c9d459dc10ed41e3328daf49313a34b375 | [
"MIT"
] | 5 | 2021-08-23T20:36:02.000Z | 2022-02-03T13:20:23.000Z | complex_data_structure/7_map_filter_reduce.py | ihardik/learn-python | 6b3684c9d459dc10ed41e3328daf49313a34b375 | [
"MIT"
] | null | null | null | ######## map
# Transform each object of list
# i.e. multiple each object by 3 in [0,1,2,3]
x = range(5)
print(list(x))
y = map(lambda x: x*3,x)
def multiply_5(num):
return num*5
print(list(y))
y = map(multiply_5,x)
print(list(y))
######## filter
# Removed items from list based on condition
y = filter(lambda i: i%2==0, x)
print(list(y))
######## reduce
from functools import reduce
y = reduce(lambda a,b: a+b, x)
print(y)
####### Play around with OS module.
import os
import time
print(time.time())
print(os.getcwd())
print(os.listdir())
x = ["ABC","ABCD","PQR"]
x_lower = list(map(str.lower, x))
print(x_lower)
print([w for w in x if w.startswith('A')])
x = [2,4,6,8,10]
x_2 = list(map(lambda i: i/2, x))
print(x_2)
value = list(map(lambda x: str(x).startswith('p'), os.listdir()))
print(value)
print(list(filter(lambda x: str(x).find("cwd") > 0, dir(os))))
print([x for x in dir(os) if x.find("cwd") > 0])
######## del keyword
x= [1,2,3]
print(x)
del x[1]
print(x)
x = {"key1":"Value1","key2":"Value2"}
print(x)
del x['key1']
print(x)
######## in keyword
print("a" in ["a","b"])
print("a" in "abc")
x = {"a":1}
print("a" in x)
x = {"key":"a"}
print("a" in x.values())
| 16.0125 | 66 | 0.558938 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 345 | 0.269321 |
d57e965e9de5274c6fa912c32713dec8917703fa | 10,781 | py | Python | venv/lib/python3.8/site-packages/ansible_collections/community/crypto/plugins/module_utils/acme/challenges.py | saeedya/docker-ansible | 6fb0cfc6bc4a5925b21380952a5a4502ec02119a | [
"Apache-2.0"
] | null | null | null | venv/lib/python3.8/site-packages/ansible_collections/community/crypto/plugins/module_utils/acme/challenges.py | saeedya/docker-ansible | 6fb0cfc6bc4a5925b21380952a5a4502ec02119a | [
"Apache-2.0"
] | null | null | null | venv/lib/python3.8/site-packages/ansible_collections/community/crypto/plugins/module_utils/acme/challenges.py | saeedya/docker-ansible | 6fb0cfc6bc4a5925b21380952a5a4502ec02119a | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright: (c) 2016 Michael Gruener <michael.gruener@chaosmoon.net>
# Copyright: (c) 2021 Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import base64
import hashlib
import json
import re
import time
from ansible.module_utils.common.text.converters import to_bytes
from ansible_collections.community.crypto.plugins.module_utils.acme.utils import (
nopad_b64,
)
from ansible_collections.community.crypto.plugins.module_utils.acme.errors import (
format_error_problem,
ACMEProtocolException,
ModuleFailException,
)
try:
import ipaddress
except ImportError:
pass
def create_key_authorization(client, token):
'''
Returns the key authorization for the given token
https://tools.ietf.org/html/rfc8555#section-8.1
'''
accountkey_json = json.dumps(client.account_jwk, sort_keys=True, separators=(',', ':'))
thumbprint = nopad_b64(hashlib.sha256(accountkey_json.encode('utf8')).digest())
return "{0}.{1}".format(token, thumbprint)
def combine_identifier(identifier_type, identifier):
return '{type}:{identifier}'.format(type=identifier_type, identifier=identifier)
def split_identifier(identifier):
parts = identifier.split(':', 1)
if len(parts) != 2:
raise ModuleFailException(
'Identifier "{identifier}" is not of the form <type>:<identifier>'.format(identifier=identifier))
return parts
class Challenge(object):
def __init__(self, data, url):
self.data = data
self.type = data['type']
self.url = url
self.status = data['status']
self.token = data.get('token')
@classmethod
def from_json(cls, client, data, url=None):
return cls(data, url or (data['uri'] if client.version == 1 else data['url']))
def call_validate(self, client):
challenge_response = {}
if client.version == 1:
token = re.sub(r"[^A-Za-z0-9_\-]", "_", self.token)
key_authorization = create_key_authorization(client, token)
challenge_response['resource'] = 'challenge'
challenge_response['keyAuthorization'] = key_authorization
challenge_response['type'] = self.type
client.send_signed_request(
self.url,
challenge_response,
error_msg='Failed to validate challenge',
expected_status_codes=[200, 202],
)
def to_json(self):
return self.data.copy()
def get_validation_data(self, client, identifier_type, identifier):
token = re.sub(r"[^A-Za-z0-9_\-]", "_", self.token)
key_authorization = create_key_authorization(client, token)
if self.type == 'http-01':
# https://tools.ietf.org/html/rfc8555#section-8.3
return {
'resource': '.well-known/acme-challenge/{token}'.format(token=token),
'resource_value': key_authorization,
}
if self.type == 'dns-01':
if identifier_type != 'dns':
return None
# https://tools.ietf.org/html/rfc8555#section-8.4
resource = '_acme-challenge'
value = nopad_b64(hashlib.sha256(to_bytes(key_authorization)).digest())
record = (resource + identifier[1:]) if identifier.startswith('*.') else '{0}.{1}'.format(resource, identifier)
return {
'resource': resource,
'resource_value': value,
'record': record,
}
if self.type == 'tls-alpn-01':
# https://www.rfc-editor.org/rfc/rfc8737.html#section-3
if identifier_type == 'ip':
# IPv4/IPv6 address: use reverse mapping (RFC1034, RFC3596)
resource = ipaddress.ip_address(identifier).reverse_pointer
if not resource.endswith('.'):
resource += '.'
else:
resource = identifier
value = base64.b64encode(hashlib.sha256(to_bytes(key_authorization)).digest())
return {
'resource': resource,
'resource_original': combine_identifier(identifier_type, identifier),
'resource_value': value,
}
# Unknown challenge type: ignore
return None
class Authorization(object):
def _setup(self, client, data):
data['uri'] = self.url
self.data = data
self.challenges = [Challenge.from_json(client, challenge) for challenge in data['challenges']]
if client.version == 1 and 'status' not in data:
# https://tools.ietf.org/html/draft-ietf-acme-acme-02#section-6.1.2
# "status (required, string): ...
# If this field is missing, then the default value is "pending"."
self.status = 'pending'
else:
self.status = data['status']
self.identifier = data['identifier']['value']
self.identifier_type = data['identifier']['type']
if data.get('wildcard', False):
self.identifier = '*.{0}'.format(self.identifier)
def __init__(self, url):
self.url = url
self.data = None
self.challenges = []
self.status = None
self.identifier_type = None
self.identifier = None
@classmethod
def from_json(cls, client, data, url):
result = cls(url)
result._setup(client, data)
return result
@classmethod
def from_url(cls, client, url):
result = cls(url)
result.refresh(client)
return result
@classmethod
def create(cls, client, identifier_type, identifier):
'''
Create a new authorization for the given identifier.
Return the authorization object of the new authorization
https://tools.ietf.org/html/draft-ietf-acme-acme-02#section-6.4
'''
new_authz = {
"identifier": {
"type": identifier_type,
"value": identifier,
},
}
if client.version == 1:
url = client.directory['new-authz']
new_authz["resource"] = "new-authz"
else:
if 'newAuthz' not in client.directory.directory:
raise ACMEProtocolException(client.module, 'ACME endpoint does not support pre-authorization')
url = client.directory['newAuthz']
result, info = client.send_signed_request(
url, new_authz, error_msg='Failed to request challenges', expected_status_codes=[200, 201])
return cls.from_json(client, result, info['location'])
@property
def combined_identifier(self):
return combine_identifier(self.identifier_type, self.identifier)
def to_json(self):
return self.data.copy()
def refresh(self, client):
result, dummy = client.get_request(self.url)
changed = self.data != result
self._setup(client, result)
return changed
def get_challenge_data(self, client):
'''
Returns a dict with the data for all proposed (and supported) challenges
of the given authorization.
'''
data = {}
for challenge in self.challenges:
validation_data = challenge.get_validation_data(client, self.identifier_type, self.identifier)
if validation_data is not None:
data[challenge.type] = validation_data
return data
def raise_error(self, error_msg, module=None):
'''
Aborts with a specific error for a challenge.
'''
error_details = []
# multiple challenges could have failed at this point, gather error
# details for all of them before failing
for challenge in self.challenges:
if challenge.status == 'invalid':
msg = 'Challenge {type}'.format(type=challenge.type)
if 'error' in challenge.data:
msg = '{msg}: {problem}'.format(
msg=msg,
problem=format_error_problem(challenge.data['error'], subproblem_prefix='{0}.'.format(challenge.type)),
)
error_details.append(msg)
raise ACMEProtocolException(
module,
'Failed to validate challenge for {identifier}: {error}. {details}'.format(
identifier=self.combined_identifier,
error=error_msg,
details='; '.join(error_details),
),
extras=dict(
identifier=self.combined_identifier,
authorization=self.data,
),
)
def find_challenge(self, challenge_type):
for challenge in self.challenges:
if challenge_type == challenge.type:
return challenge
return None
def wait_for_validation(self, client, callenge_type):
while True:
self.refresh(client)
if self.status in ['valid', 'invalid', 'revoked']:
break
time.sleep(2)
if self.status == 'invalid':
self.raise_error('Status is "invalid"', module=client.module)
return self.status == 'valid'
def call_validate(self, client, challenge_type, wait=True):
'''
Validate the authorization provided in the auth dict. Returns True
when the validation was successful and False when it was not.
'''
challenge = self.find_challenge(challenge_type)
if challenge is None:
raise ModuleFailException('Found no challenge of type "{challenge}" for identifier {identifier}!'.format(
challenge=challenge_type,
identifier=self.combined_identifier,
))
challenge.call_validate(client)
if not wait:
return self.status == 'valid'
return self.wait_for_validation(client, challenge_type)
def deactivate(self, client):
'''
Deactivates this authorization.
https://community.letsencrypt.org/t/authorization-deactivation/19860/2
https://tools.ietf.org/html/rfc8555#section-7.5.2
'''
if self.status != 'valid':
return
authz_deactivate = {
'status': 'deactivated'
}
if client.version == 1:
authz_deactivate['resource'] = 'authz'
result, info = client.send_signed_request(self.url, authz_deactivate, fail_on_error=False)
if 200 <= info['status'] < 300 and result.get('status') == 'deactivated':
self.status = 'deactivated'
return True
return False
| 35.580858 | 127 | 0.602727 | 9,201 | 0.853446 | 0 | 0 | 1,555 | 0.144235 | 0 | 0 | 2,738 | 0.253965 |
d57eb3183cea1c9fed2cc78a667014a3b96be463 | 115 | py | Python | example/order_scope_level/feature2/test_b.py | DevilXD/pytest-order | 88685d802cb18bf04f72d0e8ec484d56bb3473d3 | [
"MIT"
] | 41 | 2021-03-16T07:57:00.000Z | 2022-03-01T10:02:10.000Z | example/order_scope_level/feature2/test_b.py | DevilXD/pytest-order | 88685d802cb18bf04f72d0e8ec484d56bb3473d3 | [
"MIT"
] | 39 | 2021-03-04T16:50:04.000Z | 2022-02-18T18:51:14.000Z | example/order_scope_level/feature2/test_b.py | DevilXD/pytest-order | 88685d802cb18bf04f72d0e8ec484d56bb3473d3 | [
"MIT"
] | 9 | 2021-03-04T18:27:12.000Z | 2021-12-16T06:46:13.000Z | import pytest
@pytest.mark.order(4)
def test_four():
pass
@pytest.mark.order(3)
def test_three():
pass
| 9.583333 | 21 | 0.669565 | 0 | 0 | 0 | 0 | 95 | 0.826087 | 0 | 0 | 0 | 0 |
d57fd865a85ee217ca78b18a3c2f824a1af7f759 | 31,890 | py | Python | locate_lane_lines.py | StoicLobster/Udacity-SelfDrivingCar-T1P4 | 2425cc5859861af9add86f6b3c42c2dd1faf0560 | [
"MIT"
] | null | null | null | locate_lane_lines.py | StoicLobster/Udacity-SelfDrivingCar-T1P4 | 2425cc5859861af9add86f6b3c42c2dd1faf0560 | [
"MIT"
] | null | null | null | locate_lane_lines.py | StoicLobster/Udacity-SelfDrivingCar-T1P4 | 2425cc5859861af9add86f6b3c42c2dd1faf0560 | [
"MIT"
] | null | null | null | ## This script will define the functions used in the locate lane lines pipeline
## The end of this script will process a video file to locate and plot the lane lines
import pickle
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from moviepy.editor import VideoFileClip
import sys
## Unpickle Required Data
cam_mtx = pickle.load(open("camera_matrix.p","rb"))
dist_coef = pickle.load(open("camera_distortion_coefficients.p","rb"))
M = pickle.load(open("M.p","rb"))
Minv = pickle.load(open("Minv.p","rb"))
## Undistort Function
def undistort(img_RGB_in):
# Input RGB distorted, Output RGB undistorted
img_out = cv2.undistort(img_RGB_in, cam_mtx, dist_coef, None, cam_mtx)
return(img_out)
# Sample undistort image
if (False):
img = mpimg.imread('camera_cal/calibration1.jpg')
dst_img = undistort(img)
plt.figure(0)
plt.imshow(img)
plt.title('Original Image')
plt.savefig('output_images/distorted_image.png')
plt.figure(1)
plt.imshow(dst_img)
plt.title('Undistorted Image')
plt.savefig('output_images/undistorted_image.png')
plt.show()
# Color Threshold Function
def color_thresh(img_RGB_in,RGB_out):
# Input RGB undistorted, Output Binary (or RGB for video)
# Convert image to HSV color space
img_HSV = cv2.cvtColor(img_RGB_in, cv2.COLOR_RGB2HSV)
# Extract S layer
H_layer = img_HSV[:,:,0]*2
S_layer = img_HSV[:,:,1]/255*100
V_layer = img_HSV[:,:,2]/255*100
# Apply threshold to S layer to identify white and yellow lane lines
H_Yellow = (40,70)
S_Yellow = (30,100)
V_Yellow = (30,100)
H_White = (0,50)
S_White = (0,10)
V_White = (75,100)
img_out = np.zeros_like(H_layer)
img_out[(((H_layer >= H_Yellow[0]) & (H_layer <= H_Yellow[1])) \
& ((S_layer >= S_Yellow[0]) & (S_layer <= S_Yellow[1])) \
& ((V_layer >= V_Yellow[0]) & (V_layer <= V_Yellow[1]))) \
| (((H_layer >= H_White[0]) & (H_layer <= H_White[1])) \
& ((S_layer >= S_White[0]) & (S_layer <= S_White[1])) \
& ((V_layer >= V_White[0]) & (V_layer <= V_White[1])))] = 1
if (RGB_out):
black_out_idxs = np.where(img_out == 0)
img_out = np.copy(img_RGB_in)
img_out[black_out_idxs[0],black_out_idxs[1],:] = 0
return(img_out)
# Sample color threshold image
if (False):
img = mpimg.imread('test_images/test5.jpg')
thrsh_img = color_thresh(img,RGB_out=True)
plt.figure(2)
plt.imshow(img)
plt.title('Original Image')
plt.savefig('output_images/pre_color_thresh.png')
plt.figure(3)
plt.imshow(thrsh_img, cmap='gray')
plt.title('Color Threshold')
plt.savefig('output_images/post_color_thresh.png')
plt.show()
## Perspective Transform to Top-Down View Function
def top_down_xfrm(img_RGB_in,frwd):
# Input RGB undistorted, Output RGB top-down
# frwd is bool that specifies if normal transform is requested (true) or inverse (false)
img_size = (img_RGB_in.shape[1], img_RGB_in.shape[0])
if (frwd):
Xfrm = M
else:
Xfrm = Minv
img_RGB_out = cv2.warpPerspective(img_RGB_in, Xfrm, img_size, flags=cv2.INTER_LINEAR)
return(img_RGB_out)
# Sample top-down perspective transform on image
if (False):
img = mpimg.imread('test_images/test6.jpg')
warped = top_down_xfrm(img,frwd=True)
plt.figure(4)
plt.imshow(img)
plt.title('Original Image')
plt.savefig('output_images/pre_top_down.png')
plt.figure(5)
plt.imshow(warped)
plt.title('Top Down View Warp')
plt.savefig('output_images/post_top_down.png')
plt.show()
## Gradient Threshold Function
def grad_thresh(img_RGB_in,RGB_out):
# Input RGB top-down, Output Binary (or RGB for video)
# RGB_out boolean can be used for video testing
#Apply gradient threshold in x direction
img_GRAY = cv2.cvtColor(img_RGB_in, cv2.COLOR_RGB2GRAY)
grad_thresh = (10,100)
abs_sobel = np.absolute(cv2.Sobel(img_GRAY, cv2.CV_64F, 1, 0))
scaled_sobel = np.uint8(255*abs_sobel/np.max(abs_sobel))
img_out = np.zeros_like(img_GRAY, dtype=np.uint8)
img_out[(scaled_sobel >= grad_thresh[0]) & (scaled_sobel <= grad_thresh[1])] = 1
if (RGB_out):
black_out_idxs = np.where(img_out == 0)
img_out = np.copy(img_RGB_in)
img_out[black_out_idxs[0],black_out_idxs[1],:] = 0
# print(out.shape)
return(img_out)
# Sample gradient threshold image
if (False):
img = mpimg.imread('test_images/test6.jpg')
img = top_down_xfrm(img,frwd=True)
thrsh_img = grad_thresh(img,RGB_out=False)
plt.figure(6)
plt.imshow(img)
plt.title('Original Top Down Transformed Image')
plt.savefig('output_images/pre_grad_thresh.png')
plt.figure(7)
plt.imshow(thrsh_img, cmap='gray')
plt.title('Gradient Threshold')
plt.savefig('output_images/post_grad_thresh.png')
plt.show()
# Class to store and calculate both lane line parameters
class LaneLines():
def __init__(self,img_RGB_in,img_BIN_in):
frame_height = img_RGB_in.shape[0]
frame_width = img_RGB_in.shape[1]
# CONSTANTS
# Frame height
self.frame_height = frame_height
# Frame width
self.frame_width = frame_width
self.midpoint_width = np.int(frame_width//2)
# y values
self.ploty = np.linspace(0, frame_height-1, frame_height)
# Polynomial fit dimension
self.poly_fit_dim = 2
# FRAME
self.Frame = img_RGB_in
# Binary image for current frame
self.img_BIN_in = img_BIN_in
# Histogram for current frame
self.histogram = None
# RGB image for output of current frame
self.img_RGB_out = img_RGB_in
# Current number of consecutive failed frames
self.num_failed_frame_curr = 0
# Number of frames processed
self.frame_num = 0
# TEXT
self.font = cv2.FONT_HERSHEY_SIMPLEX
self.Ofst_Text_pos = (20,500)
self.Rad_L_Text_pos = (20,550)
self.Rad_R_Text_pos = (20,600)
self.fontScale = 1
self.fontColor = (255,255,255)
self.lineType = 2
# HYPERPARAMETERS
# Choose the number of sliding windows
self.nwindows = 9
# Set the width of the windows +/- margin
self.margin_hist = 100
# Set the width of the windows +/- margin
self.margin_poly = 100
# Set minimum number of pixels found to re-center window
self.minpix = 50
# Number of windows that must contain minpix number of pixels for lane line to be considered valid
self.nwindow_fnd = 5
# Number of pixels that must be found for poly search method to be considered valid
self.minpix_poly = 300
# Set height of windows - based on nwindows above and image shape
self.window_height = np.int(frame_height//self.nwindows)
# Define conversions in x and y from pixels space to meters
self.x_width_pix = 700 #pixel width of lane
self.y_height_pix = 720 #pixel height of lane (frame height)
self.xm_per_pix = 3.7/self.x_width_pix # meters per pixel in x dimension
self.ym_per_pix = 30/self.y_height_pix # meters per pixel in y dimension
# Number of frames that failed to find lane lines before reset
self.num_failed_frame_alwd = 25
# Number of frames for rolling average filter
self.filt_size = 25
# LINE PARAMETERS
# was the left line detected in the current frame
self.detected_L = False
self.detected_R = False
# x values of the last n fits of the left line
self.x_fit_all_L = np.empty((0,self.ploty.size), dtype='float')
self.x_fit_all_R = np.empty((0,self.ploty.size), dtype='float')
#average x values of the fitted left line over the last n iterations
self.x_fit_best_L = np.zeros((self.ploty.size), dtype='float')
self.x_fit_best_R = np.zeros((self.ploty.size), dtype='float')
#polynomial coefficients for the most recent fit
self.coef_fit_current_L = np.zeros((self.poly_fit_dim+1), dtype='float')
self.coef_fit_current_R = np.zeros((self.poly_fit_dim+1), dtype='float')
#polynomial coefficients for the previous n iterations
self.coef_fit_all_L = np.empty((0,self.poly_fit_dim+1), dtype='float')
self.coef_fit_all_R = np.empty((0,self.poly_fit_dim+1), dtype='float')
#polynomial coefficients averaged over the last n iterations
self.coef_fit_best_L = np.zeros((self.poly_fit_dim+1), dtype='float')
self.coef_fit_best_R = np.zeros((self.poly_fit_dim+1), dtype='float')
#radius of curvature of the line in [m]
self.radius_of_curvature_L = 0
self.radius_of_curvature_R = 0
#distance in meters of vehicle center from the line
self.center_line_offst = 0
#difference in fit coefficients between last and new fits
# self.diffs = np.array([0,0,0], dtype='float')
return
def update_frame(self,img_RGB_in):
'''
Stores the new frame in memory
'''
self.Frame = img_RGB_in
self.histogram = None
self.img_RGB_out = img_RGB_in
return
def hist(self):
'''
Calculate histogram of points
'''
#Grab only the bottom half of the image
#Lane lines are likely to be mostly vertical nearest to the car
#Sum across image pixels vertically - make sure to set an `axis`
#i.e. the highest areas of vertical lines should be larger values
self.histogram = np.sum(self.img_BIN_in[self.img_BIN_in.shape[0]//2:,:], axis=0)
return
def find_lane_pixels_hist(self):
'''
Find lane pixels with histogram method
'''
# Reset previous rolling average queues
self.x_fit_all_L = np.empty((0,self.ploty.size), dtype='float')
self.x_fit_all_R = np.empty((0,self.ploty.size), dtype='float')
self.coef_fit_all_L = np.empty((0,self.poly_fit_dim+1), dtype='float')
self.coef_fit_all_R = np.empty((0,self.poly_fit_dim+1), dtype='float')
# Take a histogram of the bottom half of the image
self.hist()
# Create an output image to draw on and visualize the result
self.img_RGB_out = np.dstack((self.img_BIN_in, self.img_BIN_in, self.img_BIN_in))
# Find the peak of the left and right halves of the histogram
# These will be the starting point for the left and right lines
midpoint_height = np.int(self.histogram.shape[0]//2)
leftx_base = np.argmax(self.histogram[:midpoint_height])
rightx_base = np.argmax(self.histogram[midpoint_height:]) + midpoint_height
# Identify the x and y positions of all nonzero pixels in the image
nonzero = self.img_BIN_in.nonzero()
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
# Current positions to be updated later for each window in nwindows
leftx_current = leftx_base
rightx_current = rightx_base
# Create empty lists to receive left and right lane pixel indices
left_lane_inds = []
right_lane_inds = []
# Counter of valid windows found
cnt_wdw_fnd_L = 0
cnt_wdw_fnd_R = 0
#Step through the windows one by one
for window in range(self.nwindows):
# Identify window boundaries in x and y (and right and left)
win_y_low = self.img_BIN_in.shape[0] - (window+1)*self.window_height
win_y_high = self.img_BIN_in.shape[0] - window*self.window_height
win_xleft_low = leftx_current - self.margin_hist
win_xleft_high = leftx_current + self.margin_hist
win_xright_low = rightx_current - self.margin_hist
win_xright_high = rightx_current + self.margin_hist
# Draw the windows on the visualization image
cv2.rectangle(self.img_RGB_out,(win_xleft_low,win_y_low),
(win_xleft_high,win_y_high),(0,255,0), 2)
cv2.rectangle(self.img_RGB_out,(win_xright_low,win_y_low),
(win_xright_high,win_y_high),(0,255,0), 2)
# Identify the nonzero pixels in x and y within the window
good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &
(nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]
good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &
(nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]
# Append these indices to the lists
left_lane_inds.append(good_left_inds)
right_lane_inds.append(good_right_inds)
# If you found > minpix pixels, re-center next window on their mean position (otherwise keep previous window x position)
if len(good_left_inds) > self.minpix:
cnt_wdw_fnd_L = cnt_wdw_fnd_L + 1
leftx_current = np.int(np.mean(nonzerox[good_left_inds]))
if len(good_right_inds) > self.minpix:
cnt_wdw_fnd_R = cnt_wdw_fnd_R + 1
self.detected_R = True
rightx_current = np.int(np.mean(nonzerox[good_right_inds]))
# Create numpy arrays of indices
left_lane_inds = np.concatenate(left_lane_inds)
right_lane_inds = np.concatenate(right_lane_inds)
# Determine if valid number of windows was found with pixels
self.detected_L = (self.frame_num == 0) or (cnt_wdw_fnd_L >= self.nwindow_fnd)
self.detected_R = (self.frame_num == 0) or (cnt_wdw_fnd_R >= self.nwindow_fnd)
# Color in left and right line pixels
self.img_RGB_out[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0]
self.img_RGB_out[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255]
# Extract left and right line pixel positions
leftx = nonzerox[left_lane_inds]
lefty = nonzeroy[left_lane_inds]
rightx = nonzerox[right_lane_inds]
righty = nonzeroy[right_lane_inds]
return leftx, lefty, rightx, righty
def fit_polynomial(self,x,y):
# Fit a second order polynomial to data using `np.polyfit`
# coef_fit = [A, B, C] of y = A*x^2 + B*x + C
coef_fit = np.polyfit(y, x, self.poly_fit_dim)
# Generate x and y values for plotting
x_fit = coef_fit[0]*self.ploty**2 + coef_fit[1]*self.ploty + coef_fit[2]
# Limit x_fit by size of frame
x_fit = np.minimum(np.maximum(x_fit,0),self.frame_width-1)
# Visualization
# Colors in the activated pixels
self.img_RGB_out[y, x] = [255, 0, 0]
# Colors in the poly line
self.img_RGB_out[self.ploty.astype(int), x_fit.astype(int)] = [255, 255, 0]
return coef_fit, x_fit
def find_lane_pixels_poly(self):
'''
Search around polynomial for new lane pixels
'''
# Grab activated pixels
nonzero = self.img_BIN_in.nonzero()
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
# Set the area of search based on activated x-values
# within the +/- margin of our polynomial function (from previous frame)
left_lane_inds = ((nonzerox > (self.coef_fit_current_L[0]*(nonzeroy**2) + self.coef_fit_current_L[1]*nonzeroy + self.coef_fit_current_L[2] - self.margin_poly)) & (nonzerox < (self.coef_fit_current_L[0]*(nonzeroy**2) + self.coef_fit_current_L[1]*nonzeroy + self.coef_fit_current_L[2] + self.margin_poly)))
right_lane_inds = ((nonzerox > (self.coef_fit_current_R[0]*(nonzeroy**2) + self.coef_fit_current_R[1]*nonzeroy + self.coef_fit_current_R[2] - self.margin_poly)) & (nonzerox < (self.coef_fit_current_R[0]*(nonzeroy**2) + self.coef_fit_current_R[1]*nonzeroy + self.coef_fit_current_R[2] + self.margin_poly)))
# Extract left and right line pixel positions
leftx = nonzerox[left_lane_inds]
lefty = nonzeroy[left_lane_inds]
rightx = nonzerox[right_lane_inds]
righty = nonzeroy[right_lane_inds]
# Determine pixel find validity
self.detected_L = len(leftx) > self.minpix_poly
self.detected_R = len(rightx) > self.minpix_poly
if (self.detected_L and self.detected_R):
# Prepare output RGB image
self.img_RGB_out = np.dstack((self.img_BIN_in, self.img_BIN_in, self.img_BIN_in))
# Visualization
# Create an image to draw on and an image to show the selection window
# out_img = np.dstack((img_bin, img_bin, img_bin))*255
window_img = np.zeros_like(self.img_RGB_out)
# Color in left and right line pixels
self.img_RGB_out[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0]
self.img_RGB_out[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255]
# Generate a polygon to illustrate the search window area
# And recast the x and y points into usable format for cv2.fillPoly()
coef_tmp_L, x_fit_L = self.fit_polynomial(leftx,lefty)
coef_tmp_R, x_fit_R = self.fit_polynomial(rightx,righty)
left_line_window1 = np.array([np.transpose(np.vstack([x_fit_L-self.margin_poly, self.ploty]))])
left_line_window2 = np.array([np.flipud(np.transpose(np.vstack([x_fit_L+self.margin_poly, self.ploty])))])
left_line_pts = np.hstack((left_line_window1, left_line_window2))
right_line_window1 = np.array([np.transpose(np.vstack([x_fit_R-self.margin_poly, self.ploty]))])
right_line_window2 = np.array([np.flipud(np.transpose(np.vstack([x_fit_R+self.margin_poly, self.ploty])))])
right_line_pts = np.hstack((right_line_window1, right_line_window2))
# Draw the lane onto the warped blank image
cv2.fillPoly(window_img, np.int_([left_line_pts]), (0,255, 0))
cv2.fillPoly(window_img, np.int_([right_line_pts]), (0,255, 0))
self.img_RGB_out = cv2.addWeighted(self.img_RGB_out, 1, window_img, 0.3, 0)
# Plot the polynomial lines onto the image
# plt.plot(left_fitx, ploty, color='yellow')
# plt.plot(right_fitx, ploty, color='yellow')
# End visualization steps
return leftx, lefty, rightx, righty
def calc_best(self):
'''
Perform rolling average on polynomials to determine best fit.
'''
# Reset best
self.coef_fit_best_L = np.zeros((self.poly_fit_dim+1), dtype='float')
self.coef_fit_best_R = np.zeros((self.poly_fit_dim+1), dtype='float')
self.x_fit_best_L = np.zeros((self.ploty.size), dtype='float')
self.x_fit_best_R = np.zeros((self.ploty.size), dtype='float')
# Check if size of queue is larger than filter size
if (self.x_fit_all_L.shape[0] > self.filt_size):
self.x_fit_all_L = np.delete(self.x_fit_all_L,(0),axis=0)
self.x_fit_all_R = np.delete(self.x_fit_all_R,(0),axis=0)
self.coef_fit_all_L = np.delete(self.coef_fit_all_L,(0),axis=0)
self.coef_fit_all_R = np.delete(self.coef_fit_all_R,(0),axis=0)
# Loop through and compute average
n = self.x_fit_all_L.shape[0]
for row in range(n):
for col_x_fit in range(self.x_fit_all_L.shape[1]):
self.x_fit_best_L[col_x_fit] = self.x_fit_best_L[col_x_fit] + self.x_fit_all_L[row,col_x_fit]
self.x_fit_best_R[col_x_fit] = self.x_fit_best_R[col_x_fit] + self.x_fit_all_R[row,col_x_fit]
for col_coef_fit in range(self.coef_fit_all_L.shape[1]):
self.coef_fit_best_L[col_coef_fit] = self.coef_fit_best_L[col_coef_fit] + self.coef_fit_all_L[row,col_coef_fit]
self.coef_fit_best_R[col_coef_fit] = self.coef_fit_best_R[col_coef_fit] + self.coef_fit_all_R[row,col_coef_fit]
self.x_fit_best_L = self.x_fit_best_L/n
self.x_fit_best_R = self.x_fit_best_R/n
self.coef_fit_best_L = self.coef_fit_best_L/n
self.coef_fit_best_R = self.coef_fit_best_R/n
return
def calc_rad_real(self):
'''
Calculates the radius of polynomial functions in meters.
'''
# Convert parabola coefficients into pixels
A_L = self.xm_per_pix / (self.ym_per_pix**2) * self.coef_fit_best_L[0]
B_L = self.xm_per_pix / (self.ym_per_pix) * self.coef_fit_best_L[1]
A_R = self.xm_per_pix / (self.ym_per_pix**2) * self.coef_fit_best_R[0]
B_R = self.xm_per_pix / (self.ym_per_pix) * self.coef_fit_best_R[1]
# Define y-value where we want radius of curvature
# We'll choose the maximum y-value, corresponding to the bottom of the image
y_eval = (self.frame_height - 1)*self.ym_per_pix
# Calculation of R_curve (radius of curvature)
self.radius_of_curvature_L = ((1 + (2*A_L*y_eval + B_L)**2)**1.5) / np.absolute(2*A_L)
self.radius_of_curvature_R = ((1 + (2*A_R*y_eval + B_R)**2)**1.5) / np.absolute(2*A_R)
return
def calc_offset(self):
'''
Calculates the offset between vehicle and center of lane
'''
self.center_line_offst = abs(self.midpoint_width - (self.x_fit_best_L[-1] + self.x_fit_best_R[-1])/2) * self.xm_per_pix
return
def find_lane_lines(self):
'''
Find lane lines with an appropriate method
'''
## Find lane pixels
# If left or right detection from previous loop is false: Use histogram method
if (not(self.detected_L)) or (not(self.detected_R)):
print("Histogram search method used.")
# Call histogram method to find pixel locations of lanes and determine current frame detection validity
leftx, lefty, rightx, righty = self.find_lane_pixels_hist()
else:
print("Polynomial search method used")
# Call poly search method to find pixel locations of lanes and determine current frame detection validity
leftx, lefty, rightx, righty = self.find_lane_pixels_poly()
if (not(self.detected_L)) or (not(self.detected_R)):
print("Polynomial search method failed. Histogram search method used.")
# Neither lane was found, must use histogram method
leftx, lefty, rightx, righty = self.find_lane_pixels_hist()
## Check if both lane lines were found
if (self.detected_L and self.detected_R):
# Reset failed counter
self.num_failed_frame_curr = 0
# Fit new polynomials for both lanes
self.coef_fit_current_L, x_fit_L = self.fit_polynomial(leftx,lefty)
self.coef_fit_current_R, x_fit_R = self.fit_polynomial(rightx,righty)
# Append x_fit to list
self.x_fit_all_L = np.vstack((self.x_fit_all_L, x_fit_L))
self.x_fit_all_R = np.vstack((self.x_fit_all_R, x_fit_R))
# Append coefficients to list
self.coef_fit_all_L = np.vstack((self.coef_fit_all_L, self.coef_fit_current_L))
self.coef_fit_all_R = np.vstack((self.coef_fit_all_R, self.coef_fit_current_R))
# Calculate rolling average
self.calc_best()
else:
# Increment failed counter
self.num_failed_frame_curr = self.num_failed_frame_curr + 1
print("Number of failed frames: " + str(self.num_failed_frame_curr))
# Do not compute new polynomial, use previous best
# Check if number of consecutive failed frames has exceed max
if (self.num_failed_frame_curr > self.num_failed_frame_alwd):
print("Number of consecutive failed frames exceeded.")
sys.exit()
# Calculate radius of curvature
self.calc_rad_real()
# Calculate center line offset
self.calc_offset()
return
def draw_frame(self,img_RGB_in):
'''
Draws the frame with desired polynomials in original image perspective
'''
print("\n")
#print("Processing Frame # " + str(self.frame_num))
# Store new frame
self.update_frame(img_RGB_in)
# Calculate binary image of color and gradient thresholds
self.img_BIN_in = grad_thresh(top_down_xfrm(color_thresh(undistort(img_RGB_in),RGB_out=True),frwd=True),RGB_out=False)
# Create an image to draw the lines on
warp_zero = np.zeros_like(self.img_BIN_in).astype(np.uint8)
color_warp = np.dstack((warp_zero, warp_zero, warp_zero))
# Find lane lines
self.find_lane_lines()
# Recast the x and y points into usable format for cv2.fillPoly()
pts_left = np.array([np.transpose(np.vstack([self.x_fit_best_L, self.ploty]))])
pts_right = np.array([np.flipud(np.transpose(np.vstack([self.x_fit_best_R, self.ploty])))])
pts = np.hstack((pts_left, pts_right))
# Draw the lane onto the warped blank image
cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0))
# Warp the blank back to original image space using inverse perspective matrix (Minv)
newwarp = cv2.warpPerspective(color_warp, Minv, (img_RGB_in.shape[1], img_RGB_in.shape[0]))
# Combine the result with the original image
self.Frame = cv2.addWeighted(img_RGB_in, 1, newwarp, 0.3, 0)
# Draw text on image
cv2.putText(self.Frame,"Lane Center Offset [m]: " + str(round(self.center_line_offst,2)),self.Ofst_Text_pos,self.font,self.fontScale,self.fontColor,self.lineType)
cv2.putText(self.Frame,"Radius Left [m]: " + str(round(self.radius_of_curvature_L,0)),self.Rad_L_Text_pos,self.font,self.fontScale,self.fontColor,self.lineType)
cv2.putText(self.Frame,"Radius Right [m]: " + str(round(self.radius_of_curvature_R,0)),self.Rad_R_Text_pos,self.font,self.fontScale,self.fontColor,self.lineType)
self.frame_num = self.frame_num + 1
#print("Left Radius: " + str(self.radius_of_curvature_L))
#print("Right Radius: " + str(self.radius_of_curvature_R))
#print("Lane Center Offset: " + str(lane_lines.center_line_offst))
#return(self.img_RGB_out)
return(self.Frame)
# Sample histogram
if (False):
img = mpimg.imread('test_images/test6.jpg')
img_BIN_in = grad_thresh(top_down_xfrm(color_thresh(undistort(img),RGB_out=True),frwd=True),RGB_out=False);
lane_lines = LaneLines(img,img_BIN_in)
lane_lines.hist()
histogram = lane_lines.histogram
plt.figure(7)
plt.imshow(img)
plt.title('Original Image')
plt.savefig('output_images/original_histogram.png')
plt.figure(8)
plt.imshow(img_BIN_in, cmap='gray')
plt.title('Original Binary Image')
plt.savefig('output_images/original_bin_histogram.png')
plt.figure(9)
plt.plot(histogram)
plt.title('Histogram')
plt.savefig('output_images/histogram.png')
plt.show()
# Sample polyfit with histogram search
if (False):
img = mpimg.imread('test_images/test6.jpg')
plt.figure(10)
plt.imshow(img)
plt.title('Original Image')
img_BIN_in = grad_thresh(top_down_xfrm(color_thresh(undistort(img),RGB_out=True),frwd=True),RGB_out=False)
lane_lines = LaneLines(img,img_BIN_in)
# Search for lane lines using histogram method
leftx, lefty, rightx, righty = lane_lines.find_lane_pixels_hist()
# Fit new polynomials for both lanes
lane_lines.coef_fit_current_L, x_fit_L = lane_lines.fit_polynomial(leftx,lefty)
lane_lines.coef_fit_current_R, x_fit_R = lane_lines.fit_polynomial(rightx,righty)
print("Current Left Coefficients: " + str(lane_lines.coef_fit_current_L))
print("Current Right Coefficients: " + str(lane_lines.coef_fit_current_R))
plt.figure(11)
plt.imshow(lane_lines.img_RGB_out)
plt.title('2nd Order Polynomial Fit - Histogram Search Method')
plt.savefig('output_images/poly_hist.png')
# Sample search around poly
if (False):
# Append x_fit to list
lane_lines.x_fit_all_L = np.vstack((lane_lines.x_fit_all_L, x_fit_L))
lane_lines.x_fit_all_R = np.vstack((lane_lines.x_fit_all_R, x_fit_R))
# Append coefficients to list
lane_lines.coef_fit_all_L = np.vstack((lane_lines.coef_fit_all_L, lane_lines.coef_fit_current_L))
lane_lines.coef_fit_all_R = np.vstack((lane_lines.coef_fit_all_R, lane_lines.coef_fit_current_R))
print("All Left Coefficients: " + str(lane_lines.coef_fit_all_L))
print("All Right Coefficients: " + str(lane_lines.coef_fit_all_R))
# Calculate rolling average
lane_lines.calc_best()
print("Best Left Coefficients: " + str(lane_lines.coef_fit_best_L))
print("Best Right Coefficients: " + str(lane_lines.coef_fit_best_R))
# Calculate real radius of curvature
lane_lines.calc_rad_real()
print("Left Radius: " + str(lane_lines.radius_of_curvature_L))
print("Right Radius: " + str(lane_lines.radius_of_curvature_R))
lane_lines.calc_offset()
print("Center Lane Offset: " + str(lane_lines.center_line_offst))
# Search for lane lines around previous best polynomial
leftx, lefty, rightx, righty = lane_lines.find_lane_pixels_poly()
# Fit new polynomials for both lanes
lane_lines.coef_fit_current_L, x_fit_L = lane_lines.fit_polynomial(leftx,lefty)
lane_lines.coef_fit_current_R, x_fit_R = lane_lines.fit_polynomial(rightx,righty)
plt.figure(12)
plt.imshow(lane_lines.img_RGB_out)
plt.title('2nd Order Polynomial Fit - Polynomial Search Method')
plt.savefig('output_images/poly_poly.png')
plt.show()
# Test full pipeline
if (True):
img = mpimg.imread('test_images/test6.jpg')
lane_lines = LaneLines(img,img)
plt.figure(13)
plt.imshow(img)
plt.title('Original Image')
plt.figure(14)
plt.imshow(lane_lines.draw_frame(img))
plt.title('Found Lines')
plt.savefig('output_images/full_pipeline.png')
plt.show()
## Process video
if (False):
img = mpimg.imread('test_images/test6.jpg')
lane_lines = LaneLines(img,img)
video_output = 'output_videos/challenge_video_processed.mp4'
#video_output = 'output_videos/project_video_processed.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start and end of the subclip
## You may also uncomment the following line for a subclip of the first 5 seconds
##clip1 = VideoFileClip("test_videos/solidWhiteRight.mp4").subclip(0,5)
clip = VideoFileClip("test_videos/challenge_video.mp4")
video_clip = clip.fl_image(lane_lines.draw_frame) #NOTE: this function expects color images!!
video_clip.write_videofile(video_output, audio=False)
| 46.28447 | 314 | 0.648448 | 22,127 | 0.693854 | 0 | 0 | 0 | 0 | 0 | 0 | 9,934 | 0.311508 |
d5807ccd0fe241a944ff08bce957e0086ab7a9c8 | 3,772 | py | Python | platforms/aws.py | HyechurnJang/c3mon | f5e053141372d39684e192e7c6d956125109b3c1 | [
"Apache-2.0"
] | null | null | null | platforms/aws.py | HyechurnJang/c3mon | f5e053141372d39684e192e7c6d956125109b3c1 | [
"Apache-2.0"
] | null | null | null | platforms/aws.py | HyechurnJang/c3mon | f5e053141372d39684e192e7c6d956125109b3c1 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
'''
Created on 2017. 12. 22.
@author: HyechurnJang
'''
import boto3
from datetime import datetime, timedelta
class AWS:
def __init__(self):
self.ec2 = boto3.resource('ec2')
self.cw = boto3.client('cloudwatch')
def getVMs(self):
aws = []
instances = self.ec2.instances.filter(
Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]
)
for instance in instances:
print instance.id,
desc = {
'id' : instance.id,
'publicIp' : instance.public_ip_address,
'privateIp' : instance.private_ip_address,
'metric' : {}
}
print 'OK'
aws.append(desc)
return {'amazon' : aws}
def getMetric(self, vms):
end = datetime.utcnow()
start = end - timedelta(seconds=600)
for vm in vms:
try:
cpu = self.cw.get_metric_statistics(
Period=60,
StartTime=start,
EndTime=end,
MetricName='CPUUtilization',
Namespace='AWS/EC2',
Statistics=['Average'],
Dimensions=[
{'Name' : 'InstanceId', 'Value' : vm['id']}
]
)
vm['metric']['cpu'] = cpu['Datapoints'][0]['Average']
net_in = self.cw.get_metric_statistics(
Period=60,
StartTime=start,
EndTime=end,
MetricName='NetworkIn',
Namespace='AWS/EC2',
Statistics=['Average'],
Dimensions=[
{'Name' : 'InstanceId', 'Value' : vm['id']}
]
)
vm['metric']['netIn'] = net_in['Datapoints'][0]['Average']
net_out = self.cw.get_metric_statistics(
Period=60,
StartTime=start,
EndTime=end,
MetricName='NetworkOut',
Namespace='AWS/EC2',
Statistics=['Average'],
Dimensions=[
{'Name' : 'InstanceId', 'Value' : vm['id']}
]
)
vm['metric']['netOut'] = net_out['Datapoints'][0]['Average']
disk_read = self.cw.get_metric_statistics(
Period=60,
StartTime=start,
EndTime=end,
MetricName='DiskReadBytes',
Namespace='AWS/EC2',
Statistics=['Average'],
Dimensions=[
{'Name' : 'InstanceId', 'Value' : vm['id']}
]
)
vm['metric']['diskRead'] = disk_read['Datapoints'][0]['Average']
disk_write = self.cw.get_metric_statistics(
Period=60,
StartTime=start,
EndTime=end,
MetricName='DiskWriteBytes',
Namespace='AWS/EC2',
Statistics=['Average'],
Dimensions=[
{'Name' : 'InstanceId', 'Value' : vm['id']}
]
)
vm['metric']['diskWrite'] = disk_write['Datapoints'][0]['Average']
except Exception as e: print str(e)
| 35.252336 | 83 | 0.391835 | 3,626 | 0.961294 | 0 | 0 | 0 | 0 | 0 | 0 | 678 | 0.179745 |
d58122ce2f5990ff0998eb5aff14ea21851d770b | 1,700 | py | Python | experimental/language_structure/vrnn/experiments/linear_vrnn/multiwoz_synth_bert.py | BlackHC/uncertainty-baselines | 1a28be3e41e14d8ab74dfa1e3eed15f113718f03 | [
"Apache-2.0"
] | null | null | null | experimental/language_structure/vrnn/experiments/linear_vrnn/multiwoz_synth_bert.py | BlackHC/uncertainty-baselines | 1a28be3e41e14d8ab74dfa1e3eed15f113718f03 | [
"Apache-2.0"
] | null | null | null | experimental/language_structure/vrnn/experiments/linear_vrnn/multiwoz_synth_bert.py | BlackHC/uncertainty-baselines | 1a28be3e41e14d8ab74dfa1e3eed15f113718f03 | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# Copyright 2022 The Uncertainty Baselines Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""Vizier for linear VRNN for MultiWoZSynthDataset.
"""
import multiwoz_synth_tmpl as tmpl # local file import from experimental.language_structure.vrnn.experiments.linear_vrnn
def get_config():
"""Returns the configuration for this experiment."""
config = tmpl.get_config(
shared_bert_embedding=True, bert_embedding_type='base')
config.platform = 'df'
config.tpu_topology = '4x2'
config.max_task_failures = -1
config.max_per_task_failures = 10
return config
def get_sweep(hyper):
"""Returns hyperparameter sweep."""
domain = [
hyper.sweep('config.word_weights_file_weight',
hyper.discrete([0.25 * i for i in range(5)])),
hyper.sweep('config.psl_constraint_learning_weight',
hyper.discrete([0., 0.001, 0.005, 0.01, 0.05, 0.1])),
hyper.sweep('config.model.vae_cell.encoder_hidden_size',
hyper.discrete([200, 300, 400])),
hyper.sweep('config.base_learning_rate',
hyper.discrete([3e-5, 5e-5, 1e-4, 3e-4]))
]
sweep = hyper.product(domain)
return sweep
| 32.692308 | 121 | 0.704706 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 985 | 0.579412 |
d581520a36615c52af59cc8c463ee9a8af5f732e | 1,201 | py | Python | src/ufdl/json/core/filter/_FilterSpec.py | waikato-ufdl/ufdl-json-messages | 408901bdf79aa9ae7cff1af165deee83e62f6088 | [
"Apache-2.0"
] | null | null | null | src/ufdl/json/core/filter/_FilterSpec.py | waikato-ufdl/ufdl-json-messages | 408901bdf79aa9ae7cff1af165deee83e62f6088 | [
"Apache-2.0"
] | null | null | null | src/ufdl/json/core/filter/_FilterSpec.py | waikato-ufdl/ufdl-json-messages | 408901bdf79aa9ae7cff1af165deee83e62f6088 | [
"Apache-2.0"
] | null | null | null | from typing import List
from wai.json.object import StrictJSONObject
from wai.json.object.property import ArrayProperty, OneOfProperty, BoolProperty
from .field import *
from .logical import *
from ._FilterExpression import FilterExpression
from ._OrderBy import OrderBy
class FilterSpec(StrictJSONObject['FilterSpec']):
"""
The top-level document describing how to filter a list request.
"""
# The sequential stages of filters of the list request
expressions: List[FilterExpression] = ArrayProperty(
element_property=OneOfProperty(
sub_properties=(
And.as_property(),
Or.as_property(),
*(field_filter_expression.as_property()
for field_filter_expression in ALL_FIELD_FILTER_EXPRESSIONS)
)
),
optional=True
)
# An optional final ordering on the result, in order of precedence
order_by: List[OrderBy] = ArrayProperty(
element_property=OrderBy.as_property(),
optional=True
)
# An optional flag to include soft-deleted models as well
include_inactive: bool = BoolProperty(
optional=True,
default=False
)
| 30.025 | 79 | 0.677769 | 925 | 0.770192 | 0 | 0 | 0 | 0 | 0 | 0 | 268 | 0.223147 |
d582ca9816237ee2b7fbc9eac1fc86001c97f980 | 290 | py | Python | basecam/__init__.py | sdss/baseCam | d5222f2c93df8e5b6ef894f32eca28b1cd3b3616 | [
"BSD-3-Clause"
] | null | null | null | basecam/__init__.py | sdss/baseCam | d5222f2c93df8e5b6ef894f32eca28b1cd3b3616 | [
"BSD-3-Clause"
] | 18 | 2020-01-13T20:57:48.000Z | 2021-06-22T14:43:16.000Z | basecam/__init__.py | sdss/basecam | 526f8be1b7c83e087e8f78484e63ba18531dce87 | [
"BSD-3-Clause"
] | null | null | null | # encoding: utf-8
# flake8: noqa
from sdsstools import get_package_version
NAME = "sdss-basecam"
__version__ = get_package_version(__file__, "sdss-basecam") or "dev"
from .camera import *
from .events import *
from .exceptions import *
from .exposure import *
from .notifier import *
| 17.058824 | 68 | 0.748276 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 64 | 0.22069 |
d5837ed5c9e1f4853a3b61828f36313098836798 | 571 | py | Python | temboo/core/Library/Wordnik/Account/__init__.py | jordanemedlock/psychtruths | 52e09033ade9608bd5143129f8a1bfac22d634dd | [
"Apache-2.0"
] | 7 | 2016-03-07T02:07:21.000Z | 2022-01-21T02:22:41.000Z | temboo/core/Library/Wordnik/Account/__init__.py | jordanemedlock/psychtruths | 52e09033ade9608bd5143129f8a1bfac22d634dd | [
"Apache-2.0"
] | null | null | null | temboo/core/Library/Wordnik/Account/__init__.py | jordanemedlock/psychtruths | 52e09033ade9608bd5143129f8a1bfac22d634dd | [
"Apache-2.0"
] | 8 | 2016-06-14T06:01:11.000Z | 2020-04-22T09:21:44.000Z | from temboo.Library.Wordnik.Account.GetAuthToken import GetAuthToken, GetAuthTokenInputSet, GetAuthTokenResultSet, GetAuthTokenChoreographyExecution
from temboo.Library.Wordnik.Account.GetKeyStatus import GetKeyStatus, GetKeyStatusInputSet, GetKeyStatusResultSet, GetKeyStatusChoreographyExecution
from temboo.Library.Wordnik.Account.GetUser import GetUser, GetUserInputSet, GetUserResultSet, GetUserChoreographyExecution
from temboo.Library.Wordnik.Account.GetWordLists import GetWordLists, GetWordListsInputSet, GetWordListsResultSet, GetWordListsChoreographyExecution
| 114.2 | 148 | 0.901926 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
d5838d0257d9eb7381eaac633cc981dbc3c1bfec | 9,691 | py | Python | transpose-alsaseq.py | zubilewiczm/transpose | 82cfc256555150cec7772584ab5699434f5d94fd | [
"MIT"
] | null | null | null | transpose-alsaseq.py | zubilewiczm/transpose | 82cfc256555150cec7772584ab5699434f5d94fd | [
"MIT"
] | null | null | null | transpose-alsaseq.py | zubilewiczm/transpose | 82cfc256555150cec7772584ab5699434f5d94fd | [
"MIT"
] | null | null | null | from transpose import *
import alsaseq
import alsamidi
import random
# Requires https://github.com/ppaez/alsaseq package.
alsaseq.client("pyTranspose", 0, 1, True)
class IntervalsGame(Game):
"""
IntervalsGame(name=None, autosave=True, **settings) : Game
A game to practice recognizing asceending, descending or harmonic
(simultaneous) intervals by ear. Requires a working MIDI setup.
The answers are passed to `Interval.from_name()` before evaluation.
Sample question:
<a C4 note followed by a E4 note is played>
>> M3 (...ok! (+1))
Game settings:
→ intervals : list of Interval or IntervalClass
A list of intervals chosen at random by the game.
→ adh : str
Whether the intervals chosen are ascending ("a"), descending ("d"),
or harmonic ("h"). Any combination of these letters makes the game
choose one of the options at random (e.g. "ahh" chooses between
ascending and harmonic intervals with 50:50 chance for each).
→ center : MIDInn
Average MIDI note number that the game chooses as the first note
of the interval.
→ spread : Integral
Maximal difference (in semitones) between the first note of the
interval played and the `center`.
Question parameters:
(ctr, itc, adh), where
→ ctr → first note of an interval
→ itc → the interval (determining the second note)
→ adh → ascending / descending / harmonic
`details` queries:
Combinations of the following query arguments can be passed to the
`details` method.
→ "intervals"...
= "full" (DEFAULT)
Lists the correct/total ratios for each interval stored in the
game settings separately.
= None
Lists the sum of correct/total answers with respect to
all intervals.
= at most twice nested lists of Intervals, e.g.
→ P5
Lists only the results concerning the P5 interval.
→ [P4, P5]
Lists the results concerning the P4 and P5 interval
separately.
→ [P4, [M3, m3]]
Lists the results concerning the P4 interval, and then
lists the total results concerning minor and major thirds.
→ [[P4, P5]]
Lists the total results concerning the perfect intervals.
→ "notes"...
= "full"
Lists the correct/total ratios for each note stored in
the game settings separately.
= None (DEFAULT)
Lists the sum of correct/total answers with respect to
all notes.
= at most twice nested lists of MIDInn-s, e.g.
→ C4
Lists only the results concerning the note C4.
→ [C4, D4]
Lists the results concerning the C4 and D4 notes
separately.
→ [C4, [G3, G4]]
Lists the results concerning the C4 note, and then lists
the total results concerning both G notes.
→ [[G3, G4, G5]]
Lists the total results concerning the three G notes.
→ "asc_desc"...
= "full" or "+-h"
Lists the correct/total ratios for ascending, descending and
harmonic intervals separately.
= None (DEFAULT)
Lists the sum of correct/total answers without discerning
ascending, descending or harmonic intervals.
= "+"/"-"/"h"
Lists the data only for ascending/descending/harmonic intervals
respectively.
= "m"
Lists the data concerning the melodic intervals, e.e. the
totals for both ascending and descending ones.
= "+-" or "-+"
= "+h" or "+h"
= "-h" or "h-"
= "mh" or "hm"
Applies the options corresponding to the above successively.
All of the above queries are based on the `normalized_product`
iterator. The process of parsing nested lists is explained in the
documentation of the this function. See also help-strings for
`Score`, `Score.total` and `Game._print_keys`.
"""
NAME = "Intervals"
def __init__(self, *args, **kwargs):
self.icset = ic_set_all
self.center = A4
self.spread = 12
self.adh = [-1,1]
super().__init__(*args, **kwargs)
def set_settings(self,
intervals=None,
center=None,
spread=None,
adh=None, **settings):
self.icset = intervals if intervals is not None else self.icset
self.spread = spread if spread is not None else self.spread
if center is not None:
self.center = MIDInn(center)
if adh:
self.adh = []
self.adh.append(-1) if "d" in adh else None
self.adh.append(0) if "h" in adh else None
self.adh.append(1) if "a" in adh else None
if not self.adh:
self.adh = [-1,1]
@property
def intervals(self):
return self.icset
@intervals.setter
def intervals(self, ic):
self.icset = ic
def _reset(self, session_name=None, **settings):
dct = {-1: "d", 0: "h", 1: "a"}
melo = "".join(sorted([dct[x] for x in self.adh]))
super()._reset(session_name,
intervals = self.icset,
center = self.center,
spread = self.spread,
adh = melo)
def _gen(self):
lo, hi = self.center - self.spread, self.center + self.spread
ctr = random.randint(lo, hi)
itc = random.choice(self.icset)
adh = random.choice(self.adh)
if adh == 0: # harmonic
# The correct answer is the interval measured upwards
# Uniformize distribution by switching top note with bottom one
# randomly.
if random.choice([True, False]):
# e.g. 69+5 vs 69-5 ~=~ 64+5. Note 69 is played anyway.
ctr-= int(itc)
return { "ctr": MIDInn(ctr), "itc": itc, "adh": adh }
def _exercise(self, ctr, itc, adh, **data):
sgn = -1 if adh == -1 else 1
self.play_notes(ctr, ctr+itc*sgn, (adh == 0))
inp = input(">> ")
ans = Interval.from_name(inp)
correct = itc
return inp, ans, correct
@staticmethod
def play_notes(note1, note2, simult):
# Some human variation for parameters
v1 = int(random.triangular(60,120))
v2 = int(random.triangular(60,120))
d1 = int(random.triangular(400,900))
d2 = int(random.triangular(-200,200))
if simult:
of = int(random.triangular(0,70,0))
note1,note2 = random.sample([note1,note2],2)
else:
of = d1+int(random.triangular(-100,500))
ev1 = alsamidi.noteevent(0, int(note1), v1, 0, d1)
ev2 = alsamidi.noteevent(0, int(note2), v2, of, d1+d2)
# Play sequence
alsaseq.start()
alsaseq.output(ev1)
alsaseq.output(ev2)
alsaseq.syncoutput()
alsaseq.stop()
def _store(self, ok, ctr, itc, adh, **data):
sgn = "+" if adh == 1 else "-" if adh == -1 else "h"
self._cur_score._store(ok, (ctr,sgn,itc))
def _details(self, score, adh=None, notes=None, **query):
# prepare args
if "intervals" not in query or query["intervals"]=="full":
if "intervals" in score.settings:
intervals = list(score.settings["intervals"])
else:
intervals = {q[2] for q in score.questions()}
intervals = sorted(list(intervals), key = lambda v: v.value)
else:
intervals = query["intervals"]
if notes=="full":
notes = {q[0] for q in score.questions()}
notes = sorted(list(notes), key = lambda v: v.value)
if adh=="full":
adh = ["+", "-", "h"]
elif adh is not None:
if "m" in adh:
adh = adh.replace("+","m").replace("-","m")
uniq = []
for char in adh:
if not char in uniq and char in "+-hm":
uniq.append(char)
adh = [ ["+", "-"] if e == "m" else e for e in uniq]
# prepare names
for nn, ad, ic in normalized_product(notes, adh, intervals):
namelist = []
mode = ["+","-"] if ad is None else ad
isnn = nn is not None and len(nn) == 1 and \
isinstance(nn[0], MIDInn)
isic = ic is not None and len(ic) == 1 and \
isinstance(ic[0], Interval)
if isnn:
namelist += [str(nn[0])]
namelist += ["".join(sorted(mode)).replace("+-", "m")]
if isic:
namelist += [str(ic[0])]
name = " ".join(namelist)
yield (name, (nn,mode,ic))
def _sum_scores(self, scores):
by_val = lambda x: x.value
ics = Score.sum_settings_list(scores, "intervals", by_val)
ctr = Score.sum_settings_simple(scores, "center")
spr = Score.sum_settings_simple(scores, "spread")
adh = Score.sum_settings_simple(scores, "adh")
return Score.sum_scores(scores, self.name+": Total",
intervals=ics, center=ctr, spread=spr, adh=adh)
| 39.555102 | 79 | 0.53947 | 9,568 | 0.982845 | 1,646 | 0.169081 | 879 | 0.090293 | 0 | 0 | 4,918 | 0.505187 |
d583e428836551045c331cfd1d586014de193689 | 9,585 | py | Python | condor_parser.py | ASchidler/pace17 | 755e9d652c7d4d9dd1f71fb508ebf773efee8488 | [
"MIT"
] | 1 | 2019-01-15T16:58:03.000Z | 2019-01-15T16:58:03.000Z | condor_parser.py | ASchidler/pace17 | 755e9d652c7d4d9dd1f71fb508ebf773efee8488 | [
"MIT"
] | null | null | null | condor_parser.py | ASchidler/pace17 | 755e9d652c7d4d9dd1f71fb508ebf773efee8488 | [
"MIT"
] | null | null | null | import os
import sys
from collections import defaultdict
import re
import pandas as pd
import matplotlib.pyplot as plt
class InstanceResult:
"""Represents the result of one instance run"""
def __init__(self):
# General info, name of the instance, run ID, time, memory und time for reductions
self.name = None
self.run = None
self.runtime = 0
self.memory = 0
self.reduce_time = 0
# vertex, edge, terminal count pre and post preprocessing. Only available for TU solver
self.v_start = -1
self.e_start = -1
self.t_start = -1
self.v_run = -1
self.e_run = -1
self.t_run = -1
# Result. Does the error file contain st? Out of memory, out of time, solved and what was the result?
self.error = False
self.mem_out = False
self.time_out = False
self.solved = False
self.result = -1
# Aggregation result. Divergence of numbers
self.memory_div = 0
self.runtime_div = 0
class OverallStatistic:
def __init__(self):
self.solved = 0
self.not_solved = 0
self.runtime = 0
self.memory = 0
self.runtime_div = 0
self.memory_div = 0
self.memory_out = 0
self.runtime_out = 0
self.common_runtime = 0
def parse_watcher(path, instance):
"""Parses the condor watcher file"""
f = open(path, "r")
for line in f:
if line.startswith("Real time"):
instance.runtime = float(line.split(":").pop())
elif line.startswith("Max. virtual"):
instance.memory = int(line.split(":").pop())
elif line.startswith("Maximum VSize exceeded"):
instance.mem_out = True
elif line.startswith("Maximum wall clock time exceeded"):
instance.mem_out = True
def parse_log(path, instance):
"""Parses the log file. Depending on the solver there may be more or less information"""
f = open(path, "r")
is_tu = None
def parse_counts(l):
m = re.search("([0-9]+) vertices.*?([0-9]+) edges.*?([0-9]+) terminals", l)
return int(m.group(1)), int(m.group(2)), int(m.group(3))
for line in f:
if is_tu is None:
if line.startswith("VALUE"):
instance.result = int(line.strip().split(" ").pop())
instance.solved = True
break
else:
is_tu = True
if is_tu:
if line.startswith("Loaded"):
instance.v_start, instance.e_start, instance.t_start = parse_counts(line)
elif line.startswith("Solving"):
instance.v_run, instance.e_run, instance.t_run = parse_counts(line)
elif line.startswith("Reductions completed"):
instance.reduce_time = float(line.split(" ").pop())
elif line.startswith("Final solution"):
instance.solved = True
instance.result = int(line.split(":").pop())
def parse_error(path, instance):
"""Parses the error file"""
instance.error = os.stat(path).st_size > 0
def aggregate_instance(instances):
"""Multiple runs cause multiple data for an instance to exist. This function aggregates it to one dataset"""
cnt = 0
new_instance = InstanceResult()
new_instance.run = "All"
mem_out = False
time_out = False
error = False
solved = False
for inst in instances:
new_instance.name = inst.name
solved |= inst.solved
mem_out |= inst.mem_out
time_out |= inst.time_out
error |= inst.error
if inst.solved:
cnt += 1
new_instance.solved = True
new_instance.result = inst.result
new_instance.v_run, new_instance.e_run, new_instance.t_run = inst.v_run, inst.e_run, inst.t_run
new_instance.v_start, new_instance.e_start, new_instance.t_start = inst.v_start, inst.e_start, inst.t_start
new_instance.memory += inst.memory
new_instance.reduce_time += inst.reduce_time
new_instance.runtime += inst.runtime
if cnt > 0:
new_instance.memory /= cnt
new_instance.reduce_time /= cnt
new_instance.runtime /= cnt
for inst in instances:
if inst.solved:
new_instance.runtime_div += abs(new_instance.runtime - inst.runtime)
new_instance.memory_div += abs(new_instance.memory_div - inst.memory)
else:
new_instance.time_out = time_out
new_instance.mem_out = mem_out
new_instance.error = error
return new_instance
def parse_run(base_path):
results = defaultdict(lambda: defaultdict(lambda: InstanceResult()))
for subdir, dirs, files in os.walk(base_path):
for f in files:
if f.endswith(".watcher"):
# Run ID is the last directory of the path
_, run_no = os.path.split(subdir)
# Get the instance name by stripping the .watcher extension
parts = f.split(".")
parts.pop()
instance_name = ".".join(parts)
# Set basic information
instance = results[instance_name][run_no]
instance.name = instance_name
instance.run = run_no
# Parse watcher file
parse_watcher(os.path.join(subdir, f), instance)
parse_log(os.path.join(subdir, instance_name + ".txt"), instance)
parse_error(os.path.join(subdir, instance_name + ".err"), instance)
return results
def calc_statistic(run_data):
all_stats = dict()
aggr_results = dict()
inst_results = defaultdict(list)
common_instances = defaultdict(lambda: 0)
for solver, instances in run_data.items():
stats = OverallStatistic()
result_list = []
for name, runs in instances.items():
result_list.append(aggregate_instance(runs.values()))
aggr_results[solver] = result_list
result_list.sort(key=lambda x: x.name)
for instance in result_list:
inst_results[instance.name].append(instance)
stats.runtime_div += instance.runtime_div
stats.memory_div += instance.memory_div
stats.runtime += instance.runtime
stats.memory += instance.memory
if instance.solved:
common_instances[instance.name] += 1
stats.solved += 1
else:
stats.not_solved += 1
if instance.mem_out:
stats.memory_out += 1
elif instance.time_out:
stats.runtime_out += 1
all_stats[solver] = stats
total = len(all_stats)
for solver, instances in aggr_results.items():
for inst in instances:
if common_instances[inst.name] == total:
all_stats[solver].common_runtime += inst.runtime
return all_stats, aggr_results, inst_results
def parse_benchmark(base_path):
# Find results folder
def search_folder(start_path):
for new_name in os.listdir(start_path):
new_path = os.path.join(start_path, new_name)
if os.path.isdir(new_path):
if new_name == "results":
return new_path
else:
sub_res = search_folder(new_path)
if sub_res is not None:
return sub_res
return None
target_path = search_folder(base_path)
results = dict()
for benchmark in os.listdir(target_path):
benchmark_path = os.path.join(target_path, benchmark)
if os.path.isdir(benchmark_path):
results[benchmark] = parse_run(benchmark_path)
all_stats, aggr_results, inst_results = calc_statistic(results)
benchmarks = aggr_results.keys()
benchmarks.sort()
for benchmark in benchmarks:
stats = all_stats[benchmark]
print "{}: Completed {}, Not {}, Runtime: {}, Divergence {}".format(benchmark, stats.solved, stats.not_solved,
stats.runtime, stats.runtime_div)
def parse_results(base_path, targets):
results = dict()
for name in os.listdir(base_path):
if name in targets:
full_path = os.path.join(base_path, name)
if os.path.isdir(full_path):
results[name] = parse_run(full_path)
all_stats, aggr_results, _ = calc_statistic(results)
results = aggr_results.items()
results.sort()
frames = []
names = []
for solver, instances in results:
vals = [x.runtime for x in instances if x.solved]
vals.sort()
frames += [pd.DataFrame(vals)]
names.append(solver)
stats = all_stats[solver]
print "{}: Completed {}, Not {}, Runtime: {}, Divergence {}, Common {}"\
.format(solver, stats.solved, stats.not_solved, stats.runtime, stats.runtime_div, stats.common_runtime)
frame = pd.concat(frames, ignore_index=True, axis=1)
frame.cumsum()
ax = frame.plot(style=['bs-', 'ro-', 'y^-', 'g*-'], figsize=(10,5))
ax.legend(names)
axes = plt.axes()
axes.set_xlabel("instances")
axes.set_ylabel("time (s)")
axes.set_xlim(100, 200)
plt.show()
pth = sys.argv[1]
trg = {sys.argv[i] for i in range(2, len(sys.argv))}
if len(trg) == 1:
parse_benchmark(os.path.join(pth, trg.pop()))
else:
parse_results(sys.argv[1], trg)
| 32.491525 | 119 | 0.592593 | 1,216 | 0.126865 | 0 | 0 | 0 | 0 | 0 | 0 | 1,209 | 0.126135 |
d585f8540e934ba68420f975699c9080a2e5b0cd | 100,242 | py | Python | apps/vtktools/vtkToolsGUI.py | rboman/progs | c60b4e0487d01ccd007bcba79d1548ebe1685655 | [
"Apache-2.0"
] | 2 | 2021-12-12T13:26:06.000Z | 2022-03-03T16:14:53.000Z | apps/vtktools/vtkToolsGUI.py | rboman/progs | c60b4e0487d01ccd007bcba79d1548ebe1685655 | [
"Apache-2.0"
] | 5 | 2019-03-01T07:08:46.000Z | 2019-04-28T07:32:42.000Z | apps/vtktools/vtkToolsGUI.py | rboman/progs | c60b4e0487d01ccd007bcba79d1548ebe1685655 | [
"Apache-2.0"
] | 2 | 2017-12-13T13:13:52.000Z | 2019-03-13T20:08:15.000Z | #! /usr/bin/env python3
# -*- coding: utf-8; -*-
#
# vtkToolsGUI - VTK/Tk/Python interface by RoBo - modified by vidot
# - modified by MM to create a distributable exe independent of Metafor
# jan 2019:
# F:\src\VTK-7.1.0\Wrapping\Python\vtk\tk\vtkLoadPythonTkWidgets.py
# change "vtkCommonCorePython" => "vtk.vtkCommonCorePython"
from future import standard_library
standard_library.install_aliases()
import os.path
import os
import meshingTools
import imagingTools
import generalTools
import renderingTools
import Pmw
from vtk.tk.vtkTkImageViewerWidget import *
import tkinter.messagebox
import tkinter.filedialog
from tkinter import *
from vtk.tk.vtkTkRenderWindowInteractor import vtkTkRenderWindowInteractor
from vtk.tk.vtkTkRenderWidget import *
import vtk
createExe = True
if __name__ == "__main__" and not createExe:
import os
import sys
rcfile = os.environ.get('PYTHONSTARTUP')
if os.path.isfile(rcfile):
sys.path.append(os.path.dirname(rcfile))
exec(open(rcfile).read())
if 0:
# disable warnings!
obj = vtk.vtkObject()
obj.GlobalWarningDisplayOff()
del obj
# ----------------------------------------------------------------------
class VtkWindow3DPoly(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack(side="top", expand=TRUE, fill=BOTH)
self.createWidgets()
def createWidgets(self):
self.vtkwidget = vtkTkRenderWidget(self, width=600, height=600)
self.ren = vtk.vtkRenderer()
if createExe:
self.ren.SetBackground(1., 1., 1.)
else:
self.ren.SetBackground(0.2, 0.3, 0.6)
self.vtkwidget.GetRenderWindow().AddRenderer(self.ren)
self.vtkwidget.pack(side="top", expand=TRUE, fill=BOTH)
title = Label(self, text='3D View')
title.pack(side="top", expand=FALSE, fill=BOTH)
def view(self, polydata, scalarsOn=False, edgesOn=False, colorMap='GrayScale'):
actor = renderingTools.createGridActor(
polydata, showScalar=scalarsOn, showEdges=edgesOn, colorMap=colorMap)
self.ren.AddActor(actor)
if scalarsOn:
propT = vtk.vtkTextProperty()
propT.ItalicOff()
propT.BoldOff()
propT.SetColor(0., 0., 0.)
propT.SetFontFamilyToArial()
propT.SetFontSize(50)
scalarBar = vtk.vtkScalarBarActor()
scalarBar.SetLookupTable(actor.GetMapper().GetLookupTable())
scalars = polydata.GetPointData().GetScalars()
if scalars == None:
scalars = polydata.GetPointData().GetArray(0)
if scalars == None:
scalars = polydata.GetCellData().GetScalars()
scalarBar.SetTitle(scalars.GetName())
scalarBar.SetTitleTextProperty(propT)
scalarBar.SetLabelTextProperty(propT)
self.ren.AddActor2D(scalarBar)
outline = renderingTools.createOutlineActor(polydata)
self.ren.AddActor(outline)
axes = vtk.vtkCubeAxesActor2D()
axes.SetCamera(self.ren.GetActiveCamera())
axes.SetViewProp(outline)
self.ren.AddActor(axes)
self.ren.ResetCamera()
cam1 = self.ren.GetActiveCamera()
cam1.Elevation(-70)
cam1.SetViewUp(0, 0, 1)
cam1.Azimuth(30)
self.ren.ResetCameraClippingRange()
self.vtkwidget.Render()
class VtkWindow3DPolyCut(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack(side="top", expand=TRUE, fill=BOTH)
self.createWidgets()
master.protocol("WM_DELETE_WINDOW", self.quitcallback)
def createWidgets(self):
self.ren = vtk.vtkRenderer()
self.ren.SetBackground(1., 1., 1.)
self.renWin = vtk.vtkRenderWindow()
self.renWin.AddRenderer(self.ren)
self.vtkwidget = vtkTkRenderWindowInteractor(
self, rw=self.renWin, width=600, height=600)
self.vtkwidget.pack(side="top", expand=TRUE, fill=BOTH)
title = Label(self, text='3D View')
title.pack(side="top", expand=FALSE, fill=BOTH)
def viewClip(self, polydata, scalarsOn=False, edgesOn=False, colorMap='GrayScale'):
iren = self.vtkwidget.GetRenderWindow().GetInteractor()
# tyrackball par defaut
iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
global plane, cutActor, clipActor
plane = vtk.vtkPlane()
bounds = polydata.GetBounds()
plane.SetOrigin((bounds[0]+bounds[1])/2.,
(bounds[2]+bounds[3])/2., (bounds[4]+bounds[5])/2.)
[cutActor, clipActor] = renderingTools.createClipActor(
polydata, plane, showScalar=scalarsOn, showEdges=edgesOn, colorMap=colorMap)
def planeWidgetCallback(obj, event):
obj.GetPlane(plane)
cutActor.VisibilityOn()
clipActor.VisibilityOn()
self.planeWidget = renderingTools.createPlaneWidget(polydata)
self.planeWidget.AddObserver("InteractionEvent", planeWidgetCallback)
self.planeWidget.SetInteractor(iren)
self.planeWidget.On()
self.ren.AddActor(cutActor)
self.ren.AddActor(clipActor)
if scalarsOn:
propT = vtk.vtkTextProperty()
propT.ItalicOff()
propT.BoldOff()
propT.SetColor(0., 0., 0.)
propT.SetFontSize(20)
scalarBar = vtk.vtkScalarBarActor()
scalarBar.SetLookupTable(clipActor.GetMapper().GetLookupTable())
scalars = polydata.GetPointData().GetScalars()
if scalars == None:
scalars = polydata.GetPointData().GetArray(0)
if scalars == None:
scalars = polydata.GetCellData().GetScalars()
scalarBar.SetTitle(scalars.GetName())
scalarBar.SetTitleTextProperty(propT)
scalarBar.SetLabelTextProperty(propT)
self.ren.AddActor2D(scalarBar)
outline = renderingTools.createOutlineActor(polydata)
self.ren.AddActor(outline)
axes = vtk.vtkCubeAxesActor2D()
axes.SetCamera(self.ren.GetActiveCamera())
axes.SetViewProp(outline)
self.ren.AddActor(axes)
self.ren.ResetCamera()
cam1 = self.ren.GetActiveCamera()
cam1.Elevation(-70)
cam1.SetViewUp(0, 0, 1)
cam1.Azimuth(30)
self.ren.ResetCameraClippingRange()
self.vtkwidget.Render()
def quitcallback(self):
del self.ren
del self.renWin # vtk veut qu'on vire ce truc avant fermeture
del self.vtkwidget
del self.planeWidget
self.master.destroy()
# ----------------------------------------------------------------------
class VtkWindow3Planes(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack(side="top", expand=TRUE, fill=BOTH)
self.createWidgets()
master.protocol("WM_DELETE_WINDOW", self.quitcallback)
def createWidgets(self):
self.ren = vtk.vtkRenderer()
if createExe:
self.ren.SetBackground(1., 1., 1.)
else:
self.ren.SetBackground(0.2, 0.3, 0.6)
self.renWin = vtk.vtkRenderWindow()
self.renWin.AddRenderer(self.ren)
self.vtkwidget = vtkTkRenderWindowInteractor(
self, rw=self.renWin, width=600, height=600)
self.vtkwidget.pack(side="top", expand=TRUE, fill=BOTH)
title = Label(self, text='3 Planes View')
title.pack(side="top", expand=FALSE, fill=BOTH)
def view(self, image, window, level):
self.planeWidgetX, self.planeWidgetY, self.planeWidgetZ = renderingTools.create3Planes(
image)
iren = self.vtkwidget.GetRenderWindow().GetInteractor()
# tyrackball par defaut
iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
self.planeWidgetX.SetInteractor(iren)
self.planeWidgetX.On()
self.planeWidgetY.SetInteractor(iren)
self.planeWidgetY.On()
self.planeWidgetZ.SetInteractor(iren)
self.planeWidgetZ.On()
# apres le "on" (un seul suffit!)
self.planeWidgetZ.SetWindowLevel(window, level)
outline = renderingTools.createOutlineActor(image)
self.ren.AddActor(outline)
axes = vtk.vtkCubeAxesActor2D()
axes.SetCamera(self.ren.GetActiveCamera())
axes.SetViewProp(outline)
self.ren.AddActor(axes)
self.ren.ResetCamera()
cam1 = self.ren.GetActiveCamera()
cam1.Elevation(-70)
cam1.SetViewUp(0, 0, 1)
cam1.Azimuth(30)
self.ren.ResetCameraClippingRange()
self.vtkwidget.Render()
def quitcallback(self):
del self.ren
del self.renWin # vtk veut qu'on vire ce truc avant fermeture
del self.vtkwidget
del self.planeWidgetX
del self.planeWidgetY
del self.planeWidgetZ
self.master.destroy()
# ----------------------------------------------------------------------
def CheckAbort(obj, event):
if obj.GetEventPending() != 0:
obj.SetAbortRender(1)
class ClipCallBack:
def __init__(self, planes, volumeMapper):
self.planes = planes
self.volumeMapper = volumeMapper
def callback(self, obj, event):
obj.GetPlanes(self.planes)
self.volumeMapper.SetClippingPlanes(self.planes)
class InteractionCallBack:
def __init__(self, renWin):
self.renWin = renWin
def start(self, obj, event):
self.renWin.SetDesiredUpdateRate(10)
def end(self, obj, event):
self.renWin.SetDesiredUpdateRate(0.001)
# ----------------------------------------------------------------------
class VtkWindowVolumic(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack(side="top", expand=TRUE, fill=BOTH)
self.createWidgets()
master.protocol("WM_DELETE_WINDOW", self.quitcallback)
def createWidgets(self):
self.ren = vtk.vtkRenderer()
if createExe:
self.ren.SetBackground(1., 1., 1.)
else:
self.ren.SetBackground(0.2, 0.3, 0.6)
self.renWin = vtk.vtkRenderWindow()
self.renWin.AddRenderer(self.ren)
self.vtkwidget = vtkTkRenderWindowInteractor(
self, rw=self.renWin, width=600, height=600)
self.vtkwidget.pack(side="top", expand=TRUE, fill=BOTH)
title = Label(self, text='Volumic View')
title.pack(side="top", expand=FALSE, fill=BOTH)
def view(self, image):
iren = self.vtkwidget.GetRenderWindow().GetInteractor()
# tyrackball par defaut
iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
image = generalTools.castImage(image, 'uchar')
volume, self.volumeMapper = renderingTools.createVolume(image)
self.ren.AddVolume(volume)
self.planes = vtk.vtkPlanes()
outline = renderingTools.createOutlineActor(image)
self.ren.AddActor(outline)
self.boxWidget = renderingTools.createBoxWidget(image, iren)
self.clip_cb = ClipCallBack(self.planes, self.volumeMapper)
self.boxWidget.AddObserver("InteractionEvent", self.clip_cb.callback)
self.inter_cb = InteractionCallBack(self.renWin)
self.boxWidget.AddObserver(
"StartInteractionEvent", self.inter_cb.start)
self.boxWidget.AddObserver("EndInteractionEvent", self.inter_cb.end)
self.renWin.AddObserver("AbortCheckEvent", CheckAbort)
self.ren.ResetCamera()
cam1 = self.ren.GetActiveCamera()
cam1.Elevation(-70)
cam1.SetViewUp(0, 0, 1)
cam1.Azimuth(30)
self.ren.ResetCameraClippingRange()
self.vtkwidget.Render()
def StartInteraction(self, obj, event):
self.renWin.SetDesiredUpdateRate(10)
def EndInteraction(obj, event):
self.renWin.SetDesiredUpdateRate(0.001)
def ClipVolumeRender(obj, event):
obj.GetPlanes(self.planes)
self.volumeMapper.SetClippingPlanes(self.planes)
def quitcallback(self):
del self.ren
del self.renWin # vtk veut qu'on vire ce truc avant fermeture
del self.planes
del self.clip_cb
del self.inter_cb
del self.boxWidget
del self.vtkwidget
self.master.destroy()
# ----------------------------------------------------------------------
class VtkWindow2D(Frame):
def __init__(self, master=None, size=(600, 600), range=(0, 50)):
Frame.__init__(self, master)
self.pack()
self.createWidgets(size, range)
master.protocol("WM_DELETE_WINDOW", self.quitcallback)
def createWidgets(self, size, range):
vtkwidget = vtkTkImageViewerWidget(self, width=size[0], height=size[1])
vtkwidget.pack(side="top", expand=1)
self.viewer = vtkwidget.GetImageViewer()
self.scale = Scale(self, orient=HORIZONTAL, length=200,
from_=range[0], to=range[1], tickinterval=(range[1]-range[0])/4, font=('Helvetica', 8),
command=self.selectSlice)
self.scale.pack()
title = Label(self, text='2D View')
title.pack()
def selectSlice(self, val):
self.viewer.SetZSlice(self.scale.get())
self.viewer.Render()
def view(self, image, sliceno, window, level):
self.viewer.SetInput(image)
self.viewer.SetZSlice(sliceno)
self.viewer.SetColorWindow(window)
self.viewer.SetColorLevel(level)
self.viewer.Render()
self.scale.set(sliceno)
def quitcallback(self):
del self.viewer # vtk veut qu'on vire ce truc avant fermeture
self.master.destroy()
# ----------------------------------------------------------------------
class MainWindow:
def __init__(self, master):
master.protocol("WM_DELETE_WINDOW", self.quitCallback)
self.master = master
self.status = StringVar()
self.createMenu()
self.createPages()
self.createStatusBar()
self.loadConfig()
self.status.set("Ready.")
def createPages(self):
notebook = Pmw.NoteBook(self.master)
notebook.pack(fill=BOTH, expand=YES, padx=4, pady=2)
# Add the "Imaging" page to the notebook.
page = notebook.add('Imaging')
self.imagingPage = ImagingFrame(page, self.status, self)
self.imagingPage.pack(fill=BOTH, expand=YES)
# Add the "Polydata" page to the notebook.
page = notebook.add('Polydata')
self.polydataPage = PolyDataFrame(page, self.status, self)
self.polydataPage.pack(fill=BOTH, expand=YES)
# Add the "Ugrid" page to the notebook.
page = notebook.add('Ugrid')
self.ugridPage = UgridFrame(page, self.status)
self.ugridPage.pack(fill=BOTH, expand=YES)
notebook.tab('Imaging').focus_set()
notebook.setnaturalsize()
def createMenu(self):
menu = Menu(self.master)
self.master.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Load parameters",
command=self.askLoadConfig)
filemenu.add_command(label="Save parameters",
command=self.askSaveConfig)
filemenu.add_command(label="Quit", command=self.quitCallback)
helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_command(label="Help", command=self.showHelp)
helpmenu.add_command(label="About", command=self.aboutCallback)
def createStatusBar(self):
# status bar
statusFrame = Frame(self.master, borderwidth=1) # , background="red")
statusFrame.pack(fill=X, expand=NO)
Label(statusFrame, textvariable=self.status, bd=1, relief=SUNKEN,
anchor=W).pack(fill=X, expand=YES, pady=2, padx=2)
def quitCallback(self):
# if tkMessageBox.askokcancel("Quit","Are you sure?"):
self.saveConfig()
self.master.destroy()
def aboutCallback(self):
Pmw.aboutversion('2.1')
Pmw.aboutcopyright('Copyright LTAS-MN2L 2013\nAll rights reserved')
Pmw.aboutcontact(
'For information about this application contact:\n' +
' Romain BOMAN\n' +
' Phone: +32 4 366 91 85\n' +
' email: r.boman@ulg.ac.be'
)
self.about = Pmw.AboutDialog(self.master, applicationname='VTK GUI')
self.about.show()
def saveConfig(self, filename='ImagingGUI.cfg'):
file = open(filename, 'w')
if file:
self.imagingPage.saveConfig('imagingPage', file)
self.polydataPage.saveConfig('polydataPage', file)
file.close()
def loadConfig(self, filename='ImagingGUI.cfg'):
try:
file = open(filename, 'r')
if file:
for line in file:
exec(line)
file.close()
except:
pass
self.imagingPage.loadConfig()
self.polydataPage.loadConfig()
def setPolydata(self, poly):
self.polydataPage.setPolydata(poly)
def setUgrid(self, ugrid):
self.ugridPage.setUgrid(ugrid)
def askLoadConfig(self):
fname = tkinter.filedialog.Open(
filetypes=[('Config file', '*.cfg'), ('All Files', '*.*')]).show()
if fname:
self.loadConfig(fname)
self.status.set("Config loaded from %s." % fname)
else:
self.status.set("Canceled.")
def askSaveConfig(self):
fname = tkinter.filedialog.SaveAs(
filetypes=[('Config file', '*.cfg')]).show()
if fname:
self.saveConfig(fname)
self.status.set("Config saved to %s." % fname)
else:
self.status.set("Canceled.")
def showHelp(self):
message = """
- ne pas manipuler des fichiers avec des espaces dans le nom
- lorsqu'on double-clique sur un dialog, le clic est transmis à la fenêtre en dessous!"""
Pmw.MessageDialog(self.master, title="Help", buttons=('Close',),
message_text=message, message_justify='left',
icon_bitmap='info', iconpos='w')
# ----------------------------------------------------------------------
class ImagingFrame(Frame):
def __init__(self, master, status, mainW):
Frame.__init__(self, master)
self.mainW = mainW
self.status = status
self.balloon = Pmw.Balloon(master) # aide "ballon"
self.image = None # image
self.vtkwin = None # fenetre VTK
self.datadir = '../../geniso/data/'
self.lastloaddir = '.'
self.lastsavedir = '.'
self.createWidgets()
def createDataFrame(self):
frame1 = Frame(self, bd=1, relief=GROOVE)
frame1.pack(fill=X, expand=NO)
Label(frame1, text="Image Data", bg='gray', fg='black').pack(
expand=YES, fill=X, padx=2, pady=2)
frame2 = Frame(frame1)
frame2.pack(fill=X, expand=NO)
# la colonne 2 (vide) va pouvoir s'agrandir
frame2.columnconfigure(2, weight=1)
nrow = 0 # first line
label = Label(frame2, text="filename")
label.grid(row=nrow, column=0, padx=5, pady=2, sticky=W)
self.balloon.bind(label, "filename of the image")
self.filename = StringVar()
self.filename.set('')
self.fnameField = Pmw.ScrolledField(frame2, entry_width=30, entry_relief=GROOVE,
text=self.filename.get())
self.fnameField.grid(row=nrow, column=1, padx=5,
pady=2, columnspan=2, sticky=NSEW)
nrow = nrow+1 # next line
label = Label(frame2, text="extent")
label.grid(row=nrow, column=0, padx=5, pady=2, sticky=W)
self.balloon.bind(label, "image resolution = number of voxels (x,y,z)")
self.extx1 = IntVar()
self.extx1.set(0)
self.extx2 = IntVar()
self.extx2.set(255)
self.exty1 = IntVar()
self.exty1.set(0)
self.exty2 = IntVar()
self.exty2.set(255)
self.extz1 = IntVar()
self.extz1.set(0)
self.extz2 = IntVar()
self.extz2.set(59)
frame = Frame(frame2)
frame.grid(row=nrow, column=1, padx=5, pady=2, sticky=NSEW)
Entry(frame, textvariable=self.extx1, width=6).pack(side=LEFT)
Entry(frame, textvariable=self.extx2, width=6).pack(side=LEFT)
Entry(frame, textvariable=self.exty1, width=6).pack(side=LEFT)
Entry(frame, textvariable=self.exty2, width=6).pack(side=LEFT)
Entry(frame, textvariable=self.extz1, width=6).pack(side=LEFT)
Entry(frame, textvariable=self.extz2, width=6).pack(side=LEFT)
nrow = nrow+1 # next line
label = Label(frame2, text="spacing")
label.grid(row=nrow, column=0, padx=5, pady=2, sticky=W)
self.balloon.bind(label, "size of the voxels (x,y,z)")
self.sx = DoubleVar()
self.sx.set(0.9375)
self.sy = DoubleVar()
self.sy.set(0.9375)
self.sz = DoubleVar()
self.sz.set(2.5)
frame = Frame(frame2)
frame.grid(row=nrow, column=1, padx=5, pady=2, sticky=NSEW)
Entry(frame, textvariable=self.sx, width=6).pack(side=LEFT)
Entry(frame, textvariable=self.sy, width=6).pack(side=LEFT)
Entry(frame, textvariable=self.sz, width=6).pack(side=LEFT)
nrow = nrow+1 # next line
label = Label(frame2, text="coding")
label.grid(row=nrow, column=0, padx=5, pady=2, sticky=W)
self.balloon.bind(label, "size/type of the data")
frame = Frame(frame2)
frame.grid(row=nrow, column=1, padx=5, pady=2, sticky=NSEW)
self.coding = StringVar()
self.coding.set('uchar')
self.codingCombo = Pmw.ComboBox(frame, scrolledlist_items=("uchar", "ushort", "short", "double"),
listheight=100, selectioncommand=self.codingCallBack, dropdown=True)
self.codingCombo.pack(side=LEFT)
self.codingCombo.selectitem('uchar')
nrow = nrow+1 # next line
label = Label(frame2, text="byteorder")
label.grid(row=nrow, column=0, padx=5, pady=2, sticky=W)
self.balloon.bind(
label, "type of the computer (PC/Compaq=little endian ; Sun=big endian)")
frame = Frame(frame2)
frame.grid(row=nrow, column=1, padx=5, pady=2, sticky=NSEW)
self.byteorder = StringVar()
but1 = Radiobutton(frame, text='little',
variable=self.byteorder, value='little')
but1.pack(side=LEFT)
but2 = Radiobutton(frame, text='big',
variable=self.byteorder, value='big')
but2.pack(side=LEFT)
but1.select()
nrow = nrow+1 # next line
label = Label(frame2, text="scalar range")
label.grid(row=nrow, column=0, padx=5, pady=2, sticky=W)
self.balloon.bind(label, "range of the scalar data (min, max)")
frame = Frame(frame2)
frame.grid(row=nrow, column=1, padx=5, pady=2, sticky=NSEW)
self.scalarrange = StringVar()
self.scalarrange.set("unknown")
Label(frame, textvariable=self.scalarrange).pack(side=LEFT, padx=2)
button = Button(frame, text='More Info',
command=self.moreInfo, anchor="w")
button.pack(side=RIGHT, padx=0)
self.balloon.bind(button, "print more info concerning the VTK object")
def createCreateFrame(self):
group = Pmw.Group(self, tag_text='Create')
group.pack(fill=X, expand=NO, pady=5)
creFrame = group.interior()
creFrame.columnconfigure(8, weight=1)
nrow = 0
button = Button(creFrame, text='Ellispoid',
command=self.creEllispoid, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(
button, "create an ellipsoid with the parameters on the right")
frame = Frame(creFrame)
frame.grid(row=0, column=2, padx=5, pady=2, sticky=W)
label = Label(frame, text="C")
label.grid(row=0, column=0, padx=5, pady=2, sticky=E)
self.balloon.bind(label, "center position (x,y,z) of the ellipsoid")
self.cx = IntVar()
self.cx.set(127)
Entry(frame, textvariable=self.cx, width=5).grid(
row=0, column=1, padx=5, pady=2, sticky=W)
self.cy = IntVar()
self.cy.set(127)
Entry(frame, textvariable=self.cy, width=5).grid(
row=0, column=2, padx=5, pady=2, sticky=W)
self.cz = IntVar()
self.cz.set(127)
Entry(frame, textvariable=self.cz, width=5).grid(
row=0, column=3, padx=5, pady=2, sticky=W)
label = Label(frame, text="V")
label.grid(row=nrow, column=4, sticky=E)
self.balloon.bind(label, "values (in, out) of the ellipsoid")
self.valin = IntVar()
self.valin.set(255)
Entry(frame, textvariable=self.valin, width=5).grid(
row=0, column=5, padx=5, pady=2, sticky=W)
self.valout = IntVar()
self.valout.set(0)
Entry(frame, textvariable=self.valout, width=5).grid(
row=0, column=6, padx=5, pady=2, sticky=W)
label = Label(frame, text="R")
label.grid(row=1, column=0, padx=5, pady=2, sticky=E)
self.balloon.bind(label, "radii (rx,ry,rz) of the ellipsoid")
self.rx = IntVar()
self.rx.set(50)
Entry(frame, textvariable=self.rx, width=5).grid(
row=1, column=1, padx=5, pady=2, sticky=W)
self.ry = IntVar()
self.ry.set(70)
Entry(frame, textvariable=self.ry, width=5).grid(
row=1, column=2, padx=5, pady=2, sticky=W)
self.rz = IntVar()
self.rz.set(90)
Entry(frame, textvariable=self.rz, width=5).grid(
row=1, column=3, padx=5, pady=2, sticky=W)
def createModifyFrame(self):
group = Pmw.Group(self, tag_text='Modify/Filters')
group.pack(fill=X, expand=NO, pady=5)
modFrame = group.interior()
modFrame.columnconfigure(5, weight=1)
nrow = 0
button = Button(modFrame, text='Flip Image',
command=self.modFlip, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(button, "apply a vtkImageFlip")
frame = Frame(modFrame)
frame.grid(row=nrow, column=1, sticky=W+E)
label = Label(frame, text="Axis")
label.pack(side=LEFT, padx=2)
self.balloon.bind(label, "Specify axis to flip")
self.flipAxis = DoubleVar()
self.flipAxis.set(1)
Entry(frame, textvariable=self.flipAxis,
width=5).pack(side=LEFT, padx=2)
button = Button(modFrame, text='Permute',
command=self.permute, anchor="w")
button.grid(row=nrow, column=2, padx=5, pady=2, sticky=W+E)
self.balloon.bind(button, "Permute Image")
frame = Frame(modFrame)
frame.grid(row=nrow, column=3, sticky=W+E)
label = Label(frame, text="Axis")
label.pack(side=LEFT, padx=2)
self.balloon.bind(
label, "Specify the input axes that will become X, Y, Z")
self.axX = DoubleVar()
self.axX.set(1)
Entry(frame, textvariable=self.axX, width=5).pack(side=LEFT, padx=2)
self.axY = DoubleVar()
self.axY.set(1)
Entry(frame, textvariable=self.axY, width=5).pack(side=LEFT, padx=2)
self.axZ = DoubleVar()
self.axZ.set(1)
Entry(frame, textvariable=self.axZ, width=5).pack(side=LEFT, padx=2)
nrow = nrow + 1
button = Button(modFrame, text='Negative',
command=self.modNegative, anchor="w")
button.grid(row=nrow, column=1, padx=5, pady=2, sticky=W+E)
self.balloon.bind(
button, "apply a vtkImageMathematics (SetOperationToInvert)")
button = Button(modFrame, text='Distance map',
command=self.modCreateSignedEuclideanDistanceMap, anchor="w")
button.grid(row=nrow, column=2, padx=5, pady=2, sticky=W+E)
self.balloon.bind(button, "build the energy map")
nrow = nrow+1
button = Button(modFrame, text='Reslice Nearest',
command=self.resliceWithNearestNeighbor, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(button, "resliceWithNearestNeighbor")
button = Button(modFrame, text='Reslice Linear',
command=self.resliceWithLinearInterpolation, anchor="w")
button.grid(row=nrow, column=1, padx=5, pady=2, sticky=W+E)
self.balloon.bind(button, "resliceWithLinearInterpolation")
button = Button(modFrame, text='Reslice Cubic',
command=self.resliceWithCubicInterpolation, anchor="w")
button.grid(row=nrow, column=2, padx=5, pady=2, sticky=W+E)
self.balloon.bind(button, "resliceWithCubicInterpolation")
frame = Frame(modFrame)
frame.grid(row=nrow, column=3, sticky=W+E)
label = Label(frame, text="spacing")
label.pack(side=LEFT, padx=2)
self.balloon.bind(label, "spacing to witch to reslice")
self.spx = DoubleVar()
self.spx.set(1)
Entry(frame, textvariable=self.spx, width=5).pack(side=LEFT, padx=2)
self.spy = DoubleVar()
self.spy.set(1)
Entry(frame, textvariable=self.spy, width=5).pack(side=LEFT, padx=2)
self.spz = DoubleVar()
self.spz.set(1)
Entry(frame, textvariable=self.spz, width=5).pack(side=LEFT, padx=2)
nrow = nrow+1
button = Button(modFrame, text='Erode', command=self.erode, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(button, "Erode")
button = Button(modFrame, text='Dilate',
command=self.dilate, anchor="w")
button.grid(row=nrow, column=1, padx=5, pady=2, sticky=W+E)
self.balloon.bind(button, "Dilate")
frame = Frame(modFrame)
frame.grid(row=nrow, column=2, sticky=W+E)
label = Label(frame, text="kernel")
label.pack(side=LEFT, padx=2)
self.balloon.bind(label, "kernel")
self.kx = IntVar()
self.kx.set(3)
Entry(frame, textvariable=self.kx, width=5).pack(side=LEFT, padx=2)
self.ky = IntVar()
self.ky.set(3)
Entry(frame, textvariable=self.ky, width=5).pack(side=LEFT, padx=2)
self.kz = IntVar()
self.kz.set(3)
Entry(frame, textvariable=self.kz, width=5).pack(side=LEFT, padx=2)
nrow = nrow+1
button = Button(modFrame, text='OpenClose3D',
command=self.openClose3D, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(button, "OpenClose3D")
frame = Frame(modFrame)
frame.grid(row=nrow, column=1, sticky=W+E)
label = Label(frame, text="openValue")
label.pack(side=LEFT, padx=2)
self.balloon.bind(label, "openValue")
self.openValue = DoubleVar()
self.openValue.set(0)
Entry(frame, textvariable=self.openValue,
width=5).pack(side=LEFT, padx=2)
label = Label(frame, text="closeValue")
label.pack(side=LEFT, padx=2)
self.balloon.bind(label, "closeValue")
self.closeValue = DoubleVar()
self.closeValue.set(3)
Entry(frame, textvariable=self.closeValue,
width=5).pack(side=LEFT, padx=2)
label = Label(frame, text="kernel")
label.pack(side=LEFT, padx=2)
self.balloon.bind(label, "kernel")
self.kx = IntVar()
self.kx.set(3)
Entry(frame, textvariable=self.kx, width=5).pack(side=LEFT, padx=2)
self.ky = IntVar()
self.ky.set(3)
Entry(frame, textvariable=self.ky, width=5).pack(side=LEFT, padx=2)
self.kz = IntVar()
self.kz.set(3)
Entry(frame, textvariable=self.kz, width=5).pack(side=LEFT, padx=2)
nrow = nrow+1
button = Button(modFrame, text='Threshold',
command=self.modThreshold, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(button, "threshold image")
frame = Frame(modFrame)
frame.grid(row=nrow, column=1, sticky=W+E)
label = Label(frame, text="threshold")
label.pack(side=LEFT, padx=2)
self.balloon.bind(label, "threshold used to segment image")
self.th = IntVar()
self.th.set(4)
Entry(frame, textvariable=self.th, width=5).pack(side=LEFT, padx=2)
nrow = nrow+1
button = Button(modFrame, text='Extract Iso',
command=self.buildIsoValue, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(
button, "build the skin of the image using vtkContourFilter\n (resulting mesh on the \"Polydata\" tab)")
frame = Frame(modFrame)
frame.grid(row=nrow, column=1, sticky=W+E)
label = Label(frame, text="range")
label.pack(side=LEFT, padx=2)
self.balloon.bind(label, "range used by vtkContourFilter")
self.range1 = IntVar()
self.range1.set(0)
Entry(frame, textvariable=self.range1, width=5).pack(side=LEFT, padx=2)
self.range2 = IntVar()
self.range2.set(2)
Entry(frame, textvariable=self.range2, width=5).pack(side=LEFT, padx=2)
nrow = nrow+1
button = Button(modFrame, text='Isosurf',
command=self.execIsosurf, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(
button, "run Isosurf (resulting mesh on the \"Polydata\" tab)")
frame = Frame(modFrame)
frame.grid(row=nrow, column=1, sticky=W+E)
label = Label(frame, text="res")
label.pack(side=LEFT, padx=2)
self.balloon.bind(label, "resolution used by isosurf")
self.isores = IntVar()
self.isores.set(4)
Entry(frame, textvariable=self.isores, width=5).pack(side=LEFT, padx=2)
# nrow=nrow+1
# frame = Frame(modFrame); frame.grid(row=nrow, column=2, sticky = W+E)
# label = Label(frame, text="exec"); label.pack(side=LEFT, padx=2)
# self.balloon.bind(label, "Isosurf executable")
# self.isosurf = StringVar(); self.isosurf.set('E:/local/bin/isosurf.v1_5d.exe')
# self.isosurfField = Pmw.ScrolledField(frame, entry_width = 30, entry_relief='groove',
# text = self.isosurf.get())
# self.isosurfField.pack(side=LEFT, fill=X, expand=YES, padx=2)
# button = Button(frame, text="...", command=self.findIsosurf); button.pack(side=LEFT, padx=2)
# self.balloon.bind(button, "search for Isosurf exec...")
nrow = nrow+1
button = Button(modFrame, text='Geniso',
command=self.callGeniso, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(button, "Call Geniso")
frame = Frame(modFrame)
frame.grid(row=nrow, column=1, sticky=W+E)
label = Label(frame, text="res")
label.pack(side=LEFT, padx=2)
self.balloon.bind(label, "resolution used by geniso")
self.genisoRes = DoubleVar()
self.genisoRes.set(4.0)
Entry(frame, textvariable=self.genisoRes,
width=5).pack(side=LEFT, padx=2)
def createImportFrame(self):
group = Pmw.Group(self, tag_text='Import')
group.pack(fill=X, expand=NO, pady=5)
impFrame = group.interior()
impFrame.columnconfigure(7, weight=1)
button = Button(impFrame, text='Load VTK',
command=self.loadVtkImage, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(
button, "load a .vtk file using vtkStructuredPointsReader")
button = Button(impFrame, text='Load XML',
command=self.loadXmlImage, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(
button, "load a .vti file using vtkXMLImageDataReader")
button = Button(impFrame, text='Load RAW',
command=self.loadRawImage, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(button, "load a .raw/.img file using vtkImageReader")
button = Button(impFrame, text='Load GE',
command=self.loadGEImage, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(button, "load I.* files using vtkGESignaReader")
button = Button(impFrame, text='Load NRRD',
command=self.loadNrrdImage, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(button, "load NRRD files")
button = Button(impFrame, text='Load DICOM',
command=self.loadDicomImage, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(button, "load DICOM files using vtkDICOMImageReader")
def createExportFrame(self):
group = Pmw.Group(self, tag_text='Export')
group.pack(fill=X, expand=NO, pady=5)
expFrame = group.interior()
expFrame.columnconfigure(7, weight=1)
frame = Frame(expFrame)
frame.pack(side=TOP, fill=X)
button = Button(frame, text='Save VTK Image',
command=self.saveVtkImage, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(
button, "save a .vtk file using vtkStructuredPointsWriter")
button = Button(frame, text='Save XML Image',
command=self.saveXmlImage, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(
button, "save a .vti file using vtkXMLImageDataWriter")
button = Button(frame, text='Save RAW Image',
command=self.saveRawImage, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(button, "save a .raw/.img file using vtkImageWriter")
frame = Frame(expFrame)
frame.pack(side=TOP, fill=X)
label = Label(frame, text="type")
label.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(
label, "type of the data to be written in VTK file formats")
self.asciiorbin = StringVar()
but1 = Radiobutton(frame, text='ascii',
variable=self.asciiorbin, value='ascii')
but1.pack(side=LEFT)
but2 = Radiobutton(frame, text='binary',
variable=self.asciiorbin, value='binary')
but2.pack(side=LEFT)
but2.select()
def createViewFrame(self):
group = Pmw.Group(self, tag_text='Views')
group.pack(fill=X, expand=NO, pady=5)
viewFrame = group.interior()
viewFrame.columnconfigure(7, weight=1)
nrow = 0
button = Button(viewFrame, text='Slice',
command=self.viewSlice, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(button, "Display a 2D slice (with a slider)")
frame = Frame(viewFrame)
frame.grid(row=nrow, column=1, sticky=W+E)
self.sliceno = IntVar()
self.sliceno.set(30)
label = Label(frame, text="#")
label.pack(side=LEFT, padx=2)
self.balloon.bind(label, "first slice to be seen")
Entry(frame, textvariable=self.sliceno,
width=5).pack(side=LEFT, padx=2)
label = Label(frame, text="window")
label.pack(side=LEFT, padx=2)
self.balloon.bind(
label, "window ~ brightness.\nvalues below (level-window/2) will be black\nvalues beyond (level+window/2) will be white")
self.window = IntVar()
self.window.set(3)
Entry(frame, textvariable=self.window, width=5).pack(side=LEFT, padx=2)
label = Label(frame, text="level")
label.pack(side=LEFT, padx=2)
self.balloon.bind(
label, "level ~ contrast.\nthis value will be middle-gray in the resulting picture")
self.level = IntVar()
self.level.set(2)
Entry(frame, textvariable=self.level, width=5).pack(side=LEFT, padx=2)
button = Button(frame, text='Auto', command=self.autoLevel, anchor="w")
button.pack(side=LEFT, padx=2)
self.balloon.bind(button, "Try to find best values")
nrow = nrow+1
button = Button(viewFrame, text='3 Planes',
command=self.view3Planes, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(
button, "Display the image as 3 intersecting planes\n(press x,y,z for enabling/disabling the planes,\nuse middle mouse button to move the planes)")
nrow = nrow+1
button = Button(viewFrame, text='Volumic',
command=self.viewVolumic, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(
button, "Display the image using a volumic renderer (ray casting)\nuse \"i\" for enabling/disabling the clipping box widget")
def createWidgets(self):
self.createDataFrame()
if not createExe:
self.createCreateFrame()
self.createModifyFrame()
self.createImportFrame()
self.createExportFrame()
self.createViewFrame()
Frame(self).pack(fill=BOTH, expand=TRUE) # espace vide
def codingCallBack(self, val):
self.coding.set(val)
def creEllispoid(self):
ext = (self.extx1.get(), self.extx2.get(), self.exty1.get(),
self.exty2.get(), self.extz1.get(), self.extz2.get())
center = (self.cx.get(), self.cy.get(), self.cz.get())
radius = (self.rx.get(), self.ry.get(), self.rz.get())
values = (self.valin.get(), self.valout.get())
coding = self.coding.get()
self.image = imagingTools.createEllipsoid(
ext, center, radius, coding, values)
self.filename.set("")
self.fnameField.configure(text=self.filename.get())
self.status.set("Ellipsoid created.")
def modNegative(self):
if not self.image:
self.warningNoImage()
self.status.set("Filter canceled.")
else:
self.image = imagingTools.createNegative(self.image)
self.status.set("Negative filter applied.")
def modFlip(self):
if not self.image:
self.warningNoImage()
self.status.set("Filter canceled.")
else:
self.image = imagingTools.flipImage(
self.image, self.flipAxis.get())
self.setParamFromImage()
self.status.set("Flip filter applied.")
def permute(self):
if not self.image:
self.warningNoImage()
self.status.set("Permute canceled.")
else:
self.image = imagingTools.permute(
self.image, self.axX.get(), self.axY.get(), self.axZ.get())
self.setParamFromImage()
self.status.set("Image Permuted.")
def loadVtkImage(self):
fname = tkinter.filedialog.Open(filetypes=[('VTK file', '*.vtk'), ('All Files', '*.*')],
initialdir=self.datadir).show() # or self.lastloaddir
if fname:
self.lastloaddir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
self.image = generalTools.loadVtkImage(fname)
self.setParamFromImage()
self.status.set("Image loaded (VTK).")
else:
self.status.set("Load canceled.")
def saveVtkImage(self):
if self.asciiorbin.get() == "ascii" and self.coding.get() == "uchar":
tkinter.messagebox.Message(icon='warning', type='ok',
message="Saving a \"uchar image\" in ASCII will produce"
" a \"float image\"\n(maybe a VTK bug?)\n"
"\n=>Use binary instead of ASCII\n",
title='Warning').show()
if self.image:
fname = tkinter.filedialog.SaveAs(filetypes=[('VTK file', '*.vtk')],
initialdir=self.lastsavedir).show()
if fname:
self.lastsavedir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
generalTools.saveVtkImage(
fname, self.image, self.asciiorbin.get(), self.coding.get())
self.status.set("Image saved as %s." % fname)
else:
self.status.set("Save canceled.")
else:
self.warningNoImage()
self.status.set("Save canceled.")
def loadXmlImage(self):
fname = tkinter.filedialog.Open(filetypes=[('VTK file', '*.vti'), ('All Files', '*.*')],
initialdir=self.lastloaddir).show()
if fname:
self.lastloaddir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
self.image = generalTools.loadVtkImageXML(fname)
self.setParamFromImage()
self.status.set("Image loaded (XML).")
else:
self.status.set("Load canceled.")
def saveXmlImage(self):
if self.image:
fname = tkinter.filedialog.SaveAs(filetypes=[('VTK file', '*.vti')],
initialdir=self.lastsavedir).show()
if fname:
self.lastsavedir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
generalTools.saveVtkImageXML(
fname, self.image, self.asciiorbin.get(), self.coding.get())
self.status.set("Image saved as %s." % fname)
else:
self.status.set("Save canceled.")
else:
self.warningNoImage()
self.status.set("Save canceled.")
def loadDicomImage(self):
dname = tkinter.filedialog.askdirectory(
parent=root, initialdir=self.lastloaddir, title='Choose a DICOM directory')
if dname:
self.lastloaddir = dname
self.image = generalTools.loadDicomImage(dname)
self.setParamFromImage()
self.status.set("Image loaded (DICOM).")
else:
self.status.set("Load canceled.")
def loadRawImage(self):
fname = tkinter.filedialog.Open(filetypes=[('Analyze file', '*.img'),
('Raw file', '*.raw'), ('All Files', '*.*')],
initialdir=self.lastloaddir).show()
if fname:
self.lastloaddir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
ext = (self.extx1.get(), self.extx2.get(), self.exty1.get(),
self.exty2.get(), self.extz1.get(), self.extz2.get())
sp = (self.sx.get(), self.sy.get(), self.sz.get())
self.image = generalTools.loadRawImage(
fname, extent=ext, spacing=sp, coding=self.coding.get(), byteorder=self.byteorder.get())
self.setParamFromImage()
self.status.set("Image loaded (RAW).")
else:
self.status.set("Load canceled.")
def saveRawImage(self):
if self.image:
fname = tkinter.filedialog.SaveAs(filetypes=[('All files', '*.*')],
initialdir=self.lastsavedir).show()
if fname:
self.lastsavedir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
generalTools.saveRawImage(fname, self.image, self.coding.get())
self.status.set("Image saved as %s." % fname)
else:
self.status.set("Save canceled.")
else:
self.warningNoImage()
self.status.set("Save canceled.")
def loadGEImage(self):
fname = tkinter.filedialog.Open(filetypes=[('GE Signa file', '*.001'),
('All files', '*.*')],
initialdir=self.lastloaddir).show()
# possibilité d'utiliser tkFileDialog.askdirectory(parent=root,initialdir="/",title='Choisissez un repertoire')
if fname:
self.lastloaddir = os.path.split(fname)[0]
dirname = os.path.split(fname)[0]
self.image = generalTools.loadGenesisImage(
dirname, (1, len(os.listdir(dirname))-1))
self.setParamFromImage()
self.status.set("Image loaded (GE Signa).")
else:
self.status.set("Load canceled.")
def loadNrrdImage(self):
fname = tkinter.filedialog.Open(filetypes=[('NRRD file', '*.nrrd'), ('All Files', '*.*')],
initialdir=self.lastloaddir).show()
if fname:
self.lastloaddir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
self.image = generalTools.loadNRRDImage(fname)
self.setParamFromImage()
self.status.set("Image loaded (NRRD).")
else:
self.status.set("Load canceled.")
def loadDicomImage(self):
dname = tkinter.filedialog.askdirectory(
parent=root, initialdir=self.lastloaddir, title='Choose a DICOM directory')
if dname:
self.lastloaddir = dname
self.image = generalTools.loadDicomImage(dname)
self.setParamFromImage()
self.status.set("Image loaded (DICOM).")
else:
self.status.set("Load canceled.")
# def findIsosurf(self):
# fname = tkFileDialog.Open(filetypes=[('Isosurf Executable','*.exe')]).show()
# if fname:
# self.isosurf.set(fname)
# self.status.set("Isosurf set to %s." % fname)
# self.isosurfField.configure(text = self.isosurf.get())
# else:
# self.status.set("Canceled.")
def execIsosurf(self):
if self.image:
polydata = meshingTools.callIsosurf(self.image, self.isores.get())
self.mainW.setPolydata(polydata)
else:
self.warningNoImage()
self.status.set("Execute Isosurf canceled.")
# if self.filename.get()!="":
# range=(1,255)
# ext = (self.extx2.get()-self.extx1.get()+1,self.exty2.get()-self.exty1.get()+1,self.extz2.get()-self.extz1.get()+1)
# print ext
# sp = (self.sx.get(),self.sy.get(),self.sz.get())
# print sp
# codflag='c' # 'c'='uchar' 'u'='ushort'
# filter ='b' # 'n'= none 'o'=opening, 'c' = closing, 'b'=both (default)
# cmd = "\"%s\" -t %d,%d -i %s -d %d,%d,%d -s %g,%g,%g -r %g -f %s -m %s" % (self.isosurf.get(),
# range[0], range[1], self.filename.get(), ext[0],ext[1], ext[2],
# sp[0], sp[1], sp[2], self.isores.get(), codflag, filter);
# self.status.set("Exec Isosurf.")
# print "exec:", cmd
# import os
# try:
# os.system(cmd)
# except:
# tkMessageBox.Message(icon='warning', type='ok', message='Error in isosurf!', title='Warning').show()
# return
# polydata = generalTools.off2vtk(name="surface.off")
# self.mainW.setPolydata(polydata)
# else:
# tkMessageBox.Message(icon='warning', type='ok',
# message='Image must be saved to/loaded from disk!',
# title='Warning').show()
# self.status.set("Exec Isosurf cancelled.")
def buildIsoValue(self):
if self.image:
polydata = imagingTools.createContourPolydata(
self.image, value=(self.range1.get(), self.range2.get()))
polydata.Update()
self.mainW.setPolydata(polydata)
self.status.set("Skin has been extracted.")
else:
self.warningNoImage()
self.status.set("Skin extraction canceled.")
def callGeniso(self):
if self.image:
import meshingToolsGeniso
polydata = meshingToolsGeniso.callGeniso(
self.image, self.genisoRes.get())
self.mainW.setPolydata(polydata)
self.status.set("Polydata has been created.")
else:
self.warningNoImage()
self.status.set("Geniso call canceled.")
def modThreshold(self):
if self.image:
#self.image = imagingTools.thresholdByUpper(self.image,self.th.get(),self.th.get(),0)
self.image = imagingTools.thresholdByUpper(
self.image, self.th.get(), 3, 0)
self.status.set("Image has been thresholded.")
else:
self.warningNoImage()
self.status.set("Threshold canceled")
def modCreateSignedEuclideanDistanceMap(self):
if self.image:
self.status.set("Creating Signed Euclidean Distance Map...")
self.image = imagingTools.createSignedEuclideanDistanceMap(
self.image)
self.filename.set("")
self.fnameField.configure(text=self.filename.get())
self.setParamFromImage()
self.status.set("Signed Euclidean Distance Map created.")
else:
self.warningNoImage()
self.status.set("Signed Euclidean Distance Map canceled.")
def resliceWithNearestNeighbor(self):
if self.image:
self.image = imagingTools.resliceWithNearestNeighbor(
self.image, [self.spx.get(), self.spy.get(), self.spz.get()])
self.setParamFromImage()
self.status.set("Image has been resliced.")
else:
self.warningNoImage()
self.status.set("Reslice canceled")
def resliceWithLinearInterpolation(self):
if self.image:
self.image = imagingTools.resliceWithLinearInterpolation(
self.image, [self.spx.get(), self.spy.get(), self.spz.get()])
self.setParamFromImage()
self.status.set("Image has been resliced.")
else:
self.warningNoImage()
self.status.set("Reslice canceled")
def resliceWithCubicInterpolation(self):
if self.image:
self.image = imagingTools.resliceWithCubicInterpolation(
self.image, [self.spx.get(), self.spy.get(), self.spz.get()])
self.setParamFromImage()
self.status.set("Image has been resliced.")
else:
self.warningNoImage()
self.status.set("Reslice canceled")
def erode(self):
if self.image:
self.image = imagingTools.erode(
self.image, [self.kx.get(), self.ky.get(), self.kz.get()])
self.status.set("Erode filter has been applied.")
else:
self.warningNoImage()
self.status.set("Erode canceled")
def dilate(self):
if self.image:
self.image = imagingTools.erode(
self.image, [self.kx.get(), self.ky.get(), self.kz.get()])
self.status.set("Dilate filter has been applied.")
else:
self.warningNoImage()
self.status.set("Dilate canceled")
def openClose3D(self):
if self.image:
self.image = imagingTools.openClose3D(self.image, self.openValue.get(
), self.closeValue.get(), [self.kx.get(), self.ky.get(), self.kz.get()])
self.status.set("OpenClose3D filter has been applied.")
else:
self.warningNoImage()
self.status.set("OpenClose3D canceled")
def viewSlice(self):
if self.image:
global root
self.vtkwin = Toplevel(root)
self.vtkwin.title('2D Slice Viewer')
self.vtkwin.resizable(width=NO, height=NO)
size = (self.extx2.get()-self.extx1.get(),
self.exty2.get()-self.exty1.get())
range = (self.extz1.get(), self.extz2.get())
win = VtkWindow2D(self.vtkwin, size, range)
win.view(self.image, self.sliceno.get(),
self.window.get(), self.level.get())
self.status.set("Viewing 2D Slice...")
else:
self.warningNoImage()
self.status.set("View canceled.")
def view3Planes(self):
if self.image:
global root
self.vtkwin = Toplevel(root)
self.vtkwin.title('3D Plane Viewer')
win = VtkWindow3Planes(self.vtkwin)
win.view(self.image, self.window.get(), self.level.get())
self.status.set("Viewing 3 Planes...")
else:
self.warningNoImage()
self.status.set("View canceled.")
def viewVolumic(self):
if self.image:
global root
self.vtkwin = Toplevel(root)
self.vtkwin.title('Volume Renderer')
win = VtkWindowVolumic(self.vtkwin)
win.view(self.image)
self.status.set("Viewing Volumic...")
else:
self.warningNoImage()
self.status.set("View canceled.")
def setParamFromImage(self):
if self.image:
type = self.image.GetScalarType()
if type == vtk.VTK_UNSIGNED_CHAR:
self.coding.set('uchar')
self.codingCombo.selectitem('uchar')
elif type == vtk.VTK_UNSIGNED_SHORT:
self.coding.set('ushort')
self.codingCombo.selectitem('ushort')
elif type == vtk.VTK_SHORT:
self.coding.set('short')
self.codingCombo.selectitem('ushort')
elif type == vtk.VTK_DOUBLE:
self.coding.set('double')
self.codingCombo.selectitem('double')
else:
tkinter.messagebox.Message(icon='warning', type='ok',
message='Unsupported format (%s)!' % self.image.GetScalarTypeAsString(
),
title='Warning').show()
ext = self.image.GetExtent()
self.extx1.set(ext[0])
self.extx2.set(ext[1])
self.exty1.set(ext[2])
self.exty2.set(ext[3])
self.extz1.set(ext[4])
self.extz2.set(ext[5])
sp = self.image.GetSpacing()
self.sx.set(sp[0])
self.sy.set(sp[1])
self.sz.set(sp[2])
self.scalarrange.set("(%g,%g)" % self.image.GetScalarRange())
def warningNoImage(self):
tkinter.messagebox.Message(icon='warning', type='ok',
message='No image in memory!',
title='Warning').show()
def saveConfig(self, var, file):
#file.write('self.%s.isosurf.set("%s")\n' % (var,self.isosurf.get()))
file.write('self.%s.coding.set("%s")\n' % (var, self.coding.get()))
file.write('self.%s.byteorder.set("%s")\n' %
(var, self.byteorder.get()))
file.write('self.%s.sx.set(%g)\n' % (var, self.sx.get()))
file.write('self.%s.sy.set(%g)\n' % (var, self.sy.get()))
file.write('self.%s.sz.set(%g)\n' % (var, self.sz.get()))
file.write('self.%s.extx1.set(%d)\n' % (var, self.extx1.get()))
file.write('self.%s.extx2.set(%d)\n' % (var, self.extx2.get()))
file.write('self.%s.exty1.set(%d)\n' % (var, self.exty1.get()))
file.write('self.%s.exty2.set(%d)\n' % (var, self.exty2.get()))
file.write('self.%s.extz1.set(%d)\n' % (var, self.extz1.get()))
file.write('self.%s.extz2.set(%d)\n' % (var, self.extz2.get()))
file.write('self.%s.window.set(%d)\n' % (var, self.window.get()))
file.write('self.%s.level.set(%d)\n' % (var, self.level.get()))
file.write('self.%s.sliceno.set(%d)\n' % (var, self.sliceno.get()))
if not createExe:
file.write('self.%s.range1.set(%d)\n' % (var, self.range1.get()))
file.write('self.%s.range2.set(%d)\n' % (var, self.range2.get()))
file.write('self.%s.isores.set(%d)\n' % (var, self.isores.get()))
file.write('self.%s.cx.set(%d)\n' % (var, self.cx.get()))
file.write('self.%s.cy.set(%d)\n' % (var, self.cy.get()))
file.write('self.%s.cz.set(%d)\n' % (var, self.cz.get()))
file.write('self.%s.valin.set(%d)\n' % (var, self.valin.get()))
file.write('self.%s.valout.set(%d)\n' % (var, self.valout.get()))
file.write('self.%s.asciiorbin.set("%s")\n' %
(var, self.asciiorbin.get()))
def loadConfig(self): # synchro uniqt
self.codingCombo.selectitem(self.coding.get())
#self.isosurfField.configure(text = self.isosurf.get())
def moreInfo(self):
if self.image:
win = Toplevel(root)
win.title("Image info")
msgFrame = Pmw.ScrolledText(win, vscrollmode='dynamic', hscrollmode='dynamic',
text_width=40, text_height=20, text_wrap='none')
msgFrame.insert('end', str(self.image))
#msgFrame = Message(win, text=str(self.image), bg="white", fg="red")
msgFrame.pack(fill=BOTH, expand=YES)
win.transient(root)
else:
self.warningNoImage()
def autoLevel(self):
if self.image:
range = self.image.GetScalarRange()
self.window.set(range[1]-range[0])
self.level.set((range[1]+range[0])/2)
else:
self.warningNoImage()
# ----------------------------------------------------------------------
class PolyDataFrame(Frame):
def __init__(self, master, status, mainW):
Frame.__init__(self, master)
self.mainW = mainW
self.status = status
self.balloon = Pmw.Balloon(master) # aide "ballon"
self.polydata = None # polydata
self.vtkwin = None # fenetre VTK
self.lastloaddir = '.'
self.lastsavedir = '.'
self.createWidgets()
# self.loadConfig()
def createDataFrame(self):
frame1 = Frame(self, bd=1, relief=GROOVE)
frame1.pack(fill=X, expand=NO)
Label(frame1, text="Surface mesh", bg='gray', fg='black').pack(
expand=YES, fill=X, padx=2, pady=2)
frame2 = Frame(frame1)
frame2.pack(fill=X, expand=NO)
# la colonne 2 (vide) va pouvoir s'agrandir
frame2.columnconfigure(2, weight=1)
nrow = 0 # first line
label = Label(frame2, text="filename")
label.grid(row=nrow, column=0, padx=5, pady=2, sticky=W)
self.balloon.bind(label, "filename of the polydata")
self.filename = StringVar()
self.filename.set('')
self.fnameField = Pmw.ScrolledField(frame2, entry_width=30, entry_relief=GROOVE,
text=self.filename.get())
self.fnameField.grid(row=nrow, column=1, padx=5,
pady=2, columnspan=2, sticky=NSEW)
nrow = nrow+1
Label(frame2, text="size").grid(
row=nrow, column=0, padx=5, pady=2, sticky=W)
frame = Frame(frame2)
frame.grid(row=nrow, column=1, padx=5, pady=2, sticky=W)
self.nbpts = IntVar()
self.nbpts.set(0)
Label(frame, textvariable=self.nbpts).pack(side=LEFT)
Label(frame, text="points and").pack(side=LEFT)
self.nbcells = IntVar()
self.nbcells.set(0)
Label(frame, textvariable=self.nbcells).pack(side=LEFT)
Label(frame, text="cells.").pack(side=LEFT)
button = Button(frame, text='More Info',
command=self.moreInfo, anchor="w")
button.pack(side=RIGHT, padx=0)
self.balloon.bind(button, "print more info concerning the VTK object")
def createModifyFrame(self):
group = Pmw.Group(self, tag_text='Modify/Filters')
group.pack(fill=X, expand=NO, pady=5)
modFrame = group.interior()
modFrame.columnconfigure(1, weight=1)
nrow = 0
button = Button(modFrame, text='Extract largest',
command=self.modExtractLargest, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(
button, "apply a vtkPolyDataConnectivityFilter (extract largest region)")
nrow = nrow+1
button = Button(modFrame, text='Clean Nodes',
command=self.modMergeNodes, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(
button, "Find duplicate nodes and merge them using vtkCleanpolyData")
frame = Frame(modFrame)
frame.grid(row=nrow, column=1, sticky=W+E)
label = Label(frame, text="tol")
label.pack(side=LEFT, padx=2)
self.balloon.bind(label, "tolerance")
self.mergeTol = DoubleVar()
self.mergeTol.set(0.0001)
Entry(frame, textvariable=self.mergeTol,
width=5).pack(side=LEFT, padx=2)
nrow = nrow+1
button = Button(modFrame, text='Smooth',
command=self.modSmooth, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(
button, "Smooth the polydata using vtkSmoothPolyDataFilter")
frame = Frame(modFrame)
frame.grid(row=nrow, column=1, sticky=W+E)
label = Label(frame, text="relax")
label.pack(side=LEFT, padx=2)
self.balloon.bind(label, "relaxation factor")
self.smRelax = DoubleVar()
self.smRelax.set(0.1)
Entry(frame, textvariable=self.smRelax,
width=5).pack(side=LEFT, padx=2)
nrow = nrow+1
button = Button(modFrame, text='Extract Closed Polys',
command=self.modExtractClosedPolys, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(button, "Extract all closed polys")
nrow = nrow+1
button = Button(modFrame, text='TetGen From File',
command=self.execTetGenFromFile, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(
button, "run TetGen (resulting mesh using Geniso generated .poly file on the \"Ugrid\" tab)")
frame = Frame(modFrame)
frame.grid(row=nrow, column=1, sticky=W+E)
label = Label(frame, text="q")
label.pack(side=LEFT, padx=2)
self.balloon.bind(label, "quality used by TetGen (e.g. 2.0)")
self.tetgenq = DoubleVar()
self.tetgenq.set(2.0)
Entry(frame, textvariable=self.tetgenq,
width=8).pack(side=LEFT, padx=2)
label = Label(frame, text="V")
label.pack(side=LEFT, padx=2)
self.balloon.bind(
label, "Suppresses the creation of Steiner points on the exterior boundary")
self.tetgenV = BooleanVar()
self.tetgenV.set(1)
Entry(frame, textvariable=self.tetgenV,
width=8).pack(side=LEFT, padx=2)
nrow = nrow+1
button = Button(modFrame, text='TetGen',
command=self.execTetGen, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(
button, "run TetGen (resulting mesh on the \"Ugrid\" tab)")
frame = Frame(modFrame)
frame.grid(row=nrow, column=1, sticky=W+E)
label = Label(frame, text="q")
label.pack(side=LEFT, padx=2)
self.balloon.bind(label, "quality used by TetGen (e.g. 2.0)")
self.tetgenq = DoubleVar()
self.tetgenq.set(2.0)
Entry(frame, textvariable=self.tetgenq,
width=8).pack(side=LEFT, padx=2)
label = Label(frame, text="a")
label.pack(side=LEFT, padx=2)
self.balloon.bind(label, "maximum cell volume used by TetGen")
self.tetgena = DoubleVar()
self.tetgena.set(500)
Entry(frame, textvariable=self.tetgena,
width=8).pack(side=LEFT, padx=2)
label = Label(frame, text="V")
label.pack(side=LEFT, padx=2)
self.balloon.bind(
label, "Suppresses the creation of Steiner points on the exterior boundary")
self.tetgenV = BooleanVar()
self.tetgenV.set(1)
Entry(frame, textvariable=self.tetgenV,
width=8).pack(side=LEFT, padx=2)
# nrow=nrow+1
# frame = Frame(modFrame); frame.grid(row=nrow, column=1, sticky = W+E)
# label = Label(frame, text="exec"); label.pack(side=LEFT, padx=2)
# self.balloon.bind(label, "TetGen executable")
# self.tetgen = StringVar(); self.tetgen.set('E:/dev/tetgen1.4.1/tetgen.exe')
# self.tetgenField = Pmw.ScrolledField(frame, entry_width = 30, entry_relief='groove',
# text = self.tetgen.get())
# self.tetgenField.pack(side=LEFT, fill=X, expand=YES, padx=2)
# button = Button(frame, text="...", command=self.findTetGen); button.pack(side=LEFT, padx=2)
# self.balloon.bind(button, "search for TetGen exec...")
def createImportFrame(self):
group = Pmw.Group(self, tag_text='Import')
group.pack(fill=X, expand=NO, pady=5)
impFrame = group.interior()
button = Button(impFrame, text='Load VTK Polydata',
command=self.loadVtkPolydata, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(
button, "load a .vtk polydata using vtkPolyDataReader")
button = Button(impFrame, text='Load XML Polydata',
command=self.loadXmlPolydata, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(
button, "load a .vtp polydata using vtkXMLPolyDataReader")
button = Button(impFrame, text='Load STL file',
command=self.loadStl, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(button, "load a .stl file using vtkSTLReader")
def createExportFrame(self):
group = Pmw.Group(self, tag_text='Export')
group.pack(fill=X, expand=NO, pady=5)
expFrame = group.interior()
frame = Frame(expFrame)
frame.pack(side=TOP, fill=X)
button = Button(frame, text='Save VTK Polydata',
command=self.saveVtkPolydata, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(
button, "save a .vtk polydata using vtkPolyDataWriter")
button = Button(frame, text='Save XML Polydata',
command=self.saveXmlPolydata, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(
button, "save a .vtk polydata using vtkXMLPolyDataWriter")
button = Button(frame, text='Export to Gmsh',
command=self.exportToGmsh, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(button, "save a .geo file for Gmsh")
button = Button(frame, text='Export to Tetgen',
command=self.exportToTetgen, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(button, "save a .poly file for TetGen")
frame = Frame(expFrame)
frame.pack(side=TOP, fill=X)
label = Label(frame, text="type")
label.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(
label, "type of the data to be written in VTK file formats")
self.asciiorbin = StringVar()
but1 = Radiobutton(frame, text='ascii',
variable=self.asciiorbin, value='ascii')
but1.pack(side=LEFT)
but2 = Radiobutton(frame, text='binary',
variable=self.asciiorbin, value='binary')
but2.pack(side=LEFT)
but2.select()
def createViewFrame(self):
group = Pmw.Group(self, tag_text='Views')
group.pack(fill=X, expand=NO, pady=5)
viewFrame = group.interior()
viewFrame.columnconfigure(7, weight=1)
nrow = 0
button = Button(viewFrame, text='3D View',
command=self.viewPolydata, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(button, "Simple 3D view of the polydata in memory")
frame = Frame(viewFrame)
frame.grid(row=nrow, column=1, padx=5, pady=2, sticky=W+E)
Label(frame, text="simple 3D view").pack(side=LEFT, padx=5, pady=2)
self.withEdges = IntVar()
but1 = Checkbutton(frame, text='edges on', variable=self.withEdges)
but1.pack(side=LEFT)
self.withScalars = IntVar()
but2 = Checkbutton(
frame, text='scalars', variable=self.withScalars, command=self.disableColorMap)
but2.pack(side=LEFT)
self.colorMap = StringVar()
self.but3 = Checkbutton(frame, text='GrayScale scalars', variable=self.colorMap,
onvalue='GrayScale', offvalue='colors', state=DISABLED)
self.but3.pack(side=LEFT)
if not createExe:
nrow = nrow+1
button = Button(viewFrame, text='MeshViewer',
command=self.viewPolydataInGui, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(button, "View with the MeshViewer")
frame = Frame(viewFrame)
frame.grid(row=nrow, column=1, padx=5, pady=2, sticky=W+E)
Label(frame, text="View with the MeshViewer").pack(
side=LEFT, padx=5, pady=2)
def disableColorMap(self):
self.but3.configure(state='normal')
def createWidgets(self):
self.createDataFrame()
self.createModifyFrame()
self.createImportFrame()
self.createExportFrame()
self.createViewFrame()
Frame(self).pack(fill=BOTH, expand=TRUE) # espace vide
def saveConfig(self, var, file):
#file.write('self.%s.tetgen.set("%s")\n' % (var,self.tetgen.get()))
file.write('self.%s.mergeTol.set(%g)\n' % (var, self.mergeTol.get()))
file.write('self.%s.smRelax.set(%g)\n' % (var, self.smRelax.get()))
file.write('self.%s.tetgena.set(%g)\n' % (var, self.tetgena.get()))
file.write('self.%s.tetgenq.set(%g)\n' % (var, self.tetgenq.get()))
file.write('self.%s.asciiorbin.set("%s")\n' %
(var, self.asciiorbin.get()))
def loadConfig(self): # synchro uniqt
pass
#self.tetgenField.configure(text = self.tetgen.get())
def loadVtkPolydata(self):
fname = tkinter.filedialog.Open(filetypes=[('VTK file', '*.vtk'),
('All Files', '*.*')],
initialdir=self.lastloaddir).show()
if fname:
self.lastloaddir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
self.polydata = generalTools.loadPolyData(fname)
self.setParamFromPolydata()
self.status.set("Polydata loaded (VTK).")
else:
self.status.set("Load canceled.")
def loadStl(self):
fname = tkinter.filedialog.Open(filetypes=[('STL file', '*.stl'),
('All Files', '*.*')],
initialdir=self.lastloaddir).show()
if fname:
self.lastloaddir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
self.polydata = generalTools.loadStl(fname)
self.setParamFromPolydata()
self.status.set("Polydata loaded (STL).")
else:
self.status.set("Load canceled.")
def saveVtkPolydata(self):
if self.polydata:
fname = tkinter.filedialog.SaveAs(filetypes=[('VTK file', '*.vtk')],
initialdir=self.lastsavedir).show()
if fname:
self.lastsavedir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
generalTools.savePolyData(fname, self.polydata)
self.status.set("Polydata saved as %s." % fname)
else:
self.status.set("Save canceled.")
else:
self.warningNoPolydata()
self.status.set("Save canceled.")
def loadXmlPolydata(self):
fname = tkinter.filedialog.Open(filetypes=[('XML file', '*.vtp'),
('All Files', '*.*')],
initialdir=self.lastloaddir).show()
if fname:
self.lastloaddir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
self.polydata = generalTools.loadPolyDataXML(fname)
self.setParamFromPolydata()
self.status.set("Polydata loaded (XML).")
else:
self.status.set("Load canceled.")
def saveXmlPolydata(self):
if self.polydata:
fname = tkinter.filedialog.SaveAs(filetypes=[('XML file', '*.vtp')],
initialdir=self.lastsavedir).show()
if fname:
self.lastsavedir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
generalTools.savePolyDataXML(
fname, self.polydata, self.asciiorbin.get())
self.status.set("Polydata saved as %s." % fname)
else:
self.status.set("Save canceled.")
else:
self.warningPolydata()
self.status.set("Save canceled.")
def exportToGmsh(self):
if self.polydata:
fname = tkinter.filedialog.SaveAs(filetypes=[('Gmsh input file', '*.geo')],
initialdir=self.lastsavedir).show()
if fname:
self.lastsavedir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
generalTools.vtk2gmsh(self.polydata, fname)
self.status.set("Polydata saved as %s." % fname)
else:
self.status.set("Save canceled.")
else:
self.warningPolydata()
self.status.set("Save canceled.")
def exportToTetgen(self):
if self.polydata:
fname = tkinter.filedialog.SaveAs(filetypes=[('Tetgen input file', '*.poly')],
initialdir=self.lastsavedir).show()
if fname:
self.lastsavedir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
generalTools.vtk2tetgen(self.polydata, fname)
self.status.set("Polydata saved as %s." % fname)
else:
self.status.set("Save canceled.")
else:
self.warningPolydata()
self.status.set("Save canceled.")
def setParamFromPolydata(self):
if self.polydata:
self.nbpts.set(self.polydata.GetNumberOfPoints())
self.nbcells.set(self.polydata.GetNumberOfCells())
def viewPolydata(self):
if self.polydata:
if self.withScalars.get() and not (
self.polydata.GetPointData().GetScalars() or self.polydata.GetCellData().GetScalars()
):
self.warningNoScalarField()
self.status.set("View canceled.")
else:
global root
self.vtkwin = Toplevel(root)
self.vtkwin.title('3D Viewer')
win = VtkWindow3DPoly(self.vtkwin)
win.view(self.polydata, scalarsOn=self.withScalars.get(
), edgesOn=self.withEdges.get(), colorMap=self.colorMap.get())
self.status.set("Viewing 3D.")
else:
self.warningNoPolydata()
self.status.set("View canceled.")
def viewPolydataInGui(self):
if self.polydata:
import renderingToolsQt
renderingToolsQt.displayPoly(self.polydata)
self.status.set("Viewing 3D.")
else:
self.warningNoPolydata()
self.status.set("View canceled.")
def warningNoPolydata(self):
tkinter.messagebox.Message(icon='warning', type='ok',
message='No polydata in memory!',
title='Warning').show()
def warningNoScalarField(self):
tkinter.messagebox.Message(icon='warning', type='ok',
message='No scalar field in polydata!',
title='Warning').show()
def setPolydata(self, poly):
if poly:
self.polydata = poly
self.setParamFromPolydata()
def moreInfo(self):
if self.polydata:
win = Toplevel(root)
win.title("Polydata info")
msgFrame = Pmw.ScrolledText(win, vscrollmode='dynamic', hscrollmode='dynamic',
text_width=40, text_height=20, text_wrap='none')
msgFrame.insert('end', str(self.polydata))
msgFrame.pack(fill=BOTH, expand=YES)
win.transient(root)
else:
self.warningNoPolydata()
def modExtractLargest(self):
if not self.polydata:
self.warningNoPolydata()
self.status.set("Filter canceled.")
else:
self.polydata = meshingTools.extractLargestPoly(self.polydata)
self.status.set("Extract Largest Region filter applied.")
self.setParamFromPolydata()
def modMergeNodes(self):
if not self.polydata:
self.warningNoPolydata()
self.status.set("Filter canceled.")
else:
self.polydata = meshingTools.mergeDuplicateNodes(
self.polydata, self.mergeTol.get())
self.status.set("Merge Nodes filter applied.")
self.setParamFromPolydata()
def modSmooth(self):
if not self.polydata:
self.warningNoPolydata()
self.status.set("Filter canceled.")
else:
self.polydata = meshingTools.smoothPolyData(
self.polydata, self.smRelax.get())
self.status.set("Smooth polydata filter applied.")
self.setParamFromPolydata()
def modExtractClosedPolys(self):
if not self.polydata:
self.warningNoPolydata()
self.status.set("Filter canceled.")
else:
polys = meshingTools.extractClosedSurfacesFromPoly(self.polydata)
import renderingToolsQt
renderingToolsQt.displayVectorOfPolys(polys)
self.status.set("extractClosedSurfacesFromPoly filter applied.")
# def findTetGen(self):
# fname = tkFileDialog.Open(filetypes=[('TetGen Executable','*.exe')]).show()
# if fname:
# self.tetgen.set(fname)
# self.status.set("TetGen set to %s." % fname)
# self.tetgenField.configure(text = self.tetgen.get())
# else:
# self.status.set("Canceled.")
def execTetGen(self):
if not self.polydata:
self.warningNoPolydata()
self.status.set("Exec TetGen cancelled.")
else:
ugrid = meshingTools.callTetgen(
self.polydata, self.tetgenq.get(), self.tetgena.get(), self.tetgenV.get(), 0)
self.mainW.setUgrid(ugrid)
def execTetGenFromFile(self):
fname = tkinter.filedialog.Open(filetypes=[('Tetgen file', '*.poly'),
('All Files', '*.*')],
initialdir=self.lastloaddir).show()
if fname:
ugrid = meshingTools.callTetgenMultipleRegionsFromFile(
os.path.splitext(fname)[0], self.tetgenq.get(), self.tetgenV.get())
self.mainW.setUgrid(ugrid)
self.status.set("Ugrid created.")
else:
self.status.set("Exec TetGen cancelled.")
# ----------------------------------------------------------------------
class UgridFrame(Frame):
def __init__(self, master, status):
Frame.__init__(self, master)
self.status = status
self.balloon = Pmw.Balloon(master) # aide "ballon"
self.ugrid = None # polydata
self.vtkwin = None # fenetre VTK
self.lastloaddir = '.'
self.lastsavedir = '.'
self.createWidgets()
# self.loadConfig()
def createDataFrame(self):
frame1 = Frame(self, bd=1, relief=GROOVE)
frame1.pack(fill=X, expand=NO)
Label(frame1, text="Volume mesh", bg='gray', fg='black').pack(
expand=YES, fill=X, padx=2, pady=2)
frame2 = Frame(frame1)
frame2.pack(fill=X, expand=NO)
# la colonne 2 (vide) va pouvoir s'agrandir
frame2.columnconfigure(2, weight=1)
nrow = 0 # first line
label = Label(frame2, text="filename")
label.grid(row=nrow, column=0, padx=5, pady=2, sticky=W)
self.balloon.bind(label, "filename of the ugrid")
self.filename = StringVar()
self.filename.set('')
self.fnameField = Pmw.ScrolledField(frame2, entry_width=30, entry_relief=GROOVE,
text=self.filename.get())
self.fnameField.grid(row=nrow, column=1, padx=5,
pady=2, columnspan=2, sticky=NSEW)
nrow = nrow+1
Label(frame2, text="size").grid(
row=nrow, column=0, padx=5, pady=2, sticky=W)
frame = Frame(frame2)
frame.grid(row=nrow, column=1, padx=5, pady=2, sticky=W)
self.nbpts = IntVar()
self.nbpts.set(0)
Label(frame, textvariable=self.nbpts).pack(side=LEFT)
Label(frame, text="points and").pack(side=LEFT)
self.nbcells = IntVar()
self.nbcells.set(0)
Label(frame, textvariable=self.nbcells).pack(side=LEFT)
Label(frame, text="cells.").pack(side=LEFT)
button = Button(frame, text='More Info',
command=self.moreInfo, anchor="w")
button.pack(side=RIGHT, padx=0)
self.balloon.bind(button, "print more info concerning the VTK object")
def createImportFrame(self):
group = Pmw.Group(self, tag_text='Import')
group.pack(fill=X, expand=NO, pady=5)
impFrame = group.interior()
button = Button(impFrame, text='Load VTK Ugrid',
command=self.loadVtkUgrid, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(
button, "load a .vtk ugrid using vtkUnstructuredGridReader")
button = Button(impFrame, text='Load XML Ugrid',
command=self.loadXmlUgrid, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(
button, "load a .vtu ugrid using vtkXMLUnstructuredGridReader")
def createExportFrame(self):
group = Pmw.Group(self, tag_text='Export')
group.pack(fill=X, expand=NO, pady=5)
expFrame = group.interior()
frame = Frame(expFrame)
frame.pack(side=TOP, fill=X)
button = Button(frame, text='Save VTK Ugrid',
command=self.saveVtkUgrid, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(
button, "save a .vtk ugrid using vtkUnstructuredGridWriter")
button = Button(frame, text='Save XML Ugrid',
command=self.saveXmlUgrid, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(
button, "save a .vtu ugrid using vtkXMLUnstructuredGridWriter")
if not createExe:
button = Button(frame, text='Export to Metafor',
command=self.exportToMetafor, anchor="w")
button.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(button, "save a .py file for Metafor")
frame = Frame(expFrame)
frame.pack(side=TOP, fill=X)
label = Label(frame, text="type")
label.pack(side=LEFT, expand=NO, fill=X, padx=5, pady=5)
self.balloon.bind(
label, "type of the data to be written in VTK file formats")
self.asciiorbin = StringVar()
but1 = Radiobutton(frame, text='ascii',
variable=self.asciiorbin, value='ascii')
but1.pack(side=LEFT)
but2 = Radiobutton(frame, text='binary',
variable=self.asciiorbin, value='binary')
but2.pack(side=LEFT)
but2.select()
def loadVtkUgrid(self):
fname = tkinter.filedialog.Open(filetypes=[('VTK file', '*.vtk'),
('All Files', '*.*')],
initialdir=self.lastloaddir).show()
if fname:
self.lastloaddir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
self.ugrid = generalTools.loadUgrid(fname)
self.setParamFromUgrid()
self.status.set("Ugrid loaded (VTK).")
else:
self.status.set("Load canceled.")
def saveVtkUgrid(self):
if self.ugrid:
fname = tkinter.filedialog.SaveAs(filetypes=[('VTK file', '*.vtk')],
initialdir=self.lastsavedir).show()
if fname:
self.lastsavedir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
generalTools.saveUgrid(fname, self.ugrid)
self.status.set("Ugrid saved as %s." % fname)
else:
self.status.set("Save canceled.")
else:
self.warningNoUgrid()
self.status.set("Save canceled.")
def loadXmlUgrid(self):
fname = tkinter.filedialog.Open(filetypes=[('XML file', '*.vtu'),
('All Files', '*.*')],
initialdir=self.lastloaddir).show()
if fname:
self.lastloaddir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
self.ugrid = generalTools.loadUgridXML(fname)
self.setParamFromUgrid()
self.status.set("Ugrid loaded (XML).")
else:
self.status.set("Load canceled.")
def saveXmlUgrid(self):
if self.ugrid:
fname = tkinter.filedialog.SaveAs(filetypes=[('XML file', '*.vtu')],
initialdir=self.lastsavedir).show()
if fname:
self.lastsavedir = os.path.split(fname)[0]
self.filename.set(fname)
self.fnameField.configure(text=self.filename.get())
generalTools.saveUgridXML(
fname, self.ugrid, self.asciiorbin.get())
self.status.set("Ugrid saved as %s." % fname)
else:
self.status.set("Save canceled.")
else:
self.warningUgrid()
self.status.set("Save canceled.")
def exportToMetafor(self):
pass
def createViewFrame(self):
group = Pmw.Group(self, tag_text='Views')
group.pack(fill=X, expand=NO, pady=5)
viewFrame = group.interior()
viewFrame.columnconfigure(7, weight=1)
nrow = 0
button = Button(viewFrame, text='3D View',
command=self.viewUgrid, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(button, "Simple 3D view of the ugrid in memory")
frame = Frame(viewFrame)
frame.grid(row=nrow, column=1, padx=5, pady=2, sticky=W+E)
Label(frame, text="simple 3D view").pack(side=LEFT, padx=5, pady=2)
self.withEdges = IntVar()
but1 = Checkbutton(frame, text='edges on', variable=self.withEdges)
but1.pack(side=LEFT)
self.withScalars = IntVar()
but2 = Checkbutton(
frame, text='scalars', variable=self.withScalars, command=self.disableColorMap)
but2.pack(side=LEFT)
self.colorMap = StringVar()
self.but3 = Checkbutton(frame, text='GrayScale scalars', variable=self.colorMap,
onvalue='GrayScale', offvalue='colors', state=DISABLED)
self.but3.pack(side=LEFT)
nrow += 1
button = Button(viewFrame, text='3D Cut',
command=self.viewClippedUgrid, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(
button, "Cut and view 3D view of the ugrid in memory")
frame = Frame(viewFrame)
frame.grid(row=nrow, column=1, padx=5, pady=2, sticky=W+E)
Label(frame, text="cut 3D view").pack(side=LEFT, padx=5, pady=2)
if not createExe:
nrow = 1
button = Button(viewFrame, text='Tetview',
command=self.tetview, anchor="w")
button.grid(row=nrow, column=0, padx=5, pady=2, sticky=W+E)
self.balloon.bind(button, "View with Tetview")
frame = Frame(viewFrame)
frame.grid(row=nrow, column=1, padx=5, pady=2, sticky=W+E)
Label(frame, text="view in tetview").pack(
side=LEFT, padx=5, pady=2)
def disableColorMap(self):
self.but3.configure(state='normal')
def createWidgets(self):
self.createDataFrame()
# self.createModifyFrame()
self.createImportFrame()
self.createExportFrame()
self.createViewFrame()
Frame(self).pack(fill=BOTH, expand=TRUE) # espace vide
def setParamFromUgrid(self):
if self.ugrid:
self.nbpts.set(self.ugrid.GetNumberOfPoints())
self.nbcells.set(self.ugrid.GetNumberOfCells())
def viewUgrid(self):
if self.ugrid:
scalars = self.ugrid.GetPointData().GetScalars()
if scalars == None:
scalars = self.ugrid.GetCellData().GetScalars()
if scalars == None:
scalars = self.ugrid.GetPointData().GetArray(0)
if scalars == None:
scalars = self.ugrid.GetCellData().GetArray(0)
if self.withScalars.get() and not (scalars):
self.warningNoScalarField()
self.status.set("View canceled.")
else:
global root
self.vtkwin = Toplevel(root)
self.vtkwin.title('3D Viewer')
win = VtkWindow3DPoly(self.vtkwin)
win.view(self.ugrid, scalarsOn=self.withScalars.get(
), edgesOn=self.withEdges.get(), colorMap=self.colorMap.get())
self.status.set("Viewing 3D.")
else:
self.warningNoUgrid()
self.status.set("View canceled.")
def tetview(self):
fname = tkinter.filedialog.Open(filetypes=[('Tetgen file', '*.ele'),
('All Files', '*.*')],
initialdir=self.lastloaddir).show()
if fname:
cmd = "tetview.exe %s" % (fname)
# os.system(cmd)
import subprocess
subprocess.call(cmd, shell=True)
self.status.set("Ugrid viewed in TetView window")
else:
self.status.set("View canceled.")
def viewClippedUgrid(self):
if self.ugrid:
scalars = self.ugrid.GetPointData().GetScalars()
if scalars == None:
scalars = self.ugrid.GetCellData().GetScalars()
if scalars == None:
scalars = self.ugrid.GetPointData().GetArray(0)
if scalars == None:
scalars = self.ugrid.GetCellData().GetArray(0)
if self.withScalars.get() and not (scalars):
self.warningNoScalarField()
self.status.set("View canceled.")
else:
global root
self.vtkwin = Toplevel(root)
self.vtkwin.title('3D Cut Viewer')
win = VtkWindow3DPolyCut(self.vtkwin)
win.viewClip(self.ugrid, scalarsOn=self.withScalars.get(
), edgesOn=self.withEdges.get(), colorMap=self.colorMap.get())
self.status.set("Viewing 3D.")
else:
self.warningNoUgrid()
self.status.set("View canceled.")
def moreInfo(self):
if self.ugrid:
win = Toplevel(root)
win.title("Polydata info")
msgFrame = Pmw.ScrolledText(win, vscrollmode='dynamic', hscrollmode='dynamic',
text_width=40, text_height=20, text_wrap='none')
msgFrame.insert('end', str(self.ugrid))
msgFrame.pack(fill=BOTH, expand=YES)
win.transient(root)
else:
self.warningNoUgrid()
def warningNoScalarField(self):
tkinter.messagebox.Message(icon='warning', type='ok',
message='No scalar field in ugrid!',
title='Warning').show()
def warningNoUgrid(self):
tkinter.messagebox.Message(icon='warning', type='ok',
message='No ugrid in memory!',
title='Warning').show()
def setUgrid(self, ugrid):
if ugrid:
self.ugrid = ugrid
self.setParamFromUgrid()
# ----------------------------------------------------------------------
# MAIN
# ----------------------------------------------------------------------
#general_font = ('Helvetica',10,'roman')
#root.option_add('*Font', general_font)
if __name__ == "__main__":
root = Tk()
Pmw.initialise(root)
root.title('vtkToolsGUI - a VTK/Tk/Python interface by ULg/MN2L')
win = MainWindow(root)
root.mainloop()
| 41.7675 | 159 | 0.573412 | 97,907 | 0.976677 | 0 | 0 | 0 | 0 | 0 | 0 | 17,086 | 0.170442 |
d58748147e2304d51e1ae95549251daa443eaa7d | 45,013 | py | Python | Element.py | darinpeetz/Phase_Field | f7169dadbe6f94ed85613da130104fc318358224 | [
"MIT"
] | 2 | 2020-05-28T22:01:49.000Z | 2021-09-10T02:23:04.000Z | Element.py | darinpeetz/Phase_Field | f7169dadbe6f94ed85613da130104fc318358224 | [
"MIT"
] | null | null | null | Element.py | darinpeetz/Phase_Field | f7169dadbe6f94ed85613da130104fc318358224 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 17 14:03:42 2018
@author: Darin
"""
import numpy as np
from matplotlib.patches import Polygon
class Element:
"""
Functions avaiable in this class
--------------------------------
__init__ : constructor
_Get_GP : Gets the Gauss points
_Construct_Shape : Constructs shape functions and derivatives in mapped coordinates
_Shape_Func : Gets shape function and derivatives in parent coordiates
_Assemble_B : Assembles field-to-gradient matrices
_EigenStressStrain : Calculates principle stresses and strains
_EigStrain : Eigenvalue solver for 2D strain matrix
_DiffEig : Calculates derivative of eigenvalues wrt to the matrix
_Constitutive : Provides constitutive relation for stress, stiffness, and energy
_Calc_Energy : Calculates strain energies
Get_Energy : Returns strain energies
Local_Assembly : Assembles local stiffness matrix and rhs vector
Update_Energy : Updates maximum energy values
Objects stored in this class
----------------------------
nodes : array_like
Node numbers attached to this element
eltype : string
Element type ('L2', 'Q4', 'B8', or 'T3')
dim : integer
Dimensions of the element (1, 2, or 3)
order : integer
Integration order for element
weights : 1D array
Weights associated with each Gauss point
Hist : 1D array
Maximum strain energy at each gauss point
Gc : scalar
Griffith's fractur energy
lc : scalar
Critical length factor
E : scalar
Young's Modulus
nu : scalar
Poisson's ratio
lam, mu : scalars
Lame paramters lambda and mu. Only used if E,nu = None
k : scalar
Minimum stiffness of element
aniso : bool
Flag for using anisotropic damage (True) or uniform damage (False)
N : array_like
Shape function values at the Gauss points
J : array_like
Determinants of the Jacobian matrix at the Gauss points
B_u : array_like
Matrices to convert displacements to strain at Gauss points
B_phi : array_like
Matrices to convert damage to gradient of damage at Gauss points
"""
def __init__(self, eltype, nodes, coords, order=None, Gc=500, lc=1, E=1000,
nu=0.3, lam=None, mu=None, k=1e-10, aniso=True):
"""Constructor for element class
Parameters
----------
eltype : string
Element type ('L2', 'Q4', 'B8', or 'T3')
nodes : array_like
Node numbers attached to this element
coords : array_like
Coordinates of nodes attached to this element
order : integer, optional
Integration order for element, defaults to minimum for full
accuracy in an undeformed element
Gc : scalar, optional
Griffith's fractur energy
lc : scalar, optional
Critical length factor
E : scalar, optional
Young's Modulus
nu : scalar, optional
Poisson's ratio
lam, mu : scalars, optional
Lame paramters lambda and mu. Only used if E,nu = None
k : scalar, optional
Minimum stiffness of element
aniso : bool, optional
Flag for using anisotropic damage (True) or uniform damage (False)
Adds to class object
--------------------
nodes : array_like
Node numbers attached to this element
eltype : string
Element type ('L2', 'Q4', 'B8', or 'T3')
dim : integer
Dimensions of the element (1, 2, or 3)
order : integer
Integration order for element
Gc : scalar
Griffith's fractur energy
lc : scalar
Critical length factor
E : scalar
Young's Modulus
nu : scalar
Poisson's ratio
lam, mu : scalars
Lame paramters lambda and mu. Only used if E,nu = None
k : scalar
Minimum stiffness of element
aniso : bool
Flag for using anisotropic damage (True) or uniform damage (False)
"""
if eltype not in ['L2', 'Q4', 'B8', 'T3']:
raise TypeError("Unknown element type (%s) specified"%eltype)
self.nodes = nodes
self.eltype = eltype
self.dim = coords.shape[1]
self.dof = np.array([d+nodes*(self.dim+1) for d in range(self.dim+1)]).T.reshape(-1)
self.udof = np.arange(self.dof.size)
self.phidof = self.udof[self.dim::self.dim+1]
self.udof = np.delete(self.udof,self.phidof)
if order is None:
if eltype == 'L2' or eltype == 'T3':
self.order = 1
elif eltype == 'Q4':
self.order = 2
elif eltype == 'B8':
self.order = 3
else:
self.order = order
self.Set_Properties(Gc, lc, E, nu, lam, mu, k, aniso)
self._Construct_Shape(coords)
self.patch = Polygon(coords, True)
def Set_Properties(self, Gc=500, lc=1, E=1000, nu=0.3, lam=None, mu=None,
k=1e-10, aniso=True):
"""Overrides initial settings for material parameters
Parameters
----------
Gc : scalar, optional
Griffith's fractur energy
lc : scalar, optional
Critical length factor
E : scalar, optional
Young's Modulus
nu : scalar, optional
Poisson's ratio
lam, mu : scalars, optional
Lame paramters lambda and mu. Only used if E,nu = None
k : scalar, optional
Minimum stiffness of element
"""
self.Gc = Gc
self.lc = lc
self.k = k
self.aniso = aniso
if E is None or nu is None:
if lam is None or mu is None:
raise ValueError("Must specify either E and nu or lam and mu")
else:
self.E = mu*(3*lam+2*mu)/(lam+mu)
self.nu = lam/(2*(lam+mu))
self.lam = lam
self.mu = mu
else:
self.E = E
self.nu = nu
self.lam = E*nu/((1+nu)*(1-2*nu))
self.mu = E/(2*(1+nu))
def _Get_GP(self):
"""Assumes L2, Q4, or B8 elements or 2D Tri elements
Parameters
----------
None
Returns
-------
GP : 2D array
Quadrature points
Adds to class object
--------------------
weights : 1D array
weights associated with each Gauss point
"""
if self.eltype == 'T3':
if self.dim != 2:
raise ValueError('Can only use line, quad, box, or tri elements')
# Tri elements
if self.order == 1:
GP = np.array([[1./3, 1./3]])
self.weights = np.array([1./2])
elif self.order == 2:
GP = np.array([[1./6, 1./6], [2./3, 1./6], [1./6, 2./3]])
self.weights = np.array([1./6, 1./6, 1./6])
elif self.order == 3:
GP = np.array([[1./3, 1./3], [1./5, 1./5], [1./5, 3./5], [3./5, 1./5]])
self.weights = np.array([-27., 25., 25., 25.])/96
else:
# Quad elements
GP = np.zeros((self.order*2**(self.dim-1), self.dim))
if self.order == 1:
pnts = np.array([0])
wgts = np.array([2])
elif self.order == 2:
pnts = np.array([-1/np.sqrt(3), 1/np.sqrt(3)])
wgts = np.array([1, 1])
elif self.order == 3:
pnts = np.array([-np.sqrt(0.6), 0, np.sqrt(0.6)])
wgts = np.array([5./9, 8./9, 5./9])
GP[:,0] = np.tile(pnts,2**(self.dim-1))
self.weights = np.tile(wgts, 2**(self.dim-1))
for i in range(1,self.dim):
GP[:,i] = GP[:,i-1].T.reshape(2,-1).T.reshape(-1)
self.weights *= self.weights.T.reshape(2,-1).T.reshape(-1)
return GP
def _Construct_Shape(self, coords):
"""Constructs shape functions, derivatives and B matrices for an element
Parameters
----------
coords : array_like
Coordinates of nodes attached to this element
Returns
-------
None
Adds to class object
--------------------
N : 2D array
Shape function values (dim 1) at the Gauss points (dim 0)
J : 1D array
Determinant of jacobian at each Gauss point
B_u : 3D array, optional
B matrices for u
B_phi : 2D array, optional
B vectors for phi (same as dNdx since phi is a scalar)
Hist : 1D array
Maximum strain energy values (set to zero initally)
"""
GP = self._Get_GP()
self.N, dNdxi = self._Shape_Func(GP)
self.J, self.B_u, self.B_phi = self._Assemble_B(dNdxi, coords)
self.Hist = np.zeros(self.weights.size)
def _Shape_Func(self, GP):
"""Assumes L2, Q4, or B8 elements or 2D Tri elements
Parameters
----------
GP : ND array
Gauss point coordinates
Returns
-------
N : 2D array
Shape function values (dim 1) at the Gauss points (dim 0)
dNdxi : 3D array
Shape function derivatives (dim 1) wrt parent coordinates (dim 2) at the Gauss points (dim 0)
"""
if self.eltype == 'L2':
N = np.zeros((GP.shape[0], 2))
dNdxi = np.zeros((GP.shape[0], 2, GP.shape[1]))
xi = GP[:,0]
# N1 = 1/2-xi/2, N2 = 1/2+xi/2
N[:,0] = 1./2 - xi/2
N[:,1] = 1./2 + xi/2
dNdxi[:,0,0] = -1./2
dNdxi[:,1,0] = 1./2
elif self.eltype == 'Q4':
N = np.zeros((GP.shape[0], 4))
dNdxi = np.zeros((GP.shape[0], 4, GP.shape[1]))
xi = GP[:,0]; eta = GP[:,1]
# N1 = 1/4*(1-xi)(1-eta), N2 = 1/4*(1+xi)(1-eta),
# N3 = 1/4*(1+xi)(1+eta), N4 = 1/4*(1-xi)(1+eta)
N[:,0] = 1./4*(1-xi)*(1-eta)
N[:,1] = 1./4*(1+xi)*(1-eta)
N[:,2] = 1./4*(1+xi)*(1+eta)
N[:,3] = 1./4*(1-xi)*(1+eta)
dNdxi[:,0,0] = -1./4*(1-eta); dNdxi[:,0,1] = -1./4*(1-xi)
dNdxi[:,1,0] = 1./4*(1-eta); dNdxi[:,1,1] = -1./4*(1+xi)
dNdxi[:,2,0] = 1./4*(1+eta); dNdxi[:,2,1] = 1./4*(1+xi)
dNdxi[:,3,0] = -1./4*(1+eta); dNdxi[:,3,1] = 1./4*(1-xi)
elif self.eltype == 'B8':
N = np.zeros((GP.shape[0], 8))
dNdxi = np.zeros((GP.shape[0], 8, GP.shape[1]))
xi = GP[:,0]; eta = GP[:,1]; zeta = GP[:,2]
# N1 = 1/8*(1-xi)*(1-eta)*(1-zeta)
N[:,0] = 1.0/8*(1-xi)*(1-eta)*(1-zeta)
dNdxi[:,0,0] = -1.0/8*(1-eta)*(1-zeta);
dNdxi[:,0,1] = -1.0/8*(1-xi)*(1-zeta);
dNdxi[:,0,2] = -1.0/8*(1-xi)*(1-eta);
# N2 = 1/8*(1+xi)*(1-eta)*(1-zeta)
N[:,1] = 1.0/8*(1+xi)*(1-eta)*(1-zeta)
dNdxi[:,1,0] = 1.0/8*(1-eta)*(1-zeta);
dNdxi[:,1,1] = -1.0/8*(1+xi)*(1-zeta);
dNdxi[:,1,2] = -1.0/8*(1+xi)*(1-eta);
# N3 = 1/8*(1+xi)*(1+eta)*(1-zeta)
N[:,2] = 1.0/8*(1+xi)*(1+eta)*(1-zeta)
dNdxi[:,2,0] = 1.0/8*(1+eta)*(1-zeta);
dNdxi[:,2,1] = 1.0/8*(1+xi)*(1-zeta);
dNdxi[:,2,2] = -1.0/8*(1+xi)*(1+eta);
# N4 = 1/8*(1-xi)*(1+eta)*(1-zeta)
N[:,3] = 1.0/8*(1-xi)*(1+eta)*(1-zeta)
dNdxi[:,3,0] = -1.0/8*(1+eta)*(1-zeta);
dNdxi[:,3,1] = 1.0/8*(1-xi)*(1-zeta);
dNdxi[:,3,2] = -1.0/8*(1-xi)*(1+eta);
# N5 = 1/8*(1-xi)*(1-eta)*(1+zeta)
N[:,4] = 1.0/8*(1-xi)*(1-eta)*(1+zeta)
dNdxi[:,4,0] = -1.0/8*(1-eta)*(1+zeta);
dNdxi[:,4,1] = -1.0/8*(1-xi)*(1+zeta);
dNdxi[:,4,2] = 1.0/8*(1-xi)*(1-eta);
# N6 = 1/8*(1+xi)*(1-eta)*(1+zeta)
N[:,5] = 1.0/8*(1+xi)*(1-eta)*(1+zeta)
dNdxi[:,5,0] = 1.0/8*(1-eta)*(1+zeta);
dNdxi[:,5,1] = -1.0/8*(1+xi)*(1+zeta);
dNdxi[:,5,2] = 1.0/8*(1+xi)*(1-eta);
# N7 = 1/8*(1+xi)*(1+eta)*(1+zeta)
N[:,6] = 1.0/8*(1+xi)*(1+eta)*(1+zeta)
dNdxi[:,6,0] = 1.0/8*(1+eta)*(1+zeta);
dNdxi[:,6,1] = 1.0/8*(1+xi)*(1+zeta);
dNdxi[:,6,2] = 1.0/8*(1+xi)*(1+eta);
# N8 = 1/8*(1-xi)*(1+eta)*(1+zeta)
N[:,7] = 1.0/8*(1-xi)*(1+eta)*(1+zeta)
dNdxi[:,7,0] = -1.0/8*(1+eta)*(1+zeta);
dNdxi[:,7,1] = 1.0/8*(1-xi)*(1+zeta);
dNdxi[:,7,2] = 1.0/8*(1-xi)*(1+eta);
elif self.eltype == 'T3':
N = np.zeros((GP.shape[0], 3))
dNdxi = np.zeros((GP.shape[0], 3, GP.shape[1]))
xi = GP[:,0]; eta = GP[:,1]
# N1 = xi, N2 = eta, N3 = 1 - xi - eta
N[:,0] = xi
N[:,1] = eta
N[:,2] = 1.0 - xi - eta
dNdxi[:,0,0] = 1.0; dNdxi[:,0,1] = 0.0
dNdxi[:,1,0] = 0.0; dNdxi[:,1,1] = 1.0
dNdxi[:,2,0] = -1.0; dNdxi[:,2,1] = -1.0
else:
raise TypeError('Invalid element type specified')
return N, dNdxi
def _Assemble_B(self, dNdxi, coords):
"""Converts dNdxi to dNdx and assembles B matrix for u or phi
Parameters
----------
dNdxi : 3D array
Shape function derivatives (dim 1) wrt parent coordinates (dim 2) at the Gauss points (dim 0)
coords : array_like
Coordinates of nodes attached to this element
Returns
-------
J : 1D array
Determinant of jacobian at each Gauss point
B_u : 3D array, optional
B matrices for u
B_phi : 2D array, optional
B vectors for phi (same as dNdx since phi is a scalar)
"""
nGP = dNdxi.shape[0]
J = np.zeros(nGP)
dNdx = np.zeros((self.dim, dNdxi.shape[1], nGP))
B_u = np.zeros(((self.dim**2+self.dim)/2, coords.size, nGP))
for i in range(nGP):
Jac = np.dot(dNdxi[i,:,:].T, coords)
J[i] = np.linalg.det(Jac)
dNdx[:,:,i] = np.linalg.solve(Jac, dNdxi[i,:,:].T)
if self.dim == 1:
B_u[:,:,i] = dNdx[:,:,i]
if self.dim == 2:
B_u[0,0::2,i] = dNdx[0,:,i]
B_u[1,1::2,i] = dNdx[1,:,i]
B_u[2,0::2,i] = dNdx[1,:,i]
B_u[2,1::2,i] = dNdx[0,:,i]
elif self.dim == 3:
B_u[0,0::3,i] = dNdx[0,:,i]
B_u[1,1::3,i] = dNdx[1,:,i]
B_u[2,2::3,i] = dNdx[2,:,i]
B_u[3,0::3,i] = dNdx[1,:,i]
B_u[3,1::3,i] = dNdx[0,:,i]
B_u[4,1::3,i] = dNdx[2,:,i]
B_u[4,2::3,i] = dNdx[1,:,i]
B_u[5,0::3,i] = dNdx[2,:,i]
return J, B_u, dNdx
def _EigenStressStrain(self, eps, phi, couple=False):
"""Gets the eigenstresses and eigenstrains
Parameters
----------
eps : array_like
The strain tensor in VECTOR form
phi : scalar
The damage variable at the point stresses and strains are measured
couple : boolean, optional
Whether to include coupling terms
Returns
-------
eps_princ : vector
Principal strains
sig_princ : vector
Principal stresses
dlam : array_like
First derivative of principal strains with respect to all strains
d2lam : array_like
Second derivative of principal strains with respect to all strains
H : scalar
1 or 0 indicating whether trace of strains applies to strain energy
Hi : vector
1s or 0s indicating whether each principal strain applies to strain energy
Lmat : array_like
Matrix to convert principal strains to principl stresses
"""
eps_princ = self._EigStrain(eps)
dlam, d2lam = self._DiffEig(eps, eps_princ)
H = 1
if ((eps_princ[0] + eps_princ[1]) < 0 and self.aniso):
H = 0
Hi = np.empty(2, dtype=int)
Hi.fill(1)
if (eps_princ[0] < 0 and self.aniso):
Hi[0] = 0
if (eps_princ[1] < 0 and self.aniso):
Hi[1] = 0
Lmat = np.empty((2,2))
gamma = self.lam * ((1-self.k) * (1 - H*phi)**2 + self.k)
Lmat.fill(gamma)
Lmat[0,0] += 2*self.mu*((1-self.k) * (1-Hi[0]*phi)**2 + self.k)
Lmat[1,1] += 2*self.mu*((1-self.k) * (1-Hi[1]*phi)**2 + self.k)
sig_princ = np.dot(Lmat, eps_princ)
if couple:
# dLmat/dphi
dLmat = 0 * Lmat
gamma = -2 * self.lam * (1-self.k) * H * (1 - H*phi)
dLmat += gamma
dLmat[0,0] -= 4 * self.mu * (1-self.k) * Hi[0] * (1 - Hi[0]*phi)
dLmat[1,1] -= 4 * self.mu * (1-self.k) * Hi[1] * (1 - Hi[1]*phi)
return eps_princ, sig_princ, dlam, d2lam, H, Hi, Lmat, dLmat
else:
return eps_princ, sig_princ, dlam, d2lam, H, Hi, Lmat
def _EigStrain(self, eps):
"""Gets the eigenstresses and eigenstrains
Parameters
----------
eps : vector
The strain tensor in VECTOR form
Returns
-------
lam : vector
The principle strains
"""
lam = np.empty(2)
lam.fill((eps[0]+eps[1])/2)
shift = np.sqrt((eps[0]+eps[1])**2 - 4*(eps[0]*eps[1]-eps[2]**2/4))/2
lam[0] += shift
lam[1] -= shift
return lam
def _DiffEig(self, eps, lam):
"""Returns the derivative of the eigenvalues wrt the matrix
Parameters
----------
eps : vector
The strain tensor in VECTOR form
lam : vector
The principle strains
Returns
-------
dlam : array_like
First derivative of the eigenvalues
d2lam : array_like
Second derivatives of the eigenvalues
"""
dlam = np.zeros((2,3))
d2lam = np.zeros((3,3,2))
R = np.sqrt((lam[0]+lam[1])**2 - 4*(lam[0]*lam[1]))
if ((R < (1e-8*(eps[0]+eps[1]))) or (R == 0)):
# Avoid breakdown that occurs when eigenvalue is multiple or eps = 0
dlam[0,0] = 1.
dlam[0,1] = 0.
dlam[0,2] = 0.
dlam[1,0] = 0.
dlam[1,1] = 1.
dlam[1,2] = 0.
d2lam[2,2,0] = 1./4
d2lam[2,2,1] = 1./4
else:
twoR = 2*R
cost = (eps[0]-eps[1])/R
sint = eps[2]/R
# dlam[0,0] = (1+cost)/2
# dlam[0,1] = (1-cost)/2
# dlam[0,2] = sint/2
# dlam[1,0] = (1-cost)/2
# dlam[1,1] = (1+cost)/2
# dlam[1,2] = -sint/2
#
# d2lam[0,0,0] = (1-cost**2)/twoR
# d2lam[0,1,0] = (cost**2-1)/twoR
# d2lam[0,2,0] = -sint*cost/twoR
# d2lam[1,0,0] = (cost**2-1)/twoR
# d2lam[1,1,0] = (1-cost**2)/twoR
# d2lam[1,2,0] = sint*cost/twoR
# d2lam[2,0,0] = -sint*cost/twoR
# d2lam[2,1,0] = sint*cost/twoR
# d2lam[2,2,0] = (1-sint**2)/twoR
dlam[0,0] = (1+cost)/2
dlam[0,1] = (1-cost)/2
dlam[0,2] = sint/2
dlam[1,0] = dlam[0,1]
dlam[1,1] = dlam[0,0]
dlam[1,2] = -dlam[0,2]
d2lam[0,0,0] = (1-cost**2)/twoR
d2lam[0,1,0] = -d2lam[0,0,0]
d2lam[0,2,0] = -sint*cost/twoR
d2lam[1,0,0] = -d2lam[0,0,0]
d2lam[1,1,0] = d2lam[0,0,0]
d2lam[1,2,0] = -d2lam[0,2,0]
d2lam[2,0,0] = d2lam[0,2,0]
d2lam[2,1,0] = -d2lam[0,2,0]
d2lam[2,2,0] = (1-sint**2)/twoR
d2lam[:,:,1] = -d2lam[:,:,0]
return dlam, d2lam
def _Constitutive(self, eps, phi, energy=True, couple=False):
"""Provides constitutive relations to get stress and tangent stiffness
Parameters
----------
eps : array_like
The strain tensor in VECTOR form
phi : scalar
The damage variable at the point stresses and strains are measured
energy : bool, optional
Flag whether energies should be calculated as well
couple : boolean, optional
Whether to include coupling terms
Returns
-------
stress : vector
stress values in VECTOR form
Cmat : array_like
tangent stiffness matrix
elast_eng : scalar
Elastic energy
elast_ten_eng : scalar
Elastic tensile energy
eng : scalar
Inelastic energy
"""
if (eps == 0.).all():
# When no strain is present, no priniciple strains exist
stress = 0*eps
Cmat = np.array([[1-self.nu, self.nu, 0.], [self.nu, 1-self.nu, 0.],
[0., 0., 0.5-self.nu]])
Cmat *= self.E / ( (1+self.nu) * (1-2*self.nu) )
elast_eng = 0
elast_ten_eng = 0
eng = 0
dstress = stress.copy()
dten_eng = stress.copy()
else:
if couple:
eps_princ, sig_princ, dlam, d2lam, H, Hi, Lmat, dLmat = self._EigenStressStrain(
eps, phi, couple)
else:
eps_princ, sig_princ, dlam, d2lam, H, Hi, Lmat = self._EigenStressStrain(
eps, phi, couple)
stress = np.dot(sig_princ, dlam)
# Derivative of prinicipal stress wrt damage, only necessary for coupling
if couple:
dpsdphi = np.dot(dLmat, eps_princ)
dstress = np.dot(dpsdphi, dlam)
Cmat = np.dot(dlam.T,np.dot(Lmat,dlam)) + np.dot(d2lam, sig_princ)
if energy:
if couple:
elast_eng, elast_ten_eng, eng, dten_eng = self._Calc_Energy(
eps_princ, phi, H, Hi, couple=couple)
dten_eng = np.dot(dten_eng, dlam)
else:
elast_eng, elast_ten_eng, eng = self._Calc_Energy(eps_princ, phi, H, Hi, couple=couple)
if energy:
if couple:
return stress, dstress, Cmat, elast_eng, elast_ten_eng, eng, dten_eng
else:
return stress, Cmat, elast_eng, elast_ten_eng, eng
else:
if couple:
return stress, dstress, Cmat
else:
return stress, Cmat
def _Calc_Energy(self, eps_princ, phi, H, Hi, types=7, couple=False):
"""Calculates elastic, elastic tensile, and inelastic energy
Parameters
----------
eps_princ : array_like
The principle strains
phi : scalar
The damage variable at the point stresses and strains are measured
H : scalar
1 or 0 indicating whether trace of strains applies to strain energy
Hi : vector
1s or 0s indicating whether each principal strain applies to strain energy
types : int, optional
Which energies to return (types&1:elastic, types&2:elastic tensile,
types&4:inelastic)
couple : boolean, optional
Whether to include coupling terms
Returns
-------
elast_eng : scalar
Elastic energy
elast_ten_eng : scalar
Elastic tensile energy
eng : scalar
Inelastic energy
dten_eng : scalar
Derivative of elastic tensile energy wrt eps_princ
"""
if eps_princ.size == 1:
eps_tr = eps_princ[0]
elif eps_princ.size == 2:
eps_tr = eps_princ[0] + eps_princ[1]
elif eps_princ.size == 3:
eps_tr = eps_princ[0] + eps_princ[1] + eps_princ[2]
ret = []
if types & 1:
# elast_eng
ret.append(self.lam/2*eps_tr**2 + self.mu*np.dot(eps_princ.T,eps_princ))
if types & 2:
# elast_ten_eng
ret.append(self.lam/2*H*eps_tr**2 + self.mu*np.dot(eps_princ.T,eps_princ*Hi))
if types & 4:
# eng
ret.append(self.lam/2*((1-self.k)*(1-H*phi)**2 + self.k)*eps_tr**2 +
self.mu*np.dot(eps_princ.T,eps_princ*((1-self.k)*(1-Hi*phi)**2 + self.k)))
if couple:
# dten_eng
ret.append(self.lam * H * eps_tr + 2*self.mu * Hi * eps_princ)
if len(ret) == 1:
return ret[0]
else:
return ret
def Get_Energy(self, eps, phi, types=7):
""" Returns elastic, elastic tensile, and inelastic energy
based on strain/damage values
Parameters
----------
eps : array_like
The strain tensor in VECTOR form
phi : scalar
The damage variable at the point stresses and strains are measured
types : int, optional
Which energies to return (types&1:elastic, types&2:elastic tensile,
types&3:inelastic)
Returns
-------
elast_eng : scalar
Elastic energy
elast_ten_eng : scalar
Elastic tensile energy
eng : scalar
Inelastic energy
"""
eps_princ = self._EigStrain(eps)
H = 1
if ((eps_princ[0] + eps_princ[1]) < 0 and self.aniso):
H = 0
Hi = np.zeros(2, dtype=int)
for i in range(2):
Hi[i] = 1
if (eps_princ[i] < 0 and self.aniso):
Hi[i] = 0
return self._Calc_Energy(eps_princ, phi, H, Hi, types=types, couple=False)
def Energy(self, uphi, types=7, reduction=None):
""" Returns elastic, elastic tensile, and inelastic energy at each
Gauss point based on displacement/damage vector
Parameters
----------
uphi : array_like
vector of displacements/damage for this element
types : int, optional
Which energies to return (types&1:elastic, types&2:elastic tensile,
types&3:inelastic)
reduction : operation, optional
An operation to perform to reduce the values at each Gauss point
to a single value
Returns
-------
elast_eng : scalar
Elastic energy
elast_ten_eng : scalar
Elastic tensile energy
eng : scalar
Inelastic energy
"""
energies = np.zeros((self.weights.size, (types&4)/4 + (types&2)/2 + (types&1)))
for i in range(self.weights.size):
phi = np.dot(self.N[i,:], uphi[self.phidof])
eps = np.dot(self.B_u[:,:,i], uphi[self.udof])
energies[i,:] = self.Get_Energy(eps, phi, types=7)
if reduction is None:
return energies
else:
return reduction(energies, axis=0)
def Stress(self, uphi, reduction=None):
""" Returns stress at each Gauss point based on displacement/damage vector
Parameters
----------
uphi : array_like
vector of displacements/damage for this element
reduction : operation, optional
An operation to perform to reduce the values at each Gauss point
to a single value
Returns
-------
stress : array_like
stress components in VECTOR form
"""
stress = np.zeros((self.weights.size, 3))
for i in range(self.weights.size):
phi = np.dot(self.N[i,:], uphi[self.phidof])
eps = np.dot(self.B_u[:,:,i], uphi[self.udof])
stress[i,:] = el._Constitutive(eps, phi, energy=False, couple=False)[0]
if reduction is None:
return stress
else:
return reduction(stress, axis=0)
def Local_Assembly(self, uphi, section, Assemble=3, couple=False):
"""Assembles the local tangent stiffness matrix and internal force vector
Parameters
----------
uphi : 1D array
The current approximation of u and phi
section : scalar
Part of the matrix to assemble ('uu', 'pp', 'up', or 'pu' or 'all')
'uu' and 'pp' also return the internal force vectors.
Assemble : integer, optional
If Assemble & 1 == 1, assemble K
If Assemble & 2 == 2, assemble RHS
If both true, assemble both
couple : boolean, optional
Whether to include coupling terms
Returns
-------
K_loc : 2D array
Local tangent stiffness matrix
F_loc : 1D array
Local internal force vector
"""
section = section.upper()
# Initialization
if section == 'ALL':
K = np.zeros((uphi.size,uphi.size))
F = np.zeros(uphi.size)
if section == 'UU':
K = np.zeros((self.udof.size,self.udof.size))
F = np.zeros(self.udof.size)
elif section == 'UP':
K = np.zeros((self.udof.size,self.phidof.size))
F = None
elif section == 'PU':
K = np.zeros((self.phidof.size,self.udof.size))
F = None
elif section == 'PP':
K = np.zeros((self.phidof.size,self.phidof.size))
F = np.zeros(self.phidof.size)
# Loop over integration points
for i in range(self.weights.size):
phi = np.dot(self.N[i,:], uphi[self.phidof])
if section == 'ALL' or section == 'UU' or couple:
eps = np.dot(self.B_u[:,:,i], uphi[self.udof])
if couple and section == 'ALL':
stress, dstress, D, elast_eng, elast_ten_eng, eng, dten_eng = self._Constitutive(eps, phi, energy=True, couple=couple)
elif section == 'ALL':
stress, D, elast_eng, elast_ten_eng, eng = self._Constitutive(eps, phi, energy=True, couple=False)
elif section == 'UU':
stress, D = self._Constitutive(eps, phi, energy=False, couple=False)
coeff = self.J[i]*self.weights[i]
if section == 'ALL':
# UU
if Assemble & 1 == 1:
K[self.udof[:,np.newaxis],self.udof] += np.dot(self.B_u[:,:,i].T,
np.dot(D, self.B_u[:,:,i]))*coeff
if Assemble & 2 == 2:
F[self.udof] += np.dot(self.B_u[:,:,i].T, stress)*coeff
# PP
energy = max(elast_ten_eng, self.Hist[i])
if Assemble & 1 == 1:
K[self.phidof[:,np.newaxis],self.phidof] += (self.Gc * self.lc *
np.dot(self.B_phi[:,:,i].T, self.B_phi[:,:,i]) * coeff)
K[self.phidof[:,np.newaxis],self.phidof] += ((self.Gc / self.lc +
2*(1-self.k)*energy) * np.outer(self.N[i,:].T, self.N[i,:])
* coeff)
if Assemble & 2 == 2:
gradphi = np.dot(self.B_phi[:,:,i], uphi[self.phidof])
F[self.phidof] += self.Gc * self.lc * np.dot(self.B_phi[:,:,i].T, gradphi) * coeff
F[self.phidof] += (self.Gc / self.lc + 2*(1-self.k)*energy) * self.N[i,:].T * phi * coeff
F[self.phidof] -= 2*(1-self.k)*energy * self.N[i,:].T * coeff
if couple and Assemble & 1 == 1:
# UP
K[self.udof[:,np.newaxis],self.phidof] += np.outer(np.dot(self.B_u[:,:,i].T,
dstress), self.N[i,:])*coeff
# PU
if elast_ten_eng >= self.Hist[i]:
K[self.phidof[:,np.newaxis],self.udof] += (2*(phi-1) *
(1-self.k) * np.outer(self.N[i,:].T, np.dot(dten_eng,
self.B_u[:,:,i])) * coeff)
elif section == 'UU':
# if Assemble & 1 == 1:
# K += np.dot(self.B_u[:,:,i].T, np.dot(D, self.B_u[:,:,i]))*coeff
# if Assemble & 2 == 2:
# F += np.dot(self.B_u[:,:,i].T, stress)*coeff
self.Assemble_U(K, F, D, stress, i, coeff, Assemble)
elif section == 'UP':
pass
elif section == 'PU':
pass
elif section == 'PP':
if couple:
elast_ten_eng = self.Get_Energy(eps, phi, types=2)
# Use current estimated energy for calculation
energy = max(elast_ten_eng, self.Hist[i])
else:
# Decoupled, ignore currrent approximated energy
energy = self.Hist[i]
# if Assemble & 1 == 1:
# K += self.Gc * self.lc * np.dot(self.B_phi[:,:,i].T, self.B_phi[:,:,i]) * coeff
# K += (self.Gc / self.lc + 2*(1-self.k)*energy) * np.outer(self.N[i,:].T, self.N[i,:]) * coeff
# if Assemble & 2 == 2:
# gradphi = np.dot(self.B_phi[:,:,i], uphi[self.phidof])
# F += self.Gc * self.lc * np.dot(self.B_phi[:,:,i].T, gradphi).reshape(-1) * coeff
# F += (self.Gc / self.lc + 2*(1-self.k)*energy) * self.N[i,:].T * phi * coeff
# F -= 2*(1-self.k)*energy * self.N[i,:].T * coeff
self.Assemble_P(K, F, uphi, phi, i, coeff, energy, Assemble)
return K, F
def Assemble_U(self, K, F, D, stress, i, coeff, Assemble=3):
if Assemble & 1 == 1:
K += np.dot(self.B_u[:,:,i].T, np.dot(D, self.B_u[:,:,i]))*coeff
if Assemble & 2 == 2:
F += np.dot(self.B_u[:,:,i].T, stress)*coeff
def Assemble_P(self, K, F, uphi, phi, i, coeff, energy, Assemble=3):
if Assemble & 1 == 1:
K += self.Gc * self.lc * np.dot(self.B_phi[:,:,i].T, self.B_phi[:,:,i]) * coeff
K += (self.Gc / self.lc + 2*(1-self.k)*energy) * np.dot(self.N[i,None].T, self.N[i,None]) * coeff
if Assemble & 2 == 2:
gradphi = np.dot(self.B_phi[:,:,i], uphi[self.phidof])
F += self.Gc * self.lc * np.dot(self.B_phi[:,:,i].T, gradphi) * coeff
F += (self.Gc / self.lc + 2*(1-self.k)*energy) * self.N[i,:].T * phi * coeff
F -= 2*(1-self.k)*energy * self.N[i,:].T * coeff
def RHS_FD(self, uphi, section, delta=1e-8):
"""Calculates the right hand side using finite differences
Parameters
----------
uphi : 1D array
The current approximation of u and phi
section : scalar, optional
Part of the RHS to assemble ('uu', 'pp' or 'all')
delta : scalar, optional
Finite difference step size
Returns
-------
F_loc : 1D array
Local internal force vector
"""
F_loc = np.zeros(uphi.size)
section = section.upper()
if section == 'ALL':
dof = np.arange(uphi.size)
elif section == 'UU':
dof = np.arange(0, uphi.size, self.dim+1).tolist()
for i in range(1,self.dim):
dof += np.arange(i, uphi.size, self.dim+1).tolist()
dof = np.sort(dof)
elif section == 'PP':
dof = np.arange(self.dim, uphi.size, self.dim+1)
for d in dof:
plus = 0
uphi_del = uphi.copy()
uphi_del[d] += delta
for i in range(self.weights.size):
coeff = self.J[i]*self.weights[i]
phi = np.dot(self.N[i,:],uphi_del[self.phidof])
u = np.zeros((self.dim*uphi_del.size)/(self.dim+1))
for j in range(self.dim):
u[j::self.dim] = np.dot(self.N[i,:],uphi_del[self.udof[j::self.dim]])
gradphi = np.dot(self.B_phi[:,:,i], uphi_del[self.phidof])
eps = np.dot(self.B_u[:,:,i], uphi_del[self.udof])
stress, D, elast_eng, elast_ten_eng, eng = self._Constitutive(eps, phi, energy=True, couple=False)
temp1 = eng
temp2 = self.Gc/2*(phi**2/self.lc + self.lc*np.dot(gradphi,gradphi))
plus += (temp1 + temp2)*coeff
minus = 0
uphi_del = uphi.copy()
uphi_del[d] -= delta
for i in range(self.weights.size):
coeff = self.J[i]*self.weights[i]
phi = np.dot(self.N[i,:],uphi_del[self.phidof])
u = np.zeros((self.dim*uphi_del.size)/(self.dim+1))
for j in range(self.dim):
u[j::self.dim] = np.dot(self.N[i,:],uphi_del[self.udof[j::self.dim]])
gradphi = np.dot(self.B_phi[:,:,i], uphi_del[self.phidof])
eps = np.dot(self.B_u[:,:,i], uphi_del[self.udof])
stress, D, elast_eng, elast_ten_eng, eng = self._Constitutive(eps, phi, energy=True, couple=False)
temp1 = eng
temp2 = self.Gc/2*(phi**2/self.lc + self.lc*np.dot(gradphi,gradphi))
minus += (temp1 + temp2)*coeff
F_loc[d] = (plus-minus)/2/delta;
return F_loc[dof]
def K_FD(self, uphi, section, delta=1e-8):
"""Calculates the tangent stiffness matrix using finite differences on
the RHS vector
Parameters
----------
uphi : 1D array
The current approximation of u and phi
section : scalar, optional
Part of K to assemble ('uu', 'pp' or 'all')
delta : scalar, optional
Finite difference step size
Returns
-------
K_loc : 1D array
Local internal force vector
"""
section = section.upper()
if section == 'ALL':
dof = np.arange(uphi.size)
elif section == 'UU':
dof = np.arange(0, uphi.size, self.dim+1).tolist()
for i in range(1,self.dim):
dof += np.arange(i, uphi.size, self.dim+1).tolist()
dof = np.sort(dof)
elif section == 'PP':
dof = np.arange(self.dim, uphi.size, self.dim+1)
K_loc = np.zeros((dof.size,uphi.size))
for d in dof:
uphi_del = uphi.copy()
uphi_del[d] += delta
plus = self.Local_Assembly(uphi_del, section)[1]
uphi_del = uphi.copy()
uphi_del[d] -= delta
minus = self.Local_Assembly(uphi_del, section)[1]
K_loc[:,d] = (plus-minus)/2/delta;
return K_loc[:,dof]
def K_FD2(self, uphi, section, delta=1e-8):
"""Calculates the tangent stiffness matrix using finite differences on
the energy term
Parameters
----------
uphi : 1D array
The current approximation of u and phi
section : scalar, optional
Part of K to assemble ('uu', 'pp' or 'all')
delta : scalar, optional
Finite difference step size
Returns
-------
K_loc : 1D array
Local internal force vector
"""
section = section.upper()
if section == 'ALL':
dof = np.arange(uphi.size)
elif section == 'UU':
dof = np.arange(0, uphi.size, self.dim+1).tolist()
for i in range(1,self.dim):
dof += np.arange(i, uphi.size, self.dim+1).tolist()
dof = np.sort(dof)
elif section == 'PP':
dof = np.arange(self.dim, uphi.size, self.dim+1)
K_loc = np.zeros((uphi.size,uphi.size))
for d in dof:
for f in dof:
for signs in [[1, 1], [1, -1], [-1, 1], [-1, -1]]:
uphi_del = uphi.copy()
uphi_del[d] += signs[0]*delta
uphi_del[f] += signs[1]*delta
for i in range(self.weights.size):
coeff = self.J[i]*self.weights[i]
phi = np.dot(self.N[i,:],uphi_del[self.phidof])
u = np.zeros((self.dim*uphi_del.size)/(self.dim+1))
for j in range(self.dim):
u[j::self.dim] = np.dot(self.N[i,:],uphi_del[self.udof[j::self.dim]])
gradphi = np.dot(self.B_phi[:,:,i], uphi_del[self.phidof])
eps = np.dot(self.B_u[:,:,i], uphi_del[self.udof])
stress, D, elast_eng, elast_ten_eng, eng = self._Constitutive(eps, phi, energy=True, couple=False)
temp1 = eng
temp2 = self.Gc/2*(phi**2/self.lc + self.lc*np.dot(gradphi,gradphi))
K_loc[d,f] += signs[0]*signs[1] * (temp1 + temp2)*coeff
K_loc /= 4*delta*delta
return K_loc[dof[:,np.newaxis],dof]
def Update_Energy(self, uphi):
"""Updates maximum energy value
Parameters
----------
uphi : 1D array
The current approximation of u and phi
Returns
-------
None
"""
for i in range(self.weights.size):
phi = np.dot(self.N[i,:],uphi[self.phidof])
eps = np.dot(self.B_u[:,:,i], uphi[self.udof])
eps_princ = self._EigStrain(eps)
H = 1
if ((eps_princ[0] + eps_princ[1]) < 0 and self.aniso):
H = 0
Hi = np.zeros(2, dtype=int)
for j in range(2):
Hi[j] = 1
if (eps_princ[j] < 0 and self.aniso):
Hi[j] = 0
elast_ten_eng = self._Calc_Energy(eps_princ, phi, H, Hi, types=2, couple=False)
if self.Hist[i] > elast_ten_eng:
Warning("Energy drop detected")
self.Hist[i] = max(self.Hist[i], elast_ten_eng) | 38.837791 | 135 | 0.459601 | 44,859 | 0.996579 | 0 | 0 | 0 | 0 | 0 | 0 | 17,971 | 0.39924 |
d588539983a2e180d430faf9156fe49f7c14386f | 372 | py | Python | server/tests/test_env.py | amiralis1365/cards-game | db44eaefd0c10c7876be52e97534f7e4201c9581 | [
"CNRI-Python"
] | null | null | null | server/tests/test_env.py | amiralis1365/cards-game | db44eaefd0c10c7876be52e97534f7e4201c9581 | [
"CNRI-Python"
] | null | null | null | server/tests/test_env.py | amiralis1365/cards-game | db44eaefd0c10c7876be52e97534f7e4201c9581 | [
"CNRI-Python"
] | null | null | null | """Sanity test environment setup."""
import os.path
from django.conf import settings
from django.test import TestCase
class EnvTestCase(TestCase):
"""Environment test cases."""
def test_env_file_exists(self):
"""Test environment file exists."""
env_file = os.path.join(settings.DEFAULT_ENV_PATH, ".env")
assert os.path.exists(env_file)
| 24.8 | 66 | 0.701613 | 250 | 0.672043 | 0 | 0 | 0 | 0 | 0 | 0 | 106 | 0.284946 |
d5887287725e2e8a0b6a2fd0c2f42b466eaaa2d4 | 1,705 | py | Python | iglovikov_helper_functions/utils/inpainting_utils.py | AIChuY/iglovikov_helper_functions | 46383c7a8b0f8dbdbf7907e119b6c2417877ad33 | [
"MIT"
] | 46 | 2019-09-21T02:05:50.000Z | 2022-01-02T10:27:56.000Z | iglovikov_helper_functions/utils/inpainting_utils.py | AIChuY/iglovikov_helper_functions | 46383c7a8b0f8dbdbf7907e119b6c2417877ad33 | [
"MIT"
] | 9 | 2020-04-05T01:19:56.000Z | 2021-08-02T16:53:18.000Z | iglovikov_helper_functions/utils/inpainting_utils.py | AIChuY/iglovikov_helper_functions | 46383c7a8b0f8dbdbf7907e119b6c2417877ad33 | [
"MIT"
] | 14 | 2019-09-21T02:54:17.000Z | 2022-02-28T11:58:34.000Z | import math
import random
from typing import Tuple
import cv2
import numpy as np
def np_free_form_mask(
max_vertex: int, max_length: int, max_brush_width: int, max_angle: int, height: int, width: int
) -> np.ndarray:
mask = np.zeros((height, width), np.float32)
num_vertex = random.randint(0, max_vertex)
start_y = random.randint(0, height - 1)
start_x = random.randint(0, width - 1)
brush_width = 0
for i in range(num_vertex):
angle = random.random() * max_angle
angle = math.radians(angle)
if i % 2 == 0:
angle = 2 * math.pi - angle
length = random.randint(0, max_length)
brush_width = random.randint(10, max_brush_width) // 2 * 2
next_y = start_y + length * np.cos(angle)
next_x = start_x + length * np.sin(angle)
next_y = np.maximum(np.minimum(next_y, height - 1), 0).astype(np.int)
next_x = np.maximum(np.minimum(next_x, width - 1), 0).astype(np.int)
cv2.line(mask, (start_y, start_x), (next_y, next_x), 1, brush_width)
cv2.circle(mask, (start_y, start_x), brush_width // 2, 2)
start_y, start_x = next_y, next_x
cv2.circle(mask, (start_y, start_x), brush_width // 2, 2)
return mask
def generate_stroke_mask(
image_size: Tuple[int, int],
parts: int = 7,
max_vertex: int = 25,
max_length: int = 80,
max_brush_width: int = 80,
max_angle: int = 360,
) -> np.ndarray:
mask = np.zeros(image_size, dtype=np.float32)
for _ in range(parts):
mask = mask + np_free_form_mask(
max_vertex, max_length, max_brush_width, max_angle, image_size[0], image_size[1]
)
return np.minimum(mask, 1.0)
| 28.898305 | 99 | 0.629912 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
d588f6a87c411fe8a97c1726c5e01863027c6a64 | 2,393 | py | Python | tests/tester/test_tester.py | Rajpratik71/workload-collocation-agent | 6cf7bdab97ff61d85c21c3effecea632a225c668 | [
"Apache-2.0"
] | 40 | 2019-05-16T16:42:33.000Z | 2021-11-18T06:33:03.000Z | tests/tester/test_tester.py | Rajpratik71/workload-collocation-agent | 6cf7bdab97ff61d85c21c3effecea632a225c668 | [
"Apache-2.0"
] | 72 | 2019-05-09T02:30:25.000Z | 2020-11-17T09:24:44.000Z | tests/tester/test_tester.py | Rajpratik71/workload-collocation-agent | 6cf7bdab97ff61d85c21c3effecea632a225c668 | [
"Apache-2.0"
] | 26 | 2019-05-20T09:13:38.000Z | 2021-12-15T17:57:21.000Z | # Copyright (c) 2019 Intel Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from unittest.mock import MagicMock, patch
from wca.nodes import Task
from wca.config import register
from wca.extra.static_allocator import StaticAllocator
from tests.tester.tester import IntegrationTester, FileCheck, MetricCheck
@patch('tests.tester.tester._delete_cgroup')
@patch('tests.tester.tester._create_cgroup')
@patch('sys.exit')
def test_tester(
mock_sys_exit: MagicMock,
mock_create_cgroup: MagicMock,
mock_delete_cgroup: MagicMock):
register(FileCheck)
register(MetricCheck)
register(StaticAllocator)
mock_check = MagicMock()
tester = IntegrationTester('tests/tester/test_config.yaml')
tester.testcases[0]['checks'] = [mock_check]
tester.testcases[1]['checks'] = [mock_check]
# Prepare first testcase.
assert tester.get_tasks() == [Task(
name='task1', task_id='task1', cgroup_path='/test/task1',
labels={}, resources={}, subcgroups_paths=[]), Task(
name='task2', task_id='task2', cgroup_path='/test/task2',
labels={}, resources={}, subcgroups_paths=[])]
assert mock_create_cgroup.call_count == 2
# Do checks from first testcase. Prepare second one.
assert tester.get_tasks() == [Task(
name='task2', task_id='task2', cgroup_path='/test/task2',
labels={}, resources={}, subcgroups_paths=[]), Task(
name='task4', task_id='task4', cgroup_path='/test/task4',
labels={}, resources={}, subcgroups_paths=[])]
assert mock_check.check.call_count == 1
assert mock_create_cgroup.call_count == 3
assert mock_delete_cgroup.call_count == 1
tester.get_tasks()
assert mock_check.check.call_count == 2
assert mock_create_cgroup.call_count == 3
assert mock_delete_cgroup.call_count == 3
mock_sys_exit.assert_called()
| 35.191176 | 74 | 0.708734 | 0 | 0 | 0 | 0 | 1,573 | 0.657334 | 0 | 0 | 885 | 0.369829 |
d5892906d499f0f5a6f042d091d257df411e9d0c | 31,503 | py | Python | etl/parsers/etw/Microsoft_Windows_USB_USBHUB.py | IMULMUL/etl-parser | 76b7c046866ce0469cd129ee3f7bb3799b34e271 | [
"Apache-2.0"
] | 104 | 2020-03-04T14:31:31.000Z | 2022-03-28T02:59:36.000Z | etl/parsers/etw/Microsoft_Windows_USB_USBHUB.py | IMULMUL/etl-parser | 76b7c046866ce0469cd129ee3f7bb3799b34e271 | [
"Apache-2.0"
] | 7 | 2020-04-20T09:18:39.000Z | 2022-03-19T17:06:19.000Z | etl/parsers/etw/Microsoft_Windows_USB_USBHUB.py | IMULMUL/etl-parser | 76b7c046866ce0469cd129ee3f7bb3799b34e271 | [
"Apache-2.0"
] | 16 | 2020-03-05T18:55:59.000Z | 2022-03-01T10:19:28.000Z | # -*- coding: utf-8 -*-
"""
Microsoft-Windows-USB-USBHUB
GUID : 7426a56b-e2d5-4b30-bdef-b31815c1a74a
"""
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.utils import WString, CString, SystemTime, Guid
from etl.dtyp import Sid
from etl.parsers.etw.core import Etw, declare, guid
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=1, version=0)
class Microsoft_Windows_USB_USBHUB_1_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_USB_HubDescriptor" / Int64ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=2, version=0)
class Microsoft_Windows_USB_USBHUB_2_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / CString,
"fid_USBHUB_Hub" / Int32sl
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=3, version=0)
class Microsoft_Windows_USB_USBHUB_3_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_USB_HubDescriptor" / Int64ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=10, version=0)
class Microsoft_Windows_USB_USBHUB_10_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=11, version=0)
class Microsoft_Windows_USB_USBHUB_11_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=12, version=0)
class Microsoft_Windows_USB_USBHUB_12_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=13, version=0)
class Microsoft_Windows_USB_USBHUB_13_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=14, version=0)
class Microsoft_Windows_USB_USBHUB_14_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=15, version=0)
class Microsoft_Windows_USB_USBHUB_15_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=16, version=0)
class Microsoft_Windows_USB_USBHUB_16_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=17, version=0)
class Microsoft_Windows_USB_USBHUB_17_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=18, version=0)
class Microsoft_Windows_USB_USBHUB_18_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=19, version=0)
class Microsoft_Windows_USB_USBHUB_19_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=20, version=0)
class Microsoft_Windows_USB_USBHUB_20_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=21, version=0)
class Microsoft_Windows_USB_USBHUB_21_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=22, version=0)
class Microsoft_Windows_USB_USBHUB_22_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=23, version=0)
class Microsoft_Windows_USB_USBHUB_23_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=24, version=0)
class Microsoft_Windows_USB_USBHUB_24_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=25, version=0)
class Microsoft_Windows_USB_USBHUB_25_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=26, version=0)
class Microsoft_Windows_USB_USBHUB_26_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=27, version=0)
class Microsoft_Windows_USB_USBHUB_27_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=28, version=0)
class Microsoft_Windows_USB_USBHUB_28_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=29, version=0)
class Microsoft_Windows_USB_USBHUB_29_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=30, version=0)
class Microsoft_Windows_USB_USBHUB_30_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=31, version=0)
class Microsoft_Windows_USB_USBHUB_31_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=32, version=0)
class Microsoft_Windows_USB_USBHUB_32_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=33, version=0)
class Microsoft_Windows_USB_USBHUB_33_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=34, version=0)
class Microsoft_Windows_USB_USBHUB_34_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=35, version=0)
class Microsoft_Windows_USB_USBHUB_35_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=36, version=0)
class Microsoft_Windows_USB_USBHUB_36_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=37, version=0)
class Microsoft_Windows_USB_USBHUB_37_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=39, version=0)
class Microsoft_Windows_USB_USBHUB_39_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=40, version=0)
class Microsoft_Windows_USB_USBHUB_40_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=41, version=0)
class Microsoft_Windows_USB_USBHUB_41_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=49, version=0)
class Microsoft_Windows_USB_USBHUB_49_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=50, version=0)
class Microsoft_Windows_USB_USBHUB_50_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=51, version=0)
class Microsoft_Windows_USB_USBHUB_51_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=59, version=0)
class Microsoft_Windows_USB_USBHUB_59_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=60, version=0)
class Microsoft_Windows_USB_USBHUB_60_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=61, version=0)
class Microsoft_Windows_USB_USBHUB_61_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=62, version=0)
class Microsoft_Windows_USB_USBHUB_62_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=63, version=0)
class Microsoft_Windows_USB_USBHUB_63_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=64, version=0)
class Microsoft_Windows_USB_USBHUB_64_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=70, version=0)
class Microsoft_Windows_USB_USBHUB_70_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=71, version=0)
class Microsoft_Windows_USB_USBHUB_71_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=80, version=0)
class Microsoft_Windows_USB_USBHUB_80_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_PortAttributes" / Int16ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=81, version=0)
class Microsoft_Windows_USB_USBHUB_81_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=82, version=0)
class Microsoft_Windows_USB_USBHUB_82_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=83, version=0)
class Microsoft_Windows_USB_USBHUB_83_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=84, version=0)
class Microsoft_Windows_USB_USBHUB_84_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=100, version=0)
class Microsoft_Windows_USB_USBHUB_100_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Device" / Int64sl,
"fid_USBHUB_Device_State" / Guid,
"fid_DeviceDescriptor" / Int64ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=101, version=0)
class Microsoft_Windows_USB_USBHUB_101_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / CString,
"fid_USBHUB_Device" / Int32sl
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=102, version=0)
class Microsoft_Windows_USB_USBHUB_102_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Device" / Int64sl,
"fid_USBHUB_Device_State" / Guid,
"fid_DeviceDescriptor" / Int64ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=103, version=0)
class Microsoft_Windows_USB_USBHUB_103_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8sl,
"fid_USBHUB_Device" / Int32ul,
"fid_DeviceDescription" / WString
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=110, version=0)
class Microsoft_Windows_USB_USBHUB_110_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8sl,
"fid_USBHUB_Device" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=111, version=0)
class Microsoft_Windows_USB_USBHUB_111_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8sl,
"fid_USBHUB_Device" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=112, version=0)
class Microsoft_Windows_USB_USBHUB_112_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8sl,
"fid_USBHUB_Device" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=113, version=0)
class Microsoft_Windows_USB_USBHUB_113_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8sl,
"fid_USBHUB_Device" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=114, version=0)
class Microsoft_Windows_USB_USBHUB_114_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8sl,
"fid_USBHUB_Device" / Int32ul,
"fid_DeviceDescription" / WString
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=119, version=0)
class Microsoft_Windows_USB_USBHUB_119_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8sl,
"fid_USBHUB_Device" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=120, version=0)
class Microsoft_Windows_USB_USBHUB_120_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Device" / Int64sl,
"fid_PowerState" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=121, version=0)
class Microsoft_Windows_USB_USBHUB_121_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Device" / Int64sl,
"fid_PowerState" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=122, version=0)
class Microsoft_Windows_USB_USBHUB_122_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Device" / Int64sl,
"fid_PowerState" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=123, version=0)
class Microsoft_Windows_USB_USBHUB_123_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Device" / Int64sl,
"fid_PowerState" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=130, version=0)
class Microsoft_Windows_USB_USBHUB_130_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8sl,
"fid_USBHUB_Device" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=139, version=0)
class Microsoft_Windows_USB_USBHUB_139_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8sl,
"fid_USBHUB_Device" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=140, version=0)
class Microsoft_Windows_USB_USBHUB_140_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8sl,
"fid_USBHUB_Device" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=149, version=0)
class Microsoft_Windows_USB_USBHUB_149_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8sl,
"fid_USBHUB_Device" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=150, version=0)
class Microsoft_Windows_USB_USBHUB_150_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=151, version=0)
class Microsoft_Windows_USB_USBHUB_151_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=159, version=0)
class Microsoft_Windows_USB_USBHUB_159_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=160, version=0)
class Microsoft_Windows_USB_USBHUB_160_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PowerState" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=161, version=0)
class Microsoft_Windows_USB_USBHUB_161_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PowerState" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=169, version=0)
class Microsoft_Windows_USB_USBHUB_169_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PowerState" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=170, version=0)
class Microsoft_Windows_USB_USBHUB_170_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PowerState" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=171, version=0)
class Microsoft_Windows_USB_USBHUB_171_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PowerState" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=172, version=0)
class Microsoft_Windows_USB_USBHUB_172_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=173, version=0)
class Microsoft_Windows_USB_USBHUB_173_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=174, version=0)
class Microsoft_Windows_USB_USBHUB_174_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=175, version=0)
class Microsoft_Windows_USB_USBHUB_175_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=176, version=0)
class Microsoft_Windows_USB_USBHUB_176_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=177, version=0)
class Microsoft_Windows_USB_USBHUB_177_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=178, version=0)
class Microsoft_Windows_USB_USBHUB_178_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=179, version=0)
class Microsoft_Windows_USB_USBHUB_179_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=180, version=0)
class Microsoft_Windows_USB_USBHUB_180_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=181, version=0)
class Microsoft_Windows_USB_USBHUB_181_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=183, version=0)
class Microsoft_Windows_USB_USBHUB_183_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=184, version=0)
class Microsoft_Windows_USB_USBHUB_184_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=185, version=0)
class Microsoft_Windows_USB_USBHUB_185_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=189, version=0)
class Microsoft_Windows_USB_USBHUB_189_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PowerState" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=190, version=0)
class Microsoft_Windows_USB_USBHUB_190_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PowerState" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=199, version=0)
class Microsoft_Windows_USB_USBHUB_199_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PowerState" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=200, version=0)
class Microsoft_Windows_USB_USBHUB_200_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PowerState" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=209, version=0)
class Microsoft_Windows_USB_USBHUB_209_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PowerState" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=210, version=0)
class Microsoft_Windows_USB_USBHUB_210_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int32sl,
"fid_USBHUB_Hub" / Double,
"fid_PortNumber" / Int32ul,
"fid_Class" / Int32ul,
"fid_NtStatus" / Int32ul,
"fid_UsbdStatus" / Int32ul,
"fid_DebugText" / CString
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=211, version=0)
class Microsoft_Windows_USB_USBHUB_211_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_PortStatusChange" / Int16ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=212, version=0)
class Microsoft_Windows_USB_USBHUB_212_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_TimerTag" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=213, version=0)
class Microsoft_Windows_USB_USBHUB_213_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_TimerTag" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=214, version=0)
class Microsoft_Windows_USB_USBHUB_214_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_TimerTag" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=220, version=0)
class Microsoft_Windows_USB_USBHUB_220_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8sl,
"fid_USBHUB_Device" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=229, version=0)
class Microsoft_Windows_USB_USBHUB_229_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8sl,
"fid_USBHUB_Device" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=230, version=0)
class Microsoft_Windows_USB_USBHUB_230_0(Etw):
pattern = Struct(
"fid_TimeElapsedBeforeLogStart" / Int64ul,
"fid_USBHUB_HC" / Int32ul,
"fid_USBHUB_Hub" / Int8ul,
"fid_PortNumber" / Int32ul,
"fid_Class" / Int32ul,
"fid_NtStatus" / Int32ul,
"fid_UsbdStatus" / Int32ul,
"fid_DebugText" / CString
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=231, version=0)
class Microsoft_Windows_USB_USBHUB_231_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8sl,
"fid_USBHUB_Device" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=232, version=0)
class Microsoft_Windows_USB_USBHUB_232_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8sl,
"fid_USBHUB_Device" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=233, version=0)
class Microsoft_Windows_USB_USBHUB_233_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
@declare(guid=guid("7426a56b-e2d5-4b30-bdef-b31815c1a74a"), event_id=234, version=0)
class Microsoft_Windows_USB_USBHUB_234_0(Etw):
pattern = Struct(
"fid_USBHUB_HC" / Int8ul,
"fid_USBHUB_Hub" / Int64sl,
"fid_PortNumber" / Int32ul,
"fid_Status" / Int32ul
)
| 29.917379 | 123 | 0.669301 | 21,864 | 0.694029 | 0 | 0 | 30,821 | 0.978351 | 0 | 0 | 10,300 | 0.326953 |
d5894d927b0277f7ba467a9bda0d567ef57efa68 | 678 | py | Python | tests/testapp/models/caretaker.py | BBooijLiewes/django-binder | b5bf0aad14657fd57d575f9a0ef21468533f64a7 | [
"MIT"
] | null | null | null | tests/testapp/models/caretaker.py | BBooijLiewes/django-binder | b5bf0aad14657fd57d575f9a0ef21468533f64a7 | [
"MIT"
] | null | null | null | tests/testapp/models/caretaker.py | BBooijLiewes/django-binder | b5bf0aad14657fd57d575f9a0ef21468533f64a7 | [
"MIT"
] | null | null | null | from django.db import models
from django.db.models import Count, F, Max
from binder.models import BinderModel
class Caretaker(BinderModel):
name = models.TextField()
last_seen = models.DateTimeField(null=True, blank=True)
# We have the ssn for each caretaker. We have to make sure that nobody can access this ssn in anyway, since
# this shouldn't be accessible
ssn = models.TextField(default='my secret ssn')
def __str__(self):
return 'caretaker %d: %s' % (self.pk, self.name)
class Binder:
history = True
class Annotations:
best_animal = Max('animals__name')
animal_count = Count('animals')
bsn = F('ssn') # simple alias
last_present = F('last_seen')
| 28.25 | 108 | 0.731563 | 566 | 0.834808 | 0 | 0 | 0 | 0 | 0 | 0 | 224 | 0.330383 |
d58b4673e8699aa22b8c8f9e9c79b3d6ac592f80 | 292 | py | Python | blog/2017-12-17--python-ssh-logger/scripts/create_threads.py | mpolinowski/gatsby-starter-minimal-blog | cdb628357e806be211c3220bfb7b50ac0c204a6c | [
"MIT"
] | 1 | 2020-10-20T16:39:11.000Z | 2020-10-20T16:39:11.000Z | blog/2017-12-17--python-ssh-logger/scripts/create_threads.py | mpolinowski/gatsby-starter-minimal-blog | cdb628357e806be211c3220bfb7b50ac0c204a6c | [
"MIT"
] | null | null | null | blog/2017-12-17--python-ssh-logger/scripts/create_threads.py | mpolinowski/gatsby-starter-minimal-blog | cdb628357e806be211c3220bfb7b50ac0c204a6c | [
"MIT"
] | null | null | null | import threading
# Create threads for each SSH connection
def create_threads(list, function):
threads = []
for ip in list:
th = threading.Thread(target = function, args = (ip,))
th.start()
threads.append(th)
for th in threads:
th.join() | 20.857143 | 62 | 0.59589 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 40 | 0.136986 |
d58c1422d124dbf9b76d6fdfb103b78c63395525 | 1,129 | py | Python | generate_csv.py | KishanChandravanshi/forecast-cyclone-path | 766bb8440206b24d34ccd0eae488e2651d4e0467 | [
"MIT"
] | null | null | null | generate_csv.py | KishanChandravanshi/forecast-cyclone-path | 766bb8440206b24d34ccd0eae488e2651d4e0467 | [
"MIT"
] | null | null | null | generate_csv.py | KishanChandravanshi/forecast-cyclone-path | 766bb8440206b24d34ccd0eae488e2651d4e0467 | [
"MIT"
] | null | null | null | import cv2
from darkflow.net.build import TFNet
import numpy as np
import glob
import matplotlib.pyplot as plt
options = {
'model': 'cfg/yolo-v2.cfg',
'load':8375,
'gpu':0.8,
'threshold':0.1
}
count = 1
tfnet = TFNet(options)
color = [0, 255, 0]
files_path = glob.glob('data_from_imd' + "\\*.jpg")
for file in files_path:
print('Working on {}, Please wait...'.format(file))
img = cv2.imread(file, cv2.IMREAD_COLOR)
results = tfnet.return_predict(img)
try:
top_detection = results[:1]
for result in top_detection:
# first we will be trying to store the x_coordinate, y_coordinate in the file
x1, y1 = (result['topleft']['x'], result['topleft']['y'])
x2, y2 = (result['bottomright']['x'], result['bottomright']['y'])
x_coordinate = (x1 + x2) // 2
y_coordinate = (y1 + y2) // 2
with open('csvfile.txt', 'a') as myfile:
temp = str(count) + ',' + str(x_coordinate) + "," + str(y_coordinate) + '\n'
myfile.writelines(temp)
count += 1
except Exception as e:
print(str(e))
| 33.205882 | 92 | 0.583702 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 260 | 0.230292 |
d58d822662d574ca4045a6e27ecef06bb1dab250 | 1,421 | py | Python | weibo/items.py | flyhighfairy/weibo | 469f21543facaba828fa7c0ad0dd8da130192fba | [
"MIT"
] | 1 | 2018-01-23T19:36:27.000Z | 2018-01-23T19:36:27.000Z | weibo/items.py | flyhighfairy/weibo | 469f21543facaba828fa7c0ad0dd8da130192fba | [
"MIT"
] | null | null | null | weibo/items.py | flyhighfairy/weibo | 469f21543facaba828fa7c0ad0dd8da130192fba | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class WeiboVMblogsItem(scrapy.Item):
domain = scrapy.Field()
uid = scrapy.Field()
mblog_id = scrapy.Field()
mblog_content = scrapy.Field()
created_time = scrapy.Field()
crawled_time = scrapy.Field()
def get_insert_sql(self):
insert_sql = """
insert into crawled_weibov_mblogs(domain, uid, mblog_id, mblog_content, created_time, crawled_time)
VALUES (%s, %s, %s, %s, %s, %s)
"""
params = (self["domain"], self["uid"], self["mblog_id"], self["mblog_content"], self["created_time"], self["crawled_time"])
return insert_sql, params
class WeiboVCommentsItem(scrapy.Item):
mblog_id = scrapy.Field()
uid = scrapy.Field()
comment_id = scrapy.Field()
comment_content = scrapy.Field()
created_time = scrapy.Field()
crawled_time = scrapy.Field()
def get_insert_sql(self):
insert_sql = """
insert into crawled_weibov_comments(mblog_id, uid, comment_id, comment_content, created_time, crawled_time)
VALUES (%s, %s, %s, %s, %s, %s)
"""
params = (self["mblog_id"], self["uid"], self["comment_id"], self["comment_content"], self["created_time"], self["crawled_time"])
return insert_sql, params | 30.891304 | 137 | 0.63969 | 1,250 | 0.879662 | 0 | 0 | 0 | 0 | 0 | 0 | 633 | 0.445461 |
d58eecd34de9c6681c2ee538dc026e2a42c6715b | 4,284 | py | Python | examples/acoustics/vibro_acoustic3d.py | clazaro/sfepy | 78757a6989d6aaf85a3fb27957b9179c5e2aa2c7 | [
"BSD-3-Clause"
] | 1 | 2021-05-15T16:28:45.000Z | 2021-05-15T16:28:45.000Z | examples/acoustics/vibro_acoustic3d.py | clazaro/sfepy | 78757a6989d6aaf85a3fb27957b9179c5e2aa2c7 | [
"BSD-3-Clause"
] | null | null | null | examples/acoustics/vibro_acoustic3d.py | clazaro/sfepy | 78757a6989d6aaf85a3fb27957b9179c5e2aa2c7 | [
"BSD-3-Clause"
] | null | null | null | r"""
Vibro-acoustic problem
3D acoustic domain with 2D perforated deforming interface.
*Master problem*: defined in 3D acoustic domain (``vibro_acoustic3d.py``)
*Slave subproblem*: 2D perforated interface (``vibro_acoustic3d_mid.py``)
Master 3D problem - find :math:`p` (acoustic pressure)
and :math:`g` (transversal acoustic velocity) such that:
.. math::
c^2 \int_{\Omega} \nabla q \cdot \nabla p
- \omega^2 \int_{\Omega} q p
+ i \omega c \int_{\Gamma_{in}} q p
+ i \omega c \int_{\Gamma_{out}} q p
- i \omega c^2 \int_{\Gamma_0} (q^+ - q^-) g
= 2i \omega c \int_{\Gamma_{in}} q \bar{p}
\;, \quad \forall q \;,
- i \omega \int_{\Gamma_0} f (p^+ - p^-)
- \omega^2 \int_{\Gamma_0} F f g
+ \omega^2 \int_{\Gamma_0} C f w
= 0
\;, \quad \forall f \;,
Slave 2D subproblem - find :math:`w` (plate deflection)
and :math:`\ul{\theta}` (rotation) such that:
.. math::
\omega^2 \int_{\Gamma_0} C z g
- \omega^2 \int_{\Gamma_0} S z w
+ \int_{\Gamma_0} \nabla z \cdot \ull{G} \cdot \nabla w
- \int_{\Gamma_0} \ul{\theta} \cdot \ull{G} \cdot \nabla z
= 0
\;, \quad \forall z \;,
- \omega^2 \int_{\Gamma_0} R\, \ul{\nu} \cdot \ul{\theta}
+ \int_{\Gamma_0} D_{ijkl} e_{ij}(\ul{\nu}) e_{kl}(\ul{\theta})
- \int_{\Gamma_0} \ul{\nu} \cdot \ull{G} \cdot \nabla w
+ \int_{\Gamma_0} \ul{\nu} \cdot \ull{G} \cdot \ul{\theta}
= 0
\;, \quad \forall \ul{\nu} \;,
"""
from __future__ import absolute_import
from sfepy import data_dir
filename_mesh = data_dir + '/meshes/3d/acoustic_wg.vtk'
sound_speed = 343.0
wave_num = 5.5
p_inc = 300
c = sound_speed
c2 = c**2
w = wave_num * c
w2 = w**2
wc = w * c
wc2 = w * c2
regions = {
'Omega1': 'cells of group 1',
'Omega2': 'cells of group 2',
'GammaIn': ('vertices of group 1', 'face'),
'GammaOut': ('vertices of group 2', 'face'),
'Gamma_aux': ('r.Omega1 *v r.Omega2', 'face'),
'Gamma0_1': ('copy r.Gamma_aux', 'face', 'Omega1'),
'Gamma0_2': ('copy r.Gamma_aux', 'face', 'Omega2'),
'aux_Left': ('vertices in (x < 0.001)', 'face'),
'aux_Right': ('vertices in (x > 0.299)', 'face'),
'Gamma0_1_Left': ('r.Gamma0_1 *v r.aux_Left', 'edge'),
'Gamma0_1_Right': ('r.Gamma0_1 *v r.aux_Right', 'edge'),
}
fields = {
'pressure1': ('complex', 'scalar', 'Omega1', 1),
'pressure2': ('complex', 'scalar', 'Omega2', 1),
'tvelocity': ('complex', 'scalar', 'Gamma0_1', 1),
'deflection': ('complex', 'scalar', 'Gamma0_1', 1),
}
variables = {
'p1': ('unknown field', 'pressure1', 0),
'q1': ('test field', 'pressure1', 'p1'),
'p2': ('unknown field', 'pressure2', 1),
'q2': ('test field', 'pressure2', 'p2'),
'g0': ('unknown field', 'tvelocity', 2),
'f0': ('test field', 'tvelocity', 'g0'),
'w': ('unknown field', 'deflection', 3),
'z': ('test field', 'deflection', 'w'),
}
ebcs = {
'fixed_l': ('Gamma0_1_Left', {'w.0': 0.0}),
'fixed_r': ('Gamma0_1_Right', {'w.0': 0.0}),
}
options = {
'file_per_var': True,
}
functions = {
}
materials = {
'ac' : ({'F': -2.064e+00, 'c': -1.064e+00}, ),
}
equations = {
'eq_1' : """
%e * dw_laplace.5.Omega1(q1, p1)
+ %e * dw_laplace.5.Omega2(q2, p2)
- %e * dw_volume_dot.5.Omega1(q1, p1)
- %e * dw_volume_dot.5.Omega2(q2, p2)
+ %s * dw_surface_dot.5.GammaIn(q1, p1)
+ %s * dw_surface_dot.5.GammaOut(q2, p2)
- %s * dw_surface_dot.5.Gamma0_1(q1, g0)
+ %s * dw_surface_dot.5.Gamma0_2(q2, tr(g0))
= %s * dw_surface_integrate.5.GammaIn(q1)"""\
% (c2, c2, w2, w2,
1j * wc, 1j * wc,
1j * wc2, 1j * wc2,
2j * wc * p_inc),
'eq_2' : """
- %s * dw_surface_dot.5.Gamma0_1(f0, p1)
+ %s * dw_surface_dot.5.Gamma0_1(f0, tr(p2))
- %e * dw_surface_dot.5.Gamma0_1(ac.F, f0, g0)
+ %e * dw_surface_dot.5.Gamma0_1(ac.c, f0, w)
= 0"""\
% (1j * w, 1j * w, w2, w2),
}
solvers = {
'ls': ('ls.cm_pb',
{'others': [data_dir
+ '/examples/acoustics/vibro_acoustic3d_mid.py'],
'coupling_variables': ['g0', 'w'],
}),
'nls': ('nls.newton', {
'i_max' : 1,
'eps_a' : 1e-6,
'eps_r' : 1e-6,
})
}
| 29.544828 | 73 | 0.538749 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,156 | 0.736695 |