content stringlengths 5 1.05M |
|---|
print('Helo world!')
print('Whats is your name?')
name = input()
print('It is good do meet you, ' + name)
print('The lenght of your name is: ' , len(name))
print('What is your age?')
age = input()
print('You will be ' + str(int(age) + 1) , 'in a year') |
import boto3
import main
from mock import MagicMock, patch
event = {u'Records': [{u'EventVersion': u'1.0',
u'EventSubscriptionArn': u'arn:aws:sns:us-west-2:000000000000:build_scheduled:00000000-0000-0000-0000-000000000000',
u'EventSource': u'aws:sns',
... |
"""
threading.Timer
- 일정 시간 경과 후에 쓰레드 실행
"""
import time
import threading
def thread_func():
for i in range(5):
print('Thread....')
if __name__ == '__main__':
t = threading.Timer(5, thread_func) # 5초후에 쓰레드를 시작
t.start()
# 3초후에 취소하면 5초후에 시작하려는 쓰레드가 취소되어 아무것도 출력되지 않는다
# time.sl... |
from django.http import HttpResponseRedirect
from django.views.generic import TemplateView
from django.contrib.auth.decorators import login_required
from tensor_site.decorators import login_required_message
from django.contrib import messages
import tensor_site.auth_tokens
import paramiko
class ServerView(TemplateVi... |
import cv2
import numpy as np
import torch
import time
from ossid.utils import K2meta, to_np
from zephyr.utils import projectPointsUv
def networkInference(model, dataset, data, return_time = False):
# Convert the data to pytorch data format
scoring_data = {}
img_blur = cv2.GaussianBlur(data['img'], (5,5)... |
#!/usr/bin/python3
# CKB Address test code
# cipher@nervos.org
import segwit_addr as sa
FORMAT_TYPE_SHORT = 0x01
FORMAT_TYPE_FULL_DATA = 0x02
FORMAT_TYPE_FULL_TYPE = 0x04
CODE_INDEX_SECP256K1 = 0x00
def generateShortAddress(pk, network = "mainnet"):
""" generate a standard secp256k1 short ckb address """... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2014 Lukas Kemmer
#
# 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
#
# Unl... |
test_cases = int(input())
for _ in range(test_cases):
num_of_students, *grades = map(int, input().split())
avg = sum(grades) / num_of_students
print('{:.3f}%'.format(sum(1 for grade in grades if grade > avg) / num_of_students * 100)) |
from pathlib import Path
import datetime
import httpretty
import pytest
from httpretty import httprettified
from opencage.geocoder import OpenCageGeocode
from opencage.geocoder import RateLimitExceededError
geocoder = OpenCageGeocode('abcde')
@httprettified
def test_no_rate_limit():
httpretty.register_uri(
... |
import typing
import warnings
import collections
from pathlib import Path
from typing import Union, Sequence, Optional, Any, TypeVar, Dict, List, Tuple
import torch
from torch.utils.data import Dataset
import numpy as np
from ..utils import get_stem
from ..torchio import DATA, AFFINE, TYPE, PATH, STEM, TypePath
from .i... |
from flask import render_template, request
from .. import api
from . import utils
@utils.app_errorhandler(403)
def forbidden(error):
if request.path.startswith("/api"):
return api.errors.forbidden(error)
return render_template("403.html"), 403
@utils.app_errorhandler(404)
def page_not_found(error):... |
import sys
import time
import struct
def writeData(fd, pageaddress, offsetstart, offsetend):
idx = 0
startword = offsetstart
while (startword) < offsetend:
#print(hex(startword))
bint = struct.unpack(">H",bindata[startword:startword+2])[0]
line = "ww 0x%08X 0x%04X\n"%(pageaddress+idx,bint)
#print(line)
f... |
import urllib2
from apps.lib.avatar.models import Avatar, avatar_file_path
from apps.lib.avatar.forms import PrimaryAvatarForm, DeleteAvatarForm, FacebookPictureForm
import apps.lib.facebook_api.facebook as facebook
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
... |
"""Command line interface for Operation Flag and Extended Properites Management."""
from .. import devices
from ..constants import RelayMode, ResponseStatus
from .tools_base import ToolsBase
class ToolsConfig(ToolsBase):
"""Command line interface for Operation Flag and Extended Properites Management."""
asy... |
from django import template
from ..models import CollectionExtension
register = template.Library()
@register.inclusion_tag('collection_extensions/dashboard/side_nav_inclusion.html',
takes_context=True)
def collection_extensions_side_nav(context):
return context
@register.filter
def co... |
#!/usr/bin/env python
##
"""
Copyright (C) 2018 Intel Corporation
?
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... |
name = 'pynger' |
import click
from os import path
from protect_archiver.cli.base import cli
from protect_archiver.client import ProtectClient
from protect_archiver.sync import ProtectSync
from protect_archiver.utils import print_download_stats
@cli.command(
"sync", help="Synchronize your UniFi Protect footage to a local destina... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-08-04 21:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('intake',
'0068_purgedformsubmission_add_applicant_id'),
]
operations = [
... |
__title__ = 'sqlquery'
__version__ = '1.0.1'
__author__ = 'Colin Deasy'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2015 Colin Deasy'
|
# -*- coding: utf-8 -*-
import unittest
from mcfly.models import InceptionTime
from test_modelgen import get_default, generate_train_data
class InceptionTimeSuite(unittest.TestCase):
"""
Test cases for InceptionTime models.
"""
# Tests for InceptionTime model:
def test_InceptionTime_starts_with_b... |
############### Calendar Module ################
# Enter your code here. Read input from STDIN. Print output to STDOUT
import datetime
import calendar
Date = list(map(int, raw_input().split(' ')))
Day = datetime.datetime(Date[2], Date[0], Date[1])
print(calendar.day_name[Day.weekday()].upper())
#######... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 16 10:17:36 2018
@author: Alexandre
"""
##############################################################################
import numpy as np
##############################################################################
from pyro.dynamic import system
from pyro.control i... |
import unittest
from typing import List, Set, Tuple
class Solution:
"""
This solution uses a depth-first search to count the number of enclaves.
The grid is looped over and whenever a piece of land is encountered a recursive
depth-first search is started from that point. The search will expand to
... |
_plot_added_variable_doc = """\
Create an added variable plot for a fitted regression model.
Parameters
----------
%(extra_params_doc)sfocus_exog : int or string
The column index of exog, or a variable name, indicating the
variable whose role in the regression is to be assessed.
res... |
import requests
from bs4 import BeautifulSoup
from datetime import datetime
from datetime import timedelta
import pandas as pd
class NaverScrap:
def obtain_results(queries, date_start, date_end, num_of_queries, ascending=False):
if isinstance(queries, str):
queries = [queries]
arr = [... |
import re
import numpy as np
import pytest
from pandas import DataFrame
import pandas._testing as tm
@pytest.mark.parametrize("subset", ["a", ["a"], ["a", "B"]])
def test_drop_duplicates_with_misspelled_column_name(subset):
# GH 19730
df = DataFrame({"A": [0, 0, 1], "B": [0, 0, 1], "C": [0, 0, 1]})
msg ... |
from blitzdb import Document, FileBackend
backend = FileBackend('./mob-db')
'''
A user shall have the following attributes: name, email, username/handle, twitter/facebook ID, auth token, karma points, as well
as future references to posts, comments and votes.
'''
class User(Document):
pass
'''
A post shall have t... |
from __future__ import division
import tensorflow as tf
class Regularizer(object):
def __init__(self, params):
# ----------------------------------
# regularization coefficients
# ----------------------------------
self.L1_in = params.get('L1_in', 0)
self.L1_rec = params.... |
class Solution(object):
def isPalindrome(self, s):
res = []
for char in s:
if char.isalnum():
res.append(char.lower())
return res == res[::-1]
def isPalindrome_2(self, s):
if not s:
return True
l, r = 0, len(s)-1
while l ... |
from common_functions import *
from VirtualCopernicusNG import TkCircuit
from gpiozero import LED, Button
# set udp controller
set_controller_settings()
set_receiver_settings()
# initialize the circuit inside the
circuit = TkCircuit(set_copernicus_settings("Lobby"))
global_switch_state = False
@c... |
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
df = pd.read_csv('titanic.csv')
df['male'] = df['Sex'] == 'male'
X = df[['Pclass', 'male', 'Age', 'Siblings/Spouses', 'Parents/Children', 'Fare']].values
Y = df['Survived'].values
#Y = tes.re... |
import os
import simplejson
from pylons import config
FILTER_DIR = config["selectivehearing.filter_dir"]
#just dump the JSON string here
def lookupUserFilters(username):
fn = os.path.join(FILTER_DIR, username)
if not os.path.exists(fn):
return None
return open(fn).read()
def saveUserFilters(js... |
from lib.dataset.squad_dataset import SquadDataset
from lib.dataset.squad_dataset_testpart import SquadTestDataset
from helpers.generic import print_shape_info, print_data_samples, random_generator, squad_trim, add_char_level_stuff,\
torch_model_summarize, generator_queue, evaluate
# if squad_testset.1.0.h5 file i... |
"""
Shell sort is a highly efficient sorting algorithm and is based on insertion sort algorithm.
This algorithm avoids large shifts as in case of insertion sort, if the smaller value is to
the far right and has to be moved to the far left.
This algorithm uses insertion sort on a widely spread elements, first to sort... |
from numpy import *
from geo import *
def prop2array(prop,x,y,z, undefined_value):
if(prop.size() != (x*y*z)):
print "Error! Property size is: ", prop.size(), "but given x*y*z size is: ",x*y*z
return
if type(prop) is hpgl.cont_property_array:
values = zeros(prop.size(), dtype=float64)
values_right =... |
import torch
import torch.nn.functional as F
def entropy(p):
p = F.softmax(p,dim=1)
return -torch.mean(torch.sum(p * torch.log(p+1e-5), 1))
def mpce(mat, query_labels, reference_labels,t=1, invert_distance=True):
# in parts from https://github.com/KevinMusgrave/pytorch-metric-learning/blob/master/s... |
"""
User-defined Rosenbrock distribution
=====================================
This examples shows the use of the multivariate normal distributions class. In particular:
"""
import numpy as np
from UQpy.distributions import DistributionND
import matplotlib.pyplot as plt
#%% md
#
# Example with a custom distributio... |
from PySide2.QtCore import Signal, QTimer
from PySide2.QtWidgets import QSizePolicy
from matplotlib.backends.backend_qt5agg import FigureCanvas
from matplotlib.figure import Figure
from matplotlib.widgets import Cursor
import numpy as np
class ZoomCanvas(FigureCanvas):
point_picked = Signal(object)
def _... |
# -*- coding: utf-8 -*-
"""Use case for home page.
"""
from omoide import domain
from omoide.domain import interfaces
__all__ = [
'HomeUseCase',
]
class HomeUseCase:
"""Use case for home page."""
def __init__(self, repo: interfaces.AbsItemsRepository) -> None:
"""Initialize instance."""
... |
eng_book_1= (
"I like soccer",
"I like ...",
"Do you play soccer?",
"Yes, I do.",
"No, I don't.",
"I don't play soccer.",
"I have a cat.",
"I have an eraser.",
"I have two dogs.",
"How many CDs do you have?",
"I have ten CDs.",
"I have no CDs.",
"What do you watch on ... |
"""View test."""
from unittest import mock
from django.test import TestCase
from django.urls import reverse
from export_as_bookmark.redis import Redis
class ViewTests(TestCase):
"""View test."""
def _request_get(self, name, reverse_args=None, *args, **kargs):
return self.client.get(
rev... |
from setuptools import setup, find_packages
setup(
name = 'kaggle',
version = '1.1.0',
description = 'Kaggle API',
long_description = 'Official API for https://www.kaggle.com, accessible using a command line tool implemented in Python. Beta release - Kaggle reserves the right to modify the API function... |
import pygame
from pygame.locals import *
from py2d.FOV import *
from py2d.Math import *
from examples import Example, SCREEN_WIDTH, SCREEN_HEIGHT
class FOV(Example):
"""Field of View Example
Move your mouse and watch how the obstacles affect the field of view
Have fun!
"""
def __init__(self, runner):
self.... |
from .PESQ import PESQ
from .SSNR import SSNR
from .LLR import LLR
from .WSS import WSS |
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Lic... |
import siconos.numerics as sn
import scipy.sparse
import numpy as np
import copy
from siconos.tests_setup import working_dir
data_dir = working_dir + '/data/'
dbl_eps = np.finfo(np.float).eps
def check_size(sa, sb):
assert sa[0] == sb[0]
assert sa[1] == sb[1]
def compare_with_SBM(sbmat, mat):
print('... |
import torch
from torch import nn
from data import SOS_token, indexesFromSentence2, MAX_LENGTH, normalizeString
from train_batch import load_model
class GreedySearchDecoder(nn.Module):
def __init__(self, encoder, decoder, device):
super(GreedySearchDecoder, self).__init__()
self.encoder = encoder... |
import six
from ref import backend_to_check, check_import
# no pygtk for py3
if six.PY2 and check_import("gtk"):
def test_pygtk():
backend_to_check("pygtk")
|
import tator
def test_analysis(
host: str,
token: str,
project: int) -> None:
"""
Create a set of analyses objects using the POST operation
Retrieve the set of analyses objects
Update the analysis object
Get the object and make sure it was updated
Delete the object
R... |
"""
pyflowmaps is a package that infers the horizontal, and vertical velocities
from intensity filtegrams, as well as from magnetograms obtained from the Sun
"""
__version__ = "2021.05.25"
__authors__ = "Jose Ivan Campos Rozo"
|
from typing import Optional, TYPE_CHECKING
if TYPE_CHECKING:
from Weverse.models import Community
class Artist:
r"""An Artist object that represents a Weverse Artist that belongs in a community.
It is not suggested to create an Artist manually, but rather through the
following method: :class:`Wevers... |
#!/usr/bin/env python
'''
d v job : Dimer VASP job
'''
from tsase.dimer import ssdimer
from tsase.neb.util import vunit, vrand
from ase.io import read, write
# import os
# import sys
import numpy as np
# from tsase.calculators.vasp_ext import Vasp
from ase.calculators.dftb import Dftb
import cPickle as pick
import i... |
import sys
import bisect
sys.setrecursionlimit(10**8)
def LIS(a):
lis = [a[0]]
for i in range(len(a)):
if a[i] > lis[-1]:
lis.append(a[i])
else:
lis[bisect.bisect_left(lis,a[i])] = a[i]
return len(lis)
def main():
n = int(input())
wh = []
for _ in rang... |
# coding=utf-8
from abc import ABCMeta, abstractmethod
class BaseHandler(metaclass=ABCMeta):
@abstractmethod
def do_handle(self, request_object, request_json):
pass
|
import requests
import json
with open(r"C:\work\python\win32_test-1\talk_test\kakao_code.json","r") as fp:
tokens = json.load(fp)
url="https://kapi.kakao.com/v2/api/talk/memo/default/send"
print(f"url = [{url}]")
# kapi.kakao.com/v2/api/talk/memo/default/send
headers={
"Authorization" : "Bearer " + tokens[... |
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
def add_middleware(app: FastAPI):
origins = [
"*",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],... |
import requests
def main():
# response = requests.get("https://api.exchangeratesapi.io/latest?base=USD&symbols=GBP")
payload = {"base": "USD", "symbols": "SEK"}
response = requests.get("https://api.exchangeratesapi.io/latest",
params=payload)
if response.status_code !=... |
#!/usr/bin/env python
#
# Example of one object under gravity with one contactor and a ground
# using the Siconos proposed mechanics API
#
from siconos.mechanics.collision.tools import Contactor
from siconos.io.mechanics_run import MechanicsHdf5Runner, MechanicsHdf5Runner_run_options
from siconos.mechanics.collision.... |
# code to prepend to dash apps to get the nav bar working in dash apps as well, instead of just in flask
nav_bar_template = """
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=dev... |
"""Python library to enable Axis devices to integrate with Home Assistant."""
import logging
import re
from .utils import session_request
_LOGGER = logging.getLogger(__name__)
CLASS_INPUT = 'input'
CLASS_LIGHT = 'light'
CLASS_MOTION = 'motion'
CLASS_OUTPUT = 'output'
CLASS_SOUND = 'sound'
EVENT_NAME = '{topic}_{so... |
import pytest
from pytest_mock import MockerFixture
from unittest.mock import Mock
from chris.cube.feed import Feed
from chris.tests.mocks.data.feed import data
@pytest.fixture
def session(mocker: MockerFixture) -> Mock:
return mocker.Mock()
@pytest.fixture
def feed(session) -> Feed:
return Feed(s=session,... |
import nltk
nltk.download(['punkt', 'wordnet', 'averaged_perceptron_tagger', 'stopwords'])
import sys
import pandas as pd
import numpy as np
import re
import pickle
import joblib
from sqlalchemy import create_engine
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem.wordnet impor... |
from .checker import CheckerFactory
from .checker import ImplementsType
from .rule import Rule
from .msgs import Msg
from typing import List
name = "flint"
def rule_bind_msg(r: Rule, msg: Msg):
r.bind_msg(msg.get_msg())
def rule_reg_func(rules: List[Rule], linter, options=()):
for r in rules:
_chec... |
# 3.3.1, Woche 3, Block 3, Aufgabe 1
# Dictonary
woerterbuch = {
"I" : "Ich",
"Cake" : "Kuchen",
"You" : "Du",
"Sun" : "Sonne",
"Like" : "mögen",
"Apple" : "Apfel",
"Hate" : "hassen",
"Tree" : "Baum",
}
# Ausgabe
print("Das Woerterbuch hat",len(woerterbuch),"Elemente") |
from django.db import models
from django.core.urlresolvers import reverse
from autoslug import AutoSlugField
from taggit.managers import TaggableManager
class Recipe(models.Model):
NOT_RATED = 0
AWFUL = 1
BAD = 2
AVERAGE = 3
GOOD = 4
GREAT = 5
RATING_CHOICES = (
(NOT_RATED, 'Not ra... |
"""
{This script carries out an MCMC analysis using fake data to test that
the known 5 parameter values are recovered}
"""
# Built-in/Generic Imports
import time
# Libs
from halotools.empirical_models import PrebuiltSubhaloModelFactory
from halotools.sim_manager import CachedHaloCatalog
from cosmo_utils.utils impor... |
from loguru import logger
from discord.ext import commands
import discord
###
# Other errors
###
@logger.catch
def handle_not_admin():
embed = discord.Embed(title="Command Error", color=0xE50000)
embed.description = "Only admins can run this command."
return embed
@logger.catch
def handle_unknown_error(... |
# Equação de primeiro grau
# Faça uma função que recebe dois números, a e b, e devolve a raíz da equação ax+b=0.
# O nome da sua função deve ser resolve_equacao_1o_grau.
def resolve_equacao_1o_grau (a, b):
return -b / a
|
from setuptools import setup
setup(
name='SimpleBinary',
version='0.1',
description='Converts string to binary and binary to string.',
license='MIT',
packages=['simplebinary'],
author='Aikufurr',
keywords=['binary', 'convert', 'simplebinary'],
url='https://github.com/Aikufurr/SimpleBina... |
from marshmallow import Schema, fields
class TransTextSchema(Schema):
en = fields.Str()
nb = fields.Str()
|
class SummaryRanges:
def __init__(self):
self.starts, self.ends, self.used = [-float("inf"), float("inf")], [-float("inf"), float("inf")], set()
def addNum(self, val):
if val not in self.used:
self.used.add(val)
i = bisect.bisect_left(self.starts, val) - 1
... |
import json
import numpy as np
import os
from photogrammetry_importer.camera import Camera
from photogrammetry_importer.point import Point
class OpenMVGJSONFileHandler:
@staticmethod
def parse_cameras(json_data, image_dp, image_fp_type, op):
views = {item['key']:item for item in json_data['views']}
... |
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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
... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
# In[2]:
"""i work with Santam Machine and the results are in .xls format
you can use other formats but remember to change the code,
important things are measurements and unit... |
from blazeutils.strings import randchars
class DefaultProfile(object):
SECRET_KEY = randchars()
# These three just get rid of warnings on the console.
KEG_KEYRING_ENABLE = False
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SITE_NAME = 'Keg Mail Demo'
... |
import emoji
print(emoji.emojize('Olá, Mundo! :earth_americas:', use_aliases=True))
|
"""Test the Safegate Pro local auth provider."""
import asyncio
from unittest.mock import Mock, patch
import pytest
import voluptuous as vol
from homeassistant import data_entry_flow
from homeassistant.auth import auth_manager_from_config, auth_store
from homeassistant.auth.providers import (
auth_provider_from_c... |
#!/usr/bin/env python
#
# fshack DS ChRIS plugin app
#
# (c) 2016-2020 Fetal-Neonatal Neuroimaging & Developmental Science Center
# Boston Children's Hospital
#
# http://childrenshospital.org/FNNDSC/
# dev@babyMRI.org
#
import os
import sys
import subprocess
im... |
from django.http import HttpResponse
from courses.utils import create_course
def index(request):
create_course()
return HttpResponse() |
import os
import logging
import threading
import time
import yaml
from expvar.stats import stats
class Settings(object):
def __init__(self, initial_settings):
self.settings = initial_settings
self.lock = threading.Lock()
self.logger = logging.getLogger(__name__)
self._loading_thre... |
from setuptools import setup
setup(
name='redshift-sqlalchemy',
version='0.1.2',
description='Amazon Redshift Dialect for sqlalchemy',
long_description=open("README.rst").read(),
author='Matt George',
author_email='mgeorge@gmail.com',
license="MIT",
url='https://github.com/sqlalchemy-re... |
'''
Parameters of the simulation
'''
import numpy as np
import dill
def set_parameters(case, N):
'''
Sets the parameters used in the simulation
Parameters
----------
case: dictionary
Dictionary containing infromation about whether the user homogeneous or heterogeneous
N: int
... |
#
# ByzantiumVM
#
BYZANTIUM_ROPSTEN_BLOCK = 1700000
|
from heuristicSearch.planners.mhastar import MHAstar
from heuristicSearch.envs.env import GridEnvironment
from heuristicSearch.envs.occupancy_grid import OccupancyGrid
from heuristicSearch.graph.node import Node
from heuristicSearch.utils.visualizer import ImageVisualizer
from heuristicSearch.utils.utils import *
from... |
'''tzinfo timezone information for America/La_Paz.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class La_Paz(DstTzInfo):
'''America/La_Paz timezone definition. See datetime.tzinfo for details'''
zone = 'America/La_Paz'
... |
import atexit
from Adafruit_MotorHAT import Adafruit_MotorHAT
import traitlets
from traitlets.config.configurable import Configurable
#TB 28112020_8
class Motor(Configurable):
value = traitlets.Float()
# config
alpha = traitlets.Float(default_value=1.0).tag(config=True)
beta = traitlets.Float(de... |
"""24. Swap Nodes in Pairs
https://leetcode.com/problems/swap-nodes-in-pairs/
"""
from common.list_node import ListNode
def swap_pairs(head: ListNode) -> ListNode:
if not head or not head.next:
return head
cur = head
nxt = head.next
nxt_nxt = nxt.next
nxt.next = cur
cur.next = swap_pai... |
import unittest
from connect import connect as APIConnect
def fun(x):
return x + 1
class connecttests(unittest.TestCase):
def testBuildURL(self):
connect = APIConnect()
# url only
self.assertEqual(connect.buildURL("http://example.com"), "http://example.com")
self.assertEqual(connect.b... |
#!/usr/bin/python2
import os
import subprocess
import sys
import tempfile
from Logger import logger
BASE_COMMAND = "/usr/bin/xinit /usr/bin/dbus-launch --exit-with-session %s -- :0 -nolisten tcp vt7"
try:
logger.debug("Starting ThinLauncher Daemon")
while True:
logger.debug("Launching ThinLauncher G... |
# TASK:
# Вхідні дані: 2 невід'ємних дійсних числа a та b -- аргументи командного рядка. b не дорівнює 0.
# Вихідні дані: дійсне число -- результат обчислення формули
# SOLUTION:
# Importing modules to work with embedded functions
import math
import sys
# Assigning variables values of two first cmd-line arguments
a =... |
import re
from typing import List, Mapping, Optional, Tuple
from .request import Request
BOUNDARY = "###"
VARIABLES_RE = re.compile(r"^@(\w+)\s*=\s*(.+)$", re.MULTILINE)
class ParserError(Exception):
pass
def parse(contents: str, pos: int) -> Request:
"""
Constructs a Request object from the contents... |
from numpy.testing import *
import numpy
from algopy.tracer.tracer import *
from algopy.utpm import *
D,P,N = 4,1,100
A = UTPM(numpy.random.rand(D,P,N,N))
Q,R = UTPM.qr(A)
l = UTPM(numpy.random.rand(D,P,N))
L = UTPM.diag(l)
A = UTPM.dot(Q, UTPM.dot(L,Q.T))
l2,Q2 = UTPM.eigh(A)
print('error between true and reconst... |
from PCV.classifiers import *
from PCV.clustering import *
from PCV.geometry import *
from PCV.imagesearch import *
from PCV.localdescriptors import *
from PCV.tools import * |
#!/usr/bin/env python
from ruia import Middleware, Request
middleware = Middleware()
@middleware.request
async def request_proxy(spider_ins, request: Request):
"""request using proxy example"""
# HTTP proxy
# request.aiohttp_kwargs.update({"proxy": "http://0.0.0.0:1087"})
# SOCKS5 proxy using aioht... |
# pylint: disable=not-callable, no-member, invalid-name, line-too-long, wildcard-import, unused-wildcard-import, missing-docstring
import torch
from e3nn import o3, rs
from e3nn.tensor_product import (LearnableTensorProduct, LearnableTensorSquare,
WeightedTensorProduct)
def test_learn... |
import numpy as np
class Deriv:
"""
Calculate the derivative with given order of the function f(t) at point t.
"""
def __init__(self, f, dt, o=1):
"""
Initialize the differentiation solver.
Params:
- f the name of the function object ('def f(t):...')
... |
#!/usr/bin/env python3
import os
import json
import sys
from typing import Dict, Optional
import argparse
VERSION_LINE_START = "__version__ = "
DIRECTORIES = [
"ml-agents/mlagents/trainers",
"ml-agents-environments/mlagents_envs",
"gym-unity/gym_unity",
]
MLAGENTS_PACKAGE_JSON_PATH = "com.unity.ml-agent... |
import re
import sys
GENERATIONS = 20
OFFSET = 50
pattern_re = re.compile('(.{5}) => (.)')
def init_pots_with(pots):
return '.' * OFFSET + pots + '.' * OFFSET
def run_generation(pots, patterns):
next_generation = ''
for i in range(2, len(pots) - 2):
pattern = pots[i - 2:i + 3]
next_generation += pa... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-07-30 10:11
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('js_components', '0014_promounit_show_filesize'),
]
operations = [
migratio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.