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
e0d3c8c44e9a78dfdefd3d78c0e47b2746c32032
5,233
py
Python
multitidal/client_lib.py
xa4a/multitidal
26f757f12464e8f935c0389c6356b97cfaa9f03f
[ "MIT" ]
2
2021-12-01T05:39:05.000Z
2021-12-07T07:26:16.000Z
multitidal/client_lib.py
xa4a/multitidal
26f757f12464e8f935c0389c6356b97cfaa9f03f
[ "MIT" ]
1
2021-12-02T03:54:16.000Z
2021-12-02T03:54:16.000Z
multitidal/client_lib.py
parabolala/multitidal
26f757f12464e8f935c0389c6356b97cfaa9f03f
[ "MIT" ]
null
null
null
import asyncio import json import os import pty import shutil import sys import tty import termios import time import threading import tornado.iostream from tornado.ioloop import IOLoop from tornado.websocket import websocket_connect ioloop = tornado.ioloop.IOLoop.instance() SSH_LOGIN = "root" SSH_PASSWORD = "algorave" SCREEN_TO_SCREEN_0_SEQ = b"ls -l\r\x1bOC" + b"\x010" # ^A 0 class Client: mode: str
28.911602
73
0.549016
e0d3e0406d466ee1eb3c15b25d95347feecab756
1,265
py
Python
custom_components/ge_home/entities/common/ge_water_heater.py
olds/ha_gehome
5cb24deab64bcade45861da0497a84631845922c
[ "MIT" ]
41
2021-08-02T02:15:54.000Z
2022-03-30T11:11:42.000Z
custom_components/ge_home/entities/common/ge_water_heater.py
olds/ha_gehome
5cb24deab64bcade45861da0497a84631845922c
[ "MIT" ]
46
2021-08-03T02:20:59.000Z
2022-03-30T11:17:15.000Z
custom_components/ge_home/entities/common/ge_water_heater.py
olds/ha_gehome
5cb24deab64bcade45861da0497a84631845922c
[ "MIT" ]
15
2021-08-31T00:21:33.000Z
2022-03-30T12:53:21.000Z
import abc import logging from typing import Any, Dict, List, Optional from homeassistant.components.water_heater import WaterHeaterEntity from homeassistant.const import ( TEMP_FAHRENHEIT, TEMP_CELSIUS ) from gehomesdk import ErdCode, ErdMeasurementUnits from ...const import DOMAIN from .ge_erd_entity import GeEntity _LOGGER = logging.getLogger(__name__)
28.111111
83
0.728854
e0d425874c7577ffb290b5d9bb87cc599dbdcb1a
2,790
py
Python
scrapy/contracts/default.py
zyuchuan/scrapy
ce24f53957b41877319a5ffc6cf26f0a18baaec2
[ "BSD-3-Clause" ]
null
null
null
scrapy/contracts/default.py
zyuchuan/scrapy
ce24f53957b41877319a5ffc6cf26f0a18baaec2
[ "BSD-3-Clause" ]
null
null
null
scrapy/contracts/default.py
zyuchuan/scrapy
ce24f53957b41877319a5ffc6cf26f0a18baaec2
[ "BSD-3-Clause" ]
null
null
null
import json from scrapy.item import BaseItem from scrapy.http import Request from scrapy.exceptions import ContractFail from scrapy.contracts import Contract # contracts
26.074766
70
0.576344
e0d53d1eacb61e87932581de548a87b7c4071732
3,258
py
Python
networks/metrics.py
pabloduque0/cnn_deconv_viz
3fc3d8a9dbad8e8e28d4df4023bdb438e4c9cf85
[ "MIT" ]
null
null
null
networks/metrics.py
pabloduque0/cnn_deconv_viz
3fc3d8a9dbad8e8e28d4df4023bdb438e4c9cf85
[ "MIT" ]
null
null
null
networks/metrics.py
pabloduque0/cnn_deconv_viz
3fc3d8a9dbad8e8e28d4df4023bdb438e4c9cf85
[ "MIT" ]
null
null
null
from keras import backend as K import tensorflow as tf import numpy as np custom_dice_coef = custom_dice_coefficient custom_dice_loss = custom_dice_coefficient_loss dice_coef = dice_coefficient dice_coef_loss = dice_coefficient_loss weighted_crossentropy = weighted_crossentropy_pixelwise predicted_count = prediction_count predicted_sum = prediction_sum ground_truth_count = label_count ground_truth_sum = label_sum pixel_recall = segmentation_recall obj_recall = lession_recall
30.448598
126
0.736648
e0d6966f0f4824c8705c24412698017423279002
2,193
py
Python
scrapy_template/scrapy_template/pipelines.py
kk0501/spider
404540a76922885f9dd12f9a513f5ec88b0d2072
[ "MIT" ]
null
null
null
scrapy_template/scrapy_template/pipelines.py
kk0501/spider
404540a76922885f9dd12f9a513f5ec88b0d2072
[ "MIT" ]
null
null
null
scrapy_template/scrapy_template/pipelines.py
kk0501/spider
404540a76922885f9dd12f9a513f5ec88b0d2072
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapy.exceptions import DropItem from hashlib import md5 from scrapy import log from twisted.enterprise import adbapi from scrapy_template.items import ScrapyTemplateItem
34.265625
85
0.579115
e0d7c84ced6a300c631d0fec1f9dd425ca8e581c
2,726
py
Python
run_training_size_bootstrap.py
willferreira/multilabel-stance-detection
ddc0ed9caa26b63f40e89a377f1738e83fcb7724
[ "MIT" ]
null
null
null
run_training_size_bootstrap.py
willferreira/multilabel-stance-detection
ddc0ed9caa26b63f40e89a377f1738e83fcb7724
[ "MIT" ]
null
null
null
run_training_size_bootstrap.py
willferreira/multilabel-stance-detection
ddc0ed9caa26b63f40e89a377f1738e83fcb7724
[ "MIT" ]
null
null
null
import click import pickle import numpy as np from collections import defaultdict from utils import reset_seeds, get_dataset, load_embeddings from mlp_multilabel_wrapper import PowersetKerasWrapper, MultiOutputKerasWrapper from mlp_utils import CrossLabelDependencyLoss if __name__ == '__main__': run()
41.938462
104
0.705796
e0d8a4edfd7425e0db4ca0bd8268ff4b94c0916a
1,268
py
Python
code/evaluate.py
Shuailong/CCGSupertagging
891a6a477a4a05daeb847d4a4c33a1bc929d97b2
[ "MIT" ]
3
2018-11-09T04:33:12.000Z
2021-06-04T04:23:07.000Z
code/evaluate.py
Shuailong/CCGSupertagging
891a6a477a4a05daeb847d4a4c33a1bc929d97b2
[ "MIT" ]
2
2017-03-13T02:56:09.000Z
2019-07-27T02:47:29.000Z
code/evaluate.py
Shuailong/CCGSupertagging
891a6a477a4a05daeb847d4a4c33a1bc929d97b2
[ "MIT" ]
1
2020-11-25T06:09:33.000Z
2020-11-25T06:09:33.000Z
#!/usr/bin/env python # encoding: utf-8 """ evaluate.py Created by Shuailong on 2016-12-2. Evaluate model accuracy on test set. """ from __future__ import print_function from time import time from keras.models import load_model import os from utils import true_accuracy from dataset import get_data from train import MODEL_FILE, MODEL_DIR from train import data_generator if __name__ == '__main__': main()
25.877551
108
0.645899
e0d9891ebc981dc1dd6b1f55b9d60d1a276b4e1d
1,283
py
Python
setup.py
Cloudlock/bravado
bacf49ea9d791ec9f564a3a141c77995d2f395b0
[ "BSD-3-Clause" ]
null
null
null
setup.py
Cloudlock/bravado
bacf49ea9d791ec9f564a3a141c77995d2f395b0
[ "BSD-3-Clause" ]
2
2016-12-14T07:33:33.000Z
2017-05-11T13:40:48.000Z
setup.py
Cloudlock/bravado
bacf49ea9d791ec9f564a3a141c77995d2f395b0
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # Copyright (c) 2013, Digium, Inc. # Copyright (c) 2014-2016, Yelp, Inc. import os from setuptools import setup import bravado setup( name="bravado", # cloudlock version, no twisted dependency version=bravado.version + "cl", license="BSD 3-Clause License", description="Library for accessing Swagger-enabled API's", long_description=open(os.path.join(os.path.dirname(__file__), "README.rst")).read(), author="Digium, Inc. and Yelp, Inc.", author_email="opensource+bravado@yelp.com", url="https://github.com/Yelp/bravado", packages=["bravado"], classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Topic :: Software Development :: Libraries :: Python Modules", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", ], install_requires=[ "bravado-core >= 4.2.2", "yelp_bytes", "python-dateutil", "pyyaml", "requests", "six", ], extras_require={ }, )
29.159091
71
0.59392
e0d98d3fbe99c6483d07cbca24e2f2d19d6ccfe4
4,691
py
Python
solum/api/controllers/v1/assembly.py
devdattakulkarni/test-solum
4e9ddb82d217116aa2c30a6f2581080cbdfae325
[ "Apache-2.0" ]
null
null
null
solum/api/controllers/v1/assembly.py
devdattakulkarni/test-solum
4e9ddb82d217116aa2c30a6f2581080cbdfae325
[ "Apache-2.0" ]
null
null
null
solum/api/controllers/v1/assembly.py
devdattakulkarni/test-solum
4e9ddb82d217116aa2c30a6f2581080cbdfae325
[ "Apache-2.0" ]
null
null
null
# Copyright 2013 - Red Hat, 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. import pecan from pecan import rest import wsme import wsmeext.pecan as wsme_pecan from solum.api.controllers.v1.datamodel import assembly import solum.api.controllers.v1.userlog as userlog_controller from solum.api.handlers import assembly_handler from solum.common import exception from solum.common import request from solum import objects from solum.openstack.common.gettextutils import _
39.420168
77
0.675336
e0daa9911332d847f463b64cda5a0ec1b5c5fe82
562
py
Python
server/website/website/migrations/0003_background_task_optimization.py
mjain2/ottertune
011e896bf89df831fb1189b1ab4c9a7d7dca420a
[ "Apache-2.0" ]
1
2019-08-16T19:35:35.000Z
2019-08-16T19:35:35.000Z
server/website/website/migrations/0003_background_task_optimization.py
mjain2/ottertune
011e896bf89df831fb1189b1ab4c9a7d7dca420a
[ "Apache-2.0" ]
null
null
null
server/website/website/migrations/0003_background_task_optimization.py
mjain2/ottertune
011e896bf89df831fb1189b1ab4c9a7d7dca420a
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2018-08-02 07:58 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion
25.545455
129
0.631673
e0dbf6e6b17f8d31b9acfaa5334ab33b086914a3
1,379
py
Python
src/agility/usc/settings.py
bobbyluig/6.A01
16dd8963951eca4a1312a15c216d0cc3c117d063
[ "MIT" ]
null
null
null
src/agility/usc/settings.py
bobbyluig/6.A01
16dd8963951eca4a1312a15c216d0cc3c117d063
[ "MIT" ]
null
null
null
src/agility/usc/settings.py
bobbyluig/6.A01
16dd8963951eca4a1312a15c216d0cc3c117d063
[ "MIT" ]
1
2021-02-24T07:13:01.000Z
2021-02-24T07:13:01.000Z
from agility.usc.enumeration import uscSerialMode, ChannelMode, HomeMode from agility.usc.reader import BytecodeReader
29.340426
73
0.636693
e0dd99fc8816a494d26cd7231afd96fb99ec03d8
476
py
Python
invmonInfra/domain/__init__.py
jtom38/invmon-api
28f163bef47ee5c95bac0f40198e25e44090758f
[ "MIT" ]
null
null
null
invmonInfra/domain/__init__.py
jtom38/invmon-api
28f163bef47ee5c95bac0f40198e25e44090758f
[ "MIT" ]
16
2021-12-09T06:22:29.000Z
2022-03-25T06:26:01.000Z
invmonInfra/domain/__init__.py
jtom38/invmon-api
28f163bef47ee5c95bac0f40198e25e44090758f
[ "MIT" ]
null
null
null
from .dbApiInterface import DbApiTableInterface from .dbApiTableInterface import DbApiTableInterface from .cacheInterface import CacheInterface from .loggerInterface import LoggerInterface from .envReaderInterface import EnvReaderInterface from .driverInterface import DriverInterface from .jobsInterface import JobsInterface from .jobsInventoryInterface import JobsInventoryInterface from .emailInterface import EmailInterface from .sqlTableInterface import SqlTableInterface
47.6
58
0.897059
e0e0334b9f18fc8e44cf7c368bc6aba17a751a2d
1,123
py
Python
app/app8_18mix/h_noSeqSearch.py
ameenetemady/DeepPep
121826309667f1290fa1121746a2992943d0927b
[ "Apache-2.0" ]
1
2020-05-30T06:01:50.000Z
2020-05-30T06:01:50.000Z
app/app8_18mix/h_noSeqSearch.py
ameenetemady/DeepPep
121826309667f1290fa1121746a2992943d0927b
[ "Apache-2.0" ]
null
null
null
app/app8_18mix/h_noSeqSearch.py
ameenetemady/DeepPep
121826309667f1290fa1121746a2992943d0927b
[ "Apache-2.0" ]
1
2019-10-20T21:11:48.000Z
2019-10-20T21:11:48.000Z
import sys import csv import os sys.path.append('../../') import h_lib import h_lib_noSeqSearch in_strFastaFilename = '{!s}/data/protein/18mix/18mix_db_plus_contaminants_20081209.fasta'.format(os.environ.get('HOME')) in_strPeptideFilename = '{!s}/data/protein/18mix/18_mixtures_peptide_identification.txt'.format(os.environ.get('HOME')) out_strOutputBaseDir = './sparseData_h' out_strFile = out_strOutputBaseDir + "/h_noSeqSearch.csv" YInfo = h_lib.getPeptides(in_strPeptideFilename, "\t", 0, 2) ###assuming proteins are already broken to individual files under in_strProtRefsDir #XMatchProb = h_lib.getYInfo(YInfo, in_strProtRefsDir, strXMatchProb_filename, True) XMatchProb = h_lib_noSeqSearch.getXInfo(YInfo, in_strPeptideFilename, "\t", 0, 1) YMatchProbCount = h_lib.getPeptideProteinMatches(YInfo, XMatchProb) h_lib.updateXMatchingProbabilities(XMatchProb, YMatchProbCount) XPred = h_lib.getAccumulatedXMatchingProbabilities(XMatchProb) XPred.sort() with open(out_strFile, "w") as bfFile: for row in XPred: bfFile.write('{!s},{:.6f}\n'.format(row[0], row[1])) print("result saved in:" + out_strFile)
38.724138
120
0.782725
e0e04165ecde0d603bc47e0b5c5deaa17a56ab3a
700
py
Python
normalizer.py
ashokn414/python_floating_conversions
7a132c703272e6651daf555816171f04ee5b5555
[ "Apache-2.0" ]
null
null
null
normalizer.py
ashokn414/python_floating_conversions
7a132c703272e6651daf555816171f04ee5b5555
[ "Apache-2.0" ]
null
null
null
normalizer.py
ashokn414/python_floating_conversions
7a132c703272e6651daf555816171f04ee5b5555
[ "Apache-2.0" ]
null
null
null
# for normalization we need to have the maxima of x and y values with the help of which # we can normalise the given values import csv filename = "values.csv" fields = [] rows = [] with open(filename,'r') as csvfile: reader = csv.reader(csvfile) fields = next(reader) for row in reader: rows.append(row) for row in rows: for col in row: a = col[0] norm=50 #a = float(input("enter the x cordinate:")) #b = float(input("enter the y cordinate:")) if (a>norm or b>norm or a<-(norm) or b<-(norm)): print("the value given is invalid/out of bound") else: a = a/norm b = b/norm print("the normalized values are "+str(a)+","+str(b))
26.923077
89
0.615714
e0e23eae8f30892f74e1745a5cf500f5f0c7d685
3,477
py
Python
pygdp/fwgs.py
jiwalker-usgs/pyGDP
dca4789fb0c53c889d6fa1b38ec867bc939a2d04
[ "CC0-1.0" ]
null
null
null
pygdp/fwgs.py
jiwalker-usgs/pyGDP
dca4789fb0c53c889d6fa1b38ec867bc939a2d04
[ "CC0-1.0" ]
null
null
null
pygdp/fwgs.py
jiwalker-usgs/pyGDP
dca4789fb0c53c889d6fa1b38ec867bc939a2d04
[ "CC0-1.0" ]
null
null
null
from pygdp import _execute_request from pygdp import _get_geotype from owslib.util import log def submitFeatureWeightedGridStatistics(geoType, dataSetURI, varID, startTime, endTime, attribute, value, gmlIDs, verbose, coverage, delim, stat, grpby, timeStep, summAttr, weighted, WFS_URL, outputfname, sleepSecs): """ Makes a featureWeightedGridStatistics algorithm call. The web service interface implemented is summarized here: https://my.usgs.gov/confluence/display/GeoDataPortal/Generating+Area+Weighted+Statistics+Of+A+Gridded+Dataset+For+A+Set+Of+Vector+Polygon+Features Note that varID and stat can be a list of strings. """ # test for dods: dataSetURI = _execute_request.dodsReplace(dataSetURI) log.info('Generating feature collection.') featureCollection = _get_geotype._getFeatureCollectionGeoType(geoType, attribute, value, gmlIDs, WFS_URL) if featureCollection is None: return processid = 'gov.usgs.cida.gdp.wps.algorithm.FeatureWeightedGridStatisticsAlgorithm' if weighted==False: processid = 'gov.usgs.cida.gdp.wps.algorithm.FeatureGridStatisticsAlgorithm' solo_inputs = [("FEATURE_ATTRIBUTE_NAME",attribute), ("DATASET_URI", dataSetURI), ("TIME_START",startTime), ("TIME_END",endTime), ("REQUIRE_FULL_COVERAGE",str(coverage).lower()), ("DELIMITER",delim), ("GROUP_BY", grpby), ("SUMMARIZE_TIMESTEP", str(timeStep).lower()), ("SUMMARIZE_FEATURE_ATTRIBUTE",str(summAttr).lower()), ("FEATURE_COLLECTION", featureCollection)] if isinstance(stat, list): num_stats=len(stat) if num_stats > 7: raise Exception('Too many statistics were submitted.') else: num_stats=1 if isinstance(varID, list): num_varIDs=len(varID) else: num_varIDs=1 inputs = [('','')]*(len(solo_inputs)+num_varIDs+num_stats) count=0 rmvCnt=0 for solo_input in solo_inputs: if solo_input[1]!=None: inputs[count] = solo_input count+=1 else: rmvCnt+=1 del inputs[count:count+rmvCnt] if num_stats > 1: for stat_in in stat: if stat_in not in ["MEAN", "MINIMUM", "MAXIMUM", "VARIANCE", "STD_DEV", "SUM", "COUNT"]: raise Exception('The statistic %s is not in the allowed list: "MEAN", "MINIMUM", "MAXIMUM", "VARIANCE", "STD_DEV", "SUM", "COUNT"' % stat_in) inputs[count] = ("STATISTICS",stat_in) count+=1 elif num_stats == 1: if stat not in ["MEAN", "MINIMUM", "MAXIMUM", "VARIANCE", "STD_DEV", "SUM", "COUNT"]: raise Exception('The statistic %s is not in the allowed list: "MEAN", "MINIMUM", "MAXIMUM", "VARIANCE", "STD_DEV", "SUM", "COUNT"' % stat) inputs[count] = ("STATISTICS",stat) count+=1 if num_varIDs > 1: for var in varID: inputs[count] = ("DATASET_ID",var) count+=1 elif num_varIDs == 1: inputs[count] = ("DATASET_ID",varID) output = "OUTPUT" return _execute_request._executeRequest(processid, inputs, output, verbose, outputfname, sleepSecs)
39.965517
157
0.595628
e0e302f950371ae0056fe68d4bc413f86d8a3bb5
1,180
py
Python
tests/pure-req.py
rbanffy/bjoern
b177b62aa626cee97972a2e73f8543e6d86b5eb7
[ "BSD-2-Clause" ]
2,326
2015-01-05T21:20:29.000Z
2022-03-31T15:42:24.000Z
tests/pure-req.py
rbanffy/bjoern
b177b62aa626cee97972a2e73f8543e6d86b5eb7
[ "BSD-2-Clause" ]
127
2015-04-09T03:33:17.000Z
2022-03-11T13:43:55.000Z
tests/pure-req.py
rbanffy/bjoern
b177b62aa626cee97972a2e73f8543e6d86b5eb7
[ "BSD-2-Clause" ]
190
2015-01-20T10:54:38.000Z
2022-02-23T05:45:45.000Z
import sys import socket conn = socket.create_connection(('0.0.0.0', 8080)) msgs = [ # 0 Keep-Alive, Transfer-Encoding chunked 'GET / HTTP/1.1\r\nConnection: Keep-Alive\r\n\r\n', # 1,2,3 Close, EOF "encoding" 'GET / HTTP/1.1\r\n\r\n', 'GET / HTTP/1.1\r\nConnection: close\r\n\r\n', 'GET / HTTP/1.0\r\nConnection: Keep-Alive\r\n\r\n', # 4 Bad Request 'GET /%20%20% HTTP/1.1\r\n\r\n', # 5 Bug #14 'GET /%20abc HTTP/1.0\r\n\r\n', # 6 Content-{Length, Type} 'GET / HTTP/1.0\r\nContent-Length: 11\r\n' 'Content-Type: text/blah\r\nContent-Fype: bla\r\n' 'Content-Tength: bla\r\n\r\nhello world', # 7 POST memory leak 'POST / HTTP/1.0\r\nContent-Length: 1000\r\n\r\n%s' % ('a'*1000), # 8,9 CVE-2015-0219 'GET / HTTP/1.1\r\nFoo_Bar: bad\r\n\r\n', 'GET / HTTP/1.1\r\nFoo-Bar: good\r\nFoo_Bar: bad\r\n\r\n' ] conn.send(msgs[int(sys.argv[1])].encode()) while 1: data = conn.recv(100) if not data: break print(repr(data)) if data.endswith(b'0\r\n\r\n'): if raw_input('new request? Y/n') == 'n': exit() conn.send(b'GET / HTTP/1.1\r\nConnection: Keep-Alive\r\n\r\n')
28.780488
70
0.580508
e0e356f37fd9ccf2de0310d2d8f77f903645f43e
324
py
Python
apps/odoo/lib/odoo-10.0.post20170615-py2.7.egg/odoo/addons/stock/models/web_planner.py
gtfarng/Odoo_migrade
9cc28fae4c379e407645248a29d22139925eafe7
[ "Apache-2.0" ]
1
2019-12-19T01:53:13.000Z
2019-12-19T01:53:13.000Z
apps/odoo/lib/odoo-10.0.post20170615-py2.7.egg/odoo/addons/stock/models/web_planner.py
gtfarng/Odoo_migrade
9cc28fae4c379e407645248a29d22139925eafe7
[ "Apache-2.0" ]
null
null
null
apps/odoo/lib/odoo-10.0.post20170615-py2.7.egg/odoo/addons/stock/models/web_planner.py
gtfarng/Odoo_migrade
9cc28fae4c379e407645248a29d22139925eafe7
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- from odoo import models
24.923077
74
0.697531
e0e3e3c9acda1bb91d2a503dbb2cdcf350023dcd
45,861
py
Python
wizbot.py
Wizard-Of-Chaos/WizardBot
75a2e482c7d7921e9a06dde4d210c68330c6fbe2
[ "MIT" ]
null
null
null
wizbot.py
Wizard-Of-Chaos/WizardBot
75a2e482c7d7921e9a06dde4d210c68330c6fbe2
[ "MIT" ]
null
null
null
wizbot.py
Wizard-Of-Chaos/WizardBot
75a2e482c7d7921e9a06dde4d210c68330c6fbe2
[ "MIT" ]
null
null
null
#WIZARD BOT IS LIVE import calendar import discord as dc from discord.ext.commands import Bot from discord.ext import commands from functools import partial import asyncio as aio import time from random import randint from datetime import datetime from discord.ext import commands from guildconfig import GuildConfig from rolesaver import RoleSaver #initializes bot, sets up command sign bot = commands.Bot(command_prefix = '!') bot.remove_command('help') guild_config = GuildConfig(bot, 'config.pkl') role_saver = RoleSaver(bot, 'roles.pkl') #GAME STUFF #WIZBOT OLD STUFF ENDS HERE #FUNCTIONS HERE def get_token(): with open('token.dat', 'r') as tokenfile: return ''.join( chr(int(''.join(c), 16)) for c in zip(*[iter(tokenfile.read().strip())]*2) ) def monthdelta(date, delta): m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12 if not m: m = 12 d = min(date.day, calendar.monthrange(y, m)[1]) return date.replace(day=d, month=m, year=y) #START OF EVENTS #END OF EVENTS #GAME EVENT #ABANDON ALL HOPE YE WHO GO BELOW HERE #END DUEL if __name__ == '__main__': bot.run(get_token())
48.788298
151
0.536556
e0e4e551502750847910375c9545b7c251613085
2,775
py
Python
ProyectoDAI/settings.py
javiergarridomellado/proyectodai
64944d10f543c3094630056906b5f101a73bdd7b
[ "Apache-2.0" ]
1
2019-08-21T17:21:13.000Z
2019-08-21T17:21:13.000Z
ProyectoDAI/settings.py
javiergarridomellado/proyectodai
64944d10f543c3094630056906b5f101a73bdd7b
[ "Apache-2.0" ]
null
null
null
ProyectoDAI/settings.py
javiergarridomellado/proyectodai
64944d10f543c3094630056906b5f101a73bdd7b
[ "Apache-2.0" ]
null
null
null
""" Django settings for TusPachangas project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ import django import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '26*swq94+rg+-2tc2es6j&d#&(g4@@xe7vh1hu1)6*z^v@pd2q' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'registration', #add in the registration package 'rest_framework', 'restaurante', 'easy_maps', ) if django.VERSION < (1, 7): INSTALLED_APPS += ( 'south', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'ProyectoDAI.urls' WSGI_APPLICATION = 'ProyectoDAI.wsgi.application' TEMPLATE_DIRS = (TEMPLATE_PATH,) # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } ON_HEROKU = os.environ.get('PORT') if ON_HEROKU: DATABASE_URL='postgres://kytzveedsclzaf:eIJAAuElYvSxPK-vmSdXG9Hjv8@ec2-107-21-219-235.compute-1.amazonaws.com:5432/df9sfr7a9b8vjf' DATABASES = {'default': dj_database_url.config(default=DATABASE_URL)} # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_PATH = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( STATIC_PATH, ) #Media MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
25.458716
131
0.735856
e0e5f077be0c9058daed1ddc7c50b58ba470d16a
1,169
py
Python
Plugins/UnrealEnginePython/Binaries/Win64/Lib/site-packages/tensorflow/python/eager/test.py
JustinACoder/H22-GR3-UnrealAI
361eb9ef1147f8a2991e5f98c4118cd823184adf
[ "MIT" ]
6
2022-02-04T18:12:24.000Z
2022-03-21T23:57:12.000Z
Lib/site-packages/tensorflow/python/eager/test.py
shfkdroal/Robot-Learning-in-Mixed-Adversarial-and-Collaborative-Settings
1fa4cd6a566c8745f455fc3d2273208f21f88ced
[ "bzip2-1.0.6" ]
null
null
null
Lib/site-packages/tensorflow/python/eager/test.py
shfkdroal/Robot-Learning-in-Mixed-Adversarial-and-Collaborative-Settings
1fa4cd6a566c8745f455fc3d2273208f21f88ced
[ "bzip2-1.0.6" ]
1
2022-02-08T03:53:23.000Z
2022-02-08T03:53:23.000Z
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utilities for testing tfe code.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import ops as _ops from tensorflow.python.platform import test as _test from tensorflow.python.platform.test import * # pylint: disable=wildcard-import # TODO(akshayka): Do away with this file.
38.966667
81
0.707442
e0e63ae87cd65917f81764b65113935c80fb3646
1,150
py
Python
util.py
monokim/CheesyBullets
eeb5a79a69936701ff7962b846e6310f7df91cb0
[ "BSD-3-Clause" ]
1
2021-09-28T01:02:31.000Z
2021-09-28T01:02:31.000Z
util.py
monokim/CheesyBullets
eeb5a79a69936701ff7962b846e6310f7df91cb0
[ "BSD-3-Clause" ]
null
null
null
util.py
monokim/CheesyBullets
eeb5a79a69936701ff7962b846e6310f7df91cb0
[ "BSD-3-Clause" ]
1
2021-09-28T01:02:32.000Z
2021-09-28T01:02:32.000Z
import time import pyautogui import win32gui
26.744186
74
0.508696
e0e6d5767d002512b6411fc77a77af2956e16766
19,876
py
Python
graph-to-graph/elf_correlate.py
mbrcknl/graph-refine
78c74f18127db53606f18f775a5a50de86bc6b97
[ "BSD-2-Clause", "MIT" ]
6
2017-03-17T17:57:48.000Z
2019-12-28T13:03:23.000Z
graph-to-graph/elf_correlate.py
myuluo/graph-refine
8924af0c61c3c863db7957e0ebac7ae1ceefad9d
[ "BSD-2-Clause", "MIT" ]
3
2020-04-07T09:15:55.000Z
2022-03-23T01:36:26.000Z
graph-to-graph/elf_correlate.py
myuluo/graph-refine
8924af0c61c3c863db7957e0ebac7ae1ceefad9d
[ "BSD-2-Clause", "MIT" ]
7
2020-04-16T00:32:41.000Z
2022-03-09T05:25:23.000Z
# # Copyright 2020, Data61, CSIRO (ABN 41 687 119 230) # # SPDX-License-Identifier: BSD-2-Clause # import re import graph_refine.syntax as syntax import graph_refine.problem as problem import graph_refine.stack_logic as stack_logic from graph_refine.syntax import true_term, false_term, mk_not from graph_refine.check import * import graph_refine.search as search import elf_parser import graph_refine.target_objects as target_objects from imm_utils import * from elf_file import * from addr_utils import * from call_graph_utils import gFuncsCalled from dot_utils import toDot,toGraph from addr_utils import gToPAddrP,callNodes
33.574324
132
0.550513
e0e7c60f7d5d1f6c613e5dbae742091e0b76d703
2,301
py
Python
Gelatin/parser/Parser.py
Etherbay/Gelatin
d2afa85a48034d6ee34580e49e16542f31ad208e
[ "MIT" ]
107
2015-01-26T21:37:57.000Z
2022-02-25T16:28:44.000Z
Gelatin/parser/Parser.py
Etherbay/Gelatin
d2afa85a48034d6ee34580e49e16542f31ad208e
[ "MIT" ]
20
2015-11-23T14:09:37.000Z
2021-02-11T17:57:24.000Z
Gelatin/parser/Parser.py
Etherbay/Gelatin
d2afa85a48034d6ee34580e49e16542f31ad208e
[ "MIT" ]
34
2015-01-05T18:47:34.000Z
2020-12-13T06:47:26.000Z
# Copyright (c) 2010-2017 Samuel Abels # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os import codecs from simpleparse import parser from .Newline import Newline from .Indent import Indent from .Dedent import Dedent from .util import error _ebnf_file = os.path.join(os.path.dirname(__file__), 'syntax.ebnf') with open(_ebnf_file) as _thefile: _ebnf = _thefile.read()
40.368421
80
0.704911
e0e93ce753097ffb23fb7c437281488fb715e819
308
py
Python
C03-Unit-Testing/21-C03V15/utils.py
dirchev/Python-101-Forever-1
13c3bb182747aae244ae6f9fd6f79c8223f3e9a6
[ "MIT" ]
59
2021-02-05T10:40:08.000Z
2022-01-26T08:30:43.000Z
C03-Unit-Testing/21-C03V15/utils.py
dirchev/Python-101-Forever-1
13c3bb182747aae244ae6f9fd6f79c8223f3e9a6
[ "MIT" ]
null
null
null
C03-Unit-Testing/21-C03V15/utils.py
dirchev/Python-101-Forever-1
13c3bb182747aae244ae6f9fd6f79c8223f3e9a6
[ "MIT" ]
10
2021-02-13T16:50:26.000Z
2022-03-20T12:17:00.000Z
BIG_CONSTANT = "YES" print(group_by([1, 2, 3, 4, 5, 6], lambda x: "even" if x % 2 == 0 else "odd"))
16.210526
78
0.529221
e0eb718b5df49f7654c2a9064eafc5186c980c9e
3,721
py
Python
pipeline/test_sftp_to_s3.py
streamsets/datacollector-tests-external
6f255b5e7496deeef333b57a5e9df4911ba3ef00
[ "Apache-2.0" ]
1
2020-04-14T03:01:51.000Z
2020-04-14T03:01:51.000Z
pipeline/test_sftp_to_s3.py
streamsets/datacollector-tests-external
6f255b5e7496deeef333b57a5e9df4911ba3ef00
[ "Apache-2.0" ]
null
null
null
pipeline/test_sftp_to_s3.py
streamsets/datacollector-tests-external
6f255b5e7496deeef333b57a5e9df4911ba3ef00
[ "Apache-2.0" ]
1
2019-09-14T08:30:23.000Z
2019-09-14T08:30:23.000Z
# Copyright 2019 StreamSets 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. from datetime import datetime import json import logging import os import string import time from streamsets.sdk.models import Configuration from streamsets.testframework.markers import aws, sftp, sdc_min_version from streamsets.testframework.utils import get_random_string logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Sandbox prefix for S3 bucket S3_BUCKET_PREFIX = 'sftp_upload'
42.770115
133
0.742274
e0ed1ce1a37b62c8113cea099de0a407123519d8
950
py
Python
terra/tests/__init__.py
NoahRJohnson/terra
131954ee42fb5905ceff35101e34d89c5eb6de6c
[ "MIT" ]
null
null
null
terra/tests/__init__.py
NoahRJohnson/terra
131954ee42fb5905ceff35101e34d89c5eb6de6c
[ "MIT" ]
null
null
null
terra/tests/__init__.py
NoahRJohnson/terra
131954ee42fb5905ceff35101e34d89c5eb6de6c
[ "MIT" ]
null
null
null
import os # Use this as a package level setup
38
77
0.749474
e0edc031d7ad458b3382ce23bb1ea18d6941bcf3
392
py
Python
icons/svg2png.py
benburrill/formiko
86630506c537f9517666d9b0d5b2a905e7385b01
[ "BSD-3-Clause" ]
116
2016-07-13T00:35:35.000Z
2022-02-22T15:46:44.000Z
icons/svg2png.py
benburrill/formiko
86630506c537f9517666d9b0d5b2a905e7385b01
[ "BSD-3-Clause" ]
32
2018-01-23T13:50:27.000Z
2022-03-30T05:34:56.000Z
icons/svg2png.py
benburrill/formiko
86630506c537f9517666d9b0d5b2a905e7385b01
[ "BSD-3-Clause" ]
8
2018-12-21T13:45:36.000Z
2021-11-07T22:40:05.000Z
# -*- coding: utf-8 -*- from gi.repository.GdkPixbuf import Pixbuf from os import makedirs if __name__ == "__main__": main()
24.5
77
0.591837
e0eeafb1dffc9fb35d396d75f5c0ceb8be5469f6
545
py
Python
django/currencies/migrations/0003_auto_20211121_0701.py
AngelOnFira/megagame-controller
033fec84babf80ffd0868a0f7d946ac4c18b061c
[ "MIT" ]
null
null
null
django/currencies/migrations/0003_auto_20211121_0701.py
AngelOnFira/megagame-controller
033fec84babf80ffd0868a0f7d946ac4c18b061c
[ "MIT" ]
1
2022-03-03T21:56:12.000Z
2022-03-03T21:56:12.000Z
django/currencies/migrations/0003_auto_20211121_0701.py
AngelOnFira/megagame-controller
033fec84babf80ffd0868a0f7d946ac4c18b061c
[ "MIT" ]
null
null
null
# Generated by Django 3.2.8 on 2021-11-21 12:01 from django.db import migrations, models
22.708333
53
0.577982
e0ef4cd1fe213247f6cb053cb5a43dff995c8928
5,778
py
Python
etna/transforms/decomposition/trend.py
tinkoff-ai/etna-ts
ded5161ed49f5c2697778825f899842ee30c6c61
[ "Apache-2.0" ]
96
2021-09-05T06:29:34.000Z
2021-11-07T15:22:54.000Z
etna/transforms/decomposition/trend.py
geopars/etna
ded5161ed49f5c2697778825f899842ee30c6c61
[ "Apache-2.0" ]
188
2021-09-06T15:59:58.000Z
2021-11-17T09:34:16.000Z
etna/transforms/decomposition/trend.py
geopars/etna
ded5161ed49f5c2697778825f899842ee30c6c61
[ "Apache-2.0" ]
8
2021-09-06T09:18:35.000Z
2021-11-11T21:18:39.000Z
from typing import Optional import pandas as pd from ruptures import Binseg from ruptures.base import BaseCost from sklearn.linear_model import LinearRegression from etna.transforms.base import PerSegmentWrapper from etna.transforms.decomposition.change_points_trend import BaseEstimator from etna.transforms.decomposition.change_points_trend import TDetrendModel from etna.transforms.decomposition.change_points_trend import _OneSegmentChangePointsTrendTransform
31.232432
122
0.606265
e0f004be552defdc3e85fe514fc0037369c084b9
4,027
py
Python
argopy/tests/test_fetchers_facade_index.py
schwehr/argopy
1b35d5cfb87b2f9ccd2ca45b9987a614edd30700
[ "Apache-2.0" ]
null
null
null
argopy/tests/test_fetchers_facade_index.py
schwehr/argopy
1b35d5cfb87b2f9ccd2ca45b9987a614edd30700
[ "Apache-2.0" ]
null
null
null
argopy/tests/test_fetchers_facade_index.py
schwehr/argopy
1b35d5cfb87b2f9ccd2ca45b9987a614edd30700
[ "Apache-2.0" ]
null
null
null
import xarray as xr import pytest import warnings import argopy from argopy import IndexFetcher as ArgoIndexFetcher from argopy.errors import InvalidFetcherAccessPoint, InvalidFetcher, ErddapServerError, DataNotFound from . import ( AVAILABLE_INDEX_SOURCES, requires_fetcher_index, requires_connected_erddap_index, requires_localftp_index, requires_connection, safe_to_server_errors )
35.955357
100
0.674696
e0f00c9b59cb978159364c5072c66c216bf67f98
968
py
Python
custom_components/acthor/config_flow.py
jatty/hass-acthor
9d5aaed3f01e9288fef031b47b0808e6e80c22d3
[ "MIT" ]
null
null
null
custom_components/acthor/config_flow.py
jatty/hass-acthor
9d5aaed3f01e9288fef031b47b0808e6e80c22d3
[ "MIT" ]
null
null
null
custom_components/acthor/config_flow.py
jatty/hass-acthor
9d5aaed3f01e9288fef031b47b0808e6e80c22d3
[ "MIT" ]
null
null
null
import voluptuous as vol from homeassistant.config_entries import ConfigFlow from homeassistant.const import CONF_HOST, CONF_NAME from .acthor import test_connection from .const import DEVICE_NAME, DOMAIN
32.266667
72
0.597107
e0f0a9e1fa344475b21cf62a27dc93bb2296049d
356
py
Python
doajtest/fixtures/common.py
glauberm/doaj
dc24dfcbf4a9f02ce5c9b09b611a5766ea5742f7
[ "Apache-2.0" ]
null
null
null
doajtest/fixtures/common.py
glauberm/doaj
dc24dfcbf4a9f02ce5c9b09b611a5766ea5742f7
[ "Apache-2.0" ]
null
null
null
doajtest/fixtures/common.py
glauberm/doaj
dc24dfcbf4a9f02ce5c9b09b611a5766ea5742f7
[ "Apache-2.0" ]
null
null
null
NOTES = { 'notes': [ {'date': '2014-05-22T00:00:00Z', 'note': 'Second Note'}, {'date': '2014-05-21T14:02:45Z', 'note': 'First Note'} ] } SUBJECT = { "subject": ['HB1-3840', 'H'] } OWNER = { "owner": "Owner" } EDITORIAL = { "editor_group": "editorgroup", "editor": "associate" } SEAL = { "doaj_seal": True, }
14.833333
64
0.5
e0f1a06f3be393877c548f9dcd340350faeb7ed3
46,397
py
Python
docnado/docnado.py
HEInventions/docnado
8817d8a9856b4babd9a2f81678a9ef0b8a75d4bc
[ "MIT" ]
78
2018-10-09T16:28:26.000Z
2022-02-24T15:25:26.000Z
docnado/docnado.py
HEInventions/docnado
8817d8a9856b4babd9a2f81678a9ef0b8a75d4bc
[ "MIT" ]
27
2018-11-01T16:30:50.000Z
2022-02-22T14:36:11.000Z
docnado/docnado.py
HEInventions/docnado
8817d8a9856b4babd9a2f81678a9ef0b8a75d4bc
[ "MIT" ]
9
2018-11-06T18:50:51.000Z
2020-10-24T00:56:16.000Z
""" docnado.py A rapid documentation tool that will blow you away. """ import os import re import sys import csv import glob import time import signal import shutil import urllib import base64 import hashlib import argparse import tempfile import datetime import threading import traceback import subprocess import platform import requests from bs4 import BeautifulSoup from multiprocessing import Pool from urllib.parse import urlparse from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler from xml.etree import ElementTree from flask import Flask, url_for, abort, send_from_directory, \ render_template, Markup, make_response, render_template_string import markdown import markdown.util from markdown.extensions import Extension from markdown.postprocessors import Postprocessor from markdown.inlinepatterns import LinkPattern, IMAGE_LINK_RE, dequote, handleAttributes from markdown.blockprocessors import HashHeaderProcessor from http.client import responses if __package__: from .navtree import NavItem, parse_nav_string else: from navtree import NavItem, parse_nav_string def as_video(self, m): """ Return a video element """ src, parts = self.get_src(m) el = ElementTree.Element('video') el.set('src', src) el.set("controls", "true") handleAttributes(m.group(2), el) return el def as_image(self, m): """ Return an image element """ el = ElementTree.Element('img') src, parts = self.get_src(m) el.set('src', src) # Set the title if present. if len(parts) > 1: el.set('title', dequote(self.unescape(" ".join(parts[1:])))) # Set the attributes on the element, if enabled. # Set the 'alt' attribute with whatever is left from `handleAttributes`. attrs = self.markdown.enable_attributes alt_text = handleAttributes(m.group(2), el) if attrs else m.group(2) el.set('alt', self.unescape(alt_text)) return el def as_download(self, m): """ Create card layers used to make a download button. """ src, parts = self.get_src(m) # Returns a human readable string representation of bytes # Get information required for card. split_src = os.path.split(src) file_path = os.path.join(self.markdown.page_root, *split_src) file_size = os.path.getsize(file_path) file_basename = os.path.basename(file_path) card_text = dequote(self.unescape(" ".join(parts[1:]))) if len(parts) > 1 else '' # If its a pptx, extract the thumbnail previews. # NOTE: This works, but is is removed until we support other # file types, which for now is not a priority. # preview_uri = None # import zipfile # if (file_path.endswith('pptx')): # with zipfile.ZipFile(file_path) as zipper: # with zipper.open('docProps/thumbnail.jpeg', 'r') as fp: # mime = 'image/jpeg' # data64 = base64.b64encode(fp.read()).decode('utf-8') # preview_uri = u'data:%s;base64,%s' % (mime, data64) # Card and structure. card = ElementTree.Element("div") card.set('class', 'card download-card') header = ElementTree.SubElement(card, 'div') header.set('class', 'download-card-header') body = ElementTree.SubElement(card, 'div') body.set('class', 'download-card-body') # Add preview image. # if preview_uri: # img = ET.SubElement(header, 'img') # img.set('src', preview_uri) # Filename link heading. heading = ElementTree.SubElement(body, 'a') heading.set('class', 'download-card-title') heading.set('href', src) download_icon = ElementTree.SubElement(heading, 'i') download_icon.set('class', 'fa fa-download') download_text = ElementTree.SubElement(heading, 'span') download_text.text = file_basename # Title element from the "quote marks" part. body_desc = ElementTree.SubElement(body, 'span') body_desc.text = card_text # File size span at the bottom. body_size = ElementTree.SubElement(body, 'span') body_size.set('class', 'small text-muted') body_size.text = f'{_human_size(file_size)}' return card def as_raw(self, m): """ Load the HTML document specified in the link, parse it to HTML elements and return it. """ src, parts = self.get_src(m) # Find the path to the HTML document, relative to the current markdown page. file_path = os.path.join(self.markdown.page_root, src) raw_html_string = read_html_for_injection(file_path) if len(parts) < 2: parts.append("nothing_one=1||nothing_two=2") # Helper function. # Split arg string on double pipe. Joins them to undo automattic splitting from the markdown. arg_strings = " ".join(parts[1:]).strip('\"').split("||") # Parse into dictionary of key-value pairs based on the '=' notation. try: named_args = dict([_argify(args) for args in arg_strings]) except Exception as e: raise Exception(f"Error parsing ![INJECT] arguments in {self.markdown.page_file} {repr(e)}") # Take the template renderer and give it our string, and named args. # Capture the output as a string. try: injectable_templated_str = render_template_string(raw_html_string, **named_args) except Exception as e: raise Exception(f"Error rendering ![INJECT] template for file {file_path} {repr(e)}") # Feed that string to the XML parser. try: return ElementTree.fromstring(injectable_templated_str) except Exception as e: raise Exception(f"Error parsing ![INJECT] template for file {file_path} {repr(e)}") def handleMatch(self, m): """ Use the URL extension to render the link. """ src, parts = self.get_src(m) if self._is_download(m): return self.as_download(m) elif self._is_inject(m): return self.as_raw(m) youtube = self.youtube_url_validation(src) if youtube: return self.as_youtube(m, youtube) src_lower = src.lower() if src_lower.endswith(self.SUPPORTED_TABLES): return self.as_csv(m) elif src_lower.endswith(self.SUPPORTED_PDF): return self.as_pdf(m) elif src_lower.endswith(self.SUPPORTED_VIDEO): return self.as_video(m) return self.as_image(m) class OffsetHashHeaderProcessor(HashHeaderProcessor): """ Process hash headers with an offset to control the type of heading DOM element that is generated. """ HEADING_LEVEL_OFFSET = 1 class ChecklistPostprocessor(Postprocessor): """ Adds checklist class to list element. Adapted from: `markdown_checklist.extension` """ pattern = re.compile(r'<li>\[([ Xx])\]') # Remove the `video`, `iframe`, `aside`, and `table` elements as block elements. markdown.util.BLOCK_LEVEL_ELEMENTS = re.compile( r"^(p|div|h[1-6]|blockquote|pre|dl|ol|ul" r"|script|noscript|form|fieldset|math" r"|hr|hr/|style|li|dt|dd|thead|tbody" r"|tr|th|td|section|footer|header|group|figure" r"|figcaption|article|canvas|output" r"|progress|nav|main)$", re.IGNORECASE ) # https://python-markdown.github.io/extensions/ mdextensions = [MultiExtension(), 'markdown.extensions.tables', 'markdown.extensions.meta', 'markdown.extensions.def_list', 'markdown.extensions.headerid', 'markdown.extensions.fenced_code', 'markdown.extensions.attr_list'] def build_meta_cache(root): """ Recursively search for Markdown files and build a cache of `Meta` from metadata in the Markdown. :param root: str: The path to search for files from. """ doc_files = glob.iglob(root + '/**/*.md', recursive=True) doc_files_meta = {os.path.relpath(path, start=root): _meta(path) for path in doc_files} doc_files_meta = {path: value for path, value in doc_files_meta.items() if value is not None} # If a nav filter is set, exclude relevant documents. # This takes the comma separated string supplied to `nav_limit` # and excludes certain documents if they are NOT in this list. global CMD_ARGS if CMD_ARGS.nav_limit: nav_filters = CMD_ARGS.nav_limit.split(',') nav_filters = [nav_filter.strip().lower() for nav_filter in nav_filters] nav_filters = [nav_filter for nav_filter in nav_filters if nav_filter] doc_files_meta = {path: value for path, value in doc_files_meta.items() if _should_include(value)} return doc_files_meta def build_nav_menu(meta_cache): """ Given a cache of Markdown `Meta` data, compile a structure that can be used to generate the NAV menu. This uses the `nav: Assembly>Bench>Part` variable at the top of the Markdown file. """ root = NavItem('root', 0) # Pre-sort the nav-items alphabetically by nav-string. This will get overridden with the arange() # function, but this avoids-un arranged items moving round between page refreshes due to Dicts being # unordered. sorted_meta_cache = sorted( meta_cache.items(), key = lambda items: items[1].get('nav', [''])[0].split('>')[-1] # Sort by the last part of the nav string for each page. ) for path, meta in sorted_meta_cache: nav_str = meta.get('nav', [None])[0] nav_chunks = parse_nav_string(nav_str) node = root for name, weight in nav_chunks: n = NavItem(name, weight) node = node.add(n) node.bind(meta=meta, link=path) root.arrange() return root def build_reload_files_list(extra_dirs): """ Given a list of directories, return a list of files to watch for modification and subsequent server reload. """ extra_files = extra_dirs[:] for extra_dir in extra_dirs: for dirname, dirs, files in os.walk(extra_dir): for filename in files: filename = os.path.join(dirname, filename) if os.path.isfile(filename): extra_files.append(filename) return extra_files def read_html_for_injection(path): """ Open an HTML file at the given path and return the contents as a string. If the file does not exist, we raise an exception. """ # TODO: In the future, consider adding some caching here. However, # beware of reloading / refereshing the page UX implications. with open(path) as file: return file.read() def _render_markdown(file_path, **kwargs): """ Given a `file_path` render the Markdown and return the result of `render_template`. """ global NAV_MENU, PROJECT_LOGO, PDF_GENERATION_ENABLED default_template = 'document' with open(file_path, 'r', encoding='utf-8') as f: md = markdown.Markdown(extensions=mdextensions) md.page_root = os.path.dirname(file_path) md.page_file = file_path markup = Markup(md.convert(f.read())) # Fetch the template defined in the metadata. template = md.Meta.get('template', None) template = template[0] if template else default_template if not template: raise Exception('no template found for document') template = f'{template}.html' # Load any HTML to be injected from the meta-data. injections = md.Meta.get('inject', []) injections = [os.path.join(md.page_root, file) for file in injections] injections = [read_html_for_injection(file) for file in injections] # Render it out with all the prepared data. return render_template(template, content=markup, nav_menu=NAV_MENU, project_logo=PROJECT_LOGO, pdf_enabled=PDF_GENERATION_ENABLED, injections=injections, **md.Meta, **kwargs) def configure_flask(app, root_dir): """ Setup the flask application within this scope. """ # Store the reference to the function that rebuilds the navigation cache. app.build_navigation_cache = build_navigation_cache def generate_static_pdf(app, root_dir, output_dir, nav_filter=None): """ Generate a static PDF directory for the documentation in `root_dir` into `output_dir`. """ global PORT_NUMBER # Find all markdown document paths that are in the nav. documents = build_meta_cache(root_dir) markdown_docs_urls = ['pdf/' + file.replace('\\', '/') for file in documents.keys()] # Generate URl to file pairs. pairs = [(f'http://localhost:{PORT_NUMBER}/{url}', f'{os.path.join(output_dir, *os.path.split(url))}.pdf') for url in markdown_docs_urls] # Download each pair. for source, target in pairs: os.makedirs(os.path.dirname(target), exist_ok=True) print(f'Source: {source} \n Target: {target}') urllib.request.urlretrieve(source, target) # Helper function to return the domain if present. def is_absolute(url): """ Returns True if the passed url string is an absolute path. False if not """ links = urlparse(url) return bool(links.netloc) def generate_static_html(app, root_dir, output_dir): """ Generate a static HTML site for the documentation in `root_dir` into `output_dir`. """ from flask_frozen import Freezer, MissingURLGeneratorWarning import warnings warnings.filterwarnings("ignore", category=MissingURLGeneratorWarning) # Update the flask config. app.config['FREEZER_RELATIVE_URLS'] = True app.config['FREEZER_IGNORE_MIMETYPE_WARNINGS'] = True app.config['FREEZER_DESTINATION'] = output_dir # Create the freezer app. Make it use specific URLs. freezer = Freezer(app, with_no_argument_rules=False, log_url_for=False) # Register a generator that passes ALL files in the docs directory into the # `wiki` flask route. # Save all the URLs using the correct extension and MIME type. freezer.freeze() # For each `.md` file in the output directory: for markdown_file in glob.iglob(f'{output_dir}/**/*.md', recursive=True): # Rewrite all relative links to other `.md` files to `.html.` output = '' with open(markdown_file, 'r', encoding="utf-8") as f: html = f.read() output = re.sub('href="(.*md)"', _href_replace, html) # Rename the file from `.md` to HTML. with open(markdown_file[:-3] + '.html', 'w', encoding="utf-8") as f: f.write(output) # Delete the Markdown file. os.remove(markdown_file) def load_project_logo(logo_file=None): """ Attempt to load the project logo from the specified path. If this fails, return None. If this succeeds, convert it to a data-uri. """ if not logo_file: return None if not os.path.exists(logo_file): return None with open(logo_file, 'rb') as fp: mime = 'image/png' data64 = base64.b64encode(fp.read()).decode('utf-8') preview_uri = u'data:%s;base64,%s' % (mime, data64) return preview_uri def check_pdf_generation_cap(): """ Check to see if we can use PDF generation by attempting to use the binary. """ global WKHTMLTOPDF_BINARY retcode = subprocess.call(f'{WKHTMLTOPDF_BINARY} --version', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) return retcode == 0 def copy_local_project(force=False): """ Copy the sample docs and style into the local working directory. Note: This will overwrite anything currently in those folders. """ source_root = os.path.dirname(__file__) target_root = os.getcwd() targets = ['docs', 'style', 'logo.png'] pairs = [(os.path.join(source_root, path), os.path.join(target_root, path)) for path in targets] for source, target in pairs: if os.path.isdir(source): if os.path.exists(target): if force: print(f'Deleting existing {target} and replacing it with {target}') shutil.rmtree(target) shutil.copytree(source, target) else: print(f'Warning: {target} already exists.') else: print(f'Copying: {source} -> {target}') shutil.copytree(source, target) else: if os.path.exists(target): if force: print(f'Deleting existing {target} and replacing it with {target}') os.remove(target) shutil.copyfile(source, target) else: print(f'Warning: {target} already exists.') else: print(f'Copying: {source} -> {target}') shutil.copyfile(source, target) def find_references(document_path): """ Search through the markdown 'document_path' and make a list of referenced files with paths that are relative to the directory containing the `document_path`. """ # Open the file to search. with open(document_path, 'r', encoding='utf-8') as f: markdown_raw_data = f.read() # Render as HTML. md = markdown.Markdown(extensions=mdextensions) document_dir = os.path.dirname(document_path) md.page_root = document_dir # Interpret with the BeautifulSoup HTML scraping library. soup = BeautifulSoup(md.convert(markdown_raw_data), 'html.parser') tags_to_search = { 'img': 'src', 'a': 'href', 'video': 'src', 'table': 'source', 'embed': 'src', } # For each entry in the `tags_to_search` table, extract the tag attribute value. references = set() for k, v in tags_to_search.items(): for tag in soup.find_all(k): val = tag.get(v) if val: references.add(val) # Normalise the referenced assets (to take into account relative paths). references = [os.path.join(document_dir, urllib.request.url2pathname(ref)) for ref in references] # Make unique. return set(references) def has_nav(markdown_text): """ Returns True if the passed string of text contains navbar metadata. Returns False if it does not. """ expression = re.compile(r'(?=\n|)nav:\s+\w+(?=\n |)') return True if expression.search(markdown_text) else False def find_orphans(files): """ Searches all files and folders recursively in the given path for image and video assets that are unused by markdown files. """ # Find all references in pages = {} for file in files: if file.endswith('.md'): pages[file] = find_references(file) # Remove the markdown documents that have a navbar metadata. md_with_nav = [] for file in files: if file.endswith('.md'): with open(file, encoding='utf-8') as f: if has_nav(f.read().lower()): md_with_nav.append(file) files = [x for x in files if x not in md_with_nav] # Create a flat list of all references in the markdown files all_references = [] for i in pages.values(): all_references += [k for k in i] # Output unused assets return [i for i in files if i not in all_references] def generate_metadata(path): """ Add relevant metadata to the top of the markdown file at the passed path. Title is drawn from the filename, Date from the last modified timestamp, Version defaults at 1.0.0, Nav is generated from the filepath, and Authors are generated from the git contributors (if applicable) and are otherwise left blank. Warning: Does not check if there is existing metadata. """ s = subprocess.getoutput(f"git log -p {path}") lines = s.split(os.linesep) authors = set([re.search(r'<(.*)>', line).group(1)for line in lines if 'Author:' in line]) file_status = os.stat(path) nav_path = os.path.sep.join(path.split(os.path.sep)[1:]) metadata = { 'title': ' '.join( path .split('.')[0] .split(os.path.sep)[-1] .replace('_', ' ') .replace('-', ' ') .title() .split() ), 'desc': '', 'date': datetime.datetime.utcfromtimestamp(file_status.st_mtime).strftime('%Y/%m/%d'), 'version': '1.0.0', 'template': '', 'nav': nav_path.replace(os.path.sep, '>').title().split('.')[0], 'percent': '100', 'authors': ' '.join(authors), } result = "" for key in metadata.keys(): result += ('{}:{}{}\n'.format(key, '\t' if len(key) > 6 else '\t\t', metadata[key])) with open(path, 'r+', encoding='utf-8') as f: content = f.read() f.seek(0, 0) f.write(result) f.write(content) class ReloadHandler(PatternMatchingEventHandler): """ Rebuild the document metadata / navigation cache when markdown files are updated in the documents directory. """ global CMD_ARGS, NAV_MENU, PROJECT_LOGO, WKHTMLTOPDF_BINARY, PDF_GENERATION_ENABLED, PORT_NUMBER CMD_ARGS = None NAV_MENU = {} PROJECT_LOGO = None WKHTMLTOPDF_BINARY = None PDF_GENERATION_ENABLED = False def main(): """ Application entrypoint. """ global PORT_NUMBER PORT_NUMBER = 5000 # Parse the command line arguments. parser = argparse.ArgumentParser(description='docnado: Lightweight tool for rendering \ Markdown documentation with different templates.') parser.add_argument('--html', action='store', dest='html_output_dir', help='Generate a static site from the server and output to the \ specified directory.') parser.add_argument('--pdf', action='store', dest='pdf_output_dir', help='Generate static PDFs from the server and output to the \ specified directory.') parser.add_argument('--nav-limit', action='store', dest='nav_limit', default=None, help='Include certain document trees only based on a comma separated \ list of nav strings. e.g. Tooling,Document') parser.add_argument('--new', action="store_true", dest='new_project', default=False, help='Copy the `docs` and `styles` folder into the working directory \ and output a config file that addresses them. Does not overwrite existing files.') parser.add_argument('--new-force', action="store_true", dest='new_project_force', default=False, help='Copy the `docs` and `styles` folder into the working directory \ and output a config file that addresses them. Force deletion of existing files.') parser.add_argument('--dirs', action="store_true", dest='show_dirs', default=False, help='Display the different directories the software is using \ to search for documentation and styles.') parser.add_argument('--generate-meta', action="store", dest='generate_meta', default=False, help='Generate metadata for markdown files in the specified directory.') parser.add_argument('--find-orphans', action="store_true", dest='find_orphans', default=False, help='Identify unused media assets (orphans)') parser.add_argument('--find-broken-links', action="store_true", dest='find_broken_links', default=False, help='Identify broken external links.') parser.add_argument('--port', action="store", dest='new_port_number', default=False, help='Specify a port for the docnado server') parser.add_argument('--host', action="store", dest='set_host', default=False, help='Set the docnado development server to listen on IP addresses.') # Import the command line args and make them application global. global CMD_ARGS args = parser.parse_args() CMD_ARGS = args # Load config from the environment and validate it. global PROJECT_LOGO, PDF_GENERATION_ENABLED, NAV_MENU, WKHTMLTOPDF_BINARY TRUE = 'TRUE' FALSE = 'FALSE' flask_debug = os.environ.get('DN_FLASK_DEBUG', FALSE) == TRUE watch_changes = os.environ.get('DN_RELOAD_ON_CHANGES', TRUE) == TRUE WKHTMLTOPDF_BINARY = ('wkhtmltopdf_0.12.5.exe' if platform.system() == 'Windows' else 'wkhtmltopdf') PDF_GENERATION_ENABLED = check_pdf_generation_cap() dir_documents = os.environ.get('DN_DOCS_DIR', os.path.join(os.getcwd(), 'docs')) dir_style = os.environ.get('DN_STYLE_DIR', os.path.join(os.getcwd(), 'style')) logo_location = os.environ.get('DN_PROJECT_LOGO', os.path.join(os.getcwd(), 'logo.png')) # If `style` folder does not exist, use the one in site-packages. if not os.path.exists(dir_style) and not os.path.isdir(dir_style): dir_style = os.path.join(os.path.dirname(__file__), 'style') # Attempt to load the project logo into a base64 data uri. PROJECT_LOGO = load_project_logo(logo_location) # Compute the static and template directories. dir_static = os.path.join(dir_style, 'static') dir_templates = os.path.join(dir_style, 'templates') # If the user is asking to create a new project. if args.new_project: copy_local_project() sys.exit() if args.new_project_force: copy_local_project(force=True) return 0 if args.new_port_number: PORT_NUMBER = int(args.new_port_number) if args.generate_meta: doc_files = glob.iglob(args.generate_meta + '/**/*.md', recursive=True) for i in doc_files: generate_metadata(i) return 0 if args.find_orphans: # Find all the assets in the directory/subdirectories recursively and append their file path to a list. files = glob.glob((dir_documents + '/**/*.*'), recursive=True) files = [f for f in files if not os.path.isdir(f)] orphans = find_orphans(files) if orphans: print(f'{len(orphans)} Unused assets (orphans):\n\t' + '\n\t'.join(orphans)) return -1 return 0 if args.find_broken_links: process_pool = Pool(processes=10) md_files = glob.glob((dir_documents + '/**/*.md'), recursive=True) md_reports = tuple((md, list(DocumentLinks(md).detect_broken_links(process_pool))) for md in md_files) num_broken = 0 for file, report in md_reports: if report: num_broken += len(report) print(f'{file}\n\t' + '\n\t'.join(report)) return -1 if num_broken else 0 if args.show_dirs: print('The following directories are being used: ') print('\t', f'Documents -> {dir_documents}') print('\t', f'Logo -> {logo_location}') print('\t', f'Style -> {dir_style}') print('\t', f' Static -> {dir_static}') print('\t', f' Templates -> {dir_templates}') sys.exit() if not os.path.exists(dir_documents) and not os.path.isdir(dir_documents): print(f'Error: Documents directory "{dir_documents}" does not exist. \ Create one called `docs` and fill it with your documentation.', file=sys.stderr) sys.exit(-1) if not os.path.exists(dir_static) and not os.path.isdir(dir_static): print(f'Error: Static directory "{dir_static}" does not exist.', file=sys.stderr) sys.exit(-1) if not os.path.exists(dir_templates) and not os.path.isdir(dir_templates): print(f'Error: Templates directory "{dir_templates}" does not exist.', file=sys.stderr) sys.exit(-1) # Create the server. app = Flask(__name__, static_url_path='', template_folder=dir_templates, static_folder=dir_static) # Attach routes and filters. configure_flask(app, dir_documents) # Output PDF files. if args.pdf_output_dir: if not check_pdf_generation_cap(): print(f'Error: PDF generation requires WkHTMLtoPDF.', file=sys.stderr) sys.exit(-1) t1 = threading.Thread(target=gen_pdfs) t1.start() app.run(debug=flask_debug, threaded=True, port=PORT_NUMBER) sys.exit() # Output a static site. if args.html_output_dir: PDF_GENERATION_ENABLED = False try: generate_static_html(app, dir_documents, os.path.join(os.getcwd(), args.html_output_dir)) index_html = """ <!DOCTYPE html> <html> <head> <meta http-equiv="refresh" content="0; url=./w/"> </head> <body> </body> </html>""" with open(os.path.join(os.getcwd(), args.html_output_dir, 'index.html'), 'w') as f: f.write(index_html) except Exception: traceback.print_exc(file=sys.stderr) sys.exit(-1) sys.exit() # Watch for any changes in the docs or style directories. dn_watch_files = [] observer = None if watch_changes: observer = Observer() observer.schedule(ReloadHandler(app), path=dir_documents, recursive=True) observer.start() dn_watch_files = build_reload_files_list([__name__, dir_style]) # Run the server. if args.set_host: try: print('Attempting set sevelopment server listen on public IP address: ' + args.set_host) print('WARNING: The Docnado development environment is intended to be used as a development tool ONLY, ' 'and is not recommended for use in a production environment.') app.run(debug=flask_debug, port=PORT_NUMBER, extra_files=dn_watch_files, host=args.set_host) except OSError as e: print(e) print(f'Error initialising server.') except KeyboardInterrupt: pass finally: if observer: observer.stop() observer.join() else: try: app.run(debug=flask_debug, port=PORT_NUMBER, extra_files=dn_watch_files) except OSError as e: print(e) print(f'Error initialising server.') except KeyboardInterrupt: pass finally: if observer: observer.stop() observer.join() # if running brainerd directly, boot the app if __name__ == "__main__": main()
37.782573
128
0.613078
e0f3298883d9924a9725a46789f9e295ab60fc80
15,155
py
Python
server/src/oscarbluelight/tests/offer/test_benefit_percentage.py
MaximBrewer/sebe
4b94b2c782d018b6fa3a130fa30173386cc9bfdd
[ "0BSD" ]
8
2016-06-18T01:40:26.000Z
2021-02-08T04:08:58.000Z
server/src/oscarbluelight/tests/offer/test_benefit_percentage.py
MaximBrewer/sebe
4b94b2c782d018b6fa3a130fa30173386cc9bfdd
[ "0BSD" ]
16
2018-05-04T13:00:07.000Z
2021-05-27T14:54:09.000Z
server/src/oscarbluelight/tests/offer/test_benefit_percentage.py
MaximBrewer/sebe
4b94b2c782d018b6fa3a130fa30173386cc9bfdd
[ "0BSD" ]
3
2016-12-19T11:30:47.000Z
2019-10-27T20:30:15.000Z
from decimal import Decimal as D from django.core import exceptions from django.test import TestCase from oscar.test import factories from oscar.test.basket import add_product, add_products from django_redis import get_redis_connection from oscarbluelight.offer.models import ( Range, Benefit, BluelightCountCondition, BluelightValueCondition, BluelightPercentageDiscountBenefit, ) from unittest import mock
45.374251
91
0.692577
e0f5092962647fb17fad330ad7ca8a057c8cedba
435
py
Python
CLCC/ex8.py
adstr123/LPTHW
1a331ef173ffd6122b5c5ed13d8fdcc73ab7ce66
[ "Zed" ]
null
null
null
CLCC/ex8.py
adstr123/LPTHW
1a331ef173ffd6122b5c5ed13d8fdcc73ab7ce66
[ "Zed" ]
null
null
null
CLCC/ex8.py
adstr123/LPTHW
1a331ef173ffd6122b5c5ed13d8fdcc73ab7ce66
[ "Zed" ]
null
null
null
# Moving around directories with pushd & popd # You can save directries to go back to later. These can be built up in a stack. #pushd i/like/icecream # current stack: ~temp/i/like/icecream #pushd i/like # current stack: ~temp/i/like ~temp/i/like/icecream #popd # PS ~temp/i/like #popd # PS ~temp/i/like/icecream # You can also add a directory as an argument to a pushd command to also immediately change to that directory
33.461538
109
0.728736
e0f7703f7d61c2e287ab471ebd07742e1540f442
15,577
py
Python
mkt/search/tests/test_filters.py
clouserw/zamboni
c4a568b69c1613f27da41d46328b2975cbdc1c07
[ "BSD-3-Clause" ]
null
null
null
mkt/search/tests/test_filters.py
clouserw/zamboni
c4a568b69c1613f27da41d46328b2975cbdc1c07
[ "BSD-3-Clause" ]
null
null
null
mkt/search/tests/test_filters.py
clouserw/zamboni
c4a568b69c1613f27da41d46328b2975cbdc1c07
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- import json from nose.tools import eq_, ok_ from rest_framework.exceptions import ParseError from django.contrib.auth.models import AnonymousUser from django.test.client import RequestFactory from django.test.utils import override_settings import mkt from mkt.constants.applications import DEVICE_CHOICES_IDS from mkt.constants.features import FeatureProfile from mkt.search.filters import (DeviceTypeFilter, ProfileFilter, PublicAppsFilter, PublicSearchFormFilter, RegionFilter, SearchQueryFilter, SortingFilter, ValidAppsFilter) from mkt.search.forms import TARAKO_CATEGORIES_MAPPING from mkt.search.views import SearchView from mkt.site.tests import TestCase from mkt.webapps.indexers import WebappIndexer
39.737245
79
0.560506
e0f788d3a6de0a5319ec594f010d2fc7e6bb3c93
3,206
py
Python
third_party/logging.py
sweeneyb/iot-core-micropython
7fc341902fbf8fa587f0dc3aa10c0803a5e0d6a5
[ "Apache-2.0" ]
50
2019-06-12T22:30:43.000Z
2022-02-22T18:30:26.000Z
third_party/logging.py
cashoefman/Resto-Score-for-Hack-2021-for-Positivity
cb3227c8db4b1be0e46cfe4b8d3973c1af4fe49b
[ "Apache-2.0" ]
12
2019-07-05T09:39:45.000Z
2022-03-12T05:45:01.000Z
third_party/logging.py
cashoefman/Resto-Score-for-Hack-2021-for-Positivity
cb3227c8db4b1be0e46cfe4b8d3973c1af4fe49b
[ "Apache-2.0" ]
16
2019-06-13T09:12:24.000Z
2022-03-12T05:47:22.000Z
# MIT License # # Copyright (c) 2019 Johan Brichau # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import sys CRITICAL = 50 ERROR = 40 WARNING = 30 INFO = 20 DEBUG = 10 NOTSET = 0 _level_dict = { CRITICAL: "CRIT", ERROR: "ERROR", WARNING: "WARN", INFO: "INFO", DEBUG: "DEBUG", } _stream = sys.stderr _level = INFO _loggers = {}
27.637931
80
0.647224
e0f88df1e0c707f34a922f07d69b31d76bda43ee
536
py
Python
assessments/migrations/0003_auto_20210212_1943.py
acounsel/django_msat
86a54e43429001cb6433e28b294d6b8a94b97e6e
[ "MIT" ]
null
null
null
assessments/migrations/0003_auto_20210212_1943.py
acounsel/django_msat
86a54e43429001cb6433e28b294d6b8a94b97e6e
[ "MIT" ]
null
null
null
assessments/migrations/0003_auto_20210212_1943.py
acounsel/django_msat
86a54e43429001cb6433e28b294d6b8a94b97e6e
[ "MIT" ]
null
null
null
# Generated by Django 3.1.6 on 2021-02-12 19:43 from django.db import migrations, models
28.210526
195
0.600746
e0f8b6be8671efa3ab8fb691c490862ecc07081d
668
py
Python
noxfile.py
sethmlarson/workplace-search-python
0680ce7144fc0608d3d8c336315ffaf7ddc3ca2d
[ "Apache-2.0" ]
5
2020-03-05T16:37:35.000Z
2021-02-26T03:44:09.000Z
noxfile.py
sethmlarson/workplace-search-python
0680ce7144fc0608d3d8c336315ffaf7ddc3ca2d
[ "Apache-2.0" ]
1
2019-01-08T20:10:16.000Z
2019-01-08T20:10:16.000Z
noxfile.py
sethmlarson/workplace-search-python
0680ce7144fc0608d3d8c336315ffaf7ddc3ca2d
[ "Apache-2.0" ]
1
2020-04-22T18:20:26.000Z
2020-04-22T18:20:26.000Z
import nox SOURCE_FILES = ( "setup.py", "noxfile.py", "elastic_workplace_search/", "tests/", )
20.242424
82
0.609281
e0f8ef5b2d2b11ceb48d819c7022ba608e70f8fd
17,241
py
Python
komodo2_rl/src/environments/Spawner.py
osheraz/komodo
d53759100ced7439dd501620f955f347087e4f63
[ "MIT" ]
5
2020-08-11T08:47:25.000Z
2022-02-15T06:19:18.000Z
komodo2_rl/src/environments/Spawner.py
osheraz/komodo
d53759100ced7439dd501620f955f347087e4f63
[ "MIT" ]
null
null
null
komodo2_rl/src/environments/Spawner.py
osheraz/komodo
d53759100ced7439dd501620f955f347087e4f63
[ "MIT" ]
1
2021-05-06T14:25:17.000Z
2021-05-06T14:25:17.000Z
# !/usr/bin/env python import rospy import numpy as np from gazebo_msgs.srv import SpawnModel, SpawnModelRequest, SpawnModelResponse from copy import deepcopy from tf.transformations import quaternion_from_euler sdf_cube = """<?xml version="1.0" ?> <sdf version="1.4"> <model name="MODELNAME"> <static>0</static> <link name="link"> <inertial> <mass>1.0</mass> <inertia> <ixx>0.01</ixx> <ixy>0.0</ixy> <ixz>0.0</ixz> <iyy>0.01</iyy> <iyz>0.0</iyz> <izz>0.01</izz> </inertia> </inertial> <collision name="stairs_collision0"> <pose>0 0 0 0 0 0</pose> <geometry> <box> <size>SIZEXYZ</size> </box> </geometry> <surface> <bounce /> <friction> <ode> <mu>1.0</mu> <mu2>1.0</mu2> </ode> </friction> <contact> <ode> <kp>10000000.0</kp> <kd>1.0</kd> <min_depth>0.0</min_depth> <max_vel>0.0</max_vel> </ode> </contact> </surface> </collision> <visual name="stairs_visual0"> <pose>0 0 0 0 0 0</pose> <geometry> <box> <size>SIZEXYZ</size> </box> </geometry> <material> <script> <uri>file://media/materials/scripts/gazebo.material</uri> <name>Gazebo/Wood</name> </script> </material> </visual> <velocity_decay> <linear>0.000000</linear> <angular>0.000000</angular> </velocity_decay> <self_collide>0</self_collide> <kinematic>0</kinematic> <gravity>1</gravity> </link> </model> </sdf> """ sdf_sand = """<?xml version='1.0'?> <sdf version='1.6'> <model name="MODELNAME"> <link name='link'> <pose frame=''>0 0 0.01 0 0 0 </pose> <inertial> <mass>1</mass> <inertia> <ixx>0.1</ixx> <ixy>0</ixy> <ixz>0</ixz> <iyy>0.1</iyy> <iyz>0</iyz> <izz>0.1</izz> </inertia> </inertial> <visual name='visual'> <pose frame=''>0 0 0 0 -0 0</pose> <geometry> <mesh> <scale>SIZEXYZ</scale> <uri>model://sand/sand_particle.stl</uri> </mesh> </geometry> <material> <lighting>1</lighting> <script> <uri>file://media/materials/scripts/gazebo.material</uri> <name>Gazebo/Yellow</name> </script> <ambient>0.3 0.25 0.1 1</ambient> <diffuse>0.7 0.6 0.4 1</diffuse> <specular>0.01 0.005 0.001 1</specular> <emissive>0 0 0 1</emissive> </material> <transparency>0</transparency> <cast_shadows>1</cast_shadows> </visual> <collision name='collision'> <laser_retro>0</laser_retro> <max_contacts>10</max_contacts> <pose frame=''>0 0 0 0 -0 0</pose> <geometry> <mesh> <scale>SIZEXYZ</scale> <uri>model://sand/sand_particle.stl</uri> </mesh> </geometry> <surface> <friction> <ode> <mu>1</mu> <mu2>1</mu2> <fdir1>0 0 0</fdir1> <slip1>0</slip1> <slip2>0</slip2> </ode> <torsional> <coefficient>1</coefficient> <patch_radius>0</patch_radius> <surface_radius>0</surface_radius> <use_patch_radius>1</use_patch_radius> <ode> <slip>0</slip> </ode> </torsional> </friction> <bounce> <restitution_coefficient>0.2</restitution_coefficient> <threshold>1.01</threshold> </bounce> <contact> <collide_without_contact>0</collide_without_contact> <collide_without_contact_bitmask>1</collide_without_contact_bitmask> <collide_bitmask>1</collide_bitmask> <ode> <soft_cfm>0</soft_cfm> <soft_erp>0.2</soft_erp> <kp>1e+13</kp> <kd>1</kd> <max_vel>0.01</max_vel> <min_depth>0</min_depth> </ode> <bullet> <split_impulse>1</split_impulse> <split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold> <soft_cfm>0</soft_cfm> <soft_erp>0.2</soft_erp> <kp>1e+13</kp> <kd>1</kd> </bullet> </contact> </surface> </collision> </link> <static>0</static> <allow_auto_disable>1</allow_auto_disable> </model> </sdf> """ sdf_sand_box = """<sdf version='1.6'> <model name='sand_box_osher'> <link name='sand_box_osher'> <pose frame=''>0 0 0 0 -0 0</pose> <inertial> <pose frame=''>-0.35285 -0.305 0.11027 0 -0 0</pose> <mass>2000.892</mass> <inertia> <ixx>130.2204</ixx> <ixy>-220.5538e-15</ixy> <ixz>-4.85191</ixz> <iyy>276.363</iyy> <iyz>-77.9029e-15</iyz> <izz>135.62</izz> </inertia> </inertial> <collision name='sand_box_osher_collision'> <pose frame=''>0 0 0 1.5708 -0 0</pose> <geometry> <mesh> <scale>1 0.8 1</scale> <uri>model://sand_box_osher/meshes/sand_box_osher.STL</uri> </mesh> </geometry> </collision> <visual name='sand_box_osher_visual'> <pose frame=''>0 0 0 1.5708 -0 0</pose> <geometry> <mesh> <scale>1 0.8 1</scale> <uri>model://sand_box_osher/meshes/sand_box_osher.STL</uri> </mesh> </geometry> <material> <ambient>0.3 0.25 0.1 1</ambient> <diffuse>0.7 0.6 0.4 1</diffuse> <specular>0.01 0.005 0.001 1</specular> <emissive>0 0 0 1</emissive> </material> <transparency>0.5</transparency> </visual> </link> </model> </sdf> """ sdf_unit_sphere = """<?xml version='1.0'?> <sdf version='1.6'> <model name="MODELNAME"> <link name='link'> <pose frame=''>0 0 0 0 -0 0</pose> <inertial> <mass>0.1</mass> <inertia> <ixx>0.0000490147</ixx> <ixy>0</ixy> <ixz>0</ixz> <iyy>0.000049147</iyy> <iyz>0</iyz> <izz>0.000049147</izz> </inertia> <pose frame=''>0 0 0 0 -0 0</pose> </inertial> <self_collide>0</self_collide> <kinematic>0</kinematic> <visual name='visual'> <geometry> <sphere> <radius>RADIUS</radius> </sphere> </geometry> <material> <lighting>1</lighting> <script> <uri>file://media/materials/scripts/gazebo.material</uri> <name>Gazebo/Yellow</name> </script> <ambient>0.3 0.25 0.1 1</ambient> <diffuse>0.7 0.6 0.4 1</diffuse> <specular>0.01 0.005 0.001 1</specular> <emissive>0 0 0 1</emissive> </material> <pose frame=''>0 0 0 0 -0 0</pose> <transparency>0</transparency> <cast_shadows>1</cast_shadows> </visual> <collision name='collision'> <laser_retro>0</laser_retro> <max_contacts>10</max_contacts> <pose frame=''>0 0 0 0 -0 0</pose> <geometry> <sphere> <radius>RADIUS</radius> </sphere> </geometry> <surface> <friction> <ode> <mu>1</mu> <mu2>1</mu2> <fdir1>0 0 0</fdir1> <slip1>0</slip1> <slip2>0</slip2> </ode> <torsional> <coefficient>1</coefficient> <patch_radius>0</patch_radius> <surface_radius>0</surface_radius> <use_patch_radius>1</use_patch_radius> <ode> <slip>0</slip> </ode> </torsional> </friction> <bounce> <restitution_coefficient>0</restitution_coefficient> <threshold>1e+06</threshold> </bounce> <contact> <collide_without_contact>0</collide_without_contact> <collide_without_contact_bitmask>1</collide_without_contact_bitmask> <collide_bitmask>1</collide_bitmask> <ode> <soft_cfm>0</soft_cfm> <soft_erp>0.2</soft_erp> <kp>1e+13</kp> <kd>1</kd> <max_vel>0.01</max_vel> <min_depth>0</min_depth> </ode> <bullet> <split_impulse>1</split_impulse> <split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold> <soft_cfm>0</soft_cfm> <soft_erp>0.2</soft_erp> <kp>1e+13</kp> <kd>1</kd> </bullet> </contact> </surface> </collision> </link> <static>0</static> <allow_auto_disable>1</allow_auto_disable> </model> </sdf> """ sdf_sand2 = """<?xml version='1.0'?> <sdf version='1.6'> <model name="MODELNAME"> <link name='link'> <pose frame=''>0 0 0.01 0 0 0 </pose> <inertial> <mass>1</mass> <inertia> <ixx>0.1</ixx> <ixy>0</ixy> <ixz>0</ixz> <iyy>0.1</iyy> <iyz>0</iyz> <izz>0.1</izz> </inertia> </inertial> <visual name='visual'> <pose frame=''>0 0 0 0 -0 0</pose> <geometry> <mesh> <scale>SIZEXYZ</scale> <uri>model://sand/sand_particle.stl</uri> </mesh> </geometry> <material> <lighting>1</lighting> <script> <uri>file://media/materials/scripts/gazebo.material</uri> <name>Gazebo/Yellow</name> </script> <ambient>0.3 0.25 0.1 1</ambient> <diffuse>0.7 0.6 0.4 1</diffuse> <specular>0.01 0.005 0.001 1</specular> <emissive>0 0 0 1</emissive> </material> <transparency>0</transparency> <cast_shadows>1</cast_shadows> </visual> <collision name='collision'> <laser_retro>0</laser_retro> <max_contacts>10</max_contacts> <pose frame=''>0 0 0 0 -0 0</pose> <geometry> <mesh> <scale>SIZEXYZ</scale> <uri>model://sand/sand_particle.stl</uri> </mesh> </geometry> <surface> <friction> <ode> <mu>1</mu> <mu2>1</mu2> <fdir1>0 0 0</fdir1> <slip1>0</slip1> <slip2>0</slip2> </ode> <torsional> <coefficient>1</coefficient> <patch_radius>0</patch_radius> <surface_radius>0</surface_radius> <use_patch_radius>1</use_patch_radius> <ode> <slip>0</slip> </ode> </torsional> </friction> <bounce> <restitution_coefficient>0</restitution_coefficient> <threshold>1e+06</threshold> </bounce> <contact> <collide_without_contact>0</collide_without_contact> <collide_without_contact_bitmask>1</collide_without_contact_bitmask> <collide_bitmask>1</collide_bitmask> <ode> <soft_cfm>0</soft_cfm> <soft_erp>0.2</soft_erp> <kp>1e+13</kp> <kd>1</kd> <max_vel>0.01</max_vel> <min_depth>0</min_depth> </ode> <bullet> <split_impulse>1</split_impulse> <split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold> <soft_cfm>0</soft_cfm> <soft_erp>0.2</soft_erp> <kp>1e+13</kp> <kd>1</kd> </bullet> </contact> </surface> </collision> </link> <static>0</static> <allow_auto_disable>1</allow_auto_disable> </model> </sdf> """
33.283784
108
0.463198
e0f9e97bf2ab57eb94b8a3dc17de1f26affd17b5
121
py
Python
output/models/ms_data/regex/re_l32_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
1
2021-08-14T17:59:21.000Z
2021-08-14T17:59:21.000Z
output/models/ms_data/regex/re_l32_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
4
2020-02-12T21:30:44.000Z
2020-04-15T20:06:46.000Z
output/models/ms_data/regex/re_l32_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
null
null
null
from output.models.ms_data.regex.re_l32_xsd.re_l32 import ( Regex, Doc, ) __all__ = [ "Regex", "Doc", ]
12.1
59
0.603306
e0f9f1296b023c0d6516cc11729dc5f2eb6ecdd7
4,291
py
Python
sdk/python/tests/dsl/metadata_tests.py
ConverJens/pipelines
a1d453af214ec9eebad73fb05845dd3499d60d00
[ "Apache-2.0" ]
6
2020-05-19T02:35:11.000Z
2020-05-29T17:58:42.000Z
sdk/python/tests/dsl/metadata_tests.py
ConverJens/pipelines
a1d453af214ec9eebad73fb05845dd3499d60d00
[ "Apache-2.0" ]
1,932
2021-01-25T11:23:37.000Z
2022-03-31T17:10:18.000Z
sdk/python/tests/dsl/metadata_tests.py
ConverJens/pipelines
a1d453af214ec9eebad73fb05845dd3499d60d00
[ "Apache-2.0" ]
11
2020-05-19T22:26:41.000Z
2021-01-25T09:56:21.000Z
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from kfp.components.structures import ComponentSpec, InputSpec, OutputSpec import unittest
42.91
88
0.316476
e0fb958c05e67ba3756a0924303bc1ac81028564
644
py
Python
challenges/python-solutions/day-25.py
elifloresch/thirty-days-challenge
d3d41f5ce8cc4155ebf9cf52c1ece43c15a1e2af
[ "MIT" ]
null
null
null
challenges/python-solutions/day-25.py
elifloresch/thirty-days-challenge
d3d41f5ce8cc4155ebf9cf52c1ece43c15a1e2af
[ "MIT" ]
null
null
null
challenges/python-solutions/day-25.py
elifloresch/thirty-days-challenge
d3d41f5ce8cc4155ebf9cf52c1ece43c15a1e2af
[ "MIT" ]
null
null
null
import math test_cases = int(input()) numbers = [] for test_case in range(test_cases): numbers.append(int(input())) for n in numbers: if is_prime_number(n): print('Prime') else: print('Not prime')
19.515152
58
0.57764
e0fbf814aa561afb0f3e8aefc0b444cab5d08bda
1,265
py
Python
examples/path_config.py
rnixx/garden.cefpython
91d5f69e9983a28ce1971637d7d2f0051c456882
[ "MIT" ]
13
2017-02-10T12:07:29.000Z
2021-12-15T02:07:07.000Z
examples/path_config.py
Informatic/garden.cefpython
b7a03d31fd18a32a44ae293d4101b4cf7608795b
[ "MIT" ]
22
2015-02-13T09:58:30.000Z
2015-06-12T08:55:20.000Z
examples/path_config.py
Informatic/garden.cefpython
b7a03d31fd18a32a44ae293d4101b4cf7608795b
[ "MIT" ]
12
2017-05-03T01:18:31.000Z
2021-10-01T06:57:41.000Z
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ Minimal example of the CEFBrowser widget use. Here you don't have any controls (back / forth / reload) or whatsoever. Just a kivy app displaying the chromium-webview. In this example we demonstrate how the cache path of CEF can be set. """ import os from kivy.app import App from kivy.garden.cefpython import CEFBrowser from kivy.logger import Logger if __name__ == '__main__': SimpleBrowserApp().run()
34.189189
78
0.656917
e0fc122c2f5c222700dce3588b9faccba2d8800b
312
py
Python
simple-systems/and_xor_shift.py
laserbat/random-projects
925f94f80299df6f16e91975e89f5fff7df20005
[ "WTFPL" ]
3
2019-04-14T12:29:10.000Z
2020-02-26T22:27:04.000Z
simple-systems/and_xor_shift.py
laserbat/random-projects
925f94f80299df6f16e91975e89f5fff7df20005
[ "WTFPL" ]
null
null
null
simple-systems/and_xor_shift.py
laserbat/random-projects
925f94f80299df6f16e91975e89f5fff7df20005
[ "WTFPL" ]
1
2020-06-08T22:12:16.000Z
2020-06-08T22:12:16.000Z
#!/usr/bin/python3 # If F(a) is any function that can be defined as composition of bitwise XORs, ANDs and left shifts # Then the dynac system x_(n+1) = F(x_n) is Turing complete # Proof by simulation (rule110) a = 1 while a: print(bin(a)) a = a ^ (a << 1) ^ (a & (a << 1)) ^ (a & (a << 1) & (a << 2))
26
98
0.589744
e0fc7fc48d25fb30b40c2e42b598b6eff6d50954
5,543
py
Python
trinity/protocol/common/peer_pool_event_bus.py
Gauddel/trinity
0b12943ac36f4090abc22fc965e9e9a4f42c6f35
[ "MIT" ]
null
null
null
trinity/protocol/common/peer_pool_event_bus.py
Gauddel/trinity
0b12943ac36f4090abc22fc965e9e9a4f42c6f35
[ "MIT" ]
null
null
null
trinity/protocol/common/peer_pool_event_bus.py
Gauddel/trinity
0b12943ac36f4090abc22fc965e9e9a4f42c6f35
[ "MIT" ]
null
null
null
from abc import ( abstractmethod, ) from typing import ( Any, Callable, cast, FrozenSet, Generic, Type, TypeVar, ) from cancel_token import ( CancelToken, ) from p2p.exceptions import ( PeerConnectionLost, ) from p2p.kademlia import Node from p2p.peer import ( BasePeer, PeerSubscriber, ) from p2p.peer_pool import ( BasePeerPool, ) from p2p.protocol import ( Command, PayloadType, ) from p2p.service import ( BaseService, ) from trinity.endpoint import ( TrinityEventBusEndpoint, ) from .events import ( ConnectToNodeCommand, DisconnectPeerEvent, HasRemoteEvent, PeerCountRequest, PeerCountResponse, ) TPeer = TypeVar('TPeer', bound=BasePeer) TStreamEvent = TypeVar('TStreamEvent', bound=HasRemoteEvent)
33.391566
99
0.625293
e0fe475b8134a31f2b77a708e5769cd268cfc749
18,488
py
Python
tests/e2e/performance/csi_tests/test_pvc_creation_deletion_performance.py
annagitel/ocs-ci
284fe04aeb6e3d6cb70c99e65fec8ff1b1ea1dd5
[ "MIT" ]
1
2019-09-17T08:38:05.000Z
2019-09-17T08:38:05.000Z
tests/e2e/performance/csi_tests/test_pvc_creation_deletion_performance.py
annagitel/ocs-ci
284fe04aeb6e3d6cb70c99e65fec8ff1b1ea1dd5
[ "MIT" ]
1
2021-08-30T20:06:00.000Z
2021-09-30T20:05:46.000Z
tests/e2e/performance/csi_tests/test_pvc_creation_deletion_performance.py
annagitel/ocs-ci
284fe04aeb6e3d6cb70c99e65fec8ff1b1ea1dd5
[ "MIT" ]
2
2019-09-17T10:04:14.000Z
2022-02-07T16:36:49.000Z
""" Test to verify performance of PVC creation and deletion for RBD, CephFS and RBD-Thick interfaces """ import time import logging import datetime import pytest import ocs_ci.ocs.exceptions as ex import threading import statistics from concurrent.futures import ThreadPoolExecutor from uuid import uuid4 from ocs_ci.framework.testlib import performance from ocs_ci.ocs.perftests import PASTest from ocs_ci.helpers import helpers, performance_lib from ocs_ci.ocs import constants from ocs_ci.helpers.helpers import get_full_test_logs_path from ocs_ci.ocs.perfresult import PerfResult from ocs_ci.framework import config log = logging.getLogger(__name__)
38.119588
119
0.59855
e0fe959730942d4fbe3c43eb35ca77c0cc852bbc
1,233
py
Python
templates/t/searchresult_withnone.py
MikeBirdsall/food-log
5edc1fa515d5e2721e96afb7d2b437296903a31d
[ "MIT" ]
null
null
null
templates/t/searchresult_withnone.py
MikeBirdsall/food-log
5edc1fa515d5e2721e96afb7d2b437296903a31d
[ "MIT" ]
27
2017-07-01T19:20:48.000Z
2019-03-07T06:04:22.000Z
templates/t/searchresult_withnone.py
MikeBirdsall/food-log
5edc1fa515d5e2721e96afb7d2b437296903a31d
[ "MIT" ]
null
null
null
#!/usr/bin/python3 from jinja2 import Environment, FileSystemLoader results = [ dict( description="Noodles and Company steak Stromboli", comment="", size="small", cals=530, carbs=50, fat=25, protein=27, score=30), dict( description="Steak sandwich", comment="", size="4 oz and bun", cals=480, carbs=44, fat=20, protein=27, score=30), dict( description="chipotle tacos", comment="Steak, no beans, gu...", size="", cals=285, carbs=None, fat=16, protein=None, score=30), dict( description="Steak Sandwich", comment="", size="", cals=380, carbs=45, fat=3.5, protein=34, score=30), ] input_ = dict( title="Search for Courses", h1="Full Text Search: steak NOT shake", results=results, ) env = Environment(loader=FileSystemLoader("..")) env.filters['spacenone'] = spacenone template = env.get_template("searchresult.html") output = template.render(input_) print(output)
19.887097
58
0.544201
e0ff8f36b2a500b9d978be307fa6e00f7161603f
2,146
py
Python
payments/views.py
aman-roy/pune.pycon.org
f56cc948bd56767110d337c694ecbf5540bdf4b9
[ "MIT" ]
null
null
null
payments/views.py
aman-roy/pune.pycon.org
f56cc948bd56767110d337c694ecbf5540bdf4b9
[ "MIT" ]
null
null
null
payments/views.py
aman-roy/pune.pycon.org
f56cc948bd56767110d337c694ecbf5540bdf4b9
[ "MIT" ]
null
null
null
from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from payments.models import Invoice, RazorpayKeys from payments.razorpay.razorpay_payments import RazorpayPayments from payments.models import Payment, Order import json
40.490566
91
0.66356
e0ff97e8d61ff585dcd9a0102ba24b2e2528bca2
6,541
py
Python
src/convnet/image_classifier.py
danschef/gear-detector
153d1031778f183ac38edf0532d2f266029c5ea7
[ "MIT" ]
1
2020-07-15T20:12:55.000Z
2020-07-15T20:12:55.000Z
src/convnet/image_classifier.py
danschef/gear-detector
153d1031778f183ac38edf0532d2f266029c5ea7
[ "MIT" ]
null
null
null
src/convnet/image_classifier.py
danschef/gear-detector
153d1031778f183ac38edf0532d2f266029c5ea7
[ "MIT" ]
null
null
null
import configparser import os import sys from time import localtime, strftime, mktime import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from net import Net from geo_helper import store_image_bounds from image_helper import CLASSES from image_helper import save_image from image_helper import test_set_loader from image_helper import train_set_loader from image_helper import validation_set_loader CONFIG = configparser.ConfigParser() CONFIG.read('./src/config.ini') ########################################### # Training Stage ########################################### ##################################### # Validation stage ##################################### ##################################### # Prediction stage ##################################### ################################################################ # Train network or use existing one for prediction ################################################################ main()
31.599034
92
0.581257
46004af1bf9a4f4788952ff849b76ab958f79e1c
3,035
py
Python
src/modules/AlphabetPlotter.py
aaanh/duplicated_accelcamp
7d4b60ace023bede907f8ed367ba492731a1951d
[ "FTL", "CNRI-Python", "RSA-MD" ]
null
null
null
src/modules/AlphabetPlotter.py
aaanh/duplicated_accelcamp
7d4b60ace023bede907f8ed367ba492731a1951d
[ "FTL", "CNRI-Python", "RSA-MD" ]
2
2021-05-21T16:31:41.000Z
2021-08-25T16:05:48.000Z
src/modules/AlphabetPlotter.py
aaanh/duplicated_accelcamp
7d4b60ace023bede907f8ed367ba492731a1951d
[ "FTL", "CNRI-Python", "RSA-MD" ]
null
null
null
import tkinter as tk from tkinter import filedialog import csv import matplotlib.pyplot as plt root = tk.Tk(screenName=':0.0') root.withdraw() file_path = filedialog.askopenfilename() lastIndex = len(file_path.split('/')) - 1 v0 = [0, 0, 0] x0 = [0, 0, 0] fToA = 1 error = 0.28 errorZ = 3 t = [] time = [] m = [[] for i in range(3)] magnitude = [[] for i in range(3)] shift_x = 0 shift_y = 0 # For when the data starts at (2,1) if file_path.split('/')[lastIndex].split('.')[2] == "pocket": shift_x = 2 shift_y = 1 error = 0.3 fToA = 1 # For when the data starts at (0,0) elif file_path.split('/')[lastIndex].split('.')[2] == "pocket_mobile": shift_x = 0 shift_y = 0 error = 0.3 fToA = 1 # For when the data starts at (1,0) elif file_path.split('/')[lastIndex].split('.')[2] == "android": shift_x = 0 shift_y = 1 error = 0.02 fToA = 9.81 errorZ = 100 shift = 0 uselessboolean = True with open(file_path, 'r+') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: if shift < shift_y: shift += 1 else: t = row[shift_x] m[0] = row[1 + shift_x] m[1] = row[2 + shift_x] m[2] = row[3 + shift_x] time.append(float(t)) for i in range(0, 3): magnitude[i].append(float(m[i]) if abs(float(m[i])) > error else 0) acceleration = [[(j * fToA) for j in i] for i in magnitude] acceleration[2] = [i - 9.805 for i in acceleration[2]] # Translates Data into Position velocity = [[0 for i in time] for i in range(3)] position = [[0 for i in time] for i in range(3)] for j in range(3): velocity[j][0] = v0[j] for i in range(1, len(time)): velocity[j][i] = velocity[j][i - 1] + acceleration[j][i - 1] * (time[i] - time[i - 1]) for j in range(3): position[j][0] = x0[j] for i in range(1, len(time)): position[j][i] = position[j][i - 1] + velocity[j][i - 1] * (time[i] - time[i - 1]) for i in range(len(acceleration[2])): if abs(velocity[2][i]) > errorZ: position[0][i] = 0 position[1][i] = 0 fig, axs = plt.subplots(2) axs[0].plot(time, acceleration[0]) axs[0].set_xlabel('Time (s)') axs[0].set_ylabel('AccelerationX (m/s^2)') axs[1].plot(time, acceleration[1]) axs[1].set_xlabel('Time (s)') axs[1].set_ylabel('AccelerationY (m/s^2)') ''' axs[2].scatter(time, acceleration[2]) axs[2].set_xlabel('Time (s)') axs[2].set_ylabel('AccelerationZ (m/s^2)') axs[3].scatter(time, velocity[2]) axs[3].set_xlabel('Time (s)') axs[3].set_ylabel('VelocityZ (m/s)') axs[4].scatter(time, position[2]) axs[4].set_xlabel('Time (s)') axs[4].set_ylabel('PositionZ (m)') axs.scatter(position[0], position[1], marker = "_", linewidth = 70) axs.set_xlabel('PositionX') axs.set_ylabel('PositionY') plt.plot(position[0], position[1], marker = '_', markersize = 30, linewidth = 3, markeredgewidth = 10)''' plt.show()
29.182692
106
0.577595
46023337d875860607f4a1fabbf53f963a80b88e
2,647
py
Python
users/migrations/0008_profile_fields_optional.py
mitodl/mit-xpro
981d6c87d963837f0b9ccdd996067fe81394dba4
[ "BSD-3-Clause" ]
10
2019-02-20T18:41:32.000Z
2021-07-26T10:39:58.000Z
users/migrations/0008_profile_fields_optional.py
mitodl/mit-xpro
981d6c87d963837f0b9ccdd996067fe81394dba4
[ "BSD-3-Clause" ]
2,226
2019-02-20T20:03:57.000Z
2022-03-31T11:18:56.000Z
users/migrations/0008_profile_fields_optional.py
mitodl/mit-xpro
981d6c87d963837f0b9ccdd996067fe81394dba4
[ "BSD-3-Clause" ]
4
2020-08-26T19:26:02.000Z
2021-03-09T17:46:47.000Z
# Generated by Django 2.2.3 on 2019-07-15 19:24 from django.db import migrations, models def backpopulate_incomplete_profiles(apps, schema): """Backpopulate users who don't have a profile record""" User = apps.get_model("users", "User") Profile = apps.get_model("users", "Profile") for user in User.objects.annotate( has_profile=models.Exists(Profile.objects.filter(user=models.OuterRef("pk"))) ).filter(has_profile=False): Profile.objects.get_or_create(user=user) def remove_incomplete_profiles(apps, schema): """Delete records that will cause rollbacks on nullable/blankable fields to fail""" Profile = apps.get_model("users", "Profile") Profile.objects.filter( models.Q(birth_year__isnull=True) | models.Q(gender__exact="") | models.Q(job_title__exact="") | models.Q(company__exact="") ).delete()
32.280488
87
0.574613
4602886d15507fa511fee4f9d72dd974724d982f
33,743
py
Python
test/unit_testing/grid/element_linear_dx_data/test_element_linearC/element/geom_element_AD.py
nwukie/ChiDG
d096548ba3bd0a338a29f522fb00a669f0e33e9b
[ "BSD-3-Clause" ]
36
2016-10-05T15:12:22.000Z
2022-03-17T02:08:23.000Z
test/unit_testing/grid/element_linear_dx_data/test_element_linearC/element/geom_element_AD.py
nwukie/ChiDG
d096548ba3bd0a338a29f522fb00a669f0e33e9b
[ "BSD-3-Clause" ]
17
2016-05-17T02:21:05.000Z
2017-08-10T16:33:07.000Z
test/unit_testing/grid/element_linear_dx_data/test_element_linearC/element/geom_element_AD.py
nwukie/ChiDG
d096548ba3bd0a338a29f522fb00a669f0e33e9b
[ "BSD-3-Clause" ]
20
2016-07-18T16:20:47.000Z
2020-11-27T19:26:12.000Z
from __future__ import division import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import sys import os import time # # TORCH INSTALLATION: refer to https://pytorch.org/get-started/locally/ # cls() ################################################################################################################ # Initialize torch tensor for coordiantes coords_data = [[ 0.0 , 0.0 , 0.0 ], [ 1.0/(2.0**0.5), 0.0 , 1.0/(2.0**0.5)], [ 1.0/(2.0**0.5), 0.0 ,-1.0/(2.0**0.5)], [ 2.0**0.5 , 0.0 , 0.0 ], [ 0.0 , 1.0 , 0.0 ], [ 1.0/(2.0**0.5), 1.0 , 1.0/(2.0**0.5)], [ 1.0/(2.0**0.5), 1.0 ,-1.0/(2.0**0.5)], [ 2.0**0.5 , 1.0 , 0.0 ], ] coords = torch.tensor(coords_data,requires_grad=True,dtype=torch.float64) nnodes_r = coords.size(0) nnodes_ie = 8 nnodes_if = 4 nterms_s = 8 ndirs = 3 coord_sys = 'CARTESIAN' # Define matrix of polynomial basis terms at support nodes val_r_data = [[ 1.0,-1.0,-1.0,-1.0, 1.0, 1.0, 1.0,-1.0], [ 1.0,-1.0,-1.0, 1.0,-1.0,-1.0, 1.0, 1.0], [ 1.0, 1.0,-1.0,-1.0,-1.0, 1.0,-1.0, 1.0], [ 1.0, 1.0,-1.0, 1.0, 1.0,-1.0,-1.0,-1.0], [ 1.0,-1.0, 1.0,-1.0, 1.0,-1.0,-1.0, 1.0], [ 1.0,-1.0, 1.0, 1.0,-1.0, 1.0,-1.0,-1.0], [ 1.0, 1.0, 1.0,-1.0,-1.0,-1.0, 1.0,-1.0], [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], ] val_r = torch.tensor(val_r_data,requires_grad=False,dtype=torch.float64) # Define matrices at interpolation nodes (quadrature, level = 1) val_i_data = [[ 1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0, 1.0/3.0, 1.0/3.0,-1.0/3.0*np.sqrt(1.0/3.0)], [ 1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0,-1.0/3.0, 1.0/3.0, 1.0/3.0*np.sqrt(1.0/3.0)], [ 1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0, 1.0/3.0,-1.0/3.0, 1.0/3.0*np.sqrt(1.0/3.0)], [ 1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0,-1.0/3.0,-1.0/3.0,-1.0/3.0*np.sqrt(1.0/3.0)], [ 1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0,-1.0/3.0,-1.0/3.0, 1.0/3.0*np.sqrt(1.0/3.0)], [ 1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0, 1.0/3.0,-1.0/3.0,-1.0/3.0*np.sqrt(1.0/3.0)], [ 1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0,-1.0/3.0, 1.0/3.0,-1.0/3.0*np.sqrt(1.0/3.0)], [ 1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0, 1.0/3.0, 1.0/3.0, 1.0/3.0*np.sqrt(1.0/3.0)], ] val_i = torch.tensor(val_i_data,requires_grad=False,dtype=torch.float64) ddxi_i_data = [[ 0.0,0.0,0.0,1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),0.0, 1.0/3.0], [ 0.0,0.0,0.0,1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),0.0, 1.0/3.0], [ 0.0,0.0,0.0,1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),0.0,-1.0/3.0], [ 0.0,0.0,0.0,1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),0.0,-1.0/3.0], [ 0.0,0.0,0.0,1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),0.0,-1.0/3.0], [ 0.0,0.0,0.0,1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),0.0,-1.0/3.0], [ 0.0,0.0,0.0,1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),0.0, 1.0/3.0], [ 0.0,0.0,0.0,1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),0.0, 1.0/3.0], ] ddxi_i = torch.tensor(ddxi_i_data,requires_grad=False,dtype=torch.float64) ddeta_i_data = [[ 0.0,1.0,0.0,0.0,-np.sqrt(1.0/3.0),0.0,-np.sqrt(1.0/3.0), 1.0/3.0], [ 0.0,1.0,0.0,0.0, np.sqrt(1.0/3.0),0.0,-np.sqrt(1.0/3.0),-1.0/3.0], [ 0.0,1.0,0.0,0.0,-np.sqrt(1.0/3.0),0.0,-np.sqrt(1.0/3.0), 1.0/3.0], [ 0.0,1.0,0.0,0.0, np.sqrt(1.0/3.0),0.0,-np.sqrt(1.0/3.0),-1.0/3.0], [ 0.0,1.0,0.0,0.0,-np.sqrt(1.0/3.0),0.0, np.sqrt(1.0/3.0),-1.0/3.0], [ 0.0,1.0,0.0,0.0, np.sqrt(1.0/3.0),0.0, np.sqrt(1.0/3.0), 1.0/3.0], [ 0.0,1.0,0.0,0.0,-np.sqrt(1.0/3.0),0.0, np.sqrt(1.0/3.0),-1.0/3.0], [ 0.0,1.0,0.0,0.0, np.sqrt(1.0/3.0),0.0, np.sqrt(1.0/3.0), 1.0/3.0], ] ddeta_i = torch.tensor(ddeta_i_data,requires_grad=False,dtype=torch.float64) ddzeta_i_data= [[ 0.0,0.0,1.0,0.0,0.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0], [ 0.0,0.0,1.0,0.0,0.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0], [ 0.0,0.0,1.0,0.0,0.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0], [ 0.0,0.0,1.0,0.0,0.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0], [ 0.0,0.0,1.0,0.0,0.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0], [ 0.0,0.0,1.0,0.0,0.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0], [ 0.0,0.0,1.0,0.0,0.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0], [ 0.0,0.0,1.0,0.0,0.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0], ] ddzeta_i = torch.tensor(ddzeta_i_data,requires_grad=False,dtype=torch.float64) # Define element interpolation nodes weights for linear element weights_e_data = [1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0] weights_e = torch.tensor(weights_e_data,requires_grad=False,dtype=torch.float64) # Define val_f for each face # Face 1, XI_MIN val_1_data = [[ 1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0,-1.0/3.0], [ 1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0, 1.0/3.0], [ 1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0, 1.0/3.0], [ 1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0,-1.0/3.0], ] val_1 = torch.tensor(val_1_data,requires_grad=False,dtype=torch.float64) # Face 2, XI_MAX val_2_data = [[ 1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0, 1.0/3.0], [ 1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0,-1.0/3.0], [ 1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0,-1.0/3.0], [ 1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0, 1.0/3.0], ] val_2 = torch.tensor(val_2_data,requires_grad=False,dtype=torch.float64) # Face 3, ETA_MIN val_3_data = [[ 1.0,-1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0, np.sqrt(1.0/3.0),-1.0/3.0], [ 1.0,-1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0, np.sqrt(1.0/3.0), 1.0/3.0], [ 1.0,-1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0,-np.sqrt(1.0/3.0), 1.0/3.0], [ 1.0,-1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0,-np.sqrt(1.0/3.0),-1.0/3.0], ] val_3 = torch.tensor(val_3_data,requires_grad=False,dtype=torch.float64) # Face 4, ETA_MAX val_4_data = [[ 1.0,1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0,-np.sqrt(1.0/3.0), 1.0/3.0], [ 1.0,1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0,-np.sqrt(1.0/3.0),-1.0/3.0], [ 1.0,1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0, np.sqrt(1.0/3.0),-1.0/3.0], [ 1.0,1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0, np.sqrt(1.0/3.0), 1.0/3.0], ] val_4 = torch.tensor(val_4_data,requires_grad=False,dtype=torch.float64) # Face 5, ZETA_MIN val_5_data = [[ 1.0,-np.sqrt(1.0/3.0),-1.0,-np.sqrt(1.0/3.0), 1.0/3.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0], [ 1.0,-np.sqrt(1.0/3.0),-1.0, np.sqrt(1.0/3.0),-1.0/3.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0], [ 1.0, np.sqrt(1.0/3.0),-1.0,-np.sqrt(1.0/3.0),-1.0/3.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0], [ 1.0, np.sqrt(1.0/3.0),-1.0, np.sqrt(1.0/3.0), 1.0/3.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0], ] val_5 = torch.tensor(val_5_data,requires_grad=False,dtype=torch.float64) # Face 6, ZETA_MAX val_6_data = [[ 1.0,-np.sqrt(1.0/3.0),1.0,-np.sqrt(1.0/3.0), 1.0/3.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0], [ 1.0,-np.sqrt(1.0/3.0),1.0, np.sqrt(1.0/3.0),-1.0/3.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0], [ 1.0, np.sqrt(1.0/3.0),1.0,-np.sqrt(1.0/3.0),-1.0/3.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0], [ 1.0, np.sqrt(1.0/3.0),1.0, np.sqrt(1.0/3.0), 1.0/3.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0], ] val_6 = torch.tensor(val_6_data,requires_grad=False,dtype=torch.float64) #-------------------------------------------------------------------- # Matrix modes_to_nodes val_r_inv = torch.inverse(val_r) # Computes coordiantes modes coords_modes = torch.mm(val_r_inv,coords) # Initialized coordiantes interp_coords = torch.mm(val_i,coords_modes) # Initialized jacobian jacobian = torch.empty(3,3,nnodes_ie, dtype=torch.float64) for inode in range(0,nnodes_ie): jacobian[0,0,inode] = torch.dot(ddxi_i[inode,:] , coords_modes[:,0]) jacobian[0,1,inode] = torch.dot(ddeta_i[inode,:] , coords_modes[:,0]) jacobian[0,2,inode] = torch.dot(ddzeta_i[inode,:] , coords_modes[:,0]) jacobian[1,0,inode] = torch.dot(ddxi_i[inode,:] , coords_modes[:,1]) jacobian[1,1,inode] = torch.dot(ddeta_i[inode,:] , coords_modes[:,1]) jacobian[1,2,inode] = torch.dot(ddzeta_i[inode,:] , coords_modes[:,1]) jacobian[2,0,inode] = torch.dot(ddxi_i[inode,:] , coords_modes[:,2]) jacobian[2,1,inode] = torch.dot(ddeta_i[inode,:] , coords_modes[:,2]) jacobian[2,2,inode] = torch.dot(ddzeta_i[inode,:] , coords_modes[:,2]) update_progress("Computing Jacobian ", inode/(nnodes_ie-1)) if coord_sys == 'CYLINDRICAL': scaling_factor = torch.mm(val_i,coords_modes[:,0]) for inode in range(0,nnodes_ie): jacobian[1,0,inode] = jacobian[1,0,inode] * scaling_factor[inode] jacobian[1,1,inode] = jacobian[1,1,inode] * scaling_factor[inode] jacobian[1,2,inode] = jacobian[1,2,inode] * scaling_factor[inode] # Matrics and Determinant metrics = torch.empty(3,3,nnodes_ie, dtype=torch.float64) jinv = torch.empty(nnodes_ie, dtype=torch.float64) for inode in range(0,nnodes_ie): ijacobian = torch.empty(3,3, dtype=torch.float64) imetric = torch.empty(3,3, dtype=torch.float64) for irow in range(0,3): for icol in range(0,3): ijacobian[irow,icol] = jacobian[irow,icol,inode] # Compute jacobian for the ith node update_progress("Computing Jinv and Metric ", inode/(nnodes_ie-1)) jinv[inode] = torch.det(ijacobian) imetric = torch.inverse(ijacobian) for irow in range(0,3): for icol in range(0,3): metrics[irow,icol,inode] = imetric[irow,icol] # Compute inverse Mass matrix invmass = torch.empty(nterms_s,nterms_s,nnodes_ie, dtype=torch.float64) mass = torch.empty(nterms_s,nterms_s,nnodes_ie, dtype=torch.float64) val_tmp = torch.empty(nterms_s,nnodes_ie, dtype=torch.float64) i = 1 for iterm in range(0,nterms_s): for inode in range(0,nnodes_ie): val_tmp[inode,iterm] = val_i[inode,iterm] * weights_e[inode] * jinv[inode] update_progress("Computing invmass ", i/(nterms_s*nnodes_ie)) i += 1 mass = torch.mm(torch.t(val_tmp),val_i) invmass = torch.inverse(mass) # Compute BR2_VOL for each face br2_vol_face1 = torch.mm(val_i,torch.mm(invmass,torch.t(val_1))) br2_vol_face2 = torch.mm(val_i,torch.mm(invmass,torch.t(val_2))) br2_vol_face3 = torch.mm(val_i,torch.mm(invmass,torch.t(val_3))) br2_vol_face4 = torch.mm(val_i,torch.mm(invmass,torch.t(val_4))) br2_vol_face5 = torch.mm(val_i,torch.mm(invmass,torch.t(val_5))) br2_vol_face6 = torch.mm(val_i,torch.mm(invmass,torch.t(val_6))) update_progress("Computing br2_vol ", 1) # Compute BR2_FACE for each face br2_face_face1 = torch.mm(val_1,torch.mm(invmass,torch.t(val_1))) br2_face_face2 = torch.mm(val_2,torch.mm(invmass,torch.t(val_2))) br2_face_face3 = torch.mm(val_3,torch.mm(invmass,torch.t(val_3))) br2_face_face4 = torch.mm(val_4,torch.mm(invmass,torch.t(val_4))) br2_face_face5 = torch.mm(val_5,torch.mm(invmass,torch.t(val_5))) br2_face_face6 = torch.mm(val_6,torch.mm(invmass,torch.t(val_6))) update_progress("Computing br2_face ", 1) # Grad1, Grad2, and Grad3 grad1 = torch.empty(nnodes_ie,nterms_s, dtype=torch.float64) grad2 = torch.empty(nnodes_ie,nterms_s, dtype=torch.float64) grad3 = torch.empty(nnodes_ie,nterms_s, dtype=torch.float64) i = 1 for iterm in range(0,nterms_s): for inode in range(0,nnodes_ie): grad1[inode,iterm] = metrics[0,0,inode] * ddxi_i[inode,iterm] + metrics[1,0,inode] * ddeta_i[inode,iterm] + metrics[2,0,inode] * ddzeta_i[inode,iterm] grad2[inode,iterm] = metrics[0,1,inode] * ddxi_i[inode,iterm] + metrics[1,1,inode] * ddeta_i[inode,iterm] + metrics[2,1,inode] * ddzeta_i[inode,iterm] grad3[inode,iterm] = metrics[0,2,inode] * ddxi_i[inode,iterm] + metrics[1,2,inode] * ddeta_i[inode,iterm] + metrics[2,2,inode] * ddzeta_i[inode,iterm] update_progress("Computing grad1, grad2, grad3 ", i/(nnodes_ie*nterms_s)) i += 1 #WRITE_____________________ # # Metrics # f = open("metrics.txt","w") i = 1 for inode in range (0,nnodes_ie): f.write("Metric interpolation node %d \n" % (inode+1)) array = np.zeros([3, 3]) for irow in range(0,3): for icol in range(0,3): array[irow,icol] = metrics[irow,icol,inode].item() update_progress("Writing metrics to file ", i/(nnodes_ie*9)) i += 1 np.savetxt(f,array) f.close() # # jinv # f = open("jinv.txt","w") array = np.zeros([1]) i = 1 for inode in range (0,nnodes_ie): f.write("Jinv interpolation node %d \n" % (inode+1)) array[0] = jinv[inode].item() np.savetxt(f,array) update_progress("Writing jinv to file ", i/(nnodes_ie)) i += 1 f.close() # # Grad1 # f = open("grad1.txt","w") f.write("Grad1 \n") array = np.zeros([nnodes_ie,nterms_s]) i = 1 for inode in range (0,nnodes_ie): for iterm in range(0,nterms_s): array[inode,iterm] = grad1[inode,iterm].item() update_progress("Writing grad1 to file ", i/(nnodes_ie*nterms_s)) i += 1 np.savetxt(f,array) f.close() # # Grad2 # f = open("grad2.txt","w") f.write("Grad2 \n") array = np.zeros([nnodes_ie,nterms_s]) i = 1 for inode in range (0,nnodes_ie): for iterm in range(0,nterms_s): array[inode,iterm] = grad2[inode,iterm].item() update_progress("Writing grad2 to file ", i/(nnodes_ie*nterms_s)) i += 1 np.savetxt(f,array) f.close() # # Grad3 # f = open("grad3.txt","w") f.write("Grad3 \n") array = np.zeros([nnodes_ie,nterms_s]) i = 1 for inode in range (0,nnodes_ie): for iterm in range(0,nterms_s): array[inode,iterm] = grad3[inode,iterm].item() update_progress("Writing grad3 to file ", i/(nnodes_ie*nterms_s)) i += 1 np.savetxt(f,array) f.close() # # dmetric_dx # f = open("dmetric_dx.txt","w") i = 1 for inode in range (0,nnodes_ie): for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): array = np.zeros([3,3]) f.write("dmetric_dx interpolation node %s, diff_node %s, diff_dir %s \n" % (inode+1,inode_diff+1,idir+1)) for irow in range(0,3): for icol in range(0,3): data = metrics[irow,icol,inode] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dmetric_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*3*3)) # This avoid to accumulate derivatives dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() # # interp_coords_dx # f = open("dinterp_xcoords_dx.txt","w") i = 1 f.write("xcoord interpolation, coord 1, row=node, col=nnodes_r*dir \n") array = np.zeros([nnodes_ie,nnodes_r*ndirs]) for inode in range (0,nnodes_ie): data = interp_coords[inode,0] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): if idir == 0: index = inode_diff elif idir == 1: index = nnodes_r + inode_diff elif idir == 2: index = 2*nnodes_r + inode_diff array[inode,index] = ddata_np[inode_diff,idir] update_progress("Writing interp_xcoords_dx to file ", i/(nnodes_ie*nnodes_r*3)) i += 1 # This avoid to accumulate derivatives dummy = coords.grad.data.zero_() np.savetxt(f,array) f.close() f = open("dinterp_ycoords_dx.txt","w") i = 1 f.write("ycoord interpolation, coord 2, row=node, col=nnodes_r*dir \n") array = np.zeros([nnodes_ie,nnodes_r*ndirs]) for inode in range (0,nnodes_ie): data = interp_coords[inode,1] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): if idir == 0: index = inode_diff elif idir == 1: index = nnodes_r + inode_diff elif idir == 2: index = 2*nnodes_r + inode_diff array[inode,index] = ddata_np[inode_diff,idir] update_progress("Writing interp_ycoords_dx to file ", i/(nnodes_ie*nnodes_r*3)) i += 1 # This avoid to accumulate derivatives dummy = coords.grad.data.zero_() np.savetxt(f,array) f.close() f = open("dinterp_zcoords_dx.txt","w") i = 1 f.write("zcoord interpolation, coord 3, row=node, col=nnodes_r*dir \n") array = np.zeros([nnodes_ie,nnodes_r*ndirs]) for inode in range (0,nnodes_ie): data = interp_coords[inode,2] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): if idir == 0: index = inode_diff elif idir == 1: index = nnodes_r + inode_diff elif idir == 2: index = 2*nnodes_r + inode_diff array[inode,index] = ddata_np[inode_diff,idir] update_progress("Writing interp_zcoords_dx to file ", i/(nnodes_ie*nnodes_r*3)) i += 1 # This avoid to accumulate derivatives dummy = coords.grad.data.zero_() np.savetxt(f,array) f.close() # # djinv_dx # f = open("djinv_dx.txt","w") i = 1 for inode in range (0,nnodes_ie): array = np.zeros([nnodes_r,ndirs]) f.write("djinv_dx interpolation node %s, row=inode_diff, col=dir \n" % (inode+1)) for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): data = jinv[inode] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[inode_diff,idir] = ddata_np[inode_diff,idir] update_progress("Writing djinv_dx to file ", i/(nnodes_ie*nnodes_r*ndirs)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() # # dmass_dx # f = open("dmass_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dmass_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nterms_s,nterms_s]) for irow in range(0,nterms_s): for icol in range(0,nterms_s): data = mass[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dmass_dx to file ", i/(nterms_s*nnodes_r*ndirs*nterms_s)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() # # dinvmass_dx # f = open("dinvmass_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dinvmass_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nterms_s,nterms_s]) for irow in range(0,nterms_s): for icol in range(0,nterms_s): data = invmass[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dinvmass_dx to file ", i/(nterms_s*nnodes_r*ndirs*nterms_s)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() # # dbr2_vol_dx # # f = open("dbr2_vol_face1_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_vol_face1_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nnodes_if]) for irow in range(0,nnodes_ie): for icol in range(0,nnodes_if): data = br2_vol_face1[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_vol_face1_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_vol_face2_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_vol_face2_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nnodes_if]) for irow in range(0,nnodes_ie): for icol in range(0,nnodes_if): data = br2_vol_face2[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_vol_face2_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_vol_face3_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_vol_face3_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nnodes_if]) for irow in range(0,nnodes_ie): for icol in range(0,nnodes_if): data = br2_vol_face3[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_vol_face3_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_vol_face4_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_vol_face4_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nnodes_if]) for irow in range(0,nnodes_ie): for icol in range(0,nnodes_if): data = br2_vol_face4[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_vol_face4_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_vol_face5_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_vol_face5_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nnodes_if]) for irow in range(0,nnodes_ie): for icol in range(0,nnodes_if): data = br2_vol_face5[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_vol_face5_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_vol_face6_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_vol_face6_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nnodes_if]) for irow in range(0,nnodes_ie): for icol in range(0,nnodes_if): data = br2_vol_face6[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_vol_face6_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() # # dbr2_face_dx # # f = open("dbr2_face_face1_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_face_face1_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_if,nnodes_if]) for irow in range(0,nnodes_if): for icol in range(0,nnodes_if): data = br2_face_face1[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_face_face1_dx to file ", i/(nnodes_if*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_face_face2_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_face_face2_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_if,nnodes_if]) for irow in range(0,nnodes_if): for icol in range(0,nnodes_if): data = br2_face_face2[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_face_face2_dx to file ", i/(nnodes_if*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_face_face3_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_face_face3_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_if,nnodes_if]) for irow in range(0,nnodes_if): for icol in range(0,nnodes_if): data = br2_face_face3[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_face_face3_dx to file ", i/(nnodes_if*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_face_face4_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_face_face4_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_if,nnodes_if]) for irow in range(0,nnodes_if): for icol in range(0,nnodes_if): data = br2_face_face4[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_face_face4_dx to file ", i/(nnodes_if*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_face_face5_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_face_face5_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_if,nnodes_if]) for irow in range(0,nnodes_if): for icol in range(0,nnodes_if): data = br2_face_face5[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_face_face5_dx to file ", i/(nnodes_if*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_face_face6_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_face_face6_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_if,nnodes_if]) for irow in range(0,nnodes_if): for icol in range(0,nnodes_if): data = br2_face_face6[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_face_face6_dx to file ", i/(nnodes_if*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() # # dgrad1_dx # f = open("dgrad1_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dgrad1_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nterms_s]) for irow in range(0,nnodes_ie): for icol in range(0,nterms_s): data = grad1[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dgrad1_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nterms_s)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() # # dgrad2_dx # f = open("dgrad2_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dgrad2_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nterms_s]) for irow in range(0,nnodes_ie): for icol in range(0,nterms_s): data = grad2[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dgrad2_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nterms_s)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() # # dgrad3_dx # f = open("dgrad3_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dgrad3_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nterms_s]) for irow in range(0,nnodes_ie): for icol in range(0,nterms_s): data = grad3[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dgrad3_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nterms_s)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close()
40.950243
159
0.564532
4602f7f46fb5876b81f698415a8de6581f32551a
2,827
py
Python
osr_stat_generator/generator.py
brian-thomas/osr_stat_generator
89f6a71e17c274befa3af7222a24c34a77f1f40e
[ "MIT" ]
null
null
null
osr_stat_generator/generator.py
brian-thomas/osr_stat_generator
89f6a71e17c274befa3af7222a24c34a77f1f40e
[ "MIT" ]
null
null
null
osr_stat_generator/generator.py
brian-thomas/osr_stat_generator
89f6a71e17c274befa3af7222a24c34a77f1f40e
[ "MIT" ]
null
null
null
""" OSR (LOTFP) stat generator. """ import random def d(num_sides): """ Represents rolling a die of size 'num_sides'. Returns random number from that size die """ return random.randint(1, num_sides) def xdy(num_dice, num_sides): """ represents rolling num_dice of size num_sides. Returns random number from that many dice being 'rolled'. """ return sum(d(num_sides) for i in range(num_dice)) class Stat_Set(object): """ Define a package of OSR/DnD stats """ _Stat_Name = ["CON", "DEX", "INT", "WIS", "STR", "CHA"] def generate_stats (nrof_sets:int=1, no_hopeless_char:bool=True)->list: """ Generate stats for a character. """ stat_sets = [] while (nrof_sets > 0): stats = [] for i in range (0, 6): stats.append(xdy(3,6)) stat_set = Stat_Set(stats) # no "hopeless" characters if no_hopeless_char and stat_set.is_hopeless: continue stat_sets.append(stat_set) nrof_sets -= 1 return stat_sets
22.798387
81
0.562434
4604dc5f65cd5f7e83502d4f9fd70d81c2c12903
4,178
py
Python
cohesity_management_sdk/models/health_tile.py
nick6655/management-sdk-python
88e792cb83e5c24a22af495b220c145d0c45841d
[ "Apache-2.0" ]
18
2019-09-24T17:35:53.000Z
2022-03-25T08:08:47.000Z
cohesity_management_sdk/models/health_tile.py
nick6655/management-sdk-python
88e792cb83e5c24a22af495b220c145d0c45841d
[ "Apache-2.0" ]
18
2019-03-29T19:32:29.000Z
2022-01-03T23:16:45.000Z
cohesity_management_sdk/models/health_tile.py
nick6655/management-sdk-python
88e792cb83e5c24a22af495b220c145d0c45841d
[ "Apache-2.0" ]
16
2019-02-27T06:54:12.000Z
2021-11-16T18:10:24.000Z
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. import cohesity_management_sdk.models.alert
38.330275
109
0.646003
460510280808ce5edf4deb0f4ea853f4de886f05
4,149
py
Python
TextRank/textrank.py
nihanjali/PageRank
baea9d89fb962fd1311a61127123bf36d9d2dd38
[ "Apache-2.0" ]
null
null
null
TextRank/textrank.py
nihanjali/PageRank
baea9d89fb962fd1311a61127123bf36d9d2dd38
[ "Apache-2.0" ]
null
null
null
TextRank/textrank.py
nihanjali/PageRank
baea9d89fb962fd1311a61127123bf36d9d2dd38
[ "Apache-2.0" ]
null
null
null
import os import sys import copy import collections import nltk import nltk.tokenize sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) import pagerank ''' textrank.py ----------- This module implements TextRank, an unsupervised keyword significance scoring algorithm. TextRank builds a weighted graph representation of a document using words as nodes and coocurrence frequencies between pairs of words as edge weights. It then applies PageRank to this graph, and treats the PageRank score of each word as its significance. The original research paper proposing this algorithm is available here: https://web.eecs.umich.edu/~mihalcea/papers/mihalcea.emnlp04.pdf ''' ## TextRank ##################################################################################### def __preprocessDocument(document, relevantPosTags): ''' This function accepts a string representation of a document as input, and returns a tokenized list of words corresponding to that document. ''' words = __tokenizeWords(document) posTags = __tagPartsOfSpeech(words) # Filter out words with irrelevant POS tags filteredWords = [] for index, word in enumerate(words): word = word.lower() tag = posTags[index] if not __isPunctuation(word) and tag in relevantPosTags: filteredWords.append(word) return filteredWords def textrank(document, windowSize=2, rsp=0.15, relevantPosTags=["NN", "ADJ"]): ''' This function accepts a string representation of a document and three hyperperameters as input. It returns Pandas matrix (that can be treated as a dictionary) that maps words in the document to their associated TextRank significance scores. Note that only words that are classified as having relevant POS tags are present in the map. ''' # Tokenize document: words = __preprocessDocument(document, relevantPosTags) # Build a weighted graph where nodes are words and # edge weights are the number of times words cooccur # within a window of predetermined size. In doing so # we double count each coocurrence, but that will not # alter relative weights which ultimately determine # TextRank scores. edgeWeights = collections.defaultdict(lambda: collections.Counter()) for index, word in enumerate(words): for otherIndex in range(index - windowSize, index + windowSize + 1): if otherIndex >= 0 and otherIndex < len(words) and otherIndex != index: otherWord = words[otherIndex] edgeWeights[word][otherWord] += 1.0 # Apply PageRank to the weighted graph: wordProbabilities = pagerank.powerIteration(edgeWeights, rsp=rsp) wordProbabilities.sort_values(ascending=False) return wordProbabilities ## NLP utilities ################################################################################ ## tests ######################################################################################## if __name__ == "__main__": main()
33.731707
97
0.644493
4606c41942e35425a62e84ea16612cc308900a33
10,472
py
Python
tests/test_exploration.py
lionelkusch/neurolib
714eef48616af0ebdb62decc84826221472398f9
[ "MIT" ]
null
null
null
tests/test_exploration.py
lionelkusch/neurolib
714eef48616af0ebdb62decc84826221472398f9
[ "MIT" ]
null
null
null
tests/test_exploration.py
lionelkusch/neurolib
714eef48616af0ebdb62decc84826221472398f9
[ "MIT" ]
null
null
null
import logging import os import random import string import time import unittest import neurolib.utils.paths as paths import neurolib.utils.pypetUtils as pu import numpy as np import pytest import xarray as xr from neurolib.models.aln import ALNModel from neurolib.models.fhn import FHNModel from neurolib.models.multimodel import MultiModel from neurolib.models.multimodel.builder.fitzhugh_nagumo import FitzHughNagumoNetwork from neurolib.optimize.exploration import BoxSearch from neurolib.utils.loadData import Dataset from neurolib.utils.parameterSpace import ParameterSpace def randomString(stringLength=10): """Generate a random string of fixed length""" letters = string.ascii_lowercase return "".join(random.choice(letters) for i in range(stringLength)) if __name__ == "__main__": unittest.main()
36.110345
120
0.629297
46077178da4bf46135d1fc5fee2cb11b113e0b42
3,568
py
Python
irc3/tags.py
belst/irc3
c89303cf5937a4dc7cf1eda8e662dc702b5e0ad9
[ "MIT" ]
null
null
null
irc3/tags.py
belst/irc3
c89303cf5937a4dc7cf1eda8e662dc702b5e0ad9
[ "MIT" ]
null
null
null
irc3/tags.py
belst/irc3
c89303cf5937a4dc7cf1eda8e662dc702b5e0ad9
[ "MIT" ]
1
2018-07-22T18:40:37.000Z
2018-07-22T18:40:37.000Z
# -*- coding: utf-8 -*- ''' Module offering 2 functions, encode() and decode(), to transcode between IRCv3.2 tags and python dictionaries. ''' import re import random import string _escapes = ( ("\\", "\\\\"), (";", r"\:"), (" ", r"\s"), ("\r", r"\r"), ("\n", r"\n"), ) # make the possibility of the substitute actually appearing in the text # negligible. Even for targeted attacks _substitute = (";TEMP:%s;" % ''.join(random.choice(string.ascii_letters) for i in range(20))) _unescapes = ( ("\\\\", _substitute), (r"\:", ";"), (r"\s", " "), (r"\r", "\r"), (r"\n", "\n"), (_substitute, "\\"), ) # valid tag-keys must contain of alphanumerics and hyphens only. # for vendor-tagnames: TLD with slash appended _valid_key = re.compile("^([\w.-]+/)?[\w-]+$") # valid escaped tag-values must not contain # NUL, CR, LF, semicolons or spaces _valid_escaped_value = re.compile("^[^ ;\n\r\0]*$") def encode(tags): '''Encodes a dictionary of tags to fit into an IRC-message. See IRC Message Tags: http://ircv3.net/specs/core/message-tags-3.2.html >>> from collections import OrderedDict >>> encode({'key': 'value'}) 'key=value' >>> d = {'aaa': 'bbb', 'ccc': None, 'example.com/ddd': 'eee'} >>> d_ordered = OrderedDict(sorted(d.items(), key=lambda t: t[0])) >>> encode(d_ordered) 'aaa=bbb;ccc;example.com/ddd=eee' >>> d = {'key': 'value;with special\\\\characters', 'key2': 'with=equals'} >>> d_ordered = OrderedDict(sorted(d.items(), key=lambda t: t[0])) >>> print(encode(d_ordered)) key=value\\:with\\sspecial\\\characters;key2=with=equals >>> print(encode({'key': r'\\something'})) key=\\\\something ''' tagstrings = [] for key, value in tags.items(): if not _valid_key.match(key): raise ValueError("dictionary key is invalid as tag key: " + key) # if no value, just append the key if value: tagstrings.append(key + "=" + _escape(value)) else: tagstrings.append(key) return ";".join(tagstrings) def decode(tagstring): '''Decodes a tag-string from an IRC-message into a python dictionary. See IRC Message Tags: http://ircv3.net/specs/core/message-tags-3.2.html >>> from pprint import pprint >>> pprint(decode('key=value')) {'key': 'value'} >>> pprint(decode('aaa=bbb;ccc;example.com/ddd=eee')) {'aaa': 'bbb', 'ccc': None, 'example.com/ddd': 'eee'} >>> s = r'key=value\\:with\\sspecial\\\\characters;key2=with=equals' >>> pprint(decode(s)) {'key': 'value;with special\\\\characters', 'key2': 'with=equals'} >>> print(decode(s)['key']) value;with special\\characters >>> print(decode(r'key=\\\\something')['key']) \\something ''' if not tagstring: # None/empty = no tags return {} tags = {} for tag in tagstring.split(";"): # value is either everything after "=", or None key, value = (tag.split("=", 1) + [None])[:2] if not _valid_key.match(key): raise ValueError("invalid tag key: " + key) if value: if not _valid_escaped_value.match(value): raise ValueError("invalid escaped tag value: " + value) value = _unescape(value) tags[key] = value return tags
28.31746
79
0.580998
4607ba171b6d586a01f576a069c7a776194711fd
2,646
py
Python
app/forms.py
Rahmatullina/FinalYearProject
326f521b9f600dbbc7ace2223bd5aafc79b2267c
[ "Apache-2.0" ]
null
null
null
app/forms.py
Rahmatullina/FinalYearProject
326f521b9f600dbbc7ace2223bd5aafc79b2267c
[ "Apache-2.0" ]
9
2020-09-26T01:09:35.000Z
2022-02-10T01:32:30.000Z
app/forms.py
Rahmatullina/FinalYearProject
326f521b9f600dbbc7ace2223bd5aafc79b2267c
[ "Apache-2.0" ]
null
null
null
from django import forms from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm # from .models import RegionModel # from .models import SERVICE_CHOICES, REGION_CHOICES from django.contrib.auth import authenticate # from django.contrib.auth.forms import UserCreationForm, UserChangeForm # from .models import CustomUser # class PassResetForm(PasswordResetForm): # email = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter email', # 'type':'email'}), max_length=100) # # # class PassResetConfirmForm(SetPasswordForm): # new_password1 = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', # 'placeholder':'Enter new password', # 'type':'password'}), max_length=100) # new_password2 = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', # 'placeholder': 'Enter new password again', # 'type': 'password'}), max_length=100) # class CustomUserCreationForm(UserCreationForm): # # class Meta(UserCreationForm): # model = CustomUser # fields = UserCreationForm.Meta.fields + ('region_name',) # # # class CustomUserChangeForm(UserChangeForm): # email = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=100) # username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=254) # # class Meta: # model = CustomUser # fields = ('email','username')
46.421053
120
0.62585
46085291ee66b159174d6179bad5ab2c5199a92f
28,019
py
Python
src/fedavg_trainer.py
MrZhang1994/mobile-federated-learning
6e088a91266d889869af5a1eb0bad83ca635a4a5
[ "Apache-2.0" ]
null
null
null
src/fedavg_trainer.py
MrZhang1994/mobile-federated-learning
6e088a91266d889869af5a1eb0bad83ca635a4a5
[ "Apache-2.0" ]
null
null
null
src/fedavg_trainer.py
MrZhang1994/mobile-federated-learning
6e088a91266d889869af5a1eb0bad83ca635a4a5
[ "Apache-2.0" ]
1
2021-07-06T04:53:06.000Z
2021-07-06T04:53:06.000Z
# newly added libraries import copy import wandb import time import math import csv import shutil from tqdm import tqdm import torch import numpy as np import pandas as pd from client import Client from config import * import scheduler as sch
52.965974
206
0.5891
46087abee7bffbddb94f7edf7ace7481d6b4e5e7
15,539
py
Python
src/test.py
jfparentledartech/DEFT
6e7e98664cd635509bdff69533a24a7c4e4e3ea3
[ "MIT" ]
null
null
null
src/test.py
jfparentledartech/DEFT
6e7e98664cd635509bdff69533a24a7c4e4e3ea3
[ "MIT" ]
null
null
null
src/test.py
jfparentledartech/DEFT
6e7e98664cd635509bdff69533a24a7c4e4e3ea3
[ "MIT" ]
null
null
null
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time import cv2 import matplotlib.pyplot as plt import numpy as np from progress.bar import Bar import torch import pickle import motmetrics as mm from lib.opts import opts from lib.logger import Logger from lib.utils.utils import AverageMeter from lib.dataset.dataset_factory import dataset_factory from lib.utils.pixset_metrics import compute_metrics pixset_categories = [ 'car', 'truck', 'bus', 'pedestrian', 'motorcyclist', 'cyclist', 'van' ] opt = opts().parse() filename = '../options/test_opt_pixset.txt' with open(filename, 'wb') as f: pickle.dump(opt, f) # # print('dataset -> ', opt.dataset) # print('lstm -> ', opt.lstm) # print(f'saved {filename}') # with open(filename, 'rb') as f: # opt = pickle.load(f) # print('use pixell ->', opt.use_pixell) from lib.detector import Detector from lib.utils.image import plot_tracking, plot_tracking_ddd import json min_box_area = 20 _vehicles = ["car", "truck", "bus", "van"] _cycles = ["motorcyclist", "cyclist"] _pedestrians = ["pedestrian"] attribute_to_id = { "": 0, "cycle.with_rider": 1, "cycle.without_rider": 2, "pedestrian.moving": 3, "pedestrian.standing": 4, "pedestrian.sitting_lying_down": 5, "vehicle.moving": 6, "vehicle.parked": 7, "vehicle.stopped": 8, } id_to_attribute = {v: k for k, v in attribute_to_id.items()} nuscenes_att = np.zeros(8, np.float32) if __name__ == "__main__": # opt = opts().parse() prefetch_test(opt)
36.137209
140
0.533882
460899f19cdb6ea7310d1622b1d7bbb727078007
8,796
py
Python
compiler_gym/envs/gcc/datasets/csmith.py
AkillesAILimited/CompilerGym
34c0933ba26b385ebd2cd67f5d8edbb046c6bf02
[ "MIT" ]
null
null
null
compiler_gym/envs/gcc/datasets/csmith.py
AkillesAILimited/CompilerGym
34c0933ba26b385ebd2cd67f5d8edbb046c6bf02
[ "MIT" ]
null
null
null
compiler_gym/envs/gcc/datasets/csmith.py
AkillesAILimited/CompilerGym
34c0933ba26b385ebd2cd67f5d8edbb046c6bf02
[ "MIT" ]
1
2021-10-01T05:52:34.000Z
2021-10-01T05:52:34.000Z
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import shutil import subprocess import tempfile from pathlib import Path from threading import Lock from typing import Iterable, Optional, Union import numpy as np from fasteners import InterProcessLock from compiler_gym.datasets import Benchmark, BenchmarkSource, Dataset from compiler_gym.datasets.benchmark import BenchmarkWithSource from compiler_gym.envs.gcc.gcc import Gcc from compiler_gym.util.decorators import memoized_property from compiler_gym.util.runfiles_path import runfiles_path from compiler_gym.util.shell_format import plural from compiler_gym.util.truncate import truncate # The maximum value for the --seed argument to csmith. UINT_MAX = (2 ** 32) - 1 _CSMITH_BIN = runfiles_path("compiler_gym/third_party/csmith/csmith/bin/csmith") _CSMITH_INCLUDES = runfiles_path( "compiler_gym/third_party/csmith/csmith/include/csmith-2.3.0" ) _CSMITH_INSTALL_LOCK = Lock() # TODO(github.com/facebookresearch/CompilerGym/issues/325): This can be merged # with the LLVM implementation. def benchmark(self, uri: str) -> CsmithBenchmark: return self.benchmark_from_seed(int(uri.split("/")[-1])) def _random_benchmark(self, random_state: np.random.Generator) -> Benchmark: seed = random_state.integers(UINT_MAX) return self.benchmark_from_seed(seed) def benchmark_from_seed( self, seed: int, max_retries: int = 3, retry_count: int = 0 ) -> CsmithBenchmark: """Get a benchmark from a uint32 seed. :param seed: A number in the range 0 <= n < 2^32. :return: A benchmark instance. :raises OSError: If Csmith fails. :raises BenchmarkInitError: If the C program generated by Csmith cannot be lowered to LLVM-IR. """ if retry_count >= max_retries: raise OSError( f"Csmith failed after {retry_count} {plural(retry_count, 'attempt', 'attempts')} " f"with seed {seed}" ) self.install() # Run csmith with the given seed and pipe the output to clang to # assemble a bitcode. self.logger.debug("Exec csmith --seed %d", seed) csmith = subprocess.Popen( [str(self.csmith_bin_path), "--seed", str(seed)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) # Generate the C source. src, stderr = csmith.communicate(timeout=300) if csmith.returncode: try: stderr = "\n".join( truncate(stderr.decode("utf-8"), max_line_len=200, max_lines=20) ) logging.warning("Csmith failed with seed %d: %s", seed, stderr) except UnicodeDecodeError: # Failed to interpret the stderr output, generate a generic # error message. logging.warning("Csmith failed with seed %d", seed) return self.benchmark_from_seed( seed, max_retries=max_retries, retry_count=retry_count + 1 ) # Pre-process the source. with tempfile.TemporaryDirectory() as tmpdir: src_file = f"{tmpdir}/src.c" with open(src_file, "wb") as f: f.write(src) preprocessed_src = self.gcc( "-E", "-I", str(self.site_data_path / "includes"), "-o", "-", src_file, cwd=tmpdir, timeout=60, volumes={ str(self.site_data_path / "includes"): { "bind": str(self.site_data_path / "includes"), "mode": "ro", } }, ) return self.benchmark_class.create( f"{self.name}/{seed}", preprocessed_src.encode("utf-8"), src )
35.756098
98
0.620509
46089e52d9f3438c0d2bdc953655d9f0dafbf49b
444
py
Python
dans_pymodules/power_of_two.py
DanielWinklehner/dans_pymodules
04dfdaeccc171712cad6eb24202608e2eda21eca
[ "MIT" ]
null
null
null
dans_pymodules/power_of_two.py
DanielWinklehner/dans_pymodules
04dfdaeccc171712cad6eb24202608e2eda21eca
[ "MIT" ]
null
null
null
dans_pymodules/power_of_two.py
DanielWinklehner/dans_pymodules
04dfdaeccc171712cad6eb24202608e2eda21eca
[ "MIT" ]
null
null
null
__author__ = "Daniel Winklehner" __doc__ = "Find out if a number is a power of two" def power_of_two(number): """ Function that checks if the input value (data) is a power of 2 (i.e. 2, 4, 8, 16, 32, ...) """ res = 0 while res == 0: res = number % 2 number /= 2.0 print("res: {}, data: {}".format(res, number)) if number == 1 and res == 0: return True return False
19.304348
66
0.529279
460a17e5a2d4a382d4b56fd109a6fc2250ecd27e
535
py
Python
examples/index/context.py
rmorshea/viewdom
24c528642e9ef0179999936b2e6f3b8a9d770df8
[ "MIT" ]
null
null
null
examples/index/context.py
rmorshea/viewdom
24c528642e9ef0179999936b2e6f3b8a9d770df8
[ "MIT" ]
null
null
null
examples/index/context.py
rmorshea/viewdom
24c528642e9ef0179999936b2e6f3b8a9d770df8
[ "MIT" ]
null
null
null
from viewdom import html, render, use_context, Context expected = '<h1>My Todos</h1><ul><li>Item: first</li></ul>' # start-after title = 'My Todos' todos = ['first'] result = render(html(''' <{Context} prefix="Item: "> <h1>{title}</h1> <{TodoList} todos={todos} /> <//> ''')) # '<h1>My Todos</h1><ul><li>Item: first</li></ul>'
20.576923
62
0.588785
460a2bcd85d3d00d44d62b6c67fe157741f17339
363
py
Python
biblioteca/views.py
Dagmoores/ProjetoIntegradorIUnivesp
86f5004c359b760cceec87bfa905db16e3375653
[ "MIT" ]
null
null
null
biblioteca/views.py
Dagmoores/ProjetoIntegradorIUnivesp
86f5004c359b760cceec87bfa905db16e3375653
[ "MIT" ]
null
null
null
biblioteca/views.py
Dagmoores/ProjetoIntegradorIUnivesp
86f5004c359b760cceec87bfa905db16e3375653
[ "MIT" ]
null
null
null
from django.views.generic import DetailView, ListView, TemplateView from .models import Books
24.2
67
0.77135
460ac56ca325f939e25bdbf44f40c51f97e73226
429
py
Python
choir/evaluation/__init__.py
scwangdyd/large_vocabulary_hoi_detection
db7a4397c3050b1bf9a3f7473edf125e2b1046c4
[ "MIT" ]
9
2021-11-13T17:14:07.000Z
2022-03-29T00:27:54.000Z
choir/evaluation/__init__.py
scwangdyd/large_vocabulary_hoi_detection
db7a4397c3050b1bf9a3f7473edf125e2b1046c4
[ "MIT" ]
1
2022-02-04T16:28:01.000Z
2022-02-04T16:28:01.000Z
choir/evaluation/__init__.py
scwangdyd/large_vocabulary_hoi_detection
db7a4397c3050b1bf9a3f7473edf125e2b1046c4
[ "MIT" ]
null
null
null
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from .evaluator import DatasetEvaluator, DatasetEvaluators, inference_context, inference_on_dataset from .testing import print_csv_format, verify_results from .hico_evaluation import HICOEvaluator from .swig_evaluation import SWIGEvaluator # from .doh_evaluation import DOHDetectionEvaluator __all__ = [k for k in globals().keys() if not k.startswith("_")]
47.666667
99
0.822844
460b1c41c9223f051fce73e3d45305d26f20419f
4,092
py
Python
api_yamdb/reviews/models.py
LHLHLHE/api_yamdb
bda83815a47f3fda03d54220dfe41e9263ff1b05
[ "MIT" ]
null
null
null
api_yamdb/reviews/models.py
LHLHLHE/api_yamdb
bda83815a47f3fda03d54220dfe41e9263ff1b05
[ "MIT" ]
null
null
null
api_yamdb/reviews/models.py
LHLHLHE/api_yamdb
bda83815a47f3fda03d54220dfe41e9263ff1b05
[ "MIT" ]
null
null
null
import datetime as dt from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from django.core.exceptions import ValidationError from users.models import CustomUser def validate_year(value): """ . """ if value > dt.datetime.now().year: raise ValidationError( ' !') return value
24.650602
77
0.608016
460cac61f3a5248165f741d16e8295c7d5e81b06
127,462
py
Python
angr/engines/pcode/arch/ArchPcode_PowerPC_LE_32_QUICC.py
matthewpruett/angr
bfba2af1ea2eb941001339f47a1264a685c60eec
[ "BSD-2-Clause" ]
6,132
2015-08-06T23:24:47.000Z
2022-03-31T21:49:34.000Z
angr/engines/pcode/arch/ArchPcode_PowerPC_LE_32_QUICC.py
matthewpruett/angr
bfba2af1ea2eb941001339f47a1264a685c60eec
[ "BSD-2-Clause" ]
2,272
2015-08-10T08:40:07.000Z
2022-03-31T23:46:44.000Z
angr/engines/pcode/arch/ArchPcode_PowerPC_LE_32_QUICC.py
matthewpruett/angr
bfba2af1ea2eb941001339f47a1264a685c60eec
[ "BSD-2-Clause" ]
1,155
2015-08-06T23:37:39.000Z
2022-03-31T05:54:11.000Z
### ### This file was automatically generated ### from archinfo.arch import register_arch, Endness, Register from .common import ArchPcode register_arch(['powerpc:le:32:quicc'], 32, Endness.LE, ArchPcode_PowerPC_LE_32_QUICC)
39.449706
85
0.545692
460d6b3dd6eff2aa0cc70e0bbc8f6441baed0341
6,796
py
Python
makesense/graph.py
sieben/makesense
485e71903bcc9446482f21bb5d0c7a392ca1efca
[ "Apache-2.0" ]
5
2015-02-03T12:28:55.000Z
2019-03-20T08:11:22.000Z
makesense/graph.py
sieben/makesense
485e71903bcc9446482f21bb5d0c7a392ca1efca
[ "Apache-2.0" ]
4
2016-05-16T07:26:19.000Z
2016-06-23T22:22:10.000Z
makesense/graph.py
sieben/makesense
485e71903bcc9446482f21bb5d0c7a392ca1efca
[ "Apache-2.0" ]
1
2016-05-16T07:28:53.000Z
2016-05-16T07:28:53.000Z
# -*- coding: utf-8 -*- import json import pdb import os from os.path import join as pj import networkx as nx import pandas as pd from networkx.readwrite.json_graph import node_link_data def plot_graph(self): """ Plot the transmission graph of the simulation. TODO: Draw arrows and have a directed graph. http://goo.gl/Z697dH TODO: Graph with big nodes for big transmissions """ fig = plt.figure() ax1 = fig.add_subplot(111) ax1.set_title("Transmission / RPL tree") ax1.axis("off") val_color = {"udp_server": 0.5714285714285714} pos = {node: data["pos"] for node, data in self.radio_tree.nodes(data=True)} # color for all nodes node_color = [val_color.get(data["mote_type"], 0.25) for node, data in self.radio_tree.nodes(data=True)] # Drawing the nodes nx.draw_networkx_nodes(self.radio_tree, pos, node_color=node_color, ax=ax1) nx.draw_networkx_labels(self.radio_tree, pos, ax=ax1) # Drawing radio edges nx.draw_networkx_edges(self.radio_tree, pos, edgelist=self.radio_tree.edges(), width=8, alpha=0.5, ax=ax1) # Adding the depth of each node. with open(PJ(self.result_dir, "depth.csv")) as depth_f: reader = DictReader(depth_f) for row in reader: node = int(row["node"]) depth = row["depth"] ax1.text(pos[node][0] + 5, pos[node][1] + 5, depth, bbox=dict(facecolor='red', alpha=0.5), horizontalalignment='center') # Drawing RPL edges nx.draw_networkx_edges( self.rpl_tree, pos, edge_color='r', nodelist=[], arrows=True, ax=ax1) img_path = PJ(self.img_dir, "graph.pdf") fig.savefig(img_path, format="pdf") update_report(self.result_dir, "plot_graph", { "img_src": "img/graph.pdf", "comment": """ When the edge is thick it means edges are in an RPL instance. Otherwise it means that the two nodes can see each others. """, "text": """ We generate a random geometric graph then use information coming to the RPL root to construct the gateway representation of the RPL tree. We add into this tree representation the traffic generated. """}) def transmission_graph(self): """ Plot the transmission graph of the simulation. """ settings = self.settings["transmission_graph"] output_path = pj(self.result_folder_path, *settings["output_path"]) fig_rplinfo, ax_transmission_graph = plt.subplots() net = nx.Graph() # nodes mote_types = self.settings["mote_types"] motes = self.settings["motes"] position = {} for mote in motes: mote_type = mote["mote_type"] mote_id = mote["mote_id"] position[mote_id] = (mote["x"], mote["y"]) mote_types[mote_type] \ .setdefault("nodes", []) \ .append(mote["mote_id"]) # edges transmitting_range = self.settings["transmitting_range"] for couple in itertools.product(motes, motes): if 0 < distance(couple) <= transmitting_range: net.add_edge(couple[0]["mote_id"], couple[1]["mote_id"]) for mote_type in mote_types: color = mote_types[mote_type]["color"] nodelist = mote_types[mote_type]["nodes"] nx.draw_networkx_nodes(net, position, nodelist=nodelist, node_color=color, ax=ax_transmission_graph) nx.draw_networkx_edges(net, pos=position, ax=ax_transmission_graph) # labels nx.draw_networkx_labels(net, position, ax=ax_transmission_graph) plt.axis('off') plt.savefig(output_path) # save as PNG return ax_transmission_graph def rpl_graph(folder): """ Build up the RPL representation at the gateway """ output_folder = pj(folder, "results", "graph") if not os.path.exists(output_folder): os.makedirs(output_folder) df = pd.read_csv(pj(folder, "results", "messages.csv")) parent_df = df[df.message_type == "parent"] rpl_graph = nx.DiGraph() for c, p in parent_df.iterrows(): rpl_graph.add_edge(p["mote_id"], p["node"]) with open(pj(output_folder, "rpl_graph.json"), "w") as f: f.write(json.dumps(node_link_data(rpl_graph), sort_keys=True, indent=4))
27.626016
82
0.59741
460d75e0442c54e12cc43f9bb046096139d2369e
2,741
py
Python
recipes/Python/52228_Remote_control_with_telnetlib/recipe-52228.py
tdiprima/code
61a74f5f93da087d27c70b2efe779ac6bd2a3b4f
[ "MIT" ]
2,023
2017-07-29T09:34:46.000Z
2022-03-24T08:00:45.000Z
recipes/Python/52228_Remote_control_with_telnetlib/recipe-52228.py
unhacker/code
73b09edc1b9850c557a79296655f140ce5e853db
[ "MIT" ]
32
2017-09-02T17:20:08.000Z
2022-02-11T17:49:37.000Z
recipes/Python/52228_Remote_control_with_telnetlib/recipe-52228.py
unhacker/code
73b09edc1b9850c557a79296655f140ce5e853db
[ "MIT" ]
780
2017-07-28T19:23:28.000Z
2022-03-25T20:39:41.000Z
# auto_telnet.py - remote control via telnet import os, sys, string, telnetlib from getpass import getpass if __name__ == '__main__': basename = os.path.splitext(os.path.basename(sys.argv[0]))[0] logname = os.environ.get("LOGNAME", os.environ.get("USERNAME")) host = 'localhost' import getopt optlist, user_list = getopt.getopt(sys.argv[1:], 'c:f:h:') usage = """ usage: %s [-h host] [-f cmdfile] [-c "command"] user1 user2 ... -c command -f command file -h host (default: '%s') Example: %s -c "echo $HOME" %s """ % (basename, host, basename, logname) if len(sys.argv) < 2: print usage sys.exit(1) cmd_list = [] for (opt, optarg) in optlist: if opt == '-f': for r in open(optarg).readlines(): if string.rstrip(r): cmd_list.append(r) elif opt == '-c': command = optarg if command[0] == '"' and command[-1] == '"': command = command[1:-1] cmd_list.append(command) elif opt == '-h': host = optarg autoTelnet = AutoTelnet(user_list, cmd_list, host=host)
34.2625
76
0.553448
460e2d1d15ba01da3b9d59848ee03f3a71e7df89
5,511
py
Python
FFTNet_dilconv.py
mimbres/FFTNet
3a6bfb4731bab2e0a59fc3a1ddb55f19f84aeba2
[ "Apache-2.0" ]
null
null
null
FFTNet_dilconv.py
mimbres/FFTNet
3a6bfb4731bab2e0a59fc3a1ddb55f19f84aeba2
[ "Apache-2.0" ]
null
null
null
FFTNet_dilconv.py
mimbres/FFTNet
3a6bfb4731bab2e0a59fc3a1ddb55f19f84aeba2
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 7 09:46:10 2018 @author: sungkyun FFTNet model using 2x1 dil-conv """ import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # Models with Preset (for convenience) ''' dim_input: dimension of input (256 for 8-bit mu-law input) num_layer: number of layers (11 in paper). receptive field = 2^11 (2,048) io_ch: number of input(=output) channels in each fft layers skip_ch: number of skip-channels, only required for fft-residual net. Annotations: B: batch dimension C: channel dimension L: length dimension ''' # FFT_Block: define a basic FFT Block ''' FFT_Block: - using 2x1 dilated-conv, instead of LR split 1x1 conv. - described in the paper, section 2.2. - in case of the first layer used in the first FFT_Block, we use nn.embedding layer for one-hot index(0-255) entries. ''' ''' FFTNet: - [11 FFT_blocks] --> [FC_layer] --> [softmax] '''
40.822222
147
0.551987
460e42fc65b233b72dc53c72b8b11991e2b52abd
1,390
py
Python
snewpdag/plugins/Copy.py
SNEWS2/snewpdag
57f886cf08e1acd8af48ee486a1c2400e2b77b8b
[ "BSD-3-Clause" ]
null
null
null
snewpdag/plugins/Copy.py
SNEWS2/snewpdag
57f886cf08e1acd8af48ee486a1c2400e2b77b8b
[ "BSD-3-Clause" ]
21
2021-06-09T10:31:40.000Z
2022-03-21T17:14:03.000Z
snewpdag/plugins/Copy.py
SNEWS2/snewpdag
57f886cf08e1acd8af48ee486a1c2400e2b77b8b
[ "BSD-3-Clause" ]
9
2021-07-11T17:45:42.000Z
2021-09-09T22:07:18.000Z
""" Copy - copy fields into other (possibly new) fields configuration: on: list of 'alert', 'revoke', 'report', 'reset' (optional: def 'alert' only) cp: ( (in,out), ... ) Field names take the form of dir1/dir2/dir3, which in the payload will be data[dir1][dir2][dir3] """ import logging from snewpdag.dag import Node
25.272727
79
0.576978
460ec208b3e5e026467442540a94ba66de7fb38a
1,562
py
Python
pages/aboutus.py
BuildWeek-AirBnB-Optimal-Price/application
c65e1ec3db309dd3afbcf9429d16489ccda534d8
[ "MIT" ]
null
null
null
pages/aboutus.py
BuildWeek-AirBnB-Optimal-Price/application
c65e1ec3db309dd3afbcf9429d16489ccda534d8
[ "MIT" ]
1
2021-08-23T21:22:51.000Z
2021-08-23T21:22:51.000Z
pages/aboutus.py
BuildWeek-AirBnB-Optimal-Price/application
c65e1ec3db309dd3afbcf9429d16489ccda534d8
[ "MIT" ]
null
null
null
''' houses each team member's link to personal GitHub io or website or blog space RJProctor ''' # Imports from 3rd party libraries import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output from app import app # 1 column layout # https://dash-bootstrap-components.opensource.faculty.ai/l/components/layout column1 = dbc.Col( [ dcc.Markdown( """ ## The Team: Select a link to learn more about each of our team members. """ ), ], ) # create footer column2 = dbc.Col( [ dcc.Markdown( """ **Debbie Cohen** https://github.com/dscohen75/dscohen75.github.io https://medium.com/@debbiecohen_22419 **Moe Fa** --- **Eduardo Padilla** https://medium.com/@eprecendez --- **R. Jeannine Proctor** https://jproctor-rebecca.github.io/ https://medium.com/@jproctor.m.ed.tn --- **Code Review Team Members:** Taylor Curran, Regina Dircio, Robert Giuffrie, Ryan Herr, Brendon Hoss, Anika Nacey, Tomas Phillips, Raymond Tan, and Rebecca Duke-Wiesenberg """ ), ], ) layout = dbc.Row([column1, column2])
20.025641
77
0.518566
4610420d2938e979a1edec925cfaa9db7b11366a
755
py
Python
Codes/Python32/Lib/importlib/test/extension/test_path_hook.py
eyantra/FireBird_Swiss_Knife
cac322cf28e2d690b86ba28a75e87551e5e47988
[ "MIT" ]
319
2016-09-22T15:54:48.000Z
2022-03-18T02:36:58.000Z
Codes/Python32/Lib/importlib/test/extension/test_path_hook.py
eyantra/FireBird_Swiss_Knife
cac322cf28e2d690b86ba28a75e87551e5e47988
[ "MIT" ]
9
2016-11-03T21:56:41.000Z
2020-08-09T19:27:37.000Z
Codes/Python32/Lib/importlib/test/extension/test_path_hook.py
eyantra/FireBird_Swiss_Knife
cac322cf28e2d690b86ba28a75e87551e5e47988
[ "MIT" ]
27
2016-10-06T16:05:32.000Z
2022-03-18T02:37:00.000Z
from importlib import _bootstrap from . import util import collections import imp import sys import unittest if __name__ == '__main__': test_main()
23.59375
77
0.721854
46114f85ae8065583b2a1f11692dfc71d3d35a86
480
py
Python
3. count_words/solution.py
dcragusa/WeeklyPythonExerciseB2
a7da3830e27891060dcfb0804c81f52b1f250ce8
[ "MIT" ]
null
null
null
3. count_words/solution.py
dcragusa/WeeklyPythonExerciseB2
a7da3830e27891060dcfb0804c81f52b1f250ce8
[ "MIT" ]
null
null
null
3. count_words/solution.py
dcragusa/WeeklyPythonExerciseB2
a7da3830e27891060dcfb0804c81f52b1f250ce8
[ "MIT" ]
null
null
null
import os from glob import iglob from concurrent.futures import ThreadPoolExecutor
24
62
0.729167
46116c9d8947552c6fd85dd9c709b4bd524230cf
141
py
Python
kafka-connect-azblob/docs/autoreload.py
cirobarradov/kafka-connect-hdfs-datalab
7e2b23bdb78b34f9934b8d56618a8035b75f6f54
[ "Apache-2.0" ]
null
null
null
kafka-connect-azblob/docs/autoreload.py
cirobarradov/kafka-connect-hdfs-datalab
7e2b23bdb78b34f9934b8d56618a8035b75f6f54
[ "Apache-2.0" ]
null
null
null
kafka-connect-azblob/docs/autoreload.py
cirobarradov/kafka-connect-hdfs-datalab
7e2b23bdb78b34f9934b8d56618a8035b75f6f54
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python from livereload import Server, shell server = Server() server.watch('*.rst', shell('make html')) server.serve()
20.142857
42
0.680851
4612cb4af177cb85c305bcbf02040e60659a77f5
3,008
py
Python
keras_textclassification/conf/path_config.py
atom-zh/Keras-TextClassification
26c549e8e23c6a10905c2dcef7eef557dc43c932
[ "MIT" ]
null
null
null
keras_textclassification/conf/path_config.py
atom-zh/Keras-TextClassification
26c549e8e23c6a10905c2dcef7eef557dc43c932
[ "MIT" ]
null
null
null
keras_textclassification/conf/path_config.py
atom-zh/Keras-TextClassification
26c549e8e23c6a10905c2dcef7eef557dc43c932
[ "MIT" ]
null
null
null
# -*- coding: UTF-8 -*- # !/usr/bin/python # @time :2019/6/5 21:04 # @author :Mo # @function :file of path import os import pathlib import sys # path_root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) path_root = path_root.replace('\\', '/') path_top = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) path_top = path_top.replace('\\', '/') # path of embedding path_embedding_user_dict = path_root + '/data/embeddings/user_dict.txt' path_embedding_random_char = path_root + '/data/embeddings/term_char.txt' path_embedding_random_word = path_root + '/data/embeddings/term_word.txt' path_embedding_bert = path_root + '/data/embeddings/chinese_L-12_H-768_A-12/' path_embedding_xlnet = path_root + '/data/embeddings/chinese_xlnet_mid_L-24_H-768_A-12/' path_embedding_albert = path_root + '/data/embeddings/albert_base_zh' path_embedding_vector_word2vec_char = path_root + '/data/embeddings/multi_label_char.vec' path_embedding_vector_word2vec_word = path_root + '/data/embeddings/multi_label_word.vec' path_embedding_vector_word2vec_char_bin = path_root + '/data/embeddings/multi_label_char.bin' path_embedding_vector_word2vec_word_bin = path_root + '/data/embeddings/multi_label_word.bin' # classify data of baidu qa 2019 path_baidu_qa_2019_train = path_root + '/data/baidu_qa_2019/baike_qa_train.csv' path_baidu_qa_2019_valid = path_root + '/data/baidu_qa_2019/baike_qa_valid.csv' # path_byte_multi_news_train = path_root + '/data/byte_multi_news/train.csv' path_byte_multi_news_valid = path_root + '/data/byte_multi_news/valid.csv' path_byte_multi_news_label = path_root + '/data/byte_multi_news/labels.csv' # classify data of baidu qa 2019 path_sim_webank_train = path_root + '/data/sim_webank/train.csv' path_sim_webank_valid = path_root + '/data/sim_webank/valid.csv' path_sim_webank_test = path_root + '/data/sim_webank/test.csv' # classfiy multi labels 2021 path_multi_label_train = path_root + '/data/multi_label/train.csv' path_multi_label_valid = path_root + '/data/multi_label/valid.csv' path_multi_label_labels = path_root + '/data/multi_label/labels.csv' path_multi_label_tests = path_root + '/data/multi_label/tests.csv' # path_label = path_multi_label_labels path_train = path_multi_label_train path_valid = path_multi_label_valid path_tests = path_multi_label_tests path_edata = path_root + "/../out/error_data.csv" # fast_text config path_out = path_top + "/out/" # path_model_dir = path_root + "/data/model/fast_text/" # path_model = path_root + '/data/model/fast_text/model_fast_text.h5' # path_hyper_parameters = path_root + '/data/model/fast_text/hyper_parameters.json' # embedding path_fineture = path_root + "/data/model/fast_text/embedding_trainable.h5" # - path_category = path_root + '/data/multi_label/category2labels.json' # l2i_i2l path_l2i_i2l = path_root + '/data/multi_label/l2i_i2l.json'
41.777778
94
0.772939
4612f94a5e19222b82ccef62fa3f6a2d792d2930
2,617
py
Python
tests/test_apyhgnc.py
robertopreste/apyhgnc
26efa764a2262cfa12c8a2f0f077569e7f3e4e79
[ "MIT" ]
null
null
null
tests/test_apyhgnc.py
robertopreste/apyhgnc
26efa764a2262cfa12c8a2f0f077569e7f3e4e79
[ "MIT" ]
64
2019-04-21T09:22:01.000Z
2022-03-31T23:01:14.000Z
tests/test_apyhgnc.py
robertopreste/apyhgnc
26efa764a2262cfa12c8a2f0f077569e7f3e4e79
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Created by Roberto Preste import pytest import asyncio from pandas.testing import assert_frame_equal from apyhgnc import apyhgnc # apyhgnc.info # apyhgnc.fetch # apyhgnc.search
27.840426
69
0.762323
46134dbafabea71d237df09c989e61b23906b699
2,770
py
Python
bdaq/tools/extract_enums.py
magnium/pybdaq
8511cff42b7f953c105e7a78c8c62f6deb2430ec
[ "MIT" ]
null
null
null
bdaq/tools/extract_enums.py
magnium/pybdaq
8511cff42b7f953c105e7a78c8c62f6deb2430ec
[ "MIT" ]
null
null
null
bdaq/tools/extract_enums.py
magnium/pybdaq
8511cff42b7f953c105e7a78c8c62f6deb2430ec
[ "MIT" ]
1
2018-08-28T06:12:06.000Z
2018-08-28T06:12:06.000Z
import os.path import argparse from xml.etree import ElementTree as ET if __name__ == "__main__": main()
27.156863
78
0.640794
46138642b2c4dc6d2e31c500bf65e34679d07086
1,230
py
Python
Objetos/biblioteca.py
SebaB29/Python
8fe7b375e200d2a629e3ef83a2356002621267a6
[ "MIT" ]
null
null
null
Objetos/biblioteca.py
SebaB29/Python
8fe7b375e200d2a629e3ef83a2356002621267a6
[ "MIT" ]
null
null
null
Objetos/biblioteca.py
SebaB29/Python
8fe7b375e200d2a629e3ef83a2356002621267a6
[ "MIT" ]
null
null
null
libro = Libro("HyP", "JK") libro1 = Libro("La Isla M", "JCortazar") libro2 = Libro("El tunel", "Sabato") biblio = Biblioteca() biblio.agregar_libro(libro) biblio.agregar_libro(libro1) biblio.agregar_libro(libro2) print(biblio.contiene_libro("HyP", "JK")) print(biblio.sacar_libro("HyP", "JK")) print(biblio.contiene_libro("HyP", "JK"))
27.954545
63
0.582927
4613a39367cc38fb7bf09761273d5ec4ce7cfaaf
5,540
py
Python
parser_tool/tests/test_htmlgenerator.py
Harvard-ATG/visualizing_russian_tools
e8e5cf8c5b7eee0b6855594ad41b3ccd70a2d467
[ "BSD-3-Clause" ]
2
2020-07-10T14:17:03.000Z
2020-11-17T09:18:26.000Z
parser_tool/tests/test_htmlgenerator.py
eelegiap/visualizing_russian_tools
9c36baebc384133c7c27d7a7c4e0cedc8cb84e74
[ "BSD-3-Clause" ]
13
2019-03-17T13:27:31.000Z
2022-01-18T17:03:14.000Z
parser_tool/tests/test_htmlgenerator.py
eelegiap/visualizing_russian_tools
9c36baebc384133c7c27d7a7c4e0cedc8cb84e74
[ "BSD-3-Clause" ]
2
2019-10-19T16:37:44.000Z
2020-06-22T13:30:20.000Z
# -*- coding: utf-8 -*- import unittest from xml.etree import ElementTree as ET from parser_tool import tokenizer from parser_tool import htmlgenerator
49.026549
192
0.658845
4613c4acf26a49b9382fcd9cbead5b7bfa04eb32
1,772
py
Python
taiga/hooks/gitlab/migrations/0002_auto_20150703_1102.py
threefoldtech/Threefold-Circles
cbc433796b25cf7af9a295af65d665a4a279e2d6
[ "Apache-2.0" ]
1
2017-05-29T19:01:06.000Z
2017-05-29T19:01:06.000Z
docker-images/taigav2/taiga-back/taiga/hooks/gitlab/migrations/0002_auto_20150703_1102.py
mattcongy/itshop
6be025a9eaa7fe7f495b5777d1f0e5a3184121c9
[ "MIT" ]
12
2019-11-25T14:08:32.000Z
2021-06-24T10:35:51.000Z
taiga/hooks/gitlab/migrations/0002_auto_20150703_1102.py
threefoldtech/Threefold-Circles
cbc433796b25cf7af9a295af65d665a4a279e2d6
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.core.files import File
34.745098
79
0.603273
4615c8d476cced9b6746382173a9829cad6f16c7
995
bzl
Python
external_plugin_deps.bzl
michalgagat/plugins_oauth
47cc344013bd43a4ac508c578f2d93f37a166ee6
[ "Apache-2.0", "MIT" ]
143
2015-03-09T21:18:39.000Z
2022-03-02T13:27:12.000Z
external_plugin_deps.bzl
michalgagat/plugins_oauth
47cc344013bd43a4ac508c578f2d93f37a166ee6
[ "Apache-2.0", "MIT" ]
162
2015-03-15T04:00:41.000Z
2022-02-24T07:29:17.000Z
external_plugin_deps.bzl
michalgagat/plugins_oauth
47cc344013bd43a4ac508c578f2d93f37a166ee6
[ "Apache-2.0", "MIT" ]
97
2015-02-27T18:35:20.000Z
2022-01-08T13:17:21.000Z
load("//tools/bzl:maven_jar.bzl", "maven_jar")
34.310345
84
0.629146
461741b98d074cd4fe4db2b2b85584fd2a2f2b2d
442
py
Python
11.-Operaciones_entero_con_float_python.py
emiliocarcanobringas/11.-Operaciones_entero_con_float_python
faf3bf2fae3b7a990e0d20483ac9ac219dcb7857
[ "MIT" ]
null
null
null
11.-Operaciones_entero_con_float_python.py
emiliocarcanobringas/11.-Operaciones_entero_con_float_python
faf3bf2fae3b7a990e0d20483ac9ac219dcb7857
[ "MIT" ]
null
null
null
11.-Operaciones_entero_con_float_python.py
emiliocarcanobringas/11.-Operaciones_entero_con_float_python
faf3bf2fae3b7a990e0d20483ac9ac219dcb7857
[ "MIT" ]
null
null
null
# Este programa muestra la suma de dos variables, de tipo int y float print("Este programa muestra la suma de dos variables, de tipo int y float") print("Tambin muestra que la variable que realiza la operacin es de tipo float") numero1 = 7 numero2 = 3.1416 sumadeambos = numero1 + numero2 print("El resultado de la suma es: ") print(sumadeambos) print(type(sumadeambos)) # Este programa fue escrito por Emilio Carcao Bringas
34
83
0.748869
46175a845f983668cd1561f331edd1b1e7cee344
12,398
py
Python
main_gat.py
basiralab/RG-Select
074274f61667611205724c4423fc498ee4a0a9d0
[ "MIT" ]
1
2021-09-07T06:55:37.000Z
2021-09-07T06:55:37.000Z
main_gat.py
basiralab/RG-Select
074274f61667611205724c4423fc498ee4a0a9d0
[ "MIT" ]
null
null
null
main_gat.py
basiralab/RG-Select
074274f61667611205724c4423fc498ee4a0a9d0
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from sklearn import preprocessing from torch.autograd import Variable from models_gat import GAT import os import torch import numpy as np import argparse import pickle import sklearn.metrics as metrics import cross_val import time import random torch.manual_seed(0) np.random.seed(0) random.seed(0) device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') def evaluate(dataset, model_GAT, args, threshold_value, model_name): """ Parameters ---------- dataset : dataloader (dataloader for the validation/test dataset). model_GCN : nn model (GAT model). args : arguments threshold_value : float (threshold for adjacency matrices). Description ---------- This methods performs the evaluation of the model on test/validation dataset Returns ------- test accuracy. """ model_GAT.eval() labels = [] preds = [] for batch_idx, data in enumerate(dataset): adj = Variable(data['adj'].float(), requires_grad=False).to(device) labels.append(data['label'].long().numpy()) adj = torch.squeeze(adj) features = np.identity(adj.shape[0]) features = Variable(torch.from_numpy(features).float(), requires_grad=False).cpu() if args.threshold in ["median", "mean"]: adj = torch.where(adj > threshold_value, torch.tensor([1.0]), torch.tensor([0.0])) ypred = model_GAT(features, adj) _, indices = torch.max(ypred, 1) preds.append(indices.cpu().data.numpy()) labels = np.hstack(labels) preds = np.hstack(preds) simple_r = {'labels':labels,'preds':preds} with open("./gat/Labels_and_preds/"+model_name+".pickle", 'wb') as f: pickle.dump(simple_r, f) result = {'prec': metrics.precision_score(labels, preds, average='macro'), 'recall': metrics.recall_score(labels, preds, average='macro'), 'acc': metrics.accuracy_score(labels, preds), 'F1': metrics.f1_score(labels, preds, average="micro")} if args.evaluation_method == 'model assessment': name = 'Test' if args.evaluation_method == 'model selection': name = 'Validation' print(name, " accuracy:", result['acc']) return result['acc'] def train(args, train_dataset, val_dataset, model_GAT, threshold_value, model_name): """ Parameters ---------- args : arguments train_dataset : dataloader (dataloader for the validation/test dataset). val_dataset : dataloader (dataloader for the validation/test dataset). model_GAT : nn model (GAT model). threshold_value : float (threshold for adjacency matrices). Description ---------- This methods performs the training of the model on train dataset and calls evaluate() method for evaluation. Returns ------- test accuracy. """ params = list(model_GAT.parameters()) optimizer = torch.optim.Adam(params, lr=args.lr, weight_decay=args.weight_decay) test_accs = [] train_loss=[] val_acc=[] for epoch in range(args.num_epochs): print("Epoch ",epoch) print("Size of Training Set:" + str(len(train_dataset))) print("Size of Validation Set:" + str(len(val_dataset))) model_GAT.train() total_time = 0 avg_loss = 0.0 preds = [] labels = [] for batch_idx, data in enumerate(train_dataset): begin_time = time.time() adj = Variable(data['adj'].float(), requires_grad=False).to(device) label = Variable(data['label'].long()).to(device) #adj_id = Variable(data['id'].int()).to(device) adj = torch.squeeze(adj) features = np.identity(adj.shape[0]) features = Variable(torch.from_numpy(features).float(), requires_grad=False).cpu() if args.threshold in ["median", "mean"]: adj = torch.where(adj > threshold_value, torch.tensor([1.0]), torch.tensor([0.0])) ypred = model_GAT(features, adj) _, indices = torch.max(ypred, 1) preds.append(indices.cpu().data.numpy()) labels.append(data['label'].long().numpy()) loss = model_GAT.loss(ypred, label) model_GAT.zero_grad() loss.backward() #nn.utils.clip_grad_norm_(model_DIFFPOOL.parameters(), args.clip) optimizer.step() avg_loss += loss elapsed = time.time() - begin_time total_time += elapsed if epoch == args.num_epochs-1: model_GAT.is_trained = True preds = np.hstack(preds) labels = np.hstack(labels) print("Train accuracy : ", np.mean( preds == labels )) test_acc = evaluate(val_dataset, model_GAT, args, threshold_value, model_name) print('Avg loss: ', avg_loss, '; epoch time: ', total_time) test_accs.append(test_acc) train_loss.append(avg_loss) val_acc.append(test_acc) path = './gat/weights/W_'+model_name+'.pickle' if os.path.exists(path): os.remove(path) os.rename('GAT_W.pickle',path) los_p = {'loss':train_loss} with open("./gat/training_loss/Training_loss_"+model_name+".pickle", 'wb') as f: pickle.dump(los_p, f) torch.save(model_GAT,"./gat/models/GAT_"+model_name+".pt") return test_acc def load_data(args): """ Parameters ---------- args : arguments Description ---------- This methods loads the adjacency matrices representing the args.view -th view in dataset Returns ------- List of dictionaries{adj, label, id} """ #Load graphs and labels with open('data/'+args.dataset+'/'+args.dataset+'_edges','rb') as f: multigraphs = pickle.load(f) with open('data/'+args.dataset+'/'+args.dataset+'_labels','rb') as f: labels = pickle.load(f) adjacencies = [multigraphs[i][:,:,args.view] for i in range(len(multigraphs))] #Normalize inputs if args.NormalizeInputGraphs==True: for subject in range(len(adjacencies)): adjacencies[subject] = minmax_sc(adjacencies[subject]) #Create List of Dictionaries G_list=[] for i in range(len(labels)): G_element = {"adj": adjacencies[i],"label": labels[i],"id": i,} G_list.append(G_element) return G_list def arg_parse(dataset, view, num_shots=2, cv_number=5): """ arguments definition method """ parser = argparse.ArgumentParser(description='Graph Classification') parser.add_argument('--mode', type=str, default='train', choices=['train', 'test']) parser.add_argument('--v', type=str, default=1) parser.add_argument('--data', type=str, default='Sample_dataset', choices = [ f.path[5:] for f in os.scandir("data") if f.is_dir() ]) parser.add_argument('--dataset', type=str, default=dataset, help='Dataset') parser.add_argument('--view', type=int, default=view, help = 'view index in the dataset') parser.add_argument('--num_epochs', type=int, default=1, #50 help='Training Epochs') parser.add_argument('--num_shots', type=int, default=num_shots, #100 help='number of shots') parser.add_argument('--cv_number', type=int, default=cv_number, help='number of validation folds.') parser.add_argument('--NormalizeInputGraphs', default=False, action='store_true', help='Normalize Input adjacency matrices of graphs') parser.add_argument('--evaluation_method', type=str, default='model assessment', help='evaluation method, possible values : model selection, model assessment') parser.add_argument('--threshold', dest='threshold', default='mean', help='threshold the graph adjacency matrix. Possible values: no_threshold, median, mean') parser.add_argument('--no-cuda', action='store_true', default=False, help='Disables CUDA training.') parser.add_argument('--num-classes', dest='num_classes', type=int, default=2, help='Number of label classes') parser.add_argument('--lr', type=float, default=0.001, help='Initial learning rate.') parser.add_argument('--weight_decay', type=float, default=5e-4, help='Weight decay (L2 loss on parameters).') parser.add_argument('--hidden', type=int, default=8, help='Number of hidden units.') parser.add_argument('--nb_heads', type=int, default=8, help='Number of head attentions.') parser.add_argument('--dropout', type=float, default=0.8, help='Dropout rate (1 - keep probability).') parser.add_argument('--alpha', type=float, default=0.2, help='Alpha for the leaky_relu.') return parser.parse_args() def benchmark_task(args, model_name): """ Parameters ---------- args : Arguments Description ---------- Initiates the model and performs train/test or train/validation splits and calls train() to execute training and evaluation. Returns ------- test_accs : test accuracies (list) """ G_list = load_data(args) num_nodes = G_list[0]['adj'].shape[0] test_accs = [] folds = cross_val.stratify_splits(G_list,args) [random.shuffle(folds[i]) for i in range(len(folds))] for i in range(args.cv_number): train_set, validation_set, test_set = cross_val.datasets_splits(folds, args, i) if args.evaluation_method =='model selection': train_dataset, val_dataset, threshold_value = cross_val.model_selection_split(train_set, validation_set, args) if args.evaluation_method =='model assessment': train_dataset, val_dataset, threshold_value = cross_val.model_assessment_split(train_set, validation_set, test_set, args) print("CV : ",i) model_GAT = GAT(nfeat=num_nodes, nhid=args.hidden, nclass=args.num_classes, dropout=args.dropout, nheads=args.nb_heads, alpha=args.alpha) test_acc = train(args, train_dataset, val_dataset, model_GAT, threshold_value, model_name+"_CV_"+str(i)+"_view_"+str(args.view)) test_accs.append(test_acc) return test_accs
37.008955
137
0.607275
4617a69a551305b5f32925b26d808534b36117fc
12,752
py
Python
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Python/piexif/_dump.py
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
8
2019-10-07T16:33:47.000Z
2020-12-07T03:59:58.000Z
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Python/piexif/_dump.py
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
1
2018-02-18T22:24:55.000Z
2018-02-21T18:36:09.000Z
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Python/piexif/_dump.py
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
5
2020-08-27T20:44:18.000Z
2021-08-21T22:54:11.000Z
import copy import numbers import struct from ._common import * from ._exif import * TIFF_HEADER_LENGTH = 8 def dump(exif_dict_original): """ py:function:: piexif.load(data) Return exif as bytes. :param dict exif: Exif data({"0th":dict, "Exif":dict, "GPS":dict, "Interop":dict, "1st":dict, "thumbnail":bytes}) :return: Exif :rtype: bytes """ exif_dict = copy.deepcopy(exif_dict_original) header = b"Exif\x00\x00\x4d\x4d\x00\x2a\x00\x00\x00\x08" exif_is = False gps_is = False interop_is = False first_is = False if "0th" in exif_dict: zeroth_ifd = exif_dict["0th"] else: zeroth_ifd = {} if (("Exif" in exif_dict) and len(exif_dict["Exif"]) or ("Interop" in exif_dict) and len(exif_dict["Interop"]) ): zeroth_ifd[ImageIFD.ExifTag] = 1 exif_is = True exif_ifd = exif_dict["Exif"] if ("Interop" in exif_dict) and len(exif_dict["Interop"]): exif_ifd[ExifIFD. InteroperabilityTag] = 1 interop_is = True interop_ifd = exif_dict["Interop"] elif ExifIFD. InteroperabilityTag in exif_ifd: exif_ifd.pop(ExifIFD.InteroperabilityTag) elif ImageIFD.ExifTag in zeroth_ifd: zeroth_ifd.pop(ImageIFD.ExifTag) if ("GPS" in exif_dict) and len(exif_dict["GPS"]): zeroth_ifd[ImageIFD.GPSTag] = 1 gps_is = True gps_ifd = exif_dict["GPS"] elif ImageIFD.GPSTag in zeroth_ifd: zeroth_ifd.pop(ImageIFD.GPSTag) if (("1st" in exif_dict) and ("thumbnail" in exif_dict) and (exif_dict["thumbnail"] is not None)): first_is = True exif_dict["1st"][ImageIFD.JPEGInterchangeFormat] = 1 exif_dict["1st"][ImageIFD.JPEGInterchangeFormatLength] = 1 first_ifd = exif_dict["1st"] zeroth_set = _dict_to_bytes(zeroth_ifd, "0th", 0) zeroth_length = (len(zeroth_set[0]) + exif_is * 12 + gps_is * 12 + 4 + len(zeroth_set[1])) if exif_is: exif_set = _dict_to_bytes(exif_ifd, "Exif", zeroth_length) exif_length = len(exif_set[0]) + interop_is * 12 + len(exif_set[1]) else: exif_bytes = b"" exif_length = 0 if gps_is: gps_set = _dict_to_bytes(gps_ifd, "GPS", zeroth_length + exif_length) gps_bytes = b"".join(gps_set) gps_length = len(gps_bytes) else: gps_bytes = b"" gps_length = 0 if interop_is: offset = zeroth_length + exif_length + gps_length interop_set = _dict_to_bytes(interop_ifd, "Interop", offset) interop_bytes = b"".join(interop_set) interop_length = len(interop_bytes) else: interop_bytes = b"" interop_length = 0 if first_is: offset = zeroth_length + exif_length + gps_length + interop_length first_set = _dict_to_bytes(first_ifd, "1st", offset) thumbnail = _get_thumbnail(exif_dict["thumbnail"]) thumbnail_max_size = 64000 if len(thumbnail) > thumbnail_max_size: raise ValueError("Given thumbnail is too large. max 64kB") else: first_bytes = b"" if exif_is: pointer_value = TIFF_HEADER_LENGTH + zeroth_length pointer_str = struct.pack(">I", pointer_value) key = ImageIFD.ExifTag key_str = struct.pack(">H", key) type_str = struct.pack(">H", TYPES.Long) length_str = struct.pack(">I", 1) exif_pointer = key_str + type_str + length_str + pointer_str else: exif_pointer = b"" if gps_is: pointer_value = TIFF_HEADER_LENGTH + zeroth_length + exif_length pointer_str = struct.pack(">I", pointer_value) key = ImageIFD.GPSTag key_str = struct.pack(">H", key) type_str = struct.pack(">H", TYPES.Long) length_str = struct.pack(">I", 1) gps_pointer = key_str + type_str + length_str + pointer_str else: gps_pointer = b"" if interop_is: pointer_value = (TIFF_HEADER_LENGTH + zeroth_length + exif_length + gps_length) pointer_str = struct.pack(">I", pointer_value) key = ExifIFD.InteroperabilityTag key_str = struct.pack(">H", key) type_str = struct.pack(">H", TYPES.Long) length_str = struct.pack(">I", 1) interop_pointer = key_str + type_str + length_str + pointer_str else: interop_pointer = b"" if first_is: pointer_value = (TIFF_HEADER_LENGTH + zeroth_length + exif_length + gps_length + interop_length) first_ifd_pointer = struct.pack(">L", pointer_value) thumbnail_pointer = (pointer_value + len(first_set[0]) + 24 + 4 + len(first_set[1])) thumbnail_p_bytes = (b"\x02\x01\x00\x04\x00\x00\x00\x01" + struct.pack(">L", thumbnail_pointer)) thumbnail_length_bytes = (b"\x02\x02\x00\x04\x00\x00\x00\x01" + struct.pack(">L", len(thumbnail))) first_bytes = (first_set[0] + thumbnail_p_bytes + thumbnail_length_bytes + b"\x00\x00\x00\x00" + first_set[1] + thumbnail) else: first_ifd_pointer = b"\x00\x00\x00\x00" zeroth_bytes = (zeroth_set[0] + exif_pointer + gps_pointer + first_ifd_pointer + zeroth_set[1]) if exif_is: exif_bytes = exif_set[0] + interop_pointer + exif_set[1] return (header + zeroth_bytes + exif_bytes + gps_bytes + interop_bytes + first_bytes)
36.74928
117
0.571361
4617fb2b1109fbc2c363e6e5ce80547d57eca614
8,000
py
Python
portal.py
mrahman4782/portalhoop
29e87ccaca5544590aa9ed20096c3628c1ab57b1
[ "Apache-2.0" ]
null
null
null
portal.py
mrahman4782/portalhoop
29e87ccaca5544590aa9ed20096c3628c1ab57b1
[ "Apache-2.0" ]
null
null
null
portal.py
mrahman4782/portalhoop
29e87ccaca5544590aa9ed20096c3628c1ab57b1
[ "Apache-2.0" ]
null
null
null
import pygame import random from pygame import * pygame.init() width, height = 740, 500 screen = pygame.display.set_mode((width, height)) player = [pygame.transform.scale(pygame.image.load("Resources/Balljump-1(2).png"), (100,100)), pygame.transform.scale(pygame.image.load("Resources/Balljump-1.png"),(100,100))] launch = [pygame.transform.scale(pygame.image.load("Resources/Balljump-1.png"), (100,100)), pygame.transform.scale(pygame.image.load("Resources/Balljump-1(2).png"), (100,100)),pygame.transform.scale(pygame.image.load("Resources/Balljump-2.png"), (100,100)),pygame.transform.scale(pygame.image.load("Resources/Balljump-3.png"), (100,100)), pygame.transform.scale(pygame.image.load("Resources/Balljump-4.png"),(100,100))] shoot = [pygame.transform.scale(pygame.image.load("Resources/Balljump-5.png"), (100, 100)), pygame.transform.scale(pygame.image.load("Resources/Balljump-6.png"), (100, 100))] ball = pygame.transform.scale(pygame.image.load("Resources/ball.png"), (100,100)) blue = (0, 0, 128) white = (255, 255, 255) janimation, danimation, movable, motionactivate, limit_reached, nojump = False, False, False, False, False, False jumplock = True ballrelease, ballregain = False, False fr = pygame.time.Clock() c = 0 i = 0 p = 0 x, y = 0, 300 score = 0 a, b, rpos = 0, 0, 0 xpos, ypos = 17, 313 # Background image source: https://www.freepik.com/free-vector/floral-ornamental-abstract-background_6189902.htm#page=1&query=black%20background&position=40 background = pygame.image.load("Resources/back.jpg") gamestart = False while 1: keypress = pygame.key.get_pressed() fr.tick(30) screen.fill(0) if keypress[K_RETURN]: gamestart = True if gamestart == False: #screen.fill(0) screen.blit(background, (0,0)) # Draw opening texts font = pygame.font.Font("Resources/android.ttf", 64) text = font.render("Portal Hoop", True, white) textRect = text.get_rect() textRect.center = (width // 2, height // 2 - 100) screen.blit(text, textRect) font = pygame.font.Font("Resources/android.ttf", 18) text2 = font.render("Press Return to start", True, white) textRect2 = text2.get_rect() textRect2.center = (width // 2, height // 2 + 100) screen.blit(text2, textRect2) nojump = True # Check if any if gamestart == True: #screen.fill(0) player_animations() player_jump() basketball() screen_text() pygame.display.flip() pygame.display.set_caption("Portal Hoop") for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit(0)
28.776978
419
0.5115
46195f448a6bacb19ed1a57308155484d10e7c8b
2,137
py
Python
datadog_cluster_agent/tests/test_datadog_cluster_agent.py
tdimnet/integrations-core
a78133a3b71a1b8377fa214d121a98647031ab06
[ "BSD-3-Clause" ]
1
2021-12-15T22:45:14.000Z
2021-12-15T22:45:14.000Z
datadog_cluster_agent/tests/test_datadog_cluster_agent.py
tdimnet/integrations-core
a78133a3b71a1b8377fa214d121a98647031ab06
[ "BSD-3-Clause" ]
null
null
null
datadog_cluster_agent/tests/test_datadog_cluster_agent.py
tdimnet/integrations-core
a78133a3b71a1b8377fa214d121a98647031ab06
[ "BSD-3-Clause" ]
null
null
null
# (C) Datadog, Inc. 2021-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from typing import Any, Dict from datadog_checks.base.stubs.aggregator import AggregatorStub from datadog_checks.datadog_cluster_agent import DatadogClusterAgentCheck from datadog_checks.dev.utils import get_metadata_metrics NAMESPACE = 'datadog.cluster_agent' METRICS = [ 'admission_webhooks.certificate_expiry', 'admission_webhooks.mutation_attempts', 'admission_webhooks.mutation_errors', 'admission_webhooks.reconcile_errors', 'admission_webhooks.reconcile_success', 'admission_webhooks.webhooks_received', 'aggregator.flush', 'aggregator.processed', 'api_requests', 'cluster_checks.busyness', 'cluster_checks.configs_dangling', 'cluster_checks.configs_dispatched', 'cluster_checks.failed_stats_collection', 'cluster_checks.nodes_reporting', 'cluster_checks.rebalancing_decisions', 'cluster_checks.rebalancing_duration_seconds', 'cluster_checks.successful_rebalancing_moves', 'cluster_checks.updating_stats_duration_seconds', 'datadog.rate_limit_queries.limit', 'datadog.rate_limit_queries.period', 'datadog.rate_limit_queries.remaining', 'datadog.rate_limit_queries.reset', 'datadog.requests', 'external_metrics', 'external_metrics.datadog_metrics', 'external_metrics.delay_seconds', 'external_metrics.processed_value', 'secret_backend.elapsed', 'go.goroutines', 'go.memstats.alloc_bytes', 'go.threads', ]
34.467742
87
0.759944
461ab2e151fa2b1e92504b3b4e0d6a8160278475
843
py
Python
prev_ob_models/KaplanLansner2014/plotting_and_analysis/plot_results.py
fameshpatel/olfactorybulb
8d7a644b4560309ef177c0590ff73ed4c2432604
[ "MIT" ]
5
2019-10-03T14:49:02.000Z
2022-01-13T13:37:34.000Z
prev_ob_models/KaplanLansner2014/plotting_and_analysis/plot_results.py
fameshpatel/olfactorybulb
8d7a644b4560309ef177c0590ff73ed4c2432604
[ "MIT" ]
4
2019-12-30T15:57:24.000Z
2020-10-07T22:42:50.000Z
prev_ob_models/KaplanLansner2014/plotting_and_analysis/plot_results.py
fameshpatel/olfactorybulb
8d7a644b4560309ef177c0590ff73ed4c2432604
[ "MIT" ]
2
2020-05-19T20:12:48.000Z
2020-11-04T17:17:44.000Z
import pylab import numpy import sys if (len(sys.argv) < 2): fn = raw_input("Please enter data file to be plotted\n") else: fn = sys.argv[1] data = np.loadtxt(fn) # if the first line contains crap use skiprows=1 #data = np.loadtxt(fn, skiprows=1) fig = pylab.figure() ax = fig.add_subplot(111) # if you want to use multiple figures in one, use #ax1 = fig.add_subplot(211) #ax2 = fig.add_subplot(212) # and if (data.ndim == 1): x_axis = numpy.arange(data.size) ax.plot(x_axis, data) else: # ax.errorbar(data[:,0], data[:,1], yerr=data[:, 2]) # print 'mean y-value:', data[:, 1].mean() ax.plot(data[:, 0], data[:, 1], ls='-', lw=3, c='b') # ax.scatter(data[:,0], data[:,2]) # ax.plot(data[:,3], data[:,6]) # saving: # fig.savefig('output_figure.png') # otherwise nothing is shown pylab.show()
21.075
60
0.618031
1c9d4e8ece8e1713ad5f9d3791c348c5f5f83733
2,691
py
Python
lib/take2/main.py
zacharyfrederick/deep_q_gaf
6b712b17a6c89c1cba0d22e18fa336369c521d4e
[ "MIT" ]
null
null
null
lib/take2/main.py
zacharyfrederick/deep_q_gaf
6b712b17a6c89c1cba0d22e18fa336369c521d4e
[ "MIT" ]
null
null
null
lib/take2/main.py
zacharyfrederick/deep_q_gaf
6b712b17a6c89c1cba0d22e18fa336369c521d4e
[ "MIT" ]
null
null
null
from __future__ import division from lib import env_config from lib.senior_env import BetterEnvironment from keras.optimizers import Adam from rl.agents.dqn import DQNAgent from rl.policy import LinearAnnealedPolicy, BoltzmannQPolicy, EpsGreedyQPolicy from rl.memory import SequentialMemory from lib import models import random choices = [0,1,2] if __name__ == '__main__': config_ = env_config.EnvConfig('config/debug.json') env = BetterEnvironment(config_) INPUT_SHAPE = (30, 180) WINDOW_LENGTH = 4 model = models.build_paper_model() # Get the environment and extract the number of actions. nb_actions = 3 # Next, we build our model. We use the same model that was described by Mnih et al. (2015). input_shape = (WINDOW_LENGTH,) + INPUT_SHAPE # Finally, we configure and compile our agent. You can use every built-in Keras optimizer and # even the metrics! memory = SequentialMemory(limit=10000000, window_length=WINDOW_LENGTH) # Select a policy. We use eps-greedy action selection, which means that a random action is selected # with probability eps. We anneal eps from 1.0 to 0.1 over the course of 1M steps. This is done so that # the agent initially explores the environment (high eps) and then gradually sticks to what it knows # (low eps). We also set a dedicated eps value that is used during testing. Note that we set it to 0.05 # so that the agent still performs some random actions. This ensures that the agent cannot get stuck. policy = LinearAnnealedPolicy(EpsGreedyQPolicy(), attr='eps', value_max=1., value_min=.1, value_test=.05, nb_steps=1000000) # The trade-off between exploration and exploitation is difficult and an on-going research topic. # If you want, you can experiment with the parameters or use a different policy. Another popular one # is Boltzmann-style exploration: # policy = BoltzmannQPolicy(tau=1.) # Feel free to give it a try! dqn = DQNAgent(model=model, nb_actions=nb_actions, policy=policy, memory=memory, nb_steps_warmup=50000, gamma=.99, target_model_update=10000, train_interval=4, delta_clip=1.) dqn.compile(Adam(lr=.00025), metrics=['mae']) # Okay, now it's time to learn something! We capture the interrupt exception so that training # can be prematurely aborted. Notice that now you can use the built-in Keras callbacks! weights_filename = 'dqn_{}_weights.h5f'.format('god_help_me.weights') dqn.fit(env, nb_steps=100000, log_interval=10000) print(env.portfolio.print_portfolio_results())
42.714286
109
0.726867
1c9df7adb0b666ca2019704ffcc93ac51a469c6b
1,752
py
Python
src/clcore.py
ShepardPower/PyMCBuilder
b247151864cc6b7bca0dc23aa87cdbb44b52defc
[ "MIT" ]
1
2019-07-09T04:45:07.000Z
2019-07-09T04:45:07.000Z
src/clcore.py
ShepardPower/PyMCBuilder
b247151864cc6b7bca0dc23aa87cdbb44b52defc
[ "MIT" ]
null
null
null
src/clcore.py
ShepardPower/PyMCBuilder
b247151864cc6b7bca0dc23aa87cdbb44b52defc
[ "MIT" ]
null
null
null
# I'm just the one that executes the instructions! import sys, math, json, operator, time import mcpi.minecraft as minecraft from PIL import Image as pillow from blockid import get_block import mcpi.block as block import functions as pymc from tqdm import tqdm import tkinter as tk # Functions # Main code mc = minecraft.Minecraft.create() try: json_file = open("blocks.json") json_put = json.load(json_file) except: pymc.chat(mc, "blocks.json not found, exiting!", 0) sys.exit(1) try: rim = pillow.open(sys.argv[1]) except: pymc.chat(mc, "bad image, exiting!", 0) sys.exit(1) orders = [] used = [] imwid, imhei = rim.size if imhei > 200: maxheight = 200 rim.thumbnail((200, maxheight), pillow.ANTIALIAS) imwid, imhei = rim.size pymc.chat(mc, "image is over 200 pixels, reducing height.", 1) rim.convert('RGB') im = rim.load() pbar = tqdm(total=imhei*imwid) for hei in range(imhei): for wid in range(imwid): smal = pymc.comp_pixel((im[wid, hei][0], im[wid, hei][1], im[wid, hei][2]), json_put) im[wid, hei] = smal[1] used.append(str(smal[2])) pbar.update(1) pbar.close() rim.save("result.GIF") # The result json_file.close() oldPos = mc.player.getPos() playerPos = [round(oldPos.x), round(oldPos.y), round(oldPos.z)] pymc.chat(mc, "Ready!") pbar = tqdm(total=imhei*imwid) num_temp = imhei*imwid-1 for hei in range(imhei): for wid in range(imwid): #print(used[wid + (imhei * hei)]) gblock = get_block(used[num_temp]) mc.setBlock(playerPos[0]+wid, playerPos[1]+hei, playerPos[2], gblock) num_temp -= 1 pbar.update(1) pbar.close() pymc.chat(mc, "Done!!") pymc.chat(mc, "Please star us on github if you like the result!", 2)
26.545455
93
0.66153
1c9e901d1d765a0acf44b58e4a7dca2f74accdab
4,377
py
Python
gaphor/tools/gaphorconvert.py
987Frogh/project-makehuman
3afc838b03c50f8e574d8c87cb71de4435a18a6d
[ "Apache-2.0" ]
1
2020-11-27T12:39:15.000Z
2020-11-27T12:39:15.000Z
gaphor/tools/gaphorconvert.py
987Frogh/project-makehuman
3afc838b03c50f8e574d8c87cb71de4435a18a6d
[ "Apache-2.0" ]
null
null
null
gaphor/tools/gaphorconvert.py
987Frogh/project-makehuman
3afc838b03c50f8e574d8c87cb71de4435a18a6d
[ "Apache-2.0" ]
3
2020-01-23T14:13:59.000Z
2020-02-18T18:21:47.000Z
#!/usr/bin/python import optparse import os import re import sys import cairo from gaphas.painter import Context, ItemPainter from gaphas.view import View import gaphor.UML as UML from gaphor.application import Application from gaphor.storage import storage def pkg2dir(package): """ Return directory path from UML package class. """ name = [] while package: name.insert(0, package.name) package = package.package return "/".join(name)
28.796053
87
0.570482
1ca0182af54f9900fd8dd3f4d8ff457375adde5e
1,140
py
Python
test/test_ID.py
a-buntjer/tsib
9d6ddcdca55c9b8afb5324c0da8d0910cb1a326e
[ "MIT" ]
14
2019-12-16T16:54:43.000Z
2021-11-08T11:46:51.000Z
test/test_ID.py
a-buntjer/tsib
9d6ddcdca55c9b8afb5324c0da8d0910cb1a326e
[ "MIT" ]
null
null
null
test/test_ID.py
a-buntjer/tsib
9d6ddcdca55c9b8afb5324c0da8d0910cb1a326e
[ "MIT" ]
7
2020-05-27T19:49:58.000Z
2022-02-02T12:45:33.000Z
# -*- coding: utf-8 -*- """ Created on Fri Apr 08 11:33:01 2016 @author: Leander Kotzur """ import tsib
20.727273
47
0.509649
1ca13538bfcd1f5b4948e14f8020f58d87fb25a8
25,791
py
Python
dislib/model_selection/_search.py
alexbarcelo/dislib
989f81f235ae30b17410a8d805df258c7d931b38
[ "Apache-2.0" ]
36
2018-10-22T19:21:14.000Z
2022-03-22T12:10:01.000Z
dislib/model_selection/_search.py
alexbarcelo/dislib
989f81f235ae30b17410a8d805df258c7d931b38
[ "Apache-2.0" ]
329
2018-11-22T18:04:57.000Z
2022-03-18T01:26:55.000Z
dislib/model_selection/_search.py
alexbarcelo/dislib
989f81f235ae30b17410a8d805df258c7d931b38
[ "Apache-2.0" ]
21
2019-01-10T11:46:39.000Z
2022-03-17T12:59:45.000Z
from abc import ABC, abstractmethod from collections import defaultdict from collections.abc import Sequence from functools import partial from itertools import product import numpy as np from pycompss.api.api import compss_wait_on from scipy.stats import rankdata from sklearn import clone from sklearn.model_selection import ParameterGrid, ParameterSampler from numpy.ma import MaskedArray from dislib.model_selection._split import infer_cv from dislib.model_selection._validation import check_scorer, fit_and_score, \ validate_score, aggregate_score_dicts
44.087179
79
0.584351
1ca1a822fc7884017cd3ac1dd4d887f9f5596b45
1,407
py
Python
webapp/ui/tests/test_parse_search_results.py
robseed/botanist
2f4fbab5d26499105a5057c86e0e6e37a2e8a727
[ "MIT" ]
null
null
null
webapp/ui/tests/test_parse_search_results.py
robseed/botanist
2f4fbab5d26499105a5057c86e0e6e37a2e8a727
[ "MIT" ]
null
null
null
webapp/ui/tests/test_parse_search_results.py
robseed/botanist
2f4fbab5d26499105a5057c86e0e6e37a2e8a727
[ "MIT" ]
null
null
null
import os from django.test import TestCase from mock import patch from ui.views import parse_search_results FIXTURES_ROOT = os.path.join(os.path.dirname(__file__), 'fixtures') FX = lambda *relpath: os.path.join(FIXTURES_ROOT, *relpath)
43.96875
188
0.686567
1ca1fbc58c354b91137807db3948258d4447da15
4,395
py
Python
minos/api_gateway/common/exceptions.py
Clariteia/api_gateway_common
e68095f31091699fc6cc4537bd6acf97a8dc6c3e
[ "MIT" ]
3
2021-05-14T08:13:09.000Z
2021-05-26T11:25:35.000Z
minos/api_gateway/common/exceptions.py
Clariteia/api_gateway_common
e68095f31091699fc6cc4537bd6acf97a8dc6c3e
[ "MIT" ]
27
2021-05-13T08:43:19.000Z
2021-08-24T17:19:36.000Z
minos/api_gateway/common/exceptions.py
Clariteia/api_gateway_common
e68095f31091699fc6cc4537bd6acf97a8dc6c3e
[ "MIT" ]
null
null
null
""" Copyright (C) 2021 Clariteia SL This file is part of minos framework. Minos framework can not be copied and/or distributed without the express permission of Clariteia SL. """ from typing import ( Any, Type, )
30.520833
116
0.739022
1ca27636ecfdf6c794d529bed48bdedc1987bdf3
4,598
py
Python
tsdl/tools/extensions.py
burgerdev/hostload
93142628bb32923c5e6f3a8b791488d72a5c9077
[ "MIT" ]
null
null
null
tsdl/tools/extensions.py
burgerdev/hostload
93142628bb32923c5e6f3a8b791488d72a5c9077
[ "MIT" ]
null
null
null
tsdl/tools/extensions.py
burgerdev/hostload
93142628bb32923c5e6f3a8b791488d72a5c9077
[ "MIT" ]
null
null
null
""" Extensions for pylearn2 training algorithms. Those are either reimplemented to suit the execution model of this package, or new ones for recording metrics. """ import os import cPickle as pkl import numpy as np from pylearn2.train_extensions import TrainExtension from .abcs import Buildable
27.047059
78
0.626577
1ca288015e226ac02375d4c474cc5edb714fc3e0
6,189
py
Python
nogi/utils/post_extractor.py
Cooomma/nogi-backup-blog
19868511d2b0f0c4d06bf4a88981bbfadc4121e4
[ "MIT" ]
null
null
null
nogi/utils/post_extractor.py
Cooomma/nogi-backup-blog
19868511d2b0f0c4d06bf4a88981bbfadc4121e4
[ "MIT" ]
164
2020-04-02T18:25:59.000Z
2022-02-17T17:09:32.000Z
nogi/utils/post_extractor.py
Cooomma/nogi-backup-blog
19868511d2b0f0c4d06bf4a88981bbfadc4121e4
[ "MIT" ]
null
null
null
import asyncio from io import BytesIO import logging import os import random import time from typing import List from urllib.parse import urlparse import aiohttp from aiohttp import ClientSession, TCPConnector import requests from requests import Response from tqdm import tqdm from nogi import REQUEST_HEADERS from nogi.db.nogi_blog_content import NogiBlogContent from nogi.db.nogi_blog_summary import NogiBlogSummary from nogi.storages.gcs import GCS from nogi.utils.parsers import PostParser, generate_post_key logger = logging.getLogger() HEADERS = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36' }
41.26
146
0.618517
1ca3e775b2d474b15aa148de47bee4762a8d884c
1,429
py
Python
sandbox/lib/jumpscale/JumpscaleLibsExtra/sal_zos/gateway/dhcp.py
threefoldtech/threebot_prebuilt
1f0e1c65c14cef079cd80f73927d7c8318755c48
[ "Apache-2.0" ]
1
2020-10-05T08:53:57.000Z
2020-10-05T08:53:57.000Z
sandbox/lib/jumpscale/JumpscaleLibsExtra/sal_zos/gateway/dhcp.py
threefoldtech/threebot_prebuilt
1f0e1c65c14cef079cd80f73927d7c8318755c48
[ "Apache-2.0" ]
17
2019-11-14T08:41:37.000Z
2020-05-27T09:23:51.000Z
sandbox/lib/jumpscale/JumpscaleLibsExtra/sal_zos/gateway/dhcp.py
threefoldtech/threebot_prebuilt
1f0e1c65c14cef079cd80f73927d7c8318755c48
[ "Apache-2.0" ]
null
null
null
from Jumpscale import j import signal from .. import templates DNSMASQ = "/bin/dnsmasq --conf-file=/etc/dnsmasq.conf -d"
36.641026
94
0.638908
1ca47a4968ffeca31ec462add05b792e1ab435c2
340
py
Python
answer/a4_type.py
breeze-shared-inc/python_training_01
7e918b37adbce062ae279f060bc25cfacda2fb85
[ "MIT" ]
null
null
null
answer/a4_type.py
breeze-shared-inc/python_training_01
7e918b37adbce062ae279f060bc25cfacda2fb85
[ "MIT" ]
1
2020-05-11T04:59:04.000Z
2020-05-11T05:29:08.000Z
answer/a4_type.py
bzgwhite/python_training_01
7e918b37adbce062ae279f060bc25cfacda2fb85
[ "MIT" ]
null
null
null
hensu_int = 17 # hensu_float = 1.7 #() hensu_str = "HelloWorld" # hensu_bool = True # hensu_list = [] # hensu_tuple = () # hensu_dict = {} # print(type(hensu_int)) print(type(hensu_float)) print(type(hensu_str)) print(type(hensu_bool)) print(type(hensu_list)) print(type(hensu_tuple)) print(type(hensu_dict))
21.25
29
0.732353