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
fe80c401762a5612c00a9b27ab5506e10ff205c4
9979e352e8d823dec905395c0a6cc2488643ee01
/setup.py
3ba4688cada1e343051c62eb477533290e1adab1
[ "MIT" ]
permissive
ixc/django-polymorphic-auth
41f3cf1c99938e307c994937f4fcee7fb697eeea
690c5e78846b328ca1b60bd0e099fe622d40892d
refs/heads/master
2021-08-12T05:02:09.894776
2021-08-10T08:43:09
2021-08-10T08:43:09
34,054,086
6
5
null
2017-03-27T11:21:00
2015-04-16T12:19:40
Python
UTF-8
Python
false
false
1,542
py
from __future__ import print_function import setuptools import sys # Convert README.md to reStructuredText. if {'bdist_wheel', 'sdist'}.intersection(sys.argv): try: import pypandoc except ImportError: print('WARNING: You should install `pypandoc` to convert `README.md` ' 'to reStructuredText to use as long description.', file=sys.stderr) else: print('Converting `README.md` to reStructuredText to use as long ' 'description.') long_description = pypandoc.convert('README.md', 'rst') setuptools.setup( name='django-polymorphic-auth', use_scm_version={'version_scheme': 'post-release'}, author='Interaction Consortium', author_email='studio@interaction.net.au', url='https://github.com/ixc/django-polymorphic-auth', description='Polymorphic user model with plugins for common options, plus ' 'abstract and mixin classes to create your own.', long_description=locals().get('long_description', ''), license='MIT', packages=setuptools.find_packages(), include_package_data=True, install_requires=[ 'Django', 'django-polymorphic', ], extras_require={ 'dev': [ 'ipdb', 'ipython', ], 'test': [ 'coverage', 'django-dynamic-fixture', 'django-nose', 'django-webtest', 'nose-progressive', 'WebTest', ], }, setup_requires=['setuptools_scm'], )
[ "real.human@mrmachine.net" ]
real.human@mrmachine.net
047af3c638c0799e259eb7a0f2cd21a6b047142e
694d57c3e512ce916269411b51adef23532420cd
/leetcode_review/292nim_game.py
6340cc3f2e071470d640c21b078b53bb3bfc6b4a
[]
no_license
clovery410/mycode
5541c3a99962d7949832a0859f18819f118edfba
e12025e754547d18d5bb50a9dbe5e725fd03fd9c
refs/heads/master
2021-05-16T02:46:47.996748
2017-05-10T23:43:50
2017-05-10T23:43:50
39,235,141
1
1
null
null
null
null
UTF-8
Python
false
false
697
py
class Solution(object): # solution1, recursive solution, but not right def canWinNim(self, n, cacahe = {}): if n <= 0: return False if n <= 3: return True if n in cache: return cache[n] res = False for i in xrange(1, 4): if not self.canWinNim(n - i): res = True break cache[n] = res return res # solution2, use math trick, since if you are fall into 4 stones, you will absolutely lose.. so just check whether the number is a multiple of 4 def canWinNim2(self, n): if n % 4 == 0: return False return True
[ "seasoul410@gmail.com" ]
seasoul410@gmail.com
c53bc07c90f655c8c17449734bdd6286c1ea8898
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/ehyZvt6AJF4rKFfXT_19.py
4d40bc67e85b8aa828032f74be858e3060b838e7
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
726
py
""" Someone has attempted to censor my strings by replacing every vowel with a `*`, `l*k* th*s`. Luckily, I've been able to find the vowels that were removed. Given a censored string and a string of the censored vowels, return the original uncensored string. ### Example uncensor("Wh*r* d*d my v*w*ls g*?", "eeioeo") ➞ "Where did my vowels go?" uncensor("abcd", "") ➞ "abcd" uncensor("*PP*RC*S*", "UEAE") ➞ "UPPERCASE" ### Notes * The vowels are given in the correct order. * The number of vowels will match the number of `*` characters in the censored string. """ def uncensor(txt, vowels): for n in range(0,txt.count('*')): txt = txt.replace('*', vowels[n], 1) return txt
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
59a12bfbbecf0027560e12271513c1ee8de92ada
56b36ddf920b5f43e922cb84e8f420f1ad91a889
/Leetcode/Leetcode-Longest Common Prefix.py
9820848a27af5a14772e38c073f2718a3bc6f238
[]
no_license
chithien0909/Competitive-Programming
9ede2072e85d696ccf143118b17638bef9fdc07c
1262024a99b34547a3556c54427b86b243594e3c
refs/heads/master
2022-07-23T16:47:16.566430
2020-05-12T08:44:30
2020-05-12T08:44:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
675
py
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: s = "" l = len(strs) if strs == []: return "" if l == 1: return strs[0] if strs[0] == "": return "" for j in range(0, min(len(strs[0]), len(strs[1]))): if strs[0][j] == strs[1][j]: s += strs[0][j] else: break for i in range(2, l): if s in strs[i] and strs[i].index(s) == 0: continue s = s[:-1] while s not in strs[i] or strs[i].index(s) != 0: if s == "" : return "" s = s[:-1] return s
[ "ntle1@pipeline.sbcc.edu" ]
ntle1@pipeline.sbcc.edu
32c08699894dee750fa8a1522197162dd670a0ab
5a52ccea88f90dd4f1acc2819997fce0dd5ffb7d
/alipay/aop/api/domain/ActivityDiscountVoucher.py
a78120116e8b61444048e09435bd6c059aa4c491
[ "Apache-2.0" ]
permissive
alipay/alipay-sdk-python-all
8bd20882852ffeb70a6e929038bf88ff1d1eff1c
1fad300587c9e7e099747305ba9077d4cd7afde9
refs/heads/master
2023-08-27T21:35:01.778771
2023-08-23T07:12:26
2023-08-23T07:12:26
133,338,689
247
70
Apache-2.0
2023-04-25T04:54:02
2018-05-14T09:40:54
Python
UTF-8
Python
false
false
3,004
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class ActivityDiscountVoucher(object): def __init__(self): self._ceiling_amount = None self._discount = None self._floor_amount = None self._goods_name = None self._origin_amount = None @property def ceiling_amount(self): return self._ceiling_amount @ceiling_amount.setter def ceiling_amount(self, value): self._ceiling_amount = value @property def discount(self): return self._discount @discount.setter def discount(self, value): self._discount = value @property def floor_amount(self): return self._floor_amount @floor_amount.setter def floor_amount(self, value): self._floor_amount = value @property def goods_name(self): return self._goods_name @goods_name.setter def goods_name(self, value): self._goods_name = value @property def origin_amount(self): return self._origin_amount @origin_amount.setter def origin_amount(self, value): self._origin_amount = value def to_alipay_dict(self): params = dict() if self.ceiling_amount: if hasattr(self.ceiling_amount, 'to_alipay_dict'): params['ceiling_amount'] = self.ceiling_amount.to_alipay_dict() else: params['ceiling_amount'] = self.ceiling_amount if self.discount: if hasattr(self.discount, 'to_alipay_dict'): params['discount'] = self.discount.to_alipay_dict() else: params['discount'] = self.discount if self.floor_amount: if hasattr(self.floor_amount, 'to_alipay_dict'): params['floor_amount'] = self.floor_amount.to_alipay_dict() else: params['floor_amount'] = self.floor_amount if self.goods_name: if hasattr(self.goods_name, 'to_alipay_dict'): params['goods_name'] = self.goods_name.to_alipay_dict() else: params['goods_name'] = self.goods_name if self.origin_amount: if hasattr(self.origin_amount, 'to_alipay_dict'): params['origin_amount'] = self.origin_amount.to_alipay_dict() else: params['origin_amount'] = self.origin_amount return params @staticmethod def from_alipay_dict(d): if not d: return None o = ActivityDiscountVoucher() if 'ceiling_amount' in d: o.ceiling_amount = d['ceiling_amount'] if 'discount' in d: o.discount = d['discount'] if 'floor_amount' in d: o.floor_amount = d['floor_amount'] if 'goods_name' in d: o.goods_name = d['goods_name'] if 'origin_amount' in d: o.origin_amount = d['origin_amount'] return o
[ "jishupei.jsp@alibaba-inc.com" ]
jishupei.jsp@alibaba-inc.com
4b99b6d1673da8a70f3aa73976aa21a849dabad7
b637e53b36ad083575b161eaa8371f0cc11981a2
/apps/provincia/views.py
55a1aa707bfbd27a24ced0b9c850be99985ce008
[]
no_license
cienciometrico2017/cienciometrico2018v2.0
d7d014f858296aa262649696a4d3bfceb0b9afec
22e8800c921e8c4890c4f52c9826532364a99a68
refs/heads/master
2020-03-20T22:04:26.710351
2018-07-26T04:28:26
2018-07-26T04:28:26
137,777,699
0
0
null
null
null
null
UTF-8
Python
false
false
4,289
py
from django.shortcuts import render from django.core.urlresolvers import reverse_lazy from apps.provincia.form import ProvinciaForm from apps.provincia.models import provincia from django.views.generic import ListView, CreateView,UpdateView,DeleteView from apps.Investigador.models import Investigador from apps.roles.models import Rol from apps.pais.models import pais from apps.zona.models import zona # Create your views here. class ProvinciaList(ListView): model = provincia template_name = 'provincia/provincia_listar.html' paginate_by = 6 def get_context_data(self, **kwargs): context = super(ProvinciaList, self).get_context_data(**kwargs) usuario = self.request.user.id perfil = Investigador.objects.get(user_id=usuario) roles = perfil.roles.all() privi = [] privilegios = [] privilegio= [] for r in roles: privi.append(r.id) for p in privi: roles5 = Rol.objects.get(pk=p) priv = roles5.privilegios.all() for pr in priv: privilegios.append(pr.codename) for i in privilegios: if i not in privilegio: privilegio.append(i) context['usuario'] = privilegio return context class ProvinciaCreate(CreateView): model = provincia form_class = ProvinciaForm template_name = 'provincia/provincia_crear.html' success_url = reverse_lazy('provincia:provincia_listar') def get_context_data(self, **kwargs): context = super(ProvinciaCreate, self).get_context_data(**kwargs) Pais = pais.objects.all() Zona = zona.objects.all() usuario = self.request.user.id perfil = Investigador.objects.get(user_id=usuario) roles = perfil.roles.all() privi = [] privilegios = [] privilegio= [] for r in roles: privi.append(r.id) for p in privi: roles5 = Rol.objects.get(pk=p) priv = roles5.privilegios.all() for pr in priv: privilegios.append(pr.codename) for i in privilegios: if i not in privilegio: privilegio.append(i) context['usuario'] = privilegio context['Pais'] = Pais context['Zona'] = Zona return context class ProvinciaUpdate(UpdateView): model = provincia form_class = ProvinciaForm template_name = 'provincia/provincia_update.html' success_url = reverse_lazy('provincia:provincia_listar') def get_context_data(self, **kwargs): context = super(ProvinciaUpdate, self).get_context_data(**kwargs) Pais = pais.objects.all() Zona = zona.objects.all() usuario = self.request.user.id perfil = Investigador.objects.get(user_id=usuario) roles = perfil.roles.all() privi = [] privilegios = [] privilegio= [] for r in roles: privi.append(r.id) for p in privi: roles5 = Rol.objects.get(pk=p) priv = roles5.privilegios.all() for pr in priv: privilegios.append(pr.codename) for i in privilegios: if i not in privilegio: privilegio.append(i) context['usuario'] = privilegio context['Pais'] = Pais context['Zona'] = Zona return context class ProvinciaDelete(DeleteView): model = provincia template_name = 'provincia/provincia_delete.html' success_url = reverse_lazy('provincia:provincia_listar') def get_context_data(self, **kwargs): context = super(ProvinciaDelete, self).get_context_data(**kwargs) usuario = self.request.user.id perfil = Investigador.objects.get(user_id=usuario) roles = perfil.roles.all() privi = [] privilegios = [] privilegio= [] for r in roles: privi.append(r.id) for p in privi: roles5 = Rol.objects.get(pk=p) priv = roles5.privilegios.all() for pr in priv: privilegios.append(pr.codename) for i in privilegios: if i not in privilegio: privilegio.append(i) context['usuario'] = privilegio return context
[ "danilomoya19@gmail.com" ]
danilomoya19@gmail.com
7f15ab1953b900545b0e54e272e970176f2d68b9
652a173173380629e92e8b4f85b5ded0fdf2e4bf
/venv/bin/sqlformat
528a9371f9fe88d746bd7dced7c4272e82e4113c
[]
no_license
Jethet/udemycourse-producthunt-project
d28908162a64880ae761a0160905fe32e8157f12
8d1564efa2335817ad0d05c649447e290a7786e8
refs/heads/master
2023-04-04T05:42:00.962786
2021-04-21T15:03:53
2021-04-21T15:03:53
197,566,411
0
0
null
2021-04-20T18:23:50
2019-07-18T10:32:51
Python
UTF-8
Python
false
false
271
#!/Users/henriettehettinga/GitHub/producthunt_project/venv/bin/python3 # -*- coding: utf-8 -*- import re import sys from sqlparse.__main__ import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(main())
[ "henriette.hettinga@gmail.com" ]
henriette.hettinga@gmail.com
75cf96bd5078bb078561c71d9d602acf4f5bcce3
9af2312a1ea1abe1a9641b7ee578eb93828f8131
/TinySpider/01-bs4_test.py
8b19f2c2c105a2febc2a9d94afaaef28babf9d33
[]
no_license
Huangyan0804/Python
593df64fffe44822d38b3cab6f5ee7999802b8a9
6adcc342b658afcf805004b868ac0976b0fabed6
refs/heads/master
2020-06-04T13:27:56.235753
2020-02-20T15:13:31
2020-02-20T15:13:31
145,232,755
0
0
null
null
null
null
UTF-8
Python
false
false
242
py
#print(a, b, c, d, e, f, g) def work(x, a, b): if x == 0: return a + b else: return work(x - 1, a * 2, a) t = int(input()) for i in range(t): n = int(input()) ans = work(n, int(1), int(0)) print(ans)
[ "gg48@qq.com" ]
gg48@qq.com
6343453a9fd07a76c848dbceb689b069e62f8cd2
aaa204ad7f134b526593c785eaa739bff9fc4d2a
/tests/system/providers/airbyte/example_airbyte_trigger_job.py
c65df48a42ac826d5e6952344641a704118f592b
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
permissive
cfei18/incubator-airflow
913b40efa3d9f1fdfc5e299ce2693492c9a92dd4
ffb2078eb5546420864229cdc6ee361f89cab7bd
refs/heads/master
2022-09-28T14:44:04.250367
2022-09-19T16:50:23
2022-09-19T16:50:23
88,665,367
0
1
Apache-2.0
2021-02-05T16:29:42
2017-04-18T20:00:03
Python
UTF-8
Python
false
false
2,393
py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Example DAG demonstrating the usage of the AirbyteTriggerSyncOperator.""" from __future__ import annotations import os from datetime import datetime, timedelta from airflow import DAG from airflow.providers.airbyte.operators.airbyte import AirbyteTriggerSyncOperator from airflow.providers.airbyte.sensors.airbyte import AirbyteJobSensor ENV_ID = os.environ.get("SYSTEM_TESTS_ENV_ID") DAG_ID = "example_airbyte_operator" CONN_ID = '15bc3800-82e4-48c3-a32d-620661273f28' with DAG( dag_id=DAG_ID, schedule=None, start_date=datetime(2021, 1, 1), dagrun_timeout=timedelta(minutes=60), tags=['example'], catchup=False, ) as dag: # [START howto_operator_airbyte_synchronous] sync_source_destination = AirbyteTriggerSyncOperator( task_id='airbyte_sync_source_dest_example', connection_id=CONN_ID, ) # [END howto_operator_airbyte_synchronous] # [START howto_operator_airbyte_asynchronous] async_source_destination = AirbyteTriggerSyncOperator( task_id='airbyte_async_source_dest_example', connection_id=CONN_ID, asynchronous=True, ) airbyte_sensor = AirbyteJobSensor( task_id='airbyte_sensor_source_dest_example', airbyte_job_id=async_source_destination.output, ) # [END howto_operator_airbyte_asynchronous] # Task dependency created via `XComArgs`: # async_source_destination >> airbyte_sensor from tests.system.utils import get_test_run # noqa: E402 # Needed to run the example DAG with pytest (see: tests/system/README.md#run_via_pytest) test_run = get_test_run(dag)
[ "noreply@github.com" ]
cfei18.noreply@github.com
9255ed7704219f5c9d9b65a22bcc4967c6e1f444
196f7e3238f961fb5eba7a794f0b0c75d7c30ba1
/Python编程从入门到实践3.6/c14/test14/ship.py
5b286547c1a1424e828a4a64df2276be4b6bc83b
[]
no_license
Liaoyingjie/Pythonlearn
d0b1b95110017af7e063813660e52c61a6333575
8bca069f38a60719acac5aa39bd347f90ab0bfb1
refs/heads/master
2020-04-08T07:35:07.357487
2018-04-12T16:44:43
2018-04-12T16:44:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,525
py
import pygame from pygame.sprite import Sprite class Ship(Sprite): #1264加入ai_settings 来控制加入的 速度 def __init__(self,ai_settings,screen): """初始化飞船且设置启动初始位置""" super(Ship,self).__init__() self.screen = screen self.ai_settings = ai_settings # 加载飞船且获取其外接矩形 self.image = pygame.image.load('../images/ship.bmp') self.rect = self.image.get_rect() self.screen_rect =self.screen.get_rect() #放每个船在中间 和最底部 #如果这2条 都注释 就会直接到最左上角 为原点 0 0 self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom #Ship类的方法 接2个参数 SCREEN决定 飞船飞到什么地方 #加载pygame.image.load 得到这个飞船的surface 存储到image #image.get_rect得到了相应元素的rect对象 #rect 对象可以 上下左右来定位 bottom center #在pygame 原点在屏幕左上角, 右下角坐标值 慢慢增大 1200*800中 右下角坐标(1200,800) #在飞机 属性 center 中存储最小值 rect.centerx只能 存储 整数值 self.center = float(self.rect.centerx) #移动标志 #加入 2个 是左右的移动 self.moving_right = False self.moving_left = False def update(self): """根据移动标志 调整飞船的位置""" """按住右键 不放 就一直 向右进行移动""" #不是一直 按住 就是 按一下走 一下 """设置距离限制 超过范围不动了""" # Update the ship's center value, not the rect. if self.moving_right and self.rect.right < self.screen_rect.right: self.center += self.ai_settings.ship_speed_factor if self.moving_left and self.rect.left > 0: self.center -= self.ai_settings.ship_speed_factor # Update rect object from self.center. self.rect.centerx = self.center #更新rect对象 更新到最新的值 速度 self.rect.centerx = self.center def blitme(self): """在指定位置绘制船""" self.screen.blit(self.image, self.rect) def center_ship(self): #在屏幕上 飞机上居中 self.center = self.screen_rect.centerx
[ "godzoco@qq.com" ]
godzoco@qq.com
291e75936bd0c64c644451a8afeba47c13a350cb
6de40caa30577bdf7cc8d788781fd2622588cf1d
/w4/examples/shelter-demo/shelter/urls.py
7b7d8917340a2492154f386c1929a45e63b629cc
[]
no_license
momentum-cohort-2019-02/kb
ca42d4ff61a4cf08efb89bf0502788bd0eb7b648
ad8318712349600f6ab13c2a0a92a65b3ae04677
refs/heads/master
2020-04-21T13:05:52.246012
2019-04-17T14:17:39
2019-04-17T14:17:42
169,587,008
4
13
null
null
null
null
UTF-8
Python
false
false
982
py
"""shelter URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from django.conf.urls.static import static from django.conf import settings from core import views as core_views urlpatterns = [ path('admin/', admin.site.urls), path('', core_views.index_view, name="index"), ] + static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
[ "clinton@dreisbach.us" ]
clinton@dreisbach.us
0ed744a294fa836def27d2717433779dc3f9dd53
0ad2458c85ce545b1d3a4b75dabe2c94ed8c2518
/pipeline/0x02-databases/32-update_topics.py
f0deec04f31ea17769b5ba4aaa8d63a85baf3b7f
[]
no_license
felipeserna/holbertonschool-machine_learning
fc82eda9ee4cb8765ad0ffb5fa923407b200480d
161e33b23d398d7d01ad0d7740b78dda3f27e787
refs/heads/master
2023-07-06T20:26:12.892875
2021-08-17T17:03:30
2021-08-17T17:03:30
317,288,341
0
1
null
null
null
null
UTF-8
Python
false
false
285
py
#!/usr/bin/env python3 """ Changes all topics of a school document based on the name """ def update_topics(mongo_collection, name, topics): """ Return: Nothing """ new_topics = {"$set": {"topics": topics}} mongo_collection.update_many({"name": name}, new_topics)
[ "feserna86@gmail.com" ]
feserna86@gmail.com
cf1c2910de8bd2db6d9e04af294d65f29c8da0d7
58d3a6720cd6ecc420db58de002f776f717ae77f
/Array/SplitAndAppend.py
a2d6da570b537d9edcc9c166b8d9888f4c379d5b
[]
no_license
Jaydeep-07/Python-Practice
786a4763caf0c7e9b1cf7ac6773c0ba3ccbc0d12
1aec7648fa47c7cd325d3f0f466ba440a3ec1808
refs/heads/master
2020-12-29T15:53:55.954878
2020-05-09T09:34:10
2020-05-09T09:34:10
238,659,815
0
0
null
null
null
null
UTF-8
Python
false
false
350
py
# Python program to split array and move first # part to end. def splitArr(arr, n, k): for i in range(0, k): x = arr[0] for j in range(0, n-1): arr[j] = arr[j + 1] arr[n-1] = x # main arr = [12, 10, 5, 6, 52, 36] n = len(arr) position = 2 splitArr(arr, n, position) for i in range(0, n): print(arr[i], end = ' ')
[ "jaydeepvpatil225@gmail.com" ]
jaydeepvpatil225@gmail.com
b23610d4ed2d962655cbb3f9d94c100c44194741
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/2t6NvMe27HtSmqC4F_16.py
72db51f2e725cbf6c80b069f070630cf0775452d
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
1,275
py
""" Write three functions: 1. boolean_and 2. boolean_or 3. boolean_xor These functions should evaluate a list of `True` and `False` values, starting from the leftmost element and evaluating pairwise. ### Examples boolean_and([True, True, False, True]) ➞ False # [True, True, False, True] => [True, False, True] => [False, True] => False boolean_or([True, True, False, False]) ➞ True # [True, True, False, True] => [True, False, False] => [True, False] => True boolean_xor([True, True, False, False]) ➞ False # [True, True, False, False] => [False, False, False] => [False, False] => False ### Notes * `XOR` is the same as `OR`, except that it excludes `[True, True]`. * Each time you evaluate an element at 0 and at 1, you collapse it into the single result. """ def boolean_and(lst): if False in lst: return False else: return True ​ def boolean_or(lst): if True in lst: return True else: return False def boolean_xor(lst): ret=lst[0] for x in range(1,len(lst)): if lst[x]==True: if ret==True: ret=False else: ret=True elif lst[x]==False: if ret==False: ret=False else: ret=True else: ret=True return ret
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
c94460f1f5fd13eedaf09959bd0a26cad54b92a0
b3a77d07f852bc865524120d9b3c40c691aa62b5
/slguerbetal/spiders/slguerbetal.py
99c0aa2792feb87f8a55d47a41a5df80777e0bb2
[]
no_license
daniel-kanchev/slguerbetal
0a6eb2efb5701a1f86556b75ae833dc90b4cc653
2984ce5983c92b809cdb173bae14ef0b179078a8
refs/heads/main
2023-03-11T19:32:12.199529
2021-03-01T09:35:41
2021-03-01T09:35:41
343,361,118
0
0
null
null
null
null
UTF-8
Python
false
false
876
py
import scrapy from scrapy.loader import ItemLoader from itemloaders.processors import TakeFirst from datetime import datetime from slguerbetal.items import Article class SlguerbetalSpider(scrapy.Spider): name = 'slguerbetal' start_urls = ['https://www.slguerbetal.ch/de/'] def parse(self, response): articles = response.xpath('//article') for article in articles: item = ItemLoader(Article()) item.default_output_processor = TakeFirst() title = article.xpath('./h2//text()').get() content = article.xpath('./div[@class="long-text"]//text()').getall() content = [text for text in content if text.strip()] content = "\n".join(content).strip() item.add_value('title', title) item.add_value('content', content) yield item.load_item()
[ "daniel.kanchev@adata.pro" ]
daniel.kanchev@adata.pro
5b8ae701bdf1cbe048386291f6f3f6a2a33c0e76
3d54d60973f88e0ed1f6be1a03ca6c5fbd0d3244
/examples/dfp/v201403/label_service/get_all_labels.py
047731e06eb7e60616f2b8b70a2fb40be4e3721e
[ "Apache-2.0" ]
permissive
zyqkenmy/googleads-python-lib
52a4f9ef9eef0da9410c9c90322186bb7a8e408f
fb7d3c2c7c42cc1fc27a3d2bf97382e25f6a05c2
refs/heads/master
2020-02-26T13:55:31.186467
2014-03-13T20:51:33
2014-03-13T20:51:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,711
py
#!/usr/bin/python # # 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. """This code example gets all labels. To create labels, run create_labels.py. This feature is only available to DFP premium solution networks.""" __author__ = ('Nicholas Chen', 'Joseph DiLallo') # Import appropriate classes from the client library. from googleads import dfp def main(client): # Initialize appropriate service. label_service = client.GetService('LabelService', version='v201403') # Create statement to get all labels statement = dfp.FilterStatement() # Get labels by statement. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) if 'results' in response: # Display results. for label in response['results']: print ('Label with id \'%s\' and name \'%s\' was found.' % (label['id'], label['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() main(dfp_client)
[ "api.jdilallo@gmail.com" ]
api.jdilallo@gmail.com
1c7b100b3994b57253d8a6156e045b977b28db37
25160eef36f911322c3b24c3e587d66c54cdf6a8
/iconset.py
934495bad32bac2b01f3fb5a8aa2e33f889fcb48
[]
no_license
asmikush111/september
7c8dd200cded9616e10f1e93b6aebe82b07e2196
8f058d10f5781b420d1a78df10c30a5eea01bedd
refs/heads/master
2020-09-05T15:28:56.310270
2019-11-05T09:56:09
2019-11-05T09:56:09
220,144,047
1
0
null
2019-11-07T03:31:06
2019-11-07T03:31:06
null
UTF-8
Python
false
false
167
py
from tkinter import * root=Tk() root.title("My Notepad") #title name root.wm_iconbitmap("notepad.ico") #to add icon mainloop()
[ "aswanibtech@gmail.com" ]
aswanibtech@gmail.com
d6370ed3821e8c3d3368fa8e7d799b6439b64044
65113128c2bd0bfe05db1c75776cee7a22ea98fd
/deadcode/firstmodel.py
583cbfe07d4db227a5311b3463e3df2471a52c7d
[]
no_license
taygrave/salad_tool
32a539f2fba3e9478d1277d5ec5d763e2defc4ce
fa01b3ac74ea41a21e7256552f3a1e4c1c6eebb0
refs/heads/master
2021-01-13T14:04:46.272323
2015-02-18T06:16:46
2015-02-18T06:16:46
30,062,177
0
0
null
null
null
null
UTF-8
Python
false
false
2,385
py
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine from sqlalchemy import Column, Integer, String, DateTime, ForeignKey from sqlalchemy.orm import sessionmaker, scoped_session, relationship, backref import sqlite3 import csv Base = declarative_base() ENGINE = create_engine("sqlite:///saladtool.db", echo=True) Session = sessionmaker(bind=ENGINE) session = Session() #process the file and build the necessary dictionaries #searching: I live in X state, the time frame is X, I want X# of X types of food. CONN = sqlite3.connect("saladtool.db") CURSOR = CONN.cursor() #Use this for one time adds to db of all foods once scraped new data from web: http://www.sustainabletable.org/seasonalguide/seasonalfoodguide.php def add_to_db(sfile): """Adds new data file to database in the Master table""" #sfile = "db.txt" for current data #making connection with SQL database query = """INSERT INTO Master (name, type, season, state) VALUES (?,?,?,?)""" #data file must be text with four columns, for name, type, season, and state for line in sfile: my_list = line.strip().split(",") vname, vtype, vseason, vstate = my_list CURSOR.execute(query, (vname, vtype, vseason, vstate)) CONN.commit() print "Successfully added %s to Master table in saladtool.db" %sfile #Already used for a one-time add to db for list of states def states_to_db(): """Adds new data file to database in the States table""" #making connection with SQL database query = """INSERT INTO States (abbrv, state) VALUES (?,?)""" with open("states.csv", 'rb') as src_file: reader = csv.reader(src_file) for line in reader: state, abbrv = line CURSOR.execute(query, (abbrv, state)) CONN.commit() print "Successfully added states to States table in saladtool.db" #Q: Did i really have to create a class? cant I return these values better?? Was getting an error if i just returned the result of the following function w/o making a whole class and everything class State(object): """A wrapper that corresponds to rows in the States table""" def __init__(self, abbrv, state): self.abbrv = abbrv self.state = state def __repr__(self): return "<State: %s, %s>" %(self.abbrv, self.state) class Food(Base):
[ "info@hackbrightacademy.com" ]
info@hackbrightacademy.com
afa158c4929e3a0b8fa19183e2b7492a385cb1dd
25491d1b0b69911885b2ad00e9c1ef880f946ae1
/env/render.py
211bbb52bc24adfd441c4fd98670392d65e62329
[ "MIT" ]
permissive
hzheng40/distributed_es
106fe87ad2918f77c8e1803117bd2208835b520f
5f447eb3fd1159c0754dfe14e92640df75a9cde7
refs/heads/master
2022-06-05T22:23:43.395821
2020-05-03T19:38:12
2020-05-03T19:38:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,084
py
import time from argparse import Namespace from pathlib import Path from typing import Optional import click from badger_utils.sacred import SacredReader from utils.eval import simulate, build_policy_env from utils.sacred_local import get_sacred_storage @click.command() @click.argument('exp_id', type=int) @click.option('--gen', default=None, help='Generation to be deserialized (the last one by default)') @click.option('--sleep', default=0.001, help='Sleep time between the time steps') @click.option('--num_episodes', default=None, type=int, help='Override num_episodes parameter?') @click.option('--max_ep_length', default=None, type=int, help='Override the max_episode_length?') def render(exp_id: int, gen: int, sleep: float, num_episodes: Optional[int], max_ep_length: Optional[int]): """Download a given config and policy from the sacred, run the inference""" # parse arguments, init the reader reader = SacredReader(exp_id, get_sacred_storage(), data_dir=Path.cwd()) # obtain the config config = Namespace(**reader.config) num_episodes = num_episodes if num_episodes is not None else config.num_episodes max_ep_length = max_ep_length if max_ep_length is not None else config.max_ep_length env_seed = config.env_seed if config.env_seed is not None else -1 policy, env = build_policy_env(config, env_seed) # deserialize the model parameters if gen is None: gen = reader.find_last_epoch() print(f'Deserialization from the epoch: {gen}') time.sleep(2) policy.load(reader=reader, epoch=gen) fitness, num_steps_used = simulate(env=env, policy=policy, num_episodes=num_episodes, max_ep_length=max_ep_length, render=True, sleep_render=sleep) print(f'\n\n Done, fitness is: {fitness}, num_steps: {num_steps_used}\n\n') if __name__ == '__main__': render()
[ "jaroslav.vitku@goodai.com" ]
jaroslav.vitku@goodai.com
b9b442f95e158d2656877533a5b3a77333c6ed88
48bab55feaa39d8de6f05adc4dda42eab49906c6
/06 Condições (Parte 2)/ex041.py
01666f2bf170e31ea93347c9866da9dd9e9ae133
[]
no_license
bmsrangel/Python_CeV
1850e7aa23892a78ba88e566862c75772fa5dcb9
f08e28b2f0dd444a2963e97f3ac2a024a6c5cd6f
refs/heads/master
2022-12-21T01:10:13.950249
2018-11-23T21:08:12
2018-11-23T21:08:12
150,914,095
0
1
null
2022-12-18T15:04:56
2018-09-30T00:32:08
Python
UTF-8
Python
false
false
396
py
from datetime import date ano = int(input('Informe seu ano de nascimento: ')) atual = date.today().year idade = atual - ano print('O atleta tem {} anos'.format(idade)) if idade <=9: print('Categoria MIRIM') elif idade <= 14: print('Categoria INFANTIL') elif idade <= 19: print('Categoria JÚNIOR') elif idade <= 25: print('Categoria SÊNIOR') else: print('Categoria MASTER')
[ "bmsrangel@hotmail.com" ]
bmsrangel@hotmail.com
da5d4a1feffa55183c27b747c21bfbf5719f647c
39a1d46fdf2acb22759774a027a09aa9d10103ba
/model-optimizer/extensions/front/HSigmoid_fusion.py
a898308d3a18042615ded67d8b969533938ff36e
[ "Apache-2.0" ]
permissive
mashoujiang/openvino
32c9c325ffe44f93a15e87305affd6099d40f3bc
bc3642538190a622265560be6d88096a18d8a842
refs/heads/master
2023-07-28T19:39:36.803623
2021-07-16T15:55:05
2021-07-16T15:55:05
355,786,209
1
3
Apache-2.0
2021-06-30T01:32:47
2021-04-08T06:22:16
C++
UTF-8
Python
false
false
7,183
py
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np from extensions.front.AttributedClampNormalizer import AttributedClampNormalizer from extensions.ops.activation_ops import HSigmoid from mo.front.common.replacement import FrontReplacementSubgraph from mo.front.subgraph_matcher import SubgraphMatch from mo.graph.graph import Graph, rename_nodes from mo.middle.pattern_match import check_value from mo.utils.graph import Node def replace_with_hsigmoid(graph: Graph, first_node: Node, last_node: Node): # determine the input port of first and last nodes which gets the 'input' node output add_input_port_idx = int(first_node.in_port(0).get_connection().get_source().node.soft_get('op') == 'Const') last_node_name = last_node.soft_get('name', last_node.id) hsigmoid = HSigmoid(graph, {}).create_node() hsigmoid.in_port(0).connect(first_node.in_port(add_input_port_idx).get_source()) last_node.out_port(0).get_connection().set_source(hsigmoid.out_port(0)) rename_nodes([(last_node, last_node_name + '/TBR'), (hsigmoid, last_node_name)]) class HSigmoidWithClamp(FrontReplacementSubgraph): """ The transformation looks for the pattern with ReLU6 (Clamp) defining the HSigmoid function: HSigmoid(x) = Relu6(x + 3.0) / 6.0. """ enabled = True def run_after(self): return [AttributedClampNormalizer] def pattern(self): return dict( nodes=[ ('input', dict()), ('add', dict(op='Add')), ('const_0', dict(op='Const', value=lambda v: check_value(v, lambda x: np.allclose(x, 0.0, atol=1e-6)))), ('const_3', dict(op='Const', value=lambda v: check_value(v, lambda x: np.allclose(x, 3.0, atol=1e-6)))), ('const_6', dict(op='Const', value=lambda v: check_value(v, lambda x: np.allclose(x, 6.0, atol=1e-6)))), ('const_1_6', dict(op='Const', value=lambda v: check_value(v, lambda x: np.allclose(x, 1.0 / 6.0, atol=1e-6)))), ('clamp', dict(op='Clamp')), ('mul_2', dict(op='Mul')), ], edges=[ ('input', 'add', {}), ('const_3', 'add', {}), ('add', 'clamp', {'in': 0}), ('const_0', 'clamp', {'in': 1}), ('const_6', 'clamp', {'in': 2}), ('clamp', 'mul_2', {}), ('const_1_6', 'mul_2', {}), ]) def replace_sub_graph(self, graph: Graph, match: [dict, SubgraphMatch]): replace_with_hsigmoid(graph, match['add'], match['mul_2']) class HSigmoidWithMinMax(FrontReplacementSubgraph): """ The transformation looks for the pattern with Min/Max defining the HSigmoid function: HSigmoid(x) = Min(Max(x + 3.0, 0), 6.0) / 6.0. """ enabled = True def run_after(self): return [AttributedClampNormalizer] def pattern(self): return dict( nodes=[ ('input', dict()), ('add', dict(op='Add')), ('const_0', dict(op='Const', value=lambda v: check_value(v, lambda x: np.allclose(x, 0.0, atol=1e-6)))), ('const_3', dict(op='Const', value=lambda v: check_value(v, lambda x: np.allclose(x, 3.0, atol=1e-6)))), ('const_6', dict(op='Const', value=lambda v: check_value(v, lambda x: np.allclose(x, 6.0, atol=1e-6)))), ('const_1_6', dict(op='Const', value=lambda v: check_value(v, lambda x: np.allclose(x, 1.0 / 6.0, atol=1e-6)))), ('max', dict(op='Maximum')), ('min', dict(op='Minimum')), ('mul_2', dict(op='Mul')), ], edges=[ ('input', 'add', {'out': 0}), ('const_3', 'add', {}), ('add', 'max', {}), ('const_0', 'max', {}), ('max', 'min', {}), ('const_6', 'min', {}), ('min', 'mul_2', {}), ('const_1_6', 'mul_2', {}), ]) def replace_sub_graph(self, graph: Graph, match: [dict, SubgraphMatch]): replace_with_hsigmoid(graph, match['add'], match['mul_2']) class HSigmoidWithReluDiv(FrontReplacementSubgraph): """ The transformation looks for the pattern with Relu/Div defining the HSigmoid function: HSigmoid(x) = Min(Relu(x + 3.0), 6.0) / 6.0 """ enabled = True def run_after(self): return [AttributedClampNormalizer] def pattern(self): return dict( nodes=[ ('input', dict()), ('add_const', dict(op='Const', value=lambda v: check_value(v, lambda x: np.allclose(x, 3.0, atol=1e-6)))), ('add', dict(op='Add')), ('relu', dict(op='ReLU')), ('min_const', dict(op='Const', value=lambda v: check_value(v, lambda x: np.allclose(x, 6.0, atol=1e-6)))), ('min', dict(op='Minimum')), ('div_const', dict(op='Const', value=lambda v: check_value(v, lambda x: np.allclose(x, 6.0, atol=1e-6)))), ('div', dict(op='Div')), ], edges=[ ('input', 'add', {'out': 0}), ('add_const', 'add', {}), ('add', 'relu', {}), ('relu', 'min', {}), ('min_const', 'min', {}), ('min', 'div', {}), ('div_const', 'div', {}), ]) def replace_sub_graph(self, graph: Graph, match: [dict, SubgraphMatch]): replace_with_hsigmoid(graph, match['add'], match['div']) class HSigmoidWithReluMul(FrontReplacementSubgraph): """ The transformation looks for the pattern with Relu/Mul defining the HSigmoid function: HSigmoid(x) = Min(Relu(x + 3.0), 6.0) * 1.0/6.0 """ enabled = True def run_after(self): return [AttributedClampNormalizer] def pattern(self): return dict( nodes=[ ('input', dict()), ('add_const', dict(op='Const', value=lambda v: check_value(v, lambda x: np.allclose(x, 3.0, atol=1e-6)))), ('add', dict(op='Add')), ('relu', dict(op='ReLU')), ('min_const', dict(op='Const', value=lambda v: check_value(v, lambda x: np.allclose(x, 6.0, atol=1e-6)))), ('min', dict(op='Minimum')), ('mul_const', dict(op='Const', value=lambda v: check_value(v, lambda x: np.allclose(x, 1.0 / 6.0, atol=1e-6)))), ('mul', dict(op='Mul')), ], edges=[ ('input', 'add', {'out': 0}), ('add_const', 'add', {}), ('add', 'relu', {}), ('relu', 'min', {}), ('min_const', 'min', {}), ('min', 'mul', {}), ('mul_const', 'mul', {}), ]) def replace_sub_graph(self, graph: Graph, match: [dict, SubgraphMatch]): replace_with_hsigmoid(graph, match['add'], match['mul'])
[ "noreply@github.com" ]
mashoujiang.noreply@github.com
942be96b750114306413fc70537498dc6516768b
eb0711915d6bba2f765f052736e33ac9a9a397a6
/HE0435/write_file/write_glee/cre_HE.py
8a049dec0fc04d6215094467d842b6c3b5c71ad7
[]
no_license
dartoon/GL_HostGalaxy
cd2166f273ae7e0397a7d2d39f760ab59e86f014
7469f1c1e640d176a75cc6e9497920e494ad656a
refs/heads/master
2016-08-11T13:27:17.545360
2016-04-07T19:04:57
2016-04-07T19:04:57
46,524,027
1
0
null
null
null
null
UTF-8
Python
false
false
909
py
import numpy as np file1 = open('../../pylens/HE1104.txt','r') para = np.loadtxt(file1) file1.close() #for i in range(0,len(para)): # print para[i] t=np.empty(10) for i in range(0,len(para)): t[0]=para[i,0]/6*0.13 t[1]=para[i,1]/6*0.13 t[2]=para[i,2]/6*0.13 t[3]=para[i,3] t[4]=para[i,4]/180*np.pi t[5]=para[i,5] t[6]=para[i,16]/6*0.13 t[7]=para[i,17] t[8]=para[i,18]/180*np.pi t[9]=para[i,19]/2 inn = open('HE').read() out = open('HE{0}'.format(i+1), 'w') replacements = {'d0_':str(t[0]), 'd1_':str(t[1]), 'd2_':str(t[2]), 'd3_':str(t[3]), 'd4_':str(t[4]), 'd5_':str(t[5]), 'd6_':str(t[6]), 'd7_':str(t[7]), 'd8_':str(t[8]), 'd9_':str(t[9])} #print replacements for j in replacements.keys() inn = inn.replace(j, replacements[j]) #print inn out.write(inn) out.close
[ "dingxuheng@mail.bnu.edu.cn" ]
dingxuheng@mail.bnu.edu.cn
f511d276f53a6a99d60aa772674abcbd95dfbdd2
656341483ae8abe8792942d26556fdd4ff5ca7a9
/ThriftAPI/gen_py_tmp/ShareSite/ncTShareSite-remote
0e4871e944bf763b963ec05cac4e9d552778344a
[]
no_license
GWenPeng/Apitest_framework
b57ded9be4ec896d4ba8e02e9135bc7c73d90034
ab922c82c2454a3397ddbf4cd0771067734e1111
refs/heads/master
2022-11-26T05:54:47.168062
2020-08-06T01:45:12
2020-08-06T01:45:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,156
#!/usr/bin/env python # # Autogenerated by Thrift Compiler (0.13.0) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py # import sys import pprint if sys.version_info[0] > 2: from urllib.parse import urlparse else: from urlparse import urlparse from thrift.transport import TTransport, TSocket, TSSLSocket, THttpClient from thrift.protocol.TBinaryProtocol import TBinaryProtocol from ShareSite import ncTShareSite from ShareSite.ttypes import * if len(sys.argv) <= 1 or sys.argv[1] == '--help': print('') print('Usage: ' + sys.argv[0] + ' [-h host[:port]] [-u url] [-f[ramed]] [-s[sl]] [-novalidate] [-ca_certs certs] [-keyfile keyfile] [-certfile certfile] function [arg1 [arg2...]]') print('') print('Functions:') print(' void SetMultSiteStatus(bool status)') print(' bool GetMultSiteStatus()') print(' ncTSiteInfo GetLocalSiteInfo()') print(' void AddSite(ncTAddSiteParam paramInfo)') print(' void DeleteSite(string siteID)') print(' void EditSite(ncTEditSiteParam paramInfo)') print(' GetSiteInfo()') print(' ncTSiteInfo NodifySiteAddBegin()') print(' void NodifySiteAdd(string masterIp)') print(' void NodifySiteDelete()') print(' ncTSiteInfo GetLocalSiteInfoByRemote()') print(' void UpdateHeartByMaster(string siteId)') print(' void SyncSlaveToMaster(string data)') print(' void SyncMasterToSlave(string data)') print(' void UpdateSiteIp(string ip)') print(' ncTSiteInfo GetSiteInfoById(string siteid)') print(' void CheckSign(string expired, string sign, string site_id, bool flag)') print(' void RestartServer(string server_name)') print(' void UpdateEVFSSiteInfo()') print(' void CreateCrossDomainXml()') print(' void UpdateSiteMasterDbIp(string ip)') print(' void SyncOSSInfo(string data)') print(' void UpdateSiteVirusStatus(bool Status)') print(' void UpdateAllSiteVirusStatus(bool Status)') print(' bool GetSiteVirusStatus()') print('') sys.exit(0) pp = pprint.PrettyPrinter(indent=2) host = 'localhost' port = 9090 uri = '' framed = False ssl = False validate = True ca_certs = None keyfile = None certfile = None http = False argi = 1 if sys.argv[argi] == '-h': parts = sys.argv[argi + 1].split(':') host = parts[0] if len(parts) > 1: port = int(parts[1]) argi += 2 if sys.argv[argi] == '-u': url = urlparse(sys.argv[argi + 1]) parts = url[1].split(':') host = parts[0] if len(parts) > 1: port = int(parts[1]) else: port = 80 uri = url[2] if url[4]: uri += '?%s' % url[4] http = True argi += 2 if sys.argv[argi] == '-f' or sys.argv[argi] == '-framed': framed = True argi += 1 if sys.argv[argi] == '-s' or sys.argv[argi] == '-ssl': ssl = True argi += 1 if sys.argv[argi] == '-novalidate': validate = False argi += 1 if sys.argv[argi] == '-ca_certs': ca_certs = sys.argv[argi+1] argi += 2 if sys.argv[argi] == '-keyfile': keyfile = sys.argv[argi+1] argi += 2 if sys.argv[argi] == '-certfile': certfile = sys.argv[argi+1] argi += 2 cmd = sys.argv[argi] args = sys.argv[argi + 1:] if http: transport = THttpClient.THttpClient(host, port, uri) else: if ssl: socket = TSSLSocket.TSSLSocket(host, port, validate=validate, ca_certs=ca_certs, keyfile=keyfile, certfile=certfile) else: socket = TSocket.TSocket(host, port) if framed: transport = TTransport.TFramedTransport(socket) else: transport = TTransport.TBufferedTransport(socket) protocol = TBinaryProtocol(transport) client = ncTShareSite.Client(protocol) transport.open() if cmd == 'SetMultSiteStatus': if len(args) != 1: print('SetMultSiteStatus requires 1 args') sys.exit(1) pp.pprint(client.SetMultSiteStatus(eval(args[0]),)) elif cmd == 'GetMultSiteStatus': if len(args) != 0: print('GetMultSiteStatus requires 0 args') sys.exit(1) pp.pprint(client.GetMultSiteStatus()) elif cmd == 'GetLocalSiteInfo': if len(args) != 0: print('GetLocalSiteInfo requires 0 args') sys.exit(1) pp.pprint(client.GetLocalSiteInfo()) elif cmd == 'AddSite': if len(args) != 1: print('AddSite requires 1 args') sys.exit(1) pp.pprint(client.AddSite(eval(args[0]),)) elif cmd == 'DeleteSite': if len(args) != 1: print('DeleteSite requires 1 args') sys.exit(1) pp.pprint(client.DeleteSite(args[0],)) elif cmd == 'EditSite': if len(args) != 1: print('EditSite requires 1 args') sys.exit(1) pp.pprint(client.EditSite(eval(args[0]),)) elif cmd == 'GetSiteInfo': if len(args) != 0: print('GetSiteInfo requires 0 args') sys.exit(1) pp.pprint(client.GetSiteInfo()) elif cmd == 'NodifySiteAddBegin': if len(args) != 0: print('NodifySiteAddBegin requires 0 args') sys.exit(1) pp.pprint(client.NodifySiteAddBegin()) elif cmd == 'NodifySiteAdd': if len(args) != 1: print('NodifySiteAdd requires 1 args') sys.exit(1) pp.pprint(client.NodifySiteAdd(args[0],)) elif cmd == 'NodifySiteDelete': if len(args) != 0: print('NodifySiteDelete requires 0 args') sys.exit(1) pp.pprint(client.NodifySiteDelete()) elif cmd == 'GetLocalSiteInfoByRemote': if len(args) != 0: print('GetLocalSiteInfoByRemote requires 0 args') sys.exit(1) pp.pprint(client.GetLocalSiteInfoByRemote()) elif cmd == 'UpdateHeartByMaster': if len(args) != 1: print('UpdateHeartByMaster requires 1 args') sys.exit(1) pp.pprint(client.UpdateHeartByMaster(args[0],)) elif cmd == 'SyncSlaveToMaster': if len(args) != 1: print('SyncSlaveToMaster requires 1 args') sys.exit(1) pp.pprint(client.SyncSlaveToMaster(args[0],)) elif cmd == 'SyncMasterToSlave': if len(args) != 1: print('SyncMasterToSlave requires 1 args') sys.exit(1) pp.pprint(client.SyncMasterToSlave(args[0],)) elif cmd == 'UpdateSiteIp': if len(args) != 1: print('UpdateSiteIp requires 1 args') sys.exit(1) pp.pprint(client.UpdateSiteIp(args[0],)) elif cmd == 'GetSiteInfoById': if len(args) != 1: print('GetSiteInfoById requires 1 args') sys.exit(1) pp.pprint(client.GetSiteInfoById(args[0],)) elif cmd == 'CheckSign': if len(args) != 4: print('CheckSign requires 4 args') sys.exit(1) pp.pprint(client.CheckSign(args[0], args[1], args[2], eval(args[3]),)) elif cmd == 'RestartServer': if len(args) != 1: print('RestartServer requires 1 args') sys.exit(1) pp.pprint(client.RestartServer(args[0],)) elif cmd == 'UpdateEVFSSiteInfo': if len(args) != 0: print('UpdateEVFSSiteInfo requires 0 args') sys.exit(1) pp.pprint(client.UpdateEVFSSiteInfo()) elif cmd == 'CreateCrossDomainXml': if len(args) != 0: print('CreateCrossDomainXml requires 0 args') sys.exit(1) pp.pprint(client.CreateCrossDomainXml()) elif cmd == 'UpdateSiteMasterDbIp': if len(args) != 1: print('UpdateSiteMasterDbIp requires 1 args') sys.exit(1) pp.pprint(client.UpdateSiteMasterDbIp(args[0],)) elif cmd == 'SyncOSSInfo': if len(args) != 1: print('SyncOSSInfo requires 1 args') sys.exit(1) pp.pprint(client.SyncOSSInfo(args[0],)) elif cmd == 'UpdateSiteVirusStatus': if len(args) != 1: print('UpdateSiteVirusStatus requires 1 args') sys.exit(1) pp.pprint(client.UpdateSiteVirusStatus(eval(args[0]),)) elif cmd == 'UpdateAllSiteVirusStatus': if len(args) != 1: print('UpdateAllSiteVirusStatus requires 1 args') sys.exit(1) pp.pprint(client.UpdateAllSiteVirusStatus(eval(args[0]),)) elif cmd == 'GetSiteVirusStatus': if len(args) != 0: print('GetSiteVirusStatus requires 0 args') sys.exit(1) pp.pprint(client.GetSiteVirusStatus()) else: print('Unrecognized method %s' % cmd) sys.exit(1) transport.close()
[ "gu.wenpeng@eisoo.com" ]
gu.wenpeng@eisoo.com
1ed68d4f010fc1efda84c9c1ab660821e4bb0cf4
9adc810b07f7172a7d0341f0b38088b4f5829cf4
/experiments/ashvin/icml2020/hand/pen/gaussian2/mpo1.py
7ac527427c0596b9005378a26a524b4c5ff45d13
[ "MIT" ]
permissive
Asap7772/railrl_evalsawyer
7ee9358b5277b9ddf2468f0c6d28beb92a5a0879
baba8ce634d32a48c7dfe4dc03b123e18e96e0a3
refs/heads/main
2023-05-29T10:00:50.126508
2021-06-18T03:08:12
2021-06-18T03:08:12
375,810,557
1
0
null
null
null
null
UTF-8
Python
false
false
3,737
py
""" AWR + SAC from demo experiment """ from rlkit.demos.source.dict_to_mdp_path_loader import DictToMDPPathLoader from rlkit.launchers.experiments.awac.awac_rl import experiment import rlkit.misc.hyperparameter as hyp from rlkit.launchers.arglauncher import run_variants from rlkit.torch.sac.policies import GaussianPolicy if __name__ == "__main__": variant = dict( num_epochs=1001, num_eval_steps_per_epoch=1000, num_trains_per_train_loop=1000, num_expl_steps_per_train_loop=1000, min_num_steps_before_training=1000, max_path_length=1000, batch_size=1024, replay_buffer_size=int(1E6), layer_size=256, policy_class=GaussianPolicy, policy_kwargs=dict( hidden_sizes=[256, 256, ], max_log_std=0, min_log_std=-4, ), algorithm="SAC", version="normal", collection_mode='batch', trainer_kwargs=dict( discount=0.99, soft_target_tau=5e-3, target_update_period=1, policy_lr=3E-4, qf_lr=3E-4, reward_scale=1, beta=1, use_automatic_entropy_tuning=True, alpha=0, compute_bc=True, bc_num_pretrain_steps=0, q_num_pretrain1_steps=0, q_num_pretrain2_steps=25000, policy_weight_decay=1e-4, bc_loss_type="mse", rl_weight=1.0, use_awr_update=True, use_reparam_update=True, reparam_weight=0.0, awr_weight=0.0, bc_weight=1.0, awr_use_mle_for_vf=False, awr_sample_actions=False, awr_min_q=False, ), num_exps_per_instance=1, region='us-west-2', path_loader_class=DictToMDPPathLoader, path_loader_kwargs=dict( obs_key="state_observation", demo_paths=[ dict( path="demos/icml2020/hand/pen2.npy", obs_dict=True, is_demo=True, ), dict( path="demos/icml2020/hand/pen_bc5.npy", obs_dict=False, is_demo=False, train_split=0.9, ), ], ), # logger_variant=dict( # tensorboard=True, # ), load_demos=True, pretrain_policy=True, pretrain_rl=True, # save_pretrained_algorithm=True, # snapshot_mode="all", ) search_space = { 'env': ["pen-v0", ], 'trainer_kwargs.bc_loss_type': ["mle"], 'trainer_kwargs.awr_loss_type': ["mle"], 'seedid': range(3), 'trainer_kwargs.beta': [50, 100, ], 'trainer_kwargs.use_automatic_entropy_tuning': [False], # 'policy_kwargs.max_log_std': [0, ], 'policy_kwargs.min_log_std': [-6, ], 'trainer_kwargs.reparam_weight': [0], 'trainer_kwargs.awr_weight': [1.0], 'trainer_kwargs.bc_weight': [0.0, ], 'trainer_kwargs.awr_use_mle_for_vf': [True, False], 'trainer_kwargs.awr_sample_actions': [True, False], 'trainer_kwargs.awr_min_q': [True, False], } sweeper = hyp.DeterministicHyperparameterSweeper( search_space, default_parameters=variant, ) variants = [] for variant in sweeper.iterate_hyperparameters(): trainer_kwargs = variant["trainer_kwargs"] if not (trainer_kwargs["reparam_weight"] == 0 and trainer_kwargs["awr_weight"] == 0 and trainer_kwargs["bc_weight"] == 0): variants.append(variant) run_variants(experiment, variants, run_id=0)
[ "alexanderkhazatsky@gmail.com" ]
alexanderkhazatsky@gmail.com
fdff8ee5169cf72046ed0e39b6a24863d1045a9b
49ba5356bdc5df7dd9803b56fe507c5164a90716
/integer-break/solution.py
856adbbae8712f49e4d57219672d2b09cd793fc3
[]
no_license
uxlsl/leetcode_practice
d80ad481c9d8ee71cce0f3c66e98446ced149635
d8ed762d1005975f0de4f07760c9671195621c88
refs/heads/master
2021-04-25T18:12:28.136504
2020-03-11T07:54:15
2020-03-11T07:54:15
121,472,384
0
0
null
null
null
null
UTF-8
Python
false
false
404
py
class Solution: def integerBreak(self, n): """ :type n: int :rtype: int """ record = {1: 1} for i in range(2, n + 1): record[i] = 1 for j in range(1, (i + 1) // 2 + 1): record[i] = max(record[i], record[j] * record[i - j], j * record[i - j], j * (i - j)) return record[n]
[ "songlin.lin@yunfangdata.com" ]
songlin.lin@yunfangdata.com
409eab8e92a731bec8c3fbce3195ffe60d53c1e0
9625c5665611a5a1e92fa8fbe230ede1154d5a49
/apps/messenger/migrations/0001_initial.py
c4ef6f5702b59c2470d2ec769a6bf7fa81872b28
[]
no_license
Alfredynho/Sistema-Venta-de-Motos
94a6ffcc45409faaea44f89389f89b6b1bfe0905
136b6d7c7cbcf4b5432212ae588d47a27fdcb348
refs/heads/master
2021-05-15T00:46:55.811827
2017-09-10T17:58:58
2017-09-10T17:58:58
103,049,391
0
1
null
null
null
null
UTF-8
Python
false
false
1,425
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-18 03:11 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='MessengerInfo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('messenger_id', models.CharField(blank=True, max_length=255, null=True, verbose_name='Messenger ID')), ('nombre', models.CharField(blank=True, max_length=150, null=True, verbose_name='Nombre')), ('apellido', models.CharField(blank=True, max_length=150, null=True, verbose_name='Apellido')), ('foto_perfil', models.CharField(blank=True, max_length=150, null=True, verbose_name='Foto de Perfil')), ('lugar', models.CharField(blank=True, max_length=150, null=True, verbose_name='Lugar')), ('zona_horaria', models.CharField(blank=True, max_length=150, null=True, verbose_name='Zona Horaria')), ('genero', models.CharField(blank=True, max_length=150, null=True, verbose_name='Género')), ], options={ 'verbose_name_plural': 'Usuarios', 'verbose_name': 'Usuario', }, ), ]
[ "callizayagutierrezalfredo@gmail.com" ]
callizayagutierrezalfredo@gmail.com
339af08ee79097195e0eb7a1db67191f4741fa12
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/nouns/_ringers.py
3df2b9591b997bead80abf3adb13ac12e6619cac
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
238
py
from xai.brain.wordbase.nouns._ringer import _RINGER #calss header class _RINGERS(_RINGER, ): def __init__(self,): _RINGER.__init__(self) self.name = "RINGERS" self.specie = 'nouns' self.basic = "ringer" self.jsondata = {}
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
6a99650619af2f11b218bb57ff7630a44898107d
2b4e133329a5ca1ee205b026a46606b027d3f205
/Customer/urls.py
b6181d44da1f0dcdfe16696339889e7b31696a9b
[]
no_license
wadeeat786486962/bladerscenter.github.io-
06884c5ad3e7b874ce761e21ab5c00c9ab74fcfc
410d11feb6bc1885e614069a7bc5007521cf982d
refs/heads/main
2023-06-16T04:24:23.697174
2021-07-11T18:05:14
2021-07-11T18:05:14
384,936,125
0
0
null
null
null
null
UTF-8
Python
false
false
695
py
from django.urls import path from Customer.middlewares.auth import customerPanel_middleware from Customer import views urlpatterns = [ path('', customerPanel_middleware(views.customer_panel), name='customerpanel'), path('updateprofile/', customerPanel_middleware(views.profile_update), name='updateprofile'), path('wish_list/<int:id>/', views.wish_list, name='wish_list'), path('comment/<int:id>/', views.comment, name='comment'), path('wished_product/', views.wished_product, name='wished_product'), path('delete_comment/<int:id>/', views.delete_comment, name='delete_comment'), path('delete_wish_pro/<int:id>/', views.delete_wish_pro, name='delete_wish_pro'), ]
[ "mohibullahsahi419@gmail.com" ]
mohibullahsahi419@gmail.com
c6cd354f3834b048d995b22a1bb692b27b4c369f
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02392/s151511346.py
c222535b5db3bdb72e93f3da95df73cef146eb98
[]
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
132
py
def max(a,b): if a>b : return a else : return b a,b,c = map(int,raw_input().split()) if a<b<c : print'Yes' else : print'No'
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
1663460b4eb0ad56f0fc55fcc2afd8b357ecfeaf
03969015ab882f4751dc0e91beeda1212babca48
/robot_code/nimbus_explore_latest/src/util.py
a613fc7360ddb8615a72a53e5182ee94064acb96
[]
no_license
lnairGT/Thesis_code
f3ad57f4344691227dcd128a741eb9c0e937738e
6f5dbfc2510272f294a0e9bb4273beceeacbff2a
refs/heads/master
2023-03-17T21:43:56.320553
2020-09-26T16:05:31
2020-09-26T16:05:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,965
py
import glob, csv, os import numpy as np import cPickle as pickle def loadScioDataset(pklFile='sciodata', csvFile='scio_allmaterials_clean', materialNames=[], objectNames=[]): saveFilename = os.path.join('data', pklFile + '.pkl') if os.path.isfile(saveFilename): with open(saveFilename, 'rb') as f: X, y_materials, y_objects, wavelengths = pickle.load(f) else: X = [] y_materials = [] y_objects = [] filename = os.path.join('data', csvFile + '.csv') wavelengthCount = 331 with open(filename, 'rb') as f: reader = csv.reader(f) for i, row in enumerate(reader): if i < 10 or i == 11: continue if i == 10: # Header row wavelengths = [float(r.strip().split('_')[-1].split()[0]) + 740.0 for r in row[10:wavelengthCount+10]] continue obj = row[3].strip() material = row[4].strip() if material not in materialNames: continue index = materialNames.index(material) if obj not in objectNames[index]: continue values = [float(v) for v in row[10:wavelengthCount+10]] X.append(values) y_materials.append(index) y_objects.append(obj) with open(saveFilename, 'wb') as f: pickle.dump([X, y_materials, y_objects, wavelengths], f, protocol=pickle.HIGHEST_PROTOCOL) return X, y_materials, y_objects, wavelengths def firstDeriv(x, wavelengths): # First derivative of measurements with respect to wavelength x = np.copy(x) for i, xx in enumerate(x): dx = np.zeros(xx.shape, np.float) dx[0:-1] = np.diff(xx)/np.diff(wavelengths) dx[-1] = (xx[-1] - xx[-2])/(wavelengths[-1] - wavelengths[-2]) x[i] = dx return x
[ "lnair3@gatech.edu" ]
lnair3@gatech.edu
f98be85338873b97927faa46962a5b3097b14fb0
706f239f0df4586221e6a7aac001626ab531c224
/src/client_libraries/python/dynamics/customerinsights/api/models/profile_store_state_info.py
8363b24f80a213b76cc14db8a208077e35435112
[ "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
Global19-atlassian-net/Dynamics365-CustomerInsights-Client-Libraries
9681d258c649b005a2379d32b23d374695a6fca4
0ce81ae25e97c3b8de12b97963a8c765c0248238
refs/heads/main
2023-02-28T20:39:33.622885
2021-02-09T23:34:38
2021-02-09T23:34:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,739
py
# coding=utf-8 # -------------------------------------------------------------------------- # 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 ProfileStoreStateInfo(Model): """Represents runtime profile store state. Variables are only populated by the server, and will be ignored when sending a request. :param ingestion_time: Gets the latest date of ingestion. :type ingestion_time: datetime :param primary_info: :type primary_info: ~dynamics.customerinsights.api.models.ProfileStoreCollectionInfo :param secondary_info: :type secondary_info: ~dynamics.customerinsights.api.models.ProfileStoreCollectionInfo :ivar instance_id: Gets the Customer Insights instance id associated with this object. :vartype instance_id: str """ _validation = { 'instance_id': {'readonly': True}, } _attribute_map = { 'ingestion_time': {'key': 'ingestionTime', 'type': 'iso-8601'}, 'primary_info': {'key': 'primaryInfo', 'type': 'ProfileStoreCollectionInfo'}, 'secondary_info': {'key': 'secondaryInfo', 'type': 'ProfileStoreCollectionInfo'}, 'instance_id': {'key': 'instanceId', 'type': 'str'}, } def __init__(self, **kwargs): super(ProfileStoreStateInfo, self).__init__(**kwargs) self.ingestion_time = kwargs.get('ingestion_time', None) self.primary_info = kwargs.get('primary_info', None) self.secondary_info = kwargs.get('secondary_info', None) self.instance_id = None
[ "michaelajohnston@mac.com" ]
michaelajohnston@mac.com
bba4672adc471b819e4d9197f3c29cdb216a6e34
9a0d178a9128b8b3f33334f10d65abc7c2d8ed6e
/main/backend/capstone_project/diary_app/serializers.py
b197945f9c1100880d3facd8c1126b98b7fcad34
[]
no_license
kookmin-sw/capstone-2021-5
b19917d3d9fe5d2edfd8ebea5745a2806414aff3
322a2cd5d79d8bfd639f60e015af5db5dd7bc4a1
refs/heads/master
2023-05-06T01:24:00.457598
2021-05-26T14:43:28
2021-05-26T14:43:28
329,216,184
0
9
null
2021-05-24T05:05:41
2021-01-13T06:35:50
JavaScript
UTF-8
Python
false
false
1,370
py
from rest_framework import serializers from .models import Diary from django.core.exceptions import ValidationError import datetime from analysis.models import Emotion class DiarySerializer(serializers.ModelSerializer): """ 검색 기록(SearchRecord) Serializer """ class Meta: model = Diary fields = "__all__" def validate(self, data): if self.context['request'].method != "PUT" and Diary.objects.filter(profile=self.context['request'].user, title=data['title']).exists() == True: # 만약 같은 계정의 project title이 중복되면 raise ValidationError('duplicated title') today = datetime.date.today() if self.context['request'].method != "PUT" and Diary.objects.filter(profile=self.context['request'].user, pubdate = today ).exists(): raise ValidationError('already written') if self.context['request'].method == "POST" and not Emotion.objects.filter(profile=self.context['request'].user,pubdate = today).exists(): raise ValidationError('not analyzed') data['pubdate'] = today data['weather'] = Emotion.objects.get(profile=self.context['request'].user,pubdate = today).weather data['profile'] = self.context['request'].user #project 생성시 항상 author을 해당 계정으로 설정 return data
[ "you@example.com" ]
you@example.com
4e5f0dedb9fbc134b5fe17d5f1d3d24006e690b5
93289539257faa129aa2d17a42148f7d73ce4e9e
/Python/2193_PinaryNumber.py
c969c707dd349552d942546aaeaa2892839f9462
[]
no_license
Manngold/baekjoon-practice
d015dd518144a75b5cb3d4e831d6c95a3c70544f
54f9efcb6460647c2a0f465731b582fe6de89cf3
refs/heads/master
2021-06-25T13:04:23.162531
2020-10-14T08:34:28
2020-10-14T08:34:28
148,895,003
0
0
null
null
null
null
UTF-8
Python
false
false
143
py
n = int(input()) dp = [1, 1, 2] if n <= 3: pass else: for i in range(3, n): dp.append(dp[i - 2] + dp[i - 1]) print(dp[n-1])
[ "jsw4820@gmail.com" ]
jsw4820@gmail.com
f17886fdaeaef31d2dbe43e3265a80c7adac1985
884923e1d3d3705688218838c6c669230ac308f3
/Py/1204.py
07359f911918a011634f6976e5195c109ae67268
[]
no_license
gimyoni/CodeUp
1c22fa1513706eef987b7d7d7ea965ee99c72a09
97728d8772ba2a19994ca68420093ffad3fd3552
refs/heads/master
2023-04-06T13:09:10.553671
2021-04-18T13:51:46
2021-04-18T13:51:46
268,708,520
0
0
null
null
null
null
UTF-8
Python
false
false
317
py
a = int(input()) if a % 10 == 1: if a == 11: print("11th") else: print(str(a)+"st") elif a%10 ==2: if a == 12: print("12th") else: print(str(a)+"nd") elif a%10==3: if a == 13: print("13th") else: print(str(a)+"rd") else: print(str(a)+"th")
[ "noreply@github.com" ]
gimyoni.noreply@github.com
b8be4bdb76e7984b8c8b1c0c457aa46965c52abe
50402cc4388dfee3a9dbe9e121ef217759ebdba8
/Proj/UR/GeneratePaths/WorldViz.py
43eb54e6bed1c69598e6490130d3c8d6f0bcc8a4
[]
no_license
dqyi11/SVNBackup
bd46a69ec55e3a4f981a9bca4c8340944d8d5886
9ad38e38453ef8539011cf4d9a9c0a363e668759
refs/heads/master
2020-03-26T12:15:01.155873
2015-12-10T01:11:36
2015-12-10T01:11:36
144,883,382
2
1
null
null
null
null
UTF-8
Python
false
false
4,188
py
''' Created on Jul 30, 2015 @author: daqing_yi ''' import pygame, sys from pygame.locals import * import numpy as np from Path import * BLUE = (0,0,255) RED = (255,0,0) BLACK = (0,0,0) GREEN = (0,255,0) class WorldViz(object): def __init__(self, world): self.world = world pygame.init() self.screen = pygame.display.set_mode((int(self.world.width),int(self.world.height))) pygame.display.set_caption(self.world.name) self.screen.fill((255,255,255)) self.myfont = pygame.font.SysFont("monospace", 15) self.colors = [] for obj in self.world.objects: color = (np.random.randint(0,255), np.random.randint(0,255), np.random.randint(0,255)) self.colors.append(color) def update(self): for event in pygame.event.get(): if event.type == pygame.QUIT: return False elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: pos = pygame.mouse.get_pos() print "LEFT " + str(pos) self.world.init = pos else: pos = pygame.mouse.get_pos() print "RIGHT " + str(pos) self.world.goal = pos self.screen.fill((255,255,255)) RADIUS = 10 RECT_WIDTH = 16 for i in range(len(self.world.objects)): obj = self.world.objects[i] if obj.type == "robot": pygame.draw.circle(self.screen, self.colors[i], obj.center, RADIUS) else: pygame.draw.rect(self.screen, self.colors[i], (obj.center[0]-RECT_WIDTH/2, obj.center[1]-RECT_WIDTH/2, RECT_WIDTH, RECT_WIDTH)) label = self.myfont.render(obj.type+"("+obj.name+")", 1, (0,0,0)) self.screen.blit(label, (obj.center[0], obj.center[1]+15)) #pygame.draw.line(self.screen, GREEN, [int(obj.bounding[0]), int(obj.center.y)], [int(obj.bounding[2]),int(obj.center.y)], 2) #pygame.draw.line(self.screen, GREEN, [int(obj.center.x), int(obj.bounding[1])], [int(obj.center.x), int(obj.bounding[3])], 2) if self.world.init != None: pygame.draw.circle(self.screen, BLUE, self.world.init, 10, 0) if self.world.goal != None: pygame.draw.circle(self.screen, RED, self.world.goal, 10, 0) pygame.display.flip() pygame.time.delay(100) return True def close(self): pygame.quit() def drawPath(self, path, filename, background=""): surface = pygame.Surface((self.world.width, self.world.height)) if background == "": surface.fill((255,255,255)) else: #surface.fill((255,255,255)) img = pygame.image.load(background) surface.blit( img, (0,0) ) RADIUS = 10 RECT_WIDTH = 16 for i in range(len(self.world.objects)): obj = self.world.objects[i] if obj.type == "robot": pygame.draw.circle(surface, self.colors[i], obj.center, RADIUS) else: pygame.draw.rect(surface, self.colors[i], (obj.center[0]-RECT_WIDTH/2, obj.center[1]-RECT_WIDTH/2, RECT_WIDTH, RECT_WIDTH)) label = self.myfont.render(obj.type+"("+obj.name+")", 1, (0,0,0)) surface.blit(label, (obj.center[0], obj.center[1]+15)) pathLen = len(path.waypoints) #print path.waypoints for i in range(pathLen-1): pygame.draw.line(surface, (0,0,0), path.waypoints[i], path.waypoints[i+1], 6) if self.world.init != None: pygame.draw.circle(surface, BLUE, self.world.init, 10, 0) if self.world.goal != None: pygame.draw.circle(surface, RED, self.world.goal, 10, 0) pygame.image.save(surface, filename)
[ "walter@e224401c-0ce2-47f2-81f6-2da1fe30fd39" ]
walter@e224401c-0ce2-47f2-81f6-2da1fe30fd39
0ed6c6a658a25b982fcb8c2eda5f65ceaa9e1362
b13a1a96e9f1dddb3a3a44b636ca939b85962899
/Django & REST API/testalpha/demo/migrations/0002_teacher.py
b5360168e5edd1473d8dae138f464eb7dc7ed5a3
[]
no_license
jspw/Django-Test
f266331c73c34b83b1189811a163567b6b4cc60b
13a6d0146c9c78f8fa03c269e4546b5bbdb146bd
refs/heads/master
2021-03-23T17:50:21.764636
2020-10-18T09:21:23
2020-10-18T09:21:23
247,472,132
5
0
null
null
null
null
UTF-8
Python
false
false
597
py
# Generated by Django 3.0.5 on 2020-04-20 15:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('demo', '0001_initial'), ] operations = [ migrations.CreateModel( name='Teacher', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ('dept', models.ManyToManyField(related_name='teacher', to='demo.Department')), ], ), ]
[ "mhshifat757@gmail.com" ]
mhshifat757@gmail.com
fd1991fd30ed9da80b1585f41314ee041ef41214
b7ee82768de54a83a99ad4ddd9e090c61935b86a
/paper/plot-subset-sites.py
3a1d9b3df807a72e6ed633d1d9138578707b7d98
[ "MIT" ]
permissive
brentp/somalier
5042ea9e7773a311c12825ac4ad8ee4140db2412
de50b1cfe1b859407b64ba3928cc4419f85c7403
refs/heads/master
2023-09-01T16:21:31.459237
2023-08-28T10:50:30
2023-08-28T10:50:30
143,888,326
228
32
MIT
2023-08-28T10:50:31
2018-08-07T14:52:04
Nim
UTF-8
Python
false
false
968
py
import pandas as pd from matplotlib import pyplot as plt import seaborn as sns import sys sns.set_palette("Set2") df = pd.read_csv(sys.argv[1], sep="\t") fig, axes = plt.subplots(1, 1, figsize=(8, 4)) try: axes[0] except (IndexError, TypeError): axes = (axes,) sns.barplot(x="n", y="fp", hue="strict", data=df, ax=axes[0]) axes[0].set_xlabel("Number of sites") axes[0].set_ylabel("False-positive rate") #sns.barplot(x="n", y="tp", hue="strict", data=df, ax=axes[1]) #axes[1].set_xlabel("Number of sites") #axes[1].set_ylabel("True-positive rate") plt.savefig("subset-sites.png") plt.show() """ n tp fp fn strict 10 0.816905 0.183080 0.000014 false 20 0.859777 0.140218 0.000005 false 40 0.925964 0.074012 0.000024 false 100 0.985616 0.014384 0.000000 false 200 0.997638 0.002362 0.000000 false 400 0.999724 0.000276 0.000000 false 1000 0.999986 0.000014 0.000000 false 2000 1.000000 0.000000 0.000000 false 4000 1.000000 0.000000 0.000000 false """
[ "bpederse@gmail.com" ]
bpederse@gmail.com
e47a79bfda7d1e46c14a365203b23e5a4e979f72
a5570cfad2697da8f95a65e0b8a7cc0697e71a2e
/12 Python Lists.py
c252cc40019ff24e9104e7a1ad7b53030b3577d7
[]
no_license
mukund7296/Python-Brushup
c4db1d43fe6a06742f00ec4f12affec4b96c7237
367ce4ddf60aeea4f33294702f7c4b9d11231efe
refs/heads/master
2020-12-19T21:26:29.371532
2020-01-23T18:27:58
2020-01-23T18:27:58
235,858,200
0
0
null
null
null
null
UTF-8
Python
false
false
1,502
py
""" Python Collections (Arrays) There are four collection data types in the Python programming language: List is a collection which is ordered and changeable. Allows duplicate members. Tuple is a collection which is ordered and unchangeable. Allows duplicate members. Set is a collection which is unordered and unindexed. No duplicate members. Dictionary is a collection which is unordered, changeable and indexed. No duplicate members. List A list is a collection which is ordered and changeable. In Python lists are written with square brackets.""" thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist) #indexing with list print(thislist[0]) # negative indexing print(thislist[-1]) # reverse indexing print(thislist[::-1]) # range of indexing print(thislist[2:5]) # adding new fruite in list at 2 position thislist[2]="MMango" print(thislist) # removing one item from list thislist.remove("MMango") print(thislist) thislist.append("Kela") thislist.append("Kela") print(thislist) thislist.reverse() print(thislist) thislist = ["apple", "banana", "cherry"] if "apple" in thislist: print("Yes, 'apple' is in the fruits list") # copy of list thislist = ["apple", "banana", "cherry"] mylist = thislist.copy() print(mylist) list1 = ["a", "b" , "c"] list2 = [1, 2, 3] list3 = list1 + list2 print(list3) list1 = ["a", "b" , "c"] list2 = [1, 2, 3] list1.extend(list2) print(list1)
[ "noreply@github.com" ]
mukund7296.noreply@github.com
601bb4a95a862f9e49e3cba3c1813a262db8c74f
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2317/60730/280771.py
05ee5cd5914a59c30517768e788b2c0f2c7b859c
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
204
py
MOD = 10 ** 9 + 7 m = list(map(int, input().split(","))) N = len(m) m.sort() ans = 0 for i in range(N - 1): for j in range(i + 1, N): ans += pow(2, j - i - 1) * (m[j] - m[i]) print(ans % MOD)
[ "1069583789@qq.com" ]
1069583789@qq.com
e03a99f67ddefa6e40bfffa5e697884a1295f0c1
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2471/60678/253055.py
cc45c769fa61efb73585348d1e372814f6241525
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
1,824
py
class Stack: def __init__(self): self.stack = [] def pop(self): if len(self.stack) == 0: return None elem = self.stack[len(self.stack) - 1] del self.stack[len(self.stack) - 1] return elem def push(self, elem): self.stack.append(elem) def top(self): return self.stack[len(self.stack) - 1] times = int(input()) stringTest = '' for loopTimes in range(0, times): over = False string = input() stringTest = stringTest + ' ' + string listTest = [] stack = Stack() if string == '': over = True print('not balanced') for i in string: if i == '(' or i == '[' or i == '{': stack.push(i) elif i == ')': character = stack.pop() if character == '[' or character == '{': print('not balanced') listTest.append('not balanced') over = True break elif i == ']': character = stack.pop() if character == '(' or character == '{': print('not balanced') listTest.append('not balanced') over = True break elif i == '}': character = stack.pop() if character == '(' or character == '[': print('not balanced') listTest.append('not balanced') over = True break if not over and len(stack.stack) > 0: print('not balanced') listTest.append('not balanced') over = True break if not over: print('balanced') listTest.append('balanced') if listTest[0] == 'balanced' and listTest[1] == 'not balanced' and len(listTest) == 2: print(stringTest)
[ "1069583789@qq.com" ]
1069583789@qq.com
cca9577decf9449eb84c393e3b58c8a559685aa5
eec1b3d81a6dee43571f753ffa379735a3d4aa41
/webdriver_service/test/test_yintai_single/fapiao_1_liuchen.py
b88ce727956467a9292e23ef2e8f3dee0f4f0fc7
[]
no_license
fn199544123/download-demo-beyebe
be00aacb302acd8304312c5a876a3c69fb3e73e8
ec9892a582a7a69235d95e49541b3a2b14b51239
refs/heads/master
2022-12-12T18:47:34.783443
2019-04-25T11:32:33
2019-04-25T11:32:33
163,168,934
1
1
null
2022-12-08T03:08:24
2018-12-26T10:44:33
Python
UTF-8
Python
false
false
966
py
import requests import json url = "http://39.108.188.34:8893/QrcodeDetectV3" data = { "bill": {'ossPath': "http://byb-pic.oss-cn-shenzhen.aliyuncs.com/beyebe/data/20190222/cc47c589fcea0609b6ca1aadfaac7d6c.pdf"}, } data = json.dumps(data) headers = { 'User-Agent': 'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36', "Content-Type": "application/json"} response = requests.post(url, data=data, headers=headers, timeout=(500, 500)) print(response.text) # 这是两次请求,下面的是单张,上面的是PDF 其中headers和data分别是请求头和post请求体 # data = { # "bill": {'ossPath': 'http://byb-pic.oss-cn-shenzhen.aliyuncs.com/beyebe/docker/test2_0c7ed229f4fb2a3dacdf8f9f22b7677e.jpg'}, # } # data = json.dumps(data) # headers = {"Content-Type": "application/json"} # response = requests.post(url, data=data, headers=headers) # print(response.text)
[ "gudandezhupi@163.com" ]
gudandezhupi@163.com
142863b82bed966008fad305bc5092c88cecc8ce
8dcd3ee098b4f5b80879c37a62292f42f6b2ae17
/venv/Lib/site-packages/pythonwin/pywin/framework/editor/frame.py
ec2b8e6a3e5619a74efb04eb04ba088ea73b794e
[]
no_license
GregVargas1999/InfinityAreaInfo
53fdfefc11c4af8f5d2b8f511f7461d11a3f7533
2e4a7c6a2424514ca0ec58c9153eb08dc8e09a4a
refs/heads/master
2022-12-01T20:26:05.388878
2020-08-11T18:37:05
2020-08-11T18:37:05
286,821,452
0
0
null
null
null
null
UTF-8
Python
false
false
3,164
py
# frame.py - The MDI frame window for an editor. import afxres import pywin.framework.window import win32con import win32ui from . import ModuleBrowser class EditorFrame(pywin.framework.window.MDIChildWnd): def OnCreateClient(self, cp, context): # Create the default view as specified by the template (ie, the editor view) view = context.template.MakeView(context.doc) # Create the browser view. browserView = ModuleBrowser.BrowserView(context.doc) view2 = context.template.MakeView(context.doc) splitter = win32ui.CreateSplitter() style = win32con.WS_CHILD | win32con.WS_VISIBLE splitter.CreateStatic(self, 1, 2, style, win32ui.AFX_IDW_PANE_FIRST) sub_splitter = self.sub_splitter = win32ui.CreateSplitter() sub_splitter.CreateStatic(splitter, 2, 1, style, win32ui.AFX_IDW_PANE_FIRST + 1) # Note we must add the default view first, so that doc.GetFirstView() returns the editor view. sub_splitter.CreateView(view, 1, 0, (0, 0)) splitter.CreateView(browserView, 0, 0, (0, 0)) sub_splitter.CreateView(view2, 0, 0, (0, 0)) ## print "First view is", context.doc.GetFirstView() ## print "Views are", view, view2, browserView ## print "Parents are", view.GetParent(), view2.GetParent(), browserView.GetParent() ## print "Splitter is", splitter ## print "sub splitter is", sub_splitter ## Old ## splitter.CreateStatic (self, 1, 2) ## splitter.CreateView(view, 0, 1, (0,0)) # size ignored. ## splitter.CreateView (browserView, 0, 0, (0, 0)) # Restrict the size of the browser splitter (and we can avoid filling # it until it is shown) splitter.SetColumnInfo(0, 10, 20) # And the active view is our default view (so it gets initial focus) self.SetActiveView(view) def GetEditorView(self): # In a multi-view (eg, splitter) environment, get # an editor (ie, scintilla) view # Look for the splitter opened the most! if self.sub_splitter is None: return self.GetDlgItem(win32ui.AFX_IDW_PANE_FIRST) v1 = self.sub_splitter.GetPane(0, 0) v2 = self.sub_splitter.GetPane(1, 0) r1 = v1.GetWindowRect() r2 = v2.GetWindowRect() if r1[3] - r1[1] > r2[3] - r2[1]: return v1 return v2 def GetBrowserView(self): # XXX - should fix this :-) return self.GetActiveDocument().GetAllViews()[1] def OnClose(self): doc = self.GetActiveDocument() if not doc.SaveModified(): ## Cancel button selected from Save dialog, do not actually close ## print 'close cancelled' return 0 ## So the 'Save' dialog doesn't come up twice doc._obj_.SetModifiedFlag(False) # Must force the module browser to close itself here (OnDestroy for the view itself is too late!) self.sub_splitter = None # ensure no circles! self.GetBrowserView().DestroyBrowser() return self._obj_.OnClose()
[ "44142880+GregVargas1999@users.noreply.github.com" ]
44142880+GregVargas1999@users.noreply.github.com
24b1eba5f108d0b8f858ac1fa0d5b882f5a8219a
6c816f19d7f4a3d89abbb00eeaf43dd818ecc34f
/apps/payment/migrations/0003_auto_20210218_1806.py
2b9fa9d8c5a50aa3596f9d6fd7f82ebc6eeb87cd
[]
no_license
reo-dev/bolt
29ee6aa7cfc96bd50fa7a7dae07fbaafc2125e54
d1a7859dd1ebe2f5b0e6e295047b620f5afdb92e
refs/heads/master
2023-07-13T04:05:57.856278
2021-08-27T09:07:03
2021-08-27T09:07:03
382,195,547
0
0
null
null
null
null
UTF-8
Python
false
false
408
py
# Generated by Django 3.0.8 on 2021-02-18 09:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('payment', '0002_auto_20210218_1805'), ] operations = [ migrations.AlterField( model_name='paylist', name='count', field=models.IntegerField(default=0, verbose_name='개수'), ), ]
[ "75593016+reo-dev@users.noreply.github.com" ]
75593016+reo-dev@users.noreply.github.com
fb1c3a8f95eb3aa2252bd4f7443528f9b0d935a2
413125277311510b40ca481b12ab82d379f5df62
/chess (horse movement).py
2fb0d1d957c87a1bd7b22c6b33aed2d6472c4b7d
[]
no_license
Aakashbansal837/python
98d85ce1e88c73f0e5180b1b1af80714f3e45097
4de2a3d6a482fdba8809ceb81e94f201b776b00e
refs/heads/master
2021-04-06T00:16:24.884830
2018-05-30T17:42:20
2018-05-30T17:42:20
124,778,551
2
0
null
null
null
null
UTF-8
Python
false
false
1,605
py
for _ in range(int(input())): n,m,q = map(int,input().split()) arr = [[0 for x in range(m)] for y in range(n)] arr1=[] for i in range(q): tmp,tmp2 = map(int,input().split()) arr1.append([tmp-1,tmp2-1]) arr[tmp-1][tmp2-1] = 1 #print("array is:") #print(*arr,sep="\n") count = 0 for i in arr1: #print("i:",i) x,y = i[0],i[1] if x-2 >= 0: if y-1 >= 0: if arr[x-2][y-1] == 1: count+=1 #print("x-2:y-1") if y+1 < m: if arr[x-2][y+1] == 1: count+=1 #print("x-2:y+1") if x+2 < n: if y-1 >= 0: if arr[x+2][y-1] == 1: count+=1 #print("x+2:y-1") if y+1 < m: if arr[x+2][y+1] == 1: count+=1 #print("x+2:y+1") if y-2 >= 0: if x-1 >= 0: if arr[x-1][y-2] == 1: count+=1 #print("x-1:y-2") if x+1 < m: if arr[x+1][y-2] == 1: count+=1 #print("x+1:y-2") if y+2 < m: if x-1 >= 0: if arr[x-1][y+2] == 1: count+=1 #print("x-1:y-2") if x+1 < m: if arr[x+1][y+2] == 1: count+=1 #print("x+1:y+2") print(count)
[ "noreply@github.com" ]
Aakashbansal837.noreply@github.com
f57738ea9e0d933d0ce62e21f6781693aeceb9d8
3e8dfa786b7f68ac4ffbc5154448dc4f479d27be
/爬虫项目实例/BaiduStocks/BaiduStocks/pipelines.py
5cf17a6a43228d5e29fdfb995e2ed28fd3730087
[]
no_license
SmallSir/Python_
a5201cda762af8fe54a74f368eb140d354ce84d6
93367667d74bc29cfba80239334e6c3b3fa604ca
refs/heads/master
2021-09-07T03:25:57.072044
2018-02-16T15:21:32
2018-02-16T15:21:32
110,565,596
0
1
null
null
null
null
UTF-8
Python
false
false
650
py
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html class BaidustocksPipeline(object): def process_item(self, item, spider): return item class BaidustockInfoPipeline(object): def open_spider(self,spider): self.f = open('BaiduStockInfo.txt','a') def close_spider(self,spider): self.f.close() def process_item(self,item,spider): try: line = str(dict(item)) + '\n' self.f.write(line) except: pass return item
[ "280690956@qq.com" ]
280690956@qq.com
37dd944c5eec22c13d855f59bd969c0e2498e3cd
3f77dda6c8d8508902f9ae3efbd4fed8ef2ee1b2
/scrap/migrations/0031_auto_20190517_1104.py
08a68dc34f4a666813a5c290a2a3797a88b8bea2
[]
no_license
priyankush-siloria/linkedinscrap
a3d83cac1ca923e7e0f3a03e6e4c5f02b7f6a0e5
882a4df294ce8b2b01c94299471bbe6d9826f582
refs/heads/master
2020-07-07T13:38:01.659725
2019-08-20T11:40:23
2019-08-20T11:40:23
203,363,810
0
0
null
null
null
null
UTF-8
Python
false
false
455
py
# Generated by Django 2.2 on 2019-05-17 11:04 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('scrap', '0030_auto_20190517_0948'), ] operations = [ migrations.AlterField( model_name='automations', name='created_at', field=models.DateTimeField(default=datetime.datetime(2019, 5, 17, 11, 4, 51, 676236)), ), ]
[ "director@avioxtechnologies.com" ]
director@avioxtechnologies.com
51ea87311527f3de7247bb5e04a3033641a9e2db
52a3fab945f71f1bb2177c650d1e6fa9f9dd9716
/packages/motifextraction/alignment/extract_errors.py
ced825aaeb300d56ce649ce061d2f8d947d1e757
[ "MIT" ]
permissive
SimonPringleWallace/motifextraction
402430f3b51e7854b9b1c0c8c33d522f6af877cd
a39fee2a029ae7acc1cf0c5a031913bf84c948a0
refs/heads/master
2023-03-28T18:36:25.811621
2021-04-03T17:13:48
2021-04-03T17:13:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,247
py
import numpy as np from path import Path from ppm3d import load_alignment_data def extract_errors(cluster_number: int, results_fn: str, save_dir: Path, cluster_dir: Path, cutoff: float, target_path: Path = None): if save_dir and not save_dir.exists(): save_dir.makedirs() print(f"Loading {results_fn}") if target_path is None: data = load_alignment_data(results_fn, prepend_path=cluster_dir) else: data = load_alignment_data(results_fn, prepend_model_path=cluster_dir, prepend_target_path=target_path) errors = np.zeros((len(data), 4)) errors.fill(np.nan) failed = 0 for i, a in enumerate(data): if a is not None and a.successful: l2 = a.L2Norm() assert np.isclose(l2, a.error, rtol=1e-05, atol=1e-08) l1 = a.L1Norm() linf = a.LinfNorm() rcutoff = cutoff / (a.model_scale*0.5 + a.target_scale*0.5) angular = a.angular_variation(rcutoff) else: l2, l1, linf, angular = np.inf, np.inf, np.inf, np.inf failed += 1 errors[i, :] = (l2, l1, linf, angular) print(f"Finished! {failed} alignments failed.") np.save(f'{save_dir}/{cluster_number}_errors.npy', errors)
[ "jjmaldonis@gmail.com" ]
jjmaldonis@gmail.com
33220aff8c0decd5a152cb8cc96b951dd3eb037b
304926837d94f37ef33c46b8f3c71ecfac4690e8
/5.8_Hello_Admin.py
c3d19d10a8eb6df9440d75dcc566805cac6fbd35
[]
no_license
ver0nika4ka/PythonCrashCourse
1015d207d9da1b0f9efaee3acc502d2757880f33
6bde3b716deb86d022da5cb478c0a95505fe5acc
refs/heads/master
2021-07-12T17:24:16.478133
2021-06-17T03:27:24
2021-06-17T03:27:24
246,993,773
0
0
null
null
null
null
UTF-8
Python
false
false
256
py
usernames = ['veronica','nastya','victor','alex','admin'] for user in usernames: if user == 'admin': print(f"Hello admin, would you like to see a status report?") else: print(f"Hello {user.title()}, thank you for logging in again.")
[ "veranika.aizu@gmail.com" ]
veranika.aizu@gmail.com
a27e20221825939f2e9ac619b03572526083145b
7033c84a3051e51a3d38a25d52f724bc0f6aab25
/sandbox.py
54edb623375b4528317d30ce33aaa8fb7140050a
[]
no_license
andycasey/bitfitter
46332d12de79d45265f77707bd9a0749f115b75a
403624d98582a6c249ef9da347f74686c410d400
refs/heads/master
2021-01-10T13:47:02.687006
2016-02-07T17:10:13
2016-02-07T17:10:13
51,255,415
0
0
null
null
null
null
UTF-8
Python
false
false
176
py
import fitbit import auth client = fitbit.Fitbit(auth.CONSUMER_KEY, auth.CONSUMER_SECRET, oauth2=True, access_token=auth.ACCESS_TOKEN, refresh_token=auth.REFRESH_TOKEN)
[ "andycasey@gmail.com" ]
andycasey@gmail.com
255049d34adcb37d9d4241719fc8e003fe117978
95aa9069a0a115c1cbccaac38c6c7d193b5a2fb7
/home/migrations/0002_load_initial_data.py
71268fb3a0667934e255cfd24dd2754440810b82
[]
no_license
crowdbotics-apps/sunday-app-dev-5568
35f9c5b4ed8560fbb4b985f6761fb22c9eff8d34
d8ae94d463f3b6186f27ccf0fa5458c051e2955b
refs/heads/master
2022-10-09T18:05:11.968490
2020-06-07T08:36:37
2020-06-07T08:36:37
270,244,275
0
0
null
null
null
null
UTF-8
Python
false
false
1,297
py
from django.db import migrations def create_customtext(apps, schema_editor): CustomText = apps.get_model("home", "CustomText") customtext_title = "sunday app" CustomText.objects.create(title=customtext_title) def create_homepage(apps, schema_editor): HomePage = apps.get_model("home", "HomePage") homepage_body = """ <h1 class="display-4 text-center">sunday app</h1> <p class="lead"> This is the sample application created and deployed from the Crowdbotics app. You can view list of packages selected for this application below. </p>""" HomePage.objects.create(body=homepage_body) def create_site(apps, schema_editor): Site = apps.get_model("sites", "Site") custom_domain = "sunday-app-dev-5568.botics.co" site_params = { "name": "sunday app", } if custom_domain: site_params["domain"] = custom_domain Site.objects.update_or_create(defaults=site_params, id=1) class Migration(migrations.Migration): dependencies = [ ("home", "0001_initial"), ("sites", "0002_alter_domain_unique"), ] operations = [ migrations.RunPython(create_customtext), migrations.RunPython(create_homepage), migrations.RunPython(create_site), ]
[ "team@crowdbotics.com" ]
team@crowdbotics.com
ac7310af9bea64230b95d4d7b496937545189fff
86b82049d710ed27cc0a94bc776020b199d4f4ad
/setup.py
662aa245b9c64b75c5876ef2450838748e87ecfa
[ "MIT" ]
permissive
ChristopherHaydenTodd/ctodd-python-lib-revision-control
02b8e5682fc48e67ac22afdfbf503f0a9b3d124c
d9618003592d9b54957789b2baebfe6d225d6c94
refs/heads/master
2020-04-22T19:00:31.401848
2019-02-21T21:50:10
2019-02-21T21:50:10
170,594,927
1
0
null
null
null
null
UTF-8
Python
false
false
4,783
py
""" Purpose: setup.py is executed to build the python package """ # Python Imports from os import listdir from setuptools import setup, find_packages import re ### # Helper Functions ### def get_version_from_file(python_version_file="./VERSION"): """ Purpose: Get python requirements from a specified requirements file. Args: python_requirements_file (String): Path to the requirements file (usually it is requirements.txt in the same directory as the setup.py) Return: requirements (List of Strings): The python requirements necessary to run the library """ version = "unknown" with open(python_version_file) as version_file: version = version_file.readline().strip().strip("\n") return version def get_requirements_from_file(python_requirements_file="./requirements.txt"): """ Purpose: Get python requirements from a specified requirements file. Args: python_requirements_file (String): Path to the requirements file (usually it is requirements.txt in the same directory as the setup.py) Return: requirements (List of Strings): The python requirements necessary to run the library """ requirements = [] with open(python_requirements_file) as requirements_file: requirement = requirements_file.readline() while requirement: if requirement.strip().startswith("#"): pass elif requirement.strip() == "": pass else: requirements.append(requirement.strip()) requirement = requirements_file.readline() return requirements def get_requirements_from_packages(packages): """ Purpose: Get python requirements for each package. will get requirements file in each package's subdirectory Args: packages (String): Name of the packages Return: requirements (List of Strings): The python requirements necessary to run the library """ requirements = [] for package in packages: package_dir = package.replace(".", "/") requirement_files = get_requirements_files_in_package_dir(package_dir) for requirement_file in requirement_files: package_requirements =\ get_requirements_from_file(python_requirements_file=requirement_file) requirements = requirements + package_requirements return list(set(requirements)) def get_requirements_files_in_package_dir(package_dir): """ Purpose: From a package dir, find all requirements files (Assuming form requirements.txt or requirements_x.txt) Args: package_dir (String): Directory of the package Return: requirement_files (List of Strings): Requirement Files """ requirements_regex = r"^requirements[_\w]*.txt$" requirement_files = [] for requirement_file in listdir(f"./{package_dir}"): if re.match(requirements_regex, requirement_file): requirement_files.append(f"./{package_dir}/{requirement_file}") return requirement_files ### # Main Functionality ### def main(): """ Purpose: Main function for packaging and setting up packages Args: N/A Return: N/A """ # Get Version version = get_version_from_file() # Get Packages packages = find_packages() install_packages = [package for package in packages if not package.endswith(".tests")] test_packages = [package for package in packages if package.endswith(".tests")] # Get Requirements and Requirments Installation Details install_requirements = get_requirements_from_packages(install_packages) test_requirements = get_requirements_from_packages(test_packages) setup_requirements = ["pytest-runner", "pytest", "pytest-cov"] # Get Dependency Links For Each Requirement (As Necessary) dependency_links = [] setup( name="ctodd-python-lib-revision-control", version=version, python_requires=">3.0,<3.7", description=("Python utilities used for interacting with Revision Control Systems Like Git"), url="https://github.com/ChristopherHaydenTodd/ctodd-python-lib-revision-control", author="Christopher H. Todd", author_email="Christopher.Hayden.Todd@gmail.com", classifiers=["Programming Language :: Python"], keywords=["python", "libraries", "Revision Control", "Git"], packages=packages, install_requires=install_requirements, setup_requires=setup_requirements, tests_require=test_requirements, project_urls={}, ) if __name__ == "__main__": main()
[ "Christopher.Hayden.Todd@gmail.com" ]
Christopher.Hayden.Todd@gmail.com
0ce156178c0a4e5b5787386c7b7ef99496948793
c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c
/cases/pa2/sample/ast_coverage-51.py
bfef20fc22cc7201d85726659aa3556a23ea3605
[]
no_license
Virtlink/ccbench-chocopy
c3f7f6af6349aff6503196f727ef89f210a1eac8
c7efae43bf32696ee2b2ee781bdfe4f7730dec3f
refs/heads/main
2023-04-07T15:07:12.464038
2022-02-03T15:42:39
2022-02-03T15:42:39
451,969,776
0
0
null
null
null
null
UTF-8
Python
false
false
672
py
count:int = 0 def foo(s: str) -> int: return len(s) class bar(object): p: bool = True def baz($TypedVar, xx: [int]) -> str: global count x:int = 0 y:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" print(bar().baz([1,2]))
[ "647530+Virtlink@users.noreply.github.com" ]
647530+Virtlink@users.noreply.github.com
3b1373563feba29c600a45c39b4c088717a565e3
33c1c5d0f48ad952776fe546a85350a441d6cfc2
/ABC/058/C.py
5e7f508ce787e956e285580187e4f2a28810dd0c
[]
no_license
hisyatokaku/Competition
985feb14aad73fda94804bb1145e7537b057e306
fdbf045a59eccb1b2502b018cab01810de4ea894
refs/heads/master
2021-06-30T18:48:48.256652
2020-11-16T11:55:12
2020-11-16T11:55:12
191,138,764
0
0
null
null
null
null
UTF-8
Python
false
false
1,175
py
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools from collections import deque sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 DR = [1, -1, 0, 0] DC = [0, 0, 1, -1] def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def main(): N = I() strings = [] prevdic = None for _ in range(N): ch = S() curdic = collections.Counter() for c in ch: curdic[c] += 1 if prevdic: for k, v in prevdic.items(): prevdic[k] = min(v, curdic[k]) else: prevdic = curdic diclist = [] for k, v in prevdic.items(): diclist.append((k, v)) diclist = sorted(diclist, key=lambda x: x[0]) ans = '' for item in diclist: k, v = item[0], item[1] ans += k * v print(ans) main()
[ "hisyatokaku2005@yahoo.co.jp" ]
hisyatokaku2005@yahoo.co.jp
7eb97a4b679b17234e30a781df737859f3a9fec7
f89d70fc8bf370ef4e2aa54c7ee0de3b4a053624
/troposphere/validators/certificatemanager.py
c7644aacc79b763e015b48d41199629fa523839d
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yks0000/troposphere
a7622bff01c31f10dcb296d2ca353144e1d7f793
9a94a8fafd8b4da1cd1f4239be0e7aa0681fd8d4
refs/heads/main
2022-04-28T03:51:42.770881
2022-04-15T15:15:01
2022-04-15T15:15:01
482,753,190
1
0
BSD-2-Clause
2022-04-18T07:20:42
2022-04-18T07:20:42
null
UTF-8
Python
false
false
250
py
# Copyright (c) 2012-2022, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import tags_or_list def validate_tags_or_list(x): """ Property: Certificate.Tags """ return tags_or_list(x)
[ "mark@peek.org" ]
mark@peek.org
10f6a7a084d195cc8020da4f2a0f4e5ac4493b89
ebbbefbc82412d8a91c8de96a45ffebe5d625c51
/test/inspector_protocol_parser_test/inspector_protocol_parser_test.gyp
835117c5a7b9f7f8f21033995d3aee142372a057
[ "BSD-3-Clause", "SunPro", "bzip2-1.0.6" ]
permissive
riverar/v8
d93eb2aea104d10aee2a27a7763e13061ec60f4b
16397d242258b97f107e742e37cc585e77b9b3d0
refs/heads/master
2020-12-14T18:39:32.337673
2016-11-13T22:04:51
2016-11-13T22:04:51
77,864,048
2
0
null
2017-01-02T21:50:22
2017-01-02T21:50:21
null
UTF-8
Python
false
false
1,311
gyp
# Copyright 2016 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'protocol_path': '../../third_party/WebKit/Source/platform/inspector_protocol', }, 'targets': [ { 'target_name': 'inspector_protocol_parser_test', 'type': 'executable', 'dependencies': [ '../../src/inspector/inspector.gyp:inspector_protocol', '../../testing/gmock.gyp:gmock', '../../testing/gtest.gyp:gtest', ], 'include_dirs+': [ '../..', '<(protocol_path)/../..', ], 'defines': [ 'V8_INSPECTOR_USE_STL', ], 'sources': [ '<(protocol_path)/ParserTest.cpp', 'RunTests.cpp', ] }, ], 'conditions': [ ['test_isolation_mode != "noop"', { 'targets': [ { 'target_name': 'inspector_protocol_parser_test_run', 'type': 'none', 'dependencies': [ 'inspector_protocol_parser_test', ], 'includes': [ '../../gypfiles/features.gypi', '../../gypfiles/isolate.gypi', ], 'sources': [ 'inspector_protocol_parser_test.isolate', ], }, ], }], ], }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
c4fc69e83f8f586a7eac0551aaba42be7e4142fa
9e988c0dfbea15cd23a3de860cb0c88c3dcdbd97
/sdBs/AllRun/pg_1713+248/sdB_pg_1713+248_coadd.py
512545067cc439b9893d34f29e077ea79ff244a5
[]
no_license
tboudreaux/SummerSTScICode
73b2e5839b10c0bf733808f4316d34be91c5a3bd
4dd1ffbb09e0a599257d21872f9d62b5420028b0
refs/heads/master
2021-01-20T18:07:44.723496
2016-08-08T16:49:53
2016-08-08T16:49:53
65,221,159
0
0
null
null
null
null
UTF-8
Python
false
false
430
py
from gPhoton.gMap import gMap def main(): gMap(band="NUV", skypos=[258.910292,24.789658], skyrange=[0.0333333333333,0.0333333333333], stepsz = 30., cntfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdBs/sdB_pg_1713+248/sdB_pg_1713+248_movie_count.fits", cntcoaddfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdB/sdB_pg_1713+248/sdB_pg_1713+248_count_coadd.fits", overwrite=True, verbose=3) if __name__ == "__main__": main()
[ "thomas@boudreauxmail.com" ]
thomas@boudreauxmail.com
3d4853aadd426ddffba132f55513da77925f1a05
72dbf8366cf17b6a81ab37e72af667726e3f2661
/store/migrations/0004_customer_profile_pic.py
3c6be38b982836d8550da5a4b198ba126e8f506e
[]
no_license
Rayhun/Django_E-Commerce_website
3aef732ffa0a41509be95ced3c33b845233903a7
1a5f7e31f942914256e49ba7da1f7367a799f097
refs/heads/main
2023-05-23T18:18:27.875328
2021-04-30T19:29:06
2021-04-30T19:29:06
306,414,778
3
1
null
2021-04-30T19:28:58
2020-10-22T17:41:57
CSS
UTF-8
Python
false
false
412
py
# Generated by Django 3.1.1 on 2020-10-31 15:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store', '0003_auto_20201030_1534'), ] operations = [ migrations.AddField( model_name='customer', name='profile_pic', field=models.ImageField(blank=True, null=True, upload_to=''), ), ]
[ "rayhunkhan27@gmail.com" ]
rayhunkhan27@gmail.com
5dbd1f7c42544433d409a21de2f3f2b30ab38bb3
31730fbdf50dcbc36205911e3a676f0d826157b1
/setup.py
87aa04ba1362ee17f5c2df4173f3d322c339a45c
[ "MIT" ]
permissive
Harpuia/terminal-leetcode
954a270784fe920eb49f1fc4b8e66b379377e608
39b27b3a6260195376c0cdffb7697b4aa5c60ca8
refs/heads/master
2021-01-22T02:04:19.470178
2017-05-21T21:34:26
2017-05-21T21:34:26
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,133
py
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() requirements = ['urwid', 'requests', 'bs4', 'lxml'] setup( name = "terminal-leetcode", version = "0.0.11", author = "Liyun Xiu", author_email = "chishui2@gmail.com", description = "A terminal based leetcode website viewer", license = "MIT", keywords = "leetcode terminal urwid", url = "https://github.com/chishui/terminal-leetcode", packages=['leetcode', 'leetcode/views'], long_description=read('README.md'), include_package_data=True, install_requires=requirements, entry_points={'console_scripts': ['leetcode=leetcode.__main__:main']}, #classifiers=[ #"Operating System :: MacOS :: MacOS X", #"Operating System :: POSIX", #"Natural Language :: English", #"Programming Language :: Python :: 2.7", #"Development Status :: 2 - Pre-Alpha", #"Environment :: Console :: Curses", #"Topic :: Utilities", #"Topic :: Terminals", #"License :: OSI Approved :: MIT License", #], )
[ "chishui2@gmail.com" ]
chishui2@gmail.com
8308c5e060050d89710a4c75af0015ccdf6f9d54
9f250956e2c19e5b51053a513a6b31ef8128d674
/myProject/account/models.py
847e54c8c8c7bd75fd82bf7bb24b88146fd4144d
[]
no_license
murali-kotakonda/pyDjango
85b9128949fcdf3bcc0e60c386decd9eeff723db
cf1a920f8146be600bc04455cb5769f369c7d6eb
refs/heads/master
2023-03-24T06:34:14.143103
2021-03-20T12:38:40
2021-03-20T12:38:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
476
py
from django.db import models # Create your models here. from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) middle_name = models.CharField(max_length=30, blank=True) dob = models.DateField(null=True, blank=True) active = models.BooleanField(default=True) pub_date = models.DateTimeField(default=timezone.now)
[ "muralidhar.reddy.kotakonda@sap.com" ]
muralidhar.reddy.kotakonda@sap.com
2b2ef12926774661cb4b51bc33a1ee978667c5e7
536bce6ca78a9a151247b51acb8c375c9db7445f
/src/plot/plot0a.py
576ed81aae88789ba020629c45a25f2e61024a75
[]
no_license
clicianaldoni/aprimeronpython
57de34313f4fd2a0c69637fefd60b0fb5861f859
a917b62bec669765a238c4b310cc52b79c7df0c9
refs/heads/master
2023-01-28T18:02:31.175511
2023-01-23T08:14:57
2023-01-23T08:14:57
112,872,454
0
0
null
2017-12-02T19:55:40
2017-12-02T19:55:40
null
UTF-8
Python
false
false
679
py
"""Plot three curves. Use Matlab-style syntax.""" from scitools.std import * # plot two curves in the same plot: t = linspace(0, 3, 51) # 51 points between 0 and 3 y1 = t**2*exp(-t**2) y2 = t**4*exp(-t**2) # pick out each 4 points and add random noise: t3 = t[::4] random.seed(11) y3 = y2[::4] + random.normal(loc=0, scale=0.02, size=len(t3)) # use Matlab syntax: plot(t, y1, 'r-') hold('on') plot(t, y2, 'b-') plot(t3, y3, 'bo') legend('t^2*exp(-t^2)', 't^4*exp(-t^2)', 'data') title('Simple Plot Demo') axis([0, 3, -0.05, 0.6]) xlabel('t') ylabel('y') show() hardcopy('tmp0.eps') # this one can be included in latex hardcopy('tmp0.png') # this one can be included in HTML
[ "martin@rodvand.net" ]
martin@rodvand.net
b6976d1ebf040e74ebb2ffe37340c1a569afacca
bc444c603a80d7c656c4f20539f6035c43fff54a
/src/dirbs/api/v2/resources/__init__.py
beaa8eb8bea4490bfdda03263a24cddeddeb4211
[ "BSD-4-Clause", "LicenseRef-scancode-other-permissive", "zlib-acknowledgement", "LicenseRef-scancode-unknown-license-reference" ]
permissive
dewipuspa/DIRBS-Core
fe1af50918333474732872b61dc3ae4f8e41c14f
702e93dcefdf0fb5787cb42c2a6bc2574e483057
refs/heads/master
2020-07-07T09:59:10.723477
2019-06-21T06:39:59
2019-06-21T06:39:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,104
py
""" DIRBS REST-ful API-V2 resource package. SPDX-License-Identifier: BSD-4-Clause-Clear Copyright (c) 2018-2019 Qualcomm Technologies, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - All advertising materials mentioning features or use of this software, or any deployment of this software, or documentation accompanying any distribution of this software, must display the trademark/logo as per the details provided here: https://www.qualcomm.com/documents/dirbs-logo-and-brand-guidelines - Neither the name of Qualcomm Technologies, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. SPDX-License-Identifier: ZLIB-ACKNOWLEDGEMENT Copyright (c) 2018-2019 Qualcomm Technologies, Inc. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment is required by displaying the trademark/logo as per the details provided here: https://www.qualcomm.com/documents/dirbs-logo-and-brand-guidelines - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. - This notice may not be removed or altered from any source distribution. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """
[ "awkhan978@gmail.com" ]
awkhan978@gmail.com
bcfeb0806979c5c3c6b5815db7dd321e6d847b41
d994cee3810de8f5fa895807f415d8051dfd1319
/HetMan/experiments/pair_inference/setup_comb.py
4ab9ea7068b4cfd9486fea0b2579d392b6315969
[]
no_license
ohsu-comp-bio/bergamot
b4e162525d1cc66975d64866cc68004ee42828e2
37fd50fc1ce6da83049a0cbbad5038a055fd3544
refs/heads/master
2023-07-24T01:15:27.695906
2019-09-19T01:39:13
2019-09-19T01:39:13
89,973,424
1
2
null
2023-07-06T21:07:53
2017-05-02T00:03:26
Python
UTF-8
Python
false
false
4,119
py
import os base_dir = os.path.dirname(__file__) import sys sys.path.extend([os.path.join(base_dir, '../../..')]) from HetMan.features.expression import get_expr_firehose from HetMan.features.variants import get_variants_mc3 from HetMan.features.cohorts import VariantCohort import synapseclient import dill as pickle import argparse firehose_dir = '/home/exacloud/lustre1/CompBio/mgrzad/input-data/firehose' def main(): """Runs the experiment.""" parser = argparse.ArgumentParser( description='Set up searching for sub-types to detect.' ) # positional command line arguments parser.add_argument('cohort', type=str, help='a TCGA cohort') parser.add_argument('classif', type=str, help='a classifier in HetMan.predict.classifiers') # optional command line arguments controlling the thresholds for which # individual mutations and how many genes' mutations are considered parser.add_argument( '--freq_cutoff', type=int, default=20, help='sub-type sample frequency threshold' ) parser.add_argument( '--max_genes', type=int, default=10, help='maximum number of mutated genes to consider' ) # optional command line argument controlling verbosity parser.add_argument('--verbose', '-v', action='store_true', help='turns on diagnostic messages') # parse the command line arguments, get the directory where found sub-types # will be saved for future use args = parser.parse_args() out_path = os.path.join(base_dir, 'output', args.cohort, args.classif, 'comb') if args.verbose: print("Looking for mutation sub-types in cohort {} with at least {} " "samples in total.\n".format( args.cohort, args.freq_cutoff)) # log into Synapse using locally-stored credentials syn = synapseclient.Synapse() syn.cache.cache_root_dir = ("/home/exacloud/lustre1/CompBio/" "mgrzad/input-data/synapse") syn.login() # load the expression matrix for the given cohort from Broad Firehose, # load the MC3 variant call set from Synapse, find the mutations for the # samples that are in both datasets expr_data = get_expr_firehose(args.cohort, firehose_dir) mc3_data = get_variants_mc3(syn) expr_mc3 = mc3_data.loc[mc3_data['Sample'].isin(expr_data.index), :] # get the genes whose mutations appear in enough samples to pass the # frequency threshold gene_counts = expr_mc3.groupby(by='Gene').Sample.nunique() common_genes = set(gene_counts.index[gene_counts >= args.freq_cutoff]) if args.verbose: print("Found {} candidate genes with at least {} potential " "mutated samples.".format(len(common_genes), args.freq_cutoff)) # if too many genes passed the frequency cutoff, use only the top n by # frequency - note that ties are broken arbitrarily and so the list of # genes chosen will differ slightly between runs if len(common_genes) >= args.max_genes: gene_counts = gene_counts[common_genes].sort_values(ascending=False) common_genes = set(gene_counts[:args.max_genes].index) if args.verbose: print("Too many genes found, culling list to {} genes which each " "have at least {} mutated samples.".format( args.max_genes, min(gene_counts[common_genes]))) cdata = VariantCohort( cohort=args.cohort, mut_genes=common_genes, mut_levels=['Gene'], expr_source='Firehose', data_dir=firehose_dir, cv_prop=1.0, syn=syn ) use_mtypes = cdata.train_mut.branchtypes(sub_levels=['Gene'], min_size=args.freq_cutoff) if args.verbose: print("\nFound {} total sub-types!".format(len(use_mtypes))) # save the list of found non-duplicate sub-types to file pickle.dump(sorted(list(use_mtypes)), open(os.path.join(out_path, 'tmp/mtype_list.p'), 'wb')) if __name__ == '__main__': main()
[ "mgrzad@gmail.com" ]
mgrzad@gmail.com
481cc8b7ab198499fce1c0a51236d4cecf13d6bf
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03495/s609850404.py
b480fa2ca615b11e243acdf596b2bb3cc9bfea4e
[]
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
261
py
N, K = map(int,input().split()) A = list(map(int,input().split())) import collections cA = collections.Counter(A) sorted_ls = sorted(list(cA.values())) sum_ls = sum(sorted_ls) if len(sorted_ls)>K: print(sum(sorted_ls[:len(sorted_ls)-K])) else: print(0)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
fc1c51f09fbcfb9579c3048674323b1c14071f24
3ef70fe63acaa665e2b163f30f1abd0a592231c1
/stackoverflow/venv/lib/python3.6/site-packages/twisted/trial/test/test_keyboard.py
71756bc7972de92fd569ca5053a3fce5ba032347
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
wistbean/learn_python3_spider
14914b63691ac032955ba1adc29ad64976d80e15
40861791ec4ed3bbd14b07875af25cc740f76920
refs/heads/master
2023-08-16T05:42:27.208302
2023-03-30T17:03:58
2023-03-30T17:03:58
179,152,420
14,403
3,556
MIT
2022-05-20T14:08:34
2019-04-02T20:19:54
Python
UTF-8
Python
false
false
4,036
py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for interrupting tests with Control-C. """ from __future__ import absolute_import, division from twisted.python.compat import NativeStringIO from twisted.trial import unittest from twisted.trial import reporter, runner class TrialTest(unittest.SynchronousTestCase): def setUp(self): self.output = NativeStringIO() self.reporter = reporter.TestResult() self.loader = runner.TestLoader() class InterruptInTestTests(TrialTest): class InterruptedTest(unittest.TestCase): def test_02_raiseInterrupt(self): raise KeyboardInterrupt def test_01_doNothing(self): pass def test_03_doNothing(self): InterruptInTestTests.test_03_doNothing_run = True def setUp(self): super(InterruptInTestTests, self).setUp() self.suite = self.loader.loadClass(InterruptInTestTests.InterruptedTest) InterruptInTestTests.test_03_doNothing_run = None def test_setUpOK(self): self.assertEqual(3, self.suite.countTestCases()) self.assertEqual(0, self.reporter.testsRun) self.assertFalse(self.reporter.shouldStop) def test_interruptInTest(self): runner.TrialSuite([self.suite]).run(self.reporter) self.assertTrue(self.reporter.shouldStop) self.assertEqual(2, self.reporter.testsRun) self.assertFalse(InterruptInTestTests.test_03_doNothing_run, "test_03_doNothing ran.") class InterruptInSetUpTests(TrialTest): testsRun = 0 class InterruptedTest(unittest.TestCase): def setUp(self): if InterruptInSetUpTests.testsRun > 0: raise KeyboardInterrupt def test_01(self): InterruptInSetUpTests.testsRun += 1 def test_02(self): InterruptInSetUpTests.testsRun += 1 InterruptInSetUpTests.test_02_run = True def setUp(self): super(InterruptInSetUpTests, self).setUp() self.suite = self.loader.loadClass( InterruptInSetUpTests.InterruptedTest) InterruptInSetUpTests.test_02_run = False InterruptInSetUpTests.testsRun = 0 def test_setUpOK(self): self.assertEqual(0, InterruptInSetUpTests.testsRun) self.assertEqual(2, self.suite.countTestCases()) self.assertEqual(0, self.reporter.testsRun) self.assertFalse(self.reporter.shouldStop) def test_interruptInSetUp(self): runner.TrialSuite([self.suite]).run(self.reporter) self.assertTrue(self.reporter.shouldStop) self.assertEqual(2, self.reporter.testsRun) self.assertFalse(InterruptInSetUpTests.test_02_run, "test_02 ran") class InterruptInTearDownTests(TrialTest): testsRun = 0 class InterruptedTest(unittest.TestCase): def tearDown(self): if InterruptInTearDownTests.testsRun > 0: raise KeyboardInterrupt def test_01(self): InterruptInTearDownTests.testsRun += 1 def test_02(self): InterruptInTearDownTests.testsRun += 1 InterruptInTearDownTests.test_02_run = True def setUp(self): super(InterruptInTearDownTests, self).setUp() self.suite = self.loader.loadClass( InterruptInTearDownTests.InterruptedTest) InterruptInTearDownTests.testsRun = 0 InterruptInTearDownTests.test_02_run = False def test_setUpOK(self): self.assertEqual(0, InterruptInTearDownTests.testsRun) self.assertEqual(2, self.suite.countTestCases()) self.assertEqual(0, self.reporter.testsRun) self.assertFalse(self.reporter.shouldStop) def test_interruptInTearDown(self): runner.TrialSuite([self.suite]).run(self.reporter) self.assertEqual(1, self.reporter.testsRun) self.assertTrue(self.reporter.shouldStop) self.assertFalse(InterruptInTearDownTests.test_02_run, "test_02 ran")
[ "354142480@qq.com" ]
354142480@qq.com
44735efc8ba871e2f2e3ca0ced6963479ab46e19
ea4567b4388ea97c8ca718d9e331dc796439ee44
/exercise_learn/new_selenium_project/util/browser_driver_test.py
af46ab09ff714df86c85b89525f0d5733303ef53
[]
no_license
Kingwolf9527/python_knowledge
ace65470ec706cae195b228b8e8d6ca8db574db8
1ccb3a788c172f3122a7c119d0607aa90934e59b
refs/heads/master
2020-12-04T06:12:49.809020
2020-02-10T18:22:36
2020-02-10T18:22:44
231,647,147
0
0
null
null
null
null
UTF-8
Python
false
false
2,783
py
# ! /usr/bin/env python # - * - coding:utf-8 - * - # __author__ : KingWolf # createtime : 2019/11/12 3:21 import os from selenium import webdriver from util.read_config import Read_Config from util.common_log import Common_Logs #实例化logger log_name = Common_Logs(logger='browser_driver') logger = log_name.get_logger() class WebdriverBrowser(object): def __init__(self,selection,key): """ 打开浏览器 :param selection: :param key: :return: """ self.browser = Read_Config().get_value(selection,key) if self.browser == 'chrome': """ 谷歌浏览器的设置 """ #设置user-data-dir的路径 newOptions = webdriver.ChromeOptions() newOptions.add_argument(r"user-data-dir=F:\data_profile") #设置谷歌浏览器的驱动路径 driverPath = os.path.dirname(os.path.dirname(__file__)) + '/browser_driver/chromedriver.exe' self.driver = webdriver.Chrome(executable_path=driverPath,options=newOptions) logger.info('-----------------open the browser:Chrome--------------------') elif self.browser == 'firefox': """ 火狐浏览器的设置 """ # #设置火狐浏览器驱动路径 driverPath = os.path.dirname(os.path.dirname(__file__)) + '/browser_driver/geckodriver.exe' self.driver = webdriver.Firefox(executable_path=driverPath) logger.info('-----------------open the browser:Firefox--------------------') else: """ edge浏览器的设置 """ # #设置edge浏览器驱动路径 driverPath = os.path.dirname(os.path.dirname(__file__)) + '/browser_driver/MicrosoftWebDriver.exe' self.driver = webdriver.Edge(executable_path=driverPath) logger.info('-----------------open the browser:Edge--------------------') def getDriver(self): """ 返回driver :return: """ return self.driver def getUrl(self,selection,key): """ 输入url地址 :param selection: :param key: :return: """ self.registerUrl = Read_Config().get_value(selection,key) self.getDriver().get(self.registerUrl) logger.info('---------------------open the url: %s -----------------------' %self.registerUrl) self.getDriver().implicitly_wait(10) self.getDriver().maximize_window() if __name__ == '__main__': dd = WebdriverBrowser('Browser','chrome_browser') dd.getUrl('Register_url','url')
[ "lccr777@163.com" ]
lccr777@163.com
8e82a7f954f34fe2899eb5500cb51358b6154c4b
747eeeed1056b69a8bde6364ee9bf266523f19e5
/Project/My solutions/12.py
83d4817a7abb86b7b2219a8886f0815ffcdfb50e
[]
no_license
LittleAndroidBunny/Python_Cheatsheet_Nohar_Batit
d18a77d455474834da99c11e763beea598947f7c
a53f5e3a635bb47012fceb50efd43ad124eff180
refs/heads/main
2023-06-10T10:40:54.746084
2021-07-03T23:25:17
2021-07-03T23:25:17
382,595,063
1
0
null
null
null
null
UTF-8
Python
false
false
7,522
py
# ###################### # ## Nohar_Batit ### # ## 315572941 ### # ###################### # ################################ import random random.seed(1) import pylab import matplotlib.pyplot as plt from scipy import stats # Question 1 # function f1 gets a natural number and returns a tuple of the biggest divider def f1(a): result = [] if a < 0: return "please insert a number higher than 0" highest_divider = 2 lowest_positive = 1 if type(a / 2) is float: highest_divider = None for i in range(2, a): if a % i == 0: highest_divider = i for j in range(1, a+1): if j != 1 and a % j == 0: if lowest_positive < j and lowest_positive == 1: lowest_positive = j if lowest_positive == 1: lowest_positive = None result.append(highest_divider) result.append(lowest_positive) result = tuple(result) return result input_1 = int(input("Enter a positive int number:\n")) print("Question 1") print(f1(input_1)) # b comp1 = "O(n)" print("The complexity of the code is:", comp1) list1 = [1, 3, 4, 5, 9, 9] list2 = [1, 2, 3, 4, 5, 0] list3 = [4, 5, 6, 6, 7, -8, 9] def f2(l1, l2, l3): list_new = [] list_all = [] for i in l1: if i in l2 + l3: list_new.append(i) for j in l2: if j in l3: if j not in l1: list_new.append(j) for k in list_new: if k not in list_all: list_all.append(k) return list_all print(f2(list1, list2, list3)) # Question 3 # function f3 is a recursive function that gets a number bigger than 1 and finds An = 2An-1 - 3An-2 def f3(n): if n == 1: return 1 if n == 2: return 4 if n < 1: return "Enter an n bigger than 1" else: return 2*f3(n-1) - 3*f3(n-2) print() print("Question 3") while True: print("Please enter an integer n biggest than 0:") num = int(input()) if num > 0: break print(f"The An is: (by An = 2An-1 - 3An-2)\n{f3(num)}") # Question 4 # function f4 gets a list of numbers and returns a dictonary of numbers # organized in keys buy the first number(from left) the keys in the dictonary are (0-9) dictonary = {} def find(f): temp = abs(f) if temp > 10: return round(find(temp / 10)) else: return round(temp) def f4(list_of_numbers): for i in range(10): dictonary[i] = [] for number in list_of_numbers: temp = find(number) for i in range(10): if i == temp: dictonary[i].append(number) return dictonary types = [] print() print("Question 4") print(f4([12, -121, 1, 1111, 22.2, 2.2, 1234314.1, 0, 0])) # # showing the keys are from int type # for k in dictonary.keys(): # types.append(type(k)) # print(types) # Question 5 # class c5 checks if the right amount of palafel balls(between 2-7) used and if there is a sauce or not class c5: def __init__(self, Nb, s): self.Nb = Nb self.s = bool(s) assert (2 <= Nb <= 7), "This is not the right amount of falafel balls, min 2, max 7" assert (s == True) or (s == False), "s should be True or False" # print function prints number of balls and if there is a spicy sauce def __str__(self): if self.s: return f"Mana: {self.Nb} balls and has spicy sauce" else: return f"Mana: {self.Nb} balls and has no spicy sauce" # 5.bet # add function that add 2 manot falafel and checks if its possible # if its possible it makes the mix and checks if there was a sauce # if on 1 of the manot was a sauce than the mix will have a sauce # if neither were with the sauce the mix wont have a sauce def __add__(self, other): if self.Nb + other.Nb < 8: self.Nb = self.Nb + other.Nb else: return "Cant add the falafels cause too many balls" if self.s and other.s: self.s = other.s return f"Mana after merge: {self.Nb} balls and has spicy sauce" elif self.s and not other.s: other.s = self.s return f"Mana after merge: {self.Nb} balls and has spicy sauce" elif not self.s and other.s: self.s = other.s return f"Mana after merge: {self.Nb} balls and has spicy sauce" else: self.s = self.s return f"Mana after merge: {self.Nb} balls and has no spicy sauce" man = c5(2, True) man2 = c5(5, False) print() print("Question 5.alef") print("1st", man) print("2nd", man2) print() print("Question 5.bet") print(man+man2) def f6(N): counter = 0 prob = 0 for i in range(N): for j in range(10): dice = random.randrange(1, 7) round(dice) if dice == 6: counter += 1 if counter == 2: prob += 1 counter = 0 return prob/N print(f6(1000000)) # Question 7 # function f7a get a list of tuples and returns 3 random tuples from the list # with using random.sample def f7a(l): random.seed(2) r_list = random.sample(l, 3) return r_list # print(f7a([(1,2,1,1),(2,2,2,2),(3,3,3,3),(4,4,4,4)])) #Question 7.bet def euclidean_dist(vec1, vec2): dist = 0 for k in range(len(vec1)): dist += (vec1[k] - vec2[k]) ** 2 return dist ** 0.5 def f7b(l1, l2): first_vector = [] sec_vector = [] third_vector = [] for i in l1: min_euc = min(euclidean_dist(i, l2[0]), euclidean_dist(i, l2[1]), euclidean_dist(i, l2[2])) if euclidean_dist(i, l2[0]) == min_euc: first_vector.append(i) elif euclidean_dist(i, l2[1]) == min_euc: sec_vector.append(i) else: third_vector.append(i) return [first_vector, sec_vector, third_vector] def f7c(l): def compute_centroid(list): vals = pylab.array([0] * len(list[0])) for vec in list: # compute mean vals += vec return tuple(vals / len(list)) return [compute_centroid(l[0]), compute_centroid(l[1]), compute_centroid(l[2])] def f7d(l): initial_centroids = f7a(l) clusters = f7b(l, initial_centroids) new_centroids = f7c(clusters) while True: initial_centroids = new_centroids clusters = f7b(l, new_centroids) new_centroids = f7c(clusters) if initial_centroids == new_centroids: break return clusters # Question 8 # function f8 gets a list and sorts it from the highest to lowest and returns it def f8(l): flag = False while not flag: flag = True for n in range(len(l)): for k in range(n, 0, -1): if l[n] > l[k]: temp = l[k] l[k] = l[n] l[n] = temp flag = False if l[0] < l[1]: temp = l[0] del l[0] l.append(temp) flag = False return l comp2 = "O(n**3)" print() print("Question 8") print(f8([12, 4, 5, 122, 1, 13, 0])) print("The complexity is:", comp2) # Question 9 # the function f9 makes a linear regression def f9(tau, alpha): slope, intercept, r, p, std_err = stats.linregress(tau, alpha) def my_func(x): return slope * x + intercept model = list(map(my_func, tau)) plt.scatter(tau, alpha) plt.plot(tau, model) plt.show() return slope print() print("Question 9") f9([1, 2, 3, 4, 5], [6, 7, 8, 9, 10])
[ "noharbatit.9@gmail.com" ]
noharbatit.9@gmail.com
ef495dc49c8aacb3b2af95d4c40ebb6a453fa1ad
c6e2e537a6bf2a2e009a64eef76954dae30ae214
/tests/test_series_replacement.py
e36974b49ae8808c00c3818d5b1560e71d388bfc
[ "Unlicense" ]
permissive
mb5/tvnamer
46d0eb0ae8b4d8e72656d2dfc239555e91b2bfd2
ce4f7374ff8abbbe137aa7c43ed0ba0fe0f2f755
refs/heads/master
2021-01-18T02:49:44.110873
2012-12-13T09:21:39
2012-12-13T09:21:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,085
py
#!/usr/bin/env python """Tests custom replacements on input/output files """ from functional_runner import run_tvnamer, verify_out_data from nose.plugins.attrib import attr @attr("functional") def test_replace_input(): """Tests replacing strings in input files """ out_data = run_tvnamer( with_files = ['scruuuuuubs.s01e01.avi'], with_config = """ { "input_series_replacements": { "scru*bs": "scrubs"}, "always_rename": true, "select_first": true } """) expected_files = ['Scrubs - [01x01] - My First Day.avi'] verify_out_data(out_data, expected_files) @attr("functional") def test_replace_output(): """Tests replacing strings in input files """ out_data = run_tvnamer( with_files = ['Scrubs.s01e01.avi'], with_config = """ { "output_series_replacements": { "Scrubs": "Replacement Series Name"}, "always_rename": true, "select_first": true } """) expected_files = ['Replacement Series Name - [01x01] - My First Day.avi'] verify_out_data(out_data, expected_files)
[ "dbr.onix@gmail.com" ]
dbr.onix@gmail.com
d831ff7bbac8a88c716b003523818b763f425495
4978ce56457ac4c64075b2d70663c74cf4dc3896
/demoVisualizeDataFrame/__init__.py
2569839deb53775254f19d982557de5c755e1a7b
[ "MIT" ]
permissive
listenzcc/data_visualize
90700f4ca9f22e351363b3c91b7bd30beac136a2
7f0867e19e3ae88041efb24c79789b1bc4b46f40
refs/heads/master
2023-03-13T20:53:01.126166
2021-03-20T02:49:14
2021-03-20T02:49:14
315,854,997
0
0
null
null
null
null
UTF-8
Python
false
false
966
py
# File: __init__.py # Aim: economyZone package startup script import configparser import logging import os import sys import pandas as pd def beside(name, this=__file__): # Get path of [name] beside __file__ return os.path.join(os.path.dirname(this), name) config = configparser.ConfigParser() config.read(beside('setting.ini')) logger = logging.Logger('demoVisualizeDataFrame', level=logging.DEBUG) for handler, formatter in zip([logging.StreamHandler(sys.stdout), logging.FileHandler('logging.log')], [logging.Formatter('%(filename)s %(levelname)s %(message)s'), logging.Formatter('%(asctime)s %(name)s %(filename)s %(levelname)s %(message)s')]): handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.DEBUG) logger.info('info') logger.debug('debug') logger.warning('warning') logger.error('error') logger.fatal('fatal')
[ "listenzcc@mail.bnu.edu.cn" ]
listenzcc@mail.bnu.edu.cn
048c2c28d81f61ade6bb91e3c6025ccdb74bd471
1ab99223dfef768cbead2813d039c66a627024be
/api/src/opentrons/drivers/temp_deck/__init__.py
91a9ef7bba1f13dc509decc0dfe380a038bf462a
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
fakela/opentrons
f399b8a9444ea557072a00477d0c8176e46e433e
7552a1cbe6d06131bd45241b027f27e11428e100
refs/heads/master
2022-11-21T01:32:40.084185
2020-06-29T18:27:00
2020-06-29T18:27:00
280,266,622
0
0
Apache-2.0
2020-07-16T21:55:27
2020-07-16T21:55:26
null
UTF-8
Python
false
false
128
py
from opentrons.drivers.temp_deck.driver import TempDeck, SimulatingDriver __all__ = [ 'TempDeck', 'SimulatingDriver' ]
[ "noreply@github.com" ]
fakela.noreply@github.com
99d407e913ff467ad42df621f0b9be1d4a91cb8f
7bededcada9271d92f34da6dae7088f3faf61c02
/pypureclient/flashblade/FB_2_2/models/object_store_user.py
511b6638e591a3c91097395f049ed12ee8273e6b
[ "BSD-2-Clause" ]
permissive
PureStorage-OpenConnect/py-pure-client
a5348c6a153f8c809d6e3cf734d95d6946c5f659
7e3c3ec1d639fb004627e94d3d63a6fdc141ae1e
refs/heads/master
2023-09-04T10:59:03.009972
2023-08-25T07:40:41
2023-08-25T07:40:41
160,391,444
18
29
BSD-2-Clause
2023-09-08T09:08:30
2018-12-04T17:02:51
Python
UTF-8
Python
false
false
4,119
py
# coding: utf-8 """ FlashBlade REST API A lightweight client for FlashBlade REST API 2.2, developed by Pure Storage, Inc. (http://www.purestorage.com/). OpenAPI spec version: 2.2 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re import six import typing from ....properties import Property if typing.TYPE_CHECKING: from pypureclient.flashblade.FB_2_2 import models class ObjectStoreUser(object): """ Attributes: swagger_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. """ swagger_types = { 'name': 'str', 'id': 'str', 'access_keys': 'list[FixedReference]', 'account': 'FixedReference', 'created': 'int' } attribute_map = { 'name': 'name', 'id': 'id', 'access_keys': 'access_keys', 'account': 'account', 'created': 'created' } required_args = { } def __init__( self, name=None, # type: str id=None, # type: str access_keys=None, # type: List[models.FixedReference] account=None, # type: models.FixedReference created=None, # type: int ): """ Keyword args: name (str): Name of the object (e.g., a file system or snapshot). id (str): A non-modifiable, globally unique ID chosen by the system. access_keys (list[FixedReference]): References of the user's access keys. account (FixedReference): Reference of the associated account. created (int): Creation timestamp of the object. """ if name is not None: self.name = name if id is not None: self.id = id if access_keys is not None: self.access_keys = access_keys if account is not None: self.account = account if created is not None: self.created = created def __setattr__(self, key, value): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `ObjectStoreUser`".format(key)) self.__dict__[key] = value def __getattribute__(self, item): value = object.__getattribute__(self, item) if isinstance(value, Property): return None else: return value def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): if hasattr(self, attr): 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: result[attr] = value if issubclass(ObjectStoreUser, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ObjectStoreUser): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "msholes@purestorage.com" ]
msholes@purestorage.com
d22c1861f13411c3d3e664e9a8bfcc28701f4a32
add7f191d38538f0ecca582264ee733d8f5d0e99
/tests/strategies/test_strategy.py
74b0acb55b9c834b446c7e4c5445e7dcddad0538
[]
no_license
netfily/simian-wallet
2feab3080adf3cf59882aba9931c70bcb38c2c38
f4b2eb1688411cddd0b6bd703a43f7c7123cc3bf
refs/heads/master
2023-02-11T03:19:07.382213
2021-01-12T20:26:29
2021-01-12T20:26:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,615
py
def test_strategy_from_owner(wallet, do_nothing, empty_strategy, owner): data = do_nothing.nothing.encode_input(0) tx = wallet.execute(do_nothing, empty_strategy, data, {'from': owner}) strategy_value = int(repr(tx.return_value[1]), 16) assert strategy_value == 666 def test_user_cant_use_strategy(wallet, do_nothing, empty_strategy, owner, user): sig = do_nothing.signatures['nothing'] wallet.permit(user, do_nothing, sig, {'from': owner}) data = do_nothing.nothing.encode_input(0) tx = wallet.execute(do_nothing, empty_strategy, data, {'from': user}) strategy_value = tx.return_value[1] assert strategy_value == "0x" def test_permit_user_strategy(wallet, do_nothing, empty_strategy, owner, user, strategy_sig): sig = do_nothing.signatures['nothing'] wallet.permit(user, do_nothing, sig, {'from': owner}) wallet.permit(user, empty_strategy, strategy_sig, {'from': owner}) data = do_nothing.nothing.encode_input(0) tx = wallet.execute(do_nothing, empty_strategy, data, {'from': user}) strategy_value = int(repr(tx.return_value[1]), 16) assert strategy_value == 666 def test_permit_user_all_strategies( wallet, empty_strategy, empty_strategy2, owner, user, all_addr, strategy_sig ): assert wallet.canCall(user, empty_strategy, strategy_sig) is False assert wallet.canCall(user, empty_strategy2, strategy_sig) is False wallet.permit(user, all_addr, strategy_sig, {'from': owner}) assert wallet.canCall(user, empty_strategy, strategy_sig) is True assert wallet.canCall(user, empty_strategy2, strategy_sig) is True
[ "matnad@gmail.com" ]
matnad@gmail.com
fe0bf6676519e72dbc2a8a07ce3b89292806afe0
2352bc07e12b0256913559cf3485a360569ccd5e
/practice/python-tutorial-master/26cv/data_enhancement/resize_demo.py
e9fc3f21cbde46712f831ed1aa864e567fd482db
[ "Apache-2.0" ]
permissive
Dis-count/Python_practice
166ae563be7f6d99a12bdc0e221c550ef37bd4fd
fa0cae54e853157a1d2d78bf90408c68ce617c1a
refs/heads/master
2022-12-12T03:38:24.091529
2021-12-22T09:51:59
2021-12-22T09:51:59
224,171,833
2
1
null
2022-12-08T05:29:38
2019-11-26T11:07:00
Jupyter Notebook
UTF-8
Python
false
false
955
py
# -*- coding: utf-8 -*- """ @author:XuMing(xuming624@qq.com) @description: """ import cv2 import os from PIL import Image def display_cv(image_path): img = cv2.imread(image_path) height, width = img.shape[:2] print(height, width) # 缩小图像 size = (200, 200) print(size) shrink = cv2.resize(img, size, interpolation=cv2.INTER_AREA) # 放大图像 fx = 1.6 fy = 1.2 enlarge = cv2.resize(img, (0, 0), fx=fx, fy=fy, interpolation=cv2.INTER_CUBIC) # 显示 cv2.imshow("src", img) cv2.imshow("shrink", shrink) cv2.imshow("enlarge", enlarge) cv2.waitKey(0) def display_pil(image_path): img = Image.open(image_path) # 缩小图像 size = (200, 200) print(size) new_img = img.resize((200, 200), Image.BILINEAR) new_img.show() new_img.save('data/resize_a.png') if __name__ == '__main__': # display_cv('flower.png') display_pil('data/flower.png')
[ "33273755+Dis-count@users.noreply.github.com" ]
33273755+Dis-count@users.noreply.github.com
982882bc61f19ad91edbfded17ce4f4cf73ba97e
d2e029233e08ea2b7f806728fb6fdb4313992d1d
/Object Orianted Programming In Python/@property.py
f4c9aceb926378d9cdc9dc96b285b0f1c7d11e2f
[]
no_license
pvr30/Python-Tutorial
f0ccc6c6af2346afc656e5f1f98bae69a58bda6d
3c4b968d0e0efbf454fbf9a9f98cd630a288b2d9
refs/heads/master
2023-06-02T10:08:50.891627
2021-06-21T16:36:11
2021-06-21T16:36:11
378,997,069
1
0
null
null
null
null
UTF-8
Python
false
false
987
py
# @property class Student: def __init__(self, name, school): self.name = name self.school = school self.marks = [] @property def average(self): return sum(self.marks) / len(self.marks) vishal = Student("Vishal Parmar","Axar") print(vishal.name) vishal.marks.append(90) vishal.marks.append(80) vishal.marks.append(55) # using @property we can make a method into value or property. # Instead of vishal.average() we can write vishal.average. print(vishal.average) """ You can do that with any method that doesn’t take any arguments. But remember, this method only returns a value calculated from the object’s properties. If you have a method that does things (e.g. save to a database or interact with other things), it can be better to stay with the brackets. Normally: * Brackets: this method does things, performs actions. * No brackets: this is a value (or a value calculated from existing values, in the case of `@property`). """
[ "vishalparmar6958@gmail.com" ]
vishalparmar6958@gmail.com
0a9fa79b93775e749b18b7dc2076725cce8b1a3a
addf291a1a4bad5d823e62422cdda4b73faa7a14
/src/util/convenient_funcs.py
4bbf2b61f62e541d7a99c01d77f3799da01d0cc8
[]
no_license
zhengxxn/AutoEssayScoring_NN
a8504f0ff975568746a8435760bea12bef410b09
faa030fe8fd8cf0612c01d4d7e94e25e76404aeb
refs/heads/master
2022-12-19T11:50:40.651591
2020-09-09T06:41:33
2020-09-09T06:41:33
294,025,273
0
0
null
null
null
null
UTF-8
Python
false
false
4,153
py
import pandas as pd # from sklearn.model_selection import train_test_split import re from pathlib import Path from collections import Counter import pickle import numpy as np def tensor2str(prediction, vocab): str = [] for i in range(0, prediction.size(0)): ch = vocab.itos[prediction[i]] if ch == '<eos>': break else: str.append(ch) return " ".join(str) def convert_xml_to_plaintext(src_file, trg_file): with open(src_file, 'r') as f: with open(trg_file, 'w') as wf: newlines = [] lines = f.readlines() for (i, line) in enumerate(lines): newline = re.sub('<seg id=\"[0-9]+\"> | </seg>', '', line, 2) if '<' not in newline: newlines.append(newline) wf.writelines(newlines) def save_to_tsv(file_path_1, file_path_2, tsv_file_path, domain=None): with open(file_path_1, encoding='utf-8') as f: src = f.read().split('\n')[:-1] with open(file_path_2, encoding='utf-8') as f: trg = f.read().split('\n')[:-1] if domain is not None: raw_data = {'src': [line for line in src], 'trg': [line for line in trg], 'domain': [domain for line in src]} else: raw_data = {'src': [line for line in src], 'trg': [line for line in trg]} df = pd.DataFrame(raw_data) df.to_csv(tsv_file_path, index=False, sep='\t') def new_save_to_tsv(config, tsv_file_path): raw_data = {} for key in config.keys(): file_name = config[key] with open(file_name, encoding='utf-8') as f: lines = f.read().split('\n')[:-1] value = [line for line in lines] raw_data[key] = value df = pd.DataFrame(raw_data) df.to_csv(tsv_file_path, index=False, sep='\t') def get_path_prefix(path): return re.sub('/[^/]+$', '', path, 1) def create_path(path): path = Path(path) path.mkdir(parents=True, exist_ok=True) def de_bpe(str): return re.sub(r'@@ |@@ ?$', '', str) def generate_vocab_counter(file): c = Counter() with open(file, 'r', encoding='utf-8') as f: lines = f.readlines() for line in lines: word, freq = line.split(' ') c[word] = int(freq) return c def print_model(model): print(model) for name, param in model.named_parameters(): print(name, param.size()) def combine_sentence_to_segment(sents: list, max_segment_len=400): segments = [] segment = '' for sent in sents: if segment == '': segment = sent elif len(segment.split(' ')) + len(sent.split(' ')) > max_segment_len: segments.append(segment) segment = '' segment = segment + sent else: segment = segment + ' ' + sent segments.append(segment) return segments def get_feature_from_ids(ids, file_name): with open('/home/user_data55/zhengx/project/data/auto_score/train.feature', 'rb') as train_f: train_features = {} train_features = pickle.load(train_f) with open('/home/user_data55/zhengx/project/data/auto_score/dev.feature', 'rb') as dev_f: dev_featues = {} dev_featues = pickle.load(dev_f) features = [] for id in ids: if id in train_features.keys(): features.append(train_features[id]) else: features.append(dev_featues[id]) return features def get_feature_from_test_ids(ids, filename): with open('/home/user_data55/zhengx/project/data/auto_score/test.feature', 'rb') as test_f: test_features = {} test_features = pickle.load(test_f) features = [] for id in ids: if id in test_features.keys(): features.append(test_features[id]) else: features.append(test_features[id]) return features def more_uniform(values): mean = np.average(values) for i, value in enumerate(values): gap = value - mean if 0 < gap < 1: value += 0.5 if 0 > gap > 1: value -= 0.5 values[i] = value return values
[ "zhengx9703@gmail.com" ]
zhengx9703@gmail.com
516a664d5e69b3e6ccc8b980b298b28226e04d80
aa9297175621fcd499cad5a0373aaad15f33cde8
/udemy-py/practica-clases/mundo_pc/raton.py
526bdec66619a3f912fd0fdfad898366d48d57f1
[]
no_license
eflipe/python-exercises
a64e88affe8f9deb34e8aa29a23a68c25e7ba08a
b7a429f57a5e4c5dda7c77db5721ca66a401d0a3
refs/heads/master
2023-04-26T19:19:28.674350
2022-07-19T20:53:09
2022-07-19T20:53:09
192,589,885
0
0
null
2023-04-21T21:23:14
2019-06-18T18:06:14
HTML
UTF-8
Python
false
false
703
py
from dispositivo_de_entrada import DispositivoEntrada class Raton(DispositivoEntrada): contador_producto = 0 def __init__(self, marca, tipo_entrada): Raton.contador_producto += 1 self._id_producto = Raton.contador_producto super().__init__(marca, tipo_entrada) def __str__(self): return f'\tID raton: {self._id_producto} \ \n\t\t\t\tMarca: {self._marca} \ \n\t\t\t\tTipo de entrada: {self._tipo_entrada}\n' if __name__ == '__main__': # es como una prueba obj_raton1 = Raton(marca='HP', tipo_entrada="USB") obj_raton2 = Raton(marca='Acer', tipo_entrada="Bluetooth") print(obj_raton1) print(obj_raton2)
[ "felipecabaleiro@gmail.com" ]
felipecabaleiro@gmail.com
aee1247903d18ea9a88a475d42322f840a9bcfbd
09cead98874a64d55b9e5c84b369d3523c890442
/py200622_python2/day12_py200730/datatype_2_decimal.py
ab59ad921dea94213327cd36e00e7fdbfcac34c5
[]
no_license
edu-athensoft/stem1401python_student
f12b404d749286036a090e941c0268381ce558f8
baad017d4cef2994855b008a756758d7b5e119ec
refs/heads/master
2021-08-29T15:01:45.875136
2021-08-24T23:03:51
2021-08-24T23:03:51
210,029,080
0
0
null
null
null
null
UTF-8
Python
false
false
1,324
py
""" numbers - decimal Due to this reason, most of the decimal fractions cannot be accurately stored in our computer. """ a = 1.1 + 2.2 # print(a) b = 3.3 # print(b) if a == b: print("a==b") else: print("a!=b") a = 1.1 + 0.1 b = 1.3 - 0.1 if a == b: print("a==b") else: print("a!=b") print() # question # 1.1 + 2.2 == 3.3 print(1.1 + 2.2 == 3.3) print(float(1.1)+float(2.2)==float(3.3)) print() print(1.1) print(2.2) print(3.3) print(1.1+2.2) print() print(1.1+2.2 > 3.3) print(1.1 + 2.2 == 3.3) print(1.1+2.2 < 3.3) print() # other example print("=== example 2 ===") f11 = 1.0 f12 = 0.1 f2 = 0.9 print("f11={}, f12={} and f2={}".format(f11,f12,f2)) print("{}-{} == {} ?".format(f11, f12, (f11-f12 == f2))) print("f11-f12 > f2 ?",f11-f12 > f2) print("f11-f12 < f2 ?",f11-f12 < f2) print() # decimal print("=== example 3 ===") f11 = 1.0 f12 = 0.3 f2 = 0.7 print("f11={}, f12={} and f2={}".format(f11,f12,f2)) print("f11-f12 == f2 ?",f11-f12 == f2) print("f11-f12 > f2 ?",f11-f12 > f2) print("f11-f12 < f2 ?",f11-f12 < f2) print() # faction print("=== example 4 ===") f11 = 1.0 f12 = 0.33 f2 = 0.67 print("f11={}, f12={} and f2={}".format(f11,f12,f2)) print("f11-f12 == f2 ?",f11-f12 == f2) print("f11-f12 > f2 ?",f11-f12 > f2) print("f11-f12 < f2 ?",f11-f12 < f2) print() print(1.0-0.33)
[ "lada314@gmail.com" ]
lada314@gmail.com
44189b3313b77752f57281d61124938352559d1a
0377a4135f9e8940809a62186b229295bed9e9bc
/201. 数字范围按位与/solution.py
cae779cbe0ac247a557b52a9f0b2723b028eedab
[]
no_license
neko-niko/leetcode
80f54a8ffa799cb026a7f60296de26d59a0826b0
311f19641d890772cc78d5aad9d4162dedfc20a0
refs/heads/master
2021-07-10T10:24:57.284226
2020-09-13T11:28:45
2020-09-13T11:28:45
198,792,951
0
0
null
null
null
null
UTF-8
Python
false
false
135
py
class Solution: def rangeBitwiseAnd(self, m: int, n: int) -> int: while m < n: n = n & (n-1) return n
[ "2361253285@qq.com" ]
2361253285@qq.com
c23bf011047c5d486f451c689ad1ad9bb5b648e7
060ce17de7b5cdbd5f7064d1fceb4ded17a23649
/fn_mcafee_esm/fn_mcafee_esm/util/config.py
18fc57d089d0070ed18677b9df04b68fd225e8a0
[ "MIT" ]
permissive
ibmresilient/resilient-community-apps
74bbd770062a22801cef585d4415c29cbb4d34e2
6878c78b94eeca407998a41ce8db2cc00f2b6758
refs/heads/main
2023-06-26T20:47:15.059297
2023-06-23T16:33:58
2023-06-23T16:33:58
101,410,006
81
107
MIT
2023-03-29T20:40:31
2017-08-25T14:07:33
Python
UTF-8
Python
false
false
1,020
py
# -*- coding: utf-8 -*- # (c) Copyright IBM Corp. 2010, 2018. All Rights Reserved. """Generate a default configuration-file section for fn_mcafee_esm""" from __future__ import print_function def config_section_data(): """Produce the default configuration section for app.config, when called by `resilient-circuits config [-c|-u]` """ config_data = u"""[fn_mcafee_esm] # url example: https://127.0.0.1 esm_url=<your_esm_url> esm_username=<your_esm_username> esm_password=<your_esm_password> # If your ESM server uses a cert which is not automatically trusted by your machine, set verify_cert=False. verify_cert=[True|False] ## ESM Polling settings # How often polling should happen. Value is in seconds. To disable polling, set this to zero. esm_polling_interval=0 #incident_template=<location_of_template_file> # If not set uses default template. # Optional settings for access to McAfee ESM via a proxy. #http_proxy=http://proxy:80 #https_proxy=http://proxy:80 """ return config_data
[ "shane.curtin@ie.ibm.com" ]
shane.curtin@ie.ibm.com
ead463a4fe241c5a35c668a64bc671fe9bf1d28b
3d30aa4f3a7a3ab8a0a2b75bf3e437834be8c354
/Victor/dq2.victor.cms/lib/dq2/common/externalcall.py
4591bda4bb0c2a8b0a928653bcb80b78219075f0
[]
no_license
mmeoni/DDM
c3baa1f97fe9d1ff0272819bee81a7424cf028db
faba3a414009a362471a8f1eae8f9c11e884c8fd
refs/heads/master
2021-01-22T07:19:06.698307
2016-08-12T07:50:37
2016-08-12T07:50:37
36,882,324
1
0
null
2015-06-04T16:28:47
2015-06-04T16:28:47
null
UTF-8
Python
false
false
2,528
py
""" Module for handling external process calls. @author: Miguel Branco @contact: miguel.branco@cern.ch @since: 1.0 @version: $Id: externalcall.py,v 1.1 2008-05-19 13:16:09 mbranco Exp $ """ import os import signal import sys import time import tempfile class ExternalCallException(Exception): pass class ExternalCallTimeOutException(ExternalCallException): pass def call(cmd, min_secs=1, timeout_secs=30, interval_secs=1, kill_on_timeout=True): """ Do external call by spawning new process. @raise ExternalCallException: In case of error. @raise ExternalCallTimeOutException: In case of timeout. @return: Tuple with status, output """ cmd = cmd.strip() try: output = tempfile.mktemp() except RuntimeWarning: pass except: raise ExternalCallException("Could not create temporary file.") startTime = time.time() try: childPid = os.fork() except: raise ExternalCallException("Could not spawn process to serve '%s'." % cmd) if childPid == 0: try: # child process os.setpgrp() # group leader # redirect outputs to file f = open(output, 'w') os.dup2(f.fileno(), sys.stdout.fileno()) os.dup2(f.fileno(), sys.stderr.fileno()) # execute ... args = cmd.split(' ') os.execvp(args[0], args) finally: os._exit(1) # parent process time.sleep(min_secs) exitCode = None finished = False while time.time() - startTime < timeout_secs: try: pid, exitCode = os.waitpid(childPid, os.P_NOWAIT) if pid == 0: # not finished time.sleep(interval_secs) continue elif pid > 0: # done finished = True break except: break try: if finished: # read output file f = open(output, 'r') ll = f.readlines() f.close() return exitCode, ''.join(ll) # timed out if kill_on_timeout: os.killpg(childPid, signal.SIGKILL) time.sleep(1) # wait for any child process without hanging try: r = os.waitpid(-1, os.WNOHANG) except: pass raise ExternalCallTimeOutException("Call to '%s' timed out." % cmd) finally: try: # always remove temporary file os.remove(output) except: pass
[ "domenico.giordano@cern.ch" ]
domenico.giordano@cern.ch
a6b8f9a1376495aee62bb8eea0c2eb13932266ce
69e7dca194ab7b190e1a72928e28aa3821b47cfb
/Concepts/2 Pointers/253.py
e02124f3f456efdf679b47a09afeffb2a9ce993d
[]
no_license
Dinesh94Singh/PythonArchivedSolutions
a392891b431d47de0d5f606f7342a11b3127df4d
80cca595dc688ca67c1ebb45b339e724ec09c374
refs/heads/master
2023-06-14T14:56:44.470466
2021-07-11T06:07:38
2021-07-11T06:07:38
384,871,541
0
0
null
null
null
null
UTF-8
Python
false
false
1,018
py
""" Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required. Example 1: Input: [[0, 30],[5, 10],[15, 20]] Output: 2 Example 2: Input: [[7,10],[2,4]] Output: 1 NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature. """ def min_meeting_rooms_using_2_ptrs(intervals): start_array = sorted([i[0] for i in intervals]) end_array = sorted([i[1] for i in intervals]) used_rooms = 0 start_ptr, end_ptr = 0, 0 while start_ptr < len(intervals): if start_array[start_ptr] >= end_array[end_ptr]: # if the meeting starts after the previous meeting - we can use the same room used_rooms -= 1 end_ptr += 1 used_rooms += 1 start_ptr += 1 return used_rooms min_meeting_rooms_using_2_ptrs([[7, 10], [2, 4]]) min_meeting_rooms_using_2_ptrs([[0, 30], [5, 10], [15, 20]])
[ "dinesh94singh@gmail.com" ]
dinesh94singh@gmail.com
3ae95fdf927adc96976bbe3b77a757f102b1f3b7
5b0f27b1a6452328b3d289a9f81ba3b23d1579b2
/search.py
6c5ff409cde9509470885667056aba148eb82795
[ "MIT" ]
permissive
gtback/rfc-elasticsearch
8151e447af267fedc772d90f4e73b2e8eeac20e3
17c03d0dfbd7f7d9c2e22e653e055d3024d5aa8a
refs/heads/master
2023-05-24T18:59:37.731462
2020-12-17T15:04:44
2020-12-17T15:04:44
28,681,471
1
0
MIT
2023-05-23T00:51:22
2015-01-01T06:06:00
Python
UTF-8
Python
false
false
559
py
#!/usr/bin/env python import sys import requests BASE_URL = "http://localhost:9200/" INDEX = "rfc" def main(): term = sys.argv[1] r = requests.get(BASE_URL + INDEX + "/_search/?q=%s" % term) results = r.json() res_count = results['hits']['total'] time = results['took'] / 1000.0 print "%s results in %s s" % (res_count, time) for hit in results['hits']['hits']: print "%s - %s (%s)" % (hit['_id'].upper(), hit['_source']['title'], hit['_score']) if __name__ == '__main__': main()
[ "gback@mitre.org" ]
gback@mitre.org
ba05471bc5c24f3e2eafdba09eec9e21d783c8a4
b45d5a1068d47efde8e3c816d68049f7195ba13e
/app/main/MyFlowDomain.py
99f631401ae5de3424c81ee3b74a1137126c0047
[]
no_license
guohongjie/YuHuiAutoApi
57e2c9c84f95030a08f3605e5d337ded051bf50f
02a52e364f79810bd902f977051469b283889407
refs/heads/master
2021-03-03T14:38:47.433661
2020-04-30T09:56:27
2020-04-30T09:56:27
245,967,508
5
0
null
null
null
null
UTF-8
Python
false
false
5,384
py
#!/usr/bin/python #-*-coding:utf-8 -*- from app.main import flow from flask import render_template,request,make_response,jsonify,session from app.config.api_models import Run_Suite,Test_Domain from app.config.user_models import DeptName from app import db from sqlalchemy import func @flow.route("/myFlowDomain",methods=["GET"]) def myFlowDomainIndex(): """ 工作流配置主页 :return: """ # api_project = Project.query.with_entities(Project.project).distinct().all() #提取测试项目,传入页面中 test_doamin = Test_Domain.query.filter(Test_Domain.statu==1).distinct().all() test_group = DeptName.query.filter(DeptName.status==1).all() return render_template("flow/flowManger.html", test_groups=test_group,test_doamin=test_doamin) @flow.route("/flowSearch",methods=["GET"]) def flowSearch(): """ 查询工作流 :return: """ test_group = request.args.get('test_group') # 项目组名称 test_domain = request.args.get('test_domain') # 项目组名称 if test_group == 'None' and test_domain == 'None': # 当项目为空、接口名为空、状态为 全部 datas = Run_Suite.query.all() elif test_group != 'None' and test_domain == 'None': datas = Run_Suite.query.filter(Run_Suite.test_group==test_group).all() elif test_group != 'None' and test_domain != 'None': datas = Run_Suite.query.filter(Run_Suite.test_group == test_group ).filter( func.find_in_set(test_domain,Run_Suite.domain)).order_by( Run_Suite.RunOrderId).all() else: datas = Run_Suite.query.filter( func.find_in_set(test_domain,Run_Suite.domain) ).order_by(Run_Suite.RunOrderId).all() suiteList = [] for singleDatas in datas: suiteDatas = {"id":singleDatas.id, "RunOrderId":singleDatas.RunOrderId, "domain":singleDatas.domain, "name":singleDatas.suiteName, "desc":singleDatas.description, "statu": "启用" if singleDatas.statu else "停用", "test_group":singleDatas.test_group} suiteList.append(suiteDatas) resp = {"status": 200, "datas": suiteList} msg_resp = make_response(jsonify(resp)) return msg_resp @flow.route("/flowSingleDatas",methods=["GET"]) def flowSingleDatas(): """修改查询数据""" flow_id = request.args.get("flow_id") datas = Run_Suite.query.filter(Run_Suite.id==flow_id).first() deptNameSession = session.get("deptName") isAdmin = session.get("isAdmin") if datas.test_group != deptNameSession and isAdmin != True: resp = {'datas': "当前部门与工作流所属部门不同,无权限修改!", 'code': '400'} return make_response(jsonify(resp)) msg = {"id":datas.id, "test_group":datas.test_group, "name":datas.suiteName, "domain":datas.domain, "statu":datas.statu, "desc":datas.description, "user":datas.user, "flow_order":datas.RunOrderId} resp ={"status":200,"datas":msg} return make_response(jsonify(resp)) @flow.route("/flowSaveUpdate",methods=["GET"]) def flowSaveUpdate(): """ 保存修改功能 :return: """ flow_id = request.args.get("flow_id") flow_name = request.args.get("flow_name") flow_domain = request.args.get("flow_domain") flow_statu = request.args.get("flow_statu") flow_desc = request.args.get("flow_desc") user = request.args.get("tester") flow_order = request.args.get("flow_order") if not flow_order.isdigit(): resp = {'datas': "执行序号必须为数字", 'code': '400'} return make_response(jsonify(resp)) try: datas = Run_Suite.query.filter_by(id=flow_id).update(dict(user=user, suiteName=flow_name, domain=flow_domain, statu= 1 if flow_statu=="1" else 0, RunOrderId=int(flow_order), description=flow_desc)) db.session.commit() resp = {'datas': '更新成功', 'code': '200'} except Exception as e: db.session.rollback() resp = {'datas': str(e), 'code': '400'} return make_response(jsonify(resp)) @flow.route("/flowDelete",methods=["GET"]) def flowDelete(): flow_id = request.args.get("flow_id") datas = Run_Suite.query.filter(Run_Suite.id == flow_id).first() deptNameSession = session.get("deptName") isAdmin = session.get("isAdmin") if datas.test_group != deptNameSession and isAdmin != True: resp = {'datas': "当前部门与工作流所属部门不同,无权限修改!", 'code': '400'} return make_response(jsonify(resp)) else: try: db.session.delete(datas) db.session.commit() resp = {'datas': '删除成功', 'code': '200'} except Exception as e: db.session.rollback() resp = {"code": 400, "datas": str(e)} return make_response(jsonify(resp))
[ "guohongjie@yunshuxie.com" ]
guohongjie@yunshuxie.com
c87f3ed339fd6c794bdc2916bc2f460d92c9aae9
f5470aedfce5d43809168e8b1c529033a14b12d9
/reudom/__init__.py
eed71ceda06a7a3ab536b304e539df50436dba8f
[ "Apache-2.0" ]
permissive
braveryzhangsan/reudom
b090db637551de6e5bd2bf726dccc9da42fa4c3a
1ce2856f2bb7e5fdd4d2d540c9f5601f4dbbadc9
refs/heads/master
2022-12-01T10:45:42.507158
2020-08-14T09:00:32
2020-08-14T09:00:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,161
py
#!/usr/bin/python # # Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from .running.test_runner import main from .case import TestCase from .case import * from .testdata import ddt, ddt_class from .skip import skip import requests from requests import * from unittest import TestCase __author__ = "Barry" __version__ = "1.2.0.3" __description__ = "Automated testing framework based on requests and unittest interface."
[ "2652612315@qq.com" ]
2652612315@qq.com
f543888adbefabe562adb049c44de8222055a93f
728871b962f2a5ec8d8ec7d5b607def074fb8864
/W261/HW3-Questions/reducer_s.py
0b5a9d1f4172b97eac80fbd901c5d89e218febb1
[]
no_license
leiyang-mids/MIDS
0191ffbaf9f7f6ec0e77522241c3e76d012850f1
918b0d8afc395840626eb31c451ad6c4b2f3bc39
refs/heads/master
2020-05-25T15:46:56.480467
2019-03-28T16:16:17
2019-03-28T16:16:17
35,463,263
1
2
null
null
null
null
UTF-8
Python
false
false
333
py
#!/usr/bin/python import sys # increase counter for mapper being called sys.stderr.write("reporter:counter:HW3_5,Reducer_s_cnt,1\n") n_out = 0 n_top = 50 print 'top %d pairs: ' %n_top for line in sys.stdin: # parse mapper output n_out += 1 if n_out <= n_top: print line.strip().replace(',', '\t')
[ "ynglei@gmail.com" ]
ynglei@gmail.com
b9384b6227707f4ed9d583e9c974d5122e70e454
ab9196b6356e3c0af7baf7b768d7eb8112243c06
/Django/Django_day1/blog/urls.py
c63f69d4cac9c4131fcef86ac418244139d24999
[]
no_license
wngus9056/Datascience
561188000df74686f42f216cda2b4e7ca3d8eeaf
a2edf645febd138531d4b953afcffa872ece469b
refs/heads/main
2023-07-01T00:08:00.642424
2021-08-07T02:10:25
2021-08-07T02:10:25
378,833,144
0
0
null
null
null
null
UTF-8
Python
false
false
187
py
from django.urls import path from blog import views urlpatterns = [ path("", views.index, name="index"), path("<int:pk>/", views.article_detail, name="article_detail"), ]
[ "noreply@github.com" ]
wngus9056.noreply@github.com
19a4702b76ab3e91095edea734a8f7632647851e
eae6ed9ec6cd4a08b133fab43c7ccd4a9de090ec
/reviews/admin.py
896e389e21e18eea5beb99413ab9776fbf5a5903
[]
no_license
apple2062/airbnb-Django
3e891ad694a023993ae22b8063774fc740f57bc6
980b9015918393ddfc3ad4646d22fe8f5be6b159
refs/heads/master
2023-03-05T17:09:51.035035
2021-02-18T08:44:11
2021-02-18T08:44:11
299,503,702
0
0
null
null
null
null
UTF-8
Python
false
false
309
py
from django.contrib import admin from . import models @admin.register(models.Review) class ReviewAdmin(admin.ModelAdmin): """Review Admin Definition """ list_display = ( "__str__", "rating_average", ) # 이와 같은 식으로 나의 __str__을 list_display에 쓸 수 있음
[ "apple2062@naver.com" ]
apple2062@naver.com
1932461e9eaad09216df97a1a08acf7dd0573387
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p00007/s079875761.py
c6d74398ecb3fb6ceb055304bb8e512da7996b70
[]
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
239
py
import sys import math def main(): n = int(input().rstrip()) r = 1.05 digit = 3 a = 100000 for i in range(n): a = math.ceil(a*r/10**digit)*10**digit print(a) if __name__ == '__main__': main()
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
685efba0c2f64061426542281e99688f1b173005
e81d274d6a1bcabbe7771612edd43b42c0d48197
/Python基础/day17(函数工具、时间工具、加密工具)/demo/03_hashlib/01_hashlib.py
ad4d27b1aad677915b9e48e3a02260f4c9eacbb9
[ "MIT" ]
permissive
ChWeiking/PythonTutorial
1259dc04c843382f2323d69f6678b9431d0b56fd
1aa4b81cf26fba2fa2570dd8e1228fef4fd6ee61
refs/heads/master
2020-05-15T00:50:10.583105
2016-07-30T16:03:45
2016-07-30T16:03:45
null
0
0
null
null
null
null
UTF-8
Python
false
false
445
py
''' 账户: laowang@qq.com laowang@qq.com 登录密码: gebilaowang 234khkhwrk998y892h3i4hkhkhwkrhwr8h2k34hk32hr 支付密码: 123321 skhksjhoiw329822oi3h4hkjshrkjshkdshfiudshsih ''' import hashlib pwd = '123456' #md5加密的对象 m = hashlib.md5() #将密码更新加密对象中 m.update(pwd.encode('utf-8')) #生成长度32的16进制组成的字符串 pwd = m.hexdigest() print(pwd) ''' 自学sha模块的加密 '''
[ "1025212779@qq.com" ]
1025212779@qq.com
1d6334b644cc3563d65c5dcb164895fcfa99b8f9
a8e2c66b3ebadfc17ee9aee197b3f466534cee16
/system/venv/Scripts/pip3.5-script.py
76456cfd70a2ec5f697bd1105a920e5d016e2128
[]
no_license
yintiannong/98kar
49b6db186a4543a7c50671df990bb491846c1a98
3863529f57e9d2d9bc1bdf8188916e25ad289db0
refs/heads/master
2022-01-07T05:49:31.566453
2019-05-22T07:04:45
2019-05-22T07:04:45
187,794,966
0
0
null
null
null
null
UTF-8
Python
false
false
393
py
#!F:\0000\system\venv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip3.5' __requires__ = 'pip==10.0.1' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('pip==10.0.1', 'console_scripts', 'pip3.5')() )
[ "1532295578@qq.com" ]
1532295578@qq.com
1effd3531266c311d607bffb7b5933a9f7a7671a
a2181507e57baca97a1cf1bbbdc9c631f133b446
/booking/admin.py
f9cdaa8eafb7b21ee90df4eb2bbcb8bce2d66ac5
[]
no_license
Fabricourt/tika
b35739cb61dde3eeb454d05acb871f992e29a82d
bcf1bc6b9cac54eb866ad1e543fba23bcdbba9e1
refs/heads/master
2023-05-02T18:37:48.487231
2019-06-13T15:46:09
2019-06-13T15:46:09
191,501,190
0
0
null
2023-04-21T20:32:25
2019-06-12T05:06:35
JavaScript
UTF-8
Python
false
false
307
py
from django.contrib import admin from .models import About, Lessor, Lessee, Truck, Onhire, Booktruck, Driver admin.site.register(About) admin.site.register(Lessor) admin.site.register(Lessee) admin.site.register(Truck) admin.site.register(Driver) admin.site.register(Onhire) admin.site.register(Booktruck)
[ "mfalme2030@gmail.com" ]
mfalme2030@gmail.com
8d7c8cce3c07460bc3645dc375c8ef5e68c8ff68
2ef27655cd1deb9de4074249e559269abd334fa1
/6 kyu/Rock, Paper, Scissor, Lizard, Spock Game.py
6b24043430a8cbc31ae6e9d04f0b19255d9e8a30
[]
no_license
sieczkah/Codewars_KATA
c7606b9a88693e2550af0ef55808f34c00e77b73
68d5d4a133a015e49bcdbff29ee45e3baefcd652
refs/heads/main
2023-05-06T03:59:01.403765
2021-05-24T19:36:34
2021-05-24T19:36:34
334,698,441
1
0
null
null
null
null
UTF-8
Python
false
false
560
py
"""https://www.codewars.com/kata/569651a2d6a620b72e000059/train/python""" options = { 'spock': ['scissor', 'rock'], 'scissor': ['paper', 'lizard'], 'paper': ['rock', 'spock'], 'rock': ['lizard', 'scissor'], 'lizard': ['spock', 'paper'] } def result(p1, p2): if p1.lower() not in options.keys() or p2.lower() not in options.keys(): return 'Oh, Unknown Thing' elif p1.lower() == p2.lower().lower(): return 'Draw!' else: return 'Player 1 won!' if p2.lower() in options[p1.lower()] else 'Player 2 won!'
[ "huberts94@gmail.com" ]
huberts94@gmail.com
01d4e8dcf4a15b667c439fd1bdde4d23f2aad2fb
0206ac23a29673ee52c367b103dfe59e7733cdc1
/src/crcm5/analyze_rpn/plot_seasonal_means_from_daily_files.py
ab4e79a4d5f0103b3070eb6fa9639041fa46cd98
[]
no_license
guziy/RPN
2304a93f9ced626ae5fc8abfcc079e33159ae56a
71b94f4c73d4100345d29a6fbfa9fa108d8027b5
refs/heads/master
2021-11-27T07:18:22.705921
2021-11-27T00:54:03
2021-11-27T00:54:03
2,078,454
4
3
null
null
null
null
UTF-8
Python
false
false
3,284
py
from datetime import datetime from pathlib import Path from matplotlib import cm from matplotlib.colors import BoundaryNorm from rpn.domains.rotated_lat_lon import RotatedLatLon from application_properties import main_decorator from mpl_toolkits.basemap import cm as cm_basemap, Basemap __author__ = 'huziy' from rpn.rpn import RPN import pandas as pd import numpy as np import matplotlib.pyplot as plt import cartopy.crs as ccrs import os """ Read data from an RPN file, calculate daily mean fields and plot them """ @main_decorator def main(): path = "/RESCUE/skynet3_rech1/huziy/CNRCWP/Calgary_flood/Global_NA_v1/Samples/Global_NA_v1_201306/pm2013010100_00017280p" varname = "PR" plot_units = "mm/day" mult_coeff = 1000 * 24 * 3600 add_offset = 0 img_folder = "/RESCUE/skynet3_rech1/huziy/CNRCWP/Calgary_flood/glob_sim/{}/monthly/{}".format(varname, os.path.basename(path)) img_folder = Path(img_folder) if not img_folder.is_dir(): img_folder.mkdir(parents=True) r = RPN(path=path) pr = r.get_all_time_records_for_name(varname=varname) lons2d, lats2d = r.get_longitudes_and_latitudes_for_the_last_read_rec() rll = RotatedLatLon(**r.get_proj_parameters_for_the_last_read_rec()) bmp = rll.get_basemap_object_for_lons_lats(lons2d=lons2d, lats2d=lats2d, resolution="c", no_rot=True) # bmp = Basemap(projection="robin", lon_0=180) xx, yy = bmp(lons2d, lats2d) dates = list(sorted(pr.keys())) data = np.array([pr[d] for d in dates]) p = pd.Panel(data=data, items=dates, major_axis=range(data.shape[1]), minor_axis=range(data.shape[2])) # p_daily = p.groupby(lambda d: d.day, axis="items").mean() p_daily = p.apply(np.mean, axis="items") print(p_daily.head()) lons2d[lons2d > 180] -= 360 bmap_params = bmp.projparams bmap_params.update({ 'llcrnrlon': lons2d[0, 0], 'urcrnrlon': lons2d[-1, -1], 'llcrnrlat': lats2d[0, 0], 'urcrnrlat': lats2d[-1, -1] }) rpole_crs = ccrs.RotatedPole(pole_longitude=bmap_params["lon_0"] + 180, pole_latitude=bmap_params["o_lat_p"]) clevs = [0, 0.01, 0.1, 1, 1.5, 2, 5, 10, 20, 40, 60, 80] norm = BoundaryNorm(clevs, ncolors=len(clevs) - 1) cmap = cm.get_cmap(cm_basemap.s3pcpn, len(clevs) - 1) field = p_daily.values * mult_coeff + add_offset fig = plt.figure() plt.title("{}, {}/{}/{}, {}".format(varname, 1, dates[0].month, dates[0].year, plot_units)) ax = plt.axes(projection=rpole_crs) ax.coastlines(resolution='110m') ax.gridlines() ax.gridlines() # cs = bmp.contourf(xx, yy, field, clevs, norm=norm, extend="max", cmap=cmap) cs = ax.pcolormesh(lons2d[:-1, :-1], lats2d[:-1, :-1], field[:-1, :-1], norm=norm, cmap=cmap, transform=rpole_crs) plt.colorbar(cs, ticks=clevs, extend="max", ax=ax) img_file = img_folder.joinpath("{:02d}-{:02d}-{}.png".format(1, dates[0].month, dates[0].year)) # bmp.drawcoastlines() # bmp.drawstates() # bmp.drawcounties() # bmp.drawcountries() plt.savefig(img_file.open("wb")) plt.close(fig) print(pr[dates[0]].mean()) if __name__ == '__main__': main()
[ "guziy.sasha@gmail.com" ]
guziy.sasha@gmail.com
9b1ccf4577a0ee9a0044fe6dbc23a91a8f570aaf
9e988c0dfbea15cd23a3de860cb0c88c3dcdbd97
/sdBs/AllRun/sdssj_115035.62+253205.1/sdB_sdssj_115035.62+253205.1_lc.py
696ade788c191929320b6afdc107af3e3807ea07
[]
no_license
tboudreaux/SummerSTScICode
73b2e5839b10c0bf733808f4316d34be91c5a3bd
4dd1ffbb09e0a599257d21872f9d62b5420028b0
refs/heads/master
2021-01-20T18:07:44.723496
2016-08-08T16:49:53
2016-08-08T16:49:53
65,221,159
0
0
null
null
null
null
UTF-8
Python
false
false
370
py
from gPhoton.gAperture import gAperture def main(): gAperture(band="NUV", skypos=[177.648417,25.53475], stepsz=30., csvfile="/data2/fleming/GPHOTON_OUTPU/LIGHTCURVES/sdBs/sdB_sdssj_115035.62+253205.1/sdB_sdssj_115035.62+253205.1_lc.csv", maxgap=1000., overwrite=True, radius=0.00555556, annulus=[0.005972227,0.0103888972], verbose=3) if __name__ == "__main__": main()
[ "thomas@boudreauxmail.com" ]
thomas@boudreauxmail.com
5b788699d45a5655649f9b4f4c5222a5daa8ec11
e53cfac2eadeaf9727ec055b4cd524320cf8ded5
/26.04/Вариант 19 Поляков/8-1942.py
397399f64c005a1bdde980e0ae6acdaec09aeb18
[]
no_license
NevssZeppeli/my_ege_solutions
55322d71dcc9980e2cf894ea2b88689dca807943
7a25c93b8a58b03d0450627f1217972fbf7d04f6
refs/heads/master
2023-06-17T19:58:28.388391
2021-07-03T16:03:36
2021-07-03T16:03:36
380,223,538
3
1
null
null
null
null
UTF-8
Python
false
false
435
py
с = 0 for x in 'НОДА': for y in 'НОДА': if x == y: continue for w in 'НОДА': if w in x + y: continue for z in 'НОДА': if z in x + y + w: continue word = x+y+z+w if ('ОА' not in word) and ('АО' not in word) and ('НД' not in word) and ('ДН' not in word): print(word)
[ "root@NevssPC.localdomain" ]
root@NevssPC.localdomain
effba01bf3546bb14704b8e9e1a0030ce9ce98ac
37d8802ecca37cc003053c2175f945a501822c82
/11-拓扑排序/0210-课程表 II .py
74c246f32580ae2fcd91dba5d7eed54baa543dbb
[ "Apache-2.0" ]
permissive
Sytx74/LeetCode-Solution-Python
cc0f51e31a58d605fe65b88583eedfcfd7461658
b484ae4c4e9f9186232e31f2de11720aebb42968
refs/heads/master
2020-07-04T18:17:24.781640
2019-07-30T03:34:19
2019-07-30T03:34:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,161
py
# 210. 课程表 II # 现在你总共有 n 门课需要选,记为 0 到 n-1。 # 在选修某些课程之前需要一些先修课程。 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们: [0,1] # 给定课程总量以及它们的先决条件,返回你为了学完所有课程所安排的学习顺序。 # 可能会有多个正确的顺序,你只要返回一种就可以了。如果不可能完成所有课程,返回一个空数组。 class Solution(object): def findOrder(self, numCourses, prerequisites): """ :type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool """ # 课程的长度 clen = len(prerequisites) if clen == 0: # 没有课程,当然可以完成课程的学习 return [i for i in range(numCourses)] # 入度数组,一开始全部为 0 in_degrees = [0 for _ in range(numCourses)] # 邻接表 adj = [set() for _ in range(numCourses)] # 想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们: [0,1] # 1 -> 0,这里要注意:不要弄反了 for second, first in prerequisites: in_degrees[second] += 1 adj[first].add(second) # print("in_degrees", in_degrees) # 首先遍历一遍,把所有入度为 0 的结点加入队列 res = [] queue = [] for i in range(numCourses): if in_degrees[i] == 0: queue.append(i) while queue: top = queue.pop(0) res.append(top) for successor in adj[top]: in_degrees[successor] -= 1 if in_degrees[successor] == 0: queue.append(successor) if len(res) != numCourses: return [] return res if __name__ == '__main__': numCourses = 4 prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]] solution = Solution() result = solution.findOrder(numCourses, prerequisites) print(result)
[ "121088825@qq.com" ]
121088825@qq.com
fcb705deeef62d671fac51dff40c11b3bac40179
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03729/s949028843.py
45c50409e0f846d9c29adc30f5988d605b546202
[]
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
153
py
Tmp = [] Tmp = input().rstrip().split(' ') S1 = Tmp[0] S2 = Tmp[1] S3 = Tmp[2] if S1[-1]==S2[0] and S2[-1]==S3[0]: print('YES') else: print('NO')
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
b2a55e6803a8cb82449b0f4480ce73159caf442d
3a570384a3fa9c4c7979d33b182556e1c637e9eb
/anwmisc/anwp/sims/missile1_h.py
520ed4c58d7fbb6a3dc46bfb12ad87458d033f4b
[]
no_license
colshag/ANW
56a028af5042db92b5ead641dc542fcb4533344e
46948d8d18a0639185dd4ffcffde126914991553
refs/heads/master
2020-03-27T00:22:49.409109
2018-10-27T06:37:04
2018-10-27T06:37:04
145,618,125
2
0
null
null
null
null
UTF-8
Python
false
false
498
py
# --------------------------------------------------------------------------- # Armada Net Wars (ANW) # missile1_H.py # Written by Chris Lewis # --------------------------------------------------------------------------- # Represents a missile sim in the simulator # --------------------------------------------------------------------------- from OpenGL import GL centerX = 0 centerY = 0 numFrames = 1 h=8 w=4 points = ( (-h,-w), (h,-w), (h,w), (-h,w) ) primitives = [ (GL.GL_QUADS, (0,1,2,3)) ]
[ "colshag@gmail.com" ]
colshag@gmail.com
ea87a929be67a2abcf9fe9a15362b1768dcc7a70
9f7d4d76c7e66aa424a5f8723575dc489f1fd2ab
/2021/4/4.py
473c4f3604c356f4364a7d7adc7f597ac43c4b9e
[ "MIT" ]
permissive
kristianwiklund/AOC
df5a873287304816f25d91259c6e6c99c7a5f4bf
d9a668c406d2fd1b805d9b6a34cffa237a33c119
refs/heads/master
2023-01-12T09:01:11.012081
2023-01-02T19:12:29
2023-01-02T19:12:29
227,458,380
5
0
null
null
null
null
UTF-8
Python
false
false
598
py
#!/usr/bin/python3 import csv,sys from pprint import pprint from bb import BB # ------ randoms = next(sys.stdin).strip().split(",") print(randoms) boards = list() try: while True: next(sys.stdin) a = BB(sys.stdin) boards.append(a) # print(a) except: pass for i in randoms: print("Drawing ",i) s = [x.draw(int(i)) for x in boards] if sum(s): break for t in range(len(s)): if s[t]: s = boards[t].score() break print("Board ",t," is the board") print("Score: ",int(i)*s)
[ "githubkristian@snabela.nl" ]
githubkristian@snabela.nl
5ae4f7b8fa1951c2a6ad2cceeb98570947a922c2
849cd35166a93259c8bf84f001a3c40d9fe18b98
/Homeworks/test.py
4e8c67718adee043fe5c125fb2ffc073b240d0c2
[]
no_license
Larionov0/Group2-lessons
98c3d20d7532583ee66e766371235cfe888264c5
6426962e9b6766a9470ab1408b95486e63e4c2fa
refs/heads/master
2023-05-07T01:42:57.290428
2021-05-27T17:52:02
2021-05-27T17:52:02
334,012,422
0
0
null
null
null
null
UTF-8
Python
false
false
1,723
py
trees = [ ["Дуб", 5 , "д", "Д", 1, [], 0 ], ["Береза", 3, "б", "Б", 3, [], 0 ], ["Сосна", 1, "с", "С", 4, [], 0 ] ] width = 6 height = 6 # матриця matrix = [] i = 0 while i < height: row = ['-'] * width matrix.append(row) i += 1 for row in matrix: row_text = '|' for element in row: row_text += str(element) + ' ' row_text = row_text[:-1] + '|' print(row_text) # геймплей while True: # хід гравця skip = input('Skip? так/ні: ') if skip == 'ні': x = int(input('x: ')) y = int(input('y: ')) tree = input('tree: ') for el in trees: if el[0] == tree and el[4] != 0: treeInfo = [] treeChar = el[2] treeMadeMoves = 0 treeX = x treeY = y treeInfo.append(treeChar) treeInfo.append(treeMadeMoves) treeInfo.append(treeX) treeInfo.append(treeY) el[5].append(treeInfo) el[6] += 1 el[4] -= 1 # ріст дерев for el in trees: for tree in el[5]: if tree[1] == el[1]: tree[0] = el[3] tree[1] += 1 print(trees) for el in trees: for tree in el[5]: matrix[tree[3]-1][tree[2]-1] = tree[0] # формування матриці for row in matrix: row_text = '|' for element in row: row_text += str(element) + ' ' row_text = row_text[:-1] + '|' print(row_text)
[ "larionov1001@gmail.com" ]
larionov1001@gmail.com
a66173adf7118eff4cc81d1df2f6e262385d23c9
1b77eaf078321b1320d72aa36a4357568101e4ca
/字典6.5/venv/Scripts/easy_install-script.py
f3f5e0912c303566f77431e585b64cff50c8b803
[]
no_license
BEE-JN/python_homework
92ffc1216a380d124901fd64cc541f70813847dc
8ba4ea79cbd422f40e6f9f1cc5fed4d75715d207
refs/heads/master
2020-03-23T08:02:47.863607
2018-07-17T15:30:21
2018-07-17T15:30:21
141,305,118
1
0
null
null
null
null
WINDOWS-1252
Python
false
false
436
py
#!E:\python\×Öµä6.5\venv\Scripts\python.exe -x # EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==28.8.0','console_scripts','easy_install' __requires__ = 'setuptools==28.8.0' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('setuptools==28.8.0', 'console_scripts', 'easy_install')() )
[ "41156190+GCS-CN@users.noreply.github.com" ]
41156190+GCS-CN@users.noreply.github.com