text stringlengths 3.07k 12.6k |
|---|
# Copyright 2015 Huawei Technologies Co., Ltd.
# 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
#
# Unl... |
import json, time
import os
from difflib import SequenceMatcher as SM
import tj,sys
from pyunpack import Archive
# import downloader
import urllib.request
FILE='D.json'
cwd=os.path.dirname(__file__)
if cwd!="":os.chdir(cwd)
D={}
D_List=[]
def setter():
dir_name=os.path.dirname(sys.argv[0])
link=r'https:/... |
from tkinter import *
# Root Widget Creation
root = Tk() # App instance
root.minsize(300,300) # App size
root.title('Tic Tac Toe') # Title
root.resizable(0,0) # No maximize
icon = PhotoImage(file='ttt.png') # Title Icon
root.iconphoto(False,ic... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# 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... |
"""
Handles command line and calls the email parser with corrent options.
"""
import argparse
import logging
import sys
import os
import shutil
import asyncio
import concurrent.futures
from itertools import islice
from functools import reduce
from multiprocessing import Manager
from . import const, Parser, config, fs... |
#na2s awl step ale bshel feha low complexity regions + get seeds remove which its score < S + extend and get score
Match ={
'A':{'A':1, 'T':2, 'G':3, 'C':4},
'T':{'A':2, 'T':1, 'G':2, 'C':2},
'G':{'A':3, 'T':2, 'G':1, 'C':3},
'C':{'A':4, 'T':2, 'G':3, 'C':1}
}
#multiple sequance every sequance in... |
"""Convert problem settings."""
import copy
from test.core.derivatives.utils import get_available_devices
from typing import Any, Iterator, List, Tuple
import torch
from torch import Tensor
from torch.nn.parameter import Parameter
from backpack import extend
from backpack.utils.subsampling import subsample
def mak... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
"""
This script deploys WebSocket/HTTP API Gateway using API Gateway Version 2.
Note: According to https://docs.aws.amazon.com/apigateway/latest/developerguide/api-ref.html
(still true on 2019-02-05)
* Amazon API Gateway Version 1 API Reference (for creating and deploying REST APIs)
* Amazon API Gateway Version 2 API ... |
"""
Creates and manages isolated build environments.
"""
import abc
import os
import platform
import shutil
import subprocess
import sys
import sysconfig
import tempfile
from types import TracebackType
from typing import Iterable, Optional, Tuple, Type
from ._compat import abstractproperty, add_metaclass
try:
imp... |
from torch.autograd import Variable
from DeepModel.NNutil import *
from DeepModel.feature_modeling import data_preparation
class SFCNet(nn.Module): # MLP方法
"""
这里选择的激活函数是sigmoid
"""
def __init__(self, input_channel, output_channel):
# 定义Net的初始化函数,这个函数定义了该神经网络的基本结构
super(SFCNet, self... |
"""Test the analysis.py file."""
import json
from kitsu_lib.analysis import (create_kitsu_database, filter_stream_urls, merge_anime_info, parse_categories,
summarize_streams)
from .configuration import TEST_DATA_DIR
# FYI: ^ Will rework functions in this file. Expect these to change
... |
import sys
sys.path.insert(0, '../')
import re
from Code.bigram import BigramModel
from Code.unigram import UnigramModel
DATA_PATH = '../DataSets/'
OUTPUT_DIR = "../Output/main/"
TRAINING_FILES_1 = {
'en': ['trainEN.txt'],
'fr': ['trainFR.txt'],
'ot': ['trainOT.txt']
}
# Legacy stuff
# TRAINING_FILES = {
# 'en'... |
"""Unittests for callsite."""
import ast
import inspect
import sys
import astor
from hamcrest import (
equal_to,
all_of,
assert_that,
contains,
has_properties,
has_property,
instance_of,
)
from . import callsite
def assert_ast(ast_node, code_str):
assert_that(astor.to_source(ast_nod... |
import re
def flatten_list(lis):
"""
Help function for using:create_experiment_list_pyGSTi
"""
from collections import Iterable
for item in lis:
if isinstance(item, Iterable) and not isinstance(item, str):
for x in flatten_list(item):
yield x
else:
... |
"""
Written by <NAME> - 2017
Definition of AlexNet architecture
"""
import tensorflow as tf
import train_util as tu
def cnn(x):
"""
AlexNet convolutional layers definition
Args:
x: tensor of shape [batch_size, width, height, channels]
Returns:
pool5: tensor with all convolutions, pooling and lrn operations... |
import requests
import os
import sys
import json
def checklist(data):
if len(data) > 0:
return True
def del_slash(path):
if path[0] == "/":
path = path[1:]
return path
def mkdir(data):
path = "".join(data)
r = requests.put(f"http://{hostname}:{port}/webhdfs/v1{hdfsPath}{path}?us... |
from twisted.trial import unittest
from twisted.words.protocols.jabber import error
from twisted.words.xish import domish
NS_XML = 'http://www.w3.org/XML/1998/namespace'
NS_STREAMS = 'http://etherx.jabber.org/streams'
NS_XMPP_STANZAS = 'urn:ietf:params:xml:ns:xmpp-stanzas'
class ErrorTest(unittest.TestCase):
de... |
"Flask app setup and creation; main entry point.."
import flask
import anubis.about
import anubis.call
import anubis.calls
import anubis.config
import anubis.review
import anubis.reviews
import anubis.proposal
import anubis.proposals
import anubis.decision
import anubis.grant
import anubis.grants
import anubis.site
i... |
import logging
import time
import typing
from pathlib import Path
import torch
import torch.nn.functional as F
from torch.cuda.amp import GradScaler, autocast
from torch.utils.data import DataLoader
from .checkpoint import Checkpoint, save_checkpoint
from .config import TrainingConfig
from .dataset import MelFunction... |
import pytest
from keyset_pagination.paginator import KeysetPaginator, InvalidPage
from ..models import Event, Location
@pytest.fixture
def events():
Event.objects.bulk_create([
Event(timestamp='2017-01-01T01:23:45Z', group="bar", reading=2),
Event(timestamp='2017-01-01T01:23:45Z', group="baz", ... |
import os
import sys
import time
import traceback
from typing import Union, Tuple, Any
import numpy as np
import cv2
from torch import Tensor
from building_footprint_segmentation.utils.date_time import get_time
from building_footprint_segmentation.utils.py_network import convert_tensor_to_numpy
def ha... |
#!/usr/bin/python
## Written by <NAME> 2019.04.01
## This script will create a JSON file from a list of descriptions and URLs
####################################################################################
## Script arguments:
## $4: username as string
## $4: <username> "optional"
## $5: school section bookmark l... |
# -*- coding: utf-8 -*-
import pandas as pd
from . import app
import numpy as np
import dash_html_components as html
from pyDOE import lhs
from diversipy.hycusampling import transform_spread_out, sukharev_grid, maximin_reconstruction, random_k_means, random_uniform
from diversipy.indicator import unanchored_L2_discrepa... |
import sys
import os
import time
import logging
from multiprocessing import Manager
from ruuvitag_sensor.data_formats import DataFormats
from ruuvitag_sensor.decoder import get_decoder, parse_mac
log = logging.getLogger(__name__)
if os.environ.get('RUUVI_BLE_ADAPTER') == 'Bleson':
from ruuvitag_sensor.adapters.... |
# -*- coding: utf-8 -*-
import platform, subprocess, json, os
import vc_tools
codec_name_image_list = ['jpg', 'jpeg', 'bmp', 'tif', 'png', 'gif', 'tga', 'ico', 'mjpeg']
def geturlMediaInfo(url):
baseinfo = {}
baseinfo['filesize'] = vc_tools.get_file_size(url)
if (platform.system()=='Windows'):
... |
"""
General collection of functions for manipulating dataframes, generally to isolate proteins or peptides that fit the criteria of interest.
"""
import numpy as np
import pandas as pd
from scipy import stats
import os
import logging
from ProteomicsUtils.LoggerConfig import logger_config
logger = logger_config(__name_... |
# Copyright 2011 <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, softw... |
import random
import heapq
import numpy as np
from Bio import SeqIO
from itertools import groupby, tee
from typing import List, Tuple, Dict
from .functional import fst, snd
def get_key_length_pairs(input_fasta_file) -> List[Tuple[str, int]]:
"""
Given a fasta file, it computes the (key, length) list of pairs fo... |
# -*- coding: utf-8 -*-
from Scrape import Scrape
from Database import Database
from Download import Download
import argparse
import time
import Constant
import logging
import logging.config
from Kits import Kits
def logger_creator():
logging.config.dictConfig(Constant.LOG_CONGIF)
logger = logging... |
import sys
import pygame
from read_config import read_config
PLAYER_COLORS = ['red', 'blue', 'teal', 'purple', 'yellow', 'orange', 'brown', 'grey', 'pink']
def gui_process(config_path, mp_utils):
gui = GUI(config_path, mp_utils)
gui.gui_loop()
sys.exit(0)
class GUI:
def __init__(self, config_path... |
import torch
import cvxpy as cp
import time
import numpy as np
import pandas as pd
from enum import Enum
import sys
sys.path.append('..')
import OptMiniModule.util as optMini_util
import OptMiniModule.cvx_runpass as optMini_cvx
import basic_util as bUtil
import seaborn as sns
import matplotlib.pyplot as plt
sns.set... |
import json
import os
import warnings
from modularodm import fields, Q
from osf.exceptions import ValidationError
from modularodm import exceptions as modm_exceptions
from framework import exceptions as framework_exceptions
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
from... |
from behave import given, when, then
from test.behave_utils.utils import *
def _get_mirror_count():
with dbconn.connect(dbconn.DbURL(dbname='template1')) as conn:
sql = """SELECT count(*) FROM gp_segment_configuration WHERE role='m'"""
count_row = dbconn.execSQL(conn, sql).fetchone()
retu... |
import locale
from datetime import datetime
import re
try:
import babel.units as babel_units
except ImportError:
babel_units = None
try:
import babel.numbers as babel_numbers
except ImportError:
babel_numbers = None
from calculate_anything.logging_wrapper import LoggingWrapper as logging
from calculate_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import zbar
import requests
from PIL import Image
from io import BytesIO
from numpy import array, uint8
import base64
import urllib
import json
import logging
scanner = zbar.Scanner()
def decode(string):
try:
return str(
base64.urlsafe_... |
import pandas as pd
from sklearn.model_selection import train_test_split
from imblearn.over_sampling import SMOTE
from sklearn.pipeline import Pipeline
from feature_extraction.doc2vec_features import *
from feature_extraction.tfidf_features import *
from feature_extraction.word2vec_features import *
from models.models ... |
# 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... |
from django.shortcuts import render, redirect, get_object_or_404
from django.http import Http404
# Create your views here.
from .models import Post, Tag
from django.views.generic import CreateView, DetailView, ListView, UpdateView, RedirectView
from django.views.generic import DayArchiveView#, View, TemplateView
fro... |
from datetime import datetime
import pytest
from apscheduler.triggers.cron.fields import DayOfMonthField, BaseField, DayOfWeekField
from apscheduler.triggers.cron.expressions import (
AllExpression, RangeExpression, WeekdayPositionExpression, WeekdayRangeExpression, LastDayOfMonthExpression)
def test_all_expres... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 10 13:55:01 2022
@author: NBPub
"""
import sqlite3
from pathlib import Path
from mutagen.oggvorbis import OggVorbis
from mutagen.easyid3 import EasyID3
from mutagen.easymp4 import EasyMP4
import pandas as pd
from rich import print
con = sqlite3.connect('database.db') #... |
#!/usr/bin/python
import base64
import json
import os
import sys
import time
import xmlrpclib
TMP_RESULTS_FILE='./tmp-tests-output.txt'
def get_job_bundle_content(server, job):
bundle_sha = server.scheduler.job_status(str(job))['bundle_sha1']
bundle = server.dashboard.get(bundle_sha)
return json.loads(b... |
import json
import anafora
import sys
def parse_element(data: anafora.AnaforaData, set_to_super_interval=False):
clean_bad_links(data)
if set_to_super_interval:
data = check_year_of_sub_interval(data)
data_file = []
for ann in data.annotations:
first_spans = True
for... |
from __future__ import print_function
from __future__ import division
import json
import codecs
import argparse
import itertools
import re
from sentence_filters import multiword
def normalize(text, bool_normalize):
if not bool_normalize:
return text
text = text.lower()
tokens = re.split('([-.,;\(\... |
from django.shortcuts import render,redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404
from .forms import ProfileUpdateForm,UserUpdateForm,ProjectAddForm,ProjectRatingForm
from .mode... |
#!/usr/bin/python3
from mrcrowbar import models as mrc
from mrcrowbar.lib.images import base as img
# source: https://en.wikipedia.org/wiki/Segment_descriptor
# https://pdos.csail.mit.edu/6.828/2005/readings/i386/s05_01.htm
class SegmentDescriptor( mrc.Block ):
limit_low = mrc.UInt16_LE( 0x00 )
base_low ... |
#!/usr/bin/env python3
import os
import random
from Pong.utils import *
from Pong.constants import *
from Pong.components.balle import Balle
from Pong.components.paddle import Paddle
from Pong.components.background import Background
from Pong.components.score import Score
# see if we can load more than standard BMP
... |
# Naive Neural Network
# nn231 using numpy.
import numpy as np
def activations(t):
return {
'sigmoid': (lambda x: 1 / (1 + np.exp(-x)), lambda x: x * (1 - x), (0, 1), .45),
'tanh': (lambda x: np.tanh(x), lambda x: 1 - x**2, (0, -1), 0.005),
'ReLU': (lambda x: x * (x > 0), lambda x: x > 0,... |
import json
from collections import OrderedDict
from django import forms
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.template.loader import get_template
from django.urls import resolve
from django.utils.translation import ugettext_lazy as _, ugettext_noop
from i18nfi... |
#
# Copyright (c) <NAME>. All rights reserved.
# Licensed under the MIT License. See LICENSE file in the project root for full license information.
#
import clr
import re
__all__ = ("NetEnum", "ConstantTypes")
# ----------------------------------------------------------------------------
# Read only constant... |
"""
Genome, genetic map and demographic model definitions for Arabidopsis thaliana.
"""
import msprime
import numpy as np
import stdpopsim
###########################################################
#
# Genome definition
#
###########################################################
# Data for length information base... |
"""Base augmentations operators."""
import numpy as np
from PIL import Image, ImageOps, ImageEnhance
import torch
# ImageNet code should change this value
IMAGE_SIZE = 32
def int_parameter(level, maxval):
"""Helper function to scale `val` between 0 and maxval .
Args:
level: Level of the operation that will... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import re
import csv
import subprocess
import multiprocessing
import matplotlib.pyplot as plt
dataDir = "/root/dataset/"
inputSizes = ["small","med","large"]
keyfiles = ["key_file_50MB.txt","key_file_100MB.txt","key_file_500MB.txt"] # as 500M is too he... |
import argparse
import logging
logging.basicConfig(level=logging.INFO)
import datetime
import pandas as pd
import numpy as np
logger = logging.getLogger(__name__)
def main(filename_db,filename_t,category,today):
logger.info('Starting loading process')
df_db = _read_data(filename_db)
df_t... |
'''
Utility functions by Jack.
'''
from os import listdir, walk
from os.path import isfile, join, exists
from collections import Counter
import json
import random
import tensorflow as tf
def get_filepathes_from_dir(file_dir, include_sub_dir=False,
file_format=None, shuffle=False):
... |
""" Char level RNN to generate words.
We try to generate surnames from 18 languages given a language code.
"""
from __future__ import unicode_literals, print_function, division
from io import open
import glob
import os
import unicodedata
import string
import torch
import torch.nn as nn
import random
import matplotlib.... |
"""Some generic utility functions.
"""
import os
import re
import datetime
import xml.etree.ElementTree as ET
import owlready2
def asstring(expr, link='{name}', n=0, exclude_object=False):
"""Returns a string representation of `expr`, which may be an entity,
restriction, or logical expression of these. `lin... |
# -*- encoding: utf-8 -*-
from nose.tools import *
from nose import SkipTest
import networkx as nx
from networkx.utils import *
def test_is_string_like():
assert_true(is_string_like("aaaa"))
assert_false(is_string_like(None))
assert_false(is_string_like(123))
def test_iterable():
assert_false(iterab... |
import pytest
from common.mayastor import container_mod, mayastor_mod
from common.msclient import get_msclient
import mayastor_pb2 as pb
import uuid
from urllib.parse import urlparse
from common.command import run_cmd_async
from common.fio_spdk import FioSpdk
POOL_NAME = "pool1"
NEXUS_GUID = "9febdeb9-cb33-4166-a89d-... |
from tensorflow.core.framework.graph_pb2 import GraphDef
import os.path
import argparse
def merge_partitioned_graphs(partitioned_graphs):
merged_graph = GraphDef()
# TODO: for now we use first partitioned graph for version
merged_graph.versions.CopyFrom(partitioned_graphs[0].versions)
merged_graph.l... |
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
from nltk.stem import WordNetLemmatizer
import requests
def get_entries_and_thesaurus(word):
app_id = '' # oxford_api_id
app_key = '' # oxford_api_key
language = 'en-gb'
word_id = word
url = 'https://od-api.oxforddictionaries.com/api/v2/entries/' + language + '/' + word_id.lower()
r = requests... |
#!/usr/bin/python3
from mdutils.mdutils import MdUtils
title = '<h1><img src="https://emojis.slackmojis.com/emojis/images/1531849430/4246/blob-sunglasses.gif?1531849430" width="30"/> Hello World ! </h1> <hr>'
resume = 'My name is {}. I work as a {} at {}.'
visitors = ':
"""Calculate the rotation matrix from beam coordinates to
instrument head coordinates.
Parameters
----------
theta : is the angle of the heads (usually... |
"""
Copyright (c) 2018-2020 Intel Corporation
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 wri... |
from absl import app
import jax
from jax._src.numpy.lax_numpy import argsort, interp, zeros_like
import jax.numpy as jnp
from jaxopt import implicit_diff
from jaxopt import linear_solve
from jaxopt import OptaxSolver, GradientDescent
from matplotlib.pyplot import vlines
import optax
from sklearn import datasets
from sk... |
from __future__ import division
import torch
import torch.nn as nn
import os
import numpy as np
from scipy.ndimage import imread
import h5py
from network.net_track1 import make_model
from tools.utils import save_matv73, AverageMeter
class args:
def __init__(self):
super(CALayer, self).__init__()
... |
from abc import ABCMeta, abstractmethod
from typing import TypeVar, Generic
import math
from jmetal.core.solution import Solution
from jmetal.util.constraint_handling import overall_constraint_violation_degree
S = TypeVar('S')
class Comparator(Generic[S]):
__metaclass__= ABCMeta
@abstractmethod
def com... |
from glob import glob
import json
import os
import signal
import socket
import subprocess
import threading
import time
import warnings
import redis
from agentworker import (
EmulationStatus,
WorkerStatus
)
from agentworker.config import Config
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
def get... |
# -*- coding: utf-8 -*-
"""
Embedding D3 and three.js for Pelican
=====================================
This plugin allows you to easily embed D3 and three.js JS and CSS in Pelicans
configuration and also the header of individual articles or pages.
It also allows for for embedding article-specific D3.js versions.
""... |
from __future__ import division
import torch
from abc import ABC, abstractmethod
from collections import defaultdict
import numpy as np
from torchvision.transforms import Compose, Normalize
from torchvision.transforms import functional as TF
from eod.utils.general.registry_factory import AUGMENTATION_REGISTRY
import co... |
import datetime
from dateutil.relativedelta import relativedelta
from typing import Any
from dataclasses import dataclass
from django.db.models import Q
from transaction.models import Transaction, RecurringTransaction
from transaction.utils import RecurringTransactionOccurence
from .models import BankBalance
day = d... |
def initialize():
"""Returns PIC starting code."""
code = "TRISB = %00000000\nTRISC = %00000000\nTRISD = %00000000\n"
return code
def setLED(coords):
"""Takes a three-digit coordinate of an led as a string and returns a list of the two ports needed to light the specified led"""
coords = coords
... |
from alembic.autogenerate import renderers
from alembic.autogenerate.api import AutogenContext
from . import ops
from . import util
import sqlalchemy as sa
# no need to put timestamps when rendering
_IGNORED_KEYS = ['created_at', 'updated_at']
@renderers.dispatch_for(ops.AddEdgesOp)
def render_add_edges(autogen_cont... |
import os
import json
import tensorflow as tf
import tensorflow.contrib as tf_contrib
__all__ = [
'HParams',
'create_hparams',
]
class HParams(tf_contrib.training.HParams):
def del_hparam(self, name):
if hasattr(self, name):
delattr(self, name)
del self._hparam_types[name]... |
# -*- coding: utf-8 -*-
"""Backend views."""
from collections import defaultdict
from flask import Blueprint, render_template, request, jsonify, redirect, url_for
from flask_login import login_required, current_user
from pid.extensions import whooshee
from pid.anomaly.models import Anomaly
from pid.asrun.models import ... |
"""
Este software fue creado por <NAME>.
This software was created by <NAME>.
Correo electronico o Email: <EMAIL>
"""
import os
import sys
import logging #Para ver lo que hace el bot
import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from funciones import *
logging.basicConfig... |
import matplotlib
matplotlib.use('TKAgg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import parse_map
import numpy as np
class Plot_3D:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
self.plot_translation_3D()
def set_axes_equal(sel... |
# Sonar
import random
import sys
def drawBoard(board):
# Draw the board data structure
hline = ' ' # initial space for the numbers down the left side of the board
for i in range(1, 6):
hline += (' ' * 9) + str(i)
# print the number across the top
print(hline)
print(' ' + ('01234... |
class Packet:
def __init__(self,version,type_id,lit_val=None,sub_packets=None):
self._version = version
self._type_id = type_id
self._lit_val = lit_val # only applies to type 4 - int
self._sub_packets = sub_packets # only applies to type <> 4 - list of packets
@pro... |
import glob
import numpy as np
import cv2
from PIL import Image
from utils import config
def write(filename, content, class_num=2, color_map=True):
"""
Save image array to a specified path.
The image will be automatically recolored via the class number.
:param filename: The specified path.
:param ... |
# see README.adoc
import math
import re
import copy
from pprint import pprint
def read_daily_input(filename):
''' Read lines from file with given input name
cast to daily required type and return list
'''
with open(filename) as input_file:
local_list = [item.strip() for item in input_file.... |
from __future__ import annotations
import numpy as np
import pandas as pd
from sklearn import datasets
from IMLearn.metrics import mean_square_error
from IMLearn.model_selection import cross_validate
from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, \
RidgeRegression
from sklearn.linear_mode... |
"""
Title: what_a_book.py
Author: <NAME>
Date: 27 July 2020
Description: WhatABook program; Console program that interfaces with a MySQL database
"""
""" import statements """
import sys
import mysql.connector
from mysql.connector import errorcode
""" database config object """
config = {
"user":... |
import argparse
import sys
class SpikeLogEntry:
def __init__(self, string_entry):
instr_string = string_entry.split('\n')[0].replace(':','').split()
commit_string = string_entry.split('\n')[1].replace('x ', 'x').split()
self.core = int(instr_string[0], 16)
self.pc = int(instr_string[1], 16)
self... |
import os
import sys
import tempfile
import importlib
import inspect
import logging
import logging.handlers
import bottle
from bottle import run, route, request, HTTPResponse, Bottle
import tomviz
from tomviz import jsonrpc
from tomviz.utility import inject
from tomviz.acquisition import AbstractSource
import shutil
... |
import requests, sys, re, time, os
from optparse import OptionParser
def banner(help=False, about=False):
os.system("clear")
print ("""
_ __ _ _____
| | / / | | / __ \
| |/ / __ ___ ____ _| | | / \/ ___ _ __ ___ _ __ __ _
| \ / _` \ \ /\ / / _`... |
#! /usr/bin/python3
import numpy as np
import tensorflow as tf
import os
def get_initial_control_points(r):
ini = 0
last = len(r) - 1
ax = (r[ini][0] + r[last][0]) / 2
ay = (r[ini][1] + r[last][1]) / 2
dnc = (r[last][0] - r[ini][0]) / 2
dns = (r[last][1] - r[ini][1]) / 2
x1 = ax - dnc
... |
from __future__ import annotations
from asyncio import gather
from typing import Any, ClassVar, Dict, Generic, List, Optional, Type, TypeVar, overload
from aiodataloader import DataLoader
from aiostream import stream
from async_search_client import Client as SearchClient
from motor.motor_asyncio import AsyncIOMotorCl... |
# RobotBitNet Car
# Licence: MIT
# Limited memory coding style, doc in the same folder
import radio as ro
import utime as ut
import random as rn
from microbit import display as di
from microbit import button_a,button_b, i2c
import struct
def mymap(x, in_min, in_max, out_min, out_max):
value = int((x-in_min) * (out... |
import torch
import torch.nn as nn
import functools
import sys
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find('BatchNorm2d') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
def... |
# Copyright 2016 by MPI-SWS and Data-Ken Research.
# Licensed under the Apache 2.0 License.
"""Transducers for streams.
A transducer maintains internal state which is updated every time
on_next is called. It implements a function
f: Input X State -> Output X State
For those who speak automata, this is a Mealy machine... |
import yaml
import os
from os import path, listdir, mkdir
from shutil import copyfile, rmtree
from collections import deque
from datetime import datetime
NAMESPACE = 'owlvey'
class Repository:
def __init__(self):
self.directory = None
self.seed_deploy = []
self.seed_service = []
... |
import json
import os
import random
import six
import socket
from collections import defaultdict
from contextlib import contextmanager
from coverage.files import PathAliases
from coverage.files import relative_filename
from coverage.files import set_relative_directory
from portalocker import Lock
from smother.python i... |
# functions that implement transformations using the stft
import numpy as np
import sys, os, math
from scipy.signal import resample
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../models/'))
import dftModel as DFT
def stftFiltering(x, fs, w, N, H, filter):
"""
Apply a filter to a sound... |
# object.py
#
#
"""
An Object adds 'dotted access' to dicts to allow for better readable code.
Object's also allow for saving JSON to disk to allow it to be restored at a later time.
"""
from meds.errors import EBORDER, ESET, ENOJSON, ESIGNATURE, ENOTSET, EISMETHOD
from meds.utils.signature import make_signa... |
import os
import sys
import getopt
import random
import requests
from bs4 import BeautifulSoup as Soup
class M3UWriter(object):
def __init__(self, write_dir):
self.cdn_nodes = ['peer1.ustv.to', 'peer2.ustv.to', 'peer3.ustv.to']
self.channel_codes = ['ABCE', 'A&E', 'AMC', 'APL', 'BBCA', 'BET', 'BO... |
import numpy as np
from pyro.infer import SVI, TraceGraph_ELBO
from pyro.optim import Adam, PyroOptim
import torch
from torchvision.utils import make_grid
from base import BaseTrainer
from utils import inf_loop, MetricTracker
class EmCounter:
def __init__(self, estep_params, mstep_params, epochs=10, even_estep=Tru... |
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponseForbidden
from django.shortcuts import get_object_or_404
from django.views.generic.base import TemplateView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView, \
... |
import os
import os.path
import torch.utils.data as data
from PIL import Image
def has_file_allowed_extension(filename, extensions):
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
Returns:
bool: True if the filename ends with a known image extension... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.