blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
288
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 684
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 147
values | src_encoding
stringclasses 25
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 128
12.7k
| extension
stringclasses 142
values | content
stringlengths 128
8.19k
| authors
listlengths 1
1
| author_id
stringlengths 1
132
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ce2c59b57ea5030b3747f41fc82eb48cbecb159b
|
d44cbbed1061299c733239c513bfa7f530d97be2
|
/adminalerts/tests/test_permissions.py
|
13f3d1ee56e0790799de2df81bc0c2806d155c80
|
[
"MIT"
] |
permissive
|
raonyguimaraes/sodar_core
|
f6cb331b31476be595ff0d5a279b82f6871530ff
|
903eda944ed75aaf54b74d959ef634790c042e57
|
refs/heads/master
| 2022-07-24T20:00:33.442200
| 2020-04-24T14:03:47
| 2020-04-24T14:03:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,699
|
py
|
"""Tests for permissions in the adminalerts app"""
from django.urls import reverse
# Projectroles dependency
from projectroles.tests.test_permissions import TestPermissionBase
from adminalerts.tests.test_models import AdminAlertMixin
class TestAdminAlertPermissions(AdminAlertMixin, TestPermissionBase):
"""Tests for AdminAlert views"""
def setUp(self):
# Create users
self.superuser = self.make_user('superuser')
self.superuser.is_superuser = True
self.superuser.is_staff = True
self.superuser.save()
self.regular_user = self.make_user('regular_user')
# No user
self.anonymous = None
# Create alert
self.alert = self._make_alert(
message='alert',
user=self.superuser,
description='description',
active=True,
)
def test_alert_create(self):
"""Test permissions for AdminAlert creation"""
url = reverse('adminalerts:create')
good_users = [self.superuser]
bad_users = [self.anonymous, self.regular_user]
self.assert_response(url, good_users, 200)
self.assert_response(url, bad_users, 302)
def test_alert_update(self):
"""Test permissions for AdminAlert updating"""
url = reverse(
'adminalerts:update', kwargs={'adminalert': self.alert.sodar_uuid}
)
good_users = [self.superuser]
bad_users = [self.anonymous, self.regular_user]
self.assert_response(url, good_users, 200)
self.assert_response(url, bad_users, 302)
def test_alert_delete(self):
"""Test permissions for AdminAlert deletion"""
url = reverse(
'adminalerts:delete', kwargs={'adminalert': self.alert.sodar_uuid}
)
good_users = [self.superuser]
bad_users = [self.anonymous, self.regular_user]
self.assert_response(url, good_users, 200)
self.assert_response(url, bad_users, 302)
def test_alert_list(self):
"""Test permissions for AdminAlert list"""
url = reverse('adminalerts:list')
good_users = [self.superuser]
bad_users = [self.anonymous, self.regular_user]
self.assert_response(url, good_users, 200)
self.assert_response(url, bad_users, 302)
def test_alert_detail(self):
"""Test permissions for AdminAlert details"""
url = reverse(
'adminalerts:detail', kwargs={'adminalert': self.alert.sodar_uuid}
)
good_users = [self.superuser, self.regular_user]
bad_users = [self.anonymous]
self.assert_response(url, good_users, 200)
self.assert_response(url, bad_users, 302)
|
[
"mikko.nieminen@bihealth.de"
] |
mikko.nieminen@bihealth.de
|
beca6c6a6fdc8c07bf59fafda1a3c0a1f35f7377
|
f13acd0d707ea9ab0d2f2f010717b35adcee142f
|
/ABC/abc101-abc150/abc125/d.py
|
65d866fb02f012f8ac51ed868bc202f0c9c93fe5
|
[
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
KATO-Hiro/AtCoder
|
126b9fe89fa3a7cffcbd1c29d42394e7d02fa7c7
|
bf43320bc1af606bfbd23c610b3432cddd1806b9
|
refs/heads/master
| 2023-08-18T20:06:42.876863
| 2023-08-17T23:45:21
| 2023-08-17T23:45:21
| 121,067,516
| 4
| 0
|
CC0-1.0
| 2023-09-14T21:59:38
| 2018-02-11T00:32:45
|
Python
|
UTF-8
|
Python
| false
| false
| 426
|
py
|
# -*- coding: utf-8 -*-
def main():
n = int(input())
a = list(map(int, input().split()))
minus_count = 0
abs_min = float('inf')
ans = 0
for ai in a:
if ai < 0:
minus_count += 1
abs_min = min(abs_min, abs(ai))
ans += abs(ai)
if minus_count % 2 == 1:
ans -= abs_min * 2
print(ans)
if __name__ == '__main__':
main()
|
[
"k.hiro1818@gmail.com"
] |
k.hiro1818@gmail.com
|
1c65e874cc500c5891439e350e89441caa59a097
|
14abe13bff2c346430ec7129c49a79ff4f52c5b0
|
/canteen_tests/test__main__.py
|
30b0a9135238a41d45d9bfcb92a8f477f5f1e761
|
[
"MIT"
] |
permissive
|
ianjw11/canteen
|
9a3122deed73a545aa8cc0c51b6913e945e23e39
|
cfc4ef00ec67df97e08b57222ca16aa9f2659a3e
|
refs/heads/master
| 2021-01-21T02:41:11.139310
| 2014-07-09T15:59:05
| 2014-07-09T15:59:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 388
|
py
|
# -*- coding: utf-8 -*-
'''
canteen: main tests
~~~~~~~~~~~~~~~~~~~
tests things at the top-level package main for canteen.
:author: Sam Gammon <sg@samgammon.com>
:copyright: (c) Sam Gammon, 2014
:license: This software makes use of the MIT Open Source License.
A copy of this license is included as ``LICENSE.md`` in
the root of the project.
'''
|
[
"sam@keen.io"
] |
sam@keen.io
|
3d2bd8ff970e7a9fa6ed06d06362d446b3f710cd
|
41dbb27af3a3ecabeb06e2fb45b3440bcc9d2b75
|
/client/migrations/0001_initial.py
|
8e69fdd04b310bf4d984b437435a5d02419dcaa0
|
[] |
no_license
|
joypaulgmail/Dookan
|
4df83f37b7bcaff9052d5a09854d0bb344b9f05a
|
7febf471dd71cc6ce7ffabce134e1e37a11309f7
|
refs/heads/main
| 2023-03-02T04:10:19.611371
| 2021-02-09T11:45:32
| 2021-02-09T11:45:32
| 336,476,910
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,240
|
py
|
# Generated by Django 3.1 on 2020-11-28 06:01
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='ClientDetail',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=60)),
('primary_contact', models.IntegerField()),
('secondary_contact', models.IntegerField()),
('address', models.TextField()),
('pin', models.IntegerField()),
('image', models.ImageField(upload_to='client/')),
('idproof', models.ImageField(upload_to='client/id')),
('password', models.CharField(max_length=50)),
('confirm_password', models.CharField(max_length=50)),
],
options={
'db_table': 'clientdetail',
},
),
migrations.CreateModel(
name='ClientInfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=60)),
('primary_contact', models.IntegerField()),
('secondary_contact', models.IntegerField()),
('address', models.TextField()),
('pin', models.IntegerField()),
('image', models.ImageField(upload_to='client/')),
('idproof', models.ImageField(upload_to='client/id')),
('password', models.CharField(max_length=50)),
('confirm_password', models.CharField(max_length=50)),
],
),
migrations.CreateModel(
name='detail',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=20)),
('roll', models.IntegerField()),
],
options={
'db_table': 'detail',
},
),
]
|
[
"joypaul650@gmail.com"
] |
joypaul650@gmail.com
|
5138f623d82eed67afff76da96329637b5feec7f
|
853d4cec42071b76a80be38c58ffe0fbf9b9dc34
|
/venv/Lib/site-packages/pandas/tests/sparse/test_pivot.py
|
44a8194bd5813d75ac10e22e2c0fafc7a5de7834
|
[] |
no_license
|
msainTesting/TwitterAnalysis
|
5e1646dbf40badf887a86e125ef30a9edaa622a4
|
b1204346508ba3e3922a52380ead5a8f7079726b
|
refs/heads/main
| 2023-08-28T08:29:28.924620
| 2021-11-04T12:36:30
| 2021-11-04T12:36:30
| 424,242,582
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,369
|
py
|
import numpy as np
import pytest
import pandas as pd
import pandas.util.testing as tm
@pytest.mark.filterwarnings("ignore:Sparse:FutureWarning")
@pytest.mark.filterwarnings("ignore:Series.to_sparse:FutureWarning")
@pytest.mark.filterwarnings("ignore:DataFrame.to_sparse:FutureWarning")
class TestPivotTable:
def setup_method(self, method):
rs = np.random.RandomState(0)
self.dense = pd.DataFrame(
{
"A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
"B": ["one", "one", "two", "three", "two", "two", "one", "three"],
"C": rs.randn(8),
"D": rs.randn(8),
"E": [np.nan, np.nan, 1, 2, np.nan, 1, np.nan, np.nan],
}
)
self.sparse = self.dense.to_sparse()
def test_pivot_table(self):
res_sparse = pd.pivot_table(self.sparse, index="A", columns="B", values="C")
res_dense = pd.pivot_table(self.dense, index="A", columns="B", values="C")
tm.assert_frame_equal(res_sparse, res_dense)
res_sparse = pd.pivot_table(self.sparse, index="A", columns="B", values="E")
res_dense = pd.pivot_table(self.dense, index="A", columns="B", values="E")
tm.assert_frame_equal(res_sparse, res_dense)
res_sparse = pd.pivot_table(
self.sparse, index="A", columns="B", values="E", aggfunc="mean"
)
res_dense = pd.pivot_table(
self.dense, index="A", columns="B", values="E", aggfunc="mean"
)
tm.assert_frame_equal(res_sparse, res_dense)
def test_pivot_table_with_nans(self):
res_sparse = pd.pivot_table(
self.sparse, index="A", columns="B", values="E", aggfunc="sum"
)
res_dense = pd.pivot_table(
self.dense, index="A", columns="B", values="E", aggfunc="sum"
)
tm.assert_frame_equal(res_sparse, res_dense)
def test_pivot_table_multi(self):
res_sparse = pd.pivot_table(
self.sparse, index="A", columns="B", values=["D", "E"]
)
res_dense = pd.pivot_table(
self.dense, index="A", columns="B", values=["D", "E"]
)
res_dense = res_dense.apply(lambda x: x.astype("Sparse[float64]"))
tm.assert_frame_equal(res_sparse, res_dense)
|
[
"msaineti@icloud.com"
] |
msaineti@icloud.com
|
90f9d81e1ac37422b6bc4c3d5187d3f54eb2b54c
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_083/ch129_2020_04_01_17_04_56_778073.py
|
63194e8b169fab2b441de017db0cc2185bde9181
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628
| 2020-12-16T05:21:31
| 2020-12-16T05:21:31
| 306,735,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 211
|
py
|
def verifica_quadrado_perfeito(n):
i=1
y=1
while n>=i:
y=n-i
if y==0:
return True
else:
return False
i+=2
print(verifica_quadrado_perfeito(25))
|
[
"you@example.com"
] |
you@example.com
|
a0e585c73ccd0f53b6602f193b8f888584358b58
|
0fd2b832673946c9ee532686a2a35bf2680f8408
|
/CybORG/CybORG/Shared/Actions/GlobalActions/ListGames.py
|
76795b71f41c8585e6fe71ad744f82fc4ac7f0bd
|
[
"MIT"
] |
permissive
|
pvu1984/cage-challenge-2
|
4e57bad7bc30c7df2b90c2fabc8395a5f2a3e65c
|
e76722dcd79a6b7511e185cde34fac1e0b45720e
|
refs/heads/main
| 2023-09-02T15:11:32.072215
| 2021-11-12T02:33:19
| 2021-11-12T02:33:19
| 429,307,660
| 0
| 0
|
MIT
| 2021-11-18T05:27:36
| 2021-11-18T05:27:35
| null |
UTF-8
|
Python
| false
| false
| 477
|
py
|
# Copyright DST Group. Licensed under the MIT license.
from CybORG.Shared import Observation
from .GlobalAction import GlobalAction
class ListGames(GlobalAction):
"""Get a list of all active games """
def emu_execute(self, team_server) -> Observation:
self._log_info("Listing games")
obs = Observation()
game_ids = team_server.get_games_list()
obs.set_success(True)
obs.add_key_value("game_ids", game_ids)
return obs
|
[
"david@pop-os.localdomain"
] |
david@pop-os.localdomain
|
3a241204309bb872de8646ff5018a65a4c3b3f50
|
a97fb0584709e292a475defc8506eeb85bb24339
|
/source code/code/ch713.py
|
0b37f65b4505c1c49f2186b0ad00f91dad64d26c
|
[] |
no_license
|
AAQ6291/PYCATCH
|
bd297858051042613739819ed70c535901569079
|
27ec4094be785810074be8b16ef84c85048065b5
|
refs/heads/master
| 2020-03-26T13:54:57.051016
| 2018-08-17T09:05:19
| 2018-08-17T09:05:19
| 144,963,014
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 824
|
py
|
#!/usr/bin/env python
#coding=utf-8
"""
# 多載overloading觀念, 註解的這個區塊無法在Python裡正常運作.
class Obj:
def __init__(self):
pass
def func(self, x=0):
print "func: x = %d ", x
def func(self, x=0, y=x+x):
print "func: x = %d, y = %d", x, y
def func(self, y=0):
print "func: y = %d ", y
"""
"""
我們可以改變觀念, 將上面的寫法改成下面的寫法,
將要傳入的參數都設定在__init__()函數內,
透過這個函數去接收使用者傳進來的值
"""
class Obj:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
self.printState()
def printState(self):
print "func: x = %d, y = %d", self.x, self.y
# class overloading.
obj1 = Obj(10)
obj2 = Obj(10, 10+10)
obj3 = Obj(y=30)
|
[
"angelak.tw@gmail.com"
] |
angelak.tw@gmail.com
|
b59d95850094a8e35402245c52ec57944a360d0d
|
50948d4cb10dcb1cc9bc0355918478fb2841322a
|
/azure-mgmt-resource/azure/mgmt/resource/managedapplications/models/resource_py3.py
|
5de1d2d3bb943026662197eb95d8d4819b5633fb
|
[
"MIT"
] |
permissive
|
xiafu-msft/azure-sdk-for-python
|
de9cd680b39962702b629a8e94726bb4ab261594
|
4d9560cfd519ee60667f3cc2f5295a58c18625db
|
refs/heads/master
| 2023-08-12T20:36:24.284497
| 2019-05-22T00:55:16
| 2019-05-22T00:55:16
| 187,986,993
| 1
| 0
|
MIT
| 2020-10-02T01:17:02
| 2019-05-22T07:33:46
|
Python
|
UTF-8
|
Python
| false
| false
| 1,617
|
py
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class Resource(Model):
"""Resource information.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource ID
:vartype id: str
:ivar name: Resource name
:vartype name: str
:ivar type: Resource type
:vartype type: str
:param location: Resource location
:type location: str
:param tags: Resource tags
:type tags: dict[str, str]
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
}
def __init__(self, *, location: str=None, tags=None, **kwargs) -> None:
super(Resource, self).__init__(**kwargs)
self.id = None
self.name = None
self.type = None
self.location = location
self.tags = tags
|
[
"noreply@github.com"
] |
xiafu-msft.noreply@github.com
|
632531ce3e51e510b87b765c03cfa5f6ea264d16
|
e1a78591c9702a7e61fbf076d78b59073ff33c37
|
/InternetSemLimites/core/tests/test_fame_view.py
|
e938694682951acc076cf431f78fd1435b7febff
|
[
"MIT"
] |
permissive
|
sebshub/PublicAPI
|
eb26f22a34a7022bccd6aaecdfa0c35e5fdf4c7a
|
82677389430a30ad82be9fa81643431d9db24f0c
|
refs/heads/master
| 2021-01-19T19:06:40.791795
| 2016-04-14T22:18:43
| 2016-04-14T22:18:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,489
|
py
|
from django.shortcuts import resolve_url
from django.test import TestCase
from InternetSemLimites.core.models import Provider, State
class TestGet(TestCase):
def setUp(self):
sc = State.objects.get(abbr='SC')
go = State.objects.get(abbr='GO')
props = {'name': 'Xpto',
'url': 'http://xp.to',
'source': 'http://twitter.com/xpto',
'category': Provider.FAME,
'other': 'Lorem ipsum',
'published': True}
provider = Provider.objects.create(**props)
provider.coverage = [sc, go]
self.resp = self.client.get(resolve_url('fame'))
def test_get(self):
self.assertEqual(200, self.resp.status_code)
def test_type(self):
self.assertEqual('application/json', self.resp['Content-Type'])
def test_contents(self):
json_resp = self.resp.json()
fame = json_resp['providers']
with self.subTest():
self.assertEqual(1, len(fame))
self.assertNotIn('hall-of-shame', json_resp)
self.assertIn('headers', json_resp)
self.assertEqual('Xpto', fame[0]['name'])
self.assertEqual('http://xp.to', fame[0]['url'])
self.assertEqual('http://twitter.com/xpto', fame[0]['source'])
self.assertEqual(['GO', 'SC'], fame[0]['coverage'])
self.assertEqual('F', fame[0]['category'])
self.assertEqual('Lorem ipsum', fame[0]['other'])
|
[
"cuducos@gmail.com"
] |
cuducos@gmail.com
|
049c15190f0142931a95e324dcc39ec13e781818
|
0e1e643e864bcb96cf06f14f4cb559b034e114d0
|
/Exps_7_v3/doc3d/Ablation4_ch016_ep003_7_10/Gather1_W_change_C_fix_2blk/ep0_test/pyr_0s/L5/step10_a.py
|
4ff6c76e23f16f7c54b25b5ca0b4b4c49fbd9a01
|
[] |
no_license
|
KongBOy/kong_model2
|
33a94a9d2be5b0f28f9d479b3744e1d0e0ebd307
|
1af20b168ffccf0d5293a393a40a9fa9519410b2
|
refs/heads/master
| 2022-10-14T03:09:22.543998
| 2022-10-06T11:33:42
| 2022-10-06T11:33:42
| 242,080,692
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,733
|
py
|
#############################################################################################################################################################################################################
#############################################################################################################################################################################################################
### 把 kong_model2 加入 sys.path
import os
code_exe_path = os.path.realpath(__file__) ### 目前執行 step10_b.py 的 path
code_exe_path_element = code_exe_path.split("\\") ### 把 path 切分 等等 要找出 kong_model 在第幾層
code_dir = "\\".join(code_exe_path_element[:-1])
kong_layer = code_exe_path_element.index("kong_model2") ### 找出 kong_model2 在第幾層
kong_model2_dir = "\\".join(code_exe_path_element[:kong_layer + 1]) ### 定位出 kong_model2 的 dir
import sys ### 把 kong_model2 加入 sys.path
sys.path.append(kong_model2_dir)
sys.path.append(code_dir)
# print(__file__.split("\\")[-1])
# print(" code_exe_path:", code_exe_path)
# print(" code_exe_path_element:", code_exe_path_element)
# print(" code_dir:", code_dir)
# print(" kong_layer:", kong_layer)
# print(" kong_model2_dir:", kong_model2_dir)
#############################################################################################################################################################################################################
kong_to_py_layer = len(code_exe_path_element) - 1 - kong_layer ### 中間 -1 是為了長度轉index
# print(" kong_to_py_layer:", kong_to_py_layer)
if (kong_to_py_layer == 0): template_dir = ""
elif(kong_to_py_layer == 2): template_dir = code_exe_path_element[kong_layer + 1][0:] ### [7:] 是為了去掉 step1x_, 後來覺得好像改有意義的名字不去掉也行所以 改 0
elif(kong_to_py_layer == 3): template_dir = code_exe_path_element[kong_layer + 1][0:] + "/" + code_exe_path_element[kong_layer + 2][0:] ### [5:] 是為了去掉 mask_ ,前面的 mask_ 是為了python 的 module 不能 數字開頭, 隨便加的這樣子, 後來覺得 自動排的順序也可以接受, 所以 改0
elif(kong_to_py_layer > 3): template_dir = code_exe_path_element[kong_layer + 1][0:] + "/" + code_exe_path_element[kong_layer + 2][0:] + "/" + "/".join(code_exe_path_element[kong_layer + 3: -1])
# print(" template_dir:", template_dir) ### 舉例: template_dir: 7_mask_unet/5_os_book_and_paper_have_dtd_hdr_mix_bg_tv_s04_mae
#############################################################################################################################################################################################################
exp_dir = template_dir
#############################################################################################################################################################################################################
from step06_a_datas_obj import *
from step09_0side_L5 import *
from step10_a2_loss_info_obj import *
from step10_b2_exp_builder import Exp_builder
rm_paths = [path for path in sys.path if code_dir in path]
for rm_path in rm_paths: sys.path.remove(rm_path)
rm_moduless = [module for module in sys.modules if "step09" in module]
for rm_module in rm_moduless: del sys.modules[rm_module]
import Exps_7_v3.doc3d.Ablation4_ch016_ep003_7_10.I_w_M_to_W_pyr.pyr_0s.L5.step10_a as I_w_M_to_W_p20_pyr
from Exps_7_v3.doc3d.Ablation4_ch016_ep003_7_10.W_w_M_to_C_pyr.pyr_2s.L5.step10_a import ch032_1side_6__2side_6__ep010 as W_w_M_to_C_p20_2s_L5_Mae_Sob_k09
#############################################################################################################################################################################################################
'''
exp_dir 是 決定 result_dir 的 "上一層"資料夾 名字喔! exp_dir要巢狀也沒問題~
比如:exp_dir = "6_mask_unet/自己命的名字",那 result_dir 就都在:
6_mask_unet/自己命的名字/result_a
6_mask_unet/自己命的名字/result_b
6_mask_unet/自己命的名字/...
'''
use_db_obj = type8_blender_kong_doc3d_v2
use_loss_obj = [mae_s001_sobel_k9_s001_loss_info_builder.set_loss_target("UNet_Wz").copy(), mae_s001_sobel_k9_s001_loss_info_builder.set_loss_target("UNet_Wy").copy(), mae_s001_sobel_k9_s001_loss_info_builder.set_loss_target("UNet_Wx").copy(), mae_s001_sobel_k9_s001_loss_info_builder.set_loss_target("UNet_Cx").copy(), mae_s001_sobel_k9_s001_loss_info_builder.set_loss_target("UNet_Cy").copy()] ### z, y, x 順序是看 step07_b_0b_Multi_UNet 來對應的喔
#############################################################
### 為了resul_analyze畫空白的圖,建一個empty的 Exp_builder
empty = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_0side_and_1s6_2s6, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_0side.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900 * 5, it_save_fq=900 * 5, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_result_name(result_name="為了resul_analyze畫空白的圖,建一個empty的 Exp_builder")
#############################################################
ch032_0side = Exp_builder().set_basic("train", use_db_obj, ch032_pyramid_0side_and_1s6_2s6, use_loss_obj, exp_dir=exp_dir, code_exe_path=code_exe_path, describe_end=ch032_pyramid_0side.kong_model.model_describe) .set_train_args(epochs= 1) .set_train_iter_args(it_see_fq=900 * 5, it_save_fq=900 * 5, it_down_step="half", it_down_fq=900).set_train_in_gt_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_multi_model_reload_exp_builders_dict(I_to_Wx_Wy_Wz=I_w_M_to_W_p20_pyr.ch032_0side, W_to_Cx_Cy=W_w_M_to_C_p20_2s_L5_Mae_Sob_k09).set_result_name(result_name="p20_L5-ch032_0side")
#############################################################
if(__name__ == "__main__"):
print("build exps cost time:", time.time() - start_time)
if len(sys.argv) < 2:
############################################################################################################
### 直接按 F5 或打 python step10_b1_exp_obj_load_and_train_and_test.py,後面沒有接東西喔!才不會跑到下面給 step10_b_subprocss.py 用的程式碼~~~
ch032_0side.build().run()
# print('no argument')
sys.exit()
### 以下是給 step10_b_subprocess.py 用的,相當於cmd打 python step10_b1_exp_obj_load_and_train_and_test.py 某個exp.build().run()
eval(sys.argv[1])
|
[
"s89334roy@yahoo.com.tw"
] |
s89334roy@yahoo.com.tw
|
1acdfb1920626d1363c04b1ba023704c5c8ca65d
|
0676f6e4d3510a0305d29aa0b1fe740d538d3b63
|
/Python/FitPLine/InterpPline.py
|
6390298333cf36a43eb18f5776c4babdb66361c4
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
pgolay/PG_Scripts
|
f70ffe7e5ca07acd6f4caedc9a9aec566542da7c
|
796704a7daa6ac222a40bb02afdb599f74a6b0d4
|
refs/heads/master
| 2021-01-19T16:53:41.525879
| 2017-02-07T18:26:10
| 2017-02-07T18:26:10
| 2,730,362
| 9
| 1
| null | 2016-12-30T17:58:08
| 2011-11-08T00:04:33
|
Python
|
UTF-8
|
Python
| false
| false
| 482
|
py
|
import Rhino
import scriptcontext as sc
import rhinoscriptsyntax as rs
def Test():
pLineId = rs.GetObject("Select a polyline", 4, preselect=True)
if pLineId is None: return
pLineObj= sc.doc.Objects.Find(pLineId)
rc, pLine = pLineObj.Geometry.TryGetPolyline()
ang = Rhino.RhinoMath.ToRadians(30)
x = pLine.BreakAtAngles(ang)
for item in x:
sc.doc.Objects.AddPolyline(item)
pass
if __name__ == "__main__":
Test()
|
[
"noreply@github.com"
] |
pgolay.noreply@github.com
|
d031f9d17e6d7442b98764362e2808e3192189ab
|
25e627d2931b89eb53d7dad91b200c1c29fe0233
|
/code/lab_05_Important_Trick/sys_demo(3).py
|
0740b2d3d833b437ef0f896f320dcf4511a6b1a6
|
[] |
no_license
|
tcano2003/ucsc-python-for-programmers
|
efb973b39dbff9a7d30505fecbd9afb1e4d54ae9
|
cc7fe1fb9f38f992464b5d86d92eb073e18e57d5
|
refs/heads/master
| 2020-03-26T22:13:29.256561
| 2018-08-26T14:54:08
| 2018-08-26T14:54:08
| 145,442,055
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 718
|
py
|
#!/usr/bin/env python3
"""Demonstrating the sys module."""
import sys
def DemoOpenStreams():
"""Demos stderr, stdout and stdin. Also sys.exit()"""
sys.stderr.write('You can write to stderr.\n')
print (>> sys.stderr, "You might like the >> syntax.") # look this up how to convert to Python 3
sys.stdout.write('A fancier way to write to stdout.\n')
print ('Type something: ')
text = sys.stdin.readline()
print ('You said:', text)
def DemoCommandLine():
"""Shows the command line."""
print ('This program is named:', sys.argv[0]) #arg vector
print ('The command line arguments are:', sys.argv[1:])
def main():
DemoCommandLine()
DemoOpenStreams()
main()
|
[
"traviscano@msn.com"
] |
traviscano@msn.com
|
cc176a774c950fca1179196f76975994db0ffdf0
|
82042141439ae004fc38bb2ef6238f36ec6bb050
|
/accounting/tables.py
|
e59289b4a7eb9e31422231abdbecd07c0d90f405
|
[] |
no_license
|
psteichen/clusil-intranet
|
2e9a2cf3b00692a4ef441ebf669af4e63945e9a2
|
5c028d33f6a8559af57a4eeb02fc0f612cb1b261
|
refs/heads/master
| 2021-07-13T15:40:06.464105
| 2020-06-30T19:51:00
| 2020-06-30T19:51:00
| 27,195,950
| 2
| 1
| null | 2021-06-10T20:06:47
| 2014-11-26T20:59:46
|
Python
|
UTF-8
|
Python
| false
| false
| 1,272
|
py
|
#coding=utf-8
from django.conf import settings
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django_tables2.tables import Table
from django_tables2 import Column
from cms.functions import visualiseDateTime
from cms.tables import gen_table_actions
from .models import Fee
#table for visualisation via django_tables2
class InvoiceTable(Table):
row_class = Column(visible=False, empty_values=()) #used to highlight some rows
actions = Column(verbose_name='Actions',empty_values=())
def render_row_class(self, value, record):
if record.paid:
return 'success'
def render_paid(self, value, record):
if value and record.paid_date: #paid
return mark_safe('<span class="glyphicon glyphicon-ok"></span> ('+visualiseDateTime(record.paid_date)+')')
else:
return mark_safe('<span class="glyphicon glyphicon-remove"></span>')
def render_actions(self, value, record):
actions = settings.TEMPLATE_CONTENT['accounting']['actions']['table']
return gen_table_actions(actions,{'id':record.member.id,'year':record.year})
class Meta:
model = Fee
fields = ( 'year', 'member.gen_name', 'invoice', 'paid', 'actions', )
attrs = {"class": "table table-stripped"}
|
[
"pst@libre.lu"
] |
pst@libre.lu
|
24c37b2731f76d1274c85d3269703a9dd52a74b7
|
b2913030cf1646310b08efaa57c2199bb08e37c9
|
/general/object_id/apero_astrometrics.py
|
8f21305a71d1f0d505c9856a0c692a251e7481f5
|
[
"MIT"
] |
permissive
|
njcuk9999/apero-utils
|
6f5b5083537562a31573b5c4cc76908c5fe194b9
|
368d53182428ca8befcdd3e5c8ca054f61913711
|
refs/heads/master
| 2023-08-31T02:56:01.369406
| 2023-08-18T15:12:59
| 2023-08-18T15:12:59
| 238,777,509
| 3
| 5
|
MIT
| 2023-08-17T14:15:41
| 2020-02-06T20:24:49
|
Python
|
UTF-8
|
Python
| false
| false
| 5,169
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# CODE NAME HERE
# CODE DESCRIPTION HERE
Created on 2021-11-10 at 16:04
@author: cook
"""
from astroquery.utils.tap.core import TapPlus
from astroquery.simbad import Simbad
import numpy as np
from typing import Dict, List, Tuple
import warnings
from apero import lang
from apero.base import base
from apero.core import constants
from apero.core.core import drs_log
from apero.core.core import drs_database
from apero.tools.module.database import manage_databases
# =============================================================================
# Define variables
# =============================================================================
__NAME__ = 'apero_astrometrics.py'
__INSTRUMENT__ = 'None'
__PACKAGE__ = base.__PACKAGE__
__version__ = base.__version__
__author__ = base.__author__
__date__ = base.__date__
__release__ = base.__release__
# get text entry instance
textentry = lang.textentry
# Get Logging function
WLOG = drs_log.wlog
# get the databases
IndexDatabase = drs_database.IndexDatabase
ObjectDatabase = drs_database.ObjectDatabase
# simbad additional columns
SIMBAD_COLUMNS = ['ids']
# =============================================================================
# Define functions
# =============================================================================
def query_object(rawobjname):
# set up the TapPlus class
# simbad = TapPlus(url=URL)
# execute the job
# sjob = simbad.launch_job(QUERY.format(rawobjname))
# get the results
# table = sjob.get_results()
# get results
with warnings.catch_warnings(record=True) as _:
# add ids column
for simbad_column in SIMBAD_COLUMNS:
Simbad.add_votable_fields(simbad_column)
# query simbad
table = Simbad.query_object(rawobjname)
return 0
def query_database(params, rawobjnames: List[str] ) -> List[str]:
"""
Find all objects in the object database and return list of unfound
objects
:param params:
:param rawobjnames:
:return:
"""
# ---------------------------------------------------------------------
# get psuedo constants
pconst = constants.pload()
# ---------------------------------------------------------------------
# Update the object database (recommended only for full reprocessing)
# check that we have entries in the object database
manage_databases.object_db_populated(params)
# update the database if required
if params['UPDATE_OBJ_DATABASE']:
# log progress
WLOG(params, '', textentry('40-503-00039'))
# update database
manage_databases.update_object_database(params, log=False)
# ---------------------------------------------------------------------
# print progress
WLOG(params, '', 'Searching local object database for object names...')
# load the object database after updating
objdbm = ObjectDatabase(params)
objdbm.load_db()
# storage for output - assume none are found
unfound = []
# loop around objects and find them in database
for rawobjname in rawobjnames:
# clean the object
objname = pconst.DRS_OBJ_NAME(rawobjname)
# find correct name in the database (via objname or aliases)
correct_objname, found = objdbm.find_objname(pconst, objname)
# deal with found / not found
if found:
msg = '\tObject: "{0}" found in database as "{1}"'
margs = [rawobjname, correct_objname]
WLOG(params, '', msg.format(*margs))
else:
msg = '\tObject: "{0}" not found in database'
margs = [rawobjname]
WLOG(params, '', msg.format(*margs), colour='yellow')
# add to unfound list
unfound.append(rawobjname)
# return the entry names and the found dictionary
return unfound
# =============================================================================
# Start of code
# =============================================================================
# Main code here
if __name__ == "__main__":
# ----------------------------------------------------------------------
# get params
params = constants.load()
params.set('PID', 'None')
params.set('UPDATE_OBJ_DATABASE', False)
rawobjs = ['Gl699', 'Trappist1', 'Neil']
# ----------------------------------------------------------------------
# step 1: Is object in database?
# ----------------------------------------------------------------------
# query local object database
unfound_objs = query_database(params, rawobjs)
# stop here if all objects found
print('stop')
# ----------------------------------------------------------------------
# step 2: if not in database see if we can find it in simbad
# _ = query_object('Gl699')
# ----------------------------------------------------------------------
# step 3: add to pending database if submitted
# =============================================================================
# End of code
# =============================================================================
|
[
"neil.james.cook@gmail.com"
] |
neil.james.cook@gmail.com
|
957e9a83a0906447bcd7c0b17c13adc0c9d0a9e7
|
f338eb32c45d8d5d002a84798a7df7bb0403b3c4
|
/DQMOffline/Alignment/test/testMuAlDQM.py
|
dafae5c403d9e801584a14e97431e543ac40337d
|
[] |
permissive
|
wouf/cmssw
|
0a8a8016e6bebc611f1277379e12bef130464afb
|
60da16aec83a0fc016cca9e2a5ed0768ba3b161c
|
refs/heads/CMSSW_7_3_X
| 2022-06-30T04:35:45.380754
| 2015-05-08T17:40:17
| 2015-05-08T17:40:17
| 463,028,972
| 0
| 0
|
Apache-2.0
| 2022-02-24T06:05:30
| 2022-02-24T06:05:26
| null |
UTF-8
|
Python
| false
| false
| 4,965
|
py
|
import os
import FWCore.ParameterSet.Config as cms
process = cms.Process("MuonAlignmentMonitor")
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.MessageLogger.cerr.FwkReport.reportEvery = 1000000
process.load("DQMOffline.Alignment.muonAlignment_cfi")
process.load("DQMServices.Components.MEtoEDMConverter_cff")
process.load("Configuration.StandardSequences.Geometry_cff")
process.load("Configuration.StandardSequences.MagneticField_cff")
# ideal geometry and interface
process.load("Geometry.CMSCommonData.cmsIdealGeometryXML_cfi")
process.load("Geometry.TrackerNumberingBuilder.trackerNumberingGeometry_cfi")
process.load("Geometry.MuonNumbering.muonNumberingInitialization_cfi")
process.load("Geometry.CommonDetUnit.bareGlobalTrackingGeometry_cfi")
# reconstruction sequence for Cosmics
process.load("Configuration.StandardSequences.ReconstructionCosmics_cff")
process.load("TrackPropagation.SteppingHelixPropagator.SteppingHelixPropagator_cfi")
#from DQMOffline.Alignment.input_cfi import source
#process.source = source
process.source = cms.Source("PoolSource",
# fileNames = cms.untracked.vstring('/store/data/Commissioning08/Cosmics/ALCARECO/CRAFT_ALL_V4_StreamALCARECOMuAlCalIsolatedMu_step2_AlcaReco-v1/0008/001A49E8-93C3-DD11-9720-003048D15CFA.root')
#fileNames = cms.untracked.vstring('/store/data/Commissioning08/Cosmics/ALCARECO/CRAFT_ALL_V9_StreamALCARECOMuAlStandAloneCosmics_225-v3/0008/4EE39297-01FF-DD11-82CF-003048678C9A.root')
fileNames= cms.untracked.vstring('/store/data/Commissioning08/Cosmics/RAW-RECO/CRAFT_ALL_V11_227_Tosca090216_ReReco_FromTrackerPointing_v2/0006/F453F276-8421-DE11-ABFE-001731AF66A7.root')
)
#process.muonAlignment.MuonCollection = "cosmicMuons"
process.muonAlignment.MuonCollection = "ALCARECOMuAlStandAloneCosmics"
#process.muonAlignment.MuonCollection = "ALCARECOMuAlCalIsolatedMu:StandAlone"
#process.muonAlignment.MuonCollection = "ALCARECOMuAlCalIsolatedMu:SelectedMuons"
process.muonAlignment.OutputMEsInRootFile = cms.bool(True)
process.muonAlignment.doSummary= cms.untracked.bool(True)
process.myDQM = cms.OutputModule("PoolOutputModule",
outputCommands = cms.untracked.vstring('drop *','keep *_MEtoEDMConverter_*_MuonAlignmentMonitor'),
SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vstring('p')),
fileName = cms.untracked.string('dqm.root')
)
#process.p = cms.Path(process.muonAlignment*process.MEtoEDMConverter)
#process.load("DQMServices.Core.DQM_cfg")
#process.dqmSaverMy = cms.EDFilter("DQMFileSaver",
# convention=cms.untracked.string("Offline"),
# workflow=cms.untracked.string("/Alignment/Muon/ALCARECOMuAlGlobalCosmics_v11_SAalgo"),
# dirName=cms.untracked.string("."),
# saveAtJobEnd=cms.untracked.bool(True),
# forceRunNumber=cms.untracked.int32(1)
# )
process.myTracks = cms.EDFilter("MyTrackSelector",
# src = cms.InputTag("ALCARECOMuAlCalIsolatedMu:StandAlone"),
src = cms.InputTag("ALCARECOMuAlStandAloneCosmics"),
# src = cms.InputTag("cosmicMuons"),
cut = cms.string("pt > 40"),
filter = cms.bool(True)
)
process.p = cms.Path(
#process.myTracks *
process.muonAlignment
# *process.dqmSaverMy
# *process.MEtoEDMConverter
)
process.outpath = cms.EndPath(process.myDQM)
from CondCore.DBCommon.CondDBSetup_cfi import *
#process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_noesprefer_cff")
process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
if os.environ["CMS_PATH"] != "":
del process.es_prefer_GlobalTag
del process.SiStripPedestalsFakeESSource
del process.siStripBadChannelFakeESSource
del process.siStripBadFiberFakeESSource
del process.DTFakeVDriftESProducer
#process.prefer("GlobalTag")
#process.prefer("GlobalTag")
process.GlobalTag.globaltag = 'CRAFT_ALL_V11::All'
process.myAlignment = cms.ESSource("PoolDBESSource",CondDBSetup,
#connect = cms.string('sqlite_file:/afs/cern.ch/user/p/pablom/public/DBs/Alignments_CRAFT_ALL_V4_refitter.db'),
#connect = cms.string('sqlite_file:/afs/cern.ch/cms/CAF/CMSALCA/ALCA_MUONALIGN/HWAlignment/AlignmentDB/AlignmentsNewEndcap.db'),
connect = cms.string('sqlite_file:/afs/cern.ch/user/p/pivarski/public/CRAFTalignment4_NewTracker_xyphiz2_alignedonlyAPEs.db'),
#DBParameters = CondCore.DBCommon.CondDBSetup_cfi.CondDBSetup.DBParameters,
toGet = cms.VPSet(
cms.PSet(
record = cms.string('DTAlignmentRcd'),
tag = cms.string('DTAlignmentRcd')
),
cms.PSet(
record = cms.string('DTAlignmentErrorRcd'),
tag = cms.string('DTAlignmentErrorRcd')
),
cms.PSet(
record = cms.string('CSCAlignmentRcd'),
tag = cms.string('CSCAlignmentRcd')
),
cms.PSet(
record = cms.string('CSCAlignmentErrorRcd'),
tag = cms.string('CSCAlignmentErrorRcd')
)
)
)
process.es_prefer_myAlignment = cms.ESPrefer("PoolDBESSource","myAlignment")
#process.schedule = cms.Schedule(process.p,process.outpath)
|
[
"giulio.eulisse@gmail.com"
] |
giulio.eulisse@gmail.com
|
be210f89568c29063428ef21602005c46b94af7c
|
e86d020f8ade86b86df6ad8590b4458a9d415491
|
/test-xooj/practice_infiltration/resource.py
|
54fa54208d6e269ffbafe87eff7295d066e7fde0
|
[
"BSD-2-Clause"
] |
permissive
|
g842995907/guops-know
|
e4c3b2d47e345db80c27d3ba821a13e6bf7191c3
|
0df4609f3986c8c9ec68188d6304d033e24b24c2
|
refs/heads/master
| 2022-12-05T11:39:48.172661
| 2019-09-05T12:35:32
| 2019-09-05T12:35:32
| 202,976,887
| 1
| 4
| null | 2022-11-22T02:57:53
| 2019-08-18T08:10:05
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 787
|
py
|
# -*- coding: utf-8 -*-
from common_env.models import Env
from practice import resource
class PracticeInfiltrationTaskMeta(resource.SolvedBaseTask):
subsidiary = [{
'force': {
'create_user_id': None,
'last_edit_user_id': None,
},
'subsidiary': {
'category': {
'get': lambda self: self.category,
'set': lambda self, category: setattr(self, 'category', category),
},
'envs': {
'many_to_many': True,
'get': lambda self: self.envs.filter(env__status=Env.Status.TEMPLATE),
'set': lambda self, task_envs: self.envs.add(*task_envs),
},
},
'markdownfields': ['content', 'official_writeup']
}]
|
[
"842995907@qq.com"
] |
842995907@qq.com
|
48cf24d2660484608ab2a4153721faff3b921745
|
61673ab9a42f7151de7337608c442fa6247f13bb
|
/tkinter/minimize - iconify/main.py
|
5f35a5d61c37b30d04da61f12bdcb2aa2ff74595
|
[
"MIT"
] |
permissive
|
furas/python-examples
|
22d101670ecd667a29376d7c7d7d86f8ec71f6cf
|
95cb53b664f312e0830f010c0c96be94d4a4db90
|
refs/heads/master
| 2022-08-23T23:55:08.313936
| 2022-08-01T14:48:33
| 2022-08-01T14:48:33
| 45,575,296
| 176
| 91
|
MIT
| 2021-02-17T23:33:37
| 2015-11-04T23:54:32
|
Python
|
UTF-8
|
Python
| false
| false
| 648
|
py
|
#!/usr/bin/env python3
# date: 2020.06.27
import tkinter as tk
root = tk.Tk()
# button [X] minimize (iconify) the main window
root.protocol("WM_DELETE_WINDOW", root.iconify)
# key ESC minimize (iconify) the main window
#root.bind('<Escape>', lambda event: root.destroy())
root.bind('<Escape>', lambda event: root.iconify())
# create a menu bar with an `Exit` and `Hide`
menubar = tk.Menu(root)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="Hide", command=root.iconify)
filemenu.add_command(label="Exit", command=root.destroy)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
root.mainloop()
|
[
"furas@tlen.pl"
] |
furas@tlen.pl
|
508ba345964380a61362afc629dea987c61c2b0c
|
c97ad9dbc96d151b5ef38a6d6dbac454d6e57576
|
/architectures/preprocessing.py
|
f15f66e3b153c6b3f0bbf3ec310c58605c37fd61
|
[
"BSD-3-Clause"
] |
permissive
|
WangVictor/jets
|
75177ff68fad2eaf3274537afcee325d93ff1d5f
|
1f7209b4c026b63cad94aa8c93e2b8721b259b98
|
refs/heads/master
| 2021-07-14T05:39:54.983839
| 2017-10-17T20:48:01
| 2017-10-17T20:48:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,137
|
py
|
import numpy as np
import copy
import pickle
import torch
from torch.autograd import Variable
# wrapping
def wrap(y, dtype='float'):
y_wrap = Variable(torch.from_numpy(y))
if dtype=='float':
y_wrap = y_wrap.float()
elif dtype == 'long':
y_wrap = y_wrap.long()
if torch.cuda.is_available():
y_wrap = y_wrap.cuda()
return y_wrap
def unwrap(y_wrap):
if y_wrap.is_cuda:
y = y_wrap.cpu().data.numpy()
else:
y = y_wrap.data.numpy()
return y
def wrap_X(X):
X_wrap = copy.deepcopy(X)
for jet in X_wrap:
jet["content"] = wrap(jet["content"])
return X_wrap
def unwrap_X(X_wrap):
X_new = []
for jet in X_wrap:
jet["content"] = unwrap(jet["content"])
X_new.append(jet)
return X_new
'''
def wrap(y, dtype='float'):
y_wrap = Variable(torch.from_numpy(y))
if dtype=='float':
y_wrap = y_wrap.float()
elif dtype == 'long':
y_wrap = y_wrap.long()
if torch.cuda.is_available():
y_wrap = y_wrap.cuda()
#y = y_wrap
return y_wrap
def unwrap(y):
if y.is_cuda:
y_unwrap = y.cpu().data.numpy()
else:
y_unwrap = y.data.numpy()
return y_unwrap
def wrap_X(X):
for jet in X:
jet['content'] = wrap(jet["content"])
#X = copy.copy(X_)
#for i, (jet, jet_) in enumerate(X, X_):
# jet['content'] = wrap(jet_["content"])
return X
def unwrap_X(X):
for jet in X:
jet["content"] = unwrap(jet["content"])
return X
'''
# Data loading related
def load_from_pickle(filename, n_jets):
jets = []
fd = open(filename, "rb")
for i in range(n_jets):
jet = pickle.load(fd)
jets.append(jet)
fd.close()
return jets
# Jet related
def _pt(v):
pz = v[2]
p = (v[0:3] ** 2).sum() ** 0.5
eta = 0.5 * (np.log(p + pz) - np.log(p - pz))
pt = p / np.cosh(eta)
return pt
def permute_by_pt(jet, root_id=None):
# ensure that the left sub-jet has always a larger pt than the right
if root_id is None:
root_id = jet["root_id"]
if jet["tree"][root_id][0] != -1:
left = jet["tree"][root_id][0]
right = jet["tree"][root_id][1]
pt_left = _pt(jet["content"][left])
pt_right = _pt(jet["content"][right])
if pt_left < pt_right:
jet["tree"][root_id][0] = right
jet["tree"][root_id][1] = left
permute_by_pt(jet, left)
permute_by_pt(jet, right)
return jet
def rewrite_content(jet):
jet = copy.deepcopy(jet)
if jet["content"].shape[1] == 5:
pflow = jet["content"][:, 4].copy()
content = jet["content"]
tree = jet["tree"]
def _rec(i):
if tree[i, 0] == -1:
pass
else:
_rec(tree[i, 0])
_rec(tree[i, 1])
c = content[tree[i, 0]] + content[tree[i, 1]]
content[i] = c
_rec(jet["root_id"])
if jet["content"].shape[1] == 5:
jet["content"][:, 4] = pflow
return jet
def extract(jet, pflow=False):
# per node feature extraction
jet = copy.deepcopy(jet)
s = jet["content"].shape
if not pflow:
content = np.zeros((s[0], 7))
else:
# pflow value will be one-hot encoded
content = np.zeros((s[0], 7+4))
for i in range(len(jet["content"])):
px = jet["content"][i, 0]
py = jet["content"][i, 1]
pz = jet["content"][i, 2]
p = (jet["content"][i, 0:3] ** 2).sum() ** 0.5
eta = 0.5 * (np.log(p + pz) - np.log(p - pz))
theta = 2 * np.arctan(np.exp(-eta))
pt = p / np.cosh(eta)
phi = np.arctan2(py, px)
content[i, 0] = p
content[i, 1] = eta if np.isfinite(eta) else 0.0
content[i, 2] = phi
content[i, 3] = jet["content"][i, 3]
content[i, 4] = (jet["content"][i, 3] /
jet["content"][jet["root_id"], 3])
content[i, 5] = pt if np.isfinite(pt) else 0.0
content[i, 6] = theta if np.isfinite(theta) else 0.0
if pflow:
if jet["content"][i, 4] >= 0:
content[i, 7+int(jet["content"][i, 4])] = 1.0
jet["content"] = content
return jet
def randomize(jet):
# build a random tree
jet = copy.deepcopy(jet)
leaves = np.where(jet["tree"][:, 0] == -1)[0]
nodes = [n for n in leaves]
content = [jet["content"][n] for n in nodes]
nodes = [i for i in range(len(nodes))]
tree = [[-1, -1] for n in nodes]
pool = [n for n in nodes]
next_id = len(nodes)
while len(pool) >= 2:
i = np.random.randint(len(pool))
left = pool[i]
del pool[i]
j = np.random.randint(len(pool))
right = pool[j]
del pool[j]
nodes.append(next_id)
c = (content[left] + content[right])
if len(c) == 5:
c[-1] = -1
content.append(c)
tree.append([left, right])
pool.append(next_id)
next_id += 1
jet["content"] = np.array(content)
jet["tree"] = np.array(tree).astype(int)
jet["root_id"] = len(jet["tree"]) - 1
return jet
def sequentialize_by_pt(jet, reverse=False):
# transform the tree into a sequence ordered by pt
jet = copy.deepcopy(jet)
leaves = np.where(jet["tree"][:, 0] == -1)[0]
nodes = [n for n in leaves]
content = [jet["content"][n] for n in nodes]
nodes = [i for i in range(len(nodes))]
tree = [[-1, -1] for n in nodes]
pool = sorted([n for n in nodes],
key=lambda n: _pt(content[n]),
reverse=reverse)
next_id = len(pool)
while len(pool) >= 2:
right = pool[-1]
left = pool[-2]
del pool[-1]
del pool[-1]
nodes.append(next_id)
c = (content[left] + content[right])
if len(c) == 5:
c[-1] = -1
content.append(c)
tree.append([left, right])
pool.append(next_id)
next_id += 1
jet["content"] = np.array(content)
jet["tree"] = np.array(tree).astype(int)
jet["root_id"] = len(jet["tree"]) - 1
return jet
|
[
"isaachenrion@gmail.com"
] |
isaachenrion@gmail.com
|
e42b386d67393c6af683599183132b972f57f57a
|
928c53ea78be51eaf05e63f149fb291ec48be73e
|
/Min_Steps_to_Make_Piles_Equal_Height.py
|
527f25bb619af81199021e028c3d6393516d14b4
|
[] |
no_license
|
saurabhchris1/Algorithm-Pratice-Questions-LeetCode
|
35021d8fc082ecac65d7970d9f83f9be904fb333
|
ea4a7d6a78d86c8619f91a75594de8eea264bcca
|
refs/heads/master
| 2022-12-10T16:50:50.678365
| 2022-12-04T10:12:18
| 2022-12-04T10:12:18
| 219,918,074
| 5
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,697
|
py
|
# Alexa is given n piles of equal or unequal heights. In one step, Alexa can remove any number
# of boxes from the pile which has the maximum height and try to make it equal to the one which
# is just lower than the maximum height of the stack. Determine the minimum number of steps
# required to make all of the piles equal in height.
#
# Example 1:
#
# Input: piles = [5, 2, 1]
# Output: 3
# Explanation:
# Step 1: reducing 5 -> 2 [2, 2, 1]
# Step 2: reducing 2 -> 1 [2, 1, 1]
# Step 3: reducing 2 -> 1 [1, 1, 1]
# So final number of steps required is 3.
#
# Let's take an example.
# Input : [1, 1, 2, 2, 2, 3, 3, 3, 4, 4]
# Output : 15
# After sorting in reverse, we have...
# [4, 4, 3, 3, 3, 2, 2, 2, 1] --> (2 steps to transform the 4's) --> The 3's must wait for 2 numbers
# before it to finish their reduction
# [3, 3, 3, 3, 3, 2, 2, 2, 1] --> (5 steps to transform the 3's) --> The 2's must wait for 5 numbers
# before it to finish their reduction
# [2, 2, 2, 2, 2, 2, 2, 2, 1] --> (8 steps to transform the 2's) --> The 1's must wait for 8 numbers
# before it to finish their reduction
# [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
#
# Why did we sort in reverse? Because we want to process the maximum / largest number(s) first, which
# is what the question wants. At each step, we can only reduce the largest number(s) to the value of
# the 2nd-largest number(s)
#
# The main idea throughout the algorithm is that - Every time I meet a different number in the
# reverse-sorted array, I have to count how many numbers came before it. This represents the number
# of steps that was taken to reduce these numbers to the current number
# Reference https://leetcode.com/discuss/interview-question/364618/ by Wei_lun
def min_steps_balance(piles):
"""
Time : O(N log N)
Space : O(1), where N = len(s)
"""
# EDGE CASE
if len(piles) < 2:
return 0
# SORT THE BLOCKS
piles = sorted(piles, reverse=True)
# COUNT THE STEPS WE NEED
steps = 0
# EACH TIME WE SEE A DIFFERENT ELEMENT, WE NEED TO SEE HOW MANY ELEMENTS ARE BEFORE IT
for i in range(1, len(piles)):
steps += i if piles[i - 1] != piles[i] else 0
return steps
if __name__ == "__main__":
print(min_steps_balance([50]) == 0)
print(min_steps_balance([10, 10]) == 0)
print(min_steps_balance([5, 2, 1]) == 3)
print(min_steps_balance([4, 2, 1]) == 3)
print(min_steps_balance([4, 5, 5, 4, 2]) == 6)
print(min_steps_balance([4, 8, 16, 32]) == 6)
print(min_steps_balance([4, 8, 8]) == 2)
print(min_steps_balance([4, 4, 8, 8]) == 2)
print(min_steps_balance([1, 2, 2, 3, 3, 4]) == 9)
print(min_steps_balance([1, 1, 2, 2, 2, 3, 3, 3, 4, 4]) == 15)
|
[
"saurabhchris1@gmail.com"
] |
saurabhchris1@gmail.com
|
11b02e051010453eb013a89954d8791c7033b396
|
4daeb9ebf92d9826028a50bf4e4715c1ab145db1
|
/Problem-Set/Numerical_Computing/INSOMA3/run.py
|
119445d7f7fd419363c3de405740eab234b29f25
|
[] |
no_license
|
Rahul2025/Thesis
|
4148653fcc96d623d602ba58e33cc6465d1cd9f5
|
df31863194e2e0b69646e3a48fcaf90541a55c2a
|
refs/heads/master
| 2020-05-02T00:48:09.593873
| 2013-04-21T20:23:02
| 2013-04-21T20:23:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 172
|
py
|
# filename : run.py
import time
f = open('/home/Rahul/Desktop/Thesis/Scripts/cyth_time', 'a')
start = time.time()
import qq18_tim
f.write(str(time.time() - start))
f.close
|
[
"rahulgupta2025@gmail.com"
] |
rahulgupta2025@gmail.com
|
fce0c0cbd8334360a36182f7f12a1d6bf9d2bbbb
|
66d79b863ef112d3e93770c695751d2f70c94aa5
|
/pygeopressure_gui/views/well_log_view.py
|
49097e2b311fa64d202ac8cf8d506a05529973d4
|
[] |
no_license
|
whimian/pyGeoPressure_gui
|
95d11edbd0589d1ef4368298dbac2abdbd76d203
|
a36777cf06a48eea681acc481880ee2e9309ac24
|
refs/heads/master
| 2020-03-11T22:26:56.967910
| 2018-05-09T08:20:48
| 2018-05-09T08:20:48
| 130,292,422
| 2
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,505
|
py
|
# -*- coding: utf-8 -*-
"""
a Well log display widget based on matplotlib
Created on Tue May 2nd 2018
"""
from __future__ import (division, absolute_import, print_function,
with_statement, unicode_literals)
from future.builtins import super
__author__ ="Yu Hao"
from pathlib2 import Path
from PyQt4.QtGui import QIcon, QDialog, QFileDialog, QWidget, QHBoxLayout, QGridLayout
from PyQt4 import uic, QtCore
from pygeopressure_gui.ui.ui_well_log_view_control import Ui_well_Log_View_Control
from pygeopressure_gui.widgets.matplotlib_widget import MatplotlibWidget
from pygeopressure_gui.config import CONF
class WellLogView(QWidget):
def __init__(self, parent=None):
super().__init__()
# self.setupUi(self)
self.initUI()
# connect
# self.surveyListWidget.itemSelectionChanged.connect(
# self.display_map_and_info)
# self.surveyButton.clicked.connect(self.on_clicked_surveyButton)
# self.selectButton.clicked.connect(self.on_clicked_selectButton)
# self.load_survey_list()
def initUI(self):
layout = QHBoxLayout(self)
self.control_widget = Well_Log_View_Control(self)
self.matplotlib_widget = MatplotlibWidget(self)
layout.addWidget(self.control_widget)
layout.addWidget(self.matplotlib_widget)
class Well_Log_View_Control(QWidget, Ui_well_Log_View_Control):
def __init__(self, parent=None):
super().__init__()
self.setupUi(self)
|
[
"yuhao89@live.cn"
] |
yuhao89@live.cn
|
2292b674d56303f1c405fe6e8fd757ff063bcd65
|
4e3c976773526fd610d64ffb83589bccfaee5e68
|
/sponge-app/sponge-app-demo-service/sponge/sponge_demo_forms_library_args.py
|
bb2475d0c06d7040720b9ffa792fd6294790e641
|
[
"Apache-2.0"
] |
permissive
|
softelnet/sponge
|
2313d2328953fcff49a002e727bb803757870627
|
7190f23ae888bbef49d0fbb85157444d6ea48bcd
|
refs/heads/master
| 2022-10-28T16:19:55.619882
| 2021-09-16T19:50:08
| 2021-09-16T19:50:08
| 95,256,030
| 10
| 2
|
Apache-2.0
| 2022-10-04T23:55:09
| 2017-06-23T20:58:49
|
Java
|
UTF-8
|
Python
| false
| false
| 4,364
|
py
|
"""
Sponge Knowledge Base
Demo Forms - Library as action arguments
"""
class ArgLibraryForm(Action):
def onConfigure(self):
self.withLabel("Library (books as arguments)")
self.withArgs([
StringType("search").withNullable().withLabel("Search").withFeature("responsive", True),
StringType("order").withLabel("Sort by").withProvided(ProvidedMeta().withValue().withValueSet()),
# Provided with overwrite to allow GUI refresh.
ListType("books").withLabel("Books").withProvided(ProvidedMeta().withValue().withOverwrite().withDependencies(
["search", "order"])).withFeatures({
"createAction":SubAction("ArgCreateBook"),
"readAction":SubAction("ArgReadBook").withArg("bookId", "@this"),
"updateAction":SubAction("ArgUpdateBook").withArg("bookId", "@this"),
"deleteAction":SubAction("ArgDeleteBook").withArg("bookId", "@this"),
"refreshable":True,
}).withElement(
IntegerType().withAnnotated()
)
]).withNonCallable().withFeature("icon", "library")
def onProvideArgs(self, context):
global LIBRARY
if "order" in context.provide:
context.provided["order"] = ProvidedValue().withValue("author").withAnnotatedValueSet([
AnnotatedValue("author").withValueLabel("Author"), AnnotatedValue("title").withValueLabel("Title")])
if "books" in context.provide:
context.provided["books"] = ProvidedValue().withValue(
map(lambda book: AnnotatedValue(int(book.id)).withValueLabel("{} - {}".format(book.author, book.title)).withValueDescription("Sample description (ID: " + str(book.id) +")"),
sorted(LIBRARY.findBooks(context.current["search"]), key = lambda book: book.author.lower() if context.current["order"] == "author" else book.title.lower())))
class ArgCreateBook(Action):
def onConfigure(self):
self.withLabel("Add a new book")
self.withArgs([
StringType("author").withLabel("Author"),
StringType("title").withLabel("Title")
]).withNoResult()
self.withFeatures({"visible":False, "callLabel":"Save", "cancelLabel":"Cancel"})
def onCall(self, author, title):
global LIBRARY
LIBRARY.addBook(author, title)
class ArgAbstractReadUpdateBook(Action):
def onConfigure(self):
self.withArgs([
IntegerType("bookId").withAnnotated().withFeature("visible", False),
StringType("author").withLabel("Author").withProvided(ProvidedMeta().withValue().withDependency("bookId")),
StringType("title").withLabel("Title").withProvided(ProvidedMeta().withValue().withDependency("bookId"))
]).withNoResult()
self.withFeatures({"visible":False})
def onProvideArgs(self, context):
global LIBRARY
if "author" in context.provide or "title" in context.provide:
book = LIBRARY.getBook(context.current["bookId"].value)
context.provided["author"] = ProvidedValue().withValue(book.author)
context.provided["title"] = ProvidedValue().withValue(book.title)
class ArgReadBook(ArgAbstractReadUpdateBook):
def onConfigure(self):
ArgAbstractReadUpdateBook.onConfigure(self)
self.withLabel("View the book").withNonCallable()
self.withFeatures({"cancelLabel":"Close"})
def onCall(self, bookId, author, title):
pass
class ArgUpdateBook(ArgAbstractReadUpdateBook):
def onConfigure(self):
ArgAbstractReadUpdateBook.onConfigure(self)
self.withLabel("Modify the book")
self.withFeatures({"callLabel":"Save", "cancelLabel":"Cancel"})
def onCall(self, bookId, author, title):
global LIBRARY
LIBRARY.updateBook(bookId.value, author, title)
class ArgDeleteBook(Action):
def onConfigure(self):
self.withLabel("Remove the book")
self.withArgs([
IntegerType("bookId").withAnnotated().withFeature("visible", False),
]).withNoResult()
self.withFeatures({"visible":False, "callLabel":"Save", "cancelLabel":"Cancel"})
def onCall(self, bookId):
global LIBRARY
self.logger.info("Deleting book id: {}", bookId.value)
LIBRARY.removeBook(bookId.value)
|
[
"marcin.pas@softelnet.com"
] |
marcin.pas@softelnet.com
|
7af57a4dd70f7a9cde6ca5ae074f3d75c585b917
|
176481563e0978340c737f61a4f85203ebb65c0b
|
/ptsites/sites/hdhome.py
|
f44a99bb7c69afa0dd0174e5d8ff0e93ad0ddf06
|
[
"MIT"
] |
permissive
|
ronioncloud/flexget_qbittorrent_mod
|
328bd6448e6908bfb8d953e83e826ee8e966eee6
|
a163a87328eeadf5ae961db4aec89f3f3ce48ad8
|
refs/heads/master
| 2023-01-20T03:43:07.664080
| 2020-11-21T10:28:13
| 2020-11-21T10:28:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,114
|
py
|
from ..schema.site_base import SiteBase
from ..schema.nexusphp import NexusPHP
# auto_sign_in
URL = 'https://hdhome.org/attendance.php'
SUCCEED_REGEX = '这是您的第 .* 次签到,已连续签到 .* 天,本次签到获得 .* 个魔力值。|您今天已经签到过了,请勿重复刷新。'
# html_rss
ROOT_ELEMENT_SELECTOR = '#torrenttable > tbody > tr:not(:first-child)'
FIELDS = {
'title': {
'element_selector': 'a[href*="details.php"]',
'attribute': 'title'
},
'url': {
'element_selector': 'a[href*="download.php"]',
'attribute': 'href'
},
'leecher': {
'element_selector': 'td:nth-child(7)',
'attribute': 'textContent'
},
'hr': {
'element_selector': 'img.hitandrun',
'attribute': 'alt'
}
}
class MainClass(NexusPHP):
@staticmethod
def build_sign_in(entry, config):
SiteBase.build_sign_in_entry(entry, config, URL, SUCCEED_REGEX)
@staticmethod
def build_html_rss_config(config):
config['root_element_selector'] = ROOT_ELEMENT_SELECTOR
config['fields'] = FIELDS
|
[
"12468675@qq.com"
] |
12468675@qq.com
|
eee84b835b4bb691bc922942e4d6e792138a170e
|
18fa0ad57cd9c26bc2622ead61b88c81e017e2e8
|
/kits/task_master.py
|
3452c834c4cdd786cd94314026e08537c0677050
|
[] |
no_license
|
weihhh/ECG_pro
|
45da18fad4709009cd4766a870fac7c5d5514a92
|
1e013cbb7352ad896661412f036fd9c6242a6001
|
refs/heads/master
| 2021-05-04T13:52:17.259815
| 2018-07-20T02:39:16
| 2018-07-20T02:39:16
| 120,323,445
| 2
| 4
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,361
|
py
|
# task_master.py
import random, time, queue
from multiprocessing.managers import BaseManager
# 发送任务的队列:
task_queue = queue.Queue()
# 接收结果的队列:
result_queue = queue.Queue()
# 从BaseManager继承的QueueManager:
class QueueManager(BaseManager):
pass
def return_task_queue():
global task_queue
return task_queue
def return_result_queue():
global result_queue
return result_queue
def task_run():
# 把两个Queue都注册到网络上, callable参数关联了Queue对象:
QueueManager.register('get_task_queue', callable=return_task_queue)
QueueManager.register('get_result_queue', callable=return_result_queue)
# 绑定端口5000, 设置验证码'abc':
manager = QueueManager(address=('127.0.0.1', 5000), authkey=b'abc')
# 启动Queue:
manager.start()
# 获得通过网络访问的Queue对象:
task = manager.get_task_queue()
result = manager.get_result_queue()
# 放几个任务进去:
for i in range(10):
n = random.randint(0, 10000)
print('Put task %d...' % n)
task.put(n)
# 从result队列读取结果:
print('Try get results...')
for i in range(10):
r = result.get(timeout=10)
print('Result: %s' % r)
# 关闭:
manager.shutdown()
print('master exit.')
if __name__ == '__main__':
task_run()
|
[
"wz591757596@163.com"
] |
wz591757596@163.com
|
7b02be135bb7cd1c50578c242919e30865e8ccb5
|
191a7f83d964f74a2b3c7faeb4fc47d9c63d521f
|
/.history/main_20210523152024.py
|
f07a1738d818cc8037a69010ee1541519e6e81c2
|
[] |
no_license
|
AndreLiu1225/Kinder-Values-Survey
|
2a317feee8d5b17c27da2b2116742656e35d8ab9
|
090c27da0c822abb7dfc0ec6e13ae1b3dcb7bbf3
|
refs/heads/master
| 2023-05-03T00:26:00.481423
| 2021-06-04T03:24:19
| 2021-06-04T03:24:19
| 371,989,154
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,821
|
py
|
from flask import Flask, render_template, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, TextField, SubmitField, IntegerField, SelectField, RadioField
from wtforms.validators import DataRequired, Email, EqualTo, Length, ValidationError
app = Flask(__name__)
app.config['SECRET_KEY'] = "0c8973c8a5e001bb0c816a7b56c84f3a"
class MCQ(FlaskForm):
age = IntegerField("Please enter your age", validators=[DataRequired()])
profession = StringField("What is your profession?", validators=[DataRequired(), Length(max=30)])
power = RadioField("Do you desire a higher social status and dominance over others?", choices=[('Yes', 'It is my priority'), ('No', 'It is not my priority')])
tradition = RadioField("Do you desire a higher social status and dominance over others?", choices=[('Yes', 'It is my priority'), ('No', 'It is not my priority')])
achievement = RadioField("Do you desire a higher social status and dominance over others?", choices=[('Yes', 'It is my priority'), ('No', 'It is not my priority')])
stimulation = RadioField("Do you desire a higher social status and dominance over others?", choices=[('Yes', 'It is my priority'), ('No', 'It is not my priority')])
hedonism = RadioField("Do you desire a higher social status and dominance over others?", choices=[('Yes', 'It is my priority'), ('No', 'It is not my priority')])
conformity = RadioField("Do you desire a higher social status and dominance over others?", choices=[('Yes', 'It is my priority'), ('No', 'It is not my priority')])
self_direction = RadioField("Do you desire a higher social status and dominance over others?", choices=[('Yes', 'It is my priority'), ('No', 'It is not my priority')])
submit = SubmitField("Submit")
if __name__ == "__main__":
app.run(debug=True)
|
[
"andreliu2004@gmail.com"
] |
andreliu2004@gmail.com
|
c27d32cdd1b7b026779339fc68a7830871f34535
|
4dd811c2595a990cb21327afe7a2dfd54ba9b52f
|
/Open-CV_Basics/threshold_example.py
|
3b3018af5e505a219059d82806e1a161262e2bc4
|
[] |
no_license
|
mitesh55/Deep-Learning
|
40842af8b8f1ea3c041fa4de2e76d068f554c1a4
|
0a7c0305edb027acfaad38e7abe52808260cede9
|
refs/heads/master
| 2023-07-25T14:31:14.285489
| 2021-09-09T13:46:31
| 2021-09-09T13:46:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,288
|
py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 24 09:09:57 2020
@author: pavankunchala
"""
import cv2
from matplotlib import pyplot as plt
def show_img_with_matplotlib(color_img, title, pos):
"""Shows an image using matplotlib capabilities"""
# Convert BGR image to RGB
img_RGB = color_img[:, :, ::-1]
ax = plt.subplot(3, 3, pos)
plt.imshow(img_RGB)
plt.title(title)
plt.axis('off')
# Create the dimensions of the figure and set title and color:
fig = plt.figure(figsize=(9, 9))
plt.suptitle("Thresholding example", fontsize=14, fontweight='bold')
fig.patch.set_facecolor('silver')
# Load the image and convert it to grayscale:
image = cv2.imread('img.png')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Plot the grayscale image:
show_img_with_matplotlib(cv2.cvtColor(gray_image, cv2.COLOR_GRAY2BGR), "img", 1)
# Apply cv2.threshold() with different thresholding values:
ret1, thresh1 = cv2.threshold(gray_image, 60, 255, cv2.THRESH_BINARY)
ret2, thresh2 = cv2.threshold(gray_image, 70, 255, cv2.THRESH_BINARY)
ret3, thresh3 = cv2.threshold(gray_image, 80, 255, cv2.THRESH_BINARY)
ret4, thresh4 = cv2.threshold(gray_image, 90, 255, cv2.THRESH_BINARY)
ret5, thresh5 = cv2.threshold(gray_image, 100, 255, cv2.THRESH_BINARY)
ret6, thresh6 = cv2.threshold(gray_image, 110, 255, cv2.THRESH_BINARY)
ret7, thresh7 = cv2.threshold(gray_image, 120, 255, cv2.THRESH_BINARY)
ret8, thresh8 = cv2.threshold(gray_image, 130, 255, cv2.THRESH_BINARY)
# Plot all the thresholded images:
show_img_with_matplotlib(cv2.cvtColor(thresh1, cv2.COLOR_GRAY2BGR), "threshold = 60", 2)
show_img_with_matplotlib(cv2.cvtColor(thresh2, cv2.COLOR_GRAY2BGR), "threshold = 70", 3)
show_img_with_matplotlib(cv2.cvtColor(thresh3, cv2.COLOR_GRAY2BGR), "threshold = 80", 4)
show_img_with_matplotlib(cv2.cvtColor(thresh4, cv2.COLOR_GRAY2BGR), "threshold = 90", 5)
show_img_with_matplotlib(cv2.cvtColor(thresh5, cv2.COLOR_GRAY2BGR), "threshold = 100", 6)
show_img_with_matplotlib(cv2.cvtColor(thresh6, cv2.COLOR_GRAY2BGR), "threshold = 110", 7)
show_img_with_matplotlib(cv2.cvtColor(thresh7, cv2.COLOR_GRAY2BGR), "threshold = 120", 8)
show_img_with_matplotlib(cv2.cvtColor(thresh8, cv2.COLOR_GRAY2BGR), "threshold = 130", 9)
# Show the Figure:
plt.show()
|
[
"pavankuchalapk@gmail.com"
] |
pavankuchalapk@gmail.com
|
500729c399198a7f347c002ba8524217d5ad7c11
|
4324d19af69080f45ff60b733c940f7dc1aa6dae
|
/google-ads-python/google/ads/google_ads/v0/proto/services/ad_group_bid_modifier_service_pb2_grpc.py
|
323a703193e94e53842992d5f9f98450e7ec0307
|
[
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
ljborton/Forked_Work
|
cc8a3813c146ea4547aca9caeb03e649bbdb9076
|
7aaf67af8d9f86f9dc0530a1ad23951bcb535c92
|
refs/heads/master
| 2023-07-19T22:26:48.085129
| 2019-11-27T02:53:51
| 2019-11-27T02:53:51
| 224,321,748
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,600
|
py
|
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.ads.google_ads.v0.proto.resources import ad_group_bid_modifier_pb2 as google_dot_ads_dot_googleads__v0_dot_proto_dot_resources_dot_ad__group__bid__modifier__pb2
from google.ads.google_ads.v0.proto.services import ad_group_bid_modifier_service_pb2 as google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_ad__group__bid__modifier__service__pb2
class AdGroupBidModifierServiceStub(object):
"""Service to manage ad group bid modifiers.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.GetAdGroupBidModifier = channel.unary_unary(
'/google.ads.googleads.v0.services.AdGroupBidModifierService/GetAdGroupBidModifier',
request_serializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_ad__group__bid__modifier__service__pb2.GetAdGroupBidModifierRequest.SerializeToString,
response_deserializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_resources_dot_ad__group__bid__modifier__pb2.AdGroupBidModifier.FromString,
)
self.MutateAdGroupBidModifiers = channel.unary_unary(
'/google.ads.googleads.v0.services.AdGroupBidModifierService/MutateAdGroupBidModifiers',
request_serializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_ad__group__bid__modifier__service__pb2.MutateAdGroupBidModifiersRequest.SerializeToString,
response_deserializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_ad__group__bid__modifier__service__pb2.MutateAdGroupBidModifiersResponse.FromString,
)
class AdGroupBidModifierServiceServicer(object):
"""Service to manage ad group bid modifiers.
"""
def GetAdGroupBidModifier(self, request, context):
"""Returns the requested ad group bid modifier in full detail.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def MutateAdGroupBidModifiers(self, request, context):
"""Creates, updates, or removes ad group bid modifiers.
Operation statuses are returned.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_AdGroupBidModifierServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'GetAdGroupBidModifier': grpc.unary_unary_rpc_method_handler(
servicer.GetAdGroupBidModifier,
request_deserializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_ad__group__bid__modifier__service__pb2.GetAdGroupBidModifierRequest.FromString,
response_serializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_resources_dot_ad__group__bid__modifier__pb2.AdGroupBidModifier.SerializeToString,
),
'MutateAdGroupBidModifiers': grpc.unary_unary_rpc_method_handler(
servicer.MutateAdGroupBidModifiers,
request_deserializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_ad__group__bid__modifier__service__pb2.MutateAdGroupBidModifiersRequest.FromString,
response_serializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_ad__group__bid__modifier__service__pb2.MutateAdGroupBidModifiersResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'google.ads.googleads.v0.services.AdGroupBidModifierService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
|
[
"noreply@github.com"
] |
ljborton.noreply@github.com
|
c199a8c9d14036ef6e195fc868e7c99f7939151e
|
29ac2c1477b2972820dd024ee443b8626e3224cf
|
/gallery/migrations/0002_auto_20210608_0440.py
|
87afdaaf43bc510f256b14412bc81c86310e8178
|
[] |
no_license
|
devArist/school_project3
|
5cdf1955e60ff727a64cf7cb50987da70149b0b8
|
c153339cf55a87cb81b331ce7fbd43615a0435aa
|
refs/heads/main
| 2023-05-09T19:48:32.092513
| 2021-06-08T10:07:25
| 2021-06-08T10:07:25
| 374,965,640
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 559
|
py
|
# Generated by Django 3.2.3 on 2021-06-08 04:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gallery', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='photo',
name='formats',
field=models.CharField(max_length=50, null=True, verbose_name='format'),
),
migrations.AddField(
model_name='video',
name='duration',
field=models.DurationField(null=True),
),
]
|
[
"aridev97@gmail.com"
] |
aridev97@gmail.com
|
a68d760a069c84b3e5c6d1a92d06ab3f2bd4fd43
|
950ce2ac7aa569c7e82bd135492c0ff94ef97c74
|
/test/myapp/myapp/spiders/item_xpath.py
|
4f8a0120bf12e339747335c62122f88055842a82
|
[] |
no_license
|
ShichaoMa/webWalker
|
74ea7f38b74272d951e8bccea730a40f7f0c72b4
|
8c085d6f385f85f193b0992b1148f165652e3a98
|
refs/heads/master
| 2021-01-12T16:50:36.331337
| 2017-12-08T11:26:46
| 2017-12-08T11:26:46
| 71,446,722
| 62
| 18
| null | 2017-12-08T11:26:47
| 2016-10-20T09:27:08
|
Python
|
UTF-8
|
Python
| false
| false
| 236
|
py
|
# -*- coding:utf-8 -*-
ITEM_XPATH = {
"bluefly": [
'//ul[@class="mz-productlist-list mz-l-tiles"]/li//a[@class="mz-productlisting-title"]/@href',
],
"douban": [
"//a[@class='product-photo']/@href",
]
}
|
[
"308299269@qq.com"
] |
308299269@qq.com
|
ea2dd8bf45e6bb9c2b6ff09afb422072ab1fe92b
|
8566f9905a831b05dd79c0cb0d1cf99bd258a917
|
/models/sml/sml_celeba_cactus.py
|
0360822647d3a2a0a40c06b37deafe44bdd0e926
|
[
"Apache-2.0"
] |
permissive
|
emerld2011/MetaLearning-TF2.0
|
8e81db2a5489ffc2ccb4f21eb8202d1c50106844
|
de852bd3b2ff46f8d390cebf561add3a166ee855
|
refs/heads/main
| 2023-08-14T18:21:23.539460
| 2021-09-17T14:42:22
| 2021-09-17T14:42:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,397
|
py
|
import tensorflow as tf
from models.sml.sml import SML
from networks.maml_umtra_networks import MiniImagenetModel
from databases import CelebADatabase, LFWDatabase
def run_celeba():
celeba_database = CelebADatabase()
base_model = tf.keras.applications.VGG19(weights='imagenet')
feature_model = tf.keras.models.Model(inputs=base_model.input, outputs=base_model.layers[24].output)
sml = SML(
database=celeba_database,
target_database=LFWDatabase(),
network_cls=MiniImagenetModel,
n=5,
k=1,
k_val_ml=5,
k_val_val=15,
k_val_test=15,
k_test=15,
meta_batch_size=4,
num_steps_ml=5,
lr_inner_ml=0.05,
num_steps_validation=5,
save_after_iterations=15000,
meta_learning_rate=0.001,
n_clusters=500,
feature_model=feature_model,
# feature_size=288,
feature_size=4096,
input_shape=(224, 224, 3),
preprocess_function=tf.keras.applications.vgg19.preprocess_input,
log_train_images_after_iteration=1000,
number_of_tasks_val=100,
number_of_tasks_test=1000,
clip_gradients=True,
report_validation_frequency=250,
experiment_name='cactus_celeba_original3'
)
sml.train(iterations=60000)
sml.evaluate(iterations=50, seed=42)
if __name__ == '__main__':
run_celeba()
|
[
"siavash.khodadadeh@gmail.com"
] |
siavash.khodadadeh@gmail.com
|
6327cc15593e29d7b0f45312359af9350a81a2cc
|
15d477b2bc7da4e1bddd6fa33f0768fcbd4c82c3
|
/simple_3d_engine.py
|
62feb8ad80ef2a33f85e02f37a7f238e444e751b
|
[] |
no_license
|
gunny26/pygame
|
364d4a221e2d11bd491190f97670b09123146ad7
|
1fd421195a2888c0588a49f5a043a1110eedcdbf
|
refs/heads/master
| 2022-10-20T00:56:34.415095
| 2022-10-03T19:27:52
| 2022-10-03T19:27:52
| 7,414,604
| 5
| 11
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,778
|
py
|
#!/usr/bin/python3
import sys
import math
import time
# non std
import pygame
class Vec2d:
def __init__(self, x, y):
self.x = x
self.y = y
class Vec3d:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class Vec4d:
def __init__(self, x, y, z, w):
self.x = x
self.y = y
self.z = z
self.w = w
class Triangle:
def __init__(self, v1, v2, v3):
self.v1 = v1
self.v2 = v2
self.v3 = v3
class Mesh:
def __init__(self, triangles):
self.triangles = triangles
def __getitem__(self, index):
return self.triangles[index]
class Matrix4x4:
def __init__(self, vecs):
self.vecs = vecs
def __mul__(self, vec3d):
vec4d = Vec4d(*[
vec3d.x * self.vecs[0][0] + vec3d.y * self.vecs[1][0] + vec3d.z * self.vecs[2][0] + self.vecs[3][0],
vec3d.x * self.vecs[0][1] + vec3d.y * self.vecs[1][1] + vec3d.z * self.vecs[2][1] + self.vecs[3][1],
vec3d.x * self.vecs[0][2] + vec3d.y * self.vecs[1][2] + vec3d.z * self.vecs[2][2] + self.vecs[3][2],
vec3d.x * self.vecs[0][3] + vec3d.y * self.vecs[1][3] + vec3d.z * self.vecs[2][3] + self.vecs[3][3]
])
if vec4d.w != 0.0:
vec4d.x /= vec4d.w
vec4d.y /= vec4d.w
vec4d.z /= vec4d.w
return vec4d
def draw_triangle(surface, color, triangle):
pygame.draw.line(surface, color, (triangle.v1.x, triangle.v1.y), (triangle.v2.x, triangle.v2.y), 1)
pygame.draw.line(surface, color, (triangle.v2.x, triangle.v2.y), (triangle.v3.x, triangle.v3.y), 1)
pygame.draw.line(surface, color, (triangle.v3.x, triangle.v3.y), (triangle.v1.x, triangle.v1.y), 1)
if __name__=='__main__':
try:
surface = pygame.display.set_mode((600,600))
pygame.init()
# constants
FPS = 20
WHITE = (255, 255, 255) # white
clock = pygame.time.Clock()
width = surface.get_width()
height = surface.get_height()
theta = 90.0 # sixtee degree
z_near = 0.1
z_far = 1000.0
# some well known terms
fov = 1 / math.tan(theta / 2) # field of view
aspect = width / height
q = z_far / (z_far - z_near) # z projection
# help:
# x = aspect * fov * x / z
# y = fov * y / z
# z = z * (q - q * z_near)
projection_matrix = Matrix4x4([
[ aspect * fov, 0 , 0 , 0],
[ 0 , fov, 0 , 0],
[ 0 , 0 , q , 1],
[ 0 , 0 , -z_near * q, 0]
])
# define cube, all triangle in same direction
cube = Mesh([
Triangle(Vec3d(0, 0, 0), Vec3d(0, 1, 0), Vec3d(1, 1, 0)), # south
Triangle(Vec3d(1, 1, 0), Vec3d(1, 0, 0), Vec3d(0, 0, 0)), # south
Triangle(Vec3d(1, 0, 0), Vec3d(1, 1, 0), Vec3d(1, 1, 1)), # east
Triangle(Vec3d(1, 1, 1), Vec3d(1, 0, 1), Vec3d(1, 0, 0)), # east
Triangle(Vec3d(0, 0, 1), Vec3d(0, 1, 1), Vec3d(0, 1, 0)), # west
Triangle(Vec3d(0, 1, 0), Vec3d(0, 0, 0), Vec3d(0, 0, 1)), # west
Triangle(Vec3d(1, 0, 1), Vec3d(1, 1, 1), Vec3d(0, 0, 1)), # north
Triangle(Vec3d(0, 0, 1), Vec3d(0, 1, 1), Vec3d(1, 1, 1)), # north
Triangle(Vec3d(0, 0, 1), Vec3d(0, 0, 0), Vec3d(1, 0, 0)), # bottom
Triangle(Vec3d(1, 0, 0), Vec3d(1, 0, 1), Vec3d(0, 0, 1)), # bottom
Triangle(Vec3d(0, 1, 0), Vec3d(0, 1, 1), Vec3d(1, 1, 1)), # top
Triangle(Vec3d(1, 1, 1), Vec3d(1, 1, 0), Vec3d(0, 1, 0)) # top
])
while True:
clock.tick(FPS)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
sys.exit(0)
keyinput = pygame.key.get_pressed()
if keyinput is not None:
# print keyinput
if keyinput[pygame.K_ESCAPE]:
sys.exit(1)
surface.fill(0)
# create rotation matrix around x and z axis
f_theta = time.time()
rot_x = Matrix4x4([
[ 1, 0, 0, 0 ],
[ 0, math.cos(f_theta), -math.sin(f_theta), 0 ],
[ 0, math.sin(f_theta), math.cos(f_theta), 0 ],
[ 0, 0, 0, 1 ]
])
rot_y = Matrix4x4([
[ math.cos(f_theta), 0, math.sin(f_theta), 0 ],
[ 0, 1, 0, 0 ],
[ -math.sin(f_theta), 0, math.cos(f_theta), 0 ],
[ 0, 0, 0, 1 ]
])
rot_z = Matrix4x4([
[ math.cos(f_theta * 0.5), -math.sin(f_theta * 0.5), 0, 0 ],
[ math.sin(f_theta * 0.5), math.cos(f_theta * 0.5), 0, 0 ],
[ 0, 0, 1, 0 ],
[ 0, 0, 0, 1 ]
])
# do projection
for triangle in cube:
# rotate z
t_z = Triangle(*[
rot_z * triangle.v1,
rot_z * triangle.v2,
rot_z * triangle.v3
])
# rotate x
t_x = Triangle(*[
rot_x * t_z.v1,
rot_x * t_z.v2,
rot_x * t_z.v3
])
# translate into Z
t_t = Triangle(*[
Vec3d(t_x.v1.x, t_x.v1.y, t_x.v1.z + 3.0),
Vec3d(t_x.v2.x, t_x.v2.y, t_x.v2.z + 3.0),
Vec3d(t_x.v3.x, t_x.v3.y, t_x.v3.z + 3.0)
])
# project
t_p = Triangle(*[
projection_matrix * t_t.v1,
projection_matrix * t_t.v2,
projection_matrix * t_t.v3
])
# shift to positive values
t_p.v1.x += 1.0
t_p.v1.y += 1.0
t_p.v2.x += 1.0
t_p.v2.y += 1.0
t_p.v3.x += 1.0
t_p.v3.y += 1.0
# scale by half the screen
t_p.v1.x *= width / 2
t_p.v1.y *= height / 2
t_p.v2.x *= width/2
t_p.v2.y *= height / 2
t_p.v3.x *= width/2
t_p.v3.y *= height / 2
draw_triangle(surface, WHITE, t_p)
pygame.display.flip()
except KeyboardInterrupt:
print('shutting down')
|
[
"arthur.messner@gmail.com"
] |
arthur.messner@gmail.com
|
7a08c8c0f10a0f895db76c5b49933e2ec90cfd3c
|
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
|
/8WvpPQto44PqNLSqJ_16.py
|
1beb2118e0b5593eebf9a90ec62cd377057db150
|
[] |
no_license
|
daniel-reich/ubiquitous-fiesta
|
26e80f0082f8589e51d359ce7953117a3da7d38c
|
9af2700dbe59284f5697e612491499841a6c126f
|
refs/heads/master
| 2023-04-05T06:40:37.328213
| 2021-04-06T20:17:44
| 2021-04-06T20:17:44
| 355,318,759
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 190
|
py
|
def pad(message):
if len(message)<140:
if not len(message)%2:
message += ' l'
else:
message += 'l'
while len(message)<140:
message += 'ol'
return message
|
[
"daniel.reich@danielreichs-MacBook-Pro.local"
] |
daniel.reich@danielreichs-MacBook-Pro.local
|
d1297225e16ebf5161aebae8590fb1060bd9310e
|
e6f16fbba8fba750099252c3490f00079cb19101
|
/算法/053_最大子序求和.py
|
e493a34fa89f268394e4fe3b768062a9898cacd9
|
[] |
no_license
|
hookeyplayer/exercise.io
|
0a36fbec9df6c24b60ff6f97de27d3d5ae7769d4
|
605c81cb44443efd974db9fa0a088ddcd5a96f0f
|
refs/heads/master
| 2023-06-20T17:03:20.310816
| 2021-07-31T12:50:21
| 2021-07-31T12:50:21
| 277,175,487
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,012
|
py
|
from typing import List
class Solution:
# DP1
# 贪心
def maxSubArray(self, nums: List[int]) -> int:
thisSum = 0
maxSum = -2**31
for i in range(len(nums)):
if thisSum < 0:
thisSum = 0
thisSum += nums[i]
maxSum = max(maxSum, thisSum)
return maxSum
# DP2
def maxSubArray(self, nums: List[int]) -> int:
# 构造子序列时保证以第n个元素结尾
# 原先是正增益的作用,则包含到新的子序列中;否则抛弃前面的子序列
dp = [0] * len(nums)
dp[0] = nums[0]
ans = nums[0]
for i in range(1, len(nums)):
dp[i] = max(dp[i-1], 0) + nums[i]
ans = max(ans, dp[i])
return ans
# DP3
def maxSubArray(self, nums: List[int]) -> int:
maxEndingHere = ans = nums[0]
for i in range(1, len(nums)):
maxEndingHere = max(maxEndingHere+nums[i], nums[i])
ans = max(maxEndingHere, ans)
return ans
if __name__ == '__main__':
test = Solution()
print(test.maxSubArray([-2, 3, -1, -8]))
|
[
"noreply@github.com"
] |
hookeyplayer.noreply@github.com
|
9ea0d53abc6fe76ea844647c939081ba7bef497d
|
986a8c5de450fc436897de9aaff4c5f737074ee3
|
/笔试题/2019 PayPal实习生招聘编程卷/2_寻找关联用户.py
|
9f80fb24348a2f07ea5df09bb989cd129384753d
|
[] |
no_license
|
lovehhf/newcoder_py
|
7a0ef03f0ea733ec925a10f06566040f6edafa67
|
f8ae73deef1d9422ca7b0aa9f484dc96db58078c
|
refs/heads/master
| 2020-04-27T18:20:19.082458
| 2019-05-24T15:30:13
| 2019-05-24T15:30:13
| 174,564,930
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,697
|
py
|
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
PayPal上海团队一直致力于风险控制,风控需要收集各种信息,有时需要通过地理位置找出用户与用户之间存在的关联关系,
这一信息可能会用于找出用户潜在存在的风险问题。我们记两个用户的关联关系可以表示为:
(1). user1,user2与他们最常发生交易的地理位置分别为(x1, y1),(x2, y2),当这两个用户的欧氏距离不超过d时,我们就认为两个用户关联。
(2). **用户关联性具有传递性**,若用户1与用户2关联,用户2与用户3关联,那么用户1,2,3均关联。
给定N个用户及其地理位置坐标,将用户按照关联性进行划分,要求返回一个集合,集合中每个元素是属于同一个范围的用户群。
输入描述:
d:欧式距离
N:用户数
之后的N行表示第0个用户到第N-1个用户的地理位置坐标
输出描述:
一个数组集合,所有关联的用户在一个数组中。
输出数组需要按照从小到大的顺序排序,每个集合内的数组也需要按照从小到大的顺序排序。
输入例子1:
2.0
5
3.0 5.0
6.0 13.0
2.0 6.0
7.0 12.0
0.0 2.0
输出例子1:
[[0, 2], [1, 3], [4]]
欧氏距离(Euclid Distance)也称欧几里得度量、欧几里得距离,
是一个通常采用的距离定义,它是在m维空间中两个点之间的真实距离.在二维空间中的欧氏距离就是两点之间的直线段距离.
"""
def solve(d, n, grid):
r = [[] for _ in range(n)]
s = {x for x in range(n)}
for i in range(n - 1):
x1, y1 = grid[i][0], grid[i][1]
for j in range(i + 1, n):
x2, y2 = grid[j][0], grid[j][1]
td = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 # 欧氏距离
if td - d <= 1e-6:
r[i].append(j)
r[j].append(i)
s -= {i, j}
# print(s)
# print(r)
# for i in range(n):
# print(i, r[i])
# print(grid[5],grid[0])
res = []
visited = set()
for i in range(n):
if not r[i] or (i in visited):
continue
queue = [i] + r[i]
t = set()
# print(queue,visited)
visited.add(i)
while queue:
cur = queue.pop(0)
t.add(cur)
if r[cur] and not cur in visited:
visited.add(cur)
queue.extend(r[cur])
res.append(sorted(t))
res += [[x] for x in s]
res = sorted(res)
print(res)
def test():
d = 12.6
n = 100
grid = [[11.12, 99.45], [87.04, 54.52], [8.49, 56.22], [44.36, 63.42], [51.64, 16.18], [78.87, 44.55],
[68.98, 8.36], [38.5, 60.72], [8.9, 18.52], [66.65, 69.37], [16.94, 89.92], [2.91, 95.37], [88.73, 67.56],
[48.36, 10.49], [77.66, 81.33], [19.84, 23.79], [93.73, 53.5], [70.4, 84.37], [2.96, 45.82], [71.81, 86.02],
[25.85, 32.62], [38.68, 41.81], [37.4, 97.38], [23.97, 66.08], [91.64, 2.62], [30.52, 60.87],
[28.77, 75.35], [64.51, 54.66], [74.76, 83.85], [3.17, 82.11], [9.85, 55.38], [61.39, 25.37],
[64.98, 98.91], [19.56, 59.94], [3.41, 52.19], [18.59, 60.89], [58.39, 68.43], [37.04, 28.99],
[27.38, 93.92], [40.0, 90.5], [68.04, 65.41], [29.76, 9.24], [2.14, 73.34], [34.22, 25.04], [9.62, 95.71],
[40.49, 98.77], [86.92, 5.87], [18.53, 0.91], [51.52, 97.44], [82.42, 28.02], [97.19, 49.6], [5.07, 69.3],
[43.87, 76.62], [36.86, 74.31], [80.08, 67.32], [77.6, 91.9], [65.82, 21.78], [17.34, 60.42],
[49.76, 35.59], [91.91, 29.64], [55.63, 65.11], [95.93, 86.18], [9.62, 31.09], [58.24, 35.57],
[13.12, 82.71], [12.43, 66.84], [13.45, 49.13], [88.7, 88.32], [88.66, 51.46], [12.21, 76.92],
[42.25, 34.59], [18.11, 27.49], [98.4, 5.19], [83.28, 23.66], [98.97, 30.16], [31.31, 77.16],
[30.12, 57.63], [88.39, 98.54], [47.77, 72.19], [55.23, 69.07], [29.1, 84.83], [12.87, 81.05],
[50.15, 89.02], [98.83, 1.52], [78.53, 84.48], [73.81, 93.22], [74.51, 82.02], [49.29, 95.63],
[13.84, 54.87], [61.39, 29.04], [81.36, 94.3], [57.4, 34.96], [35.52, 60.97], [8.04, 7.26], [11.1, 97.25],
[70.59, 0.15], [9.76, 80.16], [6.05, 21.77], [26.16, 50.0], [96.66, 34.61]]
solve(d, n, grid)
def main():
grid = []
d = float(input())
n = int(input())
for _ in range(n):
grid.append(list(map(float, input().split())))
solve(d, n, grid)
def test2():
x1, y1 = [78.87, 44.55]
for x2, y2 in [[87.04, 54.52], [93.73, 53.5], [97.19, 49.6], [88.66, 51.46]]:
print(((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5)
main()
|
[
"853885165@qq.com"
] |
853885165@qq.com
|
285805fef3a2ff9e680c5ab423f7d70e47b906fb
|
71962596a0693e03e19257f1beb3bdda223ed4ff
|
/profile_xf05id1/startup/81-saturn.py
|
f8188b0e760c0e83d75202caca233c3c59ee06b7
|
[
"BSD-2-Clause"
] |
permissive
|
tacaswell/ipython_srx
|
53561979f27a108063f4851ea314073768098cbb
|
e3dbb45cfd87c166878e8420654cc7995f772eda
|
refs/heads/master
| 2020-12-25T00:19:11.936763
| 2016-02-18T00:30:51
| 2016-02-18T00:30:51
| 51,659,688
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,831
|
py
|
from ophyd.mca import (EpicsMCA, EpicsDXP)
from ophyd import (Component as Cpt, Device, EpicsSignal, EpicsSignalRO,
EpicsSignalWithRBV, DeviceStatus)
from ophyd.device import (BlueskyInterface, Staged)
class SaturnMCA(EpicsMCA):
# TODO: fix upstream
preset_real_time = Cpt(EpicsSignal, '.PRTM')
preset_live_time = Cpt(EpicsSignal, '.PLTM')
elapsed_real_time = Cpt(EpicsSignalRO, '.ERTM')
elapsed_live_time = Cpt(EpicsSignalRO, '.ELTM')
check_acquiring = Cpt(EpicsSignal, 'CheckACQG')
client_wait = Cpt(EpicsSignal, 'ClientWait')
collect_data = Cpt(EpicsSignal, 'CollectData')
enable_wait = Cpt(EpicsSignal, 'EnableWait')
erase = Cpt(EpicsSignal, 'Erase')
erase_start = Cpt(EpicsSignal, 'EraseStart')
read = Cpt(EpicsSignal, 'Read')
read_callback = Cpt(EpicsSignal, 'ReadCallback')
read_data_once = Cpt(EpicsSignal, 'ReadDataOnce')
read_status_once = Cpt(EpicsSignal, 'ReadStatusOnce')
set_client_wait = Cpt(EpicsSignal, 'SetClientWait')
start = Cpt(EpicsSignal, 'Start')
status = Cpt(EpicsSignal, 'Status')
stop_signal = Cpt(EpicsSignal, 'Stop')
when_acq_stops = Cpt(EpicsSignal, 'WhenAcqStops')
why1 = Cpt(EpicsSignal, 'Why1')
why2 = Cpt(EpicsSignal, 'Why2')
why3 = Cpt(EpicsSignal, 'Why3')
why4 = Cpt(EpicsSignal, 'Why4')
class SaturnDXP(EpicsDXP):
baseline_energy_array = Cpt(EpicsSignal, 'BaselineEnergyArray')
baseline_histogram = Cpt(EpicsSignal, 'BaselineHistogram')
calibration_energy = Cpt(EpicsSignal, 'CalibrationEnergy_RBV')
current_pixel = Cpt(EpicsSignal, 'CurrentPixel')
dynamic_range = Cpt(EpicsSignal, 'DynamicRange_RBV')
elapsed_live_time = Cpt(EpicsSignal, 'ElapsedLiveTime')
elapsed_real_time = Cpt(EpicsSignal, 'ElapsedRealTime')
elapsed_trigger_live_time = Cpt(EpicsSignal, 'ElapsedTriggerLiveTime')
energy_threshold = Cpt(EpicsSignalWithRBV, 'EnergyThreshold')
gap_time = Cpt(EpicsSignalWithRBV, 'GapTime')
max_width = Cpt(EpicsSignalWithRBV, 'MaxWidth')
mca_bin_width = Cpt(EpicsSignal, 'MCABinWidth_RBV')
num_ll_params = Cpt(EpicsSignal, 'NumLLParams')
peaking_time = Cpt(EpicsSignalWithRBV, 'PeakingTime')
preset_events = Cpt(EpicsSignalWithRBV, 'PresetEvents')
preset_mode = Cpt(EpicsSignalWithRBV, 'PresetMode')
preset_triggers = Cpt(EpicsSignalWithRBV, 'PresetTriggers')
read_ll_params = Cpt(EpicsSignal, 'ReadLLParams')
trace_data = Cpt(EpicsSignal, 'TraceData')
trace_mode = Cpt(EpicsSignalWithRBV, 'TraceMode')
trace_time_array = Cpt(EpicsSignal, 'TraceTimeArray')
trace_time = Cpt(EpicsSignalWithRBV, 'TraceTime')
trigger_gap_time = Cpt(EpicsSignalWithRBV, 'TriggerGapTime')
trigger_peaking_time = Cpt(EpicsSignalWithRBV, 'TriggerPeakingTime')
trigger_threshold = Cpt(EpicsSignalWithRBV, 'TriggerThreshold')
class Saturn(Device):
dxp = Cpt(SaturnDXP, 'dxp1:')
mca = Cpt(SaturnMCA, 'mca1')
channel_advance = Cpt(EpicsSignal, 'ChannelAdvance')
client_wait = Cpt(EpicsSignal, 'ClientWait')
dwell = Cpt(EpicsSignal, 'Dwell')
max_scas = Cpt(EpicsSignal, 'MaxSCAs')
num_scas = Cpt(EpicsSignalWithRBV, 'NumSCAs')
poll_time = Cpt(EpicsSignalWithRBV, 'PollTime')
prescale = Cpt(EpicsSignal, 'Prescale')
save_system = Cpt(EpicsSignalWithRBV, 'SaveSystem')
save_system_file = Cpt(EpicsSignal, 'SaveSystemFile')
set_client_wait = Cpt(EpicsSignal, 'SetClientWait')
class SaturnSoftTrigger(BlueskyInterface):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._status = None
self._acquisition_signal = self.mca.erase_start
self.stage_sigs[self.mca.stop_signal] = 1
self.stage_sigs[self.dxp.preset_mode] = 'Real time'
self._count_signal = self.mca.preset_real_time
self._count_time = None
def stage(self):
if self._count_time is not None:
self.stage_sigs[self._count_signal] = self._count_time
super().stage()
def unstage(self):
try:
super().unstage()
finally:
if self._count_signal in self.stage_sigs:
del self.stage_sigs[self._count_signal]
self._count_time = None
def trigger(self):
"Trigger one acquisition."
if self._staged != Staged.yes:
raise RuntimeError("This detector is not ready to trigger."
"Call the stage() method before triggering.")
self._status = DeviceStatus(self)
self._acquisition_signal.put(1, callback=self._acquisition_done)
return self._status
def _acquisition_done(self, **kwargs):
'''pyepics callback for when put completion finishes'''
if self._status is not None:
self._status._finished()
self._status = None
@property
def count_time(self):
'''Exposure time, as set by bluesky'''
return self._count_time
@count_time.setter
def count_time(self, count_time):
self._count_time = count_time
class SRXSaturn(SaturnSoftTrigger, Saturn):
def __init__(self, prefix, *, read_attrs=None, configuration_attrs=None,
**kwargs):
if read_attrs is None:
read_attrs = ['mca.spectrum']
if configuration_attrs is None:
configuration_attrs = ['mca.preset_real_time',
'mca.preset_live_time',
'dxp.preset_mode',
]
super().__init__(prefix, read_attrs=read_attrs,
configuration_attrs=configuration_attrs, **kwargs)
if __name__ == '__main__':
from ophyd.commands import setup_ophyd
setup_ophyd()
saturn = SRXSaturn('dxpSaturn:', name='saturn')
|
[
"klauer@bnl.gov"
] |
klauer@bnl.gov
|
8c529c07af84d91fd9c4e3012908fb6f78b74f9e
|
e5d83ede8521027b05d9b91c43be8cab168610e6
|
/0x01-python-if_else_loops_functions/0-positive_or_negative.py
|
7db6d2d5aec2226e9657ea987dac24bd7104128f
|
[] |
no_license
|
Danielo814/holbertonschool-higher_level_programming
|
8918c3a6a9c136137761d47c5162b650708dd5cd
|
832b692529198bbee44d2733464aedfe650bff7e
|
refs/heads/master
| 2020-03-28T11:09:00.343055
| 2019-02-22T03:33:54
| 2019-02-22T03:33:54
| 148,181,433
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 238
|
py
|
#!/usr/bin/python3
import random
number = random.randint(-10, 10)
if number < 0:
print("{} is negative".format(number))
if number == 0:
print("{} is zero".format(number))
if number > 0:
print("{} is positive".format(number))
|
[
"211@holbertonschool.com"
] |
211@holbertonschool.com
|
30ee5b82371e74006e13d114f8f1da5e37e2137d
|
956cc6ff2b58a69292f7d1223461bc9c2b9ea6f1
|
/monk/tf_keras_1/transforms/common.py
|
9253e05c5cce0e7d2d18e4deaa3832cf3c094726
|
[
"Apache-2.0"
] |
permissive
|
Aanisha/monk_v1
|
c24279b2b461df9b3de2984bae0e2583aba48143
|
c9e89b2bc0c1dbb320aa6da5cba0aa1c1526ad72
|
refs/heads/master
| 2022-12-29T00:37:15.320129
| 2020-10-18T09:12:13
| 2020-10-18T09:12:13
| 286,278,278
| 0
| 0
|
Apache-2.0
| 2020-08-09T16:51:02
| 2020-08-09T16:51:02
| null |
UTF-8
|
Python
| false
| false
| 3,810
|
py
|
from monk.tf_keras_1.transforms.imports import *
from monk.system.imports import *
from monk.tf_keras_1.transforms.transforms import transform_color_jitter
from monk.tf_keras_1.transforms.transforms import transform_random_affine
from monk.tf_keras_1.transforms.transforms import transform_random_horizontal_flip
from monk.tf_keras_1.transforms.transforms import transform_random_rotation
from monk.tf_keras_1.transforms.transforms import transform_random_vertical_flip
from monk.tf_keras_1.transforms.transforms import transform_mean_subtraction
from monk.tf_keras_1.transforms.transforms import transform_normalize
@accepts(dict, list, post_trace=False)
#@TraceFunction(trace_args=False, trace_rv=False)
def set_transforms(system_dict, set_phases):
'''
Set transforms depending on the training, validation and testing phases.
Args:
system_dict (dict): System dictionary storing experiment state and set variables
set_phases (list): Phases in which to apply the transforms.
Returns:
dict: updated system dict
'''
transforms_test = [];
transforms_train = [];
transforms_val = [];
transformations = system_dict["dataset"]["transforms"];
normalize = False;
for phase in set_phases:
tsf = transformations[phase];
if(phase=="train"):
train_status = True;
val_status = False;
test_status = False;
elif(phase=="val"):
train_status = False;
val_status = True;
test_status = False;
else:
train_status = False;
val_status = False;
test_status = True;
for i in range(len(tsf)):
name = list(tsf[i].keys())[0]
input_dict = tsf[i][name];
train = train_status;
val = val_status;
test = test_status;
if(name == "ColorJitter"):
system_dict = transform_color_jitter(
system_dict,
input_dict["brightness"], input_dict["contrast"], input_dict["saturation"], input_dict["hue"],
train, val, test, retrieve=True
);
elif(name == "RandomAffine"):
system_dict = transform_random_affine(
system_dict,
input_dict["degrees"], input_dict["translate"], input_dict["scale"], input_dict["shear"],
train, val, test, retrieve=True
);
elif(name == "RandomHorizontalFlip"):
system_dict = transform_random_horizontal_flip(
system_dict,
input_dict["p"],
train, val, test, retrieve=True
);
elif(name == "RandomVerticalFlip"):
system_dict = transform_random_vertical_flip(
system_dict,
input_dict["p"],
train, val, test, retrieve=True
);
elif(name == "RandomRotation"):
system_dict = transform_random_rotation(
system_dict,
input_dict["degrees"],
train, val, test, retrieve=True
);
elif(name == "MeanSubtraction"):
system_dict = transform_mean_subtraction(
system_dict,
input_dict["mean"],
train, val, test, retrieve=True
);
elif(name == "Normalize"):
system_dict = transform_normalize(
system_dict,
input_dict["mean"], input_dict["std"],
train, val, test, retrieve=True
);
return system_dict;
|
[
"abhishek4273@gmail.com"
] |
abhishek4273@gmail.com
|
9498db4276799b71082911df61014f50e9e00ed4
|
c879972850bdef6f9c05ec57c964125e4d5d8dfa
|
/lino/management/commands/qtclient.py
|
d7596bcdee3da87a45dd2c84f87e0999c0367cd2
|
[
"BSD-2-Clause"
] |
permissive
|
forexblog/lino
|
845c17f22c6f58fbf0247b084ceacb5e89fba2ef
|
68cbd5dd985737b63091b232b9c788a3a9875eef
|
refs/heads/master
| 2023-02-16T02:33:08.387853
| 2021-01-15T09:39:58
| 2021-01-15T09:39:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,738
|
py
|
# -*- coding: UTF-8 -*-
# Copyright 2017-2021 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
from django.core.management.base import BaseCommand
from django.conf import settings
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton,
QMessageBox, QDesktopWidget, QMainWindow,
QAction, qApp, QTextEdit, QHBoxLayout,
QVBoxLayout)
# from PyQt5.QtCore import QCoreApplication
from PyQt5.QtGui import QIcon
from lino.api import rt
from lino.core.menus import Menu # , MenuItem
from unipath import Path
images_path = Path(settings.STATIC_ROOT, Path('static/images/mjames'))
class ItemCaller(object):
def __init__(self, win, mi):
self.mi = mi
self.win = win
def __call__(self, event):
if False:
QMessageBox.question(
self.win, str(self.mi.label),
str(self.mi.help_text),
QMessageBox.Yes |
QMessageBox.No, QMessageBox.Yes)
self.frm = DetailForm(self.win, self.mi)
self.frm.show()
class DetailForm(QWidget):
def __init__(self, win, mi):
self.mi = mi
super().__init__(win)
self.setWindowTitle(str(self.mi.label))
self.initUI()
def initUI(self):
okButton = QPushButton("OK")
cancelButton = QPushButton("Cancel")
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(okButton)
hbox.addWidget(cancelButton)
vbox = QVBoxLayout()
vbox.addStretch(1)
vbox.addLayout(hbox)
self.setLayout(vbox)
self.setGeometry(300, 300, 300, 150)
# self.show()
class LinoClient(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
textEdit = QTextEdit()
self.setCentralWidget(textEdit)
self.setGeometry(300, 300, 300, 220)
self.center()
self.setWindowTitle('qtclient.py')
self.setWindowIcon(QIcon('../../.static/logo.png'))
self.setToolTip('This is a <b>QWidget</b> widget')
self.menubar = self.menuBar()
user_type = rt.models.users.UserTypes.get_by_value('900')
menu = settings.SITE.get_site_menu(user_type)
self.load_menu(menu, self.menubar)
self.show()
self.statusBar().showMessage('Ready')
def load_menu(self, menu, menubar):
for mi in menu.items:
if isinstance(mi, Menu):
submenu = menubar.addMenu(str(mi.label))
self.load_menu(mi, submenu)
else:
a = QAction(QIcon(images_path.child('cancel.png')),
str(mi.label), self)
if mi.hotkey:
a.setShortcut(mi.hotkey)
a.setStatusTip(str(mi.help_text))
a.triggered.connect(ItemCaller(self, mi))
menubar.addAction(a)
# fileMenu = menubar.addMenu('&File')
exitAction = QAction(QIcon('exit.png'), '&Exit', self)
# exitAction.setShortcut('Ctrl+Q')
# exitAction.setStatusTip('Exit application')
# exitAction.triggered.connect(qApp.quit)
# fileMenu.addAction(exitAction)
# a = QAction(QIcon('detail.png'), '&Detail', self)
# a.triggered.connect(self.show_detail)
# fileMenu.addAction(a)
# self.toolbar = self.addToolBar('Exit')
# self.toolbar.addAction(exitAction)
# btn = QPushButton('Quit', self)
# btn.clicked.connect(QCoreApplication.instance().quit)
# btn.setToolTip('This is a <b>QPushButton</b> widget')
# btn.resize(btn.sizeHint())
# btn.move(50, 50)
# def show_detail(self, event):
# self.detail_form = DetailForm()
# self.detail_form.show()
def closeEvent(self, event):
if True:
event.accept()
return
reply = QMessageBox.question(self, 'MessageBox',
"This will close the window! Are you sure?",
QMessageBox.Yes |
QMessageBox.No, QMessageBox.Yes)
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
def center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
class Command(BaseCommand):
help = """Run a Qt client for this site."""
def handle(self, *args, **options):
app = QApplication(sys.argv)
self.ex = LinoClient()
# sys.exit(app.exec_())
return app.exec_()
|
[
"luc.saffre@gmail.com"
] |
luc.saffre@gmail.com
|
723d1ab3fba8472207d08566888754ff280a6ce1
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p02622/s420656500.py
|
ba3844bb33b39a0bd750b8488ba05864255e60b4
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 134
|
py
|
s = [x for x in input()]
t = [y for y in input()]
count = 0
for _ in range(len(s)):
if s[_] != t[_]:
count+=1
print(count)
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
ea8181be3486f3495b71aed3582a1cd0ce049fb5
|
412d0f01ab87c6b1e96f5f8afc263a3c33188b2f
|
/plots/fps_bar_chart.py
|
1b735fc4f4b009283bc7ea4997f878756bc13cae
|
[
"MIT"
] |
permissive
|
neevparikh/sample-factory
|
7e48a8b4c7d0b534642bd90d28e66677f03b715e
|
1b57647a231359ed6794db72bcc39b4ebb01b39e
|
refs/heads/master
| 2023-03-16T05:15:05.945225
| 2021-03-09T02:28:03
| 2021-03-09T02:28:03
| 290,346,928
| 0
| 0
|
MIT
| 2020-08-25T23:36:01
| 2020-08-25T23:36:00
| null |
UTF-8
|
Python
| false
| false
| 1,909
|
py
|
import math
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set()
labels = ['20', '40', '80', '160', '320', '640']
# fps_by_method_10_core_cpu = dict(
# deepmind_impala=[8590, 10596, 10941, 10928, 13328, math.nan],
# rllib_appo=[9384, 9676, 11171, 11328, 11590, 11345],
# ours=[11565, 16982, 25068, 37410, 46977, 52033]
# )
# data = fps_by_method_10_core_cpu
fps_by_method_36_core_cpu = dict(
deepmind_impala=[6951, 8191, 8041, 9900, 10014, math.nan],
rllib_appo=[13308, 23608, 30568, 31002, 32840, 33784],
ours=[11586, 20410, 33326, 46243, 70124, 86753],
)
data = fps_by_method_36_core_cpu
# ours: 160=40x4, 320=40x8 with 3072 bs, 640=80x8 with 3072 bs
# multi-policy:
# 2 policies, 640 actors, 93284 FPS
# 4 policies: 1600 actors, 116320 FPS
# 8 policies: 1600 actors,
x = np.arange(len(labels)) # the label locations
width = 0.25 # the width of the bars
fig, ax = plt.subplots(figsize=(12, 8))
item_idx = 0
bars = dict()
for key, value in data.items():
rects = ax.bar(x + item_idx * width - len(data) * width / 2, value, width, label=key)
bars[key] = rects
item_idx += 1
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_xlabel('Num. environments in parallel')
ax.set_ylabel('Environment frames per second')
ax.set_title('Throughput of different RL methods')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
def autolabel(rects):
"""Attach a text label above each bar in *rects*, displaying its height."""
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords='offset points',
ha='center', va='bottom')
autolabel(bars['ours'])
fig.tight_layout()
plt.show()
|
[
"petrenko@usc.edu"
] |
petrenko@usc.edu
|
cd99c5c4b1cb47999230fedf11bf9d56d4b14c76
|
bd5f807161da0a9d3f6f8c5c3b4da073545eaafc
|
/day_1/print_function.py
|
86260c5a4cb8249a92687577759a3a34cc0eb9c8
|
[
"MIT"
] |
permissive
|
anishLearnsToCode/python-workshop-7
|
a6a497ddb6cf41a2097ac976426710ca4aa41987
|
2d5933be2629600f5f9e8efea58403421737a299
|
refs/heads/main
| 2023-02-07T21:00:01.308260
| 2020-12-27T08:22:14
| 2020-12-27T08:22:14
| 323,645,763
| 5
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 131
|
py
|
print('i am batman', end='\n')
print('hello world', end='\t\t')
print('this is cool\n', end=' ----- ')
print('i am still here')
|
[
"anish_@outlook.com"
] |
anish_@outlook.com
|
74612d03df0d217ddea8a2be6fec57fb41f85c27
|
bb68c958809899a24ec7d250adacc70c30203b04
|
/rti_python/Ensemble/NmeaData.py
|
5ca12f52eb8356dbba94010a0c6d4f1277627fc5
|
[] |
no_license
|
jjt53/ReadPlotCSV_streamlit
|
d9e432ec83ec930d3e6aa6b8f07bf3329c8081b8
|
3fddf73033e3648bc86ccbf0c5cce2b7868250d9
|
refs/heads/main
| 2023-01-29T14:05:35.667192
| 2020-12-09T17:17:23
| 2020-12-09T17:17:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,745
|
py
|
import pynmea2
from rti_python.Ensemble.Ensemble import Ensemble
import logging
from pygeodesy import ellipsoidalVincenty
from decimal import *
class NmeaData:
"""
NMEA DataSet.
String data to decode.
"""
def __init__(self, num_elements=0, element_multiplier=1):
self.ds_type = 50 # Bytes
self.num_elements = num_elements
self.element_multiplier = element_multiplier
self.image = 0
self.name_len = 8
self.Name = "E000011\0"
self.nmea_sentences = []
# Initialize with bad values
self.GPGGA = None
self.GPVTG = None
self.GPRMC = None
self.GPGLL = None
self.GPGSV = None
self.GPGSA = None
self.GPHDT = None
self.GPHDG = None
self.latitude = 0.0
self.longitude = 0.0
self.speed_knots = 0.0 # Speed in Knots
self.speed_m_s = 0.0 # Speed in m/s
self.heading = 0.0
self.datetime = None # Date and Time from GGA
def decode(self, data):
"""
Take the data bytearray. Decode the data to populate
the NMEA data.
:param data: Bytearray for the dataset.
"""
packet_pointer = Ensemble.GetBaseDataSize(self.name_len)
nmea_str = str(data[packet_pointer:], "UTF-8")
self.num_elements = len(nmea_str)
for msg in nmea_str.split():
# Add the NMEA message
self.add_nmea(msg)
logging.debug(nmea_str)
logging.debug(self.nmea_sentences)
def add_nmea(self, msg):
try:
# Increment the number of elements
self.num_elements += len(msg)
# Parse the NMEA data
nmea_msg = pynmea2.parse(msg)
if isinstance(nmea_msg, pynmea2.types.talker.GGA):
self.GPGGA = nmea_msg
self.latitude = nmea_msg.latitude
self.longitude = nmea_msg.longitude
self.datetime = nmea_msg.timestamp
if isinstance(nmea_msg, pynmea2.types.talker.VTG):
self.GPVTG = nmea_msg
self.speed_knots = nmea_msg.spd_over_grnd_kts
self.speed_m_s = nmea_msg.spd_over_grnd_kts * Decimal(0.51444444444444)
if isinstance(nmea_msg, pynmea2.types.talker.RMC):
self.GPRMC = nmea_msg
if isinstance(nmea_msg, pynmea2.types.talker.GLL):
self.GPGLL = nmea_msg
if isinstance(nmea_msg, pynmea2.types.talker.GSV):
self.GPGSV = nmea_msg
if isinstance(nmea_msg, pynmea2.types.talker.GSA):
self.GPGSA = nmea_msg
if isinstance(nmea_msg, pynmea2.types.talker.HDT):
self.GPHDT = nmea_msg
self.heading = nmea_msg.heading
if isinstance(nmea_msg, pynmea2.types.talker.HDG):
self.GPHDG = nmea_msg
self.nmea_sentences.append(msg.strip())
except pynmea2.nmea.ParseError as pe:
logging.debug("Bad NMEA String")
except Exception as e:
logging.debug("Error decoding NMEA msg", e)
def encode(self):
"""
Encode the data into RTB format.
:return:
"""
result = []
# Combine all the NMEA strings into one long string
str_nmea = ""
for nmea in self.nmea_sentences:
str_nmea += nmea + "\n"
# Generate the number of elements from the number of characters
self.num_elements = len(str_nmea)
# Generate header
result += Ensemble.generate_header(self.ds_type,
self.num_elements,
self.element_multiplier,
self.image,
self.name_len,
self.Name)
# Convert the strings to bytes
result += str_nmea.encode("UTF-8")
return result
def encode_csv(self, dt, ss_code, ss_config, blank=0, bin_size=0):
"""
Encode into CSV format.
:param dt: Datetime object.
:param ss_code: Subsystem code.
:param ss_config: Subsystem Configuration
:param blank: Blank or first bin position in meters.
:param bin_size: Bin size in meters.
:return: List of CSV lines.
"""
str_result = []
# Create the CSV strings for each NMEA string
for nmea in self.nmea_sentences:
str_result.append(Ensemble.gen_csv_line(dt, Ensemble.CSV_NMEA, ss_code, ss_config, 0, 0, blank, bin_size, nmea))
return str_result
def get_new_position(self, distance: float, bearing: float):
"""
This function is typically used to create a ship track plot with a vector to represent the
water current. The distance will be the magnitude of the water currents, the bearing will be the
direction of the water currents. This will allow you to plot the LatLon and also a vector off this
LatLon point.
:param distance: Distance (magnitude)
:param bearing: Direction to travel
:return The new position based on the input and current position. (lat, lon)
"""
return NmeaData.get_new_lat_lon_position(self.latitude, self.longitude, distance, bearing)
@staticmethod
def get_new_lat_lon_position(latitude: float, longitude: float, distance: float, bearing: float):
"""
This function is typically used to create a ship track plot with a vector to represent the
water current. The distance will be the magnitude of the water currents, the bearing will be the
direction of the water currents. This will allow you to plot the LatLon and also a vector off this
LatLon point.
:param latitude: Start latitude position
:param longitude: Start longitude position
:param distance: Distance (magnitude)
:param bearing: Direction to travel
:return The new position based on the input and current position. (lat, lon)
"""
# Choose a ellipsoid
LatLon = ellipsoidalVincenty.LatLon
# Verify we have a latitude and longitude value
if latitude and longitude:
# Set the current location
curr_loc = LatLon(latitude, longitude)
# Get the new position based on distance and bearing
new_loc = curr_loc.destination(distance=distance, bearing=bearing)
# Return lat, lon
return new_loc.lat, new_loc.lon
return 0.0, 0.0
|
[
"rcastelo@rowetechinc.com"
] |
rcastelo@rowetechinc.com
|
657b51d419bef4689b2a3a559a1039f993d7a58b
|
db5684eeac1c7359017a5d109028ce2b8b49d1a7
|
/app_rbac/service/AutoFindUrls.py
|
fbad0d42e31869cebeef14f5a4056828e68f6a7c
|
[] |
no_license
|
Alan-AW/CrmSys
|
a4873c52e1f6bb05c45377459b0a040ff7dbbc75
|
95119dd7b96b981a00541e8adcee410eb1fbe865
|
refs/heads/main
| 2023-08-22T08:04:44.207347
| 2021-10-13T08:08:44
| 2021-10-13T08:08:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,541
|
py
|
from collections import OrderedDict
from django.conf import settings as sys
from django.utils.module_loading import import_string # 内置工具,根据字符串进行导入模块
from django.urls import URLResolver, URLPattern
import re
"""
自动发现项目中的url方法
"""
class AutoFindUrl:
def check_url_exclude(self, url):
"""
白名单设置;排除一些特定的url的查找
:param url:
:return:
"""
for regex in sys.AUTO_DISCOVER_EXCLUDE:
if re.match(regex, url):
return True
def recursion_urls(self, pre_namespace, pre_url, url_patterns, url_ordered_dict):
"""
:param pre_namespace: namespace的前缀, 以后用于拼接name
:param pre_url: url的前缀, 以后用于拼接url
:param url_patterns: 用于循环的路由, 路由关系列表
:param url_ordered_dict: 用于保存递归中获取的所有路由,有序字典
:return:
"""
for item in url_patterns:
if isinstance(item, URLPattern): # 非路由分发
if not item.name:
continue
name = item.name if not pre_namespace else "%s:%s" % (pre_namespace, item.name)
url = pre_url + item.pattern.regex.pattern
url = url.replace('^', '').replace('$', '')
if self.check_url_exclude(url):
continue
url_ordered_dict[name] = {'name': name, 'url': url}
elif isinstance(item, URLResolver): # 路由分发, 递归
if pre_namespace:
namespace = "%s:%s" % (pre_namespace, item.namespace) if item.namespace else item.namespace
else:
namespace = item.namespace if item.namespace else None
self.recursion_urls(namespace, pre_url + item.pattern.regex.pattern, item.url_patterns, url_ordered_dict)
def get_all_url_dict(self):
"""
自动发现项目中的URL(必须有 name 别名)
:return: 所有url的有序字典
"""
url_ordered_dict = OrderedDict() # {'rbac:menu_list': {name:'rbac:menu_list', url: 'xxx/xxx/menu_list'}}
md = import_string(sys.ROOT_URLCONF) # 根据字符串的形式去导入一个模块,在settings中 ROOT_URLCONF 指向的就是项目根路由的文件地址
self.recursion_urls(None, '/', md.urlpatterns, url_ordered_dict) # 递归的获取所有的url
return url_ordered_dict
|
[
"xcdh560@foxmail.com"
] |
xcdh560@foxmail.com
|
9a2222854f5cf34881162cdee222723b8dd7793d
|
c8c855a6ebb3b3101e5c3a80b94514c36b103495
|
/semana_3/Calculadora.py
|
677552a81732c0ddcb86782beae94726fe52561a
|
[] |
no_license
|
K-A-R-L-A-Robles/poo-1719110219
|
835965c0e3100c9d6770678eb67920945942fa80
|
7d1fc57cd4157e5b52a153210311821d8290144d
|
refs/heads/master
| 2022-11-03T04:54:42.675869
| 2020-06-15T03:46:42
| 2020-06-15T03:46:42
| 265,970,361
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 812
|
py
|
class calculadora:
"atríbutos"
signos=30
botones =30
baterias= 2
led=1
carcasa=1
#métodos
def encender(self):
print("encender")
def apagar(self):
print("apagar")
def __init__(self):
pass
class casio(calculadora):
#atríbutos
color="gris"
longitud= "15cm"
#métodos
def sumar(self):
print("sumar")
def restar(self):
print("restar")
def __init__(self):
print("constructor de casio")
pass
casio= casio()
print("signos= "+str(casio.signos))
print("botones= "+str(casio.botones))
print("baterias= "+str(casio.baterias))
print("led= "+str(casio.led))
("carcasa= "+str(casio.carcasa))
print("color= "+str(casio.color))
print("longitud= "+str(casio.longitud))
casio.encender()
casio.apagar()
casio.sumar()
casio.restar()
|
[
"replituser@example.com"
] |
replituser@example.com
|
010d835db31f6a76e42a04916bd4a4af607762b4
|
62e58c051128baef9452e7e0eb0b5a83367add26
|
/edifact/D08B/COMDISD08BUN.py
|
100dbc7a1d02e66ba3a3780d0077c6f131fd407a
|
[] |
no_license
|
dougvanhorn/bots-grammars
|
2eb6c0a6b5231c14a6faf194b932aa614809076c
|
09db18d9d9bd9d92cefbf00f1c0de1c590fe3d0d
|
refs/heads/master
| 2021-05-16T12:55:58.022904
| 2019-05-17T15:22:23
| 2019-05-17T15:22:23
| 105,274,633
| 0
| 0
| null | 2017-09-29T13:21:21
| 2017-09-29T13:21:21
| null |
UTF-8
|
Python
| false
| false
| 1,035
|
py
|
#Generated by bots open source edi translator from UN-docs.
from bots.botsconfig import *
from edifact import syntax
from recordsD08BUN import recorddefs
structure = [
{ID: 'UNH', MIN: 1, MAX: 1, LEVEL: [
{ID: 'BGM', MIN: 1, MAX: 1},
{ID: 'RFF', MIN: 0, MAX: 9},
{ID: 'DTM', MIN: 0, MAX: 9},
{ID: 'CUX', MIN: 0, MAX: 9},
{ID: 'NAD', MIN: 0, MAX: 99, LEVEL: [
{ID: 'CTA', MIN: 0, MAX: 1},
{ID: 'COM', MIN: 0, MAX: 5},
]},
{ID: 'DOC', MIN: 0, MAX: 9999, LEVEL: [
{ID: 'DTM', MIN: 0, MAX: 9},
{ID: 'MOA', MIN: 0, MAX: 2},
{ID: 'AJT', MIN: 0, MAX: 9, LEVEL: [
{ID: 'FTX', MIN: 0, MAX: 9},
]},
{ID: 'INP', MIN: 0, MAX: 9, LEVEL: [
{ID: 'FTX', MIN: 0, MAX: 9},
]},
{ID: 'DLI', MIN: 0, MAX: 9999, LEVEL: [
{ID: 'MOA', MIN: 0, MAX: 2},
{ID: 'AJT', MIN: 0, MAX: 9, LEVEL: [
{ID: 'FTX', MIN: 0, MAX: 9},
]},
]},
]},
{ID: 'UNT', MIN: 1, MAX: 1},
]},
]
|
[
"jason.capriotti@gmail.com"
] |
jason.capriotti@gmail.com
|
dc83a61491aaa7474ca75f5417cccf54a741e2a2
|
1f7d287ef90041e20468513a26a39e1f3d221289
|
/Level-2/s18/guvi-L2-s18-py06.py
|
21f5db26fcc71bb3aa20c4faae14685578b46595
|
[] |
no_license
|
ksthacker/python
|
d787d69f954c0e9b59b0cc96a8b8fc5c0594d8a0
|
3a3775e1b9349e313f8c96ea11eade54a7e9bf54
|
refs/heads/master
| 2021-04-27T16:32:40.923316
| 2019-08-21T04:50:22
| 2019-08-21T04:50:22
| 122,303,461
| 0
| 17
| null | 2019-10-03T14:59:51
| 2018-02-21T07:09:32
|
Python
|
UTF-8
|
Python
| false
| false
| 262
|
py
|
import sys, string, math
s1,s2 = input().split()
dic1 = {}
dic2 = {}
for c in s1 :
dic1[c] = dic1.get(c,0) + 1
for c in s2 :
dic2[c] = dic2.get(c,0) + 1
#print(dic1,dic2)
if dic1.keys() == dic2.keys() :
print('true')
else :
print('false')
|
[
"noreply@github.com"
] |
ksthacker.noreply@github.com
|
9deb933676e6f8022a6d68c76123cb045891c191
|
672d535e7586289873fd5167bd9888383aff02e4
|
/src/chapter_10/file_writer.py
|
05d3024a8efc186caf79a788cbcce915c16e552a
|
[] |
no_license
|
CatchTheDog/python_crash_course
|
889fd151323e48dfbc6754b86132aad3f1d37856
|
148eda5eb96c501060115aad0bfd6e15ccd04c37
|
refs/heads/master
| 2020-03-29T22:06:32.015096
| 2018-09-29T02:36:51
| 2018-09-29T02:36:51
| 150,402,932
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 168
|
py
|
file_name = "..\\test_files\\programming.txt"
with open(file_name,'a') as file_object:
file_object.write("I love programming!\n")
file_object.write("Yes,you are!\n")
|
[
"1924528451@qq.com"
] |
1924528451@qq.com
|
d6938327087879a9f4238e51bda9ed19d1500dd6
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03261/s340412788.py
|
5a6e7ab12a4f437b7b0e143245721a1a5d7f2d38
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 272
|
py
|
def resolve():
N = int(input())
W = [input() for _ in range(N)]
if len(set(W)) != N:
print('No')
return
for i in range(N-1):
if W[i][-1] != W[i+1][0]:
print('No')
return
print('Yes')
return
resolve()
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
13fb7bd55c6b4c3bcf6151f1231cd06bed96325b
|
ff6248be9573caec94bea0fa2b1e4b6bf0aa682b
|
/StudentProblem/10.21.12.20/5/1569572839.py
|
b804973202990b201d8fa526eab461fdb643c04b
|
[] |
no_license
|
LennartElbe/codeEvo
|
0e41b1a7705204e934ef71a5a28c047366c10f71
|
e89b329bc9edd37d5d9986f07ca8a63d50686882
|
refs/heads/master
| 2020-12-21T17:28:25.150352
| 2020-03-26T10:22:35
| 2020-03-26T10:22:35
| 236,498,032
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 285
|
py
|
import functools
import typing
import string
import random
import pytest
## Lösung Teil 1.
def mysum(zs : list) -> int:
return sum(xs)
## Lösung Teil 2. (Tests)
def test_2():
assert mysum([1,2,3]) == 6
######################################################################
|
[
"lenni.elbe@gmail.com"
] |
lenni.elbe@gmail.com
|
7bb0b9509db055c53732ac141dd5e0394c6ef70b
|
2c3f13857d4a915410de5ac9547745eb2769db5f
|
/eval/e43/compare_text.py
|
87358093ffb7d43d225e9232d6c758060c29fa51
|
[] |
no_license
|
andrewhead/StackSkim
|
43a4cf769645bb70202075f8077fa4d5d7be2a4b
|
9ac11705ff82aa978d1a87177059e665f4e5ebef
|
refs/heads/master
| 2020-06-03T16:15:15.127268
| 2016-01-16T17:16:36
| 2016-01-16T17:16:36
| 50,692,945
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,056
|
py
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
import codecs
logging.basicConfig(level=logging.INFO, format="%(message)s")
def main():
with codecs.open('javascript_text.txt', 'r', 'utf-8') as js_file:
with codecs.open('beautifulsoup_text.txt', 'r', 'utf-8') as bs_file:
js_text = js_file.read()
bs_text = bs_file.read()
for i in range(min([len(js_text), len(bs_text)])):
if js_text[i] != bs_text[i]:
print "==== Mismatch at index ====", i
print "Javascript: ", repr(js_text[i])
print "BeautifulSoup: ", repr(bs_text[i])
print "* Javascript before: "
print repr(js_text[i-50:i])
print "* BeautifulSoup before: "
print repr(bs_text[i-50:i])
print "* Javascript after: "
print repr(js_text[i:i+50])
print "* BeautifulSoup after: "
print repr(bs_text[i:i+50])
break
if __name__ == '__main__':
main()
|
[
"head.andrewm@gmail.com"
] |
head.andrewm@gmail.com
|
0516724e956d3a03c966ac81dd33f50bb9a93f14
|
f019ca1e4029b4077472087d1b677052583c0392
|
/qa/rpc-tests/keypool.py
|
aeaa4435c0d9ce9ede5ce333dced5cf31e78ffc9
|
[
"MIT"
] |
permissive
|
mirzaei-ce/core-civilbit
|
9204dd9c4c3ce04f867105da4e7fa9a56af1f8ba
|
cab3e53bdc6b04a84f4bc48114efc07865be814a
|
refs/heads/master
| 2021-04-26T05:03:32.282526
| 2017-10-16T15:39:44
| 2017-10-16T15:39:44
| 107,148,188
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,338
|
py
|
#!/usr/bin/env python2
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Exercise the wallet keypool, and interaction with wallet encryption/locking
# Add python-civilbitrpc to module search path:
from test_framework.test_framework import CivilbitTestFramework
from test_framework.util import *
def check_array_result(object_array, to_match, expected):
"""
Pass in array of JSON objects, a dictionary with key/value pairs
to match against, and another dictionary with expected key/value
pairs.
"""
num_matched = 0
for item in object_array:
all_match = True
for key,value in to_match.items():
if item[key] != value:
all_match = False
if not all_match:
continue
for key,value in expected.items():
if item[key] != value:
raise AssertionError("%s : expected %s=%s"%(str(item), str(key), str(value)))
num_matched = num_matched+1
if num_matched == 0:
raise AssertionError("No objects matched %s"%(str(to_match)))
class KeyPoolTest(CivilbitTestFramework):
def run_test(self):
nodes = self.nodes
# Encrypt wallet and wait to terminate
nodes[0].encryptwallet('test')
civilbitd_processes[0].wait()
# Restart node 0
nodes[0] = start_node(0, self.options.tmpdir)
# Keep creating keys
addr = nodes[0].getnewaddress()
try:
addr = nodes[0].getnewaddress()
raise AssertionError('Keypool should be exhausted after one address')
except JSONRPCException,e:
assert(e.error['code']==-12)
# put three new keys in the keypool
nodes[0].walletpassphrase('test', 12000)
nodes[0].keypoolrefill(3)
nodes[0].walletlock()
# drain the keys
addr = set()
addr.add(nodes[0].getrawchangeaddress())
addr.add(nodes[0].getrawchangeaddress())
addr.add(nodes[0].getrawchangeaddress())
addr.add(nodes[0].getrawchangeaddress())
# assert that four unique addresses were returned
assert(len(addr) == 4)
# the next one should fail
try:
addr = nodes[0].getrawchangeaddress()
raise AssertionError('Keypool should be exhausted after three addresses')
except JSONRPCException,e:
assert(e.error['code']==-12)
# refill keypool with three new addresses
nodes[0].walletpassphrase('test', 12000)
nodes[0].keypoolrefill(3)
nodes[0].walletlock()
# drain them by mining
nodes[0].generate(1)
nodes[0].generate(1)
nodes[0].generate(1)
nodes[0].generate(1)
try:
nodes[0].generate(1)
raise AssertionError('Keypool should be exhausted after three addesses')
except JSONRPCException,e:
assert(e.error['code']==-12)
def setup_chain(self):
print("Initializing test directory "+self.options.tmpdir)
initialize_chain(self.options.tmpdir)
def setup_network(self):
self.nodes = start_nodes(1, self.options.tmpdir)
if __name__ == '__main__':
KeyPoolTest().main()
|
[
"mirzaei@ce.sharif.edu"
] |
mirzaei@ce.sharif.edu
|
e842a0b0122230b18a59c01e0b2b0561a33e8a9a
|
6a33cb94d4af1d8a7329ddc6c9d42f870c35bb2f
|
/python/euler24.py
|
f4dfa43b28627a2b567d1d09688bcc6fd94d3b85
|
[] |
no_license
|
vochong/project-euler
|
836321cc8e7d2e7cdf22b3b136d44dcba74a8701
|
6a0c7103861ff825bf84800b6e2e62819a41e36d
|
refs/heads/master
| 2020-04-29T10:41:48.487159
| 2018-09-19T00:13:34
| 2018-09-19T00:13:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 602
|
py
|
from itertools import permutations
def euler24():
"""
A permutation is an ordered arrangement of objects. For example, 3124 is
one possible permutation of the digits 1, 2, 3 and 4. If all of the
permutations are listed numerically or alphabetically, we call it
lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3,
4, 5, 6, 7, 8 and 9?
"""
perms = [''.join(p) for p in permutations("0123456789")]
return perms[999999]
if __name__ == "__main__":
print euler24()
|
[
"kueltz.anton@gmail.com"
] |
kueltz.anton@gmail.com
|
eaa9e3662e78f9f1fb39c52cf1e2e525f22310eb
|
a169199ebb9f4a7b81cd00ff23af50aeb591ffe4
|
/clpy/types/mutabledict.py
|
8b4c40a0ef9fc6e1b78077e8aad89ceb47cf9954
|
[] |
no_license
|
zielmicha/clojure-pypy
|
b2eab9437997e4c250d455b3a6d5f4c036855cdf
|
41c8f14a19173c1b5452bcdb1f7f6df23e6cdecf
|
refs/heads/master
| 2021-01-23T12:18:45.583076
| 2014-02-21T19:22:30
| 2014-02-21T19:22:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 723
|
py
|
from clpy.types.root import Root
from clpy.types.dict import PersistentHashTrie
class MutableDict(Root):
'''
Mutable dictionary that should be based on PyPy's implementation,
but I can't get it accepted by translator.
So, for now, it's based on persistent hash trie.
'''
def __init__(self, space):
self.container = PersistentHashTrie(space)
def repr(self):
return 'MutableDict{%s}' % ', '.join([
'%s: %s' % (k.repr(), self.container.get_item(k).repr())
for k in self.container.keys() ])
def set_item(self, key, val):
self.container = self.container.assoc(key, val)
def get_item(self, key):
return self.container.get_item(key)
|
[
"michal@zielinscy.org.pl"
] |
michal@zielinscy.org.pl
|
34d3bd0138a6b1ff374de550600bd1e994e01e20
|
15fb62305a2fa0146cc84b289642cc01a8407aab
|
/Python/230-KthSmallestElementInBST.py
|
e1fce7116f90027161bad3e1f527125aaa0290c7
|
[] |
no_license
|
geniousisme/leetCode
|
ec9bc91864cbe7520b085bdab0db67539d3627bd
|
6e12d67e4ab2d197d588b65c1ddb1f9c52a7e047
|
refs/heads/master
| 2016-09-09T23:34:03.522079
| 2015-09-23T16:15:05
| 2015-09-23T16:15:05
| 32,052,408
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,342
|
py
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param {TreeNode} root
# @param {integer} k
# @return {integer}
def recurKthSmallest(self, root, k):
res = []
self.inorderTraversal(root.left, res)
return res[k - 1]
def inorderTraversal(self, root, res):
if root:
self.inorderTraversal(root.left, res)
res.append(root.val)
self.inorderTraversal(root.right, res)
return
def kthSmallest(self, root, k):
stack = []
node = root
while node:
stack.append(node)
node = node.left
count = 1
while stack and count <= k:
node = stack.pop()
count += 1
right = node.right
while right:
stack.append(right)
right = right.left
return node.val
if __name__ == '__main__':
s = Solution()
test = TreeNode(4)
test.left = TreeNode(2)
test.right = TreeNode(6)
test.left.left = TreeNode(1)
test.left.right = TreeNode(3)
test.right.left = TreeNode(5)
test.right.right = TreeNode(7)
# print s.countTreeNum(test)
s.kthSmallest(test, 1)
|
[
"chia-hao.hsu@aiesec.net"
] |
chia-hao.hsu@aiesec.net
|
755d6aaeee71030185d492833dfef66356bbd803
|
d293b1b5037f7e493eddbe8572cc03ffd9f78890
|
/code/sort.py
|
574a24cd3b45ffb3a643147fc331bc61787fd95d
|
[] |
no_license
|
weilaidb/pyqt5
|
49f587e6ec3b74f6b27f070cd007a6946a26820a
|
0ad65ed435ecfc87ca32e392bbf67973b4b13e68
|
refs/heads/master
| 2020-03-07T23:04:51.365624
| 2018-08-01T15:30:44
| 2018-08-01T15:30:44
| 127,771,719
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 316
|
py
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
print(sorted([36, 5, -12, 9, -21]))
print(sorted([36, 5, -12, 9, -21], key=abs))
print(sorted(['bob', 'about', 'Zoo', 'Credit']))
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower))
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True))
|
[
"wxjlmr@126.com"
] |
wxjlmr@126.com
|
d49d9eb6c8717ccde8a3a9fb5629628f7f989129
|
ecf0d106831b9e08578845674a457a166b6e0a14
|
/OOP/inheritance_EXERCISE/players_and_monsters/project/blade_knight.py
|
f3fe7f02553cff2f5de2b7045840784a828df529
|
[] |
no_license
|
ivo-bass/SoftUni-Solutions
|
015dad72cff917bb74caeeed5e23b4c5fdeeca75
|
75612d4bdb6f41b749e88f8d9c512d0e00712011
|
refs/heads/master
| 2023-05-09T23:21:40.922503
| 2021-05-27T19:42:03
| 2021-05-27T19:42:03
| 311,329,921
| 8
| 5
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 169
|
py
|
from project.dark_knight import DarkKnight
class BladeKnight(DarkKnight):
def __init__(self, username: str, level: int):
super().__init__(username, level)
|
[
"ivailo.ignatoff@gmail.com"
] |
ivailo.ignatoff@gmail.com
|
d86ebf62cfba1698923c1901510e7e9f1be2816c
|
955b968d46b4c436be55daf8aa1b8fc8fe402610
|
/other/get_timezone.py
|
d32feb2a1fb16ad7235d22228884263287fa7712
|
[] |
no_license
|
han-huang/python_selenium
|
1c8159fd1421b1f0e87cb0df20ae4fe82450f879
|
56f9f5e5687cf533c678a1c12e1ecaa4c50a7795
|
refs/heads/master
| 2020-03-09T02:24:48.882279
| 2018-04-07T15:06:18
| 2018-04-07T15:06:18
| 128,535,917
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,387
|
py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from time import gmtime, strftime, localtime
import locale, time, sys
# Windows 10 platform
tz1 = strftime("%z", gmtime())
print('gmtime()', gmtime())
print(tz1) # +0800
tz2 = strftime("%z", localtime())
print('localtime()', localtime())
print(tz2) # +0800
print()
tz3 = strftime("%Z", localtime())
print(tz3)
# https://segmentfault.com/a/1190000007598639
# 當在shell裡啟動python repl(交互器)時,默認的環境local設置為'C', 也就是沒有當地語系化設置,
# 這時候可以通過 locale.getdefaultlocale() 來查看shell當前環境的locale設置, 並通過 locale.setlocale(locale.LC_ALL, '')
# 將python解譯器的locale設置成shell環境的locale
print('locale.getlocale()', locale.getlocale())
print('locale.getdefaultlocale()', locale.getdefaultlocale())
locale.setlocale(locale.LC_ALL, '')
print('locale.getlocale()', locale.getlocale())
tz4 = strftime("%Z", localtime())
print(tz4) # 台北標準時間
print()
# http://bbs.fishc.com/thread-76584-1-1.html
# >>> [bytes([ord(c) for c in s]).decode('gbk') for s in time.tzname ]
# ['中国标准时间', '中国标准时间']
tz5 = time.tzname
print(tz5)
tz6 = [bytes([ord(c) for c in s]).decode('big5') for s in time.tzname]
print(tz6) # ['台北標準時間', '台北日光節約時間']
print()
print('sys.stdout.encoding', sys.stdout.encoding) # sys.stdout.encoding utf-8
print('sys.getdefaultencoding()', sys.getdefaultencoding()) # sys.stdout.encoding utf-8
print()
# https://docs.python.org/3/library/functions.html#ord
# ord(c)
# Given a string representing one Unicode character, return an integer representing the Unicode code point of that character.
# For example, ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().
print(ord('a')) # 97
print(chr(97)) # a
print()
print(ord('€')) # 8364
print(chr(8364)) # €
print()
# https://r12a.github.io/app-conversion/
print(ord('\u6642')) # 26178
print(ord('時')) # 26178
print(chr(26178)) # 時
data_utf8 = b'\xE6\x99\x82' # https://r12a.github.io/app-conversion/ 時 UTF-8 code units E6 99 82
print("data_utf8.decode('utf_8')",data_utf8.decode('utf_8')) # data_utf8.decode('utf_8') 時
print("data_utf8.decode('utf_8').encode('utf_8')",data_utf8.decode('utf_8').encode('utf_8')) # data_utf8.decode('utf_8').encode('utf_8') b'\xe6\x99\x82'
|
[
"vagrant@LaravelDemoSite"
] |
vagrant@LaravelDemoSite
|
61144733a7ba970967c47e9af7a46cadf1f7c2db
|
3be8b5d0334de1f3521dd5dfd8a58704fb8347f9
|
/create_session_index.py
|
dc01fc1ffa77f8416331b23701799095cea70a20
|
[
"MIT"
] |
permissive
|
bmillham/djrq2
|
21a8cbc3087d7ad46087cd816892883cd276db7d
|
5f357b3951600a9aecbe6c50727891b1485df210
|
refs/heads/master
| 2023-07-07T01:07:35.093669
| 2023-06-26T05:21:33
| 2023-06-26T05:21:33
| 72,969,773
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 239
|
py
|
""" Run this one time, to setup the automatic expiration of sessions """
from web.app.djrq.model.session import Session
from pymongo import MongoClient
collection = MongoClient().djrq2.sessions
Session._expires.create_index(collection)
|
[
"bmillham@gmail.com"
] |
bmillham@gmail.com
|
0f5084fe7deefe3d514592c7c60d72832e33f11f
|
066612a390af03bb170d74a21b0fb0b7bcbfe524
|
/tests/testcases.py
|
12602c0da2e5760fc9d92fd91d9c22da1a2732ca
|
[
"MIT"
] |
permissive
|
kikeh/django-graphql-extensions
|
873577cc9e0085630889fea9fa5539962c31dbcc
|
951b295235ca68270066cc70148e2ae937d4eb56
|
refs/heads/master
| 2020-12-26T05:23:12.039826
| 2020-01-31T09:41:43
| 2020-01-31T09:41:43
| 237,398,866
| 0
| 0
|
MIT
| 2020-01-31T09:32:25
| 2020-01-31T09:32:24
| null |
UTF-8
|
Python
| false
| false
| 685
|
py
|
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.test import testcases
from graphql_extensions import testcases as extensions_testcases
from . import schema
class TestCase(testcases.TestCase):
def setUp(self):
self.group = Group.objects.create(name='flavors')
self.user = get_user_model().objects.create_user(
username='test',
password='dolphins')
class SchemaTestCase(TestCase, extensions_testcases.SchemaTestCase):
Query = schema.Query
Mutations = None
def setUp(self):
super().setUp()
self.client.schema(query=self.Query, mutation=self.Mutations)
|
[
"domake.io@gmail.com"
] |
domake.io@gmail.com
|
273fd9f145e716e3be92436742505363a1f97b3e
|
a6e812e138640e63ccf25bc795d08cea584031e8
|
/Codeforces/381/A.py
|
a56be37e923308335c6c7e716b4f91442338b30a
|
[] |
no_license
|
abhigupta4/Competitive-Coding
|
b80de4cb5d5cf0cf14266b2d05f9434348f51a9e
|
5ec0209f62a7ee38cb394d1a00dc8f2582ff09be
|
refs/heads/master
| 2021-01-17T06:54:12.707692
| 2020-12-10T18:00:17
| 2020-12-10T18:00:17
| 49,972,984
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 189
|
py
|
def ii():
return map(int,raw_input().split())
n,a,b,c = ii()
if n%4 == 0:
print 0
elif n%4 == 1:
print min(c,3*a,b+a)
elif n%4 == 2:
print min(2*a,b,2*c)
else:
print min(a,b+c,3*c)
|
[
"abhinavgupta6245@gmail.com"
] |
abhinavgupta6245@gmail.com
|
9bb1fba15b061678ffcff2219bc7888f2a3681bd
|
963a49b8a48764929169edb57e492b5021331c87
|
/tests/volume_system_test.py
|
5d4b9236f96e02ee546f514160efbb9699654d30
|
[
"MIT"
] |
permissive
|
ralphje/imagemounter
|
d0e73b72fe354c23607361db26906e1976b5d8ee
|
383b30b17fe24df64ccef071ffb5443abf203368
|
refs/heads/master
| 2023-02-22T14:27:54.279724
| 2022-04-04T15:08:56
| 2022-04-04T15:08:56
| 16,476,185
| 98
| 51
|
MIT
| 2023-02-09T10:49:23
| 2014-02-03T10:27:32
|
Python
|
UTF-8
|
Python
| false
| false
| 869
|
py
|
import sys
from imagemounter._util import check_output_
from imagemounter.disk import Disk
from imagemounter.parser import ImageParser
class TestParted:
def test_parted_requests_input(self, mocker):
check_output = mocker.patch("imagemounter.volume_system._util.check_output_")
def modified_command(cmd, *args, **kwargs):
if cmd[0] == 'parted':
# A command that requests user input
return check_output_([sys.executable, "-c", "exec(\"try: input('>> ')\\nexcept: pass\")"],
*args, **kwargs)
return mocker.DEFAULT
check_output.side_effect = modified_command
disk = Disk(ImageParser(), path="...")
list(disk.volumes.detect_volumes(method='parted'))
check_output.assert_called()
# TODO: kill process when test fails
|
[
"ralph@ralphbroenink.net"
] |
ralph@ralphbroenink.net
|
e77a593197bf45d0a7c18466dd8753c90f6313e4
|
6e701e3cff75a12a6f7f591fab440e62c2ecb198
|
/bookmarks/settings/base.py
|
1e1ddc46ec07903323915f87ddcaa7b1e3b5622a
|
[] |
no_license
|
WellingtonIdeao/d3ex_bookmarks
|
10350f54c396881bc9e81b96cb86d3f6d74c8b34
|
52c1a5493202dc415f00c4d63b64e9533ac1845d
|
refs/heads/main
| 2023-06-07T02:40:34.806602
| 2021-07-06T00:30:28
| 2021-07-06T00:30:28
| 381,181,357
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,172
|
py
|
"""
Django settings for bookmarks project.
Generated by 'django-admin startproject' using Django 3.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os.path
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent.parent
# Application definition
INSTALLED_APPS = [
'account.apps.AccountConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'social_django',
'images.apps.ImagesConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'bookmarks.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'bookmarks.wsgi.application'
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'pt-br'
TIME_ZONE = 'America/Recife'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LOGIN_URL = 'account:login'
LOGIN_REDIRECT_URL = 'account:dashboard'
LOGOUT_URL = 'account:logout'
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'account.authentication.EmailAuthBackend',
'social_core.backends.facebook.FacebookOAuth2',
]
|
[
"wellington.ideao@gmail.com"
] |
wellington.ideao@gmail.com
|
5eacb8622f507ddfb3d83ff89f5001b3f5fa21e3
|
634367d6a94d9bce231a8c29cf9713ebfc4b1de7
|
/covid_dashboard/views/get_district_stats_on_given_date/api_wrapper.py
|
83bfdd8ad95f836f4c9f6a6c05a99e3b45ee01c2
|
[] |
no_license
|
saikiranravupalli/covid_dashboard
|
5a48c97597983ada36a3bf131edf5ca15f1dedec
|
954dd02819fb8f6776fa2828e8971bd55efa657c
|
refs/heads/master
| 2022-11-08T10:11:27.836507
| 2020-06-30T09:00:27
| 2020-06-30T09:00:27
| 269,610,409
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,399
|
py
|
import json
from django.http import HttpResponse
from django_swagger_utils.drf_server.utils.decorator.interface_decorator \
import validate_decorator
from .validator_class import ValidatorClass
from covid_dashboard.interactors\
.get_day_wise_district_details_on_given_date_interactor import \
DistrictStatisticsInteractor
from covid_dashboard.storages.district_storage_implementation import \
DistrictStorageImplementation
from covid_dashboard.storages.mandal_storage_implementation import \
MandalStorageImplementation
from covid_dashboard.presenters.presenter_implementation import \
PresenterImplementation
@validate_decorator(validator_class=ValidatorClass)
def api_wrapper(*args, **kwargs):
district_id = kwargs['district_id']
request_data = kwargs['request_data']
for_date = request_data['for_date']
district_storage = DistrictStorageImplementation()
mandal_storage = MandalStorageImplementation()
presenter = PresenterImplementation()
interactor = DistrictStatisticsInteractor(
district_storage=district_storage,
mandal_storage=mandal_storage,
presenter=presenter
)
response = \
interactor.get_district_statistics_on_given_date(
district_id=district_id,
for_date=for_date
)
json_data = json.dumps(response)
return HttpResponse(json_data, status=200)
|
[
"saikiranravupalli@gmail.com"
] |
saikiranravupalli@gmail.com
|
6e9393d3d17cfc7054199e6f3782dfc6383250df
|
11052dcb2ee70b601c521ba40685fd8e03c86a45
|
/apps/oinkerprofile/models.py
|
3fcf6b96b867f697ad2cba296ea083b482cb2fd7
|
[] |
no_license
|
naistangz/twitter-clone
|
53757959de8f3f063cd1fbbc9bc72c024beee22f
|
56f44610a729cd040857786f481c8b7f94397a3d
|
refs/heads/master
| 2023-04-13T14:16:44.357440
| 2021-04-25T08:18:42
| 2021-04-25T08:18:42
| 354,792,080
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 474
|
py
|
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
class OinkerProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
follows = models.ManyToManyField(
'self', related_name='followed_by', symmetrical=False)
avatar = models.ImageField(upload_to='uploads/', blank=True, null=True)
User.oinkerprofile = property(
lambda u: OinkerProfile.objects.get_or_create(user=u)[0])
|
[
"a6anaistang@hotmail.co.uk"
] |
a6anaistang@hotmail.co.uk
|
1d0c5a63ebb091013f41650238f7244a2189d919
|
a9243f735f6bb113b18aa939898a97725c358a6d
|
/0.15/_downloads/plot_time_frequency_erds.py
|
ade2c6289d640ea78caded44665a8d296b989398
|
[] |
permissive
|
massich/mne-tools.github.io
|
9eaf5edccb4c35831400b03278bb8c2321774ef2
|
95650593ba0eca4ff8257ebcbdf05731038d8d4e
|
refs/heads/master
| 2020-04-07T08:55:46.850530
| 2019-09-24T12:26:02
| 2019-09-24T12:26:02
| 158,233,630
| 0
| 0
|
BSD-3-Clause
| 2018-11-19T14:06:16
| 2018-11-19T14:06:16
| null |
UTF-8
|
Python
| false
| false
| 5,229
|
py
|
"""
===============================
Compute and visualize ERDS maps
===============================
This example calculates and displays ERDS maps of event-related EEG data. ERDS
(sometimes also written as ERD/ERS) is short for event-related
desynchronization (ERD) and event-related synchronization (ERS) [1]_.
Conceptually, ERD corresponds to a decrease in power in a specific frequency
band relative to a baseline. Similarly, ERS corresponds to an increase in
power. An ERDS map is a time/frequency representation of ERD/ERS over a range
of frequencies [2]_. ERDS maps are also known as ERSP (event-related spectral
perturbation) [3]_.
We use a public EEG BCI data set containing two different motor imagery tasks
available at PhysioNet. The two tasks are imagined hand and feet movement. Our
goal is to generate ERDS maps for each of the two tasks.
First, we load the data and create epochs of 5s length. The data sets contain
multiple channels, but we will only consider the three channels C3, Cz, and C4.
We compute maps containing frequencies ranging from 2 to 35Hz. We map ERD to
red color and ERS to blue color, which is the convention in many ERDS
publications. Note that we do not perform any significance tests on the map
values, but instead we display the whole time/frequency maps.
References
----------
.. [1] G. Pfurtscheller, F. H. Lopes da Silva. Event-related EEG/MEG
synchronization and desynchronization: basic principles. Clinical
Neurophysiology 110(11), 1842-1857, 1999.
.. [2] B. Graimann, J. E. Huggins, S. P. Levine, G. Pfurtscheller.
Visualization of significant ERD/ERS patterns in multichannel EEG and
ECoG data. Clinical Neurophysiology 113(1), 43-47, 2002.
.. [3] S. Makeig. Auditory event-related dynamics of the EEG spectrum and
effects of exposure to tones. Electroencephalography and Clinical
Neurophysiology 86(4), 283-293, 1993.
"""
# Authors: Clemens Brunner <clemens.brunner@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import mne
from mne.datasets import eegbci
from mne.io import concatenate_raws, read_raw_edf
from mne.time_frequency import tfr_multitaper
def center_cmap(cmap, vmin, vmax):
"""Center given colormap (ranging from vmin to vmax) at value 0.
Note that eventually this could also be achieved by re-normalizing a given
colormap by subclassing matplotlib.colors.Normalize as described here:
https://matplotlib.org/users/colormapnorms.html#custom-normalization-two-linear-ranges
""" # noqa: E501
vzero = abs(vmin) / (vmax - vmin)
index_old = np.linspace(0, 1, cmap.N)
index_new = np.hstack([np.linspace(0, vzero, cmap.N // 2, endpoint=False),
np.linspace(vzero, 1, cmap.N // 2)])
cdict = {"red": [], "green": [], "blue": [], "alpha": []}
for old, new in zip(index_old, index_new):
r, g, b, a = cmap(old)
cdict["red"].append((new, r, r))
cdict["green"].append((new, g, g))
cdict["blue"].append((new, b, b))
cdict["alpha"].append((new, a, a))
return LinearSegmentedColormap("erds", cdict)
# load and preprocess data ####################################################
subject = 1 # use data from subject 1
runs = [6, 10, 14] # use only hand and feet motor imagery runs
fnames = eegbci.load_data(subject, runs)
raws = [read_raw_edf(f, preload=True, stim_channel='auto') for f in fnames]
raw = concatenate_raws(raws)
raw.rename_channels(lambda x: x.strip('.')) # remove dots from channel names
events = mne.find_events(raw, shortest_event=0, stim_channel='STI 014')
picks = mne.pick_channels(raw.info["ch_names"], ["C3", "Cz", "C4"])
# epoch data ##################################################################
tmin, tmax = -1, 4 # define epochs around events (in s)
event_ids = dict(hands=2, feet=3) # map event IDs to tasks
epochs = mne.Epochs(raw, events, event_ids, tmin - 0.5, tmax + 0.5,
picks=picks, baseline=None, preload=True)
# compute ERDS maps ###########################################################
freqs = np.arange(2, 36, 1) # frequencies from 2-35Hz
n_cycles = freqs # use constant t/f resolution
vmin, vmax = -1, 1.5 # set min and max ERDS values in plot
cmap = center_cmap(plt.cm.RdBu, vmin, vmax) # zero maps to white
for event in event_ids:
power = tfr_multitaper(epochs[event], freqs=freqs, n_cycles=n_cycles,
use_fft=True, return_itc=False, decim=2)
power.crop(tmin, tmax)
fig, ax = plt.subplots(1, 4, figsize=(12, 4),
gridspec_kw={"width_ratios": [10, 10, 10, 1]})
for i in range(3):
power.plot([i], baseline=[-1, 0], mode="percent", vmin=vmin, vmax=vmax,
cmap=(cmap, False), axes=ax[i], colorbar=False, show=False)
ax[i].set_title(epochs.ch_names[i], fontsize=10)
ax[i].axvline(0, linewidth=1, color="black", linestyle=":") # event
if i > 0:
ax[i].set_ylabel("")
ax[i].set_yticklabels("")
fig.colorbar(ax[0].collections[0], cax=ax[-1])
fig.suptitle("ERDS ({})".format(event))
fig.show()
|
[
"larson.eric.d@gmail.com"
] |
larson.eric.d@gmail.com
|
c5dd27af9004567fed4a4c508b43d1acfce35e68
|
8fcae139173f216eba1eaa01fd055e647d13fd4e
|
/.history/scraper_20191220154310.py
|
85e5bdeab8d217043d007104d46a712f7cdf91d4
|
[] |
no_license
|
EnriqueGalindo/backend-web-scraper
|
68fdea5430a0ffb69cc7fb0e0d9bcce525147e53
|
895d032f4528d88d68719838a45dae4078ebcc82
|
refs/heads/master
| 2020-11-27T14:02:59.989697
| 2019-12-21T19:47:34
| 2019-12-21T19:47:34
| 229,475,085
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,308
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module docstring: One line description of what your program does.
There should be a blank line in between description above, and this
more detailed description. In this section you should put any caveats,
environment variable expectations, gotchas, and other notes about running
the program. Author tag (below) helps instructors keep track of who
wrote what, when grading.
"""
__author__ = "Enrique Galindo"
# Imports go at the top of your file, after the module docstring.
# One module per import line. These are for example only.
import sys
import requests
import re
import pprint
from html.parser import HTMLParser
regex_email = r'''(?:[a-z0-9!#$%&‘*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&‘*+/=?^_`{|}~-]+)*|“(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*“)@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])'''
regex_phone = r'''(1?\W*([2-9][0-8][0-9])\W*([2-9][0-9]{2})\W*([0-9]{4})(\se?x?t?(\d*))?)'''
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print( "Encountered a start tag:", tag)
def handle_endtag(self, tag):
print() "Encountered an end tag :", tag
def handle_data(self, data):
print "Encountered some data :", data
def main(args):
"""Main function is declared as standalone, for testability"""
good_phone_list = []
url = args[0]
response = requests.get(url)
response.raise_for_status()
url_list = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', response.text)
email_list = set(re.findall(regex_email, response.text))
bad_phone_list = set(re.findall(regex_phone, response.text))
for number in bad_phone_list:
good_phone_list.append(number[1] + number[2] + number[3])
print(email_list)
pprint.pprint(good_phone_list)
parser = HTMLParser()
link_list = HTMLParser.handle_starttag('a', [('href', 'http://'), ('href', 'https://')])
if __name__ == '__main__':
"""Docstring goes here"""
main(sys.argv[1:])
|
[
"egalindo@protonmail.com"
] |
egalindo@protonmail.com
|
febb96c94ce8da0983d61e5f72ae3c876d19bac4
|
a4e1093cd868cc16cf909b8f7b84832a823a97bf
|
/utils/criterion.py
|
1d10cbdcb99de7980901e1cde9c148fb1d57396b
|
[] |
no_license
|
hermanprawiro/gan-playground
|
8fb7eed54314661d9d1b908fe2cb1695eb1e3881
|
bf4c270ad4696d61df0dbe2afb8c9ebafb9c2ba3
|
refs/heads/master
| 2020-09-06T19:43:22.685332
| 2019-12-24T10:45:12
| 2019-12-24T10:45:12
| 220,529,636
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,740
|
py
|
import torch
import torch.nn as nn
class GANLoss(nn.Module):
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0, target_fake_G_label=1.0):
super().__init__()
self.gan_mode = gan_mode
self.register_buffer('real_label', torch.tensor(target_real_label))
self.register_buffer('fake_label', torch.tensor(target_fake_label))
self.register_buffer('fake_G_label', torch.tensor(target_fake_G_label))
if gan_mode == 'vanilla':
self.loss = nn.BCEWithLogitsLoss()
elif gan_mode == 'lsgan':
self.loss = nn.MSELoss()
elif gan_mode == 'hinge':
self.loss = None
else:
raise NotImplementedError('GAN mode %s is not implemented' % gan_mode)
def _get_target_tensor(self, prediction, is_real, is_generator=False):
if is_real:
target_tensor = self.real_label
elif is_generator:
target_tensor = self.fake_G_label
else:
target_tensor = self.fake_label
return target_tensor.expand_as(prediction)
def forward(self, prediction, is_real, is_generator=False):
if self.gan_mode in ['vanilla', 'lsgan']:
target_tensor = self._get_target_tensor(prediction, is_real, is_generator)
loss = self.loss(prediction, target_tensor)
else:
if is_real:
loss = nn.functional.relu(1. - prediction).mean()
elif is_generator:
loss = - prediction.mean()
else:
loss = nn.functional.relu(1. + prediction).mean()
return loss
class VAELoss(nn.Module):
def __init__(self, recon_mode='l2', beta=1):
super().__init__()
recon_dict = {
'bce': nn.BCELoss(reduction='none'),
'l1': nn.L1Loss(reduction='none'),
'l2': nn.MSELoss(reduction='none'),
'smoothl1': nn.SmoothL1Loss(reduction='none'),
'none': None,
}
if recon_mode not in recon_dict.keys():
raise NotImplementedError('Reconstruction mode %s is not implemented' % recon_mode)
# Normalized beta = beta * latent_dim / input_dim
self.beta = beta
self.recon_criterion = recon_dict[recon_mode]
def forward(self, mu, logvar, recon_x=None, target_x=None):
if self.recon_criterion is not None:
recon_loss = self.recon_criterion(recon_x, target_x).sum((1, 2, 3)).mean()
else:
recon_loss = 0
# KL Divergence => 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)
kld_loss = (-0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp(), 1)).mean()
return recon_loss + self.beta * kld_loss
|
[
"herman.prawiro@gmail.com"
] |
herman.prawiro@gmail.com
|
0f08a7de43e780c241ac24fe25e5d88f5c7bb850
|
a46d135ba8fd7bd40f0b7d7a96c72be446025719
|
/packages/python/plotly/plotly/validators/icicle/outsidetextfont/_family.py
|
9f2822cabc11769355cd3ba0b30e64667849668e
|
[
"MIT"
] |
permissive
|
hugovk/plotly.py
|
5e763fe96f225d964c4fcd1dea79dbefa50b4692
|
cfad7862594b35965c0e000813bd7805e8494a5b
|
refs/heads/master
| 2022-05-10T12:17:38.797994
| 2021-12-21T03:49:19
| 2021-12-21T03:49:19
| 234,146,634
| 0
| 0
|
MIT
| 2020-01-15T18:33:43
| 2020-01-15T18:33:41
| null |
UTF-8
|
Python
| false
| false
| 571
|
py
|
import _plotly_utils.basevalidators
class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self, plotly_name="family", parent_name="icicle.outsidetextfont", **kwargs
):
super(FamilyValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop("array_ok", True),
edit_type=kwargs.pop("edit_type", "plot"),
no_blank=kwargs.pop("no_blank", True),
strict=kwargs.pop("strict", True),
**kwargs
)
|
[
"nicolas@plot.ly"
] |
nicolas@plot.ly
|
17f6b3138f1968e2507a1f897c7af44cf61fed90
|
0981ddfcd812cdd66f3509b4a052d30e098d8f44
|
/start-content/gerando_mensagens.py
|
af6f574bbb6c37ef8ad9963c8f71c3fa2e19a8c7
|
[] |
no_license
|
ricardofelixmont/Udacity-Fundamentos-IA-ML
|
3c49532e0a3bd662d6b5262cab056281f0020689
|
dda2afc0e31ab94fef937be31b1b12685f447a71
|
refs/heads/master
| 2020-04-10T13:44:19.472140
| 2019-04-16T21:24:22
| 2019-04-16T21:24:22
| 161,058,181
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 514
|
py
|
names = input('digite os nomes: ').split().title()
assignments = input('Digite os assignments: ').split()
grades = input('Digite as notas: ').split()
message = 'Hi {},This is a reminder that you have {} assignments left to submit before you can graduate. Your current grade is {} and can increase to {} if you submit all assignments before the due date.'
for nome, tarefa, nota in names, assignments, grades:
notaPotencial = nota + 2*assignments
print(message.format(nome, tarefa, nota, notaPotencial))
|
[
"ricardofelix_mont@outlook.com"
] |
ricardofelix_mont@outlook.com
|
5a6434d9a3bdeaec69b62fd4db7eeaa128efe908
|
f66da3c9293d9f680ab54cf3c562ef5dd661137c
|
/docs/source/examples/index.py
|
731aa4fd9d3096b22bd8ae9a9f1393d90efd68fb
|
[
"MIT"
] |
permissive
|
dvincentwest/gtimer
|
c49ef33ecdfeaf55298283cfd24953d372a3f4e5
|
2146dab459e5d959feb291821733d3d3ba7c523c
|
refs/heads/master
| 2022-04-21T22:08:06.103426
| 2016-10-05T07:44:04
| 2016-10-05T07:44:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 262
|
py
|
import gtimer as gt
import time
@gt.wrap
def some_function():
time.sleep(1)
gt.stamp('some_method')
time.sleep(2)
gt.stamp('another_function')
some_function()
gt.stamp('some_function')
time.sleep(1)
gt.stamp('another_method')
print gt.report()
|
[
"adam.stooke@gmail.com"
] |
adam.stooke@gmail.com
|
4df46f23c7e369d02d8672af00dd27c657d333c3
|
f9d564f1aa83eca45872dab7fbaa26dd48210d08
|
/huaweicloud-sdk-cce/huaweicloudsdkcce/v3/model/nic_spec.py
|
b40e87c841b9dc1783c70313cbd1039699834425
|
[
"Apache-2.0"
] |
permissive
|
huaweicloud/huaweicloud-sdk-python-v3
|
cde6d849ce5b1de05ac5ebfd6153f27803837d84
|
f69344c1dadb79067746ddf9bfde4bddc18d5ecf
|
refs/heads/master
| 2023-09-01T19:29:43.013318
| 2023-08-31T08:28:59
| 2023-08-31T08:28:59
| 262,207,814
| 103
| 44
|
NOASSERTION
| 2023-06-22T14:50:48
| 2020-05-08T02:28:43
|
Python
|
UTF-8
|
Python
| false
| false
| 5,520
|
py
|
# coding: utf-8
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class NicSpec:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'subnet_id': 'str',
'fixed_ips': 'list[str]',
'ip_block': 'str'
}
attribute_map = {
'subnet_id': 'subnetId',
'fixed_ips': 'fixedIps',
'ip_block': 'ipBlock'
}
def __init__(self, subnet_id=None, fixed_ips=None, ip_block=None):
"""NicSpec
The model defined in huaweicloud sdk
:param subnet_id: 网卡所在子网的网络ID。主网卡创建时若未指定subnetId,将使用集群子网。拓展网卡创建时必须指定subnetId。
:type subnet_id: str
:param fixed_ips: 主网卡的IP将通过fixedIps指定,数量不得大于创建的节点数。fixedIps或ipBlock同时只能指定一个。
:type fixed_ips: list[str]
:param ip_block: 主网卡的IP段的CIDR格式,创建的节点IP将属于该IP段内。fixedIps或ipBlock同时只能指定一个。
:type ip_block: str
"""
self._subnet_id = None
self._fixed_ips = None
self._ip_block = None
self.discriminator = None
if subnet_id is not None:
self.subnet_id = subnet_id
if fixed_ips is not None:
self.fixed_ips = fixed_ips
if ip_block is not None:
self.ip_block = ip_block
@property
def subnet_id(self):
"""Gets the subnet_id of this NicSpec.
网卡所在子网的网络ID。主网卡创建时若未指定subnetId,将使用集群子网。拓展网卡创建时必须指定subnetId。
:return: The subnet_id of this NicSpec.
:rtype: str
"""
return self._subnet_id
@subnet_id.setter
def subnet_id(self, subnet_id):
"""Sets the subnet_id of this NicSpec.
网卡所在子网的网络ID。主网卡创建时若未指定subnetId,将使用集群子网。拓展网卡创建时必须指定subnetId。
:param subnet_id: The subnet_id of this NicSpec.
:type subnet_id: str
"""
self._subnet_id = subnet_id
@property
def fixed_ips(self):
"""Gets the fixed_ips of this NicSpec.
主网卡的IP将通过fixedIps指定,数量不得大于创建的节点数。fixedIps或ipBlock同时只能指定一个。
:return: The fixed_ips of this NicSpec.
:rtype: list[str]
"""
return self._fixed_ips
@fixed_ips.setter
def fixed_ips(self, fixed_ips):
"""Sets the fixed_ips of this NicSpec.
主网卡的IP将通过fixedIps指定,数量不得大于创建的节点数。fixedIps或ipBlock同时只能指定一个。
:param fixed_ips: The fixed_ips of this NicSpec.
:type fixed_ips: list[str]
"""
self._fixed_ips = fixed_ips
@property
def ip_block(self):
"""Gets the ip_block of this NicSpec.
主网卡的IP段的CIDR格式,创建的节点IP将属于该IP段内。fixedIps或ipBlock同时只能指定一个。
:return: The ip_block of this NicSpec.
:rtype: str
"""
return self._ip_block
@ip_block.setter
def ip_block(self, ip_block):
"""Sets the ip_block of this NicSpec.
主网卡的IP段的CIDR格式,创建的节点IP将属于该IP段内。fixedIps或ipBlock同时只能指定一个。
:param ip_block: The ip_block of this NicSpec.
:type ip_block: str
"""
self._ip_block = ip_block
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, NicSpec):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
[
"hwcloudsdk@huawei.com"
] |
hwcloudsdk@huawei.com
|
420fe9952d25789d462ba42a6cd0d82c5d3005e8
|
8a1686aeeefa80afeb0aa9f45ed72a75883458c4
|
/dit/divergences/maximum_correlation.py
|
80b8a60874ec9a78929efb6b7f35b7813c08a5da
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
heleibin/dit
|
70afd57f31be346e48b9b28c67fd6e019132ac36
|
ebd0c11600e559bf34cf12a6b4e451057838e324
|
refs/heads/master
| 2020-09-27T07:42:15.991500
| 2019-11-23T06:10:11
| 2019-11-23T06:10:11
| 226,466,522
| 1
| 0
|
BSD-3-Clause
| 2019-12-07T06:26:50
| 2019-12-07T06:26:50
| null |
UTF-8
|
Python
| false
| false
| 3,451
|
py
|
"""
Compute the maximum correlation:
\rho(X:Y) = max_{f, g} E(f(X)g(Y))
"""
import numpy as np
from ..exceptions import ditException
from ..helpers import normalize_rvs
svdvals = lambda m: np.linalg.svd(m, compute_uv=False)
def conditional_maximum_correlation_pmf(pmf):
"""
Compute the conditional maximum correlation from a 3-dimensional
pmf. The maximum correlation is computed between the first two dimensions
given the third.
Parameters
----------
pmf : np.ndarray
The probability distribution.
Returns
-------
rho_max : float
The conditional maximum correlation.
"""
pXYgZ = pmf / pmf.sum(axis=(0,1), keepdims=True)
pXgZ = pXYgZ.sum(axis=1, keepdims=True)
pYgZ = pXYgZ.sum(axis=0, keepdims=True)
Q = np.where(pmf, pXYgZ / (np.sqrt(pXgZ)*np.sqrt(pYgZ)), 0)
Q[np.isnan(Q)] = 0
rho_max = max([svdvals(np.squeeze(m))[1] for m in np.dsplit(Q, Q.shape[2])])
return rho_max
def maximum_correlation_pmf(pXY):
"""
Compute the maximum correlation from a 2-dimensional
pmf. The maximum correlation is computed between the two dimensions.
Parameters
----------
pmf : np.ndarray
The probability distribution.
Returns
-------
rho_max : float
The maximum correlation.
"""
pX = pXY.sum(axis=1, keepdims=True)
pY = pXY.sum(axis=0, keepdims=True)
Q = pXY / (np.sqrt(pX)*np.sqrt(pY))
Q[np.isnan(Q)] = 0
rho_max = svdvals(Q)[1]
return rho_max
def maximum_correlation(dist, rvs=None, crvs=None, rv_mode=None):
"""
Compute the (conditional) maximum or Renyi correlation between two variables:
rho_max = max_{f, g} rho(f(X,Z), g(Y,Z) | Z)
Parameters
----------
dist : Distribution
The distribution for which the maximum correlation is to computed.
rvs : list, None; len(rvs) == 2
A list of lists. Each inner list specifies the indexes of the random
variables for which the maximum correlation is to be computed. If None,
then all random variables are used, which is equivalent to passing
`rvs=dist.rvs`.
crvs : list, None
A single list of indexes specifying the random variables to
condition on. If None, then no variables are conditioned on.
rv_mode : str, None
Specifies how to interpret `rvs` and `crvs`. Valid options are:
{'indices', 'names'}. If equal to 'indices', then the elements of
`crvs` and `rvs` are interpreted as random variable indices. If
equal to 'names', the the elements are interpreted as random
variable names. If `None`, then the value of `dist._rv_mode` is
consulted, which defaults to 'indices'.
Returns
-------
rho_max : float; -1 <= rho_max <= 1
The conditional maximum correlation between `rvs` given `crvs`.
"""
rvs, crvs, rv_mode = normalize_rvs(dist, rvs, crvs, rv_mode)
if len(rvs) != 2:
msg = 'Maximum correlation can only be computed for 2 variables, not {}.'.format(len(rvs))
raise ditException(msg)
if crvs:
dist = dist.copy().coalesce(rvs + [crvs])
else:
dist = dist.copy().coalesce(rvs)
dist.make_dense()
pmf = dist.pmf.reshape(list(map(len, dist.alphabet)))
if crvs:
rho_max = conditional_maximum_correlation_pmf(pmf)
else:
rho_max = maximum_correlation_pmf(pmf)
return rho_max
|
[
"ryangregoryjames@gmail.com"
] |
ryangregoryjames@gmail.com
|
867a8ce5135318155e8e9463699c47f23b4859b6
|
d7016f69993570a1c55974582cda899ff70907ec
|
/sdk/recoveryservices/azure-mgmt-recoveryservicesbackup/generated_samples/get_resource_guard_proxy.py
|
a085c61f352a1766d44f4096824fb137a79e154c
|
[
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] |
permissive
|
kurtzeborn/azure-sdk-for-python
|
51ca636ad26ca51bc0c9e6865332781787e6f882
|
b23e71b289c71f179b9cf9b8c75b1922833a542a
|
refs/heads/main
| 2023-03-21T14:19:50.299852
| 2023-02-15T13:30:47
| 2023-02-15T13:30:47
| 157,927,277
| 0
| 0
|
MIT
| 2022-07-19T08:05:23
| 2018-11-16T22:15:30
|
Python
|
UTF-8
|
Python
| false
| false
| 1,712
|
py
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from azure.identity import DefaultAzureCredential
from azure.mgmt.recoveryservicesbackup import RecoveryServicesBackupClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-recoveryservicesbackup
# USAGE
python get_resource_guard_proxy.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = RecoveryServicesBackupClient(
credential=DefaultAzureCredential(),
subscription_id="0b352192-dcac-4cc7-992e-a96190ccc68c",
)
response = client.resource_guard_proxy.get(
vault_name="sampleVault",
resource_group_name="SampleResourceGroup",
resource_guard_proxy_name="swaggerExample",
)
print(response)
# x-ms-original-file: specification/recoveryservicesbackup/resource-manager/Microsoft.RecoveryServices/stable/2023-01-01/examples/ResourceGuardProxyCRUD/GetResourceGuardProxy.json
if __name__ == "__main__":
main()
|
[
"noreply@github.com"
] |
kurtzeborn.noreply@github.com
|
51ec22fa4a3789ebde8822eb40cf8fb7046df5fc
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p02646/s812265777.py
|
bf9bfeae85ecdf39cf4a7df800b93778ecaceb82
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 717
|
py
|
A, V = map(int, input().split(" "))
B, W = map(int, input().split(" "))
T = int(input())
if W > V:
print("NO")
else:
if abs(A - B) <= T * (V - W):
print("YES")
else:
print("NO")
# if A - B > 0:
# # 負の方向に逃げる
# if (B + 10**9) / W <= T:
# # print("left reach")
# # T立つよりも先に端に到達してしまう場合
# Bdist = (B + 10**9)
# else:
# # print("run left")
# Bdist = W * T
# else:
# # 正の方向に逃げる
# if (10**9 - B) / W <= T:
# # print("right reach")
# Bdist = (10**9 - B)
# else:
# # print("run right")
# Bdist = W * T
# Adist = V * T
# if Bdist + abs(A - B) <= Adist:
# print("YES")
# else:
# print("NO")
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
86b3f2d69deb2248d91d4be3c74f7213daf6915f
|
15f321878face2af9317363c5f6de1e5ddd9b749
|
/solutions_python/Problem_84/33.py
|
57b6d1e3842473c752fac1c09401d02031ba1c9c
|
[] |
no_license
|
dr-dos-ok/Code_Jam_Webscraper
|
c06fd59870842664cd79c41eb460a09553e1c80a
|
26a35bf114a3aa30fc4c677ef069d95f41665cc0
|
refs/heads/master
| 2020-04-06T08:17:40.938460
| 2018-10-14T10:12:47
| 2018-10-14T10:12:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 621
|
py
|
def solve():
r,c = map(int,raw_input().split())
a = [list(raw_input()) for _ in xrange(r)]
for i in xrange(r):
for j in xrange(c):
if a[i][j]!='#': continue
if i==r-1 or j==c-1: return None
if a[i+1][j]!='#': return None
if a[i+1][j+1]!='#': return None
if a[i][j+1]!='#': return None
a[i][j]=a[i+1][j+1]='/'
a[i+1][j]=a[i][j+1]='\\'
return a
t = input()
for tn in xrange(t):
r = solve()
print "Case #%d:"%(tn+1)
if r is None: print "Impossible"
else: print '\n'.join(''.join(x) for x in r)
|
[
"miliar1732@gmail.com"
] |
miliar1732@gmail.com
|
f2c2740bf34812d6361ee4b4a9a39f9f1a9d983b
|
86318359cde2629f68113f7fe097757ef8e4923a
|
/mep/books/migrations/0023_merge_20200406_1206.py
|
507c1ce7a10f2e1cdb1c549e0585c76c6e7fc95f
|
[
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] |
permissive
|
Princeton-CDH/mep-django
|
214f68a9c99b5025722c7301c976004edd277d9b
|
6103855f07c2c0123ab21b93b794ea5d5ca39aa2
|
refs/heads/main
| 2023-08-03T10:15:02.287018
| 2022-09-06T21:16:01
| 2022-09-06T21:16:01
| 94,891,547
| 6
| 0
|
Apache-2.0
| 2023-07-20T22:07:34
| 2017-06-20T13:00:00
|
Python
|
UTF-8
|
Python
| false
| false
| 271
|
py
|
# Generated by Django 2.2.11 on 2020-04-06 16:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('books', '0021_creator_type_order'),
('books', '0022_generate_work_slugs'),
]
operations = [
]
|
[
"rebecca.s.koeser@princeton.edu"
] |
rebecca.s.koeser@princeton.edu
|
d893501915448c66c6bda1af06cc5994eb4911be
|
3428950daafacec9539a83809cf9752000508f63
|
/data_struct/10_combination.py
|
136a9f2a426e90a1e6863a66530fc3a6d61f865a
|
[] |
no_license
|
HyunAm0225/Python_Algorithm
|
759b91743abf2605dfd996ecf7791267b0b5979a
|
99fb79001d4ee584a9c2d70f45644e9101317764
|
refs/heads/master
| 2023-05-24T05:29:12.838390
| 2021-06-15T16:36:33
| 2021-06-15T16:36:33
| 274,587,523
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 304
|
py
|
def combination(s):
if len(s) < 2:
return s
res = []
for i, c in enumerate(s):
res.append(c) # 추가된 부분
for j in combination(s[:i]+s[i+1:]):
res.append(c+j)
return res
if __name__ == "__main__":
data = "abc"
print(combination(data))
|
[
"tlfgjawlq@naver.com"
] |
tlfgjawlq@naver.com
|
9c99e9c602c04babded94612e54aa4147608301e
|
265403cd620f1729176343626db909ccecc67243
|
/runserver.py
|
c80b199e83158ccb7fb8c091ddaef40bbfda8d39
|
[
"MIT"
] |
permissive
|
djpnewton/beerme
|
a5486efe8f3a632ff479f75fde825264f8c45d42
|
b06564f897c5e63a6af6229aa5234ef5de4820a7
|
refs/heads/master
| 2020-04-05T23:21:15.375723
| 2015-07-01T07:37:02
| 2015-07-01T07:37:02
| 37,122,757
| 1
| 1
| null | 2015-07-05T12:26:55
| 2015-06-09T09:25:34
|
Python
|
UTF-8
|
Python
| false
| false
| 2,544
|
py
|
#!/usr/bin/python
from beerme import app
import os
host = os.getenv('HOST', '127.0.0.1')
port = int(os.getenv('PORT', 5000))
# get filenames before daemonizing
app_log_filename = os.path.realpath('log/beerme.log')
access_log_filename = os.path.realpath('log/access.log')
def log_app():
import cherrypy
from paste.translogger import TransLogger
import logging
from logging.handlers import RotatingFileHandler
# Enable app/error logging
handler = RotatingFileHandler(app_log_filename, maxBytes=10000000, backupCount=5)
handler.setLevel(logging.DEBUG)
app.logger.addHandler(handler)
cherrypy.log.error_file = ''
cherrypy.log.error_log.addHandler(handler)
# Enable WSGI access logging access via Paste
app_logged = TransLogger(app)
handler = RotatingFileHandler(access_log_filename, maxBytes=10000000, backupCount=5)
logger = logging.getLogger('wsgi')
logger.addHandler(handler)
cherrypy.log.access_file = ''
return app_logged
def start_cherrypy():
import cherrypy
# create cherrypy logged app
app_logged = log_app()
# Mount the WSGI callable object (app) on the root directory
cherrypy.tree.graft(app_logged, '/')
# Set the configuration of the web server
cherrypy.config.update({
'engine.autoreload.on': True,
'log.screen': True,
'server.socket_host': host,
'server.socket_port': port,
# Do not just listen on localhost
'server.socket_host': '0.0.0.0'
})
# Start the CherryPy WSGI web server
cherrypy.engine.start()
cherrypy.engine.block()
def start_debug():
app.debug = True
app.run(host, port)
if __name__ == '__main__':
import sys
if len(sys.argv) == 2 and 'debug' == sys.argv[1]:
start_debug()
else:
from beerme.daemon import Daemon
class BitriskDaemon(Daemon):
def run(self):
start_cherrypy()
daemon = BitriskDaemon('/tmp/beerme-daemon.pid')
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
daemon.start()
elif 'stop' == sys.argv[1]:
daemon.stop()
elif 'restart' == sys.argv[1]:
daemon.restart()
elif 'foreground' == sys.argv[1]:
daemon.run()
else:
print "Unknown command"
sys.exit(2)
sys.exit(0)
else:
print "usage: %s start|stop|restart|foreground|debug" % sys.argv[0]
sys.exit(2)
|
[
"djpnewton@gmail.com"
] |
djpnewton@gmail.com
|
1a7a6d6691359a38be4991eefc4ff9dd19b73511
|
4edb067c8c748e503e154bb2b9190843f6f1684a
|
/tests/test_utils/test_decorators.py
|
99e6a477f5b2abc16262433e3225e0fbb78a035e
|
[
"Apache-2.0"
] |
permissive
|
DistrictDataLabs/yellowbrick-docs-zh
|
5ecbdccfaff4a6822d60250719b37af9b8d37f61
|
3118e67f2bed561a00885e6edb2cabb3520ad66b
|
refs/heads/master
| 2021-04-09T11:00:29.709555
| 2019-04-06T15:23:55
| 2019-04-06T15:23:55
| 125,447,764
| 22
| 5
|
Apache-2.0
| 2019-04-06T14:52:40
| 2018-03-16T01:37:09
|
Python
|
UTF-8
|
Python
| false
| false
| 2,788
|
py
|
# tests.test_utils.test_decorators
# Tests for the decorators module in Yellowbrick utils.
#
# Author: Benjamin Bengfort <bbengfort@districtdatalabs.com>
# Created: Thu May 18 15:14:34 2017 -0400
#
# Copyright (C) 2017 District Data Labs
# For license information, see LICENSE.txt
#
# ID: test_decorators.py [79cd8cf] benjamin@bengfort.com $
"""
Tests for the decorators module in Yellowbrick utils.
"""
##########################################################################
## Imports
##########################################################################
import unittest
from yellowbrick.utils.decorators import *
##########################################################################
## Decorator Tests
##########################################################################
class DecoratorTests(unittest.TestCase):
"""
Tests for the decorator utilities.
"""
def test_memoization(self):
"""
Test the memoized property decorator on a class.
"""
class Visualizer(object):
@memoized
def foo(self):
return "bar"
viz = Visualizer()
self.assertFalse(hasattr(viz, "_foo"))
self.assertEqual(viz.foo, "bar")
self.assertEqual(viz._foo, "bar")
def test_docutil(self):
"""
Test the docutil docstring copying methodology.
"""
class Visualizer(object):
def __init__(self):
"""
This is the correct docstring.
"""
pass
def undecorated(*args, **kwargs):
"""
This is an undecorated function string.
"""
pass
# Test the undecorated string to protect from magic
self.assertEqual(
undecorated.__doc__.strip(), "This is an undecorated function string."
)
# Decorate manually and test the newly decorated return function.
decorated = docutil(Visualizer.__init__)(undecorated)
self.assertEqual(
decorated.__doc__.strip(), "This is the correct docstring."
)
# Assert that decoration modifies the original function.
self.assertEqual(
undecorated.__doc__.strip(), "This is the correct docstring."
)
@docutil(Visualizer.__init__)
def sugar(*args, **kwargs):
pass
# Assert that syntactic sugar works as expected.
self.assertEqual(
sugar.__doc__.strip(), "This is the correct docstring."
)
##########################################################################
## Execute Tests
##########################################################################
if __name__ == "__main__":
unittest.main()
|
[
"benjamin@bengfort.com"
] |
benjamin@bengfort.com
|
63546a63ea14ce3fc5fadc04ebc9988761286182
|
d1ddb9e9e75d42986eba239550364cff3d8f5203
|
/google-cloud-sdk/lib/surface/compute/instance_groups/unmanaged/delete.py
|
955dc6c5dfd2b844563c81ffbc6b0310d1d95757
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
bopopescu/searchparty
|
8ecd702af0d610a7ad3a8df9c4d448f76f46c450
|
afdc2805cb1b77bd5ac9fdd1a76217f4841f0ea6
|
refs/heads/master
| 2022-11-19T14:44:55.421926
| 2017-07-28T14:55:43
| 2017-07-28T14:55:43
| 282,495,798
| 0
| 0
|
Apache-2.0
| 2020-07-25T17:48:53
| 2020-07-25T17:48:52
| null |
UTF-8
|
Python
| false
| false
| 2,378
|
py
|
# Copyright 2014 Google Inc. 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.
"""Command for deleting unmanaged instance groups."""
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import flags as compute_flags
from googlecloudsdk.command_lib.compute.instance_groups import flags
class Delete(base.DeleteCommand):
r"""Delete Google Compute Engine unmanaged instance groups.
*{command}* deletes one or more Google Compute Engine unmanaged
instance groups. This command just deletes the instance group and does
not delete the individual virtual machine instances
in the instance group.
For example:
$ {command} example-instance-group-1 example-instance-group-2 \
--zone us-central1-a
The above example deletes two instance groups, example-instance-group-1
and example-instance-group-2, in the ``us-central1-a'' zone.
"""
@staticmethod
def Args(parser):
Delete.ZonalInstanceGroupArg = flags.MakeZonalInstanceGroupArg(plural=True)
Delete.ZonalInstanceGroupArg.AddArgument(parser, operation_type='delete')
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
instance_group_refs = Delete.ZonalInstanceGroupArg.ResolveAsResource(
args,
holder.resources,
scope_lister=compute_flags.GetDefaultScopeLister(client))
utils.PromptForDeletion(instance_group_refs, 'zone')
requests = []
for instance_group_ref in instance_group_refs:
requests.append((client.apitools_client.instanceGroups, 'Delete',
client.messages.ComputeInstanceGroupsDeleteRequest(
**instance_group_ref.AsDict())))
return client.MakeRequests(requests)
|
[
"vinvivo@users.noreply.github.com"
] |
vinvivo@users.noreply.github.com
|
8b37cfa66542bbb293a615730337867c31ead081
|
bb932a93d3face2458dc00329e3811664baa6b52
|
/unittest/asyncio_queue.py
|
f02aba922836f18e965d7c7bc443e2e333a97c6c
|
[
"MIT"
] |
permissive
|
Emptyset110/Morphe
|
5dfc5d836b13d8edd074a231faa923add6b98bbe
|
762a031298addf9a34425dbecaa793727aeed4c2
|
refs/heads/master
| 2021-01-19T09:21:11.323822
| 2017-04-15T05:16:05
| 2017-04-15T05:16:05
| 87,750,665
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,435
|
py
|
# coding: utf-8
"""
决定将queue.Queue换成asyncio.Queue前试写的demo
"""
import asyncio
from asyncio import Queue
import queue
import random
import threading
import functools
@asyncio.coroutine
def queue_feeder(q):
for i in range(0, 100):
print("Put: ", i)
yield from q.put(i)
yield from asyncio.sleep(random.random()*3)
@asyncio.coroutine
def async_get(q):
while True:
print("Start get: ...")
data = yield from q.get()
print("Get: ", data)
@asyncio.coroutine
def async_get_sync(q, out):
while True:
print("Start get: ...")
data = yield from q.get()
out.put(data)
def get(q):
import time
while True:
print("Start get from sync queue: ...")
data = q.get()
print("Sync get", data)
if __name__ == "__main__":
# q1, q2是两个异步队列
q1 = Queue()
q2 = Queue()
# 做一个同步队列用于将上游所有的异步消息同步化
out = queue.Queue()
t = threading.Thread(target=functools.partial(get, out), daemon=True)
t.start()
# 开启一个协程池, 异步执行q1, q2的异步生产和消费,消费过程是将数据丢进out这个同步队列以同步化
loop = asyncio.get_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(asyncio.gather(*[queue_feeder(q1), queue_feeder(q2), async_get_sync(q1, out), async_get_sync(q2, out)]))
|
[
"21324784@qq.com"
] |
21324784@qq.com
|
169e9831bcc3567be42765c6f6d3db237d70ede8
|
49e3663fea29ae7fabec581ebae1fda5361effcd
|
/events/migrations/0003_auto__add_field_event_short_body.py
|
ff8f2567acac4b37f3f29ef89ba73caeb15a2d8f
|
[] |
no_license
|
ikonitas/old_causenaffect
|
8fdabdc3108efa16046f6bdfa542f71d58a4e6eb
|
145f7ae82d02e39bda17aad380dac0f190f1882c
|
refs/heads/master
| 2021-05-28T08:46:49.663299
| 2014-02-17T21:42:36
| 2014-02-17T21:42:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,212
|
py
|
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Event.short_body'
db.add_column('events_event', 'short_body', self.gf('django.db.models.fields.TextField')(default=1), keep_default=False)
def backwards(self, orm):
# Deleting field 'Event.short_body'
db.delete_column('events_event', 'short_body')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'events.event': {
'Meta': {'ordering': "['-event_date']", 'object_name': 'Event'},
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'body': ('django.db.models.fields.TextField', [], {}),
'enable_comments': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'event_date': ('django.db.models.fields.DateField', [], {'default': 'datetime.datetime(2013, 1, 6, 13, 53, 36, 581221)'}),
'flayer': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'flayer_thumb': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'price': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'pub_date': ('django.db.models.fields.DateField', [], {'default': 'datetime.datetime(2013, 1, 6, 13, 53, 36, 581195)', 'auto_now_add': 'True', 'blank': 'True'}),
'short_body': ('django.db.models.fields.TextField', [], {}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50', 'db_index': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '1'}),
'time': ('django.db.models.fields.TimeField', [], {}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['events']
|
[
"ikonitas@gmail.com"
] |
ikonitas@gmail.com
|
1e4797753fd3e0fcebccf3be0b971ddb534b7452
|
9129a791f45cd3b25d8a5da57ee6936bfe4e73a2
|
/learn-django/db_ORM2/one/migrations/0002_article_username.py
|
36eb6412db4e75d303331bc845e1d0aeff1d4ef2
|
[] |
no_license
|
Sunsetjue/Django2.0
|
94be49ed9d65dab6398ab8f0ddd02bb1871afb6b
|
102bf0f2bd2d309b76f3247e396b7e83c5f6c2f8
|
refs/heads/master
| 2020-04-22T03:25:24.014196
| 2019-02-15T16:18:23
| 2019-02-15T16:18:23
| 170,086,151
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 494
|
py
|
# Generated by Django 2.0 on 2018-12-10 08:02
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('two', '0001_initial'),
('one', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='article',
name='username',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='two.Front'),
),
]
|
[
"10073631822qq.com"
] |
10073631822qq.com
|
9c70343fb4ede60d25a4826018132491b6ce3728
|
2daa3894e6d6929fd04145100d8a3be5eedbe21c
|
/tests/artificial/transf_/trend_constant/cycle_12/ar_/test_artificial_128__constant_12__20.py
|
53da275217edee4022050200a1f5d3f55f20f941
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
Henri-Lo/pyaf
|
a1f73a0cc807873bd7b79648fe51de9cfd6c126a
|
08c968425d85dcace974d90db7f07c845a0fe914
|
refs/heads/master
| 2021-07-01T12:27:31.600232
| 2017-09-21T11:19:04
| 2017-09-21T11:19:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 305
|
py
|
import pyaf.Bench.TS_datasets as tsds
import pyaf.tests.artificial.process_artificial_dataset as art
dataset = tsds.generate_random_TS(N = 128 , FREQ = 'D', seed = 0, trendtype = "constant", cycle_length = 12, transform = "", sigma = 0.0, exog_count = 20, ar_order = 0);
art.process_dataset(dataset);
|
[
"antoine.carme@laposte.net"
] |
antoine.carme@laposte.net
|
5e70ad84a6cda2ce2c916562e762ea79f62edafc
|
1c0e889b5f216549160eba5fa6960078926b6f27
|
/flaskServer.py
|
a9e1fe60fe430ae1ecbd3b75de3e2629082eb37f
|
[
"Artistic-2.0"
] |
permissive
|
ttm/aars
|
477d42f7f4627d0178ca5fabf1445d7c1819d2ef
|
481ea568321255ddc60b167325c545f84f3284ff
|
refs/heads/master
| 2021-01-01T17:32:55.940835
| 2014-12-16T06:09:05
| 2014-12-16T06:09:05
| 21,177,370
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,102
|
py
|
#-*- coding: utf-8 -*-
from flask import Flask, render_template, make_response, session, redirect, url_for, escape, request,jsonify,Response
import pymongo, __builtin__, datetime, string
from dateutil import parser
import time as T, networkx as x, json # json.dumps
#import MySQLdb, cPickle, numpy as n
from maccess import mdc as U
HTAG="#testeteste"
HTAG_=HTAG.replace("#","NEW")
U=U.u1
app = Flask(__name__)
@app.route("/")
def hello_world():
client=pymongo.MongoClient(U)
db = client[U.split("/")[-1]]
C = db[HTAG_] #collection
msgs=[i for i in C.find()]
info=[(mm["user"]["screen_name"],mm["text"],mm["created_at"]) for mm in msgs]
text_block=string.join([str(ii) for ii in info],"<br />")
return text_block
@app.route("/jsonMe/")
def jsonMe():
client=pymongo.MongoClient(U)
db = client[U.split("/")[-1]]
C = db[HTAG_] #collection
msgs=[i for i in C.find()]
info=[[mm["user"]["screen_name"],mm["text"],mm["created_at"]] for mm in msgs]
return jsonify(info=info)
if __name__ == "__main__":
app.debug = True
app.run(host='0.0.0.0')
|
[
"renato.fabbri@gmail.com"
] |
renato.fabbri@gmail.com
|
e7f67e86dc59350d2e03716109cfd53bf3497274
|
9ee5e51e96fe8baff2ccc7a03981e453b60e3bed
|
/test/technical_analysis/stock_analysis.py
|
2b69e76bf748ca07296f428bfbecce36e24c8a7e
|
[] |
no_license
|
marciopocebon/myInvestor
|
0b97a065e9f5dd9beaefca99955d4fb31a619c03
|
f4861b462b1161fb49534ec85ce259026fa20fd3
|
refs/heads/master
| 2021-12-24T03:21:05.829680
| 2017-12-05T15:45:04
| 2017-12-05T15:45:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,055
|
py
|
# must run using ipython console
# or jupyter-console
import pandas as pd
import pandas_datareader as web # Package and modules for importing data; this code may change depending on pandas version
import datetime
import matplotlib
import numpy as np
import matplotlib.pyplot as plt # Import matplotlib
# We will look at stock prices over the past year, starting at January 1, 2016
start = datetime.datetime(2016,1,1)
end = datetime.date.today()
# Let's get Apple stock data; Apple's ticker symbol is AAPL
# First argument is the series we want, second is the source ("yahoo" for Yahoo! Finance), third is the start date, fourth is the end date
apple = web.DataReader("AAPL", "yahoo", start, end)
type(apple)
apple.head()
# This line is necessary for the plot to appear in a Jupyter notebook
%matplotlib inline
# Control the default size of figures in this Jupyter notebook
%pylab inline
pylab.rcParams['figure.figsize'] = (15, 9) # Change the size of plots
apple["Adj Close"].plot(grid = True) # Plot the adjusted closing price of AAPL
|
[
"mengwangk@gmail.com"
] |
mengwangk@gmail.com
|
cbe8aff3d8002af75c4697557ef1744bc3204f6d
|
ab825ee0326e98d115b6dc02bbda02b302787d46
|
/基礎編/パスの結合・連結/モジュール/パスの結合・連結.py
|
dacca7b719dece6f3e5051edcf80d20667fd444b
|
[] |
no_license
|
holothuria/python_study
|
295dd7c30a566b5a9688b9196e25bf6e065401a0
|
7e98090e64d646d23a4189e0efd68c2905b78d04
|
refs/heads/master
| 2020-03-23T20:04:38.900368
| 2019-03-05T12:47:53
| 2019-03-05T12:47:53
| 142,019,995
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 395
|
py
|
import os
PROJECT_DIR = 'C:\python-izm'
SETTINGS_FILE = 'settings.ini'
print(os.path.join(PROJECT_DIR, SETTINGS_FILE))
print(os.path.join(PROJECT_DIR, 'settings_dir', SETTINGS_FILE))
PROJECT_DIR = 'python-izm'
print(os.path.join('C:', PROJECT_DIR, 'settings_dir', SETTINGS_FILE))
# ↑「(アルファベット一文字):」のみだと、区切りを入れて貰えない?
|
[
"umehara.daichi@withone.co.jp"
] |
umehara.daichi@withone.co.jp
|
f0002acb5507cad1be812360cbda655027b4a4ee
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03836/s741210941.py
|
115e3d1b0023264fc7ddea4090c60e0bdb2df46d
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 234
|
py
|
sx, sy, tx, ty = map(int, input().split())
X, Y = tx - sx, ty - sy
for d, n in zip("RULD", [X, Y, X, Y]):
print(d * n, end="")
for d, n in zip("DRULULDR", [1, X + 1, Y + 1, 1, 1, X + 1, Y + 1, 1]):
print(d * n, end="")
print()
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
f472bebf8fd8f21a87e1b9ff1e7bf3e60577b9b8
|
1c58aef845d5dc1398249d784450c3825a1a75a5
|
/Dynamic_Programming/speed_and_spikes.py
|
a9cbecd5027d6f47406253b683546dacd977f77a
|
[] |
no_license
|
AmitKulkarni23/Leet_HackerRank
|
b1c1d7e5915397fd971d777baf75bb0f6fd27c78
|
047b167311d2fb93a53998a20d73533a4cae2ab8
|
refs/heads/master
| 2021-06-01T20:24:40.659530
| 2020-02-06T22:10:14
| 2020-02-06T22:10:14
| 123,007,444
| 0
| 0
| null | 2018-07-12T18:42:40
| 2018-02-26T17:58:28
|
Python
|
UTF-8
|
Python
| false
| false
| 2,069
|
py
|
# Speed and spikes problem
# Source -> http://blog.refdash.com/dynamic-programming-tutorial-example/
def canStopOnRunway(init_speed, runway, init_position):
"""
Function that returns true if a person on a jumping ball with init
speed can stop on a runway
type: runway - List
type: init_speed - int
type: init_position - int
"""
# Base Cases - All negative bases cases
if init_position >= len(runway) or init_position < 0 or
init_speed < 0 or not runway[init_position]:
return False
# Positive base case
if init_speed == 0:
return True
# Now try all speeds
for adjusted_speed in [init_speed-1, init_speed, init_speed+1]:
if canStopOnRunway(adjusted_speed, runway, init_position + adjusted_speed):
return True
return False
# Iterative solution
def canStopIterative(runway, initSpeed, startIndex = 0):
# maximum speed cannot be larger than length of the runway. We will talk about
# making this bound tighter later on.
maxSpeed = len(runway)
if (startIndex >= len(runway) or startIndex < 0 or initSpeed < 0 or initSpeed > maxSpeed or not runway[startIndex]):
return False
# {position i : set of speeds for which we can stop from position i}
memo = {}
# Base cases, we can stop when a position is not a spike and speed is zero.
for position in range(len(runway)):
if runway[position]:
memo[position] = set([0])
# Outer loop to go over positions from the last one to the first one
for position in reversed(range(len(runway))):
# Skip positions which contain spikes
if not runway[position]:
continue
# For each position, go over all possible speeds
for speed in range(1, maxSpeed + 1):
# Recurrence relation is the same as in the recursive version.
for adjustedSpeed in [speed, speed - 1, speed + 1]:
if (position + adjustedSpeed in memo and
adjustedSpeed in memo[position + adjustedSpeed]):
memo[position].add(speed)
break
return initSpeed in memo[startIndex]
|
[
"amitrkulkarni232@gmail.com"
] |
amitrkulkarni232@gmail.com
|
2df8b170c2e69db0ef937e0f736d0c7f99e10784
|
3d962145fe6f6b118e059af8728ec4d302593101
|
/dbaas/dbaas/middleware.py
|
2e93c087ba2aca960ed1b7a8b12a213aa456d2de
|
[
"BSD-3-Clause"
] |
permissive
|
perry-contribs/database-as-a-service
|
f015008a29600ce128c15686c2ff00fa360600f9
|
db8fbee3982bbc32abf32aa86f7387de01a243be
|
refs/heads/master
| 2022-12-18T12:17:40.496898
| 2020-10-01T09:12:54
| 2020-10-01T09:12:54
| 300,216,997
| 0
| 0
|
BSD-3-Clause
| 2020-10-01T09:11:19
| 2020-10-01T09:11:18
| null |
UTF-8
|
Python
| false
| false
| 1,390
|
py
|
from datetime import datetime, timedelta
from threading import current_thread
from django.conf import settings
from django.contrib import auth
class AutoLogout:
def process_request(self, request):
if not request.user.is_authenticated():
return
if 'last_touch' in request.session:
max_inactive = timedelta(0, settings.AUTO_LOGOUT_DELAY * 60, 0)
current_inactive = datetime.now() - request.session['last_touch']
if current_inactive > max_inactive:
auth.logout(request)
return
request.session['last_touch'] = datetime.now()
class UserMiddleware(object):
_requests = {}
@classmethod
def current_user(cls):
current_request = cls._requests.get(current_thread().ident, None)
if not current_request:
return
return current_request.user
@classmethod
def set_current_user(cls, user):
current_request = cls._requests[current_thread().ident]
current_request.user = user
def process_request(self, request):
self._requests[current_thread().ident] = request
def process_response(self, request, response):
self._requests.pop(current_thread().ident, None)
return response
def process_exception(self, request, exception):
self._requests.pop(current_thread().ident, None)
|
[
"mauro_murari@hotmail.com"
] |
mauro_murari@hotmail.com
|
d2d0f0e9540ff72210ef46f197d0fd14ea054dae
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03546/s313305577.py
|
d170aacbf34a2d5379c9166b8773528b739fcec0
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,352
|
py
|
# G[i][j]: 頂点v_iから頂点v_jへ到達するための辺コストの和
# クラスにしてしまったけど、これ遅いのでクラスじゃ無い方が良い
class Warshall_Floyd:
def __init__(self, V):
self.V = V
self.G = [[float('inf')] * self.V for i in range(self.V)]
def add_edge(self, fr, to, cost):
self.G[fr][to] = cost
def add_multi_edge(self, v1, v2, cost):
self.G[v1][v2] = cost
self.G[v2][v1] = cost
def solve(self):
for i in range(self.V):
self.G[i][i] = 0
for k in range(self.V):
for i in range(self.V):
for j in range(self.V):
if self.G[i][k] != float("inf") and self.G[k][j] != float('inf'):
self.G[i][j] = min(self.G[i][j], self.G[i][k] + self.G[k][j])
def if_negative(self):
for i in range(self.V):
if self.G[i][i] < 0:
return True
return False
def dist(self, fr, to):
return self.G[fr][to]
G = Warshall_Floyd(10)
H, W = map(int, input().split())
for i in range(10):
for j, c in enumerate(input().split()):
G.add_edge(i, j, int(c))
G.solve()
ans = 0
for i in range(H):
for j, a in enumerate(input().split()):
if a != "-1":
ans += G.dist(int(a), 1)
print(ans)
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
7325dcc029209e10b76f417754456c26de5f846e
|
30099a17539959fd445a412c09cf5d5369971dc4
|
/test/test.py
|
2ed51d8a5db2198d4f3c88cd8b31e78cc63c9a7e
|
[] |
no_license
|
Kmmanki/bit_seoul
|
7e16d6d51c21c449dd5150a64da3233bc562dcb7
|
8d1e86a84e218c7d96d6c6f9b2b5cd69765ebb9c
|
refs/heads/main
| 2023-04-08T02:16:10.372497
| 2021-04-15T01:35:09
| 2021-04-15T01:35:09
| 311,284,716
| 1
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,536
|
py
|
import numpy as np
from tensorflow.keras.models import Sequential,Model
from tensorflow.keras.layers import Dense, LSTM, Concatenate, Input
from tensorflow.keras.callbacks import EarlyStopping
#1.data
x1 = np.array([[1,2,3],[2,3,4],[3,4,5],[4,5,6]
,[5,6,7],[6,7,8],[7,8,9,],[8,9,10]
,[9,10,11],[10,11,12]
,[20,30,40],[30,40,50],[40,50,60]
])
x2 = np.array([[10,20,30],[20,30,40],[30,40,50],[40,50,60]
,[50,60,70],[60,70,80],[70,80,90,],[80,90,100]
,[90,100,110],[100,110,120]
,[2,3,4],[3,4,5],[4,5,6]
])
x1_input = np.array([55,65,75])
x2_input = np.array([65,75,85])
y= np.array([4,5,6,7,8,9,10,11,12,13,50,60,70])
x1=x1.reshape(13,3,1)
x2=x2.reshape(13,3,1)
# #2. model
input1 = Input(shape=(3,1))
lstm_d = LSTM(5)(input1)
input1_d = LSTM(5)(lstm_d)
input2 = Input(shape=(3,1))
lstm_d2 = LSTM(5)(input2)
input2_d = LSTM(5)(lstm_d2)
concat_model = Concatenate()([input1_d, input2_d])
model_concat = Dense(1)(concat_model)
model = Model(inputs=[input1, input2], outputs=[model_concat])
model.summary()
#Compile
model.compile(loss= 'mse', metrics=['mse'], optimizer='adam')
earlyStopping = EarlyStopping(monitor='loss', patience=125, mode='min')
model.fit([x1, x2], y, batch_size=3, epochs=10000, verbose=1, callbacks=[earlyStopping])
# #predict
x1_input = x1_input.reshape(1,3)
x2_input = x2_input.reshape(1,3)
y_predict = model.predict([x1_input, x2_input])
print(y_predict)
# loss = model.evaluate(x_input, np.array([80]), batch_size=1)
# print(loss)
|
[
"aksrl25@gmail.com"
] |
aksrl25@gmail.com
|
ff0bc8e563418f52c188920b6d7c290630091b55
|
4742f8b06c0e2d537cd76d0b05664be09f2a08fb
|
/Python Scripts/_Mono_Framework/MonoButtonElement.py
|
de9bbe6e71029607e51f7408b3c822e234ac1ebe
|
[] |
no_license
|
robjac/m4m7
|
bf6414bd0dd3ebfd7da72adecb761a85bfa79ce6
|
0dc6043594effd7375e7fb893321109f85288b46
|
refs/heads/master
| 2021-01-17T23:35:34.276099
| 2015-12-06T08:17:06
| 2015-12-06T08:17:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,989
|
py
|
# by amounra 0413 : http://www.aumhaa.com
import Live
from _Framework.ButtonElement import ButtonElement, ON_VALUE, OFF_VALUE
from _Framework.Skin import Skin, SkinColorMissingError
from MonoBridgeElement import MonoBridgeProxy
from Debug import *
MIDI_NOTE_TYPE = 0
MIDI_CC_TYPE = 1
MIDI_PB_TYPE = 2
MIDI_MSG_TYPES = (MIDI_NOTE_TYPE,
MIDI_CC_TYPE,
MIDI_PB_TYPE)
MIDI_NOTE_ON_STATUS = 144
MIDI_NOTE_OFF_STATUS = 128
MIDI_CC_STATUS = 176
MIDI_PB_STATUS = 224
debug = initialize_debug()
class MonoButtonElement(ButtonElement):
__module__ = __name__
__doc__ = ' Special button class that can be configured with custom on- and off-values, some of which flash at specified intervals called by _Update_Display'
def __init__(self, is_momentary, msg_type, channel, identifier, name = 'Button', script = None, color_map = None, *a, **k):
super(MonoButtonElement, self).__init__(is_momentary, msg_type, channel, identifier, name = name, *a, **k)
self._script = script
self._color_map = color_map or [2, 64, 4, 8, 16, 127, 32]
self._num_colors = 7
self._num_flash_states = 18
self._flash_state = 0
self._color = 0
self._on_value = 127
self._off_value = 0
self._darkened = 0
self._is_enabled = True
self._force_forwarding = False
self._is_notifying = False
self._force_next_value = False
self._parameter = None
self._report_input = True
def set_color_map(self, color_map):
assert isinstance(color_map, tuple)
assert len(color_map) > 0
self._num_colors = len(color_map)
self._num_flash_states = int(127/len(color_map))
self._color_map = color_map
def set_on_off_values(self, on_value, off_value):
self._last_sent_message = None
self._on_value = on_value
self._off_value = off_value
def set_on_value(self, value):
self._last_sent_message = None
self._on_value = value
def set_off_value(self, value):
self._last_sent_message = None
self._off_value = value
def set_darkened_value(self, value = 0):
#debug('setting darkened:', value)
if value:
value = self._color_map[value-1]
self._darkened = value
def set_force_next_value(self):
self._last_sent_message = None
self._force_next_value = True
def set_enabled(self, enabled):
self._is_enabled = enabled
self._request_rebuild()
def turn_on(self, force = False):
self.force_next_send()
if self._on_value in range(0, 128):
self.send_value(self._on_value)
else:
try:
color = self._skin[self._on_value]
color.draw(self)
except SkinColorMissingError:
#super(MonoButtonElement, self).turn_on()
debug('skin color missing', self._on_value)
self.send_value(127)
def turn_off(self, force = False):
self.force_next_send()
#debug('turn off:', self._off_value)
if self._off_value in range(0, 128):
self.send_value(self._off_value)
else:
try:
color = self._skin[self._off_value]
color.draw(self)
except SkinColorMissingError:
#super(MonoButtonElement, self).turn_off()
debug('skin color missing', self._off_value)
self.send_value(0)
def reset(self, force = False):
self._darkened = 0;
self.force_next_send()
self.send_value(0)
def set_light(self, value, *a, **k):
try:
self._skin[value]
except SkinColorMissingError:
#debug('skin missing for', value)
pass
#debug('skin value:', value)
super(MonoButtonElement, self).set_light(value, *a, **k)
def send_value(self, value, force = False):
if (value != None) and isinstance(value, int) and (value in range(128)):
if (force or self._force_next_send or ((value != self._last_sent_value) and self._is_being_forwarded)):
data_byte1 = self._original_identifier
if value in range(1, 127):
data_byte2 = self._color_map[(value - 1) % (self._num_colors)]
elif value == 127:
data_byte2 = self._color_map[self._num_colors-1]
else:
data_byte2 = self._darkened
self._color = data_byte2
status_byte = self._original_channel
if (self._msg_type == MIDI_NOTE_TYPE):
status_byte += MIDI_NOTE_ON_STATUS
elif (self._msg_type == MIDI_CC_TYPE):
status_byte += MIDI_CC_STATUS
else:
assert False
self.send_midi(tuple([status_byte,
data_byte1,
data_byte2]))
self._last_sent_message = [value]
if self._report_output:
is_input = True
self._report_value(value, (not is_input))
self._flash_state = round((value -1)/self._num_colors)
self._force_next_value = False
else:
debug('Button bad send value:', value)
def script_wants_forwarding(self):
if not self._is_enabled and not self._force_forwarding:
return False
else:
return super(MonoButtonElement, self).script_wants_forwarding()
def flash(self, timer):
if (self._is_being_forwarded and self._flash_state in range(1, self._num_flash_states) and (timer % self._flash_state) == 0):
data_byte1 = self._original_identifier
data_byte2 = self._color if int((timer % (self._flash_state * 2)) > 0) else self._darkened
status_byte = self._original_channel
if (self._msg_type == MIDI_NOTE_TYPE):
status_byte += MIDI_NOTE_ON_STATUS
elif (self._msg_type == MIDI_CC_TYPE):
status_byte += MIDI_CC_STATUS
else:
assert False
self.send_midi((status_byte,
data_byte1,
data_byte2))
def release_parameter(self):
self._darkened = 0
super(MonoButtonElement, self).release_parameter()
class DescriptiveMonoButtonElement(MonoButtonElement):
def __init__(self, *a, **k):
super(DescriptiveMonoButtonElement, self).__init__(*a, **k)
self._descriptor = None
self._last_reported_descriptor = None
monobridge = k['monobridge'] if 'monobridge' in k else None
if not monobridge is None:
self._monobridge = monobridge
elif hasattr(self._script, 'notification_to_bridge'):
self._monobridge = self._script
else:
self._monobridge = MonoBridgeProxy()
def set_descriptor(self, descriptor):
self._descriptor = '.' + str(descriptor) if descriptor else ''
def _set_descriptor(self, descriptor):
#debug('_set_descriptor:', descriptor)
self.set_descriptor(descriptor)
def _get_descriptor(self):
#debug('_get_descriptor:', '' if self._descriptor is None else str(self._descriptor))
return '' if self._descriptor is None else str(self._descriptor)
descriptor = property(_get_descriptor, _set_descriptor)
def report_descriptor(self, descriptor = None, force = False):
if force or (descriptor != self._last_reported_descriptor):
self._monobridge._send(self.name, 'button_function', str(descriptor) + self.descriptor)
self._last_reported_descriptor = descriptor
def set_light(self, value, *a, **k):
try:
self._skin[value]
except SkinColorMissingError:
pass
super(MonoButtonElement, self).set_light(value, *a, **k)
self.report_descriptor(value)
def turn_on(self, force = False):
self.force_next_send()
if self._on_value in range(0, 128):
self.send_value(self._on_value)
self.report_descriptor('on')
else:
try:
color = self._skin[self._on_value]
color.draw(self)
except SkinColorMissingError:
#super(MonoButtonElement, self).turn_on()
debug('skin color missing', self._on_value)
self.send_value(127)
self.report_descriptor(self._on_value)
def turn_off(self, force = False):
self.force_next_send()
#debug('turn off:', self._off_value)
if self._off_value in range(0, 128):
self.send_value(self._off_value)
self.report_descriptor('off')
else:
try:
color = self._skin[self._off_value]
color.draw(self)
except SkinColorMissingError:
#super(MonoButtonElement, self).turn_off()
debug('skin color missing', self._off_value)
self.send_value(0)
self.report_descriptor(self._off_value)
|
[
"aumhaa@gmail.com"
] |
aumhaa@gmail.com
|
0f8e38c0a2f1ee16f600bf711b04253540799ebb
|
c6292c1dd68f0c4dd3389628de0d2b786fa0ee64
|
/0x11-python-network_1/5-hbtn_header.py
|
b8d01504078e77816dad1f5eb961ca606bc0bf7a
|
[] |
no_license
|
mj31508/holbertonschool-higher_level_programming2
|
835be695b568cd189c1448c54218a0201830005f
|
3fa47001c041cd0c74f88c3a19677e126bee37b4
|
refs/heads/master
| 2021-07-06T22:31:05.040354
| 2017-09-29T05:28:45
| 2017-09-29T05:28:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 279
|
py
|
#!/usr/bin/python3
# Taking in a URL and sends a request
import requests
import sys
if __name__ == "__main__":
url_arg = sys.argv[1]
req_arg = requests.get(url_arg)
try:
store = req_arg.headers["X-Request-Id"]
print(store)
except:
pass
|
[
"mj31508@gmail.com"
] |
mj31508@gmail.com
|
0a086ba5ffae00e39e59426d3cc287e047cf73a7
|
4d71eb6075ac388a67370fddc1ae0579575b304f
|
/examples/ssd/train_multi.py
|
8fdd055743af395d22b217e7d335ca7d5e61771e
|
[
"MIT"
] |
permissive
|
apple2373/chainercv
|
1b4a6ad80648e848c7108e53fbb3e3fd44aa5c3e
|
1442eac6a316c31eab029c156b6d6e151553be2a
|
refs/heads/master
| 2020-03-18T20:53:21.473474
| 2018-05-28T09:37:14
| 2018-05-28T09:37:14
| 135,245,197
| 1
| 0
|
MIT
| 2018-05-29T05:27:15
| 2018-05-29T05:27:15
| null |
UTF-8
|
Python
| false
| false
| 5,279
|
py
|
import argparse
import multiprocessing
import numpy as np
import chainer
from chainer.optimizer_hooks import WeightDecay
from chainer import serializers
from chainer import training
from chainer.training import extensions
from chainer.training import triggers
import chainermn
from chainercv.chainer_experimental.datasets.sliceable \
import ConcatenatedDataset
from chainercv.chainer_experimental.datasets.sliceable import TransformDataset
from chainercv.datasets import voc_bbox_label_names
from chainercv.datasets import VOCBboxDataset
from chainercv.extensions import DetectionVOCEvaluator
from chainercv.links.model.ssd import GradientScaling
from chainercv.links.model.ssd import multibox_loss
from chainercv.links import SSD300
from chainercv.links import SSD512
from train import Transform
class MultiboxTrainChain(chainer.Chain):
def __init__(self, model, alpha=1, k=3, comm=None):
super(MultiboxTrainChain, self).__init__()
with self.init_scope():
self.model = model
self.alpha = alpha
self.k = k
self.comm = comm
def __call__(self, imgs, gt_mb_locs, gt_mb_labels):
mb_locs, mb_confs = self.model(imgs)
loc_loss, conf_loss = multibox_loss(
mb_locs, mb_confs, gt_mb_locs, gt_mb_labels, self.k, self.comm)
loss = loc_loss * self.alpha + conf_loss
chainer.reporter.report(
{'loss': loss, 'loss/loc': loc_loss, 'loss/conf': conf_loss},
self)
return loss
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--model', choices=('ssd300', 'ssd512'), default='ssd300')
parser.add_argument('--batchsize', type=int, default=32)
parser.add_argument('--test-batchsize', type=int, default=16)
parser.add_argument('--out', default='result')
parser.add_argument('--resume')
args = parser.parse_args()
comm = chainermn.create_communicator()
device = comm.intra_rank
if args.model == 'ssd300':
model = SSD300(
n_fg_class=len(voc_bbox_label_names),
pretrained_model='imagenet')
elif args.model == 'ssd512':
model = SSD512(
n_fg_class=len(voc_bbox_label_names),
pretrained_model='imagenet')
model.use_preset('evaluate')
train_chain = MultiboxTrainChain(model)
chainer.cuda.get_device_from_id(device).use()
model.to_gpu()
train = TransformDataset(
ConcatenatedDataset(
VOCBboxDataset(year='2007', split='trainval'),
VOCBboxDataset(year='2012', split='trainval')
),
('img', 'mb_loc', 'mb_label'),
Transform(model.coder, model.insize, model.mean))
if comm.rank == 0:
indices = np.arange(len(train))
else:
indices = None
indices = chainermn.scatter_dataset(indices, comm, shuffle=True)
train = train.slice[indices]
# http://chainermn.readthedocs.io/en/latest/tutorial/tips_faqs.html#using-multiprocessiterator
if hasattr(multiprocessing, 'set_start_method'):
multiprocessing.set_start_method('forkserver')
train_iter = chainer.iterators.MultiprocessIterator(
train, args.batchsize // comm.size, n_processes=2)
if comm.rank == 0:
test = VOCBboxDataset(
year='2007', split='test',
use_difficult=True, return_difficult=True)
test_iter = chainer.iterators.SerialIterator(
test, args.test_batchsize, repeat=False, shuffle=False)
# initial lr is set to 1e-3 by ExponentialShift
optimizer = chainermn.create_multi_node_optimizer(
chainer.optimizers.MomentumSGD(), comm)
optimizer.setup(train_chain)
for param in train_chain.params():
if param.name == 'b':
param.update_rule.add_hook(GradientScaling(2))
else:
param.update_rule.add_hook(WeightDecay(0.0005))
updater = training.updaters.StandardUpdater(
train_iter, optimizer, device=device)
trainer = training.Trainer(updater, (120000, 'iteration'), args.out)
trainer.extend(
extensions.ExponentialShift('lr', 0.1, init=1e-3),
trigger=triggers.ManualScheduleTrigger([80000, 100000], 'iteration'))
if comm.rank == 0:
trainer.extend(
DetectionVOCEvaluator(
test_iter, model, use_07_metric=True,
label_names=voc_bbox_label_names),
trigger=(10000, 'iteration'))
log_interval = 10, 'iteration'
trainer.extend(extensions.LogReport(trigger=log_interval))
trainer.extend(extensions.observe_lr(), trigger=log_interval)
trainer.extend(extensions.PrintReport(
['epoch', 'iteration', 'lr',
'main/loss', 'main/loss/loc', 'main/loss/conf',
'validation/main/map']),
trigger=log_interval)
trainer.extend(extensions.ProgressBar(update_interval=10))
trainer.extend(extensions.snapshot(), trigger=(10000, 'iteration'))
trainer.extend(
extensions.snapshot_object(
model, 'model_iter_{.updater.iteration}'),
trigger=(120000, 'iteration'))
if args.resume:
serializers.load_npz(args.resume, trainer)
trainer.run()
if __name__ == '__main__':
main()
|
[
"Hakuyume@users.noreply.github.com"
] |
Hakuyume@users.noreply.github.com
|
0f1b7cefd176b3539ee02af4cd1b8710084794b8
|
4e7797d520a68ded9bf77be555c13aff643389f1
|
/tests/test_helper.py
|
e448b376e57a6f296b955df3b01a3e0df4fcf3f7
|
[] |
no_license
|
JBorrow/seagen
|
654cf06b3191fbd00faaa313afb2822b7ea396f2
|
fb1dbc0736593cc2cd6364812e1fcc0fabe3eb32
|
refs/heads/master
| 2021-04-27T00:20:41.761132
| 2018-03-06T15:23:18
| 2018-03-06T15:23:18
| 123,797,126
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 743
|
py
|
"""
Tests the helper functions
"""
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d
from seagen.helper import polar_to_cartesian
def test_polar_to_cartesian():
"""
Tests the polar to cartesian conversion by ensuring
that r is conserved.
"""
phi = np.random.rand(1000) * np.pi
theta = np.random.rand(1000) * np.pi * 2
r = np.array([1])
x, y, z = polar_to_cartesian(r, theta, phi)
# Here we check if r is conserved!
new_r = np.sqrt(x*x + y*y + z*z)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection="3d")
plot = ax.scatter(x, y, z)
plt.savefig("test_polar_to_cartesian.png")
assert np.isclose(r, new_r, 1e-9).all()
|
[
"joshua.borrow@durham.ac.uk"
] |
joshua.borrow@durham.ac.uk
|
c594f78b733e395a7d369bd262c7cea585fbe150
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03705/s081733428.py
|
98e064ca6f0ef5b9a31b74e618de42bb0a8fbdba
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 150
|
py
|
N, A, B = map(int,input().split())
min = A * (N - 1) + B
max = B * (N - 1) + A
if (max - min) + 1 < 0:
print("0")
else:
print((max - min) + 1)
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
7c0e2ffee816a35c2d057419a714c80b1ebecc75
|
f06cf7cf7fe12a50f45edbd56b20acfc28606a44
|
/Linked List/intersection_point_in_list.py
|
83f9cde211bce58dc409bc7e8d8650e0d63b775f
|
[] |
no_license
|
prashant97sikarwar/data-structure-and-algorithms
|
53e016e50cf2ba26d2504f5a5f1ba39ca35f13f4
|
3ebe367c96a7bd82a427fc2beb7c8edd37247de7
|
refs/heads/master
| 2023-01-18T16:15:44.935431
| 2020-11-22T14:59:54
| 2020-11-22T14:59:54
| 257,667,068
| 0
| 0
| null | 2020-10-02T09:59:27
| 2020-04-21T17:32:43
|
Python
|
UTF-8
|
Python
| false
| false
| 456
|
py
|
class node:
def __init__(self,val):
self.next = None
self.data = val
def intersetPoint(head_a,head_b):
curr = head_a
purr = head_b
while curr is not None:
curr.data = curr.data - 1001
curr = curr.next
ans = -1
while purr is not None:
if purr.data >= 0:
purr = purr.next
else:
purr.data = purr.data + 1001
ans = purr
break
return ans
|
[
"prashant97sikarwar@gmail.com"
] |
prashant97sikarwar@gmail.com
|
a4d69b5d3d6747f313209a1534539033e0d26edf
|
268568ff2d483f39de78a5b29d941ce499cace33
|
/spyder/plugins/editor/__init__.py
|
837acce64e0e7f40a42373fee3222e97d7416db5
|
[
"MIT"
] |
permissive
|
MarkMoretto/spyder-master
|
61e7f8007144562978da9c6adecaa3022758c56f
|
5f8c64edc0bbd203a97607950b53a9fcec9d2f0b
|
refs/heads/master
| 2023-01-10T16:34:37.825886
| 2020-08-07T19:07:56
| 2020-08-07T19:07:56
| 285,901,914
| 2
| 1
|
MIT
| 2022-12-20T13:46:41
| 2020-08-07T19:03:37
|
Python
|
UTF-8
|
Python
| false
| false
| 394
|
py
|
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2009- Spyder Project Contributors
#
# Distributed under the terms of the MIT License
# (see spyder/__init__.py for details)
# -----------------------------------------------------------------------------
"""
spyder.plugins.editor
=====================
Editor Plugin.
"""
|
[
"mark.moretto@forcepoint.com"
] |
mark.moretto@forcepoint.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.