content
stringlengths
0
894k
type
stringclasses
2 values
from rest_framework.response import Response from rest_framework.status import HTTP_200_OK, HTTP_500_INTERNAL_SERVER_ERROR, HTTP_201_CREATED, HTTP_404_NOT_FOUND from rest_framework.views import APIView from .custom_exceptions import RecordNotFound from .models import Product from . import util from shared import wra...
python
"""Tooling.""" import redis from django.conf import settings from . import constants def get_redis_connection(): """Return a client connection to Redis server.""" rclient = redis.Redis( host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_QUOTA_DB ) rclient....
python
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'chromium', 'depot_tools/gclient', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', 'recipe_engine/python', ]...
python
import matplotlib # matplotlib.use('Qt5Agg') import copy import glob import os import numpy as np import torch import json import algo from arguments import get_args from model import Policy from storage import RolloutStorage from osim.env import L2RunEnv from torchrunner import TorchRunner args = get_args() asser...
python
# Generated by Django 3.2.5 on 2021-07-15 20:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('recipes', '0006_auto_20210715_1454'), ] operations = [ migrations.AlterField( model_name='recipe', name='name', ...
python
x = input() y = input() z = input() print(int(x) + int(y) + int(z))
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Publish random similar poses to /ardrone/pose. """ from __future__ import division import numpy as np import rospy import tf2_ros from geometry_msgs.msg import PoseStamped, TransformStamped from helpers import Pose class PoseGenerator(object): """ A pose g...
python
import pandas as pd from bert_clf.src.pandas_dataset.PandasDataset import PandasDataset from bert_clf.src.pandas_dataset.SimpleDataFrame import SimpleDataFrame from typing import Dict, Any, List, Tuple, Optional, Union from transformers.tokenization_utils_base import PreTrainedTokenizerBase from bert_clf.src.dataset im...
python
"""Poisson solver to calculate the electron density self-interaction contribution to the potential in the DFT formalism. """ import numpy as np def phi(basis, n, cell=None, fast=True): """Solves the Poisson equation using the given basis and density vector. Args: basis (str): one of the *modules* i...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created: Aug 2017 @author: D34D9001@9R0GR4M13 """ import kerri import math import sys ########################## # MATHEMATICAL FUNCTIONS # ########################## class Math(object): """ This class controls mathimatical opperations. Most of t...
python
from armulator.armv6.opcodes.abstract_opcodes.wfi import Wfi from armulator.armv6.opcodes.opcode import Opcode class WfiT1(Wfi, Opcode): def __init__(self, instruction): Opcode.__init__(self, instruction) Wfi.__init__(self) def is_pc_changing_opcode(self): return False @staticmet...
python
#!/usr/bin/env python3 import unittest from unittest.mock import patch import re from tmc import points from tmc.utils import load, get_out, patch_helper module_name="src.file_listing" file_listing = load(module_name, "file_listing") ph = patch_helper(module_name) @points('p02-02.1') class FileListing(unittest.Test...
python
"""cisco lldp neighbour command output parser """ # ------------------------------------------------------------------------------ from facts_finder.common import remove_domain from facts_finder.common import verifid_output from facts_finder.cisco.common import standardize_if # ----------------------------------...
python
import json import logging import os from pathlib import Path from subprocess import Popen from flask import Flask, redirect from werkzeug.routing import PathConverter my_dir = Path(os.path.abspath(__file__)).parent STATIC_FOLDER = os.path.abspath(str(my_dir / '..' / 'static')) INNER_STATIC_FOLDER = os.path.abspath(s...
python
from django.conf.urls import url import datasets.views as datasets_views urlpatterns = [ url(r'^$', datasets_views.datasets_list), url(r'^reload$', datasets_views.dataset_reload), url(r'^create$', datasets_views.dataset_create), url(r'^delete$', datasets_views.dataset_delete), url(r'^dump$', dataset...
python
import io from unittest import TestCase from followthemoney import model from followthemoney.types import registry from followthemoney.export.graph import NXGraphExporter ENTITIES = [ { 'id': 'person', 'schema': 'Person', 'properties': { 'name': 'Ralph Tester', 'bir...
python
# Generated by Django 3.2.4 on 2021-08-30 13:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0001_initial'), ] operations = [ migrations.AddField( model_name='user', name='teste', field=mod...
python
import base64 import binascii import time from collections import UserDict from datetime import datetime from enum import Enum from functools import wraps from nanolib import ( InvalidSeed, nbase32_to_bytes, bytes_to_nbase32, get_account_id ) from .secret import Secret __all__ = ( "WalletSerializable", "Time...
python
# Authors: Zhaoshuo Li, Xingtong Liu, Francis X. Creighton, Russell H. Taylor, and Mathias Unberath # # Copyright (c) 2020. Johns Hopkins University - All rights reserved. import copy import numpy as np import torch import torch.nn as nn class NestedTensor(object): def __init__(self, left, right, disp=None, s...
python
from talon import Module, app from ..csv_overrides import init_csv_and_watch_changes mod = Module() mod.list("cursorless_scope_type", desc="Supported scope types") # NOTE: Please do not change these dicts. Use the CSVs for customization. # See https://github.com/pokey/cursorless-talon/blob/main/docs/customization....
python
import __main__ __main__.pymol_argv = ['pymol','-qc'] # Pymol: quiet and no GUI from time import sleep import pymol pymol.finish_launching()
python
# Copyright 2013-2021 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
python
#CODE_REVISION(2020/11/2) from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys import MySQLdb import datetime from datetime import datetime from datetime import timedelta from PyQt5.uic import loadUiType ui,_ = loadUiType('library.ui') class MainApp(QMainW...
python
conta = 0 n1 = int(input('primeiro termo :')) n2 = int(input('razão PA :')) print(n1, end=' ') while not conta == 10: conta += 1 n1 += n2 print(n1, end=" ") print('\nse n quiser mostrar mais nada e so digitar 0') pergunta1 = 1 while not pergunta1 == 0: pergunta1 = int(input('\nvc quer mostrar mais quant...
python
import os import pandas as pd def is_sas_table(path): """ Evaluates if a file is a sas table :param path: file to evaluate :return: True if file is a csv, False otherwise """ if path[-9:] == '.sas7bdat': return True return False def get_all_sas_tables(path): """ Returns a...
python
# Meadowlark_LCVR.py qtlab driver for Meadowlark LCVR # Device manual at http://www.zaber.com/wiki/Manuals/T-NM # # Reinier Heeres <reinier@heeres.eu>, 2009 # Umberto Perinetti <umberto.perinetti@gmail.com>, 2009 # # This program is free software; you can redistribute it and/or modify # it under the terms of the...
python
from rtl.tasks.regression import regression from dummy_data import KWARGS, CONTENTS3 def test_linearRegression(): KWARGS = { 'operations': [ { 'x': 'a', 'y': 'b', 'space': 'linear', 'model': 'Linear' }, ] } ...
python
m = float(input('Uma distância em metros: ')) dm = m * 10 cm = m * 100 mm = m * 1000 dam = m / 10 hm = m / 100 km = m / 1000 print('A medida de {}m corresponde a \n{}km, \n{}hm, \n{}dam, \n{:.0f}dm, \n{:.0f}cm, \n{:.0f}mm.'.format(m, km,hm, dam, dm, cm, mm))
python
try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser from InventoryFilter import InventoryFilter class BeakerInventory(InventoryFilter): def get_hostnames(self, topology): hostnames = [] if not ('beaker_res' in topology): return ...
python
import numpy as np def step_gradient_descent(params, grad, alpha): """Single iteration of gradient descent. Args: params (ndarray[1, n]): parameters for current step grad (ndarray[1, n]): gradient for current step alpha (float): learning rate Returns: p...
python
# -*- coding: utf-8 -*- """ Created on Sun Jul 21 10:04:57 2019 @author: Dominic """ import numpy as np from numba import njit, float64, int64 from enum import Enum from ...finutils.FinError import FinError from ...finutils.FinGlobalVariables import gDaysInYear from ...products.equity.FinEquityVanillaOption import ...
python
#!/usr/bin/env python import os from atizer import * from atizer.dbase import * class pyatizer(autoprog): def __init__( self, srcdir=None ): super( pyatizer, self ).__init__( "atizer", srcdir ) self.copyright_holder = "Timothy J. Giese" if len(self.sources) > 0 or len(self.headers) > 0: ...
python
""" 1) Import the random function and generate both a random number between 0 and 1 as well as a random number between 1 and 10. 2) Use the datetime library together with the random number to generate a random, unique value. """ import random from datetime import datetime import time rand_num1 = ra...
python
import datetime import json from django.shortcuts import render, redirect, reverse from django.views.generic import View from stock.models import Stock from stock.module_stock import TradingData from howdimain.utils.min_max import get_min, get_max from howdimain.utils.get_ip import get_client_ip from howdimain.howdimai...
python
import functools import inspect import sys __version__ = "0.1.3" __all__ = "Plugin Injector inject".split() py32 = sys.version_info >= (3, 2, 0) def _makelist(data): if isinstance(data, (tuple, list, set)): return list(data) elif data: return [data] else: return [] class Inject...
python
""" link: https://leetcode.com/problems/jump-game problem: 定义nums为,位于nums[k],可跳到[k-nums[k],k+nums[k]],问第n-1是否可达 solution: 45题的简化版,更新最远距离即可 """ class Solution: def canJump(self, nums: List[int]) -> bool: bound = 0 for i in range(0, len(nums)): if bound < i: return Fal...
python
""" Utilities for dealing with data Borrows from: https://github.com/guillaumegenthial/sequence_tagging """ import numpy as np import tensorflow as tf from collections import OrderedDict # shared global variables UNK = "$UNK$" NUM = "$NUM$" NONE = "o" # special error message class MyIOError(Exception): def __ini...
python
from bs4 import BeautifulSoup import re from urllib.parse import urljoin import os import urllib class HtmlParser(object): def _get_new_urls(self, soup): sets = set() # /view/123.htm #<a target="_blank" href="/item/%E6%9D%8E%C2%B7%E5%A1%94%E7%8E%9B%E9%9C%8D%E7%91%9E/5486870" data-lemmaid="5...
python
from setuptools import setup setup( name = "magpie", author = "Nicholas FitzRoy-Dale", description = "Interface compiler for the L4 microkernel", version = '11', packages = ['magpie'] )
python
import manage_server import sys manage_server.main(sys.argv)
python
import torch import numpy as np from torch.utils.data import Dataset class UNet3DDataset(Dataset): def __init__(self, scans_segs, size= None): self.img_dir = [] for s in scans_segs: # if each image is different sized, we need to get w, h here _, width, height = s[0].shape ...
python
"""Asynchronous Python client for the Geocaching API.""" import asyncio from geocachingapi import GeocachingApi async def main(): """Show example of using the Geocaching API""" async with GeocachingApi() as api: print("test") if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_...
python
from .dynamic import Dynamic from .single_integrator import SingleIntegrator from .double_integrator import DoubleIntegrator from .unicycle import Unicycle from .linear import Linear
python
# see https://www.codewars.com/kata/51e056fe544cf36c410000fb/train/python def top_3_words(text): retDict = {} text = "".join(x if x.isalpha() or x == "'" else " " for x in text) # print(text) for word in text.split(" "): if "".join(x for x in word if x.isalpha()).isalpha(): word = "".join(x for x in ...
python
# # Copyright 2019 Google LLC # # 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 ...
python
# Example preprocessing images for training in my application. # Scenario: # 1. I have the folder with all images, many subjects together # 2. The images are named with some pattern # 3. We know which original name of image matches to which personality # 4. In result, with specify pattern, for example "subjec...
python
__version__ = __import__("paka.cmark", fromlist=["cmark"]).get_version() + "dev" from .func import ( markdown_to_commonmark, markdown_to_html, markdown_to_latex, markdown_to_man, markdown_to_xml, ) from .iter import NodeIter from .node import Node from .parser import MarkdownParser __all__ = [ ...
python
# !/usr/bin/env python # -*- coding: utf-8 -*- ''' CNN+BiGRU @author Sean @last modified 2017.09.06 17:14 ''' import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from torch.autograd import Variable import numpy as np import rando...
python
from flask_admin import Admin from pagetags import login_manager from pagetags.models import db from pagetags.authentication import (load_user, authenticate, identity, payload_handler, request_handler) from pagetags import jwt from pagetags.admin import (UserModelView, Authenticate...
python
import logging logger = logging.getLogger(__name__) from core import Link import glob import serial import time GLOBS = [ '/dev/tty.usb*', '/dev/ttyUSB*' ] def scan( ): """scan all ports, retuns a list of device names.""" r = [ ] for pat in GLOBS: r.extend(glob.glob(pat)) return r def usable_response(re...
python
# Generated by Django 2.1 on 2018-09-16 13:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('demand', '0001_initial'), ] operations = [ migrations.AddField( model_name='demand', name='description', f...
python
VERSION = '0.15.1'
python
import logging import subprocess from os import makedirs, path, remove, symlink from typing import Any, Dict, Optional from tinycert import Session from .interfaces import AbstractModule log = logging.getLogger(__name__) class TinyCert(AbstractModule): def _write_file( self, file_path: str, ...
python
import trimesh import pocketing import matplotlib.pyplot as plt if __name__ == '__main__': # load 2D geometry into polygon object path = trimesh.load('../models/wrench.dxf') polygon = path.polygons_full[0] radius = .125 step = radius * 0.75 toolpath = pocketing.trochoidal.toolpath(polygon, ...
python
import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings.project')
python
from __future__ import absolute_import from typing import Callable, Optional from mypy.nodes import ARG_POS, SymbolTableNode from mypy.plugin import FunctionContext from mypy.types import CallableType from mypy.types import Type as MypyType from returns.contrib.mypy._structures.args import FuncArg from returns.contri...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # s12_clinvar_vep_stat.py # made by Daniel Minseok Kwon # 2020-02-10 15:29:47 ######################### import sys import os SVRNAME = os.uname()[1] if "MBI" in SVRNAME.upper(): sys_path = "/Users/pcaso/bin/python_lib" elif SVRNAME == "T7": sys_path = "/ms1/bin/pyth...
python
# 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 # "License"); you may not u...
python
from django.views.generic import ListView, FormView class BrowseView(ListView, FormView): """ Class Based view for working with changelists. """ def post(self, *args, **kwargs): return self.http_method_not_allowed(*args, **kwargs) def get_form_kwargs(self): kwargs = { ...
python
import unittest import tempfile import os from pathlib import Path from install import UpdateEnvVariablesStage class UpdateEnvVariablesStageTest(unittest.TestCase): def setUp(self) -> None: self.tmp_dir = tempfile.TemporaryDirectory() def create_file(self, path): os.makedirs(os.path.dirname(p...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import logging import sys import os import os.path from pprint import pformat from time import time from shutil import copyfile from urllib.parse import unquote from datetime import datetime from slcli.apis.reseplanerare3_1 import tripapi, journeydetailapi...
python
# -*- coding: utf-8 -*- import re import json import scrapy from locations.items import GeojsonPointItem from locations.hours import OpeningHours class DesignerShoeWarehouseSpider(scrapy.Spider): download_delay = 1 name = "dsw" item_attributes = {"brand": "Designer Shoe Warehouse", "brand_wikidata": "Q52...
python
# -*- encoding: utf-8 -*- import time import json import pandas as pd class Hmm: def __init__(self): self.trans_p = {'S': {}, 'B': {}, 'M': {}, 'E': {}} self.emit_p = {'S': {}, 'B': {}, 'M': {}, 'E': {}} self.start_p = {'S': 0, 'B': 0, 'M': 0, 'E': 0} self.state_num = {'S': 0, 'B':...
python
import time from gpiozero import LED class Light: def __init__(self, pin: int) -> None: self.led = LED(3) def on(self): self.led.on() def off(self): self.led.off() def blink(self, loop_time= 5): for i in range(loop_time): self.led.toggle() time.sl...
python
import sys import logging import os import json from openvino.inference_engine import IECore, IENetwork from OpenVINO_Config import Engine_State, Model_Flag, OpenVINO_Model_Data from OpenVINO_Core import OpenVINO_Core import subprocess from pathlib import Path import yaml import cv2 import time import cpuinfo class Op...
python
import io import os import re from setuptools import setup def read(*paths): with io.open(os.path.join(*paths), encoding="utf_8") as f: return f.read() def find_version(*file_paths): version_file = read(*file_paths) version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, r...
python
from datetime import datetime BASE_URL = 'http://api.stackexchange.com/2.2' COMMON_WRAPPER_FIELDS = frozenset([ ".has_more", ".items", ".quota_max", ".quota_remaining" ]) MAX_PAGE_SIZE = 100 # Limit set by stackexchange API ANSWER_BATCH_SIZE = 100 # Limit set by stackexchange API def augment_api_fi...
python
from .get_span_row_count import get_span_row_count def get_span_char_height(span, row_heights): """ Get the height of a span in the number of newlines it fills. Parameters ---------- span : list of list of int A list of [row, column] pairs that make up the span row_heights : list of i...
python
# -*- coding: utf-8 -*- """ manage ~~~~~~ Manager module """ from flask_script import Manager from flask import json, current_app from flaskproject import app from flaskproject.core import db from flaskproject.users.models import User from flaskproject.entries.models import Entry, EntryCategory from flask...
python
from a2ml.api.utils.provider_runner import ProviderRunner from a2ml.api.utils.show_result import show_result class A2ML(object): """Facade to A2ML providers.""" def __init__(self, ctx, provider = None): super(A2ML, self).__init__() self.ctx = ctx self.runner = ProviderRunner(ctx, prov...
python
from django.contrib import admin from .models import Manager class ManagerAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'email') list_display_links = ('id', 'name') search_fields = ('name',) list_per_page = 25 admin.site.register(Manager, ManagerAdmin)
python
import math import pickle import pandas import operator from misc import * if len(args) < 2: err("for numeric-only col.s of a csv, bin those quantities into modes (if applicable)" + "\n\tcsv_bin [input file.csv]") in_f = args[1] if not exists(in_f): err("could not find input file") # input data: lin...
python
# -*- coding: utf-8 -*- # Copyright 2015 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
python
import os import json import maya.cmds as cmds MAX_SIZE = 2147483647 def proxyObj(proxyName, move=None, proxyBone=None, radius=0.5): # check name is unique newName = proxyName i = 1 while cmds.objExists(newName): newName = proxyName + str(i) i += 1 name = newName ...
python
import InstallMisc class InstallLocalState(InstallMisc.InstallMisc): command_name = 'install_localstate' description = "install modifiable host-specific data" def _get_distribution_filelists(self): return self.distribution.localstate_files
python
from datetime import datetime from sqlalchemy import Boolean, Column, DateTime, Integer, String from sqlalchemy.orm import relationship from app.config import settings from app.db.base_class import Base from app.models.image_config import DockerImageConfig # noqa from app.models.image_relationship import DockerImage...
python
""" bou.backing ~~~ A bit of support code to locate where migrations are. """ import collections import enum import importlib import logging import os import sqlite3 import sys from bou.constants import INPUT, OUTPUT, TYPE from bou import BouError def create(database): """ Create an em...
python
# Noise reduction method # # utilizing "Gradual Release of Sensitive Data under Differential Privacy" # by Fragkiskos Koufogiannis, Shuo Han, and George J. Pappas # Background: # We wish to release a function f of a private database, say D. # The true output is a numpy array M = f(D). # Each entry of M has "sensitivit...
python
"""Template tests.""" import os import pytest from docknv.tests.utils import using_temporary_directory, copy_sample from docknv.utils.ioutils import io_open from docknv.project import Project from docknv.template import ( MissingTemplate, MalformedTemplate, renderer_render_template, ) CONFIG_DATA = "...
python
from typing import Any, List, Literal, TypedDict from .FHIR_code import FHIR_code from .FHIR_decimal import FHIR_decimal from .FHIR_Element import FHIR_Element from .FHIR_string import FHIR_string from .FHIR_uri import FHIR_uri # A duration of time during which an organism (or a process) has existed. FHIR_Age = Typed...
python
import socket import ast import sys ocp- import build import json import time class socketserver: def __init__(self, address='', port=9090): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.address = address self.port = port self.sock.bind((self.address, self.port...
python
from enum import Enum class ChoiceClasses(Enum): logic = 1 if_to_iff = 2 or_to_and = 3 iff_to_if = 4 nothing = 5 negative_literal_premise = 6 atmospheric = 7 ignore_not = 8 anti_atmospheric = 9 not_classified = 10 class PremiseTree: """ Class representing premises a...
python
#!/usr/bin/env python from setuptools import setup import os, sys, codecs try: # nose uses multiprocessing if available. # but setup.py atexit fails if it's loaded too late. # Traceback (most recent call last): # File "...python2.6/atexit.py", line 24, in _run_exitfuncs # func(*targs, **karg...
python
import os import numpy as np import xarray as xr from unittest import TestCase from pathlib import Path import uxarray as ux current_path = Path(os.path.dirname(os.path.realpath(__file__))) class TestGrid(TestCase): def test_read_ugrid_write_exodus(self): """Reads a ugrid file and writes and exodus fi...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from json.decoder import JSONDecodeError import os import pytest from mindmeld.models.helpers import FileBackedList def test_file_backed_list_data(): # test that the file backed list saves and retrieves data properly test_data = [1, 2, 3, {"a": "a"}, ["1", "2", "...
python
from unittest import TestCase from pred.queries.predictionquery import PredictionQuery QUERY_BASE = """SET search_path TO %s,public; select max(common_name) as common_name, string_agg(name, '; ') as name, case WHEN max(value) > abs(min(value)) THEN round(max(value), 4) ELSE round(min(value), 4) end as max_value, m...
python
# coding: utf-8 import os from envparse import env # Try to read an env file with the development # configs env.read_envfile() class Production(object): """ Production configuration """ ENVIRONMENT = "production" SECRET_KEY = env("SECRET") APP_DIR = os.path.abspath(os.path.dirname(__file__)) PR...
python
#!/usr/bin/env python3 import unittest from dabasco.adf.adf_graph import ADF from dabasco.adf.adf_node import ADFNode from dabasco.adf.import_strass import import_adf from dabasco.dbas.dbas_import import import_dbas_graph, import_dbas_user from os import path import logging.config log_file_path = path.join(path.dirn...
python
import argparse import datetime import os from pathlib import Path import stat import subprocess import git from git import Repo import numpy as np from setuptools import sandbox default_log_dir = f"/home/{os.environ['USER']}/logs" if "USER" in os.environ else "/tmp" if default_log_dir == "/tmp": print("CAUTION: ...
python
"""Process the raw DEMoS dataset. This assumes the file structure from the original compressed file: /.../ DEMOS/ NP_*.wav PR_*.wav NEU/ *.wav ... """ from pathlib import Path import click from ertk.dataset import resample_audio, write_annotations, write_filelist emotion_map = {...
python
import numpy as np import cv2 from ..config import config def get_circles(img): final_rectangles = [] cascade = cv2.CascadeClassifier(config['CASCADE']['CascadeFile']) new_img = img.copy() sf = min(640. / new_img.shape[1], 480. / new_img.shape[0]) gray = cv2.resize(new_img, (0, 0), None, sf, sf) ...
python
# @date 2018-08-23 # @author Frederic Scherma, All rights reserved without prejudices. # @license Copyright (c) 2018 Dream Overflow # Websocket connector for bitmex.com import websocket import threading import traceback import ssl from time import sleep import json import decimal from .apikeyauth import generate_nonce...
python
import os from sdc_etl_libs.sdc_data_exchange.SDCDataExchangeEndpoint import SDCDataExchangeEndpoint from sdc_etl_libs.sdc_filetransfer.SFTPFileTransfer import SFTP from sdc_etl_libs.aws_helpers.aws_helpers import AWSHelpers from sdc_etl_libs.sdc_dataframe.Dataframe import Dataframe from sdc_etl_libs.sdc_file_helpers....
python
#!/usr/bin/env python3 from time import time_ns, sleep from threading import Thread from .clock_abstract import ClockAbstract class ClockInternal(ClockAbstract): verbose = False class _Clock(Thread): def __init__(self, bpm: int, callback): Thread.__init__(self) self._bpm ...
python
'''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OT...
python
import sys import time import win32api if (len(sys.argv) < 4): print "Usage: python mousemove.py dx dy speed" sys.exit() current = win32api.GetCursorPos() cx = sx = current[0] cy = sy = current[1] mx = int(sys.argv[1]) my = int(sys.argv[2]) vx = vy = int(sys.argv[3]) print "Moving", mx, my, "with", vx, "pixels pe...
python
import pickle import argparse import numpy as np from vocab import Vocabulary from gensim.models import KeyedVectors def main(opt): vocab = pickle.load(open(opt.vocab_path, 'rb')) num = len(vocab) print (num) model = KeyedVectors.load_word2vec_format(opt.embed_weight, binary=True) matrix_le...
python
def get_template_dict() -> dict: """ Get a template for the level.dat nbt structure. :return: A template for level.dat. """ return { 'allowCommands': 1, 'BorderCenterX': 0, 'BorderCenterZ': 0, 'BorderDamagePerBlock': 0.2, 'BorderSafeZone': 5, 'BorderSize'...
python
""" https://leetcode.com/problems/backspace-string-compare/ Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. Note that after backspacing an empty text, the text will continue empty. Example 1: Input: S = "ab#c", T = "ad#c" Output: true Ex...
python
import pytest from poetry.core.exceptions import PoetryCoreException from poetry.core.toml import TOMLFile from poetry.core.utils._compat import decode def test_old_pyproject_toml_file_deprecation( pyproject_toml, build_system_section, poetry_section ): from poetry.core.utils.toml_file import TomlFile w...
python