content stringlengths 5 1.05M |
|---|
import sys
from django.apps import AppConfig
preload_models = {}
genre_rmap = {}
def load_model(model, task):
import numpy as np
import torch
import tensorflow as tf
import torch.nn.functional as F
import os
sys.path.append("..")
sys.path.extend([os.path.join(root, name) for root, dirs, _ ... |
""" Defines an example to create a dataset of an environment """
import argparse
import os
import random
from collections import namedtuple
from pdb import set_trace
from PIL import Image
from shapes3d import Shapes3D
ENV_DIM = 20
MAX_NUM_OBJS = 15
MIN_NUM_OBJS = 7
MIN_OBJ_DIM = 0.5
MAX_OBJ_DIM = 1.5
FOV = 45
PLANE_C... |
from django.conf import settings
from django.conf.urls.defaults import *
from satchmo.configuration import config_value
from satchmo.product.urls import urlpatterns as productpatterns
from satchmo.shop import get_satchmo_setting
from satchmo.utils import app_enabled
urlpatterns = get_satchmo_setting('SHOP_URLS')
urlp... |
#!/usr/bin/env python
"""
:Author: Ji Research Group/Stanford Genome Technology Center
:Contact: sgrimes@stanford.edu
:Creation date: 03/24/2021
:Description:
This script extracts soft clipped bases at beginning (FWD strand) or end (REV strand)
of read. These sequences will subsequently be searched for expected sin... |
import logging
import pytest
from pytest_docker_py.config import Config
from pytest_docker_py.docker_py_wrapper import DockerPyWrapper
logging.basicConfig(
format='%(asctime)s.%(msecs)03d %(levelname)8s --- [%(process)5d] %(filename)25s:%(funcName)30s, %(lineno)3s: %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',... |
# -*- coding: utf-8
from __future__ import absolute_import, unicode_literals
DEBUG = True
USE_TZ = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "-#5o&sf4iu8&-@na$ad*(t)0gl6_gnw-7_=mk5!zcck)p0w&30"
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
... |
#!/usr/bin/env python
import math
import rospy
from sensor_msgs.msg import Joy
from pan_tilt_msg.msg import PanTiltCmd
delta_value = 2
pan_tilt_yaw = 0.0
pan_tilt_pitch = 0.0
publisher = 0
def joy_callback(data):
global publisher
global pan_tilt_yaw, pan_tilt_pitch
# button Y
if data.buttons[0]==1... |
import unittest
from katas.kyu_8.hex_to_decimal import hex_to_dec
class HexToDecimalTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(hex_to_dec("1"), 1)
def test_equal_2(self):
self.assertEqual(hex_to_dec("a"), 10)
def test_equal_3(self):
self.assertEqual(he... |
# Copyright 2021 Hakan Kjellerstrand hakank@gmail.com
#
# 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 ... |
import random
from datetime import date, datetime, timedelta
from decimal import Decimal
from enum import Enum, auto
from typing import TypeVar, Union
from faker import Faker
T = TypeVar("T", float, int, Decimal, bytes, bool, str, date, datetime)
S = TypeVar("S", str, date, datetime)
U = TypeVar("U", int, float, Deci... |
import cv2
import json
import sys
import numpy as np
from os import path
# CNTK imports
from cntk import load_model
from cntk import placeholder
from cntk.logging.graph import find_by_name, get_node_outputs
from cntk.ops import combine
from cntk.ops.sequence import input_variable
from cntk.ops.functions im... |
import json, logging, pytest, time, os
from cryptoadvance.specter.specter import Specter
from cryptoadvance.specter.managers.wallet_manager import WalletManager
from cryptoadvance.specter.wallet import Wallet
from conftest import instantiate_bitcoind_controller
logger = logging.getLogger(__name__)
def test_check_utx... |
#!/usr/bin/env python
# -*- coding: utf-8 -*
# 用友致远A6协同系统账号密码泄露
import re
def assign(service, arg):
if service == 'yongyou_zhiyuan_a6':
return True, arg
def audit(arg):
reg = re.compile(r'[a-fA-F0-9]{32,32}')
payload = "yyoa/ext/https/getSessionList.jsp?cmd=getAll"
code,_,r... |
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.db.models import QuerySet
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from rest_framework import status
from cuisines.models import Cuisine
from cuisines.serializers ... |
from django.shortcuts import render, HttpResponse, redirect
from url.models import shorturl
def urlshort(request, query=None):
if not query or query is None:
return render(request, 'url/home.html')
else:
try:
check = shorturl.objects.get(short_query=query)
check.visits =... |
"""
The Forum Post Code
"""
import requests
from scratchlink import Exceptions
_website = "scratch.mit.edu"
_api = f"api.{_website}"
class Forum:
def __init__(self, id):
self.headers = {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like ... |
from utils import read_file
from intcode import Intcode, Task
print("#--- part1 ---#")
program = list(map(int, read_file('09.txt')[0].split(',')))
vm = Intcode()
vm.run(Task('part1', program, [1], ramsize=4096))
print(vm.tasks[0].outputs[0])
print("#--- part2 ---#")
program = list(map(int, read_file('09.txt')[0].... |
from .component import *
from .context import *
from .event import *
from .runner import *
from .utils import *
|
# -*- coding: utf-8 -*-
# Copyright (c) 2015, New Indictrans Technologies pvt.ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
from frappe.utils import nowdate
from frappe.utils.user import UserPermissions
from frappe import *
import frappe
from frappe imp... |
#!/usr/bin/env python
import os
import sys
import cv2
import numpy as np
import tensorflow as tf
import tensorflow_addons as tfa
from ravens.models import ResNet43_8s
from ravens import utils
class Attention:
"""Daniel: attention model implemented as an hourglass FCN.
Used for the picking network, and for ... |
# -*- coding: utf-8 -*-
from . import account_move
from . import payment_acquirer
from . import payment_icon
from . import payment_transaction
|
import startup
import os
import numpy as np
import imageio
import scipy.io
#import tensorflow as tf
#import tensorflow.contrib.slim as slim
import torch
from torch.utils.tensorboard import SummaryWriter
import pdb
from util.common import parse_lines
from util.app_config import config as app_config
from util.system ... |
import os
import numpy as np
import h5py
import nibabel as nb
from collections import defaultdict as dd
from pathlib import Path
import matplotlib.image as mpimg
from scipy.stats import zscore
opj = os.path.join
from prfpy.timecourse import filter_predictions
from prfpy.stimulus import PRFStimulus2D
def roi_mask(ro... |
from rest_framework.routers import DefaultRouter
from posts_areas.api_v1.views import PostAreaViewSet
# Create a router and register our viewsets with it.
# app_name = 'posts_areas'
router = DefaultRouter()
router.register(r'posts_areas', PostAreaViewSet, base_name="posts_areas-posts_areas")
urlpatterns = router.urls... |
import os
import pandas as pd
from pathlib import Path
import datetime
import logging
import boto3
def traverse_path(path, split_idx):
"""
Generates a dictionary of the path to each country.
Input:
path: str. The path to the root directory
split_idx: int. split point to capture country nam... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Train a model to classify ethnicity based on census data
Created on Thu Apr 13 16:31:53 2017
@author: dhingratul
"""
import numpy as np
my_data = np.genfromtxt('census_2000.csv', delimiter=",", dtype=str)
eth = [0, 1, 2, 3, 4, 5]
k = 3
dic = {}
np.delete(my_data, 0, ... |
import math
def gauss(n):
return (((n * n) + n) / 2)
def sumDivisibleBy(x, limit):
return x * gauss(limit // x)
no1 = int(input('First number: '))
no2 = int(input('Second number: '))
limit = int(input('Limit: ')) - 1
result = sumDivisibleBy(no1, limit) + sumDivisibleBy(no2, limit) - sumDivis... |
# -*- coding: utf-8 -*-
import logging
from pathlib import Path
from dotenv import find_dotenv, load_dotenv
import pickle
import tensorflow as tf
from text_generator import Keras_Text_Generator
def main(input_filepath, output_filepath):
""" Runs data processing scripts to turn raw data from (../raw) into
... |
'''
Opacus experiments for all the models
'''
import time
import torch
from torch import nn, optim
import data
from experimental.privacy_utils import autograd_grad_sample
from experimental.privacy_utils.privacy_engine import EfficientPrivacyEngine
from pytorch import get_data, model_dict
import utils
def main(args)... |
# Copyright (C) 2010-2011 Richard Lincoln
#
# 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, publish... |
def quicksort(arr):
if len(arr) < 2:
return arr
else:
pivot = arr[0]
less = [i for i in arr[1:] if i <= pivot]
greater = [i for i in arr[1:] if i > pivot]
return quicksort(less) + [pivot] + quicksort(greater)
test_array = [12,2,4,6,3,18]
print(quicksort(test_array)) |
"""
1. copy dna-CDS to work directory
2. translate dna
3. plot sequence length histogram for dna, untranslated dna, protein
4. run cd-hit on protein
"""
import argparse
import os
import io
import stat
import subprocess
def pipeline():
args = get_args()
qsub_params = [
'-l', 'place=pack:shared... |
"""
[ref.href] leetcode.com/problems/contains-duplicate-ii
"
Given an array of integers and an integer k, find out whether
there are two distinct indices i and j in the array such that
nums[i] = nums[j] and the difference between i and j is at most k.
"
"""
class Solution(object):
def containsNearbyDuplica... |
import os
import numpy as np
import pandas as pd
data = pd.DataFrame()
col_names = ["EmployeeName",
"JobTitle",
"BasePay",
"OvertimePay",
"OtherPay",
"Benefits",
"TotalPay",
"TotalPayBenefits",
"Year",
... |
'''
Models
------
This is currently required for:
$> python manage.py test rpc4django
to run.
see: http://code.djangoproject.com/ticket/7198
''' |
import os
import textwrap
import config
class DoNotUseThisSetting():
def __repr__(self):
raise Exception('DoNotUseThisSetting')
def inject(region, paths, fmt):
assert config.qtl_mode in ['nominal', 'permutation']
chrom = region.split(':')[0]
def register_path(fmt):
path = fmt.format(co... |
import numpy as np
from tests.extras import canosa_values
from diagnostics.z_function import get_roots_to_electrostatic_dispersion
def test_z_solver():
k0 = canosa_values.k0
w_real_actual = canosa_values.w_real
w_imag_actual = canosa_values.w_imag
for kk, wr, wi in zip(k0, w_real_actual, w_imag_actu... |
import socket
import base64
from uuid import uuid4
import cv2
import numpy as np
# pylint: disable=no-member, unused-variable
def encodeImg(img):
return base64.b64encode(cv2.imencode(".png", img)[1])
def decodeImg(img):
return cv2.imdecode(np.frombuffer(base64.b64decode(img), dtype=np.uint8), cv2.IMREAD_ANYC... |
import unittest
import finance
class TestFinanceFunctions(unittest.TestCase):
def test_symbols(self):
self.assertEqual(type(finance.symbols.dax), type(()))
if __name__ == '__main__':
unittest.main()
|
from django.urls import re_path
from django.views.decorators.csrf import csrf_exempt
from .views import ToDo, Bucket
urlpatterns = [
re_path(r'todos$',
csrf_exempt(ToDo.as_view()),
name="Todos"),
re_path(r'todos/(?P<id>\d+)$',
csrf_exempt(ToDo.as_view()),
name="T... |
__version__ = '3.0.0'
def get_version():
return __version__
|
# Telegram Bot
token = 'XXX'
# Telegram Chat Owner
api_id = 123
api_hash = 'YYY'
|
from ncvoter.settings import * # noqa: F403
DATABASES['default'].update({ # noqa: F405
'PORT': 5455,
'NAME': 'ncvoter',
'USER': '',
'PASSWORD': '',
})
NCVOTER_DOWNLOAD_PATH = "/Volumes/Untitled/downloads/ncvoter"
NCVHIS_DOWNLOAD_PATH = "/Volumes/Untitled/downloads/ncvhis"
|
#!/usr/bin/env python
# coding=utf-8
import json
import xlwt
import sys
testfile = 'student.json'
savename = '../cache/student.xls'
sheetname = 'student'
def json_to_excel():
studentList = get_json(testfile)
# workbook = xlwt.Workbook()
workbook = xlwt.Workbook(encoding='utf-8') #实际试了编码参数有无utf8,生成的文件md5... |
import os
import shutil
class NotADirectoryError(Exception):
"""Indicates a file was found when a directory was expected."""
def __init__(self, directory, message=None):
super(NotADirectoryError, self).__init__(
'Expected a directory, found a file instead at ' + directory)
self.dir... |
from oarepo_nusl_rules import rule_registry
from oarepo_nusl_rules.register import RuleRegistry
def test_register_load():
instance1 = RuleRegistry.Instance()
RuleRegistry.Instance().load()
instance2 = RuleRegistry.Instance()
assert len(RuleRegistry.Instance().rules) > 0
assert instance1 is instanc... |
"""API for Somfy bound to Open Peer Power OAuth."""
from __future__ import annotations
from asyncio import run_coroutine_threadsafe
from pymfy.api import somfy_api
from openpeerpower import config_entries, core
from openpeerpower.helpers import config_entry_oauth2_flow
class ConfigEntrySomfyApi(somfy_api.SomfyApi)... |
import json
import time
from enum import Enum
def current_time():
return int(round(time.time() * 1000))
def add_leading_zero(value):
if value >= 10:
return str(value)
return "0" + str(value)
def to_JSON(obj, sort_keys=True):
return json.dumps(obj, default=default_serializer,
... |
import os
from setuptools import setup
version_file_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
'doctor', '_version.py')
with open(version_file_path, 'r') as version_file:
exec(compile(version_file.read(), version_file_path, 'exec'))
setup(
name=__name__,
... |
#
# Copyright 2014 OpenStack Foundation
# 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 unittest2 as unittest
from Acquisition import aq_base
from plone.app.testing import TEST_USER_ID, setRoles
from collective.teamwork.tests.layers import DEFAULT_PROFILE_TESTING
from collective.teamwork.interfaces import IProjectContext, IWorkspaceContext
from fixtures import CreateContentFixtures
class Utili... |
"""
Na relação de associação um objeto pode existir sem o outro,
ma existe a possibilidade de um deles usar uma instância do outro.
"""
class Bombeiro():
def __init__(self, nome):
self.__nome = nome
self.__ferramenta = None
@property
def nome(self):
return (self.__nome + '_getter'... |
from typing import Any, Dict, Union
from tealprint import TealPrint
from tealprint.teallevel import TealLevel
from ...core.entities.color import Color
from ..interface import Interface
from ..moods import Mood
from .api import Api
class HueInterface(Interface):
INVALID_ID = -1
def __init__(self, name: str,... |
# (C) Copyright 2020- ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
#
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernme... |
a = [1,2,3,4,5,6]
def reverse(l:list):
# 首尾不停的交换
left =0
right = len(l)-1
while left<right:
l[left],l[right] = l[right],l[left]
left+=1
right-=1
return l
result = reverse(a)
print(result) |
#encoding: utf-8
from django.shortcuts import render
from django.http import JsonResponse
from .models import Client
from base import constants
from base.decorators import login_required
@login_required
def lists(request):
if request.is_ajax():
result = [client.as_dict(True) for client in Cli... |
import json
import network
import time
import math
import umqtt.simple as simple
import machine
import random
from util import Config, wait_network
sta_if = network.WLAN(network.STA_IF)
conf = Config('ibmiot')
if not conf.data:
random.seed(time.time())
conf.data = {
'orgID': 'quickstart', # <<< org_... |
import re
import time
import random
import datetime
from faker import Faker
# ----------------------------------------------------------------------
# # Do something
# ----------------------------------------------------------------------
def str_list(_str):
_str = _str.strip("['").strip("']")
_list = _str.re... |
"""
Commonmark with header level extension
"""
from CommonMark.blocks import Parser
from CommonMark.render.html import HtmlRenderer
class SteakRenderer(HtmlRenderer):
"""
Custom renderer
"""
def __init__(self, *args, **kwargs):
"""
Set options
"""
self._headerleveloffs... |
from typing import Dict
from classifier.classes.core.Model import Model
from classifier.classes.modules.images.cnn_img.ModelImagesCNN import ModelImagesCNN
from classifier.classes.modules.images.cnn_rnn_img.ModelImagesCNNRNN import ModelImagesCNNRNN
from classifier.classes.modules.images.pre_trained_cnn.ModelPreTraine... |
# Copyright 2021 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, ... |
"""
[2016-03-02] Challenge #256 [Intermediate] Guess my hat color
https://www.reddit.com/r/dailyprogrammer/comments/48l3u9/20160302_challenge_256_intermediate_guess_my_hat/
#Description
You are the game master of the game "Guess my hat color".
The game goes as following:
- You put a group of `n` people in one row, ea... |
import src.modules.cli as cli
import os
import nltk
nltk.download("all",quiet=True)
dirname = os.path.dirname(__file__)
def test_cli_pdf_similarity():
pdf1 = os.path.join(dirname, 'test_paper/rsos.201199.pdf')
pdf2 = os.path.join(dirname, 'test_paper/rsos.201199.pdf')
cli.pdf_similarity(pdf1, pdf2, False)... |
# *****************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. 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... |
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
if not filters: filters = {}
validate_filters(filters)
columns = get_columns()
stock = get_to... |
# Generated by Django 3.0.5 on 2020-04-26 13:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('covidus_main', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='profile',
name='temperature',
... |
"""
Copyright (c) 2020-2021 Deutsches Elektronen-Synchrotron DESY.
See LICENSE.txt for license details.
"""
import datetime
import getpass
import os
import socket
from typing import Iterator, List, Optional
from systemrdl.rdltypes import AccessType
from hectare._hectare_types import AddressMap, Field, Register
de... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
THOR detects differential peaks in multiple ChIP-seq profiles associated
with two distinct biological conditions.
Copyright (C) 2014-2016 Manuel Allhoff (allhoff@aices.rwth-aachen.de)
This program is free software: you can redistribute it and/or modify
it under the te... |
from __future__ import annotations
from typing import Optional
from jsonclasses import jsonclass, types
@jsonclass
class SimpleWordbook:
name: Optional[str]
words: list[str] = types.nonnull.listof(str)
|
from datetime import date
from typing import Optional
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
from road_data_scraper import __version__
from road_data_scraper.main import run
app = FastAPI(
title="Road Data Scraper API",
description="Scrapes and Cleans WebTRIS Traffic Flow ... |
import sys
from karp5 import instance_info
from .config import Config
from .configmanager import ConfigManager
# print(f"{instance_info.get_instance_path()}")
mgr = ConfigManager(instance_info.get_instance_path())
conf_mgr = mgr
|
"""
Write your logreg unit tests here. Some examples of tests we will be looking for include:
* check that fit appropriately trains model & weights get updated
* check that predict is working
More details on potential tests below, these are not exhaustive
"""
import numpy as np
import pandas as pd
from regression impo... |
import numpy as np
import torch
import os.path as osp
import json
from core.config import cfg
from manopth.manolayer import ManoLayer
class MANO(object):
def __init__(self):
self.layer = self.get_layer()
self.vertex_num = 778
self.face = self.layer.th_faces.numpy()
self.joint_regr... |
from convokit import Corpus, CorpusObject
from sklearn.model_selection import train_test_split, cross_val_score, KFold
from typing import Callable, List
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import ... |
"""
Utility functions for hear-kit
"""
import numpy as np
from tqdm import tqdm
from typing import Tuple
import torch
import torch.nn.functional as F
from torch import Tensor
def compute_scene_stats(audios, to_melspec):
mean = 0.
std = 0.
for audio in audios:
# Compute log-mel-spectrogram
l... |
# Programa que usa uma lista chamada números e duas funções chamadas sorteia() e somaPar(). A primeira função
# vai sortear 5 números e vai colocá-los dentro da lista e a segunda função mostra a soma entre todos os valores
# pares sorteados pela função anterior.
from random import randint
numerossorteados = []
def s... |
import json
import requests
import bs4
def get_license(package):
package = package.lower()
r = requests.get('https://pypi.org/project/'+package)
soup = bs4.BeautifulSoup(r.text, features="html.parser")
for link in soup.find_all('p'):
text = link.get_text()
... |
import torch
import torch.nn as nn
import intel_extension_for_pytorch as ipex
from .cpupool import CPUPool
class MultiStreamModule(nn.Module):
r"""
MultiStreamModule supports inference with multi-stream throughput mode.
If the number of cores inside ``cpu_pool`` is divisible by ``num_streams``,
the co... |
from estrategias.jogadores import Jogador
from statistics import median
from random import choice
class MeuJogador(Jogador):
def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores):
media = sum(reputacoes_dos_jogadores)/len(reputacoes_dos_jogadores)
vivos = l... |
pay = 1
pay = 2
pay = 3
over
|
import sqlite3 as sql
import sys
import cgi
import json
from flask import Flask, jsonify
app = Flask(__name__)
print("worked")
sys.stdout.write("Content-Type: application/json")
sys.stdout.write("\n")
sys.stdout.write("\n")
form = cgi.FieldStorage()
print("worked")
#sys.stdout.write(json.dumps({ 'data': form.getvalue... |
import os
import sys
import unittest
from tempfile import mkstemp
from nbformat import reads
from nbmerge import merge_notebooks, main, parse_plan, annotate_source_path
SELF_DIR = os.path.abspath(os.path.dirname(__file__))
FIXTURES_DIR = os.path.join(SELF_DIR, "fixtures")
TARGET_NBS = [os.path.join(FIXTURES_DIR, f... |
#!/usr/bin/env python3
"""PyTest tests for the get_datatype.py module.
"""
import os
import sys
sys.path.append(os.path.join(os.path.dirname(sys.path[0]),'amoebaelib')) # Customize.
from data.datatype_test_seqs import testseq1
from get_datatype import \
get_datatype_for_sequence_string, \
get_dbtype
def test_get_da... |
from ..resource import Resource
class LiveVideos(Resource):
def find(self, live_video_id:str):
return self._get(f"live_videos/{live_video_id}")
def all(self, applicant_id:str):
payload = {"applicant_id": applicant_id}
return self._get("live_videos/", payload=payload)
def download... |
# 함수로 정수 올림 한 값 리턴하기
x = float(input())
def f(key):
key = -int(-key//1)
return key
print(f(x))
print(f(x)) |
from .shared import db
student_skill = db.Table(
'student_skill', db.Model.metadata,
db.Column('rating', db.Integer, nullable=False),
db.Column('student_id', db.Integer, db.ForeignKey('student.id'), nullable=False),
db.Column('skill_id', db.Integer, db.ForeignKey('skill.id'), nullable=False)
)
course_... |
"""
Copyright (c) 2020 Cisco Systems 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.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by appl... |
"""
1. Write a Python function that takes a sequence of numbers and determines whether all the numbers are different from each other.
2. Write a Python program to create all possible strings by using 'a', 'e', 'i', 'o', 'u'. Use the characters exactly once.
3. Write a Python program to remove and print every third nu... |
import os
import sys
import random
import time
import pickle
import subprocess
import math
import pdb
import inspect
import types
import imp
import re
from string import Template
### define globals
rproc_nqstat_time = None
rproc_nqstat_output = None
MATLAB_RETURN_VALUE = None
THIS_IS_A_RPROC_PROCESS = None
rproc_wait... |
name = "connect4"
|
#!/usr/bin/env python
# coding: utf-8
from ide import CropIDE
from minicap import Stream
from queue import Queue
import logutils
import logging
log = logutils.getLogger('tkgui')
log.setLevel(logging.DEBUG)
def main(serial=None, scale=0.5):
log.debug("gui starting(scale: {}) ...".format(scale))
# d = u2.connec... |
import torch
from qulacs import QuantumCircuit
from qulacs.gate import CNOT, RX, RY, RZ
from utils import *
from sys import stdout
from itertools import product
import scipy
import VQE as vc
import os
import numpy as np
import random
import copy
import curricula
try:
from qulacs import QuantumStateGpu as QuantumSt... |
#!/usr/bin/env python2
"""
INPUT - InterProScan result file:
ERR164409.102041_1_142_- eb53bcbf0748558f1f6c087ad5c76bcb 46 Gene3D G3DSA:3.90.1150.10 2 43 9.5E-6 T 18-02-2015 IPR015422 Pyridoxal phosphate-dependent transferase, major region, subdomain 2 GO:0003824|GO:0030170
ERR164409.101777_1_384_- 61af698732af6657579... |
from utils.train import train_process
if __name__ == '__main__':
train_process()
|
# Generated by Django 2.2.6 on 2019-12-02 11:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tasks', '0002_auto_20191029_1004'),
]
operations = [
migrations.RenameField(
model_name='task',
old_name='input',
... |
import numpy as np
import torch
from . import nms_cython_backend, nms_torch_backend
def nms(dets, iou_thr, return_inds=False):
"""Dispatch to either CPU or GPU NMS implementations.
The input can be either a torch tensor or numpy array. GPU NMS will be used
if the input is a gpu tensor or device_id is sp... |
# Copyright (c) Code Written and Tested by Ahmed Emad in 28/02/2020, 16:53
from django.urls import path
from core.views import RedirectView, ShortenView
app_name = 'core'
urlpatterns = [
path('shorten', ShortenView.as_view(), name='shorten'),
path('<str:url>', RedirectView.as_view(), name='redirect')
]
|
from utils.cards import get_deck
from .common import get_turn
def initial_state(players):
deck = []
min_cards = 4 * len(players) + (5 + 4 + 3 + 2 + 1)
while len(deck) < min_cards:
deck.extend(get_deck())
state = {
'stage': 'cards',
'deck': deck,
'hands': {player: [] f... |
from django.conf import settings
from django.contrib.auth.models import User
from htauth.htpasswd import check_password, NoSuchUser
class HtauthBackend(object):
supports_inactive_user = False
def authenticate(self, username=None, password=None):
password_file = settings.HTAUTH_PASSWD_FILENAME
... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from .items import Topic, Reply
from .spiders.tools import get_hour, map_add, sortmap, write_map_to_csv, get_date
class Scrc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.