repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
leequant761/Fluent-python | 19-dyn-attr-prop/oscon/osconfeed.py | """
osconfeed.py: Script to download the OSCON schedule feed
# BEGIN OSCONFEED_DEMO
>>> feed = load() # <1> 내포된 dictionary 객체
>>> sorted(feed['Schedule'].keys()) # <2> 4개의 레코드 컬렉션 나열
['conferences', 'events', 'speakers', 'venues']
>>> for key, value in sorted(feed['Schedule'].items()): # 스케쥴 레코드의
... |
leequant761/Fluent-python | 03-dict-set/immutable_mapping.py | from types import MappingProxyType
d = {1: 'A'}
d_proxy = MappingProxyType(d)
d_proxy # mappingproxy({1: 'A'})
d_proxy[1] # 'A'
d_proxy[2] = 'B' # Error : not support item assignment
d[2] = 'B'
d_proxy[2] # 'B'
from dis import dis
dis('set([1])') |
leequant761/Fluent-python | 11-iface-abc/bingo.py | <reponame>leequant761/Fluent-python
# BEGIN TOMBOLA_BINGO
import random
from tombola import Tombola
# load() pick() 추상메서드 구현
# loaded()는 상속
# inspect()는 오버라이드
# _call()__은 추가 구현
class BingoCage(Tombola): # <1>
def __init__(self, items):
self._randomizer = random.SystemRandom() # <2>
self._ite... |
leequant761/Fluent-python | 08-obj-ref/bus.py |
"""
>>> import copy
>>> bus1 = Bus(['Alice', 'Bill', 'Claire', 'David'])
>>> bus2 = copy.copy(bus1)
>>> bus3 = copy.deepcopy(bus1)
>>> bus1.drop('Bill')
>>> bus2.passengers
['Alice', 'Claire', 'David']
>>> bus3.passengers
['Alice', 'Bill', 'Claire', 'David']
"""
# BEGIN BUS_CLASS
class Bus:
def __init__(self, p... |
leequant761/Fluent-python | 14-it-generator/sentence_gen.py | <reponame>leequant761/Fluent-python<filename>14-it-generator/sentence_gen.py
"""
Sentence: iterate over words using a generator function
"""
import re
import reprlib
RE_WORD = re.compile(r'\w+')
class Sentence:
def __init__(self, text):
self.text = text
self.words = RE_WORD.findall(text)
d... |
leequant761/Fluent-python | 16-coroutine/practice.py | def simple_coroutine():
print('-> coroutine started')
x1 = yield
print('-> coroutine received:', x1)
x2 = yield
print('-> coroutine received:', x2)
from inspect import getgeneratorstate
my_coro = simple_coroutine()
getgeneratorstate(my_coro) # GEN_CREATED
next(my_coro)
getgeneratorstate(my_coro) # ... |
leequant761/Fluent-python | 01-data-model/frenchdeck.py | <reponame>leequant761/Fluent-python<gh_stars>0
import collections
# 네임드 튜플이란?
# a = Card(10, 20)
# a.suit
# 코드의 가독성을 위해서 튜플을 대신한다. 하지만 딕셔너리를 사용하지 않는 이유는
# 불변성과 메모리 낭비를 줄이기 위해서이다. 만약에 사전으로 바꾸고 싶다면 a._asdict()
# 필드명과 클래스명을 추가한 튜플의 서브클래스를 생성하는 팩토리 함수; 디버깅할 떄 유용
Card = collections.namedtuple('Card', ['rank', 'suit'])
cla... |
leequant761/Fluent-python | 03-dict-set/strkeydict.py | """StrKeyDict always converts non-string keys to `str`
Test for initializer: keys are converted to `str`.
>>> d = StrKeyDict([(2, 'two'), ('4', 'four')])
>>> sorted(d.keys())
['2', '4']
Tests for item retrieval using `d[key]` notation::
>>> d['2']
'two'
>>> d[4]
'four'
>>> d[1]
T... |
leequant761/Fluent-python | 07-closure-deco/clockdeco_demo2.py | import time
from clockdeco2 import clock
@clock
def snooze(seconds):
time.sleep(seconds)
@clock
def factorial(n):
return 1 if n < 2 else n*factorial(n-1)
if __name__=='__main__':
print('*' * 40, 'Calling snooze(.123)')
snooze(.123)
print('*' * 40, 'Calling factorial(6)')
print('8! =', factori... |
leequant761/Fluent-python | 13-op-overloading/bingoaddable.py | <reponame>leequant761/Fluent-python
"""
======================
AddableBingoCage tests
======================
Tests for __add__:
# BEGIN ADDABLE_BINGO_ADD_DEMO
>>> vowels = 'AEIOU'
>>> globe = AddableBingoCage(vowels) # <1>
>>> globe.inspect()
('A', 'E', 'I', 'O', 'U')
>>> globe.pick() in vowels... |
leequant761/Fluent-python | 14-it-generator/psl_generators.py | # 필터링 제너레이터 함수의 예
import itertools
def vowel(c):
return c.lower() in 'aeiou'
list(filter(vowel, 'Aardvark')) # ['A', 'a', 'a']
list(itertools.filterfalse(vowel, 'Aardvark')) # ['r', 'd', 'v', 'r', 'k']
list(itertools.takewhile(vowel, 'Aardvark')) # ['A', 'a'] ; 거짓이 등장하면 생성안함
list(itertools.dropwhile(vowel, 'Aardv... |
leequant761/Fluent-python | 07-closure-deco/generic.py | <filename>07-closure-deco/generic.py<gh_stars>0
r"""
htmlize(): generic function example
# BEGIN HTMLIZE_DEMO
>>> htmlize({1, 2, 3}) # <1>
'<pre>{1, 2, 3}</pre>'
>>> htmlize(abs)
'<pre><built-in function abs></pre>'
>>> htmlize('Heimlich & Co.\n- a game') # <2> str객체는 <p>로
'<p>Heimlich & Co.<br>\n- a game... |
leequant761/Fluent-python | 19-dyn-attr-prop/bulkfood/bulkfood_v2b.py | # BEGIN LINEITEM_V2B
class LineItem:
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
def get_weight(self): # <1> 지극히 평범한 게터
return self.__wei... |
leequant761/Fluent-python | 19-dyn-attr-prop/oscon/explore1.py | <reponame>leequant761/Fluent-python
from collections import abc
import keyword
class FrozenJSON:
"""A read-only façade for navigating a JSON-like object
using attribute notation
"""
# BEGIN EXPLORE1
def __init__(self, mapping):
self.__data = {}
for key, value in mapping.items():
... |
leequant761/Fluent-python | 01-data-model/vector2d.py | from math import hypot
class Vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return 'Vector(%r, %r)' % (self.x, self.y)
# return 'Vector({0}, {1})'.format(self.x, self.y)
def __abs__(self):
return hypot(self.x, self.y)
def __bo... |
leequant761/Fluent-python | 12-inheritance/diamond.py | class A:
def ping(self):
print('Aping:', self)
class B(A):
def pong(self):
print('Bpong:', self)
class C(A):
def pong(self):
print('CPONG:', self)
class D(B, C):
def ping(self):
A.ping(self) # super().ping()과 동일
print('Dpost-ping:', self)
def pingpong(... |
leequant761/Fluent-python | 05-1class-func/ftn_is_object.py | # 1. 일급객체
def factorial(n):
'''return n!'''
return 1 if n < 1 else n * factorial(n-1)
factorial(42)
# 속성이 있는 것으로 보아 함수는 function class의 객체이다.
factorial.__doc__ # 'return n!'
type(factorial) # <class 'function'>
# 변수로 참조하기
fact = factorial
fact
# 다른 함수의 인수로 전달하기
list(map(factorial, range(11)))
# >>> [1, 1... |
leequant761/Fluent-python | 07-closure-deco/clockdeco_demo.py | <reponame>leequant761/Fluent-python
# clockdeco_demo.py
import time
from clockdeco import clock
@clock
def snooze(seconds):
time.sleep(seconds)
@clock
def factorial(n):
return 1 if n < 2 else n*factorial(n-1)
if __name__=='__main__':
print('*' * 40, 'Calling snooze(.123)')
snooze(.123)
print('*'... |
leequant761/Fluent-python | 08-obj-ref/cheese.py | <filename>08-obj-ref/cheese.py
# BEGIN CHEESE_CLASS
class Cheese:
def __init__(self, kind):
self.kind = kind
def __repr__(self):
return 'Cheese(%r)' % self.kind
# END CHEESE_CLASS
import weakref
stock = weakref.WeakValueDictionary() # 참조 아이템이 사라지면 해당 키도 사라지는 가변매핑
catalog = [Cheese('Red Leices... |
leequant761/Fluent-python | 15-context-mngr/context_manager.py | <filename>15-context-mngr/context_manager.py
with open('mirror.py') as fp:
src = fp.read(60)
len(src) # 60
fp # <_io.TextIOWrapper name='mirror.py' mode='r' encoding='cp949'>
fp.closed, fp.encoding # (True, 'cp949')
fp.read(60) # 더이상 파일 입출력은 할 수 없다
from mirror import LookingGlass
with LookingGlass() as what:
... |
leequant761/Fluent-python | 19-dyn-attr-prop/oscon/schedule1.py | <reponame>leequant761/Fluent-python<filename>19-dyn-attr-prop/oscon/schedule1.py
# BEGIN SCHEDULE1 딕셔너리 순회하는 것을 생각하면 된다
import warnings
import osconfeed # <1>
DB_NAME = 'data/schedule1_db'
CONFERENCE = 'conference.115'
class Record:
def __init__(self, **kwargs):
self.__dict__.update(kwargs) # <2> 키워드 ... |
leequant761/Fluent-python | 08-obj-ref/haunted_bus.py | # BEGIN HAUNTED_BUS_CLASS
class HauntedBus:
"""A bus model haunted by ghost passengers"""
def __init__(self, passengers=[]): # <1>mutable
self.passengers = passengers # <2>mutable
def pick(self, name):
self.passengers.append(name) # <3>mutable한 객체 변경
def drop(self, name):
s... |
leequant761/Fluent-python | 02-array-seq/array.py | # 1. 커다란 실수 배열의 생성 저장 로딩
from array import array
from random import random
floats = array('d', (random() for i in range(10**7))) # 실수 타입의 배열
floats[-1]
# binary 파일에 배열을 저장; array.tofile()
fp = open('floats.bin', 'wb') # write and binary
floats.tofile(fp)
fp.close()
# binary 파일에서 배열을 로딩; array.fromfile()
floats2 = ar... |
leequant761/Fluent-python | 04-text-byte/default_encodings.py | import sys, locale
expressions = """
locale.getpreferredencoding()
type(my_file)
my_file.encoding
sys.stdout.isatty()
sys.stdout.encoding
sys.stdin.isatty()
sys.stdin.encoding
sys.stderr.isatty()
sys.stderr.encoding
sys.getdefaultencoding(... |
leequant761/Fluent-python | 17-futures/tqdm_practice.py | <gh_stars>0
import time
from tqdm import tqdm
for i in tqdm(range(10)):
time.sleep(0.1) |
leequant761/Fluent-python | 05-1class-func/clip.py | <gh_stars>0
"""
>>> clip('banana ', 6)
'banana'
>>> clip('banana ', 7)
'banana'
>>> clip('banana ', 5)
'banana'
>>> clip('banana split', 6)
'banana'
>>> clip('banana split', 7)
'banana'
>>> clip('banana split', 10)
'banana'
>>> clip('banana split', 11)
'banana'
... |
leequant761/Fluent-python | 19-dyn-attr-prop/bulkfood/bulkfood_v2prop.py | <reponame>leequant761/Fluent-python
# BEGIN LINEITEM_V2_PROP_FACTORY_FUNCTION
def quantity(storage_name): # <1> 이 argument가 프로퍼티를 어디에 저장할 지 결정
def qty_getter(instance): # <2> instance는 LineItem 객체를 가르킴
return instance.__dict__[storage_name] # <3> 그 객체에서 attribute를 직접 가져온다
def qty_setter(instance, v... |
leequant761/Fluent-python | 20-descriptor/bulkfood/bulkfood_v3.py | <filename>20-descriptor/bulkfood/bulkfood_v3.py<gh_stars>0
# BEGIN LINEITEM_V3
class Quantity: # <1> 디스크립터 프로토콜
def __init__(self, storage_name):
self.storage_name = storage_name # <2> 관리 대상 객체(LineItem)에서 값을 보관할 곳
def __set__(self, instance, value): # <3> instance에는 LineItem 객체가 들어갈 것이고 value는 할당 ... |
leequant761/Fluent-python | 02-array-seq/metro_lat_long.py | <gh_stars>0
# 튜플 언패킹하기
temp = [(idx, n) for n, idx in enumerate(list('abcde'))]
result = []
for _, n in temp:
result.append(n)
# 튜플 언패킹하기
a, b = (10, 20)
# 초과 항목을 잡기 위한 병렬 할당
a, b, *rest = range(5)
rest # [2, 3, 4]
# 내포된 튜플 언패킹하기 - 예시
metro_areas = [
('Tokyo', 'JP', 36.933, (35.689722, 139.691667)), # <1>
... |
leequant761/Fluent-python | 15-context-mngr/mirror_gen.py | <reponame>leequant761/Fluent-python
"""
A "mirroring" ``stdout`` context manager.
While active, the context manager reverses text output to
``stdout``::
# BEGIN MIRROR_GEN_DEMO_1
>>> from mirror_gen import looking_glass
>>> with looking_glass() as what: # <1>
... print('Alice, Kitty and Snowdrop')
... |
leequant761/Fluent-python | 07-closure-deco/fibo_demo_lru.py | import functools
from clockdeco import clock
@functools.lru_cache() # <1> argument(optional) 받기 때문에 일반 함수처럼 데코
@clock # <2>
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-2) + fibonacci(n-1)
if __name__=='__main__':
print(fibonacci(6))
# functools.lru_cache(maxsize=128, typed=False)
# ... |
jonathanadams/Home-Assistant-Configuration | custom_components/alexa_media/const.py | <filename>custom_components/alexa_media/const.py<gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
"""
Support to interface with Alexa Devices.
For more details about this platform, please refer to the documentation at
https://community.home-assistant.io/t/echo-device... |
jaymzh/collectd-apachelog | apachelog.py | #!/usr/bin/env python
""" A collectd-python plugin for retrieving
metrics from Apache access log file. """
import sys
import subprocess
from os import access, R_OK
from threading import Thread
from datetime import datetime
from Queue import Queue, Empty
from apache_log_parser import make_parser, LineDoesntMatchEx... |
linlabcode/pipeline | crc/CRC_chip_delta_degree.py | #!/usr/bin/python
'''
The MIT License (MIT)
Copyright (c) 2018 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, ... |
linlabcode/pipeline | enhancerPromoter.py | #!/usr/bin/python
'''
The MIT License (MIT)
Copyright (c) 2016 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, m... |
linlabcode/pipeline | process_chiprx_sam.py | <filename>process_chiprx_sam.py
#!/usr/bin/python
import sys
import os
import argparse
import string
import utils
def split_sam(suffix,samfile,header1,header2,outfile1,outfile2):
'''
splits the sam by suffix
cats on the header
'''
print(suffix)
temp_outfile1 = outfile1+'.temp'
temp_outfil... |
linlabcode/pipeline | crc/CRC_wrapper.py |
#!/usr/bin/python
'''
The MIT License (MIT)
Copyright (c) 2016 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, ... |
linlabcode/pipeline | ROSE2_main.py | #!/usr/bin/env python
'''
PROGRAM TO STITCH TOGETHER REGIONS TO FORM ENHANCERS, MAP READ DENSITY TO STITCHED REGIONS,
AND RANK ENHANCERS BY READ DENSITY TO DISCOVER SUPER-ENHANCERS
May2, 2014
VERSION 0.2
CONTACT: <EMAIL>
'''
from __future__ import absolute_import # , division, print_function, unicode_literals
import ... |
linlabcode/pipeline | pipeline_template_new.py | <filename>pipeline_template_new.py
#!/usr/bin/python
'''
The MIT License (MIT)
Copyright (c) 2018 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without l... |
linlabcode/pipeline | dynamicEnhancer_meta.py | #!/usr/bin/python
#131108_dynamicEnhancer.py
#131108
#<NAME>
#Description:
'''
pipeline to run dynamic enhancer analysis
The MIT License (MIT)
Copyright (c) 2013 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software... |
linlabcode/pipeline | crc/CRC3.py | #!/usr/bin/env python
######################
#
# Core Regulatory Circuits
# Young and Bradner Labs
# Version 1.0
# 140724
#
######################
######################
# Dependencies
######################
import os
import sys
import string
whereAmI = os.path.dirname(os.path.realpath(__file__)... |
linlabcode/pipeline | pipeline_template.py | <filename>pipeline_template.py<gh_stars>1-10
#!/usr/bin/python
#pipeline_template.py
'''
The MIT License (MIT)
Copyright (c) 2016 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without r... |
GabrielTheophilo/CovidApiScript | filewrite.py | <filename>filewrite.py<gh_stars>1-10
from datetime import date
from parse import ParseCsv
import os
import os.path
class FolderWrite:
def FolderWrite():
username = os.getlogin()
try:
os.mkdir(f'C:\\Users\\{username}\\Desktop\\CovidApiScript')
return 0
ex... |
GabrielTheophilo/CovidApiScript | url.py | <filename>url.py
from apikey import ApiKey
class UrlGeneral(ApiKey):
url = "https://covid-193.p.rapidapi.com/statistics"
headers = {
'x-rapidapi-key': f'{ApiKey.ApiKey}',
'x-rapidapi-host': "covid-193.p.rapidapi.com"
}
class UrlHistorical(ApiKey):
url = "https://covid-193.p.rapidapi... |
GabrielTheophilo/CovidApiScript | content.py | <gh_stars>1-10
from parse import Parse
from filewrite import FileWrite
class Content:
def Content(wdata):
i = 0
Pais = str(input("Insira o nome do país que precisa procurar. Obs:. Na grafia inglesa e primeira letra maíuscula: "))
if wdata["results"] != 0:
for x in wdata["response... |
GabrielTheophilo/CovidApiScript | apikey.py | <reponame>GabrielTheophilo/CovidApiScript
class ApiKey:
ApiKey = ""
|
GabrielTheophilo/CovidApiScript | request.py | <gh_stars>1-10
import requests
import json
class Request:
def __init__(url, headers):
response = requests.request("GET", url, headers=headers)
json_data = response.json()
data = json.dumps(json_data, indent=4)
return data
class RequestHistorical:
def __init__(url, headers, querys... |
GabrielTheophilo/CovidApiScript | parse.py | <reponame>GabrielTheophilo/CovidApiScript
class Parse:
def ParseCountryData(wdata, i):
a = (wdata["response"][i]["continent"])
b = (wdata["response"][i]["country"])
c = (wdata["response"][i]["population"])
return (f'\nContinente: {a}\nPaís: {b}\nPopulação: {c}')
def ParseFirstDa... |
GabrielTheophilo/CovidApiScript | printmenu.py | import menuoptions
class PrintMenu:
def __init__():
print(menuoptions.menufetch())
print('Covid Api Serch - Este programa busca dados atualizados sobre o avanço do coronavírus')
print('VERSÃO ALPHA')
print('*caso encontre algum bug, por favor abra um Issue no github*')
class Choice... |
GabrielTheophilo/CovidApiScript | covidapisearch.py | import json
from filewrite import FileWrite
from content import Content
from url import *
from request import *
from printmenu import *
if __name__=="__main__":
PrintMenu.__init__()
ChoiceMenu.__init__()
escolha_dados = str(input("---->").lower())
if escolha_dados == "dados históricos" or escolha_dado... |
BarisSari/airflow-snowflake-to-s3 | dag.py | from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python_operator import PythonOperator
from helper import fetch_data_from_snowflake, upload_file_to_s3_with_hook
default_args = {
"owner": "baris",
"start_date": dat... |
BarisSari/airflow-snowflake-to-s3 | user_roles_dag.py | import os
import logging
import datetime
from datetime import timedelta
from airflow import DAG
# from airflow.models import Variable
from airflow.hooks.S3_hook import S3Hook
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python_operator import PythonOperator
from users_roles impor... |
BarisSari/airflow-snowflake-to-s3 | users_roles.py | <gh_stars>0
import os
from airflow.contrib.hooks.snowflake_hook import SnowflakeHook
from airflow.hooks.S3_hook import S3Hook
# import tempfile
# TMP_DIRECTORY = tempfile.TemporaryDirectory()
# ROLES_PATH = os.path.join(TMP_DIRECTORY.name, "snowflake_roles.csv")
# ROLE_GRANTS_PATH = os.path.join(TMP_DIRECTORY.name, "... |
security-geeks/wycheproof | tools/local_repository_defs.bzl | <reponame>security-geeks/wycheproof
"""Add test targets for using a local jar.
"""
_bouncycastle_jar_rule = """
java_import(
name = "bouncycastle_jar",
jars = ["bouncycastle.jar"],
visibility = ["//visibility:public"],
)
"""
_accp_jar_rule = """
java_import(
name = "accp_jar",
jars = ["accp.jar"... |
mrinal-sys/greyatom-python-for-data-science | STUDENT-MANAGEMENT-SYSTEM/code.py | # --------------
class_1 = [ '<NAME>', '<NAME>', '<NAME>', '<NAME>']
class_2 = [ '<NAME>', '<NAME>', '<NAME>']
new_class = class_1 + class_2
print(new_class)
new_class.append('<NAME>')
print(new_class)
new_class.remove('<NAME>')
print(new_class)
courses = {'Math' : 65, 'English' : 70, 'History' : 80, 'French' :... |
marblestation/myADSPipeline | myadsp/tests/test_app.py | import unittest
import os
import httpretty
from sqlalchemy.sql.expression import and_
from datetime import timedelta
import adsputils as utils
from myadsp import app
from myadsp.models import AuthorInfo, Results, Base
class TestmyADSCelery(unittest.TestCase):
"""
Tests the application's methods
"""
... |
marblestation/myADSPipeline | alembic/versions/782cd22eccdf_initial.py | <filename>alembic/versions/782cd22eccdf_initial.py
"""initial
Revision ID: <KEY>
Revises:
Create Date: 2019-08-06 14:29:16.421330
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy import Column, Integer, ARRAY, String, Text
from adsputils import get_date, UTCDateTime
# revision identifiers, used b... |
marblestation/myADSPipeline | myadsp/tests/test_utils.py | <reponame>marblestation/myADSPipeline<filename>myadsp/tests/test_utils.py
import unittest
import os
import httpretty
from mock import patch
import urllib
import json
import datetime
import adsputils
from myadsp import app, utils
from myadsp.models import Base
from ..emails import myADSTemplate
payload = [{'name': 'Qu... |
marblestation/myADSPipeline | alembic/versions/07ec7ca54c2f_expand_results_table.py | <filename>alembic/versions/07ec7ca54c2f_expand_results_table.py
"""expand results table
Revision ID: 07ec7ca54c2f
Revises: <KEY>
Create Date: 2020-02-20 12:18:49.152203
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '07ec7ca54c2f'
down_revision = '<KEY>'
branc... |
marblestation/myADSPipeline | alembic/versions/4d32cf06f0dd_qid_type_fix.py | <filename>alembic/versions/4d32cf06f0dd_qid_type_fix.py
"""qid type fix
Revision ID: 4d32cf06f0dd
Revises: <KEY>
Create Date: 2020-01-31 13:45:11.886780
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '4d32cf06f0dd'
do... |
laserkelvin/Spectron3000 | spectron3000/src/__init__.py | from . import classes
from . import plotting
from . import utils |
laserkelvin/Spectron3000 | spectron3000/__init__.py | from spectron3000.src import classes, utils
|
laserkelvin/Spectron3000 | spectron3000/src/classes.py | <filename>spectron3000/src/classes.py
import base64
import io
import os
from dataclasses import dataclass
import numpy as np
import pandas as pd
from src import utils
@dataclass
class Spectrum:
x: np.array
y: np.array
comment: str = "Observation"
@classmethod
def from_upload(cls, contents, fi... |
laserkelvin/Spectron3000 | spectron3000/app.py | <reponame>laserkelvin/Spectron3000
import numpy as np
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table as dt
from dash.exceptions import PreventUpdate
from src import classes
from src import plotting
external_styl... |
laserkelvin/Spectron3000 | setup.py | from setuptools import setup
setup(
name='Spectron3000',
version='0.1',
packages=['spectron3000'],
url='https://github.com/laserkelvin/Spectron3000',
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
description='Dash application for viewing astronomical spectra'
)
|
laserkelvin/Spectron3000 | spectron3000/src/utils.py | <gh_stars>0
""" units.py
Routines for performing unit conversions and quantities
that are often used in spectroscopy.
"""
import numpy as np
from scipy import constants
kbcm = constants.value("Boltzmann constant in inverse meters per kelvin") / 100.
avo = constants.Avogadro
eha = constants.value("Hartree e... |
laserkelvin/Spectron3000 | spectron3000/src/plotting.py |
from plotly import graph_objs as go
def init_layout():
"""
Initializes a layout dict for Plotly figures.
:return:
"""
layout = {
"xaxis": {
"title": "Frequency (MHz)",
"tickformat": ".,"
},
"yaxis": {
"title": "Flux (Jy/beam)",
... |
Fzx-fire/AlienInvasion | Settings.py | class Setting:
"""存储设置"""
def __init__(self):
"""初始化游戏静态设置"""
self.screen_width = 1200
self.screen_height = 800
# 设置背景色
self.bg_color = (230, 230, 230)
self.ship_limit=3
self.bullet_width=3
self.bullet_height=15
self.bullet_color=(60,60,... |
Fzx-fire/AlienInvasion | Ship.py | <reponame>Fzx-fire/AlienInvasion
import pygame
from pygame.sprite import Sprite
class Ships(Sprite):
"""管理飞船的类"""
def __init__(self,ai_game):
"""初始化飞船并设置初始位置"""
super().__init__()
self.screen=ai_game.screen
self.settings=ai_game.settings
self.screen_rect=ai_game.screen.... |
Fzx-fire/AlienInvasion | alien_invasion.py | <reponame>Fzx-fire/AlienInvasion
import sys
import pygame
# 设置类
from Settings import Setting
# 飞船
from Ship import Ships
# 子弹
from Bullet import Bullets
# 外星人
from alien import Alien
from time import sleep
from game_status import GameStatus
from button import Button
from scoreboard import Scoreboard
class AlienInvasi... |
Fzx-fire/AlienInvasion | game_status.py | class GameStatus:
"""跟踪游戏的统计信息"""
def __init__(self,ai_game):
self.settings=ai_game.settings
self.reset_stats()
self.game_active=False
self.high_score=0
self.level=1
def reset_stats(self):
self.ships_left=self.settings.ship_limit
self.score=0 |
Fzx-fire/AlienInvasion | scoreboard.py | import pygame.font
from pygame.sprite import Group
from Ship import Ships
class Scoreboard:
"""显示得分信息"""
def __init__(self,ai_game):
self.ai_game=ai_game
self.screen=ai_game.screen
self.screen_rect=self.screen.get_rect()
self.settings=ai_game.settings
self.stats=ai_game... |
Fzx-fire/AlienInvasion | button.py | <filename>button.py
import pygame.font
class Button:
def __init__(self,ai_game,msg):
self.screen=ai_game.screen
self.screen_rect=self.screen.get_rect()
# 设置按钮尺寸和属性
self.width,self.height=200,50
self.button_color=(0,255,0)
self.text_color=(255,255,255)
self... |
Fzx-fire/AlienInvasion | Bullet.py | import pygame
from pygame.sprite import Sprite
class Bullets(Sprite):
"""管理发射的子弹"""
def __init__(self,ai_game):
super().__init__()
self.screen=ai_game.screen
self.settings=ai_game.settings
self.color=self.settings.bullet_color
# 在(0,0)处创建子弹,在设置正确的位置
self.rect=py... |
synergia/SCS | server/__init__.py | import os
from flask import Flask
from flask_socketio import SocketIO
from flask import render_template
import pins
from gevent import monkey
import log
monkey.patch_all()
client_path = os.path.abspath('client')
app = Flask(__name__, template_folder=client_path, static_folder=client_path)
app.config['SECRET_KEY'] = ... |
synergia/SCS | install/install_system.py | #!/usr/bin/env python
import subprocess
def main():
# Install system dependencies
subprocess.call(["apt-get", "update"])
subprocess.call(["apt-get", "-y", "upgrade"])
subprocess.call(["apt-get", "-y", "install", "python-dev"])
subprocess.call(["apt-get", "-y", "install", "python-pip"])
# subp... |
synergia/SCS | server/log.py | # Create a logger object.
import logging
import coloredlogs
import os
os.environ['COLOREDLOGS_LOG_FORMAT'] ='%(asctime)s.%(msecs)03d %(name)s - %(message)s'
os.environ['COLOREDLOGS_DATE_FORMAT'] ='%H%M%S'
logger = logging.getLogger("SCSystem")
logging.getLogger("engineio").setLevel(logging.WARNING)
logging.getLogger(... |
synergia/SCS | server/pins/read.py | <filename>server/pins/read.py
from server.log import logger
class Read():
def read_config(self):
res = []
pins = {'pins': []}
arch = {'architecture': self.architecture}
logger.info('Read: assembling response: config')
for pin_num, pin_values in self.pins.items():
... |
synergia/SCS | server/sockets.py | <gh_stars>0
from flask_socketio import emit
from server import socketio
from pins import PIN_MANAGER
from server.log import logger
@socketio.on('connection')
def connection():
pass
@socketio.on('config')
def config():
response = PIN_MANAGER.read_config()
emit('config', response)
@socketio.on('pin:list')... |
synergia/SCS | server/pins/initialize.py | import json
import pigpio
from server.log import logger
PINS_JSON = './config/pins.json'
'''
Parsing JSON, saving architecture value to variable, setup pins
http://stackoverflow.com/a/17166144/1589989
'''
class Initialize():
def load_json(self):
try:
with open(PINS_JSON) as file_data:
... |
synergia/SCS | server/pins/__init__.py | # http://abyz.co.uk/rpi/pigpio/python.html#write
import pigpio
from config_loader import ConfigLoader
from read import Read
from update import Update
from setup import Setup
from initialize import Initialize
from server.log import logger
class PinManager(object, ConfigLoader, Read, Update, Setup, Initialize):
def... |
synergia/SCS | server/pins/update.py | from server.log import logger
class Update():
def update_value(self, num, value):
try:
logger.info('Trying to set value', num, value)
# Updating value in object
self.pins[num]['value'] = value
pin_num = int(num)
self.gpio.set_mode(pin_num, pigpio... |
denis-ftc-denisov/rpi_dht_modbus | read.py | <filename>read.py
#!/usr/bin/env python3
import Adafruit_DHT
import json
import time
from collections import defaultdict
from threading import Thread
from pymodbus.constants import Endian
from pymodbus.server.sync import StartTcpServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore impo... |
sye8/dicom2png | dicom2png.py | """
Extracts the pixel arrays from dicom files
in a directory and save those as 16-bit png.
The pixel values are rescaled using the
`RescaleSlope` and `RescaleIntercept`
stored in the DICOM file.
By default, the PNG will be named using
DICOM `InstanceNumber`.
The original filename can be optionally
chosen to be appen... |
iDebugAll/toolz | traceroute_by_routing_tables/traceroute_by_routing_tables.py |
import os
import re
import pytricia
from time import time
# Path to directory with routing table files.
# Each routing table MUST be in a separate .txt file.
RT_DIRECTORY = "./routing_tables"
# RegEx template string for IPv4 address matching.
REGEXP_IPv4_STR = (
r'((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.'
... |
sophiamarani/py-telegram-bot-alcohol | bot.py | <reponame>sophiamarani/py-telegram-bot-alcohol<filename>bot.py
#codes from pythonanywhere
import telebot
import time
bot_token = 'bot_api_token' #your Telegram Bot API Token generated by @BotFather
bot = telebot.TeleBot(token=bot_token)
@bot.message_handler(commands=['start']) #answer if command is start
... |
azarshab-saeed/docker-flask-postgres | app/app.py | import time
from flask import Flask, render_template, flash, redirect, request, url_for
from flask_sqlalchemy import SQLAlchemy
DBUSER = 'marco'
DBPASS = '<PASSWORD>'
DBHOST = 'db'
DBPORT = '5432'
DBNAME = 'testdb'
app = Flask(__name__)
# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'
app.conf... |
bow/biostuff | fastqc/pyfastqc.py | """
Python library for parsing FastQC results.
Provides methods and classes for parsing a FastQC run results.
Tested with FastQC 0.9.5 output, should work with other versions as well.
Requirements:
* Python == 2.7.x
Copyright (c) 2013 <NAME> <<EMAIL>>
Copyright (c) 2013 LUMC Sequencing Analysis Support Core <<... |
bow/biostuff | misc_scripts/analyze_dna_rna_calls.py | #!/usr/bin/env python2.7
"""
Allelic expression finder.
This script compares calls from at least two VCF files: one from DNA-seq and
the other from RNA-seq to find candidate positions where expression is
monoallelic.
Monoallelicly-expressed regions are deduced from positions where the RNA-seq
variant is homozygous ... |
bow/biostuff | fasta/fa_build_deepsage_lib.py | #!/usr/bin/env python
"""
Build SAGE tag library from Ensembl genes for mapping with Bowtie 1.0.0.
This script creates a FASTA file containing all SAGE tags from all Ensembl
transcript (ENST) records. Identical tags from the same gene (occurs when a
gene has multiple isoforms with the same 3'-most tag) are collapsed... |
bow/biostuff | fastq/fq_trim_ns.py | #!/usr/bin/env python
"""
Quick and dirty script for removing N's from FASTQ records.
By default only Ns at the 3' ends are removed. To remove Ns
in the 5', use the --remove-5prime-n flag.
Requirements:
* Python == 2.7.x
* Biopython >= 1.63
Author: <EMAIL>
"""
import argparse
import re
from Bio import Se... |
bow/biostuff | bed/bed_squish.py | #!/usr/bin/env python2
"""
Overlapping regions removal in a single BED file.
The script will adjust feature coordinates so that no overlaps are present. If
a feature is enveloped entirely by another feature, the smaller feature will be
removed and the enveloping feature split into two.
Input BED files must be posit... |
bow/biostuff | bam/bam_split_by_ref.py | #!/usr/bin/env python2
"""
Spliting a single BAM file into multiple BAM files based on the reference.
For a given BAM file, this script will produce multiple BAM files, each
containing reads mapped to a single record in the BAM reference. For example, a
BAM file from a full human genome sequencing will be split into... |
bow/biostuff | gtf/gtf_ucsc_geneid_fix.py | <reponame>bow/biostuff<filename>gtf/gtf_ucsc_geneid_fix.py
#!/usr/bin/env python2.7
"""
Updates 'gene_id' entries in a GTF file downloaded from UCSC Table Browser
to have gene IDs as values instead of transcript IDs.
Two types annotation sources can be used to replace the 'gene_id' values:
1. Local annotation sourc... |
EE559DeepLearningEPFL/Project2 | neural_network.py | import torch
from layer_module import Module
class NeuralNet(Module):
def __init__(self,
layer_type,
if_batchnorm=None,
activation_type=None,
params_shape=None,
bn_param={'eps':1e-5, 'momentum':0.9},
conv... |
EE559DeepLearningEPFL/Project2 | test.py | import torch
import math
from layer_module import Module
from neural_network import NeuralNet
import matplotlib.pyplot as plt
# device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
device = 'cpu'
dtype = torch.float32
print("-------------------------------------------------------")
print("----------- Single laye... |
EE559DeepLearningEPFL/Project2 | layer_module.py | <filename>layer_module.py
import torch
import math
torch.set_grad_enabled(False)
class Module(object):
# constructor
def __init__(self,
layer_type,
if_batchnorm=None,
activation_type=None,
params_shape=None,
bn_param... |
hbergen/minimal-python-package | setup.py | <filename>setup.py
from setuptools import setup
setup(name='minimum-python-package',
version='0.1',
description='Hodor',
url='https://github.com/hbergen/minimal-python-package',
author='hbergen',
author_email='<EMAIL>',
license='MIT',
packages=['winterfell'],
zip_safe=Fa... |
hbergen/minimal-python-package | winterfell/hodor.py | <reponame>hbergen/minimal-python-package<filename>winterfell/hodor.py
__all__ = ["speak", "fight", "chatter"]
def speak():
""" A typical Hodor response
"""
return ("Hodor")
def fight():
""" Hodor gets angry
"""
return ("Hodor!!!!!!!!!@$^&&J##HODOR!!!!!!!!!")
def chatter(nwords):
""" H... |
alukard6942/mandelbrodSet | mandlebrod.py | #!bin/py
import numpy as np
import cv2 as cv2
# this is a python
height, width = 500, 500
img = np.zeros((height+1, width+1, 3), np.uint8)
img[:,:] = [0,0,0]
zoom = 2.0
rNum = -1
iNum = .0
def main():
# redner margin
render()
cv2.imshow("image", img)
cv2.namedWindow('image')
cv2.setMouseCallback('image',... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.