text stringlengths 3.07k 12.6k |
|---|
from functools import reduce
from os import listdir
from os.path import join, splitext
from re import M
from re import search as re_search
from typing import Any, Union
from docopt import docopt
from snakypy.helpers.ansi import FG, NONE
from snakypy.helpers.logging import Log
from snakypy.zshpower import __info__
fro... |
"""Test all functions related to the basic accessory implementation.
This includes tests for all mock object types.
"""
from unittest.mock import patch
# pylint: disable=unused-import
from pyhap.loader import get_serv_loader, get_char_loader # noqa F401
from homeassistant.components.homekit.accessories import (
... |
from wk import web
import wk
from wk.web import join_path
from wk.web.modules.login import LoginManager
from wk.web.modules.apis.aliyun import AliyunSmsService
from wk.web.modules.apis.qq import get_openid, get_user_info
from wk.web.modules.email import EmailSender
from wk import PointDict, Pather
from flask_restful im... |
from collections import OrderedDict
import torch.nn as nn
import torch
__all__ = ['resnet50']
class Bottleneck(nn.Module):
"""
Base class for Bottlenecks.
'forward()' method has been implemented.
"""
expansion = 4
def __init__(self, inplanes, planes, groups, reduction, stride=1, downsample... |
"""Runtime API."""
import abc
from typing import NamedTuple, Any, Dict, List, Tuple, Awaitable
import http
import json
# import os
import tornado.concurrent
import tornado.ioloop
import tornado.web
import tornado.platform.asyncio
import tornado.httpclient
from tornado.escape import json_encode, json_decode
from ... |
# -*- coding: utf-8 -*-
import click
import logging
from pathlib import WindowsPath
from pathlib import Path
from dotenv import find_dotenv, load_dotenv
from kaggle.api.kaggle_api_extended import KaggleApi
from zipfile import ZipFile
from typing import Tuple, List
import pandas as pd
from joblib import load
@click.co... |
# Unit 6: Fun with Words
"""
A portmanteau word is a blend of two or more words, like 'mathelete',
which comes from 'math' and 'athelete'. You will write a function to
find the 'best' portmanteau word from a list of dictionary words.
Because 'portmanteau' is so easy to misspell, we will call our
function 'natalie' in... |
'''
Created on Feb 15, 2015
@author: <NAME> <<EMAIL>>
'''
from __future__ import division
import select
import subprocess as sp
import os
import threading
import six
class WorkerThread(object):
""" class that launches a worker thread as a daemon that applies a given
function """
def __init__(sel... |
import math
import numpy as np
from scipy import stats
def _memoize(f):
# custom memoization decorator for _makeA, which works around the
# fact that a numpy array is not inherently hashable
class memodict(dict):
def __init__(self, f):
self.f = f
def __call__(self, sig):
... |
# tasks.py -- task to remove old and uploaded packages from Debexpo
#
# This file is part of debexpo -
# https://salsa.debian.org/mentors.debian.net-team/debexpo
#
# Copyright © 2011 <NAME> <<EMAIL>>
# Copyright © 2020 <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person
# obta... |
#!/usr/bin/env python
import Tkinter, Pmw
import math, whrandom, Numeric, copy, time
from scitools.CanvasCoords import CanvasCoords
C = CanvasCoords() # transformation object
# default values
C.set_coordinate_system(400,800,200,200)
from vtk import *
import vtkTkRenderWidget
from model1 import *
class Plane... |
'''After escaping the pirate's cave without drowning, you stumble upon a
field where it's rumored a lot of gold can be found. You even have a map that
shows where all of the biggest hauls are located!
Unfortunately, the sun is going down, so you don't have a ton of time to
search. You decide to take one quick pass thr... |
# Copyright (c) 2020 UAVCAN Consortium
# This software is distributed under the terms of the MIT License.
# Author: <NAME> <<EMAIL>>
import typing
import asyncio
import logging
import pathlib
import pytest
import pyuavcan
from pyuavcan.transport.can import CANTransport
from pyuavcan.presentation import Presentation
fr... |
# -*- coding: UTF-8 -*
'''
Created on 2018-06-15
@author: trb
'''
from pymongo import ASCENDING, DESCENDING
import six
class Manager(object):
def __init__(self, db=None, model=None):
self.db = db
self.model = model
def find(self, *args, **kwargs):
query = QuerySet(self)
if a... |
import os
import builtins
from io import BytesIO
from pathlib import Path
from json import load
from warnings import warn
from unittest import mock
import pytest
from PIL import Image, ImageCms, UnidentifiedImageError
from pillow_heif import (
register_heif_opener,
options,
HeifBrand,
)
register_heif_ope... |
from brainiak.eventseg.event import EventSegment
from scipy.special import comb
import numpy as np
import pytest
from sklearn.exceptions import NotFittedError
def test_create_event_segmentation():
es = EventSegment(5)
assert es, "Invalid EventSegment instance"
def test_fit_shapes():
K = 5
V = 3
... |
"""wrap.py - wrapper classes for mongoengine Documents."""
from .doc import Doc
from .game_factory import GolfGameFactory
class DCourse(Doc):
def setStats(self):
"""Par totals."""
self.out_tot = sum([hole.par for hole in self.holes[:9]])
self.in_tot = sum([hole.par for hole in self.holes[9:]])
self.... |
import argparse
from collections import defaultdict
import pathlib
import re
from defusedxml import ElementTree
xml = """<?xml version="1.0"?>
<package>
<name>ros_tutorials</name>
<version>0.10.2</version>
<description>
ros_tutorials contains packages that demonstrate various features of ROS,
as well a... |
# math AAT (Alternative Assessment Tool)
# python math project - chapter 2 - numerical methods
# Newton's Backward Interpolation Formula
# 18th October, 2015
import time
diff_file = open('NewtonBIF.txt', 'w')
diff_file.close()
def factorialfunc(n):
'''
Returns the factorial of a positive integer.
'''
... |
# <NAME> - I.D 316113422, <NAME> - I.D 206197816
import numpy as np
import ast
import torch
import os
from my_detectron2 import *
# def run1(myAnnFileName, buses):
#
# annFileNameGT = os.path.join(os.getcwd(),'annotationsTrain.txt')
# writtenAnnsLines = {}
# annFileEstimations = open(myAnnFileName, 'w+')
#... |
# Copyright (c) 2019 <NAME> UCSB
# Licensed under BSD 2-Clause [see LICENSE for details]
# Written by <NAME>
#This file contains functions used with ABRS
import numpy as np
import scipy
from scipy import ndimage
from scipy import misc
import time
import matplotlib.pyplot as plt
import os
from ABRS_modules import eth... |
import fitbit
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from ast import literal_eval
# 更新時間管理など
import datetime
import time
# Ctrl+Cで終了時の処理のため
import signal
import sys
# モジュール変数の定義
import config
# OSC関係のため
import argparse
from pythonosc import osc_message_builder
... |
"""
Unit and regression test for the mapsci package.
"""
# Import package, test suite, and other packages as needed
import mapsci
import pytest
import sys
import os
import logging
import random
logger = logging.getLogger(__name__)
temperature = 273 # [K]
bead_library = {
"CO2": {'epsilon': 353.55, 'sigma': 3.741... |
import json
import torch
import shutil
import os
import logging
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime as dt
# %%
class Report():
def __init__(self, filename='report', file_format='md') -> None:
self.file = filename
self.format = file_format
self.f... |
from flask import Flask, jsonify, request, send_from_directory
import requests
from threading import Thread
import os
import shutil
app = Flask(__name__)
app.config['UPLOAD_FOLDER']='usersContent'
def verifyJson(dadosNext):
tempHTML = ''
if (len(list(dadosNext)) > 0):
for dado in dadosNext:
... |
from django.shortcuts import render,redirect,get_object_or_404
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden, Http404, HttpResponseNotFound,QueryDict
from .models import Order,Comments,Transaction
from bike.models import Bike,Photo
from participator.models import Participator
from ... |
from __future__ import print_function
import sys
import xlrd
exporter_path = '/usr/src/app/'
sys.path.append( exporter_path )
from exporter import objects
from tweaker import DatabaseTweaker
debugging = True
logger = None
def main( fileposition, config, log ) :
global logger
logger = log
data, object_name = ... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... |
import unittest
class DictNested(dict):
"""
Naive dictionary extension to work with deeply nested keys.
Class provides methods to get values and dictionaries from deeply nested
dictionary and set/reset/delete values in nested dictionary.
"""
def check_input(self, path):
if isinstance(s... |
import gensim.downloader
import numpy as np
from gensim.corpora import Dictionary
from gensim.models import TfidfModel
from argparse import ArgumentParser
from logging import Logger
from pathlib import Path
from typing import List
from speechless.edit_context.common import TimelineChange
from speechless.processing.an... |
# experiments run for FPDGD
import itertools
import numpy as np
from multiprocessing import Pool
from tqdm import tqdm
from data.LetorDataset import LetorDataset
from clickModel.click_simulate import CcmClickModel
from client.federated_optimize import train_uniform
from ranker.PDGDLinearRanker import PDGDLinearRanker... |
import torch
from torch import nn
from torch.autograd import Variable
from torch.nn import functional as F
import torch.utils.data
from torchvision.models.inception import inception_v3
import numpy as np
from scipy.stats import entropy
# DCGAN
class generator(nn.Module):
def __init__(self):
super(generat... |
#!/usr/bin/env python
##########################################################################
# Copyright 2019 Kata.ai
#
# 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.ap... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: GAN.py
# Author: <NAME> <<EMAIL>>
import tensorflow as tf
import numpy as np
import time
from tensorpack import (FeedfreeTrainerBase, QueueInput,
ModelDesc, DataFlow, StagingInputWrapper,
MultiGPUTrainerBase, LeastLoa... |
import csv
import datetime
import io
import logging
import re
import tablib
from dateutil.parser import parse as dateparse
from import_export.fields import Field
from import_export.resources import ModelResource
from import_export.instance_loaders import CachedInstanceLoader
from import_export.results import Error, Re... |
#!/usr/bin/env python
# coding=utf-8
# aeneas is a Python/C library and a set of tools
# to automagically synchronize audio and text (aka forced alignment)
#
# Copyright (C) 2012-2013, <NAME> (www.albertopettarin.it)
# Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it)
# Copyright (C) 2015-2017, <NAME> (www... |
__author__="<NAME>, <NAME>"
__copyright__="January 31, 2016"
__version__= 2
import queue
import threading
import socket
from utility import *
from constants import *
# from lidar_servo_driver import turnTo
##############################
# PROGRAM MAIN ENTRY POINT #
##############################
def main():
lt... |
import os, os.path
import csv
import math
import numpy
import gzip
from isodist.Isochrone import Isochrone, FEH2Z, Z2FEH, dict2recarray
from isodist.PadovaIsochrone import _DATADIR
_ANZSOLAR= 0.0176
_ZS= [-0.1,-0.2,-0.3,-0.5,-1.,-1.5,-2.,-3.,0.,0.1,0.2,0.4]
class AnIsochrone (Isochrone):
"""Class that represents a ... |
# -*- coding: utf-8 -*-
# from contextlib import contextmanager
from datetime import datetime, timedelta
import requests
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import Screen
from kivy.weakproxy import WeakProxy
from kivymd.uix.bottomsheet import... |
import logging
from dataclasses import dataclass
import csv
@dataclass
class Analogy:
q_1_type: str
q_1_id: str
q_2_type: str
q_2_id: str
p_type: str
p_id: str
q_1_source: str
q_1_source_id: str
q_1_source_context: str
q_1_target: str
q_1_target_id: str
q_1_target_conte... |
import sys
import time
import re
import os
import configparser
from datetime import datetime, date
from influxdb import InfluxDBClient
from pyunifi import controller
# Logging Related
import logging
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s',
stream=sys.stderr, level=logg... |
from contextlib import contextmanager
from copy import deepcopy
import math
from .util import Geometry
class Leaf:
def __init__(self, level, data):
self.value = data
self.level = level
if self.level < 0:
raise ValueError(self.level)
def clone(self, level):
return... |
"""
Code to visualize Gaussian processes.
"""
import numpy as np
import matplotlib.pyplot as plt
def visualize_gp(gp, domain, data=None, n_grid=500, n_gen=20000, n_samp_plot=10,
std_mult=3, show_sp=True, ylim=[-4, 4], save_str=None,
exact_post=True):
"""
Visualize gp posteri... |
import os
import frappe
from PIL import Image
from frappe.utils import cint
def is_image_path(path):
if not path:
return
exts = ["jpg", "jpeg", "png"]
path = path.lower()
for e in exts:
if e in path:
return True
return False
def get_extension(filename):
s = filename.rsplit('.', 1)
retur... |
from typing import Callable, Optional
import pp
from pp.add_tapers import add_tapers
from pp.component import Component
from pp.components.grating_coupler.elliptical_trenches import (
grating_coupler_te,
grating_coupler_tm,
)
from pp.components.taper import taper
from pp.container import container
from pp.rout... |
from CHECLabPy.core.io import TIOReader
import numpy as np
from numba import njit, prange, float32, float64, guvectorize
from scipy.ndimage import correlate1d
from scipy import interpolate
path = "/Users/Jason/Software/CHECLabPy/refdata/Run17473_r1.tio"
r = TIOReader(path)
ref_path = r.reference_pulse_path
wf = r[0]
... |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may n... |
import gym
import time
from balboa.a_star import AStar
import numpy as np
from balboa.BalboaRPiSlaveDemo.lsm6 import LSM6
"""
Instructions
Gyro calibration
The /balboa/__init__.py should be customized with the gyro calibration coefficients
To obtain them, run the calibrate_gyro script: python3 -m balboa.characterizati... |
from locale import DAY_2
import streamlit as st
import numpy as np
import pandas as pd
import sqlalchemy as sa
import classes
import config
from sqlalchemy import orm
import pydeck as pdk
@st.experimental_singleton
def getSqlEngine():
return sa.create_engine(config.SQL_ADDRESS, echo=False, future=True)
@st.expe... |
from django.contrib import admin
from django.contrib.admin.templatetags.admin_urls import add_preserved_filters
from django.conf.urls import url
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.conf import settings
from django.utils import timezone
from django.utils.translation i... |
import math
from math import pi
import numpy as np
from gym.spaces import Box, Discrete
from ray.rllib.utils import merge_dicts
from ray.rllib.env.multi_agent_env import MultiAgentEnv
def direction_to_coord(direction):
"""takes x \in [0,1), returns 2d coords on unit circle"""
return tuple([math.cos(2*pi*direc... |
"""Handle multiple samples present on a single flowcell
Merges samples located in multiple lanes on a flowcell. Unique sample names identify
items to combine within a group.
"""
import os
import shutil
import subprocess
from bcbio import bam, utils
from bcbio.distributed.transaction import file_transaction, tx_tmpdir... |
import math
import sys
import typing
import numpy as np
from analysis import plot_common
from analysis import video_analysis
from analysis import video_data
from analysis import video_utils
def gnuplot_acceleration(stream: typing.TextIO=sys.stdout) -> typing.List[str]:
timebase = video_analysis.ground_speed_tim... |
# -*- coding: utf-8 -*-
import os
import glob
# define sone struct
ROOT_PATH = 'I:/Documents/Database/' # root path
FOLDER_NAME_FORMAT = '%04d/'
RAW_DATA_FOLDER = 'frames_cleanpass/TRAIN/%s/'
LABLE_FOLDER = 'disparity/TRAIN/%s/'
LEFT_FOLDER = 'left/'
RIGHT_FOLDER = 'right/'
FILE_NAME = '%s%04d'
RAW_DATA_TYPE = '.png... |
from keras.layers.core import Activation, Dropout
from keras.layers.convolutional import Conv2D
from keras.layers.merge import Concatenate
from keras.layers.normalization import BatchNormalization
from keras.regularizers import l2
from keras.models import Model
from ..encoder import build_encoder, scope_table
from ..u... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# protocon/conversion.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this lis... |
# Copyright 2018/2019 The RLgraph authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
from __future__ import print_function
import sys
import argparse
import os
from collections import namedtuple
from statsmodels.stats.proportion import proportion_confint
# Appending current working directory to sys.path
# So that user can run randomtester from the directory where sut.py is located
current_working_dir... |
import logging
import openpyxl
from ExcelRobot.reader import ExcelReader
from ExcelRobot.utils import (BoolFormat, DataType, DateFormat, NumberFormat,
copy_file, del_file, excel_name2coord,
get_file_path, is_file, random_temp_file)
from six import PY2
from xl... |
"""
.. ma.py
Moving averages.
"""
## Inheritance
import base
## Math
import math
inf = float('inf')
class EMA(base.Mover):
""" A fast exponential moving average with typical period of size *n*.
This is practically O(m) where m is the data size, regardless of the size
of *n*. If *mstd*, moving standard ... |
import mongoengine
import datetime
from Alert import Alert
from Connection import Connection
from Mails import Mail
from Status import Status
from Subject import Subject
from Event import Event
import sys
class Data:
INIT = False
mongoip = "NotYetDeclared"
def global_init():
if not Data.INIT:
if D... |
import re
from collections import defaultdict
from typing import Any, List, Tuple
from daily_solutions.base import BaseDailySolution
"""
You come across a field of hydrothermal vents on the ocean floor! These vents constantly produce large, opaque clouds,
so it would be best to avoid them if possible.
They tend to f... |
# coding=utf-8
from __future__ import division, absolute_import, print_function
from base64 import b64encode
from fractions import gcd
from random import randrange
from collections import namedtuple
from math import log
from binascii import hexlify, unhexlify
import sys
PY3 = sys.version_info[0] == 3
if PY3:
bina... |
from datetime import datetime
from bson import ObjectId
from lib.mongo import (
negotiation_collection,
details_collection,
bids_collection,
members_collection,
)
NEGOTIATION_ASCENDING = "ascending"
NEGOTIATION_DESCENDING = "descending"
def get_negotiation(negotiation_id):
negotiation_id = Obje... |
"""
Copyright (C) 2012-2013 <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, modify, merge, publish, distribute, su... |
import os
import glob
import time
import random
from PIL import Image
import numpy as np
import trimesh
from src.data.core import Field
from pdb import set_trace as st
from src.data.add_sensor import *
class IndexField(Field):
''' Basic index field.'''
def load(self, model_path, idx, category):
''' Lo... |
import asyncio
import discord
from discord.ext import commands
from clam.utils import db, emojis
from clam.utils.errors import PrivateCog
class ArchivedChannels(db.Table, table_name="archived_channels"):
id = db.PrimaryKeyColumn()
channel_id = db.Column(db.Integer(big=True))
category_id = db.Column(db.... |
# Aces, Twos, Threes, Fours, fives and Sixes
def get_number_of_eyes_for_number(roll, number):
return get_number_of_hits_for_number(roll, number) * number
def get_number_of_hits_for_number(roll, number):
return [roll[key] for key in roll].count(number)
def get_aces(roll):
"""
This function returns ... |
# Copyright 2018- Onai (Onu Technology, Inc., San Jose, California)
#
# 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, co... |
import argparse
import time
import config
from data_operations.dataset_feed import create_dataset
from data_operations.data_preprocessing import import_cbisddsm_training_dataset, import_minimias_dataset, \
dataset_stratified_split, generate_image_transforms, import_cbisddsm_testing_dataset
from data_visualisation.... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from PIL import Image
import random
import math
import torch
from torchvision.transforms import *
class Random2DTranslation(object):
"""
With a probability, first increase image size to (... |
r"""
Produces a plot of the densities of infall, star formation, and gas as a
function of simulation time for all models.
"""
from .. import env
from .utils import (named_colors, mpl_loc, yticklabel_formatter,
dummy_background_axes)
from ..._globals import ZONE_WIDTH
import matplotlib.pyplot as plt
import math as m
i... |
# -*- coding: utf-8 -*-
import numpy as np
from scipy import linalg
from scipy.special import logsumexp
from emgpb2.states import Gaussian, GMM
from emgpb2.utils import Utility
class KalmanFilter:
""" """
@staticmethod
def filter(state, measurement, model, initial=False, shape=None):
# Transitio... |
import sys
from typing import *
import requests
import json
from urllib.parse import urlparse
from gravsdk import gravcrud
class GravError(Exception):
"""
# Exception Class: `GravError`
Exception raised for general SDK errors
|Attribute|Description|
|-|-|
|`responsetext`|Descriptive text of the... |
import asyncio
from collections import defaultdict
from datetime import date
from datetime import datetime
import json
import itertools as itt
import pandas as pd
from pathlib import Path
import re
class UserInteractionCollector:
def __init__(self, client):
self.client = client
self.reset_users() ... |
"""
Process launcher for run an ad-hoc job
"""
import yaml
import json
import datetime
import tempfile
import time
import sys
import os
from msbase.utils import getenv, datetime_str
from msbase.logging import logger
from common import get_jobs_config
from model import DB
from resource import Resource
from notif impor... |
import json
from types import MethodType
from typing import Sequence, List, Dict, Any
from pytest import fixture, raises
from tenark.common import (
QueryParser, TenantRetrievalError)
from tenark.models import Tenant
from tenark.cataloguer import SchemaCataloguer
@fixture
def connection():
class MockConnectio... |
import json
from avatar.templatetags.avatar_tags import avatar_url
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.db import transaction, DatabaseError
from django.http import HttpResponseForbidden, JsonResponse, HttpResponseBadR... |
import numpy as np
from networkx.algorithms.centrality import current_flow_betweenness_centrality
from networkx.algorithms.centrality import degree_centrality, betweenness_centrality, eigenvector_centrality
from numba import njit
from numba import types
from numba.typed import Dict
from scipy.ndimage import distance_tr... |
# Importando as bibliotecas relevantes
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import datetime as dt
# Passos iniciais
df = pd.read_csv('CRDS_Jaragua_G2301_hour_LT.txt') # dataframe de trabalho
df = df.set_index('DATE_TIME') # definição da coluna 'DATE-TIME' como index
df.index = pd.... |
from . import Plot
from data import DAILY, TimeSeries
from keras.callbacks import ModelCheckpoint, EarlyStopping
from keras.layers import Conv1D, Dropout, LeakyReLU, LSTM
from keras.models import Sequential, load_model
import numpy
import os
import random
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" # disable the verbose... |
"""Calulate zonal statistics and return a json or a geojson."""
import logging
from collections import defaultdict
from datetime import datetime
from json import dump, load
from urllib.parse import urlencode
from app.caching import cache_file, get_json_file
from app.timer import timed
import rasterio
from rasterstat... |
# network create wireguard interface
from .ip_wrapper import ip_wrapper, Ip_Wrapper_Command_Error
from .network_create_namespace import netns_setdns
import wgconfig
from pprint import pprint
def wireguard_config_load(interface_name):
"""Load config from file."""
wc = wgconfig.WGConfig(interface_name)
try... |
"""
.. module stratumgs.game.runner
Classes and helpers in this module create and manage engine runners, which
manage the game engines which run as background processes.
"""
import json
import multiprocessing
import os
import tornado.ioloop
import tornado.iostream
import stratumgs.client.proxy
import stratumgs.gam... |
import os, sys
import time
import argparse
import configparser
import numpy as np
import warnings
warnings.filterwarnings("ignore", category=RuntimeWarning)
from keras.models import load_model
sys.path.append('../src/')
from python import helper as hp
from python import fixed_parameters as FP
from python import da... |
from firebase_admin import credentials
from firebase_admin import firestore
from bs4 import BeautifulSoup
from utilities import sms
import firebase_admin
import requests
import sys
import re
import os
# Initializing Firebase Database called covid19
cred = credentials.Certificate(os.path.join(sys.path[0], 'fbapp.json')... |
from lxml import html
from json import dump,loads
from requests import get
import json
from re import sub
from dateutil import parser as dateparser
from time import sleep
def ParseReviews(asin):
amazon_url = 'http://www.amazon.in/dp/'+asin
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/5... |
from nltk.tree import Tree
def left_branching(tree):
t = Tree('NAN', [tree.leaves()[0]])
for i, l in enumerate(tree.leaves()[1:]):
t = Tree('NAN', [t, Tree('NAN', [l])])
return t
def right_branching(tree):
t = Tree('NAN', [tree.leaves()[-1]])
for i, l in enumerate(reversed(tree.leaves()[:-... |
import numpy as np
import os.path
from . import download
_folder_path = os.path.abspath("./TE_process/")
"""Setup names of data sets"""
_training_sets = []
_test_sets = []
for i in range(22):
_training_sets.append("d" + str(i).zfill(2) + ".dat")
_test_sets.append("d" + str(i).zfill(2) + "_te.dat")
def data_... |
from util.decorators import *
def test_background():
# Make a "result" object that gets a specific result from the
# parent function. Make that object callable and give it good help
# documentation.
# Define a function that can take a little while.
@background
def sleep(time):
from tim... |
import boto3
from botocore.exceptions import ClientError
import logging
import os
import time
logger = logging.getLogger(__name__)
logger.setLevel(os.getenv('LOG_LEVEL', 'INFO'))
# Collect environment variables
APPLICATION_NAME = os.getenv('APPLICATION_NAME')
ARTIFACT_BUCKET_ARN = os.getenv('ARTIFACT_BUCKET_ARN')
ART... |
import torch
import torch.nn as nn
from einops import rearrange, repeat
from ...common.base_model import BaseClassificationModel
from ...decoder.mlp import MLPDecoder
from ...encoder.embedding import LinearVideoEmbedding, PosEmbedding, TubeletEmbedding
from ...encoder.vanilla import VanillaEncoder
from ...encoder.vivi... |
#!/usr/bin/python3
from tornado.web import url,RequestHandler
from tornado.web import Application, RequestHandler
from tornado.ioloop import IOLoop
from tornado.httpserver import HTTPServer
import tornado.autoreload
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
import ... |
#!/usr/bin/python
# Copyright 2018 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
# The Expat License
#
# Copyright (c) 2020, <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, modify, merge... |
# -*- coding: utf-8 -*-
# @Time : 2019/8/23 11:49
# @Author : chensi
# @File : main_attack_baseline.py
# @Software : PyCharm
# @Desciption : None
import sys, argparse
sys.path.append("../")
from utils.load_data.load_data import *
from utils.load_data.load_attack_info import *
from model.attack_model... |
#coding=utf-8
'''
order /docs/*
'''
import os
import re
from functools import singledispatch
current_chap='chap5'
path_of_this_to_cata_dir='docs/'
def get_fnames(pattern:'re r-string')->'filenames_list':
'''
get filenames list
cwd : in files dir
'''
allfiles_lst = list(os.popen('ls -1 '... |
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
from numpy import fft
import cv2
from temp_004 import psf2otf
def motion_blur(gray, degree=7, angle=60):
gray = np.array(gray)
M = cv2.getRotationMatrix2D((round(degree / 2), round(degree / 2)), angle, 1)
motion_blur_kernel = np.diag(np.on... |
import time
import glob
import struct
import curses
import binascii
from multiprocessing import Process, Manager
from .utils import *
DWELL_TIME = 60
T = Manager().dict()
def parse_frame(data: Frame.data, signals: dict) -> dict:
message = {}
b = "".join("{0:08b}".format(i) for i in data)
for name, sign... |
import os
import sys
import time
import numpy as np
import configparser
import json
et = 1e-8
def load_json(path):
with open(path,'r') as load_f:
load_dict = json.load(load_f)
return load_dict
def save_json(path, data):
with open(path,'w') as f:
json.dump(data,f)
def print_dict(x):
for key in x:
print(k... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.