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
db06ec79437b5fec5dd8a6154fc72aafe2ba691a
b15d2787a1eeb56dfa700480364337216d2b1eb9
/samples/cli/accelbyte_py_sdk_cli/session/_admin_update_game_session_member.py
0cfbe740caa10f08efc0ff3f32d4ca2edae4c635
[ "MIT" ]
permissive
AccelByte/accelbyte-python-sdk
dedf3b8a592beef5fcf86b4245678ee3277f953d
539c617c7e6938892fa49f95585b2a45c97a59e0
refs/heads/main
2023-08-24T14:38:04.370340
2023-08-22T01:08:03
2023-08-22T01:08:03
410,735,805
2
1
MIT
2022-08-02T03:54:11
2021-09-27T04:00:10
Python
UTF-8
Python
false
false
2,622
py
# Copyright (c) 2021 AccelByte Inc. All Rights Reserved. # This is licensed software from AccelByte Inc, for limitations # and restrictions contact your company contract manager. # # Code generated. DO NOT EDIT! # template_file: python-cli-command.j2 # AGS Session Service (2.22.2) # pylint: disable=duplicate-code # pylint: disable=line-too-long # pylint: disable=missing-function-docstring # pylint: disable=missing-module-docstring # pylint: disable=too-many-arguments # pylint: disable=too-many-branches # pylint: disable=too-many-instance-attributes # pylint: disable=too-many-lines # pylint: disable=too-many-locals # pylint: disable=too-many-public-methods # pylint: disable=too-many-return-statements # pylint: disable=too-many-statements # pylint: disable=unused-import import json import yaml from typing import Optional import click from .._utils import login_as as login_as_internal from .._utils import to_dict from accelbyte_py_sdk.api.session import ( admin_update_game_session_member as admin_update_game_session_member_internal, ) from accelbyte_py_sdk.api.session.models import ( ApimodelsUpdateGameSessionMemberStatusResponse, ) from accelbyte_py_sdk.api.session.models import ResponseError @click.command() @click.argument("member_id", type=str) @click.argument("session_id", type=str) @click.argument("status_type", type=str) @click.option("--namespace", type=str) @click.option("--login_as", type=click.Choice(["client", "user"], case_sensitive=False)) @click.option("--login_with_auth", type=str) @click.option("--doc", type=bool) def admin_update_game_session_member( member_id: str, session_id: str, status_type: str, namespace: Optional[str] = None, login_as: Optional[str] = None, login_with_auth: Optional[str] = None, doc: Optional[bool] = None, ): if doc: click.echo(admin_update_game_session_member_internal.__doc__) return x_additional_headers = None if login_with_auth: x_additional_headers = {"Authorization": login_with_auth} else: login_as_internal(login_as) result, error = admin_update_game_session_member_internal( member_id=member_id, session_id=session_id, status_type=status_type, namespace=namespace, x_additional_headers=x_additional_headers, ) if error: raise Exception(f"adminUpdateGameSessionMember failed: {str(error)}") click.echo(yaml.safe_dump(to_dict(result), sort_keys=False)) admin_update_game_session_member.operation_id = "adminUpdateGameSessionMember" admin_update_game_session_member.is_deprecated = False
[ "elmernocon@gmail.com" ]
elmernocon@gmail.com
00a2f8092e27e95dfa914d874b0b8943e4cac22d
1431cf722b926207f2777bd238d5cd030e4c0744
/exshell/ex_python.py
c167b0c632ce27cb7008c387027973d40f7c072a
[]
no_license
bedreamer/plane-ui
d96f8b6b09b955e278cf63289897733de0de69bb
19f5879c50bc5ecc12a2340f7f9d0e7864735001
refs/heads/master
2020-07-28T02:42:09.751249
2019-09-19T13:29:11
2019-09-19T13:29:11
209,282,512
1
1
null
null
null
null
UTF-8
Python
false
false
461
py
# -*- coding: utf-8 -*- import profile import sys import os __doc__ = """平台默认python操作接口""" __usage__ = __doc__ + """ Usage: python [command] {parameters}""" def main(ctx, cmd, *args): if ' ' in sys.executable: execute_path = ''.join(['"', sys.executable, '"']) else: execute_path = sys.executable command = [execute_path] command.extend(args) command_line = ' '.join(command) os.system(command_line)
[ "bedreamer@163.com" ]
bedreamer@163.com
41d5d45967b3ba4d4268c4d4dc5581986b31e78f
2f989d067213e7a1e19904d482a8f9c15590804c
/lib/python3.4/site-packages/allauth/socialaccount/providers/edmodo/provider.py
751de91ffa5a8f304c3c5e15eea9edcd69abb947
[ "MIT" ]
permissive
levabd/smart4-portal
beb1cf8847134fdf169ab01c38eed7e874c66473
2c18ba593ce7e9a1e17c3559e6343a14a13ab88c
refs/heads/master
2023-02-18T05:49:40.612697
2022-08-02T09:35:34
2022-08-02T09:35:34
116,001,098
0
1
MIT
2023-02-15T21:34:01
2018-01-02T10:00:07
Roff
UTF-8
Python
false
false
1,086
py
from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class EdmodoAccount(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get('profile_url') def get_avatar_url(self): return self.account.extra_data.get('avatar_url') class EdmodoProvider(OAuth2Provider): id = 'edmodo' name = 'Edmodo' account_class = EdmodoAccount def get_default_scope(self): return ['basic'] def extract_uid(self, data): return str(data['id']) def extract_common_fields(self, data): return dict(first_name=data.get('first_name'), last_name=data.get('last_name'), email=data.get('email', '')) def extract_extra_data(self, data): return dict(user_type=data.get('type'), profile_url=data.get('url'), avatar_url=data.get('avatars').get('large')) providers.registry.register(EdmodoProvider)
[ "levabd@gmail.com" ]
levabd@gmail.com
96bc3ffe27abcd7c712182e049bc0293c2dac27f
b535aa6260350f2f19f93b02b4fda5ab6f8eb3fe
/tests/conftest.py
bb965e89848bdd0248461ed076ae78e1f3abec0d
[ "MIT" ]
permissive
nexB/Lawu
e5d3b9ac5c855f204953ff98501960e633a1ff61
d9e4f79ea2d805f6d64c160c766c033a031403e1
refs/heads/master
2023-07-23T15:40:34.103991
2019-06-06T00:14:13
2019-06-06T00:14:13
258,251,793
0
0
MIT
2020-04-23T15:40:05
2020-04-23T15:40:04
null
UTF-8
Python
false
false
215
py
from pathlib import Path import pytest from jawa.classloader import ClassLoader @pytest.fixture(scope='session') def loader() -> ClassLoader: return ClassLoader(Path(__file__).parent / 'data', max_cache=-1)
[ "tk@tkte.ch" ]
tk@tkte.ch
4eaba41a750842ffcf74d1a7aeaafc267d40c819
e38d634d508578523ac41b3babd0c1e618dec64b
/getHeightOfTree.py
6bd1738056108dbdb3e4c6aeae7a9846135316ee
[]
no_license
hebertomoreno/PythonScr
d611e1e683ffc1566d51ae4d13362b94820c9af7
b77d22519ada971a95ff7f84f205db11fd492bca
refs/heads/master
2023-03-23T11:50:40.391715
2017-05-24T17:01:31
2017-05-24T17:01:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
642
py
class Node: def __init__(self,data): self.right=self.left=None self.data = data class Solution: def insert(self,root,data): if root==None: return Node(data) else: if data<=root.data: cur=self.insert(root.left,data) root.left=cur else: cur=self.insert(root.right,data) root.right=cur return root def getHeight(self,root): if root == None: return -1 else: return 1 + max(self.getHeight(root.left), self.getHeight(root.right)) T=int(input()) myTree=Solution() root=None for i in range(T): data=int(input()) root=myTree.insert(root,data) height=myTree.getHeight(root) print ("Height: ",height)
[ "nikolasmurdock@gmail.com" ]
nikolasmurdock@gmail.com
8ce348f31e1f6bf8afdd77cb87db214d89dc6267
6497bc5638453877744c900f7accef0203f36e89
/landmark_point/main.py
2eae1dc481c8cee6da5cd4e3cbda9e4bb793fd6b
[]
no_license
budaLi/leetcode-python-
82e9affb3317f63a82d89d7e82650de3c804a5ac
4221172b46d286ab6bf4c74f4d015ee9ef3bda8d
refs/heads/master
2022-01-30T00:55:26.209864
2022-01-05T01:01:47
2022-01-05T01:01:47
148,323,318
46
23
null
null
null
null
UTF-8
Python
false
false
209
py
# @Time : 2020/4/26 16:14 # @Author : Libuda # @FileName: main.py # @Software: PyCharm # 打开6个子集 取出图片及其98真实关键点 # 打开检测数据 5点 # 计算nme auc fr等 写入 问价
[ "1364826576@qq.com" ]
1364826576@qq.com
193a470139e9e8268bcb2f631f03957ec8370be5
c26c190986c1f30e6cc6f9a78fc56f6652536860
/cryptofeed/kraken/kraken.py
cb47092badbf27b1d80f19f92c5bb320d1ed9b9e
[ "Python-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
gavincyi/cryptofeed
92d89589e80f746d7206c90684c68446f0c07e59
6bac86237c57b697fb91b8193c71c2e7a615d4d2
refs/heads/master
2020-04-14T14:26:01.595616
2019-01-10T22:41:25
2019-01-10T22:41:25
163,896,590
0
0
NOASSERTION
2019-01-02T22:34:29
2019-01-02T22:34:28
null
UTF-8
Python
false
false
4,127
py
import asyncio from decimal import Decimal import time from sortedcontainers import SortedDict as sd from cryptofeed.feed import RestFeed from cryptofeed.defines import TRADES, BID, ASK, TICKER, L2_BOOK, KRAKEN from cryptofeed.standards import pair_exchange_to_std import aiohttp class Kraken(RestFeed): id = KRAKEN def __init__(self, pairs=None, channels=None, callbacks=None, **kwargs): super().__init__('https://api.kraken.com/0/public/', pairs, channels, callbacks, **kwargs) def __reset(self): self.last_trade_update = None async def _trades(self, session, pair): if self.last_trade_update is None: async with session.get("{}Trades?pair={}".format(self.address, pair)) as response: data = await response.json() self.last_trade_update = data['result']['last'] else: async with session.get("{}Trades?pair={}&since={}".format(self.address, pair, self.last_trade_update)) as response: data = await response.json() self.last_trade_update = data['result']['last'] if data['result'][pair] == []: return else: for trade in data['result'][pair]: # <price>, <volume>, <time>, <buy/sell>, <market/limit>, <miscellaneous> price, amount, timestamp, side, _, _ = trade await self.callbacks[TRADES](feed=self.id, pair=pair_exchange_to_std(pair), side=BID if side == 'b' else ASK, amount=Decimal(amount), price=Decimal(price), order_id=None, timestamp=timestamp) async def _ticker(self, session, pair): async with session.get("{}Ticker?pair={}&count=100".format(self.address, pair)) as response: data = await response.json() bid = Decimal(data['result'][pair]['b'][0]) ask = Decimal(data['result'][pair]['a'][0]) await self.callbacks[TICKER](feed=self.id, pair=pair_exchange_to_std(pair), bid=bid, ask=ask) async def _book(self, session, pair): async with session.get("{}Depth?pair={}".format(self.address, pair)) as response: data = await response.json() ts = time.time() data = data['result'][pair] book = {BID: sd(), ASK: sd()} for bids in data['bids']: price, amount, _ = bids price = Decimal(price) amount = Decimal(amount) book[BID][price] = amount for bids in data['asks']: price, amount, _ = bids price = Decimal(price) amount = Decimal(amount) book[ASK][price] = amount await self.callbacks[L2_BOOK](feed=self.id, pair=pair_exchange_to_std(pair), book=book, timestamp=ts) async def subscribe(self): self.__reset() return async def message_handler(self): async with aiohttp.ClientSession() as session: for chan in self.channels: for pair in self.pairs: if chan == TRADES: await self._trades(session, pair) elif chan == TICKER: await self._ticker(session, pair) elif chan == L2_BOOK: await self._book(session, pair) # KRAKEN's documentation suggests no more than 1 request a second # to avoid being rate limited await asyncio.sleep(1)
[ "bmoscon@gmail.com" ]
bmoscon@gmail.com
bec5d7a526d10be62caac399f9e3e9e95eb2fd8d
13ecaed116dd1367a09b6393d69a415af099b401
/backend/rock_crawler_20354/urls.py
a7d1509c41377bae2ed4d4eeded7703023fff231
[]
no_license
crowdbotics-apps/rock-crawler-20354
5cd650518c8e47c71c5941fd6c283eeed185bad8
77ae896728649368aa80aa20ca28224889e8fd99
refs/heads/master
2022-12-18T17:13:05.564163
2020-09-17T01:55:04
2020-09-17T01:55:04
296,190,734
0
0
null
null
null
null
UTF-8
Python
false
false
2,078
py
"""rock_crawler_20354 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/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, include from allauth.account.views import confirm_email from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi urlpatterns = [ path("", include("home.urls")), path("accounts/", include("allauth.urls")), path("api/v1/", include("home.api.v1.urls")), path("admin/", admin.site.urls), path("users/", include("users.urls", namespace="users")), path("rest-auth/", include("rest_auth.urls")), # Override email confirm to use allauth's HTML view instead of rest_auth's API view path("rest-auth/registration/account-confirm-email/<str:key>/", confirm_email), path("rest-auth/registration/", include("rest_auth.registration.urls")), path("api/v1/", include("event.api.v1.urls")), path("event/", include("event.urls")), path("home/", include("home.urls")), ] admin.site.site_header = "rock crawler" admin.site.site_title = "rock crawler Admin Portal" admin.site.index_title = "rock crawler Admin" # swagger api_info = openapi.Info( title="rock crawler API", default_version="v1", description="API documentation for rock crawler App", ) schema_view = get_schema_view( api_info, public=True, permission_classes=(permissions.IsAuthenticated,), ) urlpatterns += [ path("api-docs/", schema_view.with_ui("swagger", cache_timeout=0), name="api_docs") ]
[ "team@crowdbotics.com" ]
team@crowdbotics.com
efa94b6e1a9475a4198230da2e46d73389f60a3f
7f4b1d5e9963d63dd45b31c6cad8ced70d823217
/interview-prep/techie_delight/array/find_pair_sum.py
e1ab55be1dbf32abcb9f8348762855ef08cbea1a
[]
no_license
mdhatmaker/Misc-python
b8be239619788ed343eb55b24734782e227594dc
92751ea44f4c1d0d4ba60f5a1bb9c0708123077b
refs/heads/master
2023-08-24T05:23:44.938059
2023-08-09T08:30:12
2023-08-09T08:30:12
194,360,769
3
4
null
2022-12-27T15:19:06
2019-06-29T03:39:13
Python
UTF-8
Python
false
false
692
py
import sys # https://www.techiedelight.com/find-pair-with-given-sum-array/ # Find pair with given sum in the array. def find_pair_sum(arr, k): print(k, end=' ') arr.sort() low = 0 high = len(arr)-1 while (low < high): if arr[low] + arr[high] == k: return (arr[low], arr[high]) if arr[low] + arr[high] < k: low += 1 else: high -= 1 return (-1, -1) ############################################################################### if __name__ == "__main__": arr = [8, 7, 2, 5, 3, 1] print(arr) print(find_pair_sum(arr, 10)) print(find_pair_sum(arr, 9)) print(find_pair_sum(arr, 14))
[ "hatmanmd@yahoo.com" ]
hatmanmd@yahoo.com
c795292c2114df7d363630fd1724fc653ddd9e47
cc1b87f9368e96e9b3ecfd5e0822d0037e60ac69
/dashboard/dashboard/pinpoint/models/change/commit_cache.py
71909eda2e2d51149392a316f5a3d6975015f867
[ "BSD-3-Clause" ]
permissive
CTJyeh/catapult
bd710fb413b9058a7eae6073fe97a502546bbefe
c98b1ee7e410b2fb2f7dc9e2eb01804cf7c94fcb
refs/heads/master
2020-08-19T21:57:40.981513
2019-10-17T09:51:09
2019-10-17T18:30:16
215,957,813
1
0
BSD-3-Clause
2019-10-18T06:41:19
2019-10-18T06:41:17
null
UTF-8
Python
false
false
2,286
py
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import print_function from __future__ import division from __future__ import absolute_import from google.appengine.ext import ndb _MEMCACHE_TIMEOUT = 60 * 60 * 24 * 30 def Get(id_string): """Retrieve cached commit or patch details from the Datastore. Args: id_string: A string that uniquely identifies a Commit or Patch. Returns: A dict with the fields {'url', 'author', created', 'subject', 'message'}. """ entity = ndb.Key(Commit, id_string).get(use_datastore=False) if not entity: raise KeyError('Commit or Patch not found in the Datastore:\n' + id_string) return { 'url': entity.url, 'author': entity.author, 'created': entity.created, 'subject': entity.subject, 'message': entity.message, } def Put( id_string, url, author, created, subject, message, memcache_timeout=_MEMCACHE_TIMEOUT): """Add commit or patch details to the Datastore cache. Args: id_string: A string that uniquely identifies a Commit or Patch. url: The URL of the Commit or Patch. author: The author of the Commit or Patch. created: A datetime. When the Commit was committed or the Patch was created. subject: The title/subject line of the Commit or Patch. message: The Commit message. """ if not memcache_timeout: memcache_timeout = _MEMCACHE_TIMEOUT Commit( url=url, author=author, created=created, subject=subject, message=message, id=id_string).put(use_datastore=False, memcache_timeout=memcache_timeout) class Commit(ndb.Model): # Never write/read from Datastore. _use_datastore = False # Rely on this model being cached only in memory or memcache. _use_memcache = True _use_cache = True # Cache the data in Memcache for up-to 30 days _memcache_timeout = _MEMCACHE_TIMEOUT url = ndb.StringProperty(indexed=False, required=True) author = ndb.StringProperty(indexed=False, required=True) created = ndb.DateTimeProperty(indexed=False, required=True) subject = ndb.StringProperty(indexed=False, required=True) message = ndb.TextProperty(required=True)
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
53966e3f7870ceb362b412c8f33214acba0eee74
3bda645720e87bba6c8f960bbc8750dcea974cb0
/data/phys/fill_6192/xangle_150/DoubleEG/input_files.py
569cc557af310a17a3d989b5dbd84856890742d2
[]
no_license
jan-kaspar/analysis_ctpps_alignment_2017_preTS2
0347b8f4f62cf6b82217935088ffb2250de28566
0920f99080a295c4e942aa53a2fe6697cdff0791
refs/heads/master
2021-05-10T16:56:47.887963
2018-01-31T09:28:18
2018-01-31T09:28:18
118,592,149
0
2
null
null
null
null
UTF-8
Python
false
false
207
py
import FWCore.ParameterSet.Config as cms input_files = cms.vstring( "root://eostotem.cern.ch//eos/totem/data/ctpps/reconstruction/2017/preTS2_alignment_data/version1/fill6192_xangle150_DoubleEG.root" )
[ "jan.kaspar@cern.ch" ]
jan.kaspar@cern.ch
ad9f7d677d6aef12a21ccf2023c36309198ff516
fbf82e9a3d6e7b4dbaa2771eed0d96efabc87b3b
/platform/imageAuth/imageAuth/db/ormData.py
745c1a5b58daaa1d7bf869db4db8dee208149366
[]
no_license
woshidashayuchi/boxlinker-all
71603066fee41988108d8e6c803264bd5f1552bc
318f85e6ff5542cd70b7a127c0b1d77a01fdf5e3
refs/heads/master
2021-05-09T03:29:30.652065
2018-01-28T09:17:18
2018-01-28T09:17:18
119,243,814
1
0
null
null
null
null
UTF-8
Python
false
false
5,460
py
#!/usr/bin/env python # encoding: utf-8 """ @version: 0.1 @author: liuzhangpei @contact: liuzhangpei@126.com @site: http://www.livenowhy.com @time: 17/2/28 14:07 @ orm 数据结构 """ import sqlalchemy as sa from sqlalchemy.dialects import mysql from sqlalchemy.ext.declarative import declarative_base # 创建对象的基类: Base = declarative_base() # 资源的acl控制 class ResourcesAcl(Base): """ 资源的acl控制 """ __tablename__ = 'resources_acl' resource_uuid = sa.Column(sa.String(64), primary_key=True, nullable=False) resource_type = sa.Column(sa.String(64), primary_key=True, nullable=False) admin_uuid = sa.Column(sa.String(64), primary_key=True, nullable=False) team_uuid = sa.Column(sa.String(64), primary_key=True, nullable=False) project_uuid = sa.Column(sa.String(64), primary_key=True, nullable=False) user_uuid = sa.Column(sa.String(64), primary_key=True, nullable=False) create_time = sa.Column(mysql.TIMESTAMP, nullable=True) update_time = sa.Column(mysql.TIMESTAMP, nullable=True) class ImageRepository(Base): """ 镜像仓库 Repository, 无论构建镜像还是用户终端之间上传镜像都要注册在该表中 """ __tablename__ = 'image_repository' image_uuid = sa.Column(sa.String(64), primary_key=True, nullable=False) # 镜像uuid team_uuid = sa.Column(sa.String(64), nullable=False, index=True) # 组织uuid repository = sa.Column(sa.String(126), nullable=False, primary_key=True, index=True) # 镜像名 boxlinker/xxx deleted = sa.Column(sa.Integer, nullable=False, server_default=sa.text("'0'")) # 是否被删除 creation_time = sa.Column(mysql.TIMESTAMP, nullable=True) # 创建时间 update_time = sa.Column(mysql.TIMESTAMP, nullable=True) # 更新时间 is_public = sa.Column(sa.Integer, nullable=False, server_default=sa.text("'0'")) # 是否公开 short_description = sa.Column(sa.String(256)) # 简单描述 detail = sa.Column(sa.Text) # 详细描述 download_num = sa.Column(sa.Integer, nullable=False, server_default=sa.text("'0'")) # 下载次数 enshrine_num = sa.Column(sa.Integer, nullable=False, server_default=sa.text("'0'")) # 收藏次数 review_num = sa.Column(sa.Integer, nullable=False, server_default=sa.text("'0'")) # 评论次数 version = sa.Column(sa.String(64)) # 版本,[字典格式存储] latest_version = sa.Column(sa.String(30)) # 最新版本 pushed = sa.Column(sa.Integer, nullable=False, server_default=sa.text("'0'")) # 是否已经被推送,0->还没; 1->已经 is_code = sa.Column(sa.Integer, nullable=False, server_default=sa.text("'0'")) # 是否是代码构建的镜像仓库 logo = sa.Column(sa.String(126), server_default='') # 头像 src_type = sa.Column(sa.String(30)) # 代码类型 class RepositoryEvents(Base): """ 仓库事件通知,记录镜像的push/delete操作 """ __tablename__ = 'repository_events' id = sa.Column(sa.Integer, primary_key=True, autoincrement=True, nullable=False) repository = sa.Column(sa.String(128)) # 镜像名 url = sa.Column(sa.String(256)) lengths = sa.Column(sa.String(24)) tag = sa.Column(sa.String(60)) actor = sa.Column(sa.String(128)) actions = sa.Column(sa.String(24), server_default="push") digest = sa.Column(sa.String(256)) sizes = sa.Column(sa.String(256)) repo_id = sa.Column(sa.String(256)) source_instanceID = sa.Column(sa.String(256)) source_addr = sa.Column(sa.String(256)) deleted = sa.Column(sa.Integer, nullable=False, server_default=sa.text("'0'")) creation_time = sa.Column(mysql.TIMESTAMP) update_time = sa.Column(mysql.TIMESTAMP) # 第三方认证, 用户认证表 class CodeOauth(Base): __tablename__ = 'code_oauth' code_oauth_uuid = sa.Column(sa.String(64), primary_key=True, nullable=False) team_uuid = sa.Column(sa.String(64), nullable=False) # 和组织相关, 不要绑定用户 src_type = sa.Column(sa.String(20), nullable=False) # 代码来源 git_name = sa.Column(sa.String(64)) git_emain = sa.Column(sa.String(64)) git_uid = sa.Column(sa.String(20)) access_token = sa.Column(sa.String(60)) # code_oauth code_repo # 20160928 代码源 class CodeRepo(Base): __tablename__ = 'code_repo' code_repo_uuid = sa.Column(sa.Integer, primary_key=True, autoincrement=True, nullable=False) team_uuid = sa.Column(sa.String(64), nullable=False) repo_uid = sa.Column(sa.String(64)) # github 用户id repo_id = sa.Column(sa.String(64)) # 项目id repo_name = sa.Column(sa.String(64)) # 项目名 repo_branch = sa.Column(sa.String(64)) # 项目名,分支 repo_hook_token = sa.Column(sa.String(64)) # web hooks token hook_id = sa.Column(sa.String(256)) # web hook id,删除和修改时用 html_url = sa.Column(sa.String(256)) # 项目 url ssh_url = sa.Column(sa.String(256)) # 项目 git clone 地址 git_url = sa.Column(sa.String(256)) description = sa.Column(sa.String(256)) is_hook = sa.Column(sa.String(1), nullable=False, server_default='0') # 是否已经被授权hook src_type = sa.Column(sa.String(20), nullable=False, server_default='github') # 代码来源 deleted = sa.Column(sa.Integer, nullable=False, server_default=sa.text("'0'")) creation_time = sa.Column(mysql.TIMESTAMP, nullable=True) update_time = sa.Column(mysql.TIMESTAMP, nullable=True)
[ "359876749@qq.com" ]
359876749@qq.com
b1d9b794bd63e59dcbabad3196e3405ffebc42a8
f4054fcf13c72f450bed662e01ca6fcc9c2b8111
/pages/urls.py
e8de8e82edc8b3938f442bcc36d4ed9163d189f2
[]
no_license
skiboorg/global
a54210bccaa5a82db395241d3470b5450b87a51f
eebcbcfadd4b94f5588db3392ce171948f1d5cf8
refs/heads/master
2022-12-12T00:27:02.449806
2020-09-04T05:32:56
2020-09-04T05:32:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
726
py
from django.urls import path,include from . import views urlpatterns = [ path('', views.index, name='index'), path('contests', views.contests, name='contests'), path('instructions', views.instructions, name='instructions'), path('startups/<id>', views.startups, name='startups'), path('admin_page/jury/invite', views.invite, name='invite'), path('admin_page/<category_id>', views.admin, name='admin_page'), path('rate', views.rate, name='rate'), path('rate_stage2', views.rate_stage2, name='rate_stage2'), path('start_stage2', views.start_stage2, name='start_stage2'), path('send_notify', views.send_notify, name='send_notify'), path('results', views.GeneratePdf.as_view()), ]
[ "11@11.11" ]
11@11.11
a9fd81720b3a00dc1f25d9a163cbad2593f7e27d
8d3e3887b02ad2d5e75edb5e56e11c33d0f440bd
/config.py
05a6f247f55996795ae9ba9a9c8f3eba8529600b
[]
no_license
makalaaneesh/momentipy
e423a5e1b4e59a18a4ed5c1d7c07934dcda4a695
b62f52b536890a0bc7c924a10fbd73cb04f10535
refs/heads/master
2021-01-10T07:50:18.756563
2016-03-24T18:31:50
2016-03-24T18:31:50
53,156,335
0
0
null
null
null
null
UTF-8
Python
false
false
1,412
py
JPG_EXTENSIONS = ('.jpg', '.jpeg', '.jpe', '.JPG') RAW_EXTENSIONS = ('.3fr','.3pr','.arw','.ce1','.ce2','.cib','.cmt','.cr2','.craw','.crw', '.dc2','.dcr','.dng','.erf','.exf','.fff','.fpx','.gray','.grey','.gry', '.iiq','.kc2','.kdc','.mdc','.mef','.mfw','.mos','.mrw','.ndd','.nef','.nop', '.nrw','.nwb','.orf','.pcd','.pef','.ptx','.ra2','.raf','.raw','rw2','.rwl', '.rwz','.sd0','.sd1','.sr2','.srf','.srw','.st4','.st5','.st6','.st7','.st8', '.stx','.x3f','.ycbcra') PHOTO_EXTENSIONS = JPG_EXTENSIONS + RAW_EXTENSIONS MOVIE_EXTENSIONS = ('.3g2','.3gp','.asf','.asx','.avi','.flv','.m4v','.mov','.mp4','.mpg', '.rm','.srt','.swf','.vob','.wmv','.aepx','.ale','.avp','.avs','.bdm', '.bik','.bin','.bsf','.camproj','.cpi','.dash','.divx','.dmsm','.dream', '.dvdmedia','.dvr-ms','.dzm','.dzp','.edl','.f4v','.fbr','.fcproject', '.hdmov','.imovieproj','.ism','.ismv','.m2p','.mkv','.mod','.moi', '.mpeg','.mts','.mxf','.ogv','.otrkey','.pds','.prproj','.psh','.r3d', '.rcproject','.rmvb','.scm','.smil','.snagproj','.sqz','.stx','.swi','.tix', '.trp','.ts','.veg','.vf','.vro','.webm','.wlmp','.wtv','.xvid','.yuv') VALID_EXTENSIONS = PHOTO_EXTENSIONS + MOVIE_EXTENSIONS
[ "makalaaneesh@yahoo.com" ]
makalaaneesh@yahoo.com
45a934609592023102cc9deabe6dd15559740b0e
8f0b0ec0a0a2db00e2134b62a1515f0777d69060
/scripts/study_case/ID_61/multi_layer_perceptron_grist.py
95b6cf3951fe9293450c55fd79acb2813e3208f1
[ "Apache-2.0" ]
permissive
Liang813/GRIST
2add5b4620c3d4207e7661eba20a79cfcb0022b5
544e843c5430abdd58138cdf1c79dcf240168a5f
refs/heads/main
2023-06-09T19:07:03.995094
2021-06-30T05:12:19
2021-06-30T05:12:19
429,016,034
0
0
Apache-2.0
2021-11-17T11:19:48
2021-11-17T11:19:47
null
UTF-8
Python
false
false
3,207
py
from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf import numpy as np import sys sys.path.append("/data") # 导入数据并创建一个session mnist = input_data.read_data_sets('./MNIST_data', one_hot=True) sess = tf.InteractiveSession() # 定义节点,权重和偏置 in_uints = 784 # 输入节点数 h1_uints = 300 # 隐含层节点数 W1 = tf.Variable(tf.truncated_normal([in_uints, h1_uints], stddev=0.1)) # 初始化截断正态分布,标准差为0.1 b1 = tf.Variable(tf.zeros([h1_uints])) W2 = tf.Variable(tf.zeros([h1_uints, 10])) # mnist数据集共10类,所以W2的形状为(h1_uints,10) b2 = tf.Variable(tf.zeros([10])) # 输入数据和dropout的比率 x = tf.placeholder(tf.float32, [None, in_uints]) keep_prob = tf.placeholder(tf.float32) # 定义模型结构, 输入层-隐层-输出层 hidden1 = tf.nn.relu(tf.matmul(x, W1) + b1) # relu激活函数 hidden1_drop = tf.nn.dropout(hidden1, keep_prob) # dropout随机使部分节点置零,克服过拟合 y = tf.nn.softmax(tf.matmul(hidden1_drop, W2) + b2) # softmax多分类 y_ = tf.placeholder(tf.float32, [None, 10]) # 定义损失函数和优化器 obj_var = y cross_entropy = -tf.reduce_sum(y_ * tf.log(y)) # 学习率为0.1,cost变为正常 optimizer = tf.train.AdagradOptimizer(0.01).minimize(cross_entropy) # 初始化所有的参数 init = tf.initialize_all_variables() sess.run(init) # 通过循环训练数据 n_samples = int(mnist.train.num_examples) # 总样本数 batch_size = 100 # batch_size数目 epochs = 5 # epochs数目 display_step = 1 # 迭代多少次显示loss """insert code""" from scripts.utils.tf_utils import GradientSearcher gradient_search = GradientSearcher(name="tensorflow_project_grist") obj_function = tf.reduce_min(tf.abs(obj_var)) obj_grads = tf.gradients(obj_function, x)[0] batch_xs, batch_ys = mnist.train.next_batch(batch_size) max_val, min_val = np.max(batch_xs), np.min(batch_xs) gradient_search.build(batch_size=batch_size, min_val=min_val, max_val=max_val) """insert code""" while True: avg_cost = 0 total_batch = int(n_samples / batch_size) for i in range(total_batch): """inserted code""" monitor_vars = {'loss': cross_entropy, 'obj_function': obj_function, 'obj_grad': obj_grads} feed_dict = {x: batch_xs, y_: batch_ys, keep_prob: 1} batch_xs, scores_rank = gradient_search.update_batch_data(session=sess, monitor_var=monitor_vars, feed_dict=feed_dict, input_data=batch_xs, ) """inserted code""" loss, opt = sess.run((cross_entropy, optimizer), feed_dict=feed_dict) """inserted code""" new_batch_xs, new_batch_ys = mnist.train.next_batch(batch_size) new_data_dict = {'x': new_batch_xs, 'y': new_batch_ys} old_data_dict = {'x': batch_xs, 'y': batch_ys} batch_xs, batch_ys = gradient_search.switch_new_data(new_data_dict=new_data_dict, old_data_dict=old_data_dict, scores_rank=scores_rank) gradient_search.check_time() """inserted code"""
[ "793679547@qq.com" ]
793679547@qq.com
24042473cd5cd6af11e11bca2ae2954f7f570a7f
be50b4dd0b5b8c3813b8c3158332b1154fe8fe62
/Hashing/Python/SubarrayWithEqualOccurences.py
6822fc464cb733519f70a6b48c8348a5929eaf57
[]
no_license
Zimmermann25/InterviewBit
a8d89e090068d9644e28085625963c8ce75d3dff
6d2138e740bd5ba8eab992d9bf090977e077bfc5
refs/heads/main
2023-03-24T18:12:48.244950
2021-03-24T14:36:48
2021-03-24T14:36:48
350,835,917
0
0
null
null
null
null
UTF-8
Python
false
false
1,015
py
class Solution: # @param A : list of integers # @param B : integer # @param C : integer # @return an integer # subarrays with 0 sum def solve(self, A, B, C): if len(A) < 2: return 0 # B != C for i in range(len(A)): if A[i] == B: A[i] = 1 elif A[i] == C:A[i] = -1 else:A[i] = 0 output = 0 prevEqual = 0 # w O(N^2) łatwo, ale dla O(N) troche trudniej # na podstawie https://www.youtube.com/watch?v=bqN9yB0vF08 Dict = {0:1} # base case tempSum = 0 #print(A) for i in range(len(A)): tempSum +=A[i] # 0 w miejsce K if tempSum - 0 in Dict: output += Dict[tempSum - 0] if tempSum in Dict: Dict[tempSum] +=1 else: Dict[tempSum] = 1 #print("i: ", i, "out: ", output, "dict: ", Dict) return output
[ "noreply@github.com" ]
Zimmermann25.noreply@github.com
685bdecd8e029b131145675a3b0238c77eba91e3
2fa12cde6a091a1559617e8f825b00f2a5c7f8ba
/src/190page.py
d2ae5ba7ae41ce90d64d657c541acac146722424
[]
no_license
yeasellllllllll/bioinfo-lecture-2021-07
b9b333183047ddac4436180cd7c679e3cc0e399a
ce695c4535f9d83e5c9b4a1a8a3fb5857d2a984f
refs/heads/main
2023-06-15T20:31:35.101747
2021-07-18T14:31:27
2021-07-18T14:31:27
382,995,460
0
0
null
2021-07-05T06:06:35
2021-07-05T02:45:29
Python
UTF-8
Python
false
false
232
py
f = "data.txt" d = {} with open(f, "r") as fr: for line in fr: l = line.strip().split(" ") gene, val = l[0], l[1] d[gene] = val print(d.items()) print(sorted(d.items(), key=lambda x: x[1], reverse=True))
[ "yeasel6112@gmail.com" ]
yeasel6112@gmail.com
5b658965a62b686a1ddb2d499ca537ed24219f98
56ade096db1fe376ee43d38c96b43651ee07f217
/647. Palindromic Substrings/Python/Solution.py
45128cf5cd3cad9ddcdddbb855a52902fe6045c7
[]
no_license
xiaole0310/leetcode
c08649c3f9a9b04579635ee7e768fe3378c04900
7a501cf84cfa46b677d9c9fced18deacb61de0e8
refs/heads/master
2020-03-17T05:46:41.102580
2018-04-20T13:05:32
2018-04-20T13:05:32
133,328,416
1
0
null
null
null
null
UTF-8
Python
false
false
451
py
class Solution: def countSubstrings(self, s): """ :type s: str :rtype: int """ self.result = 0 def count(s, left, right): while left >= 0 and right < len(s) and s[left] == s[right]: self.result += 1 left -= 1 right += 1 for i in range(len(s)): count(s, i, i) count(s, i, i + 1) return self.result
[ "zhantong1994@163.com" ]
zhantong1994@163.com
800d4590249dde33a636159d00ba3a38bc667b46
44a7101ae18c84ffa0e3c674763ba7b500937773
/root/Desktop/Scripts/Python Forensic Scripts/Violent Python/idsFoil.py
0ad7588cd59c0f4c4836e0b32135b8289ba10bdd
[]
no_license
Draft2007/Scripts
cbaa66ce0038f3370c42d93da9308cbd69fb701a
0dcc720a1edc882cfce7498ca9504cd9b12b8a44
refs/heads/master
2016-09-05T20:05:46.601503
2015-06-23T00:05:02
2015-06-23T00:05:02
37,945,893
7
2
null
null
null
null
UTF-8
Python
false
false
2,641
py
import optparse from scapy.all import * from random import randint def ddosTest(src, dst, iface, count): # Crafts a decoy TFN Probe pkt=IP(src=src,dst=dst)/ICMP(type=8,id=678)/Raw(load='1234') send(pkt, iface=iface, count=count) # Crafts a decoy tfn2k icmp possible communication pkt = IP(src=src,dst=dst)/ICMP(type=0)/Raw(load='AAAAAAAAAA') send(pkt, iface=iface, count=count) # Crafts a decoy Trin00 Daemon to Master PONG message pkt = IP(src=src,dst=dst)/UDP(dport=31335)/Raw(load='PONG') send(pkt, iface=iface, count=count) # Crafts a decoy TFN client command BE pkt = IP(src=src,dst=dst)/ICMP(type=0,id=456) send(pkt, iface=iface, count=count) def exploitTest(src, dst, iface, count): # Crafts a decoy EXPLOIT ntalkd x86 Linux overflow pkt = IP(src=src, dst=dst) / UDP(dport=518) \ /Raw(load="\x01\x03\x00\x00\x00\x00\x00\x01\x00\x02\x02\xE8") send(pkt, iface=iface, count=count) # Crafts a decoy EXPLOIT x86 Linux mountd overflow pkt = IP(src=src, dst=dst) / UDP(dport=635) \ /Raw(load="^\xB0\x02\x89\x06\xFE\xC8\x89F\x04\xB0\x06\x89F") send(pkt, iface=iface, count=count) def scanTest(src, dst, iface, count): # Crafts a decoy SCAN cybercop udp bomb pkt = IP(src=src, dst=dst) / UDP(dport=7) \ /Raw(load='cybercop') send(pkt) # Crafts a decoy SCAN Amanda client request pkt = IP(src=src, dst=dst) / UDP(dport=10080) \ /Raw(load='Amanda') send(pkt, iface=iface, count=count) def main(): parser = optparse.OptionParser('usage %prog '+\ '-i <iface> -s <src> -t <target> -c <count>' ) parser.add_option('-i', dest='iface', type='string',\ help='specify network interface') parser.add_option('-s', dest='src', type='string',\ help='specify source address') parser.add_option('-t', dest='tgt', type='string',\ help='specify target address') parser.add_option('-c', dest='count', type='int',\ help='specify packet count') (options, args) = parser.parse_args() if options.iface == None: iface = 'eth0' else: iface = options.iface if options.src == None: src = '.'.join([str(randint(1,254)) for x in range(4)]) else: src = options.src if options.tgt == None: print parser.usage exit(0) else: dst = options.tgt if options.count == None: count = 1 else: count = options.count ddosTest(src, dst, iface, count) exploitTest(src, dst, iface, count) scanTest(src, dst, iface, count) if __name__ == '__main__': main()
[ "root@localhost.localdomain" ]
root@localhost.localdomain
d1e68bd9c6aaa166ed0e00dfa42dee16851652b2
09e57dd1374713f06b70d7b37a580130d9bbab0d
/data/cirq_new/cirq_program/startCirq_noisy941.py
da12e8a16d52deb8656030cb8f1149daefd14cc9
[ "BSD-3-Clause" ]
permissive
UCLA-SEAL/QDiff
ad53650034897abb5941e74539e3aee8edb600ab
d968cbc47fe926b7f88b4adf10490f1edd6f8819
refs/heads/main
2023-08-05T04:52:24.961998
2021-09-19T02:56:16
2021-09-19T02:56:16
405,159,939
2
0
null
null
null
null
UTF-8
Python
false
false
2,569
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=4 # total number=23 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[1])) # number=7 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=5 c.append(cirq.H.on(input_qubit[0])) # number=16 c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=17 c.append(cirq.H.on(input_qubit[0])) # number=18 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=8 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=9 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=10 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=11 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=12 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=13 c.append(cirq.SWAP.on(input_qubit[3],input_qubit[0])) # number=14 c.append(cirq.SWAP.on(input_qubit[3],input_qubit[0])) # number=15 c.append(cirq.SWAP.on(input_qubit[3],input_qubit[0])) # number=19 c.append(cirq.SWAP.on(input_qubit[3],input_qubit[0])) # number=20 c.append(cirq.Y.on(input_qubit[2])) # number=21 c.append(cirq.Y.on(input_qubit[2])) # number=22 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 4 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count,input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count =2820 circuit = circuit.with_noise(cirq.depolarize(p=0.01)) simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq_noisy941.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit,file=writefile) writefile.close()
[ "wangjiyuan123@yeah.net" ]
wangjiyuan123@yeah.net
fa444d7edff7bcce427df85f79853825bf777c7c
0ae2bb21d7ca71a691e33cb044a0964d380adda2
/uber/uber_algo/LC636ExeclusiveTimeOfFunctions_UB.py
e5e2bbce96747c00ed9c42ec84e9e14940c8ff2b
[]
no_license
xwang322/Coding-Interview
5d27ec92d6fcbb7b929dd98bb07c968c1e1b2a04
ee5beb79038675ce73c6d147ba9249d9a5ca346a
refs/heads/master
2020-03-10T08:18:34.980557
2018-06-24T03:37:12
2018-06-24T03:37:12
129,282,263
2
6
null
2018-04-19T19:31:24
2018-04-12T16:41:28
Python
UTF-8
Python
false
false
1,289
py
/* * Implement a function return the exclusive running time of a function, given the function name and a list of logs. * List<string> stands for a list of logs. The logs have the following structure: * functionName StartOrEnd Time * A start 10 * B start 11 * B end 12 * A end 20 * exclusive running time means the total running time of a function minus the total running time of its nested functions. * for example, the exclusive running time of A = T(A) - T(B) T stands for the total running time of a fuction * Func A{ * Func B(); * } **/ class Solution(object): def exclusiveTime(self, n, logs): if not n or not logs: return [] stack = [] answer = [0]*n temp = 0 for log in logs: log = log.split(':') functionName, ty, timestamp = int(log[0]), log[1], int(log[2]) if not stack: stack.append(functionName) temp = timestamp elif ty == 'start': answer[stack[-1]] += timestamp-temp stack.append(functionName) temp = timestamp elif ty == 'end': answer[stack.pop()] += timestamp-temp+1 temp = timestamp+1 return answer
[ "noreply@github.com" ]
xwang322.noreply@github.com
f1fcf8c31077a0ecbd3a6c84b39d5c8fa8378439
9fdee128812956e1e1919a58c7f64561543abf56
/Lorry_with_coffee.py
6e56c5a6108abf4d6a47d1e65880856b90ea793a
[]
no_license
OleksandrMyshko/python
38139b72a75d52ca0a6a5787c5e6357432ec6799
1caed3c05d513c0dd62d6ff77910e9596c50969f
refs/heads/master
2021-07-03T03:31:11.198438
2017-09-25T17:43:59
2017-09-25T17:43:59
104,762,652
0
0
null
null
null
null
UTF-8
Python
false
false
824
py
class Coffee: def __init__(self, type, price): self.type = type self.price = price class Box: def __init__(self, volume, coffee): self.volume = volume self.coffee = coffee class Lorry: def __init__(self): self.boxes = [] def add_box(self, box): self.boxes.append(box) def total(self): sum = 0 for box in self.boxes: sum += box.volume * box.coffee.price return sum def main(): coffee1 = Coffee('arabica', 20) coffee2 = Coffee('rabusta', 10) box1 = Box(40, coffee1) box2 = Box(50, coffee2) box3 = Box(10, coffee2) box4 = Box(30, coffee1) lorry = Lorry() lorry.add_box(box1) lorry.add_box(box2) lorry.add_box(box3) lorry.add_box(box4) print(lorry.total()) main()
[ "sashamushko@gmail.com" ]
sashamushko@gmail.com
fe1595a84a84e39fed7f7ef5bb3f26584c14aa2f
1f93178e536219f89dfb4ec748ebacb548276626
/tests/test_utils.py
29a0ef25439a56f1985353c95a5db459f08e845b
[ "MIT" ]
permissive
WillWang99/pyModbusTCP
9c97ef24c46f3473ad47f44c7ba5ed6d1b2021b0
8d09cac1752707770c2039d16173a2427dbc1c61
refs/heads/master
2021-03-16T08:33:56.440811
2017-11-13T08:18:53
2017-11-13T08:18:53
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,050
py
# -*- coding: utf-8 -*- import unittest import math from pyModbusTCP import utils class TestUtils(unittest.TestCase): def test_get_bits_from_int(self): # default bits list size is 16 self.assertEqual(len(utils.get_bits_from_int(0)), 16) # for 8 size (positional arg) self.assertEqual(len(utils.get_bits_from_int(0, 8)), 8) # for 32 size (named arg) self.assertEqual(len(utils.get_bits_from_int(0, val_size=32)), 32) # test binary decode self.assertEqual(utils.get_bits_from_int(6, 4), [False, True, True, False]) def test_decode_ieee(self): # test IEEE NaN self.assertTrue(math.isnan(utils.decode_ieee(0x7fffffff))) # test +/- infinity self.assertTrue(math.isinf(utils.decode_ieee(0xff800000))) self.assertTrue(math.isinf(utils.decode_ieee(0x7f800000))) # test some values self.assertAlmostEqual(utils.decode_ieee(0x3e99999a), 0.3) self.assertAlmostEqual(utils.decode_ieee(0xbe99999a), -0.3) def test_encode_ieee(self): # test IEEE NaN self.assertEqual(utils.encode_ieee(float('nan')), 2143289344) # test +/- infinity # self.assertTrue(math.isinf(utils.decode_ieee(0xff800000))) # self.assertTrue(math.isinf(utils.decode_ieee(0x7f800000))) # test some values self.assertAlmostEqual(utils.encode_ieee(0.3), 0x3e99999a) self.assertAlmostEqual(utils.encode_ieee(-0.3), 0xbe99999a) def test_word_list_to_long(self): # empty list, return empty list self.assertEqual(utils.word_list_to_long([]), []) # if len of list is odd ignore last value self.assertEqual(utils.word_list_to_long([0x1, 0x2, 0x3]), [0x10002]) # test convert with big and little endian word_list = utils.word_list_to_long([0xdead, 0xbeef]) self.assertEqual(word_list, [0xdeadbeef]) word_list = utils.word_list_to_long([0xdead, 0xbeef, 0xdead, 0xbeef]) self.assertEqual(word_list, [0xdeadbeef, 0xdeadbeef]) word_list = utils.word_list_to_long([0xdead, 0xbeef], big_endian=False) self.assertEqual(word_list, [0xbeefdead]) word_list = utils.word_list_to_long([0xdead, 0xbeef, 0xdead, 0xbeef], big_endian=False) self.assertEqual(word_list, [0xbeefdead, 0xbeefdead]) def test_get_2comp(self): # 2's complement of 16bits 0x0001 value is 1 self.assertEqual(utils.get_2comp(0x0001, 16), 1) # 2's complement of 16bits 0x8000 value is -32768 self.assertEqual(utils.get_2comp(0x8000, 16), -0x8000) # 2's complement of 16bits 0xFFFF value is -1 self.assertEqual(utils.get_2comp(0xFFFF, 16), -0x0001) def test_get_list_2comp(self): # with 1 item self.assertEqual(utils.get_list_2comp([0x8000], 16), [-32768]) # with 3 items self.assertEqual(utils.get_list_2comp([0x8000, 0xFFFF, 0x0042], 16), [-0x8000, -0x0001, 0x42]) if __name__ == '__main__': unittest.main()
[ "loic.celine@free.fr" ]
loic.celine@free.fr
329c0af3339a265620d8e1bac177ef51198df554
cb9dca7c997337f59468ef2369a15fa920202e8f
/09_regular_expressions/exercise/03_find_occurrences_of_word_in_sentence.py
dc986ed137b967c1009c20694093865e9cf49bd7
[]
no_license
M0673N/Programming-Fundamentals-with-Python
6e263800bad7069d6f2bf8a10bee87a39568c162
a1e9493a6f458ddc8d14ae9c0893c961fe351e73
refs/heads/main
2023-05-26T18:27:03.098598
2021-06-06T19:00:57
2021-06-06T19:00:57
361,785,714
0
0
null
null
null
null
UTF-8
Python
false
false
150
py
import re sentence = input().lower() word = input().lower() pattern = r"\b" + word + r"\b" result = re.findall(pattern, sentence) print(len(result))
[ "m0673n@abv.bg" ]
m0673n@abv.bg
a87406c60058422469cd9cfaeaea19ef0d9de260
7251f1742615752e402dadcb4d59c9e543ecf824
/Train/PolyTrain.py
1051171859da265d655871804b499c6de323caef
[]
no_license
xinxiaoli/ambf_walker
c6f2bca047de0d38a61358f3d290e2d73eb494a1
2b909f1c340f95a6c2a0b7356c8e218c1c55356a
refs/heads/master
2022-12-27T02:50:22.036730
2020-08-12T23:18:48
2020-08-12T23:18:48
294,125,031
0
0
null
2020-09-09T13:42:17
2020-09-09T13:42:17
null
UTF-8
Python
false
false
1,736
py
from GaitAnaylsisToolkit.LearningTools.Runner import TPGMMRunner from GaitAnaylsisToolkit.LearningTools.Trainer import TPGMMTrainer from random import seed from random import gauss import numpy as np import matplotlib.pyplot as plt import numpy.polynomial.polynomial as poly def coef(b, dt): A = np.array([[1.0, 0, 0, 0], [0, 1.0, 0, 0], [1.0, dt, dt**2, dt**3], [0, 1.0, 2*dt, 3*dt**2]]) return np.linalg.pinv(A).dot(b) # seed random number generator seed(1) b = np.array([ [-0.3], [0.], [ -0.7 ], [0.0] ]) x = coef(b, 10) fit = poly.Polynomial(x.flatten()) t = np.linspace(0,10,100) y_prime = fit(t) hip = [] for i in range(10): y = y_prime + gauss(-0.05, 0.05) hip.append(y) b = np.array([ [0.2], [0.0], [0.5], [0.0] ]) x = coef(b, 10) fit = poly.Polynomial(x.flatten()) t = np.linspace(0,10,100) y_prime = fit(t) knee = [] for i in range(10): y = y_prime + gauss(-0.05, 0.05) knee.append(y) b = np.array([ [0.257], [0.0], [ 0.0 ], [0.0] ]) x = coef(b, 10) fit = poly.Polynomial(x.flatten()) t = np.linspace(0,10,100) y_prime = fit(t) ankle = [] for i in range(10): y = y_prime + gauss(-0.05, 0.05) ankle.append(y) trainer = TPGMMTrainer.TPGMMTrainer(demo=[hip, knee, ankle,hip, knee, ankle], file_name="gotozero", n_rf=5, dt=0.01, reg=[1e-4], poly_degree=[3,3,3,3,3,3]) trainer.train() runner = TPGMMRunner.TPGMMRunner("gotozero") path = runner.run() fig, axs = plt.subplots(3) print(path) for p in hip: axs[0].plot(p) axs[0].plot(path[:, 0], linewidth=4) for p in knee: axs[1].plot(p) axs[1].plot(path[:, 1], linewidth=4) for p in ankle: axs[2].plot(p) axs[2].plot(path[:, 2], linewidth=4) plt.show()
[ "nagoldfarb@wpi.edu" ]
nagoldfarb@wpi.edu
af15d7024d0a48e2e7498f7989c22aacdc552f6a
62343cc4b4c44baef354f4552b449a9f53ca799e
/Model/__init__.py
e755d87124450cd8f784260a03671013533b6ad7
[]
no_license
xwjBupt/simpleval
7c71d178657ae12ac1a5ac6f1275940023573884
87234e630d7801479575015b8c5bdd3588a3ceed
refs/heads/master
2023-02-03T13:42:07.013196
2020-12-25T09:08:01
2020-12-25T09:08:01
324,154,886
0
0
null
null
null
null
UTF-8
Python
false
false
939
py
from .single_stage_detector import SingleStageDetector from .backbone import ResNet, ResNetV1d from .engine import InferEngine, ValEngine, BaseEngine from .builder import build_engine, build_detector, build_backbone, build_head, build_neck from .heads import AnchorHead, IoUAwareRetinaHead from .necks import FPN from .meshgrids import BBoxAnchorMeshGrid, BBoxBaseAnchor from .converters import IoUBBoxAnchorConverter from .bbox_coders import delta_xywh_bbox_coder, bbox_overlaps from .parallel import DataContainer from .ops import batched_nms __all__ = ['InferEngine', 'ValEngine', 'SingleStageDetector', 'ResNet', 'ResNetV1d', 'build_engine', 'build_detector', 'build_backbone', 'build_head', 'build_neck', 'FPN', 'AnchorHead', 'IoUAwareRetinaHead', 'BBoxAnchorMeshGrid', 'BBoxBaseAnchor', 'IoUBBoxAnchorConverter', 'delta_xywh_bbox_coder', 'DataContainer', 'bbox_overlaps', 'batched_nms' ]
[ "xwj_bupt@163.com" ]
xwj_bupt@163.com
bd34d37546f838ec5960e3bc75ada531113248aa
7d096568677660790479d87c22b47aae838ef96b
/stubs-legacy/System/Windows/Media/Animation_parts/AnimationException.py
928a9c5a3de8a33b97a425e31bf64e5273703759
[ "MIT" ]
permissive
NISystemsEngineering/rfmx-pythonnet
30adbdd5660b0d755957f35b68a4c2f60065800c
cd4f90a88a37ed043df880972cb55dfe18883bb7
refs/heads/master
2023-02-04T00:39:41.107043
2023-02-01T21:58:50
2023-02-01T21:58:50
191,603,578
7
5
MIT
2023-02-01T21:58:52
2019-06-12T16:02:32
Python
UTF-8
Python
false
false
1,398
py
class AnimationException(SystemException,ISerializable,_Exception): """ The exception that is thrown when an error occurs while animating a property. """ def add_SerializeObjectState(self,*args): """ add_SerializeObjectState(self: Exception,value: EventHandler[SafeSerializationEventArgs]) """ pass def remove_SerializeObjectState(self,*args): """ remove_SerializeObjectState(self: Exception,value: EventHandler[SafeSerializationEventArgs]) """ pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __reduce_ex__(self,*args): pass def __str__(self,*args): pass Clock=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the clock that generates the animated values. Get: Clock(self: AnimationException) -> AnimationClock """ Property=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the animated dependency property. Get: Property(self: AnimationException) -> DependencyProperty """ Target=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the animated object. Get: Target(self: AnimationException) -> IAnimatable """
[ "sean.moore@ni.com" ]
sean.moore@ni.com
739509fe9d0b3d52864e729246e1fcdb09324e2d
b9000b4f492c6f51fc1277589095c92b25f41328
/lingvo/datasets_test.py
4a0abac8ce7f8d569225f446affe1131a6fb3e80
[ "Apache-2.0" ]
permissive
donstang/lingvo
a30175a4c756ce006a9c7dfbe472477a928d5f3f
9b2b4714c50be695420eb99fd87b4f1c4d0855ca
refs/heads/master
2022-07-26T14:33:36.357634
2022-07-01T03:16:49
2022-07-01T03:17:51
183,879,138
0
0
null
null
null
null
UTF-8
Python
false
false
4,221
py
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for datasets.""" from lingvo import datasets from lingvo.core import base_model_params from lingvo.core import test_utils class DatasetsTest(test_utils.TestCase): def testGetDatasetsFindsAllPublicMethods(self): class DummyDatasetHolder(base_model_params._BaseModelParams): def Train(self): pass def UnexpectedDatasetName(self): pass found_datasets = datasets.GetDatasets(DummyDatasetHolder) self.assertAllEqual(['Train', 'UnexpectedDatasetName'], found_datasets) def testGetDatasetsRaisesErrorOnInvalidDatasets(self): class DummyDatasetHolder(base_model_params._BaseModelParams): def Train(self): pass def BadDataset(self, any_argument): pass with self.assertRaises(datasets.DatasetFunctionError): datasets.GetDatasets(DummyDatasetHolder, warn_on_error=False) def testGetDatasetsWarnsOnError(self): class DummyDatasetHolder(base_model_params._BaseModelParams): def Train(self): pass def BadDataset(self, any_argument): pass with self.assertLogs() as assert_log: found_datasets = datasets.GetDatasets( DummyDatasetHolder, warn_on_error=True) self.assertAllEqual(['Train'], found_datasets) self.assertIn('WARNING:absl:Found a public function BadDataset', assert_log.output[0]) def testGetDatasetsFindsAllPublicMethodsOnInstanceVar(self): class DummyDatasetHolder(base_model_params._BaseModelParams): def Train(self): pass def UnexpectedDatasetName(self): pass found_datasets = datasets.GetDatasets(DummyDatasetHolder()) self.assertAllEqual(['Train', 'UnexpectedDatasetName'], found_datasets) def testGetDatasetsRaisesErrorOnInvalidDatasetsOnInstanceVar(self): class DummyDatasetHolder(base_model_params._BaseModelParams): def Train(self): pass def BadDataset(self, any_argument): pass with self.assertRaises(datasets.DatasetFunctionError): datasets.GetDatasets(DummyDatasetHolder(), warn_on_error=False) def testGetDatasetsWarnsOnErrorOnInstanceVar(self): class DummyDatasetHolder(base_model_params._BaseModelParams): def Train(self): pass def BadDataset(self, any_argument): pass with self.assertLogs() as assert_log: found_datasets = datasets.GetDatasets( DummyDatasetHolder(), warn_on_error=True) self.assertAllEqual(['Train'], found_datasets) self.assertIn('WARNING:absl:Found a public function BadDataset', assert_log.output[0]) def testGetDatasetsWithGetAllDatasetParams(self): class DummyDatasetHolder(base_model_params._BaseModelParams): def GetAllDatasetParams(self): return {'Train': None, 'Dev': None} self.assertAllEqual(['Dev', 'Train'], datasets.GetDatasets(DummyDatasetHolder)) self.assertAllEqual(['Dev', 'Train'], datasets.GetDatasets(DummyDatasetHolder())) def testGetDatasetsOnClassWithPositionalArgumentInit(self): class DummyDatasetHolder(base_model_params._BaseModelParams): def __init__(self, model_spec): pass def Train(self): pass def Dev(self): pass def Search(self): pass self.assertAllEqual(['Dev', 'Train'], datasets.GetDatasets( DummyDatasetHolder, warn_on_error=True)) if __name__ == '__main__': test_utils.main()
[ "copybara-worker@google.com" ]
copybara-worker@google.com
39780953a892df003f3cf73fb888f6ec3b514526
8a10d97fd8be9c8df20bf64acb62cff4931bcf46
/models.py
7600153374f9760a8e77475c4e01629e8291fe60
[]
no_license
chensandiego/render_places
5816eb9b143020db02c4316516ff000560269415
165ab8023ac1e38cb0e86f8d6b1f047622c46d87
refs/heads/master
2021-01-15T08:31:39.705395
2016-07-26T01:47:16
2016-07-26T01:47:16
64,180,658
0
1
null
2016-09-08T04:38:53
2016-07-26T01:45:59
HTML
UTF-8
Python
false
false
2,049
py
from flask.ext.sqlalchemy import SQLAlchemy from werkzeug import generate_password_hash,check_password_hash import geocoder import json from urllib.request import urlopen from urllib.parse import urljoin db=SQLAlchemy() class User(db.Model): __tablename__ ='users' uid = db.Column(db.Integer,primary_key=True) firstname=db.Column(db.String(100)) lastname=db.Column(db.String(100)) email = db.Column(db.String(120),unique=True) pwdhash = db.Column(db.String(54)) def __init__(self,firstname,lastname,email,password): self.firstname=firstname.title() self.lastname=lastname.title() self.email=email.lower() self.set_password(password) def set_password(self,password): self.pwdhash=generate_password_hash(password) def check_password(self,password): return check_password_hash(self.pwdhash,password) # p = Place() # places = p.query("1600 Amphitheater Parkway Mountain View CA") class Place(object): def meters_to_walking_time(self, meters): # 80 meters is one minute walking time return int(meters / 80) def wiki_path(self, slug): return urljoin("http://en.wikipedia.org/wiki/", slug.replace(' ', '_')) def address_to_latlng(self, address): g = geocoder.google(address) return (g.lat, g.lng) def query(self, address): lat, lng = self.address_to_latlng(address) query_url = 'https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=5000&gscoord={0}%7C{1}&gslimit=20&format=json'.format(lat, lng) g = urlopen(query_url) results = g.read().decode('utf8') g.close() data = json.loads(results) places = [] for place in data['query']['geosearch']: name = place['title'] meters = place['dist'] lat = place['lat'] lng = place['lon'] wiki_url = self.wiki_path(name) walking_time = self.meters_to_walking_time(meters) d = { 'name': name, 'url': wiki_url, 'time': walking_time, 'lat': lat, 'lng': lng } places.append(d) return places
[ "chensandiego@gmail.com" ]
chensandiego@gmail.com
0c2553972497c5c92dc8250a3febff16a529ad00
effce116340b7d937bd285e43b49e1ef83d56156
/data_files/377 Combination Sum IV.py
54ebc48fd1647b66ada9e61912eea5443cdad119
[]
no_license
DL2021Spring/CourseProject
a7c7ef57d69bc1b21e3303e737abb27bee3bd585
108cdd906e705e9d4d05640af32d34bfc8b124da
refs/heads/master
2023-04-11T18:52:30.562103
2021-05-18T09:59:59
2021-05-18T09:59:59
365,733,976
0
1
null
null
null
null
UTF-8
Python
false
false
485
py
__author__ = 'Daniel' class Solution(object): def combinationSum4(self, nums, target): F = [0 for _ in xrange(target + 1)] nums = filter(lambda x: x <= target, nums) for k in nums: F[k] = 1 for i in xrange(target + 1): for k in nums: if i - k >= 0: F[i] += F[i-k] return F[target] if __name__ == "__main__": assert Solution().combinationSum4([1, 2, 3], 4) == 7
[ "1042448815@qq.com" ]
1042448815@qq.com
7bee13d0cb73112e145bfacd1f65772a9339d4a8
44b389338c12b0dc2018d8022031b58090c58a63
/Byte_of_Python/str_format.py
37d384f0a73528d7d6a49621979ddd9af022ee12
[]
no_license
llcawthorne/old-python-learning-play
cbe71b414d6fafacec7bad681b91976648b230d3
5241613a5536cd5c086ec56acbc9d825935ab292
refs/heads/master
2016-09-05T17:47:47.985814
2015-07-13T01:25:44
2015-07-13T01:25:44
38,983,419
0
0
null
null
null
null
UTF-8
Python
false
false
178
py
#!/usr/bin/python #Filename: str_format.py age = 25 name = 'Swaroop' print('{0} is {1} years old'.format(name,age)) print('Why is {0} playing with that python?'.format(name))
[ "LLC@acm.org" ]
LLC@acm.org
ae669605ec9b63f7de4aded534b4943cd4f76a68
a9a9e19b1f24033d7141dd6da6572cb425acc09b
/elsie/ext/__init__.py
ab05e9c4d013b72e18d7676980310c548fcf875b
[ "MIT" ]
permissive
spirali/elsie
88be594fec51cfa12f9e5c69bea7b1fd539da9fe
fd95c841d03e453aaac4acd27939ca614cd5ac79
refs/heads/master
2023-06-09T05:59:18.051813
2023-05-25T12:08:50
2023-05-25T12:09:00
134,177,408
49
6
MIT
2023-05-25T12:04:21
2018-05-20T18:48:53
Python
UTF-8
Python
false
false
298
py
""" This module contains extension and helper classes which are not part of the Elsie core. Items from this module may experience backwards-incompatible changes even in non-major releases of Elsie. """ from .list import ordered_list, unordered_list # noqa from .markdown import markdown # noqa
[ "stanislav.bohm@vsb.cz" ]
stanislav.bohm@vsb.cz
58ba36f83dde33f4fc01a00d8a1c5e0a650a051c
04d954f7734a48bb00d510f58793cb516ef03891
/5_CNN对CIFAR-10进行分类/cnn_lrn.py
b2441337d55e1eee197fbbfc96c8632a59b4a516
[]
no_license
MrKingJM/TensorFlow
5ef17a47128ed0b9897d0ffc166edf51d2fc9575
703b6446402c2f15d90b08a9593bcc0517775555
refs/heads/master
2020-03-10T18:53:00.867240
2017-06-13T08:27:58
2017-06-13T08:27:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,982
py
# coding=utf-8 # cnn_lrn from __future__ import division import cifar10, cifar10_input import tensorflow as tf import numpy as np import math import time data_dir = 'cifar10_data/cifar-10-batches-bin' # 下载 CIFAR-10 的默认路径 cifar10.maybe_download_and_extract() # 下载数据集,并解压、展开到其默认位置 batch_size = 128 images_train, labels_train = cifar10_input.distorted_inputs(data_dir=data_dir, batch_size=batch_size) images_test, labels_test = cifar10_input.inputs(eval_data=True, data_dir=data_dir, batch_size=batch_size) def weight_variable(shape, stddev): var = tf.Variable(tf.truncated_normal(shape, stddev=stddev)) # stddev=stddev!!! return var def bias_variable(cons, shape): initial = tf.constant(cons, shape=shape) # 必须是 shape=shape return tf.Variable(initial) def conv(x, W): return tf.nn.conv2d(x, W, [1, 1, 1, 1], padding='SAME') def max_pool_3x3(x): return tf.nn.max_pool(x, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME') image_holder = tf.placeholder(tf.float32, [batch_size, 24, 24, 3]) label_holder = tf.placeholder(tf.int32, [batch_size]) # 第一层 weight1 = weight_variable([5, 5, 3, 64], 5e-2) bias1 = bias_variable(0.0, [64]) conv1 = tf.nn.relu(conv(image_holder, weight1) + bias1) pool1 = max_pool_3x3(conv1) norm1 = tf.nn.lrn(pool1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75) # 第二层 weight2 = weight_variable([5, 5, 64, 64], 5e-2) bias2 = bias_variable(0.1, [64]) conv2 = tf.nn.relu(conv(norm1, weight2) + bias2) norm2 = tf.nn.lrn(conv2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75) pool2 = max_pool_3x3(norm2) reshape = tf.reshape(pool2, [batch_size, -1]) dim = reshape.get_shape()[1].value # 全连接层 weight3 = weight_variable([dim, 384], 0.04) bias3 = bias_variable(0.1, [384]) local3 = tf.nn.relu(tf.matmul(reshape, weight3) + bias3) # 全连接层 weight4 = weight_variable([384, 192], 0.04) bias4 = bias_variable(0.1, [192]) local4 = tf.nn.relu(tf.matmul(local3, weight4) + bias4) # 输出 weight5 = weight_variable([192, 10], 1 / 192.0) bias5 = bias_variable(0.0, [10]) logits = tf.matmul(local4, weight5) + bias5 # 损失函数 def loss(logits, labels): labels = tf.cast(labels, tf.int64) cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels, name='cross_entropy_per_example') cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy') tf.add_to_collection('losses', cross_entropy_mean) return tf.add_n(tf.get_collection('losses'), name='total_loss') loss = loss(logits, label_holder) train_op = tf.train.AdamOptimizer(1e-3).minimize(loss) top_k_op = tf.nn.in_top_k(logits, label_holder, 1) sess = tf.InteractiveSession() tf.global_variables_initializer().run() tf.train.start_queue_runners() max_steps = 3000 for step in range(max_steps): start_time = time.time() image_batch, label_batch = sess.run([images_train, labels_train]) _, loss_value = sess.run([train_op, loss], feed_dict={image_holder: image_batch, label_holder: label_batch}) duration = time.time() - start_time if step % 10 == 0: examples_per_sec = batch_size / duration sec_per_batch = float(duration) print 'step {},loss={},({} examples/sec; {} sec/batch)'.format(step, loss_value, examples_per_sec, sec_per_batch) num_examples = 10000 num_iter = int(math.ceil(num_examples / batch_size)) # 计算一共有多少组 true_count = 0 total_sample_count = num_iter * batch_size step = 0 while step < num_iter: image_batch, label_batch = sess.run([images_test, labels_test]) predictions = sess.run([top_k_op], feed_dict={image_holder: image_batch, label_holder: label_batch}) true_count += np.sum(predictions) step += 1 precision = true_count / total_sample_count print 'precision = ', precision
[ "ywtail@gmail.com" ]
ywtail@gmail.com
f9f753802fda005a7df3d8e87f1684460ae38ba1
7e5dd510284f6944995f1c8586309e6e3acecb84
/main.py
c674ccbbc2802acc706c683b667d6d27caceb6ae
[]
no_license
Namenaro/frog_demo
b3a630d7f8a4139954ebb92c0c83dd76b49f6fb6
b74da899f949233aed1fb07bd48314e961ba99e7
refs/heads/master
2020-03-31T10:52:55.876607
2018-10-08T22:20:56
2018-10-08T22:20:56
152,153,855
0
0
null
null
null
null
UTF-8
Python
false
false
3,425
py
import os from pprint import pprint import tkinter as tk class MainScreen(tk.Frame): def __init__(self, parent): self.frame = tk.Frame(parent) self.frame.pack() self.parent = parent folder = "frog_muskle" self.image_0 = tk.PhotoImage(file=os.path.join(folder, "zero_freq.png")) self.image_1 = tk.PhotoImage(file=os.path.join(folder, "one_freq.png")) self.image_27 = tk.PhotoImage(file=os.path.join(folder, "two_7_freq.png")) self.image_8 = tk.PhotoImage(file=os.path.join(folder, "tetanus.png")) self.pic_freq = {0: self.image_0, 1: self.image_1, 2: self.image_27, 3: self.image_27, 4: self.image_27, 5: self.image_27, 6: self.image_27, 7: self.image_27, 8: self.image_8} self.panel_frame = tk.Frame(self.frame) self.panel_frame.grid(row=0, column=0, padx=25, pady=25) # статическая подпись про герцы self.freq_static_var = tk.StringVar() self.freq_static_label = tk.Label(self.panel_frame, textvariable=self.freq_static_var, relief=tk.RAISED) self.freq_static_var.set(" Гц ") self.freq_static_label.grid(row=0, column=2, padx=5) # статическая подпись про милливольты self.voltage_static_var = tk.StringVar() self.voltage_static_label = tk.Label(self.panel_frame, textvariable=self.voltage_static_var, relief=tk.RAISED) self.voltage_static_var.set(" мВ ") self.voltage_static_label.grid(row=3, column=2, padx=5) # поле ввода про милливольты self.voltage_var = tk.StringVar() self.voltage_var.set("1.5") self.voltage_entry = tk.Entry(self.panel_frame, width=4, state=tk.DISABLED, textvariable=self.voltage_var) self.voltage_entry.grid(row=3, column=1, padx=5) # статическая картинка лягушки frog_pic = os.path.join(folder, "frog.png") self.frog_img = tk.PhotoImage(file=frog_pic) self.label_frog = tk.Label(self.frame, image=self.frog_img, relief=tk.RAISED) self.label_frog.grid(row=0, column=2, padx=25, pady=25) # меняющаяся картика с графиком self.label_graph = tk.Label(self.frame, image=self.pic_freq[0], relief=tk.RAISED) self.label_graph.grid(row=0, column=1, padx=25, pady=25) # ползунок self.freq_var = tk.IntVar() self.scale = tk.Scale(self.panel_frame, variable=self.freq_var, to=8, showvalue=False, command=self.slider_moved) self.scale.grid(row=0, column=0, rowspan=4, sticky=tk.W, padx=5) # поле ввода про герцы self.freq_entry = tk.Entry(self.panel_frame, width=4, textvariable=self.freq_var) self.freq_entry.grid(row=0, column=1, padx=5) def slider_moved(self,value_slider): # сменим картинку self.label_graph.configure(image=self.pic_freq[int(value_slider)]) self.label_graph.image = self.pic_freq[int(value_slider)] def main(): root = tk.Tk() app = MainScreen(root) app.parent.title("Лягушка - демо") root.mainloop() if __name__ == '__main__': main()
[ "nanenaro@gmail.com" ]
nanenaro@gmail.com
51033624394c62c952b6c453f0d94e4a26252199
9fb2139bf41e2301f9ee9069d649c5afe8e7735c
/python/En19cs306027_Lovesh_Kumrawat_Self_created_function_similar_to_'.astype'_in_numpy.py
48ce29a748e1c7cd8b8b7bf5eabfc24d5bf3a64b
[]
no_license
codewithgauri/HacktoberFest
9bc23289b4d93f7832271644a2ded2a83aa22c87
8ce8f687a4fb7c3953d1e0a5b314e21e4553366e
refs/heads/master
2023-01-02T07:20:51.634263
2020-10-26T07:02:34
2020-10-26T07:02:34
307,285,210
3
0
null
null
null
null
UTF-8
Python
false
false
838
py
# In 'numpy' we can convert values of matrix into 'integer' by 'np.matrix('1.4 0.6;1.8 3.2;1.4 4.2',dtype=int)' or 'matrix_variable.astype('int32')' but i created a function for this. import numpy as np def matrix_integer_values_any_shape(inp): #* For any shape of matrix. lst=[] mtx=np.matrix([int(j) for i in np.array(inp) for j in i]) for i in range(0,inp.shape[0]*inp.shape[1],inp.shape[1]): temp=[] [temp.append(mtx[0,i+j]) for j in range(inp.shape[1])],lst.append(temp) return np.matrix(lst) print('Real Matrix with Floating Values:') z_4_3=np.matrix('1.4 3.6 5.7 4.3;1.8 3.2 34.64 235.77;1.4 34.213 4.2 653.567') print(z_4_3,z_4_3.shape,'\n') print('With Self Created Function:') z=matrix_integer_values_any_shape(z_4_3) print(z,z.shape,'\n') print('With Inbuilt Function:') z=z.astype('int32') print(z,z.shape,'\n')
[ "noreply@github.com" ]
codewithgauri.noreply@github.com
43a34c8971cd8b4b94a667b95d9f50b718825d12
8a8974f433ed4c86eec3960ef953ddd21464448b
/doi_request/__init__.py
99c59af476fba1092d357b903fbdaa02df3f9bef
[ "BSD-2-Clause" ]
permissive
scieloorg/doi_request
70c533afb135ebd11a61b3c782750e4938033260
52da64d8e5cc1782cd91968f2a8da3d4c9c736dc
refs/heads/master
2023-08-19T02:55:27.466086
2021-03-08T18:36:09
2021-03-08T18:36:09
87,971,952
1
4
BSD-2-Clause
2023-07-27T00:01:41
2017-04-11T19:33:40
JavaScript
UTF-8
Python
false
false
2,233
py
import os from pyramid.config import Configurator from pyramid.session import SignedCookieSessionFactory from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from doi_request.models import initialize_sql VERSION = '1.2.0' def version(request): return VERSION def db(request): maker = request.registry.dbmaker session = maker() def cleanup(request): if request.exception is not None: session.rollback() else: session.commit() session.close() request.add_finished_callback(cleanup) return session def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) # Database Config engine = create_engine(os.environ.get('SQL_ENGINE', 'sqlite:///:memory:')) static_assets = os.environ.get('STATIC_MEDIA', 'media') config.registry.dbmaker = sessionmaker(bind=engine) config.scan('doi_request.models') # the "important" line initialize_sql(engine) config.add_request_method(db, reify=True) config.add_request_method(version) config.include('pyramid_mako') config.add_static_view('static', 'static', cache_max_age=3600) config.add_static_view('media', static_assets, cache_max_age=3600) config.add_route('list_deposits', '/') config.add_route('help', '/help') config.add_route('deposit_request', '/deposit/request') config.add_route('expenses', '/expenses') config.add_route('expenses_details', '/expenses/details') config.add_route('deposit_post', '/deposit/post') config.add_route('deposit', '/deposit') config.add_route('downloads', '/downloads') config.add_subscriber('doi_request.subscribers.add_renderer_globals', 'pyramid.events.BeforeRender') config.add_subscriber('doi_request.subscribers.add_localizer', 'pyramid.events.NewRequest') config.add_translation_dirs('doi_request:locale') # Session config navegation_session_factory = SignedCookieSessionFactory('sses_navegation') config.set_session_factory(navegation_session_factory) config.scan() return config.make_wsgi_app()
[ "fabiobatalha@gmail.com" ]
fabiobatalha@gmail.com
58e052ed808c502f500414a25bdc06bdbdc8c904
46ac0965941d06fde419a6f216db2a653a245dbd
/sdks/python/test/test_NotificationConfigApple.py
39490853d098bca2c7862b7c84916113eb5abb7c
[ "MIT", "Unlicense" ]
permissive
b3nab/appcenter-sdks
11f0bab00d020abb30ee951f7656a3d7ed783eac
bcc19c998b5f648a147f0d6a593dd0324e2ab1ea
refs/heads/master
2022-01-27T15:06:07.202852
2019-05-19T00:12:43
2019-05-19T00:12:43
187,386,747
0
3
MIT
2022-01-22T07:57:59
2019-05-18T17:29:21
Python
UTF-8
Python
false
false
985
py
# coding: utf-8 """ App Center Client Microsoft Visual Studio App Center API # noqa: E501 OpenAPI spec version: preview Contact: benedetto.abbenanti@gmail.com Project Repository: https://github.com/b3nab/appcenter-sdks """ from __future__ import absolute_import import unittest import appcenter_sdk from NotificationConfigApple.clsNotificationConfigApple import NotificationConfigApple # noqa: E501 from appcenter_sdk.rest import ApiException class TestNotificationConfigApple(unittest.TestCase): """NotificationConfigApple unit test stubs""" def setUp(self): pass def tearDown(self): pass def testNotificationConfigApple(self): """Test NotificationConfigApple""" # FIXME: construct object with mandatory attributes with example values # model = appcenter_sdk.models.clsNotificationConfigApple.NotificationConfigApple() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "b3nab@users.noreply.github.com" ]
b3nab@users.noreply.github.com
a125ff9ec9ac7d4c723caf648f66e55462f31b62
ee974d693ca4c4156121f8cb385328b52eaac07c
/env/lib/python3.6/site-packages/pip/_vendor/urllib3/filepost.py
e01a1a0d1044c86119534bb92e511348ffac1217
[]
no_license
ngonhi/Attendance_Check_System_with_Face_Recognition
f4531cc4dee565d0e45c02217f73f3eda412b414
92ff88cbc0c740ad48e149033efd38137c9be88d
refs/heads/main
2023-03-12T07:03:25.302649
2021-02-26T15:37:33
2021-02-26T15:37:33
341,493,686
1
0
null
null
null
null
UTF-8
Python
false
false
129
py
version https://git-lfs.github.com/spec/v1 oid sha256:27650543085246b415561217c916ce5c820588dd89fe70824bb6db3e60d439ae size 2534
[ "Nqk180998!" ]
Nqk180998!
53e98abf1cde068fde4788a1920f72b9e87e3665
11334e46d3575968de5062c7b0e8578af228265b
/Examples/voltagereadspeed/orig/orig_batt_test.py
45a6743f58a9ee101f6baf28fd3738d5bc9aad21
[]
no_license
slowrunner/Carl
99262f16eaf6d53423778448dee5e5186c2aaa1e
1a3cfb16701b9a3798cd950e653506774c2df25e
refs/heads/master
2023-06-08T05:55:55.338828
2023-06-04T02:39:18
2023-06-04T02:39:18
145,750,624
19
2
null
2023-06-04T02:39:20
2018-08-22T18:59:34
Roff
UTF-8
Python
false
false
2,419
py
#!/usr/bin/python3 import sys from easygopigo3 import EasyGoPiGo3 from time import sleep mybot = EasyGoPiGo3() value = 0 count = 0 Reference_Input_Voltage = 12.00 file1 = open("./voltage_test.txt", "a") def round_up(x, decimal_precision=2): # "x" is the value to be rounded using 4/5 rounding rules # always rounding away from zero # # "decimal_precision is the number of decimal digits desired # after the decimal divider mark. # # It returns the **LESSER** of: # (a) The number of digits requested # (b) The number of digits in the number if less # than the number of decimal digits requested # Example: (Assume decimal_precision = 3) # round_up(1.123456, 3) will return 1.123. (4 < 5) # round_up(9.876543, 3) will return 9.877. (5 >= 5) # round_up(9.87, 3) will return 9.87 # because there are only two decimal digits and we asked for 3 # if decimal_precision < 0: decimal_precision = 0 exp = 10 ** decimal_precision x = exp * x if x > 0: val = (int(x + 0.5) / exp) elif x < 0: val = (int(x - 0.5) / exp) else: val = 0 if decimal_precision <= 0: return (int(val)) else: return (val) try: while True: Measured_Battery_Voltage = round_up(mybot.get_voltage_battery(), 3) Five_v_System_Voltage = round_up(mybot.get_voltage_5v(), 3) Measured_voltage_differential = round_up((Reference_Input_Voltage - Measured_Battery_Voltage),3) value = value + Measured_voltage_differential count = count+1 print("Measured Battery Voltage =", Measured_Battery_Voltage) print("Measured voltage differential = ", Measured_voltage_differential) print("5v system voltage =", Five_v_System_Voltage, "\n") print("Total number of measurements so far is ", count) sleep(1.00) except KeyboardInterrupt: print("\nThat's All Folks!\n") data = ["\nWe took ", str(count), " measurements and the average differential was ", str(round_up(value/count, 3)), "\n(based on an input reference voltage of ", str(Reference_Input_Voltage), ")\n"] file1.writelines(data) print("We took ", str(count), " measurements and the average differential was ", str(round_up(value/count, 3)), "\n(based on an input reference voltage of ", str(Reference_Input_Voltage), ")\n") file1.close() sys.exit(0)
[ "slowrunner@users.noreply.github.com" ]
slowrunner@users.noreply.github.com
a6ffeeae418a936374b98c0f082f122766428944
60d5b5b1f1c912d1655de3884efc09dfddd8d132
/sites/kotourism/events/feeds.py
27d81038a0eeef22fe3d06582bed6104baaf1b6b
[]
no_license
alexgula/django_sites
15033c739401f24603e957c5a034d63652f0d21f
038834c0f544d6997613d61d593a7d5abf673c70
refs/heads/master
2016-09-05T11:02:43.838095
2014-07-07T11:36:07
2014-07-07T11:36:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,464
py
# coding=utf-8 from datetime import timedelta from collections import namedtuple from django.utils.timezone import now from django.contrib.syndication.views import Feed from django.utils.feedgenerator import Atom1Feed from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext, pgettext, get_language from picassoft.utils.templatetags.markup import restructuredtext from .models import Event, EVENT_TYPES_SOURCE EVENT_TYPES = dict(EVENT_TYPES_SOURCE) EventType = namedtuple('EventType', ['code', 'desc']) class EventFeed(Feed): feed_type = Atom1Feed description = _("Updates on changes and additions to ko-tourism.gov.ua.") subtitle = description def get_object(self, request, type_slug): return EventType(type_slug, pgettext('plural', EVENT_TYPES[type_slug])) def title(self, obj): return ugettext("Latest tourists {} of Kyiv oblast.").format(obj.desc.lower()) def link(self, obj): from django.core import urlresolvers return urlresolvers.reverse('typed_event_list', kwargs=dict(type_slug=obj.code)) def items(self, obj): return Event.objects.active().filter(type=obj.code, post_date__gte=now()-timedelta(weeks=13)).order_by('-post_date') def item_title(self, item): return item.name def item_description(self, item): return restructuredtext(item.desc) def item_pubdate(self, item): return item.post_date
[ "alexgula@gmail.com" ]
alexgula@gmail.com
cbc4a88ee7d1c9890db6f01b5bc2df4ac1869912
44064ed79f173ddca96174913910c1610992b7cb
/Second_Processing_app/temboo/Library/Facebook/Actions/Video/WantsToWatch/UpdateWantsToWatch.py
bff67d21bb448deb53c6b84900556134e8237aeb
[]
no_license
dattasaurabh82/Final_thesis
440fb5e29ebc28dd64fe59ecd87f01494ed6d4e5
8edaea62f5987db026adfffb6b52b59b119f6375
refs/heads/master
2021-01-20T22:25:48.999100
2014-10-14T18:58:00
2014-10-14T18:58:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,766
py
# -*- coding: utf-8 -*- ############################################################################### # # UpdateWantsToWatch # Updates an existing wants_to_watch action. # # Python version 2.6 # ############################################################################### from temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class UpdateWantsToWatch(Choreography): def __init__(self, temboo_session): """ Create a new instance of the UpdateWantsToWatch Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ Choreography.__init__(self, temboo_session, '/Library/Facebook/Actions/Video/WantsToWatch/UpdateWantsToWatch') def new_input_set(self): return UpdateWantsToWatchInputSet() def _make_result_set(self, result, path): return UpdateWantsToWatchResultSet(result, path) def _make_execution(self, session, exec_id, path): return UpdateWantsToWatchChoreographyExecution(session, exec_id, path) class UpdateWantsToWatchInputSet(InputSet): """ An InputSet with methods appropriate for specifying the inputs to the UpdateWantsToWatch Choreo. The InputSet object is used to specify input parameters when executing this Choreo. """ def set_AccessToken(self, value): """ Set the value of the AccessToken input for this Choreo. ((required, string) The access token retrieved from the final step of the OAuth process.) """ InputSet._set_input(self, 'AccessToken', value) def set_ActionID(self, value): """ Set the value of the ActionID input for this Choreo. ((required, string) The id of the action to update.) """ InputSet._set_input(self, 'ActionID', value) def set_AiringEndTime(self, value): """ Set the value of the AiringEndTime input for this Choreo. ((optional, date) The time that the airing ends.) """ InputSet._set_input(self, 'AiringEndTime', value) def set_AiringID(self, value): """ Set the value of the AiringID input for this Choreo. ((optional, string) The id of the video airing.) """ InputSet._set_input(self, 'AiringID', value) def set_AiringStartTime(self, value): """ Set the value of the AiringStartTime input for this Choreo. ((optional, date) The time that the airing begins.) """ InputSet._set_input(self, 'AiringStartTime', value) def set_EndTime(self, value): """ Set the value of the EndTime input for this Choreo. ((optional, date) The time that the user ended the action (e.g. 2013-06-24T18:53:35+0000).) """ InputSet._set_input(self, 'EndTime', value) def set_Episode(self, value): """ Set the value of the Episode input for this Choreo. ((optional, string) The URL or ID for an Open Graph object representing an episode of a show.) """ InputSet._set_input(self, 'Episode', value) def set_ExpiresIn(self, value): """ Set the value of the ExpiresIn input for this Choreo. ((optional, integer) The amount of time (in milliseconds) from the publish_time that the action will expire.) """ InputSet._set_input(self, 'ExpiresIn', value) def set_Message(self, value): """ Set the value of the Message input for this Choreo. ((optional, string) A message attached to this action. Setting this parameter requires enabling of message capabilities.) """ InputSet._set_input(self, 'Message', value) def set_Movie(self, value): """ Set the value of the Movie input for this Choreo. ((optional, string) The URL or ID for an Open Graph object representing a movie.) """ InputSet._set_input(self, 'Movie', value) def set_Other(self, value): """ Set the value of the Other input for this Choreo. ((optional, string) The URL or ID for an Open Graph object representing any general video content.) """ InputSet._set_input(self, 'Other', value) def set_Place(self, value): """ Set the value of the Place input for this Choreo. ((optional, string) The URL or ID for an Open Graph object representing the location associated with this action.) """ InputSet._set_input(self, 'Place', value) def set_TVShow(self, value): """ Set the value of the TVShow input for this Choreo. ((optional, string) The URL or ID for an Open Graph object representing a TV show.) """ InputSet._set_input(self, 'TVShow', value) def set_Tags(self, value): """ Set the value of the Tags input for this Choreo. ((optional, string) A comma separated list of other profile IDs that also performed this action.) """ InputSet._set_input(self, 'Tags', value) class UpdateWantsToWatchResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the UpdateWantsToWatch Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. """ def getJSONFromString(self, str): return json.loads(str) def get_Response(self): """ Retrieve the value for the "Response" output from this Choreo execution. (The response from Facebook.) """ return self._output.get('Response', None) class UpdateWantsToWatchChoreographyExecution(ChoreographyExecution): def _make_result_set(self, response, path): return UpdateWantsToWatchResultSet(response, path)
[ "dattasaurabh82@gmail.com" ]
dattasaurabh82@gmail.com
4c049858fdeff016c62349c76078e6d0a75dc918
10d98fecb882d4c84595364f715f4e8b8309a66f
/aloe/aloe/rfill/utils/rfill_consts.py
18131c6e49d3a1e196701d0718b8cdc9deb7edbe
[ "CC-BY-4.0", "Apache-2.0" ]
permissive
afcarl/google-research
51c7b70d176c0d70a5ee31ea1d87590f3d6c6f42
320a49f768cea27200044c0d12f394aa6c795feb
refs/heads/master
2021-12-02T18:36:03.760434
2021-09-30T20:59:01
2021-09-30T21:07:02
156,725,548
1
0
Apache-2.0
2018-11-08T15:13:53
2018-11-08T15:13:52
null
UTF-8
Python
false
false
2,663
py
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # 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. """Robustfill program graph representation. Constants are predefined here. """ # pylint: skip-file import string CONSTANTS = ['dummy', ']', ',', '-', '.', '@', "'", '\"', '(', ')', ':', '%'] REGEXES = [None] * 10 REGEXES[1] = '[A-Z]([a-z])+' # ProperCase REGEXES[2] = '[A-Z]+' # CAPS REGEXES[3] = '[a-z]+' # lowercase REGEXES[4] = r'\d+' # Digits REGEXES[5] = '[a-zA-Z]+' # Alphabets REGEXES[6] = '[a-zA-Z0-9]+' # Alphanumeric REGEXES[7] = r'\s+' # Whitespace REGEXES[8] = '^' REGEXES[9] = '$' STR_VOCAB = (''.join(CONSTANTS[1:]) + string.ascii_lowercase + string.ascii_uppercase + string.digits) + ' ' RFILL_NODE_TYPES = { 'ConstPos--1': 0, 'ConstPos--2': 1, 'ConstPos--3': 2, 'ConstPos--4': 3, 'ConstPos-0': 4, 'ConstPos-1': 5, 'ConstPos-2': 6, 'ConstPos-3': 7, 'ConstPos-4': 8, 'ConstStr-1': 9, 'ConstStr-10': 10, 'ConstStr-11': 11, 'ConstStr-2': 12, 'ConstStr-3': 13, 'ConstStr-4': 14, 'ConstStr-5': 15, 'ConstStr-6': 16, 'ConstStr-7': 17, 'ConstStr-8': 18, 'ConstStr-9': 19, 'ConstTok': 20, 'RegPos': 21, 'RegexTok': 22, 'SubStr': 23, 'c1-1': 24, 'c1-10': 25, 'c1-11': 26, 'c1-2': 27, 'c1-3': 28, 'c1-4': 29, 'c1-5': 30, 'c1-6': 31, 'c1-7': 32, 'c1-8': 33, 'c1-9': 34, 'direct-End': 35, 'direct-Start': 36, 'expr_root': 37, 'idx--1': 38, 'idx--2': 39, 'idx--3': 40, 'idx--4': 41, 'idx-0': 42, 'idx-1': 43, 'idx-2': 44, 'idx-3': 45, 'idx-4': 46, 'r1-1': 47, 'r1-2': 48, 'r1-3': 49, 'r1-4': 50, 'r1-5': 51, 'r1-6': 52, 'r1-7': 53, 'r1-8': 54, 'r1-9': 55 } RFILL_EDGE_TYPES = { 'c1': 0, 'direct': 1, 'idx': 2, 'p1': 3, 'p2': 4, 'pos_param': 5, 'r1': 6, 'subexpr': 7, 'succ': 8, 'rev-c1': 9, 'rev-direct': 10, 'rev-idx': 11, 'rev-p1': 12, 'rev-p2': 13, 'rev-pos_param': 14, 'rev-r1': 15, 'rev-subexpr': 16, 'rev-succ': 17 }
[ "copybara-worker@google.com" ]
copybara-worker@google.com
d63074174c227a34a29aa659680afcb60b7d057f
bf3049a786140bca8d6f5dfdd754086d9395a5e2
/src/main/management/commands/correctdb.py
8f1b309b5cbd2e24488be7108872853bd7e6a558
[]
no_license
nvbn/djang0byte
ecefccc60f622c8aa55315ab478aacddbd8fc3b5
39deb1dc046c80edd6bfdfbef8391842eda35dd2
refs/heads/reload
2016-09-05T17:03:44.323217
2014-10-01T17:20:12
2014-10-01T17:20:12
2,582,402
26
7
null
2014-10-01T17:20:12
2011-10-15T16:06:06
Python
UTF-8
Python
false
false
549
py
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand from main.models import Post from django.db.models import Q class Command(BaseCommand): def handle(self, **options): qs = Post.objects.filter( Q(title__icontains=u'решен') | Q(title__icontains=u'решён') | Q(title__icontains=u'solv'), blog__type__is_qa=True, ) print 'fix %d posts' % qs.count() for post in qs: #Shit, update not work post.solved = True post.save(convert=True)
[ "nvbn.rm@gmail.com" ]
nvbn.rm@gmail.com
a716c01559400043f512cdc990ebfc7b5cb59da6
92949cad6725d61d4a40717bb3d859911e152664
/ytree/frontends/rockstar/arbor.py
6da1a94c02cf0fd0962d4e695a8e85b42ee0ae1d
[ "BSD-3-Clause" ]
permissive
jwise77/ytree
662fca1df8358d7d1c13103bf86de97ddb16de2a
f179c07ae4696cce7ae6376417e814dabd6c9d1b
refs/heads/master
2023-06-13T06:22:55.513112
2020-01-06T19:14:45
2020-01-06T19:14:45
238,534,101
0
0
NOASSERTION
2020-02-05T19:44:23
2020-02-05T19:44:22
null
UTF-8
Python
false
false
4,186
py
""" RockstarArbor class and member functions """ #----------------------------------------------------------------------------- # Copyright (c) ytree development team. All rights reserved. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- import glob from yt.units.yt_array import \ UnitParseError from ytree.data_structures.arbor import \ CatalogArbor from ytree.frontends.rockstar.fields import \ RockstarFieldInfo, \ setup_field_groups from ytree.frontends.rockstar.io import \ RockstarDataFile class RockstarArbor(CatalogArbor): """ Class for Arbors created from Rockstar out_*.list files. Use only descendent IDs to determine tree relationship. """ _suffix = ".list" _field_info_class = RockstarFieldInfo _data_file_class = RockstarDataFile def _parse_parameter_file(self): fgroups = setup_field_groups() rems = ["%s%s%s" % (s[0], t, s[1]) for s in [("(", ")"), ("", "")] for t in ["physical, peculiar", "comoving", "physical"]] f = open(self.filename, "r") # Read the first line as a list of all fields. fields = f.readline()[1:].strip().split() # Get box size, cosmological parameters, and units. while True: line = f.readline() if line is None or not line.startswith("#"): break elif line.startswith("#Om = "): pars = line[1:].split(";") for j, par in enumerate(["omega_matter", "omega_lambda", "hubble_constant"]): v = float(pars[j].split(" = ")[1]) setattr(self, par, v) elif line.startswith("#Box size:"): pars = line.split(":")[1].strip().split() self.box_size = self.quan(float(pars[0]), pars[1]) # Looking for <quantities> in <units> elif line.startswith("#Units:"): if " in " not in line: continue quan, punits = line[8:].strip().split(" in ", 2) for rem in rems: while rem in punits: pre, mid, pos = punits.partition(rem) punits = pre + pos try: self.quan(1, punits) except UnitParseError: punits = "" for group in fgroups: if group.in_group(quan): group.units = punits break f.close() fi = {} for i, field in enumerate(fields): for group in fgroups: units = "" if group.in_group(field): units = getattr(group, "units", "") break fi[field] = {"column": i, "units": units} # the scale factor comes from the catalog file header fields.append("scale_factor") fi["scale_factor"] = {"source": "header", "units": ""} self.field_list = fields self.field_info.update(fi) def _get_data_files(self): """ Get all out_*.list files and sort them in reverse order. """ prefix = self.filename.rsplit("_", 1)[0] suffix = self._suffix my_files = glob.glob("%s_*%s" % (prefix, suffix)) # sort by catalog number my_files.sort( key=lambda x: self._get_file_index(x, prefix, suffix), reverse=True) self.data_files = \ [self._data_file_class(f, self) for f in my_files] def _get_file_index(self, f, prefix, suffix): return int(f[f.find(prefix)+len(prefix)+1:f.rfind(suffix)]), @classmethod def _is_valid(self, *args, **kwargs): """ File should end in .list. """ fn = args[0] if not fn.endswith(".list"): return False return True
[ "brittonsmith@gmail.com" ]
brittonsmith@gmail.com
b11951b8ce3f201f333ca12180beaa1dba34b567
f0b75bd94f133a13f469f429a696f26be3be9862
/week 2/.history/utils_20200204173854.py
2e69e8e8be516eac983005ccf56b3881f8eceb20
[]
no_license
dechavez4/Python_handin_assignments
023350fabd212cdf2a4ee9cd301306dc5fd6bea0
82fd8c991e560c18ecb2152ea5a8fc35dfc3c608
refs/heads/master
2023-01-11T23:31:27.220757
2020-05-22T10:33:56
2020-05-22T10:33:56
237,179,899
0
0
null
2022-12-30T20:14:04
2020-01-30T09:30:16
Python
UTF-8
Python
false
false
400
py
import os.path from os import path from sys import argv import python_second_assignment as myList # A. first function takes a path to a folder and writes all filenames in the folder to a specified output file folderpath = "/Users/robin/Desktop/semester_4/python/myPythonCode/week 2" def read_folder(): entries = os.listdir(folderpath) for entry in entries: print(entry) read_folder()
[ "chavezgamingv2@hotmail.com" ]
chavezgamingv2@hotmail.com
a8f873115c95b3d8eecb33fcdafaac877d78ad6a
5a52ccea88f90dd4f1acc2819997fce0dd5ffb7d
/alipay/aop/api/domain/KoubeiMarketingCampaignMerchantActivityOfflineModel.py
3cbd886eb6742480b12b1db2f30f6611b7c11127
[ "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
2,955
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class KoubeiMarketingCampaignMerchantActivityOfflineModel(object): def __init__(self): self._activity_id = None self._memo = None self._operator = None self._operator_type = None self._out_request_no = None @property def activity_id(self): return self._activity_id @activity_id.setter def activity_id(self, value): self._activity_id = value @property def memo(self): return self._memo @memo.setter def memo(self, value): self._memo = value @property def operator(self): return self._operator @operator.setter def operator(self, value): self._operator = value @property def operator_type(self): return self._operator_type @operator_type.setter def operator_type(self, value): self._operator_type = value @property def out_request_no(self): return self._out_request_no @out_request_no.setter def out_request_no(self, value): self._out_request_no = value def to_alipay_dict(self): params = dict() if self.activity_id: if hasattr(self.activity_id, 'to_alipay_dict'): params['activity_id'] = self.activity_id.to_alipay_dict() else: params['activity_id'] = self.activity_id if self.memo: if hasattr(self.memo, 'to_alipay_dict'): params['memo'] = self.memo.to_alipay_dict() else: params['memo'] = self.memo if self.operator: if hasattr(self.operator, 'to_alipay_dict'): params['operator'] = self.operator.to_alipay_dict() else: params['operator'] = self.operator if self.operator_type: if hasattr(self.operator_type, 'to_alipay_dict'): params['operator_type'] = self.operator_type.to_alipay_dict() else: params['operator_type'] = self.operator_type if self.out_request_no: if hasattr(self.out_request_no, 'to_alipay_dict'): params['out_request_no'] = self.out_request_no.to_alipay_dict() else: params['out_request_no'] = self.out_request_no return params @staticmethod def from_alipay_dict(d): if not d: return None o = KoubeiMarketingCampaignMerchantActivityOfflineModel() if 'activity_id' in d: o.activity_id = d['activity_id'] if 'memo' in d: o.memo = d['memo'] if 'operator' in d: o.operator = d['operator'] if 'operator_type' in d: o.operator_type = d['operator_type'] if 'out_request_no' in d: o.out_request_no = d['out_request_no'] return o
[ "liuqun.lq@alibaba-inc.com" ]
liuqun.lq@alibaba-inc.com
7384f79ed839dd47ca168b9eca226acf619fa1ef
bf769a3a3935a8e08f11fdf606f2e2e2bc6a5307
/PyQtGui/stickyNotes/Ui_mainwindow.py
b82b0e288c448dca5912a3ce5bb22d61848d9bbb
[]
no_license
metanoia1989/QTStudy
b71f2c8cf6fd001a14db3f1b5ece82c1cc7f7a93
29465c6bb9fc0ef2e50a9bf2f66d996ecbd086c0
refs/heads/master
2021-12-25T16:50:26.915441
2021-10-10T01:26:14
2021-10-10T01:26:14
193,919,811
3
2
null
2021-01-25T09:23:30
2019-06-26T14:22:41
HTML
UTF-8
Python
false
false
3,005
py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'd:\WorkSpace\QT\QTStudy\PyQtGui\stickyNotes\mainwindow.ui' # # Created by: PyQt5 UI code generator 5.14.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(378, 333) MainWindow.setStyleSheet("QPushButton {\n" " border: 0px;\n" "}") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.closeButton = QtWidgets.QPushButton(self.centralwidget) self.closeButton.setMinimumSize(QtCore.QSize(25, 20)) self.closeButton.setMaximumSize(QtCore.QSize(25, 20)) self.closeButton.setBaseSize(QtCore.QSize(2, 0)) font = QtGui.QFont() font.setPointSize(30) font.setBold(True) font.setWeight(75) self.closeButton.setFont(font) self.closeButton.setObjectName("closeButton") self.horizontalLayout.addWidget(self.closeButton) spacerItem = QtWidgets.QSpacerItem(228, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.moreButton = QtWidgets.QPushButton(self.centralwidget) self.moreButton.setMinimumSize(QtCore.QSize(25, 25)) self.moreButton.setMaximumSize(QtCore.QSize(25, 25)) self.moreButton.setBaseSize(QtCore.QSize(0, 0)) font = QtGui.QFont() font.setPointSize(30) font.setBold(True) font.setWeight(75) self.moreButton.setFont(font) self.moreButton.setObjectName("moreButton") self.horizontalLayout.addWidget(self.moreButton) self.verticalLayout.addLayout(self.horizontalLayout) self.textEdit = QtWidgets.QTextEdit(self.centralwidget) font = QtGui.QFont() font.setPointSize(11) self.textEdit.setFont(font) self.textEdit.setFrameShape(QtWidgets.QFrame.NoFrame) self.textEdit.setFrameShadow(QtWidgets.QFrame.Plain) self.textEdit.setLineWidth(0) self.textEdit.setObjectName("textEdit") self.verticalLayout.addWidget(self.textEdit) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.closeButton.setText(_translate("MainWindow", "×")) self.moreButton.setText(_translate("MainWindow", "+"))
[ "sogaxili@gmail.com" ]
sogaxili@gmail.com
6c9b556dd08e9ff9e09b54f91e034188ecff94ee
9b0b2029225c680f978ae041552cf68d977144ac
/test_singleton.py
99dedd8f298421b143d9fe46cae0786cf26e5f3d
[]
no_license
1151332702/flask_rest_api
59547189d5928a16f7cee7b36a99f365627f4814
ad5df495157e12858c2869c8899ded10650c2e88
refs/heads/master
2021-06-23T10:47:01.280030
2019-10-24T10:31:25
2019-10-24T10:31:25
208,002,649
0
0
null
2021-03-20T01:59:21
2019-09-12T08:34:33
Python
UTF-8
Python
false
false
985
py
# -*- coding: utf-8 -*- # @Time : 2019/1/31 16:37 # @Author : lilong # @File : test_singleton.py # @Description: 单例模式 def singletom(cls): _instance = {} def decorator(*args, **kwargs): if cls not in _instance: _instance[cls] = cls(*args, **kwargs) return _instance[cls] return decorator @singletom class A(object): a = 100 def __init__(self, x): self.x = x class B(object): a = 100 def __init__(self, x): self.x = x # 利用线程实现 import threading class Singleton(object): _instance_lock = threading.Lock() def __init__(self): pass def __new__(cls, *args, **kwargs): if not hasattr(Singleton, '_instance'): with Singleton._instance_lock: if not hasattr(Singleton, '_instance'): Singleton._instance = object.__new__(cls) return Singleton._instance o1 = Singleton() o2 = Singleton() print(o1) print(o2)
[ "12345678" ]
12345678
8b8dce1c9245308e1dfb6e30ce3d4510f9f9fcd4
64bf39b96a014b5d3f69b3311430185c64a7ff0e
/intro-ansible/venv3/lib/python3.8/site-packages/ansible/module_utils/compat/importlib.py
eee0ddf7bcfc9b2fe9f587bbecf72611eb19c6a3
[ "MIT" ]
permissive
SimonFangCisco/dne-dna-code
7072eba7da0389e37507b7a2aa5f7d0c0735a220
2ea7d4f00212f502bc684ac257371ada73da1ca9
refs/heads/master
2023-03-10T23:10:31.392558
2021-02-25T15:04:36
2021-02-25T15:04:36
342,274,373
0
0
MIT
2021-02-25T14:39:22
2021-02-25T14:39:22
null
UTF-8
Python
false
false
580
py
# Copyright (c) 2020 Matt Martz <matt@sivel.net> # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import sys try: from importlib import import_module except ImportError: # importlib.import_module returns the tail # whereas __import__ returns the head # compat to work like importlib.import_module def import_module(name): __import__(name) return sys.modules[name]
[ "sifang@cisco.com" ]
sifang@cisco.com
d22ae5e1ce4798f74ede4ea8c8c34e9499269554
ab8187626aa68c1f92301db78e9f8b0c4b088554
/Greedy/1561_h.py
249aef34c00cf89b7823a2d1498b920884dffe79
[]
no_license
khj68/algorithm
2818f87671019f9f2305ec761fd226e737f12025
efebe142b9b52e966e0436be3b87fb32b4f7ea32
refs/heads/master
2023-04-25T02:33:13.403943
2021-05-04T03:09:38
2021-05-04T03:09:38
287,733,041
0
0
null
null
null
null
UTF-8
Python
false
false
347
py
class Solution: def maxCoins(self, piles: List[int]) -> int: if len(piles) == 3: return piles[1] # print(len(piles)%2) # print(list((i, a) for i, a in enumerate(sorted(piles)[len(piles)//3:]) if i % 2 == len(piles)%2)) return sum(a for i, a in enumerate(sorted(piles)[len(piles)//3:]) if i % 2 == 0)
[ "maga40@naver.com" ]
maga40@naver.com
ee5061ff77da5e4d545b401ec0ba8bd3739049c2
4f74e6d72b98cd1da2190313e4a7eb9d342cc93d
/organizations_ext/migrations/0003_auto_20200516_1724.py
57927d172cf2467165b5a315fade75348b42c88c
[ "BSD-3-Clause", "MIT" ]
permissive
adamgogogo/glitchtip-backend
ef0c529b71d5a4632a235b40a10e0b428a1cee3a
ee71d1b732d92868189d520aa111c09b116b7b22
refs/heads/master
2023-02-01T23:10:53.734450
2020-12-19T19:32:10
2020-12-19T19:32:10
323,588,534
0
0
null
null
null
null
UTF-8
Python
false
false
477
py
# Generated by Django 3.0.6 on 2020-05-16 17:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('organizations_ext', '0002_organization_is_accepting_events'), ] operations = [ migrations.AlterField( model_name='organization', name='is_accepting_events', field=models.BooleanField(default=True, help_text='Used for throttling at org level'), ), ]
[ "david@burkesoftware.com" ]
david@burkesoftware.com
8ffa10b8e5334346b910ca9a0e0357a52d68c971
a2f6e449e6ec6bf54dda5e4bef82ba75e7af262c
/venv/Lib/site-packages/pandas/core/common.py
395464a24bdf2b741b5354fd0af8e443c99af55b
[]
no_license
mylonabusiness28/Final-Year-Project-
e4b79ccce6c19a371cac63c7a4ff431d6e26e38f
68455795be7902b4032ee1f145258232212cc639
refs/heads/main
2023-07-08T21:43:49.300370
2021-06-05T12:34:16
2021-06-05T12:34:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
130
py
version https://git-lfs.github.com/spec/v1 oid sha256:b63cf39ef1bd3fc626c028f158f4a70e0c602beae099dd24576a97afa69d6250 size 14109
[ "chuksajeh1@gmail.com" ]
chuksajeh1@gmail.com
a8897543440a99c7f65add70fcdc2ec5e1552753
829fbf5717b902f48ca6e748a51cf4febb59451e
/test/functional/p2p_pos_fakestake.py
ada5258fb6080a031ddfe53a533cba6cbf4f6ad7
[ "MIT" ]
permissive
suprnurd/KuboCoin
bb03614814c2112f7745a15e9774639e280f2aff
d77bae8cc5fe4efdbd16a384554b7829a704291f
refs/heads/master
2022-11-06T09:53:34.348555
2020-05-24T22:27:08
2020-05-24T22:27:08
273,895,805
0
0
MIT
2020-06-21T12:02:38
2020-06-21T12:02:37
null
UTF-8
Python
false
false
2,299
py
#!/usr/bin/env python3 # Copyright (c) 2019 The KuboCoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Covers the scenario of a PoS block where the coinstake input prevout is already spent. ''' from time import sleep from fake_stake.base_test import kubocoin_FakeStakeTest class PoSFakeStake(kubocoin_FakeStakeTest): def run_test(self): self.description = "Covers the scenario of a PoS block where the coinstake input prevout is already spent." self.init_test() INITAL_MINED_BLOCKS = 150 # First mined blocks (rewards collected to spend) MORE_MINED_BLOCKS = 100 # Blocks mined after spending STAKE_AMPL_ROUNDS = 2 # Rounds of stake amplification self.NUM_BLOCKS = 3 # Number of spammed blocks # 1) Starting mining blocks self.log.info("Mining %d blocks.." % INITAL_MINED_BLOCKS) self.node.generate(INITAL_MINED_BLOCKS) # 2) Collect the possible prevouts self.log.info("Collecting all unspent coins which we generated from mining...") # 3) Create 10 addresses - Do the stake amplification self.log.info("Performing the stake amplification (%d rounds)..." % STAKE_AMPL_ROUNDS) utxo_list = self.node.listunspent() address_list = [] for i in range(10): address_list.append(self.node.getnewaddress()) utxo_list = self.stake_amplification(utxo_list, STAKE_AMPL_ROUNDS, address_list) self.log.info("Done. Utxo list has %d elements." % len(utxo_list)) sleep(2) # 4) Start mining again so that spent prevouts get confirmted in a block. self.log.info("Mining %d more blocks..." % MORE_MINED_BLOCKS) self.node.generate(MORE_MINED_BLOCKS) sleep(2) # 5) Create "Fake Stake" blocks and send them self.log.info("Creating Fake stake blocks") err_msgs = self.test_spam("Main", utxo_list) if not len(err_msgs) == 0: self.log.error("result: " + " | ".join(err_msgs)) raise AssertionError("TEST FAILED") self.log.info("%s PASSED" % self.__class__.__name__) if __name__ == '__main__': PoSFakeStake().main()
[ "ultrapoolcom@gmail.com" ]
ultrapoolcom@gmail.com
d48cd1dfcd8d6ec6180938eff41489abb81ac7f5
9f1b8a1ada57198e2a06d88ddcdc0eda0c683df7
/submission - lab9/set 2/AMANDA C NAGLE_19369_assignsubmission_file_lab9/lab9/F.py
d3445accd6f6b54d58b32508c8790ff3da0e9d33
[]
no_license
sendurr/spring-grading
90dfdced6327ddfb5c311ae8f42ae1a582768b63
2cc280ee3e0fba02e95b6e9f45ad7e13bc7fad54
refs/heads/master
2020-04-15T17:42:10.781884
2016-08-29T20:38:17
2016-08-29T20:38:17
50,084,068
0
0
null
null
null
null
UTF-8
Python
false
false
203
py
from math import * class F: def __init__ (self,a,w): self.a=a self.w=w def value(self, x): return (e**(-self.a*x))*sin(self.w*x) f= F(a=1.0, w=0.1) print f.value(x=pi) f.a=2 print f.value(pi)
[ "sendurr@hotmail.com" ]
sendurr@hotmail.com
9f416affbe20c12f10bd3ac826e901fa23ecbeeb
96a34a048c783a75736bf0ec775df22142f9ee53
/packages/postgres-database/src/simcore_postgres_database/migration/versions/0208f6b32f32_adds_version_control_tables.py
d87b9322a22d297d87280f446fbcade581643aa2
[ "MIT" ]
permissive
ITISFoundation/osparc-simcore
77e5b9f7eb549c907f6ba2abb14862154cc7bb66
f4c57ffc7b494ac06a2692cb5539d3acfd3d1d63
refs/heads/master
2023-08-31T17:39:48.466163
2023-08-31T15:03:56
2023-08-31T15:03:56
118,596,920
39
29
MIT
2023-09-14T20:23:09
2018-01-23T10:48:05
Python
UTF-8
Python
false
false
6,043
py
"""Adds version control tables Revision ID: 0208f6b32f32 Revises: d10c53a5bea6 Create Date: 2021-09-06 14:19:42.599645+00:00 """ import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "0208f6b32f32" down_revision = "d10c53a5bea6" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "projects_vc_snapshots", sa.Column("checksum", sa.String(), nullable=False), sa.Column( "content", postgresql.JSONB(astext_type=sa.Text()), server_default=sa.text("'{}'::jsonb"), nullable=False, ), sa.PrimaryKeyConstraint("checksum"), ) op.create_table( "projects_vc_repos", sa.Column("id", sa.BigInteger(), nullable=False), sa.Column("project_uuid", sa.String(), nullable=False), sa.Column("project_checksum", sa.String(), nullable=True), sa.Column( "created", sa.DateTime(), server_default=sa.text("now()"), nullable=False ), sa.Column( "modified", sa.DateTime(), server_default=sa.text("now()"), nullable=False ), sa.ForeignKeyConstraint( ["project_uuid"], ["projects.uuid"], name="fk_projects_vc_repos_project_uuid", ), sa.PrimaryKeyConstraint("id"), sa.UniqueConstraint("project_uuid"), ) op.create_table( "projects_vc_commits", sa.Column("id", sa.BigInteger(), nullable=False), sa.Column("repo_id", sa.BigInteger(), nullable=False), sa.Column("parent_commit_id", sa.BigInteger(), nullable=True), sa.Column("snapshot_checksum", sa.String(), nullable=False), sa.Column("message", sa.String(), nullable=True), sa.Column( "created", sa.DateTime(), server_default=sa.text("now()"), nullable=False ), sa.ForeignKeyConstraint( ["parent_commit_id"], ["projects_vc_commits.id"], name="fk_projects_vc_commits_parent_commit_id", onupdate="CASCADE", ), sa.ForeignKeyConstraint( ["repo_id"], ["projects_vc_repos.id"], name="fk_projects_vc_commits_repo_id", ondelete="CASCADE", ), sa.ForeignKeyConstraint( ["snapshot_checksum"], ["projects_vc_snapshots.checksum"], name="fk_projects_vc_commits_snapshot_checksum", ondelete="RESTRICT", ), sa.PrimaryKeyConstraint("id"), ) op.create_table( "projects_vc_branches", sa.Column("id", sa.BigInteger(), nullable=False), sa.Column("repo_id", sa.BigInteger(), nullable=False), sa.Column("head_commit_id", sa.BigInteger(), nullable=True), sa.Column("name", sa.String(), nullable=True), sa.Column( "created", sa.DateTime(), server_default=sa.text("now()"), nullable=False ), sa.Column( "modified", sa.DateTime(), server_default=sa.text("now()"), nullable=False ), sa.ForeignKeyConstraint( ["head_commit_id"], ["projects_vc_commits.id"], name="fk_projects_vc_branches_head_commit_id", ondelete="RESTRICT", ), sa.ForeignKeyConstraint( ["repo_id"], ["projects_vc_repos.id"], name="projects_vc_branches_repo_id", ondelete="CASCADE", ), sa.PrimaryKeyConstraint("id"), sa.UniqueConstraint("name", "repo_id", name="repo_branch_uniqueness"), ) op.create_table( "projects_vc_tags", sa.Column("id", sa.BigInteger(), nullable=False), sa.Column("repo_id", sa.BigInteger(), nullable=False), sa.Column("commit_id", sa.BigInteger(), nullable=False), sa.Column("name", sa.String(), nullable=True), sa.Column("message", sa.String(), nullable=True), sa.Column("hidden", sa.Boolean(), nullable=True), sa.Column( "created", sa.DateTime(), server_default=sa.text("now()"), nullable=False ), sa.Column( "modified", sa.DateTime(), server_default=sa.text("now()"), nullable=False ), sa.ForeignKeyConstraint( ["commit_id"], ["projects_vc_commits.id"], name="fk_projects_vc_tags_commit_id", ondelete="CASCADE", ), sa.ForeignKeyConstraint( ["repo_id"], ["projects_vc_repos.id"], name="fk_projects_vc_tags_repo_id", ondelete="CASCADE", ), sa.PrimaryKeyConstraint("id"), sa.UniqueConstraint("name", "repo_id", name="repo_tag_uniqueness"), ) op.create_table( "projects_vc_heads", sa.Column("repo_id", sa.BigInteger(), nullable=False), sa.Column("head_branch_id", sa.BigInteger(), nullable=True), sa.Column( "modified", sa.DateTime(), server_default=sa.text("now()"), nullable=False ), sa.ForeignKeyConstraint( ["head_branch_id"], ["projects_vc_branches.id"], name="fk_projects_vc_heads_head_branch_id", ondelete="CASCADE", ), sa.ForeignKeyConstraint( ["repo_id"], ["projects_vc_repos.id"], name="projects_vc_branches_repo_id", ondelete="CASCADE", ), sa.PrimaryKeyConstraint("repo_id"), sa.UniqueConstraint("head_branch_id"), ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table("projects_vc_heads") op.drop_table("projects_vc_tags") op.drop_table("projects_vc_branches") op.drop_table("projects_vc_commits") op.drop_table("projects_vc_repos") op.drop_table("projects_vc_snapshots") # ### end Alembic commands ###
[ "noreply@github.com" ]
ITISFoundation.noreply@github.com
cb7273d729baf1a6dfb7f10dcb88a7cee2620eb4
bf000a932237a790770227e48a529a31d167e94e
/flash_es.py
1a7d9a6224c607194385a037b0a23d66fe7afd90
[]
no_license
o7s8r6/machineLearning
bf38b91d00def60e554384853b6f6b5640bc0929
5842dad6a1b12e0a02b3a8ecff0f610dd0fca0cb
refs/heads/master
2021-05-27T15:56:57.559788
2014-07-22T05:57:44
2014-07-22T05:57:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
635
py
import flask import rawes import json from flask import Flask query = "python" es = rawes.Elastic('localhost:9200') response = es.get('dns/nyc/_search', data={ "query":{ "bool":{ "must":[{ "wildcard":{ "answer":query }}], "must_not":[], "should":[]}}, "from":0, "size":50, "sort":[], "facets":{} }) back = response['hits']['hits'][0]['_source'].values() app = Flask(__name__) @app.route('/') def hello_world(): return back[3] if __name__ == '__main__': app.run()
[ "ohprecio@gmail.com" ]
ohprecio@gmail.com
f72c6047f22259d6bc991d05e3e8eb0bf3bc6385
677a3a76807d8585f65ec0e0839bb3a8b833e2fb
/2.Classes and Objects/Lab/Exercise/To-Do List/task.py
e16400b24b6a440e72139113289a663db3e02166
[]
no_license
negative0101/Python-OOP
0d531a1b72beb3e58f9486df88d457ecd59be10e
b5825e66a909c947a46458712d683e8a38035912
refs/heads/main
2023-07-14T11:27:34.841594
2021-08-20T08:49:04
2021-08-20T08:49:04
381,475,313
0
0
null
2021-07-25T19:52:38
2021-06-29T19:26:42
Python
UTF-8
Python
false
false
984
py
class Task: def __init__(self, name, due_date): self.name = name self.due_date = due_date self.comments = [] self.completed = False def change_name(self, new_name): if new_name == self.name: return 'Name cannot be the same.' self.name = new_name return self.name def change_due_date(self, new_date): if new_date == self.due_date: return 'Date cannot be the same.' self.due_date = new_date return self.due_date def add_comment(self, comment): self.comments.append(comment) def edit_comment(self, comment_number, new_comment): try: self.comments[comment_number] = new_comment return f'{", ".join([str(i) for i in self.comments])}' except IndexError: return f'Cannot find comment.' def details(self): return f"Name: {self.name} - Due date: {self.due_date}"
[ "noreply@github.com" ]
negative0101.noreply@github.com
26e2bb321b86356992457a81f13187c17629437e
2aace9bb170363e181eb7520e93def25f38dbe5c
/build/idea-sandbox/system/python_stubs/-57053121/ruamel_yaml/ext/_ruamel_yaml/SerializerError.py
e83d1c3946c75b93d44acb32132de12201751af3
[]
no_license
qkpqkp/PlagCheck
13cb66fd2b2caa2451690bb72a2634bdaa07f1e6
d229904674a5a6e46738179c7494488ca930045e
refs/heads/master
2023-05-28T15:06:08.723143
2021-06-09T05:36:34
2021-06-09T05:36:34
375,235,940
1
0
null
null
null
null
UTF-8
Python
false
false
605
py
# encoding: utf-8 # module ruamel_yaml.ext._ruamel_yaml # from C:\Users\Doly\Anaconda3\lib\site-packages\ruamel_yaml\ext\_ruamel_yaml.cp37-win_amd64.pyd # by generator 1.147 # no doc # imports import builtins as __builtins__ # <module 'builtins' (built-in)> import ruamel_yaml.error as __ruamel_yaml_error import ruamel_yaml.events as __ruamel_yaml_events import ruamel_yaml.nodes as __ruamel_yaml_nodes import ruamel_yaml.tokens as __ruamel_yaml_tokens class SerializerError(__ruamel_yaml_error.YAMLError): # no doc def __init__(self, *args, **kwargs): # real signature unknown pass
[ "qinkunpeng2015@163.com" ]
qinkunpeng2015@163.com
9d8f8fdd93316ade60c63318be40b169f5a7f2f8
8cf633e92a0671c8201268620a0372f250c8aeb2
/35.搜索插入位置.py
064363a1fe9b0bcd0030c245e5a0fdad177a2b06
[ "Unlicense" ]
permissive
SprintGhost/LeetCode
76da5c785009d474542e5f2cdac275675b8e60b8
cdf1a86c83f2daedf674a871c4161da7e8fad17c
refs/heads/develop
2021-06-06T04:04:28.883692
2021-01-01T14:09:26
2021-01-01T14:09:26
230,635,046
0
0
Unlicense
2020-12-11T14:55:36
2019-12-28T16:34:39
Python
UTF-8
Python
false
false
2,189
py
# # @lc app=leetcode.cn id=35 lang=python3 # # [35] 搜索插入位置 # # Accepted # 62/62 cases passed (60 ms) # Your runtime beats 78.63 % of python3 submissions # Your memory usage beats 95.67 % of python3 submissions (13.5 MB) # @lc code=start class Solution: def searchInsert(self, nums, target: int) -> int: nums_len = len(nums) if (nums_len == 0): return 0 start = 0 end = nums_len - 1 mid = nums_len // 2 while (mid <= end) and (mid > start): if (target == nums[mid]): return mid elif (target > nums[mid]): start = mid mid = (end - mid) // 2 + mid else: end = mid mid = (start + mid) // 2 if (start == 0) and (mid == start) and (target <= nums[start]): return 0 if ((end == nums_len - 1) and (target > nums[end])) and ((mid == end) or (mid == end -1)): return end + 1 return mid + 1 # A = Solution() # print (A.searchInsert([3,4,7,9,10],8)) # print (A.searchInsert([1,3,5,6],7) # Accepted # 62/62 cases passed (52 ms) # Your runtime beats 95.91 % of python3 submissions # Your memory usage beats 97.58 % of python3 submissions (13.5 MB) class Solution: def searchInsert(self, nums: List[int], target: int) -> int: # 返回大于等于 target 的索引,有可能是最后一个 size = len(nums) # 特判 if size == 0: return 0 left = 0 # 如果 target 比 nums里所有的数都大,则最后一个数的索引 + 1 就是候选值,因此,右边界应该是数组的长度 right = size # 二分的逻辑一定要写对,否则会出现死循环或者数组下标越界 while left < right: mid = left + (right - left) // 2 if nums[mid] < target: left = mid + 1 else: assert nums[mid] >= target # [1,5,7] 2 right = mid # 调试语句 # print('left = {}, right = {}, mid = {}'.format(left, right, mid)) return left # @lc code=end
[ "864047435@qq.com" ]
864047435@qq.com
5193ea9938e1348f0d38402741fadf0dcc544c3b
fbbe424559f64e9a94116a07eaaa555a01b0a7bb
/LightGBM_sklearn_scipy_numpy/source/sklearn/manifold/tests/test_mds.py
7b432dea1370e22b8590a106c29161e9b1ee7eea
[ "MIT" ]
permissive
ryfeus/lambda-packs
6544adb4dec19b8e71d75c24d8ed789b785b0369
cabf6e4f1970dc14302f87414f170de19944bac2
refs/heads/master
2022-12-07T16:18:52.475504
2022-11-29T13:35:35
2022-11-29T13:35:35
71,386,735
1,283
263
MIT
2022-11-26T05:02:14
2016-10-19T18:22:39
Python
UTF-8
Python
false
false
1,873
py
import numpy as np from numpy.testing import assert_array_almost_equal from sklearn.manifold import mds from sklearn.utils.testing import assert_raises def test_smacof(): # test metric smacof using the data of "Modern Multidimensional Scaling", # Borg & Groenen, p 154 sim = np.array([[0, 5, 3, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]]) Z = np.array([[-.266, -.539], [.451, .252], [.016, -.238], [-.200, .524]]) X, _ = mds.smacof(sim, init=Z, n_components=2, max_iter=1, n_init=1) X_true = np.array([[-1.415, -2.471], [1.633, 1.107], [.249, -.067], [-.468, 1.431]]) assert_array_almost_equal(X, X_true, decimal=3) def test_smacof_error(): # Not symmetric similarity matrix: sim = np.array([[0, 5, 9, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]]) assert_raises(ValueError, mds.smacof, sim) # Not squared similarity matrix: sim = np.array([[0, 5, 9, 4], [5, 0, 2, 2], [4, 2, 1, 0]]) assert_raises(ValueError, mds.smacof, sim) # init not None and not correct format: sim = np.array([[0, 5, 3, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]]) Z = np.array([[-.266, -.539], [.016, -.238], [-.200, .524]]) assert_raises(ValueError, mds.smacof, sim, init=Z, n_init=1) def test_MDS(): sim = np.array([[0, 5, 3, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]]) mds_clf = mds.MDS(metric=False, n_jobs=3, dissimilarity="precomputed") mds_clf.fit(sim)
[ "ryfeus@gmail.com" ]
ryfeus@gmail.com
502738773bd47c5de6fe95d9b3588481c2cd2f96
f4afb11d9d6b8f391a270fb9309285d0fa9acd1a
/push-branches.py
ec4387ca14bcce4bec8d48849b9ff6242339ef5a
[ "CC-BY-4.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Vasilov345/book
2fdf886ab1dfe7c799d3797c8ed4d0e72bc4e5fb
bed2853f0ceaf3f868832ece860d566a7b43f870
refs/heads/master
2020-08-29T13:50:17.804015
2019-10-28T09:53:28
2019-10-28T09:53:28
218,051,897
0
1
NOASSERTION
2019-10-28T13:23:42
2019-10-28T13:23:41
null
UTF-8
Python
false
false
704
py
#!/usr/bin/env python import subprocess from pathlib import Path from chapters import CHAPTERS, NO_EXERCISE for chapter in CHAPTERS: print('pushing', chapter, end=': ') subprocess.run( ['git', 'push', '--force-with-lease', 'origin', chapter], cwd=Path(__file__).parent / 'code' ) if chapter in NO_EXERCISE: continue exercise_branch = f'{chapter}_exercise' print('pushing', exercise_branch) subprocess.run( ['git', 'push', '--force-with-lease', 'origin', exercise_branch], cwd=Path(__file__).parent / 'code' ) subprocess.run( ['git', 'push', '--force-with-lease', 'origin', 'master'], cwd=Path(__file__).parent / 'code' )
[ "hjwp2@cantab.net" ]
hjwp2@cantab.net
f7afb7aabe368850e011393d0592ecf4deedc093
b7e1d227d41542bf20f92d08bb0d453058cf6d19
/orders/migrations/0004_auto_20191013_1723.py
67a3105db42b46792574796f27d8aa582c0765e5
[]
no_license
rusrom/django-ecommerce
dfa35bdb2832abf4077dd0883ec0e5e79ffa9662
aebef77713ab7c1c2118d5c190deee5ccfbd3cb9
refs/heads/master
2020-08-04T23:36:09.610480
2019-10-22T14:00:04
2019-10-22T14:00:04
212,315,359
0
0
null
null
null
null
UTF-8
Python
false
false
909
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2019-10-13 17:23 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('addresses', '0001_initial'), ('orders', '0003_auto_20191004_1111'), ] operations = [ migrations.AddField( model_name='order', name='billing_address', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='billing_address', to='addresses.Address'), ), migrations.AddField( model_name='order', name='shipping_address', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='shipping_address', to='addresses.Address'), ), ]
[ "rusrom@guyfawkes.33mail.com" ]
rusrom@guyfawkes.33mail.com
66998a2b2dbaa169192f4819c93e0ab1ea9968bf
038e6e41d117431869edad4952a5b1463d5131bc
/users/migrations/0002_auto_20210129_1642.py
db97d69b8e56b712626a94b937e9838ae9e2dd5d
[ "MIT" ]
permissive
MikaelSantilio/aprepi-django
c49290855b7c83ecaf08de82ee9eedf8e8baa15a
5e2b5ecffb287eab929c0759ea35ab073cc19d96
refs/heads/master
2023-06-19T00:18:15.986920
2021-06-15T20:15:59
2021-06-15T20:15:59
329,428,268
0
1
MIT
2021-02-05T16:21:45
2021-01-13T20:50:18
Python
UTF-8
Python
false
false
566
py
# Generated by Django 3.1.5 on 2021-01-29 19:42 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.AlterField( model_name='benefactor', name='user', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='benefactor', serialize=False, to=settings.AUTH_USER_MODEL), ), ]
[ "mikael.santilio@gmail.com" ]
mikael.santilio@gmail.com
6ab61b38006dc25fb6f347f5d1870d9bd6cbebf7
cb46ad4fedaf1dd6fad71c3ec3766604578fb340
/tests.py
22eb08230b9927699a2f32fd13466bbc6eb70b2e
[]
no_license
whitneybelba/Flask-Testing
2ae14ef04988ce3b1ee8f65bbdd20ff4a0c4a8c1
2e2e5be334f1d7a9331f63fd9a9d33aabf1b10db
refs/heads/master
2021-01-20T18:24:27.019968
2016-08-05T20:02:18
2016-08-05T20:02:18
65,045,647
0
0
null
null
null
null
UTF-8
Python
false
false
1,776
py
import unittest from party import app from model import db, example_data, connect_to_db class PartyTests(unittest.TestCase): """Tests for my party site.""" def setUp(self): self.client = app.test_client() app.config['TESTING'] = True def test_homepage(self): result = self.client.get("/") self.assertIn("board games, rainbows, and ice cream sundaes", result.data) def test_no_rsvp_yet(self): # FIXME: Add a test to show we see the RSVP form, but NOT the # party details result = self.client.get("/") self.assertNotIn("Party Details", result.data) def test_rsvp(self): result = self.client.post("/rsvp", data={"name": "Jane", "email": "jane@jane.com"}, follow_redirects=True) self.assertIn("Party Details", result.data) class PartyTestsDatabase(unittest.TestCase): """Flask tests that use the database.""" def setUp(self): """Stuff to do before every test.""" self.client = app.test_client() app.config['TESTING'] = True # Connect to test database (uncomment when testing database) # connect_to_db(app, "postgresql:///testdb") # Create tables and add sample data (uncomment when testing database) # db.create_all() # example_data() def tearDown(self): """Do at end of every test.""" # (uncomment when testing database) # db.session.close() # db.drop_all() def test_games(self): #FIXME: test that the games page displays the game from example_data() print "FIXME" if __name__ == "__main__": unittest.main()
[ "info@hackbrightacademy.com" ]
info@hackbrightacademy.com
bbf1ede6f241dd795910462f1b9f83ffd97a1947
d2189145e7be2c836017bea0d09a473bf1bc5a63
/20 Clases CBLUE (RVT)/Identificador.py
e9dd400cd7a6736317231a0f4c9e5294b27ecb62
[]
no_license
emilianoNM/Tecnicas3
12d10ce8d78803c8d2cd6a721786a68f7ee2809d
6ad7f0427ab9e23643a28ac16889bca8791421d0
refs/heads/master
2020-03-25T18:06:34.126165
2018-11-24T04:42:14
2018-11-24T04:42:14
144,013,045
3
5
null
2018-09-14T10:47:26
2018-08-08T12:49:57
Python
UTF-8
Python
false
false
249
py
# coding: utf-8 # In[ ]: #20 Clases Empresa #Por Cblue (RVT) class Identificador(object): def__init__(self,LogotipoEMP,ColorCaracteristico) self.LogotipoEMP=LogotipoEMP self.ColorCaracteristico=ColorCaracteristico
[ "noreply@github.com" ]
emilianoNM.noreply@github.com
afb52d927ca3b977196758f7985e91c241b07721
2e74c7339c63385172629eaa84680a85a4731ee9
/sdg/data_prep/compileNTDs.py
26c89bfdf2636badf5e8fa2d616af8f4faa2ea46
[]
no_license
zhusui/ihme-modeling
04545182d0359adacd22984cb11c584c86e889c2
dfd2fe2a23bd4a0799b49881cb9785f5c0512db3
refs/heads/master
2021-01-20T12:30:52.254363
2016-10-11T00:33:36
2016-10-11T00:33:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,898
py
import pandas as pd import sys from scipy.stats import gmean from getpass import getuser sys.path.append(SDG_REPO) import sdg_utils.draw_files as dw INDICATOR_ID_COLS = ['location_id', 'year_id'] def compile_df_using_dict(input_file_dict): """Compile dataframe together using dictionary indicator_id-->file""" dfs = [] for indicator_id in input_file_dict.keys(): print indicator_id df = pd.read_hdf(input_file_dict[indicator_id]) df = df[INDICATOR_ID_COLS + dw.DRAW_COLS] dfs.append(df) df = pd.concat(dfs, ignore_index=True) return df def get_child_indicators(indic_table, parent_stamp): """Use indicator table filepaths to pull ntd data""" tbl_rows = indic_table.ix[ (indic_table['indicator_stamp'].str.startswith(parent_stamp)) & \ (indic_table['indicator_level']==3) ] input_file_dict = tbl_rows[ ['indicator_id', 'clean_input_data_file'] ].set_index('indicator_id').to_dict()['clean_input_data_file'] df = compile_df_using_dict(input_file_dict) return df def compile_sum(indic_table, parent_stamp, assert_0_1=False): """Sum together the children of the given parent. Optionally assert that values are between 0 and 1. """ df = get_child_indicators(indic_table, parent_stamp) df = df.groupby(INDICATOR_ID_COLS)[dw.DRAW_COLS].sum() if assert_0_1: assert df.applymap(lambda x: x>0 and x<1).values.all(), \ 'sum produced rates outside of realistic bounds' df = df.reset_index() return df def compile_ncds(indic_table): """Compile together aggregate indicators for NTDs and NCDs""" print 'NCDS' ncds = compile_sum(indic_table, 'i_341', assert_0_1=True) out_path = "/ihme/scratch/projects/sdg/input_data/dalynator/{}/ncds.h5".format(dw.DALY_VERS) ncds.to_hdf(out_path, key="data", format="table", data_columns=['location_id', 'year_id']) def compile_ntds(indic_table): print 'NTDs' ntds = compile_sum(indic_table, 'i_335', assert_0_1=False) # cant assert that prevalence is below 1 because it might be above assert (ntds[dw.DRAW_COLS] > 0).values.all(), 'values below 0 in ntds' out_path = "/ihme/scratch/projects/sdg/input_data/como_prev/{}/ntds.h5".format(dw.COMO_VERS) ntds.to_hdf(out_path, key="data", format="table", data_columns=['location_id', 'year_id']) def compile_tb(indic_table): print 'TB' tb = compile_sum(indic_table, 'i_332') out_path = "/ihme/scratch/projects/sdg/input_data/como_inc/{}/tb.h5".format(dw.COMO_VERS) tb.to_hdf(out_path, key="data", format="table", data_columns=['location_id', 'year_id']) indic_table = pd.read_csv( "/home/j/WORK/10_gbd/04_journals/" "gbd2015_capstone_lancet_SDG/02_inputs/indicator_ids.csv" ) compile_ntds(indic_table) compile_tb(indic_table)
[ "nsidles@uw.edu" ]
nsidles@uw.edu
c187f26acf02adbbc468f5bf96a6b6af692a8d02
a1c6caa9ff52d4377529c7727eb5517041b04311
/Exe16_Loja_de_tinta.py
adb1f3b81505e3857f7a47487058062e967cf7f7
[ "MIT" ]
permissive
lucaslk122/Exercicios-em-python
b83b5abd5da7a7cf15ac50a213bad708501c8863
2daa92dcb19296f580d673376af375d11c9c041b
refs/heads/main
2022-12-26T04:22:40.365925
2020-10-09T18:05:31
2020-10-09T18:05:31
302,362,419
0
0
null
null
null
null
UTF-8
Python
false
false
398
py
import math print("1L de tinta pinta 3 metros quadrados, cada galão possui 18L e custam R$80.00 cada") Area = float(input("Digite o tamanho da area em metros quadrados a ser pintada: ")) Litros = float(Area/3) Latas = float(Litros/18) Preço = float(round(Latas,0)*80) print(f"Voce vai precisar de {math.ceil(Latas)} lata de tinta para pintar {Area}m^2, portanto, pagará R${round(Preço,2)}")
[ "71664028+lucaslk122@users.noreply.github.com" ]
71664028+lucaslk122@users.noreply.github.com
6508bfa49a20c5e33ddd9d77cb81eb6289502300
c8a131d6f9d58f54a8736cae939529741b3858f8
/mysite/blog/models.py
8685f23c28416b661749aa9d952e46b42f882ddd
[]
no_license
aliensmart/simple_web
0e5d7fd1205bfed3145cce45dbcf374a9e63f7bc
9b948de933ff5304f92ca80d5c556507f3000095
refs/heads/master
2022-06-28T17:28:33.325312
2020-05-10T13:28:47
2020-05-10T13:28:47
261,683,101
0
0
null
null
null
null
UTF-8
Python
false
false
1,278
py
from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now self.save() def approve_comments(self): return self.comments.filter(approve_comment=True) def get_absolute_url(self): return reverse("post_detail", kwargs={'pk':self.pk}) def __str__(self): return self.title class Comment(models.Model): port = models.ForeignKey('blog.Post', related_name='comments', on_delete=models.CASCADE) author = models.CharField(max_length=200) text = models.TextField() create_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default = False) def approve(self): self.approved_comment = True self.save() def get_absolute_url(self): return reverse('post_list') def __str__(self): return self.text
[ "kaoua17@gmail.com" ]
kaoua17@gmail.com
e3282eb1cfcf9fe7aac2622513c0d4ec3a83ef22
ff23e5c890216a1a63278ecb40cd7ac79ab7a4cd
/clients/hydra/python/test/test_is_ready200_response.py
703e166a1c68f6cddf8085ea803a197d52a0a45b
[ "Apache-2.0" ]
permissive
ory/sdk
fcc212166a92de9d27b2dc8ff587dcd6919e53a0
7184e13464948d68964f9b605834e56e402ec78a
refs/heads/master
2023-09-01T10:04:39.547228
2023-08-31T08:46:23
2023-08-31T08:46:23
230,928,630
130
85
Apache-2.0
2023-08-14T11:09:31
2019-12-30T14:21:17
C#
UTF-8
Python
false
false
785
py
""" Ory Hydra API Documentation for all of Ory Hydra's APIs. # noqa: E501 The version of the OpenAPI document: v2.2.0-rc.3 Contact: hi@ory.sh Generated by: https://openapi-generator.tech """ import sys import unittest import ory_hydra_client from ory_hydra_client.model.is_ready200_response import IsReady200Response class TestIsReady200Response(unittest.TestCase): """IsReady200Response unit test stubs""" def setUp(self): pass def tearDown(self): pass def testIsReady200Response(self): """Test IsReady200Response""" # FIXME: construct object with mandatory attributes with example values # model = IsReady200Response() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "3372410+aeneasr@users.noreply.github.com" ]
3372410+aeneasr@users.noreply.github.com
11cbf11fd837f408935a4f30b359536ebafaf26d
d7249238cf7c42ec7ee4dd8dfa7c1ba80b0d93d6
/01_sklearn/02_weight_height_test.py
9d612682a720ea8065bdf9a44692f105330ce222
[]
no_license
happyquokkka/TIL_AI
eb47e9e419d7344e8a5fac27dc00ccaf16962368
4d13716867dfd9d938f866f769a74ea03b93c88a
refs/heads/master
2023-07-18T14:24:45.290908
2021-08-27T13:34:44
2021-08-27T13:34:44
399,787,222
0
0
null
null
null
null
UTF-8
Python
false
false
2,053
py
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt # pip install pandas # 공공데이터포털 -> '교육부 학생건강검사 결과분석' rawdata 서울 2015 다운로드 -> weight_height 로 파일명 변경 # 문제상황 : 여학생의 몸무게를 입력하면, 키를 예측하고 싶다. # 데이터 준비 pd.set_option("display.width", 300) pd.set_option("display.max_rows",1000) pd.set_option("display.max_columns",30) df = pd.read_csv("weight_height.csv", encoding="euc-kr") df = df[['학교명', '학년', '성별', '키', '몸무게']] df.dropna(inplace=True) # 학년 표기 변경 : 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 로 변경 df['grade'] = list(map(lambda x:0 if x[-4:] == "초등학교" else (6 if x[-3:] == "중학교" else 9), df["학교명"])) + df["학년"] # 얘는 왜 list로 변환하는거지? df["학년"] list와 더하려고? df.drop(["학교명", "학년"], axis="columns", inplace=True) # 컬럼명 변경 df.columns = ["gender", "height", "weight", "grade"] # df['gender'] 의 값을, 남 -> 0, 여 -> 1로 변환 df['gender'] = df['gender'].map(lambda x:0 if x=="남" else 1) # print(df) # 여자인 df만 분리 is_girl = df["gender"] == 1 girl_df = df[is_girl] # print(girl_df) # 데이터 분할 X = girl_df['weight'] y = girl_df['height'] # train / test set 분리 train_X, test_X, train_y, test_y = train_test_split(X, y, test_size=0.3, random_state=1) # 2차원 데이터로 가공 train_X = train_X.values.reshape(-1, 1) test_X = test_X.values.reshape(-1, 1) # 모델 준비 (선형회귀분석모델) linear = LinearRegression() # 학습 linear.fit(train_X, train_y) # 예측 및 평가 predict = linear.predict(test_X) # 그래프 그리기 plt.plot(test_X, test_y, "b.") plt.plot(test_X, predict, "r.") plt.xlim(10, 140) plt.ylim(100, 220) plt.grid() # plt.show() # 몸무게가 50kg인 사람의 키는? pred_grd = linear.predict([[60]]) print("여학생 키 예측 :", pred_grd)
[ "yjmooon96@gmail.com" ]
yjmooon96@gmail.com
cc5830bd8d5626e4aad789d1ad95107800ba6894
a177699f24936458b9fe9eb73d9af51668601d20
/src/zojax/subscription/subscription.py
0c39a99d0d13a4ec928e717e197664cdebc47436
[ "ZPL-2.1" ]
permissive
Zojax/zojax.subscription
868dfbcc07f0abcc3f0e92ebf8051de0a544bfba
f72fa6cf7ad885519d4da23dc5cd5b6b1ae0d92c
refs/heads/master
2020-05-17T03:36:52.743843
2014-01-31T11:06:15
2014-01-31T11:06:15
2,018,696
0
0
null
null
null
null
UTF-8
Python
false
false
1,665
py
############################################################################## # # Copyright (c) 2009 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """ $Id$ """ from persistent import Persistent from zope import interface from zope.component import getUtility, queryUtility from zope.security.management import queryInteraction from zope.app.intid.interfaces import IIntIds from interfaces import ISubscription, ISubscriptionDescription class Subscription(Persistent): interface.implements(ISubscription) id = None oid = 0 principal = u'' type = u'' def __init__(self, principal=None, **kw): if principal is None: interaction = queryInteraction() if interaction is not None: for participation in interaction.participations: principal = participation.principal.id self.principal = principal for attr, value in kw.items(): setattr(self, attr, value) @property def object(self): return getUtility(IIntIds).queryObject(self.oid) @property def description(self): return getUtility(ISubscriptionDescription, self.type)
[ "andrey.fedoseev@gmail.com" ]
andrey.fedoseev@gmail.com
754a9e6ac4ad159d561e3bc49223a97c83cfe3d5
5b04b47b9498890ef95fa6e78fe7135c570a3f43
/try_tables.py
01c7612337c5cd00e0169b6d9038e2becabec074
[]
no_license
donboyd5/puf_analysis_frozen
8ca3ea7e899a7db60fe7b3ed681cbd80ef0f59e8
3aa2b1cb680aad16987ed776bcfdc878418e7a64
refs/heads/main
2023-04-12T12:55:48.495699
2020-12-16T09:48:39
2020-12-16T09:48:39
361,897,853
0
0
null
null
null
null
UTF-8
Python
false
false
1,398
py
# -*- coding: utf-8 -*- """ Created on Fri Oct 23 03:14:39 2020 @author: donbo """ # %% notes # https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html # https://pbpython.com/styling-pandas.html # https://mkaz.blog/code/python-string-format-cookbook/ # https://www.youtube.com/watch?v=Sj42rqym9lk # https://mode.com/example-gallery/python_dataframe_styling/ # https://github.com/spyder-ide/spyder-notebook # https://groups.google.com/g/spyderlib # https://plotly.com/python/table/ # https://mode.com/example-gallery/python_dataframe_styling/ # %% imports import pandas as pd import plotly.graph_objects as go import matplotlib # %% check 1 df = pd.DataFrame([[3,2,10,4],[20,1,3,2],[5,4,6,1]]) df.style.background_gradient() pathfn = r'c:\temp\fn.html' # x create and write to new file # w for writing, overwrite existing # a for appending # note that directory must exist f = open(pathfn, mode='a') f.write(df.style.background_gradient().render()) f.close() # %% data df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_usa_states.csv') fig = go.Figure(data=[go.Table( header=dict(values=list(df.columns), fill_color='paleturquoise', align='left'), cells=dict(values=[df.Rank, df.State, df.Postal, df.Population], fill_color='lavender', align='left')) ]) fig.show()
[ "donboyd5@gmail.com" ]
donboyd5@gmail.com
2168445a69fd58027a1d22b32431a5f3569f52c3
1c39d98a7f4be6939bcbacbf3b4f7d9610bf2ea9
/0.Basis/0.pythonbook/25.RegularExpressions.py
c8cad87c86ebaf715bf911029b2cde0a21867e3e
[]
no_license
vlong638/VL.Python
03ae0da96164d9cd2de521faea2cb86e68152bc8
06499fa1f7f7e4b4ae9f9e470c04f78bce86a7b1
refs/heads/master
2021-01-13T11:01:29.137801
2016-11-04T05:47:09
2016-11-04T05:47:09
69,540,586
0
0
null
null
null
null
UTF-8
Python
false
false
7,928
py
import PrintHelper PrintHelper.PrintTitle('Regular Expressions With Python') print('适用于数据挖掘,数据处理,抓取网页数据,大量的数据集合的模式化匹配') print('正则表达式是字符串的模式化匹配,本章介绍如何使用正则表达式进行匹配') PrintHelper.PrintSubtitle('The re Module') PrintHelper.PrintHint('re,正则表达式模块') PrintHelper.PrintHint('@pattern=re.compile(r@pattenString)','编译pattern') PrintHelper.PrintHint('@pattern.findall(@stringForMatch)','使用pattern对象进行字符串匹配') PrintHelper.PrintCode('import re') PrintHelper.PrintCode('pAplus = re.compile( r\"a+\" )') PrintHelper.PrintCode('lAplus = pAplus.findall( \"aardvark\" )') PrintHelper.PrintCode('print( lAplus )') import re pAplus = re.compile( r"a+" ) lAplus = pAplus.findall( "aardvark" ) print( lAplus ) PrintHelper.PrintSubtitle('Shorthand,简写') PrintHelper.PrintHint('re.findall(r@patternString,@stringForMatch)','直接使用patternString进行字符串匹配') PrintHelper.PrintSubtitle('Match Objects') print('当你需要更多的匹配信息的时候,re模块提供了一种称为MatchObjects的对象类型') print('这种对象包含了更多的关于匹配的信息') PrintHelper.PrintHint('@match=re.search(r@patternString,@stringForMatch)') PrintHelper.PrintHint('@match.group()','匹配的内容') PrintHelper.PrintHint('@match.start()','匹配的起始位置') PrintHelper.PrintHint('@match.end()','匹配的结束位置') PrintHelper.PrintCode('m = re.search( r\"a+\", \"Look out for the aardvark!\" )') PrintHelper.PrintCode('print( \"{} is found at index {}\".format( m.group(), m.start() ) )') m = re.search( r"a+", "Look out for the aardvark!" ) print( "{} is found at index {}".format( m.group(), m.start() ) ) PrintHelper.PrintSubtitle('Lists Of Matches',"多项匹配结果") PrintHelper.PrintCode('import re') PrintHelper.PrintCode('mlist = re.finditer( r\"a+\", \"Look out! A dangerous aardvark is on the loose!\" )') PrintHelper.PrintCode('for m in mlist:') PrintHelper.PrintCode(' print( \"{} is found at index {} and ends at index {}.\".format( m.group(), m.start(), m.end())) ') import re mlist = re.finditer( r"a+", "Look out! A dangerous aardvark is on the loose!" ) for m in mlist: print( "{} is found at index {} and ends at index {}.".format( m.group(), m.start(), m.end())) PrintHelper.PrintTitle('Writing Regular Expressions') PrintHelper.PrintSubtitle('Regular Expressions With Square Brackets') PrintHelper.PrintCode('import re') PrintHelper.PrintCode('slist = re.findall( r\"b[aeiou]ll\", \"Bill Gates and Uwe Boll \\ drank Red Bull at a football match in Campbell.\" )') PrintHelper.PrintCode('print( slist )') import re slist = re.findall( r"b[aeiou]ll", "Bill Gates and Uwe Boll \ drank Red Bull at a football match in Campbell." ) print( slist ) PrintHelper.PrintSubtitle('Special Sequences,特殊序列标记') PrintHelper.PrintSampleWithDescription('\\b','word boundary,单词边界') PrintHelper.PrintSampleWithDescription('\\B','not a word boundary,非单次边界') PrintHelper.PrintSampleWithDescription('\\d','digit,数字') PrintHelper.PrintSampleWithDescription('\\D','not a digit,非数字') PrintHelper.PrintSampleWithDescription('\\n','newline,换行') PrintHelper.PrintSampleWithDescription('\\r','carriage return,回车') PrintHelper.PrintSampleWithDescription('\\s','whitespace,空格') PrintHelper.PrintSampleWithDescription('\\S','not a whitespace,非空格') PrintHelper.PrintSampleWithDescription('\\t','tabulation,缩进') PrintHelper.PrintSampleWithDescription('\\w','alphanumeric character,数字+字母') PrintHelper.PrintSampleWithDescription('\\W','not an alphanumeric character,非数字和字母') PrintHelper.PrintSampleWithDescription('\\/','forward slash,斜杠,左下斜杠') PrintHelper.PrintSampleWithDescription('\\\\','backslash,反斜杠,右下反斜杠') PrintHelper.PrintSampleWithDescription('\\\"','double quote,双眼号') PrintHelper.PrintSampleWithDescription('\\\'','single quote,单眼号') PrintHelper.PrintSampleWithDescription('-','start of a string,字符串头') PrintHelper.PrintSampleWithDescription('$','end of a string,字符串尾') PrintHelper.PrintSampleWithDescription('.','any character,任意字符') PrintHelper.PrintSubtitle('Repetition,重复标记') PrintHelper.PrintSampleWithDescription('*','zero or more,0次或更多') PrintHelper.PrintSampleWithDescription('+','one or more,至少一次') PrintHelper.PrintSampleWithDescription('?','zero or one,可能出现一次') PrintHelper.PrintSampleWithDescription('{n,m}','at least n and at most m,至少n次,最多m次') PrintHelper.PrintSampleWithDescription('{n,}','at least n,至少n次') PrintHelper.PrintSampleWithDescription('{n}','exactly n,正好n次') PrintHelper.PrintTitle('Grouping,匹配分组') PrintHelper.PrintCode('import re') PrintHelper.PrintCode('pDate = re.compile( r\"(\\d{1,2})-(\\d{1,2})-(\\d{4})\" )') PrintHelper.PrintCode('m = pDate.search( \"In response to your letter of 25-3-2015, \\ I decided to hire a hitman to get you.\" )') PrintHelper.PrintCode('if m:') PrintHelper.PrintCode(' print( \"Date {}; day {}; month {}; year {}\"') PrintHelper.PrintCode(' .format( m.group(0), m.group(1), m.group(2), m.group(3) ) )') import re pDate = re.compile( r"(\d{1,2})-(\d{1,2})-(\d{4})" ) m = pDate.search( "In response to your letter of 25-3-2015, \ I decided to hire a hitman to get you." ) if m: print( "Date {}; day {}; month {}; year {}" .format( m.group(0), m.group(1), m.group(2), m.group(3) ) ) PrintHelper.PrintSubtitle('findall() and Groups') PrintHelper.PrintHint('findall(@stringForMatch)') PrintHelper.PrintCode('import re') PrintHelper.PrintCode('pDate = re.compile( r\"(\\d{1,2})-(\\d{1,2})-(\\d{4})\" )') PrintHelper.PrintCode('datelist = pDate.findall( \"In response to your letter of \\ 25-3-2015, on 27-3-2015 I decided to hire a hitman to get you.\" )') PrintHelper.PrintCode('for date in datelist:') PrintHelper.PrintCode(' print( date )') import re pDate = re.compile( r"(\d{1,2})-(\d{1,2})-(\d{4})" ) datelist = pDate.findall( "In response to your letter of \ 25-3-2015, on 27-3-2015 I decided to hire a hitman to get you." ) for date in datelist: print( date ) PrintHelper.PrintSubtitle('Named Groups,组命名') PrintHelper.PrintHint('(?P<@name>...)') PrintHelper.PrintCode('pDate = re.compile( r\"(?P<day>\\d{1,2})-(?P<month>\\d{1,2})-(?P<year>\\d{4})\")') PrintHelper.PrintCode('m = pDate.search( \"In response to your letter of 25-3-2015, \\ I curse you.\" )') PrintHelper.PrintCode('if m:') PrintHelper.PrintCode(' print( \"day is {}\".format( m.group( \'day\') ) )') PrintHelper.PrintCode(' print( \"month is {}\".format( m.group( \'month\') ) )') PrintHelper.PrintCode(' print( \"year is {}\".format( m.group( \'year\') ) )') pDate = re.compile( r"(?P<day>\d{1,2})-(?P<month>\d{1,2})-(?P<year>\d{4})") m = pDate.search( "In response to your letter of 25-3-2015, \ I curse you." ) if m: print( "day is {}".format( m.group( 'day') ) ) print( "month is {}".format( m.group( 'month') ) ) print( "year is {}".format( m.group( 'year') ) ) PrintHelper.PrintSubtitle('Referring Within A Regular Expression,匹配内引用') PrintHelper.PrintHint('\\n,如(\\S).*\\1指代任意非空格的字符,且重复两次,\\1指第一个匹配项') PrintHelper.PrintTitle('Replacing,替换') print('正则通常用以匹配内容,当然你也可以使用正则进行替换处理') PrintHelper.PrintHint('re.sub(r@pattern,@replace,@stringForMatch)') PrintHelper.PrintCode('import re') PrintHelper.PrintCode('s = re.sub( r\"([iy])se\", \"\\g<1>ze\", \"Whether you categorise, \\ emphasise, or analyse, you should use American spelling!\" )') PrintHelper.PrintCode('print( s )') import re s = re.sub( r"([iy])se", "\g<1>ze", "Whether you categorise, \ emphasise, or analyse, you should use American spelling!" ) print( s ) print()
[ "vlong638@163.com" ]
vlong638@163.com
2ee3baa013cf6894c49b26fbbcd9f1e7e01a7640
6ff51e18e843e07fb9a08f299d6cd90c17ec54f0
/softwares/base16/output/prompt-toolkit/base16/base16-codeschool.py
979d22ad9c27e68a5a3835d2c224fab69e871df6
[]
no_license
xzdandy/Configs
79258716f658a38dbcf6483acd206b747d445fe2
cc6f32462f49998fac69327ec6983de8067352ae
refs/heads/master
2022-05-05T14:32:16.011938
2022-03-31T23:03:07
2022-03-31T23:03:07
173,981,390
0
0
null
null
null
null
UTF-8
Python
false
false
2,365
py
# -*- coding: utf-8 -*- # base16-prompt-toolkit (https://github.com/memeplex/base16-prompt-toolkit) # Base16 Prompt Toolkit template by Carlos Pita (carlosjosepita@gmail.com # Codeschool scheme by blockloop from prompt_toolkit.terminal.vt100_output import _256_colors from pygments.style import Style from pygments.token import (Keyword, Name, Comment, String, Error, Text, Number, Operator, Literal, Token) # See http://chriskempson.com/projects/base16/ for a description of the role # of the different colors in the base16 palette. base00 = '#232c31' base01 = '#1c3657' base02 = '#2a343a' base03 = '#3f4944' base04 = '#84898c' base05 = '#9ea7a6' base06 = '#a7cfa3' base07 = '#b5d8f6' base08 = '#2a5491' base09 = '#43820d' base0A = '#a03b1e' base0B = '#237986' base0C = '#b02f30' base0D = '#484d79' base0E = '#c59820' base0F = '#c98344' # See https://github.com/jonathanslenders/python-prompt-toolkit/issues/355 colors = (globals()['base0' + d] for d in '08BADEC5379F1246') for i, color in enumerate(colors): r, g, b = int(color[1:3], 16), int(color[3:5], 16), int(color[5:], 16) _256_colors[r, g, b] = i + 6 if i > 8 else i # See http://pygments.org/docs/tokens/ for a description of the different # pygments tokens. class Base16Style(Style): background_color = base00 highlight_color = base02 default_style = base05 styles = { Text: base05, Error: '%s bold' % base08, Comment: base03, Keyword: base0E, Keyword.Constant: base09, Keyword.Namespace: base0D, Name.Builtin: base0D, Name.Function: base0D, Name.Class: base0D, Name.Decorator: base0E, Name.Exception: base08, Number: base09, Operator: base0E, Literal: base0B, String: base0B } # See https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/styles/defaults.py # for a description of prompt_toolkit related pseudo-tokens. overrides = { Token.Prompt: base0B, Token.PromptNum: '%s bold' % base0B, Token.OutPrompt: base08, Token.OutPromptNum: '%s bold' % base08, Token.Menu.Completions.Completion: 'bg:%s %s' % (base01, base04), Token.Menu.Completions.Completion.Current: 'bg:%s %s' % (base04, base01), Token.MatchingBracket.Other: 'bg:%s %s' % (base03, base00) }
[ "xzdandy@gmail.com" ]
xzdandy@gmail.com
5b7e1f7fad59a55adecd2e085f93e88b7e02d4c3
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2653/60698/274540.py
b57d02b4c40b0bf4962611a78c22b05da38bef51
[]
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
281
py
def test(): t = int(input()) for _ in range(0, t): nx=input().split() n=int(nx[0]) x=int(nx[1]) if x>=10: print(0) return else: time=10-x num=n-1 print (num*time) test()
[ "1069583789@qq.com" ]
1069583789@qq.com
fc414bd6e874eb9170259bd11f5421cd9647564f
393a9ce7e465d211f99926afbc20f8e72fa6ce4d
/venv/bin/pip3
114101786a2c6dd465e49a127d0fda760e887e51
[]
no_license
GarrettMatthews/Artemia
210079f50c94c09c732c25efc6554b009e339856
008f8c46abdf5dbf270b057a820665e796d4a213
refs/heads/master
2020-07-29T05:29:45.979474
2019-12-10T17:52:38
2019-12-10T17:52:38
209,684,936
0
0
null
null
null
null
UTF-8
Python
false
false
413
#!/home/garrett/Desktop/Git_Repositories/Artemia/venv/bin/python # EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip3' __requires__ = 'pip==19.0.3' 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==19.0.3', 'console_scripts', 'pip3')() )
[ "garrettemathews@gmail.com" ]
garrettemathews@gmail.com
cc1186b87d73c60fd1286cb040e3c7be0884f0c9
7b9f0f9be9d7422546c300b0d4dead3b10fb7ee7
/ariaml/createInput.py
df341539f8702167c06251b98a295bc65b24a1fa
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0" ]
permissive
aria-jpl/ariamh
73f163f0c80da949f6ea88469fd2c67ab229ef20
b6a06330cb5a592022070724b34eb6a011e7cbdc
refs/heads/develop
2022-12-26T13:45:29.287226
2022-02-10T05:08:43
2022-02-10T05:08:43
124,922,867
6
7
Apache-2.0
2022-12-13T13:53:45
2018-03-12T17:02:52
Python
UTF-8
Python
false
false
330
py
#!/usr/bin/env python import sys, json def write_input(ctx_file, in_file): with open(ctx_file) as f: j = json.load(f) input = { "url": j['rule_hit']['_source']['urls'][0] } with open(in_file, 'w') as f: json.dump(input, f, indent=2) if __name__ == "__main__": write_input(sys.argv[1], sys.argv[2])
[ "pymonger@gmail.com" ]
pymonger@gmail.com
ea5bb42024088a52e5faddafce1ae405b2c755af
c6d389f085c683f33cc0d0ab6497b3f042f7c905
/distanceBetweenPointAndSegment.py
ed8315fdfa93c2689eee34f35a3b9d99e47aff07
[]
no_license
irhadSaric/computer-geometry
0d23fbafbedb18b22df30cc8071f4103237eef2d
25a73c756472896c316d685ca6792c8c94f31361
refs/heads/master
2020-04-04T08:01:38.501815
2019-02-26T20:05:08
2019-02-26T20:05:08
155,768,457
0
0
null
2019-02-26T20:10:33
2018-11-01T19:56:17
Python
UTF-8
Python
false
false
635
py
from math import sqrt def distancePtoS(point, segment): x = point[0] y = point[1] x1 = segment[0][0] y1 = segment[0][1] x2 = segment[1][0] y2 = segment[1][1] A = x - x1 B = y - y1 C = x2 - x1 D = y2 - y1 dot = A * C + B * D len_sq = C * C + D * D param = -1 if (len_sq != 0): #// in case of 0 length line param = dot / len_sq if (param < 0): xx = x1 yy = y1 elif param > 1: xx = x2 yy = y2 else: xx = x1 + param * C yy = y1 + param * D dx = x - xx dy = y - yy return sqrt(dx * dx + dy * dy)
[ "irhad.saric@hotmail.com" ]
irhad.saric@hotmail.com
205750ec03969e29011a40ca0bb85064d668571e
678e374616008bd3d72e2c399ece7e219601bebc
/src/billing/models.py
fd28f1b45c723ff87727da6e38eda558ca08bff0
[ "MIT" ]
permissive
LABETE/srvup_and_drf
74d454f7fc2aa1f7869b2a40f15f18cfdecc9835
e6b09ce8f8b01bbcbdce291efbbba16c2837b38f
refs/heads/master
2016-08-12T19:04:05.411849
2016-01-26T17:16:26
2016-01-26T17:16:26
50,445,171
0
0
null
null
null
null
UTF-8
Python
false
false
3,892
py
import datetime import random from django.conf import settings from django.contrib.auth.signals import user_logged_in from django.db import models from django.db.models.signals import post_save from django.utils import timezone from .signals import membership_dates_update from .utils import update_braintree_membership def user_logged_in_receiver(sender, user, **kwargs): update_braintree_membership(user) user_logged_in.connect(user_logged_in_receiver) class UserMerchantId(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) customer_id = models.CharField(max_length=120) subscription_id = models.CharField(max_length=120, null=True, blank=True) plan_id = models.CharField(max_length=120, null=True, blank=True) merchant_name = models.CharField(max_length=120, default="Braintree") def __str__(self): return self.customer_id class Membership(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) start_date = models.DateTimeField(default=timezone.now) end_date = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.user.username) def update_status(self): if self.end_date >= timezone.now() and not self.user.is_member: self.user.is_member = True self.user.save() elif self.end_date <= timezone.now() and self.user.is_member: self.user.is_member = False self.user.save() def update_membership_status(sender, instance, created, *args, **kwargs): if not created: instance.update_status() post_save.connect(update_membership_status, sender=Membership) def update_membership_dates(sender, new_start_date, **kwargs): membership = sender current_end_date = membership.end_date if current_end_date >= new_start_date: membership.end_date = current_end_date + \ datetime.timedelta(days=30, hours=10) membership.save() else: membership.start_date = new_start_date membership.end_date = new_start_date + \ datetime.timedelta(days=30, hours=10) membership.save() membership_dates_update.connect(update_membership_dates) class TransactionManager(models.Manager): def create_new(self, user, transaction_id, amount, card_type, success=None, last_four=None, transaction_status=None): if not user: raise ValueError("Must be a user.") if not transaction_id: raise ValueError("Must complete a transaction to add new.") new_order_id = "{0}{1}{2}".format( transaction_id[:2], random.randint(1, 9), transaction_id[2:]) new_trans = self.model( user=user, transaction_id=transaction_id, amount=amount, order_id=new_order_id, card_type=card_type ) if success: new_trans.success = success if last_four: new_trans.last_four = last_four if transaction_status: new_trans.transaction_status = transaction_status new_trans.save(using=self._db) return new_trans class Transaction(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) transaction_id = models.CharField(max_length=120) order_id = models.CharField(max_length=120) amount = models.DecimalField(max_digits=100, decimal_places=2) success = models.BooleanField(default=True) transaction_status = models.CharField( max_length=220, null=True, blank=True) card_type = models.CharField(max_length=120) last_four = models.PositiveIntegerField(null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) objects = TransactionManager() class Meta: ordering = ["-timestamp"] def __str__(self): return self.order_id
[ "eddie.valv@gmail.com" ]
eddie.valv@gmail.com
4e87a4a33512bdf4d49b79da2a44373a7c62dab8
e8bf00dba3e81081adb37f53a0192bb0ea2ca309
/domains/nav/problems/training/problem1032_SD.py
bce3f354d7fa46d2c39311b6b2bf4b2ab138740f
[ "BSD-3-Clause" ]
permissive
patras91/rae_release
1e6585ee34fe7dbb117b084df982ca8a8aed6795
0e5faffb7eb732fdb8e3bbf2c6d2f2cbd520aa30
refs/heads/master
2023-07-13T20:09:41.762982
2021-08-11T17:02:58
2021-08-11T17:02:58
394,797,515
2
1
null
null
null
null
UTF-8
Python
false
false
1,203
py
__author__ = 'patras' from domain_springDoor import * from timer import DURATION from state import state, rv DURATION.TIME = { 'unlatch1': 5, 'unlatch2': 5, 'holdDoor': 2, 'passDoor': 3, 'releaseDoor': 2, 'closeDoors': 3, 'move': 7, 'take': 2, 'put': 2, } DURATION.COUNTER = { 'unlatch1': 5, 'unlatch2': 5, 'holdDoor': 2, 'passDoor': 3, 'releaseDoor': 2, 'closeDoors': 3, 'move': 7, 'take': 2, 'put': 2, } rv.LOCATIONS = [1, 2, 3, 4, 5, 6] rv.EDGES = {1: [4], 2: [5], 3: [6], 4: [1, 5], 5: [2, 4, 6], 6: [3, 5]} rv.DOORS = ['d1', 'd2', 'd3'] rv.DOORLOCATIONS = {(1, 4): 'd3', (2, 5): 'd2', (3, 6): 'd1'} rv.DOORTYPES = {'d1': 'ordinary', 'd2': 'spring', 'd3': 'spring'} rv.ROBOTS = ['r1', 'r2', 'r3'] def ResetState(): state.load = {'r1': NIL, 'r2': NIL, 'r3': NIL} state.status = {'r1': 'free', 'r2': 'free', 'r3': 'free'} state.loc = {'r1': 1, 'r2': 5, 'r3': 3} state.pos = {'o1': 3} state.doorStatus = {'d1': 'closed', 'd2': 'closed', 'd3': 'closed', } state.doorType = {'d1': UNK, 'd2': UNK, 'd3': UNK, } tasks = { 5: [['fetch', 'r1', 'o1', 3]], 9: [['collision', 'r1']], } eventsEnv = { }
[ "patras@umd.edu" ]
patras@umd.edu
14b61fbbc57d056ce76adcf743c6de1c24e1669e
ca27df9a42fdba2fb9c42ced68b1b3e734e0fb76
/src/modu/editable/datatypes/boolean.py
b695dbf72fee4b17b8ff56ca82ed177cbfd26c68
[ "MIT" ]
permissive
philchristensen/modu
1696ecf36908367b0358b06c3bee02552fc76651
795f3bc413956b98522ac514dafe35cbab0d57a3
refs/heads/master
2016-09-06T10:54:59.286492
2015-03-29T21:22:47
2015-03-29T21:22:47
829,469
0
0
null
null
null
null
UTF-8
Python
false
false
3,285
py
# modu # Copyright (c) 2006-2010 Phil Christensen # http://modu.bubblehouse.org # # # See LICENSE for details """ Datatypes to manage boolean-type fields. """ from zope.interface import implements from modu.persist import sql from modu.editable import IDatatype, define from modu.util import form from modu import persist class CheckboxField(define.definition): """ Displays a field as an HTML checkbox. Provides modified update behavior to deal with the fact that checkboxes only submit form data when checked. """ implements(IDatatype) search_list = ['unchecked', 'checked', 'no search'] def get_element(self, req, style, storable): """ @see: L{modu.editable.define.definition.get_element()} """ frm = form.FormNode(self.name) if(style == 'search'): search_value = getattr(storable, self.get_column_name(), '2') frm(type='radiogroup', options=self.search_list, value=search_value) else: frm(type='checkbox', value=self.get('checked_value', 1)) if(str(getattr(storable, self.get_column_name(), None)) == str(self.get('checked_value', 1))): frm(checked=True) default_value = self.get('default_value', None) if(not storable.get_id() and default_value is not None): frm(checked=bool(default_value)) if(style == 'listing' or self.get('read_only', False)): frm(disabled=True) return frm def get_search_value(self, value, req, frm): if(value is not None): value = value.value if(value == '0'): return sql.RAW('COALESCE(%%s, 0) <> %s' % self.get('checked_value', 1)) elif(value == '1'): return sql.RAW('COALESCE(%%s, 0) = %s' % self.get('checked_value', 1)) # a trick - return a statement that is always true return sql.RAW('COALESCE(%s = %%s, 1) = 1' % sql.escape_dot_syntax(self.get_column_name())) def update_storable(self, req, form, storable): """ @see: L{modu.editable.define.definition.update_storable()} """ form_name = '%s-form' % storable.get_table() if(form_name in req.data): form_data = req.data[form_name] if(self.name in form_data): setattr(storable, self.get_column_name(), form_data[self.name].value) else: setattr(storable, self.get_column_name(), self.get('unchecked_value', 0)) return True class NonNullSearchField(define.definition): search_list = ['empty', 'not empty', 'no search'] def get_element(self, req, style, storable): if(style != 'search'): return form.FormNode(self.name)(type='label', value='n/a - Search Use Only') else: search_value = getattr(storable, self.get_column_name(), '2') frm = form.FormNode(self.name) frm(type='radiogroup', options=self.search_list, value=search_value) return frm def get_search_value(self, value, req, frm): if(value is not None): if(value.value == '0'): return sql.RAW('ISNULL(%s)') elif(value.value == '1'): return sql.RAW('NOT(ISNULL(%s))') # a trick return sql.RAW('IF(%s, 1, 1)') def update_storable(self, req, form, storable): pass class NonBlankSearchField(NonNullSearchField): def get_search_value(self, value, req, frm): if(value is not None): if(value.value == '0'): return sql.RAW('ISNULL(%s)') elif(value.value == '1'): return sql.RAW("IFNULL(%s, '') <> ''") # a trick return sql.RAW('IF(%s, 1, 1)')
[ "phil@bubblehouse.org" ]
phil@bubblehouse.org
1081ea17c0124f9ba46398a111ac9aa9c1c6bc52
3ac0923505e1e03a07742355edec43f23ead82b7
/Daily/PY/LCP7-传递信息.py
47dde08f7b68165b4b97ab8cafc5df622c6a5329
[]
no_license
lock19960613/SCL
5055c940d2529eef981a29698c7ea04212a8b9de
3ea28fd8f5d5233411341283c85667e4b9fc64d5
refs/heads/main
2023-08-03T04:36:33.555296
2021-09-11T06:48:49
2021-09-11T06:48:49
null
0
0
null
null
null
null
UTF-8
Python
false
false
502
py
from typing import List class Solution: def numWays(self, n: int, relation: List[List[int]], k: int) -> int: edges = [[] for _ in range(n)] for s2d in relation: edges[s2d[0]].append(s2d[1]) ans = [0] def dfs(idx,step,ans): if step == k: if idx == n - 1: ans[0] += 1 return for dst in edges[idx]: dfs(dst,step + 1,ans) dfs(0,0,ans) return ans[0]
[ "597494370@qq.com" ]
597494370@qq.com
e39b7a772ddc094a8023faf4ec83d011face4a00
82aee3211216f55392d5a757eb57f02c859e9a28
/Easy/141_linkedListCycle.py
d23cc846dcdedbbb257bffebfd2150b7ee2dddbb
[]
no_license
Yucheng7713/CodingPracticeByYuch
505d18095d4b9a35c1f3b23632a90a76d811b64a
1461b10b8910fa90a311939c6df9082a8526f9b1
refs/heads/master
2022-05-01T11:51:00.612603
2022-04-18T09:46:55
2022-04-18T09:46:55
198,961,132
0
0
null
null
null
null
UTF-8
Python
false
false
490
py
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): if not head: return False l_index = f_index = head while f_index != None and f_index.next != None: l_index = l_index.next f_index = f_index.next.next if l_index == f_index: return True return False
[ "yuchengh@usc.edu" ]
yuchengh@usc.edu
7bb147fb781245b85941bb53ade305b787c1f256
7ba9ba1570ef44ced18bf7689329d5f5d4bcc350
/src/fracx/api/models.py
f1a9f5909798a2fd90a16181348846977c0a88d7
[ "MIT" ]
permissive
la-mar/permian-frac-exchange
90992393cdcdb6c6a8b697a5c7d8fc64a4bff2f2
a7ba410c02b49d05c5ad28eff0619a3c198d3fd0
refs/heads/master
2020-06-12T04:40:52.642629
2020-04-14T23:50:07
2020-04-14T23:50:07
194,196,884
0
1
null
null
null
null
UTF-8
Python
false
false
1,102
py
import logging from sqlalchemy.sql import func from api.mixins import CoreMixin from config import get_active_config from fracx import db conf = get_active_config() logger = logging.getLogger(__name__) class FracSchedule(CoreMixin, db.Model): __tablename__ = conf.FRAC_SCHEDULE_TABLE_NAME api14 = db.Column(db.String(14), nullable=False, primary_key=True) api10 = db.Column(db.String(10), nullable=False) wellname = db.Column(db.String(), nullable=True) operator = db.Column(db.String()) frac_start_date = db.Column(db.Date(), primary_key=True) frac_end_date = db.Column(db.Date(), primary_key=True) status = db.Column(db.String()) tvd = db.Column(db.Integer()) target_formation = db.Column(db.String()) shllat = db.Column(db.Float()) shllon = db.Column(db.Float()) bhllat = db.Column(db.Float()) bhllon = db.Column(db.Float()) created_at = db.Column( db.DateTime(timezone=True), default=func.now(), nullable=False ) updated_at = db.Column( db.DateTime(timezone=True), default=func.now(), nullable=False )
[ "brocklfriedrich@gmail.com" ]
brocklfriedrich@gmail.com
383074dc0b73c2d849f90519a9ec6f5795dc935c
e92a3d0fb77120be99de6040cb6cd34eda0a95f4
/urllib, requests, re, webcrawler - усиленная работа со скрапперами сайтов/code/filter_example_10.py
7ec48ce5918ab84d7e1f5f1e182bb92b97a14424
[]
no_license
Python18Academy/python_first_level
495f85631f5afc737aa156ef8ca0ea307340c322
9ce490da3108474b135a17086f4d11f2a3bbbe55
refs/heads/master
2023-09-04T17:00:36.920987
2021-03-31T18:44:37
2021-03-31T18:44:37
331,934,029
0
0
null
null
null
null
UTF-8
Python
false
false
134
py
a = [1, -4, 6, 8, -10] def func(x): if x > 0: return 1 else: return 0 b = filter(func, a) b = list(b) print(b)
[ "isakura313@gmail.com" ]
isakura313@gmail.com
5a4fca19914b7786c3fc10ad8986966a961fd341
5585352909cb26420ec3f4b54df2253a2112c5c9
/0925/isLongPressedName.py
c6c189d7901cc900138377cabcd1a1d06b6031af
[]
no_license
minuso/leetcode
fd05472a782463b27575c9149081bcd38f03a7c5
56cafa52a6a3534efc2c32db4acf516b2a285a46
refs/heads/master
2020-04-25T17:18:56.299245
2019-06-16T16:19:09
2019-06-16T16:19:09
172,943,397
0
0
null
null
null
null
UTF-8
Python
false
false
239
py
def isLongPressedName(self, name: str, typed: str) -> bool: i, j = 0, 0 while i < len(name) and j < len(typed): if name[i] == typed[j]: i, j = i+1, j+1 else: j += 1 return i == len(name)
[ "minuscholar@gmail.com" ]
minuscholar@gmail.com
319efc41188b3161c74b9492ad912388557f640e
91b2fb1fb6df216f2e365c3366bab66a567fc70d
/Week10/每日一题/面试题 02.05. 链表求和.py
adeaf8a3b372d2228ba46b48489634b0acdac3df
[]
no_license
hrz123/algorithm010
d17aee642f03f607a7984beb099eec18f2de1c8e
817911d4282d2e226518b3533dff28282a91b3d4
refs/heads/master
2022-12-20T14:09:26.365781
2020-10-11T04:15:57
2020-10-11T04:15:57
270,178,423
1
0
null
2020-06-07T03:21:09
2020-06-07T03:21:09
null
UTF-8
Python
false
false
2,392
py
# 面试题 02.05. 链表求和.py # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: carry = 0 dummy = ListNode(0) cur = dummy while l1 or l2: n1 = l1.val if l1 else 0 n2 = l2.val if l2 else 0 carry, val = divmod(n1 + n2 + carry, 10) cur.next = ListNode(val) cur = cur.next l1 = l1.next if l1 else None l2 = l2.next if l2 else None if carry: cur.next = ListNode(1) return dummy.next # 进阶 class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: v1, v2 = 0, 0 while l1: v1 = v1 * 10 + l1.val l1 = l1.next while l2: v2 = v2 * 10 + l2.val l2 = l2.next val = v1 + v2 pre, cur = None, None while val: val, mod = divmod(val, 10) cur = ListNode(mod) cur.next = pre pre = cur return cur class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: dummy = ListNode(0) cur = dummy carry = 0 while l1 or l2: n1, l1 = (l1.val, l1.next) if l1 else (0, l1) n2, l2 = (l2.val, l2.next) if l2 else (0, l2) carry, mod = divmod(n1 + n2 + carry, 10) cur.next = ListNode(mod) cur = cur.next if carry: cur.next = ListNode(1) return dummy.next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: v1, v2 = 0, 0 while l1: v1 = v1 * 10 + l1.val l1 = l1.next while l2: v2 = v2 * 10 + l2.val l2 = l2.next val = v1 + v2 pre = cur = None while val: val, mod = divmod(val, 10) cur = ListNode(val) cur.next = pre pre = cur return cur def main(): sol = Solution() l1 = ListNode(1) l1.next = ListNode(2) l2 = ListNode(2) l2.next = ListNode(8) l3 = sol.addTwoNumbers(l1, l2) while l3: print(l3.val) l3 = l3.next if __name__ == '__main__': main()
[ "2403076194@qq.com" ]
2403076194@qq.com
d687316af88ab599c537375566f06965c12be41d
e522dc3b8ae16fb6adf8c679c2fcd61e06979f29
/example/gpio_example.py
389b5f9b1201efa4304a5a4758bf4f01ffb70ffb
[ "MIT" ]
permissive
amaork/raspi-io
96e92330555e7700f54633f582efbc7620f8b10b
aaea4532569010a64f3c54036b9db7eb81515d1a
refs/heads/master
2021-09-17T15:27:43.853195
2021-08-27T08:51:24
2021-08-27T08:51:24
94,192,125
8
1
null
null
null
null
UTF-8
Python
false
false
457
py
#!/usr/bin/env python3.5 from raspi_io import GPIO import raspi_io.utility as utility if __name__ == "__main__": io = [20, 21] gpio = GPIO(utility.scan_server()[0]) gpio.setmode(GPIO.BCM) gpio.setup(io, GPIO.OUT) gpio.output(io, 1) gpio.output(io, 0) gpio.output(io, [1, 0]) gpio.output(io, [0, 1]) gpio.setup(21, GPIO.IN, GPIO.PUD_DOWN) print(gpio.input(21)) print(gpio.input(21)) print(gpio.input(21))
[ "amaork@gmail.com" ]
amaork@gmail.com
92f985f89dee5987ed7ece4d443d4638d9a09a6e
711756b796d68035dc6a39060515200d1d37a274
/output_exocyst_tags/optimized_3617_sml.py
ee0308f6fdb401a92bd718d4bf86136600712fb3
[]
no_license
batxes/exocyst_scripts
8b109c279c93dd68c1d55ed64ad3cca93e3c95ca
a6c487d5053b9b67db22c59865e4ef2417e53030
refs/heads/master
2020-06-16T20:16:24.840725
2016-11-30T16:23:16
2016-11-30T16:23:16
75,075,164
0
0
null
null
null
null
UTF-8
Python
false
false
4,722
py
import _surface import chimera try: import chimera.runCommand except: pass from VolumePath import markerset as ms try: from VolumePath import Marker_Set, Link new_marker_set=Marker_Set except: from VolumePath import volume_path_dialog d= volume_path_dialog(True) new_marker_set= d.new_marker_set marker_sets={} surf_sets={} if "Sec3_GFPN" not in marker_sets: s=new_marker_set('Sec3_GFPN') marker_sets["Sec3_GFPN"]=s s= marker_sets["Sec3_GFPN"] mark=s.place_marker((405.721, 519.261, 370.977), (0.15, 0.78, 0.66), 2) if "Sec3_GFPC" not in marker_sets: s=new_marker_set('Sec3_GFPC') marker_sets["Sec3_GFPC"]=s s= marker_sets["Sec3_GFPC"] mark=s.place_marker((391.015, 482.144, 340.67), (0.15, 0.78, 0.66), 2) if "Sec3_Anch" not in marker_sets: s=new_marker_set('Sec3_Anch') marker_sets["Sec3_Anch"]=s s= marker_sets["Sec3_Anch"] mark=s.place_marker((544.978, 316.762, 358.566), (0.15, 0.58, 0.66), 2) if "Sec5_GFPN" not in marker_sets: s=new_marker_set('Sec5_GFPN') marker_sets["Sec5_GFPN"]=s s= marker_sets["Sec5_GFPN"] mark=s.place_marker((440.321, 499.369, 427.91), (0.38, 0.24, 0.37), 2) if "Sec5_GFPC" not in marker_sets: s=new_marker_set('Sec5_GFPC') marker_sets["Sec5_GFPC"]=s s= marker_sets["Sec5_GFPC"] mark=s.place_marker((408.241, 464.21, 314.908), (0.38, 0.24, 0.37), 2) if "Sec6_GFPN" not in marker_sets: s=new_marker_set('Sec6_GFPN') marker_sets["Sec6_GFPN"]=s s= marker_sets["Sec6_GFPN"] mark=s.place_marker((399.76, 448.081, 410.929), (0.84, 0.98, 0.24), 2) if "Sec6_GFPC" not in marker_sets: s=new_marker_set('Sec6_GFPC') marker_sets["Sec6_GFPC"]=s s= marker_sets["Sec6_GFPC"] mark=s.place_marker((580.779, 491.271, 431.133), (0.84, 0.98, 0.24), 2) if "Sec6_Anch" not in marker_sets: s=new_marker_set('Sec6_Anch') marker_sets["Sec6_Anch"]=s s= marker_sets["Sec6_Anch"] mark=s.place_marker((565.705, 663.093, 336.353), (0.84, 0.78, 0.24), 2) if "Sec8_GFPC" not in marker_sets: s=new_marker_set('Sec8_GFPC') marker_sets["Sec8_GFPC"]=s s= marker_sets["Sec8_GFPC"] mark=s.place_marker((615.651, 489.717, 370.16), (0.62, 0.67, 0.45), 2) if "Sec8_Anch" not in marker_sets: s=new_marker_set('Sec8_Anch') marker_sets["Sec8_Anch"]=s s= marker_sets["Sec8_Anch"] mark=s.place_marker((491.39, 296.306, 340.713), (0.62, 0.47, 0.45), 2) if "Sec10_GFPN" not in marker_sets: s=new_marker_set('Sec10_GFPN') marker_sets["Sec10_GFPN"]=s s= marker_sets["Sec10_GFPN"] mark=s.place_marker((650.698, 503.069, 401.115), (0, 0.91, 0), 2) if "Sec10_GFPC" not in marker_sets: s=new_marker_set('Sec10_GFPC') marker_sets["Sec10_GFPC"]=s s= marker_sets["Sec10_GFPC"] mark=s.place_marker((432.995, 465.737, 224.378), (0, 0.91, 0), 2) if "Sec10_Anch" not in marker_sets: s=new_marker_set('Sec10_Anch') marker_sets["Sec10_Anch"]=s s= marker_sets["Sec10_Anch"] mark=s.place_marker((514.351, 652.063, 435.66), (0, 0.71, 0), 2) if "Sec15_GFPN" not in marker_sets: s=new_marker_set('Sec15_GFPN') marker_sets["Sec15_GFPN"]=s s= marker_sets["Sec15_GFPN"] mark=s.place_marker((471.642, 498.911, 488.563), (0.11, 0.51, 0.86), 2) if "Sec15_GFPC" not in marker_sets: s=new_marker_set('Sec15_GFPC') marker_sets["Sec15_GFPC"]=s s= marker_sets["Sec15_GFPC"] mark=s.place_marker((658.697, 497.172, 336.078), (0.11, 0.51, 0.86), 2) if "Sec15_Anch" not in marker_sets: s=new_marker_set('Sec15_Anch') marker_sets["Sec15_Anch"]=s s= marker_sets["Sec15_Anch"] mark=s.place_marker((565.639, 553.271, 211.433), (0.11, 0.31, 0.86), 2) if "Exo70_GFPN" not in marker_sets: s=new_marker_set('Exo70_GFPN') marker_sets["Exo70_GFPN"]=s s= marker_sets["Exo70_GFPN"] mark=s.place_marker((398.709, 504.236, 326.959), (0.89, 0.47, 0.4), 2) if "Exo70_GFPC" not in marker_sets: s=new_marker_set('Exo70_GFPC') marker_sets["Exo70_GFPC"]=s s= marker_sets["Exo70_GFPC"] mark=s.place_marker((637.387, 452.385, 390.377), (0.89, 0.47, 0.4), 2) if "Exo70_Anch" not in marker_sets: s=new_marker_set('Exo70_Anch') marker_sets["Exo70_Anch"]=s s= marker_sets["Exo70_Anch"] mark=s.place_marker((424.742, 698.993, 443.663), (0.89, 0.27, 0.4), 2) if "Exo84_GFPN" not in marker_sets: s=new_marker_set('Exo84_GFPN') marker_sets["Exo84_GFPN"]=s s= marker_sets["Exo84_GFPN"] mark=s.place_marker((451.255, 515.043, 419.368), (0.5, 0.7, 0), 2) if "Exo84_GFPC" not in marker_sets: s=new_marker_set('Exo84_GFPC') marker_sets["Exo84_GFPC"]=s s= marker_sets["Exo84_GFPC"] mark=s.place_marker((425.023, 454.16, 296.551), (0.5, 0.7, 0), 2) if "Exo84_Anch" not in marker_sets: s=new_marker_set('Exo84_Anch') marker_sets["Exo84_Anch"]=s s= marker_sets["Exo84_Anch"] mark=s.place_marker((520.301, 618.746, 241.537), (0.5, 0.5, 0), 2) for k in surf_sets.keys(): chimera.openModels.add([surf_sets[k]])
[ "batxes@gmail.com" ]
batxes@gmail.com
b72f8e277d42961c941209ec8450b8269aa663e5
240dc81851dd0243c0b14511f6d8b563ab91c890
/admin/backup_views.py
76ae812e8d20d8a67fe351feec027d7f34568084
[]
no_license
prcek/TSReg
0aac7ffc7992b731d12dc3959d661bc8c3639744
ea6eac514d8e783ddaeeed6181b9ab45d5673c05
refs/heads/master
2020-05-30T03:19:46.737202
2017-06-08T08:14:00
2017-06-08T08:14:00
2,208,569
0
0
null
null
null
null
UTF-8
Python
false
false
3,578
py
# -*- coding: utf-8 -*- from django import forms from django.http import HttpResponse, Http404, HttpResponseRedirect from django.shortcuts import render_to_response, redirect, get_object_or_404 from django.template import RequestContext,Context, loader import utils.config as cfg from utils.data import UnicodeReader from utils.mail import valid_email from enroll.models import Course,Student,Season from admin.models import FileBlob,CourseBackup from google.appengine.api import taskqueue import urllib import logging import cStringIO import datetime from utils.locale import local_timezone ERROR_MESSAGES={'required': 'Položka musí být vyplněna', 'invalid': 'Neplatná hodnota'} class SeasonField(forms.ChoiceField): def valid_value(self, value): self._set_choices(Season.get_SEASON_CHOICES()) return super(SeasonField,self).valid_value(value) class SeasonFilterForm(forms.Form): season_key = SeasonField(label='sezóna', error_messages=ERROR_MESSAGES) def __init__(self,data = None, **kwargs): super(self.__class__,self).__init__(data, **kwargs) self.fields['season_key']._set_choices(Season.get_SEASON_CHOICES()) def index(request): season = None if request.method == 'POST': filter_form = SeasonFilterForm(request.POST) if filter_form.is_valid(): season = Season.get(str(filter_form.cleaned_data['season_key'])) if not season is None: request.session['backup_season_key']=str(season.key()) else: bskey = request.session.get('backup_season_key',None) if not bskey is None: season = Season.get(str(bskey)) if season is None: filter_form = SeasonFilterForm() else: filter_form = SeasonFilterForm({'season_key':str(season.key())}) if season is None: course_list = None else: course_list = Course.list_season(str(season.key())) return render_to_response('admin/backup_index.html', RequestContext(request, { 'filter_form':filter_form, 'course_list': course_list})) def plan_backup(request,course_id): course = Course.get_by_id(int(course_id)) if course is None: raise Http404 logging.info('course: %s'%course) taskqueue.add(url='/task/course_backup/', params={'course_id':course.key().id()}) return HttpResponseRedirect('../..') def plan_fullsync(request,course_id): course = Course.get_by_id(int(course_id)) if course is None: raise Http404 logging.info('course: %s'%course) taskqueue.add(url='/task/course_fullsync/', params={'course_id':course.key().id()}) return HttpResponseRedirect('../..') def index_course(request, course_id): course = Course.get_by_id(int(course_id)) if course is None: raise Http404 logging.info('course: %s'%course) backup_list = CourseBackup.list_for_course(str(course.key())) return render_to_response('admin/backup_list.html', RequestContext(request, { 'backup_list': backup_list, 'course':course})) def get_backup(request, course_id, course_backup_id): course = Course.get_by_id(int(course_id)) if course is None: raise Http404 course_backup = CourseBackup.get_by_id(int(course_backup_id)) if course_backup is None: raise Http404 r = HttpResponse(course_backup.data,mimetype='application/vnd.ms-excel') file_name = urllib.quote(course_backup.filename) logging.info(file_name) r['Content-Disposition'] = "attachment; filename*=UTF-8''%s"%file_name return r
[ "tomas.hluchan@gmail.com" ]
tomas.hluchan@gmail.com
ea8ce920973c4519f0a07fbdcfc341110505353f
bf9b4ff0145381084e11b2df64a8399b46328b36
/libby/main.py
ba1af7b19c80ad799f69e55ca89c5b4114208fd1
[]
no_license
kwarwp/grete
f6fbf7e21464536cb27253aa02de4b3292179883
e5f02660c57ba3d271b059d8b7972099226a0987
refs/heads/master
2023-04-06T21:11:37.811621
2023-03-16T21:32:04
2023-03-16T21:32:04
128,999,048
0
0
null
null
null
null
UTF-8
Python
false
false
4,438
py
# grete.libby.main.py #REVISADO PRONTO from _spy.vitollino.main import Cena,Elemento,Texto, Sala, INVENTARIO #CAMPO = "https://image.freepik.com/fotos-gratis/paisagem-de-campo-de-golfe_1388-96.jpg" #CASAL = "https://images.vexels.com/media/users/3/129903/isolated/preview/c996f5193090b3a642ffc069bc81da0c-silhueta-do-casal-andando-12-by-vexels.png ''' def boyfriendsatthecamp(): campo = Cena (img = CAMPO) casal = Elemento(img = CASAL, tit = "casal", style = dict(left = 150, top = 60, height = 200)) txtcasal = Texto(casal,"let's eat something!") casal.entra(campo) casal.vai = txtcasal.vai campo.vai() loversatthecamp() ''' sn = "https://i.imgur.com/evlSZig.jpg" sl = "https://i.imgur.com/Ax1XDBU.jpg" ss = "https://i.imgur.com/9Vg7DzJ.jpg" so = "https://i.imgur.com/haPQ4rZ.jpg" #OBJECTS tomada = "https://i.imgur.com/l6INRuQ.jpg" interruptor = "https://i.imgur.com/olpkjL0.jpg" interfone = "https://i.imgur.com/4s1Pbpv.jpg" extintor = "https://i.imgur.com/AJzKYaE.jpg" garrafa_termica = "https://i.imgur.com/M9oUgH6.jpg" bebedouro = "https://i.imgur.com/GDRYgs3.jpg" # grete.amanda.main.py from _spy.vitollino.main import STYLE, INVENTARIO, Sala, Texto, Cena STYLE["width"] = 800 STYLE["height"] = "600px" children = "https://i.imgur.com/4fTrn8X.jpg" toy = "https://i.imgur.com/57cOaZ9.jpg" sckoolhouse = "https://i.imgur.com/oXsdN2c.jpg" leyden = "https://i.imgur.com/abeXKwL.jpg" volcano = "https://i.imgur.com/4Y5aie8.jpg" globe = "https://i.imgur.com/EQtHzod.jpg" ball = "https://i.imgur.com/rBbRsFU.jpg" TIRINHA_DA_SECRETARIA= "https://i.imgur.com/555hVt2.png" SECRETARY = None def secretary(): global SECRETARY if SECRETARY: return SECRETARY def _gone_secretary(): try: gimnasium().sul.vai() except: from anastasia.main import gimnasium gimnasium().sul.vai() def _go_kitchen(): try: kitchen().oeste.vai() except: from callie.main import kitchen kitchen().oeste.vai() def _go_secretary(): SECRETARY.oeste.meio= Cena(vai = _gone_secretary) _vai = Cena() def redir(): _vai.vai = _gone_secretary historia = Cena(TIRINHA_DA_SECRETARIA, _vai, _vai, _vai) texto = """Cleison enteres the school excitedly and sees the three secretaries. Boring, so boring that you would even want to die just to look at them. He went to speak to them. Getting closer, he saw on their shirts the following sentence : 'Become Claudemilson'. He said hello and they answerd: -Become Claudemillson! Where is your shirt? He said: -I am a former student, I just came to visit the school. See you! He left and the three of them looked at him leaving, just turning their heads. """ _vai.vai = Texto(historia, '', texto, foi=redir).vai historia.vai() def go_secretary(): _go_secretary() SECRETARY = _sala = Sala(sn,sl,ss,so, "trig") from naomi.main import Elemento _sala.oeste.meio = Cena(TIRINHA_DA_SECRETARIA, vai = go_secretary) _sala.sul.meio= Cena(vai = _go_kitchen) bebedouro_ = Elemento(bebedouro, tit = "switch", drag=True, x = 460, y = 192, w = 80, h = 90, drop="drinking fountain", cena=_sala.sul, texto="Please help me, fix my name.") tomada_ = Elemento(tomada, tit = "thermal bottle", drag=True, x = 185, y = 30, w = 80, h = 100, drop="socket", cena=_sala.leste, texto="Please help me, fix my name.") extintor_ = Elemento(extintor, tit = "socket", drag=True, x = 30, y = 500, w = 100, h = 120,drop="fire extinguisher", cena=_sala.leste, texto="Please help me, fix my name.") garrafa_termica_ = Elemento(garrafa_termica, tit = "fire extinguisher", drag=True, x = 520, y = 220, w = 90, h = 60, drop="thermal bottle", cena=_sala.sul, texto="Please help me, fix my name.") interfone_ = Elemento(interfone, tit = "drinking fountain", drag=True, x = 700, y = 220, w = 90, h = 60, drop="communicator", cena=_sala.sul, texto="Please help me, fix my name.") interruptor_ = Elemento(interruptor, tit = "communicator", drag=True, x = 100, y = 220, w = 90, h = 60, drop="switch", cena=_sala.oeste, texto="Please help me, fix my name.") return _sala if __name__ == "__main__": INVENTARIO.inicia() secretary().norte.vai()
[ "38007182+kwarwp@users.noreply.github.com" ]
38007182+kwarwp@users.noreply.github.com
55f4c8eb3f284879551872c0d056599a50209d67
6643bd4ecd44a21944debc75d79c4616bdac7868
/datawarehouse/opertaion/script/ETL_P2P.py
e41ca1fb1dac6f879da61768c24a2d36d4b7928b
[]
no_license
smartbrandnew/vobileETLCode
d14fb9f34eb1f76e6e60253557c8b964137f6cb4
210e9060ed9fc1d278373910cfe203808b1afb04
refs/heads/master
2021-07-14T07:30:08.018828
2016-07-04T08:40:57
2016-07-04T08:40:57
62,543,866
0
2
null
2020-07-22T19:56:50
2016-07-04T08:12:01
Python
UTF-8
Python
false
false
2,050
py
#!/usr/bin/python import MySQLdb import sys import time import datetime # downloads conn=MySQLdb.connect(host='p2p-1-replica.c85gtgxi0qgc.us-west-1.rds.amazonaws.com',user='kettle',passwd='k3UTLe',port=3306) conn.select_db('hubble_stat') dlcur=conn.cursor() dlcur.execute('select date_format(finished_at, "%Y-%m-%d"), count(*) from finishedDNAIdentifyTask where error_code = 0 and download_time > 0 and finished_at >="2015-07-01" and finished_at <"2016-03-01" and dna_generate_time > 0 group by 1') dlrows = dlcur.fetchall() conn=MySQLdb.connect(host='192.168.110.114',user='kettle',passwd='k3UTLe',port=3306) dlcur=conn.cursor() conn.select_db('DW_VTMetrics') for e in dlrows: downloads_insert = "insert into VTMetricsReport(company_id,website_type,reportedDate,downloads) values('%s','%s','%s','%s')" %(14,'P2P',e[0],e[1]) dlcur.execute(downloads_insert) conn.commit() dlcur.close() conn.close() #matched seed/ matches/ Ips of matches / matches with notices sent conn=MySQLdb.connect(host='eqx-vtweb-slave-db',user='kettle',passwd='k3UTLe',port=3306) conn.select_db('tracker2') mtcur=conn.cursor() mtcur.execute('select date(a.created_at), count(distinct a.key_id) Matched_Seed, count(a.id) Matches, sum(a.view_count), sum(if(a.count_send_notice > 0,1,0)) send_Notices from matchedVideo a, mddb.trackingWebsite b where a.company_id = 14 and a.trackingWebsite_id = b.id and a.hide_flag = 2 and b.website_type in ("p2p") and a.created_at >= "2015-07-01" and a.created_at < "2016-03-01" group by 1') mtrows = mtcur.fetchall() conn=MySQLdb.connect(host='192.168.110.114',user='kettle',passwd='k3UTLe',port=3306) mtcur=conn.cursor() conn.select_db('DW_VTMetrics') for e in mtrows: matches_insert = "update VTMetricsReport set matchedSeeds = '%s', matches = '%s', matchedURLs_IPs = '%s', matchedWithNoticeSent = '%s' where company_id = 14 and website_type='%s' and reportedDate in ('%s')" %(e[1],e[2],e[3],e[4],'P2P',e[0]) mtcur.execute(matches_insert) conn.commit() mtcur.close() conn.close()
[ "smartbrandnew@163.com" ]
smartbrandnew@163.com
6c882c2b99ed74a91f891acc54ce5e7717911120
d94b6845aeeb412aac6850b70e22628bc84d1d6d
/yoto/problems/base.py
28a7ba39f965d68d325b980d3acc1a0d43a249af
[ "CC-BY-4.0", "Apache-2.0" ]
permissive
ishine/google-research
541aea114a68ced68736340e037fc0f8257d1ea2
c1ae273841592fce4c993bf35cdd0a6424e73da4
refs/heads/master
2023-06-08T23:02:25.502203
2023-05-31T01:00:56
2023-05-31T01:06:45
242,478,569
0
0
Apache-2.0
2020-06-23T01:55:11
2020-02-23T07:59:42
Jupyter Notebook
UTF-8
Python
false
false
1,804
py
# coding=utf-8 # Copyright 2023 The Google Research Authors. # # 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. """Common interfaces for multi-objective problems.""" import abc import six @six.add_metaclass(abc.ABCMeta) class Problem(object): """Abstract class for multi-loss optimization problems.""" @abc.abstractmethod def losses_and_metrics(self, inputs, inputs_extra=None, training=False): """Compute the losses and some additional metrics. Args: inputs: Dict[ Str: tf.Tensor]. Maps input names (for instance, "image" or "label") to their values. inputs_extra: tf.Tensor. Additional conditioning inputs. training: Bool. Whether to run the model in the training mode (mainly important for models with batch normalization). Returns: losses: Dict[ Str: tf.Tensor]. A dictionary mapping loss names to tensors of their per-sample values. metrics: Dict[ Str: tf.Tensor]. A dictionary mapping metric names to tensors of their per-sample values. """ @abc.abstractmethod def initialize_model(self): pass @abc.abstractproperty def losses_keys(self): """Names of the losses used in the problem (keys in the dict of losses).""" @abc.abstractproperty def module_spec(self): """TF Hub Module spec."""
[ "copybara-worker@google.com" ]
copybara-worker@google.com
c308f7c1b5031043658b922ec5cf81a010636bb4
1647dd424edd275a4b078bcc5a0cba7312e81fdc
/common_utils/data_types/correlation_matrix.py
f117d3adb988b301dc88494b9d433ea3ee02523a
[ "MIT" ]
permissive
CroP-BioDiv/zcitools
a72646bec8795bd24aca2dc7fa91c116be6abd7a
3340a92f710f4acb5d3507bec639c40a17dfb5f2
refs/heads/master
2022-09-23T07:09:16.671748
2022-09-17T11:09:21
2022-09-17T11:09:21
222,237,739
0
1
null
null
null
null
UTF-8
Python
false
false
2,334
py
from common_utils.import_method import import_pandas from common_utils.exceptions import ZCItoolsValueError class CorrelationMatrix: def __init__(self, columns, list_values=None): self._columns = [c.replace(' ', '_') for c in columns] self._columns_lower = [c.lower().replace(' ', '_') for c in columns] self._values = dict() # tuple(sorted(c1, c2)) -> value. Note: value can be missing if list_values: assert len(columns) - 1 == len(list_values), (len(columns), len(list_values)) for i, (c1, vs) in enumerate(zip(self._columns, list_values)): c2s = self._columns[i+1:] assert len(c2s) == len(vs), (i, c1, len(c2s), len(vs)) for c2, v in zip(c2s, vs): if v is not None: self.set(c1, c2, v) def num_columns(self): return len(self._columns) def check_column(self, c, to_assert=False): c = c.lower() if c in self._columns_lower: return c if to_assert: assert False, (c, self._columns) # def set(self, c1, c2, v): c1 = self.check_column(c1, to_assert=True) c2 = self.check_column(c2, to_assert=True) k = (c1, c2) if c1 < c2 else (c2, c1) if v is None: self._values.pop(k) else: self._values[k] = v def get(self, c1, c2): c1 = self.check_column(c1, to_assert=True) c2 = self.check_column(c2, to_assert=True) k = (c1, c2) if c1 < c2 else (c2, c1) return self._values.get(k) @staticmethod def from_excel(filename, triangular='L'): df = import_pandas().read_excel(filename, sheet_name='Sheet1') columns = list(df.columns[1:]) if triangular.upper() == 'L': list_values = [list(df[c1][i+1:]) for i, c1 in enumerate(columns[:-1])] else: raise NotImplementedError('Upper triangular') return CorrelationMatrix(columns, list_values=list_values) @staticmethod def from_file(filename, triangular='L'): # Lower/Upper triangular if filename.endswith('.xlsx'): return CorrelationMatrix.from_excel(filename, triangular=triangular) raise ZCItoolsValueError(f"Can't import correlation data from file {filename}!")
[ "ante.turudic@gmail.com" ]
ante.turudic@gmail.com
50fb251c0bd246cad074f7cca232173dd0b7c5ed
f998a574343292d050777f616b408a74fde05738
/eshop_docker/eshop/apps/trade/adminx.py
e70a39d7f2b85434781c6c7f8b3084dfc5e3750e
[]
no_license
Boomshakal/Django
7987e0572fc902bd56360affea0b5087a4cb04a7
a149691c472eab3440028bf2460cd992acec0f8a
refs/heads/master
2023-01-11T06:16:29.283428
2022-12-23T08:00:05
2022-12-23T08:00:05
199,360,433
0
0
null
2020-06-06T09:37:02
2019-07-29T02:01:09
Python
UTF-8
Python
false
false
716
py
# -*- coding:utf-8 -*- __author__ = 'xojisi' __date__ = '2018/2/1 13:42' import xadmin from .models import ShoppingCart, OrderInfo, OrderGoods class ShoppingCartAdmin(object): list_display = ["user", "goods", "nums", ] class OrderInfoAdmin(object): list_display = ["user", "order_sn", "trade_no", "pay_status", "post_script", "order_mount", "order_mount", "pay_time", "add_time"] class OrderGoodsInline(object): model = OrderGoods exclude = ['add_time', ] extra = 1 style = 'tab' inlines = [OrderGoodsInline, ] xadmin.site.register(ShoppingCart, ShoppingCartAdmin) xadmin.site.register(OrderInfo, OrderInfoAdmin)
[ "362169885@qq.com" ]
362169885@qq.com
0c9aadc2d0cb47adbdf5eb01b41759191fbb4b89
5a391bc46a3649d22e4f928ff995daf55caebf9d
/Day2/AsyncHttp2.py
db9e05a3dc416a83571e0943db548571c01b008a
[]
no_license
artheadsweden/Python_Adv_Nov_19
d4d4c45b34394bf3b64ba3c64c91213bd5d21594
edae48c6cdab2e3c2090394fc499f4cc500df13a
refs/heads/master
2020-09-20T05:41:35.817957
2019-11-27T21:34:31
2019-11-27T21:34:31
224,390,626
1
1
null
null
null
null
UTF-8
Python
false
false
1,021
py
from aiohttp import ClientSession import asyncio async def get(session, url): async with session.get(url) as response: return await response.text() async def fetch(url): async with ClientSession() as session: print("Fetching", url) html = await get(session, url) print(url, "is done") return html async def print_when_done(tasks): result = [await res for res in asyncio.as_completed(tasks)] print("Got", len(result), "pages") print("They got the titles") for page in result: title_index = page.index("<title>") title_end_index = page.index("</title>") title = page[title_index+7: title_end_index] print(title.strip()) async def get_urls(): urls = ["http://cnn.com", "http://bbc.com", "http://aljazeera.com"] tasks = [fetch(url) for url in urls] await print_when_done(tasks) def main(): loop = asyncio.get_event_loop() loop.run_until_complete(get_urls()) if __name__ == '__main__': main()
[ "joakim@arthead.se" ]
joakim@arthead.se
fb3497f271ad83c243e1b67f2e965dad71f998f4
eb9f655206c43c12b497c667ba56a0d358b6bc3a
/python/helpers/typeshed/stubs/Pillow/PIL/SgiImagePlugin.pyi
e7f4ff96e1b777c06448cd814b82d888da0b87e3
[ "Apache-2.0", "MIT" ]
permissive
JetBrains/intellij-community
2ed226e200ecc17c037dcddd4a006de56cd43941
05dbd4575d01a213f3f4d69aa4968473f2536142
refs/heads/master
2023-09-03T17:06:37.560889
2023-09-03T11:51:00
2023-09-03T12:12:27
2,489,216
16,288
6,635
Apache-2.0
2023-09-12T07:41:58
2011-09-30T13:33:05
null
UTF-8
Python
false
false
301
pyi
from typing import Any, ClassVar from typing_extensions import Literal from .ImageFile import ImageFile, PyDecoder MODES: Any class SgiImageFile(ImageFile): format: ClassVar[Literal["SGI"]] format_description: ClassVar[str] class SGI16Decoder(PyDecoder): def decode(self, buffer): ...
[ "intellij-monorepo-bot-no-reply@jetbrains.com" ]
intellij-monorepo-bot-no-reply@jetbrains.com
cd2837c6567f62732024d941943feef047ced534
662422157827bfa076cde1369117b04646bc09af
/DNS/bruteforce_ipv6.py
2ed8ed208fa1325a6cffa48b16d7209ecee4d5ea
[]
no_license
macavalcantep/MBA_IMPACTA
d1d1e37de6bc1a2d02a8bb9a0e5112f9b9fd8ef5
9228d7f55a23b51c8e4b908333eb6e89431c76a2
refs/heads/main
2023-08-04T03:06:54.290331
2021-09-27T21:20:11
2021-09-27T21:20:11
402,221,762
0
0
null
null
null
null
UTF-8
Python
false
false
680
py
#!/usr/bin/python import dns.resolver myquery = dns.resolver.Resolver() domain = "yahoo.com" #host ="www" #target = host + "." + domain def func_a(_target): question = myquery.query(_target, 'AAAA') for _addr in question: print('[+] - ' + _target + '---> ' + str(_addr)) def bruteforce_dns_ipv6(_wordlist): with open(_wordlist, 'r') as machines: while True: machine = machines.readline().strip("\n") if not machine: break try: target = machine + "." + domain func_a(target) except: pass bruteforce_dns_ipv6("file.txt")
[ "yellow@battosai.yellow.dojo" ]
yellow@battosai.yellow.dojo
734cf2f816bfa171b109a2ecd2be7c9fe690212b
decea024dde21a9e4847992c53c67da2bc3f365c
/Lectures/Intro to Frameworks/Lab/ORMs/app/models.py
2f5358169b9efc5eaf88d1be4ea29ac2cdbeceda
[]
no_license
rjglushko/IOLab
bd0d2fd941a0ab592ca84ff9c679b24cad9dbf7d
08e08691ecf488ef35faf3d431681756c7d7995a
refs/heads/master
2021-01-10T04:21:44.095280
2016-03-19T05:03:22
2016-03-19T05:03:22
47,841,381
0
3
null
2016-03-19T04:28:29
2015-12-11T17:36:30
HTML
UTF-8
Python
false
false
472
py
from app import db class Customer(db.Model): id = db.Column(db.Integer, primary_key=True) company = db.Column(db.String(120), unique=False) email = db.Column(db.String(120)) # You need to a relationship to Address table here # see http://flask-sqlalchemy.pocoo.org/2.1/models/#one-to-many-relationships def __repr__(self): return '<Customer %r>' % self.email # Your Address code should go here # class Address(db.Model):
[ "=" ]
=
5b06e6d0a8f9dec3336df8b334522c5d6177989a
3ca57c41e909849729a6be0a9cbfd0f09d8c23cc
/plot_compound_length_thesis.py
d53d1d4da7ad778f3e5e5953e26eb96fa44c5cec
[ "Apache-2.0" ]
permissive
evanmiltenburg/MeasureDiversity
ec060132e51a4203daa725eeca2f0d3ca4ba6e38
8b79349ac339d949156cdc90d3cab9abc332c978
refs/heads/master
2021-03-27T06:27:27.749091
2019-12-29T12:40:13
2019-12-29T12:40:13
117,252,509
12
3
Apache-2.0
2019-07-11T10:51:06
2018-01-12T14:46:43
Python
UTF-8
Python
false
false
2,827
py
import json from matplotlib import pyplot as plt from matplotlib.lines import Line2D import seaborn as sns import pandas as pd sns.set_style("white") sns.set_context('paper', font_scale=7) my_palette = sns.cubehelix_palette(10, start=.8, rot=-.95)#sns.color_palette("cubehelix", 10) sns.set_palette(my_palette) system2label = {'Dai-et-al-2017': 'Dai et al. 2017', 'Liu-et-al-2017': 'Liu et al. 2017', 'Mun-et-al-2017': 'Mun et al. 2017', 'Shetty-et-al-2016': 'Shetty et al. 2016', 'Shetty-et-al-2017': 'Shetty et al. 2017', 'Tavakoli-et-al-2017': 'Tavakoli et al. 2017', 'Vinyals-et-al-2017': 'Vinyals et al. 2017', 'Wu-et-al-2016': 'Wu et al. 2016', 'Zhou-et-al-2017': 'Zhou et al. 2017'} with open('Data/Output/nouns_pps.json') as f: data = json.load(f) def get_val(data): val = {2:[], 3:[], 4:[]} for compound_data in data['val']['compound_data']: val[2].append(compound_data['compound_lengths']['2']) val[3].append(compound_data['compound_lengths']['3']) val[4].append(compound_data['compound_lengths']['4']) for i, results in val.items(): val[i] = round(sum(results)/len(results)) return val to_plot = dict(system=[], length=[], number=[]) for system, label in system2label.items(): to_plot['system'].extend([label] * 3) to_plot['length'].extend(['len2','len3','len4']) to_plot['number'].extend([data[system]['compound_data']['compound_lengths'].get(i,0) for i in ['2','3','4']]) val = get_val(data) to_plot['system'].extend(['zzzval'] * 3) to_plot['length'].extend(['len2','len3','len4']) to_plot['number'].extend([val[i] for i in [2,3,4]]) df = pd.DataFrame(to_plot) ax = sns.barplot(x='number', y='length', hue='system', data=df) fig, ax = plt.subplots(figsize=(45,28)) ax = sns.barplot(x='number', y='length', hue='system', data=df) ax.set_xscale('log') labels = list(system2label.values()) + ['Validation data'] legend_markers = [Line2D(range(1), range(1), linewidth=0, # Invisible line marker='o', markersize=40, markerfacecolor=my_palette[i]) for i, name in enumerate(labels)] plt.legend(legend_markers, labels, numpoints=1, loc='center left', bbox_to_anchor=(1, 0.5), ncol=1, handletextpad=-0.3, columnspacing=0) sns.despine() plt.tick_params(direction='in', length=10, width=4, bottom=True, left=True) plt.tight_layout() plt.ylabel('Compound length',labelpad=50) ax.set_yticklabels(['2','3','4']) ax.tick_params(axis='both', which='major', pad=15) plt.xlabel('Number of tokens',labelpad=50) plt.savefig('Data/Output/compound_lengths_thesis.pdf')
[ "emielonline@gmail.com" ]
emielonline@gmail.com