text stringlengths 3.07k 12.6k |
|---|
"""Running online al_mlp learner using VaspInteractive
Dependency:
- https://github.com/ulissigroup/al_mlp
- https://github.com/ulissigroup/cluster_mlp
This example requires CPU cores >= 8.0
"""
from al_mlp.atomistic_methods import replay_trajectory
from ase.calculators.vasp import Vasp
from vasp_interactiv... |
from doctest import master
import tkinter as tk
import tkinter.font as tkFont
from PIL import ImageTk, Image
from ctypes import windll
# import module for getting card information
import search_engine as search
from config import *
class App():
def __init__(self) -> None:
self.tk = tk.Tk()... |
import sys
import struct
import os
CSF_CHUNK = b'CSFCHUNK'
CHUNK_HEADER = b'CHNKHead'
CHUNK_EXTERNAL = b'CHNKExta'
CHUNK_SQLITE = b'CHNKSQLi'
CHUNK_FOOTER = b'CHNKFoot'
BLOCK_DATA_BEGIN_CHUNK = b'\x00B\x00l\x00o\x00c\x00k\x00D\x00a\x00t\x00a\x00B\x00e\x00g\x00i\x00n\x00C\x00h\x00u\x00n\x00k'
BLOCK_DATA_END_CHUNK = b'... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable-msg=import-error
"""
run_preprocess.py is writen for preprocessing tweets
"""
__author__ = "<NAME>"
__project__ = "Persian Emoji Prediction"
__credits__ = ["<NAME>"]
__license__ = "Public Domain"
__version__ = "1.0.0"
__maintainer__ = "<NAME>"
__email__... |
from __future__ import annotations
from gi.repository import GLib
import boto3
import botocore
from ..engine import Engine, EngineThread
from ..file import S3Object, FileStatus
from ..operations.s3_uploader import AWS_S3_ENGINE_IGNORE_ME
from ..utils import LongTaskWindow, match_path
import logging
from pathlib impo... |
import typing as t
from abc import ABCMeta, abstractmethod
from pathlib import Path
import attr
import h5py
from phd_qmclib.qmc_base import dmc as dmc_base, vmc as vmc_base_udf
from phd_qmclib.util.attr import str_validator
from . import data, proc
T_State = t.Union[dmc_base.State, vmc_base_udf.State]
T_SamplingData... |
"""
Sieve filter build and apply operations
https://support.tigertech.net/sieve
http://pigeonhole.dovecot.org/doc/man1/sieve-filter.1.html
http://www.gyford.com/phil/writing/2010/07/02/sieve-filters.php
"""
import os
import re
import logging
from mail_serv.user import user_list
from mail_serv.config import config_sie... |
#!/usr/bin/env python
#################################################################################################################
# Copyright 2018 Symantec Corporation. All rights reserved.
# Script to get Events
# You need to provide Client ID and Client Secret Key in config.ini file under Credentials sections,... |
from GA.ranking import Elo
from game.enums import PlayerType
from game.state import GameState
from characters.characters import Character
from input.pad import Pad
from input.enums import Button
from training.reward import Rewards
import numpy as np
import threading
from collections import deque
from time import time... |
import pandas as pd
import numpy as np
import sys
import traceback
from tqdm.auto import tqdm
#import git
import os
def get_date(x):
return '-'.join(x.split('-')[:3])
def get_fips(x):
return x.split('-')[-1]
def pinball_loss(y_true, y_pred, quantile = 0.5):
delta = y_true - y_pred
loss_above = np.sum(... |
# coding: utf-8
"""
Base para desarrollo de modulos externos.
Para obtener el modulo/Funcion que se esta llamando:
GetParams("module")
Para obtener las variables enviadas desde formulario/comando Rocketbot:
var = GetParams(variable)
Las "variable" se define en forms del archivo package.json
Para modifica... |
from datetime import datetime, timedelta
import functools
import os
from typing import Callable, Dict, Hashable
from bs4 import BeautifulSoup
from dask.diagnostics import ProgressBar
import fsspec
from fsspec.implementations.local import LocalFileSystem
from fsspec_reference_maker.hdf import SingleHdf5ToZarr
import pa... |
import socket
import os
import fcntl
import ctypes
import re
from binascii import hexlify
from datetime import datetime as dt
from PacketSniffer import Dissector
ETH_P_ALL = 0x003
IFF_PROMISC = 0x100
SIOCGIFFLAGS = 0x8913
SIOCSIFFLAGS = 0x8914
class ifreq(ctypes.Structure):
_fields_ = [
... |
"""
뉴스 데이터 가져와서 전처리하는 py
"""
import pandas as pd
import numpy as np
import warnings
import datetime
warnings.filterwarnings('ignore')
from sklearn.preprocessing import OneHotEncoder
from sklearn import preprocessing
from hugging_classifier import HuggingClassifier, model_param_bert_pt, NEWS_OM_MODEL, ... |
import sys
import pygame
from bullet import Bullet
from alien import Alien
from time import sleep
def check_events(ai_settings, stats, screen, ship, bullets, aliens, play_button):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
... |
#!python3
# Created 5 Dec 2020
# @author: andreas
""" Advent of code 2020
Day 4: Passport Processing
"""
from argparse import ArgumentParser
import logging
import re
import os
import sys
LOG = logging.getLogger(__name__)
def read_passports(fn):
pps = list()
pp = dict()
with open(fn) as fh:
f... |
import argparse
import json
import logging
import os
import pickle
import time
import numpy as np
import scipy.sparse
import sklearn.preprocessing
import utils
def dump_docvectors(config):
for source in config['sources']:
qrels = source['qrels']
source_name = source['name']
index = sourc... |
import numpy as np
import pandas as pd
from mmm import DataHandler as DH
from scipy.stats import entropy
from sklearn.neighbors import KernelDensity
from tqdm import tqdm
kde = KernelDensity(
bandwidth=0.01,
metric='euclidean',
kernel='gaussian',
algorithm='ball_tree'
)
x_min = -175 * np.pi / 180.
x_m... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 4 15:17:30 2017
@author: nberliner
"""
import numpy as np
import pandas as pd
from features.seaIce import get_seaIce
from features.krillbase import KrillBase
from features.temperature import Temperature
from utils.NestDistance import NestDistance
from utils.utils impor... |
import codecs
import requests
single_param_operations = [
# Operations that receive a Decimal and return a Decimal
"abs", "acos", "acosh", "asin", "asinh", "atan", "atanh",
"cbrt", "ceil", "cos", "cosh", "exp", "floor", "ln", "log2",
"log10", "neg", "round", "sin", "sinh", "sqrt", "tan", "tanh", "trunc... |
from bovidecoapp.models import *
from django.contrib import admin
class measurementInline(admin.TabularInline):
model = measurement
extra = 10
class observationInline(admin.TabularInline):
model = observation
extra = 3
class MetricCharacterAdmin(admin.ModelAdmin):
list_display = ("code","element","name","metho... |
import json, requests, time, datetime, sys, getopt, csv
from datetime import datetime, timedelta
# Usage
# python3 ap-cochannel-neighbors.py --endpoint https://https://domain.nyansa.com/api/v2/graphql --apikey <API_Key> --jsonoutput output.json --csvoutput output.csv
# if on OnPrem please disable SSL-Validation... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, absolute_import
import os
import sys
import os.path
import shutil
import errno
import logging
import io
import hashlib
import simiki
from simiki.compat import unicode
logger = logging.getLogger(__name__)
COLOR_CODE... |
import torch.nn as nn
import torch
from . import darts_ops
import torch.nn.functional as F
import collections
import numpy as np
class MixedLayer(nn.Module):
"""
Represents a mixture of weighted primitive units
"""
def __init__(self, primitives, c, stride):
super().__init__()
self.lay... |
# -*- coding: utf-8 -*-
"""
PyTest file for offshore econ and losses
Created on Dec 16 2019
@author: gbuster
"""
import os
import pandas as pd
import numpy as np
import shutil
import pytest
import tempfile
from reV.handlers.outputs import Outputs
from reV.offshore.offshore import Offshore
from reV import TESTDATADI... |
#!/usr/bin/env python
''' ---------------- About the script ----------------
Assignment 4: Network analysis: creating reusable network analysis pipeline
This command-line tool takes a given dataset and perform simple network analysis. In particular, it builds networks based on entities appearing together in the sam... |
import os, stat, errno
import fuse
from fuse import Fuse
import redis
import logging
from redisfs import RFS, RFolder, RFile
if not hasattr(fuse, '__version__'):
raise RuntimeError("your fuse-py doesn't know of fuse.__version__, probably it's too old.")
fuse.fuse_python_api = (0, 2)
log = logging.getLogger(__name... |
import functools
import logging
import numpy as np
import os
import matplotlib.pyplot as plt
import shutil
from __init__ import local_pc_root, project_root
from time import time
from scipy.stats import norm
from scipy.special import logsumexp
def merge_dicts(*dict_args):
"""
Given any number of dicts, shallow... |
from botnet.config import Config
from botnet.modules.builtin.admin import Admin
from botnet.message import Message
from botnet.signals import message_in, admin_message_in
data1 = [
':server.example.com 311 target_nick nick1 ~user freebsd/user/username * :real name',
':server.example.com 312 target_nick nick1 ... |
from pathlib import Path
import re
from glob import glob
from cumulusci.core.tasks import BaseTask
from cumulusci.core.utils import process_list_arg
from cumulusci.core.exceptions import SalesforceException, TaskOptionsError
from cumulusci.utils.fileutils import load_from_source
class AddNamespaceTokens(BaseTask):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from enums.url_enums import General
from util import wait_until_find_xpath, wait_until_find_xpaths, log
import os
from . import driver, MAIN_LINK, HASH_CODE
import time
import re
# Higher freq for main auction
# Longer noise for "too short" notification
# Parse values ... |
from itertools import combinations, islice
import math
import numpy as np
import pandas as pd
import pyproj
from shapely.ops import transform
import humanleague as hl
from pathlib import Path
import shutil
from .initialisation import CORE_FUNCTIONS
_bng_proj = pyproj.Proj(init='epsg:27700')
_lonlat_proj = pyproj.Pr... |
# TODO Not finished yet
"""Notebooks"""
def run_notebook(self, workspace_id, user_id, payload, command_to_execute):
# e.g. notebook_url = "http://10.10.0.199:8000/api/v1.0/run_notebook_in_docker"
notebook_url = "{0}/v1.0/{1}".format(self.base_url, command_to_execute)
url = self._add_token_to_url(notebook... |
from __future__ import unicode_literals
import os
import json
from flask import Blueprint, render_template, url_for, redirect, current_app, jsonify, flash, request
from flask_login import current_user, login_required
from app import db
from app.models import EditableHTML, OralHistory, WikipediaSuggest, Entity, EntityM... |
import os
import csv
import awstools
import datetime
from pprint import pprint
TIMEZERO = datetime.datetime(year=2005,month=1,day=18)
def StringToDate(s):
return datetime.datetime.strptime(s,"%Y-%m-%d %X")
def lambda_handler(event,context):
os.chdir('/tmp')
TOTAL_SUBMISSIONS = 0
SKIPPED = 0
PROCESSED_SUBMIS... |
"""
Cifar100 Dataloader implementation
"""
import logging
import numpy as np
import copy
import random
import torch
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from torch.utils.data import DataLoader
class Cifar100DataLoader:
def __init__(self, config):
torch.ba... |
""""Test cases for proxy objects."""
from jsonpointer import resolve_pointer
import pytest
from ymlref.proxies import MappingProxy, SequenceProxy
INNER_REF_DICT = {
'components': {
'person': {'name': 'string', 'age': 'number'},
'pet': {'petId': 'number', 'name': 'string'}
},
'foo': {'$ref'... |
# yellowbrick.features.pcoords
# Implementations of parallel coordinates for feature analysis.
#
# Author: <NAME> <<EMAIL>>
# Created: Mon Oct 03 21:46:06 2016 -0400
#
# Copyright (C) 2016 District Data Labs
# For license information, see LICENSE.txt
#
# ID: pcoords.py [] <EMAIL> $
"""
Implementations of parallel c... |
import random,copy,math
import numpy as np
import settings
import quantum_routines
import scipy.integrate
from scipy.optimize import minimize
import scipy
import igraph
from scipy.sparse import csr_matrix
class Graph:
"""
Graph used for QAOA,either for MIS or for MaxCut
Attributes : None, random gene... |
import csv
def load_tasks_from_csv(path_to_csv):
"""Loads tasks from a csv file and returns a map of tasks
The CSV file must have the first row be a header row, wich the columsn in the following order:
* task_id
* name
* duration
* predecessor ids (with each predecessor ID separated by a comma)
Args:
path_to_... |
from django.test import TestCase
from django.test.client import Client
try:
import json
except:
from django.utils import simplejson as json
from MacroExpansion import MacroExpansion
from KeyValueTree import KeyValueTree
from truth.models import Truth, KeyValue as TruthKeyValue
class TestMacroExpansion(TestCas... |
##################################################
# Copyright (c) <NAME> [GitHub D-X-Y], 2019 #
######################################################################################
import os, sys, time, glob, random, argparse
import numpy as np
from copy import deepcopy
import torch
import torch.nn as nn
from pathli... |
import datetime
import importlib
import json
import logging
import logging.config
import pathlib
import sqlite3
import sys
import zlib
from collections import MutableMapping, OrderedDict
from string import Formatter
from types import ModuleType
import box
import dill
import sqlitedict
from irc.client import NickMask
... |
# Implementation of classic arcade game Pong
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
paddle1_pos = 180
paddle1_vel = 0
paddle2_pos = 180
paddle2_vel = 0
HALF_PAD_WID... |
#Copyright [2015] Hewlett-Packard Development Company, L.P.
#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 ag... |
import os.path
import sys
import subprocess
from collections import namedtuple
import re
import exceptions
from lxml import etree
def assertEquals(expected, actual, what=None, msg=None):
if msg is None and what is None:
msg = "Expected %r, got %r instead" % (expected, actual)
elif msg is None:
... |
# -*- coding: utf-8 -*-
# @File : tryEverything/beam_search.py
# @Info : @ TSMC-SIGGRAPH, 2018/6/19
# @Desc : refer to google/im2txt
# -.-.. - ... -- -.-. .-.. .- -... .---. -.-- ..- .-.. --- -. --. ..-. .- -.
import heapq
import math
import numpy as np
class Caption(object):
"""Represents a compl... |
import glob
import os
import subprocess
import sys
if len(sys.argv) != 3:
print("Usage: GenForwarders.py <vs_folder> <vc_version_to_generate>")
print("Last version generated 14.21.27702")
exit()
VSFolder = sys.argv[1]
VCVersion = sys.argv[2]
archs = ["x86", "x64", "arm64"]
importLibMapping = {
"... |
import re
import logging
from termcolor import colored
from itertools import groupby
from clldutils.misc import nfilter, slug
from pygrambank import bib
REFS = {
('Strauß', 'n.d.', 'melp1238'): 's:Strauss:Melpa',
('Thurston', '1987', 'kuan1248'): 'hvw:Thurston:NBritain',
("Z'Graggen", '1969', 'geda1237')... |
# ******************************************************************************
# pysimm.utils module
# ******************************************************************************
#
# ******************************************************************************
# License
# *****************************************... |
import logging
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.admin import ModelAdmin
from django.contrib.auth.admin import csrf_protect_m
from django.core.exceptions import PermissionDenied
from django.db.models import Count
from django.http import HttpResponseBadRequest, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Implements the mathematical representation of the 1976 Committee on Extension to the Standard Atmosphere (COESA) United States standard lower atmospheric values for absolute temperature, pressure, density, and speed of sound for the input geopotential altitude.
Below 3... |
from settings import Settings
from a_star import *
from rand_maze import *
from recursive_backtracker import rec_backtracker
import time, pygame, random, math
import numpy as np
'''This is a basic implementation of the A* shortest path finding algorithm.
For all versions, within the arrays:
0 represents a passa... |
"""A generic rest serving layer for NDB models."""
import logging
import sys
from google.appengine.api import namespace_manager
from google.appengine.ext import db
import flask
import flask.views
from appengine import user
def command(func):
"""Command decorator - automatically dispatches methods."""
setattr(f... |
#!/usr/bin/env python3
import sys
import os
import argparse
import json
import random
import shutil
import copy
import pickle
import torch
from torch import cuda
import numpy as np
import time
import logging
from tokenizer import Tokenizer
from utils import *
from torch.nn.utils.rnn import pad_sequence
parser = argpa... |
import json
import logging
import platform
import re
from io import BytesIO
from subprocess import check_output, CalledProcessError
import time
import os
import yaml
from binstar_client import errors
from binstar_client.utils import get_server_api, store_token
from binstar_client.utils.notebook.inflection import para... |
""" This exercises and tests Ellis.py """
import pytest
import socket
import json
TEST_FORMAT = [{'name':'Potato', 'region':'potato'}, {'name':'Potato2', 'region':'potato'}]
TEST_JSON = '[{"name":"Potato","region":"potato"},{"name":"Potato2","region":"potato"}]\n'
@pytest.fixture(autouse=True)
def patch_modules(mon... |
import os
import pandas as pd
import numpy as np
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
df_all = pd.read_csv("result_all.csv")
df_kanto = pd.read_csv("result_kanto.csv")
df_kanto_groupby = df_kanto.groupby("station_id", as_index=False).mean()
d... |
# Copyright 2019 1QBit
#
# 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 ... |
from matplotlib import pyplot as plt
import imageio
from scipy import ndimage
import math
import numpy as np
##
# @brief: Crop image ifname and store to ofname
# @param ifname: input file name
# @param ofnmae: output file name
# @param bb_dots: four dots defining the bounding box of what needs to be cropped
# @verbose... |
# Copyright 2019 Population Health Sciences and Image Analysis, German Center for Neurodegenerative Diseases(DZNE)
#
# 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://... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2019 <NAME> (Basalt AB)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version... |
from flask import Flask
import flask_login
from flask_sqlalchemy import SQLAlchemy
import yaml
import datetime
from werkzeug.security import generate_password_hash, check_password_hash
with open('./web/secret.yaml') as f: # 設定ファイル
secret = yaml.safe_load(f)
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_U... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@File : element_tree_xml_parser
@Author : 周恒-z50003220
@Email : <EMAIL>
@Create : 2019/8/12-10:21
@Python :Python 3.7.3
@IDE : PyCharm
@Version : 0.0.1
@Change_log
2019/8/12-10:21 created
"""
import re
from collections.abc import Iterable
from xml.e... |
"""
40. Combination Sum II
Medium
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.
Each number in candidates may only be used once in the combination.
Note: The solution set must not contain dupl... |
import tornado.ioloop
import tornado.web
from tornado.gen import coroutine
from tornado_swirl import api_routes
from tornado_swirl.swagger import Application, describe, restapi, schema, add_global_tag, add_security_scheme
from tornado_swirl.openapi import security
describe(title='Test API', description='Just things ... |
import numpy as np
import rasterio
from rasterio import Affine
from rasterio.warp import reproject, Resampling
import types
import tqdm
from rasterio.windows import Window
from rasterio.coords import BoundingBox
import shapely
import pyproj
from functools import partial
from spacenetutilities import geoTools as gT
de... |
from __future__ import unicode_literals, absolute_import
import json
import urlquick
from requests.auth import AuthBase
from mediasetinfinity.support import strings, logger
from mediasetinfinity.support.routing import utils, callback
BASE_URL = "https://api.one.accedo.tv"
APP_KEY = "6023de431de1c4001877be3b"
GID = "de... |
import argparse
import importlib
import os
import subprocess
import time
from doctr.travis import run_command_hiding_token as doctr_run
from . import sensitive_env
from .utils import load_graph
BUILD_URL_KEY = "CIRCLE_BUILD_URL"
INT_SCRIPT_DICT = {
0: {"module": "all_feedstocks", "func": "main"},
1: {"modul... |
import contextlib
import tempfile
import shutil
import random
import pytest
import gevent
from gevent import socket
from geth import ( # noqa: E402
LoggingMixin,
DevGethProcess,
)
class GethProcess(LoggingMixin, DevGethProcess):
pass
def get_open_port():
s = socket.socket(socket.AF_INET, socket.... |
from __future__ import annotations
from enum import Enum
from typing import List, Tuple
import random
def roll_dice() -> int:
return random.randint(1, 6)
def pretty_print_enum(enum: Enum):
return " ".join(list(map(lambda s: s.lower().capitalize(), enum.name.split("_"))))
class Room(Enum):
STUDY = 1
LIBRARY = 2
... |
from nesta.core.orms.orm_utils import db_session
from nesta.core.orms.orm_utils import get_mysql_engine
from nesta.core.orms.mag_orm import FieldOfStudy as FoS
from more_itertools import unique_everseen
from collections import defaultdict
import json
class _UniqueList(list):
"""List with insert-ordered unique ent... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 13 15:31:35 2021
@author: <NAME>, BSE, UW-SMPH '24
"""
import time
import pickle
import collections
from Bio import Entrez
from Bio import Medline
import nltk
from http.client import HTTPException
# You must enter your email and the toolname for Entre... |
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from p... |
from algorithms.classic.sample_based.core.vertex import Vertex
from structures import Point
from structures.tracked import Tracked
from structures.factory import prefer_tracked
from simulator.services.services import Services
import torch
from abc import ABC, abstractmethod
from typing import Callable, List, Tuple, An... |
"""Comparing low vs. high dimensions/embeddings."""
# -------------------------------
# Name : flameplot.py
# Author : Erdogan.Taskesen
# Licence : See licences
# -------------------------------
# %% Libraries
import os
import numpy as np
from tqdm import tqdm
from scipy.spatial.distance import pdist
... |
'''
Runs unit tests on Reporters
'''
import unittest
import Tests.utils
import Reporters, Monitors
class TestBaseReporter(unittest.TestCase):
def setUp(self):
self.base_reporter = Reporters.Base_Reporter()
# Tests whether the Base_Reporter class initalizes correctly
# Should have methods updat... |
# -*- coding: utf-8 *-*
# Copyright (C) 2011-2012 Canonical Services Ltd
#
# 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 us... |
import argparse
import importlib
import traceback
import sys
import os
__version__ = "1.1"
def execute(command, phase):
""" executes a command inside a phase """
try:
print(phase)
input("EXECUTE : " + command)
return os.system(command)
except Exception as e:
print("SOMETH... |
"""
FCN16 class.
Library: Tensowflow 2.2.0, pyTorch 1.5.1
Author: <NAME>
Email: <EMAIL>
"""
from __future__ import absolute_import, division, print_function
import torch
from ..encoders.squeeze_extractor import *
class FCN16(torch.nn.Module):
def __init__(self, n_classes, pretrained_model: SqueezeExtractor):
s... |
import argparse
import xml.etree.ElementTree as ET
import requests
import numpy
from progress.bar import Bar
bar = Bar('Sending', max=4000)
try :
dictdata = numpy.load("stockDictionary.npy",allow_pickle=True)
except :
if args.downloadStock or args.syncDictionary :
pass
else:
print("Try ... |
''' Translation functions that take Cells/Devices in different types of languages
and convert them to Cells/Devices in other languages
Supported: phidl, pya (GSI version), klayout.db (standalone version)
Not yet supported: nazca, IPKISS, gdspy, other suggestions?
'''
import os
default_phidl_portlayer = 41... |
"""Init tables
Revision ID: 645807399320
Revises:
Create Date: 2019-06-21 13:14:40.700747+00:00
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '645807399320'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto ... |
from datetime import date, datetime
from django.forms import model_to_dict
from django.http import JsonResponse
from django.shortcuts import render
from django.views.generic.base import View
from .models import *
from django.core.files.storage import default_storage
#from django.views.decorators.csrf import csrf... |
# Modifications © 2020 Hashmap, Inc
#
# 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 wr... |
import tensorflow as tf
import logging
from tqdm import tqdm
import numpy as np
import time
import os
from RAM import RAMNetwork
from input_fn import get_data
from utility import Utility, auto_adjust_flags
from Visualization import Visualization
def eval(model, sess, FLAGS, handle, num_batches, writer, pr... |
# Python tool to convert an image to map for the Anarch game. The input image
# has to be in gif format.
#
# by drummyfish
# released under CC0 1.0.
import sys
from PIL import Image
elementTypes = [
"NONE",
"BARREL",
"HEALTH",
"BULLETS",
"ROCKETS",
"PLASMA",
"TREE",
"FINISH",
"TELE... |
#!/usr/bin/env python
"""Performs the big scrape."""
import argparse
import datetime
import json
import logging
import os
import re
from typing import Any, Dict, FrozenSet, Iterator
import wikipron # type: ignore
from data.scrape.lib.codes import (
LANGUAGES_PATH,
LOGGING_PATH,
PHONES_DIRECTORY,
TS... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
# Copyright (c) 2017. <NAME>. All rights reserved. #
# See the accompanying LICENSE file for terms. #
# ... |
# training CNN with ESC-50 dataset
# from https://qiita.com/cvusk/items/61cdbce80785eaf28349
import os
#import random
import numpy as np
import pandas as pd
import librosa
import librosa.display
#import matplotlib.pyplot as plt
#import seaborn as sn
from sklearn import model_selection
#from sklearn import preprocessing... |
import sys
import inspect
from collections import namedtuple
from functools import update_wrapper
if sys.version_info < (3,): # Python 2
from httplib import responses as http_reasons
from cStringIO import StringIO as BytesIO
from urlparse import urlparse, parse_qsl
def _exec(code, g):
exec... |
import logging
import os
import shutil
import zipfile
from concurrent.futures import ThreadPoolExecutor, wait
from threading import Thread
from urllib.request import urlopen
import boto3
import requests
from bs4 import BeautifulSoup
import newstools
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def ge... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import time
import csv
import statistics
from utils import *
def test_client_request(cmd, ip = '127.0.0.1', port = 9999):
BUFSIZE = 1024
client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
client.sendto(cmd.encode('utf-8'), (ip, port))
data,se... |
import os
import sys
import json
import yfinance as yf
import pandas as pd
from .items import Portfolio, Holding
from .utils import get_one_price, get_many_prices, color_picker
class Game:
def __init__(self, mcl_path):
config = os.path.join(mcl_path, "config.json")
with open(config, 'r') as f:
... |
import docx
import glob
import pandas as pd
import numpy as np
import io
import csv
from docx import table
class ProtocolData(object):
"""
Required data from all protocols in a folder
"""
def __init__(self, path):
self.file_list = glob.glob(path + '/*-ПРЧ.docx')
self.parsed_data = {}
... |
from syn.five import xrange, STR
from collections import Sequence, MutableSequence
from .logic import implies
from .py import getitem
#-------------------------------------------------------------------------------
# ListView
class ListView(MutableSequence):
'''A list view.'''
def __init__(self, lst, start,... |
from bokeh.io import output_file
from bokeh.layouts import column, row
from bokeh.models import HoverTool
from bokeh.models.callbacks import CustomJS
from bokeh.models.widgets import Select
from bokeh.plotting import figure, ColumnDataSource, save
import json
import numpy as np
import sobol_seq
class Slice1D:
de... |
"""
This script allows to automate basic gameplay of the Idle Breakout game.
https://armorgames.com/idle-breakout-game/18584
"""
import time
import numpy as np
import cv2
import pyautogui as gui
from utils import show, dump
from frames_provider import FramesProvider, FrameSources
def detect_bricks(
i... |
import pytest
from runtime_context import Context, RuntimeContextWrapper
def test_rc_basics(rc):
"""
Basics are:
* calling creates a context manager
* nested contexts inherit values from contexts above
* unknown attributes raise AttributeError
"""
with rc(a=1):
assert... |
# The MIT License (MIT)
#
# Copyright (C) 2015 - <NAME> <<EMAIL>>
# 2015 - <NAME> <<EMAIL>>
#
# 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 with... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.