content stringlengths 5 1.05M |
|---|
from setuptools import Extension, setup
try:
import numpy.distutils.misc_util
except ModuleNotFoundError:
from setuptools import dist
dist.Distribution().fetch_build_eggs(["numpy"])
import numpy.distutils.misc_util
with open("README.md", "r") as f:
long_description = f.read()
setup(
name="... |
#!/usr/bin/python3
from lib.ListLibraries import ListNode, ListNodeInitialize
class Solution:
def hasCycle(self, head: ListNode) -> bool:
"""
:type head: ListNode
:rtype: bool
"""
arr = []
if head is None or head.next is None:
return False
whil... |
# Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""
Main documentation builder script.
Use the following command to get usage message::
$ python -m docbuilder --help
"""
import os
import shutil
from argparse import ArgumentParser
from sphinx.appl... |
from __future__ import annotations
import asyncio
import random
import ssl
from dataclasses import dataclass
from functools import partial
from typing import (
Annotated,
Any,
Awaitable,
Callable,
Iterator,
Optional,
TypeVar,
Union,
)
from . import exceptions, schema
from .client impor... |
from setuptools import setup, find_packages
from ddpw import __version__, __build__
with open("README.md", "r", encoding="utf-8") as f:
long_description = f.read()
setup(
name="ddpw",
version=__version__,
build=__build__,
author="Sujal T.V.",
url="https://ddpw.projects.sujal.tv",
description=r"""A uti... |
from client import *
client = create_pubsub_client()
next_page_token = None
while True:
resp = client.projects().topics().list(
project='projects/single-object-747',
pageToken=next_page_token).execute()
# Process each topic
for topic in resp['topics']:
print topic['name']
next... |
'''
Created by auto_sdk on 2020.11.23
'''
from dingtalk.api.base import RestApi
class OapiEduFeedSyncRequest(RestApi):
def __init__(self,url=None):
RestApi.__init__(self,url)
self.album_id = None
self.dept_id = None
self.fee_type = None
self.feed_medias = None
self.future = None
self.media_uid = None
s... |
#!/usr/bin/env python
#
# Client for live queries to JPL database lookup
#
import sys
import urllib
import re
import json
import time
from bs4 import BeautifulSoup
from datetime import datetime
class Asteroid:
def __init__(self, name):
self.name = name
def load(self):
r = JPL_Query(self.name)
self.d... |
# Generated by Django 3.0.4 on 2020-05-20 11:13
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='user',
fields=[
... |
# ==============================================================================
# An implementation of DR
# that simply resolves the residual forces at the nodes
# by moving along a damped residual force/movement vector.
# ==============================================================================
# class ForceNe... |
#!/usr/bin/env python
import serial, glob, time, requests, string
## TODO if already connected, it goes infinite loop in conn_serial
# eject USB or send something client reset
class slave_connection (object) :
def __init__(self) :
# set connection_to_bluetooth_module
self.conn_state = 0
# 0 set af... |
def compile_results(results, job, delete_mode=False):
files_scanned = 0
files_unchanged = 0
files_updated = 0
files_created = 0
files_skipped = []
files_not_found = []
for el in results:
files_scanned += el[0]
files_unchanged += el[1]
files_updated += el[2]
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, with_statement
from revolver import package
_TOOLS = ["atop", "htop", "iftop", "iotop", "itop", "latencytop", "powertop"]
def install():
package.install(_TOOLS)
def ensure():
package.ensure(_TOOLS)
|
import os
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
from unidecode import unidecode
entity_file = open("/Users/stephenross/Downloads/finalResult.txt", 'r')
ttlFile = open("/Users/stephenross/Downloads/fdata.ttl",'w')
with open("/Users/stephenross/Downloads/finalResult.txt", 'r') as entity_file:
file_... |
import random
import argparse
def split_file(file, out1, out2, percentage=0.75, shuffle=True, seed=123):
"""Splits a file in 2 given the `percentage` to go in the large file."""
random.seed(seed)
with open(file, 'r', encoding="utf-8") as fin, \
open(out1, 'w') as foutBig, \
open(ou... |
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
current_version = str('1.6.0')
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f... |
# -*- coding: utf-8 -*-
# @Time : 2019/12/6 11:19
# @Author : zhoujun
from torch import nn
class ConvBnRelu(nn.Module):
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
dilation... |
from odoo import models, fields, api, _
class DeliveryCarrier(models.Model):
_inherit = "delivery.carrier"
is_global_delivery_method = fields.Boolean(string="Is Global?", help="is available for all sellers?", default=False, copy=False)
marketplace_seller_id = fields.Many2one("res.partner", string="Seller... |
# Copyright 2014 Mirantis, Inc.
# 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... |
# Copyright 2018 Simon Biggs
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 11 20:02:37 2017
@author: tzave
"""
import numpy as np
def swap(r, p, E, cols=None):
if cols is None:
b = np.copy(E[r, :])
E[r, :] = E[p, :]
E[p, :] = np.copy(b)
else:
b = np.copy(E[:, r])
E[:, r] = E[:, p]
E[:, p... |
# wifi_commands.py/Open GoPro, Version 2.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro).
# This copyright was auto-generated on Tue Sep 7 21:35:52 UTC 2021
"""WiFi API for Open GoPro version 1.0"""
from __future__ import annotations
import logging
from pathlib import Path
from typing import An... |
import numpy as np
import matplotlib.pyplot as plt
from travelplanner.read_passengers import Read_route
class Route:
def __init__(self, route, speed=10):
self.speed = speed
self.route = Read_route(route)
self.xcoord = []
self.ycoord = []
self.bstop = []
for points ... |
from .flappy_bird.wrapped_flappy_bird import GameState
from .AbstractEnv import AbsImageEnv
import numpy as np
import cv2
class FlappyBirdEnv(AbsImageEnv):
frame_size = (80, 80)
def _obs_dim(self):
# 目前环境对象向策略网络返回的状态矩阵为连续4帧80X80的二值型图片
obs_dim = (self.frame_size[0], self.frame_siz... |
import math
class Accion:
DERECHA = 1
IZQUIERDA = 0
#NADA = 2
maxValor = 1
class Posicion:
BORDE_IZQUIERDO = 1
BORDE_DERECHO = 2
CENTRO = 3
class Estado:
angulo = 0
velocidadAngular = 0
posicion = Posicion.CENTRO
def __init__(self):
self.angulo = math.pi
... |
import tensorflow as tf
import tensorflow.python.keras.backend as K
from loguru import logger as log
from prepare_dataset import create_pairs
IMG_SHAPE = (64, 64, 3)
def tf_siamese_nn(shape, embedding=64, fine_tune=False):
inputs = tf.keras.layers.Input(shape)
base_model = tf.keras.applications.vgg19.VGG19(... |
from setuptools import setup
setup(
name='obs-tower2',
version='0.0.1',
description='Obstacle tower private data',
url='https://github.com/unixpickle/obs-tower2',
author='Alex Nichol',
author_email='unixpickle@gmail.com',
license='BSD',
classifiers=[
'Development Status :: 4 - B... |
import os
import pika
import sys
from time import sleep
DEBUG = int(os.environ.get('DEBUG', 0))
QUEUE = os.environ.get('QUEUE', 'default')
if DEBUG == 1:
print("env:", DEBUG, QUEUE)
# MESSAGE BROKER
BROKER_HOST = os.environ.get('BROKER', 'non-existent-broker')
BROKER_USER = os.environ.get('BROKER_USER', 'guest')
B... |
import numpy as np
from skorch import NeuralNet
import torch
from torch import nn
from spacecutter.callbacks import AscensionCallback
from spacecutter.losses import CumulativeLinkLoss
from spacecutter.models import OrdinalLogisticModel
SEED = 666
def test_loss_lowers_on_each_epoch():
torch.manual_seed(SEED)
... |
for i in range(int(input())):
a, b, c, d = map(int, input().split())
print(f'{b} {c} {c}')
|
"""
Script to evaluate the activation functions for the selected network + grid.
"""
import sys
import os
sys.path.insert(0, os.getcwd())
import numpy as np
import sys
import os
import subprocess
import itertools
import imageio
import json
import torch
import io
import shutil
import matplotlib.pyp... |
#
# Copyright (c) Contributors to the Open 3D Engine Project.
# For complete copyright and license terms please see the LICENSE at the root of this distribution.
#
# SPDX-License-Identifier: Apache-2.0 OR MIT
#
#
import boto3
import logging
import json
import os
import requests
from botocore.exceptions import ClientE... |
import subprocess
import click
from .commands.system import check_beam
def running():
click.echo("")
click.echo("Beam Pilot is running")
click.echo("")
return
def stopped():
click.echo("")
click.echo("Beam Pilot is stopped")
click.echo("")
return
def error():
click.echo("")
... |
import argparse
from smtplib import SMTP_PORT
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="SMTP server for testing mail functionality"
)
parser.add_argument(
"--output-filename",
"-o",
nargs="?",
default="-",
help="o... |
import argparse
import warnings
import pandas as pd
from schools3.config import main_config as config
from schools3.ml.experiments import *
warnings.filterwarnings('ignore')
def add_args(parser):
parser.add_argument('--name', default='ignore', help='name of current experiment')
parser.add_argument('--exp', de... |
import pytest
from basin3d.core.models import DataSource, MeasurementTimeseriesTVPObservation
from basin3d.plugins.usgs import USGSMeasurementTimeseriesTVPObservationAccess
@pytest.fixture
def datasource(name='Alpha', location='https://asource.foo/', id_prefix='A'):
"""
Create a DataSource object
"""
... |
import io
from conftest import check
import elsie
@check("imagefrag", expect_count=6, cairo_threshold=15)
def test_line_highlight_fragments(test_env):
slide = test_env.slide
img = test_env.assets_path("testimage.svg")
slide.image(img)
b = slide.box(x="[90%]", y="[30%]", width="30%", height="30%", ... |
from import_export import resources
import models as operacion
class ServicioInform(resources.ModelResource):
class Meta:
model = operacion.Servicio
fields = ('nombre','costo','comision')
export_order = ('nombre','costo','comision')
# end class
# end class
|
#
# PySNMP MIB module MPLS-TE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MPLS-TE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:19:49 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, 0... |
from coderz import Robot
def read_sensor_values():
conf = {
"name": "Me",
"parts": [
{"name": "csl", "type": "color"},
{"name": "csr", "type": "color"},
{"name": "us", "type": "ultrasonic"},
{"name": "cs", "type": "controlSystem"},
{"name... |
# Generated by Django 2.2.13 on 2021-04-07 21:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('desire_api', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Ecoddomains',
fields=[
... |
import time
import socket
s = socket.socket()
s.connect(('', 25000))
# hide the cursor, clear screen, move cursor to 1,1
s.send(b'\x1b[?25l' b'\x1b[2J' b'\x1b[;H')
# send hello
s.send(b'Hello, world!\n')
# send a progress bar
for i in range(1, 101):
msg = "\r{0:>3}% [\x1b[32m{1:<50}\x1b[0m]".format(i, int(i/2)*"#... |
import re, json, os
from collections import defaultdict
def json_data(filename):
item_aspect_dict = defaultdict(list)
with open(filename, "r") as f:
aspect_list = json.loads(f.read()) # Returns a list of dictionaries containing aspects and items
for aspect_dict in aspect_list:
... |
"""
ALPModule
"""
import torch
import math
from torch import nn
from torch.nn import functional as F
import numpy as np
from pdb import set_trace
import matplotlib.pyplot as plt
# for unit test from spatial_similarity_module import NONLocalBlock2D, LayerNorm
class MultiProtoAsConv(nn.Module):
def __init__(self, pr... |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... |
#!/usr/bin/env python
#module for importing/exporting pdb files
#ryan g. coleman ryangc@mail.med.upenn.edu
import string
import math
import sys
import geometry # distance function
import unionfind2
import collections
#declare this here
radiiDefault = {
'C': 1.9, 'O': 1.6, 'N': 1.65, 'P': 1.9, 'S': 1.9, 'H': 0.,
... |
import unittest
import os
import lob
class TestBulkUSVerificationFunctions(unittest.TestCase):
def setUp(self):
lob.api_key = os.environ.get('LOB_API_KEY')
def test_bulk_us_verification(self):
response = lob.BulkUSVerification.create(
addresses=[
{
... |
from pathlib import Path
def read(filename='in'):
file_path = Path(__file__).parent / filename
with file_path.open('r') as file:
return read_lines(file.readlines())
def read_lines(lines):
cells = {}
for y in range(len(lines)):
line = lines[y].strip()
for x in range(len(line))... |
'''
We define a harmonious array as an array where the
difference between its maximum value and its minimum
value is exactly 1.
Given an integer array nums, return the length of its
longest harmonious subsequence among all its possible
subsequences.
A subsequence of array is a sequence... |
from .visualizer import PredictionVisualizer, DataVisualizer
from .device import CV2Screen, CV2VideoWriter, output_device_factory
|
import utils
import socket
# Server Configuration
port = 60009
host = socket.gethostname()
listen_request = 5
transmission_size = 65536
bank_server = utils.server(host=host, port=port, transmission_size=transmission_size,
listen_request=listen_request)
bank_server.run()
|
# --------------------------------------------------------------------- #
# This file is a part of ShapeMapper, and is licensed under the terms #
# of the MIT license. Copyright 2018 Steven Busan. #
# --------------------------------------------------------------------- #
import subprocess as sp... |
from datetime import date
from functools import partial
from typing import Callable
import numpy as np
import wandb
from deeplookup import datasets, metrics, nn
ROOT_DIR = "csv-datasets"
B_MODELS = [
(nn.create_cnn, "model/b-dga-zhang.h5"),
(nn.create_woodbridge_rnn, "model/b-dga-woodbridge.h5"),
(nn.c... |
"""Inspect APIs
"""
import operator
import unittest
import requests
from .config import *
from .techstacks_dtos import *
@dataclass_json(undefined=Undefined.EXCLUDE)
@dataclass
class GithubRepo:
name: str
description: Optional[str] = None
homepage: Optional[str] = None
lang: Optional[str] = field(m... |
#!/usr/bin/python
'''
From:
LOCATION,DNS,WIN_DOMAIN,SCMD,PREFIX,NETWORK,POC
BEL AB FLORENNES,2wtac.mil.be,n666.mil.be,FLO,2WTACNS,10.90.61.0/25,32110001
BEL AB KLEINE BROGEL,17sqn.mil.be,n17.mil.be,KBR,KBNS,10.90.62.0/24,32110002
BEL AB KOKSIJDE,sar.mil.be,n69.mil.be,BKO,SARNS,19.90.63.0/24,32110003
BEL AB FLORENNES ... |
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
# Compatibility imports
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import time
import tensorflow as tf
import scipy.io.wavfile as wav
import numpy as np
from six.moves import xrange as range
try:
... |
#! /usr/bin/env python
# encoding: utf-8
from dxfwrite import DXFEngine as dxf
def plot(drawing, x, y, xdiv, ydiv, tan, ofs):
x = float(x)
y = float(y)
tan = float(tan)
def pos(x, y):
return([float(ofs[0])+x, float(ofs[1])+y])
# draw vertical boundaries
drawing.add(dxf.line(pos(0, 0), pos(0, y), color = 7)... |
n1 = float(input('Digite um número: '))
n2 = float(input('Digite outro número: '))
if n1 > n2:
print('O \033[32mprimeiro\033[m valor é maior.')
elif n2 > n1:
print('O \033[32msegundo\033[m valor é maior.')
else:
print('Os dois valores são \033[32miguais\033[m.')
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def caschool(path):
"""The California Test Score Data Set
a cross-sect... |
"""
tknorris shared module
Copyright (C) 2016 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
... |
import os
import pytest
import tensorflow as tf
from speech_recognition.data import (
get_dataset,
get_tfrecord_dataset,
make_log_mel_spectrogram,
make_mfcc,
make_spectrogram,
spec_augment,
)
from .const import MP3_DATASET_PATH, PCM_DATASET_PATH, TFRECORD_DATASET_PATH, WAV_DATASET_PATH
clas... |
from __future__ import unicode_literals
import textwrap
import pytest
from plette import Lockfile, Pipfile
from plette.models import Package, SourceCollection
HASH = "9aaf3dbaf8c4df3accd4606eb2275d3b91c9db41be4fd5a97ecc95d79a12cfe6"
def test_lockfile_load(tmpdir):
fi = tmpdir.join("in.json")
fi.write(tex... |
import pickle, math
import numpy as np
import gurobipy as gp
from gurobipy import *
import time, sys
from numpy import *
from .lp_gurobi import *
import logging
def select_by_sorted_num(raw_datas, pref, budget):
maxTries = 1000
curTries = 0
interestChanged = True
sum_of_cols = None
listOfInterest ... |
from .test_UVIRepo import *
from .test_UVIGithub import *
from .test_UVIIssue import *
|
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 20 16:04:52 2020
@author: rjovelin
"""
|
import src.api_paths as apis
import src.constants as constants
from http import HTTPStatus
from src.validators import Validators as expect
import pytest_check as check
def test_post_posts(client):
body = {
"title": "Test title",
"body": "Test body",
"userId": 55
}
response = client.... |
#-*- coding:utf-8 -*-
import requests
import json
############################################################
#SlackでWebhookAPIを作って、表示されたURLを記入して下さい
API_URL = 'https://hooks.slack.com/services/ランダム文字列'
############################################################
def post(postText):
print(API_URL)
print(p... |
from setuptools import setup
def get_data_files():
"""Get the data files for the package.
"""
data_files = [
('etc/jupyter/jupyter_server_config.d', ['etc/jupyter/jupyter_server_config.d/jupytexpr.json']),
('etc/jupyter/jupyter_notebook_config.d', ['etc/jupyter/jupyter_notebook_config.d/jup... |
import os
# PATHS
if 'AVD_DATASET' in os.environ:
AVD_DATASET = os.environ['AVD_DATASET']
else:
AVD_DATASET = os.path.join(os.path.dirname(__file__), 'AVD_Dataset')
IMG_FOLDER = 'jpg_rgb'
DEPTH_FOLDER = 'high_res_depth'
# FILENAMES
SCENE_ANNOTATIONS_FNAME = 'annotations.json'
IMG_STRUCT_FNAME = 'image_structs... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013-2014 Telefónica Investigación y Desarrollo S.A.U.
#
# 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... |
# https://www.runoob.com/python/python-object.html
# !/usr/bin/python
# -*- coding: UTF-8 -*-
class Parent: # 定义父类
parentAttr = 100
def __init__(self):
print("调用父类构造函数")
def parentMethod(self):
print('调用父类方法')
def setAttr(self, attr):
Parent.parentAttr = attr
def getAt... |
"""
Parsed Config File Produces Expected Behaviors - fixed parameters
"""
import inspect
import os
import deeplenstronomy.deeplenstronomy as dl
doc = """
\tRunning tests from test_expected_behaviors_fixed.py
\tThe tests included in this module demonstrate that the values of fixed parameters
\tin the main configu... |
def main(request, response):
response.headers.set(b"Cache-Control", b"no-store")
response.headers.set(b"Access-Control-Allow-Origin", request.headers.get(b"origin"))
response.headers.set(b"Access-Control-Allow-Credentials", b"true")
uid = request.GET.first(b"uid", None)
if request.method == u"OPTIO... |
# coding=utf-8
# Copyright 2021 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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/lice... |
#adjust brightness of an image
#when the user enters 'i' key then increase the brightness and when 'd' decrease the brightness
#brightness can be adjusted just by increasing / decreasing the intensity values of RGB
import cv2
#open image file
img = cv2.imread( 'lenna.jpg',-1)
#get image dimesions
prop = img.shape
... |
# -*- coding: utf-8 -*-
def to_text(path, language='fra'):
"""Wraps Tesseract 4 OCR with custom language model.
Parameters
----------
path : str
path of electronic invoice in JPG or PNG format
Returns
-------
extracted_str : str
returns extracted text from image in JPG or P... |
# https://www.interviewbit.com/problems/itertools-combinatoric-iterators/
from itertools import permutations as p
def main():
# YOUR CODE GOES HERE
# Please take input and print output to standard input/output (stdin/stdout)
# E.g. 'input()/raw_input()' for input & 'print' for output
s,k = input()... |
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy.sparse import issparse, spdiags, coo_matrix, csc_matrix
from past.utils import old_div
from scipy.ndimage.measurements import center_of_mass
import tifffile as tiff
import os, sys
import matplotlib.gridspec as gridspec
import scipy.i... |
import os
import subprocess
def main(complex_folder, rosetta_path):
repack_options = os.path.join(complex_folder, "repack2.options")
#/home/claudio/tesis/rosetta_src_2021.16.61629_bundle/main/source/bin/rosetta_scripts.linuxgccrelease
subprocess.run([f"{rosetta_path}/source/bin/rosetta_scripts.linuxgccrel... |
# -*- coding: utf-8 -*-
#Версия Python 2.7
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
@pytest.fixture
def start(request):
driver = webdriver.Chrome()
request.addfinalizer(driver.quit)
return driver
def test(start... |
"""entity drop.
Revision ID: 4f5eb9113692
Revises: afd5bb9f5004
Create Date: 2016-04-14 14:19:37.177074
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '4f5eb9113692'
down_revision = 'afd5bb9f5004'
def upgrade():
... |
#!/usr/bin/python
'''
USAGE: flash device recovery.fstab device.img [fstab_version]
device: [boot|recovery]
device.img: [boot.img|recovery.img]
fstab_version: [1|2]
1 for android 4.0 - 4.2 (DEFAULT)
2 for android 4.3 - *
Created on Jul 31, 2014
@author: tangliuxiang
'''
imp... |
from crypto_ml.manager import CryptoManager
from crypto_ml.worker import app as celery_app
__all__ = [ 'CryptoManager', 'celery_app' ]
|
import unittest
import utils
class UtilTest(unittest.TestCase):
def test_valida_maiuscula(self):
resultado = utils.mudar_para_maiuscula("julio")
self.assertEqual(resultado, "JULIO",
"Funcao deveria retornar JULIO em caps")
def test_valida_minuscula(self):
res... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013-2014 Telefónica Investigación y Desarrollo S.A.U.
#
# 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... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from rest_framework.parsers import BaseParser, DataAndFiles
class TusUploadStreamParser(BaseParser):
media_type = 'application/offset+octet-stream'
def parse(self, stream, media_type=None, parser_context=None):
return DataAndFiles({'chu... |
from django.utils.decorators import method_decorator
from inbox.api.serializers import (
NotificationSerializer,
NotificationSerializerForUpdate,
)
from ratelimit.decorators import ratelimit
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.permissions ... |
import numpy as np
from keras.models import *
from keras.layers import *
from keras.optimizers import *
from keras.callbacks import *
from Approximator import Approximator
from util import DotDic
class OXONeuralNetwork(Approximator):
def __init__(self, task):
self.args = DotDic({
'numEpochs': 30,
'batchSize... |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... |
from arclet.alconna import Alconna, compile, Arpamar
from arclet.letoderea.utils import ArgumentPackage
from arclet.letoderea.entities.auxiliary import BaseAuxiliary
from ..main.message.chain import MessageChain
class AlconnaAuxiliary(BaseAuxiliary):
alconna: Alconna
def __init__(self, alconna: Alconna):
... |
import operator
class Interpreter:
ops = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv,
'^': operator.pow
}
def __init__(self, ctx=None):
self.ctx = ctx if ctx else {}
def evaluate(self, node):
method_name = ... |
from __future__ import print_function
import json
import os
import sys
import urllib
import django
from bs4 import BeautifulSoup
from django.db.models import Q
if '__file__' in locals():
sys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir))
django.setup()
from article.models import Article
fr... |
# -*- coding: utf-8 -*-
'''
:codeauthor: Erik Johnson <erik@saltstack.com>
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import errno
import os
import shutil
import tempfile
import textwrap
import tornado.ioloop
import logging
import stat
try:
imp... |
N = int(input())
ns = []
for i in range(0,N):
ns.append(input())
D = int(input())
ds = []
for i in range(0,D):
d = input()
ds.append(sum(1 for x in ns if x == d))
for a in ds:
print(str(a)) |
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
"""Test target reading from file."""
import json
import os
from pathlib import Path
import pytest
from click.testing import CliRunner
from samples.sample_target_csv.csv_target import SampleTargetCSV
SAMPLE_FILENAME = Path(__file__).parent / Path("./resources/messages.jsonl")
EXPECTED_OUTPUT = """"id" "name"
1 "Chri... |
#!/usr/bin/env python3
import os
import sys
import shlex
import argparse
import subprocess
from functools import partial
def main():
head_description = (
"""Bambino wrapper (with hardcoded parameters) that works with RNAIndel."""
)
parser = argparse.ArgumentParser(
formatter_class=argpars... |
import unittest
import numpy as np
from apal_cxx import PyQuadraticKernel
from apal_cxx import PyKernelRegressor
from apal_cxx import PyGaussianKernel
from apal.phasefield_util import fit_kernel
class TestRegressionKernels(unittest.TestCase):
def test_quadtratic_kernel(self):
width = 2.0
kernel = ... |
import json
import sys
class JsonFileLoader:
@staticmethod
def load_file(path: str) -> dict:
try:
with open(path) as json_file:
return json.load(json_file)
except(FileNotFoundError, json.JSONDecodeError):
sys.exit('Can not load json file')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.