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
b5feaca4c7898be1eafff6774aa6c07103db3835
444
py
Python
djangoProject/webApp/models.py
ChenxuanZhao/wireless-fire-alarm-software-system
6800eda7c96e55fdca8fab5b3a0cb09f05df2416
[ "Apache-2.0" ]
null
null
null
djangoProject/webApp/models.py
ChenxuanZhao/wireless-fire-alarm-software-system
6800eda7c96e55fdca8fab5b3a0cb09f05df2416
[ "Apache-2.0" ]
null
null
null
djangoProject/webApp/models.py
ChenxuanZhao/wireless-fire-alarm-software-system
6800eda7c96e55fdca8fab5b3a0cb09f05df2416
[ "Apache-2.0" ]
null
null
null
from django.db import models # Create your models here. class UserSensorDataModel(models.Model): temperature = models.FloatField('温度') smokescope = models.FloatField('烟雾浓度') updateTime = models.DateTimeField(auto_now=True) class UserSensorConfigModel(models.Model): temperatureThreshold = models.FloatField('温度阈值') concentrationThreshold = models.FloatField('浓度阈值') updateTime = models.DateTimeField(auto_now=True)
27.75
54
0.763514
45
444
7.488889
0.577778
0.189911
0.172107
0.195846
0.237389
0.237389
0
0
0
0
0
0
0.135135
444
15
55
29.6
0.877604
0.054054
0
0.222222
0
0
0.033493
0
0
0
0
0
0
1
0
false
0
0.111111
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
bd1493316b096cde669da8a2865558abfc875a85
529
py
Python
python/turbodbc/__init__.py
fjetter/turbodbc
b11f0a1bc7d67bc3cbc60f564594f0e735f524f4
[ "MIT" ]
null
null
null
python/turbodbc/__init__.py
fjetter/turbodbc
b11f0a1bc7d67bc3cbc60f564594f0e735f524f4
[ "MIT" ]
null
null
null
python/turbodbc/__init__.py
fjetter/turbodbc
b11f0a1bc7d67bc3cbc60f564594f0e735f524f4
[ "MIT" ]
null
null
null
from __future__ import absolute_import from .api_constants import apilevel, threadsafety, paramstyle from .connect import connect from .constructors import Date, Time, Timestamp from .exceptions import Error, InterfaceError, DatabaseError, ParameterError from .data_types import STRING, BINARY, NUMBER, DATETIME, ROWID from .options import make_options from turbodbc_intern import Rows, Megabytes import pkg_resources try: __version__ = pkg_resources.get_distribution(__name__).version except: __version__ = 'unknown'
31.117647
76
0.824197
63
529
6.539683
0.650794
0.058252
0
0
0
0
0
0
0
0
0
0
0.122873
529
16
77
33.0625
0.887931
0
0
0
0
0
0.013233
0
0
0
0
0
0
1
0
false
0
0.692308
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
bd182270c3c3ae6edb0c81c95285d8c03af54b20
818
py
Python
features/steps/managers/__init__.py
CMoncur/launchkey-python
7bed012c183e5011fbeddd9353ed70fde899f932
[ "MIT" ]
null
null
null
features/steps/managers/__init__.py
CMoncur/launchkey-python
7bed012c183e5011fbeddd9353ed70fde899f932
[ "MIT" ]
null
null
null
features/steps/managers/__init__.py
CMoncur/launchkey-python
7bed012c183e5011fbeddd9353ed70fde899f932
[ "MIT" ]
null
null
null
from .directory import DirectoryManager from .directory_device import DirectoryDeviceManager from .directory_service import DirectoryServiceManager from .directory_service_auths import DirectoryServiceAuthsManager from .directory_service_policy import DirectoryServicePolicyManager from .directory_service_session import DirectoryServiceSessionManager from .directory_session import DirectorySessionManager from .keys import KeysManager from .organization_service import OrganizationServiceManager from .organization_service_policy import OrganizationServicePolicyManager from .entity_manager import EntityManager from .auth_policy import AuthPolicyManager from .sample_app_device_manager import SampleAppDeviceManager from .kobiton_manager import KobitonManager from .appium_device_manager import AppiumDeviceManager
51.125
73
0.908313
80
818
9.0375
0.4
0.125864
0.11065
0
0
0
0
0
0
0
0
0
0.07335
818
15
74
54.533333
0.953826
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
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
1
0
0
0
0
2
1f9ac24a6445f1f9906249b0ee25a4e22ee85681
541
py
Python
tests/core/interactions/test_visualization.py
Flipajs/FERDA
120a9e16d7ab4877f72fadbe4484c8b91adf22c4
[ "MIT" ]
1
2021-04-23T10:00:49.000Z
2021-04-23T10:00:49.000Z
tests/core/interactions/test_visualization.py
Flipajs/FERDA
120a9e16d7ab4877f72fadbe4484c8b91adf22c4
[ "MIT" ]
null
null
null
tests/core/interactions/test_visualization.py
Flipajs/FERDA
120a9e16d7ab4877f72fadbe4484c8b91adf22c4
[ "MIT" ]
null
null
null
import unittest import matplotlib.pylab as plt import pandas as pd from core.interactions.visualization import plot_interaction class InteractionResultsTestCase(unittest.TestCase): def test_plot_interaction(self): pred = pd.DataFrame([{'0_x': 10, '0_y': 20, '0_angle_deg_cw': 20, '0_minor': 3, '0_major': 8}]) gt = pd.DataFrame([{'0_x': 14, '0_y': 21, '0_angle_deg_cw': 25, '0_minor': 4, '0_major': 10}]) plot_interaction(1, pred, gt) plt.xlim(0, 30) plt.ylim(0, 30) # plt.show()
24.590909
103
0.645102
82
541
4.036585
0.536585
0.135952
0.072508
0.07855
0
0
0
0
0
0
0
0.079254
0.207024
541
21
104
25.761905
0.692308
0.018484
0
0
0
0
0.129771
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
1fa2ad746fe4a6df37bbc64362e80c1582008f88
1,622
py
Python
RoomsOnRent/room_service/models.py
DX9807/RoomsOnRent.com
4147efdce8e13930672c3c7cb12a1f25a70708ed
[ "MIT" ]
null
null
null
RoomsOnRent/room_service/models.py
DX9807/RoomsOnRent.com
4147efdce8e13930672c3c7cb12a1f25a70708ed
[ "MIT" ]
null
null
null
RoomsOnRent/room_service/models.py
DX9807/RoomsOnRent.com
4147efdce8e13930672c3c7cb12a1f25a70708ed
[ "MIT" ]
null
null
null
from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User from user_auth.choices import * def upload_room_images(instance,filename): return "Room/Images/{room}/{filename}/".format(room=instance.room,filename=filename) def upload_cover_image(instance,filename): return "Room/cover/{id}/{filename}/".format(id=instance.id,filename=filename) class Room(models.Model): ownner = models.ForeignKey(User, on_delete=models.CASCADE) state = models.CharField(choices = STATES_UNION_TERRITORIES,blank=False, max_length=256 ) city_area = models.CharField(blank=False, max_length=256) street_address = models.CharField(blank=False, max_length=300) mobile = models.BigIntegerField(blank=False) room_status = models.CharField(blank=False, max_length=10) religious_group = models.CharField(choices = RELIGIOUS_GROUP , max_length=15) monthly_rent = models.CharField(blank=False,max_length=10) desciption = models.TextField(blank=True,max_length=2048) added_date = models.DateTimeField(auto_now=True) cover_image = models.ImageField(upload_to =upload_cover_image, blank=False ) def __str__(self): return "Room-{id}".format(id=str(self.id)) class RoomImages(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE ,related_name='room_images') room_image = models.ImageField(upload_to=upload_room_images,null=False, blank=False) def get_absolute_url(self): return reverse("room_service:room_list") def __str__(self): return str(self.room)
39.560976
93
0.759556
220
1,622
5.390909
0.35
0.067454
0.054806
0.080101
0.198145
0.177066
0.060708
0
0
0
0
0.013437
0.128237
1,622
40
94
40.55
0.825318
0
0
0.066667
0
0
0.061036
0.048705
0
0
0
0
0
1
0.166667
false
0
0.166667
0.166667
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
0
1
1
0
0
2
1faeba59741c1ec9aa4cdc356648407bd8672739
737
py
Python
mastermind_py/mastermind/models.py
Rydra/mastermind-api
f315eedc4e2e1397f319e3d9ab90d580ba1626b4
[ "MIT" ]
null
null
null
mastermind_py/mastermind/models.py
Rydra/mastermind-api
f315eedc4e2e1397f319e3d9ab90d580ba1626b4
[ "MIT" ]
3
2022-01-02T14:49:35.000Z
2022-01-02T14:49:35.000Z
mastermind_py/mastermind/models.py
Rydra/mastermind-api
f315eedc4e2e1397f319e3d9ab90d580ba1626b4
[ "MIT" ]
null
null
null
from django.db import models from django.contrib.postgres.fields import ArrayField class GuessModel(models.Model): code = ArrayField(models.CharField(max_length=10)) black_pegs = models.IntegerField(null=False) white_pegs = models.IntegerField(null=False) game = models.ForeignKey( "GameModel", on_delete=models.CASCADE, related_name="guesses" ) class GameModel(models.Model): num_colors = models.IntegerField(null=False) reference = models.CharField(null=False, unique=True, max_length=10) num_slots = models.IntegerField(null=False) secret_code = ArrayField(models.CharField(max_length=10)) max_guesses = models.IntegerField(null=False) status = models.CharField(max_length=10)
33.5
72
0.751696
92
737
5.891304
0.434783
0.099631
0.202952
0.249077
0.309963
0.147601
0.147601
0
0
0
0
0.012658
0.142469
737
21
73
35.095238
0.844937
0
0
0
0
0
0.02171
0
0
0
0
0
0
1
0
false
0
0.125
0
0.875
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
1fd48aad6ea28bd842fc0e0e885e0f0e0c49ec5f
287
py
Python
rllib/agents/trainer_template.py
andenrx/ray
0ad4113e22aa4ec40f87d4a16e474a452f9c8af7
[ "Apache-2.0" ]
null
null
null
rllib/agents/trainer_template.py
andenrx/ray
0ad4113e22aa4ec40f87d4a16e474a452f9c8af7
[ "Apache-2.0" ]
2
2022-03-31T11:58:47.000Z
2022-03-31T11:58:49.000Z
rllib/agents/trainer_template.py
AyushExel/ray
46465abd6d866c3903b17c601e84e81b46c67190
[ "Apache-2.0" ]
null
null
null
from ray.rllib.utils.deprecation import Deprecated @Deprecated( new="Sub-class from Trainer (or another Trainer sub-class) directly! " "See e.g. ray.rllib.agents.dqn.dqn.py for an example.", error=True, ) def build_trainer(*args, **kwargs): pass # deprecated w/ error
26.090909
74
0.703833
42
287
4.785714
0.738095
0.079602
0
0
0
0
0
0
0
0
0
0
0.170732
287
10
75
28.7
0.844538
0.066202
0
0
0
0
0.43609
0.101504
0
0
0
0
0
1
0.125
true
0.125
0.125
0
0.25
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
1
0
0
0
0
0
2
1feb28924b6ef90bf1b1ffa3bccfbeab0f304d97
1,199
py
Python
cart/models.py
Slohn/myshop
4e5034dc3b1561773060319f16628d44910c4a20
[ "MIT" ]
20
2021-05-07T19:32:56.000Z
2022-02-06T12:12:56.000Z
cart/models.py
Slohn/myshop
4e5034dc3b1561773060319f16628d44910c4a20
[ "MIT" ]
9
2021-04-08T18:29:18.000Z
2022-03-11T23:28:23.000Z
cart/models.py
Slohn/myshop
4e5034dc3b1561773060319f16628d44910c4a20
[ "MIT" ]
10
2021-02-22T13:50:24.000Z
2022-03-15T11:51:27.000Z
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from shop.models import Product from accounts.models import User class Cart(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) is_in_order = models.BooleanField(default=False) class Meta: ordering = ('-created',) def __str__(self): return 'cart {}'.format(self.user.email) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class CartItem(models.Model): cart = models.ForeignKey(Cart, related_name='items', null=True, on_delete=models.CASCADE, ) product = models.ForeignKey(Product, related_name='cart_items', on_delete=models.CASCADE, ) price = models.DecimalField(max_digits=10, decimal_places=2, default=0) quantity = models.PositiveIntegerField(default=1) def __str__(self): return '{}'.format(self.product.name) def get_cost(self): return self.price * self.quantity
27.883721
75
0.69975
153
1,199
5.287582
0.45098
0.049444
0.051916
0.077874
0
0
0
0
0
0
0
0.006135
0.18432
1,199
42
76
28.547619
0.821063
0.017515
0
0.129032
0
0
0.027211
0
0
0
0
0
0
1
0.129032
false
0
0.129032
0.129032
0.774194
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
1ff72bb7db82b9288581b3f78667cda61db7ba9f
2,365
py
Python
dissonance/client/client.py
jhgg/dissonance
48059e6d7f80472611f202fa7349bf7f92f5ad48
[ "Unlicense", "MIT" ]
5
2016-03-07T19:37:00.000Z
2021-04-28T21:35:01.000Z
dissonance/client/client.py
jhgg/dissonance
48059e6d7f80472611f202fa7349bf7f92f5ad48
[ "Unlicense", "MIT" ]
null
null
null
dissonance/client/client.py
jhgg/dissonance
48059e6d7f80472611f202fa7349bf7f92f5ad48
[ "Unlicense", "MIT" ]
1
2019-01-28T17:09:28.000Z
2019-01-28T17:09:28.000Z
from .api_client import APIClient from .gateway_socket import GatewaySocket from ..lib.event_emitter import EventEmitter from ..stores import Stores, autodiscover autodiscover() class Client(object): def __init__(self): self._gateway_socket = None self.config = {} self.events = EventEmitter() self.api_client = APIClient(self) self.stores = Stores(self) self.stores.dispatcher.link_events(self.events) self.me = None self.scheduled_greenlets = set() def login(self, email, password): self.api_client.login(email, password) return self def start(self): gateway = self.api_client.discover_gateway() self._gateway_socket = GatewaySocket(gateway, self) self._gateway_socket.start() return self def stop(self): if self._gateway_socket: self._gateway_socket.kill() self._gateway_socket = None for greenlet in self.scheduled_greenlets: greenlet.kill() self.scheduled_greenlets.clear() def join(self): if self._gateway_socket: self._gateway_socket.join() def handle_packet(self, packet): event = packet['t'] data = packet['d'] import json print(json.dumps(data, sort_keys=True, indent=2)) self.stores.dispatch(event, data) handler_name = 'handle_%s' % event.lower() handler_fn = getattr(self, handler_name, None) if handler_fn: handler_fn(data) def handle_ready(self, data): print('ready', data.keys()) self.me = self.stores.users.with_id(data['user']['id']) self.emit('ready', ready_data=data) def handle_message_create(self, message): message = self.stores.messages.with_id(message['id']) self.emit('message-create', message=message) def emit(self, event, **kwargs): self.events.emit(event, client=self, **kwargs) def call_later(self, callback, *args, **kwargs): pass def cancel_call_later(self, greenlet): self.scheduled_greenlets.discard(greenlet) greenlet.kill() def send_message(self, channel, message): """ Convenience function to send a message to a channel. """ return self.api_client.create_message(channel.id, message)
29.197531
66
0.634672
280
2,365
5.175
0.303571
0.080745
0.093858
0.028986
0.05521
0.05521
0.05521
0.05521
0
0
0
0.000569
0.257082
2,365
80
67
29.5625
0.824132
0.021987
0
0.135593
0
0
0.018818
0
0
0
0
0
0
1
0.20339
false
0.050847
0.084746
0
0.355932
0.033898
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
1ff93f04da4655e95fde0815583a8d109a760970
863
py
Python
backend/api/fixtures/operational/0030_update_signing_authority_assertions.py
kuanfan99/zeva
57b506a108fe57438506569d5503c90c52216b2f
[ "Apache-2.0" ]
3
2020-03-25T03:06:20.000Z
2021-01-20T23:36:03.000Z
backend/api/fixtures/operational/0030_update_signing_authority_assertions.py
kuanfan99/zeva
57b506a108fe57438506569d5503c90c52216b2f
[ "Apache-2.0" ]
740
2019-12-16T15:53:39.000Z
2022-03-26T08:25:10.000Z
backend/api/fixtures/operational/0030_update_signing_authority_assertions.py
kuanfan99/zeva
57b506a108fe57438506569d5503c90c52216b2f
[ "Apache-2.0" ]
11
2019-11-28T20:39:15.000Z
2022-01-31T17:53:31.000Z
from django.db import transaction from api.management.data_script import OperationalDataScript from api.models.signing_authority_assertion import SigningAuthorityAssertion class UpdateSigningAuthorityAssertions(OperationalDataScript): """ Update the assertions for the compliance report """ is_revertable = False comment = 'Update the assertions for the compliance report' def check_run_preconditions(self): return True def update_assertions(self): text = "I confirm this consumer ZEV sales information is complete and correct." assertion = SigningAuthorityAssertion.objects.get( module="consumer_sales") assertion.description = text assertion.save() @transaction.atomic def run(self): self.update_assertions() script_class = UpdateSigningAuthorityAssertions
28.766667
87
0.741599
87
863
7.241379
0.586207
0.022222
0.060317
0.069841
0.130159
0.130159
0.130159
0
0
0
0
0
0.200464
863
29
88
29.758621
0.913043
0.054461
0
0
0
0
0.16375
0
0
0
0
0
0.5
1
0.166667
false
0
0.166667
0.055556
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
1
0
0
0
0
0
0
1
0
0
2
951411a30f4c017b1fbfea8fbb4ca963972f6012
513
py
Python
12/00/RegexFlag.IGNORECASE.py
pylangstudy/201708
126b1af96a1d1f57522d5a1d435b58597bea2e57
[ "CC0-1.0" ]
null
null
null
12/00/RegexFlag.IGNORECASE.py
pylangstudy/201708
126b1af96a1d1f57522d5a1d435b58597bea2e57
[ "CC0-1.0" ]
39
2017-07-31T22:54:01.000Z
2017-08-31T00:19:03.000Z
12/00/RegexFlag.IGNORECASE.py
pylangstudy/201708
126b1af96a1d1f57522d5a1d435b58597bea2e57
[ "CC0-1.0" ]
null
null
null
#!python3.6 import re #英大文字・小文字を区別せずにマッチングを行います。 print(re.IGNORECASE) pattern = r'^ab' #pattern = r'あいう' #pattern = r'あいう$' #pattern = '.*あいう$' #pattern = None #pattern = r'' #patternA = re.compile(pattern) #patternA = re.compile(pattern, re.A) patternA = re.compile(pattern, re.IGNORECASE) for target in ['a', 'ab', 'abc', 'ABC', 'aB012', 'Ab 01', 'あいう', 'ABあいう']: print(patternA.match(target)) print(re.match(r'^ab', 'aBcdefg', re.IGNORECASE)) print(re.match(r'^ab', 'Abcdefg', re.IGNORECASE | re.DEBUG))
25.65
74
0.662768
75
513
4.546667
0.36
0.140762
0.14956
0.211144
0.351906
0.199413
0.199413
0.199413
0
0
0
0.015487
0.118908
513
19
75
27
0.736726
0.348928
0
0
0
0
0.153846
0
0
0
0
0
0
1
0
false
0
0.125
0
0.125
0.5
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
0
1
0
2
951ac612b9c50b3102e8edce16375f8bde40c2c0
1,620
py
Python
cms/templates/Admin/users-add.py
angeal185/python-flask-material-design-cms
32c6251792bca75aebe231ab08b6de7ea1936998
[ "MIT" ]
null
null
null
cms/templates/Admin/users-add.py
angeal185/python-flask-material-design-cms
32c6251792bca75aebe231ab08b6de7ea1936998
[ "MIT" ]
null
null
null
cms/templates/Admin/users-add.py
angeal185/python-flask-material-design-cms
32c6251792bca75aebe231ab08b6de7ea1936998
[ "MIT" ]
null
null
null
{% extends "Admin/base.py" %} {% block pagewrapper %} <!-- Page Content --> <div id="page-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-12"> <h1 class="page-header">Add New User</h1> <form method="post" action=""> <div class="row"> <div class="form-group col-md-4"> <label for="username">Username</label> <input type="text" class="form-control" id="username" name="username"> </div> </div> <div class="row"> <div class="form-group col-md-4"> <label for="password1">Password</label> <input type="password" class="form-control" id="password1" name="password1"> </div> </div> <div class="row"> <div class="form-group col-md-4"> <label for="password2">Confirm Password</label> <input type="password" class="form-control" id="password2" name="password2"> </div> </div> <div class="row"> <div class="form-group col-md-4"> <label for="email">Email</label> <input type="text" class="form-control" id="email" name="email"> </div> </div> <div class="row"> <div class="form-group col-md-4"> <button type="submit" class="btn btn-success">Add User</button> </div> </div> </form> </div> <!-- /.col-lg-12 --> </div> <!-- /.row --> </div> <!-- /.container-fluid --> </div> <!-- /#page-wrapper --> {% endblock %}
28.421053
88
0.489506
181
1,620
4.381215
0.265193
0.131148
0.083228
0.105927
0.520807
0.496847
0.496847
0.496847
0.406053
0.284994
0
0.015302
0.314198
1,620
56
89
28.928571
0.69847
0.009877
0
0.520833
0
0
0.22645
0
0
0
0
0
0
0
null
null
0.083333
0
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
0
0
1
0
0
1
0
0
0
0
0
2
95293e9566453d3a7cd9db18f27c4d7bf830c3a5
63
py
Python
tests/roots/test-build-htmlhelp/conf.py
smart1004/sphinx_doc
e2bda50167b86963642b77c11b9465aaf4d8d0dd
[ "BSD-2-Clause" ]
null
null
null
tests/roots/test-build-htmlhelp/conf.py
smart1004/sphinx_doc
e2bda50167b86963642b77c11b9465aaf4d8d0dd
[ "BSD-2-Clause" ]
null
null
null
tests/roots/test-build-htmlhelp/conf.py
smart1004/sphinx_doc
e2bda50167b86963642b77c11b9465aaf4d8d0dd
[ "BSD-2-Clause" ]
null
null
null
# -*- coding: utf-8 -*- project = 'test' master_doc = 'index'
12.6
23
0.571429
8
63
4.375
1
0
0
0
0
0
0
0
0
0
0
0.019608
0.190476
63
4
24
15.75
0.666667
0.333333
0
0
0
0
0.225
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
20fdd3303f9578c018561374987dce934ddd6b47
1,359
py
Python
Part_3_advanced/m17_tests_II/tdd/example_1/eshop/tests/test_order.py
Mikma03/InfoShareacademy_Python_Courses
3df1008c8c92831bebf1625f960f25b39d6987e6
[ "MIT" ]
null
null
null
Part_3_advanced/m17_tests_II/tdd/example_1/eshop/tests/test_order.py
Mikma03/InfoShareacademy_Python_Courses
3df1008c8c92831bebf1625f960f25b39d6987e6
[ "MIT" ]
null
null
null
Part_3_advanced/m17_tests_II/tdd/example_1/eshop/tests/test_order.py
Mikma03/InfoShareacademy_Python_Courses
3df1008c8c92831bebf1625f960f25b39d6987e6
[ "MIT" ]
null
null
null
import pytest from eshop.order import Order @pytest.fixture def jan_order() -> Order: return Order(client_first_name="Jan", client_last_name="Nowak") @pytest.fixture def other_jan_order() -> Order: return Order(client_first_name="Jan", client_last_name="Nowak") def test_add_element(jan_order): jan_order.add_element("Rower", quantity=1, price=3_500) assert len(jan_order.elements) == 1 assert jan_order.elements[0].product == "Rower" assert jan_order.elements[0].quantity == 1 assert jan_order.elements[0].price == 3_500 def test_empty_order_equality(jan_order, other_jan_order): ula_order = Order(client_first_name="Ula", client_last_name="Nowak") jan_kowalski_order = Order(client_first_name="Jan", client_last_name="Kowalski") assert jan_order == other_jan_order assert jan_order != 0 assert jan_order != ula_order assert jan_order != jan_kowalski_order def test_order_with_different_number_of_elements_not_equals(jan_order, other_jan_order): jan_order.add_element("Rower", quantity=1, price=3_500) assert jan_order != other_jan_order def test_orders_with_different_elements_not_equals(jan_order, other_jan_order): jan_order.add_element("Rower", quantity=1, price=3_500) other_jan_order.add_element("Opona", quantity=2, price=50) assert jan_order != other_jan_order
29.543478
88
0.762325
208
1,359
4.581731
0.206731
0.218258
0.132214
0.100735
0.603358
0.525708
0.396642
0.396642
0.357817
0.357817
0
0.023789
0.133922
1,359
45
89
30.2
0.785896
0
0
0.321429
0
0
0.04415
0
0
0
0
0
0.357143
1
0.214286
false
0
0.071429
0.071429
0.357143
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
20ff58f621c4a5c589ff4f078d0eef03a0f9d3d9
5,475
py
Python
simple_http_server_redis_session/http_session_redis_impl.py
keijack/python-simple-http-server-redis-session
84c16037370e621d093452ea2e4898dcc357871e
[ "MIT" ]
2
2021-05-13T11:16:07.000Z
2021-05-27T22:40:33.000Z
simple_http_server_redis_session/http_session_redis_impl.py
keijack/python-simple-http-server-redis-session
84c16037370e621d093452ea2e4898dcc357871e
[ "MIT" ]
null
null
null
simple_http_server_redis_session/http_session_redis_impl.py
keijack/python-simple-http-server-redis-session
84c16037370e621d093452ea2e4898dcc357871e
[ "MIT" ]
1
2021-08-08T05:21:47.000Z
2021-08-08T05:21:47.000Z
# -*- coding: utf-8 -*- """ Copyright (c) 2021 Keijack Wu 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 uuid import time import redis import pickle from typing import Any, List, Tuple, Union from simple_http_server import Session, SessionFactory, DEFAULT_ENCODING from simple_http_server.logger import get_logger _logger = get_logger("redis_http_session") class ObjectSerializer: def object_to_bytes(self, obj: Any) -> bytes: return pickle.dumps(obj) def bytes_to_objects(self, value: bytes) -> Any: return pickle.loads(value) def _get_redis_client(host="localhost", port=6379, db=0, username="", password="") -> redis.Redis: return redis.Redis(host=host, port=port, db=db, username=username, password=password) def _get_session_hash_name(session_id: str) -> str: return f"__py_si_ht_se_{session_id}".encode(DEFAULT_ENCODING) def _to_byte(val: Union[bytes, str]) -> bytes: if isinstance(val, bytes): return val elif isinstance(val, str): return val.encode(DEFAULT_ENCODING) else: return f"{val}".encode(DEFAULT_ENCODING) class RedisSessionImpl(Session): _KEY_PRE: str = "val_" def __init__(self, id: str, obj_serializer: ObjectSerializer, redis: redis.Redis): super().__init__() self.__id = id if id else uuid.uuid4().hex self.__redis_hash_name = _get_session_hash_name(self.__id) self.__obj_ser: ObjectSerializer = obj_serializer self.__clz_creation_time = time.time() self.__is_new = False self.__redis = redis self.__sync_redis() self.__set_expire() def __sync_redis(self) -> bool: if not self.__redis.exists(self.__redis_hash_name): self.__set_("creation_time", self.__clz_creation_time) self.__is_new = True self.__set_("last_accessed_time", self.__clz_creation_time) def __set_(self, key: str, val: Any): self.__redis.hset(self.__redis_hash_name, _to_byte(key), _to_byte(val)) def __get_(self, key: str) -> bytes: return self.__redis.hget(self.__redis_hash_name, _to_byte(key)) def __exists(self, key: str) -> bool: return self.__redis.hexists(self.__redis_hash_name, _to_byte(key)) def __set_expire(self): self.__redis.expire(self.__redis_hash_name, self.max_inactive_interval) @property def id(self) -> str: return self.__id @property def creation_time(self) -> float: try: return float(self.__get_("creation_time")) except: return self.__clz_creation_time @property def last_accessed_time(self) -> float: try: return float(self.__get_("last_accessed_time")) except: return self.__clz_creation_time @property def is_new(self) -> bool: return self.__is_new @property def is_valid(self) -> bool: return self.__redis.exists(self.__redis_hash_name) @property def attribute_names(self) -> Tuple: keys: List[bytes] = self.__redis.hkeys(self.__redis_hash_name) return tuple([k.decode(DEFAULT_ENCODING)[len(self._KEY_PRE):] for k in keys if k.decode(DEFAULT_ENCODING).startswith(self._KEY_PRE)]) def get_attribute(self, name: str) -> Any: val_key = f"{self._KEY_PRE}{name}" if not self.__exists(val_key): return None val = self.__get_(val_key) _logger.debug(f"Get attribute {name} -> bytes -> {val}") return self.__obj_ser.bytes_to_objects(val) def set_attribute(self, name: str, value: Any) -> None: self.__set_(f"{self._KEY_PRE}{name}", self.__obj_ser.object_to_bytes(value)) def invalidate(self) -> None: self.__redis.delete(self.__redis_hash_name) class RedisSessionFactory(SessionFactory): def __init__(self, host="localhost", port=6379, db=0, username="", password="", redis_client: redis.Redis = None, object_serializer: ObjectSerializer = None): self.__obj_ser = object_serializer or ObjectSerializer() self.__redis = redis_client or _get_redis_client(host=host, port=port, db=db, username=username, password=password) def get_session(self, session_id: str, create: bool = False) -> Session: hash_name = _get_session_hash_name(session_id) if not self.__redis.exists(hash_name) and not create: return None else: return RedisSessionImpl(session_id, self.__obj_ser, self.__redis)
34.433962
162
0.701187
757
5,475
4.722589
0.26288
0.052867
0.032727
0.042797
0.204755
0.16951
0.147692
0.122517
0.087273
0.036364
0
0.003663
0.202192
5,475
158
163
34.651899
0.814789
0.19653
0
0.168421
0
0
0.048508
0.015486
0
0
0
0
0
1
0.231579
false
0.042105
0.073684
0.094737
0.568421
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
1f2f331d6e11c2d9c7f1630e9c7225fce0913c78
1,966
py
Python
tests/app/models/custom.py
dldevinc/paper-uploads
9414b6e6fbaa52eadacd9852ce3c4d84c6c2c939
[ "BSD-3-Clause" ]
3
2020-06-05T10:43:05.000Z
2022-02-22T16:46:16.000Z
tests/app/models/custom.py
dldevinc/paper-uploads
9414b6e6fbaa52eadacd9852ce3c4d84c6c2c939
[ "BSD-3-Clause" ]
2
2021-04-03T12:25:20.000Z
2022-02-02T06:10:46.000Z
tests/app/models/custom.py
dldevinc/paper-uploads
9414b6e6fbaa52eadacd9852ce3c4d84c6c2c939
[ "BSD-3-Clause" ]
null
null
null
from django.db import models from django.utils.translation import gettext_lazy as _ from paper_uploads.models import * from paper_uploads.cloudinary.models import * __all__ = [ "CustomUploadedFile", "CustomUploadedImage", "CustomCloudinaryFile", "CustomProxyGallery", "CustomGallery", "CustomCloudinaryGallery", ] # =========== Proxy models ================== class CustomUploadedFile(UploadedFile): class Meta: proxy = True def get_file_folder(self) -> str: return "custom-files/%Y" class CustomUploadedImage(UploadedImage): class Meta: proxy = True def get_file_folder(self) -> str: return "custom-images/%Y" class CustomProxyImageItem(ImageItem): class Meta: proxy = True def get_file_folder(self) -> str: return "collections/custom-images/%Y" class CustomCloudinaryFile(CloudinaryFile): class Meta: proxy = True def get_file_folder(self) -> str: return "custom-files/%Y" # =========== Concrete models ================== class CustomImageItem(ImageItemBase): caption = models.TextField(_("caption"), blank=True) def get_file_folder(self) -> str: return "collections/custom-images/%Y" class CustomCloudinaryImageItem(CloudinaryImageItemBase): caption = models.TextField(_("caption"), blank=True) def get_file_folder(self) -> str: return "collections/custom-images/%Y" class CustomProxyGallery(ImageCollection): VARIATIONS = dict( desktop=dict( size=(1200, 0), clip=False, ) ) image = CollectionItem(CustomProxyImageItem) class CustomGallery(ImageCollection): VARIATIONS = dict( desktop=dict( size=(1200, 0), clip=False, ) ) image = CollectionItem(CustomImageItem) class CustomCloudinaryGallery(CloudinaryImageCollection): image = CollectionItem(CustomCloudinaryImageItem)
21.139785
57
0.653611
180
1,966
7.016667
0.338889
0.033254
0.047506
0.066508
0.469517
0.469517
0.469517
0.469517
0.469517
0.469517
0
0.006549
0.223296
1,966
92
58
21.369565
0.820563
0.045778
0
0.5
0
0
0.136145
0.057128
0
0
0
0
0
1
0.103448
false
0
0.068966
0.103448
0.62069
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
1f5a4311730ae0538ecb7cb9beec9655c54f5e32
52
py
Python
hello.py
jinheebee/github_test
33b67f7f165876b5eec2e5e72f50e0948c4f1ba6
[ "MIT" ]
null
null
null
hello.py
jinheebee/github_test
33b67f7f165876b5eec2e5e72f50e0948c4f1ba6
[ "MIT" ]
null
null
null
hello.py
jinheebee/github_test
33b67f7f165876b5eec2e5e72f50e0948c4f1ba6
[ "MIT" ]
null
null
null
print("hello world") a = 3 b = 4 c = a * b print(c)
8.666667
20
0.538462
12
52
2.333333
0.666667
0
0
0
0
0
0
0
0
0
0
0.052632
0.269231
52
5
21
10.4
0.684211
0
0
0
0
0
0.211538
0
0
0
0
0
0
1
0
false
0
0
0
0
0.4
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
1f609c4332b3128b9feba25f3402b1cdf4710ac8
623
py
Python
templogboss/myapp/models.py
Bossabossy/Templog
1d653f9a1c23d189940950bce808a3e26d618e15
[ "BSD-2-Clause" ]
null
null
null
templogboss/myapp/models.py
Bossabossy/Templog
1d653f9a1c23d189940950bce808a3e26d618e15
[ "BSD-2-Clause" ]
null
null
null
templogboss/myapp/models.py
Bossabossy/Templog
1d653f9a1c23d189940950bce808a3e26d618e15
[ "BSD-2-Clause" ]
null
null
null
from __future__ import unicode_literals from django.db import models class Node(models.Model): node_name=models.CharField(max_length=100) description=models.CharField(max_length=100) def __str__(self): return "{}:{}:{}".format(self.id, self.node_name, self.description) class Record(models.Model): created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) node=models.ForeignKey(Node, on_delete=models.CASCADE) value=models.FloatField(default=0.0) class Attribute(models.Model): attribute=models.CharField(max_length=100) description=models.CharField(max_length=100)
23.074074
69
0.794543
86
623
5.534884
0.465116
0.12605
0.151261
0.201681
0.273109
0.273109
0.273109
0.273109
0.273109
0.273109
0
0.024476
0.081862
623
26
70
23.961538
0.807692
0
0
0.133333
0
0
0.012966
0
0
0
0
0
0
1
0.066667
false
0
0.133333
0.066667
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
1f7db3de9fb8ed4c7539d6b2e746e9aad8f5f517
2,303
py
Python
src/compute_rnaQuast.py
Kingsford-Group/lrassemblyanalysis
e4fceca0808b39194ccd5935e0ba16ca68b96f3c
[ "BSD-3-Clause" ]
4
2019-04-16T15:20:10.000Z
2022-02-18T07:21:45.000Z
src/compute_rnaQuast.py
Kingsford-Group/lrassemblyanalysis
e4fceca0808b39194ccd5935e0ba16ca68b96f3c
[ "BSD-3-Clause" ]
null
null
null
src/compute_rnaQuast.py
Kingsford-Group/lrassemblyanalysis
e4fceca0808b39194ccd5935e0ba16ca68b96f3c
[ "BSD-3-Clause" ]
2
2019-11-03T06:40:28.000Z
2021-11-12T19:55:34.000Z
# compute_rnaQuast.py # # Laura Tung # # Usage: compute_rnaQuast.py <result_dir> # # <result_dir> is the directory containing rnaQUAST_output and rnaQUAST_output_1 import sys import numpy as np def load_data(dataset): loaded_isoform = np.loadtxt(dataset+"/isoform_data", dtype='int', usecols=(2, 3, 4)) loaded_matched = np.loadtxt(dataset+"/matched_data", dtype='int', usecols=(1, 2, 3)) return loaded_isoform, loaded_matched if __name__ == "__main__": # load rnaQUAST_output (75% and 95%) loaded_isoform, loaded_matched = load_data(sys.argv[1]+"/rnaQUAST_output") # load rnaQUAST_output_1 (0% and 50%) loaded_isoform_1, loaded_matched_1 = load_data(sys.argv[1]+"/rnaQUAST_output_1") print("\t\t\t\tScallop\t\tStringTie\tIsoseq") # assembled isoforms print("0-50%-assembled-isoforms\t"+str(loaded_isoform_1[0][0]-loaded_isoform_1[1][0])+"\t\t"+str(loaded_isoform_1[0][1]-loaded_isoform_1[1][1])+"\t\t"+str(loaded_isoform_1[0][2]-loaded_isoform_1[1][2])) print("50-75%-assembled-isoforms\t"+str(loaded_isoform_1[1][0]-loaded_isoform[0][0])+"\t\t"+str(loaded_isoform_1[1][1]-loaded_isoform[0][1])+"\t\t"+str(loaded_isoform_1[1][2]-loaded_isoform[0][2])) print("75-95%-assembled-isoforms\t"+str(loaded_isoform[0][0]-loaded_isoform[1][0])+"\t\t"+str(loaded_isoform[0][1]-loaded_isoform[1][1])+"\t\t"+str(loaded_isoform[0][2]-loaded_isoform[1][2])) print("95-100%-assembled-isoforms\t"+str(loaded_isoform[1][0])+"\t\t"+str(loaded_isoform[1][1])+"\t\t"+str(loaded_isoform[1][2])) # matched print("0-50%-matched-transcripts\t"+str(loaded_matched_1[0][0]-loaded_matched_1[1][0])+"\t\t"+str(loaded_matched_1[0][1]-loaded_matched_1[1][1])+"\t\t"+str(loaded_matched_1[0][2]-loaded_matched_1[1][2])) print("50-75%-matched-transcripts\t"+str(loaded_matched_1[1][0]-loaded_matched[0][0])+"\t\t"+str(loaded_matched_1[1][1]-loaded_matched[0][1])+"\t\t"+str(loaded_matched_1[1][2]-loaded_matched[0][2])) print("75-95%-matched-transcripts\t"+str(loaded_matched[0][0]-loaded_matched[1][0])+"\t\t"+str(loaded_matched[0][1]-loaded_matched[1][1])+"\t\t"+str(loaded_matched[0][2]-loaded_matched[1][2])) print("95-100%-matched-transcripts\t"+str(loaded_matched[1][0])+"\t\t"+str(loaded_matched[1][1])+"\t\t"+str(loaded_matched[1][2]))
52.340909
207
0.700391
406
2,303
3.736453
0.130542
0.214239
0.158207
0.116018
0.617007
0.52472
0.437047
0.317732
0.156889
0
0
0.072402
0.076422
2,303
43
208
53.55814
0.640809
0.107686
0
0
0
0
0.192948
0.125367
0
0
0
0
0
1
0.055556
false
0
0.111111
0
0.222222
0.5
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
0
1
0
2
1f7efbe17a367c1c70b6129232790bd8f912a272
956
py
Python
asm_analyser/parser.py
NielsMittelstaedt/ASM-Analyser
472e3441be6f6879468ea1e4f9829db6916a14b9
[ "MIT" ]
1
2022-02-13T11:40:04.000Z
2022-02-13T11:40:04.000Z
asm_analyser/parser.py
NielsMittelstaedt/ASM-Analyser
472e3441be6f6879468ea1e4f9829db6916a14b9
[ "MIT" ]
null
null
null
asm_analyser/parser.py
NielsMittelstaedt/ASM-Analyser
472e3441be6f6879468ea1e4f9829db6916a14b9
[ "MIT" ]
null
null
null
'''Provides the basis for a Parser. ''' from abc import ABC, abstractmethod from typing import List from asm_analyser.blocks.code_block import CodeBlock class Parser(ABC): '''Converts the input into a suitable format. Parser class, responsible for reading the assembler input file. Transforms the lines into code blocks. ''' def __init__(self, filepath: str) -> None: super().__init__() self.filepath = filepath @abstractmethod def create_blocks(self) -> List[CodeBlock]: '''Splits the instructions into a list of code blocks. Returns ------- list[CodeBlock] List of code blocks with a name and a set of instructions for each block. ''' @abstractmethod def _parse_file(self) -> None: '''Splits the input lines and throws away unnecessary lines. Every line is numbered to identify it later for counting. '''
25.837838
69
0.646444
118
956
5.127119
0.508475
0.049587
0.052893
0.052893
0
0
0
0
0
0
0
0
0.274059
956
36
70
26.555556
0.871758
0.48431
0
0.181818
0
0
0
0
0
0
0
0
0
1
0.272727
false
0
0.272727
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
1
0
0
0
0
1
0
0
2
1f7f6464af36949c37a8738e4e1a5beb45cc20cf
326
py
Python
conclave/scenario_result.py
DasAng/paraworld
fe202fadfaac6884370a8f27e29e113b13565e63
[ "MIT" ]
null
null
null
conclave/scenario_result.py
DasAng/paraworld
fe202fadfaac6884370a8f27e29e113b13565e63
[ "MIT" ]
null
null
null
conclave/scenario_result.py
DasAng/paraworld
fe202fadfaac6884370a8f27e29e113b13565e63
[ "MIT" ]
null
null
null
from typing import Any from dataclasses import dataclass @dataclass class ScenarioResult: scenario: Any = None steps: Any = None id: str = None message: str = None elapsed: float = 0.0 exception: str = None threadId: int = None pid: int = None startTime: Any = None endTime: Any = None
21.733333
33
0.650307
42
326
5.047619
0.547619
0.132075
0
0
0
0
0
0
0
0
0
0.008511
0.279141
326
15
34
21.733333
0.893617
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.142857
0
0.928571
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
1f82bfbae202bfa67d4922d1b86be4807f0e978c
636
py
Python
Pk/count_files.py
leanderthiele/Quijote-simulations
6a8ed8f557a28aab1fe9b5f58293a5359c60a558
[ "MIT" ]
64
2019-06-01T17:28:40.000Z
2022-03-29T18:32:21.000Z
Pk/count_files.py
leanderthiele/Quijote-simulations
6a8ed8f557a28aab1fe9b5f58293a5359c60a558
[ "MIT" ]
null
null
null
Pk/count_files.py
leanderthiele/Quijote-simulations
6a8ed8f557a28aab1fe9b5f58293a5359c60a558
[ "MIT" ]
253
2019-09-03T19:00:29.000Z
2021-11-26T12:40:49.000Z
import numpy as np import sys,os,glob ######################################### INPUT ######################################## root = '/simons/scratch/fvillaescusa/pdf_information/Pk' folders = ['Om_p', 'Ob_p', 'Ob2_p', 'h_p', 'ns_p', 's8_p', 'Om_m', 'Ob_m', 'Ob2_m', 'h_m', 'ns_m', 's8_m', 'Mnu_p', 'Mnu_pp', 'Mnu_ppp', 'fiducial'] ######################################################################################## # do a loop over the different folders for cosmo in folders: files = glob.glob('%s/matter/%s/*/Pk_*z=127.txt'%(root,cosmo)) print 'Found %d files for %s at z=127'%(len(files),cosmo)
42.4
88
0.45283
83
636
3.26506
0.578313
0.02952
0
0
0
0
0
0
0
0
0
0.018182
0.13522
636
14
89
45.428571
0.474545
0.06761
0
0
0
0
0.424171
0.177725
0
0
0
0
0
0
null
null
0
0.222222
null
null
0.111111
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
2
1f900394a31fb55260b38ef3640faae9d924d713
5,599
py
Python
App.py
morantobias/tobys-app
a98ea27ec32887a666cf9e6387639b499e1f05eb
[ "Apache-2.0" ]
null
null
null
App.py
morantobias/tobys-app
a98ea27ec32887a666cf9e6387639b499e1f05eb
[ "Apache-2.0" ]
null
null
null
App.py
morantobias/tobys-app
a98ea27ec32887a666cf9e6387639b499e1f05eb
[ "Apache-2.0" ]
null
null
null
#app is latest working import dash from dash.dependencies import Input, Output, State import dash_core_components as dcc import dash_html_components as html from pandas_datareader import data as web from datetime import datetime as dt import plotly.graph_objs as go #latest working import dash from dash.dependencies import Input, Output, State, Event import dash_core_components as dcc import dash_html_components as html from pandas_datareader import data as web from datetime import datetime as dt import plotly.graph_objs as go import numpy as np app = dash.Dash(_name_) server = app.server app.scripts.config.serve_locally = True app.config['suppress_callback_exceptions']=True app.layout = html.Div([ html.Div([ html.H4('Enter a stock symbol'), html.H5 ('for australian stocks use symbol + .AX eg WBC.AX'), dcc.Input(id='input-1-state',type='text',value='AAPL'), html.Button('Submit',id='submit-button') ]), dcc.Tabs( tabs=[ {'label': 'Price', 'value': 1}, {'label': 'Returns', 'value': 2}, {'label': 'Volatility', 'value': 3} ], #detrmines default tab to show value=1,id='tabs' ), html.Div(id='tab-output') ], style={ 'width': '60%', 'fontFamily': 'Sans-Serif', 'margin-left': 'auto', 'margin-right': 'auto'} ) @app.callback(Output('tab-output', 'children'), [Input('tabs', 'value')], events=[Event('submit-button', 'click')], state=[State('input-1-state', 'value')]) def display_content(value,stock_ticker): df = web.DataReader( stock_ticker, data_source='yahoo', start=dt(2017, 1, 1), end=dt.now()) x = df.index price = df.Close #need Adj Close. volume = df.Volume vol = price.pct_change() perc_ret = (np.exp(np.log1p(vol).cumsum())-1)*100 if value==1: #no seperate tab for return. have scale for return on right side of price graph. #see wind streaming app to simply return of graph and trace attributes #option for line & candlestick #stock tickers example for search box - compile a csv file for all exchanges, or dynamic? #graph multiple traces #drag bar to change scale #introduce commentary return html.Div([ dcc.Graph( id='price', figure={'data': [{ 'x': x, 'y': price}], 'layout': {'title': 'Price' } } ), dcc.Graph( id='volume', figure={'data': [go.Bar(x=x,y=volume)], 'layout': {'title': 'Daily Volume' } } ) ]) if value==2: return html.Div([ dcc.Graph( id='return', figure={ 'data': [{ 'x': x, 'y': perc_ret}], 'layout': {'title': 'Cumulative Return' } } ), ]) if value==3: return html.Div([ dcc.Graph( id='vol', figure={'data': [{ 'x': x, 'y': vol}] } ), dcc.Graph( id='volhist', figure={'data': [go.Histogram( x=df.Close.pct_change() )]} ) ]) if __name__ == '__main__': app.run_server(debug=True) import numpy as np app = dash.Dash() app.scripts.config.serve_locally = True app.config['suppress_callback_exceptions']=True app.layout = html.Div([ html.Div([ html.H4('Enter a stock symbol'), dcc.Input( id='stock-submit', placeholder='Enter a stock to analyse', type='text', value='AAPL', ), html.Button('Submit', id='submit-stock') ]), dcc.Tabs( tabs=[ {'label': 'Price', 'value': 1}, {'label': 'Returns', 'value': 2}, {'label': 'Volatility', 'value': 3} ], #detrmines default tab to show value=1, id='tabs' ), html.Div(id='tab-output') ], style={ 'width': '60%', 'fontFamily': 'Sans-Serif', 'margin-left': 'auto', 'margin-right': 'auto' }) @app.callback(Output('stock', 'value'),[Input('submit-stock', 'n_clicks')], state=[State('stock-submit', 'value')]) def update_stock(stock_submit_value): stock=stock_submit_value @app.callback(Output('tab-output', 'children'), [Input('tabs', 'value')]) def display_content(value): #error here as value passes is value of tab, eg 1 or 2 not value of input box #temp fix change value to 'AAPL' need another call back df = web.DataReader( stock, data_source='yahoo', start=dt(2017, 1, 1), end=dt.now()) x = df.index price = df.Close vol = df.Close.pct_change() perc_ret = (np.exp(np.log1p(vol).cumsum())-1)*100 if value==1: return html.Div([ dcc.Graph( id='price', figure={'data': [{ 'x': x, 'y': price}] } ) ]) #no seperate tab for return. have scale for return on right side of price graph. if value==2: #trace1 = ... #tracen = ... #plot traces in graph as per examples return html.Div([ dcc.Graph( id='return', figure={ 'data': [{ 'x': x, 'y': perc_ret}] } ), ]) if value==3: return html.Div([ dcc.Graph( id='vol', figure={'data': [{ 'x': x, 'y': vol}] } ), dcc.Graph( id='volhist', figure={'data': [go.Histogram( x=df.Close.pct_change() )]} ) ]) if __name__ == '__main__': app.run_server(debug=True)
22.130435
115
0.547598
696
5,599
4.321839
0.257184
0.027926
0.02992
0.031915
0.704122
0.687832
0.687832
0.670545
0.670545
0.617021
0
0.012201
0.297375
5,599
252
116
22.218254
0.752415
0.132702
0
0.682796
0
0
0.169905
0.011575
0
0
0
0
0
0
null
null
0
0.086022
null
null
0
0
0
0
null
0
0
0
0
0
0
0
0
1
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
2f11b5c2786474588b672ba08a8b825d60f8f1c3
2,278
py
Python
src/sima/riflex/blueprints/externalwrappingtype.py
SINTEF/simapy
650b8c2f15503dad98e2bfc0d0788509593822c7
[ "MIT" ]
null
null
null
src/sima/riflex/blueprints/externalwrappingtype.py
SINTEF/simapy
650b8c2f15503dad98e2bfc0d0788509593822c7
[ "MIT" ]
null
null
null
src/sima/riflex/blueprints/externalwrappingtype.py
SINTEF/simapy
650b8c2f15503dad98e2bfc0d0788509593822c7
[ "MIT" ]
null
null
null
# # Generated with ExternalWrappingTypeBlueprint from dmt.blueprint import Blueprint from dmt.dimension import Dimension from dmt.attribute import Attribute from dmt.enum_attribute import EnumAttribute from dmt.blueprint_attribute import BlueprintAttribute from sima.sima.blueprints.namedobject import NamedObjectBlueprint class ExternalWrappingTypeBlueprint(NamedObjectBlueprint): """""" def __init__(self, name="ExternalWrappingType", package_path="sima/riflex", description=""): super().__init__(name,package_path,description) self.attributes.append(Attribute("name","string","",default="")) self.attributes.append(Attribute("description","string","",default="")) self.attributes.append(Attribute("_id","string","",default="")) self.attributes.append(BlueprintAttribute("scriptableValues","sima/sima/ScriptableValue","",True,Dimension("*"))) self.attributes.append(Attribute("mass","number","Mass per unit length",default=0.0)) self.attributes.append(Attribute("buoyancy","number","Buoyancy volume/length",default=0.0)) self.attributes.append(Attribute("gyrationRadius","number","Radius of gyration around x-axis",default=0.0)) self.attributes.append(Attribute("coveredFraction","number","Fraction of the segment that is covered. 0 < FRAC < 1.0.",default=0.0)) self.attributes.append(Attribute("wrappingItemLength","number","Length of wrapping item. Only used for graphics.",default=1.0)) self.attributes.append(Attribute("tangentialDrag","number","Drag force coefficient in tangential direction",default=0.0)) self.attributes.append(Attribute("normalDrag","number","Drag force coefficient in normal direction",default=0.0)) self.attributes.append(Attribute("tangentialAddedMass","number","Added mass per length in tangential direction",default=0.0)) self.attributes.append(Attribute("normalAddedMass","number","Added mass per length in normal direction",default=0.0)) self.attributes.append(Attribute("tangentialLinearDrag","number","Linear drag force coefficients in tangential direction",default=0.0)) self.attributes.append(Attribute("normalLinearDrag","number","Linear drag force coefficients in tangential direction",default=0.0))
78.551724
143
0.751536
258
2,278
6.585271
0.317829
0.123602
0.176574
0.238964
0.467334
0.399647
0.321954
0.277222
0.225427
0.225427
0
0.012334
0.110184
2,278
29
144
78.551724
0.825851
0.019315
0
0
1
0
0.354157
0.011236
0
0
0
0
0
1
0.041667
false
0
0.25
0
0.333333
0.208333
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
2f129ea5aa02086f779235b60214f35969417160
1,341
py
Python
lib/python/import_util.py
leozz37/makani
c94d5c2b600b98002f932e80a313a06b9285cc1b
[ "Apache-2.0" ]
1,178
2020-09-10T17:15:42.000Z
2022-03-31T14:59:35.000Z
lib/python/import_util.py
leozz37/makani
c94d5c2b600b98002f932e80a313a06b9285cc1b
[ "Apache-2.0" ]
1
2020-05-22T05:22:35.000Z
2020-05-22T05:22:35.000Z
lib/python/import_util.py
leozz37/makani
c94d5c2b600b98002f932e80a313a06b9285cc1b
[ "Apache-2.0" ]
107
2020-09-10T17:29:30.000Z
2022-03-18T09:00:14.000Z
# Copyright 2020 Makani Technologies LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility to import classes.""" import importlib def ImportClass(path_to_module): """Import the module give the path to its file and the class. Args: path_to_module: A string specifying the location of the module. E.g. makani.analysis.my_checks.MyModule. Returns: The module object. """ class_path = path_to_module.split('.') class_name = class_path[-1] module_path = '.'.join(class_path[:-1]) module = importlib.import_module(module_path) try: cls = getattr(module, class_name) return cls except AttributeError, e: raise AttributeError(('Cannot import "%s" from "%s" because of ' 'AttributeError: %s.') % (class_name, path_to_module, e.message))
32.707317
74
0.700969
189
1,341
4.878307
0.539683
0.065076
0.052061
0.034707
0
0
0
0
0
0
0
0.009425
0.208799
1,341
40
75
33.525
0.859566
0.418345
0
0
0
0
0.120553
0
0
0
0
0
0
0
null
null
0
0.307692
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
0
0
1
0
0
0
1
0
0
0
0
2
2f23c841b4a903bc05de9a2eedcb7670a6274369
446
py
Python
tests/test_imports.py
ethan-jiang-1/ahrs
e1725267b0009a8a573f99dbf8d06e8481407ab6
[ "MIT" ]
184
2019-09-06T07:58:52.000Z
2022-03-31T04:27:09.000Z
tests/test_imports.py
ethan-jiang-1/ahrs
e1725267b0009a8a573f99dbf8d06e8481407ab6
[ "MIT" ]
48
2019-11-13T15:42:46.000Z
2022-03-31T23:53:53.000Z
tests/test_imports.py
ethan-jiang-1/ahrs
e1725267b0009a8a573f99dbf8d06e8481407ab6
[ "MIT" ]
34
2019-12-19T16:22:00.000Z
2022-03-14T09:51:50.000Z
# -*- coding: utf-8 -*- """ Test module imports =================== """ import sys def test_module_imports(): try: import ahrs except: sys.exit("[ERROR] Package AHRS not found. Go to root directory of package and type:\n\n\tpip install .\n") try: import numpy, scipy, matplotlib except ModuleNotFoundError: sys.exit("[ERROR] You don't have the required packages. Try reinstalling the package.")
23.473684
114
0.618834
57
446
4.807018
0.684211
0.072993
0.124088
0
0
0
0
0
0
0
0
0.002915
0.230942
446
18
115
24.777778
0.795918
0.139013
0
0.2
0
0.1
0.450667
0
0
0
0
0
0
1
0.1
true
0
0.4
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
0
1
0
1
0
0
0
0
2
2f242fb083c3ac571d233f65b374f2bb7b6f2d53
414
py
Python
users/signals.py
StitiFatah/Django_Rest_Framework_BoilerPlate
19e3fe41027853c0e491bdf97acb89c10c2ab0b4
[ "MIT" ]
null
null
null
users/signals.py
StitiFatah/Django_Rest_Framework_BoilerPlate
19e3fe41027853c0e491bdf97acb89c10c2ab0b4
[ "MIT" ]
null
null
null
users/signals.py
StitiFatah/Django_Rest_Framework_BoilerPlate
19e3fe41027853c0e491bdf97acb89c10c2ab0b4
[ "MIT" ]
null
null
null
# from django.db.models.signals import post_save # from users.models import PersoUser # from django.dispatch import receiver # @receiver(post_save, sender=PersoUser) # def create_Profile(sender, instance, created, **kwargs): # if created: # Profile.objects.create(user=instance) # @receiver(post_save, sender=PersoUser) # def save_Profile(sender, instance, **kwargs): # instance.profile.save()
27.6
58
0.736715
51
414
5.882353
0.431373
0.08
0.106667
0.146667
0.226667
0.226667
0
0
0
0
0
0
0.142512
414
14
59
29.571429
0.84507
0.939614
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
2f5790e03e5effd6fb7fca106845fc419671f3a1
301
py
Python
Python/basics/Modules/key.py
vinitraj10/A-week-with-Java
1c174fec98c8c078e1fc18ee497d1a517567defe
[ "Apache-2.0" ]
1
2017-08-01T19:41:37.000Z
2017-08-01T19:41:37.000Z
Python/basics/Modules/key.py
vinitraj10/Programming
1c174fec98c8c078e1fc18ee497d1a517567defe
[ "Apache-2.0" ]
2
2017-07-22T17:10:50.000Z
2017-07-22T17:12:53.000Z
Python/basics/Modules/key.py
vinitraj10/Java-Implementations
1c174fec98c8c078e1fc18ee497d1a517567defe
[ "Apache-2.0" ]
null
null
null
import keyword key = "elif" s="vinit" if keyword.iskeyword(key): print(key," is keyword") else: print(key," is not keyword") if keyword.iskeyword(s): print(s," is keyword") else: print(s," is not keyword") #This method is use to print the set of keywords present in python print(keyword.kwlist)
20.066667
66
0.714286
50
301
4.3
0.48
0.083721
0.167442
0.167442
0
0
0
0
0
0
0
0
0.152824
301
15
67
20.066667
0.843137
0.215947
0
0.166667
0
0
0.258475
0
0
0
0
0
0
1
0
false
0
0.083333
0
0.083333
0.416667
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
0
1
0
2
2f80eff5b3cc60933fa09f7f3453b70105181876
588
py
Python
ex044.py
GuilhermeAntony14/Estudando-Python
b020f6d2625e7fcc42d30658bcbd881b093434dd
[ "MIT" ]
null
null
null
ex044.py
GuilhermeAntony14/Estudando-Python
b020f6d2625e7fcc42d30658bcbd881b093434dd
[ "MIT" ]
null
null
null
ex044.py
GuilhermeAntony14/Estudando-Python
b020f6d2625e7fcc42d30658bcbd881b093434dd
[ "MIT" ]
null
null
null
print('{:=^40}'.format('Lojas Gui')) n = float(input('Coloque o valor do produto: R$ ')) print('''forma de pagamento. [1] Dinheiro/cheque. [2] Cartão. [3] 2x cartão. [4] 3x ou mais.''') n2 = int(input('Coloque a opção: ')) print('===') if n2 == 1: print(f'O valor a ser pago e R$ {n-(n*(10/100))}.') elif n2 == 2: print(f'O valor a ser pago é R$ {n-(n*(5/100))}.') elif n2 == 3: print(f'O valor a ser pago e R$ {n} \n2x de {n/2}.') elif n2 == 4: print(f'O valor a ser pago é R$ {n+(n*(20/100))} \n3x de {(n+(n*(20/100)))/3}.') else: print('Você fez algo errado.')
29.4
84
0.552721
115
588
2.826087
0.434783
0.092308
0.086154
0.147692
0.289231
0.289231
0.289231
0.289231
0.289231
0.289231
0
0.084567
0.195578
588
19
85
30.947368
0.602537
0
0
0
0
0.052632
0.62585
0.035714
0
0
0
0
0
1
0
false
0
0
0
0
0.421053
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
0
0
0
0
1
0
2
2f868b5576022c3bbf1451ead364883996c9c866
872
py
Python
feder/teryt/models.py
dzemeuksis/feder
32ef7793af6256d4ecada61505c7baf334b34419
[ "MIT" ]
16
2015-08-11T17:20:26.000Z
2022-02-11T20:15:41.000Z
feder/teryt/models.py
dzemeuksis/feder
32ef7793af6256d4ecada61505c7baf334b34419
[ "MIT" ]
534
2015-08-04T00:10:54.000Z
2022-03-17T10:44:47.000Z
feder/teryt/models.py
dzemeuksis/feder
32ef7793af6256d4ecada61505c7baf334b34419
[ "MIT" ]
10
2017-08-30T13:34:32.000Z
2022-02-18T13:00:35.000Z
from django.urls import reverse from teryt_tree.models import JednostkaAdministracyjna class JST(JednostkaAdministracyjna): def institution_qs(self): Institution = self.institution_set.model return Institution.objects.area(self) def case_qs(self): Case = self.institution_set.field.model.case_set.field.model return Case.objects.area(self) def get_absolute_url(self): return reverse("teryt:details", kwargs={"slug": self.slug}) def get_full_name(self): name = "{} ({}, {})".format(self.name, self.id, self.category) if self.parent: name = "{} / {}".format(self.parent, name) if self.parent.parent: name = "{} / {}".format(self.parent.parent, name) return name def __str__(self): return self.name class Meta: proxy = True
29.066667
70
0.629587
103
872
5.194175
0.378641
0.074766
0.078505
0.06729
0.097196
0
0
0
0
0
0
0
0.248853
872
29
71
30.068966
0.816794
0
0
0
0
0
0.048165
0
0
0
0
0
0
1
0.227273
false
0
0.090909
0.090909
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
1
0
0
0
0
1
0
0
2
2f8c8608a2f0f574033ea8711ddee6aad54d44db
87
py
Python
steps/02_data_container/benchmarks/__init__.py
karthikn72/enhancement-proposals
8200d8d5ec409bf76a2f8af6d12b17fe201afa0a
[ "BSD-3-Clause" ]
7
2020-10-16T14:56:54.000Z
2022-02-17T11:50:09.000Z
steps/02_data_container/benchmarks/__init__.py
karthikn72/enhancement-proposals
8200d8d5ec409bf76a2f8af6d12b17fe201afa0a
[ "BSD-3-Clause" ]
11
2020-11-02T17:55:21.000Z
2021-10-19T09:26:39.000Z
steps/02_data_container/benchmarks/__init__.py
karthikn72/enhancement-proposals
8200d8d5ec409bf76a2f8af6d12b17fe201afa0a
[ "BSD-3-Clause" ]
13
2020-11-26T23:04:06.000Z
2022-02-09T11:22:17.000Z
#!/usr/bin/env python3 -u # coding: utf-8 __author__ = ["Markus Löning"] __all__ = []
14.5
30
0.643678
12
87
4
1
0
0
0
0
0
0
0
0
0
0
0.027397
0.16092
87
5
31
17.4
0.630137
0.436782
0
0
0
0
0.276596
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
2f96c1a9a8a13e97ae22faa4d12d0fe3ab936262
1,465
py
Python
panoptes_cli/scripts/panoptes.py
sarpu/panoptes-cli
cb2e6fc3a17644055102f396344f8390c3878d3f
[ "Apache-2.0" ]
16
2016-06-16T16:02:00.000Z
2021-07-01T13:22:18.000Z
panoptes_cli/scripts/panoptes.py
sarpu/panoptes-cli
cb2e6fc3a17644055102f396344f8390c3878d3f
[ "Apache-2.0" ]
106
2016-01-18T10:26:21.000Z
2022-03-24T10:48:27.000Z
panoptes_cli/scripts/panoptes.py
sarpu/panoptes-cli
cb2e6fc3a17644055102f396344f8390c3878d3f
[ "Apache-2.0" ]
5
2016-01-19T09:47:23.000Z
2020-12-19T10:03:00.000Z
import click import os import yaml from panoptes_client import Panoptes @click.version_option(prog_name='Panoptes CLI') @click.group() @click.option( '--endpoint', '-e', help="Overides the default API endpoint", type=str, ) @click.option( '--admin', '-a', help=( "Enables admin mode. Ignored if you're not logged in as an " "administrator." ), is_flag=True, ) @click.pass_context def cli(ctx, endpoint, admin): ctx.config_dir = os.path.expanduser('~/.panoptes/') ctx.config_file = os.path.join(ctx.config_dir, 'config.yml') ctx.config = { 'endpoint': 'https://www.zooniverse.org', 'username': '', 'password': '', } try: with open(ctx.config_file) as conf_f: ctx.config.update(yaml.full_load(conf_f)) except IOError: pass if endpoint: ctx.config['endpoint'] = endpoint if ctx.invoked_subcommand != 'configure': Panoptes.connect( endpoint=ctx.config['endpoint'], username=ctx.config['username'], password=ctx.config['password'], admin=admin, ) from panoptes_cli.commands.configure import * from panoptes_cli.commands.info import * from panoptes_cli.commands.project import * from panoptes_cli.commands.subject import * from panoptes_cli.commands.subject_set import * from panoptes_cli.commands.user import * from panoptes_cli.commands.workflow import *
25.258621
68
0.647099
178
1,465
5.207865
0.432584
0.097087
0.113269
0.173679
0.202805
0.07767
0
0
0
0
0
0
0.225939
1,465
57
69
25.701754
0.81746
0
0
0.039216
0
0
0.171331
0
0
0
0
0
0
1
0.019608
false
0.078431
0.215686
0
0.235294
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
85cb2633d2b9e482f67e53d4228bd4e049ba540f
4,404
py
Python
test/test_stdio.py
razor-1/apns-clerk
807c1166d463d9be022eedf69ce9be0bf776f096
[ "Apache-2.0" ]
null
null
null
test/test_stdio.py
razor-1/apns-clerk
807c1166d463d9be022eedf69ce9be0bf776f096
[ "Apache-2.0" ]
null
null
null
test/test_stdio.py
razor-1/apns-clerk
807c1166d463d9be022eedf69ce9be0bf776f096
[ "Apache-2.0" ]
1
2019-12-17T18:45:13.000Z
2019-12-17T18:45:13.000Z
# Author Aleksi Hoffman # Based on apns-client implementation by Sardar Yumatov # # 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. if __name__ == '__main__': import os.path import sys sys.path.append(os.path.dirname(os.path.dirname(__file__))) import unittest import datetime from apns_clerk import Session CERTIFICATE = b"""-----BEGIN CERTIFICATE----- MIIDPTCCAuegAwIBAgIJALpcHuGZGDLzMA0GCSqGSIb3DQEBBQUAMIGdMQswCQYD VQQGEwJOTDESMBAGA1UECBMJR3JvbmluZ2VuMRIwEAYDVQQHEwlHcm9uaW5nZW4x FDASBgNVBAoTC2FwbnMtY2xpZW50MRUwEwYDVQQLEwxjZXJ0aWZpY2F0ZXMxFzAV BgNVBAMTDlNhcmRhciBZdW1hdG92MSAwHgYJKoZIhvcNAQkBFhFqYS5kb21hQGdt YWlsLmNvbTAeFw0xNDA1MjUxMjEwMjNaFw0xNDA2MjQxMjEwMjNaMIGdMQswCQYD VQQGEwJOTDESMBAGA1UECBMJR3JvbmluZ2VuMRIwEAYDVQQHEwlHcm9uaW5nZW4x FDASBgNVBAoTC2FwbnMtY2xpZW50MRUwEwYDVQQLEwxjZXJ0aWZpY2F0ZXMxFzAV BgNVBAMTDlNhcmRhciBZdW1hdG92MSAwHgYJKoZIhvcNAQkBFhFqYS5kb21hQGdt YWlsLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQC8hz/oFmBrSXpVwipPxFxZ qzSGgojSVxM/Mzaf24l/b9oeszfnrq0owk40PG7InSv6l5Z71SXKIOLKwJBgI8Od AgMBAAGjggEGMIIBAjAdBgNVHQ4EFgQUW0eeuZwjTcf1irE+11/C8fF2tSowgdIG A1UdIwSByjCBx4AUW0eeuZwjTcf1irE+11/C8fF2tSqhgaOkgaAwgZ0xCzAJBgNV BAYTAk5MMRIwEAYDVQQIEwlHcm9uaW5nZW4xEjAQBgNVBAcTCUdyb25pbmdlbjEU MBIGA1UEChMLYXBucy1jbGllbnQxFTATBgNVBAsTDGNlcnRpZmljYXRlczEXMBUG A1UEAxMOU2FyZGFyIFl1bWF0b3YxIDAeBgkqhkiG9w0BCQEWEWphLmRvbWFAZ21h aWwuY29tggkAulwe4ZkYMvMwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAANB AGwgOsUkTIo1y9v3Y77r02RjJLQRL1P68J8Exiunc53LR97Cg+o7LmaHonaLTUUH jahmYuZGN/Mty0brOn9hTI0= -----END CERTIFICATE-----""" PRIVATE_KEY = b"""-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,3195B956C3AD71F6 g7mfzdit5/26briSho71co+eqHV4Xxw7Y/lJzjuN7SGFjUbh/mBNjOxNmXzVSBWo 50SH/NgyqW7wy4glVLIdZ7u7iR8JZjXeBmH1Aee7+4TLGT5fTDR5aYWW7EPIRJ+E fAgEm1A0fsiHf7ki++UAFtZTPVcQg1NGeYjkJmpgn4CQwyztcfq1psIvNBBgAdrG UkHeJvwMalS/cmnVVdH2jR2liCsJhfH4lqH8eUSfGwCBeEjAY0Lg6HPwZY+eiVay /F5D8oL8GvqrM4hyzxU0KOZ8Pu0VUe1wDXDiNv3TUypZm5Y5sRi9DZ6jwZa7/hiE h3nbwhSfx2WC3bN8Gs8G9pJV9LGiBY2y2zANYTrq7Mv3iVLkHY8BQIUYQuiUnT20 8jeLSXRfZauDrVW5a8wGSJJLAyHGbXMAMV81z129xf8= -----END RSA PRIVATE KEY-----""" PRIVATE_PASS = "test" class Python26Mixin(object): """ Adds missing methods to test cases in Python 2.6 environment. """ def assertIsNotNone(self, value, msg=None): """ Fail if value is None. """ parent = super(Python26Mixin, self) if hasattr(parent, 'assertIsNotNone'): parent.assertIsNotNone(value, msg) else: if value is None: raise self.failureException(msg or '%r is None' % value) class StdIOBackendTest(Python26Mixin, unittest.TestCase): """ Test stdio features. """ def setUp(self): self.session = Session(pool="apns_clerk.backends.stdio") def test_locking(self): """ Test thread locking mechanism """ lock = self.session.pool.create_lock() self.assertIsNotNone(lock) self.assertTrue(hasattr(lock, "acquire")) self.assertTrue(hasattr(lock, "release")) lock.acquire() lock.release() def test_certificates(self): """ Test pyOpenSSL certificates. """ cert = self.session.pool.get_certificate({ "cert_string": CERTIFICATE, "key_string": PRIVATE_KEY, "passphrase": PRIVATE_PASS }) cert2 = self.session.pool.get_certificate({ "cert_string": (CERTIFICATE + b"\n" + PRIVATE_KEY), "passphrase": PRIVATE_PASS }) self.assertIsNotNone(cert.get_context()) self.assertEqual(cert, cert2) def test_outdate(self): # we are not allowed to do any IO in tests, so no real connections. # however, it is good idea to test utility functions even with empty pool. self.session.outdate(datetime.timedelta(seconds=60)) self.session.shutdown() if __name__ == '__main__': unittest.main()
36.7
82
0.769528
395
4,404
8.483544
0.544304
0.017905
0.013429
0.009549
0.048344
0.029842
0.029842
0.029842
0
0
0
0.058336
0.151453
4,404
119
83
37.008403
0.838373
0.205041
0
0.162162
0
0
0.544428
0.46136
0
1
0
0
0.108108
1
0.067568
false
0.040541
0.067568
0
0.162162
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
1
null
1
0
0
0
0
0
0
0
0
0
0
0
0
2
85cfddb855bfe365af5d52b3ebaf536333077899
190
py
Python
main.py
SuperKogito/Texhide
853b08191ce6c4f2d3b4ec10b3e97173e6a4643e
[ "MIT" ]
2
2018-04-24T21:38:53.000Z
2022-03-26T07:58:44.000Z
main.py
SuperKogito/Texhide
853b08191ce6c4f2d3b4ec10b3e97173e6a4643e
[ "MIT" ]
null
null
null
main.py
SuperKogito/Texhide
853b08191ce6c4f2d3b4ec10b3e97173e6a4643e
[ "MIT" ]
1
2022-03-26T07:58:49.000Z
2022-03-26T07:58:49.000Z
# -*- coding: utf-8 -*- """ Created on Mon Oct 9 03:14:54 2017 @author: kogito """ from Gui import MainWindow def main(): MainWindow('Texhide') if __name__ == '__main__': main()
13.571429
35
0.615789
26
190
4.192308
0.884615
0
0
0
0
0
0
0
0
0
0
0.08
0.210526
190
13
36
14.615385
0.646667
0.389474
0
0
0
0
0.138889
0
0
0
0
0
0
1
0.2
true
0
0.2
0
0.4
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
85db0bd6f56386e218c0e8e4ae1486775e584c22
1,527
py
Python
src/algorithms/metrics.py
jbustospelegri/breast_cancer_diagnosis
38eb990ef716912c6acabb443e6eb5c21d9b4e0d
[ "MIT" ]
5
2022-02-10T12:36:41.000Z
2022-03-23T17:28:35.000Z
src/algorithms/metrics.py
jbustospelegri/breast_cancer_diagnosis
38eb990ef716912c6acabb443e6eb5c21d9b4e0d
[ "MIT" ]
null
null
null
src/algorithms/metrics.py
jbustospelegri/breast_cancer_diagnosis
38eb990ef716912c6acabb443e6eb5c21d9b4e0d
[ "MIT" ]
1
2022-03-16T10:41:17.000Z
2022-03-16T10:41:17.000Z
from tensorflow.keras import backend def f1_score(y_true, y_pred): """ Función utilizada para calcular la métrica F1 a partir de las predicciones y los labels verdaderos :param y_true: array con labels verdaderos :param y_pred: array con las predicciones :return: métrica f1 """ def get_recall(true_label, pred_label): """Recall metric. Only computes a batch-wise average of recall. Computes the recall, a metric for multi-label classification of how many relevant items are selected. """ true_positives = backend.sum(backend.round(backend.clip(true_label * pred_label, 0, 1))) possible_positives = backend.sum(backend.round(backend.clip(true_label, 0, 1))) return true_positives / (possible_positives + backend.epsilon()) def get_precision(true_label, pred_label): """ Precision metric. Only computes a batch-wise average of precision. Computes the precision, a metric for multi-label classification of how many selected items are relevant. """ true_positives = backend.sum(backend.round(backend.clip(true_label * pred_label, 0, 1))) predicted_positives = backend.sum(backend.round(backend.clip(pred_label, 0, 1))) return true_positives / (predicted_positives + backend.epsilon()) precision = get_precision(y_true, y_pred) recall = get_recall(y_true, y_pred) return 2 * ((precision * recall) / (precision + recall + backend.epsilon()))
37.243902
102
0.686968
199
1,527
5.115578
0.301508
0.094303
0.051081
0.070727
0.424361
0.424361
0.378193
0.336935
0.264244
0.129666
0
0.010135
0.224623
1,527
41
103
37.243902
0.849662
0.354944
0
0.153846
0
0
0
0
0
0
0
0
0
1
0.230769
false
0
0.076923
0
0.538462
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
85e1b58620622fc3af6939f20661bd3133e64372
6,104
py
Python
chandra_suli/gif_generator.py
nitikayad96/chandra_suli
905ded69825f8b3d4fa29a84661697abdb827a87
[ "BSD-3-Clause" ]
1
2020-01-08T19:57:19.000Z
2020-01-08T19:57:19.000Z
chandra_suli/gif_generator.py
nitikayad96/chandra_suli
905ded69825f8b3d4fa29a84661697abdb827a87
[ "BSD-3-Clause" ]
null
null
null
chandra_suli/gif_generator.py
nitikayad96/chandra_suli
905ded69825f8b3d4fa29a84661697abdb827a87
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python """ Generate lightcurves for each candidate given a list of candidates """ import argparse import os import sys import numpy as np import astropy.io.fits as pyfits import matplotlib.pyplot as plt import seaborn as sbs from matplotlib.colors import LogNorm from astropy.convolution import convolve, Gaussian2DKernel from matplotlib.animation import ArtistAnimation, FFMpegWriter from chandra_suli.find_files import find_files from chandra_suli import logging_system from chandra_suli.run_command import CommandRunner from chandra_suli.sanitize_filename import sanitize_filename import matplotlib matplotlib.use("tkagg") if __name__=="__main__": parser = argparse.ArgumentParser(description='Generate gifs to visualize transient') parser.add_argument("--masterfile", help="Path to file containing list of transients", required=True, type=str) parser.add_argument("--data_path", help="Path to directory containing data of all obsids", required=True, type=str) parser.add_argument("--verbose-debug", action='store_true') # Get the logger logger = logging_system.get_logger(os.path.basename(sys.argv[0])) # Get the command runner runner = CommandRunner(logger) args = parser.parse_args() data_path = sanitize_filename(args.data_path) masterfile = sanitize_filename(args.masterfile) transient_data = np.array(np.recfromtxt(masterfile, names=True), ndmin=1) for transient in transient_data: obsid = transient['Obsid'] ccd = transient['CCD'] candidate = transient['Candidate'] tstart = transient['Tstart'] tstop = transient['Tstop'] duration = tstop-tstart event_file = find_files(os.path.join(data_path, str(obsid)), "ccd_%s_%s_filtered_nohot.fits" % (ccd, obsid))[0] # get start and stop time of observation with pyfits.open(event_file, memmap=False) as event_ext: tmin = event_ext['EVENTS'].header['TSTART'] tmax = event_ext['EVENTS'].header['TSTOP'] # Get minimum and maximum X and Y, so we use always the same binning for the images xmin, xmax = event_ext['EVENTS'].data.field("X").min(), event_ext['EVENTS'].data.field("X").max() ymin, ymax = event_ext['EVENTS'].data.field("Y").min(), event_ext['EVENTS'].data.field("Y").max() print "Duration: %s" %duration print "Tmin: %s" % tmin print "Tmax: %s" %tmax print "Obs Time: %s" %(tmax-tmin) # Use the interval before the transient and the interval after the transient, as well as of course # the interval of the transient itself intervals = [tmin] # Add tstart only if it is sufficiently different from tmin (so we don't get an empty interval when the # transient is right at the beginning) if abs(tstart - tmin) > 0.1: intervals.append(tstart) intervals.append(tstop) # Add tmax only if it is sufficiently different from tstop, so we don't get an empty interval when the # transient is right at the end) if abs(tmax - tstop) > 0.1: intervals.append(tmax) evt_name, evt_file_ext = os.path.splitext(os.path.basename(event_file)) # Create individual time interval files images = [] for i in range(len(intervals)-1): outfile = "%s_TI_%s_cand_%s%s" %(evt_name, i+1, candidate, evt_file_ext) cmd_line = 'ftcopy \"%s[(TIME >= %s) && (TIME <= %s)]\" %s clobber=yes ' \ % (event_file, intervals[i], intervals[i+1], outfile) runner.run(cmd_line) images.append(outfile) #create a list of frames that will be animated into a gif frames = [] # Prepare bins xbins = np.linspace(xmin, xmax, 300) ybins = np.linspace(ymin, ymax, 300) fig = plt.figure() sub = fig.add_subplot(111) sub.set_title("ObsID %s, CCD %s \nTstart = %s, Tstop = %s" % (obsid, ccd, tstart, tstop)) for i, image in enumerate(images): #get x and y coordinates of image from fits file data = pyfits.getdata(image) x = data.field("x") y = data.field("y") #create 2D histogram data from it sbs.set(rc={'axes.facecolor': 'black', 'axes.grid': False}) hh, X, Y = np.histogram2d(x, y, bins=[xbins, ybins]) #smooth data gauss_kernel = Gaussian2DKernel(stddev=0.7, x_size=9, y_size=9) smoothed_data_gauss = convolve(hh, gauss_kernel, normalize_kernel=True) if x.shape[0] > 0: img = sub.imshow(smoothed_data_gauss, cmap='hot', animated=True, origin='lower') else: # No events in this image. Generate an empty image img = sub.imshow(smoothed_data_gauss, cmap='hot', animated=True, origin='lower') text = sub.annotate("%i / %i" % (i+1, len(images)), xy=(xbins.shape[0]/2.0, -20), xycoords='data', annotation_clip=False) # Compute interval duration dt = intervals[i+1] - intervals[i] text2 = sub.annotate("%i events" % (x.shape[0]), xy=(-120, ybins.shape[0]/2.0), xycoords='data', annotation_clip=False) text3 = sub.annotate("Duration: %.2f s" % (dt), xy=(-120, ybins.shape[0]/2.0 + 30), xycoords='data', annotation_clip=False) sub.set_yticklabels([]) sub.set_xticklabels([]) #add this image to list of frames frames.append([img, text, text2, text3]) # Remove the image os.remove(image) #animate and save gif print "Creating gif ObsID %s, CCD %s, Candidate %s...\n" %(obsid, ccd, candidate) anim = ArtistAnimation(fig, frames, interval=2000) anim.save("%s_cand_%s.gif" %(evt_name, candidate), writer='imagemagick') plt.close()
33.911111
119
0.61386
793
6,104
4.62169
0.325347
0.01528
0.02292
0.019645
0.163438
0.138063
0.110232
0.061664
0.061664
0.061664
0
0.013471
0.270315
6,104
179
120
34.100559
0.809385
0.15154
0
0.053763
1
0.010753
0.121236
0.005708
0
0
0
0
0
0
null
null
0
0.16129
null
null
0.053763
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
1
0
0
0
0
0
0
0
0
2
85f0d095368922974cb8bd87c7515c3d8aab57cd
1,384
py
Python
paper_retrieval/kompetenzpool_expert_list.py
JNKielmann/Master-Thesis
47475d15a2d63e11320405cc60b0e49ccda2c468
[ "MIT" ]
null
null
null
paper_retrieval/kompetenzpool_expert_list.py
JNKielmann/Master-Thesis
47475d15a2d63e11320405cc60b0e49ccda2c468
[ "MIT" ]
1
2020-05-17T11:20:51.000Z
2020-05-17T11:20:51.000Z
paper_retrieval/kompetenzpool_expert_list.py
JNKielmann/Master-Thesis
47475d15a2d63e11320405cc60b0e49ccda2c468
[ "MIT" ]
1
2021-02-17T21:24:55.000Z
2021-02-17T21:24:55.000Z
""" Expert list created from Kompetenzpool data. List contains Microsoft Academic Graph Ids """ kompetenzpool_expert_list = { "Internet of Things": [ 2241467651, 673846798, 2236413454 ], "blockchain": { 1245553041, 2021103267, }, "natural language processing": { 2794237920, 2578689274, }, "autonomous driving": { 2490080048, 2156656717, }, "humanoid robot": { 1047662447, 2570474579, 2772428913, 2588863116, 2910150326, 2248512682, 2565089218, }, "evolutionary algorithm": { 2104163988, 2036573014, }, "remote sensing": [ 1983767936, 2471318715, 2636005816, ], "cellular automaton": [ 183621591, 2484531368, ], "electronic voting": [ 2038785220, ], "kalman filter": [ 154988935, 2165996130, 2228035992, ], "software architecture": [ 2145590652, ], "robot grasping": [ 1047662447, 2565089218, ], "ubiquitous computing": [ 673846798, ], "human-computer interaction": [ 673846798, 332721774, ], "digital health": [ 2021103267, ] }
19.492958
44
0.493497
81
1,384
8.407407
0.876543
0.029369
0
0
0
0
0
0
0
0
0
0.409314
0.410405
1,384
70
45
19.771429
0.425245
0.062861
0
0.272727
0
0
0.206362
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
85f993e4d9e3c50ae4090aaa01b29ff8b6c4ef4e
260
py
Python
Exercicios - Mundo1/Ex023.py
BrianMath/ExerciciosPythonCeV
4960f1a58d281b32afd5dfd6ea65e0ae5ad48b4f
[ "MIT" ]
null
null
null
Exercicios - Mundo1/Ex023.py
BrianMath/ExerciciosPythonCeV
4960f1a58d281b32afd5dfd6ea65e0ae5ad48b4f
[ "MIT" ]
null
null
null
Exercicios - Mundo1/Ex023.py
BrianMath/ExerciciosPythonCeV
4960f1a58d281b32afd5dfd6ea65e0ae5ad48b4f
[ "MIT" ]
null
null
null
# Ex. 023 num = str(input("Digite um número: ")) # .zfill(4) -> preenche com 0 até completar 4 casas while len(num) < 4: num = "0" + num print("Unidade: ", num[3]) print("Dezena: ", num[2]) print("Centena: ", num[1]) print("Unidade de milhar: ", num[0])
26
91
0.6
42
260
3.714286
0.642857
0.051282
0
0
0
0
0
0
0
0
0
0.056604
0.184615
260
9
92
28.888889
0.679245
0.219231
0
0
0
0
0.32
0
0
0
0
0
0
1
0
false
0
0
0
0
0.571429
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
0
0
0
1
0
2
c81404879e6cbba9858293410a55e502f9a2a495
4,999
py
Python
src/colornames.py
vishnubob/pyscad
3530285011c757fbfbbb36201b8e40ce4cf16c49
[ "MIT" ]
8
2015-09-27T07:58:04.000Z
2019-11-14T16:35:56.000Z
src/colornames.py
vishnubob/pyscad
3530285011c757fbfbbb36201b8e40ce4cf16c49
[ "MIT" ]
1
2017-06-12T15:51:39.000Z
2017-06-21T12:02:41.000Z
src/colornames.py
vishnubob/pyscad
3530285011c757fbfbbb36201b8e40ce4cf16c49
[ "MIT" ]
1
2021-01-31T16:54:53.000Z
2021-01-31T16:54:53.000Z
ColorNames = \ { u'aliceblue': (240, 248, 255), u'antiquewhite': (250, 235, 215), u'aqua': (0, 255, 255), u'aquamarine': (127, 255, 212), u'azure': (240, 255, 255), u'beige': (245, 245, 220), u'bisque': (255, 228, 196), u'black': (0, 0, 0), u'blanchedalmond': (255, 235, 205), u'blue': (0, 0, 255), u'blueviolet': (138, 43, 226), u'brown': (165, 42, 42), u'burlywood': (222, 184, 135), u'cadetblue': (95, 158, 160), u'chartreuse': (127, 255, 0), u'chocolate': (210, 105, 30), u'coral': (255, 127, 80), u'cornflowerblue': (100, 149, 237), u'cornsilk': (255, 248, 220), u'crimson': (220, 20, 60), u'cyan': (0, 255, 255), u'darkblue': (0, 0, 139), u'darkcyan': (0, 139, 139), u'darkgoldenrod': (184, 134, 11), u'darkgray': (169, 169, 169), u'darkgreen': (0, 100, 0), u'darkgrey': (169, 169, 169), u'darkkhaki': (189, 183, 107), u'darkmagenta': (139, 0, 139), u'darkolivegreen': (85, 107, 47), u'darkorange': (255, 140, 0), u'darkorchid': (153, 50, 204), u'darkred': (139, 0, 0), u'darksalmon': (233, 150, 122), u'darkseagreen': (143, 188, 143), u'darkslateblue': (72, 61, 139), u'darkslategray': (47, 79, 79), u'darkslategrey': (47, 79, 79), u'darkturquoise': (0, 206, 209), u'darkviolet': (148, 0, 211), u'deeppink': (255, 20, 147), u'deepskyblue': (0, 191, 255), u'dimgray': (105, 105, 105), u'dimgrey': (105, 105, 105), u'dodgerblue': (30, 144, 255), u'firebrick': (178, 34, 34), u'floralwhite': (255, 250, 240), u'forestgreen': (34, 139, 34), u'fuchsia': (255, 0, 255), u'gainsboro': (220, 220, 220), u'ghostwhite': (248, 248, 255), u'gold': (255, 215, 0), u'goldenrod': (218, 165, 32), u'gray': (128, 128, 128), u'green': (0, 128, 0), u'greenyellow': (173, 255, 47), u'grey': (128, 128, 128), u'honeydew': (240, 255, 240), u'hotpink': (255, 105, 180), u'indianred': (205, 92, 92), u'indigo': (75, 0, 130), u'ivory': (255, 255, 240), u'khaki': (240, 230, 140), u'lavender': (230, 230, 250), u'lavenderblush': (255, 240, 245), u'lawngreen': (124, 252, 0), u'lemonchiffon': (255, 250, 205), u'lightblue': (173, 216, 230), u'lightcoral': (240, 128, 128), u'lightcyan': (224, 255, 255), u'lightgoldenrodyellow': (250, 250, 210), u'lightgray': (211, 211, 211), u'lightgreen': (144, 238, 144), u'lightgrey': (211, 211, 211), u'lightpink': (255, 182, 193), u'lightsalmon': (255, 160, 122), u'lightseagreen': (32, 178, 170), u'lightskyblue': (135, 206, 250), u'lightslategray': (119, 136, 153), u'lightslategrey': (119, 136, 153), u'lightsteelblue': (176, 196, 222), u'lightyellow': (255, 255, 224), u'lime': (0, 255, 0), u'limegreen': (50, 205, 50), u'linen': (250, 240, 230), u'magenta': (255, 0, 255), u'maroon': (128, 0, 0), u'mediumaquamarine': (102, 205, 170), u'mediumblue': (0, 0, 205), u'mediumorchid': (186, 85, 211), u'mediumpurple': (147, 112, 219), u'mediumseagreen': (60, 179, 113), u'mediumslateblue': (123, 104, 238), u'mediumspringgreen': (0, 250, 154), u'mediumturquoise': (72, 209, 204), u'mediumvioletred': (199, 21, 133), u'midnightblue': (25, 25, 112), u'mintcream': (245, 255, 250), u'mistyrose': (255, 228, 225), u'moccasin': (255, 228, 181), u'navajowhite': (255, 222, 173), u'navy': (0, 0, 128), u'oldlace': (253, 245, 230), u'olive': (128, 128, 0), u'olivedrab': (107, 142, 35), u'orange': (255, 165, 0), u'orangered': (255, 69, 0), u'orchid': (218, 112, 214), u'palegoldenrod': (238, 232, 170), u'palegreen': (152, 251, 152), u'paleturquoise': (175, 238, 238), u'palevioletred': (219, 112, 147), u'papayawhip': (255, 239, 213), u'peachpuff': (255, 218, 185), u'peru': (205, 133, 63), u'pink': (255, 192, 203), u'plum': (221, 160, 221), u'powderblue': (176, 224, 230), u'purple': (128, 0, 128), u'red': (255, 0, 0), u'rosybrown': (188, 143, 143), u'royalblue': (65, 105, 225), u'saddlebrown': (139, 69, 19), u'salmon': (250, 128, 114), u'sandybrown': (244, 164, 96), u'seagreen': (46, 139, 87), u'seashell': (255, 245, 238), u'sienna': (160, 82, 45), u'silver': (192, 192, 192), u'skyblue': (135, 206, 235), u'slateblue': (106, 90, 205), u'slategray': (112, 128, 144), u'slategrey': (112, 128, 144), u'snow': (255, 250, 250), u'springgreen': (0, 255, 127), u'steelblue': (70, 130, 180), u'tan': (210, 180, 140), u'teal': (0, 128, 128), u'thistle': (216, 191, 216), u'tomato': (255, 99, 71), u'turquoise': (64, 224, 208), u'violet': (238, 130, 238), u'wheat': (245, 222, 179), u'white': (255, 255, 255), u'whitesmoke': (245, 245, 245), u'yellow': (255, 255, 0), u'yellowgreen': (154, 205, 50)}
33.550336
45
0.528506
736
4,999
3.589674
0.381793
0.011355
0.013248
0.006056
0
0
0
0
0
0
0
0.307773
0.235647
4,999
148
46
33.777027
0.383669
0
0
0
0
0
0.261852
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
c816683bddaba0615c01f85d0794bc16f39e96e7
419
py
Python
topy/data/__init__.py
TarcisioLOliveira/topy
060da675e6494fee63fa5547befcb1f8ecc39fdc
[ "MIT" ]
1
2021-01-25T00:13:34.000Z
2021-01-25T00:13:34.000Z
topy/data/__init__.py
TarcisioLOliveira/topy
060da675e6494fee63fa5547befcb1f8ecc39fdc
[ "MIT" ]
null
null
null
topy/data/__init__.py
TarcisioLOliveira/topy
060da675e6494fee63fa5547befcb1f8ecc39fdc
[ "MIT" ]
null
null
null
""" # ============================================================================== # ToPy -- Topology optimization with Python. # Copyright (C) 2012, 2015, 2016, 2017 William Hunter. # Copyright (C) 2020, 2021 Tarcísio L. de Oliveira # ============================================================================== """ __all__ = ['H8bar_K', 'H8_K', 'H8T_K', 'H18B_K', 'Q4a5B_K', 'Q4bar_K', 'Q4_K', 'Q4T_K', 'Q5B_K']
41.9
96
0.398568
40
419
3.85
0.75
0.12987
0
0
0
0
0
0
0
0
0
0.093085
0.102625
419
9
97
46.555556
0.316489
0.74463
0
0
0
0
0.505051
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
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
c81da102b3010b0c5b4a0969dd227a880958f612
188
py
Python
esp32/frozen/_boot.py
InnovatePCU/ESP32_Micropython
46f7a10815b4137be02d54799377eb1826bbc4dc
[ "MIT" ]
null
null
null
esp32/frozen/_boot.py
InnovatePCU/ESP32_Micropython
46f7a10815b4137be02d54799377eb1826bbc4dc
[ "MIT" ]
null
null
null
esp32/frozen/_boot.py
InnovatePCU/ESP32_Micropython
46f7a10815b4137be02d54799377eb1826bbc4dc
[ "MIT" ]
null
null
null
# _boot.py -- always run on boot-up, even during safe boot import os from machine import UART UART(1, 115200) UART(2, 115200) os.dupterm(UART(0, 115200)) UART(1).deinit() UART(2).deinit()
20.888889
58
0.718085
34
188
3.941176
0.588235
0.074627
0
0
0
0
0
0
0
0
0
0.141104
0.132979
188
8
59
23.5
0.680982
0.297872
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.285714
0
0.285714
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
1
0
0
0
0
0
0
2
c8439bb368dc8173ad0adabef75d06f6f00ff198
695
py
Python
muz/frontend/__init__.py
Akaricchi/muz
87c443ae26fc287dda38ca1066856048642295a6
[ "WTFPL" ]
9
2016-09-20T16:53:55.000Z
2018-07-06T06:47:12.000Z
muz/frontend/__init__.py
Akaricchi/muz
87c443ae26fc287dda38ca1066856048642295a6
[ "WTFPL" ]
null
null
null
muz/frontend/__init__.py
Akaricchi/muz
87c443ae26fc287dda38ca1066856048642295a6
[ "WTFPL" ]
null
null
null
from __future__ import absolute_import from __future__ import print_function from __future__ import division from __future__ import unicode_literals import importlib, pkgutil from .misc import QuitRequest, Command from .abstract import Sound, Music, Clock, Frontend def get(name, frontendArgs=None, frontendArgsNamespace=None): return importlib.import_module(__name__ + "." + name).Frontend(args=frontendArgs, namespace=frontendArgsNamespace) def iter(): prefix = __name__ + "." for importer, modname, ispkg in pkgutil.iter_modules(__path__, prefix): if ispkg: modname = modname[len(prefix):] if "." not in modname: yield modname
31.590909
118
0.730935
78
695
6.089744
0.538462
0.084211
0.134737
0
0
0
0
0
0
0
0
0
0.191367
695
21
119
33.095238
0.845196
0
0
0
0
0
0.004323
0
0
0
0
0
0
1
0.125
false
0
0.5625
0.0625
0.75
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
0
0
0
1
0
1
0
0
2
c846ff1eb1ce291ffe2d355f4fb5cea046a7128a
12,071
py
Python
pysnmp-with-texts/ENTERASYS-VLAN-AUTHORIZATION-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
8
2019-05-09T17:04:00.000Z
2021-06-09T06:50:51.000Z
pysnmp-with-texts/ENTERASYS-VLAN-AUTHORIZATION-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
4
2019-05-31T16:42:59.000Z
2020-01-31T21:57:17.000Z
pysnmp-with-texts/ENTERASYS-VLAN-AUTHORIZATION-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
10
2019-04-30T05:51:36.000Z
2022-02-16T03:33:41.000Z
# # PySNMP MIB module ENTERASYS-VLAN-AUTHORIZATION-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-VLAN-AUTHORIZATION-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:04:50 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint") dot1dBasePortEntry, = mibBuilder.importSymbols("BRIDGE-MIB", "dot1dBasePortEntry") etsysModules, = mibBuilder.importSymbols("ENTERASYS-MIB-NAMES", "etsysModules") EnabledStatus, = mibBuilder.importSymbols("P-BRIDGE-MIB", "EnabledStatus") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") MibIdentifier, Bits, NotificationType, IpAddress, TimeTicks, Counter64, iso, Integer32, Counter32, ObjectIdentity, Unsigned32, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Bits", "NotificationType", "IpAddress", "TimeTicks", "Counter64", "iso", "Integer32", "Counter32", "ObjectIdentity", "Unsigned32", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") etsysVlanAuthorizationMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48)) etsysVlanAuthorizationMIB.setRevisions(('2004-06-02 19:22',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setRevisionsDescriptions(('The initial version of this MIB module',)) if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setLastUpdated('200406021922Z') if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setOrganization('Enterasys Networks, Inc') if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setContactInfo('Postal: Enterasys Networks, Inc. 50 Minuteman Rd. Andover, MA 01810-1008 USA Phone: +1 978 684 1000 E-mail: support@enterasys.com WWW: http://www.enterasys.com') if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setDescription("This MIB module defines a portion of the SNMP MIB under Enterasys Networks' enterprise OID pertaining to proprietary extensions to the IETF Q-BRIDGE-MIB, as specified in RFC2674, pertaining to VLAN authorization, as specified in RFC3580. Specifically, the enabling and disabling of support for the VLAN Tunnel-Type attribute returned from a RADIUS authentication, and how that attribute is applied to the port which initiated the authentication.") class VlanAuthEgressStatus(TextualConvention, Integer32): description = 'The possible egress configurations which may be applied in response to a successful authentication. none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. dynamic(4) The authenticating port will use information returned in the authentication response to modify the current egress lists.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4)) namedValues = NamedValues(("none", 1), ("tagged", 2), ("untagged", 3), ("dynamic", 4)) etsysVlanAuthorizationObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1)) etsysVlanAuthorizationSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 1)) etsysVlanAuthorizationPorts = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2)) etsysVlanAuthorizationEnable = MibScalar((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 1, 1), EnabledStatus().clone('disabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: etsysVlanAuthorizationEnable.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationEnable.setDescription('The enable/disable state for the VLAN authorization feature. When disabled, no modifications to the VLAN attributes related to packet switching should be enforced.') etsysVlanAuthorizationTable = MibTable((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1), ) if mibBuilder.loadTexts: etsysVlanAuthorizationTable.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationTable.setDescription('Extensions to the table that contains information about every port that is associated with this transparent bridge.') etsysVlanAuthorizationEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1), ) dot1dBasePortEntry.registerAugmentions(("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationEntry")) etsysVlanAuthorizationEntry.setIndexNames(*dot1dBasePortEntry.getIndexNames()) if mibBuilder.loadTexts: etsysVlanAuthorizationEntry.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationEntry.setDescription('A list of extensions that support the management of proprietary features for each port of a transparent bridge. This is indexed by dot1dBasePort.') etsysVlanAuthorizationStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 1), EnabledStatus().clone('enabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: etsysVlanAuthorizationStatus.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationStatus.setDescription('The enabled/disabled status for the application of VLAN authorization on this port, if disabled, the information returned in the VLAN-Tunnel-Type from the authentication will not be applied to the port (although it should be represented in this table). If enabled, those results will be applied to the port.') etsysVlanAuthorizationAdminEgress = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 2), VlanAuthEgressStatus().clone('untagged')).setMaxAccess("readwrite") if mibBuilder.loadTexts: etsysVlanAuthorizationAdminEgress.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationAdminEgress.setDescription('Controls the modification of the current vlan egress list (of the vlan returned in the VLAN-Tunnel-Type, and reported by etsysVlanAuthorizationVlanID) upon successful authentication in the following manner: none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. dynamic(4) The authenticating port will use information returned in the authentication response to modify the current egress lists. This value is supported only if the device supports a mechanism through which the egress status may be returned through the RADIUS response. Should etsysVlanAuthorizationEnable become disabled, etsysVlanAuthorizationStatus become disabled for a port, or should etsysVlanAuthorizationVlanID become 0 or 4095, all effect on the port egress MUST be removed.') etsysVlanAuthorizationOperEgress = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 3), VlanAuthEgressStatus().clone('none')).setMaxAccess("readonly") if mibBuilder.loadTexts: etsysVlanAuthorizationOperEgress.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationOperEgress.setDescription('Reports the current state of modification to the current vlan egress list (of the vlan returned in the VLAN-Tunnel-Type) upon successful authentication, if etsysVlanAuthorizationStatus is enabled, in the following manner: none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. The purpose of this leaf is to report, specifically when etsysVlanAuthorizationAdminEgress has been set to dynamic(4), the currently enforced egress modification. If the port is unauthenticated, or no VLAN-ID has been applied, this leaf should return none(1).') etsysVlanAuthorizationVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4094), ValueRangeConstraint(4095, 4095), ))).setMaxAccess("readonly") if mibBuilder.loadTexts: etsysVlanAuthorizationVlanID.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationVlanID.setDescription('The 12 bit VLAN identifier for a given port, used to override the PVID of the given port, obtained as a result of an authentication. A value of zero indicates that there is no authenticated VLAN ID for the given port. Should a port become unauthenticated this value MUST be returned to zero. A value of 4095 indicates that a the port has been authenticated, but that the VLAN returned could not be applied to the port (possibly because of resource constraints or misconfiguration). In this instance, the original PVID should still be applied. Should the feature become disabled or the session terminate, all effect on the Port VLAN ID MUST be removed.') etsysVlanAuthorizationConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2)) etsysVlanAuthorizationGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 1)) etsysVlanAuthorizationCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 2)) etsysVlanAuthorizationGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 1, 1)).setObjects(("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationEnable"), ("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationStatus"), ("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationAdminEgress"), ("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationOperEgress"), ("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationVlanID")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): etsysVlanAuthorizationGroup = etsysVlanAuthorizationGroup.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationGroup.setDescription('A collection of objects relating to VLAN Authorization.') etsysVlanAuthorizationCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 2, 1)).setObjects(("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): etsysVlanAuthorizationCompliance = etsysVlanAuthorizationCompliance.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationCompliance.setDescription('The compliance statement for devices that support the Enterasys VLAN Authorization MIB.') mibBuilder.exportSymbols("ENTERASYS-VLAN-AUTHORIZATION-MIB", etsysVlanAuthorizationVlanID=etsysVlanAuthorizationVlanID, etsysVlanAuthorizationGroup=etsysVlanAuthorizationGroup, etsysVlanAuthorizationEnable=etsysVlanAuthorizationEnable, etsysVlanAuthorizationOperEgress=etsysVlanAuthorizationOperEgress, etsysVlanAuthorizationAdminEgress=etsysVlanAuthorizationAdminEgress, etsysVlanAuthorizationConformance=etsysVlanAuthorizationConformance, VlanAuthEgressStatus=VlanAuthEgressStatus, etsysVlanAuthorizationPorts=etsysVlanAuthorizationPorts, etsysVlanAuthorizationStatus=etsysVlanAuthorizationStatus, etsysVlanAuthorizationCompliance=etsysVlanAuthorizationCompliance, etsysVlanAuthorizationMIB=etsysVlanAuthorizationMIB, etsysVlanAuthorizationGroups=etsysVlanAuthorizationGroups, etsysVlanAuthorizationObjects=etsysVlanAuthorizationObjects, etsysVlanAuthorizationTable=etsysVlanAuthorizationTable, etsysVlanAuthorizationSystem=etsysVlanAuthorizationSystem, etsysVlanAuthorizationEntry=etsysVlanAuthorizationEntry, etsysVlanAuthorizationCompliances=etsysVlanAuthorizationCompliances, PYSNMP_MODULE_ID=etsysVlanAuthorizationMIB)
170.014085
1,125
0.806893
1,400
12,071
6.955714
0.231429
0.005135
0.045287
0.006572
0.298008
0.200965
0.185664
0.185664
0.185664
0.185664
0
0.04307
0.099826
12,071
70
1,126
172.442857
0.85312
0.029658
0
0.05
0
0.15
0.473855
0.059638
0
0
0
0
0
1
0
false
0
0.15
0
0.233333
0
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
c84c08d2bdf14de84f283b3e2ec639ff95fc3933
5,163
py
Python
summer21/owen_experiments/csds_to_hf.py
gu-sentiment-2021/sent
a3874a7286c965684d92fcf78e4091ad3a33aae1
[ "MIT" ]
null
null
null
summer21/owen_experiments/csds_to_hf.py
gu-sentiment-2021/sent
a3874a7286c965684d92fcf78e4091ad3a33aae1
[ "MIT" ]
null
null
null
summer21/owen_experiments/csds_to_hf.py
gu-sentiment-2021/sent
a3874a7286c965684d92fcf78e4091ad3a33aae1
[ "MIT" ]
null
null
null
# Owen's experiment to convert a CSDS to the HF data structure import datasets import numpy as np from transformers import AutoModelForSequenceClassification, AutoTokenizer, Trainer, TrainingArguments from datasets import Dataset, DatasetDict, ClassLabel, load_metric # create a CSDS as dict # First create a mapping from string labels to integers c2l = ClassLabel(num_classes=3, names=['CB', 'NCB', 'NA']) csds_train_dict = {'text': ["John said he * likes * beets.", "Mary sometimes says she likes beets.", "Mary sometimes says she likes beets.", "Mary sometimes says she likes beets.", "Mary sometimes says she likes beets.", "Mary sometimes says she likes beets.", "Mary sometimes says she likes beets.", "Mary sometimes says she likes beets.", "Mary sometimes says she likes beets.", "Mary sometimes says she likes beets.", "Mary sometimes says she likes beets.", "Mary sometimes says she likes beets.", "Mary sometimes says she likes beets.", "Mary sometimes says she likes beets.", "Mary sometimes says she likes beets.", "Mary sometimes says she likes beets.", "Mary sometimes says she likes beets.", "Mary sometimes says she likes beets.", "Mary sometimes says she likes beets.", "Mary maybe likes beets." ], 'label': map(c2l.str2int, ["CB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB"])} csds_eval_dict = {'text': ["Peter said he likes beets.", "Joan sometimes says she likes beets.", "Joan sometimes says she likes beets.", "Joan sometimes says she likes beets.", "Joan sometimes says she likes beets.", "Joan sometimes says she likes beets.", "Joan sometimes says she likes beets.", "Joan sometimes says she likes beets.", "Joan sometimes says she likes beets.", "Joan sometimes says she likes beets.", "Joan sometimes says she likes beets.", "Joan sometimes says she likes beets.", "Joan sometimes says she likes beets.", "Joan sometimes says she likes beets.", "Joan sometimes says she likes beets.", "Joan sometimes says she likes beets.", "Joan sometimes says she likes beets.", "Joan sometimes says she likes beets.", "Joan sometimes says she likes beets.", "Joan maybe likes beets." ], 'label': map(c2l.str2int, ["CB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB", "NCB"])} csds_train_dataset = Dataset.from_dict(csds_train_dict) csds_eval_dataset = Dataset.from_dict(csds_eval_dict) csds_datasets = DatasetDict({'train': csds_train_dataset, 'eval': csds_eval_dataset}) def notify(string): print(">>>> ", string, " <<<<") notify("Created datset, now tokenizing dataset") tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") def tokenize_function(examples): return tokenizer(examples["text"], padding="max_length", truncation=True) tokenized_csds_datasets = csds_datasets.map(tokenize_function, batched=True) notify("Done tokenizing dataset") model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=3) metric = load_metric("accuracy") # In the named arguments below, replace full_train_dataset # and full-eval_dataset with small_train_dataset and # small_eval_dataset, respectively, for experimentation with # a small subset of the input data and a shorter running time. def compute_metrics(eval_pred): logits, labels = eval_pred predictions = np.argmax(logits, axis=-1) return metric.compute(predictions=predictions, references=labels) notify("Starting training") training_args = TrainingArguments("../CSDS/test_trainer") trainer = Trainer( model=model, args=training_args, train_dataset=tokenized_csds_datasets['train'], eval_dataset=tokenized_csds_datasets['eval'], compute_metrics=compute_metrics, ) trainer.train() notify("Done training") results = trainer.evaluate() print(results)
43.754237
102
0.552198
535
5,163
5.231776
0.22243
0.142908
0.205788
0.270096
0.502322
0.464452
0.464452
0.464452
0.464452
0.464452
0
0.002383
0.349797
5,163
117
103
44.128205
0.831397
0.070502
0
0.52381
0
0
0.362137
0
0
0
0
0
0
1
0.035714
false
0
0.047619
0.011905
0.107143
0.02381
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
c85025922e071d45e3fb3d24498ed5f0d783223b
1,706
py
Python
pycc/tests/test_015_ints.py
zw0930/pycc
4b58b55f44467ea556c08fe0d7b3fc35b403e93e
[ "BSD-3-Clause" ]
10
2021-08-04T01:21:10.000Z
2022-03-21T04:28:46.000Z
pycc/tests/test_015_ints.py
zw0930/pycc
4b58b55f44467ea556c08fe0d7b3fc35b403e93e
[ "BSD-3-Clause" ]
19
2021-07-04T23:57:56.000Z
2022-03-31T20:40:49.000Z
pycc/tests/test_015_ints.py
zw0930/pycc
4b58b55f44467ea556c08fe0d7b3fc35b403e93e
[ "BSD-3-Clause" ]
6
2021-07-19T02:49:09.000Z
2022-03-21T04:28:47.000Z
""" Test integrators with simple ODE dx/dy = 3x^2y given x0 = 1, y0 = 2 ANALYTIC SOLUTION: y = e^{x^3 + c}, c = ln(2) - 1 y(1,1.1,1.2,1.3,1.4) = [2,2.78471958461639,4.141869187709196,6.6203429951303265,11.440356871885081] """ # Import package, test suite, and other packages as needed import numpy as np from pycc.rt import integrators as ints def f(x,y): """dy/dx = f(x,y) = 3x^2y""" Y = 3.*x**2. * y return Y def chk_ode(ode): h = 0.1 ODE = ode(h) t0 = 1 y0 = 2 y1 = ODE(f,t0,y0) y2 = ODE(f,t0+h,y1) y3 = ODE(f,t0+2*h,y2) y4 = ODE(f,t0+3*h,y3) return np.array([y0,y1,y2,y3,y4]) def test_rk4(): """Test 4th-order Runge-Kutta""" rk4 = chk_ode(ints.rk4) ref = np.array([2,2.7846419118859376,4.141490537335979,6.618844434974082,11.434686303979237]) assert np.allclose(rk4,ref) def test_rk38(): """Test "corrected" 3rd-order Runge-Kutta""" rk38 = chk_ode(ints.rk38) ref = np.array([2,2.7846719015333337,4.141594947022453,6.619134913159302,11.435455703714204]) assert np.allclose(rk38,ref) def test_rk3(): """Test 3rd-order Runge-Kutta""" rk3 = chk_ode(ints.rk3) ref = np.array([2,2.783897725,4.137908208354427,6.60545045860959,11.38808439342214]) assert np.allclose(rk3,ref) def test_rk2(): """Test 2nd-order Runge-Kutta""" rk2 = chk_ode(ints.rk2) ref = np.array([2,2.7643999999999997,4.066743395,6.396857224546359,10.804576512405294]) assert np.allclose(rk2,ref) def test_gl6(): """Test 6th-order Gauss-Legendre""" gl6 = chk_ode(ints.gl6) ref = np.array([2,2.78364923694925,4.1371512621094695,6.603613786914487,11.383853535021142]) assert np.allclose(gl6,ref)
26.246154
99
0.652989
280
1,706
3.939286
0.335714
0.010879
0.045331
0.049864
0.054397
0
0
0
0
0
0
0.329757
0.180539
1,706
64
100
26.65625
0.459227
0.263189
0
0
0
0
0
0
0
0
0
0
0.142857
1
0.2
false
0
0.057143
0
0.314286
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
c850a4d8009b9936dcc00fbacfde40ddb89cd586
246
py
Python
bose/sto_quad/copy_run.py
chem12346789/deom_mpi
66b03eb5855e31b587368bb42c5897c3829e1fa0
[ "MIT" ]
1
2022-02-21T11:01:52.000Z
2022-02-21T11:01:52.000Z
bose/sto_quad/copy_run.py
chem12346789/deom_mpi
66b03eb5855e31b587368bb42c5897c3829e1fa0
[ "MIT" ]
null
null
null
bose/sto_quad/copy_run.py
chem12346789/deom_mpi
66b03eb5855e31b587368bb42c5897c3829e1fa0
[ "MIT" ]
null
null
null
import os for i in range(10): cmd = r'cd ' + str(i) + '&&' cmd += r'echo new > out' + '&&' cmd += r'cp ../decompose_any_spe.py ./&&' cmd += r'cp ../r.sh ./&&' cmd += r'python3 decompose_any_spe.py >> out&' os.system(cmd)
24.6
50
0.5
40
246
2.975
0.55
0.168067
0.10084
0.285714
0
0
0
0
0
0
0
0.016484
0.260163
246
9
51
27.333333
0.637363
0
0
0
0
0
0.418699
0.093496
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
c850ba37cfa27f1b9a382804c1f0f76b8c4d80b3
28,233
py
Python
nuage_tempest_plugin/tests/api/test_floating_ips_nuage.py
nuagenetworks/nuage-tempest-plugin
ac1bfb0709c7bbaf04017af3050fb3ed1ad1324a
[ "Apache-1.1" ]
1
2021-01-03T01:47:51.000Z
2021-01-03T01:47:51.000Z
nuage_tempest_plugin/tests/api/test_floating_ips_nuage.py
nuagenetworks/nuage-tempest-plugin
ac1bfb0709c7bbaf04017af3050fb3ed1ad1324a
[ "Apache-1.1" ]
null
null
null
nuage_tempest_plugin/tests/api/test_floating_ips_nuage.py
nuagenetworks/nuage-tempest-plugin
ac1bfb0709c7bbaf04017af3050fb3ed1ad1324a
[ "Apache-1.1" ]
1
2020-10-16T12:04:39.000Z
2020-10-16T12:04:39.000Z
# Copyright 2015 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from netaddr import IPAddress from netaddr import IPNetwork import testtools import uuid from testtools.matchers import ContainsDict from testtools.matchers import Equals from tempest.api.network import test_floating_ips from tempest.common.utils import net_utils from tempest.lib.common.utils import data_utils from tempest.lib import exceptions from tempest.test import decorators from nuage_tempest_plugin.lib.features import NUAGE_FEATURES from nuage_tempest_plugin.lib.topology import Topology from nuage_tempest_plugin.lib.utils import constants from nuage_tempest_plugin.services.nuage_client import NuageRestClient CONF = Topology.get_conf() class FloatingIPTestJSONNuage(test_floating_ips.FloatingIPTestJSON): _interface = 'json' @classmethod def setup_clients(cls): super(FloatingIPTestJSONNuage, cls).setup_clients() cls.nuage_client = NuageRestClient() @classmethod def resource_setup(cls): super(FloatingIPTestJSONNuage, cls).resource_setup() # Creating two more ports which will be added in VSD for i in range(2): post_body = { "device_owner": "compute:None", "device_id": str(uuid.uuid1())} if CONF.network.port_vnic_type: post_body['binding:vnic_type'] = CONF.network.port_vnic_type if CONF.network.port_profile: post_body['binding:profile'] = CONF.network.port_profile port = cls.create_port(cls.network, **post_body) cls.ports.append(port) def _verify_fip_on_vsd(self, created_floating_ip, router_id, port_id, subnet_id, associated=True): # verifying on Domain level that the floating ip is added nuage_domain = self.nuage_client.get_l3domain( filters='externalID', filter_value=router_id) nuage_domain_fip = self.nuage_client.get_floatingip( constants.DOMAIN, nuage_domain[0]['ID']) if associated: # verifying on vminterface level that the floating ip is associated vsd_subnets = self.nuage_client.get_domain_subnet( None, None, 'externalID', subnet_id) nuage_vport = self.nuage_client.get_vport(constants.SUBNETWORK, vsd_subnets[0]['ID'], 'externalID', port_id) validation = False for fip in nuage_domain_fip: if (fip['address'] == created_floating_ip['floating_ip_address'] and nuage_vport[0]['associatedFloatingIPID'] == fip['ID']): validation = True error_message = ("FIP IP on OpenStack " + created_floating_ip['floating_ip_address'] + " does not match VSD FIP IP" + " (OR) FIP is not" " associated to the port" + port_id + " on VSD") self.assertTrue(validation, msg=error_message) else: vsd_fip_list = [fip['address'] for fip in nuage_domain_fip] self.assertNotIn(created_floating_ip['floating_ip_address'], vsd_fip_list) @decorators.attr(type='smoke') def test_create_list_show_update_delete_floating_ip(self): # Creates a floating IP body = self.floating_ips_client.create_floatingip( floating_network_id=self.ext_net_id, port_id=self.ports[2]['id']) created_floating_ip = body['floatingip'] self.addCleanup(self.floating_ips_client.delete_floatingip, created_floating_ip['id']) self.assertIsNotNone(created_floating_ip['id']) self.assertIsNotNone(created_floating_ip['tenant_id']) self.assertIsNotNone(created_floating_ip['floating_ip_address']) self.assertEqual(created_floating_ip['port_id'], self.ports[2]['id']) self.assertEqual(created_floating_ip['floating_network_id'], self.ext_net_id) self.assertIn(created_floating_ip['fixed_ip_address'], [ip['ip_address'] for ip in self.ports[2]['fixed_ips']]) # Verifies the details of a floating_ip floating_ip = self.floating_ips_client.show_floatingip( created_floating_ip['id']) shown_floating_ip = floating_ip['floatingip'] self.assertEqual(shown_floating_ip['id'], created_floating_ip['id']) self.assertEqual(shown_floating_ip['floating_network_id'], self.ext_net_id) self.assertEqual(shown_floating_ip['tenant_id'], created_floating_ip['tenant_id']) self.assertEqual(shown_floating_ip['floating_ip_address'], created_floating_ip['floating_ip_address']) self.assertEqual(shown_floating_ip['port_id'], self.ports[2]['id']) # VSD Validation self._verify_fip_on_vsd( created_floating_ip, created_floating_ip['router_id'], self.ports[2]['id'], self.subnet['id'], True) # Verify the floating ip exists in the list of all floating_ips floating_ips = self.floating_ips_client.list_floatingips() floatingip_id_list = list() for f in floating_ips['floatingips']: floatingip_id_list.append(f['id']) self.assertIn(created_floating_ip['id'], floatingip_id_list) # Disassociate floating IP from the port floating_ip = self.floating_ips_client.update_floatingip( created_floating_ip['id'], port_id=None) updated_floating_ip = floating_ip['floatingip'] self.assertIsNone(updated_floating_ip['port_id']) self.assertIsNone(updated_floating_ip['fixed_ip_address']) self.assertIsNone(updated_floating_ip['router_id']) # Associate floating IP to the other port floating_ip = self.floating_ips_client.update_floatingip( created_floating_ip['id'], port_id=self.ports[3]['id']) updated_floating_ip = floating_ip['floatingip'] self.assertEqual(updated_floating_ip['port_id'], self.ports[3]['id']) self.assertEqual(updated_floating_ip['fixed_ip_address'], self.ports[3]['fixed_ips'][0]['ip_address']) self.assertEqual(updated_floating_ip['router_id'], self.router['id']) # VSD Validation self._verify_fip_on_vsd( created_floating_ip, created_floating_ip['router_id'], self.ports[3]['id'], self.subnet['id'], True) # Disassociate floating IP from the port floating_ip = self.floating_ips_client.update_floatingip( created_floating_ip['id'], port_id=None) updated_floating_ip = floating_ip['floatingip'] self.assertIsNone(updated_floating_ip['port_id']) self.assertIsNone(updated_floating_ip['fixed_ip_address']) self.assertIsNone(updated_floating_ip['router_id']) # VSD Validation self._verify_fip_on_vsd( created_floating_ip, self.router['id'], None, None, False) @decorators.attr(type='smoke') def test_create_update_floating_ip(self): # Creates a floating IP body = self.floating_ips_client.create_floatingip( floating_network_id=self.ext_net_id, port_id=self.ports[2]['id']) created_floating_ip = body['floatingip'] self.addCleanup(self.floating_ips_client.delete_floatingip, created_floating_ip['id']) self.assertIsNotNone(created_floating_ip['id']) self.assertIsNotNone(created_floating_ip['tenant_id']) self.assertIsNotNone(created_floating_ip['floating_ip_address']) self.assertEqual(created_floating_ip['port_id'], self.ports[2]['id']) self.assertEqual(created_floating_ip['floating_network_id'], self.ext_net_id) self.assertIn(created_floating_ip['fixed_ip_address'], [ip['ip_address'] for ip in self.ports[2]['fixed_ips']]) # Verifies the details of a floating_ip floating_ip = self.floating_ips_client.show_floatingip( created_floating_ip['id']) shown_floating_ip = floating_ip['floatingip'] self.assertEqual(shown_floating_ip['id'], created_floating_ip['id']) self.assertEqual(shown_floating_ip['floating_network_id'], self.ext_net_id) self.assertEqual(shown_floating_ip['tenant_id'], created_floating_ip['tenant_id']) self.assertEqual(shown_floating_ip['floating_ip_address'], created_floating_ip['floating_ip_address']) self.assertEqual(shown_floating_ip['port_id'], self.ports[2]['id']) # VSD Validation self._verify_fip_on_vsd( created_floating_ip, created_floating_ip['router_id'], self.ports[2]['id'], self.subnet['id'], True) # Verify the floating ip exists in the list of all floating_ips floating_ips = self.floating_ips_client.list_floatingips() floatingip_id_list = list() for f in floating_ips['floatingips']: floatingip_id_list.append(f['id']) self.assertIn(created_floating_ip['id'], floatingip_id_list) if Topology.from_openstack('Newton') and Topology.is_ml2: self.floating_ips_client.update_floatingip( created_floating_ip['id'], port_id=self.ports[3]['id']) updated_floating_ip = self.floating_ips_client.show_floatingip( created_floating_ip['id'])['floatingip'] self.assertEqual(updated_floating_ip['port_id'], self.ports[3]['id']) self._verify_fip_on_vsd( updated_floating_ip, updated_floating_ip['router_id'], self.ports[3]['id'], self.subnet['id'], True) else: # Associate floating IP to the other port self.assertRaises(exceptions.ServerFault, self.floating_ips_client.update_floatingip, created_floating_ip['id'], port_id=self.ports[3]['id']) @decorators.attr(type='smoke') def test_floating_ip_delete_port(self): # Create a floating IP body = self.floating_ips_client.create_floatingip( floating_network_id=self.ext_net_id) created_floating_ip = body['floatingip'] self.addCleanup(self.floating_ips_client.delete_floatingip, created_floating_ip['id']) # Create a port post_body = { "device_owner": "compute:None", "device_id": str(uuid.uuid1())} port = self.ports_client.create_port( network_id=self.network['id'], **post_body) created_port = port['port'] floating_ip = self.floating_ips_client.update_floatingip( created_floating_ip['id'], port_id=created_port['id']) self.assertIsNotNone(floating_ip) # VSD Validation self._verify_fip_on_vsd(created_floating_ip, self.router['id'], created_port['id'], self.subnet['id'], True) # Delete port self.ports_client.delete_port(created_port['id']) # Verifies the details of the floating_ip floating_ip = self.floating_ips_client.show_floatingip( created_floating_ip['id']) shown_floating_ip = floating_ip['floatingip'] # Confirm the fields are back to None self.assertEqual(shown_floating_ip['id'], created_floating_ip['id']) self.assertIsNone(shown_floating_ip['port_id']) self.assertIsNone(shown_floating_ip['fixed_ip_address']) self.assertIsNone(shown_floating_ip['router_id']) def test_floating_ip_update_different_router(self): # Associate a floating IP to a port on a router body = self.floating_ips_client.create_floatingip( floating_network_id=self.ext_net_id, port_id=self.ports[3]['id']) created_floating_ip = body['floatingip'] self.addCleanup(self.floating_ips_client.delete_floatingip, created_floating_ip['id']) self.assertEqual(created_floating_ip['router_id'], self.router['id']) # VSD Validation self._verify_fip_on_vsd( created_floating_ip, created_floating_ip['router_id'], self.ports[3]['id'], self.subnet['id'], True) network2 = self.create_network() subnet2 = self.create_subnet(network2) router2 = self.create_router(data_utils.rand_name('router-'), external_network_id=self.ext_net_id) self.create_router_interface(router2['id'], subnet2['id']) post_body = { "device_owner": "compute:None", "device_id": str(uuid.uuid1())} port_other_router = self.create_port(network2, **post_body) self.floating_ips_client.update_floatingip( created_floating_ip['id'], port_id=port_other_router['id']) updated_floating_ip = self.floating_ips_client.show_floatingip( created_floating_ip['id'])['floatingip'] self.assertEqual(updated_floating_ip['port_id'], port_other_router['id']) self._verify_fip_on_vsd( updated_floating_ip, updated_floating_ip['router_id'], port_other_router['id'], subnet2['id'], True) @testtools.skipIf(Topology.before_nuage('5.4'), 'Unsupported pre-5.4') def test_floating_ip_disassociate_delete_router_associate(self): # Create topology network = self.create_network() subnet = self.create_subnet(network) router = self.create_router(data_utils.rand_name('router-'), external_network_id=self.ext_net_id) self.create_router_interface(router['id'], subnet['id']) post_body = { "device_owner": "compute:None", "device_id": str(uuid.uuid1())} port1 = self.create_port(network, **post_body) # Associate a floating IP to a port on a router body = self.floating_ips_client.create_floatingip( floating_network_id=self.ext_net_id, port_id=port1['id']) created_floating_ip = body['floatingip'] self.addCleanup(self.floating_ips_client.delete_floatingip, created_floating_ip['id']) self.assertEqual(created_floating_ip['router_id'], router['id']) # VSD Validation self._verify_fip_on_vsd( created_floating_ip, created_floating_ip['router_id'], port1['id'], subnet['id'], True) # Disassociate fip from port self.floating_ips_client.update_floatingip( created_floating_ip['id'], port_id=None) # Delete existing router self.delete_router(router) # Associate to second router network2 = self.create_network() subnet2 = self.create_subnet(network2) router2 = self.create_router(data_utils.rand_name('router-'), external_network_id=self.ext_net_id) self.create_router_interface(router2['id'], subnet2['id']) post_body = { "device_owner": "compute:None", "device_id": str(uuid.uuid1())} port_other_router = self.create_port(network2, **post_body) self.floating_ips_client.update_floatingip( created_floating_ip['id'], port_id=port_other_router['id']) updated_floating_ip = self.floating_ips_client.show_floatingip( created_floating_ip['id'])['floatingip'] self.assertEqual(updated_floating_ip['port_id'], port_other_router['id']) self._verify_fip_on_vsd( updated_floating_ip, updated_floating_ip['router_id'], port_other_router['id'], subnet2['id'], True) @decorators.attr(type='smoke') def test_create_floating_ip_specifying_a_fixed_ip_address(self): body = self.floating_ips_client.create_floatingip( floating_network_id=self.ext_net_id, port_id=self.ports[3]['id'], fixed_ip_address=self.ports[3]['fixed_ips'][0]['ip_address']) created_floating_ip = body['floatingip'] self.addCleanup(self.floating_ips_client.delete_floatingip, created_floating_ip['id']) self.assertIsNotNone(created_floating_ip['id']) self.assertEqual(created_floating_ip['fixed_ip_address'], self.ports[3]['fixed_ips'][0]['ip_address']) # VSD validation self._verify_fip_on_vsd( created_floating_ip, created_floating_ip['router_id'], self.ports[3]['id'], self.subnet['id'], True) floating_ip = self.floating_ips_client.update_floatingip( created_floating_ip['id'], port_id=None) self.assertIsNone(floating_ip['floatingip']['port_id']) # VSD Validation self._verify_fip_on_vsd( created_floating_ip, self.router['id'], None, None, False) @decorators.attr(type='smoke') def test_create_update_floatingip_with_port_multiple_ip_address(self): # TODO(Team) Adapt once we are on 5.3.2 # Find out ips that can be used for tests list_ips = net_utils.get_unused_ip_addresses( self.ports_client, self.subnets_client, self.subnet['network_id'], self.subnet['id'], 2) fixed_ips = [{'ip_address': list_ips[0]}, {'ip_address': list_ips[1]}] # Create port body = self.ports_client.create_port(network_id=self.network['id'], fixed_ips=fixed_ips) port = body['port'] self.addCleanup(self.ports_client.delete_port, port['id']) # Create floating ip self.assertRaises(exceptions.BadRequest, self.floating_ips_client.create_floatingip, floating_network_id=self.ext_net_id, port_id=port['id'], fixed_ip_address=list_ips[0]) @decorators.attr(type='smoke') def test_create_floatingip_with_rate_limiting(self): rate_limit = 10 # Create port post_body = {"network_id": self.network['id']} body = self.ports_client.create_port(**post_body) port = body['port'] self.addCleanup(self.ports_client.delete_port, port['id']) # Associate a fip to the port body = self.floating_ips_client.create_floatingip( floating_network_id=self.ext_net_id, port_id=port['id'], fixed_ip_address=port['fixed_ips'][0]['ip_address'], nuage_fip_rate=rate_limit) created_floating_ip = body['floatingip'] self.addCleanup(self.floating_ips_client.delete_floatingip, created_floating_ip['id']) self.assertIsNotNone(created_floating_ip['id']) fip_id = created_floating_ip['id'] body = self.floating_ips_client.show_floatingip(fip_id) fip = body['floatingip'] if NUAGE_FEATURES.bidirectional_fip_rate_limit: # rate_limit is in kbps now! self.assertThat(fip, ContainsDict( {'nuage_ingress_fip_rate_kbps': Equals(-1)})) self.assertThat(fip, ContainsDict( {'nuage_egress_fip_rate_kbps': Equals(rate_limit * 1000)})) # attribute 'nuage_fip_rate' is no longer in response self.assertIsNone(fip.get('nuage_fip_rate')) else: self.assertThat(fip, ContainsDict( {'nuage_fip_rate': Equals(str(rate_limit))})) # Check vsd vsd_subnets = self.nuage_client.get_domain_subnet( None, None, 'externalID', self.subnet['id']) self.assertEqual(1, len(vsd_subnets)) vports = self.nuage_client.get_vport(constants.SUBNETWORK, vsd_subnets[0]['ID'], 'externalID', port['id']) self.assertEqual(1, len(vports)) qos = self.nuage_client.get_qos(constants.VPORT, vports[0]['ID']) self.assertEqual(1, len(qos)) self.assertThat(qos[0], ContainsDict( {'externalID': Equals(self.nuage_client.get_vsd_external_id(fip_id))})) self.assertThat(qos[0], ContainsDict( {'FIPRateLimitingActive': Equals(True)})) self.assertThat(qos[0], ContainsDict( {'FIPPeakInformationRate': Equals(str(rate_limit))})) self.assertThat(qos[0], ContainsDict( {'FIPPeakBurstSize': Equals(str(100))})) if NUAGE_FEATURES.bidirectional_fip_rate_limit: self.assertThat(qos[0], ContainsDict( {'EgressFIPPeakInformationRate': Equals('INFINITY')})) self.assertThat(qos[0], ContainsDict( {'EgressFIPPeakBurstSize': Equals(str(100))})) else: self.assertEqual(str(rate_limit), qos[0]['FIPPeakInformationRate']) @decorators.attr(type='smoke') def test_create_floatingip_without_rate_limiting(self): # Create port post_body = {"network_id": self.network['id']} body = self.ports_client.create_port(**post_body) port = body['port'] self.addCleanup(self.ports_client.delete_port, port['id']) # Associate a fip to the port body = self.floating_ips_client.create_floatingip( floating_network_id=self.ext_net_id, port_id=port['id'], fixed_ip_address=port['fixed_ips'][0]['ip_address']) created_floating_ip = body['floatingip'] self.addCleanup(self.floating_ips_client.delete_floatingip, created_floating_ip['id']) self.assertIsNotNone(created_floating_ip['id']) fip_id = created_floating_ip['id'] body = self.floating_ips_client.show_floatingip(fip_id) fip = body['floatingip'] if NUAGE_FEATURES.bidirectional_fip_rate_limit: self.assertIsNotNone(fip.get('nuage_ingress_fip_rate_kbps')) self.assertIsNotNone(fip.get('nuage_egress_fip_rate_kbps')) else: os_fip_rate = fip.get('nuage_fip_rate') self.assertIsNotNone(os_fip_rate) # Check vsd vsd_subnets = self.nuage_client.get_domain_subnet( None, None, 'externalID', self.subnet['id']) self.assertEqual(1, len(vsd_subnets)) vports = self.nuage_client.get_vport(constants.SUBNETWORK, vsd_subnets[0]['ID'], 'externalID', port['id']) self.assertEqual(1, len(vports)) qos = self.nuage_client.get_qos(constants.VPORT, vports[0]['ID']) self.assertEqual(1, len(qos)) self.assertEqual(self.nuage_client.get_vsd_external_id(fip_id), qos[0]['externalID']) self.assertEqual(True, qos[0]['FIPRateLimitingActive']) if NUAGE_FEATURES.bidirectional_fip_rate_limit: self.assertEqual('INFINITY', qos[0]['FIPPeakInformationRate']) self.assertEqual('INFINITY', qos[0]['EgressFIPPeakInformationRate']) else: self.assertEqual('INFINITY', qos[0]['FIPPeakInformationRate']) @decorators.attr(type='smoke') def test_delete_associated_port_fip_cleanup(self): port = self.create_port(self.network) fip = self.floating_ips_client.create_floatingip( floating_network_id=self.ext_net_id, port_id=port['id'])['floatingip'] self.ports_client.delete_port(port['id']) self.floating_ips_client.delete_floatingip(fip['id']) vsd_l3domain = self.nuage_client.get_l3domain( filters='externalID', filter_value=fip['router_id']) vsd_fips = self.nuage_client.get_floatingip( constants.DOMAIN, vsd_l3domain[0]['ID']) for vsd_fip in vsd_fips: if vsd_fip['address'] == fip['floating_ip_address']: self.fail("No cleanup happened. Floatingip still exists on " "VSD and not in Neutron.") @decorators.attr(type='smoke') def test_fip_on_multiple_ip_port(self): network = self.create_network() self.assertIsNotNone(network, "Unable to create network") subnet = self.create_subnet(network) self.assertIsNotNone(subnet, "Unable to create subnet") router = self.create_router( admin_state_up=True, external_network_id=CONF.network.public_network_id) self.assertIsNotNone(router, "Unable to create router") self.create_router_interface(router_id=router["id"], subnet_id=subnet["id"]) # 1. Assigning fip to port with multiple ip address cidr4 = IPNetwork(CONF.network.project_network_cidr) port_args = { 'fixed_ips': [ {'subnet_id': subnet['id'], 'ip_address': str(IPAddress(cidr4.first) + 4)}, {'subnet_id': subnet['id'], 'ip_address': str(IPAddress(cidr4.first) + 5)}, {'subnet_id': subnet['id'], 'ip_address': str(IPAddress(cidr4.first) + 6)}, {'subnet_id': subnet['id'], 'ip_address': str(IPAddress(cidr4.first) + 7)}], } port = self.create_port(network=network, **port_args) floating_ip = self.create_floatingip( external_network_id=CONF.network.public_network_id) self.assertIsNotNone(floating_ip, "Unabe to create floating ip") msg = 'floating ip cannot be associated to port %s ' \ 'because it has multiple ipv4 or multiple ipv6ips' % port['id'] self.assertRaisesRegex(exceptions.BadRequest, msg, self.floating_ips_client.update_floatingip, floating_ip['id'], port_id=port['id']) # 2. Assigning multiple ip address to a port with fip port = self.create_port(network=network) floating_ip = self.create_floatingip( external_network_id=CONF.network.public_network_id) self.assertIsNotNone(floating_ip, "Unable to create floating ip") self.floating_ips_client.update_floatingip( floating_ip['id'], port_id=port['id']) port_args = { 'fixed_ips': [ {'subnet_id': subnet['id'], 'ip_address': str(IPAddress(cidr4.first) + 8)}, {'subnet_id': subnet['id'], 'ip_address': str(IPAddress(cidr4.first) + 9)}]} msg = ("It is not possible to add multiple ipv4 or multiple ipv6" " addresses on port {} since it has fip {} associated" "to it.").format(port['id'], floating_ip['id']) self.assertRaisesRegex(exceptions.BadRequest, msg, self.update_port, port=port, **port_args)
46.359606
79
0.621436
3,267
28,233
5.056627
0.09244
0.108959
0.082324
0.052119
0.746005
0.702482
0.672518
0.636562
0.626634
0.607869
0
0.006634
0.273899
28,233
608
80
46.435855
0.79922
0.071335
0
0.633333
0
0
0.108078
0.012846
0
0
0
0.001645
0.175
1
0.029167
false
0
0.03125
0
0.064583
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
c856a71b3488640d4656a1234bc4b99d2ab768dd
850
py
Python
onlineticket/sections/head.py
joushx/Online-Ticket-Code
593f5c73991be7061d36400a184a531adfb3e2f2
[ "MIT" ]
null
null
null
onlineticket/sections/head.py
joushx/Online-Ticket-Code
593f5c73991be7061d36400a184a531adfb3e2f2
[ "MIT" ]
null
null
null
onlineticket/sections/head.py
joushx/Online-Ticket-Code
593f5c73991be7061d36400a184a531adfb3e2f2
[ "MIT" ]
null
null
null
from kaitaistruct import KaitaiStream, BytesIO from onlineticket.generated.head import Head class HeadSectionParser: def parse(self, section): parsed = Head(KaitaiStream(BytesIO(section.data))) return { 'company': parsed.rics, 'ticket_id': parsed.ticket_id, 'edition_time': { 'year': parsed.edition_time.year, 'month': parsed.edition_time.month, 'day': parsed.edition_time.day, 'hour': parsed.edition_time.hour, 'minute': parsed.edition_time.minute }, 'flags': { 'international': parsed.flag.international, 'test': parsed.flag.test }, 'languages': [ parsed.lang, parsed.lang2 ] }
32.692308
59
0.521176
73
850
5.958904
0.479452
0.151724
0.195402
0
0
0
0
0
0
0
0
0.001883
0.375294
850
26
60
32.692308
0.817326
0
0
0
1
0
0.095182
0
0
0
0
0
0
1
0.041667
false
0
0.083333
0
0.208333
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
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
c06f4e54c1bb1504bf0d83f73890945bb76306ac
390
py
Python
{{cookiecutter.plugin_name}}/{{cookiecutter.plugin_name}}/views.py
qlands/formshare-cookiecutter-plugin
722cb82649111e6f88a15d52542e33c3e98a00f1
[ "BSD-3-Clause" ]
null
null
null
{{cookiecutter.plugin_name}}/{{cookiecutter.plugin_name}}/views.py
qlands/formshare-cookiecutter-plugin
722cb82649111e6f88a15d52542e33c3e98a00f1
[ "BSD-3-Clause" ]
null
null
null
{{cookiecutter.plugin_name}}/{{cookiecutter.plugin_name}}/views.py
qlands/formshare-cookiecutter-plugin
722cb82649111e6f88a15d52542e33c3e98a00f1
[ "BSD-3-Clause" ]
1
2019-10-18T14:30:45.000Z
2019-10-18T14:30:45.000Z
from formshare.plugins.utilities import FormSharePublicView, FormSharePrivateView class MyPublicView(FormSharePublicView): def process_view(self): return {} class MyPrivateView(FormSharePrivateView): def process_view(self): self.set_active_menu("myCustomMenu") self.showWelcome = True return {"message": self._("Just a message from the plugin")}
27.857143
81
0.730769
39
390
7.179487
0.666667
0.071429
0.1
0.128571
0
0
0
0
0
0
0
0
0.182051
390
13
82
30
0.877743
0
0
0.222222
0
0
0.125641
0
0
0
0
0
0
1
0.222222
false
0
0.111111
0.111111
0.777778
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
c06f59dc6494394ac903b8ae32c0564d01e349ec
156
py
Python
packages/submodopt/submodopt/__init__.py
toruurakawa/DiPS
211316a699b62c3aa1191c5eff3d923f0d359bfa
[ "Apache-2.0" ]
75
2019-06-04T23:37:58.000Z
2022-03-15T03:11:35.000Z
packages/submodopt/submodopt/__init__.py
ibrahim85/DiPS
8ea9747b1c104b6490000cdff15a522e9b860c05
[ "Apache-2.0" ]
20
2019-06-04T22:45:31.000Z
2022-03-11T23:49:38.000Z
packages/submodopt/submodopt/__init__.py
ibrahim85/DiPS
8ea9747b1c104b6490000cdff15a522e9b860c05
[ "Apache-2.0" ]
14
2019-06-19T05:03:32.000Z
2022-01-07T08:05:26.000Z
"""submodopt - A package for maximizing submodular functions""" __version__ = '0.1.0' __author__ = 'Satwik Bhattamishra <satwik55@gmail.com>' __all__ = []
26
63
0.730769
18
156
5.666667
0.944444
0
0
0
0
0
0
0
0
0
0
0.036765
0.128205
156
5
64
31.2
0.713235
0.365385
0
0
0
0
0.483871
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
c06fb992eef10824cf4d54d8b0b8345eecd3ec56
930
py
Python
virtual_bird/Models/Dlib_model.py
birdmandayum0131/virtual-bird
bf52b326df0a8ee12018434d98bde1ebb06548a8
[ "MIT" ]
5
2022-01-07T10:24:56.000Z
2022-02-18T07:13:57.000Z
virtual_bird/Models/Dlib_model.py
birdmandayum0131/virtual-bird
bf52b326df0a8ee12018434d98bde1ebb06548a8
[ "MIT" ]
null
null
null
virtual_bird/Models/Dlib_model.py
birdmandayum0131/virtual-bird
bf52b326df0a8ee12018434d98bde1ebb06548a8
[ "MIT" ]
2
2022-01-10T07:51:11.000Z
2022-02-18T07:10:52.000Z
import dlib import numpy as np from ..Abstract import FaceDetector, LandmarksDetector class Dlib_Face(FaceDetector): def __init__(self): self.detector = dlib.get_frontal_face_detector() def detect_faces_from_image(self, image_RGB): return [[dlib_rectangle.left(), dlib_rectangle.top(), dlib_rectangle.right(), dlib_rectangle.bottom()] for dlib_rectangle in self.detector(image_RGB, 1)] class Dlib_Landmark(LandmarksDetector): def __init__(self, dat_file="./virtual_bird/weights/shape_predictor_68_face_landmarks.dat"): self.detector = dlib.shape_predictor(dat_file) def detect_landmarks_from_face(self, face_image, detected_face): left, top, right, bottom = detected_face[:4] shape = self.detector(face_image, dlib.rectangle(int(left), int(top), int(right), int(bottom))) return np.asarray([(shape.part(i).x, shape.part(i).y) for i in range(68)], dtype=np.float)
48.947368
161
0.737634
131
930
4.946565
0.389313
0.12037
0.033951
0
0
0
0
0
0
0
0
0.007509
0.14086
930
19
162
48.947368
0.803504
0
0
0
0
0
0.064447
0.064447
0
0
0
0
0
1
0.266667
false
0
0.2
0.066667
0.733333
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
c083a119b1aa8f411da7e400b0f1ee9eab83b03b
1,110
py
Python
data/train/python/c083a119b1aa8f411da7e400b0f1ee9eab83b03burls.py
harshp8l/deep-learning-lang-detection
2a54293181c1c2b1a2b840ddee4d4d80177efb33
[ "MIT" ]
84
2017-10-25T15:49:21.000Z
2021-11-28T21:25:54.000Z
data/train/python/c083a119b1aa8f411da7e400b0f1ee9eab83b03burls.py
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
5
2018-03-29T11:50:46.000Z
2021-04-26T13:33:18.000Z
data/train/python/c083a119b1aa8f411da7e400b0f1ee9eab83b03burls.py
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
24
2017-11-22T08:31:00.000Z
2022-03-27T01:22:31.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- from app.controllers import IndexController from app.controllers import QController from app.controllers import SettingsPartiesController from app.controllers import SettingsTubiController from app.controllers import StartController from app.controllers.auth import LoginAuthorizedController from app.controllers.auth import LoginController from app.controllers.birri import BirriController from app.controllers.parties import PartiesController from app.controllers.parties import SelectPartyController from app.controllers.requests import RequestsController from app.controllers.tubi import TubiController URLS = ( '/', IndexController, '/login', LoginController, '/login/authorized', LoginAuthorizedController, '/settings/parties', SettingsPartiesController, '/parties', PartiesController, '/parties/select', SelectPartyController, '/settings/tubi', SettingsTubiController, '/tubi', TubiController, '/birri', BirriController, '/start', StartController, '/q', QController, '/requests', RequestsController )
34.6875
58
0.785586
102
1,110
8.54902
0.343137
0.09633
0.247706
0.137615
0.135321
0
0
0
0
0
0
0.00103
0.125225
1,110
31
59
35.806452
0.897013
0.037838
0
0
0
0
0.099437
0
0
0
0
0
0
1
0
false
0
0.461538
0
0.461538
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
0
0
0
1
0
0
0
0
2
c0885b51c72a870cf9009274c5a00c60d49a3967
15,369
py
Python
k1lib/cli/utils.py
157239n/k1lib
285520b8364ad5b21cb736b44471aa939e692e9b
[ "MIT" ]
1
2021-08-11T19:10:08.000Z
2021-08-11T19:10:08.000Z
k1lib/cli/utils.py
157239n/k1lib
285520b8364ad5b21cb736b44471aa939e692e9b
[ "MIT" ]
null
null
null
k1lib/cli/utils.py
157239n/k1lib
285520b8364ad5b21cb736b44471aa939e692e9b
[ "MIT" ]
null
null
null
# AUTOGENERATED FILE! PLEASE DON'T EDIT """ This is for all short utilities that has the boilerplate feeling. Conversion clis might feel they have different styles, as :class:`toFloat` converts object iterator to float iterator, while :class:`toPIL` converts single image url to single PIL image, whereas :class:`toSum` converts float iterator into a single float value. The general convention is, if the intended operation sounds simple (convert to floats, strings, types, ...), then most likely it will convert iterator to iterator, as you can always use the function directly if you only want to apply it on 1 object. If it sounds complicated (convert to PIL image, tensor, ...) then most likely it will convert object to object. Lastly, there are some that just feels right to input an iterator and output a single object (like getting max, min, std, mean values).""" from k1lib.cli.init import patchDefaultDelim, BaseCli, Table, T import k1lib.cli as cli, numbers, torch, numpy as np from typing import overload, Iterator, Any, List, Set, Union import k1lib __all__ = ["size", "shape", "item", "identity", "iden", "toStr", "join", "toNumpy", "toTensor", "toList", "wrapList", "toSet", "toIter", "toRange", "toType", "equals", "reverse", "ignore", "toSum", "toAvg", "toMean", "toMax", "toMin", "toPIL", "toBin", "toIdx", "lengths", "headerIdx", "deref", "bindec"] settings = k1lib.settings.cli def exploreSize(it): """Returns first element and length of array""" if isinstance(it, str): raise TypeError("Just here to terminate shape()") sentinel = object(); it = iter(it) o = next(it, sentinel); count = 1 if o is sentinel: return None, 0 try: while True: next(it); count += 1 except StopIteration: pass return o, count class size(BaseCli): def __init__(self, idx=None): """Returns number of rows and columns in the input. Example:: # returns (3, 2) [[2, 3], [4, 5, 6], [3]] | size() # returns 3 [[2, 3], [4, 5, 6], [3]] | size(0) # returns 2 [[2, 3], [4, 5, 6], [3]] | size(1) # returns (2, 0) [[], [2, 3]] | size() # returns (3,) [2, 3, 5] | size() # returns 3 [2, 3, 5] | size(0) # returns (3, 2, 2) [[[2, 1], [0, 6, 7]], 3, 5] | size() # returns (1,) and not (1, 3) ["abc"] | size() # returns (1, 2, 3) [torch.randn(2, 3)] | size() # returns (2, 3, 5) size()(np.random.randn(2, 3, 5)) There's also :class:`lengths`, which is sort of a simplified/faster version of this, but only use it if you are sure that ``len(it)`` can be called. If encounter PyTorch tensors or Numpy arrays, then this will just get the shape instead of actually looping over them. :param idx: if idx is None return (rows, columns). If 0 or 1, then rows or columns""" super().__init__(); self.idx = idx def __ror__(self, it:Iterator[str]): if self.idx is None: answer = [] try: while True: if isinstance(it, (torch.Tensor, np.ndarray)): return tuple(answer + list(it.shape)) it, s = exploreSize(it); answer.append(s) except TypeError: pass return tuple(answer) else: return exploreSize(it | cli.item(self.idx))[1] shape = size noFill = object() class item(BaseCli): def __init__(self, amt:int=1, fill=noFill): """Returns the first row. Example:: # returns 0 iter(range(5)) | item() # returns torch.Size([5]) torch.randn(3,4,5) | item(2) | shape() # returns 3 [] | item(fill=3) :param amt: how many times do you want to call item() back to back? :param fill: if iterator length is 0, return this""" self.amt = amt; self.fill = fill self.fillP = [fill] if fill != noFill else [] # preprocessed, to be faster def __ror__(self, it:Iterator[str]): if self.amt != 1: return it | cli.serial(*(item(fill=self.fill) for _ in range(self.amt))) return next(iter(it), *self.fillP) class identity(BaseCli): """Yields whatever the input is. Useful for multiple streams. Example:: # returns range(5) range(5) | identity()""" def __ror__(self, it:Iterator[Any]): return it iden = identity class toStr(BaseCli): def __init__(self, column:int=None): """Converts every line to a string. Example:: # returns ['2', 'a'] [2, "a"] | toStr() | deref() # returns [[2, 'a'], [3, '5']] assert [[2, "a"], [3, 5]] | toStr(1) | deref()""" super().__init__(); self.column = column def __ror__(self, it:Iterator[str]): c = self.column if c is None: for line in it: yield str(line) else: for row in it: yield [e if i != c else str(e) for i, e in enumerate(row)] class join(BaseCli): def __init__(self, delim:str=None): r"""Merges all strings into 1, with `delim` in the middle. Basically :meth:`str.join`. Example:: # returns '2\na' [2, "a"] | join("\n")""" super().__init__(); self.delim = patchDefaultDelim(delim) def __ror__(self, it:Iterator[str]): return self.delim.join(it | toStr()) class toNumpy(BaseCli): """Converts generator to numpy array. Essentially ``np.array(list(it))``""" def __ror__(self, it:Iterator[float]) -> np.array: return np.array(list(it)) class toTensor(BaseCli): def __init__(self, dtype=torch.float32): """Converts generator to :class:`torch.Tensor`. Essentially ``torch.tensor(list(it))``. Also checks if input is a PIL Image. If yes, turn it into a :class:`torch.Tensor` and return.""" self.dtype = dtype def __ror__(self, it:Iterator[float]) -> torch.Tensor: try: import PIL; pic=it if isinstance(pic, PIL.Image.Image): # stolen from torchvision ToTensor transform mode_to_nptype = {'I': np.int32, 'I;16': np.int16, 'F': np.float32} img = torch.from_numpy(np.array(pic, mode_to_nptype.get(pic.mode, np.uint8), copy=True)) if pic.mode == '1': img = 255 * img img = img.view(pic.size[1], pic.size[0], len(pic.getbands())) return img.permute((2, 0, 1)).contiguous().to(self.dtype) # put it from HWC to CHW format except: pass return torch.tensor(list(it)).to(self.dtype) class toList(BaseCli): """Converts generator to list. :class:`list` would do the same, but this is just to maintain the style""" def __ror__(self, it:Iterator[Any]) -> List[Any]: return list(it) class wrapList(BaseCli): """Wraps inputs inside a list. There's a more advanced cli tool built from this, which is :meth:`~k1lib.cli.structural.unsqueeze`.""" def __ror__(self, it:T) -> List[T]: return [it] class toSet(BaseCli): """Converts generator to set. :class:`set` would do the same, but this is just to maintain the style""" def __ror__(self, it:Iterator[T]) -> Set[T]: return set(it) class toIter(BaseCli): """Converts object to iterator. `iter()` would do the same, but this is just to maintain the style""" def __ror__(self, it:List[T]) -> Iterator[T]: return iter(it) class toRange(BaseCli): """Returns iter(range(len(it))), effectively""" def __ror__(self, it:Iterator[Any]) -> Iterator[int]: for i, _ in enumerate(it): yield i class toType(BaseCli): """Converts object to its type. Example:: # returns [int, float, str, torch.Tensor] [2, 3.5, "ah", torch.randn(2, 3)] | toType() | deref()""" def __ror__(self, it:Iterator[T]) -> Iterator[type]: for e in it: yield type(e) class _EarlyExp(Exception): pass class equals: """Checks if all incoming columns/streams are identical""" def __ror__(self, streams:Iterator[Iterator[str]]): streams = list(streams) for row in zip(*streams): sampleElem = row[0] try: for elem in row: if sampleElem != elem: yield False; raise _EarlyExp() yield True except _EarlyExp: pass class reverse(BaseCli): """Reverses incoming list. Example:: # returns [3, 5, 2] [2, 5, 3] | reverse() | deref()""" def __ror__(self, it:Iterator[str]) -> List[str]: return reversed(list(it)) class ignore(BaseCli): r"""Just loops through everything, ignoring the output. Example:: # will just return an iterator, and not print anything [2, 3] | apply(lambda x: print(x)) # will prints "2\n3" [2, 3] | apply(lambda x: print(x)) | ignore()""" def __ror__(self, it:Iterator[Any]): for _ in it: pass class toSum(BaseCli): """Calculates the sum of list of numbers. Can pipe in :class:`torch.Tensor`. Example:: # returns 45 range(10) | toSum()""" def __ror__(self, it:Iterator[float]): if isinstance(it, torch.Tensor): return it.sum() return sum(it) class toAvg(BaseCli): """Calculates average of list of numbers. Can pipe in :class:`torch.Tensor`. Example:: # returns 4.5 range(10) | toAvg() # returns nan [] | toAvg()""" def __ror__(self, it:Iterator[float]): if isinstance(it, torch.Tensor): return it.mean() s = 0; i = -1 for i, v in enumerate(it): s += v i += 1 if not k1lib.settings.cli.strict and i == 0: return float("nan") return s / i toMean = toAvg class toMax(BaseCli): """Calculates the max of a bunch of numbers. Can pipe in :class:`torch.Tensor`. Example:: # returns 6 [2, 5, 6, 1, 2] | toMax()""" def __ror__(self, it:Iterator[float]) -> float: if isinstance(it, torch.Tensor): return it.max() return max(it) class toMin(BaseCli): """Calculates the min of a bunch of numbers. Can pipe in :class:`torch.Tensor`. Example:: # returns 1 [2, 5, 6, 1, 2] | toMin()""" def __ror__(self, it:Iterator[float]) -> float: if isinstance(it, torch.Tensor): return it.min() return min(it) class toPIL(BaseCli): def __init__(self): """Converts a path to a PIL image. Example:: ls(".") | toPIL().all() | item() # get first image""" import PIL; self.PIL = PIL def __ror__(self, path) -> "PIL.Image.Image": return self.PIL.Image.open(path) class toBin(BaseCli): """Converts integer to binary string. Example:: # returns "101" 5 | toBin()""" def __ror__(self, it): return bin(int(it))[2:] class toIdx(BaseCli): def __init__(self, chars:str): """Get index of characters according to a reference. Example:: # returns [1, 4, 4, 8] "#&&*" | toIdx("!#$%&'()*+") | deref()""" self.chars = {v:k for k, v in enumerate(chars)} def __ror__(self, it): chars = self.chars for e in it: yield chars[e] class lengths(BaseCli): """Returns the lengths of each element. Example:: [range(5), range(10)] | lengths() == [5, 10] This is a simpler (and faster!) version of :class:`shape`. It assumes each element can be called with ``len(x)``, while :class:`shape` iterates through every elements to get the length, and thus is much slower.""" def __ror__(self, it:Iterator[List[Any]]) -> Iterator[int]: for e in it: yield len(e) def headerIdx(): """Cuts out first line, put an index column next to it, and prints it out. Useful when you want to know what your column's index is to cut it out. Also sets the context variable "header", in case you need it later. Example:: # returns [[0, 'a'], [1, 'b'], [2, 'c']] ["abc"] | headerIdx() | deref()""" return item() | cli.wrapList() | cli.transpose() | cli.insertIdColumn(True) settings.atomic.add("deref", (numbers.Number, np.number, str, dict, bool, bytes, torch.nn.Module), "used by deref") Tensor = torch.Tensor; atomic = settings.atomic class inv_dereference(BaseCli): def __init__(self, ignoreTensors=False): """Kinda the inverse to :class:`dereference`""" super().__init__(); self.ignoreTensors = ignoreTensors def __ror__(self, it:Iterator[Any]) -> List[Any]: for e in it: if e is None or isinstance(e, atomic.deref): yield e elif isinstance(e, Tensor): if not self.ignoreTensors and len(e.shape) == 0: yield e.item() else: yield e else: try: yield e | self except: yield e class deref(BaseCli): def __init__(self, maxDepth=float("inf"), ignoreTensors=True): """Recursively converts any iterator into a list. Only :class:`str`, :class:`numbers.Number` and :class:`~torch.nn.Module` are not converted. Example:: # returns something like "<range_iterator at 0x7fa8c52ca870>" iter(range(5)) # returns [0, 1, 2, 3, 4] iter(range(5)) | deref() # returns [2, 3], yieldSentinel stops things early [2, 3, yieldSentinel, 6] | deref() You can also specify a ``maxDepth``:: # returns something like "<list_iterator at 0x7f810cf0fdc0>" iter([range(3)]) | deref(0) # returns [range(3)] iter([range(3)]) | deref(1) # returns [[0, 1, 2]] iter([range(3)]) | deref(2) There are a few classes/types that are considered atomic, and :class:`deref` will never try to iterate over it. If you wish to change it, do something like:: settings.cli.atomic.deref = (int, float, ...) .. warning:: Can work well with PyTorch Tensors, but not Numpy arrays as they screw things up with the __ror__ operator, so do torch.from_numpy(...) first. Don't worry about unnecessary copying, as numpy and torch both utilizes the buffer protocol. :param maxDepth: maximum depth to dereference. Starts at 0 for not doing anything at all :param ignoreTensors: if True, then don't loop over :class:`torch.Tensor` internals""" super().__init__(); self.ignoreTensors = ignoreTensors self.maxDepth = maxDepth; self.depth = 0 def __ror__(self, it:Iterator[T]) -> List[T]: ignoreTensors = self.ignoreTensors if self.depth >= self.maxDepth: return it elif isinstance(it, atomic.deref): return it elif isinstance(it, Tensor): if ignoreTensors: return it if len(it.shape) == 0: return it.item() try: iter(it) except: return it self.depth += 1; answer = [] for e in it: if e is cli.yieldSentinel: return answer answer.append(self.__ror__(e)) self.depth -= 1; return answer def __invert__(self) -> BaseCli: """Returns a :class:`~k1lib.cli.init.BaseCli` that makes everything an iterator. Not entirely sure when this comes in handy, but it's there.""" return inv_dereference(self.ignoreTensors) class bindec(BaseCli): def __init__(self, cats:List[Any], f=None): """Binary decodes the input. Example:: # returns ['a', 'c'] 5 | bindec("abcdef") # returns 'a,c' 5 | bindec("abcdef", join(",")) :param cats: categories :param f: transformation function of the selected elements. Defaulted to :class:`toList`, but others like :class:`join` is useful too""" self.cats = cats; self.f = f or toList() def __ror__(self, it): it = bin(int(it))[2:][::-1] return (e for i, e in zip(it, self.cats) if i == '1') | self.f
38.042079
136
0.613703
2,183
15,369
4.229043
0.200183
0.017548
0.029246
0.032496
0.158471
0.132907
0.095212
0.083297
0.070299
0.070299
0
0.019674
0.242631
15,369
404
137
38.042079
0.773454
0.469582
0
0.121212
1
0
0.031402
0
0
0
0
0
0
1
0.20202
false
0.030303
0.030303
0.050505
0.494949
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
1
0
0
0
0
0
0
0
2
c095e0406851668f536f037523c078b508b0b407
6,004
py
Python
public/chart/integrations/django/samples/fusioncharts/samples/Single_Event_Overlay.py
AizaDapitan/PMC-IMS_V3
271ce3193edbf5182a9e232666ca417561ba2d16
[ "MIT" ]
14
2016-11-03T19:06:21.000Z
2021-11-24T09:05:09.000Z
public/chart/integrations/django/samples/fusioncharts/samples/Single_Event_Overlay.py
AizaDapitan/PMC-IMS_V3
271ce3193edbf5182a9e232666ca417561ba2d16
[ "MIT" ]
10
2022-02-16T07:17:49.000Z
2022-03-08T12:43:51.000Z
asset/integrations/django/samples/fusioncharts/samples/Single_Event_Overlay.py
Piusshungu/catherine-junior-school
5356f4ff5a5c8383849d32e22a60d638c35b1a48
[ "MIT" ]
17
2016-05-19T13:16:34.000Z
2021-04-30T14:38:42.000Z
from django.shortcuts import render from django.http import HttpResponse # Include the `fusioncharts.py` file which has required functions to embed the charts in html page from ..fusioncharts import FusionCharts from ..fusioncharts import FusionTable from ..fusioncharts import TimeSeries import requests # Loading Data and schema from a Static JSON String url # The `chart` method is defined to load chart data from an JSON string. def chart(request): data = requests.get('https://s3.eu-central-1.amazonaws.com/fusion.store/ft/data/single-event-overlay-data.json').text schema = requests.get('https://s3.eu-central-1.amazonaws.com/fusion.store/ft/schema/single-event-overlay-schema.json').text fusionTable = FusionTable(schema, data) timeSeries = TimeSeries(fusionTable) timeSeries.AddAttribute("caption", """{ text: 'Interest Rate Analysis' }""") timeSeries.AddAttribute("subCaption", """{ text: 'Federal Reserve (USA)' }""") timeSeries.AddAttribute("yAxis", """[{ plot: 'Interest Rate', format:{ suffix: '%' }, title: 'Interest Rate' }]""") timeSeries.AddAttribute("xAxis", """{ plot: 'Time', timemarker: [{ start: 'Mar-1980', label: 'US inflation peaked at 14.8%.', timeFormat: ' %b -%Y', style: { marker: { fill: '#D0D6F4' } } }, { start: 'May-1981', label: 'To control inflation, the Fed started {br} raising interest rates to over {br} 20%.', timeFormat: '%b-%Y' }, { start: 'Jun-1983', label: 'By proactive actions of Mr.Volcker, {br} the inflation falls to 2.4% {br} from the peak of over 14% {br} just three years ago.', timeFormat: '%b-%Y', style: { marker: { fill: '#D0D6F4' } } }, { start: 'Oct-1987', label: 'The Dow Jones Industrial Average lost {br} about 30% of it’s value.', timeFormat: '%b-%Y', style: { marker: { fill: '#FBEFCC' } } }, { start: 'Jan-1989', label: 'George H.W. Bush becomes {br} the 41st president of US!', timeFormat: '%b-%Y' }, { start: 'Aug-1990', label: 'The oil prices spiked to $35 {br} per barrel from $15 per barrel {br} because of the Gulf War.', timeFormat: '%b-%Y' }, { start: 'Dec-1996', label: 'Alan Greenspan warns of the dangers {br} of \"irrational exuberance\" in financial markets, {br} an admonition that goes unheeded', timeFormat: '%b-%Y' }, { start: 'Sep-2008', label: 'Lehman Brothers collapsed!', timeFormat: '%b-%Y' },{ start: 'Mar-2009', label: 'The net worth of US households {br} stood at a trough of $55 trillion.', timeFormat: '%b-%Y', style: { marker: { fill: '#FBEFCC' } } }, { start: 'Oct-2009', label: 'Unemployment rate peaked {br} in given times to 10%.', timeFormat: '%b-%Y' }] }""") # Create an object for the chart using the FusionCharts class constructor fcChart = FusionCharts("timeseries", "ex1", 700, 450, "chart-1", "json", timeSeries) # returning complete JavaScript and HTML code, which is used to generate chart in the browsers. return render(request, 'index.html', {'output' : fcChart.render(),'chartTitle': "Single event overlay"})
56.11215
179
0.340273
411
6,004
4.970803
0.493917
0.053842
0.058737
0.041605
0.126285
0.126285
0.126285
0.126285
0.051884
0.051884
0
0.031238
0.578781
6,004
107
180
56.11215
0.776592
0.06429
0
0.362637
0
0.087912
0.875802
0
0
0
0
0
0
1
0.010989
false
0
0.065934
0
0.087912
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
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
c09d6a4f52332e958259618fdd68d8aeb7391b21
227
py
Python
Lib/__hello__.py
ErikBjare/cpython
b68431fadb3150134ac6ccbf501cdfeaf4c75678
[ "0BSD" ]
2
2022-03-27T14:52:48.000Z
2022-03-27T17:35:22.000Z
Lib/__hello__.py
dalakatt/cpython
2f49b97cc5426087b46515254b9a97a22ee8c807
[ "0BSD" ]
8
2022-01-07T11:31:11.000Z
2022-03-04T00:07:16.000Z
Lib/__hello__.py
dalakatt/cpython
2f49b97cc5426087b46515254b9a97a22ee8c807
[ "0BSD" ]
1
2022-03-27T18:34:54.000Z
2022-03-27T18:34:54.000Z
initialized = True class TestFrozenUtf8_1: """\u00b6""" class TestFrozenUtf8_2: """\u03c0""" class TestFrozenUtf8_4: """\U0001f600""" def main(): print("Hello world!") if __name__ == '__main__': main()
13.352941
26
0.621145
23
227
5.652174
0.73913
0.438462
0
0
0
0
0
0
0
0
0
0.104972
0.202643
227
16
27
14.1875
0.61326
0.022026
0
0
0
0
0.106952
0
0
0
0
0
0
1
0.125
false
0
0
0
0.5
0.125
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
c0b0d23b937a9b2ef80e1c13407d4dc1c458035c
685
py
Python
porteiros/models.py
lucasazevedo/visitor-control
2daed747f68d04b1bda98bd51fe0876044e1cc54
[ "MIT" ]
null
null
null
porteiros/models.py
lucasazevedo/visitor-control
2daed747f68d04b1bda98bd51fe0876044e1cc54
[ "MIT" ]
null
null
null
porteiros/models.py
lucasazevedo/visitor-control
2daed747f68d04b1bda98bd51fe0876044e1cc54
[ "MIT" ]
null
null
null
from django.db import models class Porteiro(models.Model): usuario = models.OneToOneField('usuarios.Usuario', verbose_name='Usuário', on_delete=models.PROTECT) nome_completo = models.CharField(verbose_name='Nome completo', max_length=194) cpf = models.CharField(verbose_name='CPF', max_length=11) telefone = models.CharField(verbose_name='Telefone de contato', max_length=11) data_nascimento = models.DateField(verbose_name='Data de nascimento', auto_now=False, auto_now_add=False) class Meta: verbose_name = 'Porteiro' verbose_name_plural = 'Porteiros' db_table = 'porteiro' def __str__(self): return self.nome_completo
38.055556
109
0.732847
87
685
5.505747
0.494253
0.160752
0.137787
0.162839
0
0
0
0
0
0
0
0.012216
0.163504
685
17
110
40.294118
0.823735
0
0
0
0
0
0.147445
0
0
0
0
0
0
1
0.076923
false
0
0.076923
0.076923
0.769231
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
c0df5c3ccbd262e20ba4a3da038fce301e205995
6,377
py
Python
old_experiments/generate_data.py
weepingwillowben/reward-surfaces
f27211faf3784df3305972b7cad65002fd57d7bf
[ "MIT" ]
null
null
null
old_experiments/generate_data.py
weepingwillowben/reward-surfaces
f27211faf3784df3305972b7cad65002fd57d7bf
[ "MIT" ]
null
null
null
old_experiments/generate_data.py
weepingwillowben/reward-surfaces
f27211faf3784df3305972b7cad65002fd57d7bf
[ "MIT" ]
2
2021-10-03T14:51:38.000Z
2021-11-10T02:54:26.000Z
import os os.environ['OPENBLAS_NUM_THREADS'] = '1' from generate_test_files import generate_test_file from test_env import test_env_true_reward from generate_random_filter import generate_random_directions import os import multiprocessing as mp import numpy as np import shutil import json import tempfile def get_data_path(source_file): source_path = source_file.split("/") algo = source_path[-2] env_name = source_path[-1][:-4] data_folder = os.path.join("generated_dirs", algo, env_name) out_folder = os.path.join("output_files", algo, env_name) return data_folder+"/", out_folder+"/", algo, env_name def extension(path): return "."+path.strip().split(".")[-1] def generate_data(source_file, x_window, y_window): data_folder, _, algo, env_name = get_data_path(source_file) os.makedirs(data_folder) ext = extension(source_file) new_base_data = os.path.join(data_folder,"base_params"+ext) shutil.copyfile(source_file, new_base_data) generate_random_directions(new_base_data, data_folder) def get_rewards(args): (data_path, ext, env_name, algo, num_episodes, max_frames, xwin, ywin, xpos, ypos) = args with tempfile.NamedTemporaryFile(suffix=ext) as file: generate_test_file(data_path, file.name, xwin, ywin, xpos, ypos) print("genereated") return test_env_true_reward(file.name, env_name, algo, num_episodes, max_frames) def run_on_data(source_file, num_episodes, max_frames, x_window, y_window): data_folder, output_folder, algo, env_name = get_data_path(source_file) ext = extension(source_file) all_args = [] for x_pos in range(x_window): for y_pos in range(y_window): #print(data_fname) args = (data_folder, ext, env_name, algo, num_episodes, max_frames, x_window, y_window, x_pos, y_pos) all_args.append(args) #results = [sing_src_rew_eval(arg) for arg in all_args] print(f"pooled result: {len(all_args)}") print(f"pooled result: {x_window}") print(f"pooled result: {y_window}") print(f"pooled result: {len(all_args)}") print(f"pooled result: {len(all_args)}") print(f"pooled result: {len(all_args)}") pool = mp.Pool(6) results = list(pool.map(get_rewards, all_args)) print("fetched results") true_rewards = [true_rew for true_rew, est_val, true_val in results] est_vals = [est_val for true_rew, est_val, true_val in results] true_vals = [true_val for true_rew, est_val, true_val in results] os.makedirs(output_folder,exist_ok=True) #results = np.zeros(144) def save_data(results, name): results = np.asarray(results).reshape([x_window, y_window]).T result_fname = f"{output_folder}/{name}_<{x_window},{y_window}>_{num_episodes}_{max_frames}.npy" np.save(result_fname,results) print(f"saved {result_fname}") save_data(true_rewards, "true_values") save_data(est_vals, "mean_est_values") save_data(true_vals, "mean_values") if __name__ == "__main__": data_of_interest = open("envs.txt").readlines() data_of_interest = [line.strip() for line in data_of_interest] data_of_interest = data_of_interest#[:60] data_of_interest = [name for name in data_of_interest if "NoFrameskip-v4" in name] #data_of_interest = data_of_interest[::-1] data_of_interest = [ "trained_agents/a2c/BeamRiderNoFrameskip-v4.pkl", "trained_agents/a2c/BreakoutNoFrameskip-v4.pkl", "trained_agents/a2c/EnduroNoFrameskip-v4.pkl", "trained_agents/a2c/MsPacmanNoFrameskip-v4.pkl", "trained_agents/a2c/PongNoFrameskip-v4.pkl", "trained_agents/a2c/QbertNoFrameskip-v4.pkl", "trained_agents/a2c/SeaquestNoFrameskip-v4.pkl", "trained_agents/a2c/SpaceInvadersNoFrameskip-v4.pkl", "trained_agents/acer/BeamRiderNoFrameskip-v4.pkl", "trained_agents/acer/EnduroNoFrameskip-v4.pkl", "trained_agents/acer/MsPacmanNoFrameskip-v4.pkl", "trained_agents/acer/PongNoFrameskip-v4.pkl", "trained_agents/acer/QbertNoFrameskip-v4.pkl", "trained_agents/acer/SeaquestNoFrameskip-v4.pkl", "trained_agents/acer/SpaceInvadersNoFrameskip-v4.pkl", "trained_agents/acktr/BeamRiderNoFrameskip-v4.pkl", "trained_agents/acktr/BreakoutNoFrameskip-v4.pkl", "trained_agents/acktr/EnduroNoFrameskip-v4.pkl", "trained_agents/acktr/MsPacmanNoFrameskip-v4.pkl", "trained_agents/acktr/PongNoFrameskip-v4.pkl", "trained_agents/acktr/QbertNoFrameskip-v4.pkl", "trained_agents/acktr/SeaquestNoFrameskip-v4.pkl", "trained_agents/acktr/SpaceInvadersNoFrameskip-v4.pkl", "trained_agents/dqn/BeamRiderNoFrameskip-v4.pkl", "trained_agents/dqn/BreakoutNoFrameskip-v4.pkl", "trained_agents/dqn/EnduroNoFrameskip-v4.pkl", "trained_agents/dqn/MsPacmanNoFrameskip-v4.pkl", "trained_agents/dqn/PongNoFrameskip-v4.pkl", "trained_agents/dqn/QbertNoFrameskip-v4.pkl", "trained_agents/dqn/SeaquestNoFrameskip-v4.pkl", "trained_agents/dqn/SpaceInvadersNoFrameskip-v4.pkl", # "trained_agents/ppo2/BeamRiderNoFrameskip-v4.pkl", # "trained_agents/ppo2/BreakoutNoFrameskip-v4.pkl", # "trained_agents/ppo2/EnduroNoFrameskip-v4.pkl", # "trained_agents/ppo2/MsPacmanNoFrameskip-v4.pkl", # "trained_agents/ppo2/PongNoFrameskip-v4.pkl", # "trained_agents/ppo2/QbertNoFrameskip-v4.pkl", # "trained_agents/ppo2/SeaquestNoFrameskip-v4.pkl", # "trained_agents/ppo2/SpaceInvadersNoFrameskip-v4.pkl" ] print(json.dumps(data_of_interest,indent=4)) #exit(0) #[ #"trained_agents/trpo/LunarLander-v2.pkl", #"trained_agents/ppo2/LunarLander-v2.pkl", # "trained_agents/ddpg/BipedalWalker-v2.pkl", # "trained_agents/td3/BipedalWalker-v2.zip", # "trained_agents/dqn/QbertNoFrameskip-v4.pkl", # "trained_agents/ppo2/QbertNoFrameskip-v4.pkl", #] x_window = 17 y_window = 17 for data in data_of_interest: try: generate_data(data, x_window, y_window) except FileExistsError: pass for data in data_of_interest: # folder_path = get_data_path(data) # print(folder_path) max_frames = 10000 run_on_data(data, 50, max_frames, x_window, y_window)
44.594406
113
0.705504
843
6,377
5.046263
0.181495
0.137518
0.157969
0.165021
0.560884
0.191349
0.148096
0.140809
0.074048
0.04866
0
0.017127
0.175945
6,377
142
114
44.908451
0.792388
0.13486
0
0.09009
1
0
0.332969
0.270162
0
0
0
0
0
1
0.054054
false
0.009009
0.09009
0.009009
0.171171
0.09009
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
c0e4c0082eb6700bee3e03318b971566519341c0
99
py
Python
flexbe_widget/flexbe_widget/__init__.py
FlexBE/flexbe_behavior_engine
735a3b68dfbe817db9383e53fef63afd6868219d
[ "BSD-3-Clause" ]
1
2022-03-11T04:56:31.000Z
2022-03-11T04:56:31.000Z
flexbe_widget/flexbe_widget/__init__.py
FlexBE/flexbe_behavior_engine
735a3b68dfbe817db9383e53fef63afd6868219d
[ "BSD-3-Clause" ]
null
null
null
flexbe_widget/flexbe_widget/__init__.py
FlexBE/flexbe_behavior_engine
735a3b68dfbe817db9383e53fef63afd6868219d
[ "BSD-3-Clause" ]
null
null
null
from .behavior_action_server import BehaviorActionServer __all__ = [ 'BehaviorActionServer' ]
16.5
56
0.79798
8
99
9.125
0.875
0
0
0
0
0
0
0
0
0
0
0
0.141414
99
5
57
19.8
0.858824
0
0
0
0
0
0.20202
0
0
0
0
0
0
1
0
false
0
0.25
0
0.25
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
c0ea0b7a6dd4f9a1509f84fa884f4edb0c28c26e
4,739
py
Python
deprecated/heekspython/examples/polar_array.py
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
deprecated/heekspython/examples/polar_array.py
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
deprecated/heekspython/examples/polar_array.py
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # generated by wxGlade 0.6.3 on Fri Jul 24 14:50:26 2009 import HeeksPython as cad import math import wx # begin wxGlade: extracode # end wxGlade class MyFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MyFrame.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.x_center_label = wx.StaticText(self, -1, "X center") self.x_center_entry = wx.TextCtrl(self, -1, "") self.y_center_label = wx.StaticText(self, -1, "Y center") self.y_center_entry = wx.TextCtrl(self, -1, "") self.z_center_label = wx.StaticText(self, -1, "Z center") self.z_center_entry = wx.TextCtrl(self, -1, "") self.number_points_label = wx.StaticText(self, -1, "Number of Points") self.no_of_holes_entry = wx.TextCtrl(self, -1, "") self.diameter_label = wx.StaticText(self, -1, "Polar Array Diameter") self.bolt_circle_diameter_entry = wx.TextCtrl(self, -1, "") self.angle_label = wx.StaticText(self, -1, "Starting Angle") self.start_angle_entry = wx.TextCtrl(self, -1, "") self.scale_label = wx.StaticText(self, -1, "Scale") self.Scale_entry = wx.TextCtrl(self, -1, "") self.GenButton = wx.Button(self, -1, "Generate Points") self.quit = wx.Button(self, -1, "Close") self.__set_properties() self.__do_layout() self.Bind(wx.EVT_BUTTON, self.GenCode, self.GenButton) self.Bind(wx.EVT_BUTTON, self.OnCloseMe, self.quit) # end wxGlade def __set_properties(self): # begin wxGlade: MyFrame.__set_properties self.SetTitle("Generate Polar Array of Points") # end wxGlade def __do_layout(self): # begin wxGlade: MyFrame.__do_layout grid_sizer_1 = wx.GridSizer(9, 2, 0, 0) grid_sizer_1.Add(self.x_center_label, 0, wx.ALIGN_RIGHT, 0) grid_sizer_1.Add(self.x_center_entry, 0, 0, 0) grid_sizer_1.Add(self.y_center_label, 0, wx.ALIGN_RIGHT, 0) grid_sizer_1.Add(self.y_center_entry, 0, 0, 0) grid_sizer_1.Add(self.z_center_label, 0, wx.ALIGN_RIGHT, 0) grid_sizer_1.Add(self.z_center_entry, 0, 0, 0) grid_sizer_1.Add(self.number_points_label, 0, wx.ALIGN_RIGHT, 0) grid_sizer_1.Add(self.no_of_holes_entry, 0, 0, 0) grid_sizer_1.Add(self.diameter_label, 0, wx.ALIGN_RIGHT, 0) grid_sizer_1.Add(self.bolt_circle_diameter_entry, 0, 0, 0) grid_sizer_1.Add(self.angle_label, 0, wx.ALIGN_RIGHT, 0) grid_sizer_1.Add(self.start_angle_entry, 0, 0, 0) grid_sizer_1.Add(self.scale_label, 0, wx.ALIGN_RIGHT, 0) grid_sizer_1.Add(self.Scale_entry, 0, 0, 0) grid_sizer_1.Add(self.GenButton, 0, 0, 0) grid_sizer_1.Add(self.quit, 0, 0, 0) self.SetSizer(grid_sizer_1) grid_sizer_1.Fit(self) self.Layout() # end wxGlade def OnCloseMe(self, event): # wxGlade: MyFrame.<event_handler> print "We're Done!!!!!" self.Destroy() def GenCode(self, event): # wxGlade: MyFrame.<event_handler> cad.sketch() sketch = cad.getlastobj() x_center=float(self.x_center_entry.GetValue()) y_center=float(self.y_center_entry.GetValue()) z_center=float(self.z_center_entry.GetValue()) no_of_holes=float(self.no_of_holes_entry.GetValue()) bolt_circle_diameter=float(self.bolt_circle_diameter_entry.GetValue()) start_angle=float(self.start_angle_entry.GetValue()) scale=float(self.Scale_entry.GetValue()) count = 0 anglecount=1 circle_division_angle=(360/no_of_holes) calc_angle=start_angle while (count < no_of_holes): x1=math.cos(math.radians(calc_angle))*(bolt_circle_diameter/2) y1=math.sin(math.radians(calc_angle))*(bolt_circle_diameter/2) x=(x1+x_center)*scale y=(y1+y_center)*scale z=(z_center)*scale cad.point(x,y,z) cad.add(sketch,cad.getlastobj()) data=str('X%.4f Y%.4f Z%.4f '% (x, y, z)+'\n') print data anglecount=anglecount+1 calc_angle=calc_angle + circle_division_angle count=count+1 cad.reorder(sketch); return sketch # end of class MyFrame #we don't need the next section of code- it would crash Heeks '''if __name__ == "__main__": app = wx.PySimpleApp(0) wx.InitAllImageHandlers() frame_1 = MyFrame(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() app.MainLoop()'''
36.175573
78
0.625448
682
4,739
4.070381
0.20088
0.061599
0.068444
0.063401
0.423991
0.353746
0.247118
0.210735
0.166787
0.130764
0
0.03281
0.247521
4,739
130
79
36.453846
0.745653
0.08947
0
0
1
0
0.041159
0
0
0
0
0
0
0
null
null
0
0.036585
null
null
0.02439
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
1
0
0
0
0
0
0
0
0
2
8d050d3d1d0fe9bed9c144753d3ea902c1ec727c
188
py
Python
algorithms/reverse_bits.py
kainonly/leetcode
83a84ad48d517eb7f1377cb2a3aa3fe763da6627
[ "MIT" ]
null
null
null
algorithms/reverse_bits.py
kainonly/leetcode
83a84ad48d517eb7f1377cb2a3aa3fe763da6627
[ "MIT" ]
null
null
null
algorithms/reverse_bits.py
kainonly/leetcode
83a84ad48d517eb7f1377cb2a3aa3fe763da6627
[ "MIT" ]
null
null
null
class Solution: def reverseBits(self, n: int) -> int: val = 0 for i in range(32): val <<= 1 val += n & 1 n >>= 1 return val
20.888889
41
0.398936
24
188
3.125
0.666667
0.053333
0
0
0
0
0
0
0
0
0
0.0625
0.489362
188
8
42
23.5
0.71875
0
0
0
0
0
0
0
0
0
0
0
0
1
0.125
false
0
0
0
0.375
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
8d0a7446dbbcaf9d0140a056a947d3b80ba9cba3
2,656
py
Python
pythonequipmentdrivers/multimeter/Keysight_34461A.py
admleman/PythonEquipmentDrivers
1e1fbf96ae372757ad90339af5863ab64daef2a0
[ "MIT" ]
6
2021-02-01T14:23:22.000Z
2021-12-31T12:26:07.000Z
pythonequipmentdrivers/multimeter/Keysight_34461A.py
admleman/PythonEquipmentDrivers
1e1fbf96ae372757ad90339af5863ab64daef2a0
[ "MIT" ]
5
2020-08-17T12:59:06.000Z
2022-03-24T02:19:31.000Z
pythonequipmentdrivers/multimeter/Keysight_34461A.py
TedKus/PythonEquipmentDrivers
d758a6fb0f7d505d46b24fcd55170e90d2a06cd0
[ "MIT" ]
3
2020-12-30T17:25:55.000Z
2021-07-27T13:52:44.000Z
from .HP_34401A import HP_34401A # TODO: Add in additional measurement functionallity not written in the # original HP_34401A Class. Look into adding functionallity for adjusting the # triggering settings class Keysight_34461A(HP_34401A): """ Keysight_34461A() address: str, address of the connected multimeter factor: float, multiplicitive scale for all measurements defaults to 1. Object for accessing basic functionallity of the Keysight_34461A multimeter The factor term allows for measurements to be multiplied by some number before being returned. For example, in the case of measuring the voltage across a current shunt this factor can represent the conductance of the shunt. This factor defaults to 1 (no effect on measurement). Additional Information: https://literature.cdn.keysight.com/litweb/pdf/34460-90901.pdf """ valid_ranges = {'AUTO', 'MIN', 'MAX', 'DEF', '0.1', '1', '10', '100', '1000'} valid_cranges = {'AUTO', 'MIN', 'MAX', 'DEF', '0.0001', '0.001', '0.01', '0.1', '1', '3'} valid_Rranges = {'AUTO', 'MIN', 'MAX', 'DEF', '100', '1E3', '10E3', '100E3', '1E6', '10E6', '100E6'} def set_display_text(self, text: str) -> None: self.instrument.write(f'DISP:TEXT "{text}"') def get_display_text(self) -> str: response = self.instrument.query('DISP:TEXT?') text = response.strip().replace('"', '') return text def clear_display_text(self) -> None: self.set_display_text("") def set_display_state(self, state: bool) -> None: if state: self.instrument.write('DISP ON') else: self.instrument.write('DISP OFF') def get_display_state(self) -> bool: response = self.instrument.query('DISP?') return bool(int(response)) def set_display_mode(self, mode: str) -> None: mode = str(mode).upper() if mode not in ['NUM', 'HIST', 'TCH', 'MET']: raise ValueError(f'Invalid mode for arg "mode" ({mode})') self.instrument.write(f'DISP:VIEW {mode}') def get_display_mode(self) -> str: response = self.instrument.query('DISP:VIEW?') return response.strip() def set_label_text(self, label: str) -> None: self.instrument.write(f'SYSTEM:LABEL "{label}"') def get_label_text(self) -> str: response = self.instrument.query('SYSTEM:LABEL?') label = response.strip().replace('"', '') return label def clear_label_text(self) -> None: self.set_label_text('') if __name__ == '__main__': pass
32
79
0.625377
339
2,656
4.775811
0.39823
0.077826
0.058678
0.066708
0.183447
0.106238
0.072885
0
0
0
0
0.047572
0.240211
2,656
82
80
32.390244
0.754708
0.282756
0
0
0
0
0.144246
0
0
0
0
0.012195
0
1
0.238095
false
0.02381
0.02381
0
0.452381
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
1
0
0
0
0
0
0
0
2
23a3645631b36d2dab81ddd820a1e359a0ec68bb
1,426
py
Python
OracleWebCenterContent/dockerfiles/12.2.1.4/container-scripts/setTopology.py
rmohare/oracle-product-images
a5b0fc823de9258a0d0d63aed5837abb46b17cf3
[ "UPL-1.0" ]
5,519
2015-01-23T15:07:05.000Z
2022-03-31T12:12:19.000Z
OracleWebCenterContent/dockerfiles/12.2.1.4/container-scripts/setTopology.py
rmohare/oracle-product-images
a5b0fc823de9258a0d0d63aed5837abb46b17cf3
[ "UPL-1.0" ]
1,492
2015-01-26T05:31:35.000Z
2022-03-31T21:16:34.000Z
OracleWebCenterContent/dockerfiles/12.2.1.4/container-scripts/setTopology.py
rmohare/oracle-product-images
a5b0fc823de9258a0d0d63aed5837abb46b17cf3
[ "UPL-1.0" ]
5,850
2015-01-22T01:40:51.000Z
2022-03-31T12:12:19.000Z
#!/usr/bin/python # Copyright (c) 2021, Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl # # ============================================== import sys admin_name = os.environ['ADMIN_USERNAME'] admin_pass = os.environ['ADMIN_PASSWORD'] admin_port = os.environ['ADMIN_PORT'] admin_container = os.environ['ADMIN_SERVER_CONTAINER_NAME'] admin_host = sys.argv[1] url = admin_container + ':' + admin_port print('url :' + url); connect(admin_name, admin_pass, url) edit() startEdit() cd('/Servers/IBR_server1') cmo.setMachine(getMBean('/Machines/machine1')) cmo.setCluster(getMBean('/Clusters/ibr_cluster1')) cd('/Servers/UCM_server1') cmo.setMachine(getMBean('/Machines/machine1')) cmo.setCluster(getMBean('/Clusters/ucm_cluster1')) cd('/CoherenceClusterSystemResources/defaultCoherenceCluster/CoherenceClusterResource/defaultCoherenceCluster/CoherenceClusterParams/defaultCoherenceCluster/CoherenceClusterWellKnownAddresses/defaultCoherenceCluster') cmo.createCoherenceClusterWellKnownAddress('WKA-0') cd('/CoherenceClusterSystemResources/defaultCoherenceCluster/CoherenceClusterResource/defaultCoherenceCluster/CoherenceClusterParams/defaultCoherenceCluster/CoherenceClusterWellKnownAddresses/defaultCoherenceCluster/CoherenceClusterWellKnownAddresses/WKA-0') cmo.setListenAddress('localhost') save() activate() disconnect() exit()
33.162791
258
0.792426
140
1,426
7.935714
0.521429
0.032403
0.050405
0.050405
0.50045
0.50045
0.50045
0.50045
0.50045
0.131413
0
0.011186
0.059607
1,426
42
259
33.952381
0.817301
0.150771
0
0.08
0
0.04
0.553897
0.442786
0
0
0
0
0
1
0
false
0.08
0.04
0
0.04
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
1
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
23a9ed8039f11c2507b84f06661d2ddae5677e4b
872
py
Python
build_gromacs/module.py
daniellandau/shell-magic
10f00662ff85ad6a87c874537e071b3bd1d5973d
[ "Apache-2.0" ]
null
null
null
build_gromacs/module.py
daniellandau/shell-magic
10f00662ff85ad6a87c874537e071b3bd1d5973d
[ "Apache-2.0" ]
null
null
null
build_gromacs/module.py
daniellandau/shell-magic
10f00662ff85ad6a87c874537e071b3bd1d5973d
[ "Apache-2.0" ]
null
null
null
import os, string import subprocess if not os.environ.has_key('MODULE_VERSION'): os.environ['MODULE_VERSION_STACK'] = '3.2.6.7' os.environ['MODULE_VERSION'] = '3.2.6.7' else: os.environ['MODULE_VERSION_STACK'] = os.environ['MODULE_VERSION'] os.environ['MODULESHOME'] = '/opt/modules/3.2.6.7' if not os.environ.has_key('MODULEPATH'): os.environ['MODULEPATH'] = os.popen("""sed 's/#.*$//' ${MODULESHOME}/init/.modulespath | awk 'NF==1{printf("%s:",$1)}'""").readline() if not os.environ.has_key('LOADEDMODULES'): os.environ['LOADEDMODULES'] = ''; def module(command, *arguments): pipe = subprocess.Popen(['/opt/modules/%s/bin/modulecmd' \ % (os.environ['MODULE_VERSION']), 'python', \ command] + list(arguments), stdout=subprocess.PIPE, stderr=subprocess.PIPE) exec pipe.stdout.read() return pipe.stderr.read()
34.88
141
0.658257
117
872
4.811966
0.384615
0.175844
0.133215
0.195382
0.202487
0.106572
0
0
0
0
0
0.018642
0.138761
872
24
142
36.333333
0.731025
0
0
0
0
0.055556
0.34558
0.098737
0
0
0
0
0
0
null
null
0
0.111111
null
null
0.055556
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
23c22f69d65d4b2230b43270268b45ba2df0f6cc
2,314
py
Python
konduto/api/clients/v1/order.py
ZXVentures/konduto-sdk
1a8151115232c9de4abe1acc6754c593542f2569
[ "MIT" ]
4
2020-04-29T07:53:59.000Z
2021-05-26T20:13:51.000Z
konduto/api/clients/v1/order.py
ZXVentures/konduto-sdk
1a8151115232c9de4abe1acc6754c593542f2569
[ "MIT" ]
7
2020-04-05T08:05:55.000Z
2021-04-07T19:24:15.000Z
konduto/api/clients/v1/order.py
ZXVentures/konduto-sdk
1a8151115232c9de4abe1acc6754c593542f2569
[ "MIT" ]
1
2021-06-15T17:37:20.000Z
2021-06-15T17:37:20.000Z
from datetime import date, datetime from decimal import Decimal from enum import Enum from typing import Union from dacite import from_dict, Config from konduto import KONDUTO_DOMAIN from konduto.api.clients import KondutoHttpClient from konduto.api.resources.konduto_order_status import KondutoOrderStatus from konduto.api.resources.requests.konduto_order_request import KondutoOrderRequest from konduto.api.resources.requests.konduto_order_status_request import KondutoOrderStatusRequest from konduto.api.resources.response.konduto_error import KondutoError from konduto.api.resources.response.konduto_order_response import KondutoOrderResponse, KondutoRecommendation from konduto.infrastructure.either import Right, Left from konduto.infrastructure.parsers import datetime_str_to_datetime, float_to_decimal, date_str_to_date, to_int ENDPOINT = f'{KONDUTO_DOMAIN}v1/orders'.strip('/') class KondutoOrderClient(KondutoHttpClient): def create(self, payload: KondutoOrderRequest) -> Union[Right, Left]: result = self.post(ENDPOINT, payload.json) if result.is_right: response_order = result.value['order'] recommendation = KondutoRecommendation.from_string(response_order['recommendation']) order_response = KondutoOrderResponse(id=response_order['id'], score=response_order['score'], recommendation=recommendation, status=KondutoOrderStatus.from_string(response_order['status'])) return Right(order_response) return result def change_status(self, order_id: str, payload: KondutoOrderStatusRequest) -> Union[Right, Left]: result = self.put(f'{ENDPOINT}/{order_id}', payload.json) return result def load(self, order_id: str) -> Union[Right, Left]: result = self.get(f'{ENDPOINT}/{order_id}') if result.is_right: hooks = {date: date_str_to_date, Decimal: float_to_decimal, datetime: datetime_str_to_datetime, int: to_int} response = from_dict(data_class=KondutoOrderResponse, data=result.value['order'], config=Config(cast=[Enum, int], type_hooks=hooks)) return Right(response) return result
45.372549
114
0.715644
259
2,314
6.200772
0.262548
0.061644
0.052304
0.071606
0.145704
0.100872
0.053549
0
0
0
0
0.000543
0.203544
2,314
50
115
46.28
0.870863
0
0
0.131579
0
0
0.045376
0.028954
0
0
0
0
0
1
0.078947
false
0
0.368421
0
0.605263
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
23c779ac291911cedce74e51cd461b1a3b2ae204
1,310
py
Python
grocers_panel/migrations/0014_auto_20220109_2140.py
delitamakanda/GroceryApp
8b0eeb40197b480598928dd7e95e63ca180c9bf1
[ "MIT" ]
1
2021-05-25T02:46:42.000Z
2021-05-25T02:46:42.000Z
grocers_panel/migrations/0014_auto_20220109_2140.py
delitamakanda/GroceryApp
8b0eeb40197b480598928dd7e95e63ca180c9bf1
[ "MIT" ]
null
null
null
grocers_panel/migrations/0014_auto_20220109_2140.py
delitamakanda/GroceryApp
8b0eeb40197b480598928dd7e95e63ca180c9bf1
[ "MIT" ]
null
null
null
# Generated by Django 3.2.3 on 2022-01-09 21:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('grocers_panel', '0013_remove_shop_ratings'), ] operations = [ migrations.AddField( model_name='meal', name='category', field=models.CharField(choices=[('TR', 'Trier'), ('OF', 'Offres'), ('DI', 'Diététique')], default='TR', max_length=2), ), migrations.AddField( model_name='meal', name='discount_price', field=models.FloatField(blank=True, null=True), ), migrations.AddField( model_name='meal', name='is_active', field=models.BooleanField(default=True), ), migrations.AddField( model_name='meal', name='label', field=models.CharField(choices=[('T', 'Toutes les offres'), ('J', "Jusqu'à 50% de réduction"), ('C', 'Choix de restaurants'), ('P', 'Commandez plus, économisez plus'), ('A', 'Articles gratuits'), ('M', 'Meals Deals')], default='T', max_length=1), ), migrations.AddField( model_name='meal', name='stock_no', field=models.CharField(default=99, max_length=10), ), ]
33.589744
258
0.555725
137
1,310
5.20438
0.583942
0.126227
0.16129
0.189341
0.256662
0.256662
0.109397
0
0
0
0
0.028815
0.284733
1,310
38
259
34.473684
0.732124
0.034351
0
0.46875
1
0
0.203484
0.019002
0
0
0
0
0
1
0
false
0
0.03125
0
0.125
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
23d50365d7ba232a30cdf3453bbbb5adf423f338
217
py
Python
src/lib/searchio/cmd/__init__.py
cgxxv/alfred-searchio
f4a14cbe5350b83d6d962aa993abf01f14b60d33
[ "MIT" ]
304
2015-01-15T08:18:47.000Z
2022-03-31T10:41:52.000Z
src/lib/searchio/cmd/__init__.py
cgxxv/alfred-searchio
f4a14cbe5350b83d6d962aa993abf01f14b60d33
[ "MIT" ]
66
2015-03-14T18:10:36.000Z
2022-03-27T11:33:56.000Z
src/lib/searchio/cmd/__init__.py
cgxxv/alfred-searchio
f4a14cbe5350b83d6d962aa993abf01f14b60d33
[ "MIT" ]
36
2015-04-12T16:50:17.000Z
2022-03-28T09:53:32.000Z
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2016 Dean Jackson <deanishe@deanishe.net> # # MIT Licence. See http://opensource.org/licenses/MIT # # Created on 2016-12-17 # """CLI program sub-commands."""
18.083333
57
0.691244
32
217
4.6875
0.90625
0
0
0
0
0
0
0
0
0
0
0.069149
0.133641
217
11
58
19.727273
0.728723
0.884793
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
23d88761bf0399128d2751e5fe15ec42df388eb3
730
py
Python
tests/mocks.py
AtteqCom/zsl
0d418ef957c9780263b1031dbc59482cd974bc04
[ "MIT" ]
2
2017-05-17T08:08:52.000Z
2019-03-25T00:24:51.000Z
tests/mocks.py
AtteqCom/zsl
0d418ef957c9780263b1031dbc59482cd974bc04
[ "MIT" ]
100
2017-01-11T13:43:11.000Z
2022-02-10T09:27:18.000Z
tests/mocks.py
AtteqCom/zsl
0d418ef957c9780263b1031dbc59482cd974bc04
[ "MIT" ]
1
2017-05-10T10:27:01.000Z
2017-05-10T10:27:01.000Z
from __future__ import absolute_import, division, print_function, unicode_literals from builtins import * import unittest.mock as mock from zsl.service.service import SessionFactory from zsl.testing.db import TestSessionFactory as DbTestTestSessionFactory from zsl.utils.injection_helper import bind def mock_db_session(): mock_sess = mock.MagicMock() def session_holder(): return mock_sess class TestSessionFactory(DbTestTestSessionFactory): def __init__(self): super(TestSessionFactory, self).__init__() self._session_holder = session_holder bind(SessionFactory, to=TestSessionFactory) bind(DbTestTestSessionFactory, to=TestSessionFactory) return mock_sess
29.2
82
0.771233
79
730
6.810127
0.443038
0.039033
0.052045
0
0
0
0
0
0
0
0
0
0.169863
730
24
83
30.416667
0.887789
0
0
0.117647
0
0
0
0
0
0
0
0
0
1
0.176471
false
0
0.352941
0.058824
0.705882
0.058824
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
23ebf14e099d895ec0298ea1fa8cbb1733831e97
1,879
py
Python
tests/importer/test_importer.py
madman-bob/python-custom-imports
e9d6979865bfde5f149a2190d8f2895d333ab219
[ "MIT" ]
null
null
null
tests/importer/test_importer.py
madman-bob/python-custom-imports
e9d6979865bfde5f149a2190d8f2895d333ab219
[ "MIT" ]
1
2020-05-21T02:36:07.000Z
2020-05-21T12:55:24.000Z
tests/importer/test_importer.py
madman-bob/python-custom-imports
e9d6979865bfde5f149a2190d8f2895d333ab219
[ "MIT" ]
null
null
null
import sys from dataclasses import dataclass from unittest import TestCase from custom_imports.importer import Importer, SimpleFinder, SimpleLoader @dataclass class SimpleLocator: fullname: str @dataclass class SimpleModule: value: str = "" def set_value(self, locator): self.value = locator.fullname class TestImporter(TestCase): def setUp(self): finder = SimpleFinder( locate_module=lambda fullname, path, target: SimpleLocator(fullname) ) loader = SimpleLoader( module_type=SimpleModule, load_module=SimpleModule.set_value ) self.importer = Importer(finder=finder, loader=loader) def test_importer(self): importer = self.importer with self.subTest("Module unavailable before registration"), self.assertRaises( ImportError ): import fake_module with self.subTest("Module importable"): importer.register() import fake_module self.assertIsInstance(fake_module, SimpleModule) self.assertEqual("fake_module", fake_module.value) with self.subTest("Module unavailable after deregistration"): del sys.modules["fake_module"] importer.deregister() with self.assertRaises(ImportError): import fake_module def test_importer_context_manager(self): with self.subTest("Module available inside context manager"): with self.importer: import fake_module self.assertIsInstance(fake_module, SimpleModule) self.assertEqual("fake_module", fake_module.value) with self.subTest("Module unavailable outside context manager"): del sys.modules["fake_module"] with self.assertRaises(ImportError): import fake_module
27.632353
87
0.655136
185
1,879
6.52973
0.302703
0.107616
0.062086
0.086921
0.393212
0.328642
0.293046
0.215232
0.215232
0.215232
0
0
0.271421
1,879
67
88
28.044776
0.882396
0
0
0.319149
0
0
0.116551
0
0
0
0
0
0.148936
1
0.085106
false
0
0.446809
0
0.638298
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
23f0ccaaba7eebeb54f929980974ee92f041bf50
5,932
py
Python
Match.py
gregorscholz/Pyke
d256cb8fbbdc5c35daaa064232f345afdcbd0d3b
[ "MIT" ]
null
null
null
Match.py
gregorscholz/Pyke
d256cb8fbbdc5c35daaa064232f345afdcbd0d3b
[ "MIT" ]
null
null
null
Match.py
gregorscholz/Pyke
d256cb8fbbdc5c35daaa064232f345afdcbd0d3b
[ "MIT" ]
null
null
null
import requests import Pyke class Match_History: def __init__(self, puuid: str, region: str = 'europe', start_time: int = None, end_time: int = None, queue: int = None, type: str = None, start: int = 0, count: int = 20) -> None: __json = Match_History.__match_history_data(puuid, region, start_time, end_time, queue, type, start, count) self.match_history = Match_History.__match_history(__json) def __match_history_data(puuid: str, region: str, start_time: int, end_time: int, queue: int, type: str, start: int, count: int): response = requests.get(f'https://{region}.api.riotgames.com/lol/match/v5/matches/by-puuid/{puuid}/ids?startTime={start_time}&endTime={end_time}&queue={queue}&type={type}&start={start}&count={count}&api_key={Pyke.Pyke.token}') response.encoding = 'ISO-8859-1' return response.json() def __match_history(__json): return __json[0] class Match: def __init__(self, id: str, region: str = 'europe') -> None: __json = Match.__match_data() # metadata self.data_version = self.__data_version(__json['metadata']) # Match data version self.match_id = id # Match id self.participants_puuids = self.__participants_puuids(__json['metadata']) # A list of participant PUUIDs # info self.game_creation = self.__game_creation(__json['info']) # Unix timestamp for when the game is created on the game server (i.e., the loading screen) self.game_duration = self.__game_duration(__json['info']) # Prior to patch 11.20, this field returns the game length in milliseconds calculated from gameEndTimestamp - gameStartTimestamp. Post patch 11.20, this field returns the max timePlayed of any participant in the game in seconds, which makes the behavior of this field consistent with that of match-v4. The best way to handling the change in this field is to treat the value as milliseconds if the gameEndTimestamp field isn't in the response and to treat the value as seconds if gameEndTimestamp is in the response. self.game_end_timestamp = self.__game_end_timestamp(__json['info']) # Unix timestamp for when match ends on the game server. This timestamp can occasionally be significantly longer than when the match "ends". The most reliable way of determining the timestamp for the end of the match would be to add the max time played of any participant to the gameStartTimestamp. This field was added to match-v5 in patch 11.20 on Oct 5th, 2021. self.game_id = self.__game_id(__json['info']) # self.game_mode = self.__game_mode(__json['info']) # Refer to the Game Constants documentation self.game_name = self.__game_name(__json['info']) # self.game_start_timestamp = self.__game_start_timestamp(__json['info']) # Unix timestamp for when match starts on the game server self.game_type = self.__game_type(__json['info']) # self.game_version = self.__game_version(__json['info']) # The first two parts can be used to determine the patch a game was played on self.map_id = self.__map_id(__json['info']) # Refer to the Game Constants documentation self.participants = self.__participants(__json['info']) # self.platform_id = self.__platform_id(__json['info']) # Platform where the match was played self.queue_id = self.__queue_id(__json['info']) # Refer to the Game Constants documentation self.teams = self.__teams(__json['info']) # self.tournament_code = self.__tournament_code(__json['info']) # Tournament code used to generate the match. This field was added to match-v5 in patch 11.13 on June 23rd, 2021 def __match_data(id: str, region): response = requests.get(f'https://{region}.api.riotgames.com/lol/match/v5/matches/{id}?api_key={Pyke.Pyke.token}') response.encoding = 'ISO-8859-1' return response.json() # metadata def __data_version(__json): return __json['dataVersion'] def __participants_puuids(__json): return __json['participants'] # info def __game_creation(__json): return __json['gameCreation'] def __game_duration(__json): return __json['gameDuration'] def __game_end_timestamp(__json): return __json['gameEndTimestamp'] def __game_id(__json): return __json['gameId'] def __game_mode(__json): return __json['gameMode'] def __game_name(__json): return __json['gameName'] def __game_start_timestamp(__json): return __json['gameStartTimestamp'] def __game_type(__json): return __json['gameType'] def __game_version(__json): return __json['gameVersion'] def __map_id(__json): return __json['mapId'] def __participants(__json): return __json['participants'] def __platform_id(__json): return __json['platformId'] def __queue_id(__json): return __json['queueId'] def __teams(__json): return __json['teams'] def __tournament_code(__json): return __json['tournamentCode']
58.156863
603
0.601483
695
5,932
4.739568
0.230216
0.054645
0.076503
0.019429
0.202793
0.192471
0.183971
0.16697
0.141469
0.126897
0
0.011263
0.311531
5,932
102
604
58.156863
0.795299
0.245954
0
0.084507
0
0.028169
0.127387
0
0
0
0
0
0
1
0.309859
false
0
0.028169
0.253521
0.647887
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
23f966facd3757ae3ae22a169b418e72c9f65645
313
py
Python
primeira_lista/ex010.py
PedroSantana2/exercicios-em-python
e0a98e699ba49873f67438fd9092dc3ab0ca719c
[ "MIT" ]
1
2021-03-16T03:58:39.000Z
2021-03-16T03:58:39.000Z
primeira_lista/ex010.py
PedroSantana2/exercicios-em-python
e0a98e699ba49873f67438fd9092dc3ab0ca719c
[ "MIT" ]
null
null
null
primeira_lista/ex010.py
PedroSantana2/exercicios-em-python
e0a98e699ba49873f67438fd9092dc3ab0ca719c
[ "MIT" ]
null
null
null
''' Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre em graus Fahrenheit. ''' temperatura = float(input('Digite a temperatura em graus Celsius: ')) fahrenheit = temperatura * 9 / 5 + 32 print('{:.1f} graus Celsius equivale a {:.1f} graus Fahrenheit!'.format(temperatura, fahrenheit))
44.714286
98
0.738019
42
313
5.5
0.571429
0.090909
0.121212
0.164502
0.225108
0
0
0
0
0
0
0.022388
0.14377
313
6
99
52.166667
0.839552
0.313099
0
0
0
0
0.458937
0
0
0
0
0
0
1
0
false
0
0
0
0
0.333333
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
9b1493fcb9c0b6a2b3303a0b419765613bd404ef
1,211
py
Python
tests/sources_test.py
otienotimothy/news-arc
00b2ba82125571653f356a5d671af63c1b295ed3
[ "MIT" ]
null
null
null
tests/sources_test.py
otienotimothy/news-arc
00b2ba82125571653f356a5d671af63c1b295ed3
[ "MIT" ]
null
null
null
tests/sources_test.py
otienotimothy/news-arc
00b2ba82125571653f356a5d671af63c1b295ed3
[ "MIT" ]
null
null
null
import unittest from app.models import News_Source class News_sourcesTest(unittest.TestCase): ''' Test Class to test the behaviour of the New Source Class ''' def setUp(self): ''' Set up method that will run before every Test ''' self.news_source = News_Source("abc-news", "ABC News", 'Your trusted source for breaking news and analysis', "en", "https://abcnews.go.com", "us") def test_instance(self): ''' Test that the instance created was created from the News_Source class ''' self.assertTrue(isinstance(self.news_source, News_Source)) def test_attr(self): ''' Test that the instance were created correctly ''' self.assertEqual(self.news_source.id, "abc-news") self.assertEqual(self.news_source.name, "ABC News") self.assertEqual(self.news_source.description, 'Your trusted source for breaking news and analysis') self.assertEqual(self.news_source.language, "en") self.assertEqual(self.news_source.url, "https://abcnews.go.com") self.assertEqual(self.news_source.country, "us")
35.617647
116
0.625103
148
1,211
5.013514
0.371622
0.161725
0.150943
0.185984
0.495957
0.212938
0.212938
0.115903
0
0
0
0
0.270851
1,211
33
117
36.69697
0.840317
0.180017
0
0
0
0
0.202643
0
0
0
0
0
0.4375
1
0.1875
false
0
0.125
0
0.375
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
1
0
0
0
0
0
0
0
0
0
2
9b1814ba51a6041ee546b15ac68bd3132c1fbef2
2,123
py
Python
menger/measure.py
bertrandchenal/menger
090ce7a6b893305c4a356b3cc6dc007162903be1
[ "MIT" ]
null
null
null
menger/measure.py
bertrandchenal/menger
090ce7a6b893305c4a356b3cc6dc007162903be1
[ "MIT" ]
null
null
null
menger/measure.py
bertrandchenal/menger
090ce7a6b893305c4a356b3cc6dc007162903be1
[ "MIT" ]
null
null
null
import locale class Measure(object): def __init__(self, label, type=float): self.label = label self.name = None self.type = type def format(self, value, fmt_type=None): if self.type == float: return locale.format('%.2f', value) return self.type(value) def aggregator(self): total = 0 while True: new_value = yield if new_value is None: yield total return total += new_value def __hash__(self): return hash(self.name) def __eq__(self, other): return self.name == other.name def __repr__(self): return '<Measure %s>' % self.name class Sum(Measure): def __init__(self, label, type=float): super(Sum, self).__init__(label, type=type) if self.type == int: self.sql_type = 'integer' elif self.type == float: self.sql_type = 'float' else: raise Exception('Type %s not supported for dimension %s' % ( type, label )) def increment(self, old_value, new_value): return old_value + new_value def clone(self): return Sum(self.label, self.type) class Computed(Measure): def __init__(self, label, *args): self.args = args super(Computed, self).__init__(label) def compute(self, *args): raise NotImplementedError class Average(Computed): def compute(self, total, count): if count == 0: return 0 return total / count def aggregator(self): cnt = 0 total = 0 while True: new_value = yield if new_value is None: yield cnt if cnt == 0 else total / cnt return total += new_value cnt += 1 def clone(self): return Average(self.label, *self.args) class Difference(Computed): def compute(self, first_msr, second_msr): return first_msr - second_msr def clone(self): return Difference(self.label, *self.args)
22.827957
72
0.552991
252
2,123
4.464286
0.238095
0.056889
0.029333
0.042667
0.158222
0.131556
0.087111
0.087111
0.087111
0.087111
0
0.00581
0.35139
2,123
92
73
23.076087
0.811184
0
0
0.283582
0
0
0.031088
0
0
0
0
0
0
1
0.238806
false
0
0.014925
0.119403
0.537313
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
9b1e1857ae23cefd1b89eda5cdf9c4c03d773fc0
2,623
py
Python
buttons.py
docputs/BRCoronavirusBot
7c0b8c616d5890ca0df68368f0033f3b7ce818fa
[ "MIT" ]
1
2020-06-05T13:54:45.000Z
2020-06-05T13:54:45.000Z
buttons.py
docputs/BRCoronavirusBot
7c0b8c616d5890ca0df68368f0033f3b7ce818fa
[ "MIT" ]
null
null
null
buttons.py
docputs/BRCoronavirusBot
7c0b8c616d5890ca0df68368f0033f3b7ce818fa
[ "MIT" ]
1
2020-06-04T08:57:30.000Z
2020-06-04T08:57:30.000Z
from telebot import types as t class Buttons: botoes = t.ReplyKeyboardMarkup(row_width=1) botao1 = t.KeyboardButton('Dados recentes') botao2 = t.KeyboardButton('Dados por estado') botao3 = t.KeyboardButton('Dados por cidade') botoes.add(botao1, botao2, botao3) class Estados: estados = t.InlineKeyboardMarkup(row_width=5) AC = t.InlineKeyboardButton('AC', callback_data='AC') AL = t.InlineKeyboardButton('AL', callback_data='AL') AP = t.InlineKeyboardButton('AP', callback_data='AP') AM = t.InlineKeyboardButton('AM', callback_data='AM') BA = t.InlineKeyboardButton('BA', callback_data='BA') CE = t.InlineKeyboardButton('CE', callback_data='CE') DF = t.InlineKeyboardButton('DF', callback_data='DF') ES = t.InlineKeyboardButton('ES', callback_data='ES') GO = t.InlineKeyboardButton('GO', callback_data='GO') MA = t.InlineKeyboardButton('MA', callback_data='MA') MT = t.InlineKeyboardButton('MT', callback_data='MT') MS = t.InlineKeyboardButton('MS', callback_data='MS') MG = t.InlineKeyboardButton('MG', callback_data='MG') PA = t.InlineKeyboardButton('PA', callback_data='PA') PB = t.InlineKeyboardButton('PB', callback_data='PB') PR = t.InlineKeyboardButton('PR', callback_data='PR') PE = t.InlineKeyboardButton('PE', callback_data='PE') PI = t.InlineKeyboardButton('PI', callback_data='PI') RJ = t.InlineKeyboardButton('RJ', callback_data='RJ') RN = t.InlineKeyboardButton('RN', callback_data='RN') RS = t.InlineKeyboardButton('RS', callback_data='RS') RO = t.InlineKeyboardButton('RO', callback_data='RO') RR = t.InlineKeyboardButton('RR', callback_data='RR') SC = t.InlineKeyboardButton('SC', callback_data='SC') SP = t.InlineKeyboardButton('SP', callback_data='SP') SE = t.InlineKeyboardButton('SE', callback_data='SE') TO = t.InlineKeyboardButton('TO', callback_data='TO') SIGLAS = t.InlineKeyboardButton('SIGLAS', callback_data='SIGLAS') estados.row(AC, AL, AP, AM, BA) estados.row(CE, DF, ES, GO, MA) estados.row(MT, MS, MG, PA, PB) estados.row(PR, PE, PI, RJ, RN) estados.row(RS, RO, RR, SC, SP) estados.row(SE, TO, SIGLAS) class CidadeRepetida: def __init__(self, uf, cidade): self.uf = uf self.markup = t.InlineKeyboardMarkup() self.cont = len(uf) self.cid = cidade @property def reply_markup(self): buttons = [ self.markup.add( t.InlineKeyboardButton(f'{self.cid} ({uf})', callback_data=f'{self.cid}*{uf}')) for uf in self.uf ] return self.markup
40.984375
113
0.664506
330
2,623
5.172727
0.218182
0.356766
0.035149
0.026948
0
0
0
0
0
0
0
0.003717
0.179565
2,623
63
114
41.634921
0.789498
0
0
0
0
0
0.075486
0
0
0
0
0
0
1
0.035714
false
0
0.017857
0
0.714286
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
f1b426acfaecc71f7f944e0f84827eaedb830b4a
629
py
Python
hse_de_project/DEMethod.py
kekekekule/Differential-equations-project
51c7e2324f06c7900ba821f09d6c9523c5346555
[ "MIT" ]
null
null
null
hse_de_project/DEMethod.py
kekekekule/Differential-equations-project
51c7e2324f06c7900ba821f09d6c9523c5346555
[ "MIT" ]
null
null
null
hse_de_project/DEMethod.py
kekekekule/Differential-equations-project
51c7e2324f06c7900ba821f09d6c9523c5346555
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import sys sys.path.append(".") import sympy from sympy.abc import x, y class DESolveMethod: def __init__(self): pass def solve(self, *args): raise NotImplementedError('Method not determined.') def __str__(self): return 'Differential equation solve method.' def support_lambda(solve_function): def wrapper(*args): func = args[1] if isinstance(func, tuple(sympy.core.all_classes)): func = sympy.utilities.lambdify([x, y], func) args = list(args) args[1] = func return solve_function(*args) return wrapper
22.464286
59
0.63752
78
629
4.987179
0.576923
0.010283
0
0
0
0
0
0
0
0
0
0.006369
0.251192
629
27
60
23.296296
0.819533
0.033386
0
0
0
0
0.095552
0
0
0
0
0
0
1
0.25
false
0.05
0.15
0.05
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
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
f1c77d22f404ea91482e8356116c705ddd052dad
248
py
Python
oop/data-hiding.py
sinhdev/python-demo
77e97d01d853799aef9a71cd6b7892847f85727d
[ "MIT" ]
null
null
null
oop/data-hiding.py
sinhdev/python-demo
77e97d01d853799aef9a71cd6b7892847f85727d
[ "MIT" ]
null
null
null
oop/data-hiding.py
sinhdev/python-demo
77e97d01d853799aef9a71cd6b7892847f85727d
[ "MIT" ]
null
null
null
#!/usr/bin/python class JustCounter: __secret_count = 0 def count(self): self.__secret_count += 1 print(self.__secret_count) counter = JustCounter() counter.count() counter.count() # can't access print(counter.__secret_count)
17.714286
32
0.705645
32
248
5.09375
0.5
0.269939
0.184049
0
0
0
0
0
0
0
0
0.009756
0.173387
248
14
33
17.714286
0.785366
0.116935
0
0.222222
0
0
0
0
0
0
0
0
0
1
0.111111
false
0
0
0
0.333333
0.222222
0
0
0
null
1
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
0
0
0
0
0
0
0
0
2
f1c7e7076f4083409b97ca9e30980a5ee437cf93
155
py
Python
AtCoder/ABC/160-169/ABC163_C.py
sireline/PyCode
8578467710c3c1faa89499f5d732507f5d9a584c
[ "MIT" ]
null
null
null
AtCoder/ABC/160-169/ABC163_C.py
sireline/PyCode
8578467710c3c1faa89499f5d732507f5d9a584c
[ "MIT" ]
null
null
null
AtCoder/ABC/160-169/ABC163_C.py
sireline/PyCode
8578467710c3c1faa89499f5d732507f5d9a584c
[ "MIT" ]
null
null
null
N = int(input()) A = [int(n) for n in input().split()] ans = [0] + [0]*N for i in range(N-1): ans[A[i]] += 1 for i in range(1, N+1): print(ans[i])
19.375
37
0.503226
35
155
2.228571
0.371429
0.102564
0.153846
0.282051
0
0
0
0
0
0
0
0.05042
0.232258
155
7
38
22.142857
0.605042
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0.142857
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
f1d05a20c34a194d6b031a53807bc56fd3ecc1f7
1,778
py
Python
src/nodes/data_viz.py
alitaca/Projeto_final
ba915bb8075d1bf9dd552fe93cfb9b19f71237a7
[ "RSA-MD" ]
null
null
null
src/nodes/data_viz.py
alitaca/Projeto_final
ba915bb8075d1bf9dd552fe93cfb9b19f71237a7
[ "RSA-MD" ]
null
null
null
src/nodes/data_viz.py
alitaca/Projeto_final
ba915bb8075d1bf9dd552fe93cfb9b19f71237a7
[ "RSA-MD" ]
null
null
null
import logging import pandas as pd logger = logging.getLogger('nodes.data_viz') def update(client, params): ''' Esta funcao faz extracao de dados no database e salva os dados extraidos em arquivo csv. Parameters ---------- client : class parametros de conexao da pipeline. params : class parametros da pipeline. Returns ------- None. ''' # Construindo query query = ''' SELECT MIN(data) AS data, ano, mes, semana, CASE WHEN pass_bus.fim_de_semana = 0 THEN 'dia de semana' ELSE 'fim de semana' END AS fim_de_semana, tipo, area, pass_bus.n_linha, desc_linha, SUM(pagantes_dinheiro) AS pagantes_dinheiro, SUM(pagantes_bu_e_vt) AS pagantes_bu_e_vt, SUM(pagantes_estudantes) AS pagantes_estudantes, SUM(total_estudantes) AS total_estudantes, SUM(passageiros_pagantes) AS passageiros_pagantes, SUM(gratuidades_outras) AS gratuidades_outras, SUM(integracao_onibus) AS integracao_onibus, SUM(total_passageiros) AS total_passageiros, AVG(extensao_ida) AS extensao_ida, AVG(extensao_volta) AS extensao_volta, SUM(partidas_ida) AS partidas_ida, SUM(partidas_volta) AS partidas_volta FROM passageiros_onibus AS pass_bus LEFT JOIN linha ON linha.n_linha = pass_bus.n_linha AND linha.fim_de_semana = pass_bus.fim_de_semana GROUP BY ano, mes, semana, pass_bus.fim_de_semana, tipo, area, pass_bus.n_linha, desc_linha''' # Extraindo tabela do SQL onibus = pd.read_sql(query, con=client.conn) # Salvando resultado em csv onibus.to_csv(params.processed_data+r'\\onibus.csv', index=False) def done(client, params): if params.viz == True: return False else: return True
35.56
108
0.692913
248
1,778
4.741935
0.407258
0.041667
0.056122
0.030612
0.116497
0.10119
0.069728
0.069728
0.069728
0.069728
0
0.000726
0.224972
1,778
50
109
35.56
0.852685
0.170979
0
0
0
0.08
0.737994
0.189266
0
0
0
0
0
1
0.08
false
0.32
0.08
0
0.24
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
f1dce76aa187223a0987586b7b10977e79592fce
1,036
py
Python
application/migrations/0020_auto_20210509_1659.py
geeksforsocialchange/imok
efb7189c13c398dbd5d4301ca496a2e583b0f5b7
[ "MIT" ]
6
2021-05-12T08:40:36.000Z
2022-01-25T08:31:06.000Z
application/migrations/0020_auto_20210509_1659.py
geeksforsocialchange/imok
efb7189c13c398dbd5d4301ca496a2e583b0f5b7
[ "MIT" ]
14
2021-05-12T09:03:08.000Z
2021-06-10T13:18:52.000Z
application/migrations/0020_auto_20210509_1659.py
geeksforsocialchange/imok
efb7189c13c398dbd5d4301ca496a2e583b0f5b7
[ "MIT" ]
1
2021-05-14T20:54:15.000Z
2021-05-14T20:54:15.000Z
# Generated by Django 3.2.2 on 2021-05-09 15:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('application', '0019_alter_member_telegram_username'), ] operations = [ migrations.RemoveField( model_name='member', name='is_warning', ), migrations.AddField( model_name='member', name='overdue_message_sent_at', field=models.DateTimeField(null=True), ), migrations.AddField( model_name='member', name='sos_alert_received_at', field=models.DateTimeField(null=True), ), migrations.AddField( model_name='member', name='warning_message_sent_at', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='member', name='is_ok', field=models.BooleanField(default=True, verbose_name='Is safe'), ), ]
27.263158
76
0.573359
100
1,036
5.73
0.49
0.078534
0.13089
0.165794
0.500873
0.427574
0.363002
0.363002
0.363002
0.247819
0
0.026836
0.316602
1,036
37
77
28
0.782486
0.043436
0
0.516129
1
0
0.166835
0.103134
0
0
0
0
0
1
0
false
0
0.032258
0
0.129032
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
f1eaeef6d4704f3dd4ae7d087c7ccca70285e004
28,800
py
Python
tests/test_landsat_c2.py
cogeotiff/rio-tiler-pds
52482c80baf7fd26cf06cd2af2961cca396b20e0
[ "BSD-3-Clause" ]
30
2020-07-21T23:32:14.000Z
2022-02-21T23:35:35.000Z
tests/test_landsat_c2.py
cogeotiff/rio-tiler-pds
52482c80baf7fd26cf06cd2af2961cca396b20e0
[ "BSD-3-Clause" ]
36
2020-07-21T20:48:51.000Z
2021-10-06T08:15:00.000Z
tests/test_landsat_c2.py
cogeotiff/rio-tiler-pds
52482c80baf7fd26cf06cd2af2961cca396b20e0
[ "BSD-3-Clause" ]
4
2020-07-23T06:19:30.000Z
2021-11-18T03:27:04.000Z
from pathlib import Path from unittest.mock import patch import numpy import pytest import rasterio from rio_tiler.errors import InvalidBandName, MissingBands, TileOutsideBounds from rio_tiler_pds.errors import InvalidLandsatSceneId from rio_tiler_pds.landsat.aws import LandsatC2Reader from rio_tiler_pds.landsat.utils import ( ETM_L1_BANDS, MSS_L1_BANDS, OLI_L1_BANDS, OLI_L1_QA_BANDS, OLI_SR_BANDS, TIRS_L1_BANDS, TIRS_L1_QA_BANDS, TIRS_ST_BANDS, TM_L1_BANDS, TM_SR_BANDS, TM_ST_BANDS, sceneid_parser, ) # sceneid,expected_content LANDSAT_SCENE_PARSER_TEST_CASES = ( # Collection 2 Level 2 OLI-TIRS 8 SP (both SR and ST) ( "LC08_L2SP_001062_20201031_20201106_02_T2", { "sensor": "C", "satellite": "08", "processingCorrectionLevel": "L2SP", "path": "001", "row": "062", "acquisitionYear": "2020", "acquisitionMonth": "10", "acquisitionDay": "31", "processingYear": "2020", "processingMonth": "11", "processingDay": "06", "collectionNumber": "02", "collectionCategory": "T2", "scene": "LC08_L2SP_001062_20201031_20201106_02_T2", "date": "2020-10-31", "_processingLevelNum": "2", "sensor_name": "oli-tirs", "_sensor_s3_prefix": "oli-tirs", "bands": OLI_SR_BANDS + TIRS_ST_BANDS, "category": "standard", }, ), # Collection 2 Level 2 OLI-TIRS 8 SR (no ST) ( "LC08_L2SR_122108_20201031_20201106_02_T2", { "sensor": "C", "satellite": "08", "processingCorrectionLevel": "L2SR", "path": "122", "row": "108", "acquisitionYear": "2020", "acquisitionMonth": "10", "acquisitionDay": "31", "processingYear": "2020", "processingMonth": "11", "processingDay": "06", "collectionNumber": "02", "collectionCategory": "T2", "scene": "LC08_L2SR_122108_20201031_20201106_02_T2", "date": "2020-10-31", "_processingLevelNum": "2", "sensor_name": "oli-tirs", "_sensor_s3_prefix": "oli-tirs", "bands": OLI_SR_BANDS, "category": "standard", }, ), # Collection 2 Level 2 TM SP (both SR and ST) ( "LT05_L2SP_014032_20111018_20200820_02_T1", { "sensor": "T", "satellite": "05", "processingCorrectionLevel": "L2SP", "path": "014", "row": "032", "acquisitionYear": "2011", "acquisitionMonth": "10", "acquisitionDay": "18", "processingYear": "2020", "processingMonth": "08", "processingDay": "20", "collectionNumber": "02", "collectionCategory": "T1", "scene": "LT05_L2SP_014032_20111018_20200820_02_T1", "date": "2011-10-18", "_processingLevelNum": "2", "sensor_name": "tm", "_sensor_s3_prefix": "tm", "bands": TM_SR_BANDS + TM_ST_BANDS, "category": "standard", }, ), # Collection 2 Level 2 TM SR (no ST) ( "LT05_L2SR_089076_20110929_20200820_02_T2", { "sensor": "T", "satellite": "05", "processingCorrectionLevel": "L2SR", "path": "089", "row": "076", "acquisitionYear": "2011", "acquisitionMonth": "09", "acquisitionDay": "29", "processingYear": "2020", "processingMonth": "08", "processingDay": "20", "collectionNumber": "02", "collectionCategory": "T2", "scene": "LT05_L2SR_089076_20110929_20200820_02_T2", "date": "2011-09-29", "_processingLevelNum": "2", "sensor_name": "tm", "_sensor_s3_prefix": "tm", "bands": TM_SR_BANDS, "category": "standard", }, ), # Collection 2 Level 2 ETM SP (both SR and ST) ( "LE07_L2SP_175066_20201026_20201121_02_T1", { "sensor": "E", "satellite": "07", "processingCorrectionLevel": "L2SP", "path": "175", "row": "066", "acquisitionYear": "2020", "acquisitionMonth": "10", "acquisitionDay": "26", "processingYear": "2020", "processingMonth": "11", "processingDay": "21", "collectionNumber": "02", "collectionCategory": "T1", "scene": "LE07_L2SP_175066_20201026_20201121_02_T1", "date": "2020-10-26", "_processingLevelNum": "2", "sensor_name": "etm", "_sensor_s3_prefix": "etm", "bands": TM_SR_BANDS + TM_ST_BANDS, "category": "standard", }, ), # Collection 2 Level 2 ETM SR (no ST) ( "LE07_L2SR_123067_20201030_20201126_02_T1", { "sensor": "E", "satellite": "07", "processingCorrectionLevel": "L2SR", "path": "123", "row": "067", "acquisitionYear": "2020", "acquisitionMonth": "10", "acquisitionDay": "30", "processingYear": "2020", "processingMonth": "11", "processingDay": "26", "collectionNumber": "02", "collectionCategory": "T1", "scene": "LE07_L2SR_123067_20201030_20201126_02_T1", "date": "2020-10-30", "_processingLevelNum": "2", "sensor_name": "etm", "_sensor_s3_prefix": "etm", "bands": TM_SR_BANDS, "category": "standard", }, ), # Collection 2 Level 1 OLI, L1GT ( "LO08_L1GT_108030_20201114_20201119_02_T2", { "sensor": "O", "satellite": "08", "processingCorrectionLevel": "L1GT", "path": "108", "row": "030", "acquisitionYear": "2020", "acquisitionMonth": "11", "acquisitionDay": "14", "processingYear": "2020", "processingMonth": "11", "processingDay": "19", "collectionNumber": "02", "collectionCategory": "T2", "scene": "LO08_L1GT_108030_20201114_20201119_02_T2", "date": "2020-11-14", "_processingLevelNum": "1", "sensor_name": "oli", "_sensor_s3_prefix": "oli-tirs", "bands": OLI_L1_BANDS + OLI_L1_QA_BANDS, "category": "standard", }, ), # Collection 2 Level 1 OLI, L1TP ( "LO08_L1TP_108070_20201114_20201119_02_T1", { "sensor": "O", "satellite": "08", "processingCorrectionLevel": "L1TP", "path": "108", "row": "070", "acquisitionYear": "2020", "acquisitionMonth": "11", "acquisitionDay": "14", "processingYear": "2020", "processingMonth": "11", "processingDay": "19", "collectionNumber": "02", "collectionCategory": "T1", "scene": "LO08_L1TP_108070_20201114_20201119_02_T1", "date": "2020-11-14", "_processingLevelNum": "1", "sensor_name": "oli", "_sensor_s3_prefix": "oli-tirs", "bands": OLI_L1_BANDS + OLI_L1_QA_BANDS, "category": "standard", }, ), # Collection 2 Level 1 OLI-TIRS, L1GT ( "LC08_L1GT_229113_20201129_20201211_02_T2", { "sensor": "C", "satellite": "08", "processingCorrectionLevel": "L1GT", "path": "229", "row": "113", "acquisitionYear": "2020", "acquisitionMonth": "11", "acquisitionDay": "29", "processingYear": "2020", "processingMonth": "12", "processingDay": "11", "collectionNumber": "02", "collectionCategory": "T2", "scene": "LC08_L1GT_229113_20201129_20201211_02_T2", "date": "2020-11-29", "_processingLevelNum": "1", "sensor_name": "oli-tirs", "_sensor_s3_prefix": "oli-tirs", "bands": OLI_L1_BANDS + TIRS_L1_BANDS + OLI_L1_QA_BANDS, "category": "standard", }, ), # Collection 2 Level 1 OLI-TIRS, L1TP ( "LC08_L1TP_092017_20201129_20201210_02_T1", { "sensor": "C", "satellite": "08", "processingCorrectionLevel": "L1TP", "path": "092", "row": "017", "acquisitionYear": "2020", "acquisitionMonth": "11", "acquisitionDay": "29", "processingYear": "2020", "processingMonth": "12", "processingDay": "10", "collectionNumber": "02", "collectionCategory": "T1", "scene": "LC08_L1TP_092017_20201129_20201210_02_T1", "date": "2020-11-29", "_processingLevelNum": "1", "sensor_name": "oli-tirs", "_sensor_s3_prefix": "oli-tirs", "bands": OLI_L1_BANDS + TIRS_L1_BANDS + OLI_L1_QA_BANDS, "category": "standard", }, ), # Collection 2 Level 1 TIRS, L1GT ( "LT08_L1GT_019213_20201130_20201210_02_T2", { "sensor": "T", "satellite": "08", "processingCorrectionLevel": "L1GT", "path": "019", "row": "213", "acquisitionYear": "2020", "acquisitionMonth": "11", "acquisitionDay": "30", "processingYear": "2020", "processingMonth": "12", "processingDay": "10", "collectionNumber": "02", "collectionCategory": "T2", "scene": "LT08_L1GT_019213_20201130_20201210_02_T2", "date": "2020-11-30", "_processingLevelNum": "1", "sensor_name": "tirs", "_sensor_s3_prefix": "oli-tirs", "bands": TIRS_L1_BANDS + TIRS_L1_QA_BANDS, "category": "standard", }, ), # Collection 2 Level 1 ETM, L1GS ( "LE07_L1GS_189036_20201129_20201129_02_RT", { "sensor": "E", "satellite": "07", "processingCorrectionLevel": "L1GS", "path": "189", "row": "036", "acquisitionYear": "2020", "acquisitionMonth": "11", "acquisitionDay": "29", "processingYear": "2020", "processingMonth": "11", "processingDay": "29", "collectionNumber": "02", "collectionCategory": "RT", "scene": "LE07_L1GS_189036_20201129_20201129_02_RT", "date": "2020-11-29", "_processingLevelNum": "1", "sensor_name": "etm", "_sensor_s3_prefix": "etm", "bands": ETM_L1_BANDS, "category": "standard", }, ), # Collection 2 Level 1 ETM, L1GT ( "LE07_L1GT_023046_20201204_20201206_02_RT", { "sensor": "E", "satellite": "07", "processingCorrectionLevel": "L1GT", "path": "023", "row": "046", "acquisitionYear": "2020", "acquisitionMonth": "12", "acquisitionDay": "04", "processingYear": "2020", "processingMonth": "12", "processingDay": "06", "collectionNumber": "02", "collectionCategory": "RT", "scene": "LE07_L1GT_023046_20201204_20201206_02_RT", "date": "2020-12-04", "_processingLevelNum": "1", "sensor_name": "etm", "_sensor_s3_prefix": "etm", "bands": ETM_L1_BANDS, "category": "standard", }, ), # Collection 2 Level 1 ETM, L1TP ( "LE07_L1TP_030042_20201205_20201205_02_RT", { "sensor": "E", "satellite": "07", "processingCorrectionLevel": "L1TP", "path": "030", "row": "042", "acquisitionYear": "2020", "acquisitionMonth": "12", "acquisitionDay": "05", "processingYear": "2020", "processingMonth": "12", "processingDay": "05", "collectionNumber": "02", "collectionCategory": "RT", "scene": "LE07_L1TP_030042_20201205_20201205_02_RT", "date": "2020-12-05", "_processingLevelNum": "1", "sensor_name": "etm", "_sensor_s3_prefix": "etm", "bands": ETM_L1_BANDS, "category": "standard", }, ), # Collection 2 Level 1 TM, L1GS ( "LT05_L1GS_127054_20111111_20200820_02_T2", { "sensor": "T", "satellite": "05", "processingCorrectionLevel": "L1GS", "path": "127", "row": "054", "acquisitionYear": "2011", "acquisitionMonth": "11", "acquisitionDay": "11", "processingYear": "2020", "processingMonth": "08", "processingDay": "20", "collectionNumber": "02", "collectionCategory": "T2", "scene": "LT05_L1GS_127054_20111111_20200820_02_T2", "date": "2011-11-11", "_processingLevelNum": "1", "sensor_name": "tm", "_sensor_s3_prefix": "tm", "bands": TM_L1_BANDS, "category": "standard", }, ), # Collection 2 Level 1 TM, L1TP ( "LT05_L1TP_014032_20111018_20200820_02_T1", { "sensor": "T", "satellite": "05", "processingCorrectionLevel": "L1TP", "path": "014", "row": "032", "acquisitionYear": "2011", "acquisitionMonth": "10", "acquisitionDay": "18", "processingYear": "2020", "processingMonth": "08", "processingDay": "20", "collectionNumber": "02", "collectionCategory": "T1", "scene": "LT05_L1TP_014032_20111018_20200820_02_T1", "date": "2011-10-18", "_processingLevelNum": "1", "sensor_name": "tm", "_sensor_s3_prefix": "tm", "bands": TM_L1_BANDS, "category": "standard", }, ), # Collection 2 Level 1 MSS, L1GS ( "LM05_L1GS_176025_20120901_20200820_02_T2", { "sensor": "M", "satellite": "05", "processingCorrectionLevel": "L1GS", "path": "176", "row": "025", "acquisitionYear": "2012", "acquisitionMonth": "09", "acquisitionDay": "01", "processingYear": "2020", "processingMonth": "08", "processingDay": "20", "collectionNumber": "02", "collectionCategory": "T2", "scene": "LM05_L1GS_176025_20120901_20200820_02_T2", "date": "2012-09-01", "_processingLevelNum": "1", "sensor_name": "mss", "_sensor_s3_prefix": "mss", "bands": MSS_L1_BANDS, "category": "standard", }, ), # Collection 2 Level 1 MSS, L1TP ( "LM05_L1TP_015032_20121230_20200820_02_T2", { "sensor": "M", "satellite": "05", "processingCorrectionLevel": "L1TP", "path": "015", "row": "032", "acquisitionYear": "2012", "acquisitionMonth": "12", "acquisitionDay": "30", "processingYear": "2020", "processingMonth": "08", "processingDay": "20", "collectionNumber": "02", "collectionCategory": "T2", "scene": "LM05_L1TP_015032_20121230_20200820_02_T2", "date": "2012-12-30", "_processingLevelNum": "1", "sensor_name": "mss", "_sensor_s3_prefix": "mss", "bands": MSS_L1_BANDS, "category": "standard", }, ), # Collection 2 Level2 Albers ( "LC08_L2SP_077010_20210616_20210623_02_A1", { "sensor": "C", "satellite": "08", "processingCorrectionLevel": "L2SP", "path": "077", "row": "010", "acquisitionYear": "2021", "acquisitionMonth": "06", "acquisitionDay": "16", "processingYear": "2021", "processingMonth": "06", "processingDay": "23", "collectionNumber": "02", "collectionCategory": "A1", "scene": "LC08_L2SP_077010_20210616_20210623_02_A1", "date": "2021-06-16", "_processingLevelNum": "2", "sensor_name": "oli-tirs", "_sensor_s3_prefix": "oli-tirs", "bands": OLI_SR_BANDS + TIRS_ST_BANDS, "category": "albers", }, ), ) @pytest.mark.parametrize("sceneid,expected_content", LANDSAT_SCENE_PARSER_TEST_CASES) def test_landsat_sceneid_parser(sceneid, expected_content): """Parse landsat valid collection1 sceneid and return metadata.""" assert sceneid_parser(sceneid) == expected_content LANDSAT_SCENE_C2 = "LC08_L2SP_001062_20201031_20201106_02_T2" LANDSAT_BUCKET = Path(__file__).resolve().parent / "fixtures" / "usgs-landsat" LANDSAT_PATH = ( LANDSAT_BUCKET / "collection02" / "level-2" / "standard" / "oli-tirs" / "2020" / "001" / "062" / LANDSAT_SCENE_C2 ) INVALID_LANDSAT_SCENE_C2 = "LC08_001062_20201031_20201106_02_T2" with open(LANDSAT_PATH / f"{LANDSAT_SCENE_C2}_SR_stac.json", "r") as f: LANDSAT_METADATA = f.read().encode("utf-8") @pytest.fixture(autouse=True) def testing_env_var(monkeypatch): """Set fake env to make sure we don't hit AWS services.""" monkeypatch.setenv("AWS_ACCESS_KEY_ID", "jqt") monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "rde") monkeypatch.delenv("AWS_PROFILE", raising=False) monkeypatch.setenv("AWS_CONFIG_FILE", "/tmp/noconfigheere") monkeypatch.setenv("AWS_SHARED_CREDENTIALS_FILE", "/tmp/noconfighereeither") monkeypatch.setenv("GDAL_DISABLE_READDIR_ON_OPEN", "TRUE") def mock_rasterio_open(band): """Mock rasterio Open.""" assert band.startswith("s3://usgs-landsat") band = band.replace("s3://usgs-landsat", str(LANDSAT_BUCKET)) return rasterio.open(band) @patch("rio_tiler_pds.landsat.aws.landsat_collection2.get_object") @patch("rio_tiler.io.cogeo.rasterio") def test_LandsatC2L2Reader(rio, get_object): """Should work as expected (get and parse metadata).""" rio.open = mock_rasterio_open get_object.return_value = LANDSAT_METADATA with pytest.raises(InvalidLandsatSceneId): with LandsatC2Reader(INVALID_LANDSAT_SCENE_C2): pass with LandsatC2Reader(LANDSAT_SCENE_C2) as landsat: assert landsat.scene_params["scene"] == LANDSAT_SCENE_C2 assert landsat.minzoom == 5 assert landsat.maxzoom == 12 assert len(landsat.bounds) == 4 assert landsat.bands == OLI_SR_BANDS + TIRS_ST_BANDS with pytest.raises(MissingBands): landsat.info() with pytest.raises(InvalidBandName): landsat.info(bands="BAND5") metadata = landsat.info(bands="SR_B5") assert len(metadata["band_metadata"]) == 1 assert metadata["band_descriptions"] == [("SR_B5", "")] metadata = landsat.info(bands=landsat.bands) assert len(metadata["band_metadata"]) == len(OLI_SR_BANDS + TIRS_ST_BANDS) with pytest.raises(MissingBands): landsat.stats() stats = landsat.stats(bands="SR_B1") assert stats["SR_B1"]["percentiles"] == [7926, 49017] stats = landsat.stats(bands=landsat.bands) assert len(stats.items()) == len(OLI_SR_BANDS + TIRS_ST_BANDS) assert list(stats) == list(landsat.bands) stats = landsat.stats(bands="SR_B1", hist_options=dict(bins=20)) assert len(stats["SR_B1"]["histogram"][0]) == 20 stats = landsat.stats(pmin=10, pmax=90, bands="SR_B1") assert stats["SR_B1"]["percentiles"] == [8524, 43038] stats = landsat.stats(bands="QA_PIXEL") assert stats["QA_PIXEL"]["min"] == 1 stats = landsat.stats(bands="QA_PIXEL", nodata=0, resampling_method="bilinear") # nodata and resampling_method are set at reader level an shouldn't be set assert stats["QA_PIXEL"]["min"] == 1 with pytest.raises(MissingBands): landsat.metadata() metadata = landsat.metadata(bands="SR_B1") assert metadata["statistics"]["SR_B1"]["percentiles"] == [7926, 49017] assert metadata["band_metadata"] == [("SR_B1", {})] assert metadata["band_descriptions"] == [("SR_B1", "")] metadata = landsat.metadata(bands=("SR_B1", "SR_B2")) assert metadata["band_metadata"] == [("SR_B1", {}), ("SR_B2", {})] assert metadata["band_descriptions"] == [("SR_B1", ""), ("SR_B2", "")] # nodata and resampling_method are set at reader level an shouldn't be set metadata = landsat.metadata( bands="QA_PIXEL", nodata=0, resampling_method="bilinear" ) assert metadata["statistics"]["QA_PIXEL"]["min"] == 1 tile_z = 8 tile_x = 81 tile_y = 130 with pytest.raises(MissingBands): landsat.tile(tile_x, tile_y, tile_z) data, mask = landsat.tile( tile_x, tile_y, tile_z, bands=("SR_B4", "SR_B3", "SR_B2") ) assert data.shape == (3, 256, 256) assert data.dtype == numpy.uint16 assert mask.shape == (256, 256) assert not mask.all() # Level 2 collection 2 temperatures are uint16 data, mask = landsat.tile(tile_x, tile_y, tile_z, bands="ST_B10") assert data.shape == (1, 256, 256) assert data.dtype == numpy.uint16 assert mask.shape == (256, 256) data, mask = landsat.tile( tile_x, tile_y, tile_z, bands="QA_PIXEL", nodata=0, resampling_method="bilinear", ) assert data.shape == (1, 256, 256) assert not mask.all() # Pansharpening not yet implemented # data, mask = landsat.tile( # tile_x, tile_y, tile_z, bands=("SR_B4", "SR_B3", "SR_B2"), pan=True # ) # assert data.shape == (3, 256, 256) # assert data.dtype == numpy.uint16 # assert mask.shape == (256, 256) with pytest.raises(TileOutsideBounds): landsat.tile(701, 102, 8, bands=("SR_B4", "SR_B3", "SR_B2")) data, mask = landsat.tile( tile_x, tile_y, tile_z, expression="SR_B5*0.8, SR_B4*1.1, SR_B3*0.8" ) assert data.shape == (3, 256, 256) assert data.dtype == numpy.float64 assert mask.shape == (256, 256) with pytest.raises(MissingBands): landsat.preview() data, mask = landsat.preview(bands=("SR_B4", "SR_B3", "SR_B2")) assert data.shape == (3, 386, 379) assert data.dtype == numpy.uint16 assert mask.shape == (386, 379) assert not mask.all() # Level 2 collection 2 temperatures are uint16 data, mask = landsat.preview(bands="ST_B10") assert data.shape == (1, 386, 379) assert data.dtype == numpy.uint16 assert mask.shape == (386, 379) # Pansharpening not yet implemented # data, mask = landsat.preview( # bands=("SR_B4", "SR_B3", "SR_B2"), pan=True, width=256, height=256 # ) # assert data.shape == (3, 256, 256) # assert data.dtype == numpy.uint16 # assert mask.shape == (256, 256) data, mask = landsat.preview(expression="SR_B5*0.8, SR_B4*1.1, SR_B3*0.8") assert data.shape == (3, 386, 379) assert data.dtype == numpy.float64 assert mask.shape == (386, 379) data, mask = landsat.preview(bands="QA_PIXEL") assert data.shape == (1, 386, 379) assert mask.all() bbox = landsat.bounds point_x = (bbox[0] + bbox[2]) / 2 point_y = (bbox[1] + bbox[3]) / 2 with pytest.raises(MissingBands): landsat.point(point_x, point_y) values = landsat.point(point_x, point_y, bands="SR_B7") assert values == [16414] values = landsat.point(point_x, point_y, bands="QA_PIXEL") assert values[0] == 22280 values = landsat.point(point_x, point_y, bands=("SR_B7", "SR_B4")) assert len(values) == 2 values = landsat.point( point_x, point_y, expression="SR_B5*0.8, SR_B4*1.1, SR_B3*0.8" ) assert len(values) == 3 bbox = landsat.bounds minx = (bbox[0] + bbox[2]) * 0.25 miny = (bbox[1] + bbox[3]) * 0.25 maxx = (bbox[0] + bbox[2]) * 0.75 maxy = (bbox[1] + bbox[3]) * 0.75 part = (minx, miny, maxx, maxy) with pytest.raises(MissingBands): landsat.part(part) data, mask = landsat.part(part, bands="SR_B7") assert 1024 in data.shape assert data.dtype == numpy.uint16 assert not mask.all() data, _ = landsat.part( part, bands="QA_PIXEL", nodata=0, resampling_method="bilinear", ) assert data.shape == (1, 46, 1024) data, mask = landsat.part(part, expression="SR_B5*0.8, SR_B4*1.1, SR_B3*0.8") assert 1024 in data.shape assert data.shape[0] == 3 assert data.dtype == numpy.float64 assert not mask.all() data, mask = landsat.part( part, bands=("SR_B4", "SR_B3", "SR_B2"), width=80, height=80, ) assert data.shape == (3, 80, 80) assert data.dtype == numpy.uint16 assert mask.shape == (80, 80) ll = (minx, miny) lr = (maxx, miny) ul = (minx, maxy) ur = (maxx, maxy) feat = { "type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": [[ll, lr, ur, ul, ll]]}, } with pytest.raises(MissingBands): landsat.feature(feat) data, mask = landsat.feature(feat, bands="SR_B7") assert 1024 in data.shape assert data.dtype == numpy.uint16 assert 1024 in mask.shape data, _ = landsat.feature( feat, bands="QA_PIXEL", nodata=0, resampling_method="bilinear", ) assert data.any() data, mask = landsat.feature(feat, expression="SR_B5*0.8, SR_B4*1.1, SR_B3*0.8") assert data.any() assert data.shape[0] == 3 assert data.dtype == numpy.float64 data, mask = landsat.feature( feat, bands=("SR_B4", "SR_B3", "SR_B2"), width=80, height=80, ) assert data.shape == (3, 80, 80) assert data.dtype == numpy.uint16 assert mask.shape == (80, 80) C2_SENSOR_TEST_CASES = [ # Collection 2 Level 2 OLI-TIRS 8 SP (both SR and ST) ("LC08_L2SP_001062_20201031_20201106_02_T2", OLI_SR_BANDS + TIRS_ST_BANDS), # Collection 2 Level 2 OLI-TIRS 8 SR (no ST) ("LC08_L2SR_122108_20201031_20201106_02_T2", OLI_SR_BANDS), # Collection 2 Level 2 TM SP (both SR and ST) ("LT05_L2SP_014032_20111018_20200820_02_T1", TM_SR_BANDS + TM_ST_BANDS), # Collection 2 Level 2 TM SR (no ST) ("LT05_L2SR_089076_20110929_20200820_02_T2", TM_SR_BANDS), # Collection 2 Level 2 ETM SP (both SR and ST) ("LE07_L2SP_175066_20201026_20201121_02_T1", TM_SR_BANDS + TM_ST_BANDS), # Collection 2 Level 2 ETM SR (no ST) ("LE07_L2SR_123067_20201030_20201126_02_T1", TM_SR_BANDS), ] @patch("rio_tiler_pds.landsat.aws.landsat_collection2.get_object") @patch("rio_tiler.io.cogeo.rasterio") def test_LandsatC2L2Reader_bands(rio, get_object): """Should work as expected (get and parse metadata).""" rio.open = mock_rasterio_open get_object.return_value = LANDSAT_METADATA with pytest.raises(InvalidLandsatSceneId): with LandsatC2Reader(INVALID_LANDSAT_SCENE_C2): pass for sceneid, expected_bands in C2_SENSOR_TEST_CASES: with LandsatC2Reader(sceneid) as landsat: assert landsat.bands == expected_bands
34.204276
88
0.536771
2,906
28,800
5.07192
0.128355
0.021033
0.026053
0.037859
0.806432
0.704118
0.663614
0.543388
0.497795
0.466246
0
0.129947
0.32184
28,800
841
89
34.244946
0.624699
0.065521
0
0.538036
0
0
0.324542
0.097973
0
0
0
0
0.100968
1
0.006916
false
0.002766
0.012448
0
0.020747
0
0
0
0
null
0
0
0
1
1
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
f1f21b6d0d5e0b5b1f60de81ac6823a5f3255d54
2,295
py
Python
model/frames.py
Veronicka/Python-Serial-INPE
801661a76edbcc1a5e6256a80b1966bc846541fc
[ "MIT" ]
null
null
null
model/frames.py
Veronicka/Python-Serial-INPE
801661a76edbcc1a5e6256a80b1966bc846541fc
[ "MIT" ]
null
null
null
model/frames.py
Veronicka/Python-Serial-INPE
801661a76edbcc1a5e6256a80b1966bc846541fc
[ "MIT" ]
null
null
null
__author__ = 'Veronica' from random import randint header = [0xeb, 0x95, 0x4, 0xfa, 0x0, 0x0, 0x0, 0x0, 0x0] def checksum(frame): return 0xFF - (sum(frame[4:]) & 0xFF) def acknowledge(): ack = [0xeb, 0x95, 0x3, 0x0, 0x55, 0xAA] #ack.append(checksum(ack)) return ack def housekeeping(n, t): n_Vp = [0x7f, 0x65, 0x51, 0x40, 0x33, 0x29, 0x21, 0x1a, 0x15, 0x10, 0xd, 0xa, 0x8, 0x7, 0x5, 0x4] #voltagem das placas n_Cont = [0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64] #contador1 hkp = header hkp.append(t) hkp.append(0x7f) for vp in n_Vp: hkp.append(vp) for c1 in n_Cont: hkp.append(c1) for c1 in n_Cont: hkp.append(c1) for vp in n_Vp: hkp.append(vp) for vp in n_Vp: hkp.append(vp) hkp.append(checksum(hkp)) return hkp def modoNormal(n, t): modoN = header n_Cont1 = [0xad, 0x8a, 0x6e, 0x57, 0x46, 0x38, 0x2c, 0x23, 0x1c, 0x16, 0x12, 0xe, 0xb, 0x9, 0x7, 0x6] n_Cont2 = [0x109, 0xd3, 0xa8, 0x86, 0x6b, 0x55, 0x44, 0x36, 0x2b, 0x22, 0x1b, 0x16, 0x11, 0xe, 0xb, 0x9] n_Cont3 = [0x144, 0x102, 0xce, 0xa4, 0x83, 0x68, 0x53, 0x42, 0x35, 0x2a, 0x21, 0x1b, 0x15, 0x11, 0xd, 0xb] modoN.append(t) modoN.append(n) n_Cont = [] random = randint(1,3) if random == 3: n_Cont = n_Cont1 elif random == 2: n_Cont = n_Cont2 else: n_Cont = n_Cont3 for num in n_Cont: modoN.append(num) n_Cont = [] random = randint(1,3) if random == 3: n_Cont = n_Cont1 elif random == 2: n_Cont = n_Cont2 else: n_Cont = n_Cont3 for num in n_Cont: modoN.append(num) modoN.append(t) modoN.append(n) n_Cont = [] random = randint(1,3) if random == 3: n_Cont = n_Cont1 elif random == 2: n_Cont = n_Cont2 else: n_Cont = n_Cont3 for num in n_Cont: modoN.append(num) n_Cont = [] random = randint(1,3) if random == 3: n_Cont = n_Cont1 elif random == 2: n_Cont = n_Cont2 else: n_Cont = n_Cont3 for num in n_Cont: modoN.append(num) modoN.append(checksum(modoN)) return modoN
21.650943
122
0.565142
348
2,295
3.594828
0.293103
0.091926
0.134293
0.166267
0.517986
0.517986
0.517986
0.517986
0.503597
0.430855
0
0.172173
0.314161
2,295
105
123
21.857143
0.622618
0.023094
0
0.701299
0
0
0.003575
0
0
0
0.165773
0
0
1
0.051948
false
0
0.012987
0.012987
0.116883
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
f1ff82e6dd05ce6b009ac20b7bb19e223775ef79
1,481
py
Python
samples/table_schema_examples.py
SorenSeeberg/MrDatabase
07d39c1f227d9ceaffe7e409f0915776901dd3e9
[ "MIT" ]
null
null
null
samples/table_schema_examples.py
SorenSeeberg/MrDatabase
07d39c1f227d9ceaffe7e409f0915776901dd3e9
[ "MIT" ]
1
2018-05-28T11:55:49.000Z
2018-06-11T16:51:45.000Z
samples/table_schema_examples.py
SorenSeeberg/MrDatabase
07d39c1f227d9ceaffe7e409f0915776901dd3e9
[ "MIT" ]
null
null
null
#!/usr/bin/python3 # -*- coding: utf-8 -*- from mr_database import DataTypes from mr_database import Table from mr_database import Column class TableTemplate(Table): id = Column(DataTypes.integer, pk=True) myCol = Column(DataTypes.varchar(16), default='Hello World') class BrokenTable(Table): id = Column(DataTypes.integer, pk=True) postalCode = Column(DataTypes.smallint) cityName = Column(DataTypes.varchar(40), not_null=True, default='New York') cityId = Column(data_type=DataTypes.integer, default=0) def __init__(self): super().__init__() self.counter = 10 class City(Table): id = Column(DataTypes.integer, pk=True) postalCode = Column(DataTypes.smallint, default=9999, display_name='Postal Code') cityName = Column(DataTypes.varchar(40), default='New York', display_name='City Name') def __init__(self): super().__init__() self.id: int = City.id.default self.postalCode: int = City.postalCode.default self.cityName: str = City.cityName.default class Person(Table): id = Column(DataTypes.integer, pk=True) firstName = Column(DataTypes.varchar(40)) lastName = Column(DataTypes.varchar(40)) cityId = Column(data_type=DataTypes.integer, fk=(City, 'id'), default=0) class Image(Table): id = Column(DataTypes.integer, pk=True) md5 = Column(DataTypes.char(32)) imageName = Column(DataTypes.varchar(40)) imageData = Column(DataTypes.blob)
26.446429
90
0.6921
185
1,481
5.410811
0.340541
0.224775
0.131868
0.10989
0.424575
0.360639
0.240759
0.135864
0.135864
0.135864
0
0.020559
0.178933
1,481
55
91
26.927273
0.802632
0.026334
0
0.272727
0
0
0.034028
0
0
0
0
0
0
1
0.060606
false
0
0.090909
0
0.818182
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
7b005faa97d65355525b45fe38a63a36b3f2430a
6,920
py
Python
aleph/model/role.py
gazeti/aleph
f6714c4be038471cfdc6408bfe88dc9e2ed28452
[ "MIT" ]
1
2017-07-28T12:54:09.000Z
2017-07-28T12:54:09.000Z
aleph/model/role.py
gazeti/aleph
f6714c4be038471cfdc6408bfe88dc9e2ed28452
[ "MIT" ]
7
2017-08-16T12:49:23.000Z
2018-02-16T10:22:11.000Z
aleph/model/role.py
gazeti/aleph
f6714c4be038471cfdc6408bfe88dc9e2ed28452
[ "MIT" ]
6
2017-07-26T12:29:53.000Z
2017-08-18T09:35:50.000Z
import logging from flask import current_app from sqlalchemy import or_ from itsdangerous import URLSafeTimedSerializer from werkzeug.security import generate_password_hash, check_password_hash from normality import stringify from flask_simpleldap import LDAPException from aleph.core import db, ldap, url_for, get_config, secret_key from aleph.model.validate import validate from aleph.model.common import SoftDeleteModel, IdModel, make_textid log = logging.getLogger(__name__) membership = db.Table('role_membership', db.Column('group_id', db.Integer, db.ForeignKey('role.id')), # noqa db.Column('member_id', db.Integer, db.ForeignKey('role.id')) # noqa ) class Role(db.Model, IdModel, SoftDeleteModel): """A user, group or other access control subject.""" _schema = 'role.json#' __tablename__ = 'role' USER = 'user' GROUP = 'group' SYSTEM = 'system' TYPES = [USER, GROUP, SYSTEM] SYSTEM_GUEST = 'guest' SYSTEM_USER = 'user' #: Generates URL-safe signatures for invitations. SIGNATURE_SERIALIZER = URLSafeTimedSerializer(secret_key) #: Signature maximum age, defaults to 1 day SIGNATURE_MAX_AGE = 60 * 60 * 24 #: Password minimum length PASSWORD_MIN_LENGTH = 6 foreign_id = db.Column(db.Unicode(2048), nullable=False, unique=True) name = db.Column(db.Unicode, nullable=False) email = db.Column(db.Unicode, nullable=True) api_key = db.Column(db.Unicode, nullable=True) is_admin = db.Column(db.Boolean, nullable=False, default=False) type = db.Column(db.Enum(*TYPES, name='role_type'), nullable=False) password_digest = db.Column(db.Unicode, nullable=True) reset_token = db.Column(db.Unicode, nullable=True) permissions = db.relationship('Permission', backref='role') def update(self, data): validate(data, self._schema) self.name = data.get('name', self.name) self.email = data.get('email', self.email) def clear_roles(self): """Removes any existing roles from group membership.""" self.roles = [] db.session.add(self) def add_role(self, role): """Adds an existing role as a membership of a group.""" self.roles.append(role) db.session.add(role) db.session.add(self) @classmethod def notifiable(cls): return cls.all_ids().filter(cls.email != None) # noqa @classmethod def by_foreign_id(cls, foreign_id): if foreign_id is not None: return cls.all().filter_by(foreign_id=foreign_id).first() @classmethod def by_email(cls, email): if email: return cls.all().filter_by(email=email) @classmethod def by_api_key(cls, api_key): if api_key is not None: return cls.all().filter_by(api_key=api_key).first() @classmethod def load_or_create(cls, foreign_id, type, name, email=None, is_admin=None): role = cls.by_foreign_id(foreign_id) if role is None: role = cls() role.foreign_id = foreign_id role.name = name role.type = type role.is_admin = False if role.api_key is None: role.api_key = make_textid() role.email = email if is_admin is not None: role.is_admin = is_admin # see: https://github.com/alephdata/aleph/issues/111 auto_admins = [a.lower() for a in get_config('AUTHZ_ADMINS')] if email is not None and email.lower() in auto_admins: role.is_admin = True db.session.add(role) db.session.flush() return role @classmethod def load_id(cls, foreign_id, type=None, name=None): """Load a role and return the ID. If type is given and no role is found, a new role will be created. """ if not hasattr(current_app, '_authz_roles'): current_app._authz_roles = {} if foreign_id not in current_app._authz_roles: role = cls.by_foreign_id(foreign_id) if role is None: if type is None: return name = name or foreign_id role = cls.load_or_create(foreign_id, type, name) current_app._authz_roles[foreign_id] = role.id return current_app._authz_roles[foreign_id] @classmethod def by_prefix(cls, prefix): """Load a list of roles matching a name, email address, or foreign_id. :param str pattern: Pattern to match. """ q = cls.all() q = q.filter(Role.type == Role.USER) q = q.filter(or_( cls.foreign_id.ilike('%' + prefix + '%'), cls.email.ilike('%' + prefix + '%'), cls.name.ilike('%' + prefix + '%') )) return q @classmethod def all_groups(cls): return cls.all().filter(Role.type != Role.USER) def set_password(self, secret): """Hashes and sets the role password. :param str secret: The password to be set. """ self.password_digest = generate_password_hash(secret) def check_password(self, secret): """Checks the password if it matches the role password hash. :param str secret: The password to be checked. :rtype: bool """ return check_password_hash(self.password_digest or '', secret) @classmethod def authenticate_using_ldap(cls, identifier, password): """Autheticates using user LDAP identifier and password. :param str identifier: LDAP ID. :param str password: LDAP password. :return: A matched role. :rtype: :py:class:`Role` """ if not password: return try: base_dn = get_config('LDAP_BASE_DN') ldap_conn = ldap.initialize ldap_conn.simple_bind_s(base_dn.format(identifier), password) ldap_conn.unbind_s() except LDAPException as exception: log.info(exception) return foreign_id = 'ldap:{}'.format(identifier) return cls.load_or_create(foreign_id, cls.USER, identifier, identifier) def __repr__(self): return '<Role(%r,%r)>' % (self.id, self.foreign_id) def __unicode__(self): return self.name def to_dict(self): data = super(Role, self).to_dict() data.update({ 'api_url': url_for('roles_api.view', id=self.id), 'foreign_id': self.foreign_id, 'is_admin': self.is_admin, # 'email': self.email, 'name': self.name, 'type': self.type }) return data Role.members = db.relationship(Role, secondary=membership, primaryjoin=Role.id == membership.c.group_id, secondaryjoin=Role.id == membership.c.member_id, backref="roles")
31.598174
79
0.615751
883
6,920
4.650057
0.233296
0.05699
0.019484
0.024842
0.155626
0.129566
0.063322
0.049196
0.018997
0.018997
0
0.003002
0.278035
6,920
218
80
31.743119
0.818855
0.133815
0
0.138889
1
0
0.039458
0
0
0
0
0
0
1
0.118056
false
0.069444
0.069444
0.027778
0.444444
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
7b10a4baf330e2f2546257d21c8a753661c57bd4
3,684
py
Python
simulation.py
germtb/Pysics
af293dfcd7383860927d49cb78d7b269a0ff7a2a
[ "MIT" ]
2
2015-10-22T19:12:20.000Z
2016-05-28T11:11:50.000Z
simulation.py
germtb/Pysics
af293dfcd7383860927d49cb78d7b269a0ff7a2a
[ "MIT" ]
null
null
null
simulation.py
germtb/Pysics
af293dfcd7383860927d49cb78d7b269a0ff7a2a
[ "MIT" ]
null
null
null
from math import sqrt from numpy import arange from universal_constants import MARS_RADIUS from universal_functions import mars_density class Simulation: @property def xs(self): return [v.x for v in self.ps] @property def ys(self): return [v.y for v in self.ps] @property def zs(self): return [v.z for v in self.ps] @property def rs(self): return [p.module for p in self.ps] @property def hs(self): return [r - MARS_RADIUS for r in self.rs] def __init__(self, body, forces): self.body = body self.forces = forces self.ps = [] self.vs = [] self.gs = [] self.duration = 0 self.delta_v = 0 def run(self, time, dt, condition=lambda b: False): duration = 0 initial_speed = self.body.speed for _ in arange(0, time, dt): duration += dt self.step(dt) if condition(self.body): break self.duration = duration self.delta_v = self.body.speed - initial_speed def step(self, dt): force = self.forces(self.body) self.body.velocity += dt * force / self.body.mass self.body.position += dt * self.body.velocity self.ps.append(self.body.position) self.vs.append(self.body.velocity) self.gs.append(force.module / self.body.mass / 9.81 / dt) class ThrustSimulation(Simulation): @property def engine_mass(self): return 0.0014 * self.mass_0 * abs(self.delta_v) / self.duration + 49.6 def __init__(self, body, delta_mass, *forces): super().__init__(body, *forces) self.delta_mass = delta_mass self.propellant_mass = 0 self.mass_0 = body.mass def step(self, dt): super().step(dt) self.body.mass -= self.delta_mass * dt self.propellant_mass += self.delta_mass * dt def save_data(self, filename): import csv with open(filename + '.csv', 'a', newline='') as csvfile: spamwriter = csv.writer(csvfile) spamwriter.writerow(['Engine mass', str(self.engine_mass)]) spamwriter.writerow(['Propellant mass', str(self.propellant_mass)]) spamwriter.writerow(['Max gs', str(max(self.gs))]) class AerobreakingSimulation(Simulation): @property def shield_mass(self): return self.body.mass * 0.00091 * (self.Q * 1e-4) ** 0.51575 @property def structure_mass(self): return self.body.mass * 0.0232 * max(self.pressures) ** -0.1708 @property def back_shield_mass(self): return 0.14 * self.body.mass @property def heat_shield_mass(self): return self.shield_mass + self.structure_mass + self.back_shield_mass def __init__(self, body, *forces): super().__init__(body, *forces) self.qs = [] self.pressures = [] self.Q = 0 self.k = 1.9027e-4 # [SI] Hinc sunt draconis def q(self, b): return self.k * sqrt(mars_density(b.radius) / b.r_nose) * b.speed ** 3 def p(self, b): return mars_density(b.radius) * b.speed2 / 2 def run(self, time, dt=1, condition=lambda b: False): super().run(time, dt, condition) self.Q = sum(self.qs) * dt def step(self, dt): super().step(dt) self.qs.append(self.q(self.body)) self.pressures.append(self.p(self.body)) def save_data(self, filename): import csv with open(filename + '.csv', 'a', newline='') as csvfile: spamwriter = csv.writer(csvfile) spamwriter.writerow(['Shield mass', str(self.heat_shield_mass)])
27.492537
79
0.594463
498
3,684
4.277108
0.220884
0.078873
0.033803
0.030047
0.307042
0.216432
0.189202
0.131455
0.105164
0.105164
0
0.021196
0.282845
3,684
133
80
27.699248
0.785011
0.006243
0
0.25
0
0
0.014485
0
0
0
0
0
0
1
0.22
false
0
0.06
0.12
0.43
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
7b14578be99316bdc91f5e6c5462639763ec1f80
1,677
py
Python
attachments/migrations/0004_auto_20170303_1242.py
liddiard/appletini
fa006e1b71ac60738bb5353e949676755530c781
[ "MIT" ]
1
2015-03-17T04:13:47.000Z
2015-03-17T04:13:47.000Z
attachments/migrations/0004_auto_20170303_1242.py
liddiard/appletini
fa006e1b71ac60738bb5353e949676755530c781
[ "MIT" ]
27
2015-04-14T20:18:24.000Z
2015-06-16T20:01:06.000Z
attachments/migrations/0004_auto_20170303_1242.py
liddiard/appletini
fa006e1b71ac60738bb5353e949676755530c781
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-03 20:42 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('attachments', '0003_auto_20150505_0038'), ] operations = [ migrations.AlterField( model_name='audio', name='file', field=models.FileField(upload_to='attachments/audio/%Y/%m/%d'), ), migrations.AlterField( model_name='image', name='file', field=models.ImageField(upload_to='attachments/image/%Y/%m/%d'), ), migrations.AlterField( model_name='poll', name='is_open', field=models.BooleanField(default=True, help_text='Whether or not the poll is currently accepting new responses.'), ), migrations.AlterField( model_name='review', name='item', field=models.CharField(help_text='The item being reviewed.', max_length=64), ), migrations.AlterField( model_name='review', name='rating', field=models.PositiveSmallIntegerField(blank=True, help_text='Rating between zero and ten.', null=True, validators=[django.core.validators.MaxValueValidator(10)]), ), migrations.AlterField( model_name='video', name='youtube_id', field=models.CharField(help_text='The unique ID of this video on YouTube, found in the URL, probably around eleven characters and composed of numbers and letters.', max_length=16), ), ]
35.680851
192
0.614788
184
1,677
5.472826
0.527174
0.119166
0.148957
0.17279
0.202582
0.202582
0.063555
0
0
0
0
0.031785
0.268336
1,677
46
193
36.456522
0.788916
0.040549
0
0.410256
1
0.025641
0.244707
0.0467
0
0
0
0
0
1
0
false
0
0.076923
0
0.153846
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
9e3269149cbd5ddb55d4bd789472c82783c166ad
3,008
py
Python
src/lightuptraining/sources/antplus/messages/util.py
marcelblijleven/light-up-training
e0310ec024c03064934f5c01d3b336dd81fac93c
[ "MIT" ]
1
2021-12-05T13:55:04.000Z
2021-12-05T13:55:04.000Z
src/lightuptraining/sources/antplus/messages/util.py
marcelblijleven/light-up-training
e0310ec024c03064934f5c01d3b336dd81fac93c
[ "MIT" ]
null
null
null
src/lightuptraining/sources/antplus/messages/util.py
marcelblijleven/light-up-training
e0310ec024c03064934f5c01d3b336dd81fac93c
[ "MIT" ]
null
null
null
import struct from functools import reduce from operator import ixor from typing import Iterable, List, Tuple, Union def calculate_checksum(message: Iterable[int]) -> int: """ Calculates the checksum, which is the XOR of all bytes in the message """ return reduce(ixor, message) def validate_device_number(device_number: int): """ Validates the device number and raises a ValueError when the device number is out of range Device number is a 16 bit field, so the value must be between 0x0000 and 0xFFFF (0 and 65535) """ if not 0x0000 <= device_number <= 0xFFFF: raise ValueError('device number out of range (0x0000 <= device_number <= 0xFFFF)') def device_number_to_fields(device_number: int) -> List[int]: """ Splits the device number (16 bits) into two bytes Example with device number 1000 Full bits: 0b0000001111101000 First 8 bits: 0b00000011 == 3 Last 8 bits: 0b11101000 == 232 This function will return [232, 3] because the byte order is little endian (least significant byte first) """ return [byte for byte in struct.pack('<H', device_number)] def fields_to_device_number(fields: Union[Tuple[int, int], List[int]]) -> int: """ Joins the two 8 bit fields into a 16 bit device number Example with fields 3 and 232 3: 0b00000011 232: 0b11101000 1000: (3 << 8) | 232 (3 << 8) == 0b1100000000 0b1100000000 | 232 == 1000 """ # return struct.unpack('<H', bytes(fields))[0] return (fields[1] << 8) | fields[0] def validate_device_type(device_type: int): """ Validates the device type, the device type is sent to the ant+ device together with a pairing bit. The most significant bit is the pairing bit Max value of the pairing bit with device type is 255 Because True << 7 equals 128, the max value of device type is 255 - 128 == 127 """ if not 0 <= device_type <= 127: raise ValueError('device type out of range (0 <= device_type <= 127)') def set_pairing_bit_on_device_type(pairing_bit: bool, device_type: int): """ Shifts the pairing bit (True = 1, False = 0) 7 bits to the left and adds the device type """ return (pairing_bit << 7) + device_type def split_pairing_bit_from_device_type(device_type_with_pairing_bit: int) -> Tuple[int, int]: """ Splits the device type with pairing bit into the pairing bit and device type Converts the int to a binary string, padded to a length of 8 bits, to retrieve the pairing bit The left most bit is the pairing bit, the rest of the bits form the device type """ if not 0 <= device_type_with_pairing_bit <= 255: raise ValueError('device type with pairing bit out of range (0 <= x <= 255)') binary_string = format(device_type_with_pairing_bit, '08b') pairing_bit = int(binary_string[0]) device_type = (pairing_bit << 7) ^ device_type_with_pairing_bit return pairing_bit, device_type
34.976744
109
0.681848
453
3,008
4.403974
0.264901
0.120301
0.039098
0.063158
0.117293
0
0
0
0
0
0
0.082971
0.234707
3,008
85
110
35.388235
0.783666
0.473404
0
0
0
0
0.123755
0
0
0
0.01707
0
0
1
0.28
false
0
0.16
0
0.64
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
9e4808756721d395e2636c25f7279c1c5b24a07e
2,079
py
Python
directory/migrations/0001_initial.py
for-each-org/taf-members
a9e9663acc8ae5a321965a6340c639ede0c09754
[ "MIT" ]
null
null
null
directory/migrations/0001_initial.py
for-each-org/taf-members
a9e9663acc8ae5a321965a6340c639ede0c09754
[ "MIT" ]
19
2018-02-10T22:54:40.000Z
2018-03-03T19:06:18.000Z
directory/migrations/0001_initial.py
for-each-org/taf-members
a9e9663acc8ae5a321965a6340c639ede0c09754
[ "MIT" ]
null
null
null
# Generated by Django 2.0.2 on 2018-02-15 19:41 import django.contrib.postgres.fields.jsonb from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=256)), ], ), migrations.CreateModel( name='Profile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=256)), ('offers_private_lessons', models.BooleanField(default=False)), ('address', models.TextField()), ('bio', models.TextField()), ('website', models.CharField(max_length=256)), ('phone', models.CharField(max_length=20)), ('profile_img_url', models.CharField(max_length=256)), ('social', django.contrib.postgres.fields.jsonb.JSONField()), ('time_created', models.DateTimeField()), ('last_modified', models.DateTimeField()), ('category', models.ManyToManyField(to='directory.Category')), ], ), migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('username', models.CharField(max_length=64)), ('password', models.CharField(max_length=256)), ('name', models.CharField(max_length=256)), ('time_created', models.DateTimeField()), ('last_modified', models.DateTimeField()), ('user_type', models.IntegerField(choices=[(1, 'Admin'), (0, 'User')], default=0)), ], ), ]
39.980769
114
0.555556
192
2,079
5.880208
0.385417
0.106289
0.127547
0.170062
0.528787
0.400354
0.372896
0.372896
0.264836
0.264836
0
0.027341
0.296296
2,079
51
115
40.764706
0.744361
0.021645
0
0.5
1
0
0.107283
0.010827
0
0
0
0
0
1
0
false
0.022727
0.045455
0
0.136364
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
9e5cd8d2a098fb3407f6b897d62a65e1cb962ec8
766
py
Python
tests/test_deconvolution.py
0xDBFB7/xraylarch
3d48494d104ab31d0b3c94e3166f716fef7efe1e
[ "BSD-2-Clause" ]
null
null
null
tests/test_deconvolution.py
0xDBFB7/xraylarch
3d48494d104ab31d0b3c94e3166f716fef7efe1e
[ "BSD-2-Clause" ]
null
null
null
tests/test_deconvolution.py
0xDBFB7/xraylarch
3d48494d104ab31d0b3c94e3166f716fef7efe1e
[ "BSD-2-Clause" ]
null
null
null
#!/usr/bin/env python """ Tests of Larch Scripts """ import unittest import time import ast import numpy as np import os from sys import version_info from utils import TestCase from larch import Interpreter class TestScripts(TestCase): '''tests''' def test_basic_interp(self): self.runscript('interp.lar', dirname='../examples/basic/') assert(len(self.session.get_errors()) == 0) self.isNear("y0[1]", 0.48578, places=3) self.isNear("y1[1]", 0.81310, places=3) self.isNear("y2[1]", 0.41532, places=3) if __name__ == '__main__': # pragma: no cover for suite in (TestScripts,): suite = unittest.TestLoader().loadTestsFromTestCase(suite) unittest.TextTestRunner(verbosity=13).run(suite)
27.357143
66
0.665796
101
766
4.930693
0.643564
0.060241
0.044177
0.068273
0
0
0
0
0
0
0
0.048701
0.195822
766
27
67
28.37037
0.75974
0.088773
0
0
0
0
0.074453
0
0
0
0
0
0.052632
1
0.052632
false
0
0.421053
0
0.526316
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
9e6ab477a8216a829281be948e7a973f5c0e3f87
1,055
py
Python
corkus/objects/major_identification.py
MrBartusek/corkus.py
031c11e3e251f0bddbcb67415564357460fe7fea
[ "MIT" ]
5
2021-09-10T14:20:15.000Z
2022-01-09T11:27:49.000Z
corkus/objects/major_identification.py
MrBartusek/corkus.py
031c11e3e251f0bddbcb67415564357460fe7fea
[ "MIT" ]
11
2021-08-15T09:39:09.000Z
2022-01-12T14:11:24.000Z
corkus/objects/major_identification.py
MrBartusek/corkus.py
031c11e3e251f0bddbcb67415564357460fe7fea
[ "MIT" ]
2
2021-12-01T23:33:14.000Z
2022-01-12T11:08:18.000Z
from __future__ import annotations from typing import TYPE_CHECKING from .base import CorkusBase from corkus.data.major_ids import major_ids if TYPE_CHECKING: from corkus import Corkus class MajorIdentification(CorkusBase): """Major IDs are a type of special :py:class:`Identification` but, they are not randomly rolled and they provide a wide range of effects that cannot be acquired elsewhere""" @property def id(self) -> str: """The id of the Major ID like ``PLAGUE`` or ``ARCANES``.""" return self._attributes @property def name(self) -> str: """The name of the Major ID like ``Plague`` or ``Transcendence``.""" return self._id_data.get("name", "") @property def effect(self) -> str: """The description of effect this Major ID provide.""" return self._id_data.get("effect", "") @property def _id_data(self) -> dict: return major_ids.get(self.id, {}) def __repr__(self) -> str: return f"<MajorIdentification name={self.name!r}>"
30.142857
84
0.658768
141
1,055
4.787234
0.41844
0.047407
0.044444
0.035556
0.127407
0.071111
0.071111
0
0
0
0
0
0.227488
1,055
34
85
31.029412
0.828221
0.316588
0
0.190476
0
0
0.072254
0
0
0
0
0
0
1
0.238095
false
0
0.238095
0.095238
0.761905
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
9e8432957230c08c77bb78f607f33659db10a210
106
py
Python
databooks/version.py
datarootsio/databooks
6ecbae09c7df8149ae3ab45a88e00f6ccea7d045
[ "MIT" ]
75
2021-12-20T11:50:48.000Z
2022-03-31T19:57:26.000Z
databooks/version.py
datarootsio/databooks
6ecbae09c7df8149ae3ab45a88e00f6ccea7d045
[ "MIT" ]
26
2021-12-16T16:17:31.000Z
2022-03-03T20:58:50.000Z
databooks/version.py
datarootsio/databooks
6ecbae09c7df8149ae3ab45a88e00f6ccea7d045
[ "MIT" ]
3
2021-12-16T15:26:15.000Z
2022-03-02T10:04:34.000Z
"""Package version information - this file is dynamically overwritten in CI.""" __version__ = "0.0.0-dev"
35.333333
79
0.735849
15
106
4.933333
0.8
0.054054
0
0
0
0
0
0
0
0
0
0.032609
0.132075
106
2
80
53
0.771739
0.688679
0
0
0
0
0.333333
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
9e91fcd8769e0a959b21b0061de9d66421e4b737
3,423
py
Python
python/task.py
balder2046/my-program
53285cebb4852707596252ad93959a361144c595
[ "MIT" ]
null
null
null
python/task.py
balder2046/my-program
53285cebb4852707596252ad93959a361144c595
[ "MIT" ]
null
null
null
python/task.py
balder2046/my-program
53285cebb4852707596252ad93959a361144c595
[ "MIT" ]
null
null
null
import queue import threading class Task: def __init__(self,id,func): self.id = id self.func = func def run(self): self.func() class TaskQueue: def __init__(self): self.tasks = queue.Queue() pass def add_task(self,task): self.tasks.put(task) pass def cancel_task_by_id(self,id): pass def cancel_task(self,task): pass def pop_task(self): task = None try: task = self.tasks.get(block=True,timeout=0.1) except queue.Empty: pass return task def run_task(self,maxlimit = 0): if self.tasks.empty() : return if maxlimit <= 0: while not self.tasks.empty(): task = self.tasks.get() task.run() else: index = 0 while not self.tasks.empty(): task = self.tasks.get() task.run() index = index + 1 if index >= maxlimit : return class TaskManager: class _ThreadWrapper: def __init__(self,taskqueue): self.stop = False self.taskqueue = taskqueue pass def stop(self): self.stop = True def run(self): while not self.stop: task = self.taskqueue.pop_task() if task is not None: task.run() def __init__(self,threadcount = 3): self.main_queue = TaskQueue() self.async_queues = TaskQueue() self.name_async_queues = {} self.taskcount = 0 self.threadwrappers = [] self.set_thread_num(threadcount) pass def newid(self): self.taskcount += 1 return self.taskcount def set_thread_num(self,num): """ Set the thread num to the task manager. when num > current thread num , create new threads when num < current thread num, stop some threads and remove :param num: :return: """ nownum = len(self.threadwrappers) if nownum == num : return if nownum > num: for wrapper in self.threadwrappers[num :nownum]: wrapper.stop() del self.threadwrappers[num:nownum] else: for i in range(nownum,num): wrapper = TaskManager._ThreadWrapper(self.async_queues) thread = threading.Thread(None,wrapper.run) thread.setDaemon(True) thread.start() self.threadwrappers.append(wrapper) def add_async_task(self,func): newtask = Task(self.newid(),func) self.async_queues.add_task(newtask) def create_async_queue(self,name): taskqueue = TaskQueue() wrapper = TaskManager._ThreadWrapper(taskqueue) thread = threading.Thread(None,wrapper.run,name) thread.setDaemon(True) thread.start() self.name_async_queues[name] = wrapper def add_main_task(self,func): newtask = Task(self.newid(), func) self.main_queue.add_task(newtask) def add_name_task(self,name,func): newtask = Task(self.newid(), func) self.name_async_queues[name].taskqueue.add_task(newtask) def run_main_tasks(self,maxlimit): self.main_queue.run_task(maxlimit) def run_threads(self): pass
25.931818
98
0.556822
391
3,423
4.726343
0.196931
0.064935
0.02381
0.025974
0.230519
0.185065
0.11039
0.093074
0.093074
0.049784
0
0.004045
0.349985
3,423
131
99
26.129771
0.826517
0.049956
0
0.265306
0
0
0
0
0
0
0
0
0
1
0.204082
false
0.081633
0.020408
0
0.295918
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
9e93cbb866fe3d8bf04c4db2a4211c4222c4c706
242
py
Python
enki/modeltokenauth.py
charlf/enkiWS
789c789b2c0e46dcf568697dc2e46b82512981da
[ "Zlib" ]
1
2021-04-22T15:29:20.000Z
2021-04-22T15:29:20.000Z
enki/modeltokenauth.py
charlf/enkiWS
789c789b2c0e46dcf568697dc2e46b82512981da
[ "Zlib" ]
null
null
null
enki/modeltokenauth.py
charlf/enkiWS
789c789b2c0e46dcf568697dc2e46b82512981da
[ "Zlib" ]
null
null
null
from google.appengine.ext.ndb import model class EnkiModelTokenAuth( model.Model ): token = model.StringProperty() # unique user_id = model.IntegerProperty() # the ndb ID nr time_created = model.DateTimeProperty( auto_now_add = True )
24.2
61
0.764463
31
242
5.83871
0.774194
0
0
0
0
0
0
0
0
0
0
0
0.144628
242
9
62
26.888889
0.874396
0.082645
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.2
0
1
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
0
0
1
0
0
2
9e943a138c43468dd627b5d3cdcbab7e5d1109cf
467
py
Python
backend/protobackend/cases/urls.py
TheRayOfSeasons/django-angular-stack-study
cf62c15e1bc4738f64fc453eb59ea7c1c5ff023b
[ "MIT" ]
null
null
null
backend/protobackend/cases/urls.py
TheRayOfSeasons/django-angular-stack-study
cf62c15e1bc4738f64fc453eb59ea7c1c5ff023b
[ "MIT" ]
null
null
null
backend/protobackend/cases/urls.py
TheRayOfSeasons/django-angular-stack-study
cf62c15e1bc4738f64fc453eb59ea7c1c5ff023b
[ "MIT" ]
null
null
null
from django.urls import path from .views import CaseDetailView from .views import CaseHomeView from .views import CaseListView from .views import LongLoadingView urlpatterns = [ path('', CaseHomeView.as_view(), name='root'), path('list/', CaseListView.as_view(), name='list'), path('detail/<str:pk>/', CaseDetailView.as_view(), name='detail'), path( 'long/test/', LongLoadingView.as_view(), name='long_load_test' ) ]
21.227273
70
0.668094
54
467
5.666667
0.407407
0.117647
0.196078
0
0
0
0
0
0
0
0
0
0.188437
467
21
71
22.238095
0.807388
0
0
0
0
0
0.126338
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
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
0
0
0
1
0
0
0
0
2
9ea2320b1249a28fb4899f53811a432a6df0cb8d
219
py
Python
atomos/__about__.py
maxcountryman/atomos
418746c69134efba3c4f999405afe9113dee4827
[ "BSD-3-Clause" ]
75
2015-01-02T20:35:31.000Z
2022-03-29T01:17:30.000Z
atomos/__about__.py
maxcountryman/atomos
418746c69134efba3c4f999405afe9113dee4827
[ "BSD-3-Clause" ]
9
2015-03-13T15:14:02.000Z
2021-06-25T15:40:48.000Z
atomos/__about__.py
maxcountryman/atomos
418746c69134efba3c4f999405afe9113dee4827
[ "BSD-3-Clause" ]
9
2015-03-12T23:12:12.000Z
2022-03-24T23:33:17.000Z
# -*- coding: utf-8 -*- __title__ = 'atomos' __version_info__ = ('0', '3', '1') __version__ = '.'.join(__version_info__) __author__ = 'Max Countryman' __license__ = 'BSD' __copyright__ = 'Copyright 2014 Max Countryman'
27.375
47
0.689498
24
219
5.041667
0.75
0.181818
0
0
0
0
0
0
0
0
0
0.042105
0.13242
219
7
48
31.285714
0.594737
0.09589
0
0
0
0
0.285714
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
9ea404d962de3e4547c261ce54c483d1257e51b0
469
py
Python
datumaro/datumaro/components/converter.py
AzaelCicero/cvat
fa9b463d0eb07497ad74f24c823b5060544fdd6b
[ "MIT" ]
2
2020-01-10T08:50:50.000Z
2020-01-23T06:11:11.000Z
datumaro/datumaro/components/converter.py
AzaelCicero/cvat
fa9b463d0eb07497ad74f24c823b5060544fdd6b
[ "MIT" ]
24
2020-11-13T18:43:15.000Z
2022-03-12T00:21:52.000Z
datumaro/datumaro/components/converter.py
AzaelCicero/cvat
fa9b463d0eb07497ad74f24c823b5060544fdd6b
[ "MIT" ]
5
2020-07-01T18:02:48.000Z
2021-01-22T02:21:48.000Z
# Copyright (C) 2019 Intel Corporation # # SPDX-License-Identifier: MIT class Converter: def __init__(self, cmdline_args=None): pass def __call__(self, extractor, save_dir): raise NotImplementedError() def _parse_cmdline(self, cmdline): parser = self.build_cmdline_parser() if len(cmdline) != 0 and cmdline[0] == '--': cmdline = cmdline[1:] args = parser.parse_args(cmdline) return vars(args)
24.684211
52
0.633262
54
469
5.222222
0.62963
0.078014
0
0
0
0
0
0
0
0
0
0.020057
0.255864
469
19
53
24.684211
0.787966
0.138593
0
0
0
0
0.005
0
0
0
0
0
0
1
0.272727
false
0.090909
0
0
0.454545
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
9ebd60318507fdbc573b698af0a680735510b16a
1,048
py
Python
metasub_utils/zurich/metasub_utils/zurich/sftp_server.py
MetaSUB/metasub_utils
c52c5dde816d710db5ac8dc6f8804bb795a992e4
[ "MIT" ]
8
2018-12-30T23:35:03.000Z
2022-02-22T09:43:48.000Z
metasub_utils/zurich/metasub_utils/zurich/sftp_server.py
MetaSUB/metasub_utils
c52c5dde816d710db5ac8dc6f8804bb795a992e4
[ "MIT" ]
5
2019-01-05T04:54:46.000Z
2021-03-10T08:59:16.000Z
metasub_utils/zurich/metasub_utils/zurich/sftp_server.py
MetaSUB/metasub_utils
c52c5dde816d710db5ac8dc6f8804bb795a992e4
[ "MIT" ]
2
2019-08-26T22:08:18.000Z
2020-02-24T19:57:17.000Z
import pysftp from .constants import * class SFTPKnex: def __init__(self, username, password, dryrun=False): self.dryrun = dryrun cnopts = pysftp.CnOpts() cnopts.hostkeys = None self.knex = pysftp.Connection(URL, username=username, password=password, cnopts=cnopts) def close(self): self.knex.close() def __enter__(self): pass def __exit__(self): return self.close() def upload_file(self, localpath, remotepath): print(f'[SFTP Knex] UPLOAD {localpath} {remotepath}') if self.dryrun: return self.knex.put(localpath, remotepath=remotepath) def make_symlink(self, source_path, target_path): print(f'[SFTP Knex] SYMLINK {source_path} {target_path}') if self.dryrun: return self.knex.symlink(source_path, target_path) def make_dirs(self, remote_dirs): print(f'[SFTP Knex] MAKEDIRS {remote_dirs}') if self.dryrun: return self.knex.makedirs(remote_dirs)
26.871795
95
0.631679
123
1,048
5.186992
0.333333
0.062696
0.047022
0.065831
0.213166
0.213166
0
0
0
0
0
0
0.265267
1,048
38
96
27.578947
0.828571
0
0
0.206897
0
0
0.118321
0
0
0
0
0
0
1
0.241379
false
0.103448
0.068966
0.034483
0.482759
0.103448
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
9ebfc445844a8edd4ae12a7e14d4a5e67a5a30ed
5,320
py
Python
covid19_visualization.py
gilangsamudra/COVID19-Visualization-2020
d94e5aad6d45bb6c51f2cc9553f5adf700a95ed3
[ "MIT" ]
null
null
null
covid19_visualization.py
gilangsamudra/COVID19-Visualization-2020
d94e5aad6d45bb6c51f2cc9553f5adf700a95ed3
[ "MIT" ]
null
null
null
covid19_visualization.py
gilangsamudra/COVID19-Visualization-2020
d94e5aad6d45bb6c51f2cc9553f5adf700a95ed3
[ "MIT" ]
null
null
null
import pandas as pd import matplotlib.pyplot as plt # Bagian 1 -- Load data dari sumbernya df = pd.read_csv( 'https://raw.githubusercontent.com/datasets/covid-19/\ master/data/countries-aggregated.csv', parse_dates=['Date']) # Bagian 2 -- Melakukan filter data untuk data Malaysia dan Indonesia negara = ["Indonesia", "Malaysia", 'Singapore'] df = df[df["Country"].isin(negara)] # Bagian 3 -- Menambahkan kolom total Case, fatality rate, dan cure rate df['Cases'] = df.iloc[:, 2:5].sum(axis=1) df['FRates'] = ((df['Deaths']/df['Cases'])*100).fillna(0) df['CRates'] = ((df['Recovered']/df['Cases'])*100).fillna(0) covid19 = df.pivot(index='Date', columns='Country', values='Confirmed') cured = df.pivot(index='Date', columns='Country', values='Recovered') death = df.pivot(index='Date', columns='Country', values='Deaths') frate = df.pivot(index='Date', columns='Country', values='FRates') crate = df.pivot(index='Date', columns='Country', values='CRates') plt.style.use('fivethirtyeight') plt.figure(num=1, dpi=200) plot = covid19.plot(grid=False, fontsize=15, figsize=(12, 8), linewidth=5, legend=False, ax=plt.gca()) plot.grid(b=True, which='major', axis='y', ls='--', lw=.5, c='k', alpha=.3) plot.set_title("COVID-19 Confimed Case", fontweight='bold', loc='center') plot.set_xlabel('Dates') plot.set_ylabel('# of Infected') for country in negara: plot.text(x=covid19.index[-1], y=int(covid19[country].tail(1)), s=country+": "+str(int(covid19[country].tail(1))), fontsize=15) plot.text(x=covid19.index[1], y=-1850, s='Source: https://github.com/datasets/\ covid-19/blob/master/data/countries-aggregated.csv', fontsize=12, fontweight='bold') plot.text(x=covid19.index[1], y=-2100, s="by: GSK", fontsize=12, fontweight='bold') plt.savefig('Infected Number.png', bbox_inches="tight") plt.figure(num=2, dpi=200) plot = death.plot(grid=False, fontsize=15, figsize=(12, 8), linewidth=5, legend=False, ax=plt.gca()) plot.grid(b=True, which='major', axis='y', ls='--', lw=.5, c='k', alpha=.3) plot.set_title("COVID-19 Total Death", fontweight='bold', loc='center') plot.set_xlabel('Dates') plot.set_ylabel('# of Death') for country in negara: plot.text(x=death.index[-1], y=int(death[country].tail(1)), s=country+": "+str(int(death[country].tail(1))), fontsize=15) plot.text(x=covid19.index[1], y=-160, s='Source: https://github.com/datasets/\ covid-19/blob/master/data/countries-aggregated.csv', fontsize=12, fontweight='bold') plot.text(x=covid19.index[1], y=-180, s="by: GSK", fontsize=12, fontweight='bold') plt.savefig('Death Number.png', bbox_inches="tight") plt.figure(num=5, dpi=200) plot = cured.plot(grid=False, fontsize=15, figsize=(12, 8), linewidth=5, legend=False, ax=plt.gca()) plot.grid(b=True, which='major', axis='y', ls='--', lw=.5, c='k', alpha=.3) plot.set_title("COVID-19 Total Recovered", fontweight='bold', loc='center') plot.set_xlabel('Dates') plot.set_ylabel('# of Recovered') for country in negara: plot.text(x=cured.index[-1], y=int(cured[country].tail(1)), s=country+": "+str(int(cured[country].tail(1))), fontsize=15) plot.text(x=covid19.index[1], y=-160, s='Source: https://github.com/datasets/\ covid-19/blob/master/data/countries-aggregated.csv', fontsize=12, fontweight='bold') plot.text(x=covid19.index[1], y=-180, s="by: GSK", fontsize=12, fontweight='bold') plt.savefig('Cured Number.png', bbox_inches="tight") plt.figure(num=3, dpi=200) plot = frate.plot(grid=False, fontsize=15, figsize=(12, 8), linewidth=5, legend=False, ax=plt.gca()) plot.grid(b=True, which='major', axis='y', ls='--', lw=.5, c='k', alpha=.3) plot.set_title("COVID-19 Fatality Rate", fontweight='bold', loc='center') plot.set_xlabel('Dates') plot.set_ylabel('Fatality Rate (%)') for country in negara: plot.text(x=frate.index[-1], y=float(frate[country].tail(1)), s=country+": "+str(float("%.2f" % frate[country].tail(1)))+'%', fontsize=15) plot.text(x=covid19.index[1], y=-2.5, s='Source: https://github.com/datasets/\ covid-19/blob/master/data/countries-aggregated.csv', fontsize=12, fontweight='bold') plot.text(x=covid19.index[1], y=-2.8, s="by: GSK", fontsize=12, fontweight='bold') plt.savefig('Fatality Rate.png', bbox_inches="tight") plt.figure(num=4, dpi=200) plot = crate.plot(grid=False, fontsize=15, figsize=(12, 8), linewidth=5, legend=False, ax=plt.gca()) plot.grid(b=True, which='major', axis='y', ls='--', lw=.5, c='k', alpha=.3) plot.set_title("COVID-19 Recovered Rate", fontweight='bold', loc='center') plot.set_xlabel('Dates') plot.set_ylabel('Recovered Rate (%)') for country in negara: plot.text(x=crate.index[-1], y=float(crate[country].tail(1)), s=country+": "+str(float("%.2f" % crate[country].tail(1)))+'%', fontsize=15) plot.text(x=covid19.index[1], y=-2.5, s='Source: https://github.com/datasets/\ covid-19/blob/master/data/countries-aggregated.csv', fontsize=12, fontweight='bold') plot.text(x=covid19.index[1], y=-2.8, s="by: GSK", fontsize=12, fontweight='bold') plt.savefig('Recovered Rate.png', bbox_inches="tight")
45.470085
79
0.650752
812
5,320
4.236453
0.167488
0.030523
0.039244
0.051163
0.782558
0.743314
0.743314
0.631977
0.565116
0.553488
0
0.0459
0.135902
5,320
116
80
45.862069
0.702415
0.032895
0
0.465347
0
0
0.137133
0
0
0
0
0
0
1
0
false
0
0.019802
0
0.019802
0
0
0
0
null
0
0
0
0
1
1
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
7b386c29db12d1fcff3de5e3ebd565a3f8f80c2b
1,275
py
Python
src/estimagic/optimization/__init__.py
janosg/estimagic
58e17ff94339076f4b7688b1dbef5685f48157e2
[ "BSD-3-Clause" ]
7
2019-05-11T07:19:46.000Z
2019-05-31T07:03:13.000Z
src/estimagic/optimization/__init__.py
janosg/estimagic
58e17ff94339076f4b7688b1dbef5685f48157e2
[ "BSD-3-Clause" ]
14
2019-05-04T14:15:52.000Z
2019-06-10T11:45:27.000Z
src/estimagic/optimization/__init__.py
janosg/estimagic
58e17ff94339076f4b7688b1dbef5685f48157e2
[ "BSD-3-Clause" ]
1
2019-05-21T08:44:37.000Z
2019-05-21T08:44:37.000Z
import inspect from estimagic.optimization import bhhh from estimagic.optimization import cyipopt_optimizers from estimagic.optimization import fides_optimizers from estimagic.optimization import nag_optimizers from estimagic.optimization import neldermead from estimagic.optimization import nlopt_optimizers from estimagic.optimization import pounders from estimagic.optimization import pygmo_optimizers from estimagic.optimization import scipy_optimizers from estimagic.optimization import tao_optimizers MODULES = [ cyipopt_optimizers, fides_optimizers, nag_optimizers, nlopt_optimizers, pygmo_optimizers, scipy_optimizers, tao_optimizers, bhhh, neldermead, pounders, ] ALL_ALGORITHMS = {} AVAILABLE_ALGORITHMS = {} for module in MODULES: func_dict = dict(inspect.getmembers(module, inspect.isfunction)) for name, func in func_dict.items(): if hasattr(func, "_algorithm_info"): ALL_ALGORITHMS[name] = func if func._algorithm_info.is_available: AVAILABLE_ALGORITHMS[name] = func GLOBAL_ALGORITHMS = [ "nlopt_direct", "nlopt_esch", "nlopt_isres", "nlopt_crs2_lm", ] GLOBAL_ALGORITHMS += [name for name in AVAILABLE_ALGORITHMS if name.startswith("pygmo")]
27.12766
88
0.761569
142
1,275
6.605634
0.288732
0.138593
0.266525
0.33049
0.26226
0
0
0
0
0
0
0.00095
0.174118
1,275
46
89
27.717391
0.889839
0
0
0
0
0
0.051765
0
0
0
0
0
0
1
0
false
0
0.282051
0
0.282051
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
7b419d6e1e869080a99431fa87c917a7ba0fb977
259
py
Python
lessons/thw-testing/mean.py
burkesquires/bc
8430271460d678fe321ea22ac5fcefb9ca9cb525
[ "CC-BY-3.0" ]
18
2016-11-20T17:10:22.000Z
2021-09-10T05:40:06.000Z
lessons/thw-testing/mean.py
BernhardKonrad/2014-02-22-SFU
25cfac5f703943ddaa98cc30bb267eacba48d07f
[ "CC-BY-3.0" ]
8
2015-01-13T21:29:54.000Z
2016-08-01T10:26:45.000Z
lessons/thw-testing/mean.py
BernhardKonrad/2014-02-22-SFU
25cfac5f703943ddaa98cc30bb267eacba48d07f
[ "CC-BY-3.0" ]
16
2015-01-15T15:31:52.000Z
2016-06-29T19:15:47.000Z
def mean(numlist): try : total = sum(numlist) length = len(numlist) except TypeError : raise TypeError("The list was not numbers.") except : print "Something unknown happened with the list." return total/length
25.9
57
0.617761
30
259
5.333333
0.733333
0.0875
0
0
0
0
0
0
0
0
0
0
0.301158
259
9
58
28.777778
0.883978
0
0
0
0
0
0.254826
0
0
0
0
0
0
0
null
null
0
0
null
null
0.111111
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
1
0
0
0
0
0
0
0
0
2
7b552842777c1171fcfa9371e03619f090e43c52
741
py
Python
eblog/urls.py
pandamasta/django-eblog
13fdb27ff9584b848c512b9919a21dd3c0992816
[ "BSD-3-Clause" ]
4
2015-05-18T13:50:53.000Z
2015-05-18T14:47:27.000Z
eblog/urls.py
pandamasta/django-eblog
13fdb27ff9584b848c512b9919a21dd3c0992816
[ "BSD-3-Clause" ]
null
null
null
eblog/urls.py
pandamasta/django-eblog
13fdb27ff9584b848c512b9919a21dd3c0992816
[ "BSD-3-Clause" ]
null
null
null
from django.conf.urls import * from django.views.generic import TemplateView from views import * from models import Entry from models import Category urlpatterns = patterns('', url(r'^(?P<year>\d{4})/$', YearsView.as_view(), name="blog_years"), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/$', MonthView.as_view(), name="blog_archive_month"), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$', DayView.as_view(), name="blog_archive_day"), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[\w-]+)/$',DetailView.as_view(), name="blog_detail"), url(r'^category/(?P<slug>[\w-]+)/$', CategoryView.as_view(), name="blog_category_detail"), url(r'^$', ArchiveView.as_view(), name="blog_archive"), );
43.588235
121
0.623482
118
741
3.788136
0.313559
0.053691
0.134228
0.187919
0.319911
0.178971
0.154362
0.154362
0.154362
0.154362
0
0.013453
0.097166
741
16
122
46.3125
0.654709
0
0
0
0
0.153846
0.387838
0.243243
0
0
0
0
0
1
0
false
0
0.384615
0
0.384615
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
7b69c2532a80c44486e8e15eae0f53a4ec60e885
16,308
py
Python
Python_Controle_Multimidia_Universal/trunk/Controle/ControlMultimediaUniversal.py
felipelindemberg/ControleMultimidiaUniversal
491487411bc63db497943fac78b810ac7e37ef44
[ "Apache-2.0" ]
1
2019-02-15T03:08:07.000Z
2019-02-15T03:08:07.000Z
Python_Controle_Multimidia_Universal/trunk/Controle/ControlMultimediaUniversal.py
felipelindemberg/ControleMultimidiaUniversal
491487411bc63db497943fac78b810ac7e37ef44
[ "Apache-2.0" ]
null
null
null
Python_Controle_Multimidia_Universal/trunk/Controle/ControlMultimediaUniversal.py
felipelindemberg/ControleMultimidiaUniversal
491487411bc63db497943fac78b810ac7e37ef44
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 #!/usr/bin/python import pygame from pygame.locals import * # @UnusedWildImport @IgnorePep8 import os import sys from ServerBluetooth import * from ThreadBluetooth import * lib_path = os.path.abspath('Util/') sys.path.append(lib_path) try: import Network as util from Pygame import loadSprite except ImportError: print("erro ao importar") # variaveis do sistema class ControlMultimediaUniversal: """A Classe ControlMultimediaUniversal é uma classe que faz o controle dos equipamentos presentes no cômodo em que o mesmo se encontra :version 164 :author Lucas Salvino """ def __init__(self): """Construtor da classe """ pygame.init() # carrega imagens self.__ip_residence = util.getResidenceIp() if (self.__ip_residence != "Residence is offline"): self.font = None self.__pressed = False self.__buttonTVTurnedOn = True self.__buttonSoundTurnedOn = False self.__port = 5432 self.__sprites = {} self.__screen = pygame.display.set_mode((290, 590)) pygame.display.set_caption('Controle') self.__background = pygame.Surface(self.__screen.get_size()).convert() self.__room = None self.__background.fill((0, 0, 0)) self.__loadSprites() self.__thread = threadBluetooth(self.__ip_residence) # __thread.setDaemon(True) self.__thread.start() else: self.__screen = pygame.display.set_mode((600, 300)) self.__background = pygame.Surface(self.__screen.get_size()).convert() self.__room = None self.__background.fill((0, 0, 0)) pygame.display.set_caption('Residência não encontrada') self.__background = pygame.Surface(self.__screen.get_size()).convert() pygame.font.get_fonts() self.font = pygame.font.Font(os.path.abspath("Controle/font/ALPNSCND.TTF"), 45, bold = False) countToQuit = 0 label = self.font.render("RESIDENCIA", 1, (255, 0, 0)) label2 = self.font.render("OFFLINE", 1, (255, 0, 0)) clock = pygame.time.Clock() while True: if countToQuit == 5: pygame.quit() os._exit(0) for event in pygame.event.get(): if event == None: break if event.type == QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): pygame.quit() os._exit(0) self.__screen.blit(self.__background, (0, 0)) self.__screen.blit(label, (0, 80)) self.__screen.blit(label2, (50, 130)) pygame.display.flip() clock.tick(1) countToQuit += 1 # funcionalidades do controle-> COLOCAR FUNCOES AKI<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< # checa __room def __loadSprites(self): """Método que faz o carregamento das imagens """ self.__sprites["button_mute"] = loadSprite("Controle/images/mudo.png") self.__sprites["button_mute_animation"] = loadSprite("Controle/images/mudo_branco.png") self.__sprites["background_control"] = loadSprite("Controle/images/background.png") self.__sprites["display1"] = loadSprite("Controle/images/visor.png") self.__sprites["display"] = pygame.transform.scale(self.__sprites.get("display1"), (290, 160)) self.__sprites["button_sound"] = loadSprite("Controle/images/som.png") self.__sprites["button_sound_animation"] = loadSprite("Controle/images/som_branco.png") self.__sprites["button_tv"] = loadSprite("Controle/images/TV.png") self.__sprites["button_tv_animation"] = loadSprite("Controle/images/TV_branco.png") self.__sprites["button_channelDown"] = loadSprite("Controle/images/mudar_canal1.png") self.__sprites["button_channelDown_animation"] = loadSprite("Controle/images/mudar_canal1_brancos.png") self.__sprites["button_channelUp"] = loadSprite("Controle/images/mudar_canal2.png") self.__sprites["button_channelUp_animation"] = loadSprite("Controle/images/mudar_canal2_branco.png") self.__sprites["button_volumeDown"] = loadSprite("Controle/images/diminuir_volume.png") self.__sprites["button_volumeDown_animation"] = loadSprite("Controle/images/diminuir_volume_branco.png") self.__sprites["button_volumeUp"] = loadSprite("Controle/images/aumentar_volume.png") self.__sprites["button_volumeUp_animation"] = loadSprite("Controle/images/aumentar_volume_branco.png") self.__sprites["button_turnOff"] = loadSprite("Controle/images/image.png") self.__sprites["button_turnOff_animation"] = loadSprite("Controle/images/image_branco.png") def __printText(self, txtText, Textx, Texty, Textcolor): """Método que imprime textos """ pygame.font.get_fonts() # cor = (255,255,255) # myfont = pygame.font.SysFont(Textfont, Textsize) #self.font = pygame.font.Font(os.path.abspath("Controle/font/ALPNSCND.TTF"), 45, bold = False) # __room = font.render(txtText, False, cor) self.font = pygame.font.Font(os.path.abspath("Controle/font/ALPNSCND.TTF"), 45, bold = False) label = self.font.render(txtText, 1, Textcolor) self.__screen.blit(label, (Textx, Texty)) def __sendCommand(self, command): """Método que envia comandos :Param command: Comando :Type command: String :Return: Requisição Http Post em Residência :Rtype: Requisição Http Post """ # o command tem que ser uma string # TV if (self.__room != None and self.__room != ""): params = None if self.__buttonTVTurnedOn == True: params = {"nameRoom": self.__room, "equipment":"tv", "command": command} print (params) # SOM if self.__buttonSoundTurnedOn == True: params = {"nameRoom": self.__room, "equipment":"som", "command": command} print (params) self.__pressed = True return util.httpPostRequest(self.__ip_residence, self.__port, "sendCommand", params) def getIp(self): return self.__ip_residence def drawScreen(self, position): """Método que exibe uma tela com o nome do cômodo em que o controle se encontra """ self.__screen.blit(self.__background, (0, 0)) self.__screen.blit(self.__sprites.get("background_control"), (-10, -12)) self.__room = self.__thread.getRoom() if self.__room != None: self.__printText(self.__room, -position, 200, Color("red")) else: if position > -300: self.__printText("", 70, 200, Color("red")) if position > -150: self.__printText(".", 70, 200, Color("red")) if position > 0: self.__printText("..", 70, 200, Color("red")) if position > 150: self.__printText("...", 70, 200, Color("red")) self.__screen.blit(self.__sprites.get("display"), (-1, 138)) if self.__buttonSoundTurnedOn: self.__screen.blit(self.__sprites.get("button_sound_animation"), (190, 70)) else: self.__screen.blit(self.__sprites.get("button_sound"), (190, 70)) if self.__buttonTVTurnedOn: self.__screen.blit(self.__sprites.get("button_tv_animation"), (30, 70)) else: self.__screen.blit(self.__sprites.get("button_tv"), (30, 70)) # captura de eventos dos botoes def __unpressButton(self, eventReceiver): """Método que despressiona o botão :Param event: Evento Pygame a ser capturado :Type event: Evento Pygame """ if (eventReceiver.type == MOUSEBUTTONUP and eventReceiver.button == 1) and self.__pressed: self.__pressed = False def __isPressedButton(self, eventReceiver): """Método que verifica se o botão foi pressionado :Param event: Evento Pygame a ser checado :Type event: Evento Pygame """ return(eventReceiver.type == MOUSEBUTTONDOWN and eventReceiver.button == 1) and not self.__pressed def __capturePositionMouseX(self, minor, major): """Método que captura a posição do cursor no eixo X do plano cartesiano :Param minor: Menor limite de X :Type minor: Inteiro :Param major: Maior limite de X :Type major: Inteiro :Return: Inteiro referente a posição :Return: Inteiro """ return major > pygame.mouse.get_pos()[0] > minor def __capturePositionMouseY(self, minor, major): """Método que captura a posição do cursor no eixo Y do plano cartesiano :Param minor: Menor limite de Y :Type minor: Inteiro :Param major: Maior limite de Y :Type major: Inteiro :Return: Inteiro referente a posição :Rtype: Inteiro """ return major > pygame.mouse.get_pos()[1] > minor def turnOffCaptureEvent(self, eventReceiver): """Método que desliga o aparelho" :Param event: Evento do Pygame a ser checado :Type event: Evento Pygame """ if self.__isPressedButton(eventReceiver) and self.__capturePositionMouseX(110, 200) and self.__capturePositionMouseY(45, 135): self.__sendCommand("power") self.__unpressButton(eventReceiver) def optionTVCaptureEvent(self, eventReceiver): """Método que seleciona a opção TV :Param event: Evento do Pygame a ser checado :Type event: Evento Pygame """ if self.__isPressedButton(eventReceiver) and self.__capturePositionMouseX(30, 120) and self.__capturePositionMouseY(70, 160): self.__pressed = True print "controll" if self.__buttonSoundTurnedOn: self.__buttonSoundTurnedOn = False self.__buttonTVTurnedOn = True elif not self.__buttonTVTurnedOn: self.__buttonTVTurnedOn = True self.__unpressButton(eventReceiver) def optionSoundCaptureEvent(self, eventReceiver): """Método que seleciona a opção Som :Param event: Evento do Pygame a ser checado :Type event: Evento Pygame """ if self.__isPressedButton(eventReceiver) and self.__capturePositionMouseX(190, 280) and self.__capturePositionMouseY(70, 160): self.__pressed = True if self.__buttonTVTurnedOn: self.__buttonTVTurnedOn = False self.__buttonSoundTurnedOn = True elif not self.__buttonSoundTurnedOn: self.__buttonSoundTurnedOn = True self.__unpressButton(eventReceiver) def upVolumeCaptureEvent(self, eventReceiver): """Método que aumenta o volume :Param event: Evento do Pygame a ser checado :Type event: Evento Pygame """ if self.__isPressedButton(eventReceiver) and self.__capturePositionMouseX(192, 275) and self.__capturePositionMouseY(400, 490): self.__sendCommand("upvolume") def downVolumeCaptureEvent(self, eventReceiver): """Método que diminui o volume :Param event: Evento do Pygame a ser checado :Type event: Evento Pygame """ if self.__isPressedButton(eventReceiver) and self.__capturePositionMouseX(35, 118) and self.__capturePositionMouseY(400, 490): self.__sendCommand("downvolume") self.__unpressButton(eventReceiver) def upChannelCaptureEvent(self, eventReceiver): """Método que aumenta o canal :Param event: Evento do Pygame a ser checado :Type event: Evento Pygame """ if self.__isPressedButton(eventReceiver) and self.__capturePositionMouseX(110, 200) and self.__capturePositionMouseY(325, 408): self.__sendCommand("upChannel") self.__unpressButton(eventReceiver) def downChannelCaptureEvent(self, eventReceiver): """Método que diminui o canal :Param event: Evento do Pygame a ser checado :Type event: Evento Pygame """ if self.__isPressedButton(eventReceiver) and self.__capturePositionMouseX(110, 200) and self.__capturePositionMouseY(482, 565): self.__sendCommand("downChannel") self.__unpressButton(eventReceiver) def muteCaptureEvent(self, eventReceiver): """Método que coloca o aparelho na opção "mudo" :Param event: Evento do Pygame a ser checado :Type event: Evento Pygame """ if self.__isPressedButton(eventReceiver) and self.__capturePositionMouseX(115, 160) and self.__capturePositionMouseY(410, 480): self.__sendCommand("mute") self.__unpressButton(eventReceiver) # animacoes dos botões def turnOffAnimation(self): """Método que simula o cursor em cima do botão desligar """ if self.__capturePositionMouseX(110, 200) and self.__capturePositionMouseY(45, 135): self.__screen.blit(self.__sprites.get("button_turnOff_animation"), (110, 45)) else: self.__screen.blit(self.__sprites.get("button_turnOff"), (110, 45)) def optionTVAnimation(self): """Método que simula o cursor em cima do botão TV """ if self.__capturePositionMouseX(30, 120) and self.__capturePositionMouseY(70, 160): self.__screen.blit(self.__sprites.get("button_tv_animation"), (30, 70)) def optionSoundAnimation(self): """Método que simula o cursor em cima do botão Som """ if self.__capturePositionMouseX(190, 280) and self.__capturePositionMouseY(70, 160): self.__screen.blit(self.__sprites.get("button_sound_animation"), (190, 70)) def upVolumeAnimation(self): """Método que simula o cursor em cima do botão aumentar volume """ if self.__capturePositionMouseX(195, 275) and self.__capturePositionMouseY(400, 490): self.__screen.blit(self.__sprites.get("button_volumeUp_animation"), (185, 400)) else: self.__screen.blit(self.__sprites.get("button_volumeUp"), (185, 400)) def downVolumeAnimation(self): """Método que simula o cursor em cima do botão diminuir volume """ if self.__capturePositionMouseX(35, 115) and self.__capturePositionMouseY(400, 490): self.__screen.blit(self.__sprites.get("button_volumeDown_animation"), (35, 400)) else: self.__screen.blit(self.__sprites.get("button_volumeDown"), (35, 400)) def changeChannelUPAnimation(self): """Método que simula o cursor em cima do botão aumentar canal """ if self.__capturePositionMouseX(110, 200) and self.__capturePositionMouseY(335, 400): self.__screen.blit(self.__sprites.get("button_channelUp_animation"), (110, 325)) else: self.__screen.blit(self.__sprites.get("button_channelUp"), (110, 325)) def changeChannelDownAnimation(self): """Método que simula o cursor em cima do botão diminuir canal """ if self.__capturePositionMouseX(110, 200) and self.__capturePositionMouseY(485, 565): self.__screen.blit(self.__sprites.get("button_channelDown_animation"), (110, 475)) else: self.__screen.blit(self.__sprites.get("button_channelDown"), (110, 475)) def muteAnimation(self): """Método que simula o cursor em cima do botão mute """ if self.__capturePositionMouseX(120, 185) and self.__capturePositionMouseY(410, 480): self.__screen.blit(self.__sprites.get("button_mute_animation"), (110, 400)) else: self.__screen.blit(self.__sprites.get("button_mute"), (110, 400)) def disconnectControl(self): """Método que desconecta o controle do cômodo que está sendo controlado """ params = {"nameRoom": self.__room} util.httpPostRequest(self.__ip_residence, self.__port, "disconnectControl", params)
43.257294
138
0.636681
1,759
16,308
5.629903
0.185333
0.045542
0.035343
0.039988
0.546501
0.466424
0.417752
0.383419
0.31546
0.276886
0
0.033635
0.254354
16,308
376
139
43.37234
0.780757
0.031948
0
0.262911
0
0
0.12616
0.078344
0
0
0
0.066489
0
0
null
null
0
0.046948
null
null
0.046948
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