hexsha stringlengths 40 40 | size int64 5 2.06M | ext stringclasses 11 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 251 | max_stars_repo_name stringlengths 4 130 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 251 | max_issues_repo_name stringlengths 4 130 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 116k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 251 | max_forks_repo_name stringlengths 4 130 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 1 1.05M | avg_line_length float64 1 1.02M | max_line_length int64 3 1.04M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
71d8ae81fc5cc4e5cfdae9050c0caf054c81bfb5 | 48 | py | Python | GermanOK/run.py | romainledru/GermanOK | 77bc86de0eabbd3d7413382a288fea286d608540 | [
"MIT"
] | null | null | null | GermanOK/run.py | romainledru/GermanOK | 77bc86de0eabbd3d7413382a288fea286d608540 | [
"MIT"
] | null | null | null | GermanOK/run.py | romainledru/GermanOK | 77bc86de0eabbd3d7413382a288fea286d608540 | [
"MIT"
] | null | null | null | from Pages import *
app = App()
app.mainloop()
| 9.6 | 19 | 0.666667 |
71d94b479d90dc462de92906e5d1f18653ee665b | 433 | py | Python | cauldron/cli/server/routes/ui_statuses.py | JohnnyPeng18/cauldron | 09120c2a4cef65df46f8c0c94f5d79395b3298cd | [
"MIT"
] | 90 | 2016-09-02T15:11:10.000Z | 2022-01-02T11:37:57.000Z | cauldron/cli/server/routes/ui_statuses.py | JohnnyPeng18/cauldron | 09120c2a4cef65df46f8c0c94f5d79395b3298cd | [
"MIT"
] | 86 | 2016-09-23T16:52:22.000Z | 2022-03-31T21:39:56.000Z | cauldron/cli/server/routes/ui_statuses.py | JohnnyPeng18/cauldron | 09120c2a4cef65df46f8c0c94f5d79395b3298cd | [
"MIT"
] | 261 | 2016-12-22T05:36:48.000Z | 2021-11-26T12:40:42.000Z | import flask
from cauldron.cli.server import run as server_runner
from cauldron.ui import arguments
from cauldron.ui import statuses
| 28.866667 | 64 | 0.750577 |
71dbada9e9753ae2bf8f715ece9e73e4bfe13daa | 418 | py | Python | google_search.py | Jaram2019/minwoo | d98ce8a84675281e237368cbe97d8a2120ce5840 | [
"MIT"
] | null | null | null | google_search.py | Jaram2019/minwoo | d98ce8a84675281e237368cbe97d8a2120ce5840 | [
"MIT"
] | null | null | null | google_search.py | Jaram2019/minwoo | d98ce8a84675281e237368cbe97d8a2120ce5840 | [
"MIT"
] | null | null | null | import requests
from bs4 import BeautifulSoup
import re
rq = requests.get("https://play.google.com/store/apps/category/GAME_MUSIC?hl=ko")
rqctnt = rq.content
soup = BeautifulSoup(rqctnt,"html.parser")
soup = soup.find_all(attrs={'class':'title'})
blacklsit = ["","/TV","","","","",""]
for link in soup:
if link.text.strip() in blacklsit:
pass
else:
print(link.text.strip())
| 24.588235 | 81 | 0.674641 |
71dbf8ffa644ff16bfd38b31d3b7d01cb8ab4ea8 | 203 | py | Python | pygall/tests/test_photos.py | bbinet/PyGall | 4d83165e50ca927d664aa6b7b716eb8f484c3cd6 | [
"BSD-3-Clause"
] | 1 | 2021-05-09T16:43:49.000Z | 2021-05-09T16:43:49.000Z | pygall/tests/test_photos.py | bbinet/PyGall | 4d83165e50ca927d664aa6b7b716eb8f484c3cd6 | [
"BSD-3-Clause"
] | null | null | null | pygall/tests/test_photos.py | bbinet/PyGall | 4d83165e50ca927d664aa6b7b716eb8f484c3cd6 | [
"BSD-3-Clause"
] | 3 | 2015-10-04T20:53:04.000Z | 2017-11-20T21:51:21.000Z | from unittest import TestCase
from pyramid import testing
| 14.5 | 37 | 0.679803 |
71dd434a3adaa696a17ec425e131077b6639bbec | 2,995 | py | Python | Chapter_4/lists_data_type.py | alenasf/AutomateTheBoringStuff | 041e56221eb98d9893c24d22497034e6344c0490 | [
"Apache-2.0"
] | null | null | null | Chapter_4/lists_data_type.py | alenasf/AutomateTheBoringStuff | 041e56221eb98d9893c24d22497034e6344c0490 | [
"Apache-2.0"
] | null | null | null | Chapter_4/lists_data_type.py | alenasf/AutomateTheBoringStuff | 041e56221eb98d9893c24d22497034e6344c0490 | [
"Apache-2.0"
] | null | null | null | #Negative Indexes
spam = ['cat', 'bat', 'rat', 'elephant']
spam[-1] # elepant
spam[-3] # bat
# Getting a List from another List with Slices
spam = ['cat', 'bat', 'rat', 'elephant']
spam[0:4] # ['cat', 'bat', 'rat', 'elephant']
spam[1:3] # ['bat', 'rat']
spam[0:-1] # ['cat', 'bat', 'rat']
spam[:2] # ['cat', 'bat']
spam[1:] # ['bat', 'rat', 'elephant']
spam[:] # ['cat', 'bat', 'rat', 'elephant']
# Getting a List's length with the len() Function
spam = ['cat', 'dog', 'moose']
len(spam) # 3
# Changing Values in a List with Indexes
spam = ['cat', 'bat', 'rat', 'elephant']
spam[1] = 'aardvark'
spam # ['cat', 'aardvark', 'rat', 'elephant']
spam[2]=spam[1]
spam # ['cat', 'aardvark', 'aardvark', 'elephant']
spam[-1] = 12345
spam # ['cat', 'aardvark', 'aardvark', 12345]
# List Concatenation and List Replication
[1, 2, 3] + ['A', 'B', 'C']
# [1, 2, 3, 'A', 'B', 'C']
['X', 'Y', 'Z'] * 3
#['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
spam = [1, 2, 3]
spam = spam + ['A', 'B', 'C']
# [1, 2, 3, 'A', 'B', 'C']
# Removing Values From Lists with del Statements
spam = ['cat', 'bat', 'rat', 'elephant']
del spam[2]
spam # ['cat', 'bat', 'elephant']
del spam[2]
spam # ['cat', 'bat']
# Using for Loops with Lists
for i in range(4):
print(i)
supplies = ['pens', 'staplers', 'flamethrowers', 'binders']
for i in range(len(supplies)):
print('Index ' + str(i) + ' in supplies is: ' + supplies[i])
# The in and not in Operators
'howdy' in ['hello', 'hi', 'howdy', 'heyas'] # True
spam = ['hello', 'hi', 'howdy', 'heyas']
'cat' in spam # False
'howdy' not in spam # False
# Type in a pet name and then check wether the name is in a list of pets
myPets = ['Zophie', 'Pooka', 'Fat-tail']
print('Enter a pet name:')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')
# The Multiple Assignment Trick
cat = ['fat', 'gray', 'loud']
size = cat[0]
color = cat[1]
disposition = cat[2]
# type this line
cat = ['fat', 'gray', 'loud']
size, color, disposition = cat
# Using the enumerate() Function with Lists
# enumerate() Function is useful when you need both the item and item's index in loop's block
supplies = ['pens', 'staplers', 'flamethrowers', 'binders']
for index, item in enumerate(supplies):
print('Index ' + str(index) + ' in supplies is: ' + item)
# Using the random.choice() and random.shuffle() Function with Lists
import random
pets = ['Dog', 'Cat', 'Moose']
random.choice(pets)
random.choice(pets)
random.choice(pets)
# random.choice(someList) to be a shorter form of someList[random.randint(0, len(someList)-1)]
import random
people = ['Alice', 'Bob', 'Carol', 'David']
random.shuffle(people)
people # ['Bob', 'Carol', 'David', 'Alice']
random.shuffle(people)
people # random list of people
#Augmented Assignment Operators
spam += 1 # spam = spam + 1
spam -= 1 # spam = spam - 1
spam *= 1 # spam = spam * 1
spam /= 1 #spam = spam / 1
spam %= 1 #spam = spam % 1
| 26.043478 | 94 | 0.600334 |
71de0e1236a03e6cfb4186e21a5012996969d350 | 130 | py | Python | WebVisualizations/data.py | chuhaovince/Web-Design-Challenge | 1826a0e2dfbe4e11feb78f0ecce02e0f8a0a7eb5 | [
"ADSL"
] | null | null | null | WebVisualizations/data.py | chuhaovince/Web-Design-Challenge | 1826a0e2dfbe4e11feb78f0ecce02e0f8a0a7eb5 | [
"ADSL"
] | null | null | null | WebVisualizations/data.py | chuhaovince/Web-Design-Challenge | 1826a0e2dfbe4e11feb78f0ecce02e0f8a0a7eb5 | [
"ADSL"
] | null | null | null | import pandas as pd
path = "Resources/cities.csv"
data = pd.read_csv(path)
data_html = data.to_html("data.html", bold_rows = True) | 32.5 | 55 | 0.746154 |
71dfbd47e154641ea34b44a5f3aa8459312d608f | 3,268 | py | Python | qemu/scripts/codeconverter/codeconverter/test_patching.py | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | 44 | 2022-03-16T08:32:31.000Z | 2022-03-31T16:02:35.000Z | qemu/scripts/codeconverter/codeconverter/test_patching.py | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | 1 | 2022-03-29T02:30:28.000Z | 2022-03-30T03:40:46.000Z | qemu/scripts/codeconverter/codeconverter/test_patching.py | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | 18 | 2022-03-19T04:41:04.000Z | 2022-03-31T03:32:12.000Z | # Copyright (C) 2020 Red Hat Inc.
#
# Authors:
# Eduardo Habkost <ehabkost@redhat.com>
#
# This work is licensed under the terms of the GNU GPL, version 2. See
# the COPYING file in the top-level directory.
from tempfile import NamedTemporaryFile
from .patching import FileInfo, FileMatch, Patch, FileList
from .regexps import *
def test_container_match():
of = NamedTemporaryFile('wt')
of.writelines(['statement1()\n',
'statement2()\n',
'BEGIN function1\n',
' statement3()\n',
' statement4()\n',
'END\n',
'BEGIN function2\n',
' statement5()\n',
' statement6()\n',
'END\n',
'statement7()\n'])
of.flush()
files = FileList()
f = FileInfo(files, of.name)
f.load()
assert len(f.matches_of_type(Function)) == 2
print(' '.join(m.name for m in f.matches_of_type(Statement)))
assert len(f.matches_of_type(Statement)) == 7
f1 = f.find_match(Function, 'function1')
f2 = f.find_match(Function, 'function2')
st1 = f.find_match(Statement, 'statement1')
st2 = f.find_match(Statement, 'statement2')
st3 = f.find_match(Statement, 'statement3')
st4 = f.find_match(Statement, 'statement4')
st5 = f.find_match(Statement, 'statement5')
st6 = f.find_match(Statement, 'statement6')
st7 = f.find_match(Statement, 'statement7')
assert not f1.contains(st1)
assert not f1.contains(st2)
assert not f1.contains(st2)
assert f1.contains(st3)
assert f1.contains(st4)
assert not f1.contains(st5)
assert not f1.contains(st6)
assert not f1.contains(st7)
assert not f2.contains(st1)
assert not f2.contains(st2)
assert not f2.contains(st2)
assert not f2.contains(st3)
assert not f2.contains(st4)
assert f2.contains(st5)
assert f2.contains(st6)
assert not f2.contains(st7)
| 31.12381 | 71 | 0.597613 |
71e063f198be6d799932aa28d7e46247d3e2c98f | 634 | py | Python | Traversy Media/Python Django Dev to Deployment/Python Fundamentals/Tuples and Sets.py | Anim-101/CourseHub | 570ddc2bca794c14921991d24fdf1b4a7d0beb68 | [
"MIT"
] | 3 | 2019-11-01T17:07:13.000Z | 2020-04-01T10:27:05.000Z | Traversy Media/Python Django Dev to Deployment/Python Fundamentals/Tuples and Sets.py | Anim-101/CourseHub | 570ddc2bca794c14921991d24fdf1b4a7d0beb68 | [
"MIT"
] | 18 | 2020-08-10T05:11:24.000Z | 2021-12-03T15:13:40.000Z | Traversy Media/Python Django Dev to Deployment/Python Fundamentals/Tuples and Sets.py | Anim-101/CourseHub | 570ddc2bca794c14921991d24fdf1b4a7d0beb68 | [
"MIT"
] | null | null | null | # # Simple Tuple
# fruits = ('Apple', 'Orange', 'Mango')
# # Using Constructor
# fruits = tuple(('Apple', 'Orange', 'Mango'))
# # Getting a Single Value
# print(fruits[1])
# Trying to change based on position
# fruits[1] = 'Grape'
# Tuples with one value should have trailing comma
# fruits = ('Apple')
# fruits = ('Apple',)
# # Getting length of a tupel
# print(len(fruits))
# ## Set
fruits = {'Apple', 'Orange', 'Mango', 'Apple'}
# Checking if in Set
print('Apple' in fruits)
# Add to Set
fruits.add('Grape')
# Removing from Set
fruits.remove('Grape')
# Clearing Set
fruits.clear()
# Delete set
del fruits
print(fruits)
| 16.25641 | 50 | 0.652997 |
71e0e6976164ccf999455f35ac70c3e13a0fe3ef | 20,146 | py | Python | nerblackbox/modules/ner_training/metrics/ner_metrics.py | flxst/nerblackbox | 7612b95850e637be258f6bfb01274453b7372f99 | [
"Apache-2.0"
] | null | null | null | nerblackbox/modules/ner_training/metrics/ner_metrics.py | flxst/nerblackbox | 7612b95850e637be258f6bfb01274453b7372f99 | [
"Apache-2.0"
] | null | null | null | nerblackbox/modules/ner_training/metrics/ner_metrics.py | flxst/nerblackbox | 7612b95850e637be258f6bfb01274453b7372f99 | [
"Apache-2.0"
] | null | null | null | from dataclasses import dataclass
from dataclasses import asdict
from typing import List, Tuple, Callable
import numpy as np
from sklearn.metrics import accuracy_score as accuracy_sklearn
from sklearn.metrics import precision_score as precision_sklearn
from sklearn.metrics import recall_score as recall_sklearn
from sklearn.metrics import precision_recall_fscore_support as prf_sklearn
from sklearn.exceptions import UndefinedMetricWarning
import warnings
from seqeval.metrics import precision_score as precision_seqeval
from seqeval.metrics import recall_score as recall_seqeval
from seqeval.metrics import f1_score as f1_seqeval
from seqeval.scheme import IOB2, BILOU
from nerblackbox.modules.ner_training.annotation_tags.tags import Tags
| 36.299099 | 116 | 0.538469 |
71e128bd284f8fc2eb997551cf3f8ee9632b562a | 2,192 | py | Python | Assignments/hw4/rank_feat_by_chi_square.py | spacemanidol/CLMS572 | f0380de9912c984ec21607cdb3b1f190853c5ca8 | [
"MIT"
] | null | null | null | Assignments/hw4/rank_feat_by_chi_square.py | spacemanidol/CLMS572 | f0380de9912c984ec21607cdb3b1f190853c5ca8 | [
"MIT"
] | null | null | null | Assignments/hw4/rank_feat_by_chi_square.py | spacemanidol/CLMS572 | f0380de9912c984ec21607cdb3b1f190853c5ca8 | [
"MIT"
] | 1 | 2020-12-26T01:28:41.000Z | 2020-12-26T01:28:41.000Z | import sys
if __name__ == "__main__":
data, all_features, labelCount= readInput()
results = rankByChiSquared(data, all_features, labelCount) | 56.205128 | 323 | 0.656022 |
71e26509acc4657f75e6829c9ddc1b7eeabb62a1 | 2,530 | py | Python | Files/joinfiles.py | LeoCruzG/4chan-thread-downloader | d449e50fc7f2a6273a11da3d8ff2f46aad4951d2 | [
"MIT"
] | null | null | null | Files/joinfiles.py | LeoCruzG/4chan-thread-downloader | d449e50fc7f2a6273a11da3d8ff2f46aad4951d2 | [
"MIT"
] | null | null | null | Files/joinfiles.py | LeoCruzG/4chan-thread-downloader | d449e50fc7f2a6273a11da3d8ff2f46aad4951d2 | [
"MIT"
] | null | null | null | # Importamos la librera para leer archivos json
import json
# Abrimos el archivo master en modo lectura ('r') con todos los id de los archivos descargados
with open('master.json', 'r') as f:
# Guardamos en la variable lista el contenido de master
lista = json.load(f)
# En este ejemplo se representa cmo se asignara a la lista archivos especficos
#lista = ['2095303', '2169202']
# Abrimos el archivo tryall.json en modo lectura ('w'), si no est creado previamente
# se crea en este momento, se puede cambiar nombre a este archivo
with open('tryall.json', 'w') as outfile:
# Iniciamos un contador para ir marcando cuntos archivos llevamos unidos
contador = 0
# Esta variable ayuda a guardar el nombre del archivo anterior para
# corroborar si no se est repitiendo con el anterior
helper = 0
# Esta variable nos indica que tenemos que escribir dentro del documento lo que hay
# dentro del archivo actual
update = True
# Recorremos toda la lista de archivos descargados
for names in lista:
# Abrimos cada archivo
with open(f'{names}.json') as infile:
# Leemos los primeras 3 lneas
infile.readline()
infile.readline()
infile.readline()
# Guardamos el contenido de la 4 que tiene el nmero del thread
# en una variable temportal
temp = infile.readline()
# Comprobamos si helper tiene el mismo contenido que temp
if helper != temp:
# Si es diferente se puede hacer la actualizacin ya que no se va
# a tener threads repetidos
update = True
# asignamos el nuevo contenido a la variable persistente
helper = temp
# Si tienen el mismo contenido entonces no se hace la actualizacin
else:
update = False
# Abrimos nuevamente el archivo
with open(f'{names}.json') as infile:
# Si el post no est repetido entra
if update == True:
# Se escribe el contenido completo del thread en el archivo de salida
outfile.write(infile.read())
# Se aumenta el contador ya que se escribi un documento nuevo
contador+=1
# Se imporime el contador con el nombre del archivo ledo
print(contador, names)
# Se pone un salto de pgina para escribir el contenido del archivo siguiente
outfile.write("\n") | 42.166667 | 94 | 0.633992 |
71e353fb7e64c4a4a126f497726d3763f4f1a40c | 2,860 | py | Python | pycopula/archimedean_generators.py | SvenSerneels/pycopula | 27c703ab0d25356f6e78b7cc16c8ece1ed80f871 | [
"Apache-2.0"
] | 2 | 2020-05-09T21:08:34.000Z | 2021-02-23T06:58:51.000Z | pycopula/archimedean_generators.py | SvenSerneels/pycopula | 27c703ab0d25356f6e78b7cc16c8ece1ed80f871 | [
"Apache-2.0"
] | null | null | null | pycopula/archimedean_generators.py | SvenSerneels/pycopula | 27c703ab0d25356f6e78b7cc16c8ece1ed80f871 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file contains the generators and their inverses for common archimedean copulas.
"""
import numpy as np
| 37.142857 | 114 | 0.642308 |
71e38c0bb4ea71106c0ea08a5cac097ca0ed5c4c | 126 | py | Python | app/admin/__init__.py | blackboard/BBDN-Base-Python-Flask | 710b82bfb45217798d9e9edda13d5e0f632e2284 | [
"MIT"
] | null | null | null | app/admin/__init__.py | blackboard/BBDN-Base-Python-Flask | 710b82bfb45217798d9e9edda13d5e0f632e2284 | [
"MIT"
] | 2 | 2022-03-16T01:34:51.000Z | 2022-03-16T01:34:56.000Z | app/admin/__init__.py | Eddyjim/BB-BaseTool | 39fd41cc503b7c31886426b8b017c5f9acfe5072 | [
"MIT"
] | null | null | null | """
"""
from admin import routes
def init_app(app):
"""
:param app:
:return:
"""
routes.init_app(app)
| 9 | 24 | 0.52381 |
71e43b48b96fcad3e7e8029cf7b4f49e58e53fda | 243 | py | Python | output/models/nist_data/list_pkg/decimal/schema_instance/nistschema_sv_iv_list_decimal_pattern_2_xsd/__init__.py | tefra/xsdata-w3c-tests | b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f | [
"MIT"
] | 1 | 2021-08-14T17:59:21.000Z | 2021-08-14T17:59:21.000Z | output/models/nist_data/list_pkg/decimal/schema_instance/nistschema_sv_iv_list_decimal_pattern_2_xsd/__init__.py | tefra/xsdata-w3c-tests | b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f | [
"MIT"
] | 4 | 2020-02-12T21:30:44.000Z | 2020-04-15T20:06:46.000Z | output/models/nist_data/list_pkg/decimal/schema_instance/nistschema_sv_iv_list_decimal_pattern_2_xsd/__init__.py | tefra/xsdata-w3c-tests | b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f | [
"MIT"
] | null | null | null | from output.models.nist_data.list_pkg.decimal.schema_instance.nistschema_sv_iv_list_decimal_pattern_2_xsd.nistschema_sv_iv_list_decimal_pattern_2 import NistschemaSvIvListDecimalPattern2
__all__ = [
"NistschemaSvIvListDecimalPattern2",
]
| 40.5 | 186 | 0.888889 |
e07b1d529111d4e2e89b3b1cd2c58ff9446e312f | 6,642 | py | Python | fem/fem.py | Pengeace/DGP-PDE-FEM | 64b7f42ca7083b05f05c42baa6cad21084068d8c | [
"MIT"
] | 7 | 2019-06-26T07:25:33.000Z | 2021-06-25T03:40:22.000Z | fem/fem.py | Pengeace/DGP-PDE-FEM | 64b7f42ca7083b05f05c42baa6cad21084068d8c | [
"MIT"
] | null | null | null | fem/fem.py | Pengeace/DGP-PDE-FEM | 64b7f42ca7083b05f05c42baa6cad21084068d8c | [
"MIT"
] | null | null | null | import numpy as np
import pyamg
from scipy import sparse
from scipy.spatial import Delaunay
from linsolver import sparse_solver
from triangulation.delaunay import delaunay
| 40.012048 | 141 | 0.643029 |
e07c0e48507e0965db82bd0823c76af3d0ebb993 | 2,745 | py | Python | custom_components/tahoma/climate_devices/dimmer_exterior_heating.py | MatthewFlamm/ha-tahoma | 794e8e4a54a8e5f55622b88bb1ab5ffc3ecb0d1b | [
"MIT"
] | null | null | null | custom_components/tahoma/climate_devices/dimmer_exterior_heating.py | MatthewFlamm/ha-tahoma | 794e8e4a54a8e5f55622b88bb1ab5ffc3ecb0d1b | [
"MIT"
] | null | null | null | custom_components/tahoma/climate_devices/dimmer_exterior_heating.py | MatthewFlamm/ha-tahoma | 794e8e4a54a8e5f55622b88bb1ab5ffc3ecb0d1b | [
"MIT"
] | null | null | null | """Support for Atlantic Electrical Heater IO controller."""
import logging
from typing import List
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS
from ..coordinator import TahomaDataUpdateCoordinator
from ..tahoma_entity import TahomaEntity
_LOGGER = logging.getLogger(__name__)
COMMAND_GET_LEVEL = "getLevel"
COMMAND_SET_LEVEL = "setLevel"
CORE_LEVEL_STATE = "core:LevelState"
| 31.918605 | 82 | 0.687796 |
e07c5c23f946a28e4cc418a3bd4c6debbb0d6123 | 3,271 | py | Python | elit/components/mtl/attn/joint_encoder.py | emorynlp/stem-cell-hypothesis | 48a628093d93d653865fbac6409d179cddd99293 | [
"Apache-2.0"
] | 4 | 2021-09-17T15:23:31.000Z | 2022-02-28T10:18:04.000Z | elit/components/mtl/attn/joint_encoder.py | emorynlp/stem-cell-hypothesis | 48a628093d93d653865fbac6409d179cddd99293 | [
"Apache-2.0"
] | null | null | null | elit/components/mtl/attn/joint_encoder.py | emorynlp/stem-cell-hypothesis | 48a628093d93d653865fbac6409d179cddd99293 | [
"Apache-2.0"
] | null | null | null | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2021-03-02 13:32
from typing import Optional, Union, Dict, Any
import torch
from torch import nn
from transformers import PreTrainedTokenizer
from elit.components.mtl.attn.attn import TaskAttention
from elit.components.mtl.attn.transformer import JointEncoder
from elit.layers.embeddings.contextual_word_embedding import ContextualWordEmbeddingModule, ContextualWordEmbedding
from elit.layers.scalar_mix import ScalarMixWithDropoutBuilder
from elit.layers.transformers.utils import pick_tensor_for_each_token
| 53.622951 | 120 | 0.63956 |
e07c7e8ff8aa0c1088ab724943f3572b8b2fff02 | 68 | py | Python | simulation/sensors/__init__.py | salinsiim/petssa-simulation | 8f0f128d462831f86664bb8d246f2c7b659a0b8d | [
"MIT"
] | null | null | null | simulation/sensors/__init__.py | salinsiim/petssa-simulation | 8f0f128d462831f86664bb8d246f2c7b659a0b8d | [
"MIT"
] | null | null | null | simulation/sensors/__init__.py | salinsiim/petssa-simulation | 8f0f128d462831f86664bb8d246f2c7b659a0b8d | [
"MIT"
] | null | null | null | from sensors.sensors import sense_characteristics, sense_pedestrians | 68 | 68 | 0.911765 |
e07ce9c764d3c52f1697472892d9c4a14a2d9b6a | 5,140 | py | Python | jaxrl/agents/sac_v1/sac_v1_learner.py | anuragajay/jaxrl | a37414aea9e281f19719ccfc09702b32e1ef4e44 | [
"MIT"
] | 157 | 2021-03-12T04:30:53.000Z | 2021-06-10T11:28:48.000Z | jaxrl/agents/sac_v1/sac_v1_learner.py | anuragajay/jaxrl | a37414aea9e281f19719ccfc09702b32e1ef4e44 | [
"MIT"
] | 3 | 2021-09-23T21:13:28.000Z | 2021-11-19T12:32:34.000Z | jaxrl/agents/sac_v1/sac_v1_learner.py | anuragajay/jaxrl | a37414aea9e281f19719ccfc09702b32e1ef4e44 | [
"MIT"
] | 17 | 2021-06-15T13:38:35.000Z | 2022-03-17T15:25:23.000Z | """Implementations of algorithms for continuous control."""
import functools
from typing import Optional, Sequence, Tuple
import jax
import jax.numpy as jnp
import numpy as np
import optax
from jaxrl.agents.sac import temperature
from jaxrl.agents.sac.actor import update as update_actor
from jaxrl.agents.sac.critic import target_update
from jaxrl.agents.sac_v1.critic import update_q, update_v
from jaxrl.datasets import Batch
from jaxrl.networks import critic_net, policies
from jaxrl.networks.common import InfoDict, Model, PRNGKey
| 35.694444 | 107 | 0.596887 |
e07cfc67fee77a3b15475a7b5db3f7fe4ab08200 | 14,515 | py | Python | rbc/libfuncs.py | plures/rbc | 57c170c148000e7b56f0cda2f0dbea7bdcfa0e1b | [
"BSD-3-Clause"
] | 1 | 2019-02-15T14:14:58.000Z | 2019-02-15T14:14:58.000Z | rbc/libfuncs.py | plures/rbc | 57c170c148000e7b56f0cda2f0dbea7bdcfa0e1b | [
"BSD-3-Clause"
] | null | null | null | rbc/libfuncs.py | plures/rbc | 57c170c148000e7b56f0cda2f0dbea7bdcfa0e1b | [
"BSD-3-Clause"
] | null | null | null | """Collections of library function names.
"""
def drop_suffix(f):
s = f.rsplit('.', 1)[-1]
if s in ['p0i8', 'f64', 'f32', 'i1', 'i8', 'i16', 'i32', 'i64', 'i128']:
f = f[:-len(s)-1]
return drop_suffix(f)
return f
def get_llvm_name(f, prefix='llvm.'):
"""Return normalized name of a llvm intrinsic name.
"""
if f.startswith(prefix):
return drop_suffix(f[len(prefix):])
return f
| 46.822581 | 98 | 0.759904 |
e07d1faf3d069567748feca41784098709e225b2 | 1,143 | py | Python | quick_pandas.py | chenmich/google-ml-crash-course-exercises | d610f890d53b1537a3ce80531ce1ff2df1f5dc84 | [
"MIT"
] | null | null | null | quick_pandas.py | chenmich/google-ml-crash-course-exercises | d610f890d53b1537a3ce80531ce1ff2df1f5dc84 | [
"MIT"
] | null | null | null | quick_pandas.py | chenmich/google-ml-crash-course-exercises | d610f890d53b1537a3ce80531ce1ff2df1f5dc84 | [
"MIT"
] | null | null | null | import pandas as pd
print(pd.__version__)
city_names = pd.Series(['San Francisco', 'San Jose', 'Sacramento'])
population = pd.Series([852469, 1015785, 485199])
#city_population_table = pd.DataFrame(({'City name': city_names, 'Population': population}))
california_houseing_dataframe = pd.read_csv("https://storage.googleapis.com/mledu-datasets/california_housing_train.csv", sep=",")
california_houseing_dataframe.describe()
california_houseing_dataframe.head()
#some error
#california_houseing_dataframe.hist('housing_median_age')
cities = pd.DataFrame({'City name': city_names, 'Population': population})
#print(type(cities['City name']))
#print(cities['City name'])
#print(type(cities['City name'][1]))
#print(cities['City name'][1])
#print(type(cities[0:2]))
#print(cities[0:2])
#print(population / 1000)
import numpy as np
np.log(population)
#print(population.apply(lambda val: val > 10000))
cities['Area square miles'] = pd.Series([46.87, 176.53, 97.92])
#print(cities)
cities['Population density'] = cities['Population'] / cities['Area square miles']
#print(cities)
print(city_names.index)
print(cities.reindex([2, 0, 1]))
print(cities) | 40.821429 | 130 | 0.750656 |
e07ee60ec4a6fab177a6c8363ef9dc2508bf69c5 | 91 | py | Python | src/helloworld/__main__.py | paulproteus/briefcase-toga-button-app-with-hacks | 61ec41b154204bb4a7a59f55374193dd4f9ca377 | [
"BSD-3-Clause"
] | 2 | 2020-05-01T23:41:55.000Z | 2020-07-01T00:26:19.000Z | src/helloworld/__main__.py | paulproteus/briefcase-toga-button-app-with-hacks | 61ec41b154204bb4a7a59f55374193dd4f9ca377 | [
"BSD-3-Clause"
] | null | null | null | src/helloworld/__main__.py | paulproteus/briefcase-toga-button-app-with-hacks | 61ec41b154204bb4a7a59f55374193dd4f9ca377 | [
"BSD-3-Clause"
] | null | null | null | from helloworld.app import main
if True or __name__ == '__main__':
main().main_loop()
| 18.2 | 34 | 0.703297 |
e081143f3b7d183dce44c075a5350bb5aba51e51 | 797 | py | Python | backend/app/main.py | ianahart/blog | fc52e15a8b56bd4c6482065de7e21f8b31f5d765 | [
"MIT"
] | null | null | null | backend/app/main.py | ianahart/blog | fc52e15a8b56bd4c6482065de7e21f8b31f5d765 | [
"MIT"
] | null | null | null | backend/app/main.py | ianahart/blog | fc52e15a8b56bd4c6482065de7e21f8b31f5d765 | [
"MIT"
] | null | null | null | from fastapi import FastAPI
from dotenv import load_dotenv
from fastapi.middleware.cors import CORSMiddleware
from app.api.api_v1.api import api_router
from app.core.config import settings
app = FastAPI()
load_dotenv()
app.include_router(api_router, prefix=settings.API_V1_STR)
# Set all CORS enabled origins
if settings.BACKEND_CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=[str(origin)
for origin in settings.BACKEND_CORS_ORIGINS],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
if __name__ == "__main__":
# Use this for debugging purposes only
# pyright: reportGeneralTypeIssues=false
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8001, log_level="debug")
| 27.482759 | 68 | 0.711418 |
e083bd5dc380bfdfeec4ef47f0529d4de1bded9d | 658 | py | Python | test_data/samples/alembic_template_output.py | goldstar611/ssort | 05c35ec89dd9ff391ae824c17ed974340e2f5597 | [
"MIT"
] | 238 | 2021-04-25T11:45:54.000Z | 2022-03-30T10:49:58.000Z | test_data/samples/alembic_template_output.py | goldstar611/ssort | 05c35ec89dd9ff391ae824c17ed974340e2f5597 | [
"MIT"
] | 54 | 2021-03-29T21:40:00.000Z | 2022-03-29T20:26:31.000Z | test_data/samples/alembic_template_output.py | goldstar611/ssort | 05c35ec89dd9ff391ae824c17ed974340e2f5597 | [
"MIT"
] | 4 | 2022-02-09T02:37:11.000Z | 2022-02-23T03:07:50.000Z | """Example revision
Revision ID: fdf0cf6487a3
Revises:
Create Date: 2021-08-09 17:55:19.491713
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "fdf0cf6487a3"
down_revision = None
branch_labels = None
depends_on = None
| 20.5625 | 65 | 0.668693 |
e085ecf717371ed12e23c9cc1a56cd7685b27bf6 | 790 | py | Python | .archived/snakecode/0173.py | gearbird/calgo | ab48357100de2a5ea47fda2d9f01ced6dc73fa79 | [
"MIT"
] | 4 | 2022-01-13T03:39:01.000Z | 2022-03-15T03:16:33.000Z | .archived/snakecode/0173.py | gearbird/calgo | ab48357100de2a5ea47fda2d9f01ced6dc73fa79 | [
"MIT"
] | null | null | null | .archived/snakecode/0173.py | gearbird/calgo | ab48357100de2a5ea47fda2d9f01ced6dc73fa79 | [
"MIT"
] | 1 | 2021-12-09T12:33:07.000Z | 2021-12-09T12:33:07.000Z | from __future__ import annotations
from typing import Optional
# Definition for a binary tree node.
| 27.241379 | 104 | 0.606329 |
e086489d041ecf108f68b331e71375202940ac34 | 2,768 | py | Python | .leetcode/506.relative-ranks.py | KuiyuanFu/PythonLeetCode | 8962df2fa838eb7ae48fa59de272ba55a89756d8 | [
"MIT"
] | null | null | null | .leetcode/506.relative-ranks.py | KuiyuanFu/PythonLeetCode | 8962df2fa838eb7ae48fa59de272ba55a89756d8 | [
"MIT"
] | null | null | null | .leetcode/506.relative-ranks.py | KuiyuanFu/PythonLeetCode | 8962df2fa838eb7ae48fa59de272ba55a89756d8 | [
"MIT"
] | null | null | null | # @lc app=leetcode id=506 lang=python3
#
# [506] Relative Ranks
#
# https://leetcode.com/problems/relative-ranks/description/
#
# algorithms
# Easy (53.46%)
# Likes: 188
# Dislikes: 9
# Total Accepted: 71.1K
# Total Submissions: 132.4K
# Testcase Example: '[5,4,3,2,1]'
#
# You are given an integer array score of size n, where score[i] is the score
# of the i^th athlete in a competition. All the scores are guaranteed to be
# unique.
#
# The athletes are placed based on their scores, where the 1^st place athlete
# has the highest score, the 2^nd place athlete has the 2^nd highest score, and
# so on. The placement of each athlete determines their rank:
#
#
# The 1^st place athlete's rank is "Gold Medal".
# The 2^nd place athlete's rank is "Silver Medal".
# The 3^rd place athlete's rank is "Bronze Medal".
# For the 4^th place to the n^th place athlete, their rank is their placement
# number (i.e., the x^th place athlete's rank is "x").
#
#
# Return an array answer of size n where answer[i] is the rank of the i^th
# athlete.
#
#
# Example 1:
#
#
# Input: score = [5,4,3,2,1]
# Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"]
# Explanation: The placements are [1^st, 2^nd, 3^rd, 4^th, 5^th].
#
# Example 2:
#
#
# Input: score = [10,3,8,9,4]
# Output: ["Gold Medal","5","Bronze Medal","Silver Medal","4"]
# Explanation: The placements are [1^st, 5^th, 3^rd, 2^nd, 4^th].
#
#
#
#
# Constraints:
#
#
# n == score.length
# 1 <= n <= 10^4
# 0 <= score[i] <= 10^6
# All the values in score are unique.
#
#
#
# @lc tags=Unknown
# @lc imports=start
from imports import *
# @lc imports=end
# @lc idea=start
#
#
#
# @lc idea=end
# @lc group=
# @lc rank=
# @lc code=start
# @lc code=end
# @lc main=start
if __name__ == '__main__':
print('Example 1:')
print('Input : ')
print('score = [5,4,3,2,1]')
print('Exception :')
print('["Gold Medal","Silver Medal","Bronze Medal","4","5"]')
print('Output :')
print(str(Solution().findRelativeRanks([5, 4, 3, 2, 1])))
print()
print('Example 2:')
print('Input : ')
print('score = [10,3,8,9,4]')
print('Exception :')
print('["Gold Medal","5","Bronze Medal","Silver Medal","4"]')
print('Output :')
print(str(Solution().findRelativeRanks([10, 3, 8, 9, 4])))
print()
pass
# @lc main=end | 22.322581 | 79 | 0.600795 |
e08673d5cfeabd8f8dd35fbf0c18643dc03a42fd | 1,933 | py | Python | test/msan/lit.cfg.py | QuarkTheAwesome/compiler-rt-be-aeabi | 79e7d2bd981b0f38d60d90f8382c6cd5389b95d0 | [
"Apache-2.0"
] | 118 | 2016-02-29T01:55:45.000Z | 2021-11-08T09:47:46.000Z | test/msan/lit.cfg.py | QuarkTheAwesome/compiler-rt-be-aeabi | 79e7d2bd981b0f38d60d90f8382c6cd5389b95d0 | [
"Apache-2.0"
] | 27 | 2016-06-20T23:47:01.000Z | 2019-10-25T17:41:37.000Z | test/msan/lit.cfg.py | QuarkTheAwesome/compiler-rt-be-aeabi | 79e7d2bd981b0f38d60d90f8382c6cd5389b95d0 | [
"Apache-2.0"
] | 73 | 2016-03-01T00:50:56.000Z | 2021-12-05T03:30:35.000Z | # -*- Python -*-
import os
# Setup config name.
config.name = 'MemorySanitizer' + getattr(config, 'name_suffix', 'default')
# Setup source root.
config.test_source_root = os.path.dirname(__file__)
# Setup default compiler flags used with -fsanitize=memory option.
clang_msan_cflags = (["-fsanitize=memory",
"-mno-omit-leaf-frame-pointer",
"-fno-omit-frame-pointer",
"-fno-optimize-sibling-calls"] +
[config.target_cflags] +
config.debug_info_flags)
# Some Msan tests leverage backtrace() which requires libexecinfo on FreeBSD.
if config.host_os == 'FreeBSD':
clang_msan_cflags += ["-lexecinfo", "-fPIC"]
clang_msan_cxxflags = config.cxx_mode_flags + clang_msan_cflags
# Flags for KMSAN invocation. This is C-only, we're not interested in C++.
clang_kmsan_cflags = (["-fsanitize=kernel-memory"] +
[config.target_cflags] +
config.debug_info_flags)
config.substitutions.append( ("%clang_msan ", build_invocation(clang_msan_cflags)) )
config.substitutions.append( ("%clangxx_msan ", build_invocation(clang_msan_cxxflags)) )
config.substitutions.append( ("%clang_kmsan ", build_invocation(clang_kmsan_cflags)) )
# Default test suffixes.
config.suffixes = ['.c', '.cc', '.cpp']
if config.host_os not in ['Linux', 'NetBSD', 'FreeBSD']:
config.unsupported = True
# For mips64, mips64el we have forced store_context_size to 1 because these
# archs use slow unwinder which is not async signal safe. Therefore we only
# check the first frame since store_context size is 1.
if config.host_arch in ['mips64', 'mips64el']:
config.substitutions.append( ('CHECK-%short-stack', 'CHECK-SHORT-STACK'))
else:
config.substitutions.append( ('CHECK-%short-stack', 'CHECK-FULL-STACK'))
| 40.270833 | 88 | 0.685463 |
e086d33095f9872583586fa709b215338a8bb617 | 8,084 | py | Python | application/core/migrations/0001_initial.py | victor-freitas/ProjetoNCS | 7c80fad11e49f4ed00eefb90638730d340d78e1f | [
"Apache-2.0"
] | null | null | null | application/core/migrations/0001_initial.py | victor-freitas/ProjetoNCS | 7c80fad11e49f4ed00eefb90638730d340d78e1f | [
"Apache-2.0"
] | 2 | 2020-06-05T18:58:17.000Z | 2021-06-10T20:50:12.000Z | application/core/migrations/0001_initial.py | victor-freitas/ProjetoNCS | 7c80fad11e49f4ed00eefb90638730d340d78e1f | [
"Apache-2.0"
] | 1 | 2018-09-17T18:14:18.000Z | 2018-09-17T18:14:18.000Z | # Generated by Django 2.0.6 on 2018-06-17 04:47
from django.db import migrations, models
| 44.662983 | 120 | 0.530678 |
e087918e3b0a051f5fa5fa67e1527b89fc1bd61b | 9,606 | py | Python | dataschema/entity.py | vingkan/sql_tools | 5d6ab6a0ae31dc51e51ac1629f83f7bbf91396c1 | [
"Apache-2.0"
] | 1 | 2022-03-30T19:47:16.000Z | 2022-03-30T19:47:16.000Z | dataschema/entity.py | vingkan/sql_tools | 5d6ab6a0ae31dc51e51ac1629f83f7bbf91396c1 | [
"Apache-2.0"
] | null | null | null | dataschema/entity.py | vingkan/sql_tools | 5d6ab6a0ae31dc51e51ac1629f83f7bbf91396c1 | [
"Apache-2.0"
] | 1 | 2022-03-30T04:07:12.000Z | 2022-03-30T04:07:12.000Z | #
# nuna_sql_tools: Copyright 2022 Nuna Inc
#
# 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.
#
"""Utilityes for checking and."""
import dataclasses
import datetime
import decimal
from types import ModuleType
from typing import NewType, Union
# In your data declaration python modules define a JAVA_PACKAGE
# variable at top level to specify the corresponding Java package of generated
# classes.
JAVA_PACKAGE = 'JAVA_PACKAGE'
_SCHEMA_ANNOTATIONS = '__schema_annotations__'
_EXPECTED_DICT_KEYS = set([
'__module__', '__annotations__', '__doc__', '__dict__', '__weakref__',
'__dataclass_params__', '__dataclass_fields__', _SCHEMA_ANNOTATIONS
])
_EXPECTED_FUNCTIONS = ['__init__', '__repr__', '__eq__', '__hash__']
_BASE_TYPES = set([
int, bytes, str, float, bool, datetime.date, datetime.datetime,
decimal.Decimal
])
_SCHEMA_ANNOTATIONS = '__schema_annotations__'
_CLASS_ID = 0
def _Annotate(cls=None, annotation=None):
"""Annotates a class or a type. `annotation` should from annotation.py"""
if cls is None:
return Wrap
return Wrap(cls)
def Annotate(cls, annotation):
"""Annotates a field type with the provided annotation."""
return _Annotate(cls, annotation=annotation)
def IsAnnotatedType(field_cls: type):
"""If provided field_cls is an annotated type."""
return hasattr(field_cls, _SCHEMA_ANNOTATIONS)
def GetAnnotatedType(field_cls: type):
"""Returns the original type behind the annotation (if any)."""
if IsAnnotatedType(field_cls) and hasattr(field_cls, '__supertype__'):
return field_cls.__supertype__
return field_cls
def IsOptionalType(field_cls: type):
"""If the field_cls looks like an Optional[...] type."""
return (hasattr(field_cls, '__origin__')
# pylint: disable=comparison-with-callable
and field_cls.__origin__ == Union and len(field_cls.__args__) == 2
and field_cls.__args__[1] == type(None))
def GetOptionalType(field_cls: type):
"""Returns the type of optional & annotation or None if not optional."""
field_cls = GetAnnotatedType(field_cls)
if IsOptionalType(field_cls):
return field_cls.__args__[0]
return None
def GetOriginalType(field_cls: type):
"""Returns the type of field_cls, behind annotations and Optional."""
field_cls = GetAnnotatedType(field_cls)
if IsOptionalType(field_cls):
return field_cls.__args__[0]
return field_cls
def GetStructuredTypeName(field_cls: type):
"""Returns the structure type name for a type, behind annotation."""
field_cls = GetAnnotatedType(field_cls)
if not hasattr(field_cls, '__origin__'):
return None
if field_cls.__origin__ is dict:
return 'dict'
elif field_cls.__origin__ is list:
return 'list'
elif field_cls.__origin__ is set:
return 'set'
return None
def IsBasicType(field_cls: type):
"""If the type field_cls looks like one of the basic field types."""
if GetAnnotatedType(field_cls) in _BASE_TYPES:
return True
_MAX_DEPTH = 30
def SchemaAnnotations(cls: type):
"""Returns the schema annotations of a type."""
annotations = []
if hasattr(cls, _SCHEMA_ANNOTATIONS):
annotations.extend(cls.__schema_annotations__)
return annotations
| 36.249057 | 80 | 0.636581 |
e087f1cb73d38e79a6d1863be5eb904e7f3b6261 | 1,541 | py | Python | Data_and_Dicts.py | melkisedeath/Harmonic_Analysis_and_Trajectory | a5a2819c053ddd287dcb668fac2f1be7e44f6c59 | [
"MIT"
] | null | null | null | Data_and_Dicts.py | melkisedeath/Harmonic_Analysis_and_Trajectory | a5a2819c053ddd287dcb668fac2f1be7e44f6c59 | [
"MIT"
] | null | null | null | Data_and_Dicts.py | melkisedeath/Harmonic_Analysis_and_Trajectory | a5a2819c053ddd287dcb668fac2f1be7e44f6c59 | [
"MIT"
] | null | null | null | """HERE are the base Points for all valid Tonnetze Systems.
A period of all 12 notes divided by mod 3, mod 4 (always stable)
"""
# x = 4, y = 3
NotePointsT345 = {
0: (0, 0),
1: (1, 3),
2: (2, 2),
3: (0, 1),
4: (1, 0),
5: (2, 3),
6: (0, 2),
7: (1, 1),
8: (2, 0),
9: (0, 3),
10: (1, 2),
11: (2, 1)
}
# x = 8, y = 3
NotePointsT138 = {
0: (0, 0),
1: (2, 3),
2: (1, 2),
3: (0, 1),
4: (2, 0),
5: (1, 3),
6: (0, 2),
7: (2, 1),
8: (1, 0),
9: (0, 3),
10: (2, 2),
11: (1, 1)
}
# x = 2, y = 9
NotePointsT129 = {
0: (0, 0),
1: (2, 1),
2: (1, 0),
3: (0, 3),
4: (2, 0),
5: (1, 3),
6: (0, 2),
7: (2, 3),
8: (1, 2),
9: (0, 1),
10: (2, 2),
11: (1, 1)
}
# x = 4, y = 1
NotePointsT147 = {
0: (0, 0),
1: (0, 1),
2: (0, 2),
3: (0, 3),
4: (1, 0),
5: (1, 1),
6: (1, 2),
7: (1, 3),
8: (2, 0),
9: (2, 1),
10: (2, 2),
11: (2, 3)
}
# x = 2, y = 3
NotePointsT237 = {
0: (0, 0),
1: (2, 3),
2: (1, 0),
3: (0, 1),
4: (2, 0),
5: (1, 1),
6: (0, 2),
7: (2, 1),
8: (1, 2),
9: (0, 3),
10: (2, 2),
11: (1, 3)
}
dictOfTonnetz = {
'T345': NotePointsT345,
'T147': NotePointsT147,
'T138': NotePointsT138,
'T237': NotePointsT237,
'T129': NotePointsT129
}
dictOfTonnetze = {
'T129': [1, 2, 9],
'T138': [1, 3, 8],
'T147': [1, 4, 7],
'T156': [1, 5, 6],
'T237': [2, 3, 7],
'T345': [3, 4, 5]
}
| 14.817308 | 64 | 0.345879 |
e088029d2dd84f5afa6eb4738d0ecbd65b7b7d99 | 3,718 | py | Python | awacs/proton.py | alanjjenkins/awacs | 0065e1833eae6a6070edb4ab4f180fd10b26c19a | [
"BSD-2-Clause"
] | null | null | null | awacs/proton.py | alanjjenkins/awacs | 0065e1833eae6a6070edb4ab4f180fd10b26c19a | [
"BSD-2-Clause"
] | null | null | null | awacs/proton.py | alanjjenkins/awacs | 0065e1833eae6a6070edb4ab4f180fd10b26c19a | [
"BSD-2-Clause"
] | null | null | null | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "AWS Proton"
prefix = "proton"
CreateEnvironment = Action("CreateEnvironment")
CreateEnvironmentTemplate = Action("CreateEnvironmentTemplate")
CreateEnvironmentTemplateMajorVersion = Action("CreateEnvironmentTemplateMajorVersion")
CreateEnvironmentTemplateMinorVersion = Action("CreateEnvironmentTemplateMinorVersion")
CreateService = Action("CreateService")
CreateServiceTemplate = Action("CreateServiceTemplate")
CreateServiceTemplateMajorVersion = Action("CreateServiceTemplateMajorVersion")
CreateServiceTemplateMinorVersion = Action("CreateServiceTemplateMinorVersion")
DeleteAccountRoles = Action("DeleteAccountRoles")
DeleteEnvironment = Action("DeleteEnvironment")
DeleteEnvironmentTemplate = Action("DeleteEnvironmentTemplate")
DeleteEnvironmentTemplateMajorVersion = Action("DeleteEnvironmentTemplateMajorVersion")
DeleteEnvironmentTemplateMinorVersion = Action("DeleteEnvironmentTemplateMinorVersion")
DeleteService = Action("DeleteService")
DeleteServiceTemplate = Action("DeleteServiceTemplate")
DeleteServiceTemplateMajorVersion = Action("DeleteServiceTemplateMajorVersion")
DeleteServiceTemplateMinorVersion = Action("DeleteServiceTemplateMinorVersion")
GetAccountRoles = Action("GetAccountRoles")
GetEnvironment = Action("GetEnvironment")
GetEnvironmentTemplate = Action("GetEnvironmentTemplate")
GetEnvironmentTemplateMajorVersion = Action("GetEnvironmentTemplateMajorVersion")
GetEnvironmentTemplateMinorVersion = Action("GetEnvironmentTemplateMinorVersion")
GetService = Action("GetService")
GetServiceInstance = Action("GetServiceInstance")
GetServiceTemplate = Action("GetServiceTemplate")
GetServiceTemplateMajorVersion = Action("GetServiceTemplateMajorVersion")
GetServiceTemplateMinorVersion = Action("GetServiceTemplateMinorVersion")
ListEnvironmentTemplateMajorVersions = Action("ListEnvironmentTemplateMajorVersions")
ListEnvironmentTemplateMinorVersions = Action("ListEnvironmentTemplateMinorVersions")
ListEnvironmentTemplates = Action("ListEnvironmentTemplates")
ListEnvironments = Action("ListEnvironments")
ListServiceInstances = Action("ListServiceInstances")
ListServiceTemplateMajorVersions = Action("ListServiceTemplateMajorVersions")
ListServiceTemplateMinorVersions = Action("ListServiceTemplateMinorVersions")
ListServiceTemplates = Action("ListServiceTemplates")
ListServices = Action("ListServices")
ListTagsForResource = Action("ListTagsForResource")
TagResource = Action("TagResource")
UntagResource = Action("UntagResource")
UpdateAccountRoles = Action("UpdateAccountRoles")
UpdateEnvironment = Action("UpdateEnvironment")
UpdateEnvironmentTemplate = Action("UpdateEnvironmentTemplate")
UpdateEnvironmentTemplateMajorVersion = Action("UpdateEnvironmentTemplateMajorVersion")
UpdateEnvironmentTemplateMinorVersion = Action("UpdateEnvironmentTemplateMinorVersion")
UpdateService = Action("UpdateService")
UpdateServiceInstance = Action("UpdateServiceInstance")
UpdateServicePipeline = Action("UpdateServicePipeline")
UpdateServiceTemplate = Action("UpdateServiceTemplate")
UpdateServiceTemplateMajorVersion = Action("UpdateServiceTemplateMajorVersion")
UpdateServiceTemplateMinorVersion = Action("UpdateServiceTemplateMinorVersion")
| 49.573333 | 88 | 0.839161 |
e089b61952e1f4d0f2fb6443737c623fe7ff04be | 10,577 | py | Python | jaxline/utils_test.py | lorenrose1013/jaxline | 29fca9944651d42139d4103fe12ef29b24812eb6 | [
"Apache-2.0"
] | 1 | 2022-01-07T02:44:07.000Z | 2022-01-07T02:44:07.000Z | jaxline/utils_test.py | SuperXiang/jaxline | f1503f6a06d46aa9eb2eab8eed6130895148ffa2 | [
"Apache-2.0"
] | null | null | null | jaxline/utils_test.py | SuperXiang/jaxline | f1503f6a06d46aa9eb2eab8eed6130895148ffa2 | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 DeepMind Technologies Limited. 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.
# ==============================================================================
"""Tests for jaxline's utils."""
import functools
import itertools as it
import time
from unittest import mock
from absl.testing import absltest
from absl.testing import flagsaver
import jax
import jax.numpy as jnp
from jaxline import utils
import numpy as np
if __name__ == "__main__":
absltest.main()
| 32.345566 | 80 | 0.681573 |
e08bf2bd2a9a71b40e56dae49102323a555d5695 | 3,664 | py | Python | test/unit/mysql_class/slaverep_isslverror.py | deepcoder42/mysql-lib | d3d2459e0476fdbc4465e1d9389612e58d36fb25 | [
"MIT"
] | 1 | 2022-03-23T04:53:19.000Z | 2022-03-23T04:53:19.000Z | test/unit/mysql_class/slaverep_isslverror.py | deepcoder42/mysql-lib | d3d2459e0476fdbc4465e1d9389612e58d36fb25 | [
"MIT"
] | null | null | null | test/unit/mysql_class/slaverep_isslverror.py | deepcoder42/mysql-lib | d3d2459e0476fdbc4465e1d9389612e58d36fb25 | [
"MIT"
] | null | null | null | #!/usr/bin/python
# Classification (U)
"""Program: slaverep_isslverror.py
Description: Unit testing of SlaveRep.is_slv_error in mysql_class.py.
Usage:
test/unit/mysql_class/slaverep_isslverror.py
Arguments:
"""
# Libraries and Global Variables
# Standard
import sys
import os
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
# Third-party
# Local
sys.path.append(os.getcwd())
import mysql_class
import lib.machine as machine
import version
__version__ = version.__version__
if __name__ == "__main__":
unittest.main()
| 24.264901 | 74 | 0.570142 |
e08cc87c4cfc35f91dfef4447a5dc8af61c7fede | 545 | py | Python | problems/108.py | mengshun/Leetcode | 8bb676f2fff093e1417a4bed13d9ad708149be78 | [
"MIT"
] | null | null | null | problems/108.py | mengshun/Leetcode | 8bb676f2fff093e1417a4bed13d9ad708149be78 | [
"MIT"
] | null | null | null | problems/108.py | mengshun/Leetcode | 8bb676f2fff093e1417a4bed13d9ad708149be78 | [
"MIT"
] | null | null | null | """
108.
"""
from TreeNode import TreeNode
t = [-10,-3,0,5,9]
obj = Solution()
node = obj.sortedArrayToBST(t)
node.preorderTraversal()
| 18.793103 | 56 | 0.543119 |
e08cf0fb5bb3a579c0b07a1fe1738a0670a18bc7 | 10,230 | py | Python | src/sage/tests/books/computational-mathematics-with-sagemath/domaines_doctest.py | hsm207/sage | 020bd59ec28717bfab9af44d2231c53da1ff99f1 | [
"BSL-1.0"
] | 1,742 | 2015-01-04T07:06:13.000Z | 2022-03-30T11:32:52.000Z | src/sage/tests/books/computational-mathematics-with-sagemath/domaines_doctest.py | hsm207/sage | 020bd59ec28717bfab9af44d2231c53da1ff99f1 | [
"BSL-1.0"
] | 66 | 2015-03-19T19:17:24.000Z | 2022-03-16T11:59:30.000Z | src/sage/tests/books/computational-mathematics-with-sagemath/domaines_doctest.py | hsm207/sage | 020bd59ec28717bfab9af44d2231c53da1ff99f1 | [
"BSL-1.0"
] | 495 | 2015-01-10T10:23:18.000Z | 2022-03-24T22:06:11.000Z | ## -*- encoding: utf-8 -*-
"""
This file (./domaines_doctest.sage) was *autogenerated* from ./domaines.tex,
with sagetex.sty version 2011/05/27 v2.3.1.
It contains the contents of all the sageexample environments from this file.
You should be able to doctest this file with:
sage -t ./domaines_doctest.sage
It is always safe to delete this file; it is not used in typesetting your
document.
Sage example in ./domaines.tex, line 10::
sage: x = var('x')
Sage example in ./domaines.tex, line 69::
sage: o = 12/35
sage: type(o)
<... 'sage.rings.rational.Rational'>
Sage example in ./domaines.tex, line 82::
sage: type(12/35)
<... 'sage.rings.rational.Rational'>
Sage example in ./domaines.tex, line 131::
sage: o = 720
sage: o.factor()
2^4 * 3^2 * 5
Sage example in ./domaines.tex, line 142::
sage: type(o).factor(o)
2^4 * 3^2 * 5
Sage example in ./domaines.tex, line 157::
sage: 720.factor()
2^4 * 3^2 * 5
Sage example in ./domaines.tex, line 166::
sage: o = 720 / 133
sage: o.numerator().factor()
2^4 * 3^2 * 5
Sage example in ./domaines.tex, line 253::
sage: 3 * 7
21
Sage example in ./domaines.tex, line 261::
sage: (2/3) * (6/5)
4/5
Sage example in ./domaines.tex, line 267::
sage: (1 + I) * (1 - I)
2
Sage example in ./domaines.tex, line 274::
sage: (x + 2) * (x + 1)
(x + 2)*(x + 1)
sage: (x + 1) * (x + 2)
(x + 2)*(x + 1)
Sage example in ./domaines.tex, line 308::
sage: def fourth_power(a):
....: a = a * a
....: a = a * a
....: return a
Sage example in ./domaines.tex, line 330::
sage: fourth_power(2)
16
sage: fourth_power(3/2)
81/16
sage: fourth_power(I)
1
sage: fourth_power(x+1)
(x + 1)^4
sage: M = matrix([[0,-1],[1,0]]); M
[ 0 -1]
[ 1 0]
sage: fourth_power(M)
[1 0]
[0 1]
Sage example in ./domaines.tex, line 375::
sage: t = type(5/1); t
<... 'sage.rings.rational.Rational'>
sage: t == type(5)
False
Sage example in ./domaines.tex, line 476::
sage: a = 5; a
5
sage: a.is_unit()
False
Sage example in ./domaines.tex, line 484::
sage: a = 5/1; a
5
sage: a.is_unit()
True
Sage example in ./domaines.tex, line 507::
sage: parent(5)
Integer Ring
sage: parent(5/1)
Rational Field
Sage example in ./domaines.tex, line 515::
sage: ZZ
Integer Ring
sage: QQ
Rational Field
Sage example in ./domaines.tex, line 525::
sage: QQ(5).parent()
Rational Field
sage: ZZ(5/1).parent()
Integer Ring
sage: ZZ(1/5)
Traceback (most recent call last):
...
TypeError: no conversion of this rational to integer
Sage example in ./domaines.tex, line 543::
sage: ZZ(1), QQ(1), RR(1), CC(1)
(1, 1, 1.00000000000000, 1.00000000000000)
Sage example in ./domaines.tex, line 568::
sage: cartesian_product([QQ, QQ])
The Cartesian product of (Rational Field, Rational Field)
Sage example in ./domaines.tex, line 574::
sage: ZZ.fraction_field()
Rational Field
Sage example in ./domaines.tex, line 580::
sage: ZZ['x']
Univariate Polynomial Ring in x over Integer Ring
Sage example in ./domaines.tex, line 591::
sage: Z5 = GF(5); Z5
Finite Field of size 5
sage: P = Z5['x']; P
Univariate Polynomial Ring in x over Finite Field of size 5
sage: M = MatrixSpace(P, 3, 3); M
Full MatrixSpace of 3 by 3 dense matrices over
Univariate Polynomial Ring in x over Finite Field of size 5
Sage example in ./domaines.tex, line 602::
sage: M.random_element() # random
[2*x^2 + 3*x + 4 4*x^2 + 2*x + 2 4*x^2 + 2*x]
[ 3*x 2*x^2 + x + 3 3*x^2 + 4*x]
[ 4*x^2 + 3 3*x^2 + 2*x + 4 2*x + 4]
Sage example in ./domaines.tex, line 697::
sage: QQ.category()
Join of Category of number fields and Category of quotient fields and Category of metric spaces
Sage example in ./domaines.tex, line 704::
sage: QQ in Fields()
True
Sage example in ./domaines.tex, line 712::
sage: QQ in CommutativeAdditiveGroups()
True
Sage example in ./domaines.tex, line 718::
sage: QQ['x'] in EuclideanDomains()
True
Sage example in ./domaines.tex, line 859::
sage: 5.parent()
Integer Ring
Sage example in ./domaines.tex, line 872::
sage: type(factor(4))
<class 'sage.structure.factorization_integer.IntegerFactorization'>
Sage example in ./domaines.tex, line 895::
sage: int(5)
5
sage: type(int(5))
<... 'int'>
Sage example in ./domaines.tex, line 909::
sage: Integer(5)
5
sage: type(Integer(5))
<... 'sage.rings.integer.Integer'>
Sage example in ./domaines.tex, line 926::
sage: factorial(99) / factorial(100) - 1 / 50
-1/100
Sage example in ./domaines.tex, line 974::
sage: 72/53 - 5/3 * 2.7
-3.14150943396227
Sage example in ./domaines.tex, line 982::
sage: cos(1), cos(1.)
(cos(1), 0.540302305868140)
Sage example in ./domaines.tex, line 1000::
sage: pi.n(digits=50) # variant: n(pi,digits=50)
3.1415926535897932384626433832795028841971693993751
Sage example in ./domaines.tex, line 1020::
sage: z = CC(1,2); z.arg()
1.10714871779409
Sage example in ./domaines.tex, line 1036::
sage: I.parent()
Number Field in I with defining polynomial x^2 + 1 with I = 1*I
Sage example in ./domaines.tex, line 1043::
sage: (1.+2.*I).parent()
Complex Field with 53 bits of precision
sage: (1.+2.*SR(I)).parent()
Symbolic Ring
Sage example in ./domaines.tex, line 1064::
sage: z = 3 * exp(I*pi/4)
sage: z.real(), z.imag(), z.abs().canonicalize_radical()
(3/2*sqrt(2), 3/2*sqrt(2), 3)
Sage example in ./domaines.tex, line 1094::
sage: a, b, c = 0, 2, 3
sage: a == 1 or (b == 2 and c == 3)
True
Sage example in ./domaines.tex, line 1147::
sage: x, y = var('x, y')
sage: bool( (x-y)*(x+y) == x^2-y^2 )
True
Sage example in ./domaines.tex, line 1171::
sage: Z4 = IntegerModRing(4); Z4
Ring of integers modulo 4
sage: m = Z4(7); m
3
Sage example in ./domaines.tex, line 1184::
sage: 3 * m + 1
2
Sage example in ./domaines.tex, line 1191::
sage: Z3 = GF(3); Z3
Finite Field of size 3
Sage example in ./domaines.tex, line 1243::
sage: a = matrix(QQ, [[1,2,3],[2,4,8],[3,9,27]])
sage: (a^2 + 1) * a^(-1)
[ -5 13/2 7/3]
[ 7 1 25/3]
[ 2 19/2 27]
Sage example in ./domaines.tex, line 1259::
sage: M = MatrixSpace(QQ,3,3); M
Full MatrixSpace of 3 by 3 dense matrices over Rational Field
sage: a = M([[1,2,3],[2,4,8],[3,9,27]])
sage: (a^2 + 1) * a^(-1)
[ -5 13/2 7/3]
[ 7 1 25/3]
[ 2 19/2 27]
Sage example in ./domaines.tex, line 1283::
sage: P = ZZ['x']; P
Univariate Polynomial Ring in x over Integer Ring
sage: F = P.fraction_field(); F
Fraction Field of Univariate Polynomial Ring in x over Integer Ring
sage: p = P(x+1) * P(x); p
x^2 + x
sage: p + 1/p
(x^4 + 2*x^3 + x^2 + 1)/(x^2 + x)
sage: parent(p + 1/p)
Fraction Field of Univariate Polynomial Ring in x over Integer Ring
Sage example in ./domaines.tex, line 1382::
sage: k.<a> = NumberField(x^3 + x + 1); a^3; a^4+3*a
-a - 1
-a^2 + 2*a
Sage example in ./domaines.tex, line 1416::
sage: parent(sin(x))
Symbolic Ring
Sage example in ./domaines.tex, line 1422::
sage: SR
Symbolic Ring
Sage example in ./domaines.tex, line 1428::
sage: SR.category()
Category of fields
Sage example in ./domaines.tex, line 1482::
sage: R = QQ['x1,x2,x3,x4']; R
Multivariate Polynomial Ring in x1, x2, x3, x4 over Rational Field
sage: x1, x2, x3, x4 = R.gens()
Sage example in ./domaines.tex, line 1489::
sage: x1 * (x2 - x3)
x1*x2 - x1*x3
Sage example in ./domaines.tex, line 1496::
sage: (x1+x2)*(x1-x2) - (x1^2 - x2^2)
0
Sage example in ./domaines.tex, line 1509::
sage: P = prod( (a-b) for (a,b) in Subsets([x1,x2,x3,x4],2) ); P * P.lc()
x1^3*x2^2*x3 - x1^2*x2^3*x3 - x1^3*x2*x3^2 + x1*x2^3*x3^2
+ x1^2*x2*x3^3 - x1*x2^2*x3^3 - x1^3*x2^2*x4 + x1^2*x2^3*x4
+ x1^3*x3^2*x4 - x2^3*x3^2*x4 - x1^2*x3^3*x4 + x2^2*x3^3*x4
+ x1^3*x2*x4^2 - x1*x2^3*x4^2 - x1^3*x3*x4^2 + x2^3*x3*x4^2
+ x1*x3^3*x4^2 - x2*x3^3*x4^2 - x1^2*x2*x4^3 + x1*x2^2*x4^3
+ x1^2*x3*x4^3 - x2^2*x3*x4^3 - x1*x3^2*x4^3 + x2*x3^2*x4^3
Sage example in ./domaines.tex, line 1531::
sage: x1, x2, x3, x4 = SR.var('x1, x2, x3, x4')
sage: got = prod( (a-b) for (a,b) in Subsets([x1,x2,x3,x4],2) )
sage: expected1 = -(x1 - x2)*(x1 - x3)*(x1 - x4)*(x2 - x3)*(x2 - x4)*(x3 - x4)
sage: expected2 = (x1 - x2)*(x1 - x3)*(x1 - x4)*(x2 - x3)*(x2 - x4)*(x3 - x4)
sage: bool(got == expected1 or got == expected2)
True
Sage example in ./domaines.tex, line 1581::
sage: x = var('x')
sage: p = 54*x^4+36*x^3-102*x^2-72*x-12
sage: factor(p)
6*(x^2 - 2)*(3*x + 1)^2
Sage example in ./domaines.tex, line 1616::
sage: R = ZZ['x']; R
Univariate Polynomial Ring in x over Integer Ring
Sage example in ./domaines.tex, line 1622::
sage: q = R(p); q
54*x^4 + 36*x^3 - 102*x^2 - 72*x - 12
Sage example in ./domaines.tex, line 1629::
sage: parent(q)
Univariate Polynomial Ring in x over Integer Ring
Sage example in ./domaines.tex, line 1635::
sage: factor(q)
2 * 3 * (3*x + 1)^2 * (x^2 - 2)
Sage example in ./domaines.tex, line 1642::
sage: R = QQ['x']; R
Univariate Polynomial Ring in x over Rational Field
sage: q = R(p); q
54*x^4 + 36*x^3 - 102*x^2 - 72*x - 12
sage: factor(q)
(54) * (x + 1/3)^2 * (x^2 - 2)
Sage example in ./domaines.tex, line 1665::
sage: R = ComplexField(16)['x']; R
Univariate Polynomial Ring in x over Complex Field
with 16 bits of precision
sage: q = R(p); q
54.00*x^4 + 36.00*x^3 - 102.0*x^2 - 72.00*x - 12.00
sage: factor(q)
(54.00) * (x - 1.414) * (x + 0.3333)^2 * (x + 1.414)
Sage example in ./domaines.tex, line 1685::
sage: R = QQ[sqrt(2)]['x']; R
Univariate Polynomial Ring in x over Number Field in sqrt2 with defining polynomial x^2 - 2 with sqrt2 = 1.414213562373095?
sage: q = R(p); q
54*x^4 + 36*x^3 - 102*x^2 - 72*x - 12
sage: factor(q)
(54) * (x - sqrt2) * (x + sqrt2) * (x + 1/3)^2
Sage example in ./domaines.tex, line 1698::
sage: R = GF(5)['x']; R
Univariate Polynomial Ring in x over Finite Field of size 5
sage: q = R(p); q
4*x^4 + x^3 + 3*x^2 + 3*x + 3
sage: factor(q)
(4) * (x + 2)^2 * (x^2 + 3)
"""
| 22.93722 | 127 | 0.607527 |
e091211c57418837730aea76bfdd4d9fd710e048 | 1,978 | py | Python | src/riotwatcher/riotwatcher.py | TheBoringBakery/Riot-Watcher | 6e05fffe127530a75fd63e67da37ba81489fd4fe | [
"MIT"
] | 2 | 2020-10-06T23:33:01.000Z | 2020-11-22T01:58:43.000Z | src/riotwatcher/riotwatcher.py | TheBoringBakery/Riot-Watcher | 6e05fffe127530a75fd63e67da37ba81489fd4fe | [
"MIT"
] | null | null | null | src/riotwatcher/riotwatcher.py | TheBoringBakery/Riot-Watcher | 6e05fffe127530a75fd63e67da37ba81489fd4fe | [
"MIT"
] | null | null | null | from .Deserializer import Deserializer
from .RateLimiter import RateLimiter
from .Handlers import (
DeprecationHandler,
DeserializerAdapter,
DictionaryDeserializer,
RateLimiterAdapter,
ThrowOnErrorHandler,
TypeCorrectorHandler,
)
from .Handlers.RateLimit import BasicRateLimiter
from ._apis import BaseApi
from ._apis.riot import AccountApi
| 31.396825 | 104 | 0.637513 |
e09178ade395a6b6c4b0853c972ab7664e0aa556 | 4,175 | py | Python | webots_ros2_core/webots_ros2_core/devices/gps_device.py | TaoYibo1866/webots_ros2 | a72c164825663cebbfd27e0649ea51d3abf9bbed | [
"Apache-2.0"
] | 176 | 2019-09-06T07:02:05.000Z | 2022-03-27T12:41:10.000Z | webots_ros2_core/webots_ros2_core/devices/gps_device.py | TaoYibo1866/webots_ros2 | a72c164825663cebbfd27e0649ea51d3abf9bbed | [
"Apache-2.0"
] | 308 | 2019-08-20T12:56:23.000Z | 2022-03-29T09:49:22.000Z | webots_ros2_core/webots_ros2_core/devices/gps_device.py | omichel/webots_ros2 | 5b59d0b1fbeff4c3f75a447bd152c10853f4691b | [
"Apache-2.0"
] | 67 | 2019-11-03T00:58:09.000Z | 2022-03-18T07:11:28.000Z | # Copyright 1996-2021 Cyberbotics Ltd.
#
# 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.
"""Webots GPS device wrapper for ROS2."""
from rclpy.qos import QoSReliabilityPolicy, qos_profile_sensor_data
from std_msgs.msg import Float32
from sensor_msgs.msg import NavSatFix, NavSatStatus
from geometry_msgs.msg import PointStamped
from .sensor_device import SensorDevice
from controller import GPS
| 37.954545 | 84 | 0.648144 |
e091b9679a6111bb854970806d6dc9286999927c | 127 | py | Python | ML/complete_model/setlist.py | saisankargochhayat/doot | 00bd74463a065f23886e829aae677267b7619e13 | [
"MIT"
] | null | null | null | ML/complete_model/setlist.py | saisankargochhayat/doot | 00bd74463a065f23886e829aae677267b7619e13 | [
"MIT"
] | null | null | null | ML/complete_model/setlist.py | saisankargochhayat/doot | 00bd74463a065f23886e829aae677267b7619e13 | [
"MIT"
] | null | null | null | setlist = [['a','m','n','s','t','g','q','o','x'],['b','e','c'],['h','k','u','v'],
['d','r','p'],['f'],['l'],['i'],['w'],['y']]
| 42.333333 | 81 | 0.244094 |
e091f0178c86f87d30aea273c60c55d5d07a1bdf | 24,241 | py | Python | players/jeff.py | jtreim/cant-stop | 0ef1a2da67e4232a4ad2be150e950e8f1914a851 | [
"MIT"
] | null | null | null | players/jeff.py | jtreim/cant-stop | 0ef1a2da67e4232a4ad2be150e950e8f1914a851 | [
"MIT"
] | null | null | null | players/jeff.py | jtreim/cant-stop | 0ef1a2da67e4232a4ad2be150e950e8f1914a851 | [
"MIT"
] | 2 | 2020-12-29T21:30:54.000Z | 2021-01-02T05:23:23.000Z | from .player import Player
| 35.806499 | 95 | 0.413143 |
e09320dd89276dff3fa36b0f354e1b3cd7cffc60 | 1,767 | py | Python | Python2/src/main.py | nataddrho/digicueblue | 246c87129e6a70d384b1553688672bb3d5c6643e | [
"MIT"
] | 8 | 2017-11-02T16:04:15.000Z | 2021-11-21T18:36:18.000Z | Python2/src/main.py | nataddrho/digicueblue | 246c87129e6a70d384b1553688672bb3d5c6643e | [
"MIT"
] | 2 | 2018-01-09T15:15:12.000Z | 2018-10-11T23:56:59.000Z | Python2/src/main.py | nataddrho/digicueblue | 246c87129e6a70d384b1553688672bb3d5c6643e | [
"MIT"
] | 5 | 2018-01-08T16:06:45.000Z | 2021-11-21T19:50:20.000Z | #!/usr/bin/env python
# Nathan Rhoades 10/13/2017
import serial
import serialport
import bgapi
import gui
import digicueblue
import traceback
import time
import threading
import sys
if sys.version_info[0] < 3:
import Tkinter as Tk
else:
import tkinter as Tk
if __name__ == '__main__':
main()
| 24.887324 | 88 | 0.612903 |
e093e95399d65bf6f2743e6fc81bac4c0cc5d9b1 | 138 | py | Python | messager.py | plasticruler/newshound | c97ef09165eabb27ac65682e4893cf72dae7f3fb | [
"Apache-2.0"
] | null | null | null | messager.py | plasticruler/newshound | c97ef09165eabb27ac65682e4893cf72dae7f3fb | [
"Apache-2.0"
] | null | null | null | messager.py | plasticruler/newshound | c97ef09165eabb27ac65682e4893cf72dae7f3fb | [
"Apache-2.0"
] | null | null | null | import requests
#newspi key c2d941c74c144421945618d97a458144
| 12.545455 | 44 | 0.73913 |
e09525abcb7cde902261ff8255cd7d2143781fb5 | 8,471 | py | Python | PyMaSC/handler/mappability.py | ronin-gw/PyMaSC | 70c32b647017e162e0b004cadcf4f59a2d4012b6 | [
"MIT"
] | 2 | 2018-04-20T13:34:16.000Z | 2021-07-13T16:20:28.000Z | PyMaSC/handler/mappability.py | ronin-gw/PyMaSC | 70c32b647017e162e0b004cadcf4f59a2d4012b6 | [
"MIT"
] | 1 | 2021-03-16T11:08:46.000Z | 2021-03-16T17:26:15.000Z | PyMaSC/handler/mappability.py | ronin-gw/PyMaSC | 70c32b647017e162e0b004cadcf4f59a2d4012b6 | [
"MIT"
] | null | null | null | import logging
import os
import json
from multiprocessing import Process, Queue, Lock
import numpy as np
from PyMaSC.core.mappability import MappableLengthCalculator
from PyMaSC.utils.progress import ProgressHook, MultiLineProgressManager
from PyMaSC.utils.compatible import tostr, xrange
from PyMaSC.utils.output import prepare_outdir
from PyMaSC.utils.calc import exec_worker_pool
logger = logging.getLogger(__name__)
| 37.816964 | 107 | 0.613387 |
e0979923ac060ab5145d8b58681ac366fea606f9 | 1,190 | py | Python | courses/backend/django-for-everybody/Web Application Technologies and Django/resources/dj4e-samples/tmpl/views.py | Nahid-Hassan/fullstack-software-development | 892ffb33e46795061ea63378279a6469de317b1a | [
"CC0-1.0"
] | 297 | 2019-01-25T08:44:08.000Z | 2022-03-29T18:46:08.000Z | courses/backend/django-for-everybody/Web Application Technologies and Django/resources/dj4e-samples/tmpl/views.py | Nahid-Hassan/fullstack-software-development | 892ffb33e46795061ea63378279a6469de317b1a | [
"CC0-1.0"
] | 22 | 2019-05-06T14:21:04.000Z | 2022-02-21T10:05:25.000Z | courses/backend/django-for-everybody/Web Application Technologies and Django/resources/dj4e-samples/tmpl/views.py | Nahid-Hassan/fullstack-software-development | 892ffb33e46795061ea63378279a6469de317b1a | [
"CC0-1.0"
] | 412 | 2019-02-12T20:44:43.000Z | 2022-03-30T04:23:25.000Z | from django.shortcuts import render
from django.views import View
# Create your views here.
# Call this with a parameter number
# Using inheritance (extend)
| 27.045455 | 56 | 0.595798 |
e098554863c066d539fc03234656fd767444cd09 | 477 | py | Python | webapp/ex.py | jykim-rust/python | 50efe51733976d9f8ae3be47d628601ad002d836 | [
"MIT"
] | null | null | null | webapp/ex.py | jykim-rust/python | 50efe51733976d9f8ae3be47d628601ad002d836 | [
"MIT"
] | null | null | null | webapp/ex.py | jykim-rust/python | 50efe51733976d9f8ae3be47d628601ad002d836 | [
"MIT"
] | null | null | null | from flask import escape
'''with open('ex') as full:
for line in full:
print(line,end='**')
'''
'''
a=[]
with open('ex') as full:
for line in full:
a.append(line.split('|'))
print(a)
'''
'''
with open('ex') as full:
for line in full.readline():
print(line)
'''
contents=[]
with open('ex') as log:
for line in log:
#contents.append([])
for item in line.split('|'):
contents.append(item)
print(contents)
| 14.90625 | 36 | 0.540881 |
e0986b7dc3912a34a19f7612f40be9b6072d9a7e | 15,310 | py | Python | lib/twitter_utils.py | Vman45/ask-alexa-twitter | 1711005e51db1f66beb2e41e762c39ee003273aa | [
"MIT"
] | 310 | 2015-07-30T17:05:06.000Z | 2020-12-19T18:39:39.000Z | lib/twitter_utils.py | Vman45/ask-alexa-twitter | 1711005e51db1f66beb2e41e762c39ee003273aa | [
"MIT"
] | 29 | 2015-12-08T22:10:47.000Z | 2017-10-06T16:40:05.000Z | lib/twitter_utils.py | Vman45/ask-alexa-twitter | 1711005e51db1f66beb2e41e762c39ee003273aa | [
"MIT"
] | 73 | 2015-11-12T06:56:53.000Z | 2020-09-13T22:23:44.000Z | import requests
import jsonpickle
from requests_oauthlib import OAuth1
from urllib.parse import parse_qs, urlencode
import cherrypy
from collections import defaultdict
import json
import os
import re
from collections import defaultdict
# For readable serializations
jsonpickle.set_encoder_options('json', sort_keys=True, indent=4)
#Local cache caches tokens for different users
local_cache = LocalCache()
def strip_html(text):
""" Get rid of ugly twitter html """
text = reply_to(text)
text = text.replace('@', ' ')
return " ".join([token for token in text.split()
if ('http:' not in token) and ('https:' not in token)])
def post_tweet(user_id, message, additional_params={}):
"""
Helper function to post a tweet
"""
url = "https://api.twitter.com/1.1/statuses/update.json"
params = { "status" : message }
params.update(additional_params)
r = make_twitter_request(url, user_id, params, request_type='POST')
print (r.text)
return "Successfully posted a tweet {}".format(message)
def process_tweets(tweet_list):
""" Clean tweets and enumerate, preserving only things that we are interested in """
return [Tweet(tweet) for tweet in tweet_list]
def make_twitter_request(url, user_id, params={}, request_type='GET'):
""" Generically make a request to twitter API using a particular user's authorization """
if request_type == "GET":
return requests.get(url, auth=get_twitter_auth(user_id), params=params)
elif request_type == "POST":
return requests.post(url, auth=get_twitter_auth(user_id), params=params)
def geo_search(user_id, search_location):
"""
Search for a location - free form
"""
url = "https://api.twitter.com/1.1/geo/search.json"
params = {"query" : search_location }
response = make_twitter_request(url, user_id, params).json()
return response
def read_out_tweets(processed_tweets, speech_convertor=None):
"""
Input - list of processed 'Tweets'
output - list of spoken responses
"""
return ["tweet number {num} by {user}. {text}.".format(num=index+1, user=user, text=text)
for index, (user, text) in enumerate(processed_tweets)]
def get_retweets_of_me(user_id, input_params={}):
""" returns recently retweeted tweets """
url = "https://api.twitter.com/1.1/statuses/retweets_of_me.json"
print ("trying to get retweets")
return request_tweet_list(url, user_id)
def get_my_favourite_tweets(user_id, input_params = {}):
""" Returns a user's favourite tweets """
url = "https://api.twitter.com/1.1/favorites/list.json"
return request_tweet_list(url, user_id)
def search_for_tweets_about(user_id, params):
""" Search twitter API """
url = "https://api.twitter.com/1.1/search/tweets.json"
response = make_twitter_request(url, user_id, params)
return process_tweets(response.json()["statuses"])
| 36.279621 | 150 | 0.615741 |
e09899e15fdc6c14c2bf5b2ab6389520f9a3d9b7 | 1,399 | py | Python | sundry/serializable.py | jamesabel/sundry | 4f63bfa0624c88a3cd05adf2784e9e3e66e094f4 | [
"MIT"
] | 2 | 2019-10-02T06:30:27.000Z | 2021-07-10T22:39:30.000Z | sundry/serializable.py | jamesabel/sundry | 4f63bfa0624c88a3cd05adf2784e9e3e66e094f4 | [
"MIT"
] | 3 | 2019-03-13T17:15:58.000Z | 2019-06-04T20:26:57.000Z | sundry/serializable.py | jamesabel/sundry | 4f63bfa0624c88a3cd05adf2784e9e3e66e094f4 | [
"MIT"
] | 1 | 2019-03-08T21:37:29.000Z | 2019-03-08T21:37:29.000Z | import json
from enum import Enum
from decimal import Decimal
def convert_serializable_special_cases(o):
"""
Convert an object to a type that is fairly generally serializable (e.g. json serializable).
This only handles the cases that need converting. The json module handles all the rest.
For JSON, with json.dump or json.dumps with argument default=convert_serializable.
Example:
json.dumps(my_animal, indent=4, default=_convert_serializable)
:param o: object to be converted to a type that is serializable
:return: a serializable representation
"""
if isinstance(o, Enum):
serializable_representation = o.value
elif isinstance(o, Decimal):
# decimal.Decimal (e.g. in AWS DynamoDB), both integer and floating point
if o % 1 == 0:
# if representable with an integer, use an integer
serializable_representation = int(o)
else:
# not representable with an integer so use a float
serializable_representation = float(o)
else:
raise NotImplementedError(f"can not serialize {o} since type={type(o)}")
return serializable_representation
| 36.815789 | 97 | 0.709078 |
e09a1b7388131ca361a24a122df607870ceb2f36 | 5,249 | py | Python | legacy/neural_qa/train.py | FrancisLiang/models-1 | e14d5bc1ab36d0dd11977f27cff54605bf99c945 | [
"Apache-2.0"
] | 4 | 2020-01-04T13:15:02.000Z | 2021-07-21T07:50:02.000Z | legacy/neural_qa/train.py | FrancisLiang/models-1 | e14d5bc1ab36d0dd11977f27cff54605bf99c945 | [
"Apache-2.0"
] | 2 | 2019-06-26T03:21:49.000Z | 2019-09-19T09:43:42.000Z | legacy/neural_qa/train.py | FrancisLiang/models-1 | e14d5bc1ab36d0dd11977f27cff54605bf99c945 | [
"Apache-2.0"
] | 3 | 2019-10-31T07:18:49.000Z | 2020-01-13T03:18:39.000Z | import sys
import os
import argparse
import numpy as np
import paddle.v2 as paddle
import reader
import utils
import network
import config
from utils import logger
def show_parameter_init_info(parameters):
"""
Print the information of initialization mean and standard deviation of
parameters
:param parameters: the parameters created in a model
"""
logger.info("Parameter init info:")
for p in parameters:
p_val = parameters.get(p)
logger.info(("%-25s : initial_mean=%-7.4f initial_std=%-7.4f "
"actual_mean=%-7.4f actual_std=%-7.4f dims=%s") %
(p, parameters.__param_conf__[p].initial_mean,
parameters.__param_conf__[p].initial_std, p_val.mean(),
p_val.std(), parameters.__param_conf__[p].dims))
logger.info("\n")
def show_parameter_status(parameters):
"""
Print some statistical information of parameters in a network
:param parameters: the parameters created in a model
"""
for p in parameters:
abs_val = np.abs(parameters.get(p))
abs_grad = np.abs(parameters.get_grad(p))
logger.info(
("%-25s avg_abs_val=%-10.6f max_val=%-10.6f avg_abs_grad=%-10.6f "
"max_grad=%-10.6f min_val=%-10.6f min_grad=%-10.6f") %
(p, abs_val.mean(), abs_val.max(), abs_grad.mean(), abs_grad.max(),
abs_val.min(), abs_grad.min()))
if __name__ == "__main__":
main()
| 33.864516 | 79 | 0.638407 |
e09a68dcd0689137530fb16dbc35c12c92deee70 | 36,880 | py | Python | yggdrasil/drivers/MatlabModelDriver.py | astro-friedel/yggdrasil | 5ecbfd083240965c20c502b4795b6dc93d94b020 | [
"BSD-3-Clause"
] | null | null | null | yggdrasil/drivers/MatlabModelDriver.py | astro-friedel/yggdrasil | 5ecbfd083240965c20c502b4795b6dc93d94b020 | [
"BSD-3-Clause"
] | null | null | null | yggdrasil/drivers/MatlabModelDriver.py | astro-friedel/yggdrasil | 5ecbfd083240965c20c502b4795b6dc93d94b020 | [
"BSD-3-Clause"
] | null | null | null | import subprocess
import uuid as uuid_gen
import logging
from datetime import datetime
import os
import psutil
import warnings
import weakref
from yggdrasil import backwards, tools, platform, serialize
from yggdrasil.languages import get_language_dir
from yggdrasil.config import ygg_cfg
from yggdrasil.drivers.InterpretedModelDriver import InterpretedModelDriver
from yggdrasil.tools import TimeOut, sleep
logger = logging.getLogger(__name__)
try: # pragma: matlab
disable_engine = ygg_cfg.get('matlab', 'disable_engine', 'False').lower()
if platform._is_win or (disable_engine == 'true'):
_matlab_engine_installed = False
if not tools.is_subprocess():
logger.debug("matlab.engine disabled")
else:
import matlab.engine
_matlab_engine_installed = True
except ImportError: # pragma: no matlab
logger.debug("Could not import matlab.engine. "
+ "Matlab support for using a sharedEngine will be disabled.")
_matlab_engine_installed = False
_top_lang_dir = get_language_dir('matlab')
_compat_map = {
'R2015b': ['2.7', '3.3', '3.4'],
'R2017a': ['2.7', '3.3', '3.4', '3.5'],
'R2017b': ['2.7', '3.3', '3.4', '3.5', '3.6'],
'R2018b': ['2.7', '3.3', '3.4', '3.5', '3.6']}
def kill_all():
r"""Kill all Matlab shared engines."""
if platform._is_win: # pragma: windows
os.system(('taskkill /F /IM matlab.engine.shareEngine /T'))
else:
os.system(('pkill -f matlab.engine.shareEngine'))
def locate_matlab_engine_processes(): # pragma: matlab
r"""Get all of the active matlab sharedEngine processes.
Returns:
list: Active matlab sharedEngine processes.
"""
out = []
for p in psutil.process_iter():
p.info = p.as_dict(attrs=['name', 'pid', 'cmdline'])
if (((p.info['name'] == 'MATLAB')
and ('matlab.engine.shareEngine' in p.info['cmdline']))):
out.append(p) # p.info['pid'])
return out
def is_matlab_running():
r"""Determine if there is a Matlab engine running.
Returns:
bool: True if there is a Matlab engine running, False otherwise.
"""
if not _matlab_engine_installed: # pragma: no matlab
out = False
else: # pragma: matlab
out = (len(matlab.engine.find_matlab()) != 0)
return out
def locate_matlabroot(): # pragma: matlab
r"""Find directory that servers as matlab root.
Returns:
str: Full path to matlabroot directory.
"""
return MatlabModelDriver.get_matlab_info()[0]
def install_matlab_engine(): # pragma: matlab
r"""Install the MATLAB engine API for Python."""
if not _matlab_engine_installed:
mtl_root = locate_matlabroot()
mtl_setup = os.path.join(mtl_root, 'extern', 'engines', 'python')
cmd = 'python setup.py install'
result = subprocess.check_output(cmd, cwd=mtl_setup)
print(result)
def start_matlab_engine(skip_connect=False, timeout=None): # pragma: matlab
r"""Start a Matlab shared engine session inside a detached screen
session.
Args:
skip_connect (bool, optional): If True, the engine is not connected.
Defaults to False.
timeout (int, optional): Time (in seconds) that should be waited for
Matlab to start up. Defaults to None and is set from the config
option ('matlab', 'startup_waittime_s').
Returns:
tuple: Information on the started session including the name of the
screen session running matlab, the created engine object, the name
of the matlab session, and the matlab engine process.
Raises:
RuntimeError: If Matlab is not installed.
"""
if not _matlab_engine_installed: # pragma: no matlab
raise RuntimeError("Matlab engine is not installed.")
if timeout is None:
timeout = float(ygg_cfg.get('matlab', 'startup_waittime_s', 10))
old_process = set(locate_matlab_engine_processes())
old_matlab = set(matlab.engine.find_matlab())
screen_session = str('ygg_matlab' + datetime.today().strftime("%Y%j%H%M%S")
+ '_%d' % len(old_matlab))
try:
args = ['screen', '-dmS', screen_session, '-c',
os.path.join(_top_lang_dir, 'matlab_screenrc'),
'matlab', '-nodisplay', '-nosplash', '-nodesktop', '-nojvm',
'-r', '"matlab.engine.shareEngine"']
subprocess.call(' '.join(args), shell=True)
T = TimeOut(timeout)
while ((len(set(matlab.engine.find_matlab()) - old_matlab) == 0)
and not T.is_out):
logger.debug('Waiting for matlab engine to start')
sleep(1) # Usually 3 seconds
except KeyboardInterrupt: # pragma: debug
args = ['screen', '-X', '-S', screen_session, 'quit']
subprocess.call(' '.join(args), shell=True)
raise
if (len(set(matlab.engine.find_matlab()) - old_matlab) == 0): # pragma: debug
raise Exception("start_matlab timed out at %f s" % T.elapsed)
new_matlab = list(set(matlab.engine.find_matlab()) - old_matlab)[0]
new_process = list(set(locate_matlab_engine_processes()) - old_process)[0]
# Connect to the engine
matlab_engine = None
if not skip_connect:
matlab_engine = connect_matlab_engine(new_matlab, first_connect=True)
return screen_session, matlab_engine, new_matlab, new_process
def connect_matlab_engine(matlab_session, first_connect=False): # pragma: matlab
r"""Connect to Matlab engine.
Args:
matlab_session (str): Name of the Matlab session that should be
connected to.
first_connect (bool, optional): If True, this is the first time
Python is connecting to the Matlab shared engine and certain
environment variables should be set. Defaults to False.
Returns:
MatlabEngine: Matlab engine that was connected.
"""
matlab_engine = matlab.engine.connect_matlab(matlab_session)
matlab_engine.eval('clear classes;', nargout=0)
err = backwards.StringIO()
try:
matlab_engine.eval("YggInterface('YGG_MSG_MAX');", nargout=0,
stderr=err)
except BaseException:
for x in MatlabModelDriver.paths_to_add:
matlab_engine.addpath(x, nargout=0)
matlab_engine.eval("os = py.importlib.import_module('os');", nargout=0)
if not first_connect:
if backwards.PY2:
matlab_engine.eval("py.reload(os);", nargout=0)
else:
# matlab_engine.eval("py.importlib.reload(os);", nargout=0)
pass
return matlab_engine
def stop_matlab_engine(screen_session, matlab_engine, matlab_session,
matlab_process, keep_engine=False): # pragma: matlab
r"""Stop a Matlab shared engine session running inside a detached screen
session.
Args:
screen_session (str): Name of the screen session that the shared
Matlab session was started in.
matlab_engine (MatlabEngine): Matlab engine that should be stopped.
matlab_session (str): Name of Matlab session that the Matlab engine is
connected to.
matlab_process (psutil.Process): Process running the Matlab shared engine.
keep_engine (bool, optional): If True, the references to the engine will be
removed so it is not deleted. Defaults to False.
Raises:
RuntimeError: If Matlab is not installed.
"""
if not _matlab_engine_installed: # pragma: no matlab
raise RuntimeError("Matlab engine is not installed.")
if keep_engine and (matlab_engine is not None):
if '_matlab' in matlab_engine.__dict__:
matlab_engine.quit()
return
# Remove weakrefs to engine to prevent stopping engine more than once
if matlab_engine is not None:
# Remove weak references so engine not deleted on exit
eng_ref = weakref.getweakrefs(matlab_engine)
for x in eng_ref:
if x in matlab.engine._engines:
matlab.engine._engines.remove(x)
# Either exit the engine or remove its reference
if matlab_session in matlab.engine.find_matlab():
try:
matlab_engine.eval('exit', nargout=0)
except BaseException:
pass
else: # pragma: no cover
matlab_engine.__dict__.pop('_matlab', None)
# Stop the screen session containing the Matlab shared session
if screen_session is not None:
if matlab_session in matlab.engine.find_matlab():
os.system(('screen -X -S %s quit') % screen_session)
T = TimeOut(5)
while ((matlab_session in matlab.engine.find_matlab())
and not T.is_out):
logger.debug("Waiting for matlab engine to exit")
sleep(1)
if (matlab_session in matlab.engine.find_matlab()): # pragma: debug
if matlab_process is not None:
matlab_process.terminate()
logger.error("stop_matlab_engine timed out at %f s. " % T.elapsed
+ "Killed Matlab sharedEngine process.")
def start(self):
r"""Start asychronous call."""
self.future = self.target(*self.args, **self.kwargs)
def is_started(self):
r"""bool: Has start been called."""
return (self.future is not None)
def is_cancelled(self):
r"""bool: Was the async call cancelled or not."""
if self.is_started():
try:
return self.future.cancelled()
except matlab.engine.EngineError:
self.on_matlab_error()
return True
except BaseException:
return True
return False
def is_done(self):
r"""bool: Is the async call still running."""
if self.is_started():
try:
return self.future.done() or self.is_cancelled()
except matlab.engine.EngineError:
self.on_matlab_error()
return True
except BaseException:
return True
return False
def is_alive(self):
r"""bool: Is the async call funning."""
if self.is_started():
return (not self.is_done())
return False
def kill(self, *args, **kwargs):
r"""Cancel the async call."""
if self.is_alive():
try:
out = self.future.cancel()
self.debug("Result of cancelling Matlab call?: %s", out)
except matlab.engine.EngineError as e:
self.debug('Matlab Engine Error: %s' % e)
self.on_matlab_error()
except BaseException as e:
self.debug('Other error on kill: %s' % e)
self.print_output()
if self.is_alive():
self.info('Error killing Matlab script.')
self.matlab_engine.quit()
self.future = None
self._returncode = -1
assert(not self.is_alive())
def on_matlab_error(self):
r"""Actions performed on error in Matlab engine."""
# self.print_output()
self.debug('')
if self.matlab_engine is not None:
try:
self.matlab_engine.eval('exception = MException.last;', nargout=0)
self.matlab_engine.eval('getReport(exception)')
except matlab.engine.EngineError:
pass
class MatlabModelDriver(InterpretedModelDriver): # pragma: matlab
r"""Base class for running Matlab models.
Args:
name (str): Driver name.
args (str or list): Argument(s) for running the model in matlab.
Generally, this should be the full path to a Matlab script.
**kwargs: Additional keyword arguments are passed to parent class's
__init__ method.
Attributes:
started_matlab (bool): True if the driver had to start a new matlab
engine. False otherwise.
screen_session (str): Screen session that Matlab was started in.
mlengine (object): Matlab engine used to run script.
mlsession (str): Name of the Matlab session that was started.
Raises:
RuntimeError: If Matlab is not installed.
.. note:: Matlab models that call exit will shut down the shared engine.
"""
_schema_subtype_description = ('Model is written in Matlab.')
language = 'matlab'
language_ext = '.m'
base_languages = ['python']
default_interpreter_flags = ['-nodisplay', '-nosplash', '-nodesktop',
'-nojvm', '-batch']
version_flags = ["fprintf('R%s', version('-release')); exit();"]
path_env_variable = 'MATLABPATH'
comm_linger = (os.environ.get('YGG_MATLAB_ENGINE', '').lower() == 'true')
send_converters = {'pandas': serialize.consolidate_array,
'table': serialize.consolidate_array}
recv_converters = {'pandas': 'array'}
type_map = {
'int': 'intX',
'float': 'single, double',
'string': 'char',
'array': 'cell',
'object': 'containers.Map',
'boolean': 'logical',
'null': 'NaN',
'uint': 'uintX',
'complex': 'complex',
'bytes': 'char (utf-8)',
'unicode': 'char',
'1darray': 'mat',
'ndarray': 'mat',
'ply': 'containers.Map',
'obj': 'containers.Map',
'schema': 'containers.Map'}
function_param = {
'input': '{channel} = YggInterface(\'YggInput\', \'{channel_name}\');',
'output': '{channel} = YggInterface(\'YggOutput\', \'{channel_name}\');',
'recv': '[{flag_var}, {recv_var}] = {channel}.recv();',
'send': '{flag_var} = {channel}.send({send_var});',
'function_call': '{output_var} = {function_name}({input_var});',
'define': '{variable} = {value};',
'comment': '%',
'true': 'true',
'not': 'not',
'indent': 2 * ' ',
'quote': '\'',
'print': 'disp(\'{message}\');',
'fprintf': 'fprintf(\'{message}\', {variables});',
'error': 'error(\'{error_msg}\');',
'block_end': 'end;',
'if_begin': 'if ({cond})',
'for_begin': 'for {iter_var} = {iter_begin}:{iter_end}',
'while_begin': 'while ({cond})',
'break': 'break;',
'try_begin': 'try',
'try_except': 'catch {error_var}',
'assign': '{name} = {value};'}
def parse_arguments(self, args):
r"""Sort model arguments to determine which one is the executable
and which ones are arguments.
Args:
args (list): List of arguments provided.
"""
super(MatlabModelDriver, self).parse_arguments(args)
model_base, model_ext = os.path.splitext(os.path.basename(self.model_file))
wrap_base = 'wrapped_%s_%s' % (model_base, self.uuid.replace('-', '_'))
# Matlab has a variable name limit of 62
wrap_base = wrap_base[:min(len(wrap_base), 60)]
self.model_wrapper = os.path.join(self.model_dir, wrap_base + model_ext)
self.wrapper_products.append(self.model_wrapper)
def start_matlab_engine(self):
r"""Start matlab session and connect to it."""
ml_attr = ['screen_session', 'mlengine', 'mlsession', 'mlprocess']
attempt_connect = (len(matlab.engine.find_matlab()) != 0)
# Connect to matlab if a session exists
if attempt_connect:
for mlsession in matlab.engine.find_matlab():
try:
self.debug("Trying to connect to session %s", mlsession)
self.mlengine = connect_matlab_engine(mlsession)
self.mlsession = mlsession
self.debug("Connected to existing shared engine: %s",
self.mlsession)
break
except matlab.engine.EngineError:
pass
# Start if not running or connect failed
if self.mlengine is None:
if attempt_connect:
self.debug("Starting a matlab shared engine (connect failed)")
else:
self.debug("Starting a matlab shared engine (none existing)")
out = start_matlab_engine()
for i, attr in enumerate(ml_attr):
setattr(self, attr, out[i])
self.started_matlab = True
# Add things to Matlab environment
self.mlengine.addpath(self.model_dir, nargout=0)
self.debug("Connected to matlab session '%s'" % self.mlsession)
def before_start(self):
r"""Actions to perform before the run loop."""
kwargs = dict(fname_wrapper=self.model_wrapper)
if self.using_matlab_engine:
self.start_matlab_engine()
kwargs.update(matlab_engine=self.mlengine,
no_queue_thread=True)
else:
kwargs.update(working_dir=self.model_dir)
with self.lock:
if self.using_matlab_engine and (self.mlengine is None): # pragma: debug
self.debug('Matlab engine not set. Stopping')
return
super(MatlabModelDriver, self).before_start(**kwargs)
def run_loop(self):
r"""Loop to check if model is still running and forward output."""
if self.using_matlab_engine:
self.model_process.print_output()
self.periodic_debug('matlab loop', period=100)('Looping')
if self.model_process.is_done():
self.model_process.print_output()
self.set_break_flag()
try:
self.model_process.future.result()
self.model_process.print_output()
except matlab.engine.EngineError:
self.model_process.print_output()
except BaseException:
self.model_process.print_output()
self.exception("Error running model.")
else:
self.sleep()
else:
super(MatlabModelDriver, self).run_loop()
def after_loop(self):
r"""Actions to perform after run_loop has finished. Mainly checking
if there was an error and then handling it."""
if self.using_matlab_engine:
if (self.model_process is not None) and self.model_process.is_alive():
self.info("Model process thread still alive")
self.kill_process()
return
super(MatlabModelDriver, self).after_loop()
if self.using_matlab_engine:
with self.lock:
self.cleanup()
def cleanup(self):
r"""Close the Matlab session and engine."""
if self.using_matlab_engine:
try:
stop_matlab_engine(self.screen_session, self.mlengine,
self.mlsession, self.mlprocess,
keep_engine=(not self.started_matlab))
except (SystemError, Exception) as e: # pragma: debug
self.error('Failed to exit matlab engine')
self.raise_error(e)
self.debug('Stopped Matlab')
self.screen_session = None
self.mlsession = None
self.started_matlab = False
self.mlengine = None
self.mlprocess = None
super(MatlabModelDriver, self).cleanup()
def check_exits(self):
r"""Check to make sure the program dosn't contain any exits as exits
will shut down the Matlab engine as well as the program.
Raises:
RuntimeError: If there are any exit calls in the file.
"""
has_exit = False
with open(self.raw_model_file, 'r') as fd:
for i, line in enumerate(fd):
if line.strip().startswith('exit'):
has_exit = True
break
if self.using_matlab_engine and has_exit:
warnings.warn(
"Line %d in '%s' contains an " % (
i, self.raw_model_file)
+ "'exit' call which will exit the MATLAB engine "
+ "such that it cannot be reused. Please replace 'exit' "
+ "with a return or error.")
def set_env(self):
r"""Get environment variables that should be set for the model process.
Returns:
dict: Environment variables for the model process.
"""
out = super(MatlabModelDriver, self).set_env()
if self.using_matlab_engine:
out['YGG_MATLAB_ENGINE'] = 'True'
# TODO: Move the following to InterpretedModelDriver once another
# language sets path_env_variable
path_list = []
prev_path = out.pop(self.path_env_variable, '')
if prev_path:
path_list.append(prev_path)
if isinstance(self.paths_to_add, list):
for x in self.paths_to_add:
if x not in prev_path:
path_list.append(x)
path_list.append(self.model_dir)
if path_list:
out[self.path_env_variable] = os.pathsep.join(path_list)
return out
| 40.086957 | 85 | 0.585195 |
e09cac0b5e9ae4638a705a4871a79857b3f43a52 | 1,049 | py | Python | analysis/migrations/0032_auto_20210409_1333.py | SACGF/variantgrid | 515195e2f03a0da3a3e5f2919d8e0431babfd9c9 | [
"RSA-MD"
] | 5 | 2021-01-14T03:34:42.000Z | 2022-03-07T15:34:18.000Z | analysis/migrations/0032_auto_20210409_1333.py | SACGF/variantgrid | 515195e2f03a0da3a3e5f2919d8e0431babfd9c9 | [
"RSA-MD"
] | 551 | 2020-10-19T00:02:38.000Z | 2022-03-30T02:18:22.000Z | analysis/migrations/0032_auto_20210409_1333.py | SACGF/variantgrid | 515195e2f03a0da3a3e5f2919d8e0431babfd9c9 | [
"RSA-MD"
] | null | null | null | # Generated by Django 3.1.3 on 2021-04-09 04:03
import django.db.models.deletion
from django.db import migrations, models
| 33.83871 | 163 | 0.613918 |
e09ce665126d9b3d2e1a629422eb3823667146fa | 3,453 | py | Python | ted_sws/mapping_suite_processor/services/conceptual_mapping_generate_sparql_queries.py | meaningfy-ws/ted-sws | d1e351eacb2900f84ec7edc457e49d8202fbaff5 | [
"Apache-2.0"
] | 1 | 2022-03-21T12:32:52.000Z | 2022-03-21T12:32:52.000Z | ted_sws/mapping_suite_processor/services/conceptual_mapping_generate_sparql_queries.py | meaningfy-ws/ted-sws | d1e351eacb2900f84ec7edc457e49d8202fbaff5 | [
"Apache-2.0"
] | 24 | 2022-02-10T10:43:56.000Z | 2022-03-29T12:36:21.000Z | ted_sws/mapping_suite_processor/services/conceptual_mapping_generate_sparql_queries.py | meaningfy-ws/ted-sws | d1e351eacb2900f84ec7edc457e49d8202fbaff5 | [
"Apache-2.0"
] | null | null | null | import pathlib
from typing import Iterator
import pandas as pd
from ted_sws.resources.prefixes import PREFIXES_DEFINITIONS
import re
CONCEPTUAL_MAPPINGS_RULES_SHEET_NAME = "Rules"
RULES_SF_FIELD_ID = 'Standard Form Field ID (M)'
RULES_SF_FIELD_NAME = 'Standard Form Field Name (M)'
RULES_E_FORM_BT_ID = 'eForm BT-ID (O)'
RULES_E_FORM_BT_NAME = 'eForm BT Name (O)'
RULES_BASE_XPATH = 'Base XPath (for anchoring) (M)'
RULES_FIELD_XPATH = 'Field XPath (M)'
RULES_CLASS_PATH = 'Class path (M)'
RULES_PROPERTY_PATH = 'Property path (M)'
DEFAULT_RQ_NAME = 'sparql_query_'
SPARQL_PREFIX_PATTERN = re.compile('(?:\\s+|^)(\\w+)?:')
SPARQL_PREFIX_LINE = 'PREFIX {prefix}: <{value}>'
def mapping_suite_processor_generate_sparql_queries(conceptual_mappings_file_path: pathlib.Path,
output_sparql_queries_folder_path: pathlib.Path,
rq_name: str = DEFAULT_RQ_NAME):
"""
This function reads data from conceptual_mappings.xlsx and generates SPARQL validation queries in provided package.
:param conceptual_mappings_file_path:
:param output_sparql_queries_folder_path:
:param rq_name:
:return:
"""
with open(conceptual_mappings_file_path, 'rb') as excel_file:
conceptual_mappings_rules_df = pd.read_excel(excel_file, sheet_name=CONCEPTUAL_MAPPINGS_RULES_SHEET_NAME)
conceptual_mappings_rules_df.columns = conceptual_mappings_rules_df.iloc[0]
conceptual_mappings_rules_df = conceptual_mappings_rules_df[1:]
conceptual_mappings_rules_df = conceptual_mappings_rules_df[
conceptual_mappings_rules_df[RULES_PROPERTY_PATH].notnull()]
sparql_queries = sparql_validation_generator(conceptual_mappings_rules_df)
output_sparql_queries_folder_path.mkdir(parents=True, exist_ok=True)
for index, sparql_query in enumerate(sparql_queries):
output_file_path = output_sparql_queries_folder_path / f"{rq_name}{index}.rq"
with open(output_file_path, "w") as output_file:
output_file.write(sparql_query)
| 46.662162 | 250 | 0.705763 |
e09eabe2c9581024fbbd8098d315804c81879f55 | 205 | py | Python | src/__init__.py | codeKgu/BiLevel-Graph-Neural-Network | ed89c7d39baca757411cf333c595ac464e991a8e | [
"MIT"
] | 20 | 2020-07-22T03:56:13.000Z | 2021-12-02T01:13:09.000Z | src/__init__.py | codeKgu/BiLevel-Graph-Neural-Network | ed89c7d39baca757411cf333c595ac464e991a8e | [
"MIT"
] | 1 | 2020-07-28T17:47:17.000Z | 2020-08-03T15:38:40.000Z | src/__init__.py | codeKgu/BiLevel-Graph-Neural-Network | ed89c7d39baca757411cf333c595ac464e991a8e | [
"MIT"
] | 5 | 2020-08-09T11:14:49.000Z | 2020-12-10T11:37:44.000Z | import sys
from os.path import dirname, abspath, join
cur_folder = dirname(abspath(__file__))
sys.path.insert(0, join(dirname(cur_folder), 'src'))
sys.path.insert(0, dirname(cur_folder))
print(cur_folder) | 29.285714 | 52 | 0.77561 |
e0a0f22bfda8fa26025e7c4065f5e2b941f28ecf | 3,892 | py | Python | src/controllers/serie.py | igormotta92/gta-desafio-python-flask-api | 7c048239359e8a21d777109bdb0d58b6c2c18450 | [
"MIT"
] | null | null | null | src/controllers/serie.py | igormotta92/gta-desafio-python-flask-api | 7c048239359e8a21d777109bdb0d58b6c2c18450 | [
"MIT"
] | null | null | null | src/controllers/serie.py | igormotta92/gta-desafio-python-flask-api | 7c048239359e8a21d777109bdb0d58b6c2c18450 | [
"MIT"
] | null | null | null | # https://stackoverflow.com/questions/3300464/how-can-i-get-dict-from-sqlite-query
# from flask import Flask
from flask_restful import Resource, reqparse
from src.model.serie import SerieModel
from src.server.instance import server
from db import db
# books_db = [{"id": 0, "title": "War and Peace"}, {"id": 1, "title": "Clean Code"}]
api = server.api
| 29.938462 | 93 | 0.573741 |
e0a33a3a50dffea3e1b1459aa66fc2a300fcaf7e | 879 | py | Python | tests/test_random.py | hirnimeshrampuresoftware/python-tcod | c82d60eaaf12e50b405d55df1026c1d00dd283b6 | [
"BSD-2-Clause"
] | 231 | 2018-06-28T10:07:41.000Z | 2022-03-20T16:17:19.000Z | tests/test_random.py | hirnimeshrampuresoftware/python-tcod | c82d60eaaf12e50b405d55df1026c1d00dd283b6 | [
"BSD-2-Clause"
] | 66 | 2018-06-27T19:04:25.000Z | 2022-03-30T21:15:15.000Z | tests/test_random.py | hirnimeshrampuresoftware/python-tcod | c82d60eaaf12e50b405d55df1026c1d00dd283b6 | [
"BSD-2-Clause"
] | 31 | 2018-09-12T00:35:42.000Z | 2022-03-20T16:17:22.000Z | import copy
import pickle
import tcod
| 30.310345 | 76 | 0.675768 |
e0a616cc9e84aa1cf90226b12de930157c9cb478 | 2,538 | py | Python | src/Products/Five/viewlet/viewlet.py | rbanffy/Zope | ecf6770219052e7c7f8c9634ddf187a1e6280742 | [
"ZPL-2.1"
] | 289 | 2015-01-05T12:38:21.000Z | 2022-03-05T21:20:39.000Z | src/Products/Five/viewlet/viewlet.py | rbanffy/Zope | ecf6770219052e7c7f8c9634ddf187a1e6280742 | [
"ZPL-2.1"
] | 732 | 2015-02-09T23:35:57.000Z | 2022-03-31T09:10:13.000Z | src/Products/Five/viewlet/viewlet.py | rbanffy/Zope | ecf6770219052e7c7f8c9634ddf187a1e6280742 | [
"ZPL-2.1"
] | 102 | 2015-01-12T14:03:35.000Z | 2022-03-30T11:02:44.000Z | ##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Viewlet.
"""
import os
import zope.viewlet.viewlet
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
def SimpleViewletClass(template, bases=(), attributes=None, name=''):
"""A function that can be used to generate a viewlet from a set of
information.
"""
# Create the base class hierarchy
bases += (simple, ViewletBase)
attrs = {'index': ViewPageTemplateFile(template),
'__name__': name}
if attributes:
attrs.update(attributes)
# Generate a derived view class.
class_ = type("SimpleViewletClass from %s" % template, bases, attrs)
return class_
def JavaScriptViewlet(path):
"""Create a viewlet that can simply insert a javascript link."""
src = os.path.join(os.path.dirname(__file__), 'javascript_viewlet.pt')
klass = type('JavaScriptViewlet',
(ResourceViewletBase, ViewletBase),
{'index': ViewPageTemplateFile(src), '_path': path})
return klass
def CSSViewlet(path, media="all", rel="stylesheet"):
"""Create a viewlet that can simply insert a javascript link."""
src = os.path.join(os.path.dirname(__file__), 'css_viewlet.pt')
klass = type('CSSViewlet',
(CSSResourceViewletBase, ViewletBase),
{'index': ViewPageTemplateFile(src),
'_path': path,
'_media': media,
'_rel': rel})
return klass
| 29.511628 | 78 | 0.648542 |
e0a621c3b559223c04896e67f79d61f3971a7ebf | 920 | py | Python | problema21.py | bptfreitas/Project-Euler | 02b3ef8f8e3754b886b266fcd5eee7fd00d97dde | [
"MIT"
] | null | null | null | problema21.py | bptfreitas/Project-Euler | 02b3ef8f8e3754b886b266fcd5eee7fd00d97dde | [
"MIT"
] | null | null | null | problema21.py | bptfreitas/Project-Euler | 02b3ef8f8e3754b886b266fcd5eee7fd00d97dde | [
"MIT"
] | null | null | null | #Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
#If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers.
#For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
#Evaluate the sum of all the amicable numbers under 10000.
import euler
print euler.get_divisors(284)
print sum(euler.get_divisors(284))
limit=10000
perc=5
step=perc*limit/100
cp=0
a=1
amics=[]
print "Starting..."
for a in range(1,limit+1):
b=d(a)
if a==d(b) and a!=b:
print "Pair:" + str(a) + " and " + str(b)
if (a not in amics):
amics.append(a)
if (b not in amics):
amics.append(b)
print "Sum of amicables:"
print sum(amics)
| 20.444444 | 181 | 0.661957 |
e0a7f01f58bb59078e58b00112eda388117b8294 | 1,590 | py | Python | python-3.6.0/Doc/includes/email-unpack.py | emacslisp/python | 5b89ddcc504108f0dfa1081e338e6475cf6ccd2f | [
"Apache-2.0"
] | 854 | 2017-09-11T16:42:28.000Z | 2022-03-27T14:17:09.000Z | python-3.6.0/Doc/includes/email-unpack.py | emacslisp/python | 5b89ddcc504108f0dfa1081e338e6475cf6ccd2f | [
"Apache-2.0"
] | 164 | 2017-09-24T20:40:32.000Z | 2021-10-30T01:35:05.000Z | python-3.6.0/Doc/includes/email-unpack.py | emacslisp/python | 5b89ddcc504108f0dfa1081e338e6475cf6ccd2f | [
"Apache-2.0"
] | 73 | 2017-09-13T18:07:48.000Z | 2022-03-17T13:02:29.000Z | #!/usr/bin/env python3
"""Unpack a MIME message into a directory of files."""
import os
import email
import mimetypes
from email.policy import default
from argparse import ArgumentParser
if __name__ == '__main__':
main()
| 29.444444 | 78 | 0.611321 |
e0a80310257c1b06b4c2e9dcba5929214b903c35 | 1,400 | py | Python | src/streetview/logging_facility.py | juliantrue/Streetview-Segmenting | 337740e6ebd2284c880ace09a11032c5914b39a4 | [
"MIT"
] | 1 | 2021-02-27T07:39:05.000Z | 2021-02-27T07:39:05.000Z | src/streetview/logging_facility.py | juliantrue/Streetview-Segmenting | 337740e6ebd2284c880ace09a11032c5914b39a4 | [
"MIT"
] | null | null | null | src/streetview/logging_facility.py | juliantrue/Streetview-Segmenting | 337740e6ebd2284c880ace09a11032c5914b39a4 | [
"MIT"
] | 1 | 2021-12-06T23:35:34.000Z | 2021-12-06T23:35:34.000Z | import sys, os
import logging
import datetime
module_name = 'Streetview_Module'
debug_mode = True
| 32.55814 | 93 | 0.597857 |
e0a906006c6cdb005397afa90c409162626abaca | 536 | py | Python | tkinter_examples/draw_chess_board.py | DazEB2/SimplePyScripts | 1dde0a42ba93fe89609855d6db8af1c63b1ab7cc | [
"CC-BY-4.0"
] | 117 | 2015-12-18T07:18:27.000Z | 2022-03-28T00:25:54.000Z | tkinter_examples/draw_chess_board.py | DazEB2/SimplePyScripts | 1dde0a42ba93fe89609855d6db8af1c63b1ab7cc | [
"CC-BY-4.0"
] | 8 | 2018-10-03T09:38:46.000Z | 2021-12-13T19:51:09.000Z | tkinter_examples/draw_chess_board.py | DazEB2/SimplePyScripts | 1dde0a42ba93fe89609855d6db8af1c63b1ab7cc | [
"CC-BY-4.0"
] | 28 | 2016-08-02T17:43:47.000Z | 2022-03-21T08:31:12.000Z | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
from tkinter import *
root = Tk()
root.title('Chess board')
canvas = Canvas(root, width=700, height=700, bg='#fff')
canvas.pack()
fill = '#fff'
outline = '#000'
size = 88
for i in range(8):
for j in range(8):
x1, y1, x2, y2 = i * size, j * size, i * size + size, j * size + size
canvas.create_rectangle(x1, y1, x2, y2, fill=fill, outline=outline)
fill, outline = outline, fill
fill, outline = outline, fill
root.mainloop()
| 18.482759 | 77 | 0.606343 |
e0ab0941f48814dab8b198e84e5c5153cca3e066 | 7,827 | py | Python | sandbox_api/asandbox.py | PremierLangage/sandbox-api | 7150ddcb92ac2304ff1d7b23571ec5e20459747b | [
"MIT"
] | 4 | 2020-01-27T19:06:05.000Z | 2021-06-01T08:27:30.000Z | sandbox_api/asandbox.py | qcoumes/sandbox-api | 7150ddcb92ac2304ff1d7b23571ec5e20459747b | [
"MIT"
] | null | null | null | sandbox_api/asandbox.py | qcoumes/sandbox-api | 7150ddcb92ac2304ff1d7b23571ec5e20459747b | [
"MIT"
] | null | null | null | # asandbox.py
#
# Authors:
# - Coumes Quentin <coumes.quentin@gmail.com>
"""An asynchronous implementation of the Sandbox API."""
import io
import json
import os
from contextlib import AbstractAsyncContextManager
from typing import BinaryIO, Optional, Union
import aiohttp
from .exceptions import status_exceptions
from .utils import ENDPOINTS
| 38.55665 | 94 | 0.609046 |
e0ab889f41c5f27938c1c1068877196809ff21fd | 4,928 | py | Python | api/services/usuarios_services.py | jhonnattan123/fastapi_crud_example | 24e1c295d41ad364ef839a4756e85b5bd640385a | [
"MIT"
] | 1 | 2022-03-25T17:37:46.000Z | 2022-03-25T17:37:46.000Z | api/services/usuarios_services.py | jhonnattan123/fastapi_crud_example | 24e1c295d41ad364ef839a4756e85b5bd640385a | [
"MIT"
] | null | null | null | api/services/usuarios_services.py | jhonnattan123/fastapi_crud_example | 24e1c295d41ad364ef839a4756e85b5bd640385a | [
"MIT"
] | null | null | null | import datetime
from uuid import UUID
from api.actions import storage
from fastapi import HTTPException
from api.models.usuario import Usuario
from starlette.requests import Request
from api.dependencies import validar_email, validar_formato_fecha,validar_edad
FORMATO_FECHA = "%Y-%m-%d"
EDAD_MINIMA = 18
EDAD_MAXIMA = 100 | 32.421053 | 109 | 0.584416 |
e0ad08c2a04080e6246b307168d37bc9b104e50c | 10,204 | py | Python | certau/util/taxii/client.py | thisismyrobot/cti-toolkit | faf6e912af69376f5c55902c1592f7eeb0ce03dd | [
"BSD-3-Clause"
] | 12 | 2016-07-11T07:53:05.000Z | 2021-07-19T12:20:21.000Z | certau/util/taxii/client.py | thisismyrobot/cti-toolkit | faf6e912af69376f5c55902c1592f7eeb0ce03dd | [
"BSD-3-Clause"
] | null | null | null | certau/util/taxii/client.py | thisismyrobot/cti-toolkit | faf6e912af69376f5c55902c1592f7eeb0ce03dd | [
"BSD-3-Clause"
] | 4 | 2016-11-13T22:38:10.000Z | 2022-01-15T08:21:15.000Z | import os
import logging
import dateutil
import pickle
from six.moves.urllib.parse import urlparse
from libtaxii import get_message_from_http_response, VID_TAXII_XML_11
from libtaxii.messages_11 import PollRequest, PollFulfillmentRequest
from libtaxii.messages_11 import PollResponse, generate_message_id
from libtaxii.clients import HttpClient
from certau import version_string
def poll(self, poll_url, collection, subscription_id=None,
begin_timestamp=None, end_timestamp=None, state_file=None):
"""Send the TAXII poll request to the server using the given URL."""
# Parse the poll_url to get the parts required by libtaxii
url_parts = urlparse(poll_url)
# Allow credentials to be provided in poll_url
if url_parts.username and url_parts.password:
self.username = url_parts.username
self.password = url_parts.password
self._logger.debug('updating username and password from poll_url')
if url_parts.scheme not in ['http', 'https']:
raise Exception('invalid scheme in poll_url (%s); expected '
'"http" or "https"', poll_url)
use_ssl = True if url_parts.scheme == 'https' else False
# Initialise the authentication settings
self.setup_authentication(use_ssl)
if state_file and not begin_timestamp:
begin_timestamp = self.get_poll_time(
filename=state_file,
poll_url=poll_url,
collection=collection,
)
request = self.create_poll_request(
collection=collection,
subscription_id=subscription_id,
begin_timestamp=begin_timestamp,
end_timestamp=end_timestamp,
)
self._logger.debug('sending poll request (url=%s, collection=%s)',
poll_url, collection)
response = self.send_taxii_message(
request=request,
host=url_parts.hostname,
path=url_parts.path,
port=url_parts.port,
)
first = True
poll_end_time = None
while True:
if not isinstance(response, PollResponse):
raise Exception('didn\'t get a poll response')
self._logger.debug('received poll response '
'(content_blocks=%d, result_id=%s, more=%s)',
len(response.content_blocks),
response.result_id,
'True' if response.more else 'False')
# Save end timestamp from first PollResponse
if first:
poll_end_time = response.inclusive_end_timestamp_label
if len(response.content_blocks) == 0:
if first:
self._logger.info('poll response contained '
'no content blocks')
break
for content_block in response.content_blocks:
yield content_block
if not response.more:
break
# Send a fulfilment request
if first:
# Initialise fulfilment request values
part_number = response.result_part_number
result_id = response.result_id
first = False
part_number += 1
request = self.create_fulfillment_request(
collection=collection,
result_id=result_id,
part_number=part_number,
)
self._logger.debug('sending fulfilment request '
'(result_id=%s, part_number=%d)',
result_id, part_number)
response = self.send_taxii_message(
request=request,
host=url_parts.hostname,
path=url_parts.path,
port=url_parts.port,
)
# Update the timestamp for the latest poll
if state_file and poll_end_time:
self.save_poll_time(
filename=state_file,
poll_url=poll_url,
collection=collection,
timestamp=poll_end_time,
)
| 38.217228 | 78 | 0.591141 |
e0ada93a5debd6b2509b477f0b39c69cfae7e923 | 768 | py | Python | tutorials/registration/data.py | YipengHu/MPHY0041 | 6e9706eba2b9f9a2449539d7dea5f91dde807584 | [
"Apache-2.0"
] | 1 | 2022-02-21T23:05:49.000Z | 2022-02-21T23:05:49.000Z | tutorials/registration/data.py | YipengHu/MPHY0041 | 6e9706eba2b9f9a2449539d7dea5f91dde807584 | [
"Apache-2.0"
] | 2 | 2022-01-07T11:43:06.000Z | 2022-03-17T02:11:58.000Z | tutorials/registration/data.py | YipengHu/MPHY0041 | 6e9706eba2b9f9a2449539d7dea5f91dde807584 | [
"Apache-2.0"
] | null | null | null |
import os
import zipfile
import requests
DATA_PATH = './data'
RESULT_PATH = './result'
if not os.path.exists(DATA_PATH):
os.makedirs(DATA_PATH)
print('Downloading and extracting data...')
url = 'https://weisslab.cs.ucl.ac.uk/WEISSTeaching/datasets/-/archive/hn2dct/datasets-hn2dct.zip'
r = requests.get(url,allow_redirects=True)
temp_file = 'temp.zip'
_ = open(temp_file,'wb').write(r.content)
with zipfile.ZipFile(temp_file,'r') as zip_obj:
zip_obj.extractall(DATA_PATH)
os.remove(temp_file)
print('Done.')
print('Head-neck 2D CT data downloaded: %s' % os.path.abspath(os.path.join(DATA_PATH,'datasets-hn2dct')))
if not os.path.exists(RESULT_PATH):
os.makedirs(RESULT_PATH)
print('Result directory created: %s' % os.path.abspath(RESULT_PATH))
| 27.428571 | 105 | 0.736979 |
e0ae282e70b49bf571087a6d88c319ae9d3cc9d4 | 3,774 | py | Python | insights/parsers/tests/test_freeipa_healthcheck_log.py | lhuett/insights-core | 1c84eeffc037f85e2bbf60c9a302c83aa1a50cf8 | [
"Apache-2.0"
] | null | null | null | insights/parsers/tests/test_freeipa_healthcheck_log.py | lhuett/insights-core | 1c84eeffc037f85e2bbf60c9a302c83aa1a50cf8 | [
"Apache-2.0"
] | null | null | null | insights/parsers/tests/test_freeipa_healthcheck_log.py | lhuett/insights-core | 1c84eeffc037f85e2bbf60c9a302c83aa1a50cf8 | [
"Apache-2.0"
] | null | null | null | import doctest
from insights.parsers import freeipa_healthcheck_log
from insights.parsers.freeipa_healthcheck_log import FreeIPAHealthCheckLog
from insights.tests import context_wrap
LONG_FREEIPA_HEALTHCHECK_LOG_OK = """
[{"source": "ipahealthcheck.ipa.roles", "check": "IPACRLManagerCheck",
"result": "SUCCESS", "uuid": "1f4177a4-0ddb-4e4d-8258-a5cd5f4638fc",
"when": "20191203122317Z", "duration": "0.002254",
"kw": {"key": "crl_manager", "crlgen_enabled": true}}]
""".strip()
LONG_FREEIPA_HEALTHCHECK_LOG_FAILURES = """
[{"source": "ipahealthcheck.system.filesystemspace",
"check": "FileSystemSpaceCheck",
"result": "ERROR", "uuid": "90ed8765-6ad7-425c-abbd-b07a652649cb",
"when": "20191203122221Z", "duration": "0.000474", "kw": {
"msg": "/var/log/audit/: free space under threshold: 14 MiB < 512 MiB",
"store": "/var/log/audit/", "free_space": 14, "threshold": 512}}]
""".strip()
FREEIPA_HEALTHCHECK_LOG_DOCS_EXAMPLE = '''
[
{
"source": "ipahealthcheck.ipa.roles",
"check": "IPACRLManagerCheck",
"result": "SUCCESS",
"uuid": "1f4177a4-0ddb-4e4d-8258-a5cd5f4638fc",
"when": "20191203122317Z",
"duration": "0.002254",
"kw": {
"key": "crl_manager",
"crlgen_enabled": true
}
},
{
"source": "ipahealthcheck.ipa.roles",
"check": "IPARenewalMasterCheck",
"result": "SUCCESS",
"uuid": "1feb7f99-2e98-4e37-bb52-686896972022",
"when": "20191203122317Z",
"duration": "0.018330",
"kw": {
"key": "renewal_master",
"master": true
}
},
{
"source": "ipahealthcheck.system.filesystemspace",
"check": "FileSystemSpaceCheck",
"result": "ERROR",
"uuid": "90ed8765-6ad7-425c-abbd-b07a652649cb",
"when": "20191203122221Z",
"duration": "0.000474",
"kw": {
"msg": "/var/log/audit/: free space under threshold: 14 MiB < 512 MiB",
"store": "/var/log/audit/",
"free_space": 14,
"threshold": 512
}
}
]
'''.strip()
FREEIPA_HEALTHCHECK_LOG_OK = "".join(LONG_FREEIPA_HEALTHCHECK_LOG_OK.splitlines())
FREEIPA_HEALTHCHECK_LOG_FAILURES = "".join(LONG_FREEIPA_HEALTHCHECK_LOG_FAILURES.splitlines())
| 35.942857 | 98 | 0.673026 |
e0aedd632aed5a57b006b298a3c339eedfc172f6 | 3,484 | py | Python | recipes/recipes/windows_image_builder/winpe_customization.py | xswz8015/infra | f956b78ce4c39cc76acdda47601b86794ae0c1ba | [
"BSD-3-Clause"
] | null | null | null | recipes/recipes/windows_image_builder/winpe_customization.py | xswz8015/infra | f956b78ce4c39cc76acdda47601b86794ae0c1ba | [
"BSD-3-Clause"
] | 4 | 2022-03-17T18:58:21.000Z | 2022-03-17T18:58:22.000Z | recipes/recipes/windows_image_builder/winpe_customization.py | xswz8015/infra | f956b78ce4c39cc76acdda47601b86794ae0c1ba | [
"BSD-3-Clause"
] | null | null | null | # Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from recipe_engine import post_process
from PB.recipes.infra.windows_image_builder import windows_image_builder as wib
from PB.recipes.infra.windows_image_builder import actions
from PB.recipes.infra.windows_image_builder import sources
from recipe_engine.post_process import DropExpectation, StatusSuccess
from RECIPE_MODULES.infra.windows_scripts_executor import test_helper as t
DEPS = [
'depot_tools/gitiles',
'recipe_engine/platform',
'recipe_engine/properties',
'recipe_engine/raw_io',
'recipe_engine/json',
'windows_adk',
'windows_scripts_executor',
]
PYTHON_VERSION_COMPATIBILITY = 'PY3'
PROPERTIES = wib.Image
def RunSteps(api, image):
""" This recipe executes offline_winpe_customization."""
if not api.platform.is_win:
raise AssertionError('This recipe can only run on windows')
# this recipe will only execute the offline winpe customizations
for cust in image.customizations:
assert (cust.WhichOneof('customization') == 'offline_winpe_customization')
# initialize the image to scripts executor
api.windows_scripts_executor.init()
custs = api.windows_scripts_executor.init_customizations(image)
# pinning all the refs and generating unique keys
custs = api.windows_scripts_executor.process_customizations(custs)
# download all the required refs
api.windows_scripts_executor.download_all_packages(custs)
# download and install the windows ADK and WinPE packages
api.windows_adk.ensure()
# execute the customizations given
api.windows_scripts_executor.execute_customizations(custs)
wpe_image = 'wpe_image'
wpe_cust = 'generic'
arch = 'x86'
key = '9055a3e678be47d58bb860d27b85adbea41fd2ef3e22c5b7cb3180edf358de90'
| 35.55102 | 80 | 0.705798 |
e0afd7d06dd45ec0003e8757b057e5c949b8d859 | 374 | py | Python | back/lollangCompiler/main.py | wonjinYi/lollang-playground | 2df07ccc2518e6dc9f9aa00b2f38ad8d62cdb507 | [
"MIT"
] | 11 | 2022-03-12T06:41:29.000Z | 2022-03-15T06:15:52.000Z | back/lollangCompiler/main.py | wonjinYi/lollang-playground | 2df07ccc2518e6dc9f9aa00b2f38ad8d62cdb507 | [
"MIT"
] | 4 | 2022-03-14T12:01:09.000Z | 2022-03-26T20:19:52.000Z | back/lollangCompiler/main.py | wonjinYi/lollang-playground | 2df07ccc2518e6dc9f9aa00b2f38ad8d62cdb507 | [
"MIT"
] | null | null | null | from lollangCompiler.compiler import Compiler
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--file", required=True, help=" .")
parser.add_argument("--out", default="out.py", help=" ")
args = parser.parse_args()
cmp = Compiler()
cmp.compileFile(args.file, args.out) | 37.4 | 78 | 0.708556 |
e0b07a325b5b8caffedac977ee80452502819e41 | 4,103 | py | Python | reproducing/generator_datacreation/data/readers/SEReader.py | UKPLab/emnlp2019-duplicate_question_detection | 17a9d97c2414666fcc08015a58619fe9722daf2b | [
"Apache-2.0"
] | 5 | 2019-09-30T11:09:39.000Z | 2020-07-17T07:32:17.000Z | reproducing/generator_datacreation/data/readers/SEReader.py | UKPLab/emnlp2019-duplicate_question_detection | 17a9d97c2414666fcc08015a58619fe9722daf2b | [
"Apache-2.0"
] | 1 | 2020-07-17T07:32:46.000Z | 2020-07-17T07:34:19.000Z | reproducing/generator_datacreation/data/readers/SEReader.py | UKPLab/emnlp2019-duplicate_question_detection | 17a9d97c2414666fcc08015a58619fe9722daf2b | [
"Apache-2.0"
] | 2 | 2020-04-09T01:27:50.000Z | 2022-03-12T07:53:15.000Z | import logging
import subprocess
import xml.etree.ElementTree as ET
from tqdm import tqdm
logger = logging.getLogger('root')
POST_TYPE_QUESTION = '1'
POST_TYPE_ANSWER = '2'
| 55.445946 | 1,284 | 0.604436 |
e0b0e0083223143424e08a5e2722940882568d5e | 2,174 | py | Python | src/add_2_zip_imports.py | goubertbrent/oca-backend | b9f59cc02568aecb55d4b54aec05245790ea25fd | [
"Apache-2.0"
] | null | null | null | src/add_2_zip_imports.py | goubertbrent/oca-backend | b9f59cc02568aecb55d4b54aec05245790ea25fd | [
"Apache-2.0"
] | null | null | null | src/add_2_zip_imports.py | goubertbrent/oca-backend | b9f59cc02568aecb55d4b54aec05245790ea25fd | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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.
#
# @@license_version:1.7@@
from google.appengine.api import users as gusers
from mcfw.cache import CachedModelMixIn
from mcfw.consts import MISSING
from mcfw.restapi import register_postcall_hook, INJECTED_FUNCTIONS
from mcfw.rpc import serialize_value, get_type_details
from rogerthat.rpc import users
from rogerthat.utils import OFFLOAD_TYPE_WEB, offload
from rogerthat.utils.transactions import on_trans_committed
dummy = lambda: None
register_postcall_hook(log_restapi_call_result)
INJECTED_FUNCTIONS.get_current_session = users.get_current_session
del log_restapi_call_result
CachedModelMixIn.on_trans_committed = lambda self, f, *args, **kwargs: on_trans_committed(f, *args, **kwargs)
| 36.233333 | 117 | 0.731831 |
e0b1290a0ccf26bc0c338627492bdd788761baa7 | 8,396 | py | Python | lib/galaxy/model/migrate/versions/0026_cloud_tables.py | Galaxyinternship/Galaxy | 204be086a8c16d6684584cefa9053ed7c86a1784 | [
"CC-BY-3.0"
] | null | null | null | lib/galaxy/model/migrate/versions/0026_cloud_tables.py | Galaxyinternship/Galaxy | 204be086a8c16d6684584cefa9053ed7c86a1784 | [
"CC-BY-3.0"
] | null | null | null | lib/galaxy/model/migrate/versions/0026_cloud_tables.py | Galaxyinternship/Galaxy | 204be086a8c16d6684584cefa9053ed7c86a1784 | [
"CC-BY-3.0"
] | null | null | null | """
This script adds tables needed for Galaxy cloud functionality.
"""
from __future__ import print_function
import datetime
import logging
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, MetaData, Table, TEXT
now = datetime.datetime.utcnow
log = logging.getLogger( __name__ )
metadata = MetaData()
CloudImage_table = Table( "cloud_image", metadata,
Column( "id", Integer, primary_key=True ),
Column( "create_time", DateTime, default=now ),
Column( "update_time", DateTime, default=now, onupdate=now ),
Column( "provider_type", TEXT ),
Column( "image_id", TEXT, nullable=False ),
Column( "manifest", TEXT ),
Column( "state", TEXT ),
Column( "architecture", TEXT ),
Column( "deleted", Boolean, default=False ) )
""" UserConfiguredInstance (UCI) table """
UCI_table = Table( "cloud_uci", metadata,
Column( "id", Integer, primary_key=True ),
Column( "create_time", DateTime, default=now ),
Column( "update_time", DateTime, default=now, onupdate=now ),
Column( "user_id", Integer, ForeignKey( "galaxy_user.id" ), index=True, nullable=False ),
Column( "credentials_id", Integer, ForeignKey( "cloud_user_credentials.id" ), index=True ),
Column( "key_pair_name", TEXT ),
Column( "key_pair_material", TEXT ),
Column( "name", TEXT ),
Column( "state", TEXT ),
Column( "error", TEXT ),
Column( "total_size", Integer ),
Column( "launch_time", DateTime ),
Column( "deleted", Boolean, default=False ) )
CloudInstance_table = Table( "cloud_instance", metadata,
Column( "id", Integer, primary_key=True ),
Column( "create_time", DateTime, default=now ),
Column( "update_time", DateTime, default=now, onupdate=now ),
Column( "launch_time", DateTime ),
Column( "stop_time", DateTime ),
Column( "user_id", Integer, ForeignKey( "galaxy_user.id" ), index=True, nullable=False ),
Column( "uci_id", Integer, ForeignKey( "cloud_uci.id" ), index=True ),
Column( "type", TEXT ),
Column( "reservation_id", TEXT ),
Column( "instance_id", TEXT ),
Column( "mi_id", Integer, ForeignKey( "cloud_image.id" ), index=True ),
Column( "state", TEXT ),
Column( "error", TEXT ),
Column( "public_dns", TEXT ),
Column( "private_dns", TEXT ),
Column( "security_group", TEXT ),
Column( "availability_zone", TEXT ) )
CloudStore_table = Table( "cloud_store", metadata,
Column( "id", Integer, primary_key=True ),
Column( "create_time", DateTime, default=now ),
Column( "update_time", DateTime, default=now, onupdate=now ),
Column( "attach_time", DateTime ),
Column( "user_id", Integer, ForeignKey( "galaxy_user.id" ), index=True, nullable=False ),
Column( "uci_id", Integer, ForeignKey( "cloud_uci.id" ), index=True, nullable=False ),
Column( "volume_id", TEXT ),
Column( "size", Integer, nullable=False ),
Column( "availability_zone", TEXT ),
Column( "inst_id", Integer, ForeignKey( "cloud_instance.id" ) ),
Column( "status", TEXT ),
Column( "device", TEXT ),
Column( "space_consumed", Integer ),
Column( "error", TEXT ),
Column( "deleted", Boolean, default=False ) )
CloudSnapshot_table = Table( "cloud_snapshot", metadata,
Column( "id", Integer, primary_key=True ),
Column( "create_time", DateTime, default=now ),
Column( "update_time", DateTime, default=now, onupdate=now ),
Column( "user_id", Integer, ForeignKey( "galaxy_user.id" ), index=True, nullable=False ),
Column( "uci_id", Integer, ForeignKey( "cloud_uci.id" ), index=True ),
Column( "store_id", Integer, ForeignKey( "cloud_store.id" ), index=True, nullable=False ),
Column( "snapshot_id", TEXT ),
Column( "status", TEXT ),
Column( "description", TEXT ),
Column( "error", TEXT ),
Column( "deleted", Boolean, default=False ) )
CloudUserCredentials_table = Table( "cloud_user_credentials", metadata,
Column( "id", Integer, primary_key=True ),
Column( "create_time", DateTime, default=now ),
Column( "update_time", DateTime, default=now, onupdate=now ),
Column( "user_id", Integer, ForeignKey( "galaxy_user.id" ), index=True, nullable=False ),
Column( "provider_id", Integer, ForeignKey( "cloud_provider.id" ), index=True, nullable=False ),
Column( "name", TEXT ),
Column( "access_key", TEXT ),
Column( "secret_key", TEXT ),
Column( "deleted", Boolean, default=False ) )
CloudProvider_table = Table( "cloud_provider", metadata,
Column( "id", Integer, primary_key=True ),
Column( "create_time", DateTime, default=now ),
Column( "update_time", DateTime, default=now, onupdate=now ),
Column( "user_id", Integer, ForeignKey( "galaxy_user.id" ), index=True, nullable=False ),
Column( "type", TEXT, nullable=False ),
Column( "name", TEXT ),
Column( "region_connection", TEXT ),
Column( "region_name", TEXT ),
Column( "region_endpoint", TEXT ),
Column( "is_secure", Boolean ),
Column( "host", TEXT ),
Column( "port", Integer ),
Column( "proxy", TEXT ),
Column( "proxy_port", TEXT ),
Column( "proxy_user", TEXT ),
Column( "proxy_pass", TEXT ),
Column( "debug", Integer ),
Column( "https_connection_factory", TEXT ),
Column( "path", TEXT ),
Column( "deleted", Boolean, default=False ) )
| 54.167742 | 132 | 0.488328 |
e0b1b9a256ca71156990f5651aa970e6f745d293 | 1,524 | py | Python | apps/user/urls.py | mrf-foundation/ckios_v1 | 3556a99ba5e01f00e137fd124903ace77d2cba28 | [
"Apache-2.0"
] | null | null | null | apps/user/urls.py | mrf-foundation/ckios_v1 | 3556a99ba5e01f00e137fd124903ace77d2cba28 | [
"Apache-2.0"
] | null | null | null | apps/user/urls.py | mrf-foundation/ckios_v1 | 3556a99ba5e01f00e137fd124903ace77d2cba28 | [
"Apache-2.0"
] | null | null | null | # -*- encoding: utf-8 -*-
"""
Copyright (c) 2021 ronyman.com
"""
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from apps.user import views as user_views
from.views import EditProfilePage
urlpatterns = [
#User
path('admin/', admin.site.urls),
path('register/', user_views.register, name='register'),
path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'),
path('profile/', user_views.profile, name='profile'),
path('edit_profile/', user_views.edit_profile, name='edit_profile'),
path("myprofile/", user_views.myprofile, name="Myprofile"),
path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
#path('tinymce/', include('tinymce.urls')),
path('edit_profile_page/', user_views.EditProfilePage.as_view(template_name='registration/edit_profile_page.html'), name='edit_profile_page'),
# For PasswordPresset
path('admin/password_reset/',auth_views.PasswordResetView.as_view(),name='admin_password_reset',),
path('admin/password_reset/done/',auth_views.PasswordResetDoneView.as_view(),name='password_reset_done',),
path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(),name='password_reset_confirm',),
path('reset/done/',auth_views.PasswordResetCompleteView.as_view(),name='password_reset_complete',),
] | 47.625 | 146 | 0.75 |
e0b36f9e11e7c9c01752718dbe837832a4596d2c | 533 | py | Python | sra_django_api/user/migrations/0003_auto_20180914_1242.py | tflati/ncbi-search | 2f31c57ffb95c2c874b65c03c58edd96eb822dfb | [
"MIT"
] | null | null | null | sra_django_api/user/migrations/0003_auto_20180914_1242.py | tflati/ncbi-search | 2f31c57ffb95c2c874b65c03c58edd96eb822dfb | [
"MIT"
] | null | null | null | sra_django_api/user/migrations/0003_auto_20180914_1242.py | tflati/ncbi-search | 2f31c57ffb95c2c874b65c03c58edd96eb822dfb | [
"MIT"
] | null | null | null | # Generated by Django 2.0.3 on 2018-09-14 12:42
from django.db import migrations, models
| 22.208333 | 58 | 0.572233 |
e0b5c736d3e79ca55e6b015bca8f2bcfa9bec4d1 | 30,844 | py | Python | image_misc.py | frankgh/deep-visualization-toolbox | c9bb26eacae0b4d1a25d3844538c2830026add76 | [
"MIT"
] | null | null | null | image_misc.py | frankgh/deep-visualization-toolbox | c9bb26eacae0b4d1a25d3844538c2830026add76 | [
"MIT"
] | null | null | null | image_misc.py | frankgh/deep-visualization-toolbox | c9bb26eacae0b4d1a25d3844538c2830026add76 | [
"MIT"
] | null | null | null | #! /usr/bin/env python
import cv2
import matplotlib.pyplot as plt
import skimage
import skimage.io
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.pyplot import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
from numpy import arange, array, newaxis, tile, linspace, pad, expand_dims, \
fromstring, ceil, dtype, float32, sqrt, dot, zeros
from misc import WithTimer
def norm01c(arr, center):
'''Maps the input range to [0,1] such that the center value maps to .5'''
arr = arr.copy()
arr -= center
arr /= max(2 * arr.max(), -2 * arr.min()) + 1e-10
arr += .5
assert arr.min() >= 0
assert arr.max() <= 1
return arr
def norm0255(arr):
'''Maps the input range to [0,255] as dtype uint8'''
arr = arr.copy()
arr -= arr.min()
arr *= 255.0 / (arr.max() + 1e-10)
arr = array(arr, 'uint8')
return arr
def cv2_read_file_rgb(filename):
'''Reads an image from file. Always returns (x,y,3)'''
im = cv2.imread(filename)
if len(im.shape) == 2:
# Upconvert single channel grayscale to color
im = im[:, :, newaxis]
if im.shape[2] == 1:
im = tile(im, (1, 1, 3))
if im.shape[2] > 3:
# Chop off transparency
im = im[:, :, :3]
return cv2.cvtColor(im, cv2.COLOR_BGR2RGB) # Convert native OpenCV BGR -> RGB
def caffe_load_image(filename, color=True, as_uint=False):
'''
Copied from Caffe to simplify potential import problems.
Load an image converting from grayscale or alpha as needed.
Take
filename: string
color: flag for color format. True (default) loads as RGB while False
loads as intensity (if image is already grayscale).
Give
image: an image with type float32 in range [0, 1]
of size (H x W x 3) in RGB or
of size (H x W x 1) in grayscale.
'''
with WithTimer('imread', quiet=True):
if as_uint:
img = skimage.io.imread(filename)
else:
img = skimage.img_as_float(skimage.io.imread(filename)).astype(float32)
if img.ndim == 2:
img = img[:, :, newaxis]
if color:
img = tile(img, (1, 1, 3))
elif img.shape[2] == 4:
img = img[:, :, :3]
return img
def get_tiles_height_width(n_tiles, desired_width=None):
'''Get a height x width size that will fit n_tiles tiles.'''
if desired_width == None:
# square
width = int(ceil(sqrt(n_tiles)))
height = width
else:
assert isinstance(desired_width, int)
width = desired_width
height = int(ceil(float(n_tiles) / width))
return height, width
def get_tiles_height_width_ratio(n_tiles, width_ratio=1.0):
'''Get a height x width size that will fit n_tiles tiles.'''
width = int(ceil(sqrt(n_tiles * width_ratio)))
return get_tiles_height_width(n_tiles, desired_width=width)
def to_255(vals_01):
'''Convert vals in [0,1] to [0,255]'''
try:
ret = [v * 255 for v in vals_01]
if type(vals_01) is tuple:
return tuple(ret)
else:
return ret
except TypeError:
# Not iterable (single int or float)
return vals_01 * 255
def ensure_uint255(arr):
'''If data is float, multiply by 255 and convert to uint8. Else leave as uint8.'''
if arr.dtype == 'uint8':
return arr
elif arr.dtype in ('float32', 'float64'):
# print 'extra check...'
# assert arr.max() <= 1.1
return array(arr * 255, dtype='uint8')
else:
raise Exception('ensure_uint255 expects uint8 or float input but got %s with range [%g,%g,].' % (
arr.dtype, arr.min(), arr.max()))
def ensure_float01(arr, dtype_preference='float32'):
'''If data is uint, convert to float and divide by 255. Else leave at float.'''
if arr.dtype == 'uint8':
# print 'extra check...'
# assert arr.max() <= 256
return array(arr, dtype=dtype_preference) / 255
elif arr.dtype in ('float32', 'float64'):
return arr
else:
raise Exception('ensure_float01 expects uint8 or float input but got %s with range [%g,%g,].' % (
arr.dtype, arr.min(), arr.max()))
def resize_to_fit(img, out_max_shape,
dtype_out=None,
shrink_interpolation=cv2.INTER_LINEAR,
grow_interpolation=cv2.INTER_NEAREST):
'''Resizes to fit within out_max_shape. If ratio is different,
returns an image that fits but is smaller along one of the two
dimensions.
If one of the out_max_shape dimensions is None, then use only the other dimension to perform resizing.
Timing info on MBP Retina with OpenBlas:
- conclusion: uint8 is always tied or faster. float64 is slower.
Scaling down:
In [79]: timeit.Timer('resize_to_fit(aa, (200,200))', setup='from kerasvis.app import resize_to_fit; import numpy as np; aa = array(np.random.uniform(0,255,(1000,1000,3)), dtype="uint8")').timeit(100)
Out[79]: 0.04950380325317383
In [77]: timeit.Timer('resize_to_fit(aa, (200,200))', setup='from kerasvis.app import resize_to_fit; import numpy as np; aa = array(np.random.uniform(0,255,(1000,1000,3)), dtype="float32")').timeit(100)
Out[77]: 0.049156904220581055
In [76]: timeit.Timer('resize_to_fit(aa, (200,200))', setup='from kerasvis.app import resize_to_fit; import numpy as np; aa = array(np.random.uniform(0,255,(1000,1000,3)), dtype="float64")').timeit(100)
Out[76]: 0.11808204650878906
Scaling up:
In [68]: timeit.Timer('resize_to_fit(aa, (2000,2000))', setup='from kerasvis.app import resize_to_fit; import numpy as np; aa = array(np.random.uniform(0,255,(1000,1000,3)), dtype="uint8")').timeit(100)
Out[68]: 0.4357950687408447
In [70]: timeit.Timer('resize_to_fit(aa, (2000,2000))', setup='from kerasvis.app import resize_to_fit; import numpy as np; aa = array(np.random.uniform(0,255,(1000,1000,3)), dtype="float32")').timeit(100)
Out[70]: 1.3411099910736084
In [73]: timeit.Timer('resize_to_fit(aa, (2000,2000))', setup='from kerasvis.app import resize_to_fit; import numpy as np; aa = array(np.random.uniform(0,255,(1000,1000,3)), dtype="float64")').timeit(100)
Out[73]: 2.6078310012817383
'''
if dtype_out is not None and img.dtype != dtype_out:
dtype_in_size = img.dtype.itemsize
dtype_out_size = dtype(dtype_out).itemsize
convert_early = (dtype_out_size < dtype_in_size)
convert_late = not convert_early
else:
convert_early = False
convert_late = False
if img.shape[0] == 0 and img.shape[1] == 0:
scale = 1
elif out_max_shape[0] is None or img.shape[0] == 0:
scale = float(out_max_shape[1]) / img.shape[1]
elif out_max_shape[1] is None or img.shape[1] == 0:
scale = float(out_max_shape[0]) / img.shape[0]
else:
scale = min(float(out_max_shape[0]) / img.shape[0],
float(out_max_shape[1]) / img.shape[1])
if convert_early:
img = array(img, dtype=dtype_out)
out = cv2.resize(img,
(int(img.shape[1] * scale), int(img.shape[0] * scale)), # in (c,r) order
interpolation=grow_interpolation if scale > 1 else shrink_interpolation)
if convert_late:
out = array(out, dtype=dtype_out)
return out
def cv2_typeset_text(data, lines, loc, between=' ', string_spacing=0, line_spacing=0, wrap=False):
'''Typesets mutliple strings on multiple lines of text, where each string may have its own formatting.
Given:
data: as in cv2.putText
loc: as in cv2.putText
lines: list of lists of FormattedString objects, may be modified by this function!
between: what to insert between each string on each line, ala str.join
string_spacing: extra spacing to insert between strings on a line
line_spacing: extra spacing to insert between lines
wrap: if true, wraps words to next line
Returns:
locy: new y location = loc[1] + y-offset resulting from lines of text
'''
data_width = data.shape[1]
# lines_modified = False
# lines = lines_in # will be deepcopied if modification is needed later
if isinstance(lines, FormattedString):
lines = [lines]
assert isinstance(lines,
list), 'lines must be a list of lines or list of FormattedString objects or a single FormattedString object'
if len(lines) == 0:
return loc[1]
if not isinstance(lines[0], list):
# If a single line of text is given as a list of strings, convert to multiline format
lines = [lines]
locy = loc[1]
line_num = 0
while line_num < len(lines):
line = lines[line_num]
maxy = 0
locx = loc[0]
for ii, fs in enumerate(line):
last_on_line = (ii == len(line) - 1)
if not last_on_line:
fs.string += between
boxsize, _ = cv2.getTextSize(fs.string, fs.face, fs.fsize, fs.thick)
if fs.width is not None:
if fs.align == 'right':
locx += fs.width - boxsize[0]
elif fs.align == 'center':
locx += (fs.width - boxsize[0]) / 2
# print 'right boundary is', locx + boxsize[0], '(%s)' % fs.string
# print 'HERE'
right_edge = locx + boxsize[0]
if wrap and ii > 0 and right_edge > data_width:
# Wrap rest of line to the next line
# if not lines_modified:
# lines = deepcopy(lines_in)
# lines_modified = True
new_this_line = line[:ii]
new_next_line = line[ii:]
lines[line_num] = new_this_line
lines.insert(line_num + 1, new_next_line)
break
###line_num += 1
###continue
cv2.putText(data, fs.string, (locx, locy), fs.face, fs.fsize, fs.clr, fs.thick)
maxy = max(maxy, boxsize[1])
if fs.width is not None:
if fs.align == 'right':
locx += boxsize[0]
elif fs.align == 'left':
locx += fs.width
elif fs.align == 'center':
locx += fs.width - (fs.width - boxsize[0]) / 2
else:
locx += boxsize[0]
locx += string_spacing
line_num += 1
locy += maxy + line_spacing
return locy
def saveimage(filename, im):
'''Saves an image with pixel values in [0,1]'''
# matplotlib.image.imsave(filename, im)
if len(im.shape) == 3:
# Reverse RGB to OpenCV BGR order for color images
cv2.imwrite(filename, 255 * im[:, :, ::-1])
else:
cv2.imwrite(filename, 255 * im)
| 34.617284 | 208 | 0.57191 |
e0b6b0833654d657edf6b38b5e343a5dbb47c6d9 | 825 | py | Python | text.py | Kedyn/PingPong | 47e39a9d30e1a3a7b828c5b5e85b0666d67b0d7b | [
"MIT"
] | null | null | null | text.py | Kedyn/PingPong | 47e39a9d30e1a3a7b828c5b5e85b0666d67b0d7b | [
"MIT"
] | null | null | null | text.py | Kedyn/PingPong | 47e39a9d30e1a3a7b828c5b5e85b0666d67b0d7b | [
"MIT"
] | null | null | null | import pygame.font
import copy
| 27.5 | 76 | 0.604848 |
e0b78d074db83725adcb792c0532db942f29eb42 | 5,702 | py | Python | py/test/selenium/webdriver/common/window_tests.py | ey-advisory-technology-testing/selenium | 7e342d3b8eb913a9626475a158c4bc6ae5d68315 | [
"Apache-2.0"
] | 1 | 2020-10-06T16:55:46.000Z | 2020-10-06T16:55:46.000Z | py/test/selenium/webdriver/common/window_tests.py | ey-advisory-technology-testing/selenium | 7e342d3b8eb913a9626475a158c4bc6ae5d68315 | [
"Apache-2.0"
] | 2 | 2020-10-12T13:27:19.000Z | 2020-10-12T15:32:45.000Z | py/test/selenium/webdriver/common/window_tests.py | ey-advisory-technology-testing/selenium | 7e342d3b8eb913a9626475a158c4bc6ae5d68315 | [
"Apache-2.0"
] | 1 | 2019-03-18T14:38:08.000Z | 2019-03-18T14:38:08.000Z | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import os
import pytest
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.support.wait import WebDriverWait
# @pytest.mark.xfail_ie
# @pytest.mark.xfail_chromiumedge(reason="Fails on Travis")
# @pytest.mark.xfail_firefox(reason="Fails on Travis")
# @pytest.mark.xfail_remote(reason="Fails on Travis")
# def testShouldMaximizeTheWindow(driver):
# resize_timeout = 5
# wait = WebDriverWait(driver, resize_timeout)
# old_size = driver.get_window_size()
# driver.set_window_size(200, 200)
# wait.until(
# lambda dr: dr.get_window_size() != old_size if old_size["width"] != 200 and old_size["height"] != 200 else True)
# size = driver.get_window_size()
# driver.maximize_window()
# wait.until(lambda dr: dr.get_window_size() != size)
# new_size = driver.get_window_size()
# assert new_size["width"] > size["width"]
# assert new_size["height"] > size["height"]
# @pytest.mark.xfail_safari(raises=WebDriverException,
# reason='Fullscreen command not implemented')
# @pytest.mark.skipif(os.environ.get('TRAVIS') == 'true',
# reason='Fullscreen command causes Travis to hang')
# @pytest.mark.no_driver_after_test
# def test_should_fullscreen_the_current_window(driver):
# start_width = driver.execute_script('return window.innerWidth;')
# start_height = driver.execute_script('return window.innerHeight;')
# driver.fullscreen_window()
# WebDriverWait(driver, 2)\
# .until(lambda d: driver.execute_script('return window.innerWidth;') > start_width)
# end_width = driver.execute_script('return window.innerWidth;')
# end_height = driver.execute_script('return window.innerHeight;')
# driver.quit() # Kill driver so we aren't running fullscreen after
# assert end_width > start_width
# assert end_height > start_height
# @pytest.mark.xfail_safari(raises=WebDriverException,
# reason='Minimize command not implemented')
# @pytest.mark.skipif(os.environ.get('TRAVIS') == 'true',
# reason='Minimize command causes Travis to hang')
# @pytest.mark.no_driver_after_test
# def test_should_minimize_the_current_window(driver):
# driver.minimize_window()
# minimized = driver.execute_script('return document.hidden;')
# driver.quit() # Kill driver so we aren't running minimized after
# assert minimized is True
| 38.268456 | 122 | 0.708699 |
e0b811e924c93fc02a9d9d5f223ad493413f5e6c | 21,307 | py | Python | psydac/cad/geometry.py | mayuri-dhote/psydac | 01ddbe2d049a599684c45060912d01c2658160a3 | [
"MIT"
] | 5 | 2018-03-13T13:50:26.000Z | 2018-12-22T14:04:11.000Z | psydac/cad/geometry.py | mayuri-dhote/psydac | 01ddbe2d049a599684c45060912d01c2658160a3 | [
"MIT"
] | 3 | 2019-02-08T13:29:47.000Z | 2019-03-06T17:23:08.000Z | psydac/cad/geometry.py | mayuri-dhote/psydac | 01ddbe2d049a599684c45060912d01c2658160a3 | [
"MIT"
] | 1 | 2018-12-15T09:55:12.000Z | 2018-12-15T09:55:12.000Z | # coding: utf-8
#
# a Geometry class contains the list of patches and additional information about
# the topology i.e. connectivity, boundaries
# For the moment, it is used as a container, that can be loaded from a file
# (hdf5)
from itertools import product
from collections import abc
import numpy as np
import string
import random
import h5py
import yaml
import os
import string
import random
from mpi4py import MPI
from psydac.fem.splines import SplineSpace
from psydac.fem.tensor import TensorFemSpace
from psydac.mapping.discrete import SplineMapping, NurbsMapping
from sympde.topology import Domain, Line, Square, Cube, NCubeInterior
from sympde.topology.basic import Union
#==============================================================================
def export( self, filename ):
"""
Parameters
----------
filename : str
Name of HDF5 output file.
"""
# ...
comm = self.comm
# ...
# Create dictionary with geometry metadata
yml = {}
yml['ldim'] = self.ldim
yml['pdim'] = self.pdim
# ... information about the patches
if not( self.mappings ):
raise ValueError('No mappings were found')
patches_info = []
i_mapping = 0
for patch_name, mapping in self.mappings.items():
name = '{}'.format( patch_name )
mapping_id = 'mapping_{}'.format( i_mapping )
dtype = '{}'.format( type( mapping ).__name__ )
patches_info += [{'name': name,
'mapping_id': mapping_id,
'type': dtype}]
i_mapping += 1
yml['patches'] = patches_info
# ...
# ... topology
topo_yml = self.domain.todict()
# ...
# Create HDF5 file (in parallel mode if MPI communicator size > 1)
if not(comm is None) and comm.size > 1:
kwargs = dict( driver='mpio', comm=comm )
else:
kwargs = {}
h5 = h5py.File( filename, mode='w', **kwargs )
# ...
# Dump geometry metadata to string in YAML file format
geo = yaml.dump( data = yml, sort_keys=False)
# Write geometry metadata as fixed-length array of ASCII characters
h5['geometry.yml'] = np.array( geo, dtype='S' )
# ...
# ...
# Dump geometry metadata to string in YAML file format
geo = yaml.dump( data = topo_yml, sort_keys=False)
# Write topology metadata as fixed-length array of ASCII characters
h5['topology.yml'] = np.array( geo, dtype='S' )
# ...
i_mapping = 0
for patch_name, mapping in self.mappings.items():
space = mapping.space
# Create group for patch 0
group = h5.create_group( yml['patches'][i_mapping]['mapping_id'] )
group.attrs['shape' ] = space.vector_space.npts
group.attrs['degree' ] = space.degree
group.attrs['rational' ] = False # TODO remove
group.attrs['periodic' ] = space.periodic
for d in range( self.ldim ):
group['knots_{}'.format( d )] = space.spaces[d].knots
# Collective: create dataset for control points
shape = [n for n in space.vector_space.npts] + [self.pdim]
dtype = space.vector_space.dtype
dset = group.create_dataset( 'points', shape=shape, dtype=dtype )
# Independent: write control points to dataset
starts = space.vector_space.starts
ends = space.vector_space.ends
index = [slice(s, e+1) for s, e in zip(starts, ends)] + [slice(None)]
index = tuple( index )
dset[index] = mapping.control_points[index]
# case of NURBS
if isinstance(mapping, NurbsMapping):
# Collective: create dataset for weights
shape = [n for n in space.vector_space.npts]
dtype = space.vector_space.dtype
dset = group.create_dataset( 'weights', shape=shape, dtype=dtype )
# Independent: write weights to dataset
starts = space.vector_space.starts
ends = space.vector_space.ends
index = [slice(s, e+1) for s, e in zip(starts, ends)]
index = tuple( index )
dset[index] = mapping.weights[index]
i_mapping += 1
# Close HDF5 file
h5.close()
#==============================================================================
def export_nurbs_to_hdf5(filename, nurbs, periodic=None, comm=None ):
"""
Export a single-patch igakit NURBS object to a Psydac geometry file in HDF5 format
Parameters
----------
filename : <str>
Name of output geometry file, e.g. 'geo.h5'
nurbs : <igakit.nurbs.NURBS>
igakit geometry nurbs object
comm : <MPI.COMM>
mpi communicator
"""
import os.path
import igakit
assert isinstance(nurbs, igakit.nurbs.NURBS)
extension = os.path.splitext(filename)[-1]
if not extension == '.h5':
raise ValueError('> Only h5 extension is allowed for filename')
yml = {}
yml['ldim'] = nurbs.dim
yml['pdim'] = nurbs.dim
patches_info = []
i_mapping = 0
i = 0
rational = not abs(nurbs.weights-1).sum()<1e-15
patch_name = 'patch_{}'.format(i)
name = '{}'.format( patch_name )
mapping_id = 'mapping_{}'.format( i_mapping )
dtype = 'NurbsMapping' if rational else 'SplineMapping'
patches_info += [{'name': name , 'mapping_id':mapping_id, 'type':dtype}]
yml['patches'] = patches_info
# ...
# Create HDF5 file (in parallel mode if MPI communicator size > 1)
if not(comm is None) and comm.size > 1:
kwargs = dict( driver='mpio', comm=comm )
else:
kwargs = {}
h5 = h5py.File( filename, mode='w', **kwargs )
# ...
# Dump geometry metadata to string in YAML file format
geom = yaml.dump( data = yml, sort_keys=False)
# Write geometry metadata as fixed-length array of ASCII characters
h5['geometry.yml'] = np.array( geom, dtype='S' )
# ...
# ... topology
if nurbs.dim == 1:
bounds1 = (float(nurbs.breaks(0)[0]), float(nurbs.breaks(0)[-1]))
domain = Line(patch_name, bounds1=bounds1)
elif nurbs.dim == 2:
bounds1 = (float(nurbs.breaks(0)[0]), float(nurbs.breaks(0)[-1]))
bounds2 = (float(nurbs.breaks(1)[0]), float(nurbs.breaks(1)[-1]))
domain = Square(patch_name, bounds1=bounds1, bounds2=bounds2)
elif nurbs.dim == 3:
bounds1 = (float(nurbs.breaks(0)[0]), float(nurbs.breaks(0)[-1]))
bounds2 = (float(nurbs.breaks(1)[0]), float(nurbs.breaks(1)[-1]))
bounds3 = (float(nurbs.breaks(2)[0]), float(nurbs.breaks(2)[-1]))
domain = Cube(patch_name, bounds1=bounds1, bounds2=bounds2, bounds3=bounds3)
topo_yml = domain.todict()
# Dump geometry metadata to string in YAML file format
geom = yaml.dump( data = topo_yml, sort_keys=False)
# Write topology metadata as fixed-length array of ASCII characters
h5['topology.yml'] = np.array( geom, dtype='S' )
group = h5.create_group( yml['patches'][i]['mapping_id'] )
group.attrs['degree' ] = nurbs.degree
group.attrs['rational' ] = rational
group.attrs['periodic' ] = tuple( False for d in range( nurbs.dim ) ) if periodic is None else periodic
for d in range( nurbs.dim ):
group['knots_{}'.format( d )] = nurbs.knots[d]
group['points'] = nurbs.points[...,:nurbs.dim]
if rational:
group['weights'] = nurbs.weights
h5.close()
#==============================================================================
def refine_nurbs(nrb, ncells=None, degree=None, multiplicity=None, tol=1e-9):
"""
This function refines the nurbs object.
It contructs a new grid based on the new number of cells, and it adds the new break points to the nrb grid,
such that the total number of cells is equal to the new number of cells.
We use knot insertion to construct the new knot sequence , so the geometry is identical to the previous one.
It also elevates the degree of the nrb object based on the new degree.
Parameters
----------
nrb : <igakit.nurbs.NURBS>
geometry nurbs object
ncells : <list>
total number of cells in each direction
degree : <list>
degree in each direction
multiplicity : <list>
multiplicity of each knot in the knot sequence in each direction
tol : <float>
Minimum distance between two break points.
Returns
-------
nrb : <igakit.nurbs.NURBS>
the refined geometry nurbs object
"""
if multiplicity is None:
multiplicity = [1]*nrb.dim
nrb = nrb.clone()
if ncells is not None:
for axis in range(0,nrb.dim):
ub = nrb.breaks(axis)[0]
ue = nrb.breaks(axis)[-1]
knots = np.linspace(ub,ue,ncells[axis]+1)
index = nrb.knots[axis].searchsorted(knots)
nrb_knots = nrb.knots[axis][index]
for m,(nrb_k, k) in enumerate(zip(nrb_knots, knots)):
if abs(k-nrb_k)<tol:
knots[m] = np.nan
knots = knots[~np.isnan(knots)]
indices = np.round(np.linspace(0, len(knots) - 1, ncells[axis]+1-len(nrb.breaks(axis)))).astype(int)
knots = knots[indices]
if len(knots)>0:
nrb.refine(axis, knots)
if degree is not None:
for axis in range(0,nrb.dim):
d = degree[axis] - nrb.degree[axis]
if d<0:
raise ValueError('The degree {} must be >= {}'.format(degree, nrb.degree))
nrb.elevate(axis, times=d)
for axis in range(nrb.dim):
decimals = abs(np.floor(np.log10(np.abs(tol))).astype(int))
knots, counts = np.unique(nrb.knots[axis].round(decimals=decimals), return_counts=True)
counts = multiplicity[axis] - counts
counts[counts<0] = 0
knots = np.repeat(knots, counts)
nrb = nrb.refine(axis, knots)
return nrb
def refine_knots(knots, ncells, degree, multiplicity=None, tol=1e-9):
"""
This function refines the knot sequence.
It contructs a new grid based on the new number of cells, and it adds the new break points to the nrb grid,
such that the total number of cells is equal to the new number of cells.
We use knot insertion to construct the new knot sequence , so the geometry is identical to the previous one.
It also elevates the degree of the nrb object based on the new degree.
Parameters
----------
knots : <list>
list of knot sequences in each direction
ncells : <list>
total number of cells in each direction
degree : <list>
degree in each direction
multiplicity : <list>
multiplicity of each knot in the knot sequence in each direction
tol : <float>
Minimum distance between two break points.
Returns
-------
knots : <list>
the refined knot sequences in each direction
"""
from igakit.nurbs import NURBS
dim = len(ncells)
if multiplicity is None:
multiplicity = [1]*dim
assert len(knots) == dim
nrb = NURBS(knots)
for axis in range(dim):
ub = nrb.breaks(axis)[0]
ue = nrb.breaks(axis)[-1]
knots = np.linspace(ub,ue,ncells[axis]+1)
index = nrb.knots[axis].searchsorted(knots)
nrb_knots = nrb.knots[axis][index]
for m,(nrb_k, k) in enumerate(zip(nrb_knots, knots)):
if abs(k-nrb_k)<tol:
knots[m] = np.nan
knots = knots[~np.isnan(knots)]
indices = np.round(np.linspace(0, len(knots) - 1, ncells[axis]+1-len(nrb.breaks(axis)))).astype(int)
knots = knots[indices]
if len(knots)>0:
nrb.refine(axis, knots)
for axis in range(dim):
d = degree[axis] - nrb.degree[axis]
if d<0:
raise ValueError('The degree {} must be >= {}'.format(degree, nrb.degree))
nrb.elevate(axis, times=d)
for axis in range(dim):
decimals = abs(np.floor(np.log10(np.abs(tol))).astype(int))
knots, counts = np.unique(nrb.knots[axis].round(decimals=decimals), return_counts=True)
counts = multiplicity[axis] - counts
counts[counts<0] = 0
knots = np.repeat(knots, counts)
nrb = nrb.refine(axis, knots)
return nrb.knots
#==============================================================================
def import_geopdes_to_nurbs(filename):
"""
This function reads a geopdes geometry file and convert it to igakit nurbs object
Parameters
----------
filename : <str>
the filename of the geometry file
Returns
-------
nrb : <igakit.nurbs.NURBS>
the geometry nurbs object
"""
extension = os.path.splitext(filename)[-1]
if not extension == '.txt':
raise ValueError('> Expected .txt extension')
f = open(filename)
lines = f.readlines()
f.close()
lines = [line for line in lines if line[0].strip() != "#"]
data = _read_header(lines[0])
n_dim = data[0]
r_dim = data[1]
n_patchs = data[2]
n_lines_per_patch = 3*n_dim + 1
list_begin_line = _get_begin_line(lines, n_patchs)
nrb = _read_patch(lines, 1, n_lines_per_patch, list_begin_line)
return nrb
| 31.659733 | 112 | 0.546487 |
e0b8df2c0cc835ac66fd2676a3d3a8a967b603f8 | 6,098 | py | Python | utils.py | ok1zjf/AMNet | 51b163eec63d6d1e2e3dbc140d19afdc7b4273ee | [
"MIT"
] | 40 | 2018-06-20T20:33:38.000Z | 2022-03-21T02:00:34.000Z | utils.py | RMSnow/AMNet-Rumor | 95321bb30a303994cfae769801207bbde91d77fb | [
"MIT"
] | 5 | 2018-07-26T17:23:07.000Z | 2020-05-05T15:30:18.000Z | utils.py | RMSnow/AMNet-Rumor | 95321bb30a303994cfae769801207bbde91d77fb | [
"MIT"
] | 10 | 2018-04-10T09:42:55.000Z | 2021-04-19T19:01:27.000Z | __author__ = 'Jiri Fajtl'
__email__ = 'ok1zjf@gmail.com'
__version__= '2.2'
__status__ = "Research"
__date__ = "28/1/2018"
__license__= "MIT License"
import os
import numpy as np
import glob
import subprocess
import platform
import sys
import pkg_resources
import torch
import PIL as Image
try:
import cv2
except:
print("WARNING: Could not load OpenCV python package. Some functionality may not be available.")
if __name__ == "__main__":
print_pkg_versions()
split_files = get_split_files('datasets/lamem', 'splits', 'test_*.txt')
print(split_files)
weight_files = get_weight_files(split_files, experiment_name='lamem_ResNet50FC_lstm3_last', max_rc_checkpoints=True)
# weight_files = get_weight_files(split_files, experiment_name='lamem_ResNet50FC_lstm3')
print(weight_files) | 30.49 | 120 | 0.611512 |
e0b92dd95f8f3eb4f67617f41703129b86326aae | 1,823 | py | Python | python/aghast/aghast_generated/Slice.py | HDembinski/aghast | f3d45a6960033f48fb8f6b7e906cb36b9d9d8e95 | [
"BSD-3-Clause"
] | 18 | 2019-04-15T14:39:35.000Z | 2021-12-21T15:01:02.000Z | python/aghast/aghast_generated/Slice.py | HDembinski/aghast | f3d45a6960033f48fb8f6b7e906cb36b9d9d8e95 | [
"BSD-3-Clause"
] | 27 | 2019-04-12T20:24:00.000Z | 2021-12-03T08:51:56.000Z | python/aghast/aghast_generated/Slice.py | diana-hep/stagg | ed97e9abc870e729d300622253aa7e9c870f77ec | [
"BSD-3-Clause"
] | 11 | 2019-04-15T14:41:00.000Z | 2021-11-16T13:28:10.000Z | # automatically generated by the FlatBuffers compiler, do not modify
# namespace: aghast_generated
import flatbuffers
| 26.808824 | 79 | 0.641251 |
e0b9af8b61e8657e680602511286b7396f0d35fe | 1,075 | py | Python | axelrod/tests/strategies/test_mystrategy.py | AleksaLuka/Axelrod | 5f2fefcb2bf8f371ef489382f90f116b46ac1023 | [
"MIT"
] | null | null | null | axelrod/tests/strategies/test_mystrategy.py | AleksaLuka/Axelrod | 5f2fefcb2bf8f371ef489382f90f116b46ac1023 | [
"MIT"
] | null | null | null | axelrod/tests/strategies/test_mystrategy.py | AleksaLuka/Axelrod | 5f2fefcb2bf8f371ef489382f90f116b46ac1023 | [
"MIT"
] | null | null | null | import axelrod as axl
from .test_player import TestPlayer
C, D = axl.Action.C, axl.Action.D
| 28.289474 | 71 | 0.563721 |
e0ba84d4c91d76772295ffa29072d6de02d1a1ae | 4,516 | py | Python | analyzer/BannerTool.py | Gr1ph00n/staticwebanalyzer | 8bf6337a77192b85913d75778830ccbb9006081f | [
"MIT"
] | null | null | null | analyzer/BannerTool.py | Gr1ph00n/staticwebanalyzer | 8bf6337a77192b85913d75778830ccbb9006081f | [
"MIT"
] | null | null | null | analyzer/BannerTool.py | Gr1ph00n/staticwebanalyzer | 8bf6337a77192b85913d75778830ccbb9006081f | [
"MIT"
] | null | null | null | #FILE NAME: BannerTool.py
#created by: Ciro Veneruso
#purpose: banner localization
#last edited by: Ciro Veneruso
#INSTALL: BeautifulSoup
#TODO: this code is a blob, must be refactorized!!!!
import re
import mechanize
import socket
import urllib
from tools import BaseTool
from bs4 import BeautifulSoup
from pprint import pprint
from ipwhois import IPWhois, WhoisLookupError
from tld import get_tld
import urlparse
from tld.exceptions import TldIOError, TldDomainNotFound, TldBadUrl
from tools import ToolException
| 31.802817 | 125 | 0.601639 |
e0bae7400e763d4fa86d93ab435117f871afbd18 | 49 | py | Python | rhea/build/toolflow/xilinx/__init__.py | meetps/rhea | f8a9a08fb5e14c5c4488ef68a2dff4d18222c2c0 | [
"MIT"
] | 1 | 2022-03-16T23:56:09.000Z | 2022-03-16T23:56:09.000Z | rhea/build/toolflow/xilinx/__init__.py | meetps/rhea | f8a9a08fb5e14c5c4488ef68a2dff4d18222c2c0 | [
"MIT"
] | null | null | null | rhea/build/toolflow/xilinx/__init__.py | meetps/rhea | f8a9a08fb5e14c5c4488ef68a2dff4d18222c2c0 | [
"MIT"
] | null | null | null |
from .ise import ISE
from .vivado import Vivado
| 12.25 | 26 | 0.77551 |
e0bb4548a5ce53a84a9faca646cafe6530aa2def | 12,725 | py | Python | app/AccountManagment.py | fredpan/Prosopagnosia_Web_Server | b56b58eccdbbde6b158802d49f7bcc1b44b18b69 | [
"Apache-2.0"
] | null | null | null | app/AccountManagment.py | fredpan/Prosopagnosia_Web_Server | b56b58eccdbbde6b158802d49f7bcc1b44b18b69 | [
"Apache-2.0"
] | null | null | null | app/AccountManagment.py | fredpan/Prosopagnosia_Web_Server | b56b58eccdbbde6b158802d49f7bcc1b44b18b69 | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 EraO Prosopagnosia Helper Dev Team, Liren Pan, Yixiao Hong, Hongzheng Xu, Stephen Huang, Tiancong Wang
#
# Supervised by Prof. Steve Mann (http://www.eecg.toronto.edu/~mann/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import datetime
import mysql.connector
import re
import time
from app.sql.config.DbConfig import db_config
from flask import render_template, redirect, url_for, request, g, session
from flask_bcrypt import Bcrypt
from app import EmailSender as email_confirmation
from app import webapp
validUsernameChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
# The function used to establish connection to sql database
def connect_to_database():
'''
Function used to connect to database
:return:
'''
return mysql.connector.connect(user=db_config['user'], password=db_config['password'], host=db_config['host'],
database=db_config['database'], use_pure=True)
def get_database():
'''
function used to get database
:return:
'''
db = getattr(g, '_database', None)
if db is None:
db = g._database = connect_to_database()
return db
"""
#############################################################
Login Settings
############################################################
"""
"""
#############################################################
Sign up Settings
############################################################
"""
# Display an empty HTML form that allows users to fill the info and sign up.
# Create a new account and save them in the database.
"""
#############################################################
Secure Index
############################################################
"""
"""
#############################################################
Send Email
############################################################
"""
# Create a new account and save them in the database.
| 41.9967 | 124 | 0.659018 |
e0bd2b8b9279c8dd18c9c1094fe6466b3d0d10be | 1,403 | py | Python | scripts/slice.py | priyablue/lidar_navigation | 39cd44a44043fa001c9d797ddea6c19e3376276c | [
"Apache-2.0"
] | 2 | 2017-12-19T16:16:50.000Z | 2018-03-15T12:41:03.000Z | scripts/slice.py | athenian-programming/lidar_navigation | 39cd44a44043fa001c9d797ddea6c19e3376276c | [
"Apache-2.0"
] | null | null | null | scripts/slice.py | athenian-programming/lidar_navigation | 39cd44a44043fa001c9d797ddea6c19e3376276c | [
"Apache-2.0"
] | 1 | 2021-05-08T11:27:10.000Z | 2021-05-08T11:27:10.000Z | import math
from point2d import Point2D
| 28.06 | 101 | 0.655025 |
e0be43ac7d66987096cd0a5bf59621233ca9d1a8 | 37,056 | py | Python | src/audio_korpora_pipeline/inputadapter/adapters.py | WernerDreier/audio-korpora-pipeline | ac171cdfb0663c7b6250c06cc9c70a951b908251 | [
"MIT"
] | 1 | 2020-09-11T05:27:58.000Z | 2020-09-11T05:27:58.000Z | src/audio_korpora_pipeline/inputadapter/adapters.py | WernerDreier/audio-korpora-pipeline | ac171cdfb0663c7b6250c06cc9c70a951b908251 | [
"MIT"
] | null | null | null | src/audio_korpora_pipeline/inputadapter/adapters.py | WernerDreier/audio-korpora-pipeline | ac171cdfb0663c7b6250c06cc9c70a951b908251 | [
"MIT"
] | null | null | null | import concurrent
import os
import re
import shutil
import xml.etree.ElementTree as ET # TODO do we have this as requirement?
from concurrent.futures import as_completed
from concurrent.futures._base import as_completed
from pathlib import Path
import ffmpeg
import pandas as pd
import webrtcvad
from audio_korpora_pipeline.baseobjects import FileHandlingObject
from audio_korpora_pipeline.inputadapter.audiosplit.splitter import Splitter
from audio_korpora_pipeline.metamodel.mediasession import MediaAnnotationBundle, \
MediaAnnotationBundleWithoutTranscription, WrittenResource, MediaFile, \
MediaSessionActor, Sex, \
MediaSessionActors, MediaSession
| 48.312907 | 152 | 0.725658 |
e0beee4ee459f085172a97b3c88ddde9059df51b | 14,085 | py | Python | development/multiImage_pytorch/experiment.py | anaikawadi/svbrdf-estimation | c977aa8448b2131af3960895afd1105d29e5484a | [
"MIT"
] | null | null | null | development/multiImage_pytorch/experiment.py | anaikawadi/svbrdf-estimation | c977aa8448b2131af3960895afd1105d29e5484a | [
"MIT"
] | null | null | null | development/multiImage_pytorch/experiment.py | anaikawadi/svbrdf-estimation | c977aa8448b2131af3960895afd1105d29e5484a | [
"MIT"
] | null | null | null | import matplotlib.pyplot as plt
import math
import shutil
import torch
from accelerate import Accelerator
from tensorboardX import SummaryWriter
from cli import parse_args
from dataset import SvbrdfDataset
from losses import MixedLoss, MixedLoss2, MixedLoss3
from models import MultiViewModel, SingleViewModel
from pathlib import Path
from persistence import Checkpoint
from renderers import LocalRenderer, RednerRenderer
import utils
import environment as env
import numpy as np
import sys
from PIL import Image
args = parse_args()
clean_training = args.mode == 'train' and args.retrain
# Load the checkpoint
checkpoint_dir = Path(args.model_dir)
checkpoint = Checkpoint()
if not clean_training:
checkpoint = Checkpoint.load(checkpoint_dir)
# Immediatly restore the arguments if we have a valid checkpoint
if checkpoint.is_valid():
args = checkpoint.restore_args(args)
# Make the result reproducible
utils.enable_deterministic_random_engine()
# Determine the device
accelerator = Accelerator()
device = accelerator.device
# Create the model
model = MultiViewModel(use_coords=args.use_coords).to(device)
if checkpoint.is_valid():
model = checkpoint.restore_model_state(model)
elif args.mode == 'test':
print("No model found in the model directory but it is required for testing.")
exit(1)
# TODO: Choose a random number for the used input image count if we are training and we don't request it to be fix (see fixImageNb for reference)
data = SvbrdfDataset(data_directory=args.input_dir,
image_size=args.image_size, scale_mode=args.scale_mode, input_image_count=args.image_count, used_input_image_count=args.used_image_count,
use_augmentation=True, mix_materials=args.mode == 'train',
no_svbrdf=args.no_svbrdf_input, is_linear=args.linear_input)
epoch_start = 0
# model.generator.delete()
# model = torch.nn.Sequential(
# *list(model.children())[:-8],
# )
# print(*list(model.parameters()))
if args.mode == 'train':
validation_split = 0.01
print("Using {:.2f} % of the data for validation".format(
round(validation_split * 100.0, 2)))
training_data, validation_data = torch.utils.data.random_split(data, [int(math.ceil(
len(data) * (1.0 - validation_split))), int(math.floor(len(data) * validation_split))])
print("Training samples: {:d}.".format(len(training_data)))
print("Validation samples: {:d}.".format(len(validation_data)))
training_dataloader = torch.utils.data.DataLoader(
training_data, batch_size=8, pin_memory=True, shuffle=True)
validation_dataloader = torch.utils.data.DataLoader(
validation_data, batch_size=8, pin_memory=True, shuffle=False)
batch_count = int(math.ceil(len(training_data) /
training_dataloader.batch_size))
# Train as many epochs as specified
epoch_end = args.epochs
print("Training from epoch {:d} to {:d}".format(epoch_start, epoch_end))
# Set up the optimizer
# TODO: Use betas=(0.5, 0.999)
L = torch.FloatTensor(5, 3).uniform_(0.2, 1.0)
L = L / torch.linalg.norm(L, ord=2, dim=-1, keepdim=True)
L[:, :2] = 2.0 * L[:, :2] - 1.0
V = torch.FloatTensor(1, 3).uniform_(0.2, 1.0)
V = V / torch.linalg.norm(V, ord=2, dim=-1, keepdim=True)
V[:, :2] = 2.0 * V[:, :2] - 1.0
scenes = env.generate_specific_scenes(5, L, L)
L.requires_grad = True
VIP = [L]
# V.requires_grad = True
optimizer = torch.optim.Adam(VIP, lr=0.1)
model, optimizer, training_dataloader, validation_dataloader = accelerator.prepare(
model, optimizer, training_dataloader, validation_dataloader)
# print("scene", scene.camera)
# TODO: Use scheduler if necessary
#scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min')
# Set up the loss
loss_renderer = LocalRenderer()
loss_function = MixedLoss2(loss_renderer, scenes)
# Setup statistics stuff
statistics_dir = checkpoint_dir / "logs"
if clean_training and statistics_dir.exists():
# Nuke the stats dir
shutil.rmtree(statistics_dir)
statistics_dir.mkdir(parents=True, exist_ok=True)
writer = SummaryWriter(str(statistics_dir.absolute()))
last_batch_inputs = None
# Clear checkpoint in order to free up some memory
checkpoint.purge()
lights = []
losses = []
for epoch in range(epoch_start, epoch_end):
for i, batch in enumerate(training_dataloader):
# Unique index of this batch
print("Ldet", (L.detach().numpy())[0])
lights.append(((L.detach().numpy())[0]).tolist())
scenes = env.generate_specific_scenes(5, L, L)
print("L", L)
# if(epoch_end - epoch < 3):
loss_function = MixedLoss2(loss_renderer, scenes)
# else:
# loss_function = MixedLoss2(loss_renderer, scene[0])
batch_index = epoch * batch_count + i
# Construct inputs
batch_inputs = batch["inputs"].to(device)
batch_svbrdf = batch["svbrdf"].to(device)
# Perform a step
optimizer.zero_grad()
outputs = model(batch_inputs)
print("batch_inputs", batch_inputs.size())
print("batch_svbrdfs", batch_svbrdf.size())
print("batch_outputs", outputs.size())
loss = loss_function(outputs, batch_svbrdf)
accelerator.backward(loss)
optimizer.step()
print("Epoch {:d}, Batch {:d}, loss: {:f}".format(
epoch, i + 1, loss.item()))
losses.append((epoch, loss.item()))
# Statistics
writer.add_scalar("loss", loss.item(), batch_index)
last_batch_inputs = batch_inputs
lights.append(((L.detach().numpy())[0]).tolist())
with open('/content/experiment1/losses/loss.txt', "w") as text_file:
text_file.write(str(losses))
print("lights1", lights)
# print(len(lights))
lights2 = []
for j in range(len(lights)):
if j%10 == 0:
lights2.append(lights[j])
# print("lights2", lights)
# l=np.array(lights)
l = np.array(lights2)
renderer = LocalRenderer()
rendered_scene = env.generate_specific_scenes(1, L.detach(), L.detach())
img = renderer.render(rendered_scene[0], batch_svbrdf[0])
fig = plt.figure(frameon=False)
# fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
# print("shape", img.size())
ax.imshow(img[0].detach().permute(1,2,0), aspect='auto')
fig.savefig('/content/experiment1/figures/render1.png')
img = renderer.render(rendered_scene[0], outputs[0])
fig = plt.figure(frameon=False)
# fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
# print("shape", img.size())
ax.imshow(img[0].detach().permute(1,2,0), aspect='auto')
fig.savefig('/content/experiment1/figures/render2.png')
# print("size", batch_inputs.size())
torch.add(L, 5)
print("L", L)
rendered_scene = env.generate_specific_scenes(1, L, L)
img = renderer.render(rendered_scene[0], batch_svbrdf[0])
fig = plt.figure(frameon=False)
# fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
# print("shape", img.size())
ax.imshow(img[0].detach().permute(1,2,0), aspect='auto')
fig.savefig('/content/experiment1/figures/render3.png')
print("size", batch_inputs[0][0].size())
img = batch_inputs[0][0]
fig = plt.figure(frameon=False)
# fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
# print("shape", img.size())
ax.imshow(img.detach().permute(1,2,0), aspect='auto')
fig.savefig('/content/experiment1/figures/render4.png')
print("size", batch_inputs[0][0].size())
normals, diffuse, roughness, specular = utils.unpack_svbrdf(outputs[0])
img = normals
fig = plt.figure(frameon=False)
# fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
# print("shape", img.size())
ax.imshow(img.detach().permute(1,2,0), aspect='auto')
fig.savefig('/content/experiment1/figures/output_normal.png')
img = diffuse
fig = plt.figure(frameon=False)
# fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
# print("shape", img.size())
ax.imshow(img.detach().permute(1,2,0), aspect='auto')
fig.savefig('/content/experiment1/figures/output_diffuse.png')
img = roughness
fig = plt.figure(frameon=False)
# fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
# print("shape", img.size())
ax.imshow(img.detach().permute(1,2,0), aspect='auto')
fig.savefig('/content/experiment1/figures/output_roughness.png')
img = specular
fig = plt.figure(frameon=False)
# fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
# print("shape", img.size())
ax.imshow(img.detach().permute(1,2,0), aspect='auto')
fig.savefig('/content/experiment1/figures/output_specular.png')
print("size", batch_inputs[0][0].size())
normals, diffuse, roughness, specular = utils.unpack_svbrdf(batch_svbrdf[0])
img = normals
fig = plt.figure(frameon=False)
# fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
# print("shape", img.size())
ax.imshow(img.detach().permute(1,2,0), aspect='auto')
fig.savefig('/content/experiment1/figures/target_normal.png')
img = diffuse
fig = plt.figure(frameon=False)
# fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
# print("shape", img.size())
ax.imshow(img.detach().permute(1,2,0), aspect='auto')
fig.savefig('/content/experiment1/figures/target_diffuse.png')
img = roughness
fig = plt.figure(frameon=False)
# fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
# print("shape", img.size())
ax.imshow(img.detach().permute(1,2,0), aspect='auto')
fig.savefig('/content/experiment1/figures/target_roughness.png')
img = specular
fig = plt.figure(frameon=False)
# fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
# print("shape", img.size())
ax.imshow(img.detach().permute(1,2,0), aspect='auto')
fig.savefig('/content/experiment1/figures/target_specular.png')
images = [Image.open(x) for x in ['/content/experiment1/figures/target_normal.png', '/content/experiment1/figures/target_diffuse.png', '/content/experiment1/figures/target_roughness.png', '/content/experiment1/figures/target_specular.png']]
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
new_im.paste(im, (x_offset,0))
x_offset += im.size[0]
new_im.save('/content/experiment1/figures/target_svbrdf.png')
images = [Image.open(x) for x in ['/content/experiment1/figures/output_normal.png', '/content/experiment1/figures/output_diffuse.png', '/content/experiment1/figures/output_roughness.png', '/content/experiment1/figures/output_specular.png']]
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
new_im.paste(im, (x_offset,0))
x_offset += im.size[0]
new_im.save('/content/experiment1/figures/output_svbrdf.png')
print("size", batch_inputs[0][0].size())
normals, diffuse, roughness, specular = utils.unpack_svbrdf(outputs[0])
img = normals
fig = plt.figure(frameon=False)
# fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
# print("shape", img.size())
ax.imshow(img.detach().permute(1,2,0), aspect='auto')
fig.savefig('/content/experiment1/figures/output_normal.png')
print("lights3", l)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.scatter([0.0], [0.0], [0.0], marker='o', c='r')
# v = V.detach().numpy()
ax.scatter(l[:,0], l[:,1], l[:,2], marker='.', c='g')
# ax.scatter(v[:,0], v[:,1], v[:,2], marker='^', c='b')
ax.set_xlim(-8, 8)
ax.set_ylim(-8, 8)
ax.set_zlim(-8., 8.)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# plt.show()
plt.savefig('/content/experiment1/figures/light.png')
plt.show()
# if epoch % args.save_frequency == 0:
# Checkpoint.save(checkpoint_dir, args, model, optimizer, epoch)
# if epoch % args.validation_frequency == 0 and len(validation_data) > 0:
# model.eval()
# val_loss = 0.0
# batch_count_val = 0
# for batch in validation_dataloader:
# # Construct inputs
# batch_inputs = batch["inputs"].to(device)
# batch_svbrdf = batch["svbrdf"].to(device)
# outputs = model(batch_inputs)
# val_loss += loss_function(outputs, batch_svbrdf).item()
# batch_count_val += 1
# val_loss /= batch_count_val
# print("Epoch {:d}, validation loss: {:f}".format(epoch, val_loss))
# writer.add_scalar("val_loss", val_loss, epoch * batch_count)
# model.train()
| 34.437653 | 244 | 0.637061 |
e0bfc9b4798ab097e11ab7694665e7ba80ac9336 | 220 | py | Python | src/rekognition_online_action_detection/engines/__init__.py | amazon-research/long-short-term-transformer | a425be4b52ab68fddd85c91d26571e4cdfe8379a | [
"Apache-2.0"
] | 52 | 2021-11-19T01:35:10.000Z | 2022-03-24T11:48:10.000Z | src/rekognition_online_action_detection/engines/__init__.py | amazon-research/long-short-term-transformer | a425be4b52ab68fddd85c91d26571e4cdfe8379a | [
"Apache-2.0"
] | 9 | 2021-11-24T18:50:13.000Z | 2022-03-10T05:13:53.000Z | src/rekognition_online_action_detection/engines/__init__.py | amazon-research/long-short-term-transformer | a425be4b52ab68fddd85c91d26571e4cdfe8379a | [
"Apache-2.0"
] | 8 | 2022-01-15T08:01:33.000Z | 2022-03-20T22:08:29.000Z | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
from .engines import do_train, do_inference
from .lstr.lstr_trainer import *
from .lstr.lstr_inference import *
| 31.428571 | 68 | 0.786364 |
e0c1de96552a87c4acd6be415b90d60425c9c9cb | 64,469 | py | Python | nuage_tempest_plugin/tests/api/test_nuage_ports.py | nuagenetworks/nuage-tempest-plugin | ac1bfb0709c7bbaf04017af3050fb3ed1ad1324a | [
"Apache-1.1"
] | 1 | 2021-01-03T01:47:51.000Z | 2021-01-03T01:47:51.000Z | nuage_tempest_plugin/tests/api/test_nuage_ports.py | nuagenetworks/nuage-tempest-plugin | ac1bfb0709c7bbaf04017af3050fb3ed1ad1324a | [
"Apache-1.1"
] | null | null | null | nuage_tempest_plugin/tests/api/test_nuage_ports.py | nuagenetworks/nuage-tempest-plugin | ac1bfb0709c7bbaf04017af3050fb3ed1ad1324a | [
"Apache-1.1"
] | 1 | 2020-10-16T12:04:39.000Z | 2020-10-16T12:04:39.000Z | # Copyright 2017 NOKIA
# All Rights Reserved.
from netaddr import IPNetwork
import testtools
from tempest.common import waiters
from tempest.lib import exceptions
from tempest.scenario import manager
from tempest.test import decorators
from nuage_tempest_plugin.lib.test.nuage_test import NuageAdminNetworksTest
from nuage_tempest_plugin.lib.test.nuage_test import NuageBaseTest
from nuage_tempest_plugin.lib.topology import Topology
from nuage_tempest_plugin.lib.utils import constants
from nuage_tempest_plugin.services.nuage_client import NuageRestClient
CONF = Topology.get_conf()
LOG = Topology.get_logger(__name__)
| 41.220588 | 79 | 0.560114 |
e0c1ea88aed755291844e1e991a6d2f5cdb34cdd | 8,924 | py | Python | advent_of_code/2019/11_space_police/aoc_2019_11.py | thanosa/coding-challenges | a10b0de51da076a4bcc798b4a3d5a08e29c5af01 | [
"MIT"
] | null | null | null | advent_of_code/2019/11_space_police/aoc_2019_11.py | thanosa/coding-challenges | a10b0de51da076a4bcc798b4a3d5a08e29c5af01 | [
"MIT"
] | null | null | null | advent_of_code/2019/11_space_police/aoc_2019_11.py | thanosa/coding-challenges | a10b0de51da076a4bcc798b4a3d5a08e29c5af01 | [
"MIT"
] | null | null | null | ''' Advent of code 2019 Day 11 - Space police '''
from typing import NamedTuple
from enum import Enum
INPUT_FILE=__file__.replace('.py', '.dat')
def run_robot(code: dict, start_on_white: bool = False) -> int:
DIRECTIONS_COUNT = 4
direction = Direction.UP
panels = {}
seen = set()
color = []
position = Point(0, 0)
if start_on_white:
panels[position] = 1
finished = False
brain = run_program(code, color)
while True:
try:
# Sense the color on the point. Default is black (0).
if position in panels:
color.append(panels[position])
else:
color.append(0)
paint = next(brain)
rotation = next(brain)
if paint == "" or rotation == "":
raise RuntimeError(f"Failed to read paint: {paint}, rotation: {rotation}")
# Paints the panel.
panels[position] = paint
# Keeps track of all visited points.
seen.add(position)
# Turn left (0) or right (1).
if rotation == 0:
direction = Direction((direction.value + 1) % DIRECTIONS_COUNT)
elif rotation == 1:
direction = Direction((direction.value - 1) % DIRECTIONS_COUNT)
# Move a step forward.
if direction == Direction.UP:
position = Point(position.X, position.Y - 1)
elif direction == Direction.LEFT:
position = Point(position.X - 1, position.Y)
elif direction == Direction.DOWN:
position = Point(position.X, position.Y + 1)
elif direction == Direction.RIGHT:
position = Point(position.X + 1, position.Y)
else:
raise RuntimeError(f"Wrong direction: {direction}")
except StopIteration:
return panels
# Read the input
with open(INPUT_FILE) as f:
input_dict = get_dict(list(map(int, f.read().strip().split(','))))
# Part 1 solution
panels_count = len(run_robot(input_dict))
print(f"Part 1: {panels_count}")
# Part 2 solution
panels = run_robot(input_dict, True)
print(f"Part 2:")
print_panels(panels)
| 29.647841 | 91 | 0.438256 |
e0c4cc4a632d487744596824e2338a9f0399ee17 | 814 | py | Python | nicos_mlz/mira/setups/mezeiflip.py | jkrueger1/nicos | 5f4ce66c312dedd78995f9d91e8a6e3c891b262b | [
"CC-BY-3.0",
"Apache-2.0",
"CC-BY-4.0"
] | 12 | 2019-11-06T15:40:36.000Z | 2022-01-01T16:23:00.000Z | nicos_mlz/mira/setups/mezeiflip.py | jkrueger1/nicos | 5f4ce66c312dedd78995f9d91e8a6e3c891b262b | [
"CC-BY-3.0",
"Apache-2.0",
"CC-BY-4.0"
] | 91 | 2020-08-18T09:20:26.000Z | 2022-02-01T11:07:14.000Z | nicos_mlz/mira/setups/mezeiflip.py | jkrueger1/nicos | 5f4ce66c312dedd78995f9d91e8a6e3c891b262b | [
"CC-BY-3.0",
"Apache-2.0",
"CC-BY-4.0"
] | 6 | 2020-01-11T10:52:30.000Z | 2022-02-25T12:35:23.000Z | description = 'Mezei spin flipper using TTI power supply'
group = 'optional'
tango_base = 'tango://miractrl.mira.frm2:10000/mira/'
devices = dict(
dct1 = device('nicos.devices.entangle.PowerSupply',
description = 'current in first channel of supply (flipper current)',
tangodevice = tango_base + 'tti1/out1',
timeout = 1,
precision = 0.01,
),
dct2 = device('nicos.devices.entangle.PowerSupply',
description = 'current in second channel of supply (compensation current)',
tangodevice = tango_base + 'tti1/out2',
timeout = 1,
precision = 0.01,
),
flip = device('nicos.devices.polarized.MezeiFlipper',
description = 'Mezei flipper before sample (in shielding table)',
flip = 'dct1',
corr = 'dct2',
),
)
| 32.56 | 83 | 0.63145 |
e0c51c1373dbb36d56025f69dde451b4d208bab8 | 16,817 | py | Python | mars/learn/cluster/_k_means_init.py | hxri/mars | f7864f00911883b94800b63856f0e57648d3d9b4 | [
"Apache-2.0"
] | 2,413 | 2018-12-06T09:37:11.000Z | 2022-03-30T15:47:39.000Z | mars/learn/cluster/_k_means_init.py | hxri/mars | f7864f00911883b94800b63856f0e57648d3d9b4 | [
"Apache-2.0"
] | 1,335 | 2018-12-07T03:06:18.000Z | 2022-03-31T11:45:57.000Z | mars/learn/cluster/_k_means_init.py | hxri/mars | f7864f00911883b94800b63856f0e57648d3d9b4 | [
"Apache-2.0"
] | 329 | 2018-12-07T03:12:41.000Z | 2022-03-29T21:49:57.000Z | # Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
from ... import opcodes
from ... import tensor as mt
from ...core import OutputType, recursive_tile
from ...core.operand import OperandStage
from ...serialization.serializables import KeyField, Int32Field
from ...tensor.array_utils import as_same_device, device
from ...tensor.core import TensorOrder
from ...tensor.random import RandomStateField
from ...utils import has_unknown_shape
from ..metrics import euclidean_distances
from ..operands import LearnOperand, LearnOperandMixin
###############################################################################
# Initialization heuristic
def _k_init(X, n_clusters, x_squared_norms, random_state, n_local_trials=None):
"""Init n_clusters seeds according to k-means++
Parameters
----------
X : array or sparse matrix, shape (n_samples, n_features)
The data to pick seeds for. To avoid memory copy, the input data
should be double precision (dtype=np.float64).
n_clusters : integer
The number of seeds to choose
x_squared_norms : array, shape (n_samples,)
Squared Euclidean norm of each data point.
random_state : int, RandomState instance
The generator used to initialize the centers. Use an int to make the
randomness deterministic.
See :term:`Glossary <random_state>`.
n_local_trials : integer, optional
The number of seeding trials for each center (except the first),
of which the one reducing inertia the most is greedily chosen.
Set to None to make the number of trials depend logarithmically
on the number of seeds (2+log(k)); this is the default.
Notes
-----
Selects initial cluster centers for k-mean clustering in a smart way
to speed up convergence. see: Arthur, D. and Vassilvitskii, S.
"k-means++: the advantages of careful seeding". ACM-SIAM symposium
on Discrete algorithms. 2007
Version ported from http://www.stanford.edu/~darthur/kMeansppTest.zip,
which is the implementation used in the aforementioned paper.
"""
op = KMeansPlusPlusInit(x=X, n_clusters=n_clusters, x_squared_norms=x_squared_norms,
state=random_state, n_local_trials=n_local_trials)
return op()
| 37.288248 | 94 | 0.634477 |
e0c54a43da9d2d5736bbbaf25b05dc7746829f11 | 2,157 | py | Python | wikipedia_parser/infobox/wikitext_parser.py | ojones/wikipedia_parser | db548290fbc392299bba8adfda9fe18baa1e66fe | [
"MIT"
] | 9 | 2016-02-24T20:09:26.000Z | 2019-03-10T11:33:34.000Z | wikipedia_parser/infobox/wikitext_parser.py | ojones/wikipedia_parser | db548290fbc392299bba8adfda9fe18baa1e66fe | [
"MIT"
] | 1 | 2019-02-13T17:38:50.000Z | 2019-02-13T17:38:50.000Z | wikipedia_parser/infobox/wikitext_parser.py | ojones/wikipedia_parser | db548290fbc392299bba8adfda9fe18baa1e66fe | [
"MIT"
] | 1 | 2016-04-05T05:28:51.000Z | 2016-04-05T05:28:51.000Z | import re
from wikipedia_parser.infobox import clean_text as clean_help
from wikipedia_parser.infobox import wikitext_helpers as wtext_help
from wikipedia_parser.third_party_adapters import parserfromhell_adapter as adapter
__author__ = 'oswaldjones'
| 30.380282 | 90 | 0.592953 |
e0c5b44a98d273699a00386bb7674bf23a762723 | 227 | py | Python | sandbox/lib/jumpscale/JumpscaleLibs/clients/graphql/GraphQLFactory.py | threefoldtech/threebot_prebuilt | 1f0e1c65c14cef079cd80f73927d7c8318755c48 | [
"Apache-2.0"
] | null | null | null | sandbox/lib/jumpscale/JumpscaleLibs/clients/graphql/GraphQLFactory.py | threefoldtech/threebot_prebuilt | 1f0e1c65c14cef079cd80f73927d7c8318755c48 | [
"Apache-2.0"
] | 117 | 2019-09-01T11:59:19.000Z | 2020-07-14T11:10:08.000Z | sandbox/lib/jumpscale/JumpscaleLibs/clients/graphql/GraphQLFactory.py | threefoldtech/threebot_prebuilt | 1f0e1c65c14cef079cd80f73927d7c8318755c48 | [
"Apache-2.0"
] | 2 | 2020-04-06T15:21:23.000Z | 2020-05-07T04:29:53.000Z | from .GraphQLClient import GraphQLClient
from Jumpscale import j
JSConfigs = j.baseclasses.object_config_collection
| 18.916667 | 50 | 0.801762 |
e0c98eb51566d8d4d1edda624372a00af1731e11 | 1,339 | py | Python | src/video_transcoding/defaults.py | tumb1er/django-video-transcoding | 54c85fb4a3b58b3f3b82e461b2f54f3c8dd5fcc6 | [
"MIT"
] | 21 | 2020-02-07T17:40:16.000Z | 2021-09-02T18:56:21.000Z | src/video_transcoding/defaults.py | just-work/django-video-transcoding | c88d88de8301cd65eda95db941d72028aac57aa9 | [
"MIT"
] | 184 | 2020-02-09T10:46:17.000Z | 2022-03-28T00:53:04.000Z | src/video_transcoding/defaults.py | just-work/django-video-transcoding | c88d88de8301cd65eda95db941d72028aac57aa9 | [
"MIT"
] | 6 | 2020-02-07T13:58:33.000Z | 2021-07-27T16:24:56.000Z | from os import getenv as e
from kombu import Queue
CELERY_APP_NAME = 'video_transcoding'
VIDEO_TRANSCODING_CELERY_CONF = {
'broker_url': e('VIDEO_TRANSCODING_CELERY_BROKER_URL',
'amqp://guest:guest@rabbitmq:5672/'),
'result_backend': e('VIDEO_TRANSCODING_CELERY_RESULT_BACKEND', None),
'task_default_exchange': CELERY_APP_NAME,
'task_default_exchange_type': 'topic',
'task_default_queue': CELERY_APP_NAME,
'worker_prefetch_multiplier': 1,
'worker_concurrency': e('VIDEO_TRANSCODING_CELERY_CONCURRENCY'),
'task_acks_late': True,
'task_reject_on_worker_lost': True,
'task_queues': [
Queue(CELERY_APP_NAME, routing_key=CELERY_APP_NAME),
]
}
# Directory for large output files
VIDEO_TEMP_DIR = '/tmp'
# Download source before processing
VIDEO_DOWNLOAD_SOURCE = bool(int(e('VIDEO_DOWNLOAD_SOURCE', 0)))
# A list of WebDAV endpoints for storing video results
VIDEO_ORIGINS = e('VIDEO_ORIGINS',
'http://storage.localhost:8080/videos/').split(',')
# Video streamer public urls (comma-separated)
VIDEO_EDGES = e('VIDEO_EDGES', 'http://storage.localhost:8080/').split(',')
# Edge video manifest url template
VIDEO_URL = '{edge}/hls/{filename}1080p.mp4/index.m3u8'
# Output source files checksum
CHECKSUM_SOURCE = bool(int(e('CHECKSUM_SOURCE', 0)))
| 31.139535 | 75 | 0.726662 |
e0c9c572e013959cc1791ab9408e2433e6b096c4 | 5,104 | py | Python | wordSenseByContext.py | jmboettcher/fall2019_sentiment_in_alternative_words | d88fd0ed7d1396bb3755431d6aff85b880ffe149 | [
"Apache-2.0"
] | null | null | null | wordSenseByContext.py | jmboettcher/fall2019_sentiment_in_alternative_words | d88fd0ed7d1396bb3755431d6aff85b880ffe149 | [
"Apache-2.0"
] | null | null | null | wordSenseByContext.py | jmboettcher/fall2019_sentiment_in_alternative_words | d88fd0ed7d1396bb3755431d6aff85b880ffe149 | [
"Apache-2.0"
] | null | null | null | from collections import defaultdict
from nltk.tokenize import sent_tokenize
from nltk.corpus import wordnet as wn
from nltk.corpus import semcor as sc
from nltk.corpus import stopwords
import mywordtokenizer
"""===================================================================
Place all function calls below the following conditional so that they
are called only if this module is called with
`python ling278_assign02.py`
No functions should execute if it is instead imported with
import ling278_assign02
in the interactive shell.
"""
if __name__ == '__main__':
pass
| 36.985507 | 125 | 0.587187 |
e0c9fc5ceee51e40ba7758705226014b71dd06d7 | 3,138 | py | Python | paymentmethods/stripejs/tests.py | tjwalch/django-restshop | 569b57a5694e76a365556d7c4c9a97dd293d96c6 | [
"MIT"
] | null | null | null | paymentmethods/stripejs/tests.py | tjwalch/django-restshop | 569b57a5694e76a365556d7c4c9a97dd293d96c6 | [
"MIT"
] | null | null | null | paymentmethods/stripejs/tests.py | tjwalch/django-restshop | 569b57a5694e76a365556d7c4c9a97dd293d96c6 | [
"MIT"
] | null | null | null | import decimal
from unittest import mock
from django.conf import settings
from django.test import modify_settings
from rest_framework import test
from rest_framework.reverse import reverse
import stripe
from restshop import serializers
from restshop.models import Order
from paymentmethods.stripejs.models import StripeInvoice
import restshop.exceptions
from restshop.tests.test_product import products_and_price
| 31.069307 | 78 | 0.593372 |
e0cbddbdfa807e2e3192b9b0f5e91d704ca43fe7 | 1,684 | py | Python | tnnt/uniqdeaths.py | tnnt-devteam/python-backend | 1ecb0ddaccf176726739b64212831d038a7463a0 | [
"MIT"
] | null | null | null | tnnt/uniqdeaths.py | tnnt-devteam/python-backend | 1ecb0ddaccf176726739b64212831d038a7463a0 | [
"MIT"
] | 10 | 2021-07-19T13:04:20.000Z | 2021-12-02T18:36:29.000Z | tnnt/uniqdeaths.py | tnnt-devteam/python-backend | 1ecb0ddaccf176726739b64212831d038a7463a0 | [
"MIT"
] | 1 | 2021-10-17T10:36:51.000Z | 2021-10-17T10:36:51.000Z | from tnnt.settings import UNIQUE_DEATH_REJECTIONS, UNIQUE_DEATH_NORMALIZATIONS
import re
# post 2021 TODO: showing unique deaths of a player or clan:
# 1. list(Game.objects.values_list('death', 'player__name', 'endtime'))
# 2. iterate through list, filtering any death for which reject is True, and
# normalizing all death strings.
# 3. sort by first death, then endtime.
# 4. filter again by taking only the first player/endtime for each death and
# ignoring later ones.
| 42.1 | 80 | 0.726841 |
e0cbe510c57f6be47472391d90b71a872f267467 | 9,887 | py | Python | qutip/graph.py | anubhavvardhan/qutip | daf384840efbb44b86e39d8bda64d907d9f6b47f | [
"BSD-3-Clause"
] | null | null | null | qutip/graph.py | anubhavvardhan/qutip | daf384840efbb44b86e39d8bda64d907d9f6b47f | [
"BSD-3-Clause"
] | null | null | null | qutip/graph.py | anubhavvardhan/qutip | daf384840efbb44b86e39d8bda64d907d9f6b47f | [
"BSD-3-Clause"
] | null | null | null | # This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names
# of its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
"""
This module contains a collection of graph theory routines used mainly
to reorder matrices for iterative steady state solvers.
"""
__all__ = ['graph_degree', 'column_permutation', 'breadth_first_search',
'reverse_cuthill_mckee', 'maximum_bipartite_matching',
'weighted_bipartite_matching']
import numpy as np
import scipy.sparse as sp
from qutip.cy.graph_utils import (
_breadth_first_search, _node_degrees,
_reverse_cuthill_mckee, _maximum_bipartite_matching,
_weighted_bipartite_matching)
def graph_degree(A):
"""
Returns the degree for the nodes (rows) of a symmetric
graph in sparse CSR or CSC format, or a qobj.
Parameters
----------
A : qobj, csr_matrix, csc_matrix
Input quantum object or csr_matrix.
Returns
-------
degree : array
Array of integers giving the degree for each node (row).
"""
if not (sp.isspmatrix_csc(A) or sp.isspmatrix_csr(A)):
raise TypeError('Input must be CSC or CSR sparse matrix.')
return _node_degrees(A.indices, A.indptr, A.shape[0])
def breadth_first_search(A, start):
"""
Breadth-First-Search (BFS) of a graph in CSR or CSC matrix format starting
from a given node (row). Takes Qobjs and CSR or CSC matrices as inputs.
This function requires a matrix with symmetric structure.
Use A+trans(A) if original matrix is not symmetric or not sure.
Parameters
----------
A : csc_matrix, csr_matrix
Input graph in CSC or CSR matrix format
start : int
Staring node for BFS traversal.
Returns
-------
order : array
Order in which nodes are traversed from starting node.
levels : array
Level of the nodes in the order that they are traversed.
"""
if not (sp.isspmatrix_csc(A) or sp.isspmatrix_csr(A)):
raise TypeError('Input must be CSC or CSR sparse matrix.')
num_rows = A.shape[0]
start = int(start)
order, levels = _breadth_first_search(A.indices, A.indptr, num_rows, start)
# since maybe not all nodes are in search, check for unused entires in
# arrays
return order[order != -1], levels[levels != -1]
def column_permutation(A):
"""
Finds the non-symmetric column permutation of A such that the columns
are given in ascending order according to the number of nonzero entries.
This is sometimes useful for decreasing the fill-in of sparse LU
factorization.
Parameters
----------
A : csc_matrix
Input sparse CSC sparse matrix.
Returns
-------
perm : array
Array of permuted row and column indices.
"""
if not sp.isspmatrix_csc(A):
A = sp.csc_matrix(A)
count = np.diff(A.indptr)
perm = np.argsort(count)
return perm
def reverse_cuthill_mckee(A, sym=False):
"""
Returns the permutation array that orders a sparse CSR or CSC matrix
in Reverse-Cuthill McKee ordering. Since the input matrix must be
symmetric, this routine works on the matrix A+Trans(A) if the sym flag is
set to False (Default).
It is assumed by default (*sym=False*) that the input matrix is not
symmetric. This is because it is faster to do A+Trans(A) than it is to
check for symmetry for a generic matrix. If you are guaranteed that the
matrix is symmetric in structure (values of matrix element do not matter)
then set *sym=True*
Parameters
----------
A : csc_matrix, csr_matrix
Input sparse CSC or CSR sparse matrix format.
sym : bool {False, True}
Flag to set whether input matrix is symmetric.
Returns
-------
perm : array
Array of permuted row and column indices.
Notes
-----
This routine is used primarily for internal reordering of Lindblad
superoperators for use in iterative solver routines.
References
----------
E. Cuthill and J. McKee, "Reducing the Bandwidth of Sparse Symmetric
Matrices", ACM '69 Proceedings of the 1969 24th national conference,
(1969).
"""
if not (sp.isspmatrix_csc(A) or sp.isspmatrix_csr(A)):
raise TypeError('Input must be CSC or CSR sparse matrix.')
nrows = A.shape[0]
if not sym:
A = A + A.transpose()
return _reverse_cuthill_mckee(A.indices, A.indptr, nrows)
def maximum_bipartite_matching(A, perm_type='row'):
"""
Returns an array of row or column permutations that removes nonzero
elements from the diagonal of a nonsingular square CSC sparse matrix. Such
a permutation is always possible provided that the matrix is nonsingular.
This function looks at the structure of the matrix only.
The input matrix will be converted to CSC matrix format if
necessary.
Parameters
----------
A : sparse matrix
Input matrix
perm_type : str {'row', 'column'}
Type of permutation to generate.
Returns
-------
perm : array
Array of row or column permutations.
Notes
-----
This function relies on a maximum cardinality bipartite matching algorithm
based on a breadth-first search (BFS) of the underlying graph[1]_.
References
----------
I. S. Duff, K. Kaya, and B. Ucar, "Design, Implementation, and
Analysis of Maximum Transversal Algorithms", ACM Trans. Math. Softw.
38, no. 2, (2011).
"""
nrows = A.shape[0]
if A.shape[0] != A.shape[1]:
raise ValueError(
'Maximum bipartite matching requires a square matrix.')
if sp.isspmatrix_csr(A) or sp.isspmatrix_coo(A):
A = A.tocsc()
elif not sp.isspmatrix_csc(A):
raise TypeError("matrix must be in CSC, CSR, or COO format.")
if perm_type == 'column':
A = A.transpose().tocsc()
perm = _maximum_bipartite_matching(A.indices, A.indptr, nrows)
if np.any(perm == -1):
raise Exception('Possibly singular input matrix.')
return perm
def weighted_bipartite_matching(A, perm_type='row'):
"""
Returns an array of row permutations that attempts to maximize
the product of the ABS values of the diagonal elements in
a nonsingular square CSC sparse matrix. Such a permutation is
always possible provided that the matrix is nonsingular.
This function looks at both the structure and ABS values of the
underlying matrix.
Parameters
----------
A : csc_matrix
Input matrix
perm_type : str {'row', 'column'}
Type of permutation to generate.
Returns
-------
perm : array
Array of row or column permutations.
Notes
-----
This function uses a weighted maximum cardinality bipartite matching
algorithm based on breadth-first search (BFS). The columns are weighted
according to the element of max ABS value in the associated rows and
are traversed in descending order by weight. When performing the BFS
traversal, the row associated to a given column is the one with maximum
weight. Unlike other techniques[1]_, this algorithm does not guarantee the
product of the diagonal is maximized. However, this limitation is offset
by the substantially faster runtime of this method.
References
----------
I. S. Duff and J. Koster, "The design and use of algorithms for
permuting large entries to the diagonal of sparse matrices", SIAM J.
Matrix Anal. and Applics. 20, no. 4, 889 (1997).
"""
nrows = A.shape[0]
if A.shape[0] != A.shape[1]:
raise ValueError('weighted_bfs_matching requires a square matrix.')
if sp.isspmatrix_csr(A) or sp.isspmatrix_coo(A):
A = A.tocsc()
elif not sp.isspmatrix_csc(A):
raise TypeError("matrix must be in CSC, CSR, or COO format.")
if perm_type == 'column':
A = A.transpose().tocsc()
perm = _weighted_bipartite_matching(
np.asarray(np.abs(A.data), dtype=float),
A.indices, A.indptr, nrows)
if np.any(perm == -1):
raise Exception('Possibly singular input matrix.')
return perm
| 33.402027 | 79 | 0.670982 |
e0ccb86ce9db729b21b4c70f3e21fc86885bf209 | 83 | py | Python | test/source_dir/comments_blank_lines_code.py | Pierre-Thibault/neo-insert-imports | c20399d5666b2c3590be7f40c8be1130343bbadc | [
"MIT"
] | 1 | 2015-05-07T02:44:52.000Z | 2015-05-07T02:44:52.000Z | test/source_dir/comments_blank_lines_code.py | Pierre-Thibault/neo-insert-imports | c20399d5666b2c3590be7f40c8be1130343bbadc | [
"MIT"
] | null | null | null | test/source_dir/comments_blank_lines_code.py | Pierre-Thibault/neo-insert-imports | c20399d5666b2c3590be7f40c8be1130343bbadc | [
"MIT"
] | null | null | null | # comments------------------
if True:
a(10) | 10.375 | 28 | 0.337349 |
e0cd77f1011874355803f2699f0949c70a877b16 | 286 | py | Python | locan/data/hulls/__init__.py | super-resolution/Locan | 94ed7759f7d7ceddee7c7feaabff80010cfedf30 | [
"BSD-3-Clause"
] | 8 | 2021-11-25T20:05:49.000Z | 2022-03-27T17:45:00.000Z | locan/data/hulls/__init__.py | super-resolution/Locan | 94ed7759f7d7ceddee7c7feaabff80010cfedf30 | [
"BSD-3-Clause"
] | 4 | 2021-12-15T22:39:20.000Z | 2022-03-11T17:35:34.000Z | locan/data/hulls/__init__.py | super-resolution/Locan | 94ed7759f7d7ceddee7c7feaabff80010cfedf30 | [
"BSD-3-Clause"
] | 1 | 2022-03-22T19:53:13.000Z | 2022-03-22T19:53:13.000Z | """
Hull objects of localization data.
Submodules:
-----------
.. autosummary::
:toctree: ./
hull
alpha_shape
"""
from locan.data.hulls.alpha_shape import *
from locan.data.hulls.hull import *
__all__ = []
__all__.extend(hull.__all__)
__all__.extend(alpha_shape.__all__)
| 13.619048 | 42 | 0.688811 |
e0cde222a5f5dbe6545c933dad99fd36f05f5531 | 9,183 | py | Python | tests/test_workflow_build_combinations.py | tschoonj/cgat-daisy | f85a2c82ca04f352aad00660cfc14a9aa6773168 | [
"MIT"
] | 1 | 2020-06-29T14:39:42.000Z | 2020-06-29T14:39:42.000Z | tests/test_workflow_build_combinations.py | tschoonj/cgat-daisy | f85a2c82ca04f352aad00660cfc14a9aa6773168 | [
"MIT"
] | 1 | 2019-05-15T20:50:37.000Z | 2019-05-15T20:50:37.000Z | tests/test_workflow_build_combinations.py | tschoonj/cgat-daisy | f85a2c82ca04f352aad00660cfc14a9aa6773168 | [
"MIT"
] | 1 | 2021-11-11T13:22:56.000Z | 2021-11-11T13:22:56.000Z | import pytest
from daisy.workflow import build_combinations
| 38.746835 | 92 | 0.516607 |
e0d0af5cc2acc44430f9c71988996b1fd3a8a91a | 8,473 | py | Python | src/train_vae.py | katnoria/world-models | 6584f35fa9508c991050ddc9c17f5862a00008fe | [
"Apache-2.0"
] | null | null | null | src/train_vae.py | katnoria/world-models | 6584f35fa9508c991050ddc9c17f5862a00008fe | [
"Apache-2.0"
] | null | null | null | src/train_vae.py | katnoria/world-models | 6584f35fa9508c991050ddc9c17f5862a00008fe | [
"Apache-2.0"
] | null | null | null | # class Encoder:
# pass
# class Decoder:
# pass
# class VariationAutoEncoder:
# pass
import os
os.environ['CUDA_VISIBLE_DEVICES'] = "0"
import pickle
import logging
from glob import glob
import numpy as np
from time import time
from datetime import datetime
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import tensorflow as tf
import tensorflow.keras.backend as K
from tensorflow import keras
if not os.path.exists("logs"):
os.makedirs("logs")
today = datetime.now().strftime('%Y%m%d')
logger = logging.getLogger('worldmodels')
logger.setLevel(logging.DEBUG)
# Create logger
logger = logging.getLogger("worldmodels")
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
logger.setLevel(logging.DEBUG)
# Uncomment to enable console logger
streamhandler = logging.StreamHandler()
streamhandler.setFormatter(formatter)
streamhandler.setLevel(logging.DEBUG)
logger.addHandler(streamhandler)
filehandler = logging.FileHandler(filename='logs/dataset.{}.log'.format(today))
filehandler.setFormatter(formatter)
filehandler.setLevel(logging.DEBUG)
logger.addHandler(filehandler)
AUTOTUNE = tf.data.experimental.AUTOTUNE
INPUT_SHAPE = (64,64,3)
# INPUT_SHAPE = (128,128,3)
LATENT_DIM = 32
encoder_input = keras.Input(shape=(INPUT_SHAPE), name='encoder_input_image')
x = keras.layers.Conv2D(32, 4, strides=(2,2), activation='relu', name='conv-1')(encoder_input)
x = keras.layers.Conv2D(64, 4, strides=(2,2), activation='relu', name='conv-2')(x)
x = keras.layers.Conv2D(128, 4, strides=(2,2), activation='relu', name='conv-3')(x)
x = keras.layers.Conv2D(256, 4, strides=(2,2), activation='relu', name='conv-4')(x)
# x = keras.layers.Conv2D(512, 4, strides=(2,2), activation='relu', name='conv-5')(x)
encoder_last_conv_shape = K.int_shape(x)[1:]
logger.info("encoder_last_conv_shape: {}".format(encoder_last_conv_shape))
x = keras.layers.Flatten()(x)
mu = keras.layers.Dense(LATENT_DIM, activation='linear', name="mean")(x)
logvar = keras.layers.Dense(LATENT_DIM, activation='linear', name="variance")(x)
encoder = keras.Model(encoder_input, [mu, logvar], name='encoder')
encoder.summary()
sampled_latent_vector = keras.layers.Lambda(sample)([mu, logvar])
decoder_input = keras.layers.Input(shape=K.int_shape(sampled_latent_vector)[1:], name='decoder_input')
x = keras.layers.Dense(np.prod(encoder_last_conv_shape))(decoder_input)
x = keras.layers.Reshape((1,1,np.prod(encoder_last_conv_shape)))(x)
x = keras.layers.Conv2DTranspose(128, kernel_size=5, strides=(2,2), activation='relu')(x)
x = keras.layers.Conv2DTranspose(64, kernel_size=5, strides=(2,2), activation='relu')(x)
x = keras.layers.Conv2DTranspose(32, kernel_size=6, strides=(2,2), activation='relu')(x)
# x = keras.layers.Conv2DTranspose(32, kernel_size=4, strides=(2,2), activation='relu')(x)
decoder_output = keras.layers.Conv2DTranspose(3, kernel_size=6, strides=(2,2))(x)
decoder = keras.Model(decoder_input, decoder_output, name='decoder')
decoder.summary()
# Taken from tensorflow VAE example
def train(fnames, output_dirname="output", epochs=600, save_every_pct=0.3, print_every_pct=0.05):
logger.info('Total files: {}'.format(len(fnames)))
path_ds = tf.data.Dataset.from_tensor_slices(fnames)
image_ds = path_ds.map(load_preprocess_image, num_parallel_calls=AUTOTUNE)
# Dataset
BATCH_SIZE = 64
SHUFFLE_BUFFER_SIZE = len(fnames)
train_dataset = image_ds \
.shuffle(SHUFFLE_BUFFER_SIZE) \
.repeat() \
.batch(BATCH_SIZE) \
.prefetch(buffer_size=AUTOTUNE)
if not os.path.exists(output_dirname):
os.makedirs('{}/ckpt'.format(output_dirname))
os.makedirs('{}/imgs'.format(output_dirname))
# Number of training epochs
# EPOCHS = 600
logger.info('Training epochs: {}'.format(epochs))
# Initialize the Variational Autoencoder model
model = VAE(encoder, decoder)
# Define optimizer
optimizer = keras.optimizers.Adam(1e-4)
# keep track of losses
losses = []
# How often to print the loss
print_every = max(int(print_every_pct * epochs), 1)
# Model Checkpoint
# Save model and optimizer
ckpt = tf.train.Checkpoint(optimizer=optimizer, model=model)
# Set save path and how many checkpoints to save
checkpoint_path = '{}/ckpt/'.format(output_dirname)
logger.info('Checkpoints will be stored at {}'.format(checkpoint_path))
manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=2)
# Load the latest checkpoint and restore
latest_ckpt = manager.latest_checkpoint
ckpt.restore(latest_ckpt)
if latest_ckpt:
logger.info('Restored from {}'.format(latest_ckpt))
else:
logger.info('Training from scratch')
# How often to save the checkpoint
save_every = max(int(save_every_pct * epochs), 1)
# We are now ready to start the training loop
elapsed_loop_time = time()
for epoch in range(0, epochs):
for train_x in train_dataset:
loss = train_step(train_x, model, optimizer)
losses.append(loss)
if epoch % print_every == 0:
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
logger.info('{}:Epoch {}/{}: train loss {} in {} seconds'.format(epoch, epochs, losses[-1], time()-elapsed_loop_time))
elapsed_loop_time = time()
if epoch % save_every == 0:
save_path = manager.save()
logger.info('Saved checkpoint for step {}:{}'.format(epoch, save_path))
# Final Save
save_path = manager.save()
logger.info('Saved checkpoint for step {}'.format(save_path))
if __name__ == "__main__":
# Toons
# fnames = glob('{}/*.png'.format("/mnt/bigdrive/datasets/cartoonset/cartoonset10k/"))
# train(fnames, output_dirname="toons128")
# Car racing
fnames = glob('{}/*.png'.format("/mnt/bigdrive/projects/public_repos/world-models/src/imgs/"))
train(fnames, output_dirname="car_racing")
| 36.521552 | 130 | 0.690901 |
e0d2d2e5b75b0d0e7b995b20657ba25ef18190ee | 1,351 | py | Python | login.py | harryzcy/canvas-file-syncer | 16b98ee164df8570605b1a274c02f0dc7403730e | [
"MIT"
] | null | null | null | login.py | harryzcy/canvas-file-syncer | 16b98ee164df8570605b1a274c02f0dc7403730e | [
"MIT"
] | null | null | null | login.py | harryzcy/canvas-file-syncer | 16b98ee164df8570605b1a274c02f0dc7403730e | [
"MIT"
] | null | null | null | import time
from config import get_password, get_username
from playwright.sync_api import Page
| 29.369565 | 78 | 0.635085 |