text stringlengths 1 927k |
|---|
# -*- coding:utf-8 -*-
from pyFaceAlign.filereader import ptsReader
import pyFaceAlign.plot as plot
from pyFaceAlign.normalization import kabsch2D
import numpy as np
if __name__ == "__main__":
# 1. read all pts file to create shape model
filereader = ptsReader("./dataset")
landmarks = filereader.read()
... |
from __future__ import annotations
from contextlib import suppress
from typing import (
TYPE_CHECKING,
Callable,
DefaultDict,
Dict,
Iterable,
Iterator,
List,
Optional,
Sequence,
Tuple,
Union,
)
try:
import npe2
from npe2.io_utils import read_get_reader
from npe2... |
# MIT License
#
# Copyright (C) IBM Corporation 2018
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge... |
# 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... |
import json
import os
from aws_cdk import (
# Duration,
Stack,
RemovalPolicy,
aws_dynamodb as dynamodb,
aws_lambda as _lambda,
aws_lambda_event_sources as lambda_events,
# aws_sqs as sqs,
)
from constructs import Construct
import constants
class LambdaFiltersStack(Stack):
def __init_... |
#!/usr/bin/env python
# ===================================
# Copyright (c) Microsoft Corporation. All rights reserved.
# See license.txt for license information.
# ===================================
import socket
import os
import sys
import imp
import hashlib
import codecs
import base64
import platform
import shutil... |
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
slider = [0]*len(grid[0])
slider[0]=grid[0][0]
for i in range(1, len(grid[0])):
slider[i]=slider[i-1]+grid[0][i]
for i in range... |
# Copyright 2018 REMME
#
# 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 writing, softwa... |
import time
import gym
import numpy as np
import torch
import torch.nn.functional as F
from fireup.algos.ddpg import core
from fireup.utils.logx import EpochLogger
class ReplayBuffer:
"""
A simple FIFO experience replay buffer for DDPG agents.
"""
def __init__(self, obs_dim, act_dim, size):
... |
#! /usr/bin/env python3
""" dumps name/value pairs for form fields in PDF """
import pdfrw
ANNOT_KEY = "/Annots"
ANNOT_FIELD_KEY = "/T"
ANNOT_VAL_KEY = "/V"
SUBTYPE_KEY = "/Subtype"
WIDGET_SUBTYPE_KEY = "/Widget"
PDF_NAME = "test.pdf"
template_pdf = pdfrw.PdfReader(PDF_NAME)
for page in range(0, len(template_pdf.pag... |
# coding: utf-8
"""
Pure Storage FlashBlade REST 1.10 Python SDK
Pure Storage FlashBlade REST 1.10 Python SDK, developed by [Pure Storage, Inc](http://www.purestorage.com/). Documentations can be found at [purity-fb.readthedocs.io](http://purity-fb.readthedocs.io/).
OpenAPI spec version: 1.10
Contact... |
"""
Description
===========
A Ducci sequence is a sequence of n-tuples of integers, sometimes known as "the
Diffy game", because it is based on sequences. Given an n-tuple of integers
(a_1, a_2, ... a_n) the next n-tuple in the sequence is formed by taking the
absolute differences of neighboring integers. Ducci sequen... |
import os
import numpy as np
import pandas as pd
from PIL import Image
from matplotlib import pyplot as plt
from scipy.ndimage.measurements import label
def calculate_average_classif_results(results_dict: dict, thresholds, output_file):
avg = pd.DataFrame(columns=["Thr", "TP", "FP", "TN", "FN", "Accuracy", "Conf... |
from cortex import Cortex
class Train():
def __init__(self):
self.c = Cortex(user, debug_mode=True)
self.c.do_prepare_steps()
def train(self,
profile_name,
training_action,
number_of_train):
stream = ['sys']
self.c.sub_request(stream)
profiles = self.c.query_profile()
if profile_name not i... |
import numpy as np
from PIL import Image
from copy import deepcopy
INPUT_SHAPE = (84, 84)
def init_state():
# return np.zeros((84, 84, 4))
return np.zeros((4, 84, 84))
def append_frame(state, frame):
# new_state = deepcopy(state)
# new_state[:, :, :-1] = state[:, :, 1:]
# new_state[:, :, -1] = fr... |
from django.conf import settings as django_settings
from django.utils.functional import LazyObject
from django_comments_tree.conf import defaults as app_settings
class LazySettings(LazyObject):
def _setup(self):
self._wrapped = Settings(app_settings, django_settings)
class Settings(object):
def __i... |
# Copyright (c) 2021, ifitwala and Contributors
# See license.txt
# import frappe
import unittest
class TestPlaidSettings(unittest.TestCase):
pass |
import os
import tempfile
import uuid
from pathlib import Path
import pytest
import requests
import requests_mock
import determined.cli.cli as cli
import determined.cli.command as command
from determined.common import constants, context
from tests.filetree import FileTree
MINIMAL_CONFIG = '{"description": "test"}'
... |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
import base64
import enum
import io
import struct
import dns.enum
import dns.exception
import dns.immutable
import dns.ipv4
import dns.ipv6
import dns.name
import dns.rdata
import dns.tokenizer
import dns.wire
# Until there is an RFC, this m... |
import numpy as np
__all__ = ["binomial"]
def binomial(chr1, chr2):
"""
Picks one allele or the other with 50% success
:type chr1: Sequence
:type chr2: Sequence
"""
if len(chr1) != len(chr2):
raise ValueError("Incompatible chromosome lengths")
choice_mask = np.random.binomial(1, ... |
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
riko.modules.subelement
~~~~~~~~~~~~~~~~~~~~~~~
Provides functions for extracting sub-elements from an item
Sometimes the data you need from a stream is buried deep in its hierarchy. You
need to extract just those select sub-elements from the stream. This is what ... |
import s3Interface
s3Interface.deleteProcedure() |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from readme.models import Item
class Migration(DataMigration):
def forwards(self, orm):
for item in orm.Item.objects.all():
item.s... |
"""Initial Migration
Revision ID: 58556190cb24
Revises: 4a167476d5f7
Create Date: 2021-08-20 12:30:57.334610
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '58556190cb24'
down_revision = '4a167476d5f7'
branch_labels = None
depends_on = None
def upgrade():
... |
# coding: utf-8
"""
Payments
No descripton provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 5.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
yo... |
# Uses python3
import sys
from collections import namedtuple
Segment = namedtuple('Segment', 'start end')
def optimal_points(segments):
points = []
segments = list(map(list, segments))
segments.sort(key=lambda s: s[1], reverse=False)
for i in range(len(segments)):
if (i == 0) or (segments[i]... |
import pytest
from runner import ProjectType
from glotter import project_test, project_fixture
from test.utilities import clean_list
invalid_permutations = (
'description,in_params,expected', [
(
'no input',
None,
'Usage: please provide a list of integers (e.g. "8, 3, 1... |
from unittest import mock
from django.core.exceptions import ValidationError
import pytest
from model_mommy import mommy
import stripe
from rest_framework.reverse import reverse
from restframework_stripe.test import get_mock_resource
from restframework_stripe import models
@mock.patch("stripe.Refund.create")
@pyt... |
from vnpy.trader.constant import Offset, Direction
from vnpy.trader.object import TradeData
from vnpy.trader.engine import BaseEngine
from vnpy.app.algo_trading import AlgoTemplate
class TwapAlgo(AlgoTemplate):
""""""
display_name = "TWAP time weighted average "
default_setting = {
"vt_symbol"... |
"""
Test the about xblock
"""
import datetime
from unittest import mock
from unittest.mock import patch
import ddt
import pytz
from ccx_keys.locator import CCXLocator
from django.conf import settings
from django.test.utils import override_settings
from django.urls import reverse
from milestones.tests.utils import Mi... |
from setuptools import setup, Distribution
from setuptools.command.install import install
from setuptools.command.build_ext import build_ext
from setuptools.extension import Extension
import sys
import subprocess
import os
import glob
import shutil
from ctypes import cdll
_NAME = 'cryptoauthlib'
_DESCRIPTION = 'Pytho... |
# Copyright 2021 The TensorFlow 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 applica... |
# Copyright 2020 The Flax 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 applicable law or agreed to in wri... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 5
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import isi_sdk_8_1_0
from i... |
"""
NOTE:
Avoid using this module on your own or in plugins, this was originally made for 0.9 -> 1.0 transition.
You can safely use task.simple_persistence and manager.persist, if we implement something better we
can replace underlying mechanism in single point (and provide transparent switch).
"""
from __future__ im... |
"""
Module description:
"""
__version__ = '0.3.1'
__author__ = 'Vito Walter Anelli, Claudio Pomo'
__email__ = 'vitowalter.anelli@poliba.it, claudio.pomo@poliba.it'
import importlib
import sys
from os import path
import numpy as np
from hyperopt import Trials, fmin
import elliot.hyperoptimization as ho
from elliot.... |
# Convertendo litros para metro cubico
litros = float(input('Entre com um volume em litros: '))
m_cubicos = litros / 1000
print(m_cubicos) |
# coding: utf-8
"""
Wavefront REST API
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST ... |
"""
Adapt from:
https://github.com/facebookresearch/barlowtwins/blob/main/main.py
"""
import torch
import torch.nn as nn
from transformers import Wav2Vec2Model
from transformers.models.wav2vec2.modeling_wav2vec2 import _compute_mask_indices
def off_diagonal(x):
"""
For the purpose of calculation:
return f... |
__author__ = 'donal'
__project__ = 'ribcage' |
import sqlite3
from util.constants import DATABASE
class DBManager:
def __init__(self):
self.connection = None
self.cursor = None
def connect(self):
self.connection = sqlite3.connect(DATABASE["path"])
self.cursor = self.connection.cursor()
return self
def create_t... |
# Python multiple inheritance examples
class Base1:
# class properties
value = "I am base 1"
# class methods
def __init__(self,val1="I am base 1"):
print("Base 1 Constructor called")
self.value = val1
def display(self):
print("Base 1 display called")
class Base2:
# c... |
from intranet3 import models
class FactoryMixin(object):
# Current state of counter
cid = 1 # Client
uid = 1 # User
pid = 1 # Project
tid = 1 # Tracker
def create_user(
self,
name="",
domain="stxnext.pl",
groups=[],
**kwargs
):
username ... |
from collections import defaultdict
import inspect
import os
import os.path
import unittest
from typing import Dict
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.expected_conditions import presence_of_element_l... |
import logging
import uuid
from functools import partial
from types import FunctionType
from typing import Optional, Type, Union
import ray
import ray.cloudpickle as pickle
from ray.experimental.internal_kv import (
_internal_kv_initialized,
_internal_kv_get,
_internal_kv_put,
)
from ray.tune.error import... |
import logging
import numpy as np
import os, sys, time, re, getopt, getpass, math, tempfile
import traceback,commands
import string, json
from time import strftime
import pexpect
import urlparse
from pylons import request, response, session, app_globals, tmpl_context as c, config, url
from pylons.decorators import jso... |
#YangBot's responses
choiced_responses = {
"dank": "I sure hope you're talking about dank memes and not that dank green!",
"blaze": "I sure hope you're talking about the pizza!",
"alcohol": "Reminder that underage drinking is prohibited at UCSB.", #should only be triggered by gauchito
"mj": "Despite the passing of ... |
# These are the default configuration parameter
default_config_parameters = {
"allroles": {"infra", "infrastructure", "worker", "nfs", "sql", "dev"},
# Kubernetes setting
"service_cluster_ip_range": "10.3.0.0/16",
"pod_ip_range": "10.2.0.0/16",
# Home in server, to aide Kubernete setup
"homeinse... |
from selfdrive.car import dbc_dict
class CAR:
PRIUS = "TOYOTA PRIUS 2017"
RAV4H = "TOYOTA RAV4 HYBRID 2017"
RAV4 = "TOYOTA RAV4 2017"
COROLLA = "TOYOTA COROLLA 2017"
LEXUS_RXH = "LEXUS RX HYBRID 2017"
CHR = "TOYOTA C-HR 2018"
CHRH = "TOYOTA C-HR HYBRID 2018"
CAMRY = "TOYOTA CAMRY 2018"
CAMRYH = "TOYO... |
# from os import path
#
# os.environ['KERNEL_PHENO_PATH'] = path.dirname(path.dirname(__file__)) |
# Generated by Django 3.2.4 on 2021-06-28 11:05
from django.db import migrations, models
import omdb.models
class Migration(migrations.Migration):
dependencies = [
('omdb', '0003_alter_video_year'),
]
operations = [
migrations.AlterField(
model_name='video',
name... |
"""
This file offers the methods to automatically retrieve the graph Bartonella clarridgeiae.
The graph is automatically retrieved from the STRING repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 202... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2017-12-24 05:15
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('backend', '0003_awscredential'),
]
operations = [
... |
from sqlalchemy import *
from migrate import *
from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
the__writer = Table('the__writer', post_meta,
Column('id', Integer, primary_key=True, nullable=False),
Column('id007', String(length=25)),
Column('name', String(length=25)),
)
... |
# Taku Ito
# 03/28/2019
# RNN model training with trial dynamics
import pandas as pd
import torch
import numpy as np
from torch.autograd import Variable
import torch.nn.functional as F
import task
import multiprocessing as mp
import h5py
task = reload(task)
np.set_printoptions(suppress=True)
import time
class RNN(t... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-10-31 12:40
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('search', '0007_auto_20161031_0405'),
]
operations = [
migrations.AlterField(
... |
import serial # Allows you to talk to the Arduino board
# Select port, yours may be different so check the port for your board
usbport = 'COM4'
# create a serial object
ser = serial.Serial(usbport, 9600, timeout=1)
while True:
servo = raw_input("enter servo Nbr (0-3)")
position = raw_input("enter angle b... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.13.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re... |
from django.contrib import admin
from .models import Movie, Rating
admin.site.register(Movie)
admin.site.register(Rating) |
# -*- coding:utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import ast
import math
import os
import time
from paddle.fluid.core import AnalysisConfig, create_paddle_predictor, PaddleTensor
from paddlehub.common.logger import logge... |
# import motor.motor_asyncio
from pymongo import MongoClient
from dotenv import load_dotenv
import os
import pandas as pd
from dagster import solid
def load_env_variables():
"""
Function to load environment variables from .env file
:return: database password and database name
"""
load_dotenv()
... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
# SPDX-FileCopyrightText: Copyright (c) 2021 Pierre Constantineau for jpconstantineau.com
#
# SPDX-License-Identifier: MIT
"""
`pykey`
================================================================================
keyboard hardware drive... |
"""
Created by Joseph Edradan
Github: https://github.com/josephedradan
Date created: 2/15/2021
Purpose:
Details:
Description:
Notes:
IMPORTANT NOTES:
Explanation:
Reference:
Minimum Edit Distance Algorithm in Python in 2020 (EXPLAINED)
Notes:
Using Rylan Fowers' minimum edit distance alg... |
import os
import shutil
import numpy as np
import tensorflow as tf
def path_exists(path, overwrite=False):
if not os.path.isdir(path):
os.mkdir(path)
elif overwrite == True :
shutil.rmtree(path)
return path
def remove_dir(path):
os.rmdir(path)
return True
def relu_init(shape, dtyp... |
import pandas as pd
import pandas_gbq as gbq
import json
from google.oauth2 import service_account
from IPython.core.debugger import set_trace
from pathlib import Path
import time
from . import accounts
'''
Configuration
'''
proj = 'global-news-crawl'
table_downloaded = 'news_dataset.downloaded'
table_trashed = 'news_... |
import torch
from torch import nn
from GlobalAttention import GlobalAttention
from torch.autograd import Variable
from Beam import TreeBeam
from UtilClass import bottle, unbottle
from preprocess import rhs, CDDataset
from decoders import DecoderState, Prediction
import torch.nn.functional as F
class ConcodeDecoder(nn.... |
'Model training for NLP'
from ..torch_core import *
from ..basic_train import *
from ..callbacks import *
from ..basic_data import *
from ..datasets import untar_data
from ..metrics import accuracy
from ..train import GradientClipping
from .models import get_language_model, get_rnn_classifier
__all__ = ['RNNLearner', ... |
# Copyright 2019 D-Wave Systems 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... |
from django.contrib.auth import forms
from django.forms import ModelForm
from .models import User
class UserChangeForm(forms.UserChangeForm):
class Meta(forms.UserChangeForm.Meta):
model = User
class UserCreationForm(forms.UserCreationForm):
class Meta(forms.UserCreationForm.Meta):
model = ... |
from __future__ import unicode_literals
import json
from base64 import b64encode
from datetime import datetime
import time
from moto.core.responses import BaseResponse
from .models import ecr_backends, DEFAULT_REGISTRY_ID
class ECRResponse(BaseResponse):
@property
def ecr_backend(self):
return ecr_ba... |
# Copyright (c) 2017-2019 Cloudify Platform Ltd. 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 ... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: autopilotrpc/autopilot.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import refle... |
# MARK: - Licensing Information
# MIT License
# Copyright © 2022 Wolftail Software, Rachael Ava
# MARK: - Acknowledgements
# Stonehenge ASCII Artwork by lgbeard.
# MARK: - Print Command
print(" .-----------. .------------.\n :`.__________` :`.____________` .-----.._\n ... |
notas = []
def menu():
print("\nSISTEMA DE NOTAS\n")
print("1. Ingresar nota")
print("2. Cambiar nota")
print("3. Ver notas")
print("4. Estado final")
print("5. Salir")
while True:
try:
opcion = int(input("\nOPCION > "))
except:
opcion = -1
i... |
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Dag Wieers (@dagwieers) <dag@wieers.com>
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# pylint: disable=invalid-name,missing-docstring
from __future__ import absolute_import, division, print_function, unicode_literals
import... |
class BinaryHeap(object):
def __init__(self):
self.heap = [0]
self.currentSize = 0
def __repr__(self):
heap = self.heap[1:]
return ' '.join(str(i) for i in heap)
# for shifting the node up
def shiftUp(self, index):
while (index // 2) > 0:
if self.hea... |
import Tkinter, tkFileDialog
import socket
import sys
class Connector:
def __init__(self):
self.connected = False
def connect(self,host,port):
if not self.connected:
try:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
... |
_base_ = [
'../../../../_base_/default_runtime.py',
'../../../../_base_/datasets/ochuman.py'
]
evaluation = dict(interval=10, metric='mAP', save_best='AP')
optimizer = dict(
type='Adam',
lr=5e-4,
)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(
policy='step',
warmup... |
class Handle(dict):
def __init__(self, api, handle, callback):
# derive from dict so instances get auto serialized to JSON when passed as a parameter to an API call
super().__init__(handle=handle, callback=callback)
# however, api is a client-side instance and should not get serialized, s... |
from __future__ import absolute_import
import string
import numpy as np
from pandas import Series, DataFrame, MultiIndex
from shapely.geometry import (
Point, LinearRing, LineString, Polygon, MultiPoint)
from shapely.geometry.collection import GeometryCollection
from shapely.ops import unary_union
from geopandas... |
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
import gevent
try:
import to_bgp
except ImportError:
from schema_transformer import to_bgp
from vnc_api.vnc_api import (RouteTargetList, RouteTable, RouteTableType,
VirtualNetwork, VirtualMachineInterface, NetworkIpam, VnSubnetsType,... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# 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 ... |
"""
base.py
By Paul Malmsten, 2010
Inspired by code written by Amit Synderman and Marco Sangalli
pmalmsten@gmail.com
XBee superclass module
This class defines data and methods common to all XBee modules.
This class should be subclassed in order to provide
series-specific functionality.
"""
from xbee.frame import API... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import namedtuple
import dill
import numpy as np
import pycuda.driver as cuda
from funfact.cuda import context_manager, ManagedArray
class RBFExpansionBasePyCUDA:
def __init__(self):
context_manager.autoinit()
@staticmethod
def as_na... |
from dataclasses import dataclass
from typing import List
from shamrock.consensus.cost_calculator import NPCResult
from shamrock.types.blockchain_format.coin import Coin
from shamrock.types.blockchain_format.program import SerializedProgram
from shamrock.types.blockchain_format.sized_bytes import bytes32
from shamrock... |
# test_multival.py
"""Test suite for MultiValue class"""
# Copyright (c) 2012 Darcy Mason
# This file is part of pydicom, relased under an MIT-style license.
# See the file license.txt included with this distribution, also
# available at http://pydicom.googlecode.com
import unittest
from dicom.multival import Mu... |
##
## The packages.
from selenium import webdriver
import pandas, os, tqdm, time
##
## The arguments.
# keyword = ["Covid-19", "Stroke", "Myocardial Infarction", "influenza", "asthma", "chest cavity"]
keyword = ["chest cavity"]
for k in keyword:
platform = "pubmed"
site = "https://pubmed.ncbi.nlm.nih.go... |
import copy
import os
import os.path as osp
import numpy as np
import torch
import sys
sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
sys.path.append('/opt/ros/kinetic/lib/python2.7/dist-packages')
import cv2
from tqdm import tqdm
import time
from pvrcnn.core import cfg, Preprocessor
from pvrcnn.detect... |
"""
Given a TOML playlist configuration, rips a Widevine DRM-encrypted DASH stream by parsing
the MPD configuration, decrypting audio and video parts individually, then
combining them into a single video file.
"""
import os
import sys
from enum import Enum
from typing import Dict, List, Optional, Union
import requests... |
#! /usr/bin/env python3
from tinkoff.cloud.tts.v1 import tts_pb2_grpc, tts_pb2
from auth import authorization_metadata
from audio import audio_open_write
from common import (
BaseSynthesisParser,
make_channel,
build_synthesis_request,
)
def synthesize():
args = BaseSynthesisParser().parse_args()
if... |
from sys import stdout, stderr
from subprocess import check_call
from os import path, remove
from base64 import b64encode
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat, PrivateFormat, NoEncryption
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.back... |
""" Python 'hex_bytes' Codec - 2-digit hex codec with spaces between bytes.
Unlike most of the other codecs which target Unicode, this codec
will return Python string objects for both encode and decode.
"""
import codecs, binascii
from string import hexdigits
### Codec APIs
def hex_encode(input, errors='stri... |
"""
Crie um algoritmo que leia um número e mostre seu dobro, triplo e raíz quadrada
"""
# importando a função sqrt (raíz quadrada) da biblioteca math
from math import sqrt
n = int(input('Digite um número inteiro: '))
print(f'O dobro de \033[35m{n}\033[m é \033[31m{n * 2}\033[m')
print(f'O triplo de \033[35m{n}\033[m ... |
from bfxhfindicators.indicator import Indicator
from bfxhfindicators.ema import EMA
class MassIndex(Indicator):
def __init__(self, period, cache_size=None):
self._smoothing = period
self._singleEMA = EMA(9, cache_size)
self._doubleEMA = EMA(9, cache_size)
self._buffer = []
super().__init__({
... |
#!/usr/bin/python
"""
Test census2text.py by pulling down data for Knox County, TN and cross checking with API results
usage: test.py
Assumes that census2text can be found in the current working directory.
"""
from os import environ
import json
from urllib2 import urlopen
import re
from sys import argv
from csv impo... |
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
def load_compilado(arquivo):
path = '/home/luiza/UFSM/Myo/myo_project/datasets/oficial/' + arquivo
df = pd.read_csv(path)
return df
df = load_compilado('featu... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Noah Jacob and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import flt, nowdate
import unittest
class TestSalesInvoice(unittest.TestCase):
def test_new_sales_invoice_totals(self):
si = create_sales_invoice('Noah... |
from django.conf.urls import url
from blog.views import BlogDetail, BlogPostDetail, BlogList, BlogUpdate, BlogCreate, BlogPostCreate, BlogPostUpdate, \
BlogPostImageCreate
urlpatterns = [
url(r'^$', BlogList.as_view(), name='blog-list'),
url(r'^add/$', BlogCreate.as_view(), name='blog-create'),
url(r'^... |
import collections
import sqlite3
from collections import defaultdict
from transformers.transformer import Transformer
from openapi_server.models.names import Names
from openapi_server.models.attribute import Attribute
from openapi_server.models.element import Element
from openapi_server.models.connection import Conn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.