content stringlengths 1 1.04M | input_ids listlengths 1 774k | ratio_char_token float64 0.38 22.9 | token_count int64 1 774k |
|---|---|---|---|
from django.core import serializers as django_serializers
from rest_framework import serializers
from ..contracts.models import (
CollectionArtifact,
CollectionJob,
Contract,
Contractor,
Document,
Entity,
Service,
ServiceGroup,
)
from ..contracts.utils import get_current_fiscal_year
INITIAL_FISCAL_YEAR = 2016
CURRENT_FISCAL_YEAR = get_current_fiscal_year()
FISCAL_YEAR_CHOICES = [
(year, str(year)) for year in range(INITIAL_FISCAL_YEAR, CURRENT_FISCAL_YEAR)
]
| [
6738,
42625,
14208,
13,
7295,
1330,
11389,
11341,
355,
42625,
14208,
62,
46911,
11341,
198,
6738,
1334,
62,
30604,
1330,
11389,
11341,
198,
198,
6738,
11485,
28484,
82,
13,
27530,
1330,
357,
198,
220,
220,
220,
12251,
8001,
29660,
11,
1... | 2.626263 | 198 |
# The purpose of this notebook is to train a **Logistic Regression** model using Keras to classify the tweets' sentiment as positive or negative.
import numpy as np
import pandas as pd
import os
import io
random_seed=1
np.random.seed(random_seed)
import tensorflow as tf
import keras
from keras import backend as K
from keras.models import Model
from keras.layers import Input, merge
from keras.layers.core import Lambda
from keras import optimizers
from keras import regularizers
from keras.models import load_model
from keras.callbacks import ModelCheckpoint
from keras.utils.np_utils import to_categorical
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils.np_utils import to_categorical
from keras.models import Sequential
from keras.layers import Input, Dense, Flatten, Embedding , Activation
from nltk.tokenize import TweetTokenizer
import re
import num2words
from timeit import default_timer as timer
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import KFold
from sklearn.externals import joblib
# Path of the training file'
base_path = os.environ['HOMEPATH']
data_folder='data'
data_dir = os.path.join(base_path, data_folder)
# Path of the word vectors
embedding_folder = os.path.join(base_path, 'vectors')
vectors_file = os.path.join(embedding_folder, 'embeddings_Word2Vec_Basic.tsv')
model_identifier='evaluation_word2vec_logistic'
models_dir = os.path.join(base_path, 'model')
if not os.path.exists(models_dir):
os.makedirs(models_dir)
# # Data Preprocessing
pos_emoticons=["(^.^)","(^-^)","(^_^)","(^_~)","(^3^)","(^o^)","(~_^)","*)",":)",":*",":-*",":]",":^)",":}",
":>",":3",":b",":-b",":c)",":D",":-D",":O",":-O",":o)",":p",":-p",":P",":-P",":ร",":-ร",":X",
":-X",";)",";-)",";]",";D","^)","^.~","_)m"," ~.^","<=8","<3","<333","=)","=///=","=]","=^_^=",
"=<_<=","=>.<="," =>.>="," =3","=D","=p","0-0","0w0","8D","8O","B)","C:","d'-'","d(>w<)b",":-)",
"d^_^b","qB-)","X3","xD","XD","XP","สโฟส","โค","๐","๐","๐","๐","๐","๐","๐","๐","๐",
"๐","๐","๐","๐","๐","๐","๐ป","๐","๐","๐","โบ","๐","๐","๐","๐","๐","๐","๐",
"๐","๐","๐","๐","๐","๐ฎ","๐ธ","๐น","๐บ","๐ป","๐ผ","๐"]
neg_emoticons=["--!--","(,_,)","(-.-)","(._.)","(;.;)9","(>.<)","(>_<)","(>_>)","(ยฌ_ยฌ)","(X_X)",":&",":(",":'(",
":-(",":-/",":-@[1]",":[",":\\",":{",":<",":-9",":c",":S",";(",";*(",";_;","^>_>^","^o)","_|_",
"`_ยด","</3","<=3","=/","=\\",">:(",">:-(","๐","โน๏ธ","๐","๐","๐","๐","๐","๐","๐","๐",
"๐ ","๐ก","๐ข","๐ฃ","๐ค","๐ฅ","๐ฆ","๐ง","๐จ","๐ฉ","๐ช","๐ซ","๐ฌ","๐ญ","๐ฏ","๐ฐ","๐ฑ","๐ฒ",
"๐ณ","๐ด","๐ท","๐พ","๐ฟ","๐","๐","๐"]
# Emails
emailsRegex=re.compile(r'[\w\.-]+@[\w\.-]+')
# Mentions
userMentionsRegex=re.compile(r'(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9]+)')
#Urls
urlsRegex=re.compile('r(f|ht)(tp)(s?)(://)(.*)[.|/][^ ]+') # It may not be handling all the cases like t.co without http
#Numerics
numsRegex=re.compile(r"\b\d+\b")
punctuationNotEmoticonsRegex=re.compile(r'(?<=\w)[^\s\w](?![^\s\w])')
emoticonsDict = {} # define desired replacements here
for i,each in enumerate(pos_emoticons):
emoticonsDict[each]=' POS_EMOTICON_'+num2words.num2words(i).upper()+' '
for i,each in enumerate(neg_emoticons):
emoticonsDict[each]=' NEG_EMOTICON_'+num2words.num2words(i).upper()+' '
# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in emoticonsDict.items())
emoticonsPattern = re.compile("|".join(rep.keys()))
def read_data(filename):
"""
Read the raw tweet data from a file. Replace Emails etc with special tokens
"""
with open(filename, 'r') as f:
all_lines=f.readlines()
padded_lines=[]
for line in all_lines:
line = emoticonsPattern.sub(lambda m: rep[re.escape(m.group(0))], line.lower().strip())
line = userMentionsRegex.sub(' USER ', line )
line = emailsRegex.sub(' EMAIL ', line )
line=urlsRegex.sub(' URL ', line)
line=numsRegex.sub(' NUM ',line)
line=punctuationNotEmoticonsRegex.sub(' PUN ',line)
line=re.sub(r'(.)\1{2,}', r'\1\1',line)
words_tokens=[token for token in TweetTokenizer().tokenize(line)]
line= ' '.join(token for token in words_tokens )
padded_lines.append(line)
return padded_lines
def read_labels(filename):
""" read the tweet labels from the file
"""
arr= np.genfromtxt(filename, delimiter='\n')
arr[arr==4]=1 # Encode the positive category as 1
return arr
# # Convert Word Vectors to Sentence Vectors
# The embeddings generated by both SSWE and Word2Vec algorithms are at word level but as we are using the sentences as the input, the word embeddings need to be converted to the sentence level embeddings. We are converting the word embeddings into sentence embeddings by using the approach in the original SSWE paper i.e. stacking the word vectors into a matrix and applying min, max and average operations on each of the columns of the word vectors matrix.
def load_word_embedding(vectors_file):
""" Load the word vectors"""
vectors= np.genfromtxt(vectors_file, delimiter='\t', comments='#--#',dtype=None,
names=['Word']+['EV{}'.format(i) for i in range(1,51)])#51 is embedding length + 1, change accoridngly if the size of embedding is not 50
vectors_dc={}
for x in vectors:
vectors_dc[x['Word'].decode('utf-8','ignore')]=[float(x[each]) for each in ['EV{}'.format(i) for i in range(1,51)]]#51 is embedding length + 1, change accoridngly if the size of embedding is not 50
return vectors_dc
def get_sentence_embedding(text_data, vectors_dc):
""" This function converts the vectors of all the words in a sentence into sentence level vectors"""
""" This function stacks up all the words vectors and then applies min, max and average operations over the stacked vectors"""
""" If the size of the words vectors is n, then the size of the sentence vectors would be 3*n"""
sentence_vectors=[]
for sen in text_data:
tokens=sen.split(' ')
current_vector=np.array([vectors_dc[tokens[0]] if tokens[0] in vectors_dc else vectors_dc['<UNK>']])
for word in tokens[1:]:
if word in vectors_dc:
current_vector=np.vstack([current_vector,vectors_dc[word]])
else:
current_vector=np.vstack([current_vector,vectors_dc['<UNK>']])
min_max_mean=np.hstack([current_vector.min(axis=0),current_vector.max(axis=0),current_vector.mean(axis=0)])
sentence_vectors.append(min_max_mean)
return sentence_vectors
# # Model Training
batch_size = 1028*6 # Batch Size should be changed according to the system specifications to have better utilization of GPU
nb_epoch = 30
# # Main
print ('Step 1: Loading Training data')
train_texts=read_data(data_dir+'/training_text.csv')
train_labels=read_labels(data_dir+'/training_label.csv')
print ("Step 2: Load Word Vectors")
vectors_dc=load_word_embedding(vectors_file)
len(vectors_dc)
print ("Step 3: Converting the word vectors to sentence vectors")
train_sentence_vectors=get_sentence_embedding(train_texts,vectors_dc)
print (" Encoding the data")
train_x=train_sentence_vectors
train_y=train_labels
train_x=np.array(train_x).astype('float32')
train_y=np.array(train_y)
print (len(train_sentence_vectors), len(train_labels), len(train_texts))
print ('Step 4: Logistic regression model using Keras')
best_model=cv_estimate(3,train_x, train_y)
print ("Step 5: Saving the model")
best_model.save(models_dir+'//'+model_identifier) | [
2,
383,
4007,
286,
428,
20922,
318,
284,
4512,
257,
12429,
11187,
2569,
3310,
2234,
1174,
2746,
1262,
17337,
292,
284,
36509,
262,
12665,
6,
15598,
355,
3967,
393,
4633,
13,
198,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
19798,
... | 2.324554 | 3,417 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import sys
import os
import timeit
import re
from pprint import pprint
import copy
# argparse for information
parser = argparse.ArgumentParser()
# parser.add_argument("-d", "--directory", help="input directory of the Pfam family files")
parser.add_argument("-e", "--energy", help="input energy profile directory")
# parser.add_argument("-p", "--pdbmap", help="pdbmap location")
args = parser.parse_args()
# sanity check
if not len(sys.argv) > 1:
print "this script takes a folder of energy files and analyzes them"
parser.print_help()
sys.exit(0)
# inserts a key value pair into the dict, or adds the value if the key exists
# ------------------------------------------------- main script ------------------------------------------------------ #
start_time = timeit.default_timer()
# initialize the dict
contact_count_dict = {'A': {}, 'C': {}, 'D': {}, 'E': {}, 'F': {}, 'G': {}, 'H': {}, 'I': {}, 'K': {}, 'L': {},
'M': {}, 'N': {}, 'P': {}, 'Q': {}, 'R': {}, 'S': {}, 'T': {}, 'U': {}, 'V': {}, 'W': {}, 'Y': {}}
sub_contact_count_dict = {'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 0,
'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'U': 0, 'V': 0, 'W': 0, 'Y': 0}
for key, vale in contact_count_dict.iteritems():
contact_count_dict[key] = copy.deepcopy(sub_contact_count_dict)
continue_counter = 0
print "started!"
for dirpath, dir, files in os.walk(top=args.energy):
for energy_file in files:
print energy_file
amino_contacts_dict = {}
amino_dict_with_chains = {}
amino_seq = ""
id_list = []
with open(args.energy + "/" + energy_file, 'r') as energy_file_handle:
counter = 0
chain = ""
prev_chain = ""
for line in energy_file_handle:
if line.startswith('ENGY'):
chain = line.split("\t")[1]
if bool(re.search(r'\d', chain)):
print "ERROR: CHAIN is a Number, ", chain
continue
if prev_chain != "" and prev_chain != chain:
counter = 0
amino_dict_with_chains[prev_chain] = amino_seq
amino_seq = ""
amino = line.split("\t")[3]
contacts = line.split("\t")[6].replace(" ", "").rstrip()
id = str(counter) + chain
id_list.append(id)
insert_into_data_structure(id, contacts, amino_contacts_dict)
amino_seq += amino
counter += 1
prev_chain = chain
# one last time for adding the last chain aa_seq to the dict, or the first if only one chain
amino_dict_with_chains[prev_chain] = amino_seq
# iterate over data and count
for id in id_list:
counter = int(re.split(r'(\d+)', id)[1])
chain = re.split(r'(\d+)', id)[-1]
contacts = amino_contacts_dict[id]
if (len(contacts) != len(amino_seq)):
print "ERROR: contact length is NOT equal to the sequence length!"
continue_counter += 1
continue
amino_seq = amino_dict_with_chains[chain]
amino_now = amino_seq[counter]
contact_index = 0
for contact, amino_in_loop in zip(contacts, amino_seq):
# count all contacts except self contacts
if contact == "1" and contact_index != counter:
contact_count_dict[amino_now][amino_in_loop] += 1
contact_index += 1
print timeit.default_timer() - start_time
print "printing DICT: "
for key, value in contact_count_dict.iteritems():
print key
print contact_count_dict[key]
for key, value in contact_count_dict.iteritems():
for key2, value2 in contact_count_dict[key].iteritems():
sys.stdout.write(str(value2) + ",")
print ""
print "skipped ", continue_counter, " lines of EPs"
| [
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,
1822,
29572,
198,
11748,
25064,
198,
11748,
28686,
198,
11748,
640,
270,
198,
11748,
302,
198,
6738,
279,
4... | 2.111888 | 2,002 |
#!/usr/bin/env python3
# -*- coding: utf-8; -*-
#
# Copyright (c) 2019 รlan Crรญstoffer
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import bson.json_util as json
from bson.objectid import ObjectId
from flask import Flask, request
from flask_cors import CORS
import cups
from database import Database
app = Flask(__name__)
CORS(app)
db = Database()
crud('group', 'manage_users')
crud('policy', 'manage_users')
crud('user', 'manage_users')
crud('admin', 'manage_admins')
crud('quota', 'manage_quotas')
@app.after_request
@app.route('/auth', methods=['POST'])
def authenticate():
"""
Authenticates the user.
Should be called with a POST request containing the following body:
{
username: string
password: string
}
@returns:
On success, HTTP 200 Ok and body:
{
'user': User,
'token': string
}
On failure, HTTP 403 Unauthorized and body:
{}
"""
username = request.json.get('username', '')
password = request.json.get('password', '')
user, token = db.auth_admin(username, password)
if user:
return json.dumps({'user': user, 'token': token})
user, token = db.auth_user(username, password)
if user:
return json.dumps({'user': user, 'token': token})
return '{}', 403
@app.route('/set-own-password', methods=['POST'])
def set_own_password():
"""
Change your own password.
{
password: string
}
@returns:
On success, HTTP 200 Ok and body:
{}
On failure, HTTP 403 Unauthorized and body:
{}
"""
user = verify_token()
if not user:
return '{}', 403
user['password'] = request.json.get('password', '')
if 'permissions' in user: # admin user
db.admin_set(user)
else: # os user
db.user_set(user)
return '{}'
@app.route('/printers', methods=['GET'])
def printers():
"""
List printers
@returns:
On success, HTTP 200 Ok and body:
string[]
On failure, HTTP 403 Unauthorized and body:
{}
"""
user = verify_token()
if not user or 'manage_users' not in user['permissions']:
return '{}', 403
conn = cups.Connection()
ps = conn.getPrinters()
ps = [{'id': k, 'name': v['printer-info']} or k for k, v in ps.items()]
return json.dumps(ps)
@app.route('/quota/get', methods=['GET'])
@app.route('/job/get', methods=['GET'])
@app.route('/job', methods=['GET'])
@app.route('/report', methods=['GET'])
def verify_token():
"""
Verifies the token sent as a HTTP Authorization header.
"""
try:
authorization = request.headers.get('Authorization')
token = authorization.split(' ')[-1]
return db.verify_token(token)
except Exception as e:
return
if __name__ == "__main__":
app.run(host='0.0.0.0')
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
26,
532,
9,
12,
198,
2,
198,
2,
15069,
357,
66,
8,
13130,
6184,
223,
9620,
3864,
8836,
301,
47895,
198,
2,
198,
2,
2448,
3411,
... | 2.68107 | 1,458 |
# coding: utf-8
#
# Copyright (c) 2018, Dylan Perry <dylan.perry@gmail.com>. All rights reserved.
# Licensed under BSD 2-Clause License. See LICENSE file for full license.
from pytest import mark
from advent.input import text
from advent.inventory_management_system import is_letter_repeated_2_3_times, part1, part2, common_characters
test_is_letter_repeated_2_3_times_data = [
["abcdef", (0, 0)],
["bababc", (1, 1)],
["abbcde", (1, 0)],
["abcccd", (0, 1)],
["aabcdd", (1, 0)],
["abcdee", (1, 0)],
["ababab", (0, 1)],
]
@mark.parametrize("box_id, count", test_is_letter_repeated_2_3_times_data)
test_part1_data = """
abcdef
bababc
abbcde
abcccd
aabcdd
abcdee
ababab
"""
test_part2_data = """
abcde
fghij
klmno
pqrst
fguij
axcye
wvxyz
"""
test_common_characters_data = [
["fguij", "fghij", "fgij"],
["abcde", "pqrst", ""],
["abcde", "axcye", "ace"],
]
@mark.parametrize("this, that, common", test_common_characters_data)
| [
2,
19617,
25,
3384,
69,
12,
23,
198,
2,
198,
2,
15069,
357,
66,
8,
2864,
11,
21371,
14105,
1279,
67,
18554,
13,
525,
563,
31,
14816,
13,
785,
28401,
1439,
2489,
10395,
13,
198,
2,
49962,
739,
347,
10305,
362,
12,
2601,
682,
1378... | 2.253456 | 434 |
from codecs import open
import re
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
exec(open('what3words/version.py').read())
with open('requirements.txt') as f:
requires = f.read().splitlines()
setup(
name='what3words',
version=__version__,
author='What3Words',
author_email='support@what3words.com',
url='https://github.com/what3words/w3w-python-wrapper',
description='What3words API wrapper library',
license='MIT',
packages=['what3words'],
package_dir={'what3words': 'what3words'},
install_requires=requires,
keywords='what3words geocoder',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries',
],
)
| [
6738,
40481,
82,
1330,
1280,
198,
11748,
302,
198,
198,
28311,
25,
198,
220,
220,
220,
422,
900,
37623,
10141,
1330,
9058,
198,
16341,
17267,
12331,
25,
198,
220,
220,
220,
422,
1233,
26791,
13,
7295,
1330,
9058,
198,
198,
18558,
7,
... | 2.77551 | 441 |
"""
CEASIOMpy: Conceptual Aircraft Design Software
Developed for CFS ENGINEERING, 1015 Lausanne, Switzerland
Balance main module for preliminary design on conventional
aircraft, it evaluates:
* the centre of gravity;
* the Ixx, Iyy, Izz moments of inertia.
WARNING: The code deletes the ToolOutput folder and recreates
it at the start of each run.
The code also removes the toolinput file from the ToolInput
folder after copying it into the ToolOutput folder
as ToolOutput.xml
Python version: >=3.6
| Author : Stefano Piccini
| Date of creation: 2018-09-27
| Last modifiction: 2020-07-09 (AJ)
"""
#=============================================================================
# IMPORTS
#=============================================================================
import os
import shutil
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from ceasiompy.utils.InputClasses.Unconventional import balanceuncclass
from ceasiompy.utils.InputClasses.Unconventional import weightuncclass
from ceasiompy.utils.InputClasses.Unconventional import engineclass
from ceasiompy.BalanceUnconventional.func.Cog.unccog import unc_center_of_gravity
from ceasiompy.BalanceUnconventional.func.Cog.unccog import bwb_center_of_gravity
from ceasiompy.BalanceUnconventional.func.Inertia import uncinertia
from ceasiompy.BalanceUnconventional.func.AoutFunc import outputbalancegen
from ceasiompy.BalanceUnconventional.func.AoutFunc import cpacsbalanceupdate
from ceasiompy.BalanceUnconventional.func.AinFunc import getdatafromcpacs
from ceasiompy.utils.cpacsfunctions import aircraft_name
from ceasiompy.utils.WB.UncGeometry import uncgeomanalysis
import ceasiompy.utils.moduleinterfaces as mi
from ceasiompy.utils.ceasiomlogger import get_logger
log = get_logger(__file__.split('.')[0])
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
#=============================================================================
# CLASSES
#=============================================================================
"""All classes are defined inside the classes folder and into the
InputClasses/Uconventional folder"""
#=============================================================================
# FUNCTIONS
#=============================================================================
def get_balance_unc_estimations(cpacs_path, cpacs_out_path):
"""Function to estimate inertia value and CoF of an unconventional aircraft.
Function 'get_balance_unc_estimations' ...
Source:
* Reference paper or book, with author and date, see ...
Args:
cpacs_path (str): Path to CPACS file
cpacs_out_path (str):Path to CPACS output file
"""
# Removing and recreating the ToolOutput folder.
if os.path.exists('ToolOutput'):
shutil.rmtree('ToolOutput')
os.makedirs('ToolOutput')
if not os.path.exists(cpacs_path):
raise ValueError ('No "ToolInput.xml" file in the ToolInput folder.')
name = aircraft_name(cpacs_path)
shutil.copyfile(cpacs_path, cpacs_out_path) # TODO: shoud not be like that
newpath = 'ToolOutput/' + name
if not os.path.exists(newpath):
os.makedirs(newpath)
bout = balanceuncclass.BalanceOutputs()
# BALANCE ANALSIS INPUTS
bi = balanceuncclass.BalanceInputs()
mw = balanceuncclass.MassesWeights()
ui = weightuncclass.UserInputs()
ed = engineclass.EngineData()
adui = weightuncclass.AdvancedInputs()
(mw, ed) = getdatafromcpacs.get_data(ui, bi, mw, ed, cpacs_out_path)
# GEOMETRY ANALYSIS
(fus_nb, w_nb) = uncgeomanalysis.get_number_of_parts(cpacs_path)
if not w_nb:
log.warning('Aircraft does not have wings')
raise Exception('Aircraft does not have wings')
elif not fus_nb:
(awg, wing_nodes) =\
uncgeomanalysis.no_fuse_geom_analysis(cpacs_path, ui.FLOORS_NB, \
w_nb, ui.H_LIM_CABIN, \
ui.FUEL_ON_CABIN, name, \
ed.TURBOPROP)
else:
log.info('Fuselage detected')
log.info('Number of fuselage: ' + str(int(fus_nb)))
# Minimum fuselage segment height to be a cabin segment.
h_min = ui.FLOORS_NB * ui.H_LIM_CABIN
(afg, awg) = uncgeomanalysis.with_fuse_geom_analysis(cpacs_path, \
fus_nb, w_nb, h_min, adui, ed.TURBOPROP, ui.F_FUEL, name)
ui = getdatafromcpacs.get_user_fuel(fus_nb, ui, cpacs_out_path)
# BALANCE ANALYSIS
log.info('----- Generating output text file -----')
log.info('---- Starting the balance analysis ----')
log.info('---- Aircraft: ' + name)
# CENTER OF GRAVITY
if not fus_nb:
(bout, airplane_centers_segs) =\
bwb_center_of_gravity(awg, bout, ui, bi, mw, ed)
else:
(bout, airplane_centers_segs) =\
unc_center_of_gravity(awg, afg, bout, ui, bi, mw, ed)
# MOMENT OF INERTIA
if not fus_nb:
(bout, wx, wy, wz) = uncinertia.bwb_inertia_eval(awg, bout, bi, mw, ed, cpacs_out_path)
else:
(bout, fx, fy, fz, wx, wy, wz)\
= uncinertia.unc_inertia_eval(awg, afg, bout, bi, mw, ed, cpacs_out_path)
# OUTPUT WRITING
log.info('----- Generating output text file -----')
outputbalancegen.output_txt(bout, mw, bi, ed, name)
# CPACS WRITING
cpacsbalanceupdate.cpacs_mbd_update(bout, mw, bi, np.sum(mw.ms_zpm), cpacs_out_path)
# PLOTS
log.info('--- Generating aircraft center of gravity plot (.png) ---')
if not fus_nb:
outputbalancegen.aircraft_cog_bwb_plot(bout.center_of_gravity, bi, ed, awg, name)
else:
outputbalancegen.aircraft_cog_unc_plot(bout.center_of_gravity, bi, ed, afg, awg, name)
# Aircraft Nodes
#log.info('--- Generating aircraft nodes plot (.png) ---')
#if not fus_nb:
#outputbalancegen.aircraft_nodes_bwb_plot(wx, wy, wz, name)
#else:
#outputbalancegen.aircraft_nodes_unc_plot(fx, fy, fz, wx, wy, wz, name)
# Show plots
plt.show()
# LOG WRITING
log.info('---- Center of Gravity coordinates ----')
log.info('------ Max Payload configuration ------')
log.info('[x, y, z]: ' + str(bout.center_of_gravity))
log.info('---------------------------------------')
log.info('------- Zero Fuel configuration -------')
log.info('[x, y, z]: ' + str(bout.cg_zfm))
log.info('---------------------------------------')
log.info('----- Zero Payload configuration ------')
log.info('[x, y, z]: ' + str(bout.cg_zpm))
log.info('---------------------------------------')
log.info('---------- OEM configuration ----------')
log.info('[x, y, z]: ' + str(bout.cg_oem))
log.info('---------------------------------------')
if bi.USER_CASE:
log.info('---------- User configuration ---------')
log.info('Chosen Fuel Percentage: ' + str(bi.F_PERC))
log.info('Chosen Payload Percentage: ' + str(bi.P_PERC))
log.info('[x, y, z]: ' + str(bout.cg_user))
log.info('---------------------------------------')
log.info('---------- Inertia Evaluation ---------')
if bi.USER_EN_PLACEMENT:
log.info('------------ Engine Inertia -----------')
log.info('Roll moment, Ixx [kgm^2]: ' + str(int(round(bout.Ixxen))))
log.info('Pitch moment, Iyy [kgm^2]: ' + str(int(round(bout.Iyyen))))
log.info('Yaw moment, Izz [kgm^2]: ' + str(int(round(bout.Izzen))))
log.info('Ixy moment [kgm^2]: ' + str(int(round(bout.Ixyen))))
log.info('Iyz moment [kgm^2]: ' + str(int(round(bout.Iyzen))))
log.info('Ixz moment [kgm^2]: ' + str(int(round(bout.Ixzen))))
log.info('---------------------------------------')
log.info('--------- Lumped mass Inertia ---------')
log.info('------ Max Payload configuration ------')
log.info('Roll moment, Ixx [kgm^2]: ' + str(bout.Ixx_lump))
log.info('Pitch moment, Iyy [kgm^2]: ' + str(bout.Iyy_lump))
log.info('Yaw moment, Izz [kgm^2]: ' + str(bout.Izz_lump))
log.info('Ixy moment [kgm^2]: ' + str(bout.Ixy_lump))
log.info('Iyz moment [kgm^2]: ' + str(bout.Iyz_lump))
log.info('Ixz moment [kgm^2]: ' + str(bout.Ixz_lump))
log.info('---------------------------------------')
log.info('------- Zero Fuel configuration -------')
log.info('Roll moment, Ixx [kgm^2]: ' + str(bout.Ixx_lump_zfm))
log.info('Pitch moment, Iyy [kgm^2]: ' + str(bout.Iyy_lump_zfm))
log.info('Yaw moment, Izz [kgm^2]: ' + str(bout.Izz_lump_zfm))
log.info('Ixy moment [kgm^2]: ' + str(bout.Ixy_lump_zfm))
log.info('Iyz moment [kgm^2]: ' + str(bout.Iyz_lump_zfm))
log.info('Ixz moment [kgm^2]: ' + str(bout.Ixz_lump_zfm))
log.info('---------------------------------------')
log.info('------ Zero Payload configuration -----')
log.info('Roll moment, Ixx [kgm^2]: ' + str(bout.Ixx_lump_zpm))
log.info('Pitch moment, Iyy [kgm^2]: ' + str(bout.Iyy_lump_zpm))
log.info('Yaw moment, Izz [kgm^2]: ' + str(bout.Izz_lump_zpm))
log.info('Ixy moment [kgm^2]: ' + str(bout.Ixy_lump_zpm))
log.info('Iyz moment [kgm^2]: ' + str(bout.Iyz_lump_zpm))
log.info('Ixz moment [kgm^2]: ' + str(bout.Ixz_lump_zpm))
log.info('---------------------------------------')
log.info('---------- OEM configuration ----------')
log.info('Roll moment, Ixx [kgm^2]: ' + str(bout.Ixx_lump_oem))
log.info('Pitch moment, Iyy [kgm^2]: ' + str(bout.Iyy_lump_oem))
log.info('Yaw moment, Izz [kgm^2]: ' + str(bout.Izz_lump_oem))
log.info('Ixy moment [kgm^2]: ' + str(bout.Ixy_lump_oem))
log.info('Iyz moment [kgm^2]: ' + str(bout.Iyz_lump_oem))
log.info('Ixz moment [kgm^2]: ' + str(bout.Ixz_lump_oem))
log.info('---------------------------------------')
if bi.USER_CASE:
log.info('---------- User configuration ---------')
log.info('Roll moment, Ixx [kgm^2]: ' + str(bout.Ixx_lump_user))
log.info('Pitch moment, Iyy [kgm^2]: ' + str(bout.Iyy_lump_user))
log.info('Yaw moment, Izz [kgm^2]: ' + str(bout.Izz_lump_user))
log.info('Ixy moment [kgm^2]: ' + str(bout.Ixy_lump_user))
log.info('Iyz moment [kgm^2]: ' + str(bout.Iyz_lump_user))
log.info('Ixz moment [kgm^2]: ' + str(bout.Ixz_lump_user))
log.info('---------------------------------------')
log.info('## Uconventional Balance analysis succesfuly completed ##')
#=============================================================================
# MAIN
#=============================================================================
if __name__ == '__main__':
log.info('----- Start of ' + os.path.basename(__file__) + ' -----')
cpacs_path = os.path.join(MODULE_DIR,'ToolInput','ToolInput.xml')
cpacs_out_path = os.path.join(MODULE_DIR,'ToolOutput','ToolOutput.xml')
mi.check_cpacs_input_requirements(cpacs_path)
get_balance_unc_estimations(cpacs_path,cpacs_out_path)
log.info('----- End of ' + os.path.basename(__file__) + ' -----')
| [
37811,
198,
5222,
1921,
40,
2662,
9078,
25,
26097,
723,
30767,
8495,
10442,
198,
198,
19246,
276,
329,
327,
10652,
36924,
8881,
1137,
2751,
11,
8949,
20,
4689,
385,
21952,
11,
14679,
198,
198,
45866,
1388,
8265,
329,
15223,
1486,
319,
... | 2.450044 | 4,544 |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This script is used to synthesize generated parts of this library."""
import re
import synthtool as s
from synthtool import gcp
from synthtool.languages import python
common = gcp.CommonTemplates()
default_version = "v1"
for library in s.get_staging_dirs(default_version):
# Fix docstring with regex pattern that breaks docgen
s.replace(library / "google/**/*client.py", "(/\^.*\$/)", "``\g<1>``")
# Fix more regex in docstrings
s.replace(library / "google/**/types/*.py",
"(regex\s+)(/.*?/)\.",
"\g<1>``\g<2>``.",
flags=re.MULTILINE | re.DOTALL,
)
# Fix docstring with JSON example by wrapping with backticks
s.replace(library / "google/**/types/recommendation.py",
"( - Example: )(\{.*?\})",
"\g<1>``\g<2>``",
flags=re.MULTILINE | re.DOTALL,
)
s.move(library, excludes=["docs/index.rst", "README.rst", "setup.py"])
s.remove_staging_dirs()
# ----------------------------------------------------------------------------
# Add templated files
# ----------------------------------------------------------------------------
templated_files = common.py_library(
samples=False, # set to True only if there are samples
microgenerator=True,
cov_level=98,
)
s.move(
templated_files, excludes=[".coveragerc"]
) # microgenerator has a good .coveragerc file
python.py_samples(skip_readmes=True)
s.shell.run(["nox", "-s", "blacken"], hide_output=False)
| [
2,
15069,
13130,
3012,
11419,
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,
921,
743,
733... | 2.978038 | 683 |
# Copyright 2014 PerfKitBenchmarker Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Runs HPC Challenge.
Homepage: http://icl.cs.utk.edu/hpcc/
Most of the configuration of the HPC-Challenge revolves around HPL, the rest of
the HPCC piggybacks upon the HPL configration.
Homepage: http://www.netlib.org/benchmark/hpl/
HPL requires a BLAS library (Basic Linear Algebra Subprograms)
OpenBlas: http://www.openblas.net/
HPL also requires a MPI (Message Passing Interface) Library
OpenMPI: http://www.open-mpi.org/
MPI needs to be configured:
Configuring MPI:
http://techtinkering.com/2009/12/02/setting-up-a-beowulf-cluster-using-open-mpi-on-linux/
Once HPL is built the configuration file must be created:
Configuring HPL.dat:
http://www.advancedclustering.com/faq/how-do-i-tune-my-hpldat-file.html
http://www.netlib.org/benchmark/hpl/faqs.html
"""
import logging
import math
import re
from perfkitbenchmarker import configs
from perfkitbenchmarker import data
from perfkitbenchmarker import flags
from perfkitbenchmarker import regex_util
from perfkitbenchmarker import sample
from perfkitbenchmarker import vm_util
from perfkitbenchmarker.linux_packages import hpcc
FLAGS = flags.FLAGS
HPCCINF_FILE = 'hpccinf.txt'
MACHINEFILE = 'machinefile'
BLOCK_SIZE = 192
STREAM_METRICS = ['Copy', 'Scale', 'Add', 'Triad']
BENCHMARK_NAME = 'hpcc'
BENCHMARK_CONFIG = """
hpcc:
description: Runs HPCC. Specify the number of VMs with --num_vms
vm_groups:
default:
vm_spec: *default_single_core
vm_count: null
"""
flags.DEFINE_integer('memory_size_mb',
None,
'The amount of memory in MB on each machine to use. By '
'default it will use the entire system\'s memory.')
def CheckPrerequisites():
"""Verifies that the required resources are present.
Raises:
perfkitbenchmarker.data.ResourceNotFound: On missing resource.
"""
data.ResourcePath(HPCCINF_FILE)
def CreateMachineFile(vms):
"""Create a file with the IP of each machine in the cluster on its own line.
Args:
vms: The list of vms which will be in the cluster.
"""
with vm_util.NamedTemporaryFile() as machine_file:
master_vm = vms[0]
machine_file.write('localhost slots=%d\n' % master_vm.num_cpus)
for vm in vms[1:]:
machine_file.write('%s slots=%d\n' % (vm.internal_ip,
vm.num_cpus))
machine_file.close()
master_vm.PushFile(machine_file.name, MACHINEFILE)
def CreateHpccinf(vm, benchmark_spec):
"""Creates the HPCC input file."""
num_vms = len(benchmark_spec.vms)
if FLAGS.memory_size_mb:
total_memory = FLAGS.memory_size_mb * 1024 * 1024 * num_vms
else:
stdout, _ = vm.RemoteCommand("free | sed -n 3p | awk {'print $4'}")
available_memory = int(stdout)
total_memory = available_memory * 1024 * num_vms
total_cpus = vm.num_cpus * num_vms
block_size = BLOCK_SIZE
# Finds a problem size that will fit in memory and is a multiple of the
# block size.
base_problem_size = math.sqrt(total_memory * .1)
blocks = int(base_problem_size / block_size)
blocks = blocks if (blocks % 2) == 0 else blocks - 1
problem_size = block_size * blocks
# Makes the grid as 'square' as possible, with rows < columns
sqrt_cpus = int(math.sqrt(total_cpus)) + 1
num_rows = 0
num_columns = 0
for i in reversed(range(sqrt_cpus)):
if total_cpus % i == 0:
num_rows = i
num_columns = total_cpus / i
break
file_path = data.ResourcePath(HPCCINF_FILE)
vm.PushFile(file_path, HPCCINF_FILE)
sed_cmd = (('sed -i -e "s/problem_size/%s/" -e "s/block_size/%s/" '
'-e "s/rows/%s/" -e "s/columns/%s/" %s') %
(problem_size, block_size, num_rows, num_columns, HPCCINF_FILE))
vm.RemoteCommand(sed_cmd)
def PrepareHpcc(vm):
"""Builds HPCC on a single vm."""
logging.info('Building HPCC on %s', vm)
vm.Install('hpcc')
def Prepare(benchmark_spec):
"""Install HPCC on the target vms.
Args:
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark.
"""
vms = benchmark_spec.vms
master_vm = vms[0]
PrepareHpcc(master_vm)
CreateHpccinf(master_vm, benchmark_spec)
CreateMachineFile(vms)
master_vm.RemoteCommand('cp %s/hpcc hpcc' % hpcc.HPCC_DIR)
for vm in vms[1:]:
vm.Install('fortran')
master_vm.MoveFile(vm, 'hpcc', 'hpcc')
master_vm.MoveFile(vm, '/usr/bin/orted', 'orted')
vm.RemoteCommand('sudo mv orted /usr/bin/orted')
def ParseOutput(hpcc_output, benchmark_spec):
"""Parses the output from HPCC.
Args:
hpcc_output: A string containing the text of hpccoutf.txt.
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark.
Returns:
A list of samples to be published (in the same format as Run() returns).
"""
results = []
metadata = dict()
match = re.search('HPLMaxProcs=([0-9]*)', hpcc_output)
metadata['num_cpus'] = match.group(1)
metadata['num_machines'] = len(benchmark_spec.vms)
metadata['memory_size_mb'] = FLAGS.memory_size_mb
value = regex_util.ExtractFloat('HPL_Tflops=([0-9]*\\.[0-9]*)', hpcc_output)
results.append(sample.Sample('HPL Throughput', value, 'Tflops', metadata))
value = regex_util.ExtractFloat('SingleRandomAccess_GUPs=([0-9]*\\.[0-9]*)',
hpcc_output)
results.append(sample.Sample('Random Access Throughput', value,
'GigaUpdates/sec'))
for metric in STREAM_METRICS:
regex = 'SingleSTREAM_%s=([0-9]*\\.[0-9]*)' % metric
value = regex_util.ExtractFloat(regex, hpcc_output)
results.append(sample.Sample('STREAM %s Throughput' % metric, value,
'GB/s'))
return results
def Run(benchmark_spec):
"""Run HPCC on the cluster.
Args:
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark.
Returns:
A list of sample.Sample objects.
"""
vms = benchmark_spec.vms
master_vm = vms[0]
num_processes = len(vms) * master_vm.num_cpus
mpi_cmd = ('mpirun -np %s -machinefile %s --mca orte_rsh_agent '
'"ssh -o StrictHostKeyChecking=no" ./hpcc' %
(num_processes, MACHINEFILE))
master_vm.RobustRemoteCommand(mpi_cmd)
logging.info('HPCC Results:')
stdout, _ = master_vm.RemoteCommand('cat hpccoutf.txt', should_log=True)
return ParseOutput(stdout, benchmark_spec)
def Cleanup(benchmark_spec):
"""Cleanup HPCC on the cluster.
Args:
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark.
"""
vms = benchmark_spec.vms
master_vm = vms[0]
master_vm.RemoveFile('hpcc*')
master_vm.RemoveFile(MACHINEFILE)
for vm in vms[1:]:
vm.RemoveFile('hpcc')
vm.RemoveFile('/usr/bin/orted')
| [
2,
15069,
1946,
2448,
69,
20827,
44199,
4102,
263,
46665,
13,
1439,
2489,
10395,
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,
... | 2.588974 | 2,866 |
"""
from:
https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html
dependent on Profile model
"""
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six
account_activation_token = AccountActivationTokenGenerator()
| [
37811,
198,
6738,
25,
198,
5450,
1378,
36439,
271,
27903,
14813,
41887,
13,
785,
14,
83,
44917,
14,
5539,
14,
2999,
14,
1507,
14,
4919,
12,
1462,
12,
17953,
12,
7220,
12,
12683,
12,
929,
12,
1177,
13,
6494,
198,
198,
21186,
319,
1... | 3.215054 | 93 |
#!/usr/bin/env python3
"""
Created on 30 Jan 2018
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
from scs_host.bus.i2c import I2C
from scs_host.sys.host import Host
from scs_ndir.gas.ndir.spi_ndir_x1.spi_ndir_x1 import SPINDIRx1
# --------------------------------------------------------------------------------------------------------------------
try:
I2C.Sensors.open()
ndir = SPINDIRx1(False, Host.ndir_spi_bus(), Host.ndir_spi_device())
print(ndir)
print("-")
ndir.power_on()
status = ndir.status()
print("status: %s" % status)
print("-")
data = ndir.record_raw(0, 5, 200)
print("rec, raw_pile_ref, raw_pile_act")
for datum in data:
print("%d, %d, %d" % datum)
except ValueError as ex:
print("ValueError: %s" % ex)
except KeyboardInterrupt:
print("")
finally:
I2C.Sensors.close()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
198,
37811,
198,
41972,
319,
1542,
2365,
2864,
198,
198,
31,
9800,
25,
31045,
3944,
2364,
357,
1671,
36909,
13,
6667,
2364,
31,
35782,
1073,
5773,
4234,
13,
785,
8,
198,
37811,
1... | 2.454039 | 359 |
from django.db import models
from django.contrib.auth.models import User | [
6738,
42625,
14208,
13,
9945,
1330,
4981,
198,
6738,
42625,
14208,
13,
3642,
822,
13,
18439,
13,
27530,
1330,
11787
] | 3.6 | 20 |
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5 import QtCore, QtWidgets
import pyqtgraph as pg
import numpy as np
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import collections
import random
import time
import math
import numpy as np
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.figure import Figure
import serial
import time
from pyqtgraph.Qt import QtGui, QtCore
import collections
import random
import math
if __name__ == '__main__':
app = QApplication(sys.argv)
myapp = MyApp()
sys.exit(app.exec_())
| [
11748,
25064,
198,
6738,
9485,
48,
83,
20,
13,
48,
83,
14055,
1330,
1635,
198,
6738,
9485,
48,
83,
20,
13,
48,
83,
54,
312,
11407,
1330,
1635,
198,
6738,
9485,
48,
83,
20,
13,
48,
83,
8205,
72,
1330,
1635,
198,
6738,
9485,
48,
... | 2.904255 | 282 |
"""Custom routing classes."""
import warnings
from typing import Callable, Dict, Optional, Type
import rasterio
from fastapi.routing import APIRoute
from starlette.requests import Request
from starlette.responses import Response
def apiroute_factory(env: Optional[Dict] = None) -> Type[APIRoute]:
"""
Create Custom API Route class with custom Env.
Because we cannot create middleware for specific router we need to create
a custom APIRoute which add the `rasterio.Env(` block before the endpoint is
actually called. This way we set the env outside the threads and we make sure
that event multithreaded Reader will get the environment set.
Note: This has been tested in python 3.6 and 3.7 only.
"""
warnings.warn(
"'apiroute_factory' has been deprecated and will be removed"
"in titiler 0.1.0. Please see `gdal_config` option in endpoint factories.",
DeprecationWarning,
)
class EnvAPIRoute(APIRoute):
"""Custom API route with env."""
config = env or {}
return EnvAPIRoute
| [
37811,
15022,
28166,
6097,
526,
15931,
198,
198,
11748,
14601,
198,
6738,
19720,
1330,
4889,
540,
11,
360,
713,
11,
32233,
11,
5994,
198,
198,
11748,
374,
1603,
952,
198,
198,
6738,
3049,
15042,
13,
81,
13660,
1330,
3486,
4663,
13192,
... | 3.08046 | 348 |
from PIL import Image
import numpy as np
from chexnet import ChexNet
import os
from flask import Flask, render_template, request
from werkzeug import secure_filename
import csv
DISEASES = np.array(['Atelectasis', 'Cardiomegaly', 'Effusion', 'Infiltration', 'Mass', 'Nodule', 'Pneumonia',
'Pneumothorax', 'Consolidation', 'Edema', 'Emphysema',
'Fibrosis', 'Pleural Thickening', 'Hernia'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'C:/Users/bhave/OneDrive/Desktop/Sakshi/images/'
chexnet = ChexNet()
chexnet.eval()
@app.route('/')
@app.route('/uploader', methods = ['GET', 'POST'])
##print(result)
if __name__ == '__main__':
app.run(debug=True)
| [
6738,
350,
4146,
1330,
7412,
201,
198,
11748,
299,
32152,
355,
45941,
201,
198,
6738,
1125,
87,
3262,
1330,
2580,
87,
7934,
201,
198,
11748,
28686,
201,
198,
6738,
42903,
1330,
46947,
11,
8543,
62,
28243,
11,
2581,
201,
198,
6738,
266... | 2.400685 | 292 |
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
| [
198,
198,
2,
3406,
1855,
25896,
2134,
481,
307,
9113,
12931,
290,
1444,
355,
884,
25,
198,
2,
26181,
796,
1855,
25896,
3419,
198,
2,
26181,
13,
14689,
7,
87,
8,
198,
2,
26181,
13,
12924,
3419,
198,
2,
5772,
62,
18,
796,
26181,
1... | 2.677966 | 59 |
from sre_parse import fix_flags
from cv2 import FileStorage_UNDEFINED
import numpy as np
import pandas as pd
from pandas.io import sql
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
df= pd.read_csv('HINDALCO.csv', index_col=False, delimiter = ',')
df = df.set_index(pd.DatetimeIndex(df['datetime'].values))
# print(df.head())
plt.figure(figsize=(16,8))
plt.title('Close Price History', fontsize=18)
plt.plot(df['close'])
plt.xlabel('Date',fontsize=18)
plt.ylabel('Close Price', fontsize=18)
# plt.show()
# fn to calculate the simple moving average (SMA)
#create two colms to store 20 day and 50 day SMA
df['SMA20']=SMA(df,20)
df['SMA50']=SMA(df,50)
df['Signal'] = np.where(df['SMA20'] > df['SMA50'],1,0)
df['Position'] = df['Signal'].diff()
df["Buy"]=np.where(df['Position']==1,df['close'],0)
df["Sell"]=np.where(df['Position']==-1,df['close'],0)
plt.figure(figsize=(16,8))
plt.title('Close Price History with Buys/Sell signal', fontsize=18)
plt.plot(df['close'],alpha=0.5,label="Close")
plt.plot(df['SMA20'],alpha=0.5,label="SMA20")
plt.plot(df['SMA50'],alpha=0.5,label="SMA50")
plt.scatter(df.index, df['Buy'], alpha=1, label="Buy Signal", marker = '^' , color='green')
plt.scatter(df.index, df['Sell'], alpha=1, label="Sell Signal", marker = 'v' , color='red')
plt.xlabel('Date',fontsize=18)
plt.ylabel('Close Price', fontsize=18)
plt.show()
# preprocessing before stroing into database
df['SMA20'] = df['SMA20'].fillna(0)
df['SMA50'] = df['SMA50'].fillna(0)
df['Position'] = df['Position'].fillna(0)
print(df['Signal'].unique())
#storing into csvfile
# df.to_csv("finalhindalco.csv")
#Storing back into MYSQL into a new table
import mysql.connector as mysql
from mysql.connector import Error
try:
conn = mysql.connect(host='localhost', database='invsto', user='root', password='root')
if conn.is_connected():
cursor = conn.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
cursor.execute("CREATE TABLE hindSMA(datetime datetime,close decimal(10,4),high decimal(10,4),low decimal(10,4),open decimal(10,4),volume int,instrument varchar(255),SMA20 decimal(14,7),SMA50 decimal(14,7),signals int,position int, buy decimal(14,7), sell decimal(14,7))")
print("You're connected to database: ", record)
for i,row in df.iterrows():
# print("Record inserted",tuple(row))
sql = "INSERT INTO invsto.hindSMA VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
cursor.execute(sql, tuple(row))
conn.commit()
print("Query executed")
except Error as e:
print("Error while connecting to MySQL", e) | [
6738,
264,
260,
62,
29572,
1330,
4259,
62,
33152,
201,
198,
6738,
269,
85,
17,
1330,
9220,
31425,
62,
4944,
7206,
20032,
1961,
201,
198,
11748,
299,
32152,
355,
45941,
201,
198,
11748,
19798,
292,
355,
279,
67,
201,
198,
6738,
19798,
... | 2.276316 | 1,216 |
import dadi
import pickle
import pytest
import subprocess
import glob
import os
import signal
import time
from src.InferDFE import infer_dfe
try:
if not os.path.exists("./tests/test_results"):
os.makedirs("./tests/test_results")
except:
pass
| [
11748,
288,
9189,
198,
11748,
2298,
293,
198,
11748,
12972,
9288,
198,
11748,
850,
14681,
198,
11748,
15095,
198,
11748,
28686,
198,
11748,
6737,
198,
11748,
640,
198,
6738,
12351,
13,
818,
2232,
8068,
36,
1330,
13249,
62,
67,
5036,
198... | 2.656566 | 99 |
#!/usr/bin/env python3
"""
Written by Elena, rewritten by Dylan. This script gets the dust counts in a
night and prints it
Changelog:
2020-06-20 DG Moving main contents into a function for import functionality
"""
import argparse
import datetime
from astropy.time import Time
import numpy as np
from bin import sjd, epics_fetch
__version__ = '3.2.2'
telemetry = epics_fetch.telemetry
# TAI_UTC =34;
TAI_UTC = 0
aSjd = 40587.3
bSjd = 86400.0
if __name__ == '__main__':
main()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
37811,
198,
25354,
416,
37254,
11,
30101,
416,
21371,
13,
770,
4226,
3011,
262,
8977,
9853,
287,
257,
198,
1755,
290,
20842,
340,
198,
198,
1925,
8368,
519,
25,
198,
42334,
12,
3... | 2.75419 | 179 |
print """
CALCULO DE KM/H
***************
Selecciona la marca
*******************
1)Audi
2)Bugatti
3)Chevy
4)Toyota
*******************
"""
mi_auto = Auto(50)
mi_auto.opcion()
| [
4798,
37227,
198,
33290,
34,
6239,
46,
5550,
46646,
14,
39,
198,
220,
46068,
8162,
198,
198,
4653,
293,
535,
32792,
8591,
1667,
6888,
198,
8412,
8162,
198,
198,
16,
8,
16353,
72,
198,
17,
8,
25624,
34891,
198,
18,
8,
7376,
7670,
1... | 2.447368 | 76 |
# builtins stub with non-generic primitive types
| [
2,
3170,
1040,
17071,
351,
1729,
12,
41357,
20049,
3858,
198
] | 4.454545 | 11 |
"""Top-level package for PyJazzCash."""
__author__ = """Rana Shahraiz Ali"""
__email__ = 'shahraizali10@yahoo.com'
__version__ = '0.1.0'
integrity_salt = None
merchant_id = None
merchant_password = None
from pyjazzcash import *
from pyjazzcash.card import *
| [
37811,
9126,
12,
5715,
5301,
329,
9485,
41,
8101,
35361,
526,
15931,
628,
198,
834,
9800,
834,
796,
37227,
49,
2271,
18381,
430,
528,
12104,
37811,
198,
834,
12888,
834,
796,
705,
1477,
993,
430,
528,
7344,
940,
31,
40774,
13,
785,
... | 2.708333 | 96 |
import tarfile
import zipfile
from os.path import abspath, dirname
from os.path import join as pjoin
from unittest.mock import call, patch
from testpath import assert_isfile, modified_env
from testpath.tempdir import TemporaryDirectory
from pep517.envbuild import BuildEnvironment, build_sdist, build_wheel
SAMPLES_DIR = pjoin(dirname(abspath(__file__)), 'samples')
BUILDSYS_PKGS = pjoin(SAMPLES_DIR, 'buildsys_pkgs')
@patch.object(BuildEnvironment, 'pip_install')
@patch.object(BuildEnvironment, 'pip_install')
| [
11748,
13422,
7753,
198,
11748,
19974,
7753,
198,
6738,
28686,
13,
6978,
1330,
2352,
6978,
11,
26672,
3672,
198,
6738,
28686,
13,
6978,
1330,
4654,
355,
279,
22179,
198,
6738,
555,
715,
395,
13,
76,
735,
1330,
869,
11,
8529,
198,
198,... | 3.071006 | 169 |
#!/usr/bin/env python3
import os
from datetime import datetime
from argparse import ArgumentParser
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("builddir")
args = parser.parse_args()
td = TestDirectory(args.builddir)
td.create_new_test_dir()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
11748,
28686,
198,
6738,
4818,
8079,
1330,
4818,
8079,
198,
6738,
1822,
29572,
1330,
45751,
46677,
628,
198,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
198,
220,
... | 2.872549 | 102 |
from collections import deque
from aocd import models
from src.utils import parse_data
# create puzzle
puzzle = models.Puzzle(year=2021, day=6)
# regex pattern
line_pattern = r'(?P<numbers>.*)'
# format data
input_data = parse_data(puzzle.input_data, is_lines=True, is_numbers=True, regex=line_pattern)
fishes = deque([int(n) for n in input_data[0].numbers.split(",")])
max_days = 256
############################
weeks = max_days // 7 + 2
pascal_triangle = [[binomial_coeff(line, i) for i in range(0, line + 1)] for line in range(weeks+1)]
days = [0] * max_days
for week in range(weeks+1):
current_day = week*7
for val in pascal_triangle[week]:
if current_day < max_days:
days[current_day] += val
current_day += 2
sum_days = sum(days)
fish_count = {
1: sum_days - sum(days[-1:]),
2: sum_days - sum(days[-2:]),
3: sum_days - sum(days[-3:]),
4: sum_days - sum(days[-4:]),
5: sum_days - sum(days[-5:]),
}
total_fish = len(fishes)
for fish in fishes:
total_fish += fish_count[fish]
############################
# submit answer
puzzle.answer_b = total_fish
| [
6738,
17268,
1330,
390,
4188,
198,
198,
6738,
257,
420,
67,
1330,
4981,
198,
6738,
12351,
13,
26791,
1330,
21136,
62,
7890,
198,
198,
2,
2251,
15027,
198,
79,
9625,
796,
4981,
13,
47,
9625,
7,
1941,
28,
1238,
2481,
11,
1110,
28,
2... | 2.456522 | 460 |
import re
import os
from pathlib import Path
import sublime, sublime_plugin
| [
11748,
302,
198,
11748,
28686,
198,
6738,
3108,
8019,
1330,
10644,
198,
198,
11748,
41674,
11,
41674,
62,
33803,
198
] | 3.85 | 20 |
from .Interface import Interface
from .Enumeration import Enumeration
from .Structure import Structure
from .Agent import Agent
from .TypeInfo import TypeInfo
from .Time import Time
from .Utils import Utils
from .ValueObject import ValueObject
#
# exceptions
#
| [
6738,
764,
39317,
1330,
26491,
198,
6738,
764,
4834,
6975,
341,
1330,
2039,
6975,
341,
198,
6738,
764,
1273,
5620,
1330,
32522,
198,
6738,
764,
36772,
1330,
15906,
198,
6738,
764,
6030,
12360,
1330,
5994,
12360,
198,
6738,
764,
7575,
13... | 3.855072 | 69 |
"""
test_deckmanager_normal.py:
tests a default DeckManager()
"""
from cardgame.classes.card import Card
from cardgame.classes.deckmanager import DeckManager, EmptyDeckError
from tests.test_card import TestCard
from .helper import Helper
class TestDeckManager(TestCard):
"""
TestDeckManager():
tests against standard DeckManager()
"""
@staticmethod
def create_deck_manager(): # pylint: disable=W0221
"""
create_deck_manager():
override to return different deck manager
"""
return DeckManager()
def test_normal_deck_creation(self):
"""
test_normal_deck_creation():
test things about a normal deck that we expect
"""
deck_mgr = TestDeckManager.create_deck_manager()
deck = deck_mgr.deck()
# test to make sure we have a normal deck length
self.assertEqual(52, len(deck))
# test to make sure we have 4 known suits
# in default ranking order (low to high)
self.assertEqual(4, len(deck_mgr.suits_ranking()))
self.assertEqual(
Helper.normal_deck_suits(),
deck_mgr.suits_ranking()
)
# test to make sure we have expected card values
# in default order of low to high
self.assertEqual(
Helper.normal_deck_values(),
deck_mgr.values_ranking()
)
# make sure sorting the deck keeps original order
sorted_deck = deck_mgr.sort()
self.assertEqual(deck, sorted_deck)
# make sure we didn't lose any cards on the sort
self.assertEqual(52, len(deck))
self.assertEqual(52, len(sorted_deck))
def test_normal_deck_shuffled(self):
"""
test_normal_deck_shuffled():
tests to make sure shuffling is random
"""
deck_mgr = TestDeckManager.create_deck_manager()
original_deck = deck_mgr.deck()
shuffled_deck = deck_mgr.shuffle()
# make sure deck has been shuffled
self.assertNotEqual(original_deck, shuffled_deck)
# make sure deck mgr internal deck has been shuffed
self.assertEqual(shuffled_deck, deck_mgr.deck())
# make sure if we shuffle again, it doesn't equal
# previously shuffled deck or original deck
# (technically chances are really, really slim that
# they could equal each other)
self.assertNotEqual(shuffled_deck, deck_mgr.shuffle())
self.assertNotEqual(original_deck, deck_mgr.deck())
# make sure we didn't lose any cards
self.assertEqual(52, len(original_deck))
self.assertEqual(52, len(shuffled_deck))
def test_normal_deck_order(self):
"""
test_normal_deck_order():
test to make sure "top" card on deck matches
what we expect it to be (if not shuffled)
test 2nd card the same way
draw the rest of the cards and make sure
last card is what we expect it to be
"""
deck_mgr = TestDeckManager.create_deck_manager()
card = deck_mgr.draw_card()
# make sure card we drew is what we expected
self.assertEqual(Card('Spades', '2', 1, 2), card)
# check that first and last card are as expected
self.assertEqual(Card('Spades', '3', 1, 3), deck_mgr.draw_card())
for _ in range(0, 49):
deck_mgr.draw_card()
self.assertEqual(Card('Clubs', 'Ace', 4, 14), deck_mgr.draw_card())
def test_empty_deck_error_thrown(self):
"""
test_empty_deck_error_thrown():
normal deck, draw 52 cards, should raise error
if you try to draw more cards
"""
deck_mgr = TestDeckManager.create_deck_manager()
for _ in range(52):
deck_mgr.draw_card()
# check to make sure EmptyDeckError is thrown
# if we try to draw a card from an empty deck
self.assertRaises(EmptyDeckError, deck_mgr.draw_card)
| [
37811,
198,
9288,
62,
35875,
37153,
62,
11265,
13,
9078,
25,
198,
220,
220,
220,
5254,
257,
4277,
20961,
13511,
3419,
198,
37811,
198,
6738,
2657,
6057,
13,
37724,
13,
9517,
1330,
5172,
198,
6738,
2657,
6057,
13,
37724,
13,
35875,
371... | 2.329849 | 1,722 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import json
import math
import os
import shutil
import sys
import time
from os.path import exists, join, split
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
from torchvision import transforms
import drn
from models.grad_reversal import grad_reverse
CITYSCAPE_PALLETE = np.asarray([
[128, 64, 128],
[244, 35, 232],
[70, 70, 70],
[102, 102, 156],
[190, 153, 153],
[153, 153, 153],
[250, 170, 30],
[220, 220, 0],
[107, 142, 35],
[152, 251, 152],
[70, 130, 180],
[220, 20, 60],
[255, 0, 0],
[0, 0, 142],
[0, 0, 70],
[0, 60, 100],
[0, 80, 100],
[0, 0, 230],
[119, 11, 32],
[0, 0, 0]], dtype=np.uint8)
class DownConv(nn.Module):
"""
copied from https://github.com/jaxony/unet-pytorch/blob/master/model.py
A helper Module that performs 2 convolutions and 1 MaxPool.
A ReLU activation follows each convolution.
"""
class AverageMeter(object):
"""Computes and stores the average and current value"""
def accuracy(output, target):
"""Computes the precision@k for the specified values of k"""
# batch_size = target.size(0) * target.size(1) * target.size(2)
_, pred = output.max(1)
pred = pred.view(1, -1)
target = target.view(1, -1)
correct = pred.eq(target)
correct = correct[target != 255]
correct = correct.view(-1)
score = correct.float().sum(0).mul(100.0 / correct.size(0))
return score.data[0]
def adjust_learning_rate(args, optimizer, epoch):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.1 ** (epoch // args.step))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr
def save_output_images(predictions, filenames, output_dir):
"""
Saves a given (B x C x H x W) into an image file.
If given a mini-batch tensor, will save the tensor as a grid of images.
"""
# pdb.set_trace()
for ind in range(len(filenames)):
im = Image.fromarray(predictions[ind].astype(np.uint8))
fn = os.path.join(output_dir, filenames[ind])
out_dir = split(fn)[0]
if not exists(out_dir):
os.makedirs(out_dir)
im.save(fn)
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,
198,
11748,
1822,
29572,
198,
11748,
33918,
198,
11748,
10688,
198,
11748,
28686,
198,
11748,
4423,
346,
198,
11748,
2506... | 2.403561 | 1,011 |
import numpy as np
import sklearn.metrics as metrics
| [
11748,
299,
32152,
355,
45941,
198,
11748,
1341,
35720,
13,
4164,
10466,
355,
20731,
198
] | 3.533333 | 15 |
@w1 # f1 = w1(f1)
# innerFunc = w1(f1)
# innerFunc()
# f1 = w1(f1)
# f1()
f1() | [
198,
31,
86,
16,
1303,
277,
16,
796,
266,
16,
7,
69,
16,
8,
198,
198,
2,
8434,
37,
19524,
796,
266,
16,
7,
69,
16,
8,
198,
2,
8434,
37,
19524,
3419,
198,
198,
2,
277,
16,
796,
266,
16,
7,
69,
16,
8,
198,
2,
277,
16,
34... | 1.482143 | 56 |
from django.contrib import admin
from .models import Orchestrator, OrchestratorAuth
# Register your models here.
admin.site.register(Orchestrator, OrchestratorAdmin)
admin.site.register(OrchestratorAuth, OrchestratorAuthAdmin)
| [
6738,
42625,
14208,
13,
3642,
822,
1330,
13169,
198,
6738,
764,
27530,
1330,
30369,
2536,
1352,
11,
30369,
2536,
1352,
30515,
198,
198,
2,
17296,
534,
4981,
994,
13,
628,
628,
198,
28482,
13,
15654,
13,
30238,
7,
5574,
2395,
2536,
135... | 3.411765 | 68 |
# -*- encoding: utf8 -*-
from itertools import (combinations, groupby)
from linguistica.util import NULL
# noinspection PyPep8
def make_bisignatures(wordlist, min_stem_length, max_affix_length, suffixing):
"""
This function finds pairs of words which make a valid signature,
and makes Dictionary whose key is the signature and
whose value is a tuple: stem, word1, word2.
"""
bisigs_to_tuples = dict()
if not suffixing:
wordlist = sorted(wordlist, key=lambda x: x[::-1])
group_key = lambda x: x[-min_stem_length:] # noqa
else:
wordlist = sorted(wordlist)
group_key = lambda x: x[: min_stem_length] # noqa
wordlist = filter(lambda x: len(x) >= min_stem_length, wordlist)
for _, group in groupby(wordlist, key=group_key): # groupby from itertools
wordlist_for_analysis = list(group) # must use list() here!
# see python 3.4 documentation:
# https://docs.python.org/3/library/itertools.html#itertools.groupby
# "The returned group is itself an iterator that shares the underlying
# iterable with groupby(). Because the source is shared, when the
# groupby() object is advanced, the previous group is no longer
# visible. So, if that data is needed later, it should be stored as a
# list"
for (word1, word2) in combinations(wordlist_for_analysis, 2):
if suffixing:
stem = max_common_prefix(word1, word2)
len_stem = len(stem)
affix1 = word1[len_stem:]
affix2 = word2[len_stem:]
else:
stem = max_common_suffix(word1, word2)
len_stem = len(stem)
affix1 = word1[: -len_stem]
affix2 = word2[: -len_stem]
len_affix1 = len(affix1)
len_affix2 = len(affix2)
if len_affix1 > max_affix_length or \
len_affix2 > max_affix_length:
continue
if len_affix1 == 0:
affix1 = NULL
if len_affix2 == 0:
affix2 = NULL
bisig = tuple({affix1, affix2})
if bisig not in bisigs_to_tuples:
bisigs_to_tuples[bisig] = set()
chunk = (stem, word1, word2)
bisigs_to_tuples[bisig].add(chunk)
return bisigs_to_tuples
| [
2,
532,
9,
12,
21004,
25,
3384,
69,
23,
532,
9,
12,
198,
198,
6738,
340,
861,
10141,
1330,
357,
24011,
7352,
11,
1448,
1525,
8,
198,
198,
6738,
29929,
64,
13,
22602,
1330,
15697,
628,
628,
628,
628,
628,
198,
198,
2,
645,
1040,
... | 2.130009 | 1,123 |
""" Cisco_IOS_XR_segment_routing_ms_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR segment\-routing\-ms package operational data.
This module contains definitions
for the following management objects\:
srms\: Segment Routing Mapping Server operational data
srlb\: srlb
Copyright (c) 2013\-2018 by Cisco Systems, Inc.
All rights reserved.
"""
from collections import OrderedDict
from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64
from ydk.filters import YFilter
from ydk.errors import YError, YModelError
from ydk.errors.error_handler import handle_type_error as _handle_type_error
class SidTypeEnum(Enum):
"""
SidTypeEnum (Enum Class)
Sid type enum
.. data:: absolute = 1
Absolute SID
.. data:: index = 2
Index SID
"""
absolute = Enum.YLeaf(1, "absolute")
index = Enum.YLeaf(2, "index")
class SrmsAf(Enum):
"""
SrmsAf (Enum Class)
Srms af
.. data:: none = 0
None
.. data:: ipv4 = 1
IPv4
.. data:: ipv6 = 2
IPv6
"""
none = Enum.YLeaf(0, "none")
ipv4 = Enum.YLeaf(1, "ipv4")
ipv6 = Enum.YLeaf(2, "ipv6")
class SrmsMiAfEB(Enum):
"""
SrmsMiAfEB (Enum Class)
Srms mi af e b
.. data:: none = 0
None
.. data:: ipv4 = 1
IPv4
.. data:: ipv6 = 2
IPv6
"""
none = Enum.YLeaf(0, "none")
ipv4 = Enum.YLeaf(1, "ipv4")
ipv6 = Enum.YLeaf(2, "ipv6")
class SrmsMiFlagEB(Enum):
"""
SrmsMiFlagEB (Enum Class)
Srms mi flag e b
.. data:: false = 0
False
.. data:: true = 1
True
"""
false = Enum.YLeaf(0, "false")
true = Enum.YLeaf(1, "true")
class SrmsMiSrcEB(Enum):
"""
SrmsMiSrcEB (Enum Class)
Srms mi src e b
.. data:: none = 0
None
.. data:: local = 1
Local
.. data:: remote = 2
Remote
"""
none = Enum.YLeaf(0, "none")
local = Enum.YLeaf(1, "local")
remote = Enum.YLeaf(2, "remote")
class Srms(Entity):
"""
Segment Routing Mapping Server operational data
.. attribute:: mapping
IP prefix to SID mappings
**type**\: :py:class:`Mapping <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Mapping>`
.. attribute:: adjacency_sid
Adjacency SID
**type**\: :py:class:`AdjacencySid <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.AdjacencySid>`
.. attribute:: policy
Policy operational data
**type**\: :py:class:`Policy <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Policy>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class Mapping(Entity):
"""
IP prefix to SID mappings
.. attribute:: mapping_ipv4
IPv4 prefix to SID mappings
**type**\: :py:class:`MappingIpv4 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Mapping.MappingIpv4>`
.. attribute:: mapping_ipv6
IPv6 prefix to SID mappings
**type**\: :py:class:`MappingIpv6 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Mapping.MappingIpv6>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class MappingIpv4(Entity):
"""
IPv4 prefix to SID mappings
.. attribute:: mapping_mi
IP prefix to SID mapping item. It's not possible to list all of the IP prefix to SID mappings, as the set of valid prefixes could be very large. Instead, SID map information must be retrieved individually for each prefix of interest
**type**\: list of :py:class:`MappingMi <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Mapping.MappingIpv4.MappingMi>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class MappingMi(Entity):
"""
IP prefix to SID mapping item. It's not possible
to list all of the IP prefix to SID mappings, as
the set of valid prefixes could be very large.
Instead, SID map information must be retrieved
individually for each prefix of interest.
.. attribute:: ip
IP
**type**\: str
**pattern:** [\\w\\\-\\.\:,\_@#%$\\+=\\\|;]+
.. attribute:: prefix
Prefix
**type**\: int
**range:** 0..4294967295
.. attribute:: addr
addr
**type**\: :py:class:`Addr <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Mapping.MappingIpv4.MappingMi.Addr>`
.. attribute:: src
src
**type**\: :py:class:`SrmsMiSrcEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiSrcEB>`
.. attribute:: router
Router ID
**type**\: str
**length:** 0..30
.. attribute:: area
Area (OSPF) or Level (ISIS)
**type**\: str
**length:** 0..30
.. attribute:: prefix_xr
Prefix length
**type**\: int
**range:** 0..255
.. attribute:: sid_start
Starting SID
**type**\: int
**range:** 0..4294967295
.. attribute:: sid_count
SID range
**type**\: int
**range:** 0..4294967295
.. attribute:: last_prefix
Last IP Prefix
**type**\: str
**length:** 0..50
.. attribute:: last_sid_index
Last SID Index
**type**\: int
**range:** 0..4294967295
.. attribute:: flag_attached
Attached flag
**type**\: :py:class:`SrmsMiFlagEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiFlagEB>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class Addr(Entity):
"""
addr
.. attribute:: af
AF
**type**\: :py:class:`SrmsMiAfEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiAfEB>`
.. attribute:: ipv4
IPv4
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
.. attribute:: ipv6
IPv6
**type**\: str
**pattern:** ((\:\|[0\-9a\-fA\-F]{0,4})\:)([0\-9a\-fA\-F]{0,4}\:){0,5}((([0\-9a\-fA\-F]{0,4}\:)?(\:\|[0\-9a\-fA\-F]{0,4}))\|(((25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])\\.){3}(25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])))(%[\\p{N}\\p{L}]+)?
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class MappingIpv6(Entity):
"""
IPv6 prefix to SID mappings
.. attribute:: mapping_mi
IP prefix to SID mapping item. It's not possible to list all of the IP prefix to SID mappings, as the set of valid prefixes could be very large. Instead, SID map information must be retrieved individually for each prefix of interest
**type**\: list of :py:class:`MappingMi <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Mapping.MappingIpv6.MappingMi>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class MappingMi(Entity):
"""
IP prefix to SID mapping item. It's not possible
to list all of the IP prefix to SID mappings, as
the set of valid prefixes could be very large.
Instead, SID map information must be retrieved
individually for each prefix of interest.
.. attribute:: ip
IP
**type**\: str
**pattern:** [\\w\\\-\\.\:,\_@#%$\\+=\\\|;]+
.. attribute:: prefix
Prefix
**type**\: int
**range:** 0..4294967295
.. attribute:: addr
addr
**type**\: :py:class:`Addr <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Mapping.MappingIpv6.MappingMi.Addr>`
.. attribute:: src
src
**type**\: :py:class:`SrmsMiSrcEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiSrcEB>`
.. attribute:: router
Router ID
**type**\: str
**length:** 0..30
.. attribute:: area
Area (OSPF) or Level (ISIS)
**type**\: str
**length:** 0..30
.. attribute:: prefix_xr
Prefix length
**type**\: int
**range:** 0..255
.. attribute:: sid_start
Starting SID
**type**\: int
**range:** 0..4294967295
.. attribute:: sid_count
SID range
**type**\: int
**range:** 0..4294967295
.. attribute:: last_prefix
Last IP Prefix
**type**\: str
**length:** 0..50
.. attribute:: last_sid_index
Last SID Index
**type**\: int
**range:** 0..4294967295
.. attribute:: flag_attached
Attached flag
**type**\: :py:class:`SrmsMiFlagEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiFlagEB>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class Addr(Entity):
"""
addr
.. attribute:: af
AF
**type**\: :py:class:`SrmsMiAfEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiAfEB>`
.. attribute:: ipv4
IPv4
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
.. attribute:: ipv6
IPv6
**type**\: str
**pattern:** ((\:\|[0\-9a\-fA\-F]{0,4})\:)([0\-9a\-fA\-F]{0,4}\:){0,5}((([0\-9a\-fA\-F]{0,4}\:)?(\:\|[0\-9a\-fA\-F]{0,4}))\|(((25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])\\.){3}(25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])))(%[\\p{N}\\p{L}]+)?
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class AdjacencySid(Entity):
"""
Adjacency SID
.. attribute:: l2_adjacency
L2 Adjacency Option
**type**\: :py:class:`L2Adjacency <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.AdjacencySid.L2Adjacency>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class L2Adjacency(Entity):
"""
L2 Adjacency Option
.. attribute:: interfaces
Interface directory
**type**\: :py:class:`Interfaces <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.AdjacencySid.L2Adjacency.Interfaces>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class Interfaces(Entity):
"""
Interface directory
.. attribute:: interface
Segment Routing Adjacency SID Interface
**type**\: list of :py:class:`Interface <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.AdjacencySid.L2Adjacency.Interfaces.Interface>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class Interface(Entity):
"""
Segment Routing Adjacency SID Interface
.. attribute:: interface_name (key)
Interface name
**type**\: str
**pattern:** [a\-zA\-Z0\-9.\_/\-]+
.. attribute:: address_family
address family container
**type**\: :py:class:`AddressFamily <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.AdjacencySid.L2Adjacency.Interfaces.Interface.AddressFamily>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class AddressFamily(Entity):
"""
address family container
.. attribute:: ipv4
IP version 4
**type**\: :py:class:`Ipv4 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.AdjacencySid.L2Adjacency.Interfaces.Interface.AddressFamily.Ipv4>`
.. attribute:: ipv6
IP version 6
**type**\: :py:class:`Ipv6 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.AdjacencySid.L2Adjacency.Interfaces.Interface.AddressFamily.Ipv6>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class Ipv4(Entity):
"""
IP version 4
.. attribute:: sid_record
SID record
**type**\: list of :py:class:`SidRecord <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.AdjacencySid.L2Adjacency.Interfaces.Interface.AddressFamily.Ipv4.SidRecord>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class SidRecord(Entity):
"""
SID record
.. attribute:: sid_type
SID type
**type**\: :py:class:`SidTypeEnum <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SidTypeEnum>`
.. attribute:: sid_value
SID value
**type**\: int
**range:** 0..4294967295
.. attribute:: nexthop_address
Nexthop address
**type**\: :py:class:`NexthopAddress <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.AdjacencySid.L2Adjacency.Interfaces.Interface.AddressFamily.Ipv4.SidRecord.NexthopAddress>`
.. attribute:: interface_name
Interface name
**type**\: str
**length:** 0..64
.. attribute:: sid_value_xr
SID Value
**type**\: int
**range:** 0..4294967295
.. attribute:: sid_type_xr
SID type
**type**\: int
**range:** 0..4294967295
.. attribute:: address_family
Interface address family
**type**\: int
**range:** 0..4294967295
.. attribute:: has_nexthop
Has nexthop
**type**\: bool
.. attribute:: interface_count
Interface count
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: interface_delete_count
Interface delete count
**type**\: int
**range:** \-2147483648..2147483647
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class NexthopAddress(Entity):
"""
Nexthop address
.. attribute:: af
AF
**type**\: :py:class:`SrmsAf <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsAf>`
.. attribute:: ipv4
IPv4
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
.. attribute:: ipv6
IPv6
**type**\: str
**pattern:** ((\:\|[0\-9a\-fA\-F]{0,4})\:)([0\-9a\-fA\-F]{0,4}\:){0,5}((([0\-9a\-fA\-F]{0,4}\:)?(\:\|[0\-9a\-fA\-F]{0,4}))\|(((25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])\\.){3}(25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])))(%[\\p{N}\\p{L}]+)?
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class Ipv6(Entity):
"""
IP version 6
.. attribute:: sid_record
SID record
**type**\: list of :py:class:`SidRecord <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.AdjacencySid.L2Adjacency.Interfaces.Interface.AddressFamily.Ipv6.SidRecord>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class SidRecord(Entity):
"""
SID record
.. attribute:: sid_type
SID type
**type**\: :py:class:`SidTypeEnum <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SidTypeEnum>`
.. attribute:: sid_value
SID value
**type**\: int
**range:** 0..4294967295
.. attribute:: nexthop_address
Nexthop address
**type**\: :py:class:`NexthopAddress <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.AdjacencySid.L2Adjacency.Interfaces.Interface.AddressFamily.Ipv6.SidRecord.NexthopAddress>`
.. attribute:: interface_name
Interface name
**type**\: str
**length:** 0..64
.. attribute:: sid_value_xr
SID Value
**type**\: int
**range:** 0..4294967295
.. attribute:: sid_type_xr
SID type
**type**\: int
**range:** 0..4294967295
.. attribute:: address_family
Interface address family
**type**\: int
**range:** 0..4294967295
.. attribute:: has_nexthop
Has nexthop
**type**\: bool
.. attribute:: interface_count
Interface count
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: interface_delete_count
Interface delete count
**type**\: int
**range:** \-2147483648..2147483647
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class NexthopAddress(Entity):
"""
Nexthop address
.. attribute:: af
AF
**type**\: :py:class:`SrmsAf <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsAf>`
.. attribute:: ipv4
IPv4
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
.. attribute:: ipv6
IPv6
**type**\: str
**pattern:** ((\:\|[0\-9a\-fA\-F]{0,4})\:)([0\-9a\-fA\-F]{0,4}\:){0,5}((([0\-9a\-fA\-F]{0,4}\:)?(\:\|[0\-9a\-fA\-F]{0,4}))\|(((25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])\\.){3}(25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])))(%[\\p{N}\\p{L}]+)?
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class Policy(Entity):
"""
Policy operational data
.. attribute:: policy_ipv4
IPv4 policy operational data
**type**\: :py:class:`PolicyIpv4 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Policy.PolicyIpv4>`
.. attribute:: policy_ipv6
IPv6 policy operational data
**type**\: :py:class:`PolicyIpv6 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Policy.PolicyIpv6>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class PolicyIpv4(Entity):
"""
IPv4 policy operational data
.. attribute:: policy_ipv4_backup
IPv4 backup policy operational data
**type**\: :py:class:`PolicyIpv4Backup <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Policy.PolicyIpv4.PolicyIpv4Backup>`
.. attribute:: policy_ipv4_active
IPv4 active policy operational data
**type**\: :py:class:`PolicyIpv4Active <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Policy.PolicyIpv4.PolicyIpv4Active>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class PolicyIpv4Backup(Entity):
"""
IPv4 backup policy operational data
.. attribute:: policy_mi
Mapping Item
**type**\: list of :py:class:`PolicyMi <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Policy.PolicyIpv4.PolicyIpv4Backup.PolicyMi>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class PolicyMi(Entity):
"""
Mapping Item
.. attribute:: mi_id (key)
Mapping Item ID (0, 1, 2, ...)
**type**\: str
**pattern:** [\\w\\\-\\.\:,\_@#%$\\+=\\\|;]+
.. attribute:: addr
addr
**type**\: :py:class:`Addr <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Policy.PolicyIpv4.PolicyIpv4Backup.PolicyMi.Addr>`
.. attribute:: src
src
**type**\: :py:class:`SrmsMiSrcEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiSrcEB>`
.. attribute:: router
Router ID
**type**\: str
**length:** 0..30
.. attribute:: area
Area (OSPF) or Level (ISIS)
**type**\: str
**length:** 0..30
.. attribute:: prefix_xr
Prefix length
**type**\: int
**range:** 0..255
.. attribute:: sid_start
Starting SID
**type**\: int
**range:** 0..4294967295
.. attribute:: sid_count
SID range
**type**\: int
**range:** 0..4294967295
.. attribute:: last_prefix
Last IP Prefix
**type**\: str
**length:** 0..50
.. attribute:: last_sid_index
Last SID Index
**type**\: int
**range:** 0..4294967295
.. attribute:: flag_attached
Attached flag
**type**\: :py:class:`SrmsMiFlagEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiFlagEB>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class Addr(Entity):
"""
addr
.. attribute:: af
AF
**type**\: :py:class:`SrmsMiAfEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiAfEB>`
.. attribute:: ipv4
IPv4
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
.. attribute:: ipv6
IPv6
**type**\: str
**pattern:** ((\:\|[0\-9a\-fA\-F]{0,4})\:)([0\-9a\-fA\-F]{0,4}\:){0,5}((([0\-9a\-fA\-F]{0,4}\:)?(\:\|[0\-9a\-fA\-F]{0,4}))\|(((25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])\\.){3}(25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])))(%[\\p{N}\\p{L}]+)?
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class PolicyIpv4Active(Entity):
"""
IPv4 active policy operational data
.. attribute:: policy_mi
Mapping Item
**type**\: list of :py:class:`PolicyMi <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Policy.PolicyIpv4.PolicyIpv4Active.PolicyMi>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class PolicyMi(Entity):
"""
Mapping Item
.. attribute:: mi_id (key)
Mapping Item ID (0, 1, 2, ...)
**type**\: str
**pattern:** [\\w\\\-\\.\:,\_@#%$\\+=\\\|;]+
.. attribute:: addr
addr
**type**\: :py:class:`Addr <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Policy.PolicyIpv4.PolicyIpv4Active.PolicyMi.Addr>`
.. attribute:: src
src
**type**\: :py:class:`SrmsMiSrcEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiSrcEB>`
.. attribute:: router
Router ID
**type**\: str
**length:** 0..30
.. attribute:: area
Area (OSPF) or Level (ISIS)
**type**\: str
**length:** 0..30
.. attribute:: prefix_xr
Prefix length
**type**\: int
**range:** 0..255
.. attribute:: sid_start
Starting SID
**type**\: int
**range:** 0..4294967295
.. attribute:: sid_count
SID range
**type**\: int
**range:** 0..4294967295
.. attribute:: last_prefix
Last IP Prefix
**type**\: str
**length:** 0..50
.. attribute:: last_sid_index
Last SID Index
**type**\: int
**range:** 0..4294967295
.. attribute:: flag_attached
Attached flag
**type**\: :py:class:`SrmsMiFlagEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiFlagEB>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class Addr(Entity):
"""
addr
.. attribute:: af
AF
**type**\: :py:class:`SrmsMiAfEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiAfEB>`
.. attribute:: ipv4
IPv4
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
.. attribute:: ipv6
IPv6
**type**\: str
**pattern:** ((\:\|[0\-9a\-fA\-F]{0,4})\:)([0\-9a\-fA\-F]{0,4}\:){0,5}((([0\-9a\-fA\-F]{0,4}\:)?(\:\|[0\-9a\-fA\-F]{0,4}))\|(((25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])\\.){3}(25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])))(%[\\p{N}\\p{L}]+)?
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class PolicyIpv6(Entity):
"""
IPv6 policy operational data
.. attribute:: policy_ipv6_backup
IPv6 backup policy operational data
**type**\: :py:class:`PolicyIpv6Backup <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Policy.PolicyIpv6.PolicyIpv6Backup>`
.. attribute:: policy_ipv6_active
IPv6 active policy operational data
**type**\: :py:class:`PolicyIpv6Active <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Policy.PolicyIpv6.PolicyIpv6Active>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class PolicyIpv6Backup(Entity):
"""
IPv6 backup policy operational data
.. attribute:: policy_mi
Mapping Item
**type**\: list of :py:class:`PolicyMi <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Policy.PolicyIpv6.PolicyIpv6Backup.PolicyMi>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class PolicyMi(Entity):
"""
Mapping Item
.. attribute:: mi_id (key)
Mapping Item ID (0, 1, 2, ...)
**type**\: str
**pattern:** [\\w\\\-\\.\:,\_@#%$\\+=\\\|;]+
.. attribute:: addr
addr
**type**\: :py:class:`Addr <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Policy.PolicyIpv6.PolicyIpv6Backup.PolicyMi.Addr>`
.. attribute:: src
src
**type**\: :py:class:`SrmsMiSrcEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiSrcEB>`
.. attribute:: router
Router ID
**type**\: str
**length:** 0..30
.. attribute:: area
Area (OSPF) or Level (ISIS)
**type**\: str
**length:** 0..30
.. attribute:: prefix_xr
Prefix length
**type**\: int
**range:** 0..255
.. attribute:: sid_start
Starting SID
**type**\: int
**range:** 0..4294967295
.. attribute:: sid_count
SID range
**type**\: int
**range:** 0..4294967295
.. attribute:: last_prefix
Last IP Prefix
**type**\: str
**length:** 0..50
.. attribute:: last_sid_index
Last SID Index
**type**\: int
**range:** 0..4294967295
.. attribute:: flag_attached
Attached flag
**type**\: :py:class:`SrmsMiFlagEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiFlagEB>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class Addr(Entity):
"""
addr
.. attribute:: af
AF
**type**\: :py:class:`SrmsMiAfEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiAfEB>`
.. attribute:: ipv4
IPv4
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
.. attribute:: ipv6
IPv6
**type**\: str
**pattern:** ((\:\|[0\-9a\-fA\-F]{0,4})\:)([0\-9a\-fA\-F]{0,4}\:){0,5}((([0\-9a\-fA\-F]{0,4}\:)?(\:\|[0\-9a\-fA\-F]{0,4}))\|(((25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])\\.){3}(25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])))(%[\\p{N}\\p{L}]+)?
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class PolicyIpv6Active(Entity):
"""
IPv6 active policy operational data
.. attribute:: policy_mi
Mapping Item
**type**\: list of :py:class:`PolicyMi <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Policy.PolicyIpv6.PolicyIpv6Active.PolicyMi>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class PolicyMi(Entity):
"""
Mapping Item
.. attribute:: mi_id (key)
Mapping Item ID (0, 1, 2, ...)
**type**\: str
**pattern:** [\\w\\\-\\.\:,\_@#%$\\+=\\\|;]+
.. attribute:: addr
addr
**type**\: :py:class:`Addr <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srms.Policy.PolicyIpv6.PolicyIpv6Active.PolicyMi.Addr>`
.. attribute:: src
src
**type**\: :py:class:`SrmsMiSrcEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiSrcEB>`
.. attribute:: router
Router ID
**type**\: str
**length:** 0..30
.. attribute:: area
Area (OSPF) or Level (ISIS)
**type**\: str
**length:** 0..30
.. attribute:: prefix_xr
Prefix length
**type**\: int
**range:** 0..255
.. attribute:: sid_start
Starting SID
**type**\: int
**range:** 0..4294967295
.. attribute:: sid_count
SID range
**type**\: int
**range:** 0..4294967295
.. attribute:: last_prefix
Last IP Prefix
**type**\: str
**length:** 0..50
.. attribute:: last_sid_index
Last SID Index
**type**\: int
**range:** 0..4294967295
.. attribute:: flag_attached
Attached flag
**type**\: :py:class:`SrmsMiFlagEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiFlagEB>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class Addr(Entity):
"""
addr
.. attribute:: af
AF
**type**\: :py:class:`SrmsMiAfEB <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.SrmsMiAfEB>`
.. attribute:: ipv4
IPv4
**type**\: str
**pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)?
.. attribute:: ipv6
IPv6
**type**\: str
**pattern:** ((\:\|[0\-9a\-fA\-F]{0,4})\:)([0\-9a\-fA\-F]{0,4}\:){0,5}((([0\-9a\-fA\-F]{0,4}\:)?(\:\|[0\-9a\-fA\-F]{0,4}))\|(((25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])\\.){3}(25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])))(%[\\p{N}\\p{L}]+)?
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class Srlb(Entity):
"""
srlb
.. attribute:: srlb_inconsistency
SRLB Inconsistencies
**type**\: :py:class:`SrlbInconsistency <ydk.models.cisco_ios_xr.Cisco_IOS_XR_segment_routing_ms_oper.Srlb.SrlbInconsistency>`
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
class SrlbInconsistency(Entity):
"""
SRLB Inconsistencies
.. attribute:: start_srlb_range
Start label of Segment Routing Local Block range
**type**\: int
**range:** 0..4294967295
.. attribute:: end_srlb_range
End label of Segment Routing Local Block range
**type**\: int
**range:** 0..4294967295
"""
_prefix = 'segment-routing-ms-oper'
_revision = '2017-09-07'
| [
37811,
28289,
62,
40,
2640,
62,
55,
49,
62,
325,
5154,
62,
81,
13660,
62,
907,
62,
3575,
220,
198,
198,
1212,
8265,
4909,
257,
4947,
286,
575,
15567,
17336,
198,
1640,
28289,
314,
2640,
41441,
55,
49,
10618,
41441,
81,
13660,
41441,... | 1.403835 | 36,037 |
from peewee import *
database = MySQLDatabase('debatovani', **{'passwd': '12345', 'host': '10.0.0.100', 'port': 3306, 'user': 'debatovani'})
| [
6738,
613,
413,
1453,
1330,
1635,
198,
198,
48806,
796,
33476,
38105,
10786,
11275,
265,
709,
3216,
3256,
12429,
90,
6,
6603,
16993,
10354,
705,
10163,
2231,
3256,
705,
4774,
10354,
705,
940,
13,
15,
13,
15,
13,
3064,
3256,
705,
634,
... | 2.459016 | 61 |
# -*- coding: UTF-8 -*-
__copyright__ = """\
Copyright (c) 2012-2013 Rumma & Ko Ltd.
This software comes with ABSOLUTELY NO WARRANTY and is
distributed under the terms of the GNU Lesser General Public License.
See file COPYING.txt for more information."""
| [
2,
532,
9,
12,
19617,
25,
41002,
12,
23,
532,
9,
12,
628,
198,
834,
22163,
4766,
834,
796,
37227,
59,
198,
15269,
357,
66,
8,
2321,
12,
6390,
25463,
2611,
1222,
17634,
12052,
13,
198,
1212,
3788,
2058,
351,
29950,
3535,
3843,
3094... | 3.350649 | 77 |
"""
Revision ID: 0335_broadcast_msg_content
Revises: 0334_broadcast_message_number
Create Date: 2020-12-04 15:06:22.544803
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
revision = '0335_broadcast_msg_content'
down_revision = '0334_broadcast_message_number'
| [
37811,
198,
198,
18009,
1166,
4522,
25,
657,
27326,
62,
36654,
2701,
62,
19662,
62,
11299,
198,
18009,
2696,
25,
657,
31380,
62,
36654,
2701,
62,
20500,
62,
17618,
198,
16447,
7536,
25,
12131,
12,
1065,
12,
3023,
1315,
25,
3312,
25,
... | 2.792793 | 111 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.1.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # s_views_correlations [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=s_views_correlations&codeLang=Python)
# For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=eb-example-fpviews-correlation).
# +
import numpy as np
from arpym.statistics import meancov_sp
from arpym.views import min_rel_entropy_sp
# -
# ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_views_correlations-parameters)
# +
# scenarios of market variables
x = np.array([[0.2, 1.7, 2, 3.4], [5, 3.4, -1.3, 1]]).T
p_base = np.ones(x.shape[0]) / x.shape[0] # base flexible probabilities
rho_view = 0.2 # correlation
c = 0.2 # confidence level
# ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_views_correlations-implementation-step01): Compute parameters specifying the constraints
mu_base_1, sig2_base_1 = meancov_sp(v_1(x).T, p_base)
sig_base_1 = np.sqrt(sig2_base_1)
mu_base_2, sig2_base_2 = meancov_sp(v_2(x).T, p_base)
sig_base_2 = np.sqrt(sig2_base_2)
z_ineq = v_1(x) * v_2(x)
mu_view_ineq = (rho_view * sig_base_1 * sig_base_2 +
mu_base_1 * mu_base_2).reshape(1, )
z_eq = np.vstack((v_1(x), v_2(x), v_1(x) ** 2, v_2(x) ** 2))
mu_view_eq = np.vstack((mu_base_1, mu_base_2, mu_base_1 ** 2 + sig2_base_1,
mu_base_2 ** 2 + sig2_base_2)).reshape(4, )
# -
# ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_views_correlations-implementation-step02): Compute updated probabilities
p_upd = min_rel_entropy_sp(p_base, z_ineq, mu_view_ineq, z_eq, mu_view_eq,
normalize=False)
# ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_views_correlations-implementation-step03): Compute additive/multiplicative confidence-weighted probabilities
p_c_add = c * p_upd + (1 - c) * p_base
p_c_mul = p_upd ** c * p_base ** (1 - c) /\
np.sum(p_upd ** c * p_base ** (1 - c))
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
11420,
198,
2,
474,
929,
88,
353,
25,
198,
2,
220,
220,
474,
929,
88,
5239,
25,
198,
2,
220,
220,
220,
2... | 2.174693 | 1,059 |
from ScienceDynamics.config.configs import SFRAMES_BASE_DIR
MAG_URL_DICT = {"Affiliations":"https://zenodo.org/record/2628216/files/Affiliations.txt.gz?download=1",
"Authors":"https://zenodo.org/record/2628216/files/Authors.txt.gz?download=1",
"ConferenceInstances":"https://zenodo.org/record/2628216/files/ConferenceInstances.txt.gz?download=1",
"ConferenceSeries":"https://zenodo.org/record/2628216/files/ConferenceSeries.txt.gz?download=1",
"FieldsOfStudy":"https://zenodo.org/record/2628216/files/FieldsOfStudy.txt.gz?download=1",
"PaperFieldsOfStudy": "http://data4good.io/datasets/PaperFieldsOfStudy.txt.gz",
"FieldOfStudyChildren": "http://data4good.io/datasets/FieldOfStudyChildren.txt.gz",
"Journals":"https://zenodo.org/record/2628216/files/Journals.txt.gz?download=1",
"PaperAuthorAffiliations": "https://zenodo.org/record/2628216/files/PaperAuthorAffiliations.txt.gz?download=1",
"PaperReferences":"https://zenodo.org/record/2628216/files/PaperReferences.txt.gz?download=1",
"PaperResources":"https://zenodo.org/record/2628216/files/PaperResources.txt.gz?download=1",
"Papers":"https://zenodo.org/record/2628216/files/Papers.txt.gz?download=1",
"PaperUrls":"https://zenodo.org/record/2628216/files/PaperUrls.txt.gz?download=1"}
AMINER_URLS = ("https://academicgraphv2.blob.core.windows.net/oag/aminer/paper/aminer_papers_0.zip",
"https://academicgraphv2.blob.core.windows.net/oag/aminer/paper/aminer_papers_1.zip",
"https://academicgraphv2.blob.core.windows.net/oag/aminer/paper/aminer_papers_2.zip",
"https://academicgraphv2.blob.core.windows.net/oag/aminer/paper/aminer_papers_3.zip")
SJR_URLS = ((year, f"https://www.scimagojr.com/journalrank.php?year={year}&out=xls") for year in range(1999, 2019))
SJR_OPEN_URLS = ((year, f"https://www.scimagojr.com/journalrank.php?openaccess=true&year={year}&out=xls") for year in range(1999, 2019))
FIRST_NAMES_SFRAME = SFRAMES_BASE_DIR.joinpath('first_names_gender.sframe')
| [
6738,
5800,
35,
4989,
873,
13,
11250,
13,
11250,
82,
1330,
311,
10913,
29559,
62,
33,
11159,
62,
34720,
628,
198,
45820,
62,
21886,
62,
35,
18379,
796,
19779,
35191,
2403,
602,
2404,
5450,
1378,
4801,
24313,
13,
2398,
14,
22105,
14,
... | 2.293617 | 940 |
#!/usr/bin/env python3
from __future__ import print_function
import future
import builtins
import past
import six
from builtins import input
from colorama import Fore
from colorama import Style
from threading import RLock
from threading import Thread
import argcomplete
import argparse
import os
import readline
import shlex
import subprocess
import sys
import time
if __name__ == '__main__':
try:
parser = argparse.ArgumentParser()
parser.add_argument(
'cli', help='The command around which the CLI should be wrapped.', nargs='+')
parser.add_argument('-f', '--history-file', dest='historyFile',
default=None, help='The history file to use.')
parser.add_argument('-l', '--history-limit', dest='historyLimit', default=4096, type=int,
help='The maximum number of history entries to retain in the history file.')
argcomplete.autocomplete(parser)
args = parser.parse_args()
cli = Cliffy(args.cli, historyFile=args.historyFile,
historyLimit=args.historyLimit)
cli.start()
while cli.running():
time.sleep(0.1)
print()
except KeyboardInterrupt:
sys.exit(1)
except:
sys.exit(1)
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
198,
6738,
11593,
37443,
834,
1330,
3601,
62,
8818,
198,
11748,
2003,
198,
11748,
3170,
1040,
198,
11748,
1613,
198,
11748,
2237,
198,
6738,
3170,
1040,
1330,
5128,
198,
198,
6738,
... | 2.493204 | 515 |
""" let's make an iterator """
class Reverse:
"Iterator class for looping over a sequence backwards" | [
198,
37811,
1309,
338,
787,
281,
41313,
37227,
198,
4871,
31849,
25,
198,
220,
220,
220,
220,
198,
220,
220,
220,
220,
366,
37787,
1398,
329,
9052,
278,
625,
257,
8379,
16196,
1
] | 3.363636 | 33 |
import pyb
import math
print("Test Timers")
t2 = pyb.Timer(2)
print(t2)
t2.init(freq=1)
t2.callback(callb)
while True:
pyb.delay(1000)
| [
11748,
12972,
65,
198,
11748,
10688,
628,
198,
4798,
7203,
14402,
5045,
364,
4943,
628,
198,
83,
17,
796,
12972,
65,
13,
48801,
7,
17,
8,
198,
198,
4798,
7,
83,
17,
8,
198,
198,
83,
17,
13,
15003,
7,
19503,
80,
28,
16,
8,
198,... | 2.101449 | 69 |
import re
#search for literal strings in sentence
patterns = [ 'Tuffy', 'Pie', 'Loki' ]
text = 'Tuffy eats pie, Loki eats peas!'
for pattern in patterns:
print('"%s"์์ "%s" ๊ฒ์ ์ค ->' % (text, pattern),)
if re.search(pattern, text):
print('์ฐพ์์ต๋๋ค!')
else:
print('์ฐพ์ ์ ์์ต๋๋ค!')
#search a substring and find it's location too
text = 'Diwali is a festival of lights, Holi is a festival of colors!'
pattern = 'festival'
for match in re.finditer(pattern, text):
s = match.start()
e = match.end()
print('%d:%d์์ "%s"์(๋ฅผ) ์ฐพ์์ต๋๋ค.' % (s, e, text[s:e])) | [
11748,
302,
198,
198,
2,
12947,
329,
18875,
13042,
287,
6827,
198,
33279,
82,
796,
685,
705,
51,
15352,
3256,
705,
48223,
3256,
705,
43,
18228,
6,
2361,
198,
5239,
796,
705,
51,
15352,
25365,
2508,
11,
31771,
25365,
22589,
13679,
198,... | 2.017301 | 289 |
#
# -*- coding: utf-8 -*-
# Copyright 2021 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
"""
The junos ntp_global fact class
It is in this file the configuration is collected from the device
for a given resource, parsed, and the facts tree is populated
based on the configuration.
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils._text import to_bytes
from ansible.module_utils.basic import missing_required_lib
from copy import deepcopy
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import (
utils,
)
from ansible_collections.junipernetworks.junos.plugins.module_utils.network.junos.argspec.ntp_global.ntp_global import (
Ntp_globalArgs,
)
from ansible.module_utils.six import string_types
try:
from lxml import etree
HAS_LXML = True
except ImportError:
HAS_LXML = False
try:
import xmltodict
HAS_XMLTODICT = True
except ImportError:
HAS_XMLTODICT = False
class Ntp_globalFacts(object):
""" The junos ntp_global fact class
"""
def get_device_data(self, connection, config_filter):
"""
:param connection:
:param config_filter:
:return:
"""
return connection.get_configuration(filter=config_filter)
def populate_facts(self, connection, ansible_facts, data=None):
""" Populate the facts for ntp_gloabl
:param connection: the device connection
:param ansible_facts: Facts dictionary
:param data: previously collected conf
:rtype: dictionary
:returns: facts
"""
if not HAS_LXML:
self._module.fail_json(msg="lxml is not installed.")
if not data:
config_filter = """
<configuration>
<system>
<ntp>
</ntp>
</system>
</configuration>
"""
data = self.get_device_data(connection, config_filter)
if isinstance(data, string_types):
data = etree.fromstring(
to_bytes(data, errors="surrogate_then_replace")
)
objs = {}
resources = data.xpath("configuration/system/ntp")
for resource in resources:
if resource is not None:
xml = self._get_xml_dict(resource)
objs = self.render_config(self.generated_spec, xml)
facts = {}
if objs:
facts["ntp_global"] = {}
params = utils.validate_config(
self.argument_spec, {"config": objs}
)
facts["ntp_global"] = utils.remove_empties(params["config"])
ansible_facts["ansible_network_resources"].update(facts)
return ansible_facts
def render_config(self, spec, conf):
"""
Render config as dictionary structure and delete keys
from spec for null values
:param spec: The facts tree, generated from the argspec
:param conf: The configuration
:rtype: dictionary
:returns: The generated config
"""
ntp_global_config = {}
# Parse facts for BGP address-family global node
conf = conf.get("ntp")
# Read allow-duplicates node
if "authentication-key" in conf.keys():
auth_key_lst = []
auth_keys = conf.get("authentication-key")
auth_key_dict = {}
if isinstance(auth_keys, dict):
auth_key_dict["id"] = auth_keys["name"]
auth_key_dict["algorithm"] = auth_keys["type"]
auth_key_dict["key"] = auth_keys["value"]
auth_key_lst.append(auth_key_dict)
else:
for auth_key in auth_keys:
auth_key_dict["id"] = auth_key["name"]
auth_key_dict["algorithm"] = auth_key["type"]
auth_key_dict["key"] = auth_key["value"]
auth_key_lst.append(auth_key_dict)
auth_key_dict = {}
if auth_key_lst:
ntp_global_config["authentication_keys"] = auth_key_lst
# Read boot-server node
if "boot-server" in conf.keys():
ntp_global_config["boot_server"] = conf.get("boot-server")
# Read broadcast node
if "broadcast" in conf.keys():
broadcast_lst = []
broadcasts = conf.get("broadcast")
broadcast_dict = {}
if isinstance(broadcasts, dict):
broadcast_dict["address"] = broadcasts["name"]
if "key" in broadcasts.keys():
broadcast_dict["key"] = broadcasts["key"]
if "ttl" in broadcasts.keys():
broadcast_dict["ttl"] = broadcasts["ttl"]
if "version" in broadcasts.keys():
broadcast_dict["version"] = broadcasts["version"]
if "routing-instance-name" in broadcasts.keys():
broadcast_dict["routing_instance_name"] = broadcasts[
"routing-instance-name"
]
broadcast_lst.append(broadcast_dict)
else:
for broadcast in broadcasts:
broadcast_dict["address"] = broadcast["name"]
if "key" in broadcast.keys():
broadcast_dict["key"] = broadcast["key"]
if "ttl" in broadcast.keys():
broadcast_dict["ttl"] = broadcast["ttl"]
if "version" in broadcast.keys():
broadcast_dict["version"] = broadcast["version"]
if "routing-instance-name" in broadcast.keys():
broadcast_dict["routing_instance_name"] = broadcast[
"routing-instance-name"
]
broadcast_lst.append(broadcast_dict)
broadcast_dict = {}
if broadcast_lst:
ntp_global_config["broadcasts"] = broadcast_lst
# Read broadcast-client node
if "broadcast-client" in conf.keys():
ntp_global_config["broadcast_client"] = True
# Read interval-range node
if "interval-range" in conf.keys():
ntp_global_config["interval_range"] = conf["interval-range"].get(
"value"
)
# Read multicast-client node
if "multicast-client" in conf.keys():
ntp_global_config["multicast_client"] = conf[
"multicast-client"
].get("address")
# Read peer node
if "peer" in conf.keys():
peer_lst = []
peers = conf.get("peer")
peer_dict = {}
if isinstance(peers, dict):
peer_dict["peer"] = peers["name"]
if "key" in peers.keys():
peer_dict["key_id"] = peers["key"]
if "prefer" in peers.keys():
peer_dict["prefer"] = True
if "version" in peers.keys():
peer_dict["version"] = peers["version"]
peer_lst.append(peer_dict)
else:
for peer in peers:
peer_dict["peer"] = peer["name"]
if "key" in peer.keys():
peer_dict["key_id"] = peer["key"]
if "prefer" in peer.keys():
peer_dict["prefer"] = True
if "version" in peer.keys():
peer_dict["version"] = peer["version"]
peer_lst.append(peer_dict)
peer_dict = {}
if peer_lst:
ntp_global_config["peers"] = peer_lst
# Read server node
if "server" in conf.keys():
server_lst = []
servers = conf.get("server")
server_dict = {}
if isinstance(servers, dict):
server_dict["server"] = servers["name"]
if "key" in servers.keys():
server_dict["key_id"] = servers["key"]
if "prefer" in servers.keys():
server_dict["prefer"] = True
if "version" in servers.keys():
server_dict["version"] = servers["version"]
if "routing-instance" in servers.keys():
server_dict["routing-instance"] = servers[
"routing-instance"
]
server_lst.append(server_dict)
else:
for server in servers:
server_dict["server"] = server["name"]
if "key" in server.keys():
server_dict["key_id"] = server["key"]
if "prefer" in server.keys():
server_dict["prefer"] = True
if "version" in server.keys():
server_dict["version"] = server["version"]
if "routing-instance" in server.keys():
server_dict["routing_instance"] = server[
"routing-instance"
]
server_lst.append(server_dict)
server_dict = {}
if server_lst:
ntp_global_config["servers"] = server_lst
# Read source-address node
if "source-address" in conf.keys():
source_address_lst = []
source_addresses = conf.get("source-address")
source_address_dict = {}
if isinstance(source_addresses, dict):
source_address_dict["source_address"] = source_addresses[
"name"
]
if "routing-instance" in source_addresses.keys():
source_address_dict["routing_instance"] = source_addresses[
"routing-instance"
]
source_address_lst.append(source_address_dict)
else:
for source_address in source_addresses:
source_address_dict["source_address"] = source_address[
"name"
]
if "routing-instance" in source_address.keys():
source_address_dict[
"routing_instance"
] = source_address["routing-instance"]
source_address_lst.append(source_address_dict)
source_address_dict = {}
if source_address_lst:
ntp_global_config["source_addresses"] = source_address_lst
# Read threshold node
if "threshold" in conf.keys():
threshold = conf.get("threshold")
threshold_dict = {}
if "value" in threshold.keys():
threshold_dict["value"] = threshold.get("value")
if "action" in threshold.keys():
threshold_dict["action"] = threshold.get("action")
if threshold_dict:
ntp_global_config["threshold"] = threshold_dict
# read trusted-keys node
if "trusted-key" in conf.keys():
trusted_keys = conf.get("trusted-key")
trusted_keys_lst = []
trusted_keys_dict = {}
if isinstance(trusted_keys, list):
trusted_keys.sort(key=int)
for key in trusted_keys:
trusted_keys_dict["key_id"] = key
trusted_keys_lst.append(trusted_keys_dict)
trusted_keys_dict = {}
ntp_global_config["trusted_keys"] = trusted_keys_lst
else:
trusted_keys_dict["key_id"] = trusted_keys
trusted_keys_lst.append(trusted_keys_dict)
ntp_global_config["trusted_keys"] = trusted_keys_lst
return utils.remove_empties(ntp_global_config)
| [
2,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
15069,
33448,
2297,
10983,
198,
2,
22961,
3611,
5094,
13789,
410,
18,
13,
15,
10,
198,
2,
357,
3826,
27975,
45761,
393,
3740,
1378,
2503,
13,
41791,
13,
2... | 1.937919 | 6,266 |
import pyxel
import random
from pymunk import Space, Body, Circle, Poly, Segment, BB, Arbiter, Vec2d
FPS = 30
WIDTH, HEIGHT = SCREEN = (256, 196)
game = Game()
pyxel.init(WIDTH, HEIGHT, fps=FPS)
pyxel.mouse(True)
pyxel.run(game.update, game.draw)
| [
11748,
12972,
87,
417,
198,
11748,
4738,
198,
6738,
279,
4948,
2954,
1330,
4687,
11,
12290,
11,
16291,
11,
12280,
11,
1001,
5154,
11,
12597,
11,
33619,
263,
11,
38692,
17,
67,
198,
198,
37,
3705,
796,
1542,
198,
54,
2389,
4221,
11,
... | 2.367925 | 106 |
import trw
import torch.nn as nn
import torch.nn.functional as F
import os
if __name__ == '__main__':
# configure and run the training/evaluation
options = trw.train.Options(num_epochs=600)
trainer = trw.train.TrainerV2(callbacks_post_training=None)
transforms = [
trw.transforms.TransformRandomCutout(cutout_size=(3, 16, 16)),
trw.transforms.TransformRandomCropPad(padding=[0, 4, 4]),
]
#transforms = None
model = Net_simple(options)
results = trainer.fit(
options,
datasets=trw.datasets.create_cifar10_dataset(
transform_train=transforms, nb_workers=2, batch_size=1000, data_processing_batch_size=500),
log_path='cifar10_darts_search',
#model_fn=lambda options: Net_DARTS(options),
model=model,
optimizers_fn=lambda datasets, model: trw.train.create_adam_optimizers_fn(
datasets=datasets, model=model, learning_rate=0.01))
model.export_configuration(options.workflow_options.current_logging_directory)
print('DONE')
| [
11748,
491,
86,
198,
11748,
28034,
13,
20471,
355,
299,
77,
198,
11748,
28034,
13,
20471,
13,
45124,
355,
376,
198,
11748,
28686,
628,
628,
198,
361,
11593,
3672,
834,
6624,
705,
834,
12417,
834,
10354,
198,
220,
220,
220,
1303,
17425... | 2.423341 | 437 |
from PIL import Image
import os, time, discord
| [
6738,
350,
4146,
1330,
7412,
198,
11748,
28686,
11,
640,
11,
36446,
198
] | 3.615385 | 13 |
from django.contrib import admin
from admin_honeypot.admin import LoginAttemptAdmin
from admin_honeypot.models import LoginAttempt
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
admin.site.unregister(LoginAttempt)
@admin.register(LoginAttempt)
| [
6738,
42625,
14208,
13,
3642,
822,
1330,
13169,
198,
198,
6738,
13169,
62,
71,
1419,
13059,
13,
28482,
1330,
23093,
37177,
46787,
198,
6738,
13169,
62,
71,
1419,
13059,
13,
27530,
1330,
23093,
37177,
198,
6738,
42625,
14208,
13,
26791,
... | 3.471264 | 87 |
from django.shortcuts import render
from django.http import HttpResponse
from datetime import datetime
from rezepte.models import Rezept
# Create your views here.
| [
6738,
42625,
14208,
13,
19509,
23779,
1330,
8543,
198,
6738,
42625,
14208,
13,
4023,
1330,
367,
29281,
31077,
220,
198,
6738,
4818,
8079,
1330,
4818,
8079,
198,
6738,
302,
2736,
457,
68,
13,
27530,
1330,
797,
2736,
457,
198,
198,
2,
1... | 3.510638 | 47 |
from setuptools import find_packages, Extension, Command
from distutils.core import setup
from Cython.Build import cythonize
from clustertree import __version__
extensions = []
extensions.append( Extension( "clustertree.src.clustertree",
[ "clustertree/src/clustertree.pyx",
"src/cluster.c"], ) )
setup(version=__version__,
name='clustertree',
description="Kanwei Li's clustertree code",
long_description="Kanwei Li's clustertree code from bx-python",
author="Kanwei Li (Maintainer=Endre Bakken Stovner)",
author_email="endrebak85@gmail.com",
# package_dir = { '': 'lib' },
packages=find_packages(),
setup_requires=['cython'],
ext_modules=cythonize(extensions),
package_data={'': ['*.pyx', '*.pxd', '*.h', '*.c']},
include_dirs=["."],
)
| [
198,
6738,
900,
37623,
10141,
1330,
1064,
62,
43789,
11,
27995,
11,
9455,
198,
6738,
1233,
26791,
13,
7295,
1330,
9058,
628,
198,
6738,
327,
7535,
13,
15580,
1330,
3075,
400,
261,
1096,
198,
198,
6738,
32966,
861,
631,
1330,
11593,
96... | 2.306667 | 375 |
from PIL import Image
import numpy as np
from torchvision.transforms import functional as F
import torchvision.transforms as transforms
import torch
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
from tqdm import tqdm
from evaluation.recall import recall_at_ks
import time
cudnn.benchmark = True
import net
def predict_batchwise(model, dataloader):
'''
Predict on a batch
:return: list with N lists, where N = |{image, label, index}|
'''
# print(list(model.parameters())[0].device)
model_is_training = model.training
model.eval()
ds = dataloader.dataset
A = [[] for i in range(len(ds[0]))]
with torch.no_grad():
# extract batches (A becomes list of samples)
for batch in tqdm(dataloader, desc="Batch-wise prediction"):
for i, J in enumerate(batch):
# i = 0: sz_batch * images
# i = 1: sz_batch * labels
# i = 2: sz_batch * indices
if i == 0:
# move images to device of model (approximate device)
J = J.to(list(model.parameters())[0].device)
# predict model output for image
J = model(J).cpu()
for j in J:
#if i == 1: print(j)
A[i].append(j)
model.train()
model.train(model_is_training) # revert to previous training state
return [torch.stack(A[i]) for i in range(len(A))]
def evaluate(model, dataloader, eval_nmi=False, recall_list=[1, 2, 4, 8]):
'''
Evaluation on dataloader
:param model: embedding model
:param dataloader: dataloader
:param eval_nmi: evaluate NMI (Mutual information between clustering on embedding and the gt class labels) or not
:param recall_list: recall@K
'''
eval_time = time.time()
nb_classes = dataloader.dataset.nb_classes()
# calculate embeddings with model and get targets
X, T, *_ = predict_batchwise(model, dataloader)
print('done collecting prediction')
nmi, recall = recall_at_ks(X, T, ks=recall_list)
for i in recall_list:
print("Recall@{} {:.3f}".format(i, recall[i]))
return nmi, recall
if __name__ == '__main__':
_, result = eval(net.sphere().to('cuda'), model_path='checkpoint/CosFace_24_checkpoint.pth')
np.savetxt("result.txt", result, '%s')
| [
6738,
350,
4146,
1330,
7412,
201,
198,
11748,
299,
32152,
355,
45941,
201,
198,
201,
198,
6738,
28034,
10178,
13,
7645,
23914,
1330,
10345,
355,
376,
201,
198,
11748,
28034,
10178,
13,
7645,
23914,
355,
31408,
201,
198,
11748,
28034,
20... | 2.184859 | 1,136 |
import numpy as np
| [
11748,
299,
32152,
355,
45941,
628,
628
] | 3.142857 | 7 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@author: bo
@file: manage.py
@version:
@time: 2019/11/06
@function๏ผ ่ฟ่กflask
"""
from cookiespool.api import app
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8888)
| [
2,
48443,
14629,
14,
8800,
14,
29412,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
37811,
220,
198,
31,
9800,
25,
1489,
198,
31,
7753,
25,
6687,
13,
9078,
220,
198,
31,
9641,
25,
198,
31,
2435,
25,
13130,
... | 2.082569 | 109 |
# Note: you need to add Chromedriver to your env var path:
# In fish that means running:
# set PATH $HOME/bin $PATH
import time
import datetime
from splinter import Browser
browser = Browser('chrome', headless=False)
url = 'https://library.st-andrews.ac.uk/patroninfo~S5/'
browser.visit(url)
login()
due_status = get_due_status()
print('Checking items due on: ' + due_status)
if browser.is_text_present(due_status):
renew()
else:
print("Exiting: could not find any books due today :D")โ | [
2,
5740,
25,
345,
761,
284,
751,
18255,
276,
38291,
284,
534,
17365,
1401,
3108,
25,
198,
2,
554,
5916,
326,
1724,
2491,
25,
198,
2,
900,
46490,
720,
39069,
14,
8800,
720,
34219,
198,
198,
11748,
640,
198,
11748,
4818,
8079,
198,
... | 2.895954 | 173 |
#! /usr/bin/env python3
"""
Convert MIT Press XML files for CL and TACL to Anthology XML.
version 0.5 - reads from new MIT Press format.
version 0.4 - now updates XML directly, skips existing papers, sorts by page number
version 0.3 - produces anthology ID in new format 2020.cl-1.1
Example usage: unpack the ZIP file from MIT press. You'll have something like this:
./taclv9-11082021/
./xml/
tacl_a_00350.xml
tacl_a_00351.xml
tacl_a_00352.xml
...
./assets/
tacl_a_00350.pdf
tacl_a_00351.pdf
tacl_a_00352.pdf
...
Then, run
/path/to/anthology/bin/ingest_mitpress.py /path/to/taclv9-11082021/
This will
* infer the path of, then update or create the XML file, skipping existing papers
* copy new PDFs where they can be bundled up or rsynced over.
It assumes that you are working within a single collection (e.g., a single XML
file), but there can be multiple volumes (like for CL).
Warning (August 2020): not yet tested with CL, but should work!
Authors: Arya D. McCarthy, Matt Post
"""
import os
import shutil
import logging
import lxml.etree as etree
from pathlib import Path
from typing import List, Optional, Tuple
from anthology import Anthology, Paper, Volume
from normalize_anth import normalize
from anthology.utils import make_simple_element, indent, compute_hash_from_file
__version__ = "0.5"
TACL = "tacl"
CL = "cl"
def get_article_journal_info(xml_front_node: etree.Element, is_tacl: bool) -> str:
""" """
nsmap = xml_front_node.nsmap
journal_meta = xml_front_node.find("journal-meta", nsmap)
journal_title_group = journal_meta.find("journal-title-group", nsmap)
journal_title = journal_title_group.find("journal-title", nsmap)
# For some reason, sometimes this is not present, so look for this one
if journal_title is None:
journal_title = journal_title_group.find("abbrev-journal-title", nsmap)
journal_title_text = journal_title.text
article_meta = xml_front_node.find("article-meta", nsmap)
volume = article_meta.find("volume", nsmap)
# Fixes
journal_title_text = " ".join(
journal_title_text.split()
) # Sometimes it's split onto two lines...
journal_title_text = (
journal_title_text.replace( # Somebody in 2018 didn't know our name?
"Association of Computational Linguistics",
"Association for Computational Linguistics",
)
)
volume_text = volume.text.lstrip(
"0"
) # Somebody brilliant decided that 2018 would be "06" instead of "6"
if is_tacl:
issue_text = None
string_date_text = None
format_string = "{journal}, Volume {volume}"
else:
issue = article_meta.find("issue", nsmap)
issue_text = issue.text
pub_date = article_meta.find("pub-date", nsmap)
month = pub_date.find("month", nsmap).text
year = pub_date.find("year", nsmap).text
string_date_text = f"{month} {year}"
format_string = "{journal}, Volume {volume}, Issue {issue} - {date}"
data = dict(
journal=journal_title_text,
volume=volume_text,
issue=issue_text,
date=string_date_text,
)
logging.debug(format_string.format(**data))
return format_string.format(**data), issue_text
def process_xml(xml: Path, is_tacl: bool) -> Optional[etree.Element]:
""" """
logging.info("Reading {}".format(xml))
tree = etree.parse(open(str(xml)))
root = tree.getroot()
front = root.find("front", root.nsmap)
info, issue = get_article_journal_info(front, is_tacl)
paper = etree.Element("paper")
title_text = get_title(front)
title = etree.Element("title")
title.text = title_text
paper.append(title)
authors = get_authors(front)
for given_names, surname in authors:
first = etree.Element("first")
first.text = given_names
last = etree.Element("last")
last.text = surname
author = etree.Element("author")
author.append(first)
author.append(last)
paper.append(author)
doi_text = get_doi(front)
doi = etree.Element("doi")
doi.text = doi_text
paper.append(doi)
abstract_text = get_abstract(front)
if abstract_text:
make_simple_element("abstract", abstract_text, parent=paper)
pages_tuple = get_pages(front)
pages = etree.Element("pages")
pages.text = "โ".join(pages_tuple) # en-dash, not hyphen!
paper.append(pages)
return paper, info, issue
def issue_info_to_node(
issue_info: str, year_: str, volume_id: str, is_tacl: bool
) -> etree.Element:
"""Creates the meta block for a new issue / volume"""
meta = make_simple_element("meta")
assert int(year_)
make_simple_element("booktitle", issue_info, parent=meta)
make_simple_element("publisher", "MIT Press", parent=meta)
make_simple_element("address", "Cambridge, MA", parent=meta)
if not is_tacl:
month_text = issue_info.split()[-2] # blah blah blah month year
if not month_text in {
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
}:
logging.error("Unknown month: " + month_text)
make_simple_element("month", month_text, parent=meta)
make_simple_element("year", str(year_), parent=meta)
return meta
if __name__ == "__main__":
import sys
if sys.version_info < (3, 6):
sys.stderr.write("Python >=3.6 required.\n")
sys.exit(1)
import argparse
parser = argparse.ArgumentParser(description=__doc__)
anthology_path = os.path.join(os.path.dirname(sys.argv[0]), "..")
parser.add_argument(
"--anthology-dir",
"-r",
default=anthology_path,
help="Root path of ACL Anthology Github repo. Default: %(default)s.",
)
pdfs_path = os.path.join(os.environ["HOME"], "anthology-files")
parser.add_argument(
"--pdfs-dir",
"-p",
default=pdfs_path,
help="Root path for placement of PDF files",
)
verbosity = parser.add_mutually_exclusive_group()
verbosity.add_argument(
"-v", "--verbose", action="store_const", const=logging.DEBUG, default=logging.INFO
)
verbosity.add_argument(
"-q", "--quiet", dest="verbose", action="store_const", const=logging.WARNING
)
parser.add_argument("--version", action="version", version=f"%(prog)s v{__version__}")
parser.add_argument("root_dir", metavar="FOLDER", type=Path)
args = parser.parse_args()
args.root_dir = args.root_dir.resolve() # Get absolute path.
logging.basicConfig(level=args.verbose)
main(args)
| [
2,
0,
1220,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
37811,
198,
3103,
1851,
17168,
4332,
23735,
3696,
329,
7852,
290,
309,
2246,
43,
284,
8451,
1435,
23735,
13,
198,
198,
9641,
657,
13,
20,
532,
9743,
422,
649,
17168,
4332,
5794... | 2.456746 | 2,809 |
from tkinter import *
import tkinter as tk
import sqlite3
from tkinter import messagebox as MessageBox
raiz = Tk()
myframe = Frame(raiz, width = 800, height = 300)
raiz.geometry("280x160")
raiz.resizable(0,0)
myframe['bg'] = '#49A'
raiz['bg'] = '#49A'
myframe.pack()
raiz.title("CRUD PERSONAS")
c11 = StringVar()
c22 = StringVar()
c33 = StringVar()
c44 = StringVar()
c55 = StringVar()
Mymenu = tk.Menu(raiz)
filemenu = tk.Menu(Mymenu, tearoff=0)
Mymenu.add_cascade(label='BBDD', menu=filemenu)
filemenu.add_command(label='Conexiรณn', command= conec)
filemenu.add_separator()
filemenu.add_command(label='Salir', command=window)
raiz.config(menu=Mymenu)
editmenu = tk.Menu(Mymenu, tearoff=0)
Mymenu.add_cascade(label='CRUD', menu=editmenu)
editmenu.add_command(label='Crear',command= ins)
editmenu.add_command(label='Leer', command= read)
editmenu.add_command(label='Actualizar', command= up)
editmenu.add_command(label='Eliminar', command= dele)
editmenu1 = tk.Menu(Mymenu, tearoff=0)
Mymenu.add_cascade(label='Editar', menu=editmenu1)
editmenu1.add_command(label='Borrar datos',command=borrar)
m1 = Label(myframe , text = "ID:")
m1.place(x = 107, y = 10)
m1.config (bg ='#49A',fg ='white')
m2 = Label(myframe , text="Nombre:")
m2.place(x = 75, y = 40)
m2.config (bg ='#49A',fg ='white')
m3 = Label(myframe , text = "Apellido Paterno:")
m3.place(x = 32, y = 70)
m3.config (bg ='#49A',fg ='white')
m4 = Label(myframe , text = "Apellido Materno:")
m4.place(x = 29, y = 100)
m4.config (bg ='#49A',fg ='white')
m5 = Label(myframe , text = "Contraseรฑa:")
m5.place(x = 62, y = 130)
m5.config (bg ='#49A',fg ='white')
c1 = Entry(myframe, textvariable=c11 )
c1.place(x = 140, y = 10)
c2 = Entry(myframe, textvariable=c22 )
c2.place(x = 140, y = 40)
c3 = Entry(myframe, textvariable=c33 )
c3.place(x = 140, y = 70)
c4 = Entry(myframe, textvariable=c44 )
c4.place(x = 140, y = 100)
c5 = Entry(myframe, textvariable=c55 )
c5.place(x = 140, y = 130)
raiz.mainloop() | [
6738,
256,
74,
3849,
1330,
1635,
198,
11748,
256,
74,
3849,
355,
256,
74,
198,
11748,
44161,
578,
18,
220,
198,
6738,
256,
74,
3849,
1330,
3275,
3524,
355,
16000,
14253,
198,
430,
528,
796,
309,
74,
3419,
198,
1820,
14535,
796,
2518... | 2.330969 | 846 |
from qface.generator import FileSystem, Generator
import logging.config
import argparse
from path import Path
import qface
import subprocess
import sys
import os
parser = argparse.ArgumentParser(description='Generates bindings for Tmds based on the qface IDL.')
parser.add_argument('--input', dest='input', type=str, required=True, nargs='+',
help='input qface interfaces, folders will be globbed looking for qface interfaces')
parser.add_argument('--output', dest='output', type=str, required=False, default='.',
help='relative output path of the generated code, default value is current directory')
parser.add_argument('--dependency', dest='dependency', type=str, required=False, nargs='+', default=[],
help='path to dependency qface interfaces, leave empty if there is no interdependency')
args = parser.parse_args()
FileSystem.strict = True
Generator.strict = True
setattr(qface.idl.domain.TypeSymbol, 'qfacedotnet_type', property(qfacedotnet_type))
setattr(qface.idl.domain.Field, 'qfacedotnet_type', property(qfacedotnet_type))
setattr(qface.idl.domain.Operation, 'qfacedotnet_type', property(qfacedotnet_type))
setattr(qface.idl.domain.Property, 'qfacedotnet_type', property(qfacedotnet_type))
setattr(qface.idl.domain.Parameter, 'qfacedotnet_type', property(qfacedotnet_type))
setattr(qface.idl.domain.Property, 'cap_name', property(cap_name))
setattr(qface.idl.domain.Property, 'qfacedotnet_concrete_type', property(qfacedotnet_concrete_type))
setattr(qface.idl.domain.Operation, 'has_return_value', property(has_return_value))
here = Path(__file__).dirname()
system = FileSystem.parse(args.input)
modulesToGenerate = [module.name for module in system.modules]
system = FileSystem.parse(args.input + args.dependency)
output = args.output
generator = Generator(search_path=Path(here / 'templates'))
generator.destination = output
ctx = {'output': output}
for module in system.modules:
if module.name in modulesToGenerate:
for interface in module.interfaces:
ctx.update({'module': module})
ctx.update({'interface': interface})
module_path = '/'.join(module.name_parts)
ctx.update({'path': module_path})
generator.write('{{path}}/I' + interface.name + '.cs', 'InterfaceBase.cs.template', ctx)
generator.write('{{path}}/I' + interface.name + 'DBus.cs', 'DBusInterface.cs.template', ctx)
generator.write('{{path}}/' + interface.name + 'DBusAdapter.cs', 'DBusAdapter.cs.template', ctx)
generator.write('{{path}}/' + interface.name + 'DBusProxy.cs', 'DBusProxy.cs.template', ctx)
for struct in module.structs:
ctx.update({'module': module})
ctx.update({'struct': struct})
module_path = '/'.join(module.name_parts)
ctx.update({'path': module_path})
generator.write('{{path}}/' + struct.name + '.cs', 'Struct.cs.template', ctx)
for enum in module.enums:
ctx.update({'module': module})
ctx.update({'enum': enum})
module_path = '/'.join(module.name_parts)
ctx.update({'path': module_path})
generator.write('{{path}}/' + enum.name + '.cs', 'Enum.cs.template', ctx)
| [
6738,
10662,
2550,
13,
8612,
1352,
1330,
9220,
11964,
11,
35986,
198,
11748,
18931,
13,
11250,
198,
11748,
1822,
29572,
198,
6738,
3108,
1330,
10644,
198,
11748,
10662,
2550,
198,
11748,
850,
14681,
198,
11748,
25064,
198,
11748,
28686,
1... | 2.613238 | 1,254 |
from flask_login import UserMixin
from woeclipse.website import db, login_manager
# Tables
# Link Table USER EVENT
user_event = db.Table(
'user_event', db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
db.Column('event_id', db.Integer, db.ForeignKey('event.id')))
# Models
# TODO: delete user + avatar cascading
# Connect flask login with the user records in our database:
@login_manager.user_loader
| [
6738,
42903,
62,
38235,
1330,
11787,
35608,
259,
198,
198,
6738,
266,
2577,
17043,
13,
732,
12485,
1330,
20613,
11,
17594,
62,
37153,
628,
198,
2,
33220,
198,
198,
2,
7502,
8655,
1294,
1137,
49261,
198,
7220,
62,
15596,
796,
20613,
13... | 3.021127 | 142 |
from typing import List
import scrapy
| [
6738,
19720,
1330,
7343,
198,
198,
11748,
15881,
88,
628
] | 4 | 10 |
from pdb import DefaultConfig
| [
6738,
279,
9945,
1330,
15161,
16934,
628
] | 4.428571 | 7 |
#
# PySNMP MIB module HUAWEI-GTSM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-GTSM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:44:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint")
hwDatacomm, = mibBuilder.importSymbols("HUAWEI-MIB", "hwDatacomm")
InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
Integer32, ObjectIdentity, iso, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, IpAddress, MibIdentifier, Counter32, Counter64, ModuleIdentity, Unsigned32, Bits, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "ObjectIdentity", "iso", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "IpAddress", "MibIdentifier", "Counter32", "Counter64", "ModuleIdentity", "Unsigned32", "Bits", "Gauge32")
DisplayString, RowStatus, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "RowStatus", "TextualConvention")
hwGTSMModule = ModuleIdentity((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126))
hwGTSMModule.setRevisions(('2006-09-05 19:38',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: hwGTSMModule.setRevisionsDescriptions(('The initial revision of this MIB module.',))
if mibBuilder.loadTexts: hwGTSMModule.setLastUpdated('200611131938Z')
if mibBuilder.loadTexts: hwGTSMModule.setOrganization('Huawei Technologies co.,Ltd.')
if mibBuilder.loadTexts: hwGTSMModule.setContactInfo('VRP Team Huawei Technologies co.,Ltd. Huawei Bld.,NO.3 Xinxi Rd., Shang-Di Information Industry Base, Hai-Dian District Beijing P.R. China http://www.huawei.com Zip:100085 ')
if mibBuilder.loadTexts: hwGTSMModule.setDescription('The HUAWEI-GTSM-MIB contains all the objects that manages GTSM, it mainly contains the following five parts. 1) Default action that is used to deal with the received packets when no GTSM policy matches. 2) Policy table that is used to get or set the GTSM policy. 3) BGP peer group table that is used to get or set the GTSM policy for BGP peer group. 4) Statistics table that is used to compute the number of the packets containing received packets, passing packets and dropped packets. 5) Global configuration clear statistics table that is used to clear all statistics. The table can be used any time when users want to initialize the counter.')
hwGTSM = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1))
hwGTSMDefaultAction = MibScalar((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("pass", 1), ("drop", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hwGTSMDefaultAction.setStatus('current')
if mibBuilder.loadTexts: hwGTSMDefaultAction.setDescription('The object specifies the default action when no matching policy exists. Default value is pass.')
hwGTSMPolicyTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 2), )
if mibBuilder.loadTexts: hwGTSMPolicyTable.setStatus('current')
if mibBuilder.loadTexts: hwGTSMPolicyTable.setDescription('Information about GTSM policies. This object is used to get GTSM policy(policies), create a new policy, modify or delete GTSM policy (policies).')
hwGTSMPolicyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 2, 1), ).setIndexNames((0, "HUAWEI-GTSM-MIB", "hwGTSMvrfIndex"), (0, "HUAWEI-GTSM-MIB", "hwGTSMPolicyAddressType"), (0, "HUAWEI-GTSM-MIB", "hwGTSMPolicyProtocol"), (0, "HUAWEI-GTSM-MIB", "hwGTSMPolicySourceIpAddress"), (0, "HUAWEI-GTSM-MIB", "hwGTSMPolicyDestIpAddress"), (0, "HUAWEI-GTSM-MIB", "hwGTSMPolicySourcePort"), (0, "HUAWEI-GTSM-MIB", "hwGTSMPolicyDestPort"))
if mibBuilder.loadTexts: hwGTSMPolicyEntry.setStatus('current')
if mibBuilder.loadTexts: hwGTSMPolicyEntry.setDescription('Information about GTSM policies,it used to get gtsm policy(policies),to create a new policy,to modify or to delete gtsm policy(policies).')
hwGTSMvrfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)))
if mibBuilder.loadTexts: hwGTSMvrfIndex.setStatus('current')
if mibBuilder.loadTexts: hwGTSMvrfIndex.setDescription('The index of VPN Routing and Forwarding table.')
hwGTSMPolicyAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 2, 1, 2), InetAddressType())
if mibBuilder.loadTexts: hwGTSMPolicyAddressType.setStatus('current')
if mibBuilder.loadTexts: hwGTSMPolicyAddressType.setDescription('The type of Internet address by where the packets received and will go.')
hwGTSMPolicyProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255)))
if mibBuilder.loadTexts: hwGTSMPolicyProtocol.setStatus('current')
if mibBuilder.loadTexts: hwGTSMPolicyProtocol.setDescription('The number of protocol.')
hwGTSMPolicySourceIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 2, 1, 4), InetAddress())
if mibBuilder.loadTexts: hwGTSMPolicySourceIpAddress.setStatus('current')
if mibBuilder.loadTexts: hwGTSMPolicySourceIpAddress.setDescription('Source IP address in the GTSM policy that will be used to check the matching of source IP address in the received packets.')
hwGTSMPolicyDestIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 2, 1, 5), InetAddress())
if mibBuilder.loadTexts: hwGTSMPolicyDestIpAddress.setStatus('current')
if mibBuilder.loadTexts: hwGTSMPolicyDestIpAddress.setDescription('Destination IP address in the GTSM policy that will be used to check the matching of destination IP address in the received packets.')
hwGTSMPolicySourcePort = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)))
if mibBuilder.loadTexts: hwGTSMPolicySourcePort.setStatus('current')
if mibBuilder.loadTexts: hwGTSMPolicySourcePort.setDescription('Source port number in the GTSM policy that will be used to check the matching of source port number in the received packets.')
hwGTSMPolicyDestPort = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 2, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)))
if mibBuilder.loadTexts: hwGTSMPolicyDestPort.setStatus('current')
if mibBuilder.loadTexts: hwGTSMPolicyDestPort.setDescription('Destination port number in the GTSM policy that will be used to check the matching of destination port number in the received packets.')
hwGTSMPolicyTTLMin = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 2, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hwGTSMPolicyTTLMin.setStatus('current')
if mibBuilder.loadTexts: hwGTSMPolicyTTLMin.setDescription('The minimum TTL in the policy table. The minimum TTL is compared with the TTL in the packets to check whether the minimum TTL is between the minimum TTL and maximum TTL, and thus check the validity of the received packets.')
hwGTSMPolicyTTLMax = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 2, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hwGTSMPolicyTTLMax.setStatus('current')
if mibBuilder.loadTexts: hwGTSMPolicyTTLMax.setDescription('The maximum TTL in policy table that is compared with the TTL in the packets to check whether it is between the minimum TTL and maximum TTL ,and thus check the validity of the received packets. Default value is 255.')
hwGTSMPolicyRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 2, 1, 51), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hwGTSMPolicyRowStatus.setStatus('current')
if mibBuilder.loadTexts: hwGTSMPolicyRowStatus.setDescription('The operating state of the row.')
hwGTSMBgpPeergroupTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 3), )
if mibBuilder.loadTexts: hwGTSMBgpPeergroupTable.setStatus('current')
if mibBuilder.loadTexts: hwGTSMBgpPeergroupTable.setDescription('The table of BGP peer group policies. The table contains all the BGP peer group policies.')
hwGTSMBgpPeergroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 3, 1), ).setIndexNames((0, "HUAWEI-GTSM-MIB", "hwGTSMvrfIndex"), (0, "HUAWEI-GTSM-MIB", "hwGTSMBgpPeergroupName"))
if mibBuilder.loadTexts: hwGTSMBgpPeergroupEntry.setStatus('current')
if mibBuilder.loadTexts: hwGTSMBgpPeergroupEntry.setDescription('Information about BGP peer group policies. This table is used to get BGP peer group policy (policies), create a policy, modify or delete BGP peer group policy (policies).')
hwGTSMBgpPeergroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 3, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 47)))
if mibBuilder.loadTexts: hwGTSMBgpPeergroupName.setStatus('current')
if mibBuilder.loadTexts: hwGTSMBgpPeergroupName.setDescription('Peer group name in the BGP policy table that is compared with the peer group name to decide whether to apply this policy.')
hwGTSMBgpPeergroupTTLMin = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 3, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hwGTSMBgpPeergroupTTLMin.setStatus('current')
if mibBuilder.loadTexts: hwGTSMBgpPeergroupTTLMin.setDescription('The minimum TTL in policy table that is compared with the TTL in the packets to check whether it is between the minimum TTL and maximum TTL, and thus check the validity of the received packets.')
hwGTSMBgpPeergroupTTLMax = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 3, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hwGTSMBgpPeergroupTTLMax.setStatus('current')
if mibBuilder.loadTexts: hwGTSMBgpPeergroupTTLMax.setDescription('The maximum TTL in policy table that is compared with the TTL in the packets to check whether it is between the minimum TTL and maximum TTL, and check the validity of the received packets. Default value is 255.')
hwGTSMBgpPeergroupRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 3, 1, 51), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hwGTSMBgpPeergroupRowStatus.setStatus('current')
if mibBuilder.loadTexts: hwGTSMBgpPeergroupRowStatus.setDescription('The operating state of the row.')
hwGTSMStatisticsTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 4), )
if mibBuilder.loadTexts: hwGTSMStatisticsTable.setStatus('current')
if mibBuilder.loadTexts: hwGTSMStatisticsTable.setDescription('The table of GTSM Statistics table. The table contains the number of the packets containing received packets, passed packets and discarded packets.')
hwGTSMStatisticsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 4, 1), ).setIndexNames((0, "HUAWEI-GTSM-MIB", "hwGTSMSlotIndex"))
if mibBuilder.loadTexts: hwGTSMStatisticsEntry.setStatus('current')
if mibBuilder.loadTexts: hwGTSMStatisticsEntry.setDescription('The information of GTSM Statistics,it only can be read.')
hwGTSMSlotIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 128)))
if mibBuilder.loadTexts: hwGTSMSlotIndex.setStatus('current')
if mibBuilder.loadTexts: hwGTSMSlotIndex.setDescription('The Index of Slot which receives the packets.')
hwGTSMStatisticsRcvPacketNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 4, 1, 11), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hwGTSMStatisticsRcvPacketNumber.setStatus('current')
if mibBuilder.loadTexts: hwGTSMStatisticsRcvPacketNumber.setDescription('The total number of received packets of specific slot.')
hwGTSMStatisticsPassPacketNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 4, 1, 12), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hwGTSMStatisticsPassPacketNumber.setStatus('current')
if mibBuilder.loadTexts: hwGTSMStatisticsPassPacketNumber.setDescription('The total number of packets that have been transferred to the up layer after packets of specific slot are received.')
hwGTSMStatisticsDropPacketNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 4, 1, 13), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hwGTSMStatisticsDropPacketNumber.setStatus('current')
if mibBuilder.loadTexts: hwGTSMStatisticsDropPacketNumber.setDescription('The total number of packets that do not match the specific GTSM policy when packets of specific slot are received.')
hwGTSMGlobalConfigTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 5), )
if mibBuilder.loadTexts: hwGTSMGlobalConfigTable.setStatus('current')
if mibBuilder.loadTexts: hwGTSMGlobalConfigTable.setDescription('The table of GTSM global configuration table. The table contains all information you have operated to the statistics table.')
hwGTSMGlobalConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 5, 1), ).setIndexNames((0, "HUAWEI-GTSM-MIB", "hwGTSMSlotIndex"))
if mibBuilder.loadTexts: hwGTSMGlobalConfigEntry.setStatus('current')
if mibBuilder.loadTexts: hwGTSMGlobalConfigEntry.setDescription('The information of GTSM global configuration table.The table is used to clear all statistics, you can use this table any time when you want to initialize the counter.')
hwGTSMGlobalConfigClearStatistics = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 5, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 255))).clone(namedValues=NamedValues(("reset", 1), ("unused", 255)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hwGTSMGlobalConfigClearStatistics.setStatus('current')
if mibBuilder.loadTexts: hwGTSMGlobalConfigClearStatistics.setDescription('It is used to clear the statistics of the GTSM global configuration table.')
hwGTSMGlobalConfigLogDroppedPacket = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 5, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("log", 1), ("nolog", 2))).clone('nolog')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hwGTSMGlobalConfigLogDroppedPacket.setStatus('current')
if mibBuilder.loadTexts: hwGTSMGlobalConfigLogDroppedPacket.setDescription('It is used to decide whether to log the dropped packets.')
hwGTSMStatisticsInfoTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 6), )
if mibBuilder.loadTexts: hwGTSMStatisticsInfoTable.setStatus('current')
if mibBuilder.loadTexts: hwGTSMStatisticsInfoTable.setDescription('The table of GTSM Statistics Information. The table contains the number of the packets containing received packets, passed packets and discarded packets.')
hwGTSMStatisticsInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 6, 1), ).setIndexNames((0, "HUAWEI-GTSM-MIB", "hwGTSMSlotNum"), (0, "HUAWEI-GTSM-MIB", "hwGTSMPolicyAddressType"), (0, "HUAWEI-GTSM-MIB", "hwGTSMPolicyProtocol"))
if mibBuilder.loadTexts: hwGTSMStatisticsInfoEntry.setStatus('current')
if mibBuilder.loadTexts: hwGTSMStatisticsInfoEntry.setDescription('The information of GTSM Statistics,it only can be read.')
hwGTSMSlotNum = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 128)))
if mibBuilder.loadTexts: hwGTSMSlotNum.setStatus('current')
if mibBuilder.loadTexts: hwGTSMSlotNum.setDescription('The Index of Slot which receives the packets.')
hwGTSMStatisticsReceivePacketNum = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 6, 1, 11), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hwGTSMStatisticsReceivePacketNum.setStatus('current')
if mibBuilder.loadTexts: hwGTSMStatisticsReceivePacketNum.setDescription('The total number of received packets of specific slot.')
hwGTSMStatisticsPassPacketNum = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 6, 1, 12), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hwGTSMStatisticsPassPacketNum.setStatus('current')
if mibBuilder.loadTexts: hwGTSMStatisticsPassPacketNum.setDescription('The total number of packets that have been transferred to the up layer after packets of specific slot are received.')
hwGTSMStatisticsDropPacketNum = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 6, 1, 13), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hwGTSMStatisticsDropPacketNum.setStatus('current')
if mibBuilder.loadTexts: hwGTSMStatisticsDropPacketNum.setDescription('The total number of packets that do not match the specific GTSM policy when packets of specific slot are received.')
hwGTSMGlobalConfigInfoTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 7), )
if mibBuilder.loadTexts: hwGTSMGlobalConfigInfoTable.setStatus('current')
if mibBuilder.loadTexts: hwGTSMGlobalConfigInfoTable.setDescription('The table of GTSM global configuration table. The table contains all information you have operated to the statistics table.')
hwGTSMGlobalConfigInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 7, 1), ).setIndexNames((0, "HUAWEI-GTSM-MIB", "hwGTSMSlotNum"))
if mibBuilder.loadTexts: hwGTSMGlobalConfigInfoEntry.setStatus('current')
if mibBuilder.loadTexts: hwGTSMGlobalConfigInfoEntry.setDescription('The information of GTSM global configuration table.The table is used to clear all statistics, you can use this table any time when you want to initialize the counter.')
hwGTSMGlobalConfigClearStatisticsInfo = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 7, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 255))).clone(namedValues=NamedValues(("reset", 1), ("unused", 255)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hwGTSMGlobalConfigClearStatisticsInfo.setStatus('current')
if mibBuilder.loadTexts: hwGTSMGlobalConfigClearStatisticsInfo.setDescription('It is used to clear the statistics of the GTSM global configuration table.')
hwGTSMGlobalConfigLogDroppedPacketInfo = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 1, 7, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("log", 1), ("nolog", 2))).clone('nolog')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hwGTSMGlobalConfigLogDroppedPacketInfo.setStatus('current')
if mibBuilder.loadTexts: hwGTSMGlobalConfigLogDroppedPacketInfo.setDescription('It is used to decide whether to log the dropped packets.')
hwGTSMConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 2))
hwGTSMCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 2, 1))
hwGTSMCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 2, 1, 1)).setObjects(("HUAWEI-GTSM-MIB", "hwGTSMDefaultActionGroup"), ("HUAWEI-GTSM-MIB", "hwGTSMPolicyGroup"), ("HUAWEI-GTSM-MIB", "hwGTSMBgpPeergroupGroup"), ("HUAWEI-GTSM-MIB", "hwGTSMStatisticsGroup"), ("HUAWEI-GTSM-MIB", "hwGTSMGlobalConfigGroup"), ("HUAWEI-GTSM-MIB", "hwGTSMStatisticsInfoGroup"), ("HUAWEI-GTSM-MIB", "hwGTSMGlobalConfigInfoGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hwGTSMCompliance = hwGTSMCompliance.setStatus('current')
if mibBuilder.loadTexts: hwGTSMCompliance.setDescription('The compliance statement for systems supporting this module.')
hwGTSMGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 2, 2))
hwGTSMDefaultActionGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 2, 2, 1)).setObjects(("HUAWEI-GTSM-MIB", "hwGTSMDefaultAction"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hwGTSMDefaultActionGroup = hwGTSMDefaultActionGroup.setStatus('current')
if mibBuilder.loadTexts: hwGTSMDefaultActionGroup.setDescription('The default action group.')
hwGTSMPolicyGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 2, 2, 2)).setObjects(("HUAWEI-GTSM-MIB", "hwGTSMPolicyTTLMin"), ("HUAWEI-GTSM-MIB", "hwGTSMPolicyTTLMax"), ("HUAWEI-GTSM-MIB", "hwGTSMPolicyRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hwGTSMPolicyGroup = hwGTSMPolicyGroup.setStatus('current')
if mibBuilder.loadTexts: hwGTSMPolicyGroup.setDescription('The GTSM policy group.')
hwGTSMBgpPeergroupGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 2, 2, 3)).setObjects(("HUAWEI-GTSM-MIB", "hwGTSMBgpPeergroupTTLMin"), ("HUAWEI-GTSM-MIB", "hwGTSMBgpPeergroupTTLMax"), ("HUAWEI-GTSM-MIB", "hwGTSMBgpPeergroupRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hwGTSMBgpPeergroupGroup = hwGTSMBgpPeergroupGroup.setStatus('current')
if mibBuilder.loadTexts: hwGTSMBgpPeergroupGroup.setDescription('The GTSM BGP peer group.')
hwGTSMStatisticsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 2, 2, 4)).setObjects(("HUAWEI-GTSM-MIB", "hwGTSMStatisticsRcvPacketNumber"), ("HUAWEI-GTSM-MIB", "hwGTSMStatisticsPassPacketNumber"), ("HUAWEI-GTSM-MIB", "hwGTSMStatisticsDropPacketNumber"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hwGTSMStatisticsGroup = hwGTSMStatisticsGroup.setStatus('current')
if mibBuilder.loadTexts: hwGTSMStatisticsGroup.setDescription('The GTSM statistics group.')
hwGTSMGlobalConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 2, 2, 5)).setObjects(("HUAWEI-GTSM-MIB", "hwGTSMGlobalConfigClearStatistics"), ("HUAWEI-GTSM-MIB", "hwGTSMGlobalConfigLogDroppedPacket"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hwGTSMGlobalConfigGroup = hwGTSMGlobalConfigGroup.setStatus('current')
if mibBuilder.loadTexts: hwGTSMGlobalConfigGroup.setDescription('The GTSM global configuration group.')
hwGTSMStatisticsInfoGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 2, 2, 6)).setObjects(("HUAWEI-GTSM-MIB", "hwGTSMStatisticsReceivePacketNum"), ("HUAWEI-GTSM-MIB", "hwGTSMStatisticsPassPacketNum"), ("HUAWEI-GTSM-MIB", "hwGTSMStatisticsDropPacketNum"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hwGTSMStatisticsInfoGroup = hwGTSMStatisticsInfoGroup.setStatus('current')
if mibBuilder.loadTexts: hwGTSMStatisticsInfoGroup.setDescription('The GTSM statistics group.')
hwGTSMGlobalConfigInfoGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 5, 25, 126, 2, 2, 7)).setObjects(("HUAWEI-GTSM-MIB", "hwGTSMGlobalConfigClearStatisticsInfo"), ("HUAWEI-GTSM-MIB", "hwGTSMGlobalConfigLogDroppedPacketInfo"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hwGTSMGlobalConfigInfoGroup = hwGTSMGlobalConfigInfoGroup.setStatus('current')
if mibBuilder.loadTexts: hwGTSMGlobalConfigInfoGroup.setDescription('The GTSM global configuration group.')
mibBuilder.exportSymbols("HUAWEI-GTSM-MIB", hwGTSMPolicyDestPort=hwGTSMPolicyDestPort, hwGTSMStatisticsTable=hwGTSMStatisticsTable, hwGTSMStatisticsReceivePacketNum=hwGTSMStatisticsReceivePacketNum, hwGTSMSlotIndex=hwGTSMSlotIndex, hwGTSM=hwGTSM, hwGTSMStatisticsPassPacketNum=hwGTSMStatisticsPassPacketNum, hwGTSMStatisticsDropPacketNumber=hwGTSMStatisticsDropPacketNumber, hwGTSMPolicyDestIpAddress=hwGTSMPolicyDestIpAddress, hwGTSMCompliance=hwGTSMCompliance, hwGTSMPolicySourcePort=hwGTSMPolicySourcePort, hwGTSMCompliances=hwGTSMCompliances, hwGTSMGlobalConfigInfoGroup=hwGTSMGlobalConfigInfoGroup, hwGTSMSlotNum=hwGTSMSlotNum, hwGTSMStatisticsInfoGroup=hwGTSMStatisticsInfoGroup, hwGTSMModule=hwGTSMModule, hwGTSMPolicyRowStatus=hwGTSMPolicyRowStatus, hwGTSMBgpPeergroupName=hwGTSMBgpPeergroupName, hwGTSMPolicyTTLMin=hwGTSMPolicyTTLMin, hwGTSMBgpPeergroupTable=hwGTSMBgpPeergroupTable, hwGTSMGlobalConfigInfoEntry=hwGTSMGlobalConfigInfoEntry, hwGTSMBgpPeergroupGroup=hwGTSMBgpPeergroupGroup, hwGTSMConformance=hwGTSMConformance, hwGTSMStatisticsPassPacketNumber=hwGTSMStatisticsPassPacketNumber, hwGTSMGlobalConfigClearStatisticsInfo=hwGTSMGlobalConfigClearStatisticsInfo, PYSNMP_MODULE_ID=hwGTSMModule, hwGTSMPolicyAddressType=hwGTSMPolicyAddressType, hwGTSMPolicySourceIpAddress=hwGTSMPolicySourceIpAddress, hwGTSMBgpPeergroupTTLMax=hwGTSMBgpPeergroupTTLMax, hwGTSMStatisticsDropPacketNum=hwGTSMStatisticsDropPacketNum, hwGTSMGlobalConfigInfoTable=hwGTSMGlobalConfigInfoTable, hwGTSMStatisticsRcvPacketNumber=hwGTSMStatisticsRcvPacketNumber, hwGTSMGlobalConfigTable=hwGTSMGlobalConfigTable, hwGTSMGlobalConfigClearStatistics=hwGTSMGlobalConfigClearStatistics, hwGTSMBgpPeergroupEntry=hwGTSMBgpPeergroupEntry, hwGTSMGroups=hwGTSMGroups, hwGTSMDefaultActionGroup=hwGTSMDefaultActionGroup, hwGTSMGlobalConfigLogDroppedPacket=hwGTSMGlobalConfigLogDroppedPacket, hwGTSMGlobalConfigGroup=hwGTSMGlobalConfigGroup, hwGTSMPolicyProtocol=hwGTSMPolicyProtocol, hwGTSMvrfIndex=hwGTSMvrfIndex, hwGTSMBgpPeergroupTTLMin=hwGTSMBgpPeergroupTTLMin, hwGTSMPolicyTTLMax=hwGTSMPolicyTTLMax, hwGTSMStatisticsInfoTable=hwGTSMStatisticsInfoTable, hwGTSMPolicyTable=hwGTSMPolicyTable, hwGTSMPolicyEntry=hwGTSMPolicyEntry, hwGTSMPolicyGroup=hwGTSMPolicyGroup, hwGTSMGlobalConfigLogDroppedPacketInfo=hwGTSMGlobalConfigLogDroppedPacketInfo, hwGTSMGlobalConfigEntry=hwGTSMGlobalConfigEntry, hwGTSMStatisticsGroup=hwGTSMStatisticsGroup, hwGTSMStatisticsInfoEntry=hwGTSMStatisticsInfoEntry, hwGTSMBgpPeergroupRowStatus=hwGTSMBgpPeergroupRowStatus, hwGTSMDefaultAction=hwGTSMDefaultAction, hwGTSMStatisticsEntry=hwGTSMStatisticsEntry)
| [
2,
198,
2,
9485,
15571,
7378,
337,
9865,
8265,
367,
34970,
8845,
40,
12,
38,
4694,
44,
12,
8895,
33,
357,
4023,
1378,
16184,
76,
489,
8937,
13,
785,
14,
79,
893,
11632,
8,
198,
2,
7054,
45,
13,
16,
2723,
2393,
1378,
14,
14490,
... | 2.802748 | 9,242 |
from django.contrib import admin
from . models import project,skill,Contact
admin.site.register(project)
admin.site.register(skill)
admin.site.register(Contact) | [
6738,
42625,
14208,
13,
3642,
822,
1330,
13169,
198,
198,
6738,
764,
4981,
1330,
1628,
11,
42401,
11,
17829,
198,
198,
28482,
13,
15654,
13,
30238,
7,
16302,
8,
198,
28482,
13,
15654,
13,
30238,
7,
42401,
8,
198,
28482,
13,
15654,
1... | 3.446809 | 47 |
import math
user_num = int(input())
sumfind = int(0)
a = []
b = []
if(user_num != 0):
size = int(math.log10(user_num)+1)
splitter(size, user_num)
das_finder()
else:
print(1)
| [
11748,
10688,
198,
198,
7220,
62,
22510,
796,
493,
7,
15414,
28955,
628,
198,
16345,
19796,
796,
493,
7,
15,
8,
628,
198,
64,
796,
17635,
198,
65,
796,
17635,
628,
628,
198,
361,
7,
7220,
62,
22510,
14512,
657,
2599,
198,
220,
220... | 2.105263 | 95 |
import os
import geopandas as gpd
import io
import requests
import zipfile
from zipfile import BadZipfile
def open_zips(url, shapefile):
"""opens zipped shapefiles from a url and clips data according to a
region of interest defined by a shapefile before saving as a geopandas dataframe
Parameters
-----------
url : path to a zipped shapefile
shapefile: a shapefile for region of interest
Returns
-----------
gpd : a clipped geopandas geodataframe
"""
local_path = os.path.join('data')
if url.endswith(".zip"):
print("Great - this is a .zip file")
r = requests.get(url)
if r.status_code == 404:
print('Status code 404, check that correct url is provided')
else:
try:
z = zipfile.ZipFile(io.BytesIO(r.content))
z.extractall(path=local_path) # extract to folder
filenames = [y for y in sorted(z.namelist()) for ending in ['dbf', 'prj', 'shp', 'shx'] if y.endswith(ending)]
print(filenames)
dbf, prj, shp, shx = [filename for filename in filenames]
gpdfile = gpd.overlay(gpd.read_file(local_path + '/' + shp).to_crs(shapefile.crs), shapefile, how = 'intersection')
print("Done")
print("Shape of the dataframe: {}".format(gpdfile.shape))
print("Projection of dataframe: {}".format(gpdfile.crs))
return(gpdfile)
except BadZipfile:
print("url and data format (.zip) should be OK, check for other errors")
else:
print("Url does not end in .zip. Check file format, open_zips wants to open zipped files")
def df_to_gdf(input_df, shapefile):
"""
Convert a DataFrame with longitude and latitude columns
to a GeoDataFrame.
"""
geometry = [Point(xy) for xy in zip(input_df.long, input_df.lat)]
return gpd.clip(gpd.GeoDataFrame(input_df, crs=shapefile.crs, geometry=geometry), shapefile)
| [
11748,
28686,
198,
11748,
30324,
392,
292,
355,
27809,
67,
198,
11748,
33245,
198,
11748,
7007,
198,
11748,
19974,
7753,
198,
6738,
19974,
7753,
1330,
7772,
41729,
7753,
198,
198,
4299,
1280,
62,
89,
2419,
7,
6371,
11,
5485,
7753,
2599,... | 2.352047 | 855 |
"""
## ะะฟะธัะฐะฝะธะต ะทะฐะดะฐัะธ
ะะฐะฟะธัะฐัั ััะฝะบัะธั `squareSequenceDigit()`, ะณะดะต ัะตัะฐะปะฐัั ะฑั
ัะปะตะดัััะฐั ะทะฐะดะฐัะฐ. ะะฐะนัะธ n-ั ัะธััั ะฟะพัะปะตะดะพะฒะฐัะตะปัะฝะพััะธ ะธะท ะบะฒะฐะดัะฐัะพะฒ
ัะตะปัั
ัะธัะตะป: `149162536496481100121144...`
ะะฐะฟัะธะผะตั, 2-ั ัะธััะฐ ัะฐะฒะฝะฐ 4, 7-ั 5, 12-ั 6. ะัะฟะพะปัะทะพะฒะฐัั ะพะฟะตัะฐัะธะธ
ัะพ ัััะพะบะฐะผะธ ะฒ ััะพะน ะทะฐะดะฐัะต ะทะฐะฟัะตัะฐะตััั.
ะัะพัะตััะธัะพะฒะฐัั ะฒัะฟะพะปะฝะตะฝะธะต ะฟัะพะณัะฐะผะผั ัะพ ัะปะตะดัััะธะผะธ ะทะฝะฐัะตะฝะธัะผะธ:
* ะฟัะธ ะฒัะทะพะฒะต squareSequenceDigit(1) ะดะพะปะถะฝะพ ะฑััั 1;
* squareSequenceDigit(2) ะฒะตัะฝัั 4;
* squareSequenceDigit(7) ะฒะตัะฝัั 5;
* squareSequenceDigit(12) ะฒะตัะฝัั 6;
* squareSequenceDigit(17) ะฒะตัะฝัั 0;
* squareSequenceDigit(27) ะฒะตัะฝัั 9.
"""
import math
if __name__ == "__lab1__":
square_sequence_digit(1)
square_sequence_digit(2)
square_sequence_digit(7)
square_sequence_digit(12)
square_sequence_digit(17)
square_sequence_digit(27)
| [
37811,
198,
220,
220,
220,
22492,
12466,
252,
140,
123,
18849,
21727,
16142,
22177,
18849,
16843,
12466,
115,
16142,
43666,
16142,
141,
229,
18849,
198,
220,
220,
220,
12466,
251,
16142,
140,
123,
18849,
21727,
16142,
20375,
45367,
220,
1... | 1.396774 | 620 |
'''
Created on May 31, 2016
@author: yglazner
'''
import unittest
import threading
from cheesyweb import *
import logging
import time
import requests
_app = None
log = logging.getLogger("Logger")
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
logging.basicConfig(level=logging.DEBUG)
unittest.main(argv=['', '-v']) | [
7061,
6,
198,
41972,
319,
1737,
3261,
11,
1584,
198,
198,
31,
9800,
25,
331,
4743,
1031,
1008,
198,
7061,
6,
198,
11748,
555,
715,
395,
198,
11748,
4704,
278,
198,
6738,
45002,
12384,
1330,
1635,
198,
11748,
18931,
198,
11748,
640,
... | 2.684211 | 133 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tests for the file filters.
"""
from grepfunc import grep, grep_iter
import unittest
# test file path
test_file_path = "test.txt"
class TestGrep(unittest.TestCase):
"""
Unittests to test grep.
"""
# test words (read from file)
with open(test_file_path, 'r') as infile:
test_words = [x[:-1] for x in infile.readlines()]
@property
def test_file(self):
"""
Get opened test file.
Note: return a function and not a file instance so it will reopen it every call.
"""
return _open_test_file
@property
def test_list(self):
"""
Get test list of words.
"""
return self.test_words[:]
def get_sources(self):
"""
Get list of titles and sources.
"""
return [("file", self.test_file), ("list", self.test_list)]
def test_basic(self):
"""
Testing basic grep with regex and fixed strings.
"""
for title, source in self.get_sources():
self.assertListEqual(['chubby', 'hub', 'blue hub'], grep(source, "hub"))
self.assertListEqual(['chubby', 'hub', 'blue hub'], grep(source, "hub", F=True))
self.assertListEqual(['chubby', 'hub', 'blue hub'], grep(source, ["hub"], F=True))
self.assertListEqual(['chubby', 'hub', 'dog', 'blue hub'], grep(source, ["hub", "dog"], F=True))
def test_regex(self):
"""
Testing a simple regex expression.
"""
for title, source in self.get_sources():
self.assertListEqual(['chubby', 'hub', 'blue hub'], grep(source, "h.b"))
def test_grep_iter(self):
"""
Testing grep_iter with no special flags.
"""
for title, source in self.get_sources():
ret = []
for i in grep_iter(source, "hub"):
ret.append(i)
self.assertListEqual(['chubby', 'hub', 'blue hub'], ret)
ret = []
for i in grep_iter(source, "hub", F=True):
ret.append(i)
self.assertListEqual(['chubby', 'hub', 'blue hub'], ret)
def test_case_insensitive(self):
"""
Testing case insensitive flags.
"""
for title, source in self.get_sources():
self.assertListEqual(['chubby', 'hub', 'Hub', 'green HuB.', 'blue hub'], grep(source, "hub", i=True))
self.assertListEqual(['chubby', 'hub', 'Hub', 'green HuB.', 'blue hub'], grep(source, "hub", i=True, F=True))
def test_invert(self):
"""
Testing invert flags.
"""
for title, source in self.get_sources():
# check invert
self.assertListEqual(['Hub', 'dog', 'hottub ', 'green HuB.'], grep(source, "hub", v=True))
self.assertListEqual(['Hub', 'dog', 'hottub ', 'green HuB.'], grep(source, "hub", v=True, F=True))
# check invert with case insensitive as well
self.assertListEqual(['dog', 'hottub '], grep(source, "hub", i=True, v=True))
self.assertListEqual(['dog', 'hottub '], grep(source, "hub", i=True, v=True, F=True))
def test_whole_words(self):
"""
Testing whole words flags.
"""
for title, source in self.get_sources():
self.assertListEqual(['hub', 'blue hub'], grep(source, "hub", w=True))
self.assertListEqual(['hub', 'blue hub'], grep(source, "hub", w=True, F=True))
def test_whole_lines(self):
"""
Testing whole lines flags.
"""
for title, source in self.get_sources():
self.assertListEqual(['hub'], grep(source, "hub", x=True))
self.assertListEqual(['hub'], grep(source, "hub", x=True, F=True))
def test_count(self):
"""
Testing count flag.
"""
for title, source in self.get_sources():
self.assertEqual(3, grep(source, "hub", c=True))
self.assertEqual(4, grep(source, "h", c=True))
self.assertEqual(6, grep(source, "h", c=True, i=True))
def test_max_count(self):
"""
Testing max count flag.
"""
for title, source in self.get_sources():
self.assertEqual(2, grep(source, "h", c=True, m=2))
self.assertEqual(2, grep(source, "h", c=True, m=2, i=True))
def test_quiet(self):
"""
Testing quiet flag.
"""
for title, source in self.get_sources():
self.assertEqual(True, grep(source, "hub", c=True, q=True))
self.assertEqual(True, grep(source, "hub", c=True, q=True, i=True))
self.assertEqual(True, grep(source, "dog", c=True, q=True, i=True))
self.assertEqual(False, grep(source, "wrong", c=True, q=True, i=True))
def test_offset(self):
"""
Testing offset flag.
"""
for title, source in self.get_sources():
self.assertListEqual([(1, 'chubby'), (0, 'hub'), (5, 'blue hub')], grep(source, "hub", b=True))
def test_only_match(self):
"""
Testing only_match flag.
"""
for title, source in self.get_sources():
self.assertListEqual(['hub', 'hub', 'Hub', 'HuB', 'hub'], grep(source, "hub", o=True, i=True))
def test_line_number(self):
"""
Testing line number flag.
"""
for title, source in self.get_sources():
self.assertListEqual([(0, 'chubby'), (1, 'hub'), (6, 'blue hub')], grep(source, "hub", n=True))
def test_keep_eol(self):
"""
Testing keep eol flag.
"""
self.assertListEqual(['chubby\n', 'hub\n', 'blue hub\n'], grep(self.test_file, "hub", k=True))
self.assertListEqual(['chubby', 'hub', 'blue hub'], grep(self.test_list, "hub", k=True))
def test_trim(self):
"""
Testing trim flag.
"""
for title, source in self.get_sources():
self.assertListEqual(['hottub'], grep(source, "hottub", t=True))
def test_re_flags(self):
"""
Testing re-flags flags.
"""
import re
for title, source in self.get_sources():
# test re flag ignore case. note: in second call the flag is ignored because we use pattern as strings.
self.assertListEqual(['chubby', 'hub', 'Hub', 'green HuB.', 'blue hub'], grep(source, "hub", r=re.IGNORECASE))
self.assertListEqual(['chubby', 'hub', 'blue hub'], grep(source, "hub", r=re.IGNORECASE, F=True))
def test_after_context(self):
"""
Testing after context flag.
"""
# test after-context alone
for title, source in self.get_sources():
self.assertListEqual([['dog', 'hottub', 'green HuB.']], grep(source, "dog", A=2, t=True))
self.assertListEqual([['blue hub']], grep(source, "blue hub", A=2, t=True))
# combined with before-context
for title, source in self.get_sources():
self.assertListEqual([['Hub', 'dog', 'hottub', 'green HuB.']], grep(source, "dog", A=2, B=1, t=True))
def test_before_context(self):
"""
Testing before context flag.
"""
# test before-context alone
for title, source in self.get_sources():
self.assertListEqual([['hub', 'Hub', 'dog']], grep(source, "dog", B=2, t=True))
self.assertListEqual([['chubby']], grep(source, "chubby", B=2, t=True))
# combined with after-context
for title, source in self.get_sources():
self.assertListEqual([['hub', 'Hub', 'dog', 'hottub ']], grep(source, "dog", B=2, A=1))
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
37811,
198,
51,
3558,
329,
262,
2393,
16628,
13,
198,
37811,
198,
6738,
42717,
20786,
1330,
42717,
11,
42717,
62,
2676,... | 2.158444 | 3,547 |
""" -----------------------------------------------------
# TECHNOGIX
# -------------------------------------------------------
# Copyright (c) [2022] Technogix SARL
# All rights reserved
# -------------------------------------------------------
# Keywords to manage cloudtrail tasks
# -------------------------------------------------------
# Nadรจge LEMPERIERE, @05 october 2021
# Latest revision: 05 october 2021
# --------------------------------------------------- """
# System includes
from sys import path as syspath
from os import path
# Local include
syspath.append(path.normpath(path.join(path.dirname(__file__), './')))
from tool import Tool
class CloudtrailTools(Tool) :
""" Class providing tools to check AWS cloudtrail compliance """
def __init__(self):
""" Constructor """
super().__init__()
self.m_services.append('cloudtrail')
def list_trails(self) :
""" Returns all trails in account"""
result = []
if self.m_is_active['cloudtrail'] :
paginator = self.m_clients['cloudtrail'].get_paginator('list_trails')
response_iterator = paginator.paginate()
for response in response_iterator :
for trail in response['Trails'] :
details = self.m_clients['cloudtrail'].describe_trails( \
trailNameList = [trail['TrailARN']])
details = details['trailList'][0]
tags = self.m_clients['cloudtrail'].list_tags( \
ResourceIdList = [trail['TrailARN']])
details['Tags'] = tags['ResourceTagList'][0]['TagsList']
result.append(details)
return result
def get_status(self, trail) :
""" Returns a specific trail status
---
trail (str) : Trail to analyze
"""
result = {}
if self.m_is_active['cloudtrail'] :
result = self.m_clients['cloudtrail'].get_trail_status(Name = trail['TrailARN'])
return result
def get_events_selectors(self, trail) :
""" Returns a specific trail events selectors
---
trail (str) : Trail to analyze
"""
result = {}
if self.m_is_active['cloudtrail'] :
response = self.m_clients['cloudtrail'].get_event_selectors( \
TrailName = trail['TrailARN'])
result['basic'] = response['EventSelectors']
if 'AdvancedEventsSelectors' in response :
result['advance'] = response['AdvancedEventSelectors']
return result
| [
37811,
20368,
19351,
12,
201,
198,
2,
44999,
45,
7730,
10426,
201,
198,
2,
20368,
19351,
6329,
201,
198,
2,
15069,
357,
66,
8,
685,
1238,
1828,
60,
5429,
519,
844,
47341,
43,
201,
198,
2,
1439,
2489,
10395,
201,
198,
2,
20368,
193... | 2.318455 | 1,165 |
# -*- coding: utf-8 -*-
from valverest.database import db4 as db
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
6738,
22580,
2118,
13,
48806,
1330,
20613,
19,
355,
20613,
628,
628
] | 2.615385 | 26 |
def maxEvents(self, events: List[List[int]]) -> int:
"""
>>> Greedy
Add the events to the min heap and always attend the event that ends
earliest if possible.
"""
events.sort(reverse=True)
heap = []
ans, curDay = 0, 0
while events or heap:
# if heap is empty, this suggest we have no events to attend
# therefore to avoid unnecessary loop, we can directly jump
# into next closest date that has events
if not heap: curDay = events[-1][0]
# add the events to the heap
while events and events[-1][0] == curDay:
heapq.heappush(heap, events.pop()[1])
heapq.heappop(heap)
ans += 1
curDay += 1
# pop expired events
while heap and heap[0] < curDay:
heapq.heappop(heap)
return ans
| [
4299,
3509,
37103,
7,
944,
11,
2995,
25,
7343,
58,
8053,
58,
600,
11907,
8,
4613,
493,
25,
198,
220,
220,
220,
220,
220,
220,
220,
37227,
198,
220,
220,
220,
220,
220,
220,
220,
13163,
11955,
4716,
198,
220,
220,
220,
220,
220,
... | 1.944664 | 506 |
#!/usr/bin/env python
"""
Program to re-assign already annotated items to a new set of annotators.
This reads in the retrieved annotations from several annotators, combines them and assigns to
a list of annotators, trying to allocate the same number of items to each randomly, without
assigning an item to the same annotator twice.
"""
import json
import argparse
import runutils
import random
import sys
from collections import defaultdict, Counter
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--infiles", nargs="+", help="One or more files retrieved from their projects")
parser.add_argument("--outpref", required=True, help="Output file prefix")
parser.add_argument("--annotators", nargs="+", type=int, help="List of annotator ids to assign to")
parser.add_argument("--seed", type=int, default=42, help="Random seed (default: 42)")
parser.add_argument("-d", action="store_true", help="Debug")
args = parser.parse_args()
logger = runutils.set_logger(args)
runutils.run_start()
random.seed(args.seed)
# for each of the new annotator ids, store which object idxs have already been annotated by them
per_annid = {}
for annid in args.annotators:
per_annid[annid] = set()
# also keep track of how items get assigned from annotator to annotator
old2new = defaultdict(Counter)
new4old = defaultdict(Counter)
# each object is added to this list and uniquely identified by the index in it
all = []
n_total = 0
# First of all, read all objects from all the input files
for infile in args.infiles:
with open(infile, "rt", encoding="utf8") as reader:
objs = json.load(reader)
n_in = len(objs)
n_total += n_in
logger.info(f"Loaded {n_in} items from {infile}")
for obj in objs:
all.append(obj)
# reshuffle the list of objects
random.shuffle(all)
# store all the indices of objects already seen by each of the new annotators
for idx, obj in enumerate(all):
assigned = obj["assigned"]
for a in assigned:
if a in per_annid:
per_annid[a].add(idx)
for annid,v in per_annid.items():
logger.info(f"Items already seen by annotator {annid}: {len(v)}")
logger.debug(f"Items ids seen by {annid}: {per_annid[annid]}")
# Try to assign items in a round robin fashion randomly to each annotator
# We want to choose for each annotator from all the items not already assigned to it and
# once we have assigned an item, remove it from all the lists available to each annotator
# Let's not be clever about this and brute force this: build the list available to an annotator each time we need it
new_forann = {}
for annid in args.annotators:
new_forann[annid] = []
iterations = 0
while(True):
iterations += 1
logger.debug(f"Doing a new round: {iterations}")
added = 0
for annid in args.annotators:
logger.debug(f"Assigning to annotator {annid}")
available = []
availableidxs = []
logger.debug(f"Already used for {annid}: {per_annid[annid]}")
for idx, obj in enumerate(all):
if idx not in per_annid[annid]:
available.append(obj)
availableidxs.append(idx)
logger.debug(f"Found available: {availableidxs}")
if len(available) == 0:
logger.debug("Nothing available not doing anything for this annotator")
continue
i = random.randint(0, len(availableidxs)-1)
idx = availableidxs[i]
obj = available[i]
logger.debug(f"Randomly chosen {idx} out of {availableidxs}")
# we need a copy of the object so we do not mess up the assigned status for everyone else!
objcopy = obj.copy()
assigneds = ",".join([str(x) for x in objcopy.get("assigned", ["NA"])])
old2new[assigneds][annid] += 1
new4old[annid][assigneds] += 1
objcopy["assigned"].append(annid)
new_forann[annid].append(idx)
for a in args.annotators:
per_annid[a].add(idx)
added += 1
logger.debug(f"End of round {iterations}: added={added}")
for annid in args.annotators:
logger.debug(f"Assigned to {annid} now: {new_forann[annid]}")
if added == 0:
break
#if iterations == 2:
# break
for annid in args.annotators:
logger.info(f"Nr items assigned to new {annid} from old: {dict(new4old[annid])}")
for annid in old2new.keys():
logger.info(f"Nr items assigned from old {annid} to new: {dict(old2new[annid])}")
for annid in args.annotators:
logger.info(f"Items assigned to annotator {annid}: {len(new_forann[annid])}")
logger.debug(f"Item ids: {new_forann[annid]}")
filename = args.outpref + f"_ann{annid:02d}.json"
with open(filename, "wt", encoding="utf8") as outfp:
objs = []
for idx in new_forann[annid]:
objs.append(all[idx])
json.dump(objs, outfp)
logger.info(f"Set for annotator {annid} saved to {filename}")
runutils.run_stop() | [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
37811,
198,
15167,
284,
302,
12,
562,
570,
1541,
24708,
515,
3709,
284,
257,
649,
900,
286,
24708,
2024,
13,
198,
1212,
9743,
287,
262,
29517,
37647,
422,
1811,
24708,
2024,
11,
21001,... | 2.388839 | 2,240 |
#coding:utf8
import sys
import xlrd
cur_dir = "";
# @param {string} fileName xlsxfilename
# @param {string} sheetName sheet name
# @returns data
# @returns {map}
#
# @param {string} excelfilename
# @param {string} sheet_name
# @param {string} js_name
# @returns {string} js content
# @param {excel_table} excel_table
# @params {list} struct:[string,]
# @param {} excel_table
# @param {list} head_list
# @param {int} start_r
# @param {int} start_c
# @param {int} width
# @param {int} height
# @param {boolean} is_list
# @returns {string}
#
# @param {} excel_table
# @param {int} start_r
# @param {int} col
#
# @param {string} var_value
# @param {string} var_type
# @params {string}
#
# @param {string} data
# @param {string} fileName
#
# @param {string}
# @param {string}
if __name__ == "__main__":
import sys
print sys.getdefaultencoding();
xls_path = None;
jsPath = None
print(sys.argv)
# print sys.getdefaultencoding()
#global cur_dir
py_file = sys.argv[0]
cur_dir = py_file[:py_file.rfind("\\")]
parseAllExcelFiles("table", "server");
| [
2,
66,
7656,
25,
40477,
23,
198,
198,
11748,
25064,
198,
11748,
2124,
75,
4372,
198,
198,
22019,
62,
15908,
796,
366,
8172,
628,
198,
2,
2488,
17143,
1391,
8841,
92,
2393,
5376,
2124,
7278,
87,
34345,
198,
2,
2488,
17143,
1391,
8841... | 2.47032 | 438 |
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
import os
import codecs
import numpy as np
import hashlib
import random
import preprocess
class Preparation(object):
'''Convert dataset of different text matching tasks into a unified format as the input of deep matching modules. Users provide datasets contain pairs of texts along with their labels, and the module produces the following files:
* Word Dictionary: this file records the mapping from each word to a unique identifier.
* Corpus File: this file records the mapping from each text to a unique identifiers, along with a sequence of word identifiers contained in text.
* Relation File: this file records the relationship between two texts, each line containing the label and a pair of ids.
'''
def run_with_train_valid_test_corpus(self, train_file, valid_file, test_file):
'''
Run with pre-splited train_file, valid_file, test_file
The input format should be label \t text1 \t text2
The query ids can't be duplicated. For the same query
id, the document ids can't be duplicated.
Note that if we make queries with unique id (fixed 10 candidates for a single query), then it is
possible that multiple queries have different query ids, but with the same text (in rare cases)
:param train_file: train file
:param valid_file: valid file
:param test_file: test file
:return: corpus, rels_train, rels_valid, rels_test
'''
hashid = {}
corpus = {}
rels = []
rels_train = []
rels_valid = []
rels_test = []
# merge corpus files, but return rels for train/valid/test seperately
curQ = 'init'
curQid = 0
for file_path in list([train_file, valid_file, test_file]):
if file_path == train_file:
rels = rels_train
elif file_path == valid_file:
rels = rels_valid
if file_path == test_file:
rels = rels_test
f = codecs.open(file_path, 'r', encoding='utf8')
for line in f:
line = line
line = line.strip()
label, t1, t2 = self.parse_line(line)
id2 = self.get_text_id(hashid, t2, 'D')
# generate unique query ids
if t1 == curQ:
# same query
id1 = 'Q' + str(curQid)
else:
# new query
curQid += 1
id1 = 'Q' + str(curQid)
curQ = t1
corpus[id1] = t1
corpus[id2] = t2
rels.append((label, id1, id2))
f.close()
return corpus, rels_train, rels_valid, rels_test
@staticmethod
@staticmethod
@staticmethod
@staticmethod
def check_filter_query_with_dup_doc(input_file):
""" Filter queries with duplicated doc ids in the relation files
:param input_file: input file, which could be the relation file for train/valid/test data
The format is "label qid did"
:return:
"""
with open(input_file) as f_in, open(input_file + '.fd', 'w') as f_out:
cur_qid = 'init'
cache_did_set = set()
cache_q_lines = []
found_dup_doc = False
for l in f_in:
tokens = l.split()
if tokens[1] == cur_qid:
# same qid
cache_q_lines.append(l)
if tokens[2] in cache_did_set:
found_dup_doc = True
else:
cache_did_set.add(tokens[2])
else:
# new qid
if not found_dup_doc:
f_out.write(''.join(cache_q_lines))
else:
print('found qid with duplicated doc id/text: ', ''.join(cache_q_lines))
print('filtered... continue')
cache_q_lines = []
cache_q_lines.append(l)
found_dup_doc = False
cache_did_set.clear()
cur_qid = tokens[1]
cache_did_set.add(tokens[2])
# the last query
# print len(cache_q_lines), len(cache_did_set)
if len(cache_q_lines) != 0 and len(cache_q_lines) == len(cache_did_set):
f_out.write(''.join(cache_q_lines))
print('write the last query... done: ', ''.join(cache_q_lines))
@staticmethod
@staticmethod
if __name__ == '__main__':
prepare = Preparation()
basedir = '../../data/example/ranking/'
corpus, rels = prepare.run_with_one_corpus(basedir + 'sample.txt')
print('total corpus : %d ...' % (len(corpus)))
print('total relations : %d ...' % (len(rels)))
prepare.save_corpus(basedir + 'corpus.txt', corpus)
rel_train, rel_valid, rel_test = prepare.split_train_valid_test(rels, (0.8, 0.1, 0.1))
prepare.save_relation(basedir + 'relation_train.txt', rel_train)
prepare.save_relation(basedir + 'relation_valid.txt', rel_valid)
prepare.save_relation(basedir + 'relation_test.txt', rel_test)
print('Done ...')
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
6738,
11593,
37443,
834,
1330,
3601,
62,
8818,
198,
198,
11748,
25064,
198,
11748,
28686,
198,
11748,
40481,
82,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
12234,
801... | 2.06798 | 2,589 |
from pcraft.PluginsContext import PluginsContext
import dns.resolver
import random
| [
6738,
279,
3323,
13,
23257,
1040,
21947,
1330,
22689,
1040,
21947,
198,
11748,
288,
5907,
13,
411,
14375,
198,
11748,
4738,
198
] | 3.772727 | 22 |
#!/usr/bin/env python3
import json
import logging
import os
import requests
import flask
from flask import Flask, redirect, url_for, session, request, send_from_directory
from flask_oauthlib.client import OAuth, OAuthRemoteApp
from urllib.parse import urlparse
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.INFO)
sess = requests.Session()
adapter = requests.adapters.HTTPAdapter(pool_connections=100, pool_maxsize=100)
sess.mount('http://', adapter)
sess.mount('https://', adapter)
app = Flask(__name__)
app.debug = os.getenv('APP_DEBUG') == 'true'
app.secret_key = os.getenv('APP_SECRET_KEY', 'development')
oauth = OAuth(app)
class OAuthRemoteAppWithRefresh(OAuthRemoteApp):
'''Same as flask_oauthlib.client.OAuthRemoteApp, but always loads client credentials from file.'''
@property
@property
auth = OAuthRemoteAppWithRefresh(
oauth,
'auth',
request_token_params={'scope': 'uid'},
base_url='https://auth.zalando.com/',
request_token_url=None,
access_token_method='POST',
access_token_url='https://auth.zalando.com/oauth2/access_token?realm=/employees',
authorize_url='https://auth.zalando.com/oauth2/authorize?realm=/employees'
)
oauth.remote_apps['auth'] = auth
UPSTREAMS = list(filter(None, os.getenv('APP_UPSTREAM', '').split(',')))
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
@app.route('/health')
@app.route('/login')
@app.route('/logout')
@app.route('/login/authorized')
@auth.tokengetter
# WSGI application
application = app
if __name__ == '__main__':
# development mode: run Flask dev server
app.run()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
198,
11748,
33918,
198,
11748,
18931,
198,
11748,
28686,
198,
11748,
7007,
198,
11748,
42903,
198,
6738,
42903,
1330,
46947,
11,
18941,
11,
19016,
62,
1640,
11,
6246,
11,
2581,
11,
... | 2.770115 | 609 |
amigos=int(input("Quantidade de pessoas: "))
acerolas=int(input("Quantidade de frutas colhidas: "))
suco(amigos,acerolas)
| [
198,
198,
321,
328,
418,
28,
600,
7,
15414,
7203,
24915,
312,
671,
390,
279,
408,
78,
292,
25,
366,
4008,
198,
11736,
12456,
28,
600,
7,
15414,
7203,
24915,
312,
671,
390,
1216,
315,
292,
951,
71,
24496,
25,
366,
4008,
198,
198,
... | 2.272727 | 55 |
import sys, os, nltk, pickle, argparse, gzip, csv, json, torch, numpy as np, torch.nn as nn
from collections import defaultdict
sys.path.append('..')
from utils import Logger, get_logfiles, tokenize, architect_prefix, builder_prefix, type2id, initialize_rngs
class Vocabulary(object):
"""Simple vocabulary wrapper."""
def __init__(self, data_path='../data/logs/', vector_filename=None, embed_size=300, use_speaker_tokens=False, use_builder_action_tokens=False, add_words=True, lower=False, threshold=0, all_splits=False, add_builder_utterances=False):
"""
Args:
data_path (string): path to CwC official data directory.
vector_filename (string, optional): path to pretrained embeddings file.
embed_size (int, optional): size of word embeddings.
use_speaker_tokens (boolean, optional): use speaker tokens <Architect> </Architect> and <Builder> </Builder> instead of sentence tokens <s> and </s>
use_builder_action_tokens (boolean, optional): use builder action tokens for pickup/putdown actions, e.g. <builder_pickup_red> and <builder_putdown_red>
add_words (boolean, optional): whether or not to add OOV words to vocabulary as random vectors. If not, all OOV tokens are treated as unk.
lower (boolean, optional): whether or not to lowercase all tokens.
keep_all_embeddings (boolean, optional): whether or not to keep embeddings in pretrained files for all words (even those out-of-domain). Significantly reduces file size, memory usage, and processing time if set.
threshold (int, optional): rare word threshold (for the training set), below which tokens are treated as unk.
"""
# do not freeze embeddings if we are training our own
self.data_path = data_path
self.vector_filename = vector_filename
self.embed_size = embed_size
self.freeze_embeddings = vector_filename is not None
self.use_speaker_tokens = use_speaker_tokens
self.use_builder_action_tokens = use_builder_action_tokens
self.add_words = add_words
self.lower = lower
self.threshold = threshold
self.all_splits = all_splits
self.add_builder_utterances = add_builder_utterances
print("Building vocabulary.\n\tdata path:", self.data_path, "\n\tembeddings file:", self.vector_filename, "\n\tembedding size:", self.embed_size,
"\n\tuse speaker tokens:", self.use_speaker_tokens, "\n\tuse builder action tokens:", self.use_builder_action_tokens, "\n\tadd words:", self.add_words,
"\n\tlowercase:", self.lower, "\n\trare word threshold:", self.threshold, "\n")
# mappings from words to IDs and vice versa
# this is what defines the vocabulary
self.word2idx = {}
self.idx2word = {}
# mapping from words to respective counts in the dataset
self.word_counts = defaultdict(int)
# entire dataset in the form of tokenized utterances
self.tokenized_data = []
# words that are frequent in the dataset but don't have pre-trained embeddings
self.oov_words = set()
# store dataset in tokenized form and it's properties
self.get_dataset_properties() # self.word_counts and self.tokenized_data populated
# initialize word vectors
self.init_vectors() # self.word_vectors, self.word2idx and self.idx2word populated for aux tokens
# load pretrained word vectors
if vector_filename is not None:
self.load_vectors() # self.word_vectors, self.word2idx and self.idx2word populated for real words
# add random vectors for oov train words -- words that are in data, frequent but do not have a pre-trained embedding
if add_words or vector_filename is None:
self.add_oov_vectors()
# create embedding variable
self.word_embeddings = nn.Embedding(self.word_vectors.shape[0], self.word_vectors.shape[1])
# initialize embedding variable
self.word_embeddings.weight.data.copy_(torch.from_numpy(self.word_vectors))
# freeze embedding variable
if self.freeze_embeddings:
self.word_embeddings.weight.requires_grad = False
self.num_tokens = len(self.word2idx)
self.print_vocab_statistics()
def add_word(self, word):
""" Adds a word to the vocabulary. """
idx = len(self.word2idx)
self.word2idx[word] = idx
self.idx2word[idx] = word
def __call__(self, word):
""" Gets a word's index. If the word doesn't exist in the vocabulary, returns the index of the unk token. """
if not word in self.word2idx:
return self.word2idx['<unk>']
return self.word2idx[word]
def __len__(self):
""" Returns size of the vocabulary. """
return len(self.word2idx)
def __str__(self):
""" Prints vocabulary in human-readable form. """
vocabulary = ""
for key in self.idx2word.keys():
vocabulary += str(key) + ": " + self.idx2word[key] + "\n"
return vocabulary
def main(args):
""" Creates a vocabulary according to specified arguments and saves it to disk. """
if not os.path.isdir('../vocabulary'):
os.makedirs('../vocabulary')
# create vocabulary filename based on parameter settings
if args.vocab_name is None:
lower = "-lower" if args.lower else ""
threshold = "-"+str(args.threshold)+"r" if args.threshold > 0 else ""
speaker_tokens = "-speaker" if args.use_speaker_tokens else ""
action_tokens = "-builder_actions" if args.use_builder_action_tokens else ""
oov_as_unk = "-oov_as_unk" if args.oov_as_unk else ""
all_splits = "-all_splits" if args.all_splits else "-train_split"
architect_only = "-architect_only" if not args.add_builder_utterances else ""
if args.vector_filename is None:
args.vocab_name = "no-embeddings-"+str(args.embed_size)+"d"
else:
args.vocab_name = args.vector_filename.split("/")[-1].replace('.txt','').replace('.bin.gz','')
args.vocab_name += lower+threshold+speaker_tokens+action_tokens+oov_as_unk+all_splits+architect_only+"/"
args.vocab_name = os.path.join(args.base_vocab_dir, args.vocab_name)
if not os.path.exists(args.vocab_name):
os.makedirs(args.vocab_name)
# logger
sys.stdout = Logger(os.path.join(args.vocab_name, 'vocab.log'))
print(args)
# create the vocabulary
vocabulary = Vocabulary(data_path=args.data_path, vector_filename=args.vector_filename,
embed_size=args.embed_size, use_speaker_tokens=args.use_speaker_tokens, use_builder_action_tokens=args.use_builder_action_tokens,
add_words=not args.oov_as_unk, lower=args.lower, threshold=args.threshold, all_splits=args.all_splits, add_builder_utterances=args.add_builder_utterances)
if args.verbose:
print(vocabulary)
write_train_word_counts(args.vocab_name, vocabulary.word_counts, vocabulary.oov_words, vocabulary.threshold)
# save the vocabulary to disk
print("Saving the vocabulary ...")
with open(os.path.join(args.vocab_name, 'vocab.pkl'), 'wb') as f:
pickle.dump(vocabulary, f)
print("Saved the vocabulary to '%s'" %os.path.realpath(f.name))
print("Total vocabulary size: %d" %len(vocabulary))
sys.stdout = sys.__stdout__
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--vocab_name', type=str, nargs='?', default=None,
help='directory for saved vocabulary wrapper -- auto-generated from embeddings file name if not provided')
parser.add_argument('--base_vocab_dir', type=str, default='../vocabulary/', help='location for all saved vocabulary files')
parser.add_argument('--vector_filename', type=str, default=None,
help='path for word embeddings file')
parser.add_argument('--embed_size', type=int, default=300,
help='size of word embeddings')
parser.add_argument('--data_path', type=str, default='../data/logs/',
help='path for training data files')
parser.add_argument('--oov_as_unk', default=False, action='store_true', help='do not add oov words to the vocabulary (instead, treat them as unk tokens)')
parser.add_argument('--lower', default=False, action='store_true', help='lowercase tokens in the dataset')
parser.add_argument('--use_speaker_tokens', default=False, action='store_true', help='use speaker tokens <Architect> </Architect> and <Builder> </Builder> instead of sentence tokens <s> and </s>')
parser.add_argument('--use_builder_action_tokens', default=False, action='store_true', help='use builder action tokens for pickup/putdown actions, e.g. <builder_pickup_red> and <builder_putdown_red>')
parser.add_argument('--threshold', type=int, default=0, help='rare word threshold for oov words in the train set')
parser.add_argument('--all_splits', default=False, action='store_true', help='whether or not to use val and test data as well')
parser.add_argument('--add_builder_utterances', default=False, action='store_true', help='whether or not to include builder utterances')
parser.add_argument('--verbose', action='store_true', help='print vocabulary in plaintext to console')
parser.add_argument('--seed', type=int, default=1234, help='random seed')
args = parser.parse_args()
seed = args.seed
initialize_rngs(seed, torch.cuda.is_available())
main(args)
| [
11748,
25064,
11,
28686,
11,
299,
2528,
74,
11,
2298,
293,
11,
1822,
29572,
11,
308,
13344,
11,
269,
21370,
11,
33918,
11,
28034,
11,
299,
32152,
355,
45941,
11,
28034,
13,
20471,
355,
299,
77,
198,
6738,
17268,
1330,
4277,
11600,
1... | 2.910324 | 3,022 |
from typing import Type
from klayout.db import Layout
def layout_read_cell(layout: Type[Layout], cell_name: str, filepath: str):
"""Imports a cell from a file into current layout.
layout [pya.Layout]: layout to insert cell into
cell_name [str]: cell name from the file in filepath
filepath [str]: location of layout file you want to import
If the name already exists in the current layout, klayout will
create a new one based on its internal rules for naming
collision: name$1, name$2, ...
"""
# BUG loading this file twice segfaults klayout
layout2 = Layout()
layout2.read(filepath)
gdscell2 = layout2.cell(cell_name)
gdscell = layout.create_cell(cell_name)
gdscell.copy_tree(gdscell2)
del gdscell2
del layout2
return gdscell
Layout.read_cell = layout_read_cell
| [
6738,
19720,
1330,
5994,
198,
6738,
479,
39786,
13,
9945,
1330,
47639,
628,
198,
4299,
12461,
62,
961,
62,
3846,
7,
39786,
25,
5994,
58,
32517,
4357,
2685,
62,
3672,
25,
965,
11,
2393,
6978,
25,
965,
2599,
198,
220,
220,
220,
37227,... | 2.93007 | 286 |
import datetime
from itertools import chain
from celery.task import task
from courses.models import Course, Semester
from django.contrib.auth.models import User, Group
@task
def expire_course_visibility():
'''
Will run at the end of the semester.
Courses set to private in the current semester will have their visibility reset.
'''
# Get the semester that ended yesterday
try:
current_semester = get_yesterday_semester()
except Semester.DoesNotExist:
return
for course in current_semester.course_set.all():
course.private = False
course.save()
@task
def disable_faculty():
'''
Faculty or Adjunct Faculty who are not assigned a course next semester are disabled.
'''
try:
current_semester = get_yesterday_semester()
except Semester.DoesNotExist:
return
# Get set all Faculty
try:
all_faculty = set(Group.objects.get(name = 'Faculty').user_set.values_list('username', flat = True))
except Group.DoesNotExist:
return
# Get set of all Faculty for the next semester
next_faculty = set([instructor for instructor in chain([course.faculty.values_list('username', flat = True) for course in current_semester.get_next().course_set.all()])])
# Subract next_faculty from the all_faculty set to get those faculty not teaching next semester
faculty = all_faculty - next_faculty
# Disable all the faculty left
User.objects.filter(username__in = faculty).update(is_active = False)
| [
11748,
4818,
8079,
198,
198,
6738,
340,
861,
10141,
1330,
6333,
198,
6738,
18725,
1924,
13,
35943,
1330,
4876,
198,
6738,
10902,
13,
27530,
1330,
20537,
11,
12449,
7834,
198,
6738,
42625,
14208,
13,
3642,
822,
13,
18439,
13,
27530,
1330... | 2.857671 | 541 |
# Tai Sakuma <tai.sakuma@gmail.com>
import os
import sys
import pytest
import unittest.mock as mock
has_jupyter_notebook = False
try:
import ipywidgets as widgets
from IPython.display import display
has_jupyter_notebook = True
except ImportError:
pass
from atpbar.presentation.create import create_presentation
##__________________________________________________________________||
@pytest.fixture(
params=[True, False]
)
##__________________________________________________________________||
if has_jupyter_notebook:
is_jupyter_notebook_parames = [True, False]
else:
is_jupyter_notebook_parames = [False]
@pytest.fixture(params=is_jupyter_notebook_parames)
##__________________________________________________________________||
@pytest.fixture(
params=[True, False]
)
##__________________________________________________________________||
##__________________________________________________________________||
| [
2,
11144,
13231,
7487,
1279,
83,
1872,
13,
82,
461,
7487,
31,
14816,
13,
785,
29,
198,
11748,
28686,
198,
11748,
25064,
198,
198,
11748,
12972,
9288,
198,
198,
11748,
555,
715,
395,
13,
76,
735,
355,
15290,
198,
198,
10134,
62,
73,
... | 3.542751 | 269 |
from x_rebirth_station_calculator.station_data.station_base import Ware
names = {'L044': 'Novadrones',
'L049': 'Novadrohnen'}
Novadrones = Ware(names)
| [
6738,
2124,
62,
260,
24280,
62,
17529,
62,
9948,
3129,
1352,
13,
17529,
62,
7890,
13,
17529,
62,
8692,
1330,
28593,
198,
198,
14933,
796,
1391,
6,
43,
43977,
10354,
705,
20795,
324,
9821,
3256,
198,
220,
220,
220,
220,
220,
220,
220... | 2.382353 | 68 |
import sys
import pygame
if __name__ == '__main__':
main()
| [
11748,
25064,
198,
198,
11748,
12972,
6057,
628,
198,
198,
361,
11593,
3672,
834,
6624,
705,
834,
12417,
834,
10354,
198,
220,
220,
220,
1388,
3419,
198
] | 2.481481 | 27 |
#!/usr/bin/env python
import unittest
import numpy as np
from arte.types.scalar_bidimensional_function import \
ScalarBidimensionalFunction
from arte.types.domainxy import DomainXY
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
11748,
555,
715,
395,
198,
11748,
299,
32152,
355,
45941,
198,
6738,
46252,
13,
19199,
13,
1416,
282,
283,
62,
14065,
16198,
62,
8818,
1330,
3467,
198,
220,
220,
220,
34529,
283,
33,
... | 2.821782 | 101 |
# ----------------------------------------------------------------------
# |
# | DebugRelationalPlugin.py
# |
# | David Brownell <db@DavidBrownell.com>
# | 2020-02-05 15:04:00
# |
# ----------------------------------------------------------------------
# |
# | Copyright David Brownell 2020-21
# | Distributed under the Boost Software License, Version 1.0. See
# | accompanying file LICENSE_1_0.txt or copy at
# | http://www.boost.org/LICENSE_1_0.txt.
# |
# ----------------------------------------------------------------------
"""Contains the Plugin object"""
import os
import textwrap
import CommonEnvironment
from CommonEnvironment import Interface
from CommonSimpleSchemaGenerator.RelationalPluginImpl import RelationalPluginImpl
# ----------------------------------------------------------------------
_script_fullpath = CommonEnvironment.ThisFullpath()
_script_dir, _script_name = os.path.split(_script_fullpath)
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
@Interface.staticderived
| [
2,
16529,
23031,
201,
198,
2,
930,
201,
198,
2,
930,
220,
31687,
6892,
864,
37233,
13,
9078,
201,
198,
2,
930,
201,
198,
2,
930,
220,
3271,
4373,
695,
1279,
9945,
31,
11006,
20644,
695,
13,
785,
29,
201,
198,
2,
930,
220,
220,
... | 3.72327 | 318 |
from flutter_utils.material_icons_parser.material_icons_specs_utils import parse_as_icons_spec
# generates icon_name: IconData mapped dart code
if __name__ == "__main__":
mappings_gen() | [
6738,
781,
10381,
62,
26791,
13,
33665,
62,
34280,
62,
48610,
13,
33665,
62,
34280,
62,
4125,
6359,
62,
26791,
1330,
21136,
62,
292,
62,
34280,
62,
16684,
198,
198,
2,
18616,
7196,
62,
3672,
25,
26544,
6601,
27661,
35970,
2438,
628,
... | 3.096774 | 62 |
"""
200. Number of Islands
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
"""
| [
37811,
198,
2167,
13,
7913,
286,
12010,
198,
15056,
257,
362,
67,
10706,
3975,
286,
705,
16,
338,
357,
1044,
8,
290,
705,
15,
338,
357,
7050,
828,
954,
262,
1271,
286,
14807,
13,
1052,
7022,
318,
11191,
416,
1660,
290,
318,
7042,
... | 3.344538 | 119 |
import os
import shutil
import zipfile
import argparse
import kaggle
import pandas as pd
if __name__ == '__main__':
main()
| [
11748,
28686,
198,
11748,
4423,
346,
198,
11748,
19974,
7753,
198,
11748,
1822,
29572,
198,
11748,
479,
9460,
293,
198,
11748,
19798,
292,
355,
279,
67,
198,
198,
361,
11593,
3672,
834,
6624,
705,
834,
12417,
834,
10354,
198,
220,
220,
... | 2.844444 | 45 |
"""Base functionality for distribution configurations."""
import logging
from jade.jobs.job_configuration import JobConfiguration
from jade.jobs.job_container_by_key import JobContainerByKey
from jade.utils.utils import load_data
logger = logging.getLogger(__name__)
class DistributionConfiguration(JobConfiguration):
"""Represents the configuration options for a distribution simulation."""
def __init__(self,
inputs,
job_parameters_class,
extension_name,
**kwargs):
"""Constructs DistributionConfiguration.
Parameters
----------
inputs : str | JobInputsInterface
path to inputs directory or JobInputsInterface object
"""
super(DistributionConfiguration, self).__init__(inputs,
JobContainerByKey(),
job_parameters_class,
extension_name,
**kwargs)
@classmethod
@property
def base_directory(self):
"""Return the base directory for the inputs."""
if isinstance(self.inputs, str):
return self.inputs
return self.inputs.base_directory
def create_job_key(self, *args):
"""Create a job key from parameters."""
return self._job_parameters_class.create_job_key(*args)
| [
37811,
14881,
11244,
329,
6082,
25412,
526,
15931,
198,
198,
11748,
18931,
198,
198,
6738,
474,
671,
13,
43863,
13,
21858,
62,
11250,
3924,
1330,
15768,
38149,
198,
6738,
474,
671,
13,
43863,
13,
21858,
62,
34924,
62,
1525,
62,
2539,
... | 2.155172 | 696 |
# Copyright 2021 - 2022 Universitรคt Tรผbingen, DKFZ and EMBL
# for the German Human Genome-Phenome Archive (GHGA)
#
# 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.
"Routes for retrieving Samples"
from fastapi import APIRouter, Depends
from fastapi.exceptions import HTTPException
from metadata_repository_service.api.deps import get_config
from metadata_repository_service.config import Config
from metadata_repository_service.dao.sample import get_sample
from metadata_repository_service.models import Sample
sample_router = APIRouter()
@sample_router.get(
"/samples/{sample_id}",
response_model=Sample,
summary="Get a Sample",
tags=["Query"],
)
async def get_samples(
sample_id: str, embedded: bool = False, config: Config = Depends(get_config)
):
"""
Given a Sample ID, get the Sample record from the metadata store.
"""
sample = await get_sample(sample_id=sample_id, embedded=embedded, config=config)
if not sample:
raise HTTPException(
status_code=404,
detail=f"{Sample.__name__} with id '{sample_id}' not found",
)
return sample
| [
2,
15069,
33448,
532,
33160,
26986,
270,
11033,
83,
309,
9116,
4623,
268,
11,
32975,
37,
57,
290,
17228,
9148,
198,
2,
329,
262,
2679,
5524,
5215,
462,
12,
47,
831,
462,
20816,
357,
17511,
9273,
8,
198,
2,
198,
2,
49962,
739,
262,... | 3.095602 | 523 |
import json
import asyncio
import aiohttp
BASE = "https://mee6.xyz/api/plugins/levels/leaderboard/"
GUILD_ID = "YOUR_ID"
user_list = []
LEVEL_API_URL = BASE + str(GUILD_ID) + "?page="
asyncio.run(main()) | [
11748,
33918,
198,
198,
11748,
30351,
952,
198,
11748,
257,
952,
4023,
628,
198,
33,
11159,
796,
366,
5450,
1378,
1326,
68,
21,
13,
5431,
89,
14,
15042,
14,
37390,
14,
46170,
14,
27940,
3526,
30487,
198,
38022,
26761,
62,
2389,
796,
... | 2.370787 | 89 |
import os
import re
from azure.storage.blob import BlobServiceClient, ContainerClient
from loguru import logger
from urllib.parse import urlparse
def extract_file_path(path: str) -> str:
"""Extract the file path after from a blob storage URL.
Container name (the first path segment) is excluded.
>>> path = "https://storage-acct-name.blob.core.windows.net/container/imgs/1001.jpg"
>>> extract_file_path(path)
... "imgs/1001.jpg"
"""
return urlparse(path).path.split('/', maxsplit=2)[-1]
| [
11748,
28686,
198,
11748,
302,
198,
198,
6738,
35560,
495,
13,
35350,
13,
2436,
672,
1330,
1086,
672,
16177,
11792,
11,
43101,
11792,
198,
6738,
2604,
14717,
1330,
49706,
198,
6738,
2956,
297,
571,
13,
29572,
1330,
19016,
29572,
198,
19... | 2.916201 | 179 |
#
# ใใณใใฌใผใๆงๆใฎใในใ
#
from json import JSONDecodeError
from unittest import TestCase
from src.blueprintpy.cli.config_loader import ConfigLoader
| [
2,
198,
2,
14524,
228,
6527,
30965,
24186,
12045,
230,
162,
100,
233,
22755,
238,
5641,
24336,
43302,
198,
2,
198,
198,
6738,
33918,
1330,
19449,
10707,
1098,
12331,
198,
6738,
555,
715,
395,
1330,
6208,
20448,
198,
198,
6738,
12351,
... | 2.618182 | 55 |
import emg3d
import empymod
import numpy as np
import ipywidgets as widgets
import scipy.interpolate as si
import matplotlib.pyplot as plt
from IPython.display import display
from scipy.signal import find_peaks
# Define all errors we want to catch with the variable-checks and setting of
# default values. This is not perfect, but better than 'except Exception'.
VariableCatch = (LookupError, AttributeError, ValueError, TypeError, NameError)
# Interactive Frequency Selection
class InteractiveFrequency(emg3d.utils.Fourier):
"""App to create required frequencies for Fourier Transform."""
def __init__(self, src_z, rec_z, depth, res, time, signal=0, ab=11,
aniso=None, **kwargs):
"""App to create required frequencies for Fourier Transform.
No thorough input checks are carried out. Rubbish in, rubbish out.
See empymod.model.dipole for details regarding the modelling.
Parameters
----------
src_z, rec_z : floats
Source and receiver depths and offset. The source is located at
src=(0, 0, src_z), the receiver at rec=(off, 0, rec_z).
depth : list
Absolute layer interfaces z (m); #depth = #res - 1
(excluding +/- infinity).
res : array_like
Horizontal resistivities rho_h (Ohm.m); #res = #depth + 1.
time : array_like
Times t (s).
signal : {0, 1, -1}, optional
Source signal, default is 0:
- -1 : Switch-off time-domain response
- 0 : Impulse time-domain response
- +1 : Switch-on time-domain response
ab : int, optional
Source-receiver configuration, defaults to 11. (See
empymod.model.dipole for all possibilities.)
aniso : array_like, optional
Anisotropies lambda = sqrt(rho_v/rho_h) (-); #aniso = #res.
Defaults to ones.
**kwargs : Optional parameters:
- ``fmin`` : float
Initial minimum frequency. Default is 1e-3.
- ``fmax`` : float
Initial maximum frequency. Default is 1e1.
- ``off`` : float
Initial offset. Default is 500.
- ``ft`` : str {'dlf', 'fftlog'}
Initial Fourier transform method. Default is 'dlf'.
- ``ftarg`` : dict
Initial Fourier transform arguments corresponding to ``ft``.
Default is None.
- ``pts_per_dec`` : int
Initial points per decade. Default is 5.
- ``linlog`` : str {'linear', 'log'}
Initial display scaling. Default is 'linear'.
- ``xtfact`` : float
Factor for linear x-dimension: t_max = xtfact*offset/1000.
- ``verb`` : int
Verbosity. Only for debugging purposes.
"""
# Get initial values or set to default.
fmin = kwargs.pop('fmin', 1e-3)
fmax = kwargs.pop('fmax', 1e1)
off = kwargs.pop('off', 5000)
ft = kwargs.pop('ft', 'dlf')
ftarg = kwargs.pop('ftarg', None)
self.pts_per_dec = kwargs.pop('pts_per_dec', 5)
self.linlog = kwargs.pop('linlog', 'linear')
self.xtfact = kwargs.pop('xtfact', 1)
self.verb = kwargs.pop('verb', 1)
# Ensure no kwargs left.
if kwargs:
raise TypeError('Unexpected **kwargs: %r' % kwargs)
# Collect model from input.
self.model = {
'src': [0, 0, src_z],
'rec': [off, 0, rec_z],
'depth': depth,
'res': res,
'aniso': aniso,
'ab': ab,
'verb': self.verb,
}
# Initiate a Fourier instance.
super().__init__(time, fmin, fmax, signal, ft, ftarg, verb=self.verb)
# Create the figure.
self.initiate_figure()
def initiate_figure(self):
"""Create the figure."""
# Create figure and all axes
fig = plt.figure("Interactive frequency selection for the Fourier "
"Transform.", figsize=(9, 4))
plt.subplots_adjust(hspace=0.03, wspace=0.04, bottom=0.15, top=0.9)
# plt.tight_layout(rect=[0, 0, 1, 0.95]) # Leave space for suptitle.
ax1 = plt.subplot2grid((3, 2), (0, 0), rowspan=2)
plt.grid('on', alpha=0.4)
ax2 = plt.subplot2grid((3, 2), (0, 1), rowspan=2)
plt.grid('on', alpha=0.4)
ax3 = plt.subplot2grid((3, 2), (2, 0))
plt.grid('on', alpha=0.4)
ax4 = plt.subplot2grid((3, 2), (2, 1))
plt.grid('on', alpha=0.4)
# Synchronize x-axis, switch upper labels off
ax1.get_shared_x_axes().join(ax1, ax3)
ax2.get_shared_x_axes().join(ax2, ax4)
plt.setp(ax1.get_xticklabels(), visible=False)
plt.setp(ax2.get_xticklabels(), visible=False)
# Move labels of t-domain to the right
ax2.yaxis.set_ticks_position('right')
ax4.yaxis.set_ticks_position('right')
# Set fixed limits
ax1.set_xscale('log')
ax3.set_yscale('log')
ax3.set_yscale('log')
ax3.set_ylim([0.007, 141])
ax3.set_yticks([0.01, 0.1, 1, 10, 100])
ax3.set_yticklabels(('0.01', '0.1', '1', '10', '100'))
ax4.set_yscale('log')
ax4.set_yscale('log')
ax4.set_ylim([0.007, 141])
ax4.set_yticks([0.01, 0.1, 1, 10, 100])
ax4.set_yticklabels(('0.01', '0.1', '1', '10', '100'))
# Labels etc
ax1.set_ylabel('Amplitude (V/m)')
ax3.set_ylabel('Rel. Error (%)')
ax3.set_xlabel('Frequency (Hz)')
ax4.set_xlabel('Time (s)')
ax3.axhline(1, c='k')
ax4.axhline(1, c='k')
# Add instances
self.fig = fig
self.axs = [ax1, ax2, ax3, ax4]
# Plot initial base model
self.update_ftfilt(self.ftarg)
self.plot_base_model()
# Initiate the widgets
self.create_widget()
def reim(self, inp):
"""Return real or imaginary part as a function of signal."""
if self.signal < 0:
return inp.real
else:
return inp.imag
def create_widget(self):
"""Create widgets and their layout."""
# Offset slider.
off = widgets.interactive(
self.update_off,
off=widgets.IntSlider(
min=500,
max=10000,
description='Offset (m)',
value=self.model['rec'][0],
step=250,
continuous_update=False,
style={'description_width': '60px'},
layout={'width': '260px'},
),
)
# Pts/dec slider.
pts_per_dec = widgets.interactive(
self.update_pts_per_dec,
pts_per_dec=widgets.IntSlider(
min=1,
max=10,
description='pts/dec',
value=self.pts_per_dec,
step=1,
continuous_update=False,
style={'description_width': '60px'},
layout={'width': '260px'},
),
)
# Linear/logarithmic selection.
linlog = widgets.interactive(
self.update_linlog,
linlog=widgets.ToggleButtons(
value=self.linlog,
options=['linear', 'log'],
description='Display',
style={'description_width': '60px', 'button_width': '100px'},
),
)
# Frequency-range slider.
freq_range = widgets.interactive(
self.update_freq_range,
freq_range=widgets.FloatRangeSlider(
value=[np.log10(self.fmin), np.log10(self.fmax)],
description='f-range',
min=-4,
max=3,
step=0.1,
continuous_update=False,
style={'description_width': '60px'},
layout={'width': '260px'},
),
)
# Signal selection (-1, 0, 1).
signal = widgets.interactive(
self.update_signal,
signal=widgets.ToggleButtons(
value=self.signal,
options=[-1, 0, 1],
description='Signal',
style={'description_width': '60px', 'button_width': '65px'},
),
)
# Fourier transform method selection.
def _get_init():
"""Return initial choice of Fourier Transform."""
if self.ft == 'fftlog':
return self.ft
else:
return self.ftarg['dlf'].savename
ftfilt = widgets.interactive(
self.update_ftfilt,
ftfilt=widgets.Dropdown(
options=['fftlog', 'key_81_CosSin_2009',
'key_241_CosSin_2009', 'key_601_CosSin_2009',
'key_101_CosSin_2012', 'key_201_CosSin_2012'],
description='Fourier',
value=_get_init(), # Initial value
style={'description_width': '60px'},
layout={'width': 'max-content'},
),
)
# Group them together.
t1col1 = widgets.VBox(children=[pts_per_dec, freq_range],
layout={'width': '310px'})
t1col2 = widgets.VBox(children=[off, ftfilt],
layout={'width': '310px'})
t1col3 = widgets.VBox(children=[signal, linlog],
layout={'width': '310px'})
# Group them together.
display(widgets.HBox(children=[t1col1, t1col2, t1col3]))
# Plotting and calculation routines.
def clear_handle(self, handles):
"""Clear `handles` from figure."""
for hndl in handles:
if hasattr(self, 'h_'+hndl):
getattr(self, 'h_'+hndl).remove()
def adjust_lim(self):
"""Adjust axes limits."""
# Adjust y-limits f-domain
if self.linlog == 'linear':
self.axs[0].set_ylim([1.1*min(self.reim(self.f_dense)),
1.5*max(self.reim(self.f_dense))])
else:
self.axs[0].set_ylim([5*min(self.reim(self.f_dense)),
5*max(self.reim(self.f_dense))])
# Adjust x-limits f-domain
self.axs[0].set_xlim([min(self.freq_req), max(self.freq_req)])
# Adjust y-limits t-domain
if self.linlog == 'linear':
self.axs[1].set_ylim(
[min(-max(self.t_base)/20, 0.9*min(self.t_base)),
max(-min(self.t_base)/20, 1.1*max(self.t_base))])
else:
self.axs[1].set_ylim([10**(np.log10(max(self.t_base))-5),
1.5*max(self.t_base)])
# Adjust x-limits t-domain
if self.linlog == 'linear':
if self.signal == 0:
self.axs[1].set_xlim(
[0, self.xtfact*self.model['rec'][0]/1000])
else:
self.axs[1].set_xlim([0, max(self.time)])
else:
self.axs[1].set_xlim([min(self.time), max(self.time)])
def print_suptitle(self):
"""Update suptitle."""
plt.suptitle(
f"Offset = {np.squeeze(self.model['rec'][0])/1000} km; "
f"No. freq. coarse: {self.freq_calc.size}; No. freq. full: "
f"{self.freq_req.size} ({self.freq_req.min():.1e} $-$ "
f"{self.freq_req.max():.1e} Hz)")
def plot_base_model(self):
"""Update smooth, 'correct' model."""
# Calculate responses
self.f_dense = empymod.dipole(freqtime=self.freq_dense, **self.model)
self.t_base = empymod.dipole(
freqtime=self.time, signal=self.signal, **self.model)
# Clear existing handles
self.clear_handle(['f_base', 't_base'])
# Plot new result
self.h_f_base, = self.axs[0].plot(
self.freq_dense, self.reim(self.f_dense), 'C3')
self.h_t_base, = self.axs[1].plot(self.time, self.t_base, 'C3')
self.adjust_lim()
def plot_coarse_model(self):
"""Update coarse model."""
# Calculate the f-responses for required and the calculation range.
f_req = empymod.dipole(freqtime=self.freq_req, **self.model)
f_calc = empymod.dipole(freqtime=self.freq_calc, **self.model)
# Interpolate from calculated to required frequencies and transform.
f_int = self.interpolate(f_calc)
t_int = self.freq2time(f_calc, self.model['rec'][0])
# Calculate the errors.
f_error = np.clip(100*abs((self.reim(f_int)-self.reim(f_req)) /
self.reim(f_req)), 0.01, 100)
t_error = np.clip(100*abs((t_int-self.t_base)/self.t_base), 0.01, 100)
# Clear existing handles
self.clear_handle(['f_int', 't_int', 'f_inti', 'f_inte', 't_inte'])
# Plot frequency-domain result
self.h_f_inti, = self.axs[0].plot(
self.freq_req, self.reim(f_int), 'k.', ms=4)
self.h_f_int, = self.axs[0].plot(
self.freq_calc, self.reim(f_calc), 'C0.', ms=8)
self.h_f_inte, = self.axs[2].plot(self.freq_req, f_error, 'k.')
# Plot time-domain result
self.h_t_int, = self.axs[1].plot(self.time, t_int, 'k--')
self.h_t_inte, = self.axs[3].plot(self.time, t_error, 'k.')
# Update suptitle
self.print_suptitle()
# Interactive routines
def update_off(self, off):
"""Offset-slider"""
# Update model
self.model['rec'] = [off, self.model['rec'][1], self.model['rec'][2]]
# Redraw models
self.plot_base_model()
self.plot_coarse_model()
def update_pts_per_dec(self, pts_per_dec):
"""pts_per_dec-slider."""
# Store pts_per_dec.
self.pts_per_dec = pts_per_dec
# Redraw through update_ftfilt.
self.update_ftfilt(self.ftarg)
def update_freq_range(self, freq_range):
"""Freq-range slider."""
# Update values
self.fmin = 10**freq_range[0]
self.fmax = 10**freq_range[1]
# Redraw models
self.plot_coarse_model()
def update_ftfilt(self, ftfilt):
"""Ftfilt dropdown."""
# Check if FFTLog or DLF; git DLF filter.
if isinstance(ftfilt, str):
fftlog = ftfilt == 'fftlog'
else:
if 'dlf' in ftfilt:
fftlog = False
ftfilt = ftfilt['dlf'].savename
else:
fftlog = True
# Update Fourier arguments.
if fftlog:
self.fourier_arguments('fftlog', {'pts_per_dec': self.pts_per_dec})
self.freq_inp = None
else:
# Calculate input frequency from min to max with pts_per_dec.
lmin = np.log10(self.freq_req.min())
lmax = np.log10(self.freq_req.max())
self.freq_inp = np.logspace(
lmin, lmax, int(self.pts_per_dec*np.ceil(lmax-lmin)))
self.fourier_arguments(
'dlf', {'dlf': ftfilt, 'pts_per_dec': -1})
# Dense frequencies for comparison reasons
self.freq_dense = np.logspace(np.log10(self.freq_req.min()),
np.log10(self.freq_req.max()), 301)
# Redraw models
self.plot_base_model()
self.plot_coarse_model()
def update_linlog(self, linlog):
"""Adjust x- and y-scaling of both frequency- and time-domain."""
# Store linlog
self.linlog = linlog
# f-domain: x-axis always log; y-axis linear or symlog.
if linlog == 'log':
sym_dec = 10 # Number of decades to show on symlog
lty = int(max(np.log10(abs(self.reim(self.f_dense))))-sym_dec)
self.axs[0].set_yscale('symlog', linthresh=10**lty, linscaley=0.7)
# Remove the zero line becouse of the overlapping ticklabels.
nticks = len(self.axs[0].get_yticks())//2
iticks = np.arange(nticks)
iticks = np.r_[iticks, iticks+nticks+1]
self.axs[0].set_yticks(self.axs[0].get_yticks()[iticks])
else:
self.axs[0].set_yscale(linlog)
# t-domain: either linear or loglog
self.axs[1].set_yscale(linlog)
self.axs[1].set_xscale(linlog)
# Adjust limits
self.adjust_lim()
def update_signal(self, signal):
"""Use signal."""
# Store signal.
self.signal = signal
# Redraw through update_ftfilt.
self.update_ftfilt(self.ftarg)
# Routines for the Adaptive Frequency Selection
def get_new_freq(freq, field, rtol, req_freq=None, full_output=False):
r"""Returns next frequency to calculate.
The field of a frequency is considered stable when it fulfills the
following requirement:
.. math::
\frac{\Im(E_x - E_x^\rm{int})}{\max|E_x|} < rtol .
The adaptive algorithm has two steps:
1. As long as the field at the lowest frequency does not fulfill the
criteria, more frequencies are added at lower frequencies, half a
log10-decade at a time.
2. Once the field at the lowest frequency fulfills the criteria, it moves
towards higher frequencies, adding frequencies if it is not stable (a)
midway (log10-scale) to the next frequency, or (b) half a log10-decade,
if the last frequency was reached.
Only the imaginary field is considered in the interpolation. For the
interpolation, three frequencies are added, 1e-100, 1e4, and 1e100 Hz, all
with a field of 0 V/m. The interpolation is carried out with piecewise
cubic Hermite interpolation (pchip).
Parameters
----------
freq : ndarray
Current frequencies. Initially there must be at least two frequencies.
field : ndarray
E-field corresponding to current frequencies.
rtol : float
Tolerance, to decide if the field is stable around a given frequency.
req_freq : ndarray
Frequencies of a pre-calculated model for comparison in the plots. If
provided, a dashed line with the extent of req_freq and the current
interpolation is shown.
full_output : bool
If True, returns the data from the evaluation.
Returns
-------
new_freq : float
New frequency to be calculated. If ``full_output=True``, it is a
tuple, where the first entry is new_freq.
"""
# Pre-allocate array for interpolated field.
i_field = np.zeros_like(field)
# Loop over frequencies.
for i in range(freq.size):
# Create temporary arrays without this frequency/field.
# (Adding 0-fields at 1e-100, 1e4, and 1e100 Hz.)
if max(freq) < 1e4:
tmp_f = np.r_[1e-100, freq[np.arange(freq.size) != i], 1e4, 1e100]
tmp_s = np.r_[0, field[np.arange(field.size) != i], 0, 0]
else:
tmp_f = np.r_[1e-100, freq[np.arange(freq.size) != i], 1e100]
tmp_s = np.r_[0, field[np.arange(field.size) != i], 0]
# Now interpolate at left-out frequency.
i_field[i] = 1j*si.pchip_interpolate(tmp_f, tmp_s.imag, freq[i])
# Calculate complete interpol. if required frequency-range is provided.
if req_freq is not None:
if max(freq) < 1e4:
tmp_f2 = np.r_[1e-100, freq, 1e4, 1e100]
tmp_s2 = np.r_[0, field, 0, 0]
else:
tmp_f2 = np.r_[1e-100, freq, 1e100]
tmp_s2 = np.r_[0, field, 0]
i_field2 = 1j*si.pchip_interpolate(tmp_f2, tmp_s2.imag, req_freq)
# Calculate the error as a fct of max(|E_x|).
error = np.abs((i_field.imag-field.imag)/max(np.abs(field)))
# Check error; if any bigger than rtol, get a new frequency.
ierr = np.arange(freq.size)[error > rtol]
new_freq = np.array([])
if len(ierr) > 0:
# Calculate log10-freqs and differences between freqs.
lfreq = np.log10(freq)
diff = np.diff(lfreq)
# Add new frequency depending on location in array.
if error[0] > rtol:
# If first frequency is not stable, subtract 1/2 decade.
new_lfreq = lfreq[ierr[0]] - 0.5
elif error[-1] > rtol and len(ierr) == 1:
# If last frequency is not stable, add 1/2 decade.
new_lfreq = lfreq[ierr[0]] + 0.5
else:
# If not first and not last, create new halfway to next frequency.
new_lfreq = lfreq[ierr[0]] + diff[ierr[0]]/2
# Back from log10.
new_freq = 10**np.array([new_lfreq])
# Return new frequencies
if full_output:
if req_freq is not None:
return (new_freq, i_field, error, ierr, i_field2)
else:
return (new_freq, i_field, error, ierr)
else:
return new_freq
def design_freq_range(time, model, rtol, signal, freq_range, xlim_freq=None,
ylim_freq=None, xlim_lin=None, ylim_lin=None,
xlim_log=None, ylim_log=None, pause=0.1):
"""GUI to design required frequencies for Fourier transform."""
# Get required frequencies for provided time and ft, verbose.
time, req_freq, ft, ftarg = empymod.utils.check_time(
time=time, signal=signal, ft=model.get('ft', 'dlf'),
ftarg=model.get('ftarg', {}), verb=3
)
req_freq, ri = np.unique(req_freq, return_inverse=True)
# Use empymod-utilities to print frequency range.
mod = empymod.utils.check_model(
[], 1, None, None, None, None, None, False, 0)
_ = empymod.utils.check_frequency(req_freq, *mod[1:-1], 3)
# Calculate "good" f- and t-domain field.
fine_model = model.copy()
for key in ['ht', 'htarg', 'ft', 'ftarg']:
if key in fine_model:
del fine_model[key]
fine_model['ht'] = 'dlf'
fine_model['htarg'] = {'pts_per_dec': -1}
fine_model['ft'] = 'dlf'
fine_model['ftarg'] = {'pts_per_dec': -1}
sfEM = empymod.dipole(freqtime=req_freq, **fine_model)
stEM = empymod.dipole(freqtime=time, signal=signal, **fine_model)
# Define initial frequencies.
if isinstance(freq_range, tuple):
new_freq = np.logspace(*freq_range)
elif isinstance(freq_range, np.ndarray):
new_freq = freq_range
else:
p, _ = find_peaks(np.abs(sfEM.imag))
# Get first n peaks.
new_freq = req_freq[p[:freq_range]]
# Add midpoints, plus one before.
lfreq = np.log10(new_freq)
new_freq = 10**np.unique(np.r_[lfreq, lfreq[:-1]+np.diff(lfreq),
lfreq[0]-np.diff(lfreq[:2])])
# Start figure and print current number of frequencies.
fig, axs = plt.subplots(2, 3, figsize=(9, 8))
fig.h_sup = plt.suptitle("Number of frequencies: --.", y=1, fontsize=14)
# Subplot 1: Actual signals.
axs[0, 0].set_title(r'Im($E_x$)')
axs[0, 0].set_xlabel('Frequency (Hz)')
axs[0, 0].set_ylabel(r'$E_x$ (V/m)')
axs[0, 0].set_xscale('log')
axs[0, 0].get_shared_x_axes().join(axs[0, 0], axs[1, 0])
if xlim_freq is not None:
axs[0, 0].set_xlim(xlim_freq)
else:
axs[0, 0].set_xlim([min(req_freq), max(req_freq)])
if ylim_freq is not None:
axs[0, 0].set_ylim(ylim_freq)
axs[0, 0].plot(req_freq, sfEM.imag, 'k')
# Subplot 2: Error.
axs[1, 0].set_title(r'$|\Im(E_x-E^{\rm{int}}_x)/\max|E_x||$')
axs[1, 0].set_xlabel('Frequency (Hz)')
axs[1, 0].set_ylabel('Relative error (%)')
axs[1, 0].axhline(100*rtol, c='k') # Tolerance of error-level.
axs[1, 0].set_yscale('log')
axs[1, 0].set_xscale('log')
axs[1, 0].set_ylim([1e-2, 1e2])
# Subplot 3: Linear t-domain model.
axs[0, 1].set_xlabel('Time (s)')
axs[0, 1].get_shared_x_axes().join(axs[0, 1], axs[1, 1])
if xlim_lin is not None:
axs[0, 1].set_xlim(xlim_lin)
else:
axs[0, 1].set_xlim([min(time), max(time)])
if ylim_lin is not None:
axs[0, 1].set_ylim(ylim_lin)
else:
axs[0, 1].set_ylim(
[min(-max(stEM)/20, 0.9*min(stEM)),
max(-min(stEM)/20, 1.1*max(stEM))])
axs[0, 1].plot(time, stEM, 'k-', lw=1)
# Subplot 4: Error linear t-domain model.
axs[1, 1].set_title('Error')
axs[1, 1].set_xlabel('Time (s)')
axs[1, 1].axhline(100*rtol, c='k')
axs[1, 1].set_yscale('log')
axs[1, 1].set_ylim([1e-2, 1e2])
# Subplot 5: Logarithmic t-domain model.
axs[0, 2].set_xlabel('Time (s)')
axs[0, 2].set_xscale('log')
axs[0, 2].set_yscale('log')
axs[0, 2].get_shared_x_axes().join(axs[0, 2], axs[1, 2])
if xlim_log is not None:
axs[0, 2].set_xlim(xlim_log)
else:
axs[0, 2].set_xlim([min(time), max(time)])
if ylim_log is not None:
axs[0, 2].set_ylim(ylim_log)
axs[0, 2].plot(time, stEM, 'k-', lw=1)
# Subplot 6: Error logarithmic t-domain model.
axs[1, 2].set_title('Error')
axs[1, 2].set_xlabel('Time (s)')
axs[1, 2].axhline(100*rtol, c='k')
axs[1, 2].set_yscale('log')
axs[1, 2].set_xscale('log')
axs[1, 2].set_ylim([1e-2, 1e2])
plt.tight_layout()
fig.canvas.draw()
plt.pause(pause)
# Pre-allocate arrays.
freq = np.array([], dtype=float)
fEM = np.array([], dtype=complex)
# Loop until satisfied.
while len(new_freq) > 0:
# Calculate fEM for new frequencies.
new_fEM = empymod.dipole(freqtime=new_freq, **model)
# Combine existing and new frequencies and fEM.
freq, ai = np.unique(np.r_[freq, new_freq], return_index=True)
fEM = np.r_[fEM, new_fEM][ai]
# Check if more frequencies are required.
out = get_new_freq(freq, fEM, rtol, req_freq, True)
new_freq = out[0]
# Calculate corresponding time-domain signal.
# 1. Interpolation to required frequencies
# Slightly different for real and imaginary parts.
# 3-point ramp from last frequency, step-size is diff. btw last two
# freqs.
lfreq = np.log10(freq)
freq_ramp = 10**(np.ones(3)*lfreq[-1] +
np.arange(1, 4)*np.diff(lfreq[-2:]))
fEM_ramp = np.array([0.75, 0.5, 0.25])*fEM[-1]
# Imag: Add ramp and also 0-fields at +/-1e-100.
itmp_f = np.r_[1e-100, freq, freq_ramp, 1e100]
itmp_s = np.r_[0, fEM.imag, fEM_ramp.imag, 0]
isfEM = si.pchip_interpolate(itmp_f, itmp_s, req_freq)
# Real: Add ramp and also 0-fields at +1e-100 (not at -1e-100).
rtmp_f = np.r_[freq, freq_ramp, 1e100]
rtmp_s = np.r_[fEM.real, fEM_ramp.real, 0]
rsfEM = si.pchip_interpolate(rtmp_f, rtmp_s, req_freq)
# Combine
sfEM = rsfEM + 1j*isfEM
# Re-arrange req_freq and sfEM if ri is provided.
if ri is not None:
req_freq = req_freq[ri]
sfEM = sfEM[ri]
# 2. Carry out the actual Fourier transform.
# (without checking for QWE convergence.)
tEM, _ = empymod.model.tem(
sfEM[:, None], np.atleast_1d(model['rec'][0]), freq=req_freq,
time=time, signal=signal, ft=ft, ftarg=ftarg)
# Reshape and return
nrec, nsrc = 1, 1
tEM = np.squeeze(tEM.reshape((-1, nrec, nsrc), order='F'))
# Clean up old lines before updating plots.
names = ['tlin', 'tlog', 'elin', 'elog', 'if2', 'err', 'erd', 'err1',
'erd1']
for name in names:
if hasattr(fig, 'h_'+name):
getattr(fig, 'h_'+name).remove()
# Adjust number of frequencies.
fig.h_sup = plt.suptitle(f"Number of frequencies: {freq.size}.",
y=1, fontsize=14)
# Plot the interpolated points.
error_bars = [fEM.imag-out[1].imag, fEM.imag*0]
fig.h_err = axs[0, 0].errorbar(
freq, fEM.imag, yerr=error_bars, fmt='.', ms=8, color='k',
ecolor='C0', label='Calc. points')
# Plot the error.
fig.h_erd, = axs[1, 0].plot(freq, 100*out[2], 'C0o', ms=6)
# Make frequency under consideration blue.
ierr = out[3]
if len(ierr) > 0:
iierr = ierr[0]
fig.h_err1, = axs[0, 0].plot(freq[iierr], out[1][iierr].imag,
'bo', ms=6)
fig.h_erd1, = axs[1, 0].plot(freq[iierr], 100*out[2][iierr],
'bo', ms=6)
# Plot complete interpolation.
fig.h_if2, = axs[0, 0].plot(req_freq, out[4].imag, 'C0--')
# Plot current time domain result and error.
fig.h_tlin, = axs[0, 1].plot(time, tEM, 'C0-')
fig.h_tlog, = axs[0, 2].plot(time, tEM, 'C0-')
fig.h_elin, = axs[1, 1].plot(time, 100*abs((tEM-stEM)/stEM), 'r--')
fig.h_elog, = axs[1, 2].plot(time, 100*abs((tEM-stEM)/stEM), 'r--')
plt.tight_layout()
fig.canvas.draw()
plt.pause(pause)
# Return time-domain signal (correspond to provided times); also
# return used frequencies and corresponding signal.
return tEM, freq, fEM
| [
11748,
795,
70,
18,
67,
198,
11748,
795,
9078,
4666,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
20966,
88,
28029,
11407,
355,
40803,
198,
11748,
629,
541,
88,
13,
3849,
16104,
378,
355,
33721,
198,
11748,
2603,
29487,
8019,
13,
9... | 1.95014 | 15,002 |
import urllib
import base64
from secrets import token_hex
from mitama.app import Middleware
from mitama.app.http import Response
from mitama.models import User
class SessionMiddleware(Middleware):
"""ใญใฐใคใณๅคๅฎใใใซใฆใงใข
ใญใฐใคใณใใฆใใชใใฆใผใถใผใใขใฏใปในใใๅ ดๅใ/login?redirect_to=<URL>ใซใชใใคใฌใฏใใใพใใ
"""
class BasicMiddleware(Middleware):
"""BASIC่ช่จผใใใซใฆใงใข"""
| [
11748,
2956,
297,
571,
198,
11748,
2779,
2414,
198,
6738,
13141,
1330,
11241,
62,
33095,
198,
198,
6738,
10255,
1689,
13,
1324,
1330,
6046,
1574,
198,
6738,
10255,
1689,
13,
1324,
13,
4023,
1330,
18261,
198,
6738,
10255,
1689,
13,
27530... | 2.185185 | 162 |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import pytest
import time
import mdg
from utils import generate_random_problem
A, G, W = generate_random_problem(10)
@pytest.mark.parametrize("solver_type", [mdg.CBC, mdg.BOP, mdg.SAT])
| [
2,
15069,
6186,
13,
785,
11,
3457,
13,
393,
663,
29116,
13,
1439,
6923,
33876,
13,
198,
2,
30628,
55,
12,
34156,
12,
33234,
7483,
25,
24843,
12,
17,
13,
15,
198,
198,
11748,
12972,
9288,
198,
11748,
640,
198,
11748,
45243,
70,
198... | 2.723214 | 112 |
import pyautogui # This Python library is required in order to run this code; If you don't have this 3rd party module installed, Google it and install prior to running this code.
import time # This is a standard Python library, used in this example to delay the time between each press of the "shift" key.
pyautogui.FAILSAFE = False # This to ensure the script doesn't fail when you have the mouse pointer in the top left corner.
while 1: # I use "1" instead of "True" to shorten the code by three characters.
time.sleep(250) # This is set to 250 seconds
"""
You can use the code below, but it isn't necessary. After testing, I've found that moving the mouse is a nuisance if you're using the computer.
It turns out that the call to "shift" is all that's necessary to keep the computer awake (i.e., prevent a log out of Windows).
for i in range(1,144,4):
pyautogui.moveTo(960,i*4)
"""
pyautogui.press('shift') # I found that the "shift" key is a very good key to press - I never notice any disruption when running this script while doing my day to day work.
print('Shift was pressed at {}'.format(time.strftime('%I:%M:%S'))) # This is solely for informational purposes; this line prints the time at which "shift" is pressed to the console.
| [
11748,
12972,
2306,
519,
9019,
1303,
770,
11361,
5888,
318,
2672,
287,
1502,
284,
1057,
428,
2438,
26,
1002,
345,
836,
470,
423,
428,
513,
4372,
2151,
8265,
6589,
11,
3012,
340,
290,
2721,
3161,
284,
2491,
428,
2438,
13,
198,
11748,
... | 3.474394 | 371 |
#!/usr/bin/python
import sys
import re
end_characters = ";{}" # all the characters to be moved
# regex makes five groups: [indentation, end_chars, body, idk, end_chars, body]
# most are optional and will have the value None when checked
# regex = "([ \t]*)?([{0}]+)?([^{0}]+)([{0}]+)?(.*)$".format(end_characters)
regex = "([ \t]*)?([;{}]+)?(([^;{}]|[;{}](?=.*\))|{(?=.*}))+)([;{} ]+)?(.*)$"
delete_lines = []
file_name = sys.argv[1]
with open(file_name, 'r') as f:
file = list(f)
# replace tabs with spaces so line length is consistent
for line in range(len(file)):
file[line] = file[line].replace("\t", " ")
# place the column of characters after the longest line
padding = max(len(i) for i in file)
lastLine = 0 # the last line containing non end characters
for n, line in enumerate(file):
if any(c not in end_characters for c in line.strip()):
if sum([line.count(c) for c in end_characters]) > 0:
# split line into regex groups
match = re.match(regex, line)
# if there are end characters at the beginning put them on the previous line
if match[2]:
file[lastLine] = file[lastLine][:-1] + match[2] + '\n'
# the main part which doesn't move after
body = ""
# indentation
if match[1]:
body += match[1]
# main part before
if match[3]:
body += match[3]
# any text like comments after the last end characters
if match[6]:
body += match[6]
file[n] = body.ljust(padding)
if match[5]:
file[n] += match[5]
file[n] += '\n'
else:
file[n] = file[n][:-1].ljust(padding) + '\n'
lastLine = n
elif line.strip() != "":
# if a line is just end characters move it to the last normal line
file[lastLine] = file[lastLine][:-1] + line.strip() + '\n'
# mark the moved line to be deleted
delete_lines.append(n)
# delete all the moved lines
for line in reversed(delete_lines):
file.pop(line)
# strip trailing spaces and add newlines
for line in range(len(file)):
file[line] = file[line].rstrip() + '\n'
with open(file_name, "w") as f:
f.write("".join(file))
| [
2,
48443,
14629,
14,
8800,
14,
29412,
198,
198,
11748,
25064,
198,
11748,
302,
198,
198,
437,
62,
10641,
19858,
796,
366,
26,
90,
36786,
1303,
477,
262,
3435,
284,
307,
3888,
198,
2,
40364,
1838,
1936,
2628,
25,
685,
521,
298,
341,
... | 2.228544 | 1,037 |
'''
File: crop_img.py
Project: sketchKeras
File Created: Thursday, 18th October 2018 7:31:16 pm
Author: xiaofeng (sxf1052566766@163.com)
-----
Last Modified: Friday, 19th October 2018 5:32:45 pm
Modified By: xiaofeng (sxf1052566766@163.com>)
-----
Copyright 2018.06 - 2018 onion Math, onion Math
'''
import cv2
import os
file_list = []
# Test the function
read_file = './img/1_CropSurroundingBlack.jpg'
croped_img = CropSurroundingBlack(read_file)
cv2.imwrite('./img/1_CropSurroundingBlack_done.jpg',croped_img)
| [
198,
7061,
6,
198,
8979,
25,
13833,
62,
9600,
13,
9078,
198,
16775,
25,
17548,
42,
263,
292,
198,
8979,
15622,
25,
3635,
11,
1248,
400,
3267,
2864,
767,
25,
3132,
25,
1433,
9114,
198,
13838,
25,
2124,
544,
1659,
1516,
357,
82,
261... | 2.616162 | 198 |
import torch.nn as nn
from model_training.common.modules import ResBlock
if __name__ == '__main__':
from torchsummary import summary
net = UNetAddNet(in_channels=4, out_channels=3)
summary(net, (4, 240, 240), device='cpu')
| [
11748,
28034,
13,
20471,
355,
299,
77,
198,
6738,
2746,
62,
34409,
13,
11321,
13,
18170,
1330,
1874,
12235,
628,
198,
198,
361,
11593,
3672,
834,
6624,
705,
834,
12417,
834,
10354,
198,
220,
220,
220,
422,
28034,
49736,
1330,
10638,
6... | 2.77907 | 86 |
STEPS = [(1,1), (3,1), (5,1), (7,1), (1,2)]
file = open('input.txt')
slope_map = file.readlines()
trees_multi = 1
line_len = len(slope_map[0])
for step in STEPS:
pos = 0
trees_hit = 0
for tree_row in slope_map[step[1]::step[1]]:
pos = (pos + step[0]) % (line_len - 1)
if is_tree(tree_row[pos]):
trees_hit += 1
trees_multi *= trees_hit
file.close()
print('Trees multiplied:', trees_multi) | [
30516,
3705,
796,
47527,
16,
11,
16,
828,
357,
18,
11,
16,
828,
357,
20,
11,
16,
828,
357,
22,
11,
16,
828,
357,
16,
11,
17,
15437,
198,
198,
7753,
796,
1280,
10786,
15414,
13,
14116,
11537,
198,
6649,
3008,
62,
8899,
796,
2393,... | 2.085714 | 210 |