repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
EdwinGuo/docker-airflow
integrationtests/test_integration_simple_pipe.py
from airflow.api.common.experimental import trigger_dag as trigger from airflow.api.common.experimental import delete_dag as delete from airflow.api.common.experimental.get_dag_run_state import get_dag_run_state from airflow.utils import timezone from airflow.exceptions import AirflowException from airflow.utils.db imp...
EdwinGuo/docker-airflow
dags/simple_pipe.py
from airflow import DAG from airflow.operators.bash_operator import BashOperator from airflow.operators.python_operator import PythonOperator from datetime import datetime, timedelta default_args = { "owner": "airflow", "depends_on_past": False, "start_date": datetime(2020, 1, 1), "email": ["<EMAIL>"]...
EdwinGuo/docker-airflow
unittests/test_dag_validation.py
<reponame>EdwinGuo/docker-airflow import pytest from airflow.models import DagBag class TestDagValidation: LOAD_SECOND_THRESHOLD = 2 REQUIRED_EMAIL = "<EMAIL>" EXPECTED_NUMBER_OF_DAGS = 1 def test_import_dags(self, dagbag): """ Verify that Airflow is able to import all DAGs ...
Tramac/torchscope
setup.py
from setuptools import setup setup( name="torchscope", version="0.1.0", description="Model scope in PyTorch", url="https://github.com/Tramac/pytorchscope", author="Tramac", packages=["torchscope"], )
Tramac/torchscope
torchscope/scope.py
<filename>torchscope/scope.py import torch import torch.nn as nn import numpy as np from collections import OrderedDict from .helper import compute_madd, compute_flops __all__ = ["scope"] class ModelSummary(object): def __init__(self, model, input_size, batch_size=-1, device='cpu'): super(ModelSummary, ...
Tramac/torchscope
torchscope/helper.py
<filename>torchscope/helper.py<gh_stars>100-1000 import numpy as np import torch.nn as nn __all__ = ["compute_flops", "compute_madd"] def compute_flops(module, inp, out): if isinstance(module, nn.Conv2d): return compute_Conv2d_flops(module, inp, out) // 2 elif isinstance(module, nn.BatchNorm2d): ...
mihirp1998/Steganography
LSBSteg.py
<reponame>mihirp1998/Steganography<gh_stars>1-10 #!/usr/bin/env python # coding:UTF-8 """LSBSteg.py Usage: LSBSteg.py encode -i <input> -o <output> -f <file> LSBSteg.py decode -i <input> -o <output> Options: -h, --help Show this help --version Show the version -f,--file=<file>...
mihirp1998/Steganography
run.py
<reponame>mihirp1998/Steganography import cv2 from LSBSteg import LSBSteg def forText(): #encoding file = open('abc.txt','rb') val = '' val = val + file.read() steg = LSBSteg(cv2.imread("download.jpeg")) img_encoded = steg.encode_text(val) cv2.imwrite("my_new_image.png", img_encoded) #decoding im = cv2.imread...
ROYALBEFF/aaaaaa_arcade_game
aaaaaa/GameState.py
<gh_stars>0 import csv import os class GameState: def __init__(self): """ Initialize game state variables. """ self.__quit_game = False # score parameters self.__bonus = 20 self.__multiplier = 1 self.__score = 0 self.__nick = 'AAA' ...
ROYALBEFF/aaaaaa_arcade_game
aaaaaa/Shield.py
from aaaaaa.Powerup import Powerup class Shield(Powerup): def __init__(self): super().__init__((255, 200, 10, 255), 250)
ROYALBEFF/aaaaaa_arcade_game
aaaaaa/CollisionHandler.py
<reponame>ROYALBEFF/aaaaaa_arcade_game from aaaaaa.OneUP import OneUP from aaaaaa.Multiplier import Multiplier from aaaaaa.Shield import Shield from aaaaaa.Bomb import Bomb class CollisionHandler: def __init__(self): pass @staticmethod def check_player_obstacle_collision(player, obstacle, state,...
ROYALBEFF/aaaaaa_arcade_game
aaaaaa/Player.py
import pkg_resources import pygame class Player: def __init__(self, x, y): """ Create player object. :param x: Start position X :param y: Start position Y """ # load player image image_path = pkg_resources.resource_filename('aaaaaa....
ROYALBEFF/aaaaaa_arcade_game
aaaaaa/InputHandler.py
import pygame class InputHandler: def __init__(self): pass @staticmethod def in_game_input(state, player, screen): """ Handle keyboard input while in-game. Handles movement, use of items and pause. :param state: Current game state. :param play...
ROYALBEFF/aaaaaa_arcade_game
aaaaaa/Bomb.py
from aaaaaa.Powerup import Powerup class Bomb(Powerup): def __init__(self): super().__init__((255, 10, 10, 255), 250)
ROYALBEFF/aaaaaa_arcade_game
aaaaaa/Multiplier.py
<gh_stars>0 from aaaaaa.Powerup import Powerup class Multiplier(Powerup): def __init__(self, mul): """ Initialize Multiplier Powerup. :param mul: Value of multiplier. """ self.__mul = mul # set color to blue for x2 multiplier and to purple for x3 multi...
ROYALBEFF/aaaaaa_arcade_game
aaaaaa/Screen.py
import pkg_resources import pygame class Screen: def __init__(self): """ Initialize game screen. """ self.__clock = pygame.time.Clock() self.__size = (1000, 800) self.__screen = pygame.display.set_mode(self.__size) self.__font = pygame.font.Font(None, 24) ...
ROYALBEFF/aaaaaa_arcade_game
aaaaaa/Obstacle.py
<reponame>ROYALBEFF/aaaaaa_arcade_game<gh_stars>0 import random import pkg_resources import pygame class Obstacle: def __init__(self, speed): """ Initialize obstacle with random position. :param speed: Movement speed. """ # load obstacle image image_pa...
ROYALBEFF/aaaaaa_arcade_game
aaaaaa/ObstacleHandler.py
from aaaaaa.Obstacle import Obstacle import random class ObstacleHandler: def __init__(self): pass @staticmethod def generate_obstacle(state): """ Generate a new obstacle with a probability of obstacle_prob percent. """ p = random.randint(0, 100) if p < st...
ROYALBEFF/aaaaaa_arcade_game
aaaaaa/OneUP.py
<reponame>ROYALBEFF/aaaaaa_arcade_game from aaaaaa.Powerup import Powerup class OneUP(Powerup): def __init__(self): super().__init__((10, 255, 50, 255), 250)
ROYALBEFF/aaaaaa_arcade_game
aaaaaa/__init__.py
<reponame>ROYALBEFF/aaaaaa_arcade_game<gh_stars>0 from aaaaaa.GameState import GameState from aaaaaa.Player import Player from aaaaaa.PowerUpHandler import PowerUpHandler from aaaaaa.ObstacleHandler import ObstacleHandler from aaaaaa.Screen import Screen from aaaaaa.InputHandler import InputHandler from aaaaaa.Collisio...
ROYALBEFF/aaaaaa_arcade_game
aaaaaa/PowerUpHandler.py
from aaaaaa.OneUP import OneUP from aaaaaa.Multiplier import Multiplier from aaaaaa.Shield import Shield from aaaaaa.Bomb import Bomb import random class PowerUpHandler: def __init__(self): pass @staticmethod def update_powerups(state): """ Decrease life time of powerups and rem...
ROYALBEFF/aaaaaa_arcade_game
aaaaaa/Powerup.py
<reponame>ROYALBEFF/aaaaaa_arcade_game import random import pkg_resources import pygame class Powerup: def __init__(self, color, ticks): """ Initialize Powerup with random position. :param color: Powerup color. :param ticks: Number of ticks the powerup wil...
ROYALBEFF/aaaaaa_arcade_game
setup.py
from setuptools import setup, find_packages setup( name='AAAAAA', description='A VVVVVV inspired arcade game.', version='0.0.1', author='ROYALBEFF', license='MIT', platforms='ALL', install_requires=['pygame>=1.9.4'], packages=find_packages(), package_data={'': ['*.png']}, entry_...
Scientific-Guy/spotify-api.py
spotifyapi/__init__.py
<reponame>Scientific-Guy/spotify-api.py """ Spotify-Api.py Simple Spotify Wrapper written in python By abh80 and science spot(scientific-guy) v0.0.4 MIT License """ # Import all lib files from .Oauth import Auth from .Track import Track from .Artist import Artist from .User import User from .Album import Album from ....
luizcarloscf/is-tester-multiarch
src/is_tester_multiarch/conf/options_pb2.py
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: options.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _refle...
luizcarloscf/is-tester-multiarch
src/is_tester_multiarch/rpc.py
import time import sys from google.protobuf.struct_pb2 import Struct from opencensus.ext.zipkin.trace_exporter import ZipkinExporter from is_wire.core import Channel, StatusCode, Status, AsyncTransport from is_wire.rpc import ServiceProvider, LogInterceptor, TracingInterceptor from .utils import zipkin_uriparse, load...
luizcarloscf/is-tester-multiarch
setup.py
from setuptools import setup, find_packages setup( name='is_tester_multiarch', version='0.0.1', description='', url='http://github.com/luizcarloscf/is-tester-multiarch', author='luizcarloscf', license='MIT', packages=find_packages('src'), package_dir={'': 'src'}, entry_points={ ...
luizcarloscf/is-tester-multiarch
src/is_tester_multiarch/utils.py
<reponame>luizcarloscf/is-tester-multiarch import re from is_wire.core import Logger from google.protobuf.json_format import Parse from .conf.options_pb2 import TesterOptions def zipkin_uriparse(uri: str = "http://localhost:9411"): """ Parse Zipkin uri using RegEx (regular expression). Raises a critical err...
luizcarloscf/is-tester-multiarch
example/client.py
from is_wire.core import Channel, Message, Subscription from google.protobuf.struct_pb2 import Struct import socket channel = Channel("amqp://guest:guest@10.10.2.7:30000") subscription = Subscription(channel) # Prepare request struct = Struct() struct.fields["value"].number_value = 1.0 request = Message(content=struc...
nilsbore/rbpf_processing
scripts/replace_clouds_images.py
#!/usr/bin/python import numpy as np import os import sys def replace_clouds_images(observations_file, data_path): objects_file = np.load(os.path.join(data_path, "data_summary.npz")) home_path = os.path.join(os.path.expanduser("~"), ".ros") observations_dict = np.load(observations_file) spatial_mea...
nilsbore/rbpf_processing
scripts/rbpf_propagation.py
<filename>scripts/rbpf_propagation.py #!/usr/bin/python import os import fnmatch import sys import re import subprocess #import natsort def sortkey_natural(s): return tuple(int(part) if re.match(r'[0-9]+$', part) else part for part in re.split(r'([0-9]+)', s)) def get_sweep_xmls(data_path): file_list = [] ...
nilsbore/rbpf_processing
test/view_detections.py
#!/usr/bin/python import os import fnmatch import sys import re import shutil import subprocess def sortkey_natural(s): return tuple(int(part) if re.match(r'[0-9]+$', part) else part for part in re.split(r'([0-9]+)', s)) def get_sweep_xmls(data_path): file_list = [] # Walk through directory for dna...
nilsbore/rbpf_processing
scripts/rbpf_choose_targets.py
<filename>scripts/rbpf_choose_targets.py<gh_stars>0 #!/usr/bin/python import numpy as np import os import sys import matplotlib.pyplot as plt from matplotlib.widgets import Button import matplotlib.image as mpimg class Picker(object): def __init__(self): self.index = 0 self.indices = [] s...
nilsbore/rbpf_processing
scripts/reduce_features.py
#!/usr/bin/python import numpy as np from sklearn import manifold import matplotlib.pyplot as plt import sys import os import json import rospkg def compute_covariance(red_features, text_labels): features = red_features.copy() nbr_points = features.shape[0] labels = np.zeros((nbr_points,), dtype=int) ...
nilsbore/rbpf_processing
scripts/replace_features.py
#!/usr/bin/python import numpy as np import os import sys import matplotlib.pyplot as plt def compute_new_features(measurement_covariance, features, dims): vols = np.reshape(np.max(dims, axis=1), (-1, 1)) new_features = np.hstack((features, vols)) n, bins, patches = plt.hist(vols, 50, normed=1, facecolo...
nilsbore/rbpf_processing
scripts/cluster_objects.py
<reponame>nilsbore/rbpf_processing<gh_stars>0 #!/usr/bin/python import os import fnmatch import sys import re import subprocess import json import numpy as np #import natsort def sortkey_natural(s): return tuple(int(part) if re.match(r'[0-9]+$', part) else part for part in re.split(r'([0-9]+)', s)) def get_sweep...
nilsbore/rbpf_processing
scripts/metaroom_processing/metaroom_reduction.py
#!/usr/bin/python import numpy as np from sklearn import manifold import matplotlib.pyplot as plt import sys import os import json def dimension_reduction(data_path): with open(os.path.join(data_path, "feature_labels.json")) as data_file: feature_labels_dict = json.load(data_file) labels = feature_l...
nilsbore/rbpf_processing
test/inspect_objects.py
#!/usr/bin/python import os import fnmatch import sys import re import subprocess import json import numpy as np #import natsort def sortkey_natural(s): return tuple(int(part) if re.match(r'[0-9]+$', part) else part for part in re.split(r'([0-9]+)', s)) def get_sweep_xmls(data_path): file_list = [] # W...
nilsbore/rbpf_processing
scripts/summarize_objects.py
#!/usr/bin/python import os import fnmatch import sys import re import subprocess import json import numpy as np import xml.etree.ElementTree as ET from os.path import relpath #import natsort waypoint_to_location_id = {} def sortkey_natural(s): return tuple(int(part) if re.match(r'[0-9]+$', part) else part for p...
nilsbore/rbpf_processing
scripts/metaroom_processing/metaroom_features.py
<reponame>nilsbore/rbpf_processing #!/usr/bin/python import os import tensorflow as tf import tensorflow.python.platform from tensorflow.python.platform import gfile import numpy as np import sys import json # This code comes from https://code.oursky.com/tensorflow-svm-image-classifications-engine/ def create_graph(...
nilsbore/rbpf_processing
scripts/rbpf_conversion.py
#!/usr/bin/python import numpy as np import os import sys def compute_feature_support(features, resolution, threshold): # how do we do this? # one idea might be to discretize and count the # volume of cubes with sufficient number of points # to verify, we can check what percentage is contained # ...
nilsbore/rbpf_processing
scripts/remove_processed_objects.py
#!/usr/bin/python import os import fnmatch import sys import re import shutil def sortkey_natural(s): return tuple(int(part) if re.match(r'[0-9]+$', part) else part for part in re.split(r'([0-9]+)', s)) def get_sweep_xmls(data_path): file_list = [] # Walk through directory for dname, sdname, files ...
ajthr/fastapi-react-mongodb
{{cookiecutter.project_slug}}/api/tests/crud_test.py
<filename>{{cookiecutter.project_slug}}/api/tests/crud_test.py<gh_stars>1-10 import pytest from fastapi.testclient import TestClient from main import api @pytest.fixture def client(): yield TestClient(api) class TestItems: def test_create_item(self, client): data = { "item_name": "name",...
ajthr/fastapi-react-mongodb
{{cookiecutter.project_slug}}/api/crud/crud_item.py
from fastapi import APIRouter, Response from fastapi.responses import JSONResponse from pydantic import BaseModel from bson.json_util import dumps from bson.objectid import ObjectId from core import db router = APIRouter() Items = db.items class CreateItem(BaseModel): item_name: str item_description: str ...
ajthr/fastapi-react-mongodb
{{cookiecutter.project_slug}}/api/main.py
<gh_stars>1-10 from core import api from crud.crud_item import router api.include_router(router, prefix="/items")
ajthr/fastapi-react-mongodb
{{cookiecutter.project_slug}}/api/core/__init__.py
<gh_stars>1-10 from fastapi import FastAPI from pymongo import MongoClient from core.config import settings database_client = MongoClient(settings.MONGO_DATABASE_URL) db = database_client.{{ cookiecutter.mongodb_database }} api = FastAPI( title=settings.PROJECT_NAME, docs_url="/docs", )
ajthr/fastapi-react-mongodb
{{cookiecutter.project_slug}}/api/core/config.py
import os class Settings: PROJECT_NAME = "{{ cookiecutter.project_slug }}" MONGO_DATABASE_URL = os.environ.get("DB_URI") SECRET_KEY = os.environ.get("SECRET_KEY") settings = Settings()
voberto/glucoplot-libre
src/modules/plotter_days.py
import csv import pandas as pd import matplotlib.pyplot as plt import datetime import time import math from matplotlib import rc import numpy as np import glob def plotter_days(month_number, year_number): try: try: list_cols = ['line', 'date', 'glucose', 'idk', 'type', 'source'] in...
voberto/glucoplot-libre
src/modules/parser_days.py
<gh_stars>1-10 import csv import pandas as pd import matplotlib.pyplot as plt import datetime import time import math from matplotlib import rc def parser_days(month_number, year_number): list_cols = ['line', 'data', 'glucose', 'idk', 'type', 'source'] index_line = 0 index_data = 1 index_glucose = 2 ...
voberto/glucoplot-libre
src/glucoplot-libre.py
<gh_stars>1-10 from cmd import Cmd import sys import subprocess import modules.logger_data as logger_data import modules.parser_month as parser_month import modules.parser_days as parser_days import modules.plotter_days as plotter_days import modules.printer_days as printer_days import modules.check_cmd as check_cmd ...
voberto/glucoplot-libre
src/modules/check_cmd.py
import csv import pandas as pd import datetime import time import math import subprocess import re def func_check_cmd(): # Get glucose.csv filename with full path current_path = subprocess.check_output("pwd", shell=True) path_decoded = current_path.decode("utf-8").rstrip() dataframe_filename = path_de...
voberto/glucoplot-libre
src/modules/parser_month.py
<gh_stars>1-10 import csv import pandas as pd import matplotlib.pyplot as plt import datetime import time import math from matplotlib import rc def parser_month(month_number, year_number, datafile_str): list_cols = ['date', 'glucose', 'idk', 'type', 'source'] index_data = 0 index_glucose = 1 index_idk...
voberto/glucoplot-libre
src/modules/logger_data.py
<gh_stars>1-10 import usb import usb.core import usb.util import usb.backend.libusb1 import subprocess import re def logger_data_get(): # Free Style Libre vendor and product IDs fslibre_idvendor = 0x1a61 fslibre_idproduct = 0x3650 # USB device path dev_path_start = "/dev" # Find our device ...
voberto/glucoplot-libre
src/modules/printer_days.py
<gh_stars>1-10 from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4 from reportlab.lib.pagesizes import portrait from reportlab.platypus import Image from reportlab.lib import utils from reportlab.lib.units import inch, cm import glob import os import datetime def printer_days(month_number, year...
Rabmelon/tiSPHi
eng/muIsph.py
<gh_stars>1-10 import taichi as ti import numpy as np from .sph_solver import SPHSolver class MCmuISPHSolver(SPHSolver): def __init__(self, particle_system, TDmethod, density, cohesion, friction, eta_0): super().__init__(particle_system, TDmethod) print("Class M-C μ(I) Soil SPH Solver starts to ser...
Rabmelon/tiSPHi
eng/gguishow.py
import taichi as ti import numpy as np # TODO: find how ggui works in taichi example codes, then change my SPH show to ggui! # TODO: clarify the drawing coordinate system def gguishow(case, solver, world, s2w_ratio, write_to_disk): print("ggui starts to serve!") drawworld = [i + 2 * case.grid_size for i in...
Rabmelon/tiSPHi
temp/eng - 20220411/particle_system.py
<filename>temp/eng - 20220411/particle_system.py import taichi as ti import numpy as np from functools import reduce # 整数:累加;字符串、列表、元组:拼接。lambda为使用匿名函数 # TODO: still have something wrong in NS, producing endless loop in offset. @ti.data_oriented class ParticleSystem: def __init__(self, world, radius, kh): ...
Rabmelon/tiSPHi
temp/taichi_sph_zmr/wcsph.py
import taichi as ti from sph_base import SPHBase class WCSPHSolver(SPHBase): def __init__(self, particle_system): super().__init__(particle_system) # Pressure state function parameters(WCSPH) self.exponent = 7.0 self.stiffness = 50.0 self.d_velocity = ti.Vector.field(self.p...
Rabmelon/tiSPHi
tests/test_kf.py
<filename>tests/test_kf.py import taichi as ti import numpy as np from eng.particle_system import * from eng.sph_solver import * ti.init(arch=ti.cpu) class FunSPHSolver(SPHSolver): def __init__(self, particle_system): super().__init__(particle_system) print("Hallo, class function SPH Solver starts...
Rabmelon/tiSPHi
temp/test3.py
<gh_stars>1-10 import taichi as ti ti.init(ti.cpu) # TODO: test the maximum print N = 10 x = ti.Vector.field(2, dtype=float, shape=N) @ti.kernel def addprint(): y = ti.Vector([0.0, 0.0]) for i in range(N): x[i] = ti.Vector([ti.random(float), 10+ti.random(float)]) y = max(abs(x[i]), abs(y)) ...
Rabmelon/tiSPHi
temp/taichi_sph_zmr/particle_system.py
<reponame>Rabmelon/tiSPHi<filename>temp/taichi_sph_zmr/particle_system.py import taichi as ti import numpy as np from functools import reduce @ti.data_oriented class ParticleSystem: def __init__(self, res): self.res = res self.dim = len(res) assert self.dim > 1 self.screen_to_world...
Rabmelon/tiSPHi
eng/sph_solver.py
import taichi as ti import numpy as np # TODO: generate SPH kernel functions and the derivate of kernel functions # TODO: check boundary treatment # TODO: add different advection methods epsilon = 1e-5 @ti.data_oriented class SPHSolver: def __init__(self, particle_system, TDmethod): print("Class SPH Solv...
Rabmelon/tiSPHi
eng/DPsph.py
import taichi as ti import numpy as np from .sph_solver import SPHSolver class DPSPHSolver(SPHSolver): def __init__(self, particle_system, TDmethod, density, cohesion, friction): super().__init__(particle_system, TDmethod) print("Class Drucker-Prager Soil SPH Solver starts to serve!") # Ba...
Rabmelon/tiSPHi
temp/eng - 20220411/draft1_soil.py
import taichi as ti import numpy as np from eng.particle_system import * from eng.soilsph import * # TODO: Change the rule from N-S to DP, material from water to soil. # ti.init(arch=ti.cpu, debug=True) ti.init(arch=ti.cuda, packed=True, device_memory_fraction=0.75) # MEMORY max 4G in GUT, 6G in Legion if __name...
Rabmelon/tiSPHi
test_DP.py
from math import sqrt, tan, pi import taichi as ti import numpy as np import matplotlib.pyplot as plt import copy plt.switch_backend('TKAgg') ti.init(arch=ti.cpu) # TODO: Test the D-P stress check and update # basic property par = pi/180 epsilon = 1e-4 # input, list def initMove(dt, u, x, a): dt = dt u = u ...
Rabmelon/tiSPHi
temp/sparseTriangle.py
<gh_stars>1-10 import taichi as ti import time ti.init(arch = ti.gpu) c窗口边长 = 1024 c窗口尺寸 = (c窗口边长, c窗口边长) c网格边长 = 4**4 c网格尺寸 = (c网格边长, c网格边长) c缩放 = c窗口边长 // c网格边长 c时间间隔 = 1 / 100 @ti.data_oriented class C三角形: def __init__(self): self.m点 = ti.Vector.field(2, dtype = float, shape = 3) @ti.kernel def ...
Rabmelon/tiSPHi
tests/test_psAggui.py
import taichi as ti import numpy as np ti.init(arch=ti.cpu) @ti.data_oriented class TmpParticleSystem: def __init__(self, world, radius) -> None: print("temp particle system serve.") self.world = np.array(world) self.radius = radius self.grid_size = 6 * self.radius self.par...
Rabmelon/tiSPHi
eng/particle_system.py
import taichi as ti import numpy as np from functools import reduce # 整数:累加;字符串、列表、元组:拼接。lambda为使用匿名函数 # TODO: --ok Unify all coordinate systems and put padding area outside the real world. # TODO: still warnings in NS, offset loop die for endless # TODO: better method of update kh @ti.data_oriented class Particle...
Rabmelon/tiSPHi
eng/__init__.py
<gh_stars>1-10 from . import particle_system, sph_solver, guishow, gguishow, wcsph, DPsph, muIsph
Rabmelon/tiSPHi
temp/eng - 20220411/sph_solver.py
<filename>temp/eng - 20220411/sph_solver.py import taichi as ti import numpy as np from particle_system import ParticleSystem # TODO: use repulsive particles to replace boundary collisions later!!!!! # 此类中应包含各种核函数及其导数、各种时间积分的框架、边界处理 @ti.data_oriented class SPHSolver: def __init__(self, particle_system, TDmethod):...
Rabmelon/tiSPHi
temp/taichi_sph_zmr/demo.py
<gh_stars>1-10 import taichi as ti import numpy as np from particle_system import ParticleSystem # from wcsph import WCSPHSolver ti.init(arch=ti.cpu) # Use GPU for higher peformance if available # ti.init(arch=ti.gpu, device_memory_GB=3, packed=True) if __name__ == "__main__": ps = ParticleSystem((512, 512)) ...
Rabmelon/tiSPHi
eng/wcsph.py
import taichi as ti from .sph_solver import SPHSolver class WCSPHSolver(SPHSolver): def __init__(self, particle_system, TDmethod): super().__init__(particle_system, TDmethod) print("Hallo, class WCSPH Solver starts to serve!") # Basic paras self.density_0 = 1000.0 # reference dens...
Rabmelon/tiSPHi
temp/taichi_sph_zmr/sph_base.py
<gh_stars>1-10 import taichi as ti import numpy as np @ti.data_oriented class SPHBase: def __init__(self, particle_system): self.ps = particle_system self.g = -9.80 # Gravity self.viscosity = 0.05 # viscosity self.density_0 = 1000.0 # reference density self.mass = self.p...
Rabmelon/tiSPHi
draft0.py
import taichi as ti import numpy as np from eng.guishow import * from eng.gguishow import * from eng.particle_system import * from eng.muIsph import * from eng.wcsph import * # TODO: make unit testing for basic functions of SPH # ti.init(arch=ti.cpu, debug=True) ti.init(arch=ti.cuda, packed=True, device_memory_fracti...
Rabmelon/tiSPHi
eng/guishow.py
<filename>eng/guishow.py import taichi as ti import numpy as np def guishow(case, solver, world, screen_to_world_ratio, write_to_disk): # def show(case, solver, world, screen_to_world_ratio, write_to_disk): print("gui starts to serve!") drawworld = [i + 2 * case.grid_size for i in world] cor_dl = [case.gr...
Rabmelon/tiSPHi
temp/eng - 20220411/soilsph.py
from numpy.core.arrayprint import DatetimeFormat from numpy.lib.function_base import piecewise import taichi as ti import numpy as np from .sph_solver import SPHSolver class SoilSPHSolver(SPHSolver): def __init__(self, particle_system, TDmethod, gamma, coh, fric): super().__init__(particle_system, TDmethod...
Rabmelon/tiSPHi
temp/test.py
import taichi as ti import numpy as np from functools import reduce # 整数:累加;字符串、列表、元组:拼接。lambda为使用匿名函数 from show import * ti.init(arch=ti.cpu) m = ti.field(float, 10) tmp = ti.Vector([1, 2]) @ti.kernel def cubic_kernel_derivative(r: ti.types.ndarray()): res = ti.Vector([0.0 for _ in range(2)]) k = 40 / 7 ...
Rabmelon/tiSPHi
temp/eng - 20220411/draft2_water.py
<reponame>Rabmelon/tiSPHi import taichi as ti import numpy as np from taichi.lang.ops import truediv from particle_system import * from wcsph import * # TODO: Add DFSPH solver first? Don't sure if there is enough time remains for a real physical experiment of sand flow. # TODO: Try new methods of time integration and ...
Rabmelon/tiSPHi
temp/eng - 20220411/__init__.py
<reponame>Rabmelon/tiSPHi from . import soilsph, sph_solver, particle_system, wcsph
Rabmelon/tiSPHi
temp/test2.py
<gh_stars>1-10 from numpy.core.numeric import Inf import taichi as ti ti.init(ti.cpu) #TODO: Calculate dA and dB of boundary treatment. @ti.func def cal_d_AB(x_i, x_j, bound, padding): print('----cal starts!') # dx_ij = x_j - x_i # print('dx_ij =', dx_ij) # direction: up, down, right, left # dir ...
Rabmelon/tiSPHi
temp/show.py
<reponame>Rabmelon/tiSPHi import taichi as ti import numpy as np def guishow(radius, world, screen_to_world_ratio, write_to_disk): print("Hallo, gui starts to serve!") grid_size = 6 * radius drawworld = [i + 2 * grid_size for i in world] cor_dl = [grid_size, grid_size] res = (np.array(drawworld) *...
John-G-Thomas/twitoff-lecture
twitoff/predict.py
<reponame>John-G-Thomas/twitoff-lecture """Prediction of Users based on Tweet embeddings.""" import numpy as np from sklearn.linear_model import LogisticRegression from .models import User from .twitter import BASILICA # from .visaliztion import plot_confusion_matrix # import SentimentIntensityAnalyzer class # from...
danserie/spectranet_reboot
scripts/plottings.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 24 18:14:52 2019 @author: zqwu """ import numpy as np import matplotlib.pyplot as plt from scripts.parse_data import amino_acid_MWs, generate_mz_chart, calculate_precursor_MZ, reverse_amino_acid_coding neutral_losses = {0: 0, 1: 17, 2: 18, 3: 34, 4...
danserie/spectranet_reboot
scripts/trainer.py
<filename>scripts/trainer.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Jul 25 17:48:03 2018 @author: zqwu """ import torch as t from torch import nn from torch.autograd import Variable from torch.optim import Adam from copy import deepcopy import numpy as np from sklearn.metrics import r2_sco...
danserie/spectranet_reboot
scripts/parse_data_phospho.py
import csv import re import pickle import numpy as np from collections import Counter beginning_modifier_regex = r"^[a-z]\[\d+\]" middle_modifier_regex = r"[A-Z]\[\d+\]" position_regex = r"^[by](?P<position>\d+)" charge_regex = r"\^(?P<charge>[\d])+" neutral_loss_regex = r"[by][\d]+-(?P<neutral_loss>[\d]+)" neutral_ga...
danserie/spectranet_reboot
scripts/bkp/unique_inputs.py
<filename>scripts/bkp/unique_inputs.py import numpy as np from parse_data import reverse_one_hot_encode, amino_acid_modified_codes import pickle def pair_to_name(pair): return reverse_one_hot_encode(pair[0], amino_acid_modified_codes) + str(pair[1][0]) + str(pair[1][1]) def sim(p1, p2): return np.sum(p1[2] ...
danserie/spectranet_reboot
website.py
# Code to serve website from scripts.biLSTM import BiLSTM, MultiheadAttention from scripts.models import TestModel from scripts.trainer import Trainer import numpy as np from flask import Flask, render_template, request, jsonify, make_response from parse_data import amino_acid_name_parse from calculate_frag_mz import ...
danserie/spectranet_reboot
scripts/models.py
<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 24 15:40:34 2018 @author: zqwu """ from torch import nn import torch as t import torch.nn.functional as F import numpy as np from scripts.biLSTM import BiLSTM, MultiheadAttention, CombinedConv1D, PositionalEncoding def CELoss(labels, ou...
danserie/spectranet_reboot
run_model.py
import torch as t from torch import nn from torch.autograd import Variable from torch.optim import Adam import numpy as np import pandas as pd from scripts.models import TestModel, TransformerModel from scripts.trainer import Trainer from sklearn.metrics import precision_score, recall_score import os import pickle cla...
leequant761/Fluent-python
19-dyn-attr-prop/oscon/explore0.py
<gh_stars>0 # BEGIN EXPLORE0 from collections import abc class FrozenJSON: """A read-only façade for navigating a JSON-like object using attribute notation """ def __init__(self, mapping): self.__data = dict(mapping) # <1> mapping 인수로 부터 딕셔너리 생성 def __getattr__(self, name): # <2> na...
leequant761/Fluent-python
11-iface-abc/tombolist.py
from random import randrange from tombola import Tombola @Tombola.register # <1> 가상서브클래스로 등록(실제 부모역할안함) class TomboList(list): # <2> def pick(self): if self: # <3> list에서 self.__bool__ 을 상속받음 position = randrange(len(self)) return self.pop(position) # <4> else: ...
leequant761/Fluent-python
15-context-mngr/else.py
# else라 쓰고 then이라 읽는다. # for,while 루프가 완전히 실행된 후에(break 걸리면 안됨) else 블록 실행 for item in [1, 2, 3, 4]: if item == 5: break else: raise ValueError('No 5 found') # try 블록에서 예외가 발생하지 않으면 else블록으로 실행(else블록 예외는 except가 안잡음) import random def dangerous_call(): if random.randint(1,3) == 3: raise ...
leequant761/Fluent-python
20-descriptor/bulkfood/bulkfood_v4prop.py
<filename>20-descriptor/bulkfood/bulkfood_v4prop.py<gh_stars>0 """ A line item for a bulk food order has description, weight and price fields:: >>> raisins = LineItem('<NAME>', 10, 6.95) >>> raisins.weight, raisins.description, raisins.price (10, '<NAME>', 6.95) A ``subtotal`` method gives the total pric...
leequant761/Fluent-python
20-descriptor/bulkfood/bulkfood_v4.py
<reponame>leequant761/Fluent-python<gh_stars>0 # BEGIN LINEITEM_V4 : 속성몀을 반복하고 싶지 않다 class Quantity: __counter = 0 # <1> Quantity 객체의 수를 샌다 (2개가 될 예정) def __init__(self): cls = self.__class__ # <2> Quantity 클래스 참조 prefix = cls.__name__ # 'Quantity' index = cls.__counter # 몇번째에 생성됐냐 ...
leequant761/Fluent-python
05-1class-func/pkgs_for_ftnal.py
# 1. operator 모듈 from functools import reduce # 재귀 대신에 숫자 시퀀스를 곱하는 경우 (내장 product가 없음) def fact(n): return reduce(lambda a, b: a*b, range(1, n+1)) from operator import mul def fact(n): return reduce(mul, range(1, n+1)) # 2. from operator itemgetter(); 시퀀스 항목 참조 metro_data = [ ('Tokyo', 'JP', 36.933, (35.6...
leequant761/Fluent-python
02-array-seq/bisect_insort.py
<reponame>leequant761/Fluent-python<gh_stars>0 import bisect import random # insort : 정렬은 값비싼 연산이므로 정렬한 훙는 정렬 상태를 유지하는 것이 좋음. # 특히, insort는 정렬된 배열을 유지하면서 지속적으로 항목을 추가할 떄 쓰인다. # 인수로 들어온 my_list의 사본을 만들지 않고 객체를 직접 변경한다. # lo, hi를 설정해서 검색 범위를 설정할 수도 있다. SIZE = 7 random.seed(1729) my_list = [] # 숫자로 된 리스트를 다루고 있다면 array...
leequant761/Fluent-python
14-it-generator/sentence.py
""" Sentence: access words by index 반복형에 대해 알아보자 """ 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) # <1> 정규표현식에 매칭되는 문자열 리ㅡ트 def __getitem__(self, index): # 시퀀스 프로토콜 return self.w...
leequant761/Fluent-python
15-context-mngr/mirror_gen_exc.py
""" 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') ... print(what) ... ...
leequant761/Fluent-python
16-coroutine/coro_exc_demo.py
<reponame>leequant761/Fluent-python<gh_stars>0 """ Coroutine closing demonstration:: # BEGIN DEMO_CORO_EXC_1 >>> exc_coro = demo_exc_handling() >>> next(exc_coro) -> coroutine started >>> exc_coro.send(11) -> coroutine received: 11 >>> exc_coro.send(22) -> coroutine received: 22 >>> exc...
leequant761/Fluent-python
05-1class-func/ftn_introspection.py
# 1. 함수 인수에 대한 정보 추출하기 from clip import clip clip.__defaults__ # (80,) ; default 셋팅을 확인 clip.__code__ # <code object clip at 0x clip.__code__.co_varnames # ('text', 'max_len', 'end', 'space_before', 'space_after') clip.__code__.co_argcount # 2 # 2. inspect 모듈로 깔끔하게 함수 시그니처 추출하기 from clip import clip from inspect impor...