content stringlengths 1 1.05M | input_ids listlengths 1 883k | ratio_char_token float64 1 22.9 | token_count int64 1 883k |
|---|---|---|---|
import unittest
from mock import patch
from starter.starter_AdminEmail import starter_AdminEmail
from tests.activity.classes_mock import FakeLogger
from tests.classes_mock import FakeLayer1
import tests.settings_mock as settings_mock
| [
11748,
555,
715,
395,
198,
6738,
15290,
1330,
8529,
198,
6738,
14217,
13,
12339,
62,
46787,
15333,
1330,
14217,
62,
46787,
15333,
198,
6738,
5254,
13,
21797,
13,
37724,
62,
76,
735,
1330,
33482,
11187,
1362,
198,
6738,
5254,
13,
37724,
... | 3.790323 | 62 |
from unittest import TestCase
import numpy as np
import phi
from phi import math
from phi.math import channel, batch
from phi.math._shape import CHANNEL_DIM, BATCH_DIM, shape_stack, spatial
from phi.math._tensors import TensorStack, CollapsedTensor, wrap, tensor, cached
from phi.math.backend import Backend
BACKENDS = phi.detect_backends()
| [
6738,
555,
715,
395,
1330,
6208,
20448,
198,
198,
11748,
299,
32152,
355,
45941,
198,
198,
11748,
872,
72,
198,
6738,
872,
72,
1330,
10688,
198,
6738,
872,
72,
13,
11018,
1330,
6518,
11,
15458,
198,
6738,
872,
72,
13,
11018,
13557,
... | 2.974138 | 116 |
# Bep Marketplace ELE
# Copyright (c) 2016-2021 Kolibri Solutions
# License: See LICENSE file or https://github.com/KolibriSolutions/BepMarketplace/blob/master/LICENSE
#
from django.contrib import admin
from django.shortcuts import reverse
from django.utils.html import format_html
from .models import Track, Broadcast, FeedbackReport, UserMeta, Term, UserAcceptedTerms
admin.site.register(Term)
admin.site.register(UserAcceptedTerms, UserAcceptedTermsAdmin)
admin.site.register(UserMeta, UserMetaAdmin)
admin.site.register(Broadcast)
admin.site.register(FeedbackReport, FeedbackReportAdmin)
admin.site.register(Track)
| [
2,
220,
347,
538,
36703,
40342,
198,
2,
220,
15069,
357,
66,
8,
1584,
12,
1238,
2481,
25910,
571,
380,
23555,
198,
2,
220,
13789,
25,
4091,
38559,
24290,
2393,
393,
3740,
1378,
12567,
13,
785,
14,
42,
349,
571,
380,
50,
14191,
14,... | 3.253886 | 193 |
from datetime import datetime
from pytz import timezone
from troposphere import Ref, Template, Parameter, GetAZs, Output, Join, GetAtt, autoscaling, ec2, elasticloadbalancing as elb
t = Template()
t.add_description("Create FireCARES Webserver Load Balancer, Auto-Scaling group and Celery beat VM")
base_ami = "ami-7646e460"
now = datetime.utcnow().replace(tzinfo=timezone('UTC')).isoformat()
key_name = t.add_parameter(Parameter(
"KeyName",
Description="Name of an existing EC2 KeyPair to enable SSH access to the instances",
Type="AWS::EC2::KeyPair::KeyName",
ConstraintDescription="Must be the name of an existing EC2 KeyPair."
))
ami = t.add_parameter(Parameter(
"baseAmi",
Description="Name of the AMI to use",
Type="String",
ConstraintDescription="Must be the name of an existing AMI.",
Default=base_ami
))
beatami = t.add_parameter(Parameter(
"beatAmi",
Description="Name of the beat AMI",
Type="String",
ConstraintDescription="Must be the name of an existing AMI."
))
web_capacity = t.add_parameter(Parameter(
"WebServerCapacity",
Default="2",
Description="The initial number of WebServer instances",
Type="Number",
ConstraintDescription="must be between 1 and 5 EC2 instances.",
MinValue="1",
MaxValue="5",
))
commit = t.add_parameter(Parameter(
"CommitHash",
Description="Commit hash used for building the web VM",
Type="String"
))
beat_instance_class = t.add_parameter(Parameter(
"BeatInstanceClass",
Default="t2.large",
Description="Celery beat EC2 instance type",
Type="String",
ConstraintDescription="must be a valid EC2 instance type.",
AllowedValues=[
"t1.micro",
"t2.nano",
"t2.micro",
"t2.small",
"t2.medium",
"t2.large",
"m1.small",
"m1.medium",
"m1.large",
"m1.xlarge",
"m2.xlarge",
"m2.2xlarge",
"m2.4xlarge",
"m3.medium",
"m3.large",
"m3.xlarge",
"m3.2xlarge",
"m4.large",
"m4.xlarge",
"m4.2xlarge",
"m4.4xlarge",
"m4.10xlarge",
"c1.medium",
"c1.xlarge",
"c3.large",
"c3.xlarge",
"c3.2xlarge",
"c3.4xlarge",
"c3.8xlarge",
"c4.large",
"c4.xlarge",
"c4.2xlarge",
"c4.4xlarge",
"c4.8xlarge",
"g2.2xlarge",
"g2.8xlarge",
"r3.large",
"r3.xlarge",
"r3.2xlarge",
"r3.4xlarge",
"r3.8xlarge",
"i2.xlarge",
"i2.2xlarge",
"i2.4xlarge",
"i2.8xlarge",
"d2.xlarge",
"d2.2xlarge",
"d2.4xlarge",
"d2.8xlarge",
"hi1.4xlarge",
"hs1.8xlarge",
"cr1.8xlarge",
"cc2.8xlarge",
"cg1.4xlarge"
]
))
web_instance_class = t.add_parameter(Parameter(
"WebInstanceClass",
Default="t2.small",
Description="WebServer EC2 instance type",
Type="String",
ConstraintDescription="must be a valid EC2 instance type.",
AllowedValues=[
"t1.micro",
"t2.nano",
"t2.micro",
"t2.small",
"t2.medium",
"t2.large",
"m1.small",
"m1.medium",
"m1.large",
"m1.xlarge",
"m2.xlarge",
"m2.2xlarge",
"m2.4xlarge",
"m3.medium",
"m3.large",
"m3.xlarge",
"m3.2xlarge",
"m4.large",
"m4.xlarge",
"m4.2xlarge",
"m4.4xlarge",
"m4.10xlarge",
"c1.medium",
"c1.xlarge",
"c3.large",
"c3.xlarge",
"c3.2xlarge",
"c3.4xlarge",
"c3.8xlarge",
"c4.large",
"c4.xlarge",
"c4.2xlarge",
"c4.4xlarge",
"c4.8xlarge",
"g2.2xlarge",
"g2.8xlarge",
"r3.large",
"r3.xlarge",
"r3.2xlarge",
"r3.4xlarge",
"r3.8xlarge",
"i2.xlarge",
"i2.2xlarge",
"i2.4xlarge",
"i2.8xlarge",
"d2.xlarge",
"d2.2xlarge",
"d2.4xlarge",
"d2.8xlarge",
"hi1.4xlarge",
"hs1.8xlarge",
"cr1.8xlarge",
"cc2.8xlarge",
"cg1.4xlarge"
]
))
environment = t.add_parameter(Parameter(
"Environment",
Description="Stack environment (e.g. prod, dev, int)",
Type="String",
MinLength="1",
MaxLength="12",
Default="dev",
))
load_balancer = t.add_resource(elb.LoadBalancer(
"LoadBalancer",
CrossZone=True,
AvailabilityZones=GetAZs(""),
LoadBalancerName=Join('-', ['fc', Ref(environment), Ref(commit)]),
AppCookieStickinessPolicy=[
{
"PolicyName": "AppCookieBasedPolicy",
"CookieName": "sticky"
}
],
Listeners=[
{
"LoadBalancerPort": "80",
"InstancePort": "80",
"Protocol": "HTTP"
},
{
"LoadBalancerPort": "443",
"InstancePort": "80",
"Protocol": "HTTPS",
"SSLCertificateId": "arn:aws:acm:us-east-1:164077527722:certificate/a8085d69-3f7b-442e-baa6-70f3bd9b4981",
"PolicyNames": [
"AppCookieBasedPolicy"
]
}
]
))
web_sg = t.add_resource(ec2.SecurityGroup(
"WebServers",
GroupDescription=Join(' - ', ["FireCARES webserver group", Ref(environment), Ref(commit)]),
SecurityGroupIngress=[
ec2.SecurityGroupRule("ELBAccess",
IpProtocol="tcp",
FromPort="80",
ToPort="80",
SourceSecurityGroupOwnerId=GetAtt(load_balancer, "SourceSecurityGroup.OwnerAlias"),
SourceSecurityGroupName=GetAtt(load_balancer, "SourceSecurityGroup.GroupName")
),
ec2.SecurityGroupRule("JenkinsAccess", IpProtocol="tcp", FromPort="22", ToPort="22", CidrIp="54.173.150.226/32"),
ec2.SecurityGroupRule("TylerAccess", IpProtocol="tcp", FromPort="22", ToPort="22", CidrIp="73.173.214.176/32"),
ec2.SecurityGroupRule("JoeAccess", IpProtocol="tcp", FromPort="22", ToPort="22", CidrIp="65.254.97.100/32"),
ec2.SecurityGroupRule("JoeAccess2", IpProtocol="tcp", FromPort="22", ToPort="22", CidrIp="108.66.75.162/32"),
ec2.SecurityGroupRule("JoeAccess3", IpProtocol="tcp", FromPort="22", ToPort="22", CidrIp="71.86.4.190/32"),
ec2.SecurityGroupRule("JoeAccess4", IpProtocol="tcp", FromPort="22", ToPort="22", CidrIp="75.133.14.178/32"),
ec2.SecurityGroupRule("SontagAccess", IpProtocol="tcp", FromPort="22", ToPort="22", CidrIp="47.215.167.239/32"),
ec2.SecurityGroupRule("SontagAccess", IpProtocol="tcp", FromPort="22", ToPort="22", CidrIp="54.87.125.141/32"),
ec2.SecurityGroupRule("SontagAccess", IpProtocol="tcp", FromPort="22", ToPort="22", CidrIp="54.167.99.192/32"),
ec2.SecurityGroupRule("SontagAccess", IpProtocol="tcp", FromPort="22", ToPort="22", CidrIp="52.205.224.226/32"),
ec2.SecurityGroupRule("SontagAccess", IpProtocol="tcp", FromPort="22", ToPort="22", CidrIp="52.206.122.170/32"),
ec2.SecurityGroupRule("SontagAccess", IpProtocol="tcp", FromPort="22", ToPort="22", CidrIp="52.202.117.147/32")
],
))
launch_configuration = t.add_resource(autoscaling.LaunchConfiguration(
"WebServerLaunchConfiguration",
ImageId=Ref(ami),
InstanceType=Ref(web_instance_class),
KeyName=Ref(key_name),
SecurityGroups=[Ref(web_sg)]
))
beat = t.add_resource(ec2.Instance(
"BeatInstance",
ImageId=Ref(beatami),
InstanceType=Ref(beat_instance_class),
KeyName=Ref(key_name),
SecurityGroups=[Ref(web_sg)],
Tags=[
ec2.Tag("environment", Ref(environment)),
ec2.Tag("Name", Join('-', ['celerybeat', Ref(environment), Ref(commit)])),
ec2.Tag("Group", Join('-', ['celerybeat', Ref(environment)]))
]
))
autoscaling_group = t.add_resource(autoscaling.AutoScalingGroup(
"WebserverAutoScale",
AvailabilityZones=['us-east-1b', 'us-east-1c'],
DesiredCapacity=Ref(web_capacity),
MinSize="1",
MaxSize="5",
Tags=[
autoscaling.Tag("environment", Ref(environment), True),
autoscaling.Tag("Name", Join('-', ['web-server', Ref(environment), Ref(commit)]), True),
autoscaling.Tag("Group", Join('-', ['web-server', Ref(environment)]), True)
],
LoadBalancerNames=[Ref(load_balancer)],
HealthCheckType="EC2",
LaunchConfigurationName=Ref(launch_configuration)
))
t.add_output([
Output(
"stackURL",
Description="Stack url",
Value=Join("", [GetAtt(load_balancer, 'DNSName')]),
)
])
t.add_output([
Output(
"WebServerSecurityGroup",
Description="Web server security group.",
Value=Join("", [GetAtt(web_sg, 'GroupId')]),
)
])
t.add_output([
Output(
"AMI",
Description="Web server ami image group.",
Value=Ref(ami),
)
])
if __name__ == '__main__':
print t.to_json()
| [
6738,
4818,
8079,
1330,
4818,
8079,
198,
6738,
12972,
22877,
1330,
640,
11340,
198,
6738,
14673,
22829,
1330,
6524,
11,
37350,
11,
25139,
2357,
11,
3497,
22778,
82,
11,
25235,
11,
15251,
11,
3497,
8086,
11,
1960,
17500,
4272,
11,
9940,
... | 2.015409 | 4,478 |
# GCD Program
from math import gcd
# input
num1 = int(input('Enter a number: '))
num2 = int(input('Enter another number: '))
# processing & output
divisor = 1
upper_limit = min(num1, num2)
gcd_answer = 0
#print(num1, 'and', num2, 'share these factors:')
print('GCD of', num1, 'and', num2, 'is:')
while divisor <= upper_limit:
if num1 % divisor == 0 and num2 % divisor == 0:
gcd_answer = divisor
divisor += 1
# end of while loop
print(gcd_answer)
print('Math Module GCD:', gcd(num1,num2)) | [
2,
402,
8610,
6118,
198,
198,
6738,
10688,
1330,
308,
10210,
198,
198,
2,
5128,
198,
22510,
16,
796,
493,
7,
15414,
10786,
17469,
257,
1271,
25,
705,
4008,
198,
22510,
17,
796,
493,
7,
15414,
10786,
17469,
1194,
1271,
25,
705,
4008,... | 2.43128 | 211 |
#!/usr/bin/python
import random
word_len = 5
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
output = open('word_count', 'w')
words = set()
N = 1000*1000
for x in xrange(N):
arr = [random.choice(alphabet) for i in range(word_len)]
words.add(''.join(arr))
print len(words)
for word in words:
output.write(word)
output.write('\t')
output.write(str(random.randint(1, 2*N)))
output.write('\n')
| [
2,
48443,
14629,
14,
8800,
14,
29412,
198,
198,
11748,
4738,
198,
198,
4775,
62,
11925,
796,
642,
198,
17307,
8380,
796,
705,
24694,
32988,
17511,
23852,
42,
31288,
45,
3185,
48,
49,
2257,
52,
30133,
34278,
57,
39305,
4299,
456,
2926,... | 2.304124 | 194 |
from django.shortcuts import render
from .models import PrivRepNotification,Notification
from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
| [
6738,
42625,
14208,
13,
19509,
23779,
1330,
8543,
198,
6738,
764,
27530,
1330,
9243,
6207,
3673,
2649,
11,
3673,
2649,
198,
6738,
42625,
14208,
13,
4023,
1330,
449,
1559,
31077,
11,
367,
29281,
31077,
7738,
1060,
11,
367,
29281,
31077,
... | 3.904762 | 42 |
# Definition for singly-linked list.
# Definition for a binary tree node.
head = ListNode(1)
p1 = ListNode(2)
p2 = ListNode(3)
p3 = ListNode(4)
p4 = ListNode(5)
p5 = ListNode(6)
p6 = ListNode(7)
head.next = p1
p1.next = p2
p2.next = p3
p3.next = p4
p4.next = p5
p5.next = p6
test = Solution()
print test.sortedListToBST(head).val
| [
2,
30396,
329,
1702,
306,
12,
25614,
1351,
13,
198,
198,
2,
30396,
329,
257,
13934,
5509,
10139,
13,
628,
198,
2256,
796,
7343,
19667,
7,
16,
8,
198,
79,
16,
796,
7343,
19667,
7,
17,
8,
198,
79,
17,
796,
7343,
19667,
7,
18,
8,... | 2.226667 | 150 |
import tensorflow as tf
import tensorflow.keras as k
import numpy as np
from load_and_augment import load_and_augment_data
from modelconfig import modelconfig
from compile_model import compile_model_adam
import compile_model
if __name__=='__main__':
path=r'/content/drive/My Drive/data'
testing_path=r'/content/drive/My Drive/test/'
training_gen,val_gen,test_gen=load_and_augment_data(path,testing_path)
model=modelconfig(0.25)
model=compile_model_adam(model,0.001,1.2)
cb=tf.keras.callbacks.EarlyStopping(monitor='val_loss',
min_delta=0,
patience=5,
verbose=0, mode='auto')
history=model.fit_generator(generator=training_gen,steps_per_epoch=25,epochs=100,validation_data=val_gen, validation_steps=10,callbacks=[cb])
training=pd.DataFrame(history.history)
training.to_csv('training_statistics.csv',index=False)
evaluation_test=model.evaluate_gen(test_gen)
print('test accuracy= {} and f1={}'.format(evaluation_test[1],evaluation_test[2]))
model.save('model_polythene.h5')
| [
11748,
11192,
273,
11125,
355,
48700,
201,
198,
11748,
11192,
273,
11125,
13,
6122,
292,
355,
479,
201,
198,
11748,
299,
32152,
355,
45941,
201,
198,
6738,
3440,
62,
392,
62,
559,
5154,
1330,
3440,
62,
392,
62,
559,
5154,
62,
7890,
... | 2.297297 | 481 |
import os
import glob
import codecs
from typing import List
if __name__ == "__main__":
f2b_print_data_list()
| [
11748,
28686,
198,
11748,
15095,
198,
11748,
40481,
82,
198,
198,
6738,
19720,
1330,
7343,
628,
628,
628,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
198,
220,
220,
220,
277,
17,
65,
62,
4798,
62,
7890,
62,
4868,
3... | 2.727273 | 44 |
import time
from django import forms
from django.core.exceptions import ValidationError
from .widgets import CaptchaWidget
from .settings import DURATION
| [
11748,
640,
628,
198,
6738,
42625,
14208,
1330,
5107,
198,
6738,
42625,
14208,
13,
7295,
13,
1069,
11755,
1330,
3254,
24765,
12331,
628,
198,
6738,
764,
28029,
11407,
1330,
6790,
11693,
38300,
198,
6738,
764,
33692,
1330,
360,
4261,
6234,... | 3.809524 | 42 |
# ---
# jupyter:
# jupytext:
# cell_metadata_filter: -all
# comment_magics: true
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.11.3
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# # Existing skill tags data
# 1. Look at data
# 2. Build a simple baseline classifier
#
# Karlis tagged 50 jobs with where the skills were mentioned. Can we train something to identify sentences as about skills or not?
#
# Would be helpful for taking out the junk.
# +
from sklearn.linear_model import LogisticRegression
import json
import random
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import (
accuracy_score,
classification_report,
f1_score,
precision_score,
recall_score,
)
# -
# ### Import data
with open(
"../../../../inputs/karlis_ojo_manually_labelled/OJO_test_labelling_April2021_jobs.jsonl",
"r",
) as file:
jobs_data = [json.loads(line) for line in file]
jobs_data[0].keys()
with open(
"../../../../inputs/karlis_ojo_manually_labelled/OJO_test_labelling_April2021_labels.json",
"r",
) as file:
labels_data = json.load(file)
label_type_dict = {label_type["id"]: label_type["text"] for label_type in labels_data}
label_type_dict
# ### Restructuring to have a look
# +
all_job_tags_text = {}
for job_id, job_info in enumerate(jobs_data):
text = job_info["text"]
annotations = job_info["annotations"]
job_tags_text = {}
for label_number, label_type in label_type_dict.items():
job_tags_text[label_type] = [
text[label["start_offset"] : label["end_offset"]]
for label in annotations
if label["label"] == label_number
]
all_job_tags_text[job_id] = job_tags_text
# -
job_id = 1
print(jobs_data[job_id]["text"])
print("\n")
print(all_job_tags_text[job_id]["SKILL"])
print(all_job_tags_text[job_id]["SKILL-RELATED"])
# ## Create a basic classifier
# Label sentences with containing skills (1) or not (0)
#
# Method assumes sentences are split by full stop and will run into problems if the skill has a full stop in.
# Testing
job_id = 2
sentences, sentences_label = label_sentences(job_id)
print(all_job_tags_text[job_id]["SKILL"])
print(all_job_tags_text[job_id]["SKILL-RELATED"])
print([sentences[i] for i, label in enumerate(sentences_label) if label == 1])
print([sentences[i] for i, label in enumerate(sentences_label) if label == 0])
# Create training dataset
X = []
y = []
for job_id in range(len(jobs_data)):
sentences, sentences_label = label_sentences(job_id)
for sentence, sentence_label in zip(sentences, sentences_label):
X.append(sentence)
y.append(sentence_label)
# +
# Random shuffle data points
shuffle_index = list(range(len(X)))
random.Random(42).shuffle(shuffle_index)
X = [X[i] for i in shuffle_index]
y = [y[i] for i in shuffle_index]
# Split test/train set
train_split = 0.75
len_train = round(len(X) * train_split)
X_train = X[0:len_train]
y_train = y[0:len_train]
X_test = X[len_train:]
y_test = y[len_train:]
# -
print(len(X))
print(len(y_train))
print(len(y_test))
vectorizer = CountVectorizer(
analyzer="word",
token_pattern=r"(?u)\b\w+\b",
ngram_range=(1, 2),
stop_words="english",
)
X_train_vect = vectorizer.fit_transform(X_train)
model = MultinomialNB()
model = model.fit(X_train_vect, y_train)
X_test_vect = vectorizer.transform(X_test)
y_test_pred = model.predict(X_test_vect)
print(classification_report(y_test, y_test_pred))
# +
# LogisticRegression
model = LogisticRegression(max_iter=1000, class_weight="balanced")
model = model.fit(X_train_vect, y_train)
X_test_vect = vectorizer.transform(X_test)
y_test_pred = model.predict(X_test_vect)
print(classification_report(y_test, y_test_pred))
# -
| [
2,
11420,
198,
2,
474,
929,
88,
353,
25,
198,
2,
220,
220,
474,
929,
88,
5239,
25,
198,
2,
220,
220,
220,
220,
2685,
62,
38993,
62,
24455,
25,
532,
439,
198,
2,
220,
220,
220,
220,
2912,
62,
19726,
873,
25,
2081,
198,
2,
220... | 2.535088 | 1,596 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-11 13:45
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
2980,
515,
416,
37770,
352,
13,
940,
13,
20,
319,
2177,
12,
486,
12,
1157,
1511,
25,
2231,
198,
6738,
11593,
37443,
834,
1330,
28000,
1098,
62,
17201,
874,
198,
1... | 2.883117 | 77 |
import pytest
import pprint
import string
import random
import os
from pyatlas import AtlasClient
#from testutils import *
def test_create_apikey(client,project):
project_name=project['content']['name']
print(f'project_name={project_name}')
desc = f"test key for project {project_name}"
key = client.create_apikey(project_name=project_name
,description=desc)
print('-------------------- start generated apikey --------------------')
print(key)
print('-------------------- end generated apikey --------------------')
assert key is not None
## utils
| [
11748,
12972,
9288,
220,
198,
11748,
279,
4798,
198,
11748,
4731,
198,
11748,
4738,
198,
11748,
28686,
198,
6738,
12972,
265,
21921,
1330,
22494,
11792,
198,
2,
6738,
1332,
26791,
1330,
1635,
198,
198,
4299,
1332,
62,
17953,
62,
499,
52... | 3.175532 | 188 |
# Copyright 2022 The etils 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.
"""Abstract path."""
from __future__ import annotations
import os
import pathlib
import typing
from typing import Any, AnyStr, Iterator, Optional, Type, TypeVar
from etils.epath.typing import PathLike
T = TypeVar('T')
# Ideally, `Path` should be `abc.ABC`. However this trigger pytype errors
# when calling `Path()` (can't instantiate abstract base class)
# Also this allow path childs to only partially implement the Path API (e.g.
# read only path)
def rglob(self: T, pattern: str) -> Iterator[T]:
"""Yielding all matching files recursivelly (of any kind)."""
return self.glob(f'**/{pattern}')
def expanduser(self: T) -> T:
"""Returns a new path with expanded `~` and `~user` constructs."""
if '~' not in self.parts: # pytype: disable=attribute-error
return self
raise NotImplementedError
def read_bytes(self) -> bytes:
"""Reads contents of self as bytes."""
with self.open('rb') as f:
return f.read()
def read_text(self, encoding: Optional[str] = None) -> str:
"""Reads contents of self as bytes."""
with self.open('r', encoding=encoding) as f:
return f.read()
# ====== Write methods ======
def write_bytes(self, data: bytes) -> int:
"""Writes content as bytes."""
with self.open('wb') as f:
return f.write(data)
def write_text(
self,
data: str,
encoding: Optional[str] = None,
errors: Optional[str] = None,
) -> int:
"""Writes content as str."""
if encoding and encoding.lower() not in {'utf8', 'utf-8'}:
raise NotImplementedError(f'Non UTF-8 encoding not supported for {self}')
if errors:
raise NotImplementedError(f'Error not supported for writing {self}')
with self.open('w') as f:
return f.write(data)
def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None:
"""Create a file at this given path."""
if mode != 0o666:
raise NotImplementedError(f'Only mode=0o666 supported for {self}')
if self.exists():
if exist_ok:
return
else:
raise FileExistsError(f'{self} already exists.')
self.write_text('')
| [
2,
15069,
33160,
383,
2123,
4487,
46665,
13,
198,
2,
198,
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
198,
2,
345,
743,
407,
779,
428,
2393,
2845,
287,
11846,
351,
262,
13789,
13,
198,
2... | 2.911828 | 930 |
from .ifstat import IfStat
from .returnstat import ReturnStat
from .whilestat import WhileStat
from .breakstat import BreakStat
from .switchstat import SwitchStat
from .casestat import CaseStat
from .forstat import ForStat
from .continuestat import ContinueStat
| [
6738,
764,
361,
14269,
1330,
1002,
17126,
198,
6738,
764,
7783,
14269,
1330,
8229,
17126,
198,
6738,
764,
1929,
346,
395,
265,
1330,
2893,
17126,
198,
6738,
764,
9032,
14269,
1330,
12243,
17126,
198,
6738,
764,
31943,
14269,
1330,
14645,
... | 3.797101 | 69 |
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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
import mock
from vsphere_base_action_test_case import VsphereBaseActionTestCase
from guest_process_start import StartProgramInGuest
__all__ = [
'StartProgramInGuestTestCase'
]
| [
2,
49962,
284,
262,
23881,
32173,
11,
3457,
19203,
25896,
32173,
11537,
739,
530,
393,
517,
198,
2,
18920,
5964,
11704,
13,
220,
4091,
262,
28536,
2393,
9387,
351,
198,
2,
428,
670,
329,
3224,
1321,
5115,
6634,
9238,
13,
198,
2,
383... | 3.870833 | 240 |
from typing import (
Iterable,
Mapping,
MutableMapping,
Optional,
Tuple,
TypeVar,
Union,
)
import collections
import logging
import operator
import types
from haoda import ir
from soda import tensor
import soda.visitor
_logger = logging.getLogger().getChild(__name__)
def shift(obj, offset, excluded=(), op=operator.sub, verbose=False):
"""Shift soda.ir.Ref with the given offset.
All soda.ir.Ref, excluding the given names, will be shifted with the
given offset using the given operator. The operator will be applied pointwise
on the original index and the given offset.
Args:
obj: A haoda.ir.Node or a tensor.Tensor object.
offset: Second operand given to the operator.
excluded: Sequence of names to be excluded from the mutation. Default to ().
op: Shifting operator. Should be either add or sub. Default to sub.
verbose: Whether to log shiftings. Default to False.
Returns:
Mutated obj. If obj is an IR node, it will be a different object than the
input. If obj is a tensor, it will be the same object but with fields
mutated.
"""
if op not in (operator.add, operator.sub):
_logger.warn('shifting with neither + nor -, which most likely is an error')
if isinstance(obj, ir.Node):
return obj.visit(visitor)
if isinstance(obj, tensor.Tensor):
obj.mutate(visitor)
else:
raise TypeError('argument is not an IR node or a tensor')
return obj
def normalize(obj: Union[ir.Node, Iterable[ir.Node]],
references: Optional[Mapping[str, Tuple[int, ...]]] = None):
"""Make the least access index 0.
Works on an ir.Node or an iterable of ir.Nodes. If it is shifted, a different
object is constructed and returned. Otherwise, obj will be returned as-is.
Args:
obj: A node or an iterable of nodes.
Returns:
Normalized node or iterable.
Raises:
TypeError: If argument is not an ir.Node or an iterable of ir.Nodes.
"""
if isinstance(obj, types.GeneratorType):
return normalize(tuple(obj))
norm_idx = soda.visitor.get_normalize_index(obj, references)
shifter = lambda x: shift(x, norm_idx) if any(norm_idx) else x
if isinstance(obj, collections.Iterable):
return type(obj)(map(shifter, obj)) # type: ignore
if isinstance(obj, ir.Node):
return shifter(obj)
raise TypeError('argument is not an ir.Node or an iterable of ir.Nodes')
NodeT = TypeVar('NodeT', bound=ir.Node)
def replace_expressions(
obj: NodeT,
cses: MutableMapping[NodeT, ir.Ref],
used: Optional[MutableMapping[NodeT, NodeT]] = None,
references: Optional[Mapping[str, Tuple[int, ...]]] = None,
) -> NodeT:
"""Get AST with common subexpression elimination.
Get AST with the given common subexpressions. If used is not None, the used
common subexpressions will be added to used.
Args:
obj: An ir.Node.
cses: Dict mapping normalized common subexpressions to the new ir.Ref.
used: Set of used common subexpressions, or None.
Returns:
The ir.Node as the AST.
"""
return obj.visit(visitor, (cses, used))
| [
6738,
19720,
1330,
357,
198,
220,
220,
220,
40806,
540,
11,
198,
220,
220,
220,
337,
5912,
11,
198,
220,
220,
220,
13859,
540,
44,
5912,
11,
198,
220,
220,
220,
32233,
11,
198,
220,
220,
220,
309,
29291,
11,
198,
220,
220,
220,
... | 2.968147 | 1,036 |
from skillmap.skillmap_parser import SkillMapParser
| [
6738,
5032,
8899,
13,
42401,
8899,
62,
48610,
1330,
16023,
13912,
46677,
628
] | 4.076923 | 13 |
"""Consec days"""
import calendar
from pandas.io.sql import read_sql
from pyiem.plot.use_agg import plt
from pyiem.util import get_autoplot_context, get_dbconn
PDICT = {'above': 'Temperature At or Above (AOA) Threshold',
'below': 'Temperature Below Threshold'}
PDICT2 = {'high': 'High Temperature',
'low': 'Low Temperature'}
def get_description():
""" Return a dict describing how to call this plotter """
desc = dict()
desc['data'] = True
desc['description'] = """This chart presents the daily frequency of the
given date having the prescribed number of previous days above or below
some provided treshold."""
desc['arguments'] = [
dict(type='station', name='station', default='IATDSM',
label='Select Station:', network='IACLIMATE'),
dict(type='select', name='var', default='high', options=PDICT2,
label='Select which daily variable'),
dict(type='select', name='dir', default='above', options=PDICT,
label='Select temperature direction'),
dict(type='int', name='threshold', default='60',
label='Temperature Threshold (F):'),
dict(type='int', name='days', default='7',
label='Number of Days:')
]
return desc
def plotter(fdict):
""" Go """
pgconn = get_dbconn('coop')
ctx = get_autoplot_context(fdict, get_description())
station = ctx['station']
days = ctx['days']
threshold = ctx['threshold']
varname = ctx['var']
mydir = ctx['dir']
table = "alldata_%s" % (station[:2],)
agg = "min" if mydir == 'above' else 'max'
op = ">=" if mydir == 'above' else '<'
df = read_sql("""
with data as (select day,
"""+agg+"""("""+varname+""")
OVER (ORDER by day ASC ROWS BETWEEN %s PRECEDING
and CURRENT ROW) as agg from """ + table + """
where station = %s)
select extract(doy from day) as doy,
sum(case when agg """+op+""" %s then 1 else 0 end)
/ count(*)::float * 100. as freq
from data GROUP by doy ORDER by doy asc
""", pgconn, params=(days - 1, station, threshold), index_col='doy')
fig, ax = plt.subplots(1, 1, sharex=True)
label = "AOA" if mydir == 'above' else 'below'
ax.set_title(("[%s] %s\nFrequency of %s Consec Days"
r" with %s %s %s$^\circ$F "
) % (station, ctx['_nt'].sts[station]['name'],
days, varname.capitalize(), label, threshold))
ax.set_ylabel("Frequency of Days [%]")
ax.set_ylim(0, 100)
ax.set_yticks([0, 5, 10, 25, 50, 75, 90, 95, 100])
ax.grid(True)
ax.bar(df.index.values, df['freq'], width=1)
ax.set_xticks((1, 32, 60, 91, 121, 152, 182, 213, 244, 274,
305, 335, 365))
ax.set_xticklabels(calendar.month_abbr[1:])
ax.set_xlim(0, 366)
return fig, df
if __name__ == '__main__':
plotter(dict())
| [
37811,
3103,
2363,
1528,
37811,
198,
11748,
11845,
198,
198,
6738,
19798,
292,
13,
952,
13,
25410,
1330,
1100,
62,
25410,
198,
6738,
12972,
26597,
13,
29487,
13,
1904,
62,
9460,
1330,
458,
83,
198,
6738,
12972,
26597,
13,
22602,
1330,
... | 2.336531 | 1,251 |
"""Resolwe REST API helpers."""
| [
37811,
4965,
349,
732,
30617,
7824,
49385,
526,
15931,
198
] | 3.2 | 10 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from requests.auth import AuthBase
| [
2,
48443,
14629,
14,
8800,
14,
29412,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
6738,
7007,
13,
18439,
1330,
26828,
14881,
628
] | 2.548387 | 31 |
import csv
import numpy as np
import pickle
with open('data (2).csv','r') as f:
csv = csv.reader(f)
csvlist = []
for i in csv:
csvlist.append(i)
#6
mas = []
for i in range(364):
i+=6
a = 0
b = 0
c = 0
date = csvlist[i][0]
weather = csvlist[i][1]
if date[0:10] == "2016/11/1 " or date[0:10] == "2016/11/2 " or date[0:10] == "2016/11/3 " or date[0:9] == "2016/11/4" or date[0:9] == "2016/11/5" or date[0:9] == "2016/11/6" or date[0:9] == "2016/11/7":
continue
if weather == "1" or weather == "2":
a = 1
elif weather == "3" or weather == "4" or weather == "5" or weather == "6":
b = 1
else:
c = 1
w = [a,b,c]
print(date[0:10])
mas.append(w)
mas = np.array(mas)
with open('tenki_num.pkl','wb') as f:
pickle.dump(mas,f)
| [
11748,
269,
21370,
201,
198,
11748,
299,
32152,
355,
45941,
201,
198,
11748,
2298,
293,
201,
198,
201,
198,
4480,
1280,
10786,
7890,
357,
17,
737,
40664,
41707,
81,
11537,
355,
277,
25,
201,
198,
220,
220,
220,
269,
21370,
796,
269,
... | 1.857759 | 464 |
import os
import test
import unittest
# if __name__ == '__main__':
# Datenmodultests
tests()
| [
11748,
28686,
201,
198,
11748,
1332,
201,
198,
11748,
555,
715,
395,
201,
198,
201,
198,
201,
198,
201,
198,
2,
611,
11593,
3672,
834,
6624,
705,
834,
12417,
834,
10354,
201,
198,
2,
16092,
268,
4666,
586,
3558,
201,
198,
41989,
341... | 2.333333 | 45 |
a=1
for i in range(5):
if 'FBI' in input():
print(i+1,end=' ')
a=0
if a: print('HE GOT AWAY!') | [
64,
28,
16,
198,
1640,
1312,
287,
2837,
7,
20,
2599,
198,
611,
705,
39379,
6,
287,
5128,
33529,
198,
220,
3601,
7,
72,
10,
16,
11,
437,
11639,
705,
8,
198,
220,
257,
28,
15,
198,
361,
257,
25,
3601,
10786,
13909,
41725,
14356,
... | 2.0625 | 48 |
import torch
from torch import nn
import torch.nn.functional as F
from ntm.controller import Controller
from ntm.memory import Memory
from ntm.head import ReadHead, WriteHead
| [
11748,
28034,
198,
6738,
28034,
1330,
299,
77,
198,
11748,
28034,
13,
20471,
13,
45124,
355,
376,
198,
6738,
299,
17209,
13,
36500,
1330,
22741,
198,
6738,
299,
17209,
13,
31673,
1330,
14059,
198,
6738,
299,
17209,
13,
2256,
1330,
4149,... | 3.826087 | 46 |
# Copyright 2014 Facebook, Inc.
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.
# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright 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 facebook_business.adobjects.abstractobject import AbstractObject
from facebook_business.adobjects.abstractcrudobject import AbstractCrudObject
from facebook_business.adobjects.objectparser import ObjectParser
from facebook_business.api import FacebookRequest
from facebook_business.typechecker import TypeChecker
"""
This class is auto-generated.
For any issues or feature requests related to this class, please let us know on
github and we'll fix in our codegen framework. We'll not be able to accept
pull request for this class.
"""
| [
2,
15069,
1946,
3203,
11,
3457,
13,
198,
198,
2,
921,
389,
29376,
7520,
257,
1729,
12,
41195,
11,
8688,
11,
29359,
12,
5787,
5964,
284,
198,
2,
779,
11,
4866,
11,
13096,
11,
290,
14983,
428,
3788,
287,
2723,
2438,
393,
13934,
198,... | 3.97 | 400 |
import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
standaloneTrackMonitor = DQMEDAnalyzer('StandaloneTrackMonitor',
moduleName = cms.untracked.string("StandaloneTrackMonitor"),
folderName = cms.untracked.string("highPurityTracks"),
vertexTag = cms.untracked.InputTag("selectedPrimaryVertices"),
puTag = cms.untracked.InputTag("addPileupInfo"),
clusterTag = cms.untracked.InputTag("siStripClusters"),
trackInputTag = cms.untracked.InputTag('selectedTracks'),
offlineBeamSpot = cms.untracked.InputTag('offlineBeamSpot'),
trackQuality = cms.untracked.string('highPurity'),
doPUCorrection = cms.untracked.bool(False),
isMC = cms.untracked.bool(True),
puScaleFactorFile = cms.untracked.string("PileupScaleFactor_run203002.root"),
haveAllHistograms = cms.untracked.bool(False),
verbose = cms.untracked.bool(False),
trackEtaH = cms.PSet(Xbins = cms.int32(60), Xmin = cms.double(-3.0),Xmax = cms.double(3.0)),
trackPtH = cms.PSet(Xbins = cms.int32(100),Xmin = cms.double(0.0),Xmax = cms.double(100.0))
)
| [
11748,
48849,
14055,
13,
36301,
7248,
13,
16934,
355,
269,
907,
198,
6738,
360,
48,
5653,
712,
1063,
13,
14055,
13,
35,
48,
30733,
37702,
9107,
1330,
360,
48,
30733,
37702,
9107,
198,
1481,
17749,
24802,
35479,
796,
360,
48,
30733,
37... | 2.239252 | 535 |
import unittest
import numpy.testing as nt
import numpy as np
from spatialmath.spatialvector import *
# ---------------------------------------------------------------------------------------#
if __name__ == '__main__':
unittest.main() | [
198,
11748,
555,
715,
395,
198,
11748,
299,
32152,
13,
33407,
355,
299,
83,
198,
11748,
299,
32152,
355,
45941,
198,
198,
6738,
21739,
11018,
13,
2777,
34961,
31364,
1330,
1635,
628,
198,
198,
2,
16529,
19351,
6329,
2,
198,
361,
11593... | 4.083333 | 60 |
# \s Returns a match where the string contains a white space character
# \S Returns a match where the string DOES NOT contain a white space character
import re
s1 = '''
---
slug: python-non-greedy-regexes
title: Python non-greedy regexes
summary: How to make Python regexes a little less greedy using the `?` modifier.
cat: Code
date_published: 2019-10-19
date_updated: 2019-10-19
---
# How to make Python regexes a little less greedy
There are these little things that once you learn about them you wonder how you ever did without them. The Python non-greedy modifier definitely falls into that category. I spent far t
Here was the problem:
```
---
title: This is some title
description: This is the description
---
Some content...
```
This is a simplified version of the metadata that each piece of content on the site has. What the code needs to do is extract the metadata and the content.
This seems straightforward. You might come up with:
```
---\s([\s\S]*)\s---\s([\s\S]*)
```
We can simplify that but getting rid of the extra new lines in our captured text by using the `.strip()` function in Python so you end up with:
```
---([\s\S]*)---([\s\S]*)
```
The metadata drops into the first `()` and the content into the second `()` and there are rainbows and unicorns and all is good in the world. Until this happens...
```
---
title: This is some title
description: This is the description
---
Some content...
Item | Description
--- | ---
A | A thing
B | Another thing
Some more content...
```
And now there are tears because it all goes horribly wrong. You see Python regexes are downright greedy. They try to match as much text as possible. Which means your regex now matches right down to the first `---` in the Markdown table. This is where you probably start trying all kinds of variations on your regex to restrict the match to only the metadata. But there's an easy little fix...
```
---([\s\S]*?)---([\s\S]*)
```
The secret is that addition of the `?` operator. Like many operators it has many functions but when it's next to `*` it means "don't be so darn greedy".
Here's the actual code where I use it:
``` python
def extract_parts(source):
m = re.search(r'---([\s\S]*?)---([\s\S]*)', source, re.MULTILINE)
metadata = m.group(1)
markdown = m.group(2)
return metadata.strip(), markdown.strip()
```
This little `?` turns out to be hellishly useful. For example:
``` html
<p>Para 1</p><p>Para 2></p>
```
If you only want the first para you could use `<p>.*?</p>`, and you'd only match the first para.
You can test this out with the following code:
``` python
import re
s = "<p>para 1</p><p>para 2</p>"
m = re.search(r'<p>.*</p>', s)
print(m.group(0))
m = re.search(r'<p>.*?</p>', s)
print(m.group(0))
```
Yes. Useful indeed. Once you know about the non-greedy operator you'll wonder how you ever did without it!
'''
# Greedy *? to for matched delimiters
print(extract(s1))
| [
2,
3467,
82,
16409,
257,
2872,
810,
262,
4731,
4909,
257,
2330,
2272,
2095,
198,
2,
3467,
50,
16409,
257,
2872,
810,
262,
4731,
38359,
5626,
3994,
257,
2330,
2272,
2095,
198,
198,
11748,
302,
198,
198,
82,
16,
796,
705,
7061,
198,
... | 3.187839 | 921 |
#coding=utf-8
# Copyright (C) 2016-2018 Alibaba Group Holding Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import os
import sys
import time
import math
import random
import argparse
import tensorflow as tf
import numpy
from model import *
from utils import *
import xdl
from xdl.python.training.train_session import QpsMetricsHook, MetricsPrinterHook
#config here
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--seed", help="random seed", default=3)
parser.add_argument("-jt", "--job_type", help="'train' or 'test'", default='train')
parser.add_argument("-m", "--model", help="'din' or 'dien'", default='din_mogujie')
parser.add_argument("-si", "--save_interval", help="checkpoint save interval steps", default=20000)
parser.add_argument("-dr", "--data_dir", help="data dir")
args, unknown = parser.parse_known_args()
seed = args.seed
job_type = args.job_type
model_type = args.model
save_interval = args.save_interval
train_file = os.path.join(get_data_prefix(), "train_data.tfrecords")
if __name__ == '__main__':
SEED = seed
if SEED is None:
SEED = 3
tf.set_random_seed(SEED)
numpy.random.seed(SEED)
random.seed(SEED)
if job_type == 'train':
train()
elif job_type == 'test':
test()
else:
print('job type must be train or test, do nothing...')
| [
2,
66,
7656,
28,
40477,
12,
23,
198,
2,
15069,
357,
34,
8,
1584,
12,
7908,
41992,
4912,
31703,
15302,
198,
2,
220,
198,
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
198,
2,
345,
743,
40... | 3.055468 | 631 |
__version__ = "0.1.0"
__author__ = "Kaoru Nishikawa"
| [
834,
9641,
834,
796,
366,
15,
13,
16,
13,
15,
1,
198,
834,
9800,
834,
796,
366,
37281,
27786,
48438,
40398,
1,
198
] | 2.304348 | 23 |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 21 18:51:11 2016
@author: brady
"""
#################### TRAINING ####################
# POS DIRS
TRAIN_CLEAN = r'C:\Users\brady\GitHub\MinVAD\data\train\positive\clean'
TRAIN_0DB = r'C:\Users\brady\GitHub\MinVAD\data\train\positive\0db'
TRAIN_5DB = r'C:\Users\brady\GitHub\MinVAD\data\train\positive\5db'
TRAIN_10DB = r'C:\Users\brady\GitHub\MinVAD\data\train\positive\10db'
TRAIN_15DB = r'C:\Users\brady\GitHub\MinVAD\data\train\positive\15db'
TRAIN_ALLDB = r'C:\Users\brady\GitHub\MinVAD\data\train\positive\all_data'
TRAIN_AN4 = r'C:\Users\brady\GitHub\MinVAD\data\train\positive\an4_clstk'
TRAIN_MSAK = r'C:\Users\brady\GitHub\MinVAD\data\train\positive\msak0'
TRAIN_FSEW = r'C:\Users\brady\GitHub\MinVAD\data\train\positive\fsew0'
# NEG DIRS
TRAIN_KITCHEN = r'C:\Users\brady\GitHub\MinVAD\data\train\negative\building_106_kitchen\training_segments'
TRAIN_URBAN = r'C:\Users\brady\GitHub\MinVAD\data\train\negative\UrbanSound\data'
# Label Helpers
TRAIN_LABELS = r'C:\Users\brady\GitHub\MinVAD\data\train\positive\clean'
POS_DIRS = [TRAIN_ALLDB, TRAIN_MSAK, TRAIN_FSEW]
NEG_DIRS = [TRAIN_KITCHEN, TRAIN_URBAN]
#################### TESTING ####################
TEST_0DB = r'C:\Users\brady\GitHub\MinVAD\data\test\positive\0db'
TEST_5DB = r'C:\Users\brady\GitHub\MinVAD\data\test\positive\5db'
TEST_10DB = r'C:\Users\brady\GitHub\MinVAD\data\test\positive\10db'
TEST_15DB = r'C:\Users\brady\GitHub\MinVAD\data\test\positive\15db'
TEST_DIRS = [TEST_0DB, TEST_5DB, TEST_10DB, TEST_15DB] | [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
37811,
198,
41972,
319,
2892,
5267,
2310,
1248,
25,
4349,
25,
1157,
1584,
198,
198,
31,
9800,
25,
865,
4597,
198,
37811,
198,
14468,
4242,
29125,
1268,
2751,
1303,
14468... | 2.147632 | 718 |
#!/usr/bin/env python
# Copyright (C) 2017 Udacity Inc.
#
# This file is part of Robotic Arm: Pick and Place project for Udacity
# Robotics nano-degree program
#
# All Rights Reserved.
# Author: Harsh Pandya
# import modules
import rospy
import tf
from kuka_arm.srv import *
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
from geometry_msgs.msg import Pose
from mpmath import *
from sympy import *
import numpy
Kuka = KukaR210()
if __name__ == "__main__":
IK_server()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
198,
2,
15069,
357,
34,
8,
2177,
35774,
4355,
3457,
13,
198,
2,
198,
2,
770,
2393,
318,
636,
286,
3851,
6210,
7057,
25,
12346,
290,
8474,
1628,
329,
35774,
4355,
198,
2,
47061,
387... | 3.005988 | 167 |
import os
import csv
import glob
import time
import threading
from .misc import name2env as ru_name2env
from .misc import get_hostname as ru_get_hostname
from .misc import get_hostip as ru_get_hostip
from .read_json import read_json as ru_read_json
# ------------------------------------------------------------------------------
#
# ------------------------------------------------------------------------------
#
# ------------------------------------------------------------------------------
#
def flush(self):
if not self._enabled:
return
if self._enabled:
# see https://docs.python.org/2/library/stdtypes.html#file.flush
self.prof("flush")
self._handle.flush()
os.fsync(self._handle.fileno())
# ------------------------------------------------------------------------------
#
# --------------------------------------------------------------------------
#
def _timestamp_init(self):
"""
return a tuple of [system time, absolute time]
"""
# retrieve absolute timestamp from an external source
#
# We first try to contact a network time service for a timestamp, if that
# fails we use the current system time.
try:
import ntplib
ntphost = os.environ.get('RADICAL_UTILS_NTPHOST', '0.pool.ntp.org')
t_one = time.time()
response = ntplib.NTPClient().request(ntphost, timeout=1)
t_two = time.time()
ts_ntp = response.tx_time
ts_sys = (t_one + t_two) / 2.0
return [ts_sys, ts_ntp, 'ntp']
except Exception:
pass
# on any errors, we fall back to system time
t = time.time()
return [t,t, 'sys']
# --------------------------------------------------------------------------
#
# --------------------------------------------------------------------------
#
# ------------------------------------------------------------------------------
#
def read_profiles(profiles):
"""
We read all profiles as CSV files and convert them into lists of dicts.
"""
ret = dict()
for prof in profiles:
rows = list()
with open(prof, 'r') as csvfile:
reader = csv.DictReader(csvfile, fieldnames=Profiler.fields)
for row in reader:
if row['time'].startswith('#'):
# skip header
continue
row['time'] = float(row['time'])
rows.append(row)
ret[prof] = rows
return ret
# ------------------------------------------------------------------------------
#
def combine_profiles(profs):
"""
We merge all profiles and sort by time.
This routine expects all profiles to have a synchronization time stamp.
Two kinds of sync timestamps are supported: absolute (`sync abs`) and
relative (`sync rel`).
Time syncing is done based on 'sync abs' timestamps. We expect one such
absolute timestamp to be available per host (the first profile entry will
contain host information). All timestamps from the same host will be
corrected by the respectively determined NTP offset.
"""
pd_rel = dict() # profiles which have relative time refs
t_host = dict() # time offset per host
p_glob = list() # global profile
t_min = None # absolute starting point of profiled session
c_end = 0 # counter for profile closing tag
# first get all absolute timestamp sync from the profiles, for all hosts
for pname, prof in profs.iteritems():
if not len(prof):
print 'empty profile %s' % pname
continue
if not prof[0]['msg'] or ':' not in prof[0]['msg']:
print 'unsynced profile %s' % pname
continue
t_prof = prof[0]['time']
host, ip, t_sys, t_ntp, t_mode = prof[0]['msg'].split(':')
host_id = '%s:%s' % (host, ip)
if t_min: t_min = min(t_min, t_prof)
else : t_min = t_prof
if t_mode != 'sys':
continue
# determine the correction for the given host
t_sys = float(t_sys)
t_ntp = float(t_ntp)
t_off = t_sys - t_ntp
if host_id in t_host and t_host[host_id] != t_off:
print 'conflicting time sync for %s (%s)' % (pname, host_id)
continue
t_host[host_id] = t_off
# now that we can align clocks for all hosts, apply that correction to all
# profiles
for pname, prof in profs.iteritems():
if not len(prof):
continue
if not prof[0]['msg']:
continue
host, ip, _, _, _ = prof[0]['msg'].split(':')
host_id = '%s:%s' % (host, ip)
if host_id in t_host:
t_off = t_host[host_id]
else:
print 'WARNING: no time offset for %s' % host_id
t_off = 0.0
t_0 = prof[0]['time']
t_0 -= t_min
# correct profile timestamps
for row in prof:
t_orig = row['time']
row['time'] -= t_min
row['time'] -= t_off
# count closing entries
if row['event'] == 'END':
c_end += 1
# add profile to global one
p_glob += prof
# # Check for proper closure of profiling files
# if c_end == 0:
# print 'WARNING: profile "%s" not correctly closed.' % prof
# if c_end > 1:
# print 'WARNING: profile "%s" closed %d times.' % (prof, c_end)
# sort by time and return
p_glob = sorted(p_glob[:], key=lambda k: k['time'])
return p_glob
# ------------------------------------------------------------------------------
#
def clean_profile(profile, sid, state_final, state_canceled):
"""
This method will prepare a profile for consumption in radical.analytics. It
performs the following actions:
- makes sure all events have a `ename` entry
- remove all state transitions to `CANCELLED` if a different final state
is encountered for the same uid
- assignes the session uid to all events without uid
- makes sure that state transitions have an `ename` set to `state`
"""
entities = dict() # things which have a uid
if not isinstance(state_final, list):
state_final = [state_final]
for event in profile:
uid = event['uid' ]
state = event['state']
time = event['time' ]
name = event['event']
# we derive entity_type from the uid -- but funnel
# some cases into the session
if uid:
event['entity_type'] = uid.split('.',1)[0]
else:
event['entity_type'] = 'session'
event['uid'] = sid
uid = sid
if uid not in entities:
entities[uid] = dict()
entities[uid]['states'] = dict()
entities[uid]['events'] = list()
if name == 'advance':
# this is a state progression
assert(state)
assert(uid)
event['event_name'] = 'state'
if state in state_final and state != state_canceled:
# a final state other than CANCELED will cancel any previous
# CANCELED state.
if state_canceled in entities[uid]['states']:
del(entities[uid]['states'][state_canceled])
if state in entities[uid]['states']:
# ignore duplicated recordings of state transitions
# FIXME: warning?
continue
# raise ValueError('double state (%s) for %s' % (state, uid))
entities[uid]['states'][state] = event
else:
# FIXME: define different event types (we have that somewhere)
event['event_name'] = 'event'
entities[uid]['events'].append(event)
# we have evaluated, cleaned and sorted all events -- now we recreate
# a clean profile out of them
ret = list()
for uid,entity in entities.iteritems():
ret += entity['events']
for state,event in entity['states'].iteritems():
ret.append(event)
# sort by time and return
ret = sorted(ret[:], key=lambda k: k['time'])
return ret
# ------------------------------------------------------------------------------
| [
198,
11748,
28686,
198,
11748,
269,
21370,
198,
11748,
15095,
198,
11748,
640,
198,
11748,
4704,
278,
198,
198,
6738,
220,
220,
764,
44374,
220,
220,
220,
220,
220,
1330,
1438,
17,
24330,
220,
220,
220,
220,
355,
7422,
62,
3672,
17,
... | 2.427756 | 3,502 |
import numpy as np
import torch
from torch.utils.data import Dataset
| [
11748,
299,
32152,
355,
45941,
198,
198,
11748,
28034,
198,
6738,
28034,
13,
26791,
13,
7890,
1330,
16092,
292,
316,
628
] | 3.380952 | 21 |
peso1 = float(input('Digite o peso do primeiro animal... '))
peso2 = float(input('Digite o peso do segundo animal... '))
if peso1 > peso2:
print('O primeiro animal mais pesado')
elif peso1 < peso2:
print('O segundo animal mais pesado')
else:
print('Os dois animais tm o mesmo peso')
| [
12272,
78,
16,
796,
12178,
7,
15414,
10786,
19511,
578,
267,
32317,
78,
466,
6994,
7058,
5044,
986,
705,
4008,
198,
12272,
78,
17,
796,
12178,
7,
15414,
10786,
19511,
578,
267,
32317,
78,
466,
384,
70,
41204,
5044,
986,
705,
4008,
1... | 2.483333 | 120 |
# uniform_distribution
# used to describe the probability where every event has equal chances of
# occuring
"""
E.g. Generation of random numbers.
It has three parameters.
a - lower bound - default 0.0
b - upper bound - default 1.0
size = The shape of the returned array
"""
# 2x3 uniform distribution sample
from numpy import random
x = random.uniform(size = (2, 3))
print(x)
# visulization of uniform distribution
# from numpy import random
import matplotlib.pyplot as plt
import seaborn as sns
sns.distplot(random.uniform(size = 1000), hist = False)
plt.show()
| [
2,
8187,
62,
17080,
3890,
201,
198,
201,
198,
2,
973,
284,
6901,
262,
12867,
810,
790,
1785,
468,
4961,
8395,
286,
220,
201,
198,
2,
1609,
870,
201,
198,
201,
198,
37811,
201,
198,
36,
13,
70,
13,
16588,
286,
4738,
3146,
13,
201... | 2.890476 | 210 |
from tornado.process import Subprocess
from tornado import gen
from subprocess import PIPE
from delivery.models.execution import ExecutionResult, Execution
| [
198,
198,
6738,
33718,
13,
14681,
1330,
3834,
14681,
198,
6738,
33718,
1330,
2429,
198,
198,
6738,
850,
14681,
1330,
350,
4061,
36,
198,
198,
6738,
7585,
13,
27530,
13,
18558,
1009,
1330,
37497,
23004,
11,
37497,
628,
198
] | 4.153846 | 39 |
"""
Datos de entrada
nota_examen_ matematicas-->nem-->float
nota_ta1_matematicas-->ntm-->
nota_ta2_matematicas-->nttm-->
nota_ta3_matematicas-->ntttm-->
nota_examen_fisica-->nef-->float
nota_ta1_fisica-->ntf-->float
nota_ta2_fisica-->nttf-->float
nota_examen_quimica-->neq-->float
nota_ta1_quimica-->ntq-->float
nota_ta2_quimica-->nttq-->float
nota_ta3_quimica-->ntttq-->float
Datos de salida
Promedio_tres-->pt-->float
promedio_matematicas-->pm-->float
promedio_fisica-->pf-->float
promedio_quimica-->pq-->float
"""
#Entradas
nem=float(input("Ingrese la nota del examen de matemticas: "))
ntm=float(input("Ingrese la nota de la 1ra tarea de matemticas: "))
nttm=float(input("Ingrese la nota de la 2da tarea de matemticas: "))
ntttm=float(input("Ingrese la nota de la 3ra tarea de matemticas: "))
nef=float(input("Ingrese la nota del examen de fsica: "))
ntf=float(input("Ingrese la nota de la 1ra tarea de fsica: "))
nttf=float(input("Ingrese la nota de la 2da tarea de fsica: "))
neq=float(input("Ingrese la nota del examen de qumica: "))
ntq=float(input("Ingrese la nota de la 1ra tarea de qumica: "))
nttq=float(input("Ingrese la nota de la 2da tarea de qumica: "))
ntttq=float(input("Ingrese la nota de la 3ra tarea de qumica: "))
#Caja negra
pm=(nem*0.90)+(((ntm+nttm+ntttm)/3)*0.1)
pf=(nef*0.8)+(((ntf+nttf)/2)*0.2)
pq=(neq*0.85)+(((ntq+nttq+ntttq)/3)*0.15)
pt=(pm+pf+pq)/3
#Salidas
print("El promedio de las tres materias es: ", pt)
print("El promedio de matemticas es: ", pm)
print("El promedio de fsica es: ", pf)
print("El promedio de qumica es: ", pq) | [
37811,
198,
27354,
418,
390,
24481,
4763,
198,
1662,
64,
62,
1069,
41763,
62,
2603,
368,
1512,
292,
46904,
77,
368,
46904,
22468,
198,
1662,
64,
62,
8326,
16,
62,
6759,
368,
1512,
292,
46904,
429,
76,
46904,
198,
1662,
64,
62,
8326,... | 2.217021 | 705 |
import os
import numpy as np
from collections import namedtuple
from .chemparser import chemparse
from .xray import mu_elam, atomic_mass
from .utils import get_homedir
_materials = None
Material = namedtuple('Material', ('formula', 'density', 'name', 'categories'))
def get_user_materialsfile():
"""return name for user-specific materials.dat file
With $HOME being the users home directory, this will be
$HOME/.config/xraydb/materials.dat
"""
return os.path.join(get_homedir(), '.config', 'xraydb', 'materials.dat')
def _read_materials_db():
"""return _materials dictionary, creating it if needed"""
global _materials
if _materials is None:
# initialize materials table
_materials = {}
# first, read from standard list
local_dir, _ = os.path.split(__file__)
fname = os.path.join(local_dir, 'materials.dat')
if os.path.exists(fname):
read_materialsfile(fname)
# next, read from users materials file
fname = get_user_materialsfile()
if os.path.exists(fname):
read_materialsfile(fname)
return _materials
def material_mu(name, energy, density=None, kind='total'):
"""X-ray attenuation length (in 1/cm) for a material by name or formula
Args:
name (str): chemical formul or name of material from materials list.
energy (float or ndarray): energy or array of energies in eV
density (None or float): material density (gr/cm^3).
kind (str): 'photo' or 'total' for whether to return the
photo-absorption or total cross-section ['total']
Returns:
absorption length in 1/cm
Notes:
1. material names are not case sensitive,
chemical compounds are case sensitive.
2. mu_elam() is used for mu calculation.
3. if density is None and material is known, that density will be used.
Examples:
>>> material_mu('H2O', 10000.0)
5.32986401658495
"""
global _materials
if _materials is None:
_materials = _read_materials_db()
formula = None
_density = None
mater = _materials.get(name.lower(), None)
if mater is None:
for key, val in _materials.items():
if name.lower() == val[0].lower(): # match formula
mater = val
break
# default to using passed in name as a formula
if formula is None:
if mater is None:
formula = name
else:
formula = mater.formula
if density is None and mater is not None:
density = mater.density
if density is None:
raise Warning('material_mu(): must give density for unknown materials')
mass_tot, mu = 0.0, 0.0
for elem, frac in chemparse(formula).items():
mass = frac * atomic_mass(elem)
mu += mass * mu_elam(elem, energy, kind=kind)
mass_tot += mass
return density*mu/mass_tot
def material_mu_components(name, energy, density=None, kind='total'):
"""material_mu_components: absorption coefficient (in 1/cm) for a compound
Args:
name (str): chemical formul or name of material from materials list.
energy (float or ndarray): energy or array of energies in eV
density (None or float): material density (gr/cm^3).
kind (str): 'photo' or 'total'for whether to
return photo-absorption or total cross-section ['total']
Returns:
dict for constructing mu per element,
with elements 'mass' (total mass), 'density', and
'elements' (list of atomic symbols for elements in material).
For each element, there will be an item (atomic symbol as key)
with tuple of (stoichiometric fraction, atomic mass, mu)
Examples:
>>> xraydb.material_mu('quartz', 10000)
50.36774553547068
>>> xraydb.material_mu_components('quartz', 10000)
{'mass': 60.0843, 'density': 2.65, 'elements': ['Si', 'O'],
'Si': (1, 28.0855, 33.87943243018506), 'O': (2.0, 15.9994, 5.952824815297084)}
"""
global _materials
if _materials is None:
_materials = _read_materials_db()
mater = _materials.get(name.lower(), None)
if mater is None:
formula = name
if density is None:
raise Warning('material_mu(): must give density for unknown materials')
else:
formula = mater.formula
density = mater.density
out = {'mass': 0.0, 'density': density, 'elements':[]}
for atom, frac in chemparse(formula).items():
mass = atomic_mass(atom)
mu = mu_elam(atom, energy, kind=kind)
out['mass'] += frac*mass
out[atom] = (frac, mass, mu)
out['elements'].append(atom)
return out
def get_material(name):
"""look up material name, return formula and density
Args:
name (str): name of material or chemical formula
Returns:
chemical formula, density of material
Examples:
>>> xraydb.get_material('kapton')
('C22H10N2O5', 1.43)
See Also:
find_material()
"""
material = find_material(name)
if material is None:
return None
return material.formula, material.density
def find_material(name):
"""look up material name, return material instance
Args:
name (str): name of material or chemical formula
Returns:
material instance
Examples:
>>> xraydb.find_material('kapton')
Material(formula='C22H10N2O5', density=1.42, name='kapton', categories=['polymer'])
See Also:
get_material()
"""
global _materials
if _materials is None:
_materials = _read_materials_db()
mat = _materials.get(name.lower(), None)
if mat is not None:
return mat
for mat in _materials.values():
if mat.formula == name:
return mat
return None
def get_materials(force_read=False, categories=None):
"""get dictionary of all available materials
Args:
force_read (bool): whether to force a re-reading of the
materials database [False]
categories (list of strings or None): restrict results
to those that match category names
Returns:
dict with keys of material name and values of Materials instances
Examples:
>>> for name, m in xraydb.get_materials().items():
... print(name, m)
...
water H2O 1.0
lead Pb 11.34
aluminum Al 2.7
kapton C22H10N2O5 1.42
polyimide C22H10N2O5 1.42
nitrogen N 0.00125
argon Ar 0.001784
...
"""
global _materials
if force_read or _materials is None:
_materials = _read_materials_db()
return _materials
def add_material(name, formula, density, categories=None):
"""add a material to the users local material database
Args:
name (str): name of material
formula (str): chemical formula
density (float): density
categories (list of strings or None): list of category names
Returns:
None
Notes:
the data will be saved to $HOME/.config/xraydb/materials.dat
in the users home directory, and will be useful in subsequent sessions.
Examples:
>>> xraydb.add_material('becopper', 'Cu0.98e0.02', 8.3, categories=['metal'])
"""
global _materials
if _materials is None:
_materials = _read_materials_db()
formula = formula.replace(' ', '')
if categories is None:
categories = []
_materials[name.lower()] = Material(formula, float(density), name, categories)
fname = get_user_materialsfile()
if os.path.exists(fname):
fh = open(fname, 'r')
text = fh.readlines()
fh.close()
else:
parent, _ = os.path.split(fname)
if not os.path.exists(parent):
try:
os.makedirs(parent)
except FileExistsError:
pass
text = ['# user-specific database of materials\n',
'# name | density | categories | formulan']
catstring = ', '.join(categories)
text.append(" %s | %g | %s | %s\n" % (name, density, catstring, formula))
with open(fname, 'w') as fh:
fh.write(''.join(text))
| [
11748,
28686,
198,
11748,
299,
32152,
355,
45941,
198,
6738,
17268,
1330,
3706,
83,
29291,
198,
6738,
764,
2395,
3149,
28198,
1330,
4607,
29572,
198,
6738,
764,
87,
2433,
1330,
38779,
62,
417,
321,
11,
17226,
62,
22208,
198,
6738,
764,
... | 2.413584 | 3,460 |
#!/usr/bin/env python3
'''
Server script for simple client/server example
Copyright (C) Simon D. Levy 2021
MIT License
'''
from threading import Thread
from time import sleep
import socket
from struct import unpack
from header import ADDR, PORT
def comms(data):
'''
Communications thread
'''
# Connect to the client
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ADDR, PORT))
# Loop until main thread quits
while True:
# Receive and unpack three floating-point numbers
data[0], data[1], data[2] = unpack('=fff', sock.recv(12))
# Yield to the main thread
sleep(0.001)
main()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
7061,
6,
198,
10697,
4226,
329,
2829,
5456,
14,
15388,
1672,
198,
198,
15269,
357,
34,
8,
11288,
360,
13,
32036,
33448,
198,
198,
36393,
13789,
198,
7061,
6,
198,
6738,
4704,
278... | 2.706827 | 249 |
# -*- coding: utf8 -*-
from django.shortcuts import render
# Create your views here.
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
23,
532,
9,
12,
220,
198,
198,
6738,
42625,
14208,
13,
19509,
23779,
1330,
8543,
628,
198,
2,
13610,
534,
5009,
994,
13,
628
] | 2.8125 | 32 |
import numpy as np
from numpy.polynomial import legendre
from smuthi import spherical_functions as sf
import bessel_functions as bf
##Codebase for computing the T-matrix and its derivative with respect to height and radius for a cylindrical scatterer
# with circular cross-section in spherical coordinates.
#
# inputs:
# lmax: maximum orbital angular momentum expansion order, an integer
# Ntheta: number of sections for discretization
# geometric_params: radius (0) and height (1) in an array
# n0: refractive index of medium
# ns: refractive index of scatterer
# wavelength: excitation wavelength
# particle_type: shape of particle (cylinder, ellipsoid, etc)
#function that computes the J surface integrals and their derivatives with respect to cylinder radius (a) and cylinder
# height (h). Expands up to a specified lmax, and approximates the integrals using gaussian quadrature with Ntheta
# points for the two integrals required.
# n0 is refractive index of medium
# ns is refractive index of scatterer
# wavelength is illumination wavelength
# nu = 1 or 3
# 1: b_li are the spherical Bessel functions of the first kind (j_n(x))
# involved in rQ and drQ computation
# 3: b_li are the spherical Hankel functions of the first kind (h_n(x))
# involved in Q and dQ computation
#care should be taken to expand lmax to sufficient order,
#where lmax should be greater than (ns-n_0)*max(2*a,h)/wavelength
#compute n index (single index) for matrix element given its p (polarization), l (orbital angular momementum index),
# and m (azimuthal angular momentum index.
#selection rules taking into account different symmetries for an axisymmetric particle
if __name__ == '__main__':
import matplotlib.pyplot as plt
cyl_params = np.array([500,860])
[J11, J12, J21, J22, dJ11, dJ12, dJ21, dJ22] = compute_J_cyl(3,30,200,460,1,1.52,1000,3)
[T, dT] = compute_T(6,30,cyl_params,1,4,1000,'cylinder')
img1 = plt.imshow(np.abs(T))
plt.colorbar()
plt.title('T')
plt.show()
| [
11748,
299,
32152,
355,
45941,
198,
6738,
299,
32152,
13,
35428,
26601,
498,
1330,
8177,
260,
198,
6738,
895,
1071,
72,
1330,
43180,
62,
12543,
2733,
355,
264,
69,
198,
11748,
7284,
741,
62,
12543,
2733,
355,
275,
69,
198,
198,
2235,
... | 3.014728 | 679 |
# -*- coding: utf8 -*-
from __future__ import division, absolute_import, print_function
import os
import sys
import datetime as dt
import dvik_print as dvp
if __name__ == '__main__':
print(sys.version)
O = {
'lista': ['el1', 'el2', 1, 2, 3, 4, None, False],
'zbir': {1, 2, 1, 2, 'a', 'a', 'b', 'b'},
'krotka': ('oto', 'elementy', 'naszej', 'krotki'),
('krotka', 'klucz'): {
'klucz1': ['jaka', 'lista', 123],
'klucz2': dt.datetime.now(),
'klucz3': dt
},
(123, 'asd'): {123, 234, 345},
(123, 'asd1'): (123, 234, 345)
}
# deklarujemy obiekt dvp.PrettyPrint
pp = dvp.PrettyPrint(tab=2, head=3, tail=2, max_str_len=50, show_line=True, filename=__file__)
# obiekt jest wywoywalny
# w ten sposb wypisze na
# standardowe wyjcie obiekt O
pp(O, var='zmienna')
# mona uy wartoci domylnych
pp_domyslny = dvp.PrettyPrint()
pp_domyslny(O)
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
23,
532,
9,
12,
198,
6738,
11593,
37443,
834,
1330,
7297,
11,
4112,
62,
11748,
11,
3601,
62,
8818,
198,
198,
11748,
28686,
198,
11748,
25064,
198,
11748,
4818,
8079,
355,
288,
83,
198,
198,
1174... | 1.947896 | 499 |
"""Authors: Cody Baker and Ben Dichter."""
from abc import ABC
from pathlib import Path
import spikeextractors as se
import numpy as np
from pynwb import NWBFile, NWBHDF5IO
from pynwb.ecephys import SpikeEventSeries
from jsonschema import validate
from ...basedatainterface import BaseDataInterface
from ...utils.json_schema import (
get_schema_from_hdmf_class,
get_base_schema,
get_schema_from_method_signature,
fill_defaults,
)
from ...utils.common_writer_tools import default_export_ops, default_export_ops_schema
from ...utils import export_ecephys_to_nwb
from .baserecordingextractorinterface import BaseRecordingExtractorInterface, map_si_object_to_writer, OptionalPathType
| [
37811,
30515,
669,
25,
27035,
14372,
290,
3932,
360,
488,
353,
526,
15931,
198,
6738,
450,
66,
1330,
9738,
198,
6738,
3108,
8019,
1330,
10644,
198,
11748,
20240,
2302,
974,
669,
355,
384,
198,
11748,
299,
32152,
355,
45941,
198,
6738,
... | 3.084071 | 226 |
"""The libfuzzertest.TestCase for C++ libfuzzer tests."""
import datetime
import os
from buildscripts.resmokelib import core
from buildscripts.resmokelib import utils
from buildscripts.resmokelib.testing.fixtures import interface as fixture_interface
from buildscripts.resmokelib.testing.testcases import interface
| [
37811,
464,
9195,
69,
4715,
861,
395,
13,
14402,
20448,
329,
327,
4880,
9195,
69,
4715,
263,
5254,
526,
15931,
198,
198,
11748,
4818,
8079,
198,
11748,
28686,
198,
198,
6738,
1382,
46521,
13,
411,
76,
2088,
8019,
1330,
4755,
198,
6738... | 3.573034 | 89 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020 Ryan L. Collins <rlcollins@g.harvard.edu>
# and the Talkowski Laboratory
# Distributed under terms of the MIT license.
"""
Parse simple SEA super-enhancer BED by cell types
"""
import argparse
import csv
import subprocess
def main():
"""
Main block
"""
# Parse command line arguments and options
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('bed', help='Path to BED4 of super enhancers')
parser.add_argument('outdir', help='Output directory')
args = parser.parse_args()
outfiles = {}
with open(args.bed) as fin:
for chrom, start, end, source in csv.reader(fin, delimiter='\t'):
source = source.replace(' ', '_').replace('(', '').replace(')', '')
if source not in outfiles.keys():
outfiles[source] = open('{}/SEA.{}.bed'.format(args.outdir, source), 'w')
outfiles[source].write('\t'.join([chrom, start, end]) + '\n')
for outfile in outfiles.values():
outpath = outfile.name
outfile.close()
subprocess.run(['bgzip', '-f', outpath])
if __name__ == '__main__':
main()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
198,
2,
15069,
357,
66,
8,
12131,
6047,
406,
13,
14006,
1279,
45895,
26000,
1040,
31,
70,
13,
9869,
10187,
13,
1... | 2.525692 | 506 |
"""
python>3
"""
import os.path
import re
from pathlib import Path
VERSION = 7
BASE = r"""
set cut_paste_input [stack 0]
version 12.2 v5
push $cut_paste_input
Group {
name imageCropDivide
tile_color 0x5c3d84ff
note_font_size 25
note_font_color 0xffffffff
selected true
xpos 411
ypos -125
addUserKnob {20 User}
addUserKnob {3 width_max}
addUserKnob {3 height_max -STARTLINE}
addUserKnob {3 width_source}
addUserKnob {3 height_source -STARTLINE}
addUserKnob {26 "" +STARTLINE}
addUserKnob {22 icd_script l "Copy Setup to ClipBoard" T "$SCRIPT$" +STARTLINE}
addUserKnob {26 info l " " T "press ctrl+v in the nodegraph after clicking the above button"}
addUserKnob {20 Info}
addUserKnob {26 infotext l "" +STARTLINE T "2022 - Liam Collod<br> Visit <a style=\"color:#fefefe;\" href=\"https://github.com/MrLixm/Foundry_Nuke/tree/main/src/transforms/imageCropDivide\">the GitHub repo</a> "}
addUserKnob {26 "" +STARTLINE}
addUserKnob {26 versiontext l "" T "version $VERSION$"}
}
Input {
inputs 0
name Input1
xpos 0
}
Output {
name Output1
xpos 0
ypos 300
}
end_group
"""
MODULE_BUTTON_PATH = Path("..") / "button.py"
NODENK_PATH = Path("..") / "node.nk"
if __name__ == '__main__':
# print(__file__)
run()
| [
37811,
198,
29412,
29,
18,
198,
37811,
198,
11748,
28686,
13,
6978,
198,
11748,
302,
198,
6738,
3108,
8019,
1330,
10644,
198,
198,
43717,
796,
767,
198,
198,
33,
11159,
796,
374,
37811,
198,
2617,
2005,
62,
34274,
62,
15414,
685,
2555... | 2.602083 | 480 |
#!/usr/bin/env python3
import pytest
import os
import pandas as pd
from io import StringIO
import experiment_qc
test_output_path = os.path.dirname(os.path.abspath(__file__)) + \
'/../output/experimentQC/'
DESIGN_STRING = """sample_id\texperiment_id\tbiosample\tfactor\ttreatment\treplicate\tcontrol_id\tbam_reads
A_1\tA\tLiver\tH3K27ac\tNone\t1\tB_1\tA_1.bam
A_2\tA\tLiver\tH3K27ac\tNone\t2\tB_2\tA_2.bam
B_1\tB\tLiver\tInput\tNone\t1\tB_1\tB_1.bam
B_2\tB\tLiver\tInput\tNone\t2\tB_2\tB_2.bam
"""
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
198,
11748,
12972,
9288,
198,
11748,
28686,
198,
11748,
19798,
292,
355,
279,
67,
198,
6738,
33245,
1330,
10903,
9399,
198,
11748,
6306,
62,
80,
66,
198,
198,
9288,
62,
22915,
62,
... | 1.858657 | 283 |
from channels.routing import route
from .consumers import ws_message, ws_connect, ws_disconnect
# TODO: Edit this to make proper use of channels.routing.route() or not
channel_routing = {
# route("websocket.receive", ws_message, path=r"^/chat/"),
"websocket.connect": ws_connect,
"websocket.receive": ws_message,
"websocket.disconnect": ws_disconnect,
}
| [
6738,
9619,
13,
81,
13660,
1330,
6339,
201,
198,
6738,
764,
5936,
31260,
1330,
266,
82,
62,
20500,
11,
266,
82,
62,
8443,
11,
266,
82,
62,
6381,
8443,
201,
198,
201,
198,
2,
16926,
46,
25,
5312,
428,
284,
787,
1774,
779,
286,
96... | 2.594406 | 143 |
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import copy
import datetime
import os
import posixpath
import subprocess
import sys
import unittest
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
BUILD_TOOLS_DIR = os.path.dirname(SCRIPT_DIR)
sys.path.append(BUILD_TOOLS_DIR)
import generate_make
BASIC_DESC = {
'TOOLS': ['newlib', 'glibc'],
'TARGETS': [
{
'NAME' : 'hello_world',
'TYPE' : 'main',
'SOURCES' : ['hello_world.c'],
},
],
'DEST' : 'examples'
}
# TODO(noelallen): Add test which generates a real make and runs it.
def main():
suite = unittest.defaultTestLoader.loadTestsFromModule(sys.modules[__name__])
result = unittest.TextTestRunner(verbosity=2).run(suite)
return int(not result.wasSuccessful())
if __name__ == '__main__':
sys.exit(main())
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
15069,
357,
66,
8,
2321,
383,
18255,
1505,
46665,
13,
1439,
2489,
10395,
13,
198,
2,
5765,
286,
428,
2723,
2438,
318,
21825,
416,
257,
347,
10305,
12,
7635,
5964,
326,
460,
307,
... | 2.588076 | 369 |
from PhotoHunt import PhotoHunt
# Todo: URL12
url_list = [
"https://www.saizeriya.co.jp/entertainment/images/1710/body.png",
"https://www.saizeriya.co.jp/entertainment/images/1801/body.png",
"https://www.saizeriya.co.jp/entertainment/images/1804/body.png",
"https://www.saizeriya.co.jp/entertainment/images/1806/body.png",
"https://www.saizeriya.co.jp/entertainment/images/1810/body.png",
"https://www.saizeriya.co.jp/entertainment/images/1812/body.png",
"https://www.saizeriya.co.jp/entertainment/images/1904/body.png",
"https://www.saizeriya.co.jp/entertainment/images/1907/body.png",
"https://www.saizeriya.co.jp/entertainment/images/1910/body.png",
"https://www.saizeriya.co.jp/entertainment/images/1912/body.png",
"https://www.saizeriya.co.jp/entertainment/images/2003/body.png",
"https://www.saizeriya.co.jp/entertainment/images/2007/body.png",
"https://www.saizeriya.co.jp/entertainment/images/2009/body.png"
]
for url in url_list:
photo_hunt = PhotoHunt(url)
photo_hunt.execute()
| [
6738,
5555,
47663,
1330,
5555,
47663,
198,
198,
2,
309,
24313,
25,
10289,
1065,
198,
6371,
62,
4868,
796,
685,
198,
220,
220,
220,
366,
5450,
1378,
2503,
13,
11400,
7509,
21008,
13,
1073,
13,
34523,
14,
298,
1425,
434,
14,
17566,
14... | 2.375566 | 442 |
a = b = c = 0
while True:
flag = ''
i = -1
s = ''
while i < 0:
i = int(input('idade:\t'))
while s != 'M' and s != 'F':
s = str(input('Sexo [M] [F]:\t')).strip().upper()[0]
if i > 18:
a += 1
if s == 'M':
b += 1
elif i < 20:
c += 1
while flag != 'S' and flag != 'N':
flag = str(input('Voc quer cadastrar mais pessoas? [S] [N]\t')).strip().upper()[0]
if flag == 'N':
break
print(f'Tem {a} pessoas maior de 18 anos!\nTem {b} homens!\nTem {c} mulheres com menos de 20 anos!')
| [
64,
796,
275,
796,
269,
796,
657,
198,
4514,
6407,
25,
198,
220,
220,
220,
6056,
796,
10148,
198,
220,
220,
220,
1312,
796,
532,
16,
198,
220,
220,
220,
264,
796,
10148,
198,
220,
220,
220,
981,
1312,
1279,
657,
25,
198,
220,
22... | 1.896321 | 299 |
"""
Contains data ingest related functions
"""
import re
import os.path
from dateutil.parser import parse as dateparser
import typing
from typing import Dict
import cmr
from hatfieldcmr.ingest.file_type import MODISBlobType
MODIS_NAME = "modis-terra"
TITLE_PATTERN_STRING = r"\w+:([\w]+\.[\w]+):\w+"
TITLE_PATTERN = re.compile(TITLE_PATTERN_STRING)
GRANULE_TITLE_KEY = 'title'
GRANULE_TIME_KEY = 'time_start'
GRANULE_NAME_KEY = 'producer_granule_id'
def format_object_name(meta: Dict, object_name: str) -> str:
"""
Parameters
----------
metas: Dict
Single Granule metadata JSON response from CMR
object_name: str
Name of object (ex. hdf file, xml file)
Returns
----------
str
Object name for granule.
If insufficient information is available, empty string is returned.
"""
default_value = ""
if meta is None:
return default_value
folder_prefix = ""
try:
folder_prefix = format_object_prefix(meta)
except ValueError:
return ''
os.makedirs(folder_prefix, exist_ok=True)
return f"{folder_prefix}/{object_name}"
def format_object_prefix(meta: Dict):
"""Helper function to generate 'folder prefix' of the bucket object
"""
if not ((GRANULE_TITLE_KEY in meta) and (GRANULE_TIME_KEY in meta) and
(GRANULE_NAME_KEY in meta)):
raise ValueError('granule does not have required keys', meta)
title = meta.get(GRANULE_TITLE_KEY, "")
m = TITLE_PATTERN.match(title)
if m is None:
raise ValueError('granule does not have well formated title', title)
product_name = m.groups()[0]
date_string = dateparser(meta.get("time_start")).strftime('%Y.%m.%d')
folder_prefix = format_object_prefix_helper(product_name, date_string)
# f"{MODIS_NAME}/{product_name}/{date_string}"
return folder_prefix
| [
37811,
198,
4264,
1299,
1366,
26151,
3519,
5499,
198,
37811,
198,
11748,
302,
198,
11748,
28686,
13,
6978,
198,
6738,
3128,
22602,
13,
48610,
1330,
21136,
355,
3128,
48610,
198,
198,
11748,
19720,
198,
6738,
19720,
1330,
360,
713,
198,
... | 2.545332 | 739 |
import twitter
import datetime
import feedparser
import re
import string
from django.core.management.base import BaseCommand
from optparse import make_option
from twittersmash.models import Feed, TwitterAccount, Message
import pytz
from pytz import timezone
central = timezone('US/Central')
utc = pytz.utc
# Parses the "Tweet Format" in Twitter RSS feeds
twit_re = re.compile(r'^(?P<username>\S+): (?P<message>.*)$')
# Parses out hashtags
tag_pat = r'\#([A-Za-z0-9]+)'
tag_re = re.compile(tag_pat) | [
11748,
17044,
198,
11748,
4818,
8079,
198,
11748,
3745,
48610,
198,
11748,
302,
198,
11748,
4731,
198,
6738,
42625,
14208,
13,
7295,
13,
27604,
13,
8692,
1330,
7308,
21575,
198,
6738,
2172,
29572,
1330,
787,
62,
18076,
198,
6738,
665,
4... | 2.857143 | 175 |
import os
import unittest
from snowflet.lib import read_sql
from snowflet.lib import logging_config
from snowflet.lib import extract_args
from snowflet.lib import apply_kwargs
from snowflet.lib import strip_table
from snowflet.lib import extract_tables_from_query
from snowflet.lib import add_database_id_prefix
from snowflet.lib import is_table
from snowflet.lib import add_table_prefix_to_sql
if __name__ == "__main__":
logging_config()
unittest.main()
| [
11748,
28686,
198,
11748,
555,
715,
395,
198,
6738,
6729,
69,
1616,
13,
8019,
1330,
1100,
62,
25410,
198,
6738,
6729,
69,
1616,
13,
8019,
1330,
18931,
62,
11250,
198,
6738,
6729,
69,
1616,
13,
8019,
1330,
7925,
62,
22046,
198,
6738,
... | 2.920245 | 163 |
# -*- coding: utf-8 -*-
"""
Microsoft-Windows-AssignedAccess
GUID : 8530db6e-51c0-43d6-9d02-a8c2088526cd
"""
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
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
37811,
198,
15905,
12,
11209,
12,
8021,
3916,
15457,
198,
38,
27586,
1058,
7600,
1270,
9945,
21,
68,
12,
4349,
66,
15,
12,
3559,
67,
21,
12,
24,
67,
2999,
12,
64,
... | 2.474026 | 154 |
from capture_image import CaptureImage
if __name__ == '__main__':
"""
This can be directly used from CLI
e.g.: source /home/pi/.smartcambuddy_venv/bin/activate
python smarcambuddy/take_a_photo.py
"""
CaptureImage.trigger()
| [
6738,
8006,
62,
9060,
1330,
31793,
5159,
198,
198,
361,
11593,
3672,
834,
6624,
705,
834,
12417,
834,
10354,
198,
220,
220,
220,
37227,
198,
220,
220,
220,
770,
460,
307,
3264,
973,
422,
43749,
198,
220,
220,
220,
304,
13,
70,
11207... | 2.677419 | 93 |
from oyster.conf import settings
CELERY_IMPORTS = ['oyster.tasks'] + list(settings.CELERY_TASK_MODULES)
| [
6738,
35104,
1706,
13,
10414,
1330,
6460,
198,
198,
34,
3698,
19664,
62,
3955,
47,
33002,
796,
37250,
726,
1706,
13,
83,
6791,
20520,
1343,
1351,
7,
33692,
13,
34,
3698,
19664,
62,
51,
1921,
42,
62,
33365,
6239,
1546,
8,
198
] | 2.5 | 42 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sonnet as snt
import tensorflow as tf
from .drop_mask import make_drop_mask1
from .promotion_mask import make_promotion_mask
from ..boolean_board.black import select_black_fu_board, select_non_black_board
from ..boolean_board.empty import select_empty_board
from ..direction import Direction
from ..piece import Piece
__author__ = 'Yasuhiro'
__date__ = '2018/2/22'
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
11748,
3367,
3262,
355,
264,
429,
198,
11748,
11192,
273,
11125,
355,
48700,
198,
198,
6738,
764,
14781,
62,
27932... | 2.985915 | 142 |
from connect.devops_testing.bdd.fixtures import use_connect_request_dispatcher, use_connect_request_builder
from connect.devops_testing.request import Builder, Dispatcher
| [
6738,
2018,
13,
7959,
2840,
62,
33407,
13,
65,
1860,
13,
69,
25506,
1330,
779,
62,
8443,
62,
25927,
62,
6381,
8071,
2044,
11,
779,
62,
8443,
62,
25927,
62,
38272,
198,
6738,
2018,
13,
7959,
2840,
62,
33407,
13,
25927,
1330,
35869,
... | 3.530612 | 49 |
from django.apps import AppConfig
| [
6738,
42625,
14208,
13,
18211,
1330,
2034,
16934,
628
] | 3.888889 | 9 |
import sublime, sublime_plugin
import os, traceback
from ...libs import util
from ...libs import FlowCLI | [
11748,
41674,
11,
41674,
62,
33803,
198,
11748,
28686,
11,
12854,
1891,
198,
6738,
2644,
8019,
82,
1330,
7736,
198,
6738,
2644,
8019,
82,
1330,
27782,
5097,
40
] | 3.714286 | 28 |
import os
import sys
import base64
import fnmatch
from kconfiglib import Kconfig, expr_value, Symbol, Choice, MENU, COMMENT, BOOL, STRING, INT, HEX
from java.awt import BorderLayout, Dimension, FlowLayout
from java.awt.event import ActionListener, MouseEvent
from javax.swing import BorderFactory, BoxLayout, ImageIcon, JButton, JCheckBox, JFileChooser, JFrame, JLabel, JPanel, JRadioButton, JScrollPane, JSplitPane, JTextArea, JTextField, JTree
from javax.swing.event import ChangeEvent, DocumentListener, TreeExpansionListener, TreeSelectionListener, CellEditorListener
from javax.swing.tree import DefaultTreeModel, DefaultMutableTreeNode, DefaultTreeCellRenderer, TreeCellEditor, TreePath
from events import addActionListener
# For icons in code
from org.python.core.util import StringUtil
if 'knodeinfo' in sys.modules:
del sys.modules["knodeinfo"]
from knodeinfo import getNodeInfoString, getNodeName, setKConfig
log = PrintLogger()
# If True, use GIF image data embedded in this file instead of separate GIF
# files. See _load_images().
_USE_EMBEDDED_IMAGES = True
if __name__ == "__main__":
# Set default .config file or load it from argv
if len(sys.argv) == 2:
# Specify "Kconfig"
mpconfig = MPConfig(sys.argv[1])
else:
# Specify "Kconfig" and ".config"
mpconfig = MPConfig(sys.argv[1], sys.argv[2])
jframe = JFrame("MPLAB X Kconfig Editor")
jframe.getContentPane().add(mpconfig.getPane())
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
jframe.setSize(500, 800)
jframe.setVisible(True)
| [
11748,
28686,
198,
11748,
25064,
198,
11748,
2779,
2414,
198,
11748,
24714,
15699,
198,
6738,
479,
11250,
8019,
1330,
509,
11250,
11,
44052,
62,
8367,
11,
38357,
11,
18502,
11,
41597,
52,
11,
9440,
10979,
11,
16494,
3535,
11,
19269,
275... | 2.92081 | 543 |
# coding=utf-8
# pylint: disable=missing-docstring, unused-argument
import os.path
import sqlite3
import tempfile
import unittest
import sqlalchemy.ext.declarative
import sqlalchemy.orm
try:
# noinspection PyPackageRequirements
import ujson as json
except ImportError:
import json
import sqlalchemy_jsonfield
# Path to test database
db_path = os.path.join(tempfile.gettempdir(), "test.sqlite3")
# Table name
table_name = "create_test"
# DB Base class
Base = sqlalchemy.ext.declarative.declarative_base()
# Model
| [
2,
19617,
28,
40477,
12,
23,
198,
2,
279,
2645,
600,
25,
15560,
28,
45688,
12,
15390,
8841,
11,
21958,
12,
49140,
198,
198,
11748,
28686,
13,
6978,
198,
11748,
44161,
578,
18,
198,
11748,
20218,
7753,
198,
11748,
555,
715,
395,
198,... | 2.93956 | 182 |
'''Run Example 4.8 from Aho & Ullman p. 315-316, printing the steps to stdout.
'''
from cfg import aho_ullman, core
import sys
CFG = core.ContextFreeGrammar
G = CFG('''
S -> AA | AS | b
A -> SA | AS | a
''')
w = map(core.Terminal, 'abaab')
print 'G:'
print G
print
print 'w =', ''.join(map(str, w))
print
T = aho_ullman.cocke_younger_kasami_algorithm(G, w, out=sys.stdout, check=False)
print 'T:'
print aho_ullman.parse_table_str(T)
print
parse = aho_ullman.left_parse_from_parse_table(G, w, T, check=False)
tree = aho_ullman.LeftParse(G, parse).tree()
print 'Parse tree:', tree
| [
7061,
6,
10987,
17934,
604,
13,
23,
422,
7900,
78,
1222,
471,
297,
805,
279,
13,
32647,
12,
33400,
11,
13570,
262,
4831,
284,
14367,
448,
13,
198,
7061,
6,
198,
198,
6738,
30218,
70,
1330,
257,
8873,
62,
724,
805,
11,
4755,
198,
... | 2.348 | 250 |
from .convpool_op_base import ConvPoolOpBase
| [
6738,
764,
42946,
7742,
62,
404,
62,
8692,
1330,
34872,
27201,
18257,
14881,
628
] | 3.285714 | 14 |
import pytest
from django.db.models import Manager
from cegs_portal.search.json_templates.v1.dna_region import dnaregions
from cegs_portal.search.json_templates.v1.search_results import (
search_results as sr_json,
)
from cegs_portal.search.models import DNARegion, Facet
from cegs_portal.search.models.utils import ChromosomeLocation
pytestmark = pytest.mark.django_db
| [
11748,
12972,
9288,
198,
6738,
42625,
14208,
13,
9945,
13,
27530,
1330,
9142,
198,
198,
6738,
269,
1533,
82,
62,
634,
282,
13,
12947,
13,
17752,
62,
11498,
17041,
13,
85,
16,
13,
67,
2616,
62,
36996,
1330,
288,
77,
533,
70,
507,
1... | 2.772059 | 136 |
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2021 Apple Inc. All Rights Reserved.
#
"""Utility functions to tag tensors with metadata.
The metadata remains with the tensor under torch operations that don't change
the values, e.g. .clone(), .contiguous(), .permute(), etc.
"""
import collections
import copy
from typing import Any
from typing import Optional
import numpy as np
import torch
QuantizeAffineParams2 = collections.namedtuple(
"QuantizeAffineParams", ["scale", "zero_point", "num_bits"]
)
def tag_with_metadata(tensor: torch.Tensor, metadata: Any) -> None:
"""Tag a metadata to a tensor."""
_check_type(tensor)
tensor.__class__ = _SpecialTensor
tensor._metadata = metadata
RepresentibleByQuantizeAffine = collections.namedtuple(
"RepresentibleByQuantizeAffine", ["quant_params"]
)
def mark_quantize_affine(
tensor: torch.Tensor,
scale: float,
zero_point: int,
dtype: np.dtype = np.uint8,
) -> None:
"""Mark a tensor as quantized with affine.
See //xnorai/training/pytorch/extensions/functions:quantize_affine for more
info on this method of quantization.
The tensor itself can be a floating point Tensor. However, its values must
be representible with @scale and @zero_point. This function, for performance
reasons, does not validiate if the tensor is really quantizable as it
claims to be.
Arguments:
tensor (torch.Tensor): The tensor to be marked as affine-quantizable
Tensor.
scale (float): the scale (from quantization parameters).
zero_point (int): The zero_point (from quantization parameters).
dtype (numpy.dtype): Type of tensor when quantized (this is usually
numpy.uint8, which is used for Q8). A ValueError will be thrown if
the input dtype is not one of the following:
{numpy.uint8, numpy.int32}.
"""
allowed_dtypes = [np.uint8, np.int32]
if dtype not in allowed_dtypes:
raise ValueError(
"Provided dtype ({}) is not supported. Please use: {}".format(
dtype, allowed_dtypes
)
)
quant_params = QuantizeAffineParams2(scale, zero_point, dtype)
tag_with_metadata(tensor, RepresentibleByQuantizeAffine(quant_params))
| [
2,
198,
2,
1114,
15665,
766,
19249,
38559,
24290,
2393,
13,
198,
2,
15069,
357,
34,
8,
33448,
4196,
3457,
13,
1439,
6923,
33876,
13,
198,
2,
198,
37811,
18274,
879,
5499,
284,
7621,
11192,
669,
351,
20150,
13,
198,
198,
464,
20150,
... | 2.760192 | 834 |
# Rohan E., Luke V.
# Modeling large-deforming fluid-saturated porous media using
# an Eulerian incremental formulation.
# Advances in Engineering Software, 113:84-95, 2017,
# https://doi.org/10.1016/j.advengsoft.2016.11.003
#
# Run simulation:
#
# ./simple.py example_largedef_porodyn-1/porodynhe_example2d.py
#
# The results are stored in `example_largedef_porodyn-1/results`.
#
import numpy as nm
from porodyn_engine import incremental_algorithm,\
fc_fce, mat_fce, def_problem
import os.path as osp
wdir = osp.dirname(__file__)
| [
2,
371,
22436,
412,
1539,
11336,
569,
13,
198,
2,
9104,
278,
1588,
12,
2934,
15464,
11711,
12,
82,
30192,
48242,
2056,
1262,
198,
2,
281,
412,
18173,
666,
29497,
31760,
13,
198,
2,
8007,
1817,
287,
14044,
10442,
11,
17318,
25,
5705,... | 2.7 | 200 |
"""
Pluggable Django email backend for capturing outbound mail for QA/review purposes.
"""
__version__ = "1.0"
__author__ = "Scot Hacker"
__email__ = "shacker@birdhouse.org"
__url__ = "https://github.com/shacker/django-mailcheck"
__license__ = "BSD License"
| [
37811,
198,
3646,
6837,
540,
37770,
3053,
30203,
329,
21430,
503,
7784,
6920,
329,
1195,
32,
14,
19023,
4959,
13,
198,
37811,
198,
834,
9641,
834,
796,
366,
16,
13,
15,
1,
198,
198,
834,
9800,
834,
796,
366,
37559,
34399,
1,
198,
... | 2.954545 | 88 |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 28 13:41:03 2019
@author: bwc
"""
import numpy as np
def edges_to_centers(*edges):
"""
Convert bin edges to bin centers
Parameters
----------
*edges : bin edges
Returns
-------
centers : list of bin centers
"""
centers = []
for es in edges:
centers.append((es[0:-1]+es[1:])/2)
return centers
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
37811,
198,
41972,
319,
3300,
2447,
2579,
1511,
25,
3901,
25,
3070,
13130,
198,
198,
31,
9800,
25,
275,
86,
66,
198,
37811,
198,
198,
11748,
299,
32152,
355,
45941,
62... | 1.885496 | 262 |
import inspect # http://docs.python.org/2/library/inspect.html
from pprint import pprint
from bage_utils.dict_util import DictUtil # @UnusedImport
if __name__ == '__main__':
pprint(InspectUtil.summary())
# __test()
| [
11748,
10104,
220,
1303,
2638,
1378,
31628,
13,
29412,
13,
2398,
14,
17,
14,
32016,
14,
1040,
806,
13,
6494,
198,
6738,
279,
4798,
1330,
279,
4798,
198,
198,
6738,
275,
496,
62,
26791,
13,
11600,
62,
22602,
1330,
360,
713,
18274,
34... | 2.705882 | 85 |
import struct
| [
11748,
2878,
628,
220,
220,
220,
220
] | 2.714286 | 7 |
import os
import random
import time
import xlwt
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from front_login import *
from readConfig import ReadConfig
from db import DbOperate
from selenium.webdriver.chrome.options import Options
from mysqldb import connect
chrome_options = Options()
chrome_options.add_argument('--headless')
driver = webdriver.Chrome(chrome_options=chrome_options)
# driver = webdriver.Chrome()
driver.maximize_window()
driver.get(ReadConfig().get_root_url())
driver.get(ReadConfig().get_root_url())
| [
11748,
28686,
198,
11748,
4738,
198,
11748,
640,
198,
198,
11748,
2124,
75,
46569,
198,
6738,
384,
11925,
1505,
13,
12384,
26230,
13,
11321,
13,
2673,
62,
38861,
1330,
7561,
1925,
1299,
198,
6738,
384,
11925,
1505,
13,
12384,
26230,
13,... | 3.35 | 180 |
# dashboard_generator.py
import os.path # helps to save in a different folder
import pandas as pd
import itertools
import locale # from https://stackoverflow.com/Questions/320929/currency-formatting-in-python
from os import listdir
from os.path import isfile, join
#for chart generation
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
# FILES PATH
save_path = 'C:/Users/Owner/Desktop/NYU-MBA/Programming/Files/monthly-sales/data'
# INTRODUCTION
print("Select one month to report")
print("---------------------------------------------------------------------")
# LISTING FILES (sorted and in a proper list)
onlyfiles = [f for f in listdir(save_path) if isfile(join(save_path, f))] #https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory
onlyfiles.sort()
print(*onlyfiles, sep = "\n") #https://www.geeksforgeeks.org/print-lists-in-python-4-different-ways/
print("---------------------------------------------------------------------")
# REPORT SELECTION
selected_year = input("Please input a year (Example 2018 -- for Year): ")
selected_month = input("Please input a month (Example 01 -- for January): ")
# FILE SELECTED
file_name = "sales-" + selected_year + selected_month + ".csv"
# OPENING SPECIFIC FILE
find_file = os.path.join(save_path, file_name) #find the file
while not os.path.exists(find_file): #correct if does not exist
print("---------------------------------------------------------------------")
print("\n")
print("The file selected do not exist. Please try again")
print("\n")
print("---------------------------------------------------------------------")
exit()
stats = pd.read_csv(find_file)
# PERFORMING THE SUM
total_sales = stats["sales price"].sum()
# FORMATTING TOTAL SALES
locale.setlocale( locale.LC_ALL, '' )
total_sales_format = locale.currency(total_sales, grouping= True)
print("---------------------------------------------------------------------")
# SALES REPORT DATE
if selected_month == "01":
month_name = "JANUARY"
if selected_month == "02":
month_name = "FEBRUARY"
if selected_month == "03":
month_name = "MARCH"
if selected_month == "04":
month_name = "APRIL"
if selected_month == "05":
month_name = "MAY"
if selected_month == "06":
month_name = "JUNE"
if selected_month == "07":
month_name = "JULY"
if selected_month == "08":
month_name = "AUGUST"
if selected_month == "09":
month_name = "SEPTEMBER"
if selected_month == "10":
month_name = "OCTOBER"
if selected_month == "11":
month_name = "NOVEMBER"
if selected_month == "12":
month_name = "DECEMBER"
print("SALES REPORT " + "(" + month_name + " " + selected_year + ")")
# PRINTING TOTAL SALES
print("TOTAL SALES: " + (total_sales_format))
print("\n")
# TOP SELLING PRODUCTS
product_totals = stats.groupby(["product"]).sum()
product_totals = product_totals.sort_values("sales price", ascending=False)
top_sellers = []
rank = 1
for i, row in product_totals.iterrows():
d = {"rank": rank, "name": row.name, "monthly_sales": row["sales price"]}
top_sellers.append(d)
rank = rank + 1
print("TOP SELLING PRODUCTS:")
for d in top_sellers:
locale.setlocale( locale.LC_ALL, '' )
print(" " + str(d["rank"]) + ") " + d["name"] +
": " + to_usd(d["monthly_sales"]))
print("\n")
print("---------------------------------------------------------------------")
print("\n")
print("GENERATING BAR CHART...")
print("\n")
print("---------------------------------------------------------------------")
### PRINT BAR CHART
# first two lines are the list comprehensions to make a list of dictionaries into a list)
x = [p["name"] for p in top_sellers] ## VERY IMPORTANT
y = [p["monthly_sales"] for p in top_sellers] ## VERY IMPORTANT
#sorting in the correct order
x.reverse()
y.reverse()
# break charts into two
fig, ax = plt.subplots() # enables us to further customize the figure and/or the axes
#formatting chart
usd_formatter = ticker.FormatStrFormatter('$%1.0f')
ax.xaxis.set_major_formatter(usd_formatter)
# CHART GENERATION
plt.barh(x, y)
plt.title("TOP-SELLING PRODUCTS " + "(" + month_name + " " + selected_year + ")") # AXIS TITLES
plt.ylabel('Sales (USD)') # AXIS TITLES
plt.ylabel("Product") # AXIS TITLES
# formatting numbers
for i, v in enumerate(y):
ax.text(v, i, usd_formatter(v), color='black', fontweight='bold')
#https://matplotlib.org/users/colors.html
#https://matplotlib.org/3.1.0/gallery/pyplots/text_commands.html#sphx-glr-gallery-pyplots-text-commands-py
plt.tight_layout() # ensures all areas of the chart are visible by default (fixes labels getting cut off)
plt.show()
exit()
## FULL SOLUTION PROVIDED BY THE PROFESSOR
# # this section needs to come before the chart construction
# fig, ax = plt.subplots() # enables us to further customize the figure and/or the axes
# usd_formatter = ticker.FormatStrFormatter('$%1.0f')
# ax.xaxis.set_major_formatter(usd_formatter)
#
# # chart construction
# plt.barh(sorted_products, sorted_sales)
# plt.title(chart_title)
# plt.ylabel("Product")
# plt.xlabel("Monthly Sales (USD)")
#
# plt.tight_layout() # ensures all areas of the chart are visible by default (fixes labels getting cut off)
# plt.show() | [
2,
30415,
62,
8612,
1352,
13,
9078,
198,
198,
11748,
28686,
13,
6978,
1303,
5419,
284,
3613,
287,
257,
1180,
9483,
198,
11748,
19798,
292,
355,
279,
67,
198,
11748,
340,
861,
10141,
198,
11748,
36693,
1303,
422,
3740,
1378,
25558,
250... | 2.893617 | 1,833 |
from urllib.parse import urljoin
from scrapy import Request
from product_spider.items import RawData
from product_spider.utils.functions import strip
from product_spider.utils.spider_mixin import BaseSpider
| [
6738,
2956,
297,
571,
13,
29572,
1330,
19016,
22179,
198,
198,
6738,
15881,
88,
1330,
19390,
198,
198,
6738,
1720,
62,
2777,
1304,
13,
23814,
1330,
16089,
6601,
198,
6738,
1720,
62,
2777,
1304,
13,
26791,
13,
12543,
2733,
1330,
10283,
... | 3.559322 | 59 |
import yaml
| [
11748,
331,
43695,
628
] | 3.25 | 4 |
#!/usr/bin/python
import os
lines = [line for line in open("hehe.txt")]
for line in lines:
i = 0
for c in line:
if (c != '_' and not (c >= '0' and c <= '9')):
break
i+=1
cmd = "mv " + line[0:i].strip() + line[i+5:].strip() + " lab2_" + line[0:i].strip() + line[i+5:].strip()
print cmd
os.system(cmd)
continue
index = line.find("_lab2_")
num = line[0 : index + 1]
value = line[index + 6 : ]
nn = "lab2_" + num + value
cmd = "mv 3_" + line.strip() + " " + nn
#print cmd
os.system(cmd)
| [
2,
48443,
14629,
14,
8800,
14,
29412,
198,
198,
11748,
28686,
198,
198,
6615,
796,
685,
1370,
329,
1627,
287,
1280,
7203,
258,
258,
13,
14116,
4943,
60,
198,
198,
1640,
1627,
287,
3951,
25,
198,
197,
72,
796,
657,
198,
197,
1640,
... | 2.138075 | 239 |
#!/usr/bin/enb python
import string, re
import Handler
#######################
# Define some regular expressions inside a quoted string
# then turn the string into the actual data structure.
# (I found it was easiest to understand when done this way.)
definitions = r"""
# These are the atomic symbols Daylight allows outside of []s
# See "atom_class" for names like "a" and "A"
raw_atom Cl|Br|[cnospBCNOFPSI*]
# For atoms inside of []s
open_bracket \[
close_bracket \]
# See "element_modifiers" for the patterns for element names
# charges, chiralities, H count, etc.
# [235U]
weight \d+
# [#6]
atomic_number #\d+
# [!C]
atom_not !
# & is highest (an "and")
# , is next (an "or")
# ; is lowest (an "and")
# [n&H] [n,H] [c,h;H1]
atom_binary [&,;]
# C.C
dot \.
# - single bond (aliphatic)
# / directional single bond "up"
# \ directional single bond "down"
# /? directional bond "up or unspecified"
# \? directional bond "down or unspecified"
# = double bond
# # triple bond
# : aromatic bond
# ~ any bond (wildcard)
# @ any ring bond
bond [/\\]\??|[=#:~@-]
# *!:* -- not aromatic
bond_not !
# *@;!:* -- same as !:
bond_binary [&;,]
# (C).(C)
open_zero \(
# C(C)
open_branch \(
# [$(*C);$(*CC)]
open_recursive_smarts \$\(
# special cased because it closes open_zero, open_branch, and
# recursive_smarts
close_parens \)
# Ring closures, 1, %5 %99 (and even %00 for what it's worth)
closure \d|%\d\d?
"""
#######################
# Turn the above string into key/value pairs where the
# values are the compiled regular expressions.
info = {}
for line in string.split(definitions, "\n"):
line = string.strip(line)
if not line or line[:1] == "#":
continue
name, pattern = string.split(line)
info[name] = re.compile(pattern)
del line, name, pattern
info["atom_class"] = re.compile(r"""
(?P<raw_aromatic>a)| # Not really sure what these mean
(?P<raw_b_unknown>b)|
(?P<raw_f_unknown>f)|
(?P<raw_h_unknown>h)|
(?P<raw_i_unknown>i)|
(?P<raw_r_unknown>r)|
(?P<raw_aliphatic>A)|
(?P<raw_R_unknown>R)
""", re.X)
# 'H' is used for the hydrogen count, so those searches require a
# special recursive SMARTS definition. Eg, for deuterium or tritium
# [$([2H]),$([3H])]
# This is implemented as a special-case hack. Note: if there's
# an error in the parse string in this section then the error
# location will point to the start of this term, not at the
# character that really caused the error. Can be fixed with an
# 'error_' like I did for the SMILES -- not needed for now. XXX
hydrogen_term_fields = [
"open_recursive_smarts",
"open_bracket",
"weight",
"element",
"positive_count",
"positive_symbols",
"negative_count",
"negative_symbols",
"close_bracket",
"close_recursive_smarts",
]
info["hydrogen_term"] = re.compile(r"""
(?P<open_recursive_smarts>\$\()
(?P<open_bracket>\[)
(?P<weight>\d+)? # optional molecular weight [2H]
(?P<element>H) # Must be a hydrogen
( # optional charge
(?P<positive_count>\+\d+)| # +3
(?P<positive_symbols>\++)| # ++
(?P<negative_count>\-\d+)| # -2
(?P<negative_symbols>\-+)| # ---
)?
(?P<close_bracket>\])
(?P<close_recursive_smarts>\))
""", re.X)
element_symbols_pattern = \
r"C[laroudsemf]?|Os?|N[eaibdpos]?|S[icernbmg]?|P[drmtboau]?|" \
r"H[eofgas]|c|n|o|s|p|A[lrsgutcm]|B[eraik]?|Dy|E[urs]|F[erm]?|" \
r"G[aed]|I[nr]?|Kr?|L[iaur]|M[gnodt]|R[buhenaf]|T[icebmalh]|" \
r"U|V|W|Xe|Yb?|Z[nr]|\*"
info["element_modifier"] = re.compile(r"""
(?P<element>
# This does *not* contain H. Hydrogen searches must be done
# with a special recursive SMARTS. On the other hand, it does
# include the lower case aromatic names.
""" + element_symbols_pattern + r"""
)|
(?P<aromatic>a)| # aromatic
(?P<aliphatic>A)| # Aliphatic
(?P<degree>D\d+)| # Degree<n>
(?P<total_hcount>H\d*)| # total Hydrogen count<n> (defaults to 1)
(?P<imp_hcount>h\d*)| # implicit hydrogen count<n> (defaults to 1)
(?P<ring_membership>R\d*)| # in <n> Rings (no n means any rings)
(?P<ring_size>r\d*)| # in a ring of size <n> (no n means any rings)
(?P<valence>v\d+)| # total bond order of <n>
(?P<connectivity>X\d+)| # <n> total connections
(?P<positive_count>\+\d+)| # +2 +3
(?P<positive_symbols>\++)| # + ++ +++
(?P<negative_count>\-\d+)| # -1 -4
(?P<negative_symbols>\-+)| # -- - -------
# XXX What about chiral_count?
(?P<chiral_named> # The optional '?' means "or unspecified"
@TH[12]\??| # @TH1 @TH2?
@AL[12]\??| # @AL2?
@SP[123]\??| # @SP3 @SP1?
@TB(1[0-9]?|20?|[3-9])\??| # @TH{1 through 20}
@OH(1[0-9]?|2[0-9]?|30?|[4-9])\?? # @OH{1 through 30}
)|
(?P<chiral_symbols>@@?\??) # @ (anticlockwise) or @@ (clockwise)
""", re.X)
# The ')' closes three different open parens. This maps from the
# previous open state to the appropriate close state.
close_parens_states = {
"open_branch": "close_branch",
"open_recursive_smarts": "close_recursive_smarts",
"open_zero": "close_zero",
}
#### Some helpful definitions to reduce clutter and complication
# Possible transitions from the start node. Also visited after
# a '.' disconnect or in a recursive SMARTS.
expecting_start = ("raw_atom", "atom_class", "open_bracket", "open_zero")
# Looking for node definition, like "C" or "a" or "["
expecting_atom = ("raw_atom", "atom_class", "open_bracket")
# Inside of []s: 235U, #6, R, $([2H]), $(*=C), !
expecting_element_start = ("weight", "atomic_number",
"element_modifier", "hydrogen_term",
"open_recursive_smarts", "atom_not")
# the ';' in [n;H1] or the ']' at the end
expecting_element_end = ("atom_binary", "close_bracket")
# All bonds start with a '!' or one of the bond symbols
expecting_bond_start = ("bond", "bond_not")
expecting_raw_term = expecting_atom + expecting_bond_start + \
("close_parens", "open_branch", "dot", "closure")
expecting_modifier = ("element_modifier", "open_recursive_smarts")
table = {
"start": expecting_start,
# (C).(R).[U].([$(*)])
"open_zero": ("raw_atom", "atom_class", "open_bracket"),
# as well as (CC(C))
"close_zero": ("dot", "close_parens"),
# A raw term are the things like 'C', '[U]', '%10', '.', '(', '!#'
"raw_atom": expecting_raw_term,
# An atom_class is a non-specific atom term, like 'A' or 'r'
"atom_class": expecting_raw_term,
# the []s
"open_bracket": expecting_element_start,
"close_bracket": expecting_raw_term,
# Yes, '[!!!!C]' is legal, according to the docs, but it isn't
# supported by the parser, unless you optimze it.
"atom_not": expecting_element_start,
"atom_binary": expecting_element_start,
# "14N", "14a", ...
# Note that weight can only be set once so it isn't a modifier
# Also, "14#6" isn't legal (tested against the toolkit)
"weight": expecting_modifier,
# "#6R2" or "#8," or "#7]"
# The atomic_number can only be set once so it isn't a modifier
"atomic_number": expecting_modifier + expecting_element_end,
# All of these are type of modifiers
"element_modifier": expecting_modifier + expecting_element_end,
"hydrogen_term": expecting_modifier + expecting_element_end,
"close_recursive_smarts": expecting_modifier + expecting_element_end,
# This it the recursive part -- goes back to the beginning
"open_recursive_smarts": expecting_start,
# C=C, C1CCC=1, C~-C, C=(C)C, C=,-C
"bond": expecting_atom + ("closure", "bond", "open_branch",
"bond_binary"),
# C!!=C
"bond_not": expecting_bond_start,
# C=,-C
"bond_binary": expecting_bond_start,
"closure": expecting_raw_term,
"close_branch": expecting_raw_term,
"open_branch": expecting_atom + expecting_bond_start + ("dot",),
# After a "." we can start all over again
"dot": expecting_start,
}
| [
2,
48443,
14629,
14,
8800,
14,
268,
65,
21015,
201,
198,
201,
198,
11748,
4731,
11,
302,
201,
198,
11748,
32412,
201,
198,
201,
198,
14468,
4242,
21017,
201,
198,
201,
198,
2,
2896,
500,
617,
3218,
14700,
2641,
257,
10947,
4731,
201... | 2.231587 | 3,761 |
# This is default settings for VisARTM for local usage
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATA_DIR = os.path.join(BASE_DIR, "data")
SECRET_KEY = 'yj_fhwf$-8ws1%a_vl5c0lf($#ke@c3+lu3l-f733k(j-!q*57'
DEBUG = True
ALLOWED_HOSTS = ["127.0.0.1"]
THREADING = True
REGISTRATION_CLOSED = False
DEFAULT_FROM_EMAIL = 'visartm@yandex.ru'
SERVER_EMAIL = 'visartm@yandex.ru'
EMAIL_HOST = 'smtp.yandex.ru'
EMAIL_HOST_USER = 'visartm@yandex.ru'
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = 587
EMAIL_USE_TLS = True
INSTALLED_APPS = [
'test_without_migrations',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'datasets',
'visual',
'models',
'assessment',
'research',
'tools',
'accounts'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'visartm.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'visartm.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'visartm.sqlite',
}
}
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend']
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': (
'django.contrib.auth.password_validation.'
'UserAttributeSimilarityValidator'),
},
{
'NAME': (
'django.contrib.auth.password_validation.'
'MinimumLengthValidator'),
},
{
'NAME': (
'django.contrib.auth.password_validation.'
'CommonPasswordValidator'),
},
{
'NAME': (
'django.contrib.auth.password_validation.'
'NumericPasswordValidator'),
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = False
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
| [
2,
770,
318,
4277,
6460,
329,
6911,
7227,
44,
329,
1957,
8748,
198,
11748,
28686,
628,
198,
33,
11159,
62,
34720,
796,
28686,
13,
6978,
13,
15908,
3672,
7,
418,
13,
6978,
13,
15908,
3672,
7,
418,
13,
6978,
13,
397,
2777,
776,
7,
... | 2.086614 | 1,397 |
"""pyvizio constants."""
DEVICE_CLASS_SPEAKER = "speaker"
DEVICE_CLASS_TV = "tv"
DEVICE_CLASS_CRAVE360 = "crave360"
DEFAULT_DEVICE_ID = "pyvizio"
DEFAULT_DEVICE_CLASS = DEVICE_CLASS_TV
DEFAULT_DEVICE_NAME = "Python Vizio"
DEFAULT_PORTS = [7345, 9000]
DEFAULT_TIMEOUT = 5
MAX_VOLUME = {DEVICE_CLASS_TV: 100, DEVICE_CLASS_SPEAKER: 31, DEVICE_CLASS_CRAVE360: 100}
# Current Input when app is active
INPUT_APPS = ["SMARTCAST", "CAST"]
# App name returned when it is not in app dictionary
UNKNOWN_APP = "_UNKNOWN_APP"
NO_APP_RUNNING = "_NO_APP_RUNNING"
SMARTCAST_HOME = "SmartCast Home"
APP_CAST = "Cast"
# NAME_SPACE values that appear to be equivalent
EQUIVALENT_NAME_SPACES = (2, 4)
APP_HOME = {
"name": SMARTCAST_HOME,
"country": ["*"],
"config": [
{
"NAME_SPACE": 4,
"APP_ID": "1",
"MESSAGE": "http://127.0.0.1:12345/scfs/sctv/main.html",
}
],
}
# No longer needed but kept around in case the external source for APPS is unavailable
APPS = [
{
"name": "Prime Video",
"country": ["*"],
"id": ["33"],
"config": [
{
"APP_ID": "4",
"NAME_SPACE": 4,
"MESSAGE": "https://atv-ext.amazon.com/blast-app-hosting/html5/index.html?deviceTypeID=A3OI4IHTNZQWDD",
},
{"NAME_SPACE": 2, "APP_ID": "4", "MESSAGE": "None"},
],
},
{
"name": "CBS All Access",
"country": ["usa"],
"id": ["9"],
"config": [{"NAME_SPACE": 2, "APP_ID": "37", "MESSAGE": "None"}],
},
{
"name": "CBS News",
"country": ["usa", "can"],
"id": ["56"],
"config": [{"NAME_SPACE": 2, "APP_ID": "42", "MESSAGE": "None"}],
},
{
"name": "Crackle",
"country": ["usa"],
"id": ["8"],
"config": [{"NAME_SPACE": 2, "APP_ID": "5", "MESSAGE": "None"}],
},
{
"name": "Curiosity Stream",
"country": ["usa", "can"],
"id": ["37"],
"config": [{"NAME_SPACE": 2, "APP_ID": "12", "MESSAGE": "None"}],
},
{
"name": "Fandango Now",
"country": ["usa"],
"id": ["24"],
"config": [{"NAME_SPACE": 2, "APP_ID": "7", "MESSAGE": "None"}],
},
{
"name": "FilmRise",
"country": ["usa"],
"id": ["47"],
"config": [{"NAME_SPACE": 2, "APP_ID": "24", "MESSAGE": "None"}],
},
{
"name": "Flixfling",
"country": ["*"],
"id": ["49"],
"config": [{"NAME_SPACE": 2, "APP_ID": "36", "MESSAGE": "None"}],
},
{
"name": "Haystack TV",
"country": ["usa", "can"],
"id": ["35"],
"config": [
{
"NAME_SPACE": 0,
"APP_ID": "898AF734",
"MESSAGE": '{"CAST_NAMESPACE":"urn:x-cast:com.google.cast.media","CAST_MESSAGE":{"type":"LOAD","media":{},"autoplay":true,"currentTime":0,"customData":{"platform":"sctv"}}}',
}
],
},
{
"name": "Hulu",
"country": ["usa"],
"id": ["19"],
"config": [
{
"APP_ID": "3",
"NAME_SPACE": 4,
"MESSAGE": "https://viziosmartcast.app.hulu.com/livingroom/viziosmartcast/1/index.html#initialize",
},
{"NAME_SPACE": 2, "APP_ID": "3", "MESSAGE": "None"},
],
},
{
"name": "iHeartRadio",
"country": ["usa"],
"id": ["11"],
"config": [{"NAME_SPACE": 2, "APP_ID": "6", "MESSAGE": "None"}],
},
{
"name": "NBC",
"country": ["usa"],
"id": ["43"],
"config": [{"NAME_SPACE": 2, "APP_ID": "10", "MESSAGE": "None"}],
},
{
"name": "Netflix",
"country": ["*"],
"id": ["34"],
"config": [{"NAME_SPACE": 3, "APP_ID": "1", "MESSAGE": "None"}],
},
{
"name": "Plex",
"country": ["usa", "can"],
"id": ["40"],
"config": [
{
"APP_ID": "9",
"NAME_SPACE": 4,
"MESSAGE": "https://plex.tv/web/tv/vizio-smartcast",
},
{"NAME_SPACE": 2, "APP_ID": "9", "MESSAGE": "None"},
],
},
{
"name": "Pluto TV",
"country": ["usa"],
"id": ["12"],
"config": [
{"APP_ID": "65", "NAME_SPACE": 4, "MESSAGE": "https://smartcast.pluto.tv"},
{
"NAME_SPACE": 0,
"APP_ID": "E6F74C01",
"MESSAGE": '{"CAST_NAMESPACE":"urn:x-cast:tv.pluto","CAST_MESSAGE":{"command":"initializePlayback","channel":"","episode":"","time":0}}',
},
],
},
{
"name": "RedBox",
"country": ["usa"],
"id": ["55"],
"config": [{"NAME_SPACE": 2, "APP_ID": "41", "MESSAGE": "None"}],
},
{
"name": "TasteIt",
"country": ["*"],
"id": ["52"],
"config": [{"NAME_SPACE": 2, "APP_ID": "26", "MESSAGE": "None"}],
},
{
"name": "Toon Goggles",
"country": ["usa", "can"],
"id": ["46"],
"config": [{"NAME_SPACE": 2, "APP_ID": "21", "MESSAGE": "None"}],
},
{
"name": "Vudu",
"country": ["usa"],
"id": ["6"],
"config": [
{
"APP_ID": "31",
"NAME_SPACE": 4,
"MESSAGE": "https://my.vudu.com/castReceiver/index.html?launch-source=app-icon",
}
],
},
{
"name": "XUMO",
"country": ["usa"],
"id": ["27"],
"config": [
{
"NAME_SPACE": 0,
"APP_ID": "36E1EA1F",
"MESSAGE": '{"CAST_NAMESPACE":"urn:x-cast:com.google.cast.media","CAST_MESSAGE":{"type":"LOAD","media":{},"autoplay":true,"currentTime":0,"customData":{}}}',
}
],
},
{
"name": "YouTubeTV",
"country": ["usa", "mexico"],
"id": ["45"],
"config": [{"NAME_SPACE": 5, "APP_ID": "3", "MESSAGE": "None"}],
},
{
"name": "YouTube",
"country": ["*"],
"id": ["44"],
"config": [{"NAME_SPACE": 5, "APP_ID": "1", "MESSAGE": "None"}],
},
{
"name": "Baeble",
"country": ["usa"],
"id": ["39"],
"config": [{"NAME_SPACE": 2, "APP_ID": "11", "MESSAGE": "None"}],
},
{
"name": "DAZN",
"country": ["usa", "can"],
"id": ["57"],
"config": [{"NAME_SPACE": 2, "APP_ID": "34", "MESSAGE": "None"}],
},
{
"name": "FitFusion by Jillian Michaels",
"country": ["usa", "can"],
"id": ["54"],
"config": [{"NAME_SPACE": 2, "APP_ID": "39", "MESSAGE": "None"}],
},
{
"name": "Newsy",
"country": ["usa", "can"],
"id": ["38"],
"config": [{"NAME_SPACE": 2, "APP_ID": "15", "MESSAGE": "None"}],
},
{
"name": "Cocoro TV",
"country": ["usa", "can"],
"id": ["63"],
"config": [{"NAME_SPACE": 2, "APP_ID": "55", "MESSAGE": "None"}],
},
{
"name": "ConTV",
"country": ["usa", "can"],
"id": ["41"],
"config": [{"NAME_SPACE": 2, "APP_ID": "18", "MESSAGE": "None"}],
},
{
"name": "Dove Channel",
"country": ["usa", "can"],
"id": ["42"],
"config": [{"NAME_SPACE": 2, "APP_ID": "16", "MESSAGE": "None"}],
},
{
"name": "Love Destination",
"country": ["*"],
"id": ["64"],
"config": [{"NAME_SPACE": 2, "APP_ID": "57", "MESSAGE": "None"}],
},
{
"name": "WatchFree",
"country": ["usa"],
"id": ["48"],
"config": [{"NAME_SPACE": 2, "APP_ID": "22", "MESSAGE": "None"}],
},
{
"name": "AsianCrush",
"country": ["usa", "can"],
"id": ["50"],
"config": [
{
"NAME_SPACE": 2,
"APP_ID": "27",
"MESSAGE": "https://html5.asiancrush.com/?ua=viziosmartcast",
}
],
},
{
"name": "Disney+",
"country": ["usa"],
"id": ["51"],
"config": [
{
"NAME_SPACE": 4,
"APP_ID": "75",
"MESSAGE": "https://cd-dmgz.bamgrid.com/bbd/vizio_tv/index.html",
}
],
},
]
| [
37811,
9078,
85,
528,
952,
38491,
526,
15931,
198,
198,
7206,
27389,
62,
31631,
62,
4303,
36,
10206,
1137,
796,
366,
4125,
3110,
1,
198,
7206,
27389,
62,
31631,
62,
6849,
796,
366,
14981,
1,
198,
7206,
27389,
62,
31631,
62,
34,
3861... | 1.777073 | 4,728 |
#
# covid19.py
# owid/latest/covid
#
from owid.catalog.meta import License, Source
import datetime as dt
import pandas as pd
from owid.catalog import Dataset, Table
from etl.helpers import downloaded
MEGAFILE_URL = "https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv"
| [
2,
198,
2,
220,
39849,
312,
1129,
13,
9078,
198,
2,
220,
12334,
312,
14,
42861,
14,
66,
709,
312,
198,
2,
198,
198,
6738,
12334,
312,
13,
9246,
11794,
13,
28961,
1330,
13789,
11,
8090,
198,
11748,
4818,
8079,
355,
288,
83,
198,
... | 2.577236 | 123 |
import unittest
import interop
from SUASSystem import InteropClientConverter
from SUASSystem import Location
| [
11748,
555,
715,
395,
198,
11748,
987,
404,
198,
6738,
13558,
10705,
6781,
1330,
4225,
404,
11792,
3103,
332,
353,
198,
6738,
13558,
10705,
6781,
1330,
13397,
198
] | 3.892857 | 28 |
import os
import json
#import fire
from collections import defaultdict
from pprint import pprint
from itertools import product
from .dataset import Dataset
if __name__ == "__main__":
#fire.Fire(test)
test() | [
11748,
28686,
198,
11748,
33918,
198,
2,
11748,
2046,
198,
6738,
17268,
1330,
4277,
11600,
198,
6738,
279,
4798,
1330,
279,
4798,
198,
6738,
340,
861,
10141,
1330,
1720,
198,
198,
6738,
764,
19608,
292,
316,
1330,
16092,
292,
316,
628,
... | 3.114286 | 70 |
import os
| [
11748,
28686,
628
] | 3.666667 | 3 |
from abc import ABC, abstractmethod
from typing import Dict, Hashable, Tuple
import torch
import torch.nn as nn
import swyft
import swyft.utils
from swyft.networks.channelized import ResidualNetWithChannel
from swyft.networks.standardization import (
OnlineDictStandardizingLayer,
OnlineStandardizingLayer,
)
from swyft.types import Array, MarginalIndex, ObsShapeType
def get_marginal_classifier(
observation_key: Hashable,
marginal_indices: MarginalIndex,
observation_shapes: ObsShapeType,
n_parameters: int,
hidden_features: int,
num_blocks: int,
observation_online_z_score: bool = True,
parameter_online_z_score: bool = True,
) -> nn.Module:
observation_transform = ObservationTransform(
observation_key, observation_shapes, online_z_score=observation_online_z_score
)
n_observation_features = observation_transform.n_features
parameter_transform = ParameterTransform(
n_parameters, marginal_indices, online_z_score=parameter_online_z_score
)
n_marginals, n_block_parameters = parameter_transform.marginal_block_shape
marginal_classifier = MarginalClassifier(
n_marginals,
n_observation_features + n_block_parameters,
hidden_features=hidden_features,
num_blocks=num_blocks,
)
return Network(
observation_transform,
parameter_transform,
marginal_classifier,
)
if __name__ == "__main__":
pass
| [
6738,
450,
66,
1330,
9738,
11,
12531,
24396,
198,
6738,
19720,
1330,
360,
713,
11,
21059,
540,
11,
309,
29291,
198,
198,
11748,
28034,
198,
11748,
28034,
13,
20471,
355,
299,
77,
198,
198,
11748,
1509,
88,
701,
198,
11748,
1509,
88,
... | 2.741573 | 534 |
from output.models.nist_data.list_pkg.date.schema_instance.nistschema_sv_iv_list_date_min_length_1_xsd.nistschema_sv_iv_list_date_min_length_1 import NistschemaSvIvListDateMinLength1
__all__ = [
"NistschemaSvIvListDateMinLength1",
]
| [
6738,
5072,
13,
27530,
13,
77,
396,
62,
7890,
13,
4868,
62,
35339,
13,
4475,
13,
15952,
2611,
62,
39098,
13,
77,
1023,
2395,
2611,
62,
21370,
62,
452,
62,
4868,
62,
4475,
62,
1084,
62,
13664,
62,
16,
62,
87,
21282,
13,
77,
1023,... | 2.333333 | 102 |
from collections import defaultdict
from enum import auto
from typing import Iterable, List, Optional, TYPE_CHECKING, Union
from mstrio import config
from mstrio.api import contacts
from mstrio.distribution_services.contact_group import ContactGroup
from mstrio.distribution_services.device import Device
from mstrio.utils.entity import auto_match_args_entity, DeleteMixin, EntityBase
from mstrio.utils.enum_helper import AutoName
from mstrio.utils.helper import (
camel_to_snake, delete_none_values, Dictable, fetch_objects, get_objects_id
)
from mstrio.users_and_groups.user import User
if TYPE_CHECKING:
from mstrio.connection import Connection
def list_contacts(connection: 'Connection', to_dictionary: bool = False,
limit: Optional[int] = None, **filters) -> Union[List['Contact'], List[dict]]:
"""Get all contacts as list of Contact objects or dictionaries.
Optionally filter the contacts by specifying filters.
Args:
connection: MicroStrategy connection object
to_dictionary: If True returns a list of contact dicts,
otherwise returns a list of contact objects
limit: limit the number of elements returned. If `None` (default), all
objects are returned.
**filters: Available filter parameters:
['id', 'name', 'description', 'enabled']
"""
return Contact._list_contacts(
connection=connection,
to_dictionary=to_dictionary,
limit=limit,
**filters
)
| [
6738,
17268,
1330,
4277,
11600,
198,
6738,
33829,
1330,
8295,
198,
6738,
19720,
1330,
40806,
540,
11,
7343,
11,
32233,
11,
41876,
62,
50084,
2751,
11,
4479,
198,
198,
6738,
285,
301,
27250,
1330,
4566,
198,
6738,
285,
301,
27250,
13,
... | 2.962818 | 511 |
# Iterador a partir de una funcin generadora
f = fib()
# Recorremos nuestro iterador, llamando a next(). Dentro del for se llama automticamente a iter(f)
print(0, end=' ')
for n in range(16):
print(next(f), end=' ') | [
2,
40806,
7079,
257,
636,
343,
390,
555,
64,
1257,
17879,
1152,
324,
5799,
198,
198,
69,
796,
12900,
3419,
198,
198,
2,
3311,
273,
2787,
418,
14364,
47692,
11629,
7079,
11,
32660,
321,
25440,
257,
1306,
22446,
39078,
305,
1619,
329,
... | 2.6 | 85 |
#!/usr/bin/env python
import os
import sys
import platform
from setuptools import setup, Extension
if platform.system() != 'Windows' and platform.python_implementation() == "CPython":
ext_modules = [Extension('sevent/cbuffer', sources=['sevent/cbuffer.c'])]
else:
ext_modules = []
if os.path.exists("README.md"):
if sys.version_info[0] >= 3:
with open("README.md", encoding="utf-8") as fp:
long_description = fp.read()
else:
with open("README.md") as fp:
long_description = fp.read()
else:
long_description = ''
setup(
name='sevent',
version='0.4.6',
packages=['sevent', 'sevent.impl', 'sevent.coroutines', 'sevent.helpers'],
ext_modules=ext_modules,
package_data={
'': ['README.md'],
},
install_requires=[
'dnslib>=0.9.7',
'greenlet>=0.4.2',
],
author='snower',
author_email='sujian199@gmail.com',
url='https://github.com/snower/sevent',
license='MIT',
description='lightweight event loop',
long_description=long_description,
long_description_content_type="text/markdown",
)
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
201,
198,
201,
198,
11748,
28686,
201,
198,
11748,
25064,
201,
198,
11748,
3859,
201,
198,
6738,
900,
37623,
10141,
1330,
9058,
11,
27995,
201,
198,
201,
198,
361,
3859,
13,
10057,
3419,
14... | 2.242308 | 520 |
"""
mbed CMSIS-DAP debugger
Copyright (c) 2006-2013 ARM Limited
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 cortex_m import CortexM
| [
37811,
198,
285,
3077,
40773,
1797,
12,
35,
2969,
49518,
198,
15069,
357,
66,
8,
4793,
12,
6390,
20359,
15302,
628,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
198,
345,
743,
407,
779,
428,
2... | 3.91411 | 163 |
import os
import warnings
warnings.simplefilter("ignore")
import csv
import numpy
import hyperopt
from hyperopt import Trials,tpe,hp,fmin
from keras.utils import to_categorical
import pickle
from loadConfiguration import Configuration
from objectCreation import createImagedObjects
from trainBCNN import runOptimisingTrial,runTrial
from createModelPerformancePlots import createAccuracyPlots,createConfusionMatricies
from getObjectHierarchyLabels import getObjectHierarchyLabels
main()
| [
11748,
28686,
201,
198,
11748,
14601,
201,
198,
40539,
654,
13,
36439,
24455,
7203,
46430,
4943,
201,
198,
11748,
269,
21370,
201,
198,
11748,
299,
32152,
201,
198,
11748,
8718,
8738,
201,
198,
6738,
8718,
8738,
1330,
28945,
11,
83,
431... | 3.045977 | 174 |
from torch import cat, cos, float64, sin, stack, tensor
from torch.nn import Module, Parameter
from core.dynamics import RoboticDynamics
| [
6738,
28034,
1330,
3797,
11,
8615,
11,
12178,
2414,
11,
7813,
11,
8931,
11,
11192,
273,
198,
6738,
28034,
13,
20471,
1330,
19937,
11,
25139,
2357,
198,
6738,
4755,
13,
67,
4989,
873,
1330,
3851,
6210,
35,
4989,
873,
628,
198
] | 3.390244 | 41 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#######################################################################
# This script imports your Last.fm listening history #
# inside a MySQL or Sqlite database. #
# #
# Copyright (c) 2015-2020, Nicolas Meier #
#######################################################################
import json
import logging
import sys
from lfmconf.lfmconf import get_lastfm_conf
from lfmdb import lfmdb
from stats.stats import LastfmStats, recent_tracks, \
retrieve_total_json_tracks_from_db
from queries.inserts import get_query_insert_json_track
logging.basicConfig(
level=logging.INFO,
format=f'%(asctime)s %(levelname)s %(message)s'
)
conf = get_lastfm_conf()
user = conf['lastfm']['service']['username']
api_key = conf['lastfm']['service']['apiKey']
lastfm_stats = LastfmStats.get_lastfm_stats(user, api_key)
total_pages = lastfm_stats.nb_delta_pages()
total_plays_in_db = lastfm_stats.nb_json_tracks_in_db
logging.info('Nb page to get: %d' % total_pages)
if total_pages == 0:
logging.info('Nothing to update!')
sys.exit(1)
all_pages = []
for page_num in range(total_pages, 0, -1):
logging.info('Page %d of %d' % (page_num, total_pages))
page = recent_tracks(user, api_key, page_num)
while page.get('recenttracks') is None:
logging.info('has no tracks. Retrying!')
page = recent_tracks(user, api_key, page_num)
all_pages.append(page)
# Iterate through all pages
num_pages = len(all_pages)
for page_num, page in enumerate(all_pages):
logging.info('Page %d of %d' % (page_num + 1, num_pages))
tracks = page['recenttracks']['track']
# Remove the "nowplaying" track if found.
if tracks[0].get('@attr'):
if tracks[0]['@attr']['nowplaying'] == 'true':
tracks.pop(0)
# Get only the missing tracks.
if page_num == 0:
logging.info('Fist page')
nb_plays = lastfm_stats.nb_plays_for_first_page()
tracks = tracks[0: nb_plays]
logging.info('Getting %d plays' % nb_plays)
# On each page, iterate through all tracks
num_tracks = len(tracks)
json_tracks = []
for track_num, track in enumerate(reversed(tracks)):
logging.info('Track %d of %d' % (track_num + 1, num_tracks))
json_tracks.append(json.dumps(track))
try:
lfmdb.insert_many(get_query_insert_json_track(), json_tracks)
except Exception:
sys.exit(1)
logging.info('Done! %d rows in table json_track.' % retrieve_total_json_tracks_from_db())
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
29113,
29113,
4242,
21017,
198,
2,
770,
4226,
17944,
534,
4586,
13,
38353,
8680,
2106,
220,
220,
220,
220,
2... | 2.400359 | 1,114 |
#!/usr/bin/env python3
"""
data file
read in data
"""
from typing import Tuple, Any
import pandas as pd
import tensorflow as tf
from loguru import logger
from utils import file_path_relative
import numpy as np
from transformers import DistilBertTokenizer
NUM_ROWS_TRAIN: int = 15000
TEST_RATIO: float = 0.2
def _run_encode(texts: np.array, tokenizer: Any, maxlen: int = 512):
"""
Encoder for encoding the text into sequence of integers for transformer Input
"""
logger.info('encode')
encodings = tokenizer(
texts.tolist(),
return_token_type_ids=False,
padding='max_length',
truncation=True,
max_length=maxlen
)
return np.array(encodings['input_ids'])
def read_data_attention(strategy: tf.distribute.TPUStrategy,
max_len: int,
) -> Tuple[np.array, np.array, np.array, np.array, tf.data.Dataset, tf.data.Dataset, tf.data.Dataset, int]:
"""
read data from attention models
"""
logger.info('reading data for attention models')
# batch with number of tpu's
batch_size = 16 * strategy.num_replicas_in_sync
auto = tf.data.experimental.AUTOTUNE
# First load the tokenizer
tokenizer = DistilBertTokenizer.from_pretrained(
'distilbert-base-multilingual-cased')
train = pd.read_csv(file_path_relative('jigsaw-toxic-comment-train.csv'))
valid = pd.read_csv(file_path_relative('validation.csv'))
test = pd.read_csv(file_path_relative('test.csv'))
x_train = _run_encode(train['comment_text'].astype(str),
tokenizer, maxlen=max_len)
x_valid = _run_encode(valid['comment_text'].astype(str),
tokenizer, maxlen=max_len)
x_test = _run_encode(test['content'].astype(
str), tokenizer, maxlen=max_len)
y_train = train['toxic'].values
y_valid = valid['toxic'].values
train_dataset = (
tf.data.Dataset
.from_tensor_slices((x_train, y_train))
.repeat()
.shuffle(2048)
.batch(batch_size)
.prefetch(auto)
)
valid_dataset = (
tf.data.Dataset
.from_tensor_slices((x_valid, y_valid))
.batch(batch_size)
.cache()
.prefetch(auto)
)
test_dataset = (
tf.data.Dataset
.from_tensor_slices(x_test)
.batch(batch_size)
)
# return all datasets
return x_train, x_valid, y_train, y_valid, train_dataset, valid_dataset, \
test_dataset, batch_size
if __name__ == '__main__':
raise RuntimeError('cannot run data attention on its own')
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
37811,
198,
7890,
2393,
198,
198,
961,
287,
1366,
198,
37811,
198,
198,
6738,
19720,
1330,
309,
29291,
11,
4377,
198,
11748,
19798,
292,
355,
279,
67,
198,
11748,
11192,
273,
11125... | 2.221562 | 1,178 |
# Kratos imports
import KratosMultiphysics
import KratosMultiphysics.KratosUnittest as UnitTest
from KratosMultiphysics.WindEngineeringApplication.test_suite import SuiteFlags, TestSuite
import run_cpp_tests
# STL imports
import pathlib
def AssembleTestSuites(enable_mpi=False):
""" Populates the test suites to run.
Populates the test suites to run. At least, it should pupulate the suites:
"small", "nighlty" and "all"
Return
------
suites: A dictionary of suites
The set of suites with its test_cases added.
"""
static_suites = UnitTest.KratosSuites
# Test cases will be organized into lists first, then loaded into their
# corresponding suites all at once
local_cases = {}
for key in static_suites.keys():
local_cases[key] = []
# Glob all test cases in this application
this_directory = pathlib.Path(__file__).absolute().parent
test_loader = TestLoader()
all_tests = test_loader.discover(this_directory)
# Sort globbed test cases into lists based on their suite flags
# flags correspond to entries in KratosUnittest.TestSuites
# (small, nightly, all, validation)
#
# Cases with the 'mpi' flag are added to mpi suites as well as their corresponding normal suites.
# Cases with the 'mpi_only' flag are not added to normal suites.
for test_case in all_tests:
suite_flags = set(test_case.suite_flags)
# Check whether the test case has a flag for mpi
mpi = SuiteFlags.MPI in suite_flags
mpi_only = SuiteFlags.MPI_ONLY in suite_flags
# Don't add the test if its mpi-exclusive and mpi is not enabled
if (not enable_mpi) and mpi_only:
continue
# Remove mpi flags
if mpi:
suite_flags.remove(SuiteFlags.MPI)
if mpi_only:
suite_flags.remove(SuiteFlags.MPI_ONLY)
# Add case to the corresponding suites
for suite_flag in suite_flags:
local_cases[suite_flag.name.lower()].append(test_case)
if mpi or mpi_only:
local_cases["mpi_" + suite_flag.name.lower()].append(test_case)
# Put test in 'all' if it isn't already there
if not (SuiteFlags.ALL in suite_flags):
if not mpi_only:
local_cases["all"].append(test_case)
if mpi or mpi_only:
local_cases["mpi_all"].append(test_case)
# Load all sorted cases into the global suites
for suite_name, test_cases in local_cases.items():
static_suites[suite_name].addTests(test_cases)
return static_suites
if __name__ == "__main__":
Run(enable_mpi=False) | [
2,
509,
10366,
418,
17944,
198,
11748,
509,
10366,
418,
15205,
13323,
23154,
198,
11748,
509,
10366,
418,
15205,
13323,
23154,
13,
42,
10366,
418,
3118,
715,
395,
355,
11801,
14402,
198,
6738,
509,
10366,
418,
15205,
13323,
23154,
13,
8... | 2.527856 | 1,059 |
import re
import uuid
from copy import deepcopy
from datetime import datetime
from lxml import etree
from lxml.html import xhtml_to_html
from geoalchemy import WKTSpatialElement
from geolucidate.functions import _cleanup, _convert
from geolucidate.parser import parser_re
from cadorsfeed import db
from cadorsfeed.models import DailyReport, CadorsReport, ReportCategory
from cadorsfeed.models import Aircraft, NarrativePart, Location, LocationRef
from cadorsfeed.cadorslib.xpath_functions import extensions
from cadorsfeed.cadorslib.narrative import process_narrative, normalize_ns
from cadorsfeed.cadorslib.locations import LocationStore
from cadorsfeed.aerodb import aerodromes_re, lookup
NSMAP = {'h': 'http://www.w3.org/1999/xhtml',
'pyf': 'urn:uuid:fb23f64b-3c54-4009-b64d-cc411bd446dd',
'a': 'http://www.w3.org/2005/Atom',
'geo': 'http://www.w3.org/2003/01/geo/wgs84_pos#',
'aero':'urn:uuid:1469bf5a-50a9-4c9b-813c-af19f9d6824d'}
| [
11748,
302,
198,
11748,
334,
27112,
198,
6738,
4866,
1330,
2769,
30073,
198,
6738,
4818,
8079,
1330,
4818,
8079,
198,
198,
6738,
300,
19875,
1330,
2123,
631,
198,
6738,
300,
19875,
13,
6494,
1330,
2124,
6494,
62,
1462,
62,
6494,
198,
... | 2.54522 | 387 |
from sstcam_sandbox import get_checs
from TargetCalibSB.pedestal import PedestalTargetCalib
from TargetCalibSB import get_cell_ids_for_waveform
from CHECLabPy.core.io import TIOReader
from tqdm import tqdm
from glob import glob
if __name__ == '__main__':
main()
| [
6738,
264,
301,
20991,
62,
38142,
3524,
1330,
651,
62,
2395,
6359,
198,
6738,
12744,
9771,
571,
16811,
13,
9124,
395,
282,
1330,
13457,
395,
282,
21745,
9771,
571,
198,
6738,
12744,
9771,
571,
16811,
1330,
651,
62,
3846,
62,
2340,
62,... | 2.842105 | 95 |