content stringlengths 5 1.05M |
|---|
from arcpy import da, Array, Point, Polyline, Polygon, AddField_management, CreateFeatureclass_management
import math
def rotacionar_poligono(polygon, anchor_point, ang, proj_geo):
array = Array()
anchor_x = anchor_point.X
anchor_y = anchor_point.Y
for part in polygon:
for point in part:
... |
""" Module containing classes that model the several OCPP messages types. It
also contain some helper functions for packing and unpacking messages. """
import os
import json
import decimal
from dataclasses import asdict, is_dataclass
from jsonschema import validate
from jsonschema.exceptions import ValidationError as... |
"""Auxiliary functionality"""
from enum import Enum, auto
import time
import threading
class TaskStates(Enum):
"""Background task states"""
STOPPED = auto()
RUNNING = auto()
TERMINATING = auto()
class ConsoleHeartBeat:
"""A context manager starting a heart beater printing dots to the given
... |
import argparse
import bilby
import numpy as np
import matplotlib.pyplot as plt
plt.rc('text', usetex=False)
from rmnest.utils import *
from rmnest.likelihood import RMLikelihood, GFRLikelihood
def get_input_arguments(parser):
parser.add_argument("-a", dest="archive", type=str, default=None,
help="Input... |
#!/usr/bin/env python
import os
import shutil
import subprocess
PROJECT_DIRECTORY = os.path.realpath(os.path.curdir)
def remove_file(filepath):
os.remove(os.path.join(PROJECT_DIRECTORY, filepath))
def remove_dir(filepath):
shutil.rmtree(os.path.join(PROJECT_DIRECTORY, filepath), )
if __name__ == '__main_... |
from django.urls import include
from django.urls import path
from apps.usuarios.views import *
from django.contrib.auth import views as auth_views
urlpatterns = [
path('cotizacion',cotizar,name="cotizar"),
path('login', auth_views.login, {'template_name': 'registro/login.html'}, name='login'),
path('regis... |
import os
import numpy as np
import time
import datetime
class Log:
VERBOSE = 5
DEBUG = 4
INFO = 3
WARNING = 2
ERROR = 1
NONE = 0
__log_level = VERBOSE
__fp = None
@staticmethod
def setLevel(lvl):
Log.__log_level = lvl
@staticmethod
def timestr():
t = time.time()
msec = str(int(t ... |
#!/usr/bin/env python3
import csv
import urllib.request,urllib.parse,json
import os, ssl
# SSL exception
if (not os.environ.get('PYTHONHTTPSVERIFY', '') and
getattr(ssl, '_create_unverified_context', None)):
ssl._create_default_https_context = ssl._create_unverified_context
def getPpn(name,firstname,birthd... |
# Copyright 2016 Tesora 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 a... |
from __future__ import absolute_import, print_function, unicode_literals
import sys
import contextlib
from colorama import Fore, Back, Style, init, AnsiToWin32
from .. import utils, results
from ._utils import indent
@contextlib.contextmanager
def formatter(stream):
yield DefaultFormatter(stream)
class Defaul... |
"""arturo-stac-api."""
import os
from imp import load_source
from setuptools import find_namespace_packages, setup
with open("README.md") as f:
desc = f.read()
# Get version from stac-fastapi-api
__version__ = load_source(
"stac_fastapi.sqlalchemy.version",
os.path.join(os.path.dirname(__file__), "stac_f... |
#!/usr/bin/env python3
# Install the tulip/asyncio reactor:
from txtulip.reactor import install
install()
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
class Echo(Protocol):
def dataReceived(self, data):
self.transport.write(data)
def main():
reactor... |
from ansible.module_utils.selvpc_utils.licenses import \
get_project_licenses_quantity
from ansible.module_utils.selvpc_utils.floatingips import \
get_project_ips_quantity
from ansible.module_utils.selvpc_utils.subnets import \
get_project_subnets_quantity
from ansible.module_utils.selvpc_utils.vrrp import ... |
import discord
from discord.ext import commands
import json
import time
with open('../../setting.json', mode='r',encoding='utf8') as jfile:
jdata = json.load(jfile)
intents = discord.Intents.all()
bot=commands.Bot(command_prefix=".",intents=intents)
@bot.event
async def on_ready():
print('We have logged in a... |
import logging
from datetime import datetime
from flask import Flask, request
from flask_cors import CORS
from infrastructor.api import ErrorHandler
from infrastructor.api.BaseResponse import BaseResponse
from werkzeug.exceptions import HTTPException
from infrastructor.api.ControllerBase import ControllerBase
from m... |
#!/usr/bin/env python3.6
# Copyright 2018 U.C. Berkeley RISE Lab
#
# 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 ... |
import datetime
import pytest
from redisolar.dao.redis import CapacityReportDaoRedis
from redisolar.models import MeterReading
@pytest.fixture
def capacity_report_dao(redis, key_schema):
yield CapacityReportDaoRedis(redis, key_schema)
@pytest.fixture
def readings():
now = datetime.datetime.utcnow()
yi... |
from autokeras.tuners import greedy
IMAGE_CLASSIFIER = [{
'image_block_1/block_type': 'vanilla',
'image_block_1/normalize': True,
'image_block_1/augment': False,
'image_block_1/vanilla_1/kernel_size': 3,
'image_block_1/vanilla_1/num_blocks': 1,
'image_block_1/vanilla_1/separable': False,
'i... |
#!/usr/bin/env python
import csv
import sys
fields = sys.argv[2].split(',')
with open(sys.argv[1], 'rb') as handle:
rdr = csv.reader(handle, delimiter='\t')
for row in rdr:
if row[0].startswith('#'):
sys.stdout.write('\t'.join(row) + '\n')
continue
tags = {x.split('=')... |
from django.db import models
from django.db.models import Q, Model
class AbstractZygosityCountNode(Model):
minimum_count = models.IntegerField(null=False, default=0)
maximum_count = models.IntegerField(null=True, blank=True)
min_ref_count = models.IntegerField(null=True, blank=True)
max_ref_count = mo... |
"""
config_example.py
------------------
example config for testing
"""
## fully expanded example config
config_ex ={
'Input_dir': './example_data',
'Output_dir': 'test-out/',
'Control_dir': './',
'use_jit': 'no',
'save_runtime_data': {
'area': True,
'ald': True,
'climate_e... |
''' LISTA 02 - EXERCICIO 13
Nome: Guilherme Augusto Sbizero Correa
Data: Setembro /2020
Enunciado: Escreva um programa que converta uma temperatura digitada
em ºC em ºF. A formula para a conversão
é: F = ((9 x C)/5)+ 32
'''
c = float(input("Entre com a temperatura em ºC: "))
f = ((9 * c)/... |
#! /usr/bin/python3
# Simple flask app which listens for a json backup report payload and exposes basic metrics to prometheus
from flask import Flask, request
from flask_apscheduler import APScheduler
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from prometheus_client import make_wsgi_app, Counter,... |
"""
server module
"""
from ker.utils import request
from .list import API_LIST
class Server:
"""
server apis
"""
def __init__(self, email, token):
self.email = email
self.token = token
def list(self):
"""
list all servers
"""
return request(API_LIST... |
def f(integer):
"""
factorcalc.f(int > 0) -> list of int -- provides a list of all the factors of the first argument
"""
if type(integer)==int:
if integer>0:
possible_factors=[integer]
possible_factor=integer-1
for i in range(integer):
... |
#!/bin/python
import inspect
import os
def getThisFileDir():
this_file = inspect.currentframe().f_code.co_filename
fullmod = os.path.abspath(this_file)
# just the directory
dirname = os.path.dirname(fullmod)
return dirname
# check sinedon.cfg
from leginon import configcheck
configcheck.checkSinedonConfig()
conf... |
from ...hek.defs.ustr import *
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the makingAnagrams function below.
def makingAnagrams(s1, s2):
sbig =list(s1)
ssmall = list(s2)
for c in s1:
if c in ssmall:
ssmall.remove(c)
sbig.remove(c)
return len(ssmall)... |
import random
import numpy as np
import plotly.graph_objects as go
from scipy.stats import rv_continuous
def plot_dist_over_time(dist_params: dict, distribution: rv_continuous, range_of_plot: tuple = (0, 1)):
"""
Plotting distribution's pdf function as a dynamic graph.
Parameters
----------
dist_... |
import retro
def main():
env = retro.make(game='Pong-Atari2600', players=2)
obs = env.reset()
while True:
# action_space will by MultiBinary(16) now instead of MultiBinary(8)
# the bottom half of the actions will be for player 1 and the top half for player 2
obs, rew, done, info = e... |
# Generate All Subsets Of A Set
# Generate ALL possible subsets of a given set. The set is givet in the form of a string s containing distinct lowercase characters 'a' - 'z'.
# Example
# Input: "xy"
# Output: ["", "x", "y", "xy"]
# Notes
# Input Parameters: There is only one argument denoting string s.
# Output: Retu... |
try:
import requests
import progressbar as pb
import os
except:
print("Necessary modules not installed")
sys.exit()
def download_file(url, file_name, dest_dir):
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
full_path_to_file = dest_dir + os.path.sep + file_name
if os... |
from typing import Any, Iterable, Union, get_args
from stift.exceptions import FunctionError
ANY_NUM_ARGS = "ANY_NUM_ARGS"
ANY = Any
NUMERICAL = Union[int, float, complex]
REALS = Union[int, float]
class BaseFunction:
"""Basic function class meant to be overloaded.
arg_counts, arg_types, and process() need... |
"""
Crear una programa que contenga:
-ventana (hecho)
-tamaño fijo (hecho)
-ventana no redimensionable (hecho)
-Un Menu (Inicio, Añadir, Informacion, Salir) (hecho)
-Diferentes Pantallas (Hecho)
-Formulario de Añadir Productos (Hecho)
-Guardar datos temporalmente (Hecho)
-Listar datos en pantalla principal
-Opcion de ... |
from http.client import TEMPORARY_REDIRECT
import os
import traceback
import uuid
import docker
import shutil
import concurrent.futures
from yaml import full_load
from image_builder import utils
PENDING='PENDING'
STARTED='STARTED'
BUILDING='BUILDING'
CONVERTING='CONVERTING'
FINISHED='FINISHED'
FAILED = 'FAILED'
cl... |
import time
import json
import hmac
import hashlib
import requests
from operator import itemgetter
from datetime import datetime
class BinanceAPIException(Exception):
def __init__(self, response, status_code, text):
self.code = 0
try:
json_res = json.loads(text)
except ValueEr... |
import sys
import msvcrt
c = msvcrt.getch()
print(type(c))
print(c)
|
import re
import os
import json
import logging
import numpy as np
import pandas as pd
import requests as rq
import multiprocessing
from datetime import datetime
HOME = os.path.expanduser("~")
_RETURN_NONE = (lambda: None).__code__.co_code
minimal_headers = {
"Connection": "keep-alive",
"Upgrade-Insecure-Reque... |
from pygame import Rect
from albow.resource import get_image
class ImageArray(object):
def __init__(self, image, shape):
self.image = image
self.shape = shape
if isinstance(shape, tuple):
self.nrows, self.ncols = shape
else:
self.nrows = 1
self.n... |
import torch
import numpy as np
class Storage:
def __init__(self, obs_cluster_num, action_cluster_num, num_steps=10000):
self.input_batch = torch.zeros(num_steps, 24)
self.obs_cluster_batch = torch.zeros(num_steps, obs_cluster_num)
self.action_cluster_batch = torch.zeros(num_steps, action... |
import os
import glob
from pkg_resources import resource_filename
def get_ff_path():
return [resource_filename('oplsaafoyer', 'xml')]
def get_forcefields():
for dir_path in get_ff_path():
file_pattern = os.path.join(dir_path, '*.xml')
file_paths = [file_path for file_path in glob.glob(file_p... |
import datetime
import re
date_format = r".*\((\d+)\.(\d+)\.(\d+)\)"
id_format = r"([a-z.]+) (\d+)\.(\d)+ \((\d+)\.(\d+)\.(\d+)\)\r\n"
class LibInfo(object):
def __init__(self, name, version, revision, date, pos_size=0, neg_size=0):
"""pass either a valid id_string or a date object"""
self.name ... |
from testing.test_interpreter import BaseTestInterpreter
class TestStandardModule(BaseTestInterpreter):
def test_escapeshellarg(self):
output = self.run('''
echo escapeshellarg("xyz");
echo escapeshellarg('$X');
echo escapeshellarg("'");
echo escapeshellarg("x'y\\"z");
... |
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import matplotlib.pyplot as plt
from itertools import product
PIXEL_VALUE = [50, 90, 140, 180, 220]
np.random.shuffle(PIXEL_VALUE)
COLOR_MAP = tuple(product(PIXEL_VALUE, PIXEL_VALUE, PIXEL_VALUE))[:80]
COLOR_MAP = (255, 0, 0) + COLOR_MAP
def vis(imgs, prediction... |
import numpy as np
from jesse import utils
from jesse import factories
from typing import Union
def get_candles(exchange: str, symbol: str, timeframe: str, start_date: str, finish_date: str) -> np.ndarray:
"""
Returns candles from the database in numpy format
:param exchange: str
:param symbol: str
... |
#! /usr/bin/env python
from .triplet import TripletLoss, HardTripletLoss, FullTripletLoss
from .cross_entropy import LabelSmoothCrossEntropyLoss
|
#! /usr/bin/env python
"""
------------------------------------------------------------------------------------------------------------------------
____ __ __ __ __ __
/ __ \__ __/ /_/ /_ ____ ____ / / / /__ ____ _____/ /__ _____
... |
import hashlib
from django import forms
from safe import crypto
from safe.exceptions import *
from safe.models import Credential
class KeyField(forms.Field):
def __init__(self, *args, **kw):
kwargs = {'widget': forms.Textarea(attrs={'style': "width:100%;"})}
kwargs.update(kw)
super(KeyFie... |
from server.router import app
import os
if __name__ == '__main__':
PORT = int(os.environ['PORT'])
app.run(debug=True, port=PORT)
|
import json
class Redis:
def __init__(self, client, key='bulk_task', *,
timeout=None, json_loads=json.loads, json_dumps=json.dumps):
self.client = client
self.key = key
self.timeout = timeout
self.json_loads = json_loads
self.json_dumps = json_dumps
de... |
# インストールした discord.py を読み込む
import discord
import os
import asyncio
import time
import sys
import random
# access token
TOKEN = os.environ['DISCORD_BOT_TOKEN']
#intent
discord_intents = discord.Intents.all()
#serverID
ServerID=int(724335733841854514)
#CategoryID
ID_DIST_CATE=int(771223697071669288)
#ChannnelID List... |
color = input("Enter a Color: ")
plural_noun = input("Enter a Plural Noun: ")
celebrity = input("Enter a Celebrity Name: ")
print(f"Roses are {color}")
print(f"{plural_noun} are blue")
print(f"I Love {celebrity}")
|
from collections import defaultdict
import re
import sys
from .exceptions import DuplicateVersionException, InvalidVersionException
from .utils import (CLASS, CLASS_SUFFIX_RE, create_proxy_class,
determine_member_type, FUNCTION, FUNCTION_SUFFIX_RE,
PROXY_VERSION_TAG)
from .vali... |
import os;
import json;
from datetime import date, datetime
import pathlib
def launchZoom(id, password):
os.system('start "" "zoommtg://zoom.us/join?confno=' + id + '&pwd=' + password + '"')
with open(str(pathlib.Path(__file__).parent.absolute()) + "\\..\\data\\test-classes.json") as f:
data = json.load(f)
l... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWidgets import QMessageBox, QInputDialog
from gui_z2 import Ui_Widget, LoginDialog
import baza_z2 as baza
class Zadania(QWidget, Ui_Widget):
def __init__(self, parent=... |
# Script that wishes happy birthday to people who have number names
def happy_birthday(name):
print("Happy Birthday, dear " + name + "!")
# Try one of these
happy_birthday(100)
happy_birthday(3.1415927)
|
from openfigipy import OpenFigiClient
import pandas as pd
ofc = OpenFigiClient()
ofc.connect()
x = ofc.map_figis(['BBG0032FLQC3', 'BBG0032FLQC1', 'BBG00JPR0LW9'])
df = pd.DataFrame({'idType': ['ID_BB_GLOBAL', 'ID_BB_GLOBAL', 'ID_BB_GLOBAL'],
'idValue': ['BBG0032FLQC3', 'BBG00JPR0LW9', 'BBG00JPR0LW6']})
df = pd.... |
# Generated by Django 3.2.9 on 2021-11-06 14:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='user',
name='phone',
field=m... |
#!/usr/bin/env python3
import datetime
import io
import json
import subprocess
import sys
import time
from influxdb import InfluxDBClient
from influxdb.exceptions import InfluxDBServerError, InfluxDBClientError
from requests.exceptions import ConnectionError
import yaml
CONFIG_FILE_DEFAULT = "config.yaml"
def epri... |
import logging
import os.path
from typing import Union # noqa
from typing import List, Optional
import strictyaml
from strictyaml import Optional as Opt, EmptyDict
from strictyaml import (Bool, EmptyNone, Enum, Float, Int, Map, Seq, Str,
MapPattern)
from ruamel.yaml.error import YAMLError
fro... |
#
#
# Various constants used by the game.
#
#
# color
BLACK = 0
WHITE = 1
NULL = -1
# list directions
U = (-1, 0)
D = (1, 0)
R = (0, 1)
L = (0, -1)
UL = (-1, -1)
UR = (-1, 1)
DL = (1, -1)
DR = (1, 1)
NDIRECTIONS = [U, D, R, L] # normal
DDIRECTIONS = [UL, UR, DL, DR] # diagonal
# capture types
P = 0
A = 1
W = 2
#... |
import urllib.request
from bs4 import BeautifulSoup
url = 'https://www.google.co.jp'
with urllib.request.urlopen(url) as res:
soup = BeautifulSoup(res.read(), 'html.parser')
print(soup.select('title')[0].text) # `<title>*</title>`
|
# Databricks notebook source
# MAGIC %md
# MAGIC # Orchestrating writing features to Feature Store
# COMMAND ----------
# MAGIC %md
# MAGIC #### Inititialize feature store
# COMMAND ----------
# MAGIC %run ../../mlops/feature_store/feature_store_init
# COMMAND ----------
import datetime as dt
import numpy as np
... |
class Solution:
def maxArea(self, h: List[int]) -> int:
st=res=0
width = en = len(h)-1
for w in range(width,0,-1):
if h[st]<h[en]:
res=max(res,h[st]*w)
st+=1
else:
res=max(res,h[en]*w)
en-=1
retur... |
from Qt import QtCore, QtGui, QtWidgets
from kitsupublisher.utils.connection import open_browser
from kitsupublisher.utils.file import get_icon_file, load_ui_file, get_pixmap_file
class CustomToolBar(QtWidgets.QWidget):
def __init__(self, window):
QtWidgets.QWidget.__init__(self)
self.window = win... |
# coding=utf-8
# Copyright 2021 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 fem import *
class PeriodicBoundary(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and not near(x[0], 1) and not near(x[1], 1)
def map(self, x, y):
if near(x[0], 1):
y[0] = x[0] - 1
else:
y[0] = x[0]
if near(x[1], 1):
y... |
def asending():
a= [6, 8, 4, 3, 9, 56, 0, 34, 7, 15]
i=0
while i<len(a):
j=0
while j<len(a):
if a[i]<a[j]:
a[i],a[j]=a[j],a[i]
j=j+1
i=i+1
print(a)
asending() |
import pytest
from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from openslides.assignments.models import Assignment
from openslides.core.models import ... |
__all__ = ['classes', 'database', 'formatter', 'page_evaluator', 'urltools', 'webserver_stats', 'whois_parser']
|
from .config import Config
from .convert import Convert
from .file import File
from .db import DB
from .search import Search
from .json_manager import JsonManager
|
"""
Low level signal processing utilities
Authors
* Anonymous
"""
import torch
import math
from packaging import version
def compute_amplitude(waveforms, lengths=None, amp_type="avg", scale="linear"):
"""Compute amplitude of a batch of waveforms.
Arguments
---------
waveform : tensor
The wa... |
from os.path import join as jj
from typing import List
from workflow.utility import ensure_path, expand_basenames, expand_target_files, touch, unlink
TEST_DUMMY_FILENAMES = [
'prot-200708--13',
'prot-200001--37',
'prot-198485--141',
'prot-197576--121',
'prot-199697--42',
'prot-1944-höst-fk--28... |
class ConsoleColors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class FileTypes:
ITEMS = "item"
RAW_MATERIALS = "raw-material"
CUSTOMIZAT... |
import tensorflow as tf #2.0.0
import numpy as np
import sys
import json
import os
import re
import datetime
import txt_to_pdf as ttp
#Set Root and Version
ROOT = "."
try:
LSTM_VERSION = int(sys.argv[1])
except:
print("Enter the LSTM version number as a command line argument. Exiting...")
sys.exit()
def v... |
import os
from django.db import models
# Create your models here.
class PathItem:
name = ""
parent = ""
url = ""
def __init__(self, name, parent):
self.name = name
self.parent = parent
self.url = os.path.join(parent, name)
class FileItem:
name = ""
parent = ""
ur... |
# Generated by Django 3.0.7 on 2020-07-27 10:14
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('main', '0016_auto_20200727_1314'),
]
operations = [
migrations.CreateModel(
... |
# Copyright 2020-2022 OpenDR European Project
#
# 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 agree... |
#
# PySNMP MIB module Nortel-MsCarrier-MscPassport-AppnMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-AppnMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:28:57 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# U... |
import csv
import os
from pipes import quote
import subprocess
class InvalidHeaderError(Exception):
pass
def sort_and_merge_gzipped_csv_files(
# CSV files to sort (which may or may not be gzipped)
input_filenames,
# Output file
output_filename,
# Column names to sort by
sort_columns,
):
... |
"""
The main file to run BSDE solver to solve parabolic partial differential equations (PDEs).
"""
import json
import munch
import os
import logging
from absl import app
from absl import flags
from absl import logging as absl_logging
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import e... |
# Dindo Bot
# Copyright (c) 2018 - 2019 AXeL
import json
from .tools import read_file, save_text_to_file, get_full_path
from .shared import DebugLevel, GameVersion
def get_filename():
return get_full_path('settings.json')
def load_defaults():
settings = {
'Debug': {
'Enabled': True,
'Level': DebugLevel.L... |
import numpy as np
import operator
import pinocchio as pin
import pybullet as p
def trajectoryUpAndDown(robot, length=500, dist=0.2, orientation=True):
"""
Generate a trajectory of cartesian coordinates of an up and down movement
:param robot: Robot object
:param length: number of positions
:para... |
# http.py
#
# Copyright 2017 Daniel Mende <mail@c0decafe.de>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# ... |
import datetime
from django.urls import reverse
from django_webtest import WebTest
from employees.views import parse_date
from hours.models import ReportingPeriod
from test_common import ProtectedViewTestCase
class UserViewTests(ProtectedViewTestCase, WebTest):
csrf_checks = False
def setUp(self):
... |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter, Depends, Form
from api.db.models.discussions import update_discussion
from fastapi_cloudauth.firebase import FirebaseClaims
from api.auth.firebase import get_current_user
router = APIRouter()
@router.patch("/{topic}/threads/{th... |
"""
Client connection utilities.
"""
from asyncwebsockets.websocket import Websocket
try:
from contextlib import acontextmanager
except ImportError:
from async_generator import asynccontextmanager as acontextmanager
@acontextmanager
async def open_websocket_server(sock, filter=None): # pylint: disable=W062... |
#!/usr/bin/python
import operator
import argparse
def auto_int(x):
return int(x, 0)
parser = argparse.ArgumentParser()
parser.add_argument("start", help="Start of the ID range", type=auto_int)
parser.add_argument("end", help="End of the ID range", type=auto_int)
parser.add_argument("-e", dest="extended", help="U... |
from mpyc.runtime import mpc
from src.dataset import ObliviousDataset, Sample
from src.output import output
from src.secint import secint as s
from src.forest import train_forest
def sample(ins, out):
return Sample([s(i) for i in ins], s(out))
samples = ObliviousDataset.create(
sample([1, 1, 1, 2], 1),
... |
# -*- coding: utf-8 -*-
"""
SLMtools
=========
Tools for recording, comparing and assessing SLM build parameters
.. moduleauthor:: adlhancock
"""
__all__ = ['scanspeed',
'energydensity',
'BuildSet',
'BuildParameters',
'classes',
'NormalisedEnergyGraph',
... |
import uuid
from django.test import SimpleTestCase
from pillowtop.dao.mock import MockDocumentStore
from pillowtop.feed.couch import change_from_couch_row
from pillowtop.feed.interface import Change
from pillowtop.feed.mock import RandomChangeFeed, MockChangeFeed
from six.moves import range
class TestCouchChange(Simp... |
import numpy
import cv2
class Baron:
pass
|
"""empty message
Revision ID: d960b75824ca
Revises: ba7a57383e3e
Create Date: 2020-05-15 15:28:06.876531
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd960b75824ca'
down_revision = 'ba7a57383e3e'
branch_labels = None
depends_on = None
def upgrade():
# ... |
#Faça um programa em python que abra e reproduza o audio de arquivo MP3.
#tocando arquivo MP3
import pygame
pygame.init()
pygame.mixer.music.load("gaga.mp3")
pygame.mixer.music.play(loops=0, start=0.0)
pygame.event.wait()
input()
|
a={10,20,30,40,50}
b={30,40,50,60,70}
a.intersection_update(b)
print(a) |
# Generated by Django 3.0.6 on 2020-05-18 22:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("main", "0001_initial"),
]
operations = [
migrations.AlterField(
model_name="blog",
name="url",
field=mod... |
from typing import List, Dict
from chia.types.coin_record import CoinRecord
def get_coin_records_map(coin_records: List[CoinRecord]) -> Dict[str, CoinRecord]:
res = {}
for coin_record in coin_records:
res["0x" + coin_record.name.hex()] = coin_record
return res |
lens=[[0,0]]
for sn in range(1000000):
if not sn%10000:
print sn
n=sn
cl=1
while (n>1):
if not n%2:
n/=2
else:
n=3*n+1
cl+=1
if cl>(lens[0][1]):
print str(cl) + " > " + str(lens[0][1])
lens.pop()
lens.append([sn,cl])
print "Cadeia mais longa: " + str(l... |
import os.path
from flask import Flask, render_template, jsonify, request
from pywhale.whale import PyWhale
curr_file = os.path.abspath(os.path.dirname(__file__))
app_path = os.path.join(curr_file)
static_path = os.path.join(curr_file, 'static')
template_path = os.path.join(curr_file, 'templates')
app = Flask("PyWh... |
"""Shows app."""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.