content stringlengths 5 1.05M |
|---|
# flake8: noqa
from drem.download.ber_publicsearch import DownloadBERPublicsearch as BERPublicsearch
from drem.download.vo import DownloadValuationOffice as ValuationOffice
|
#-*- coding: utf-8 -*-
from django.db import models
import os
from .BaseDestination import BaseDestination
class LocalDestination(BaseDestination):
def backup(self, contents, subdir, filename, *args, **kwargs):
#print "Hello! This is %s's backup method" % self.__class__.__name__
fd = os.pat... |
from django.db import models
import datetime
from user.models import Student, Teacher, User
from mgmt.models import Semester
from constants import COURSE_STATUS, COURSE_OPERATION
from django.db.models.deletion import SET_NULL, CASCADE
def current_year():
# refer: https://stackoverflow.com/questions/49051017/year-... |
from unittest import TestCase
from nba_data.data.outcome import Outcome, outcome_abbreviation_to_outcome_map
class TestOutcome(TestCase):
def test_get_outcome_from_abbreviation(self):
self.assertEqual(Outcome.get_outcome_from_abbreviation("w"), Outcome.win)
self.assertEqual(Outcome.get_outcome_fr... |
from time import sleep
import pytest
import zproc
@pytest.fixture
def state() -> zproc.State:
ctx = zproc.Context()
@ctx.spawn
def mutator(ctx: zproc.Context):
state = ctx.create_state()
for n in range(10):
sleep(0.1)
state["counter"] = n
return ctx.create_... |
#----------Section 3: Plotting utilities-------------------------------
#These need to be localized, for systems that don't support Ngl
#
#This is imported into ClimateUtilities. If you want to use a
#different graphics package (e.g. MatPlotLib) as a graphics driver
#in place of Ngl, you only need to rewrite this modul... |
#!/usr/bin/env python
"""write_sourceextractor_files.py -- input directory and write out .nnw, .conv, .config. A .param is written, but check it so that it has the parameters you need, and edit as appropriate.
Usage: write_sourceextractor_files [-h] [-q] [--debug] [-s LOC] [--name STRING] [--spreadmodel] <outdirector... |
"""
A minimal example of a networked cournot game,
with 2 companies and 2 markets, and full company-market connection.
"""
from functools import partial
from typing import Sequence, Optional
import numpy as np
from graph import Graph
from ccs import Rectangle
from networked_cournot_game import Company, NetworkedCo... |
# Generated by Django 3.1 on 2021-03-09 13:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dsrs', '0007_auto_20210309_1835'),
]
operations = [
migrations.AlterField(
model_name='resource',
name='artists',
... |
import json
import os
def load_plotly_dict() -> (dict, dict):
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
layoutfile = os.path.join(
os.path.abspath(project_root), "openseries", "plotly_layouts.json"
)
logofile = os.path.join(
os.path.abspath(project_roo... |
um = int(input('Primeiro valor: '))
dois = int(input('Segundo valor: '))
print('''
[ 1 ] somar
[ 2 ] multiplcar
[ 3 ] maior
[ 4 ] novos números
[ 5 ] sair do programa''')
opcao = int(input('>>> Qual sua opção? '))
while opcao == 1:
soma = um + dois
print ('A soma dos números é igual a {}.'.... |
# This file is a part of Arjuna
# Copyright 2015-2020 Rahul Verma
# Website: www.RahulVerma.net
# 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... |
from screws.freeze.main import FrozenOnly
class _3Form_Special(FrozenOnly):
def __init__(self, _3sf):
self._sf_ = _3sf
self._freeze_self_() |
# pylint: disable=C0111,R0903
"""Displays update information per repository for pacman.
Parameters:
* pacman.sum: If you prefere displaying updates with a single digit (defaults to "False")
Requires the following executables:
* fakeroot
* pacman
"""
import os
import threading
import bumblebee.util
impo... |
# -*- coding: utf-8 -*-
from typing import Union
from ..utils.encoding import encode_block_hash, decode_block_hash
class BlockHash:
def __init__(self, bh: Union[str, bytes]) -> None:
if isinstance(bh, str):
hash_bytes = decode_block_hash(bh)
assert hash_bytes # for mypy Optional[... |
# SPDX-FileCopyrightText: Copyright (c) 2019 ladyada for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_esp32spi_socket`
================================================================================
A socket compatible interface thru the ESP SPI command set
* Author(s): ladyada
"""
# pylint: ... |
import psutil
print("############################################################")
print("# PROFILER STARTED #")
print("############################################################")
# mod counter for escape
mod_counter = 0
# coefficient and coeff-counter dict
coefficient = ... |
# 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 not use ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 26 18:22:52 2020
@author: LKUPSSINSKU
"""
#to install the library:
#pip install git+https://github.com/philferriere/cocoapi.git#subdirectory=PythonAPI
from pycocotools.coco import COCO
import numpy as np
import imageio as io
dataDir='../dataset/jandaira/pixel/'
dataTyp... |
import json
import logging
from collections import defaultdict
from time import sleep
from typing import List, Callable, Any, Dict
from django.conf import settings
from django.core.management import BaseCommand
from googleapiclient.channel import Notification
from kafka import KafkaConsumer, KafkaProducer
from kafka.c... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-05-03 12:35
from __future__ import unicode_literals
from django.db import migrations, models
def set_deadline_to_apply(apps, schema_editor):
task = apps.get_model('tasks', 'Task')
task.objects.filter(deadline_to_apply__isnull=True).update(
... |
import unittest
from buttplug.core import (ButtplugMessage, Ok, Error, ButtplugErrorCode,
Test, DeviceAdded, MessageAttributes, DeviceRemoved,
DeviceInfo, DeviceList, VibrateCmd, SpeedSubcommand,
RotateCmd, RotateSubcommand, LinearCmd,
... |
#!/usr/bin/python
import matplotlib as mpl
mpl.use('Agg')
#
import numpy as np
import matplotlib.pyplot as plt
import os
import qplot
__name__ = 'movie'
__doc__ = 'Makes gif movie from quill results'
#qplot.resread.data_folder = '../results/'
qplot.resread.data_folder = '/share/dmserebr/Quill/quill3d/results_normal_... |
import h5py
import numpy as np
from skimage import measure
from ..constants import COMPARGS
class H5TableBase(object):
def __init__(self):
pass
def __str__(self):
return '{} for {}'.format(self.table_type,self.name)
def not_found(self):
pass
def region... |
#!/usr/bin/env python
from __future__ import annotations
import sys
from pentagram.environment import base_environment
from pentagram.guest.call import GuestCall
from pentagram.interpret import interpret
from pentagram.loop import loop
from pentagram.machine import MachineEnvironment
from pentagram.machine import Mac... |
import torch
import torch.nn as nn
import thumt.modules as modules
from .transformer import Transformer
def _split_heads(tensor, num_heads, attn_head_size):
"""
Splits hidden_size dim into attn_head_size and num_heads
"""
new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
tensor = tensor... |
"""Test the zerproc lights."""
import pytest
import pyzerproc
from homeassistant import setup
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_HS_COLOR,
ATTR_RGB_COLOR,
ATTR_XY_COLOR,
SCAN_INTERVAL,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
)
from homeassistant.components.zerproc... |
#Import packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings("ignore")
from sklearn.model_selection import StratifiedKFold ,GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianN... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import*
from scipy.optimize import*
r = np.arange(-10,0,0.1)
X = np.arange(0.1,4,0.1)
x = 0
S = 0
V = 1.602*10**(-19)
a = 0.5*10**(-10)
beta = V/a
m = 206*9.11*10**(-31)
hb = (6.626*10**(-34))/(2*np.pi)
alpha = ((2*m*beta)/hb**2)**(1./3)
def Ev... |
"""Support for Xplora® Watch tracking."""
from __future__ import annotations
import logging
from collections.abc import Awaitable, Callable
from datetime import datetime, timedelta
from typing import Any, Dict, List
import aiohttp
from .geocoder import OpenCageGeocodeUA
from homeassistant.components.device_tracker ... |
"""
Create A Hillshade From a Digital Elevation Model Using EarthPy
===============================================================
Learn how to create a hillshade from a DEM using the EarthPy
es.hillshade() function.
"""
###############################################################################
# Create A Hills... |
from pathlib import Path
from fhir.resources.valueset import ValueSet as _ValueSet
from oops_fhir.utils import ValueSet
__all__ = ["BodystructureLocationQualifier"]
_resource = _ValueSet.parse_file(Path(__file__).with_suffix(".json"))
class BodystructureLocationQualifier(ValueSet):
"""
Bodystructure Loca... |
# coding=utf-8
from __future__ import division
import sys
import os
import pickle
from configuration import Configuration
import main
def run(cfg_dict):
cfg = main.main(Configuration(**cfg_dict))
fn = str(os.path.join(cfg.basepath, '.'.join(
('cfg', cfg.title, str(cfg.seed), 'pickle'))))
wit... |
from django.apps import AppConfig
class HandwritingConfig(AppConfig):
name = 'handwriting'
|
import os
import json
import random
from PIL import Image
from numpy import expand_dims
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
def generate_img(img, N, rotateRange, wShif... |
from setuptools import setup
setup(
name="apivideo_cli",
version="1.0",
packages=["av_cli"],
include_package_data=True,
install_requires=["click", "api.video"],
entry_points="""
[console_scripts]
avcli=av_cli.av_cli:cli
""",
)
|
'''Python API for Interactive Brokers" Trader Workstation API.'''
__copyright__ = "Copyright (c) 2008 Kevin J Bluck"
__version__ = "$Id$"
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Module imports. Backfill sys.modules for each
# # # # # # # # # # # # # # # # # # # # # # # # # #... |
#!/usr/bin/env python
# coding: utf8
import argparse
import gzip
import logging
import os
import random
import sys
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
VERSION = '0.5.0'
# Init.
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', d... |
import copy
import itertools
import os
import numpy as np
import pandas as pd
from pathlib import Path
from sklearn.preprocessing import PowerTransformer
from scipy.stats import yeojohnson
from tqdm import tqdm
import tensorflow as tf
import warnings
warnings.simplefilter("ignore")
n_wavelengths = 5... |
import os
import cmd2
import pydicom
from barbell2light.dicom import is_dicom_file, tag_for_name, get_dictionary_items
class DicomExplorer:
def __init__(self):
self.files = []
# LOAD
def load_file(self, f, verbose=True):
if not os.path.isfile(f):
if verbose:
... |
from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="cvxpyanalyzer",
version="0.0.3",
description="Analyzer for CVXPY problems",
long_description=long_description,
long_description_content_type="text/markdown",
packages=... |
from calendar import timegm
from copy import deepcopy
from datetime import datetime
from flask import request
from flask_login import login_required, current_user, logout_user
from flask_socketio import emit
from .Task import Task
from .Token import Token
from .Room import Room, ROOMS
from .User import User
from .Per... |
#for loop variable variation2
for steps in range(2,5):
print(steps)
#o/p 2 3 4
|
import requests
import os
import sys
currentdir = os.getcwd()
os.chdir(currentdir)
files = {}
while True:
url = input('Insert the download link (leave empty to start the download): ')
if url == '':
break
name = ''
while name == '':
name = input('Insert the name of the file: ')
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 14 18:12:50 2019
https://www.geeksforgeeks.org/radix-sort/
@author: vikash
"""
#%%
def counter_sort(lst,xPos =0):
n = len(lst)
base10list = []
for i in range(10):
base10list.append([])
output = []
for i in range(n):
num = lst[i]
... |
"""Coptic language corpora available for download or loading locally.
All remote corpora hosted by github on the cltk organization account, eg:
'http://github.com/cltk' + name
"""
COPTIC_CORPORA = [
{'encoding': 'utf-8',
'markup': 'tei_xml',
'location': 'remote',
'type': 'text',
'origin': 'http... |
Version = "3.3.9"
if __name__ == '__main__':
print (Version)
|
from django.apps import AppConfig
class DjangoOikotieConfig(AppConfig):
name = "django_oikotie"
verbose_name = "Oikotie"
default_auto_field = 'django.db.models.BigAutoField'
|
import requests
import matplotlib.pyplot as plt
from utils import get_subscription_key
from PIL import Image
from io import BytesIO
subscription_key = get_subscription_key("key.txt")
assert subscription_key
vision_base_url = "https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/"
vision_analyze_url = vision_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#coding=utf-8
import mysql.connector
from settings.configs import Database
def get_all_categories():
r = []
try:
database_ = Database()
config = database_.config
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
query = "SELECT category_name, descr... |
#
# Copyright 2017 Import.io
#
# 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, ... |
#######################################################################################################################
# Given an array of characters where each character represents a fruit tree,
# you are given two baskets and your goal is to put maximum number of fruits in each basket.
# The only restriction is that... |
import unittest
import importlib
#source: http://stackoverflow.com/a/11158224/5343977
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
import ant_colony as module
class TestAntTraverse(un... |
#!/usr/bin/env python3
import sys
import json
import string
import argparse
def template():
return {
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "AWS CloudFormation Template for CORTX on Kubernetes. See https://github.com/Seagate/cortx-k8s/blob/main/doc/cortx-aws-k8s-installation.md ... |
import json
import mock
import os
from django.contrib.auth import get_user_model
from django.core import mail
from django.core.urlresolvers import reverse
from django.test import Client
from firecares.firestation.models import FireDepartment, FireStation, DataFeedback
from firecares.firecares_core.tests.base import Bas... |
from typing import Union, Optional, Tuple
from py4j.java_gateway import java_import, JavaObject, JavaClass
from keanu.base import JavaObjectWrapper
from keanu.context import KeanuContext
from keanu.net import BayesNet
from keanu.tensor import Tensor
from keanu.vartypes import numpy_types
from keanu.vertex.base import... |
from candidate_generator.random_walk import *
class ComplexGenerator:
def __init__(self, generators, size):
self._generators = generators
self._size = size
def candidates(self, playlist):
scores = self._create_generators_scores(playlist)
tracks = self._create_candidates_from_r... |
import numpy as np
import json
import pickle
import torch
from torch.utils.data import Dataset, DataLoader
def invert_dict(d):
return {v: k for k, v in d.items()}
def load_vocab(path):
with open(path, 'r') as f:
vocab = json.load(f)
vocab['question_idx_to_token'] = invert_dict(vocab['questio... |
#!/usr/bin/env python
import webapp2
from google.appengine.api import users
import os
from google.appengine.ext.webapp import template
# import glob
# TODO(vojta): can we do the pre-auth ?
# ensure user is authenticated and gave permissions to task manager before loading the client ?
# redirects are easier to follow... |
from django.contrib import messages
from django.conf import settings
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views.generic import TemplateView, FormView
from .mixins import DragonViewMixin
from .forms import *
from .utils import *
class DragonSearchAdminView(DragonView... |
"""
Header properties configuration.
"""
from project.models.property_model import PropertyModel
from project.models.header_model import HeaderModel
from project.enums import property_types_enum as prop_type
from project.enums import string_types_enum as str_type
from typing import Union
header_properties: list[Union... |
from typing import Sequence
import pandas as pd
from IPython.core.display import display, HTML
from datacode.typing import DfDict
def display_df_dict(df_dict: DfDict):
# df_dict may either be one level deep or two levels deep.
# if two levels deep, then first level organizes which table it is,
# and the ... |
#!/usr/bin/env python
from pathlib import Path
import numpy as np
from torch import tensor
from transformers import AutoTokenizer, AutoModel
from asreview.feature_extraction.base import BaseFeatureExtraction
class Scibert(BaseFeatureExtraction):
"""BERT feature extraction"""
name = "scibert"
def __init_... |
"""
Q108
Convert Sorted Array to Binary Search Tree
Easy
Given an array where elements are sorted in ascending order,
convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined
as a binary tree in which the depth of the two subtrees of
every node never differ by more than 1.
"""
... |
import pytest
import requests
import random
from log_config import log_, pformat
from core import config
from tests.utils.utils import get_server_api, secure_random, client
from .test_login import client_login
### - - - - - - - - - - - - - - - - - - - - - - - ###
### POST NEW DSI
### - - - - - - - - - - - - - - ... |
# Complete the solve function below.
def solve(s):
for letter in s.split():
s = s.replace(letter, letter.capitalize())
return s
|
from typing import Sequence, cast, List
import networkx as nx
import numpy as np
import pytest
import cirq
import cirq.contrib.acquaintance as cca
import cirq.contrib.routing as ccr
from cirq.google import Sycamore23
from recirq.qaoa.gates_and_compilation import compile_problem_unitary_to_arbitrary_zz, \
compile_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
from . import *
_AGENT_MANIFESTS = None
def _get_api_url():
return '%s://%s:10088/efm/api' % ('http', get_hostname(),)
def _api_request(method, endpoint, expected_code=requests.codes.ok, **kwargs):
url = _get_api_url() + endpoint
return api_reque... |
load("@bazel_tools//tools/build_defs/repo:git.bzl",
"git_repository", "new_git_repository") # buildifier: disable=load
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") # buildifier: disable=load
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") # buildifier: disable=load
all_co... |
"""Converts an excel file to csv."""
import argparse
import pandas as pd
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=('''\
Converts an excel file to csv.
'''))
parser.add_argument('in_file')
parser.add_argument('out_dir')
args = parser.parse... |
import feedparser, logging, re, time
from flask import Blueprint, render_template
mod = Blueprint('home', __name__, url_prefix='/<lang_code>', template_folder='../templates/home')
logger = logging.getLogger(__name__)
@mod.route('/')
def index():
logger.info('Fetching blog posts...')
blog_feed = feedparser.p... |
"""
avwx Package Setup
"""
from setuptools import setup
setup(
name="avwx-engine",
version="1.3.10",
description="Aviation weather report parsing library",
url="https://github.com/avwx-rest/avwx-engine",
author="Michael duPont",
author_email="michael@mdupont.com",
license="MIT",
classi... |
import numpy as np
from dataset import imageCrop
import random
import rawpy
def getRawInfo():
info = {
"Exposure Time": 0.25,
"Aperture": "f 1/16",
'ISO': 12800,
"Exposure Compensation": 0
}
return info
def pack_raw(vision):
res = []
H, W = vision.shape
res.ex... |
import moment
from ..logger import Logger, bcolors
from ..configuration import Configuration
from ..request.gql import GQLClient
from ..request.query.issue import LIST_ISSUES
def list_issues(args):
"""List the issues from the given parameter."""
logger = Logger(args.verbose, args.quiet)
configuration = C... |
"""Loss functions for deep neural networks and GANs."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import os.path as osp
import tensorflow as tf
from losses.vgg_loss import VGGLoss
from losses.vgg_face_loss import VGGFaceLoss
class L... |
#basics
import pandas as pd
import numpy as np
import joblib
import pickle5 as pickle
from PIL import Image
import time
import datetime
#firestore
from google.cloud import firestore
db = firestore.Client.from_service_account_json("firestore_key.json")
#eli5
from eli5 import show_prediction
#streamlit
import streaml... |
#!/usr/bin/env python
from itertools import count
from collections import defaultdict
class Grouper:
def __init__(self):
self.group_ids = count()
self.items_per_group_id = defaultdict(set)
self.group_id_per_item = {}
def add_isolated_item(self, item):
group_id = next(self.group_... |
# This file is part of the pyMOR project (http://www.pymor.org).
# Copyright 2013-2016 pyMOR developers and contributors. All rights reserved.
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
from __future__ import absolute_import, division, print_function
import numpy as np
import scipy.... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('forum', '0077_auto_20150613_1650'),
]
operations = [
migrations.RemoveField(
model_name='forum',
nam... |
class Solution:
def longest_increasing_subsequence(self, nums):
length = len(nums)
if length < 2:
return length
dp = [1] * length
for i in range(length):
for j in range(0, i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] +... |
from django import forms
from django.contrib.gis.measure import D
class DistanceField(forms.Field):
def to_python(self, value):
if value in self.empty_values:
return None
return (value['geometry'], D(**{value['unit']: value['value']}))
|
# -*- coding: utf-8 -*-
"""Tests errors thrown for improperly implemented ComPath managers."""
import unittest
from sqlalchemy.ext.declarative import declarative_base
from bio2bel.compath import CompathManager, CompathPathwayMixin, CompathProteinMixin
from bio2bel.compath.exc import CompathManagerPathwayModelError,... |
from ksc.rewrites import parse_rule_str
index_of_build = parse_rule_str(
"""(rule "index_of_build"
((idx : Integer) (n : Integer) (e : Any))
(index idx (build n (lam (i : Integer) e)))
(let (i idx) e))""",
{},
)
|
broker_url = "redis://127.0.0.1:6379/10"
|
from pathlib import Path
from utility import next_date
def download_links(base_path):
base_url = 'https://api-ak.wunderground.com/api/606f3f6977348613/history_{}/units:metric/v:2.0/q/pws:{}.json'
weather_station = 'IUFFENHE3'
inputs = [
(Path(base_path, '{}.json'.format(formatted_date)),
... |
import datetime
from django.db import models
from django.db.models import Q
class PresentationCategory(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField()
def __unicode__(self):
return self.name
class PresentationKind(models.Model):
name = models.Char... |
"""Define Nodes for skullstrip workflow
TODO
"""
from p3.base import basenodedefs
from nipype import Node,MapNode
from nipype.interfaces import afni,fsl,ants
from nipype.interfaces.utility import Function
class definednodes(basenodedefs):
"""Class initializing all nodes in workflow
TODO
"""
de... |
from itertools import chain
from collections import defaultdict
from typing import List, Dict, Iterator
import torch
from torchtext_th.data.sentence import Sentence
from torchtext_th.utils import reverse_dict, pad_sequence
class Vocab(object):
def __init__(self):
self.char2ind: Dict[str, int] = {}
... |
"""
Print sensor data to the screen.
Press Ctrl+C to quit.
2017-02-02 13:45:25.233400
Sensor - F4:A5:74:89:16:57
Temperature: 10
Humidity: 28
Pressure: 689
"""
import os
from datetime import datetime
from ruuvitag_sensor.ruuvi import RuuviTagSensor
# Change here your own device's mac-address
mac = 'F4:A5:74:... |
#from networks.subnetworks import Pose_Enc, App_Enc, MaskNet, BGNet, FG_Dec
#from networks.gaussian_fitting import Gaussian_Fit
#from networks.vgg import Vgg19
#from utils.nn_utils import hadamard
import torch
import torch.nn as nn
from torch.optim import Adam
from torch.utils.data import DataLoader, TensorDataset
im... |
from .training import TiedParams, DualParams, RetrieverTrainState, retriever_train_step
|
# Project: GBS Tool
# Author: Jeremy VanderMeer, jbvandermeer@alaska.edu, Alaska Center for Energy and Power
# Date: February 8, 2018
# License: MIT License (see LICENSE file of this package for more information)
# imports
import numpy as np
class eesDispatch:
def runDispatch(self, eess, newP, newQ, newSRC, tInde... |
# Django
from django.db import models
# Models
from ...utils import PRMModel
class Mood(PRMModel):
"""
User feeling or mood during a day, serve as a log on how the user
have been feeling lately.
"""
owner = models.ForeignKey('users.User', on_delete=models.CASCADE)
HAPPY = 5
GOOD = 4
... |
class Key:
def __init__(self):
self.chars = []
self.csi = False
Key.closed = False
self.trackkeys = False
# TODO: Make an Escape sequence checker for linux!
def settrackkeys(self, trackkeys=None):
if trackkeys is None:
self.trackkeys = not self.trackk... |
import requests
import slack
import os
import re
import ipaddress
SLACK_TOKEN = os.environ["SLACK_API_TOKEN"]
SLACK_CHANNEL = os.environ["SLACK_CHANNEL"]
vt_api_key = os.environ["VT_API_KEY"]
base_url = "https://www.virustotal.com"
def vt_domain_get(domain):
domain = domain.lower()
path = f"/vtapi/v2/domain... |
# -*- coding: utf-8 -*-
model = {
' ku': 0,
' le': 1,
'la ': 2,
'eku': 3,
'a k': 4,
'nga': 5,
' ng': 6,
'a n': 7,
'nge': 8,
'a l': 9,
'lo ': 10,
' ne': 11,
'eti': 12,
'kwe': 13,
'ndz': 14,
'e n': 15,
'o l': 16,
' lo': 17,
'ela': 18,
'ema': 19,
'ent': 20,
'si ': 21,
' kw': 22,
'tsi': 23,
'i l': ... |
import threading
from shardingpy.constant import SQLType
from shardingpy.routing.base import SQLRouteResult, SQLExecutionUnit
from shardingpy.rule.base import MasterSlaveRule
from shardingpy.util import strutil
class ShardingMasterSlaveRouter:
def __init__(self, master_slave_rules):
self.master_slave_rul... |
"""Uninstallation utilities for accidental `pip install`s"""
from .utils import get_valid_pip_history
from .utils import get_package_groups
from .utils import get_pip_command_action
from .utils import get_pip_command_packages
from .utils import get_pip_package_key
from .utils import flatten
from pipdeptree import buil... |
"""added crontab + periodic task tables
Revision ID: 6cc745c3fb42
Revises:
Create Date: 2022-03-16 09:48:39.018910
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "6cc745c3fb42"
down_revision = None
branch_labels = None... |
import csv
import requests
import os
from src import exceptions
class Collector:
""" Calls Ensembl APIs to collect orthologue information for a collection of genes """
GENE_ID_IDX = 1
def __init__(self, gene_file_path):
"""
Constructor
:param gene_file_path: path to the file con... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.