text stringlengths 3.07k 12.6k |
|---|
# -*- coding: utf-8 -*-
"""
Logging wrapper
"""
import logging
import sys
import os
import psutil
import time
FORMAT = '%(levelname)s - %(asctime)s [%(filename)s:%(lineno)d] : %(message)s'
LOG_LEVEL = {'INFO': logging.INFO,
'DEBUG': logging.DEBUG,
'WARNING': logging.WARNING,
'ERR... |
'''
Takes 2 command line arguments:
* logging file type to analyse:
* -apache2 access log create by apache2 (e.g. access-443.log)
* -startInit -statLogin statistic logfile created by the openroberta server (e.g. ora-server.log)
* the path to the log file to analyse
The program reads the log file (assuming it is ex... |
import networkx as nx
import itertools
import numpy as np
import matplotlib.pylab as plt
import random
import logging
import qmpy
from qmpy.utils import *
logger = logging.getLogger(__name__)
__all__ = ['LatticePoint', 'LatticeNetwork']
class LatticePoint:
def __init__(self, position, spin=None):
self.... |
"""
License: Apache-2.0
Author: <NAME>
E-mail: zhangsuofei at njupt.edu.cn
"""
import tensorflow as tf
import tensorflow.contrib.slim as slim
from config import cfg
import numpy as np
# input should be a tensor with size as [batch_size, caps_num_in, channel_num_in]
def vec_transform(input, caps_num_out, channel_num_o... |
import os
import gc
from tqdm import tqdm
import numpy as np
import scipy.sparse as smat
from sklearn.svm import LinearSVR, LinearSVC
from sklearn.linear_model import Ridge, LogisticRegression
from pathlib import Path
import json
from multiprocessing import cpu_count, Pool
_FUNC = None # place holder to Pool function... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import collections
import json
import logging
import os
import socket
import errno
try:
from . import __doc__ as doc
from . import __title__ as title
from . import __version__ as version
from . import exceptions
from . ... |
import arrow
from pyspark.sql.types import (
StructField, StructType, StringType,
LongType, IntegerType, BooleanType
)
"""
Calendar for reference
January 2017
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
"""
SPBE = "scalar_parent_brows... |
'''
Whale Optimization Algorithm with cellular topological structure
@author: zzw
@reference: WOA & CGWO
@ log: 2019.7.25, create
'''
from soio.core.algorithm import Algorithm
from soio.core.problem import FloatProblem
from soio.core.solution import FloatSolution
import random
import time
import numpy as np
import mat... |
# Copyright (c) 2013 Mirantis 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 writ... |
import argparse
import os
import shutil
import threading
import time
import win32api
import win32gui
from os.path import exists, join
from subprocess import Popen, PIPE, STDOUT
from xml.dom.minidom import parse
import win32con
import xlrd
from docx import Document
def check(file, args):
check_time = time.time()
... |
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
from unittest import TestCase
from . import (ClassifyingPartitioner, InsufficientStock, Item, ItemLine,
ItemList, ItemRange, Partitioner, StockedItem, partition)
class Swallow(Item):
def get_price_per_item(self, sale=False):
... |
from nitorch import spatial, io
from nitorch.core import utils
from nitorch.core.dtypes import dtype as nitype
import torch
import os
from .parser import FileWithInfo, Linear, Velocity, Displacement
from .. import helpers
def compose(options):
read_info(options)
collapse_transforms(options)
write_data(opt... |
"""
MHTML format handling.
Based on https://github.com/Modified/MHTifier/blob/master/mhtifier.py
Usage:
mht = mhtml()
mht.from_folder(folder)
mht.save_to_file(filename)
From command line:
mhtml --pack mht folder
"""
import os
import base64
import email, email.message
import mimetypes
import codecs
... |
import pkg_resources
import sys
import os
import re
from floyd.exceptions import FloydException
from floyd.manager.auth_config import AuthConfigManager
from floyd.manager.experiment_config import ExperimentConfigManager
from floyd.manager.data_config import DataConfigManager
from floyd.constants import DOCKER_IMAGES
... |
import numpy as np
import pandas as pd
import requests
from bs4 import BeautifulSoup
import pickle
from datetime import datetime, timedelta
import time
import re
import sys
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
chromedriver = "/Applications/chromedriver"
os.environ["w... |
from discord.ext import commands
import json
import discord
from random import shuffle
import asyncio
from time import time
from humanfriendly import format_timespan
class Mystic(commands.Cog):
def __init__(self, client):
self.client = client
with open("config.json", "r") as f:
... |
from datetime import time
from typing import List, Optional
class Arduino:
def __init__(self, id: int, name: str, template_id: int):
self.__id = id
self.name = name
self.template_id = template_id
@property
def id(self) -> int:
return self.__id
class Template:
def __i... |
"""Manages loading and saving settings into the environment."""
import json
import os
import sys
import uuid
import plaidml.exceptions
def _find_config(name):
prefixes = [
sys.prefix,
os.path.join(sys.prefix, 'local'),
]
for prefix in prefixes:
cfg_path = os.path.join(prefix, 'sh... |
import torch
import torch.optim as optim
import torch.nn as nn
import numpy as np
import logging
from torch.utils.data import DataLoader, Subset
from torchvision.transforms import transforms
import json
from pathlib import Path
from datetime import datetime
from src.data import SingleImgDataset, MultiviewImgDataset
fro... |
# Copyright (C) 2008 <NAME> - CRS4. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for educational, research, and not-for-profit purposes, without
# fee and without a signed licensing agreement, is hereby granted, provided
# that the above copyright notic... |
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... |
from player import Player
from websockets.exceptions import ConnectionClosedError, ConnectionClosed
import json
import datetime
class WrongTurn(Exception):
def __init__(self):
self.message = "board.WrongTurn"
class InsuficientPlayers(Exception):
def __init__(self):
self.message = "board.insufic... |
"""
This file handles converting callables with tensorflow docstrings into config classes
by parsing their docstrings to find their default values, finding the help text
for each value, and then calling ``make_config`` to create a config class
representing the arguments to that callable.
"""
import inspect
import datac... |
import json
from copy import deepcopy
from datetime import datetime
from catcher.modules.formatter import formatter_factory
from catcher.utils import file_utils
class LogStorage:
def __init__(self, output_format) -> None:
self._data = []
self._current_test = None
self._format = output_form... |
import os
import sys
import logging
import argparse
import optparse
import traceback
import configparser
import pandas as pd
import numpy as np
from utils import unzip, client_postgreSQL
from utils.utils import *
global config
config = configparser.RawConfigParser()
config.read("./config.cfg")
def unzipping() -> No... |
import os
import sys
import unittest
from test.testUtilities import assertIterablesAlmostEqual
import MAPLEAF.IO.Logging as Logging
from MAPLEAF.IO.Logging import (Logger, MonteCarloLogger,
findNextAvailableNumberedFileName,
getSystemInfo, removeLogger)
f... |
# -*- coding: utf-8 -*-
#
# Copyright 2020 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compli... |
# RT - gban
from collections.abc import AsyncIterator
from discord.ext import commands
import discord
from core import Cog, t, DatabaseManager, cursor, RT
from data import FORBIDDEN
class DataManager(DatabaseManager):
"GBAN関連のデータを管理するマネージャーです。"
def __init__(self, cog):
self.cog = cog
async d... |
# Copyright (c) 2020 PaddlePaddle 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 app... |
from operacoes import Operacao
from typing import List, Dict
from time import sleep
import pickle
registros: List[Operacao] = []
def main() -> None:
menu()
def menu() -> None:
print('=====================================================')
print('================== MUITO DINHEIRO ===================')
... |
#
# This file is subject to the terms and conditions defined in the
# file 'LICENSE', which is part of this source code package.
#
import logging
import sys
from aou_cloud.services.gcp_cloud_function import GCPCloudFunctionContext, \
PubSubEventContext, FunctionPubSubHandler
from aou_cloud.services.gcp_cloud_tasks... |
"""
Event data class
if-algerie exams
"""
from typing import (Any, Dict, List, Iterable)
import ujson as json
import html
import re
import logging
from tcfbot.account import Account
from tcfbot.enums import exam_data
logger = logging.getLogger(__name__)
class Event:
def __init__(self, **kwargs):
... |
import argparse
import eyed3
import glob
import logging
import os
import pathlib
import platform
import re
import sys
logging.getLogger("eyed3").setLevel(logging.CRITICAL)
def get_data_from_filename(file_path):
filename = os.path.basename(file_path)
data = {
"artist": "000 - unknown artist",
... |
import typing
Iterable = typing.TypeVar('Iterable', list, dict)
def assert_true(value: object, message: str):
assert bool(value), message
def assert_false(value: object, message: str):
assert not bool(value), message
def assert_and(object1: object, object2: object, message: str):
assert object1 and o... |
# Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2018 by <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later versi... |
"""Perform routine quality checks on radar dual-polarisation moments.
.. author:: <NAME> <<EMAIL>>
"""
import os
import sys
import glob
import time
import argparse
import warnings
import traceback
import pyart
import netCDF4
import numpy as np
import pandas as pd
import dask
import dask.bag as db
def chunks(l, n):... |
from __future__ import annotations
import os
import json
from pathlib import Path
from typing import Dict
import datetime
import jsonpickle
from dataverse import xferjob
class JobHistory():
def __init__(self, globus_id: str):
# Synapse Job ID
self.job_id: str = ''
self.globus_id: str = gl... |
import math
import torch
import torch.nn.functional as F
from torch import nn
# from groupnorm import GroupNorm
class ASPP_module(nn.Module):
def __init__(self, inplanes, planes, rate):
super(ASPP_module, self).__init__()
if rate == 1:
kernel_size = 1
padding ... |
import os
import csv
import sys
import datetime
import collections
if sys.version_info.major < 3:
raise Exception('This script should be run in Python 3.')
Reference = collections.namedtuple('Reference', ['ns', 'id'])
Synonym = collections.namedtuple('Synonym', ['name', 'status'])
class OboTerm(object):
d... |
import numpy
from tsr.tsrlibrary import TSRFactory
from tsr.tsr import TSR, TSRChain
@TSRFactory('herb', 'pill_bottle', 'grasp')
def pills_grasp(robot, pills, manip=None, **kw_args):
'''
@param robot The robot performing the grasp
@param pills The pill bottle to grasp
@param manip The manipulator to pe... |
# Copyright 2019-2020 ETH Zurich and the DaCe authors. All rights reserved.
from __future__ import print_function
import argparse
import dace
from dace.transformation.dataflow import MapTiling
from dace.transformation.optimizer import SDFGOptimizer
import numpy as np
from scipy import ndimage
W = dace.symbol('W')
H =... |
#-******************************************************************************
#
# Copyright (c) 2012-2013,
# Sony Pictures Imageworks Inc. and
# Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or witho... |
"""Command line functions for interacting with MFA models"""
from __future__ import annotations
import os
import shutil
from typing import TYPE_CHECKING, Optional
from montreal_forced_aligner.config import get_temporary_directory
from montreal_forced_aligner.data import PhoneSetType
from montreal_forced_aligner.excep... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# sources: services/account/v1/account.proto
# plugin: python-betterproto
from dataclasses import dataclass
from typing import Dict, List
import betterproto
from betterproto.grpc.grpclib_server import ServiceBase
import grpclib
class ConfirmationMethod(bette... |
import os
from gi.repository import Gio
from xdg.DesktopEntry import DesktopEntry
from fluxgui.exceptions import DirectoryCreationError
################################################################
# Color temperatures.
# The color options available in the color preferences dropdown in the
# "Preferences" GUI are ... |
import argparse
from itertools import product
import os.path as osp
import numpy as np
import pandas as pd
import tqdm
from scipy.optimize import fmin_cg, minimize, least_squares
def linear(X, a, b):
return X * a + b
def grad_linear(X, a, b):
return X, np.full_like(X, 1)
def rational(X, a, b):
return... |
import random
import string
import typing # noqa
import pyparsing as pp
from wsproto.frame_protocol import Opcode
from mitmproxy.utils import strutils
from . import base, generators, actions, message, websockets_frame
NESTED_LEADER = b"pathod!"
class WF(base.CaselessLiteral):
TOK = "wf"
class OpCode(base.... |
# Copyright 2016 Bridgewater Associates
#
# 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... |
import nflgame # https://github.com/BurntSushi/nflgame
def total_stats(name, year, max_wk):
wks = []
for x in range(1, (max_wk+1)):
wks.append(x)
return player_stats(name, year, wks)
def player_stats(name, year, wk):
# takes player's full name, year of game(s), week of game(s)
# returns st... |
"""
<NAME> 2020
Examples of custome parameter types derived from pyqtgraph
"""
import sys
from PyQt5 import QtWidgets, QtCore
from pyqtgraph.parametertree import Parameter, ParameterTree
from collections import OrderedDict
from pymodaq.daq_utils import gui_utils as gutils
from pymodaq.daq_utils.parameter import pymoda... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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, Dict, List, Mapping, Optional, Tuple, Union
from .. import ... |
from time import sleep
import subprocess
import numpy as np
from warnings import warn
import os
DEBUG_MODE = False
DEFAULT_ENV = os.environ.copy()
class CalledProcessError(subprocess.CalledProcessError):
def __str__(self):
# Improve error msg with stdout and stderr
return '{}\n\nStdout:\n{}\n\nSt... |
from django.db import transaction
from django.http import HttpResponseBadRequest
from django.shortcuts import get_object_or_404
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters, status, viewsets
from rest_framework.permissions import IsAdminUser
from rest_framework.respon... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 20 23:48:00 2018
@author: Jian
"""
import numpy as np
from . import BSSA14
from . import CB14
from . import CY14
from . import ASK14
from . import helper
#%%----------------------------------------------------------------------------
def site_factor(model_name, Vs30, Z... |
'''
1. Input student data. Rno, Name, Marks for 3 subs
2. Read data
3. Calc avg
4. Grade find store desc
80 - 100 A
60 - 80 B
40 - 60 C
'''
Info = open("studInfo.txt", "w+")
Marks = open("studMarks.txt", "w+")
def writeData():
Info.write("1 : Harsh \n")
Info.write("2 : Patel \n")
Info.wri... |
########################################
# CS/CNS/EE 155 2018
# Problem Set 1
#
# Author: <NAME>
# Description: Set 1 SGD helper
########################################
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.an... |
import heapq
import time
import operator
import asyncio
from collections import OrderedDict
from .utils import OrderedSet, shared_prefix, bytes_to_bit_string
class KBucket:
"""
each node keeps a list of (ip, udp_port, node_id)
for nodes of distance between 2^i and 2^(i+1)
this list that every node ke... |
from flask import Flask, json, abort, request
from data.MongoDataLayer import MongoDataLayer
from data.MySqlDataLayer import MySqlDataLayer
import atexit
from validators.validators import Validators
from flask_cors import CORS
from decouple import config
app = Flask(__name__)
cors = CORS(app)
if config("DB") == "Mysql... |
from . import partial, Tk, ttk, filedialog, StringVar, Path
#TODO
# Move to MYSQL selector folder
class define_relation:
# Quick and dirty GUI for selecting a relational database relations
def __init__(self, columns1, columns2):
root = Tk()
def create_rbs(cols, row, var):
for ... |
import io
import pytest
import re
import os
import ctypes
from cfiddle.CProtoParser import *
from cfiddle.ProtoParser import BadParameter, UnknownType, BadParameterName, Prototype, Parameter
@pytest.mark.parametrize("t,ct", [
("long", ctypes.c_long),
("uint64_t", ctypes.c_ulonglong)
])
def test_get_ctype(CPars... |
import cv2 as cv
import os
from color import classify
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
import boto3
import psycopg2
import datetime
import calendar
import time
import pickle
from segmenter import segment
conn = None
count = 5
s3 = None
bucket='... |
"""
* This file is part of PYSLAM
*
* Copyright (C) 2016-present <NAME> <luigi dot freda at gmail dot com>
*
* PYSLAM 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 y... |
import torch
import numpy as np
from torch.distributions import Categorical
import torch.nn.functional as F
import torch.nn as nn
def discount_rewards(r, gamma):
discounted_r = torch.zeros_like(r)
running_add = 0
for t in reversed(range(0, r.size(-1))):
running_add = running_add * gamma + r[t]
... |
import collections
import itertools
import numpy
import pandas
import scipy.sparse
from hetmech.matrix import metaedge_to_adjacency_matrix
import hetmech.degree_weight
def degrees_to_degree_to_ind(degrees):
degree_to_indices = dict()
for i, degree in sorted(enumerate(degrees), key=lambda x: x[1]):
d... |
#!/usr/bin/env python3
assert __name__ == '__main__'
from common import *
import itertools
import job_client
import psutil
import threading
# --------------------------------
LockingLogHandler.install()
log_conn_counter = itertools.count(1)
def th_on_accept_log(conn, addr):
conn_id = next(log_conn_counter)
... |
# 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... |
# https://github.com/tidyverse/dplyr/blob/master/tests/testthat/test-count-tally.r
import pytest
from datar.core.backends.pandas.testing import assert_frame_equal
from datar import f
from datar.tibble import tibble
from datar.base import (
c,
letters,
factor,
FALSE,
TRUE,
NA,
)
from datar.dply... |
#!/usr/bin/env python
"""
ClusterTFBS: Performs TF clustering based on positions of TFBS across genome by calculating overlaps of sites
@author: <NAME>
@contact: mette.bentsen (at) mpi-bn.mpg.de
@license: MIT
"""
import argparse
import tempfile
import sys
import os
import numpy as np
import itertools
... |
import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
import scipy.signal as signal
from scipy.optimize import curve_fit
import sys
sys.path.insert(0, '/genesis/jwst/github/jwst-mtl/SOSS/')
sys.path.insert(0, '/genesis/jwst/github/jwst-mtl/SOSS/trace/')
sys.path.insert(0, '/genesis/jwst/g... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.db import models
from django import forms
from django.core.exceptions import ValidationError
from .fields import ModelFormField, FormField
class MetaForm(forms.Form):
age = forms.IntegerField()
sex = forms.ChoiceField(... |
# from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import gevent.monkey
gevent.monkey.patch_all()
# import urllib2
# from urlparse import urlparse
import pytest
# import websocket
import six.moves.http_client as httplib
from flask import url_for
import purkin... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 28 10:20:57 2019
@author: zmddzf
"""
import numpy as np
import matplotlib.pyplot as plt
import numpy.linalg as la
class Birds:
"""
鸟群类,用于承载粒子群的数据结构
"""
def __init__(self, popsize, dim):
"""
鸟群构造器,初始化鸟群实例
:param popsize: 种群个数
... |
# coding=utf-8
# Copyright 2021 The HuggingFace Team. 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 requir... |
from django import forms
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db import models
from django.shortcuts import redirect, render
from django.utils.translation import ugettext_lazy as _
from modelcluster.contrib.taggit import ClusterTaggableManager
from modelcluster.fields im... |
#!/usr/bin/env python3
###############################################################################
# Module Imports
###############################################################################
import arrow
import collections
import functools
import logbook
import pathlib
import pyscp
import re
import yaml
fro... |
#
# Carregador das definições para o ATmega Detonator
#
# As definições são lidas do arquivo chips.json e carregadas
# na EEProm do Detonator através da serial
#
# Assume que o arquivo json foi codificado corretamente,
# nenhuma consistência ou reformatação é feita
#
import json
import binascii
import serial
# Serial ... |
from abc import ABC, abstractmethod
import itertools
from collections.abc import Mapping as BaseMapping
import json
import inspect
import re
from typing import Dict, Callable, Any, Optional
import numpy as np
import uuid
def get_constructor_params(klass):
args_kwargs = sorted([inspect.Parameter.VAR_POSITIONAL, in... |
import json
import httpx
import asyncio
import argparse
from argparse import RawTextHelpFormatter
from prettytable import PrettyTable
import textwrap
from operator import attrgetter
class ValidationResult:
def __init__(self, label: str, success: bool, message: str, from_iri: str, expected_result: str, actual_resu... |
import asyncio
import socket
import threading
import json
import logging
from webcandy import util
from typing import NewType, Optional, Tuple, List, Dict
from flask import Flask
from .models import User
# define Address to be 2-tuple of (host, port)
Address = NewType('Address', Tuple[str, int])
class ClientManager... |
import random
from datetime import datetime, timedelta
from src.api.input.contexto import Contexto
class ContextoDataset:
def __init__(self, id_cenario, estado_frequencia_cardiaca, atividade, localizacao_semantica, duracao,
horario_inicio_final,
necessario_alerta_cuidador):
... |
import os
import sys
import pylab as plt
import logging as log
from matplotlib.ticker import MaxNLocator
log.basicConfig(format='[%(funcName)s]: %(message)s', level=log.INFO)
logger = log.getLogger()
def read_data(path):
names = []
voltage = []
g_exc = []
g_inh = []
spikes = []
for filename in filter(lambda ... |
"""
ipwatch.py - version 0.0.1
Released under MIT license
https://github.com/packetflare/ipwatch/
OSX Menu widget that displays the user's current public IP address and
associated informaton as detected by the service https://ipinfo.io/.
A request to ipinfo.io is triggered if the application detects a change
in an... |
# Copyright 2016 IBM Corp
# 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 applicable law or agreed... |
# coding=utf-8
# Copyright 2017-2020 The THUMT Authors
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import datetime
import glob
import operator
import os
import shutil
import time
import torch
import torch.distributed as dist
from thumt.utils.checkpoin... |
#!/usr/bin/env python3
import argparse
import pandas as pd
def process_metamorpheus_file(filename):
"""
Process MetaMorpheus AllPeptides file
Keeps only target peptieds with FDR <= 0.01
Explodes 'Protein Accession' column into individual rows
Parameters
----------
filename : str
... |
import numpy
import unittest
from chainer import cuda
from chainer.testing import attr
from chainer.testing import condition
from chainer import variable
def _make_data_default(shape, dtype):
x = numpy.random.uniform(-1, 1, shape).astype(dtype)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
return... |
# -*- coding: utf-8 -*-
from fractions import Fraction
import sys
import generators
import graphviz
import numpy as np
import tree
import math
from data import Data
def ij_iterator(kj, m):
"""Utility function that yields all elements of {i | 1 <= i <= kj} ^ m
Yields:
(int) * m: the cur... |
from transformers.modeling_gpt2 import GPT2LMHeadModel, GPT2Config
import torch.utils.data.dataset
import utils_tokenizer
import torch, tqdm, math
def pad(data, padval=0):
return torch.nn.utils.rnn.pad_sequence(data, batch_first=True, padding_value=padval)
class GeneTransformer:
def __init__(self, max_output... |
from flask import Blueprint, render_template
from random import randrange
from main.utils.ApiRequest import ApiRequest
sandbox = Blueprint("sandbox", __name__, url_prefix="/sandbox")
@sandbox.route("/")
def index():
return render_template("sandbox/index.html")
@sandbox.route("/expenditures")
def expenditures()... |
import pydealer
from pydealer.const import POKER_RANKS
from pprint import pprint
def rank(card):
return POKER_RANKS['values'][card.value]
def high_card(stack):
if len(stack) == 0:
return None
result = stack[0]
if len(stack) == 1:
return result
for card in stack[1:]:
if rank... |
#coding=utf8
import copy, math
import torch, dgl
import torch.nn as nn
import dgl.function as fn
from model.model_utils import Registrable, FFN
from model.encoder.rgatsql import RGATLayer, MultiViewRGATLayer
from model.encoder.functions import *
@Registrable.register('lgesql')
class LGESQL(nn.Module):
""" Compared... |
import collections
import pandas as pd
from tqdm.auto import tqdm
def get_feature_combination_df(
feature_combination: list,
df: pd.DataFrame,
index_levels: list,
column_value: str = "value",
verbose: bool = False
):
"""
For each feature combination in ``... |
import json
import os
import sublime
if int(sublime.version()) < 3000:
from sublime_haskell_common import *
import symbols
else:
from SublimeHaskell.sublime_haskell_common import *
import SublimeHaskell.symbols as symbols
CACHE_PATH = None
CABAL_CACHE_PATH = None
PROJECTS_CACHE_PATH = None
def swap_d... |
"""
This module defines the interfaces for Python based
Spark Job Server Jobs. Due to Python's typing, jobs
do not need to inherit from these classes but they must
implement the relevant methods described in SparkJob.
"""
class SparkJob:
"""
The primary interface for Python jobs in SparkJob server.
A job ... |
# -*- encoding: utf-8 -*-
# aim of this script is to aim the creation of vm thought ovh
# we use the API only in the test project PREPROD
import ovh
import logging
import sys
from time import sleep
import traceback
from .secret import get_ovh_connection_setting, get_general
from .apiovh import get_project_id, disp, ... |
import argparse
import logging
import os
import tempfile
import sys
from pyspark.conf import SparkConf
from pyspark.sql import SparkSession, DataFrame
from pyspark.sql.types import FloatType
from pyspark.sql.functions import col, collect_set, split, element_at, struct, lit
# A few genes do not have Ensembl IDs in the... |
"""
Defines decorators that Architect provides.
"""
import inspect
import functools
from .bases import BaseFeature
from .registry import registry, Registrar
from ..exceptions import (
ORMError,
FeatureInstallError,
FeatureUninstallError,
MethodAutoDecorateError
)
from copy import deepcopy
def set_li... |
"""
2014.08
S.Rodney
Define parameters for generating sncosmo simulations of HST SN surveys.
"""
# Collecting area of HST's 2.4-m diameter primary mirror, in cm^2
HSTMIRRORAREA = 45240.0 # cm^2
# (incomplete) dictionary of AB and Vega zero points for all filters
ZPTDICT = {
'AB':{
'ACSWFC':{'F435W': 25.6... |
import torch
import torch.nn as nn
import torch.nn.functional as F
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
class PreActBlock(nn.Module):
'''Pre-activation version of the BasicBlock.'''
expansion = 1
d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.