text stringlengths 3.07k 12.6k |
|---|
"""jobs.py
Jobs for the Harvest System.
"""
import os
import requests
import urllib
import datetime
from dateutil.parser import parse
import logging
from d1lod.sesame import Store, Repository
from glharvest import registry, void, util
# RQ
from redis import StrictRedis
from rq import Queue
conn = StrictRedis(host=... |
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow.compat.v1 as tf
import os
import cProfile
from contacts_dataset import *
import parser
tf.enable_eager_execution()
print(tf.executing_eagerly())
features = [
"profile",
"hhblits_profile",
"aatype"... |
# Copyright 2020 The TensorFlow Quantum 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 req... |
import secrets
import uuid
from django.contrib.auth.models import Group, User
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.urls import reverse
from django.utils import timezone
from django.... |
"""
Name:
Class:
MSSV:
You should understand your code
Several works can be added:
- Improve accuracy
- Improve speed: parrallel processing
- Add more parameters
"""
import pandas as pd
import numpy as np
import math
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, f1_s... |
import logging
import pprint
import re
import urllib
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.db.models import F, Q
from django.utils import timezone
from cityhallmonitor.models import Matter, MatterAttachment
from documentcloud import DocumentCloud
... |
import os
import sys
import argparse
import numpy as np
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
from keras_lr_multiplier import LRMultiplier
from utils import get_resolution
from data_loader import ImageLoader, VideoLoader
from model_loader import load_model, save_model_arch, save_model_weigh... |
# * ---------- IMPORTS --------- *
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
import os
import psycopg2
import cv2
import numpy as np
import re
from flask_pymongo import PyMongo
# Get the relativ path to this file (we will use it later)
FILE_PATH = os.path.dirname(os.path.real... |
"""
Python-based tests for metrohash extension
"""
import unittest
import random
import string
import sys
from metrohash import (
MetroHash64,
MetroHash128,
hash64_int as metrohash64,
hash128_int as metrohash128,
)
EMPTY_STRING = ""
EMPTY_UNICODE = u"" # pylint: disable=redundant-u-string-prefix
i... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import argparse
import csv
import os
import sys
import numpy as np
from sklearn.datasets import load_svmlight_file
from sklearn.svm import SVC, LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.... |
__id__ = "$Id: setup.py 257 2008-02-20 13:55:27Z jlconlin $"
__author__ = "$Author: jlconlin $"
__version__ = " $Revision: 257 $"
__date__ = "$Date: 2008-02-20 06:55:27 -0700 (Wed, 20 Feb 2008) $"
import distutils.ccompiler
import distutils.sysconfig
from distutils.core import setup, Extension
from distuti... |
# Copyright 2022 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from enum import Enum
class Location(Enum):
HOME = "HOME"
AWAY = "AWAY"
class Outcome(Enum):
WIN = "WIN"
LOSS = "LOSS"
class Team(Enum):
ATL = "<NAME>"
BOS = "<NAME>"
BRK = "BRO<NAME>"
CHI = "<NAME>"
CHO = "<NAME>"
CLE = "<NAME>"
DAL = "<NAME>"
DEN = "<NAME>"
DET ... |
import numpy as np
from gp_code.goal_pairs import goal_pairs
from utils.loaders.loader_ind import load_ind
from utils.loaders.loader_gcs import load_gcs
from utils.loaders.loader_edinburgh import load_edinburgh
from utils.manip_trajectories import break_multigoal_traj
from utils.manip_trajectories import separate_traje... |
"""pytest redis cache."""
# pylint: disable=c-extension-no-member
from asyncio import sleep
import pytest
pytestmark = pytest.mark.asyncio
async def test_build_cache_key(payload, cache):
"""Test health check."""
key = await cache.build_cache_key(payload)
assert key == 'opinion=[redis,rocks]|tool=pyte... |
import torch
import torch.nn as nn
import torch.fft
from torchsummary import summary
# ---------------------- Discriminator part -------------------------
def fftshift2d(img):
bs, ch, h, w = img.shape
fs11 = img[:, :, h // 2:, w // 2:]
fs12 = img[:, :, h // 2:, :w // 2]
fs21 = img[:, :, :h // 2, w //... |
#!/usr/bin/env python3
import argparse
import glob
import os
import textwrap
from osgeo import gdal
from PIL import Image
from swisssmartfarming import utils as ut
from swisssmartfarming.preprocessing import BasePreprocessor, SpectralProcessor
class MultilineFormatter(argparse.HelpFormatter):
def _fill_text(self... |
from math import prod
from operator import mul, add
import jax
import jax.numpy as np
import jax.lax as lax
from jax.tree_util import tree_map, tree_reduce
from .tools import ravel_index, ensure_tuple
##
## constants
##
ϵ = 1e-7
##
## indexing routines
##
# for each element in left space (N), take elements in rig... |
import os
import numpy as np
import pickle
import pandas as pd
from tasks.base_task import BaseTask
from helper.utils import logger,get_dataset,compress_datatype
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import roc_auc_score
from scipy import sparse
from sklearn.linear_model impo... |
# 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
__a... |
# Copyright 2019 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 agreed to in writing, ... |
import sys
import numpy as np
import datetime as dt
import matplotlib
import matplotlib.pyplot as plt
# use ggplot style for more sophisticated visuals
plt.style.use('ggplot')
is_closed = False
panning_allowed = False
def enable_panning(event):
global panning_allowed
panning_allowed = True
def disable_pan... |
import pytest
import torch
import numpy as np
from sklearn import datasets
import shadow.utils
@pytest.fixture(params=['cpu', pytest.param('cuda:7', marks=pytest.mark.gpu)])
def torch_device(request):
return torch.device(request.param)
@pytest.fixture
def simple_classification_model():
"""Simple classificat... |
import pytest
import magma as m
import mantle
from magma.testing import check_files_equal
from collections import namedtuple
import fault
from bit_vector import BitVector
op = namedtuple("op", ["name", "operator"])
@pytest.mark.parametrize("op", [
op(name="invert", operator="~"),
op(name="neg", operator="-")... |
import pygame
from pygame.locals import *
import torch
import torchvision
import numpy as np
import matplotlib.pyplot as plt
from random import random
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
pygame.init()
WIN_SIZE = 1000
win = pygame.display.set_mode((WIN_SIZE,WIN_SIZE))
pygame.display.se... |
from peewee import Model, ModelAlias, IntegrityError
from .query import (AioSelectQuery, AioUpdateQuery, AioInsertQuery,
AioDeleteQuery, AioRawQuery, AioNoopSelectQuery)
class AioModelAlias(ModelAlias):
def select(self, *selection):
if not selection:
selection = self.get_... |
from __future__ import print_function
import os.path as osp
import torch
from torch.nn.parallel import DataParallel
from .file import may_make_dir
def get_default_device():
"""Get default device for `*.to(device)`."""
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
return device
de... |
import pprint
import pandas as pd
from collections import defaultdict, OrderedDict
from matplotlib.lines import Line2D
from matplotlib.patches import Patch
from diagrams.base import *
OUTPUT = True
def output_table_and_graph(dataset_path, parallelism_levels_5_clique_workstealing, parallelism_levels_5_clique_shares, ... |
## 用于进行rtsp通讯,采用rtso/1.0
import enum
import re
@enum.unique
class METHOD(enum.Enum):
SETUP = 0
PLAY = 1
PAUSE = 2
TEARDOWN = 3
GET_PARAMETER = 4
SET_PARAMETER = 5
@enum.unique
class PARAM(enum.Enum):
FRAME_CNT = 0 # 总的帧数
FRAME_POS = 1 # 当前帧
FPS = 2
QUALITY = 3
class Rtsp:
... |
import itertools
class _Linewise(object):
def __init__(self, buffer):
self.buffer = buffer
self._lines = []
def __eq__(self, other):
z = itertools.izip_longest(self, other)
return all(line == other_line for line, other_line in z)
def __ne__(self, other):
return no... |
import time
import datetime
import logging
import locale
import argparse
import pkg_resources
import codecs
import pandas as pd
from pathlib import Path
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from .scrapers.revue2presse import scrap_revue2presse
from .scrapers.epresse imp... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Back To The Roots Communication
#
# 2020 - <NAME>
#
from ev3dev2.sensor.lego import TouchSensor
from ev3dev2.sensor import INPUT_1
from ev3dev2.display import Display
from ev3dev2.sound import Sound
from ev3dev2.led import Leds
from multiprocessing import Process
im... |
"""
Implementation of the OpenSearch specification for humfrey's ElasticSearch integration.
http://www.opensearch.org/Specifications/OpenSearch/1.1
"""
import datetime
import hashlib
import urllib
import urlparse
from django.conf import settings
from django.http import HttpResponse
from lxml import etree
from lxml.b... |
# Loss functions
# loss functions for probabilistic models
# source: https://github.com/nestordemeure/tabularGP/blob/master/loss_function.py
import numpy as np
import torch
from torch import Tensor
from fastai.tabular.all import CrossEntropyLossFlat
__all__ = ['log_standard_normal_cdf', 'gp_gaussian_marginal_log_like... |
import logging, re
from typing import Dict, List, Iterable
from collections import defaultdict
from overrides import overrides
from allennlp.common.file_utils import cached_path
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
from allennlp.data.fields import Field, TextField, SequenceLabelField,... |
import click
import configparser
from requests import HTTPError
from .helpers import rndstr
from .logger import ExporterLogger
from .logic import Exporter, GitLabClient, GitHubClient
from .config import ConfigLoader, ProjectLoader, ProjectNormalizer
def load_all_gitlab_projects(gitlab):
try:
projects = ... |
import numpy as np
from itertools import groupby
U, F, R, D, B, L = ("w", "g", "r", "y", "b", "o")
colors = [U, F, R, D, B, L]
UF, UR, UB, UL, FL, FR, BR, BL, DF, DR, DB, DL = (U + F, U + R, U + B, U + L, F + L, F + R, B + R, B + L, D + F, D + R, D + B, D + L)
edges = [UF, UR, UB, UL, FL, FR, BR, BL, DF, DR, DB, DL]
... |
#! /usr/bin/python3
"""
x x x x
0: 1: 2: 3: 4:
aaaa .... aaaa aaaa ....
b c . c . c . c b c
b c . c . c . c b c
.... .... dddd dddd dddd
e f . f e . . f . f
e f . f e . . ... |
from i2b2tools.helpers.tokens import n_tokens
from i2b2tools.helpers.utils import phi_within_range
from lxml import etree
import re
class Rule(object):
"""Each instance of a rule has a specific StandoffAnnotation
which it references.
"""
sa = None
def __init__(self, sa):
self.sa = sa
... |
from django.conf import settings
from django.db import connections
from django.db.models import Count, Q
from django_filters.rest_framework import DjangoFilterBackend
from nc import serializers
from nc.filters import DriverStopsFilter
from nc.models import SEARCH_TYPE_CHOICES as SEARCH_TYPE_CHOICES_TUPLES
from nc.model... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
from sklearn.metrics import classification_report, confusion_matrix, \
roc_auc_score, silhouette_score, roc_curve
from sklearn.model_selection import ShuffleSplit, GridSearchCV
import matplotlib.pyplot as plt
import time
def cl... |
import numpy as np
import pandas as pd
root = '/home/labuser/LogoDet/LogoDetection_DSBAProject/inference/'
# Upload test images annotations
real_box_by_image = pd.read_csv(root + 'data_iou/_annotations.csv')
real_box_by_image = real_box_by_image[real_box_by_image['filename'].notna()]
print(f'The shape of the test s... |
# coding:UTF-8
# 2018-10-30
# AdaBoost(Adaptive boosting)
# 机器学习实战
# https://blog.csdn.net/gamer_gyt/article/details/51372309
import numpy as np
__equation = ['lt', 'gt']
def loadSimpData():
"""
测试数据
"""
datMat = np.mat([[ 1. , 2.1],
[ 2. , 1.1],
[ 1.3, 1. ],
[ 1. , 1. ],
... |
"""Pre-defined Network's architectures that operate over 'time'"""
import tensorflow as tf
from tensorflow.keras.layers import *
from typing import List
def feature_net(inputs: Input, time_horizon: int, units=32, num_layers=2, activation='relu',
normalization=None) -> List[Layer]:
splits = tf.sp... |
# -*- coding: utf-8 -*-
import logging
import os
import numpy as np
import pkg_resources
from sqlalchemy import Column, Float, PickleType, String, Text, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
logging.basicConfig(level=logging.getLevelName(
... |
import time
from pathlib import Path
import psutil
import slurmee
from ruamel.yaml import YAML
from python.pipeline import ID, TIMESTAMP, JOB_ID, TASK_ID, GLOBAL_WORKING_DIR, CONFIG_NAME_WORKING_DIR, \
CONFIG_WORKING_DIR, RUN_WORKING_DIR, JOB_ID_RAW, MAX_CORES, DEVELOPMENT_MODE
from python.util.util import get_di... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python
from __future__ import print_function
import argparse
import os
import chainer
import matplotlib
matplotlib.use('Agg')
from chainer import Variable
from chainer import serializers
from PIL import Image
import numpy as np
import yaml
from utils.config import Config
clas... |
import boto3
import configparser
import json
import logging
import os
import re
import time
try:
from urlparse import urlsplit
except ImportError: # Python 3
from urllib.parse import urlsplit
logger = logging.getLogger(__name__)
CONFIG = configparser.ConfigParser()
CONFIG.read('/etc/prominence/prominence.ini... |
#!/usr/bin/env python3
import argparse
import allel
import numpy as np
def init_argparser():
p = argparse.ArgumentParser()
p.add_argument('-b', '--bedfile', required=True)
p.add_argument('-o', '--outfile', default='outbarcode.txt')
p.add_argument('-t', '--outtarget', default='')
p.add_argument('-... |
from ursina import Vec3
from panda3d.core import LMatrix3
from panda3d.bullet import BulletBodyNode, BulletRigidBodyNode, BulletGhostNode
class BodyNode(BulletBodyNode):
@property
def active(self) -> bool:
return super().active
@active.setter
def active(self, val:bool):
super().act... |
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
import sys
import time
import json
import requests
import bs4
import belgium_zipcode
class Realtor:
""" """
def __init__(self, ipi, name, company_name, street, house_number, postal_code, locality, syndic, mediator):
""" """
self.ipi = ipi if ipi is... |
"""
The following are helper functions for finding or creating various containers in
Flywheel.
"""
import logging
import os
import time
import flywheel
log = logging.getLogger(__name__)
def find_or_create_group(fw_client, group_id, label):
"""
Find or create Group indictated by "label".
Args:
f... |
#!/usr/bin/python
#
# Copyright (c) 2013 EMC Corporation
# All Rights Reserved
#
# This software contains the intellectual property of EMC Corporation
# or is licensed to EMC Corporation from third parties. Use of this
# software and the intellectual property contained therein is expressly
# limited to the terms and ... |
import random
# codificaJugada: str -> int
# Recibe un string y devuelve el codigo numero correspondiente a la jugada
# Ej: codificaJugada('tijeras') debe otorgar 0
def codificaJugada(jugada):
if jugada == 'tijeras':
return 0
elif jugada == 'papel':
return 1
elif jugada == 'piedra':
... |
# coding: utf-8
# In[1]:
#libs
import pandas as pd
import os
import shutil
import random
# In[2]:
#the csv that is going to be used
df = pd.read_csv('Complete Data Analysis.csv')
#directories used
root_dir = '/home/miuser/Downloads/1. Previous data dentistry project/All/'
current_dir = os.path.dirname(os.pat... |
from __future__ import division
import numpy as np
from numpy.linalg import inv
from scipy import stats
from itertools import islice
def online_changepoint_detection(data, hazard_func, observation_likelihood):
maxes = np.zeros(len(data) + 1)
R = np.zeros((len(data) + 1, len(data) + 1))
R[0, 0] = 1
... |
'''This code is part of the larger pyResearchInsights project, where we aim
to study the research themes being discussed in scientific publications.
This portion of the code analyzes the contents of the .txt file developed
by the Scraper.py and saves it to a .csv for later visualization by the
soon to be built Visuali... |
"""
Module for preprocessing spec before generating values. Exists to handle shorthand notation and
pushing params from URL form of field?param=value in to config object.
"""
import json
import logging
from urllib.parse import urlparse
from urllib.parse import parse_qs
import datagen
from .exceptions import SpecExcepti... |
from twisted.python import log, failure
from twisted.internet import reactor, defer, protocol
from twisted.application import service
from twisted.protocols import basic
from twisted.web.client import Agent, ResponseDone
from twisted.web.http_headers import Headers
from .eventual import eventually
class EventSourcePar... |
import collections
import operator
from itertools import izip, imap
from numpy.core.fromnumeric import std
def get_first(seq1, seq2, ignore_case=True):
"""
returns the alphabetically prior of seq1 and seq2
if they are the same or we fail to order, return seq1
if ignore_case=True, we apply str.upper to each lett... |
import ctypes
import time
from keys import *
SendInput = ctypes.windll.user32.SendInput
# C struct redefinitions
PUL = ctypes.POINTER(ctypes.c_ulong)
class KeyBdInput(ctypes.Structure):
_fields_ = [("wVk", ctypes.c_ushort),
("wScan", ctypes.c_ushort),
("dwFlags", ctypes.c_ulong),
("time", ctypes.c_ulong... |
import numpy as np
from knapsack import knapsack_dp
import math
from scipy import stats
def generate_summary(ypred, cps, n_frames, nfps, positions, proportion=0.15, method='knapsack'):
"""Generate keyshot-based video summary i.e. a binary vector.
Args:
---------------------------------------------
- ypred: predict... |
import os
import uuid
from django.http import FileResponse, HttpResponse
from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.settings import api_settings
from node.authentication import No... |
#!/usr/bin/env python
"""Extract blink data and visualize it using matplotlib.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as anim
import extract
import sys
import cv2
import webcam
import os
import sys
######################################
# Initialize animation here
dat... |
#!/usr/bin/env python
from optparse import OptionParser
import os
import numpy as np
import pysam
import pyBigWig
import tensorflow as tf
from basenji.dna_io import hot1_dna
from basenji.tfrecord_batcher import order_tfrecords
'''
tfr_bw.py
Generate BigWig tracks from TFRecords.
Experimental!
'''
#################... |
# Author: <NAME>
# Convenience class and functions for supporting reading in configuration files
import logging
import configparser
import os
# logging.basicConfig()
logger = logging.getLogger(__name__)
class SettingsFactory(object):
@staticmethod
def get_settings(cfg_path=None, program_dir=None, working_... |
import json
from abc import ABC, abstractmethod
from typing import Any, Generator
import aiohttp
import httpx
import requests
from requests.adapters import HTTPAdapter
from services.authorization import AAuthorization
from urllib3.util.retry import Retry
from utils.utils import parse_date
# SHARON_TRADING
# self.even... |
# Copyright 2017-present Kensho Technologies, LLC.
from datetime import date, datetime
import unittest
from graphql import GraphQLBoolean, GraphQLFloat, GraphQLID, GraphQLInt, GraphQLList, GraphQLString
import six
from ..exceptions import GraphQLInvalidArgumentError
from ..global_utils import is_same_type
from ..quer... |
# 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 u... |
import cv2
import qrcode
import argparse
import numpy as np
import matplotlib.pyplot as plt
import config
from utils import *
def insert_image(base_img, other_img, lower_x, upper_x, lower_y, upper_y):
base_img = base_img.copy()
other_img = other_img.copy()
base_img[lower_y:upper_y, lower_x:upper_x, :] = ... |
#
# Copyright 2015-2020 <NAME> <<EMAIL>>
#
# 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 t... |
"""
This file is subject to the terms and conditions defined in the
LICENSE file, which is part of this source code package.
"""
from lxml import etree
import Cfg
import Timer
import argparse
import logging
import os
import requests
import sys
from time import sleep
__description__ = """Posts Solr Input Documents ... |
import data_preprocessing as dp
import pandas as pd
models_to_eval = ['LightGBM Classifier', 'Logistic Regressor classifier', 'Artificial Neural Network',
'Random Forest classifier', 'Support vector machines']
def restart_clean_direc():
import os
import shutil
current_directory = os.get... |
#
# Copyright © 2020 <NAME> <<EMAIL>>
#
# Distributed under terms of the GPLv3 license.
"""
"""
from itertools import chain
from os.path import dirname, join
import matplotlib.pyplot as plt
import numpy as np
import tikzplotlib
# from https://stackoverflow.com/questions/4258106/how-to-calculate-a-fourier-series-in-... |
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, in_planes, planes, stride=1):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
... |
import numpy as np
from bgbb import BGBB
from bgbb.udfs import (
add_mau,
add_p_th,
mk_n_returns_udf,
mk_p_alive_udf,
mk_p_th_exp_udf,
)
from bgbb.wrappers import to_abgd_od
from lifetimes.datasets import load_donations
from lifetimes.fitters.beta_geo_beta_binom_fitter import BetaGeoBetaBinomFitter
... |
from django.db import models
from core import models as core_models
from django.utils.translation import ugettext_lazy as _
from orders import models as order_models
from designs import models as design_models
# 商品番号の生成のための関数
def create_product_code():
last_product = Product.objects.all().order_by("pk").last()
... |
"""
Download LADOT Downtown DASH data, and upload it to Postgres and S3.
"""
import os
from base64 import b64encode
from urllib.parse import quote_plus
import pandas
import requests
import sqlalchemy
S3_BUCKET = "s3://tmf-data/dash"
SCHEMA = "transportation"
TABLE = "dash_trips"
LOCAL_TIMEZONE = "US/Pacific"
if os.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) Metaswitch Networks.
"""ChangeLogRenderer for mistletoe."""
import collections
import html
import logging
from mistletoe.base_renderer import BaseRenderer
log = logging.getLogger(__name__)
ListEntry = collections.namedtuple("ListEntry", ["depth", "numbe... |
import sys
import time
from PIL import Image, ImageDraw
#from models.tiny_yolo import TinyYoloNet
from utils import *
from image import letterbox_image, correct_yolo_boxes
from darknet import Darknet
import train
import cv2
import json
import argparse
from pycocotools import coco
from pycocotools import cocoeval
name... |
"""
Takes a video with a "Space opera" style opening crawl and prints its text.
"""
from sys import path
from os.path import realpath, dirname
path.append(realpath(dirname(realpath(__file__)) + '/../'))
from difflib import SequenceMatcher
from statistics import median
import cv2
import numpy as np
import pytesseract
... |
import datetime
import os
import re
from abc import ABCMeta, abstractmethod
def dashed_case_to_camel_case(param_name):
pn = param_name.split('-')
first, rest = pn[0], pn[1:]
return first + ''.join(word.capitalize() for word in rest)
def snake_case_to_camel_case(param_name):
pn = param_name.split('_'... |
import base64
from typing import *
import six
from smseventlog import functions as f
from smseventlog import getlog, ic
from smseventlog.config import AZURE, AZURE_WEB
from smseventlog.utils.secrets import SecretsManager
log = getlog(__name__)
class CredentialManager(object):
"""load and save credentials to QS... |
#
# Collective Knowledge (Workflow to automate validation of results from the SysML'19 paper: "AGGREGATHOR: Byzantine Machine Learning")
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: <NAME>, <EMAIL>, http://fursin.net
#
cfg={} # Will be updated by CK (meta de... |
from logging import getLogger
from typing import Optional, Type, Dict, Union, Any, Callable, Awaitable
from aiogram.dispatcher.event.bases import CancelHandler
from aiogram.dispatcher.filters.base import BaseFilter
from aiogram.dispatcher.fsm.state import StatesGroup
from aiogram.dispatcher.fsm.storage.base import Bas... |
#!/usr/bin/env python
# coding: utf-8
# by <EMAIL>
__version__ = "0.0.1"
from numpy import append, array, mean
from torch import optim
from torch.nn import (
ELU,
Conv1d,
ConvTranspose1d,
Flatten,
Linear,
LogSoftmax,
MaxPool1d,
ReLU,
Sequential,
Sigmoid,
Softmax,
Tanh,
... |
#!/usr/bin/env python
import argparse
import itertools as itt
from copy import copy
import indextools
def pfmt(p):
return f'{p.x}_{p.y}'
def sfmt(s):
return f'agent_{pfmt(s.agent)}_item_{pfmt(s.item)}'
def afmt(a):
return a.value
def ofmt(o):
return f'{o.postype}_{pfmt(o.pos)}'
if __name__ ==... |
# Copyright 2021 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.txt" file accom... |
import os
import time
from selenium import webdriver
from logger import getLogger
def getBrowser(logdir='geckodriver.log', headless=True):
options = webdriver.FirefoxOptions()
if headless:
options.add_argument('-headless')
browser = webdriver.Firefox(options=options, log_path=logdir)
return browser
class ... |
"""Extracts serialized RDF and loads into one or more graphs"""
import pandas as pd # type: ignore
import json
import rdflib # type: ignore
import requests # type: ignore
from datetime import datetime
from typing import Dict, List, Optional
from zipfile import ZipFile
LDP = rdflib.Namespace("http://www.w3.org/ns/l... |
# -*- coding:utf-8 -*-
# Copyright (C) 2020. 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... |
"""Script to keep me posted on new anime episodes."""
import os
import json
import logging
from typing import List
from datetime import datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import jinja2
import smtplib
import requests
from bs4 import BeautifulSoup
from github im... |
import os
from PIL import Image
from torch.utils.data import Dataset
import torch
import torchvision.transforms as transforms
import numpy as np
def get_transforms(cfg):
train_transform = transforms.Compose([
transforms.Resize((cfg.DATA.RESIZE_SIZE, cfg.DATA.RESIZE_SIZE)),
transforms.RandomCrop((c... |
# basic libs
import numpy as np
import torch
# pytorch
import torch
from torch.utils.data import Dataset
import albumentations as A
# custom modules
np.random.seed(42)
class Dataset_train(Dataset):
def __init__(self, volumes_list, aug, dataset):
self.volumes_list = volumes_list
... |
import numpy as np
class MarkovRewardProcess:
def __init__(self, n_states, p, r, initial_state, r_max=1, random_reward=False, seed=None):
'''
Args:
p : (n_states, n_states)-array.
Transition matrix with the common row-column convention. p[i, j] := transition probability... |
# code for example notebook
import math
from qcodes import MockInstrument, MockModel, Parameter, Loop, DataArray
from qcodes.utils.validators import Numbers
class AModel(MockModel):
def __init__(self):
self._gates = [0.0, 0.0, 0.0]
self._excitation = 0.1
super().__init__()
def _outp... |
'''
synbiochem (c) University of Manchester 2015
synbiochem is licensed under the MIT License.
To view a copy of this license, visit <http://opensource.org/licenses/MIT/>.
@author: neilswainston
'''
# pylint: disable=superfluous-parens
# pylint: disable=too-many-public-methods
import random
import unittest
from sy... |
import os
from tensorflow.python.training.tracking import graph_view
import tensorflow as tf
import numpy
from hlp.mt.config import get_config as _config
from hlp.mt.model import nmt_model, checkpoint
from hlp.mt.model import transformer as _transformer
def load_checkpoint(transformer, optimizer, checkpoint_path=_c... |
from rest_framework import serializers
from dplace_app import models
# constants for SocietyResult
SEARCH_LANGUAGE = 'l'
SEARCH_ENVIRONMENTAL = 'e'
SEARCH_VARIABLES = 'v'
SEARCH_GEOGRAPHIC = 'g'
class SourceSerializer(serializers.ModelSerializer):
class Meta(object):
model = models.Source
# Cultural T... |
#!/usr/bin/env python3
import sys, os
import datetime
import filecmp
from pathlib import PurePath, Path
from PIL import Image
import shutil
import string
options = {'recurse': False, 'merge': False, 'extension': '.jpg', 'debug': False}
filenum_on_date = {}
#input: date of the file creation.
#input: seqno: the seque... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.