content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : download.py
@Time : 2020/11/08
@Author : Yaronzz
@Version : 1.0
@Contact : yaronhuang@foxmail.com
@Desc :
'''
import os
import aigpy
import logging
import lyricsgenius
from tidal_dl.settings import Settings
from tidal_dl... | python |
"""
plots how total workseting set increase over time
"""
import os, sys
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../"))
from utils.common import *
import bisect
SLAB_SIZES = [96, 120, 152, 192, 240, 304, 384, 480, 600, 752, 944, 1184, 1480, 1856, 2320, 2904, 3632, 4544, 5680, 71... | python |
from setuptools import setup
setup(name='carpet',
version='2021',
# description='',
url='https://cfaed.tu-dresden.de/friedrich-home',
author='Anton Solovev, Benjamin M Friedrich',
license='MIT',
packages=['carpet'],
zip_safe=False) | python |
'''
Convert a neighbors file to human-readable format,
optionally including preferred string expansion.
'''
from hedgepig_logger import log
from .. import nn_io
if __name__ == '__main__':
def _cli():
import optparse
parser = optparse.OptionParser(usage='Usage: %prog')
parser.add_option('-i... | python |
from django.db import models
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=32)
price = models.DecimalField(max_digits=8, decimal_places=2) | python |
#!/usr/bin/env python
import cv2
# from opencvutils.video import Camera
cam = cv2.VideoCapture(0)
# cam.init(cameraNumber=0, win=(640, 480))
while True:
try:
ret, img = cam.read()
cv2.imshow('img', img)
if cv2.waitKey(1) == 27:
break # esc to quit
except:
# cam.close()
break
cv2.destroyAllWindows(... | python |
import requests
import json
from xlwt import *
url = "https://api.github.com/users/andrewbeattycourseware/followers"
response = requests.get(url)
data = response.json()
filename = 'githubusers.json'
print(data)
for car in data:
print(car)
#write the Json to a file.
#import json
if filename:
with open(filename, ... | python |
from .cell_level_analysis import CellLevelAnalysis
from .pixel_level_analysis import PixellevelAnalysis
from .feature_extraction import InstanceFeatureExtraction
from .background_extraction import ExtractBackground
| python |
# -*- coding: utf-8 -*-
'''
Copyright (c) 2014, pietro partescano
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this ... | python |
import xml.etree.ElementTree as ET
import urllib2
from sqlalchemy import and_
from datetime import datetime
from .ConnectDB_ParseExcel import *
from stp0_loadCVs import Load_CV_To_DB
from stp4_loadDataValue.helper import LoadingUtils
class CUAHSI_importer():
'''
This class is used to get data putting to Wa... | python |
"""Fsubs config."""
| python |
"""Utility functions to check attributes returned in API responses and read from the AWS S3."""
import datetime
import re
def check_attribute_presence(node, attribute_name):
"""Check the attribute presence in the given dictionary or list.
To be used to check the deserialized JSON data etc.
"""
found_... | python |
gagaStop = Lorentz(name = 'gagaStop',
spins = [ 3, 3, 1 ],
structure = 'FTriPhotonTop(2*P(-1,1)*P(-1,2)) * (Metric(1,2)*P(-1,1)*P(-1,2) - P(2,1)*P(1,2))')
gagaSbot = Lorentz(name = 'gagaSbot',
spins = [ 3, 3, 1 ],
structure = 'FTriPhotonBot(2*P(-1,1)... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Zero-DCE++: Learning to Enhance Low-Light Image via Zero-Reference Deep Curve
Estimation
Zero-DCE++ has a fast inference speed (1000/11 FPS on single GPU/CPU for an
image with a size of 1200*900*3) while keeping the enhancement performance of
Zero-DCE.
References:
... | python |
"""Number constraint names."""
from jsonvl._utilities.venum import Venum
class NumberConstraintNames(Venum):
"""Constraints applied to number types."""
LT = 'lt'
GT = 'gt'
LTE = 'lte'
GTE = 'gte'
EQ = 'eq'
| python |
import time
import logging
import numpy as np
import torch
import torch.nn as nn
from data import augment, TensorDataset
from diffaugment import DiffAugment
from utils import get_time
def epoch(mode, dataloader, net, optimizer, criterion, args, aug):
loss_avg, acc_avg, num_exp = 0, 0, 0
net = net.to(args.devic... | python |
#!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
import psycopg2
def connect():
"""Connect to the PostgreSQL database. Returns a database connection."""
return psycopg2.connect("dbname=tournament")
def deleteMatches():
"""Remove all the match records from the dat... | python |
a, b = [int(x) for x in input().split()]
if a > b:
a, b = b, a
if a & 1:
a += 1
if b & 1:
b -= 1
print(((b - a) // 2 + 1) * (a + b) // 2)
| python |
from ..SimpleSymbolDownloader import SymbolDownloader
from ..symbols.Generic import Generic
from time import sleep
from ..compat import text
import requests
class TigerDownloader(SymbolDownloader):
def __init__(self):
SymbolDownloader.__init__(self, "tiger")
def _add_queries(self, prefix=''):
... | python |
from flask import Blueprint
from app.actor import get_hello
import jsonpickle
hello_resource = Blueprint('hello_resource', __name__)
@hello_resource.route('/rest/hello/', defaults={'name': 'world'})
@hello_resource.route('/rest/hello/<name>')
def get(name):
return jsonpickle.encode(get_hello.run(name), unpicklab... | python |
"""
Copyright 2020 Alexander Brauckmann.
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... | python |
# coding=utf-8
# Copyright (c) 2016-2018, F5 Networks, 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 applicabl... | python |
from __future__ import annotations
import logging
import re
from dataclasses import dataclass
from datetime import date
from wordgame_bot.attempt import Attempt, AttemptParser
from wordgame_bot.exceptions import InvalidFormatError, ParsingError
from wordgame_bot.guess import Guesses, GuessInfo
INCORRECT_GUESS_SCORE ... | python |
# https://leetcode.com/problems/magic-squares-in-grid/description/
#
# algorithms
# Medium (35.25%)
# Total Accepted: 12,752
# Total Submissions: 36,179
# beats 66.41% of python submissions
class Solution(object):
def splitIntoFibonacci(self, S):
"""
:type S: str
:rtype: List[int]
... | python |
from django import forms
from formfactory import clean_methods
@clean_methods.register
def check_if_values_match(form_instance, **kwargs):
"""Clean method for when a contact updates password.
"""
first_field = form_instance.cleaned_data["first_field"]
second_field = form_instance.cleaned_data["second... | python |
# File: worker.py
# Aim: Backend worker of the http server
# Imports
import os
import sys
from . import CONFIG
from .local_tools import Tools
tools = Tools()
CONFIG.logger.debug('Worker imported in HTTP package')
# Import other workers
other_folders = [
os.path.join(
os.path.dirname(__file... | python |
from .forms import UserProfileForm, ProfileUpdateForm
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from .models import Profile
def display_login(request):
context = {}
ret... | python |
import tensorflow as tf
import numpy as np
import os
from scipy.io import loadmat
from epi.util import dbg_check
import matplotlib.pyplot as plt
# import tensorflow_probability as tfp
FANO_EPS = 1e-6
neuron_inds = {"E": 0, "P": 1, "S": 2, "V": 3}
def load_SSSN_variable(v, ind=0):
# npzfile = np.load("data/V1_Zs... | python |
from schematics.types import ModelType, StringType, PolyModelType, FloatType, DateTimeType
from spaceone.inventory.model.sqldatabase.data import Database
from spaceone.inventory.libs.schema.metadata.dynamic_field import TextDyField, DateTimeDyField, EnumDyField, \
ListDyField
from spaceone.inventory.libs.schema.me... | python |
"""Adam Integer Check"""
def prime_adam_check(number: int) -> bool:
"""
Check if a number is Adam Integer.
A number is Adam if the square of the number and square
of the reverse of the number are reverse of each other.
Example : 11 (11^2 and 11^2 are reverse of each other).
"""
# Get the... | python |
import re
import urllib2
import urllib
import urlparse
import socket
# sniff for python2.x / python3k compatibility "fixes'
try:
basestring = basestring
except NameError:
# 'basestring' is undefined, must be python3k
basestring = str
try:
next = next
except NameError:
# builtin next function doesn... | python |
class SPI(object):
def __init__(self, clk, MOSI=None, MISO=None):
self.clk = clk
self.MOSI = MOSI
self.MISO = MISO
| python |
from core.entity.entity_exceptions import EntityOperationNotPermitted, EntityNotFoundException
from core.test.media_files_test_case import MediaFilesTestCase
class BaseTestClass(MediaFilesTestCase):
"""
provides the base class for all test cases
_check_default_fields and _check_default_change must be re-... | python |
import numpy as np
import torch
from .mask_gen import BoxMaskGenerator
class CutmixCollateWrapper(object):
def __init__(self, batch_aug_fn=None):
self.batch_aug_fn = batch_aug_fn
self.mask_generator = BoxMaskGenerator(
prop_range = (0.25, 0.5),
n_boxes = 3,
rand... | python |
"""
# BEGIN BINGO_DEMO
>>> bingo = BingoCage(range(3))
>>> bingo()
2
>>> bingo()
0
>>> callable(bingo)
True
# END BINGO_DEMO
"""
# BEGIN BINGO
import random
class BingoCage:
def __init__(self, items):
self._items = list(items) # <1>
random.shuffle(self._items) # <2>
def __call__(self):
... | python |
from json import dumps
class Node:
def __init__(self, line = 0, column = 0):
self.line = line
self.column = column
@property
def clsname(self):
return str(self.__class__.__name__)
def to_tuple(self):
return tuple([
("node_class_name", self.clsname)
... | python |
from ckan.common import config
def get_ytp_recommendation_recaptcha_sitekey():
return config.get('ckanext.ytp_recommendation.recaptcha_sitekey')
| python |
# The MIT License(MIT)
# Copyright (c) 2013-2014 Matt Thomson
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, mo... | python |
import itertools
a = input()
s = input().split()
n = int(input())
L = list(itertools.combinations(s, n))
f = filter(lambda x: 'a' in x, L)
print("{:.4f}".format(len(list(f))/len(L)))
| python |
from django.conf.urls import include, url
urlpatterns = [
# browsable REST API
url(r'^api/', include('osmaxx.rest_api.urls')),
url(r'^version/', include('osmaxx.version.urls', namespace='version')),
]
| python |
"""
Copyright MIT and Harvey Mudd College
MIT License
Summer 2020
Lab 1 - Driving in Shapes
"""
########################################################################################
# Imports
########################################################################################
import sys
sys.path.insert(1, ".... | python |
import pyOcean_cpu as ocean
a = ocean.zeros([5,5])
a[1,...,3] = 99
print(a)
| python |
import sqlite3
import pandas as pd
from .. import CONFIG
import datetime
from ..scrape.utils import PROPER_DATE_FORMAT
class DB_Query():
def __init__(self, column_names, rows):
self.column_names = column_names
self.rows = rows
def to_df(self):
return pd.DataFrame(self.rows, columns=s... | python |
#!/usr/bin/env python3
"""
This is the player application called by remctl or
through SSH; it is the replacement for the Perl command
'acoustics' and provides the same functionality.
"""
import sys
import os
import importlib
sys.path.append(os.path.dirname(sys.argv[0]) + '/lib')
from amp import db, config
if __na... | python |
import argparse
import yaml
import os
import anndata as ad
from morphelia.preprocessing import *
from morphelia.features import *
def run(inp):
"""Preprocess morphological annotated data."""
# where to save figures
figdir = os.path.join(inp['output'], './figures/')
# load data
inp_data = os.path.... | python |
"""Encoder definition for transformer-transducer models."""
import torch
from espnet.nets.pytorch_backend.transducer.blocks import build_blocks
from espnet.nets.pytorch_backend.transducer.vgg2l import VGG2L
from espnet.nets.pytorch_backend.transformer.layer_norm import LayerNorm
from espnet.nets.pytorch_backend.tran... | python |
import gym
import quadruped_gym.gym # noqa: F401
def test_reset():
env = gym.make('A1BulletGymEnv-v0')
observation = env.reset()
assert observation in env.observation_space
def test_step():
env = gym.make('A1BulletGymEnv-v0')
env.reset()
for _ in range(10):
env.step(env.action_spac... | python |
import numpy as np
if __name__=="__main__":
N=list(map(int,input().split()))
print(np.zeros(N,int))
print(np.ones(N,int)) | python |
from jivago.jivago_application import JivagoApplication
from jivago.wsgi.annotations import Resource
from jivago.wsgi.methods import GET
@Resource("/")
class HelloResource(object):
@GET
def get_hello(self) -> str:
return "Hello World!"
app = JivagoApplication()
if __name__ == '__main__':
app.r... | python |
import pandas
from matplotlib import pyplot
df = pandas.DataFrame([431-106,106])
df = df.transpose()
df.columns=['complete','incomplete']
df.plot(kind='bar', stacked=True, legend=False)
pyplot.show()
| python |
from typing import Tuple, Union, List, Optional
from sectionproperties.pre import sections
import numpy as np
import shapely
def create_line_segment(
point_on_line: Union[Tuple[float, float], np.ndarray],
vector: np.ndarray,
bounds: tuple,
):
"""
Return a LineString of a line that contains 'point... | python |
# -*- coding: utf-8 -*-
class Config(object):
def __init__(self, config_path):
config_path = Config.validate_path(config_path)
self.config_path = config_path
self._config = Config.validate_format_and_parse(config_path)
def __getitem__(self, key):
return self._config.get(key)
... | python |
from django.conf.urls import include, url
from django.contrib import admin
#handler400 = 'world.views.error400page'
#AEN: THIS doesn't work!
import voxel_globe.main.views
urlpatterns = [
#Admin site apps
url(r'^admin/', include(admin.site.urls)),
#Test app for development reasons
url(r'^world/', inc... | python |
"""added column to DT and created NewTable
Revision ID: 1100598db8eb
Revises: 66362e7784fd
Create Date: 2021-02-21 13:56:05.307362
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1100598db8eb'
down_revision = '66362e7784fd'
branch_labels = None
depends_on = No... | python |
import time
import multiprocessing
import subprocess
import sys
import os
def run(name):
dir_path = os.path.dirname(os.path.realpath(__file__))
subprocess.Popen(('%s' % sys.executable, os.path.join(dir_path, "test_remote.py"), name, "etc etc"))
if __name__ == '__main__':
multiprocessing.Process(target=ru... | python |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
from concurrent.futures import TimeoutError
from kikimr.public.sdk.python import client as ydb
import random
EXPIRATION_QUEUE_COUNT = 4
DOC_TABLE_PARTITION_COUNT = 4
ADD_DOCUMENT_TRANSACTION = """PRAGMA TablePathPrefix("%s");
DECLARE $url AS Ut... | python |
#Elsa by Frostmeister
import discord
import math
import time
import googlesearch as gs
import urbandictionary as ud
import random
import asyncio
from discord.ext import commands
####### General
class General:
def __init__(self , bot):
self.bot = bot
@commands.command()
async def in... | python |
# -*- coding:utf-8 -*-
"""
jsondict <-> dict <-> model object
\______________________/
"""
def _datetime(*args):
import pytz
from datetime import datetime
args = list(args)
args.append(pytz.utc)
return datetime(*args)
def _getTarget():
from alchemyjsonschema.mapping import Draft4MappingF... | python |
import numpy as np
'''
Reorient the mesh represented by @vertices so that the z-axis is aligned with @axis
'''
def orient_mesh(vertices, axis):
vector_norm = np.sqrt(axis[0]**2 + axis[1]**2 + axis[2]**2)
yz_length = np.sqrt(axis[1]**2 + axis[2]**2)
# Rotate around the y-axis
if vector_norm != 0:
... | python |
# -*- coding: utf-8 -*-
import logging
import math
import random
from PIL import Image, ImageDraw
from .wallpaper_filter import WallpaperFilter
from ..geom.point import Point
from ..geom.size import Size
logger = logging.getLogger(__name__)
class Tunnel(WallpaperFilter):
def _centroid(self, size) -> Point:
... | python |
#!/usr/bin/env python
#-*- coding=UTF-8 -*-
import httplib2
import json
import random
import string
import time
import urllib
from securUtil import SecurUtil
class smsUtil():
@staticmethod
def baseHTTPSRequest(url, data):
# 配置 HTTP Request Header
AppKey = '1958cd7bc542a299b0c3bc428f14006e'... | python |
"""
drift
=====
Drift calculation methods.
"""
from .continuous import drift_continuous
from .roman import drift_roman
| python |
# Copyright (c) 2019, Digi International, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, pu... | python |
import math, glm
class Camera:
def __init__(self, position):
self.position = position
self.up = glm.vec3(0, 1, 0)
self.worldUp = glm.vec3(0, 1, 0)
self.pitch = 0
self.yaw = 0
self.speed = 20
self.sensitivity = 0.25
self.updateVectors()
def moveRi... | python |
from bfieldtools import contour
import pytest
import numpy as np
from numpy.testing import (
assert_array_almost_equal,
assert_array_equal,
assert_allclose,
assert_equal,
)
def setup_contour_input():
""" Load example mesh and create scalars data
"""
from bfieldtools.utils import load_exa... | python |
# Leia um valor de comprimento em jardas e apresente-o convertido em metros
# A foruma de conversão é: M = 0.91 * J
J = float(input("Digite um valor em jardas: "))
M = 0.91 * J
print("O valor em de jardas para metros é: %0.2f" % M)
| python |
from .arch import Arch
from .debian import Debian
from .ubuntu import Ubuntu
from .redhat import RedHat
from .centos import CentOS
| python |
import argparse
import torch
from torch.autograd import Variable
import model
import util
import data
import time
import torchvision.transforms as transforms
import shutil
model_names = sorted(name for name in model.__dict__
if name.startswith("Planet")
and callable(model.__dict__[name]))
print model_names
... | python |
import abc
class RecurrentSupervisedLearningEnv(metaclass=abc.ABCMeta):
"""
An environment that's really just a supervised learning task.
"""
@abc.abstractmethod
def get_batch(self, batch_size):
"""
:param batch_size: Size of the batch size
:return: tuple (X, Y) where
... | python |
'''
Created on Aug 9, 2013
@author: salchoman@gmail.com - salcho
'''
class wsResponse:
def __init__(self, id=-1, params=None, size=-1, response=None, payload=None, plugin=None):
self.id = id
self.params = params
self.size = size
self.http_code = -1
self.response = None... | python |
import tensorflow as tf
def iou(source, target):
"""Calculates intersection over union (IoU) and intersection areas for two sets
of objects with box representations.
This uses simple arithmetic and outer products to calculate the IoU and intersections
between all pairs without looping.
Parameter... | python |
# Generated by Django 3.0.3 on 2020-08-10 13:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ecommerce_platform', '0015_auto_20200810_1252'),
]
operations = [
migrations.RenameField(
model_name='coupon',
... | python |
import pytest
from pytest import approx
import os
import shutil
import numpy as np
import pandas as pd
from tarpan.testutils.a03_cars.cars import get_fit
from tarpan.cmdstanpy.waic import (
waic, compare_waic, save_compare_waic_csv, save_compare_waic_txt,
waic_compared_to_df,
WaicData, WaicModelCompared,
... | python |
# -*- coding: utf-8 -*-
# @Date : 2019-07-26
# @Author : Xinyu Gong (xy_gong@tamu.edu)
# @Link : None
# @Version : 0.0
import os
import glob
import argparse
import numpy as np
from scipy.misc import imread
import tensorflow as tf
import utils.fid_score as fid
def parse_args():
parser = argparse.Argument... | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
'''
@author: Jinpeng LI
@contact: mr.li.jinpeng@gmail.com
@organization: I2BM, Neurospin, Gif-sur-Yvette, France
@organization: CATI, France
@organization: U{IFR 49<http://www.ifr49.org>}
@license: U{CeCILL version 2<http://www.cecill.info/licences/Lice... | python |
from dataclasses import dataclass, field
from typing import Dict
from lf3py.serialization.deserializer import DictDeserializer
@dataclass
class SNSMessage(DictDeserializer):
message: str = ''
attributes: Dict[str, Dict[str, str]] = field(default_factory=dict)
| python |
from utils import *
def cross_val_split(dataset, folds):
"""
Splits the dataset into folds number of subsets of almost equal size after randomly shuffling it, for cross
validation.
:param dataset: The dataset to be splitted.
:param folds: The number of folds to be created.
:return: The datase... | python |
import random
from abc import ABCMeta, abstractmethod
from collections import defaultdict, Counter, OrderedDict
import math
import numpy as np
from gtd.log import indent
from wge.rl import Trace
def normalize_counts(counts):
"""Return a normalized Counter object."""
normed = Counter()
total = float(sum(... | python |
#
# PySNMP MIB module FNCNMS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FNCNMS
# Produced by pysmi-0.3.4 at Wed May 1 13:14:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
... | python |
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x' 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W','X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', ... | python |
"""
Determine an optimal list of hotel to visit.
```
$ python src/domain/solver.py \
-s "/Users/fpaupier/projects/samu_social/data/hotels_subset.csv
```
Note that the first record should be the adress of the starting point (let's say the HQ of the Samu Social)
"""
import argparse
import numpy as... | python |
import torch.nn as nn
import math
import torch.nn.functional as F
__all__ = ['SENet', 'Sphere20a', 'senet50']
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
# ... | python |
# Create your views here.
from django.conf import settings
from django.core.cache import cache
from django.db.models import Prefetch
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from rest_framework.generics import RetrieveAPIView, ListAPIView
from question.m... | python |
import os.path
import random
import multiprocessing
import pandas as pd
from utils import load_library, correct_full_sequence, get_precursor_indice, tear_library, flatten_list
from mz_calculator import calc_fragment_mz
def shuffle_seq(seq = None, seed = None):
"""Fisher-Yates algorithm. Modified from PECAN's deco... | python |
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2020-2021 Micron Technology, Inc. All rights reserved.
import argparse
import datetime
import os
import time
import subprocess
import sys
import requests_unixsocket
import yaml
TZ_LOCAL = datetime.datetime.now(datetime.timezone.utc).ast... | python |
import csv
import six
import io
import json
import logging
from collections import Mapping
from ..util import resolve_file_path
logger = logging.getLogger(__name__)
EPILOG = __doc__
class MappingTableIntakeException(Exception):
""" Specific type of exception we'd like to throw if we fail in this stage
du... | python |
import numpy as np
import torch
import itertools
from torch.autograd import Variable
def getGridMask(frame, dimensions, num_person, neighborhood_size, grid_size, is_occupancy = False):
'''
This function computes the binary mask that represents the
occupancy of each ped in the other's grid
params:
... | python |
# Copyright 2021 The KaiJIN 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 applicable ... | python |
import anyio
from anyio_mqtt import AnyIOMQTTClient
import logging
_LOG = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
logging.getLogger("anyio_mqtt").setLevel(logging.DEBUG)
PAHO_LOGGER = logging.getLogger("paho")
PAHO_LOGGER.setLevel(logging.DEBUG)
async def main() -> None:
_LOG.debu... | python |
import time
import random
import numpy as np
import torch
from torchtuples import tuplefy, TupleTree
def make_name_hash(name='', file_ending='.pt'):
year, month, day, hour, minute, second = time.localtime()[:6]
ascii_letters_digits = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
random_h... | python |
# Copyright (c) Andrey Sobolev, 2019. Distributed under MIT license, see LICENSE file.
GEOMETRY_LABEL = 'Geometry optimization'
PHONON_LABEL = 'Phonon frequency'
ELASTIC_LABEL = 'Elastic constants'
PROPERTIES_LABEL = 'One-electron properties'
| python |
import django # this verifies local libraries can be packed into the egg
def addition(first, second):
return first + second
| python |
import sys
import os
import argparse
import pandas as pd
from fr.tagc.rainet.core.util.exception.RainetException import RainetException
from fr.tagc.rainet.core.util.log.Logger import Logger
from fr.tagc.rainet.core.util.time.Timer import Timer
from fr.tagc.rainet.core.util.subprocess.SubprocessUtil import SubprocessU... | python |
"""
参数及配置
"""
# main.py
small_dataset = False # 选择数据集规模
small_train_path = "../data/small_dataset/train.conll" # 小数据集-训练集
small_dev_path = "../data/small_dataset/dev.conll" # 小数据集-验证集
big_train_path = "../data/big_dataset/train" # 大数据集-训练集
big_dev_path = "../data/big_dataset/dev" # 大数据集-验证集
big_test_pat... | python |
from cakechat.utils.data_structures import create_namedtuple_instance
SPECIAL_TOKENS = create_namedtuple_instance(
'SPECIAL_TOKENS', PAD_TOKEN=u'_pad_', UNKNOWN_TOKEN=u'_unk_', START_TOKEN=u'_start_', EOS_TOKEN=u'_end_')
DIALOG_TEXT_FIELD = 'text'
DIALOG_CONDITION_FIELD = 'condition'
| python |
from models.models import Departamento | python |
# -*- coding: utf-8 -*-
"""
Python implementation of Tanner Helland's color color conversion code.
http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/
"""
import math
# Aproximate colour temperatures for common lighting conditions.
COLOR_TEMPERATURES = {
'candle': 1900,
'sunrise': 2000,
... | python |
# The MIT license:
#
# Copyright 2017 Andre Netzeband
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merg... | python |
# Generated by Django 2.2.5 on 2019-10-07 17:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cases', '0016_datetimes_to_dates'),
]
operations = [
migrations.AlterField(
model_name='preliminarycase',
name='comp... | python |
from pyvisdk.esxcli.executer import execute_soap
from pyvisdk.esxcli.base import Base
class IscsiNetworkportalIpconfig(Base):
'''
Operations that can be performed on iSCSI Network Portal (iSCSI vmknic)'s IP configuration
'''
moid = 'ha-cli-handler-iscsi-networkportal-ipconfig'
def set(self, adapte... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.