content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import random
import decimal
import datetime
from dateutil.relativedelta import relativedelta
def gen_sale(store_no, store_id, date):
# double christmas eve, every other
seasonality = 1
if date[5:len(date) - 1] == '12-24':
seasonality = 2
elif int(date[5:7]) == 12:
seasonality = 1.75
... | python |
"""https://open.kattis.com/problems/kornislav"""
nums = list(map(int, input().split()))
nums.remove(max(nums))
print(min(nums) * max(nums))
| python |
import os
from random import shuffle
########### input ########
b=10
raw_data = 'yahoo_raw_train'
userwise_data = 'yahoo_userwise_train_split%d'%b
###########################
fr = open(raw_data,'r')
nr = int(fr.readline())
for i in range(b):
f=open('raw%d'%i,'w')
if i == b-1:
tt = nr - i*(nr/b)
f.write('%d\n... | python |
class Solution:
def singleNumber(self, nums):
res = 0
# Exploit associative property of XOR and XORing the same number creates 0
for i in nums:
res ^= i
return res
z = Solution()
nums = [4, 2, 1, 2, 1]
print(z.singleNumber(nums))
| python |
from typing import Dict, Optional, Tuple
import uuid
import pandas as pd
from tqdm import tqdm_notebook
def flatten_df(
df: pd.DataFrame,
i: int = 0,
columns_map: Optional[Dict[str, str]] = None,
p_bar: Optional[tqdm_notebook] = None,
) -> Tuple[pd.DataFrame, Dict[str, str]]:
"""Expand lists and ... | python |
# -*- coding: utf-8 -*-
import uuid
import scrapy
from scrapy import Selector
from GAN_data.items import GanDataItem
class UmeiSpider(scrapy.Spider):
name = 'umei'
# allowed_domains = ['https://www.umei.cc/tags/meinv_1.htm']
start_urls = ['https://www.umei.cc/tags/meinv_1.htm']
def parse(self, r... | python |
from supervised_gym.experience import ExperienceReplay, DataCollector
from supervised_gym.models import * # SimpleCNN, SimpleLSTM
from supervised_gym.recorders import Recorder
from supervised_gym.utils.utils import try_key
from torch.optim import Adam, RMSprop
from torch.optim.lr_scheduler import ReduceLROnPlateau
fro... | python |
"""
This module contains tools for handling evaluation specifications.
"""
import warnings
from operator import itemgetter
from ruamel.yaml import YAML
from panoptic_parts.utils.utils import (
_sparse_ids_mapping_to_dense_ids_mapping as dict_to_numpy, parse__sid_pid2eid__v2)
from panoptic_parts.specs.dataset_spec... | python |
from typing import Tuple
import numpy as np
from tensorflow import Tensor
from decompose.distributions.distribution import Distribution
from decompose.distributions.normal import Normal
from decompose.distributions.product import Product
class NormalNormal(Product):
def fromUnordered(self, d0: Distribution,
... | python |
import spacy
from spacy.lang.en.stop_words import STOP_WORDS
from string import punctuation
from heapq import nlargest
class Summarizer:
def __init__(self):
print("Summarizer is being initiallized...")
def summarize(self, text):
# test1 = inputField.get('1.0', tk.END)
#test2 = numField... | python |
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Token
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.status import (
HTTP_400_BAD_REQ... | python |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
class HelicalGenerator():
def __init__(self, start_pos, des_pos, # total_time, dt, z_max=0.01,
start_vel=[0,0,0], des_vel=[0,0,0], m=1):
# self.theta = 0
self.x = 0
self.y = 0
... | python |
# Copyright (c) 2021 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 appli... | python |
from enum import Enum
from pydantic import BaseModel
class DeleteBookResponseStatus(Enum):
"""status codes for deleting a book"""
success = "book deleted"
borrowed = "book still borrowed"
fail = "book not deleted"
class DeleteBookResponseModel(BaseModel):
""""""
status: DeleteBookResponse... | python |
import string
"""
- Atividade de Logica para Computação.
- Autores: Paulo Henrique Diniz de Lima Alencar, Yan Rodrigues e Alysson Lucas Pinheiro.
- Professor: Alexandre Arruda.
"""
# Alphabet
atoms = list(string.ascii_lowercase)
operatores = ["#", ">", "&", "-"]
delimiters = ["(", ")"]
# Removing blank... | python |
from typing import Tuple, Union
import pygame
from pygame_gui.core.colour_gradient import ColourGradient
from pygame_gui.core.ui_font_dictionary import UIFontDictionary
from pygame_gui.core.utility import render_white_text_alpha_black_bg, apply_colour_to_surface
from pygame_gui.elements.text.html_parser import CharSt... | python |
import os
import sys
sys.path.append('..')
sys.path.append('.')
import mitogen
VERSION = '%s.%s.%s' % mitogen.__version__
author = u'Network Genomics'
copyright = u'2021, the Mitogen authors'
exclude_patterns = ['_build', '.venv']
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinxcontrib.programout... | python |
from ..definitions.method import MethodDefinition
from ..definitions.outputparameter import OutputParameterDefinition
from .method import ServiceMethod
class ServiceOutputParameter(object):
def __call__(self, name, convertType=None, many=False, optional=False, page=False, per_page=None):
def decorato... | python |
# -*- coding: utf-8 -*-
import pdb
import argparse
import sys as sys
import logging as logging
import time as time
import oneapi as oneapi
import oneapi.models as models
import oneapi.utils as mod_utils
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
parser = ... | python |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class IPv6_Encapsulation_Header(Base):
__slots__ = ()
_SDM_NAME = 'ipv6Encapsulation'
_SDM_ATT_MAP = {
'Security Paramaters Index': 'ipv6Encapsulation.header.spi',
'Sequence Number': 'ipv6Encapsulation.header.s... | python |
# -*- coding: utf-8 -*-
"""spear2sc.spear_utils: Utitlity methods to read SPEAR files"""
def process_line(line):
""" (list of str) -> list of list of float
Parses line, a line of time, frequency and amplitude data output by
SPEAR in the 'text - partials' format.
Returns a list of timepoints. Each ti... | python |
import threading
import os
import json
import time
from rsa import sign
from server import server_start
from client import send
from var import my_id
if os.name == "nt":
os.system("cls")
else:
os.system("clear")
if os.sys.argv[1] == "server":
server = threading.Thread(target = server_start())
server.s... | python |
from allennlp_dataframe_mapper.transforms.base import RegistrableTransform # NOQA
from allennlp_dataframe_mapper.transforms.hash_name import HashName # NOQA
from allennlp_dataframe_mapper.transforms.preprocessing import ( # NOQA
FlattenTransformer,
LabelEncoder,
Logarithmer,
MinMaxScaler,
Standar... | python |
##Classes for future implementation
def stats_player(name_player, data_df):
condition = data_df["Player" == name_player]
df_single_player = data_df[condition]
class Player():
def __init__(self, three_shot, two_shot, one_shot):
self.three_shot = three_shot
self.two_shot = two_shot
... | python |
# Calculando a raiz quadrada de um número.
n = 81 ** (1/2)
print(f'A raiz quadrada de 81 é {n}') | python |
import cmsisdsp as dsp
import numpy as np
import cmsisdsp.fixedpoint as f
import cmsisdsp.mfcc as mfcc
import scipy.signal as sig
from mfccdebugdata import *
from cmsisdsp.datatype import Q31
import cmsisdsp.datatype as dt
mfccq31=dsp.arm_mfcc_instance_q31()
sample_rate = 16000
FFTSize = 256
numOfDctOutputs = 13
... | python |
import os
import pandas as pd
import matplotlib.pyplot as plt
def get_speedup(precision: str, df1: pd.DataFrame, df2: pd.DataFrame, sys: str, dev: str) -> list:
speedup = [{} for x in range(2, 11)]
d1: pd.DataFrame = df1.copy()
d2: pd.DataFrame = df2.copy()
d1 = d1[d1['precision'] == precision]
d2... | python |
from typing import TypedDict, Optional
class IMeasInfo(TypedDict):
file_tag: str
entity_tag: str
metric_name: str
time_offset_hrs_mins: str
address: str
aggregation_strategy: Optional[str]
equation: Optional[str]
| python |
import re
import subprocess
import sys
import time
import traceback
import uuid
from collections import namedtuple
from PySide2.QtCore import (QObject, QRunnable, Qt, QThreadPool, QTimer,
Signal, Slot)
from PySide2.QtWidgets import (QApplication, QMainWindow, QPlainTextEdit,
... | python |
import os
from flask import Flask
class Config:
def __init__(self, app: Flask = None) -> None:
self.app = None
if app:
self.init_app(app)
def init_app(self, app: Flask) -> None:
config = self.get_user_config()
app.config.update(config)
@staticmethod
def ... | python |
"""
The sensors module contains the base definition for a generic
sensor call and the implementation of all the specific sensors
"""
from __future__ import print_function
from qds_sdk.qubole import Qubole
from qds_sdk.resource import Resource
from argparse import ArgumentParser
import logging
import json
log = loggi... | python |
from types import SimpleNamespace
from typing import Any, cast
from unittest.mock import Mock
import pytest
from playbacker.track import Shared, SoundTrack, StreamBuilder
from playbacker.tracks.file import FileSounds, FileTrack
from tests.conftest import get_audiofile_mock, get_tempo
@pytest.fixture
def file_track(... | python |
""" Pytest firewallreader
"""
import pickle
import pytest
from nftfw.rulesreader import RulesReader
from nftfw.ruleserr import RulesReaderError
from nftfw.firewallreader import FirewallReader
from .configsetup import config_init
@pytest.fixture
def cf(): # pylint: disable=invalid-name
""" Get config fro... | python |
from django.urls import path
from errors import views
app_name = 'errors'
urlpatterns = [
path('403.html', views.view_403, name="403"),
path('405.html', views.view_405, name="405"),
path('404.html', views.view_404, name="404"),
] | python |
"""Service module to store package loggers"""
import logging
import sys
def configure_logger():
logger = logging.getLogger(name='lexibot')
console_handler = logging.StreamHandler(stream=sys.stdout)
console_handler.setFormatter(
logging.Formatter('%(filename)s:%(lineno)d %(message)s'))
logger.a... | python |
import argparse
import glob
import math
import ntpath
import os
import shutil
import pyedflib
import numpy as np
import pandas as pd
import mxnet as mx
from sleepstage import stage_dict
from logger import get_logger
# Have to manually define based on the dataset
ann2label = {
"Sleep stage W": 0,
"Sleep stage... | python |
# Generated by Django 3.2.7 on 2021-09-28 13:56
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | python |
_base_ = [
'../_base_/datasets/dota.py',
'../_base_/schedules/schedule_1x.py',
'../../_base_/default_runtime.py'
]
model = dict(
type='OrientedRCNN',
backbone=dict(
type='SwinTransformer',
embed_dims=96,
depths=[2, 2, 6, 2],
num_heads=[3, 6, 12, 24],
windo... | python |
import sys, math
nums = map(int, sys.stdin.readlines()[1:])
gauss = lambda x: (x/2.0)*(1+x)
total = gauss(len(nums)-1)
a = max(nums)
nums.remove(a)
b = max(nums)
nums.remove(b)
if a == b:
cnt = gauss(1 + nums.count(a))
else:
cnt = 1 + nums.count(b)
shit_fmt = lambda x: math.floor(x*100.0)/100.0 # b/c hacke... | python |
downloadable_dataset_urls = {
"ag-raw-train": {
"filename": "train.csv",
"url": ("https://raw.githubusercontent.com/mhjabreel/CharCnn_Keras/master/"
"data/ag_news_csv/train.csv"),
"md5": "b1a00f826fdfbd249f79597b59e1dc12",
"untar": False,
"unzip": False,
}... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# this is a windows documentation stub, actual code lives in the .ps1
# file of the same name
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | python |
from IComprehension import Comprehension
from service.preprocess import (
check_answers_and_get_answer_sentence_matches,
check_questions_and_get_question_tokens,
_removeStopWords
)
from service.qualifier import find_similarity,find_question_similarity
class wiki(Comprehension):
def __init__(self, para... | python |
from random import randint
import numpy as np
from qiskit import execute, BasicAer
from qiskit.circuit.quantumcircuit import QuantumCircuit
cards = ["H", "H", "X", "X", "CX", "RX", "RX"]
def run(circuit: QuantumCircuit):
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
results = ex... | python |
import unittest
import datetime
import pandas as pd
from simple_ranker import Ranker
class RankerTest(unittest.TestCase):
def setUp(self):
self.current_year = datetime.datetime.now().year
def test_rank_by_PE_returns_lowest_first(self):
pe_rank = {
'name': 'pe',
'asce... | python |
from . import crop
from . import info
from . import inpaint
from . import pool
from . import unstack
| python |
"""
interchange_regression_utilities
Utilities to help with running the interchange regression tests
"""
from setuptools import find_packages, setup
setup(
name="interchange_regression_utilities",
author="Open Force Field Consortium",
author_email="info@omsf.org",
license="MIT",
packages=find_packa... | python |
from main.model import Font
from main.views import fetch_css
import requests
import datetime
import random
import string
SNAPSHOTTER_URL = "http://localhost:3000/"
def populate():
with open('urls.txt', 'r') as f:
urls = f.read().split('\n')[:10]
for url in urls:
print 'Processing', url, '...'
font_string = f... | python |
import pandas as pd
TITLE_NAME = "Auto List"
SOURCE_NAME = "auto_list"
LABELS = ["Team",
"Match",
"Starting position",
"Plate Assignments",
"Total Success",
"Total Attempt and Success",
"Scale Success",
"Switch Success",
"First Time",
... | python |
#!/usr/bin/env python
#!vim:fileencoding=UTF-8
import subprocess
jobid = (
("sf_0002", "A_onlyAICG"),
("sf_0004", "A_onlyAICG"),
("sf_0009", "I_ELE_HIS0_P1all"),
("sf_0010", "I_ELE_HIS0_P1all"),
("sf_0011", "G_ELE_HIS0_noP"),
("sf_0012", "G_ELE_HIS0_noP"),
("sf_0015", "J_ELE_HIS0_P2act"),
("sf_0016", "J_ELE_HIS0_P2ac... | python |
"""aubergine: create REST APIs using API-first approach."""
from setuptools import setup, find_packages
CLASSIFIERS = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python ... | python |
import json
import os
from datetime import datetime, timedelta
import pytz
import calculate_daily_payment_data
import calculate_market_data
import config
from manage_transactions import get_first_transaction_timestamp
from util import logging
STORE_FINAL_DATA_GENERAL = '/terra-data/v2/final/general'
log = logging.g... | python |
import re
import requests
'''
爬取校花网视频基础版
'''
response = requests.get('http://www.xiaohuar.com/v/')
# print(response.status_code)
# print(response.content)
# print(response.text)
urls = re.findall(r'class="items".*?href="(.*?)"', response.text, re.S) #re.S 把文本信息转换成1行匹配
# print(urls)
url = urls[2]
result = requests.get... | python |
# coding: utf-8
"""
Uptrends API v4
This document describes Uptrends API version 4. This Swagger environment also lets you execute API methods directly. Please note that this is not a sandbox environment: these API methods operate directly on your actual Uptrends account. For more information, please visit ... | python |
"""Compose new Django User models that follow best-practices for international names and authenticate via email instead of username."""
# This file:
# 1. define directory as module
# 2. set default app config
# pylint: disable=invalid-name
__version__ = "2.0a1"
# https://docs.djangoproject.com/en/stable/ref/ap... | python |
import utm as UTM
import math
import unittest
class UTMTestCase(unittest.TestCase):
def assert_utm_equal(self, a, b, precision=6):
self.assertAlmostEqual(a[0], b[0], precision)
self.assertAlmostEqual(a[1], b[1], precision)
self.assertEqual(a[2], b[2])
self.assertEqual(a[3].upper(),... | python |
# Software License Agreement (Apache 2.0 License)
#
# Copyright (c) 2021, The Ohio State University
# Center for Design and Manufacturing Excellence (CDME)
# The Artificially Intelligent Manufacturing Systems Lab (AIMS)
# All rights reserved.
#
# Author: Adam Exley
from typing import Union
import numpy as np
from klam... | python |
import os
from pwn import *
class tools():
def __init__(self, binary, crash):
self.binary = binary
self.crash = crash
self.core_list = filter(lambda x:"core" in x, os.listdir('.'))
self.core = self.core_list[0]
def gdb(self, command):
popen=os.popen('gdb '+self.binary+'... | python |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 19 10:36:38 2021
@author: mahdi
"""
import numpy as np
from scipy.linalg import toeplitz
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib import rc
from matplotlib.pyplot import figure
import matplotlib.colors as mcolors
import matp... | python |
import warnings
from sympy.testing.pytest import (
raises,
warns,
ignore_warnings,
warns_deprecated_sympy,
Failed,
)
from sympy.utilities.exceptions import SymPyDeprecationWarning
# Test callables
def test_expected_exception_is_silent_callable():
def f():
raise ValueError()
rai... | python |
# Verhalten sich wie 'Mengen' aus der Mathematik
# Werte müssen einmalig sein
# Kann verwendet werden um Daten aus einer Liste mit doppelungen einmalig zu machen
# Wird oft für das Nachschlagen von Werten verwendet, da sets schneller arbeiten als Listen
# sets können bei bedarf wachsen und schrumpfen
# leere Instanz e... | python |
# convert2.py
# A program to convert Celsius tempts to Fahrenheit
# This version issues heat and cold warnings.
def main():
celsius = float(input("What is the Celsius temperature?"))
fahrenheit = 9/5 * celsius + 32
print("The temperature is", fahrenheit, "degrees fahrenheit.")
# Print warnings for extreme temps
... | python |
import pickle
import os
from pprint import pprint
with open('data.pk', 'rb') as f:
data = pickle.load(f)
data.reset_index(inplace=True, drop=True)
user_list = set(data['name'])
authors = data.groupby('name')
# pprint(authors.groups)
# print(type(authors.groups))
authors_list = {}
for user, index in authors.group... | python |
#Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados.
'''num = str(input('Digite um número de 0 a 9999: '))
print(
'O número: {} está dividido entre as casas:\n'
'unidade: {}\n'
'dezena: {}\n'
'centena: {}\n'
'milhar: {}\n'.format(num, num[3], num[2], num[1... | python |
from .vault import kubeconfig_context_entry
def test_kubeconfig_context_entry_minikube():
mock_context_entry = {
'name': 'minikube',
'context': {
'cluster': 'minikube-cluster',
'user': 'minikube-user',
}
}
assert kubeconfig_context_entry('minikube') == mock_context... | python |
from dagster import repository
from simple_lakehouse.pipelines import simple_lakehouse_pipeline
@repository
def simple_lakehouse():
return [simple_lakehouse_pipeline]
| python |
# -*- coding: UTF-8 -*-
__license__="""
Copyright 2004-2008 Henning von Bargen (henning.vonbargen arcor.de)
This software is dual-licenced under the Apache 2.0 and the
2-clauses BSD license. For details, see license.txt
"""
__version__=''' $Id: __init__.py,v 1.2 2004/05/31 22:22:12 hvbargen Exp $ '''... | python |
from __future__ import absolute_import
from __future__ import print_function
from keras.datasets import stock_one
from keras.models import Sequential
from keras.layers.core import Dense, TimeDistributedDense, Dropout, Activation, Merge
from keras.regularizers import l2, l1
from keras.constraints import maxnorm
from ker... | python |
import numpy as np
import math
from scipy.optimize import linear_sum_assignment
from contourMergeTrees_helpers import *
def branchMappingDistance(nodes1,topo1,rootID1,nodes2,topo2,rootID2,editCost,traceback=False):
memT = dict()
#===================================================================... | python |
from django.contrib import admin
from .models import Customer, User
admin.site.register(Customer)
admin.site.register(User)
| python |
import numpy as np
from models.robots.robot import MujocoRobot
from utils.mjcf_utils import xml_path_completion
class Sawyer(MujocoRobot):
"""
Sawyer is a witty single-arm robot designed by Rethink Robotics.
"""
def __init__(
self,
pos=[0, 0, 0.913],
rot=[0, 0, 0],
... | python |
from tool.runners.python import SubmissionPy
from collections import defaultdict
import operator
class JulesSubmission(SubmissionPy):
def run(self, s):
def find_nearest(points, x, y):
min_distance = 1000
curr_nearest_point = -1
number_having_min_distance = 0
... | python |
from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from applications.filetracking.models import File, Tracking
from applications.ps1.models import IndentFile,StockEntry
from applications.globals.models import ExtraInfo, HoldsDesignation, Designation
from django.template... | python |
from pygame.mixer import Channel
from pygame_menu import Menu
from pygame_menu.themes import Theme
from pygame_menu.baseimage import BaseImage
from pygame_menu.baseimage import IMAGE_MODE_SIMPLE
from pygame_menu.widgets import MENUBAR_STYLE_NONE
from pygame_menu.widgets.selection.none import NoneSelection
from pygame_m... | python |
import logging
import tensorflow as tf
import ray
from replay.func import create_local_buffer
from algo.apex.actor import Monitor
logger = logging.getLogger(__name__)
def disable_info_logging(config,
display_var=False, save_code=False,
logger=False, writer=False):
config['display_var'] = displa... | python |
import PIL
from PIL import Image
import os
#5:7 Aspect ratio that is larger than cardface pngs
CARD_SIZE = (260, 364)
#adds background to transparent card faces found in /card_faces
def add_background(path):
img = Image.open(path)
dimensions = img.size
background = Image.open('card_background.png')
b... | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2020, Anima Istanbul
#
# This module is part of anima-tools and is released under the MIT
# License: http://www.opensource.org/licenses/MIT
import logging
import unittest
import sys
from anima.ui import IS_PYSIDE, IS_PYQT4, reference_editor
logger = logging.getLogger('an... | python |
#!/usr/bin/python3
#
# Read multiple yaml files output one combined json file
#
# This source file is Copyright (c) 2021, FERMI NATIONAL
# ACCELERATOR LABORATORY. All rights reserved.
import os
import sys
import yaml
import json
prog = 'parseconfig.py'
def efatal(msg, e, code=1):
print(prog + ': ' + msg + ': ... | python |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from __future__ import print_function
import os
import sys
from PIL import Image
if __name__ == "__main__":
infile = sys.argv[1]
outfile = os.path.splitext(infile)[0] + ".transpose.png"
if infile != outfile:
try:
with Image.open(infile) as ... | python |
A_1101_10 = {0: {'A': 1.5, 'C': -1.0, 'E': -2.3, 'D': -2.3, 'G': 0.0, 'F': -2.4, 'I': 0.5, 'H': -1.5, 'K': -2.3, 'M': -1.4, 'L': -2.9, 'N': -2.0, 'Q': 0.6, 'P': -2.2, 'S': 1.5, 'R': -2.3, 'T': -1.8, 'W': -1.3, 'V': -2.2, 'Y': -1.9}, 1: {'A': 0.3, 'C': -1.2, 'E': -2.7, 'D': -2.6, 'G': -2.9, 'F': -2.0, 'I': 0.0, 'H': -1.... | python |
# Generated by Django 1.11.3 on 2017-07-07 19:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration): # noqa
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Order',
fields=[
... | python |
from django.http.response import HttpResponse
from django.shortcuts import render, redirect
from .models import Pet
from .forms import PetForm
from users.models import User
def All(request):
if not request.user.is_authenticated:
print("This is a not logged user bro:")
return redirect('/accounts/lo... | python |
from controller.qt.controller import QtGameController | python |
from django.test import TestCase
from django.contrib.auth import get_user_model
class ModelTest(TestCase):
def test_create_user_with_email(self):
""" test creating user with email address """
email = "tester@mail.com"
password = "testpassword"
user = get_user_model().objects.creat... | python |
import copy
from typing import List
def selection_sort(x: List) -> List:
"""Selection sort repeatedly swaps the minimum element of a list with the left-most unsorted element, building up
a new list that's fully sorted. It has an average time complexity of Θ(n^2) due to the nesting of its two loops.
Time c... | python |
from typing import Union, Callable, Any, Optional, Dict
import os
import logging
import hashlib
from pathlib import Path
import numpy as np
try:
import soundfile as sf
from espnet2.bin.tts_inference import Text2Speech as _Text2SpeechModel
except OSError as ose:
logging.exception(
"`libsndfile` no... | python |
"""
iorodeo-potentiostat
---------------------
Python interface to LTU Electrocheminiluminescence(ECL)/Potentiometer Shield for the teensy 3.6 development
board. Based upon the IO Rodeostat potentiometer (Will Dickson, http://stuff.iorodeo.com/docs/potentiostat).
"""
from setuptools import setup, find_packages... | python |
# TODO: Implement this script fpr
as5048aencoder = Runtime.start("as5048aencoder","As5048AEncoder")... | python |
# Copyright 2022 The Bazel 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 la... | python |
from data_structures.queue.queue import Queue
# You have a group of people
# One person is holding a hot potato
# Each turn the person passes the potato to the person in the left
# Then the person gives the potato to his left and then leaves
def play_hot_potato_game(items, reps):
queue = Queue()
# O(n)
... | python |
from gaia_sdk.graphql.request.type.BuildInEvaluation import BuildInEvaluation
from gaia_sdk.graphql.request.type.SkillEvaluation import SkillEvaluation
from typing import Callable, List
from gaia_sdk.api.VariableRegistry import VariableRegistry
from gaia_sdk.graphql.request.enumeration.Order import Order
from gaia_sd... | python |
"""
Finds and stores the voting data for each candidate in every district
in the Russia 2018 Presidential election.
"""
import re
from os import stat
import time
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdri... | python |
# coding:utf-8
# @Time : 2021/6/29
# @Author : fisher yu
# @File : file_hash.py
"""
file hash: v0.0.1
"""
import argparse
import hashlib
import os
chunkSize = 8 * 1024
def valid_file(file_path):
if os.path.exists(file_path) and os.path.isfile(file_path):
return True
return False
def fil... | python |
{
'targets': [
{
'target_name': 'binding',
'sources': [ 'binding.cc' ],
'libraries': ['-lzmq'],
'cflags!': ['-fno-exceptions'],
'cflags_cc!': ['-fno-exceptions'],
'conditions': [
['OS=="mac"', {
'xcode_settings': {
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES... | python |
# -*- coding: utf-8 -*-
def main():
s = input()
t = s[::-1]
n = len(s) // 2
count = 0
for i in range(n):
if s[i] != t[i]:
count += 1
print(count)
if __name__ == '__main__':
main()
| python |
try:
import config_local as config
except:
import config
import requests
headers = {"User-Agent": "http-url-test"}
response = requests.get(config.url, headers=headers)
print('Response URL:', response.url)
print(response.text)
| python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-05-28 23:39
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import multiselectfield.db.fields
class Migration(migrations.Migration):
dependencies = [
... | python |
from unyt._unit_lookup_table import *
| python |
from datetime import datetime, timedelta
from msl.qt import QtCore, QtGui, QtWidgets, Button
from ...log import log
from ...constants import FONTSIZE
def chop_microseconds(delta):
return delta - timedelta(microseconds=delta.microseconds)
class WaitUntilTimeDisplay(QtWidgets.QDialog):
def __init__(self, l... | python |
import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET
def xml_to_csv(path):
xml_list = []
# 讀取標註檔案
for xml_file in glob.glob(path + '/*.xml'):
tree = ET.parse(xml_file)
root = tree.getroot()
for member in root.findall('object'):
value = (str(root.... | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ray
from ray.rllib.evaluation.postprocessing import compute_advantages, \
Postprocessing
from ray.rllib.policy.tf_policy_template import build_tf_policy
from ray.rllib.policy.sample_batch import Samp... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.