content stringlengths 5 1.05M |
|---|
"""
This file defines the L-Op and R-Op, based on https://j-towns.github.io/2017/06/12/A-new-trick.html
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
def Lop(nodes, x, v):
lop_out = tf.gradients(nodes, x, grad_ys=v)
re... |
from django.apps import AppConfig
class ChoresConfig(AppConfig):
name = 'chores'
|
"""Compute depth maps for images in the input folder.
"""
from operator import eq
import os
import glob
from numpy.core.defchararray import mod
from numpy.lib.shape_base import tile
from serial.win32 import EV_BREAK
from timm.models import senet
from timm.models.byobnet import num_groups
import torch
from torch.functio... |
from dateutil.tz import UTC
from dateutil.tz import gettz
from yui.apps.info.memo.models import Memo
from yui.utils.datetime import now
def test_memo_model(fx_sess):
now_dt = now()
record = Memo()
record.keyword = 'test'
record.text = 'test test'
record.author = 'U1'
record.created_at = now_... |
# -*- coding: utf-8 -*-
from django.db import models
from apps.registro.models.ExtensionAulica import ExtensionAulica
from apps.seguridad.audit import audit
@audit
class ExtensionAulicaMatricula(models.Model):
extension_aulica = models.ForeignKey(ExtensionAulica)
anio = models.IntegerField()
mixto = model... |
import unittest
from test.helpers import get_general_wrapper
class Rule1Test(unittest.TestCase):
def test_rule1_negative(self):
context = """
LABEL maintainer="foo <foo@bar.com>"
# A Comment
FROM registry.a.com/acme/centos:7
"""
wrapper = get_general_wrapper(contex... |
#!/usr/bin/env python
import Align
import sys
import pdb
inFile = open(sys.argv[1])
nMatch = 0
nTest = 0
for line in inFile.readlines():
vals = line.split()
seqs = vals[6].split(';')
if (len(seqs) == 2):
(qopt, topt, score) = Align.SWAlign(seqs[0], seqs[1], indel=0,mismatch=0)
ident = floa... |
VERSION="20200103"
|
from utils.discord import help_me, DiscordInteractive
from utils.osu.utils import CalculateMods
from utils.utils import Log
interact = DiscordInteractive.interact
class Command:
command = "ar"
description = "Calculate Approach Rate values and milliseconds with mods applied."
argsRequired = 1
usage = ... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ResourcePrice:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is a... |
import os.path as osp
from cvpods.configs.ssd_config import SSDConfig
_config_dict = dict(
MODEL=dict(
WEIGHTS="cvpods/ImageNetPretrained/mmlab/vgg16.pth",
SSD=dict(
IMAGE_SIZE=512,
FEATURE_MAP_SIZE=[64, 32, 16, 8, 4, 2, 1],
DEFAULT_BOX=dict(
SCA... |
import numpy as np
from sklearn.neural_network import MLPRegressor
import sklearn
from itertools import repeat
import warnings
warnings.filterwarnings("ignore")
from multiprocessing import Pool
class DeepNeuroevolution():
def __init__(self, env, n_individuals, n_parents, n_features, n_actions, nn_architectur... |
from __future__ import annotations
from ctc import spec
def digest_eth_get_compilers(
response: spec.RpcSingularResponse,
) -> spec.RpcSingularResponse:
return response
def digest_eth_compile_lll(
response: spec.RpcSingularResponse,
) -> spec.RpcSingularResponse:
return response
def digest_eth_co... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import sys
import os
import time
import tempfile
import re
import traceback
sys.path.insert(0, os.path.abspath(os.path.... |
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib_venn import venn2, venn2_circles, venn3, venn3_circles
from scipy.stats import hypergeom
from os import path, makedirs
from statsmodels.sandbox.stats.multicomp import multipletests
import numpy as np
from biom import load_table
import seaborn as sns
im... |
# Preppin' Data 2021 Week 25
import pandas as pd
import numpy as np
# Load data
gen_1 = pd.read_excel('unprepped_data\\PD 2021 Wk 25 Input - 2021W25 Input.xlsx', sheet_name='Gen 1')
evolution_group = pd.read_excel('unprepped_data\\PD 2021 Wk 25 Input - 2021W25 Input.xlsx', sheet_name='Evolution Group')
evolutions = pd... |
from __future__ import annotations
import lcs.agents.acs as acs
from lcs import Perception
from lcs.agents.acs2 import ProbabilityEnhancedAttribute
from .. import ImmutableSequence
DETAILED_PEE_PRINTING = True
class Effect(acs.Effect):
def __init__(self, observation):
# Convert dict to ProbabilityEnhan... |
from fastapi import Depends
from fastapi import FastAPI as App
from starlette.responses import Response
from benchmarks.utils import generate_dag
app = App()
def make_depends(type_: str, provider: str) -> str:
return f"{type_} = Depends({provider})"
glbls = {"Depends": Depends}
@app.router.get("/simple")
as... |
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the NiBabel package for the
# copyright and license terms.
#
### ### ### #... |
import re
import requests
from urllib3.exceptions import InsecureRequestWarning
from actions.casLogin import casLogin
from actions.iapLogin import iapLogin
from actions.utils import Utils
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
class wiseLoginService:
# 初始化本地登录类
def __init__(self, ... |
"""
Support for the Yahoo! Weather service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.yweather/
"""
import logging
from datetime import timedelta
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassista... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import teimedlib.pathutils as ptu
"""
scrittura comandi
uash.py dir1/dir2/cmd.py ls .
scrive in cmd.py ls .
"""
def write_cmd(lst):
name = lst[0]
cmd = " ".join(lst[1:])
# path = os.path.join(path_bin(), name)
print(name)
print(c... |
# Generated by Django 2.2.11 on 2020-04-02 18:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('facility', '0066_auto_20200402_1806'),
]
operations = [
migrations.AlterField(
model_name='historicalpatientregistration',
... |
import tensorflow as tf
import nalp.utils.logging as l
from nalp.models.generators.rmc import RMCGenerator
from nalp.models.layers.gumbel_softmax import GumbelSoftmax
logger = l.get_logger(__name__)
class GumbelRMCGenerator(RMCGenerator):
"""A GumbelRMCGenerator class is the one in charge of a generative Gumbel... |
#!/bin/env python
#
# File: PyMOLConvertPMLToPSE.py
# Author: Manish Sud <msud@san.rr.com>
#
# Copyright (C) 2018 Manish Sud. All rights reserved.
#
# The functionality available in this script is implemented using PyMOL, a
# molecular visualization system on an open source foundation originally
# developed by Warren D... |
# -*- coding: utf-8 -*-
################################################################
# The contents of this file are subject to the BSD 3Clause (New) License
# you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://directory.fsf.org/wiki/License:BSD_3Cla... |
"""StockAnalysis View"""
__docformat__ = "numpy"
# pylint:disable=too-many-arguments, too-many-lines
import copy
import logging
import os
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.config_plot import PLOT_DP... |
"""
[ BI_error_corrector_2 ]
2019-07-28
system적으로 걸러낼 수 있는 것은 완료.
1. Chunk-based Dependency Corpus의 입력이 될 pickle 파일 출력
::수정 전 파일 (입력 파일)::
".\pickle\0617_02\ch_pred_sent.pickle"
::출력 파일::
".\BI_correct\BI_correct.pickle"
2. 파일 출력 후 수동 오류 개선에 편리하게 코드 수정할 것.
1에서 출력한 파일을 코드 수정 없이 그대로 다시 입력으로 넣으면
수정 되는 항목 없어야 함.
(멀쩡한 BI까지... |
from logging import getLogger
from django.core.management.base import BaseCommand, CommandError
from worker.utils import listen, create_lircrc_tempfile
LOGGER = getLogger(__name__)
class Command(BaseCommand):
def handle(*args, **options):
name = 'riker'
fname = create_lircrc_tempfile(name)
... |
import numpy as np
import matplotlib.pyplot as plt
import bead_util as bu
import scipy.signal as ss
path = "/data/20180927/bead1/spinning/0_6mbar"
files = bu.find_all_fnames(path)
index = 0
fdrive = 1210.7
bw = 0.1
bwp = 5.
Ns = 250000
Fs = 5000.
k = 1e-13*(2.*np.pi*370.)**2
df = bu.DataFile()
def proc_f(f):
df.l... |
#!/usr/bin/env python
"""
This script is used to map fastq files to the genome. The input is a comma
separated list of fastq[.gz] files (or two lists if the input is paired-end).
The output are bam files with the mapped reads, a table containing the number
of reads mapped to each gene and a wiggle file with the covera... |
from lxml import etree
from modules.tier_1_crawler import Tier_1_Crawler
class Uniqlo_Crawler(Tier_1_Crawler):
''' This func is used by func: extract_data '''
def __get_genre_list(self):
return ["women","men","kids","baby"]
''' This func is used by func: extract_data '''
def __get_forbidde... |
import os
import sys
class local():
def __init__(self,local):
self.local=local
def local_do(self):
try:
os.mkdir(self.local)
except:
pass
try:
open(self.local+".set_color.txt","w+")
open(self.... |
import argparse
import csv
def main():
parser = argparse.ArgumentParser(description="Determine FASTQ file encoding")
# parser.add_argument("OUTFILE", help="Name to save to. If ends in '.gz', output will be gzipped")
parser.add_argument("FILE1", type=file,
help="?????")
parser.... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from .obscore import *
__all__ = ["ObsCoreMetadata"]
|
# MIT License
#
# Copyright (c) 2019
# Miguel Perales - miguelperalesbermejo@gmail.com
# Jose Manuel Caballero - jcaballeromunoz4@gmail.com
# Jose Antonio Martin - ja.martin.esteban@gmail.com
# Miguel Diaz - migueldiazgil92@gmail.com
# Jesus Blanco Garrido - jesusblancogarrido@gmail.com
#
# Permission is hereby gran... |
print("enter your config for the sudoku grid, 0 equals empty")
A1 = int(input("A1"))
A2 = int(input("A2"))
A3 = int(input("A3"))
A4 = int(input("A4"))
A5 = int(input("A5"))
A6 = int(input("A6"))
A7 = int(input("A7"))
A8 = int(input("A8"))
A9 = int(input("A9"))
B1 = int(input("B1"))
B2 = int(input("B2"))
B3 = int(i... |
# This python file takes samples per second from a video
# And determines the amount of information that it has using summing all the pixel intensities in
# its grayscale version
import cv2
import numpy as np
import os
import time
import math
# Global variables
number_samples = 100
length_of_file = 60
# Ta... |
import logging
from .base import * # noqa
logging.disable(logging.CRITICAL)
# Should only include explicit testing settings
SECRET_KEY = 'NOT A SECRET'
PROJECTS_ENABLED = True
PROJECTS_AUTO_CREATE = True
TRANSITION_AFTER_REVIEWS = 2
TRANSITION_AFTER_ASSIGNED = True
STATICFILES_STORAGE = 'django.contrib.staticf... |
lista=[]
while True:
lista.append(int(input('Digite um valor : ')))
res = str(input('Deseja continuar ? [S/N] : '))
if res in 'Nn':
break
print('+='*30)
print(f'Voce digitou {len(lista)} numeros')
lista.sort(reverse=True) # organiza em ordem crescente
print(f'Voce digitou em ordem decrescen... |
import commands
import sys,os
input_file=sys.argv[1]
current_path=commands.getoutput('pwd')
print 'Read input_file',input_file
#input file is final_combination3.csv
if os.path.isfile(input_file) == True:
#use this flow to convert file to nominal and saving as arff
file_kf=open('./convert2arff.kf','r')
file_kf_read... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
###
# Copyright (2016-2019) Hewlett Packard Enterprise Development LP
#
# 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/licen... |
from TAC_serialize import *
from tacgen import TACIndexer
from ctypes import c_int
#enum for type of object
class DataType:
Repr = ['Object', 'Int', 'Bool', 'String']
Object = 0
Int = 1
Bool = 2
String = 3
#enum for position on lattice
class DataLattice:
Repr = ['Bottom', 'Mid', 'Top']
Bot... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#传球项目1状态机:
#流程:机器前往传球区并放下铲子 -> 传球 -> 前进到找球的位置 -> 开始检测球(以原地自转的方式) -> 检测到球后接近球到球前方0.8米处
# -> 再次检测球并调整铲子方向后前进 -> 铲球 -> 调整机器角度朝向传球区 -> 投球 -> 升起铲子 -> 回家
import rospy
import smach
import math
import smach_ros
from robot_state_class.robot_state_class import *
def pass_fir... |
"""Contains core classes for planners
Code structures are borrowed from simple_rl(https://github.com/david-abel/simple_rl)
"""
from abc import ABC, abstractmethod
class Planner(ABC):
def __init__(self, name: str):
self._name = name
@property
def name(self):
return self._name
@abstra... |
#!/usr/bin/env python
from typing import Union
import numpy as np
import mapel.roommates.models.euclidean as euclidean
import mapel.roommates.models.impartial as impartial
import mapel.roommates.models.mallows as mallows
import mapel.roommates.models.urn as urn
import mapel.roommates.models.group_separable as group_... |
#!/opt/bin/lv_micropython -i
# change the above to the path of your lv_micropython -i unix binary
#
import time
#
# initialize lvgl
#
import lvgl as lv
import display_driver
from lv_colors import lv_colors
style = lv.style_t()
style.init()
# Set a background color and a radius
style.set_radius(lv.STATE.DEFAULT, 5)
sty... |
# Copyright (c) 2010-2012 Massachusetts Institute of Technology.
# MIT License (cf. MIT-LICENSE.txt or http://www.opensource.org/licenses/mit-license.php)
from django.conf.urls.defaults import *
urlpatterns = patterns('img.views',
url(r'^js/textareas/(?P<name>.+)/$', 'textareas_js', name='tinymce-js'),
|
#crie um algoritmo que leia um número
#e mostre seu dobro, triplo e raiz quadrada
n = int(input('Digite um número: '))
d = n * 2
t = n * 3
r = n ** (1/2)
print('O dobro de {} é {}, o triplo é {} e a raíz quadarada é {:.3f}'.format(n,d,t,r))
|
#!/usr/bin/env python3
import logging as log
from lxml import etree
import copy
import math as m
from enum import Enum
import converter
from objects import *
import gazebo_objects as go
# Files pathes
SAMPLE_BOX_PATH = "models/box.sdf"
SAMPLE_LINE_PATH = "models/line.sdf"
TRAFFIC_LIGHT_PATH = "model://traffic-light"
E... |
# Supplementary classes and functions for ENGSCI233 notebook Data.ipynb
# author: David Dempsey
from matplotlib import pyplot as plt
import numpy as np
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
# Module 1: Data
def show_list(ll, ax, highlight=None, label=None, **kwargs)... |
import sys
import numpy as np
import torch
from pytorch_fid.inception import InceptionV3
sys.path.insert(0, '/workspace')
from datasets.custom_subset import SingleClassSubset
from utils.stylegan import create_image
class PRCD:
def __init__(self, dataset_real, dataset_fake, device, crop_size=None, generator=None... |
import curses
from spotui.src.util import truncate
from spotui.src.menu import Menu
from spotui.src.component import Component
class DeviceMenu(Component):
def __init__(self, stdscr, api, select_device, close):
self.stdscr = stdscr
self.api = api
self.select_device = select_device
... |
import ast
import sys
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
class Kline:
def __init__(self, kl):
self.open_time = kl[0]
self.open = float(kl[1])
self.high = float(kl[2])
self.low = float(kl[3])
self.close = float(kl[4])
sel... |
var fs = require('fs');
var stemmer = require('../porter').stemmer;
process.chdir(__dirname);
exports['test Porter stemmer'] = function(test){
// check that the sample vocabulary given on
// http://tartarus.org/~martin/PorterStemmer/
// yields the expected output when stemmed.
var vocabulary = fs.readFileSy... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2018 Fedele Mantuano (https://www.linkedin.com/in/fmantuano/)
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/... |
import logging
import sys
import json
import django
from django.http import HttpResponse
logger = logging.getLogger(__name__)
class BinderException(Exception):
http_code = None
code = None
fields = None
validation_errors = None
def __init__(self):
self.fields = {}
def exception_location(self):
import... |
import numpy as np
from rh_logger.api import logger
import logging
import rh_logger
from collections import defaultdict
from mb_aligner.common import ransac
class EstimateUsingSimilarTilesMatches(object):
def __init__(self, **kwargs):
self._missing_matches = {}
if kwargs is None:
kwar... |
test = {
'name': 'matchmaker',
'points': 0,
'suites': [
{
'cases': [
{
'code': r"""
sqlite> SELECT * FROM matchmaker ORDER BY color LIMIT 50;
koala|Thinking Out Loud||red
koala|Thinking Out Loud||blue
|Sandstorm|#009abf|black and gold
t... |
# Item info
item_info_dict = {
18: {
'packagedVolume': 0.35,
'name': 'Plagioclase',
'volume': 0.35
},
19: {
'packagedVolume': 16.0,
'name': 'Spodumain',
'volume': 16.0
},
20: {
'packagedVolume': 1.2,
'name': 'Kernite',
'volume'... |
from application.model.entity.usuario import Usuario
class Leitor(Usuario):
def __init__(self, autor_seguido = [], publicacao_curtida = []):
self._autor_seguido = autor_seguido
self._publicacao_curtida = publicacao_curtida
def get_autor_seguido(self):
return self._autor_seguido... |
import itertools
import sys
##### Reading data from a text file
path_to_file = sys.argv[1]
with open(path_to_file) as f:
array = []
for line in f:
line = line.split()
if line:
line = [str(i) for i in line]
array.append(line)
array = list(itertools.chain(*array))
#####
##### Quicksort subroutine
def quick... |
import unittest
from unittest import TestCase
import numpy as np
from escnn.gspaces import *
from escnn.nn import *
from escnn.nn.modules.basismanager import BlocksBasisSampler
import torch
class TestBasisSampler(TestCase):
def test_conv2d(self):
gspaces = [
rot2dOnR2(4),
f... |
# main_B
# set configuration only for root Logger
import logging, logging.config
from package1.module1_1 import func1_1_1
from package1.package1a.module1a_1 import func1a_1_1
from package2.module2_1 import func2_1
MODE = "set_file_filter"
if __name__=="__main__":
if MODE == "unexpected_log":
# [非推奨... |
from rest_framework import permissions
class IsOfficial(permissions.BasePermission):
"""
Custom permission to allow only official users to pass.
"""
def has_object_permission(self, request, view, obj):
return request.user.is_official |
from common.python.simulations import BlockSimulation, properties_from_ini
from collections import deque
# max queue size
MAX_QUEUE = 1023
# min FPGA deadtime between queued pulses
MIN_QUEUE_DELTA = 4
# time taken to clear queue
QUEUE_CLEAR_TIME = 4
NAMES, PROPERTIES = properties_from_ini(__file__, "pulse.block.in... |
from PyQt5 import QtGui
class SLOTEditDialog(QtGui.QWidget):
def __init__(self, parent=None, model, encodingModel):
super(SLOTEditDialog, self).__init__(parent)
self.model = model
self.encodingModel = encodingModel
# Set up the widgets.
nameLabel = QtGui.QLabel... |
import os
import time
import shutil
import pathlib
from socketer import MASM
import threading
from facer import Facer
masmPath = None
pDataPath = None
pLBPHPath = None
pNamePath = None
detcMethod = 0 # 0 HAAR, 1 DNN, 2 BOTH
failTimeout = 10
memoryTimeout = 5
lastAccess = False
preparedYet = False
keepWebcamOpen = Non... |
from docs_snippets_crag.concepts.configuration.configured_named_op_example import datasets
def test_job():
result = datasets.to_job().execute_in_process(
run_config={
"ops": {
"sample_dataset": {"inputs": {"xs": [4, 8, 15, 16, 23, 42]}},
"full_dataset": {
... |
from .lit import LIT
def build_model(config):
model_type = config.MODEL.TYPE
if model_type == 'lit':
model = LIT(img_size=config.DATA.IMG_SIZE,
patch_size=config.MODEL.LIT.PATCH_SIZE,
in_chans=config.MODEL.LIT.IN_CHANS,
... |
# -*- coding: utf-8 -*-
# @File : models.py
# @Author : AaronJny
# @Time : 2020/03/26
# @Desc :
import tensorflow as tf
from dataset import tokenizer
import settings
model = tf.keras.Sequential([
tf.keras.layers.Input((None,)),
tf.keras.layers.Embedding(input_dim=tokenizer.vocab_size, output_dim=128)... |
from plotly.graph_objs import Parcoords
|
from mirari.mirari.admin import *
from .models import *
from .vars import *
@admin.register(Sellpoint)
class SellpointAdmin(PassAdmin):
pass
@admin.register(Menu)
class MenuAdmin(PassAdmin):
pass
@admin.register(Product)
class ProductAdmin(PassAdmin):
pass
@admin.register(ProductAttributes)
class Produc... |
from .models import BirthdayWRandomNumberExt
from datetime import datetime
from django.core.urlresolvers import reverse
from django.db import IntegrityError
from django.test import TestCase
#
# Model Tests
#
class BirthdayWRandomNumberExtTests(TestCase):
def test_must_have_birthday(self):
'''Test that t... |
import streamlit as st
import streamlit.components.v1 as components
def app():
components.html(
'''
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Find Homes</title>
</head>
<body>
<div id="zillow-large-search-box-widget-container"... |
# https://adventofcode.com/2021/day/6
def solve(timers, days):
if len(timers) == 0:
return 0
for day in range(0, days):
for i in range(0, len(timers)):
if timers[i] == 0:
timers[i] = 6 # reset timers
timers.append(8) # newborn lanternfish
else:
timers[i] -= 1
... |
"""
---> Car Pooling
---> Medium
"""
from heapq import *
class Solution:
def carPooling(self, trips, capacity: int) -> bool:
trips = sorted(trips, key=lambda x: x[1])
heap = []
for (c, f, t) in trips:
while heap and heap[0][0] <= f:
v = heappop(heap)[1]
... |
#!/usr/bin/env python
# coding: utf-8
import sys
import numpy as np
from scipy.linalg import logm
from scipy import sparse
import scipy.linalg as linalg
import statistics
import utils
from numba import njit
import qutip as qt
sys.path.append("/home/felipe/git-projects/syk-nonergodic/")
def _ptrace_dense(Q, dims, sel... |
reversed_letters = {
'A' : 'A',
'E' : '3',
'H' : 'H',
'I' : 'I',
'J' : 'L',
'L' : 'J',
'M' : 'M',
'O' : 'O',
'S' : '2',
'T' : 'T',
'U' : 'U',
'V' : 'V',
'W' : 'W',
'X' : 'X',
'Y' : 'Y',
'Z' : '5',
'1' : '1',
'2' : 'S',
'3' : 'E',
'5' : 'Z',
'8' : '8'
}
from sys import std... |
from __future__ import annotations
import pytest
from poetry.core.packages.specification import PackageSpecification
@pytest.mark.parametrize(
"spec1, spec2, expected",
[
(PackageSpecification("a"), PackageSpecification("a"), True),
(PackageSpecification("a", "type1"), PackageSpecification("... |
import unittest
import struct
import pytest
import pytds
from pytds.smp import *
from utils import MockSock
smp_hdr = struct.Struct('<BBHLLL')
class SmpSessionsTests(unittest.TestCase):
def setUp(self):
self.sock = MockSock()
self.mgr = SmpManager(self.sock)
self.sess = self.mgr.create_s... |
"""Procedure to run and collect latency data.
# INSTRUCTIONS PARALLEL PORT
# http://stefanappelhoff.com/blog/2017/11/23/Triggers-with-Psychopy-on-BrainVision-Recorder
import time
from ctypes import windll
# Opening up the driver (first call is always slower)
assert windll.inpoutx64.IsInpOutDriverOpen()
windll.inpout... |
from setuptools import setup
setup(
name='tweetx',
version='0.0.1',
description='In space, everyone can hear you tweet.',
packages=['tweetx', 'tweetx.bot'],
install_requires=[
'tweepy',
'websockets'
]
)
|
# _*_ coding:utf-8 _*_
import re
from app.spider_store.common import (
get_content,
)
fake_headers_mobile = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'UTF-8,*;q=0.5',
'Accept-Encoding': 'gzip,deflate,sdch',
'Accept-Language': 'en-US,en;q=0.8',
... |
from requests import get,put, delete
from tabulate import tabulate
import pprint
import argparse
import json
pp = pprint.PrettyPrinter(indent=4)
class RestApiClient():
def __init__(self):
self.cmds = {}
def execute_command(self, args):
if getattr(self, args["command"]) is not None:
... |
import math
from itertools import permutations, repeat
import numpy as np
# 500 m radius is covered by mobike request
radius = 500
# number of km per degree = ~111km
# (between 110.567km at the equator and 111.699km at the poles)
# 1km in degree = 1 / 111.32km = 0.0089
# 1m in degree = 0.0089 / 1000 = 0.0000089
coef... |
#!/usr/bin python
# -*- coding:utf-8 -*-
"""
Logging functionality: color logger, log-friendly timestamp...
"""
import logging
from typing import Optional
import socket
import sys
import datetime
#
import pytz
#
import coloredlogs
# ##############################################################################
# ... |
import os
import discord
import asyncio
import configparser
from bot.commands import Command
client = discord.Client()
@client.event
@asyncio.coroutine
def on_ready():
print('Logged in as: {0} - {1}'.format(client.user.name, client.user.id))
print('-'*20)
@client.event
@asyncio.coroutine
def on_message(mes... |
from typing import Iterable
from torch import Tensor
from torch.nn import Sequential, ModuleList
from ..neko_module import NekoModule
from ..layer import Concatenate
from ..util import ModuleFactory
class DenseBlock(NekoModule):
"""
The DenseBlock can be used to build a block with repeatable submodules with... |
import os
import sys
from girder.api import access
from girder.api.describe import autoDescribeRoute, Description
from girder.api.rest import getCurrentUser, getBodyJson, RestException
from girder.constants import TokenScope
from cumulus.taskflow import load_class
from cumulus_plugin.models.cluster import Cluster as ... |
"""
Module detecting usage of `tx.origin` in a conditional node
"""
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
class TxOrigin(AbstractDetector):
"""
Detect usage of tx.origin in a conditional node
"""
ARGUMENT = "tx-origin"
HELP = "Dangerous usage of... |
# -*- coding: utf-8 -*-
import json
import pytest
from sanic import Sanic, Blueprint
from sanic.testing import SanicTestClient
from sanic.websocket import WebSocketProtocol
from spf import SanicPluginsFramework
import sanic_restplus
from sanic_restplus import restplus
# class TestClient(SanicTestClient):
# def ge... |
import re
import urllib.request
import json
import logging
from telegram import Update, ForceReply
from telegram.ext import Updater, CommandHandler, ConversationHandler, MessageHandler, CallbackContext, Filters
from bs4 import BeautifulSoup
default_path_bike_json_file = 'bike.json'
default_path_config_json_file = 'co... |
from typing import Any, Dict, List, Optional, Sized, Tuple
from boa3.model.builtin.method.builtinmethod import IBuiltinMethod
from boa3.model.expression import IExpression
from boa3.model.type.primitive.primitivetype import PrimitiveType
from boa3.model.type.type import IType, Type
from boa3.model.variable import Vari... |
# Generated by Django 3.0.6 on 2020-05-13 17:55
import uuid
import django.contrib.gis.db.models.fields
import django.contrib.postgres.fields.ranges
import django.db.models.deletion
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
initial = True
dependenci... |
"""
Random walk algorithm implementation for a mobile robot
equipped with 4 ranger sensors (front, back, left and right)
for obstacles detection
author: Ruslan Agishev (agishev_ruslan@mail.ru)
reference: https://ieeexplore.ieee.org/abstract/document/6850799/s
"""
import matplotlib.pyplot as plt
from matplotlib.patche... |
# -*- coding: utf-8 -*-
#015_cleaner.py
#WIP
import sys
sys.path.insert(0 , 'D:/Projets/shade_django/apis/')
from voca import AddLog , StringFormatter , OutFileCreate , StrValidator , OdditiesFinder
##################################
# Init des paths et noms de fichiers
AddLog('title' , 'Début du nettoyage du... |
# STUMPY
# Copyright 2019 TD Ameritrade. Released under the terms of the 3-Clause BSD license.
# STUMPY is a trademark of TD Ameritrade IP Company, Inc. All rights reserved.
from . import core, gpu_stump
from .ostinato import _ostinato, _get_central_motif
from .gpu_aamp_ostinato import gpu_aamp_ostinato
@core.non_no... |
# -*- coding: utf-8 -*-
from setuptools import find_packages
from setuptools import setup
version = '1.0.0'
description = 'ROOCS data operations demo library.'
long_description = 'Prototype for 34e libraries and interfaces'
requirements = [line.strip() for line in open('requirements.txt')]
dev_requirements = [line.... |
import torch
from torch import nn
from torch._C import dtype
from models.nets import MLP
from models import Transform
from torch.nn import functional as F
import numpy as np
from utils import sum_except_batch
import math
# Adapted from https://github.com/bayesiains/nsf/blob/master/nde/transforms/splines/rational_quadra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.