text stringlengths 2 999k |
|---|
# benchmark_upload.py
# BRL-CAD
#
# Copyright (c) 2007-2012 United States Government as represented by
# the U.S. Army Research Laboratory.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Re... |
"""Train a Resnet model for age classification and gender regression from the imdb dataset."""
#from __future__ import absolute_import
#from __future__ import division
#from __future__ import print_function
import argparse
import os
import sys
import shutil
import glob
import cv2
import numpy as np
import datetime
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
#!/usr/bin/env python
"""This module has new tests for the pvl decoder functions."""
# Copyright 2019, Ross A. Beyer (rbeyer@seti.org)
#
# 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
#
# ... |
from models.todo import Todo
from repositories.todo_repository import todo_repository as default_todo_repository
class TodoService:
def __init__(self, todo_repository=default_todo_repository):
self._todo_repository = todo_repository
def create_todo(self, content, done=False):
return self._tod... |
from django.urls import path
from . import views
app_name = "image_versions"
urlpatterns = [
path("set-focus-point/", views.set_focus_point, name="set_focus_point"),
path("focus-point/", views.focus_point_details, name="focus_point_details"),
]
|
# coding: utf-8
"""
Keras target formatters.
"""
__all__ = ["KerasModelFormatter", "TFKerasModelFormatter"]
from law.target.formatter import Formatter
from law.target.file import get_path
class ModelFormatter(Formatter):
@classmethod
def accepts(cls, path):
return get_path(path).endswith(".h5")
... |
#!/usr/bin/env python
"""Tests of the Enumeration and Alphabet objects.
Note: individual alphabets are typically in MolType and are tested there.
"""
import pickle
from unittest import TestCase, main
from numpy.testing import assert_equal
from cogent3.core.alphabet import (
CharAlphabet,
Enumeration,
Jo... |
# -*- coding: utf-8 -*-
"""The OpenBioLink dataset.
Get a summary with ``python -m pykeen.datasets.openbiolink``
"""
import logging
import click
from .base import PackedZipRemoteDataSet
__all__ = [
'OpenBioLink',
'OpenBioLinkF1',
'OpenBioLinkF2',
'OpenBioLinkLQ',
]
HQ_URL = 'https://samwald.info/... |
""" Provides bracket matching for Q[Plain]TextEdit widgets.
"""
# System library imports
from IPython.external.qt import QtCore, QtGui
class BracketMatcher(QtCore.QObject):
""" Matches square brackets, braces, and parentheses based on cursor
position.
"""
# Protected class variables.
_openin... |
from collections import OrderedDict
from typing import Any, Dict
from ...layers.wrappers.encoder_wrapper import EncoderWrapper
from ...layers.wrappers.time_distributed_with_mask import TimeDistributedWithMask
from ...common.params import pop_choice
from .slot_similarity_tuple_matcher import SlotSimilarityTupleMatcher
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-16 14:50
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('flis_horison_scanning', '0013_auto_20170316_1447'),
]
operations = [
migrati... |
"""
The scipt that contains all the statistical metrics for measuring the result of the fit
Each metric takes at least a pred and truth list with (n_sample, n_dimension) of y pair
"""
import numpy as np
import os
from scipy.stats import spearmanr # Spearman's Rho
from scipy.stats import kendalltau ... |
# 不变的魔术师
def show_magicians(magicians):
for magician in magicians:
print('magician\'s name is ' + magician)
def make_great(magicians):
for item in magicians:
magicians[magicians.index(item)] = 'The Great ' + item
return magicians
magicians = ['singi', 'sunjun']
magicians2 = make_great(... |
"""
=====================
Visual working memory
=====================
"""
from bci_framework.extensions.stimuli_delivery import StimuliAPI
from bci_framework.extensions.stimuli_delivery.utils import keypress
from bci_framework.extensions.stimuli_delivery.utils import Widgets as w
from bci_framework.extensions.stimuli... |
"""
Functions for creating Instrument from description file
"""
import os
import json
import math
import jsonschema
from .instrument import Instrument, Collimator, Detector, Jaws, Script
from .robotics import Link, SerialManipulator
from ..io.reader import read_3d_model
from ..math.constants import VECTOR_EPS, POS_EPS
... |
#!/usr/bin/env python3
# Copyright (c) 2015-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test block processing."""
import copy
import struct
import time
from test_framework.blocktools import ... |
import networkx as nx
import random
import os.path
PREF_ATTACHMENT_GRAPH_FILE = "pref_attachment.p"
GOOGLE_GRAPH_FILE = "web-Google.txt"
GOOGLE_GRAPH_POSTPROCESSED_FILE = "web_google_maxwcc.p"
AMAZON_GRAPH_FILE = "amazon0312.txt"
def generate_pref_attachment_graph(n, r, p, seed=None):
if seed is not None:
... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: caffe2/proto/torch.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from g... |
#!/usr/bin/env python3
import click
import json
def get_conversations(data):
"""Return dict of unique conversation IDs and their participants."""
convos = {}
for conversation in data["conversation_state"]:
conversation_id = conversation["conversation_id"]["id"]
convo_participants = []
... |
async def m001_initial(db):
await db.execute(
"""
CREATE TABLE IF NOT EXISTS bleskomats (
id TEXT PRIMARY KEY,
wallet TEXT NOT NULL,
api_key_id TEXT NOT NULL,
api_key_secret TEXT NOT NULL,
api_key_encoding TEXT NOT NULL,
name T... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
__version__ = "0.1.4"
|
"""
https://github.com/tseemann/prokka
"""
from SNDG import docker_wrap_command, DOCKER_MAPPINGS, execute
class Prokka:
"""
"""
DEFAULT_DOCKER_IMG = "staphb/prokka:latest"
def __init__(self):
pass
def add_spades_data(self, fasta_path, gbk_path):
pass
def annotate(self, fas... |
# Third-party modules
try:
import simplejson as json
except ImportError:
import json
import sqlalchemy
from sqlalchemy.ext import mutable
from sqlalchemy_utils.types.json import JSONType
# Custom modules
from . import track
class NestedMutableDict(mutable.Mutable, track.TrackedDict):
@classmethod
de... |
# Generated by Django 3.1.3 on 2020-11-11 13:34
import core.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0009_board'),
]
operations = [
migrations.Creat... |
#!/usr/bin/env python
#
# BLSTM from EspNet's e2e_asr.py.
#
import argparse
import datetime
import logging
import numpy as np
import chainer
from chainer.backends import cuda
import chainer.functions as F
import chainer.links as L
from chainer import training
from chainer.training import extensions
from testcases.e... |
from pysys.constants import *
from xpybuild.xpybuild_basetest import XpybuildBaseTest
class PySysTest(XpybuildBaseTest):
def execute(self):
self.mkdir('input-files')
for i in range(256+1):
open(self.output+'/input-files/input-%d.txt'%i, 'w').close()
msg = self.xpybuild(shouldFail=False, args=['-n', '-j1'... |
from urllib.request import urlopen
import json
from time import sleep
DUMP1090DATAURL = "http://192.168.1.166:8080/data/aircraft.json"
class FlightData():
def __init__(self, data_url = DUMP1090DATAURL):
self.data_url = data_url
self.refresh()
def refresh(self):
#open the data url
... |
# coding: utf-8
import torch
from torch import nn
import math
import numpy as np
from torch.nn import functional as F
from fairseq.models.fconv import Linear, LinearizedConvolution
def position_encoding_init(n_position, d_pos_vec, position_rate=1.0):
''' Init the sinusoid position encoding table '''
# keep ... |
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import socket
class layer(object):
"""base layer"""
def __init__(self, packet=''):
self.packet = packet
def pack(self):
return self.packet
def __str__(self):
return str(self.pack())
def __repr__(self):
return '<%s>' % self.name
def json(self):
retu... |
# -*- encoding: utf-8 -*-
# Copyright 2017 NEC 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 ... |
import logging
import time
from rq.timeouts import JobTimeoutException
from redash import models, redis_connection, settings, statsd_client
from redash.models.parameterized_query import (
InvalidParameterError,
QueryDetachedFromDataSourceError,
)
from redash.tasks.failure_report import track_failure
from redas... |
import select
import sys
import pybonjour
name = sys.argv[1]
regtype = sys.argv[2]
port = int(sys.argv[3])
def register_callback(sdRef, flags, errorCode, name, regtype, domain):
if errorCode == pybonjour.kDNSServiceErr_NoError:
print 'Registered service:'
print ' name =', name
... |
# Generated by Django 3.2.5 on 2021-11-29 18:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('TravelBooking', '0002_alter_locations_risklevel'),
]
operations = [
migrations.AlterField(
model_name='locations',
n... |
from typing import Union
from mpfmc.core.config_collection import ConfigCollection
class SlideCollection(ConfigCollection):
config_section = 'slides'
collection = 'slides'
class_label = 'SlideConfig'
def process_config(self, config: Union[dict, list]) -> dict:
# config is localized to an sin... |
"""Provides device actions for Homematic(IP) Local."""
from __future__ import annotations
from typing import Any
from hahomematic.const import EVENT_PRESS_LONG, EVENT_PRESS_SHORT
from hahomematic.internal.action import HmAction
import voluptuous as vol
from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CON... |
"""
molecool
A Python package for analyzing and visualizing molecular structures. For NSF bootcamp.
"""
# Add imports here
from .functions import *
from .measure import calculate_distance, calculate_angle
from .molecule import build_bond_list
from .visualize import draw_molecule, bond_histogram
import molecool.io
# ... |
"""Insert a Figure into another (note that the x-axes stay aligned)"""
from vedo import Marker, settings, show, np
from vedo.pyplot import histogram
settings.defaultFont = "Ubuntu"
data = np.random.normal(loc=100, size=1000) + 7
################## Create the first Figure
fig1 = histogram(
data,
bins=20,
... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2021 sqlmap developers (http://sqlmap.org/)
See the file 'LICENSE' for copying permission
"""
from lib.core.enums import DBMS
from lib.core.settings import H2_SYSTEM_DBS
from lib.core.unescaper import unescaper
from plugins.dbms.h2.enumeration import Enumeration
from plugi... |
import obd
def main():
print('Hello World')
'''ports = obd.scan_serial() # return list of valid USB or RF ports
print(ports) # ['/dev/ttyUSB0', '/dev/ttyUSB1']
connection = obd.OBD()
print(connection.status())
while(1):
cmd = obd.commands.RPM
response = con... |
import random
import numpy as np
def uniform_matrix(shape, low=0.0, high=1.0):
"""Generate a uniformly random matrix of the given shape."""
return np.random.uniform(low=low, high=high, size=shape)
def randint_matrix(shape, low=0, high=100):
"""Generate a matrix of random integers of the given shape."""... |
import argparse
from builtins import input
import datetime
import logging
import pprint
import sys
import ee
import openet.ssebop as ssebop
import utils
# from . import utils
def main(ini_path=None, overwrite_flag=False, delay_time=0, gee_key_file=None,
max_ready=-1):
"""Compute monthly Tcorr images fr... |
# MIT License
#
# Copyright (c) 2022 TrigonDev
#
# 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, pu... |
import json
import datetime
import traceback
import re
from base64 import b64encode
from ast import literal_eval
from flask import Blueprint, render_template, render_template_string, make_response, url_for, current_app, request, redirect, jsonify, abort, flash, session
from flask_login import login_required, current_us... |
# -*- coding: utf-8 -*-
"""
Tests against the FIQL regex structures.
"""
from __future__ import unicode_literals
from __future__ import absolute_import
import re
import unittest
from fiql_parser.constants import (
PCT_ENCODING_REGEX, UNRESERVED_REGEX,
FIQL_DELIM_REGEX, COMPARISON_REGEX, SELECTOR_REGEX,
AR... |
"""
See the module-level docstring for implementation details
"""
import os
import re
from functools import wraps
from logging import getLogger
from tempfile import NamedTemporaryFile
from urllib.parse import parse_qsl, urlencode, urljoin, urlparse, urlsplit, urlunsplit
import requests
from celery import group, task
... |
# !/usr/bin/env python3
# -*-coding:utf-8-*-
# @file: cityscapes_loader.py
# @brief:
# @author: Changjiang Cai, ccai1@stevens.edu, caicj5351@gmail.com
# @version: 0.0.1
# @creation date: 25-01-2020
# @last modified: Sun 26 Jan 2020 01:59:45 AM EST
import json
import os
from collections import namedtuple
import zipfile... |
import random
from typing import Optional
import click
from vpype import (
Document,
LayerType,
LineCollection,
global_processor,
multiple_to_layer_ids,
single_to_layer_id,
)
from .cli import cli
__all__ = ("lcopy", "lmove", "ldelete")
@cli.command(group="Layers")
@click.argument("sources"... |
#!/usr/bin/env python
parameter_list=[[10,7,0,False]]
def tests_check_commwordkernel_memleak (num, order, gap, reverse):
import gc
from shogun import Alphabet,StringCharFeatures,StringWordFeatures,DNA
from shogun import SortWordString, MSG_DEBUG
from shogun import CommWordStringKernel, IdentityKernelNormalizer
fr... |
# Train, Evaluate and Save the DL Model
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
import numpy as np
def main():
... |
import os
import time
import torch
import numpy as np
from PIL import Image, ImageDraw
from matplotlib import pyplot as plt
from torch.utils.data import DataLoader, random_split
from data_utils import MyTestDataset, get_test_transforms
from models import Darknet
from utils import non_max_suppression
from conf.setting... |
from __future__ import unicode_literals
from django.conf.urls import url
from .api_views import APICheckedoutDocumentListView, APICheckedoutDocumentView
from .views import (
DocumentCheckInView, DocumentCheckOutDetailView, DocumentCheckOutListView,
DocumentCheckOutView
)
urlpatterns = [
url(
rege... |
import os
import sys
import errno
import inspect
import numpy as np
from collections import OrderedDict
from .mfbase import PackageContainer, ExtFileAction, PackageContainerType
from .mfbase import MFFileMgmt, MFDataException, ReadAsArraysException, \
MFInvalidTransientBlockHeaderException... |
import os
def cp2kSubparser(subparsers):
# --------------------------------------------------------------------------
# CP2K
# --------------------------------------------------------------------------
subparser = subparsers.add_parser("cp2k", help="using cp2k as calculator")
gp = subparse... |
"""Amazon Microsoft SQL Server Module."""
import importlib.util
import logging
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, TypeVar, Union
import boto3
import pandas as pd
import pyarrow as pa
from awswrangler import _data_types
from awswrangler import _databases as _db_utils
from awswra... |
from datetime import datetime
from freezegun import freeze_time
from pytz import UTC
from rest_framework import status
from rest_framework.reverse import reverse
from api.barriers.models import Barrier
from api.collaboration.models import TeamMember
from api.core.test_utils import APITestMixin, create_test_user
from ... |
class animalShelter:
def __init__(self) :
self.cats = []
self.dogs = []
def enqueue(self,animal,type):
if type == "cat":
self.cats.append(animal)
else: self.dogs.append(animal)
def dequeueCat(self):
if len(self.cats) == 0: return None
els... |
from enum import Enum
# Adapted from prompt toolkit https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/prompt_toolkit/keys.py
class Keys(str, Enum):
"""
List of keys for use in key bindings.
Note that this is an "StrEnum", all values can be compared against
strings.
"""
val... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import hashlib
import sys
from pathlib import Path
import requests
import torch as th
import tqdm
from sci... |
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager, PermissionsMixin)
from django.db import models
from django.forms.models import model_to_dict
from django.utils import timezone
from django.utils.translation import pgettext_lazy
from django_countries.fields import Country, CountryField
from... |
import argparse
import numpy
import pyRserve
import sys
def compute_importance(vectors):
conn = pyRserve.connect()
try:
conn.eval('library(\'relaimpo\')', void=True)
conn.eval('df <- data.frame()', void=True)
size = 0
results = {}
for i in range(len(vectors)):
... |
import sys
import os
import piexif
from PIL import Image
def info_extract(filename, in_path):
# load image EXIF data
exif_dict = piexif.load(in_path + filename)
# Check orientation and DateTime EXIF data present
if piexif.ImageIFD.Orientation in exif_dict["0th"]:
orientation = exif_dict["0th"][piexif.Ima... |
# Copyright 2020 The Tekton 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 wr... |
# ORM do SQLAlchemy
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import declarative_base, sessionmaker
engine = create_async_engine('sqlite+aiosqlite:///./db.db')
session = sessionmaker(
engine,
expire_on_commit=True,
... |
#!/usr/bin/env python
# coding: utf-8
# random sequence
# imports
import random
# rand_seq function
def rand_seq(s, N):
''' return a list of N random vectors (tuples) of dimension s '''
rs = []
r = random.random
for i in range(N):
rv = [(r()) for j in range(s)]
rs.append(tuple(rv))
... |
# Copyright 2020 The Tekton 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 wr... |
import numpy as np
import matplotlib.pyplot as plt
# generate measures from gaussian distribution
x = np.arange(0, 10, 1)
# values computed from "measured"
y = np.log(x)
# add some error samples from standard normal distribution
xe = 0.1 * np.abs(np.random.randn(len(y)))
# draw and show errorbar
plt.bar(x, y, yer... |
"""Module test user information reource."""
import json
from unittest import mock
from flask import Response
from .base_test import BaseTestCase, Center, Cohort, Society
from api.utils.marshmallow_schemas import basic_info_schema
def info_mock(status_code, society=None, location=None, cohort=None, data=None):
"... |
from .error import *
from .tokens import *
from .events import *
from .nodes import *
from .loader import *
from .dumper import *
__version__ = '3.12'
try:
from .cyaml import *
__with_libyaml__ = True
except ImportError:
__with_libyaml__ = False
import io
def scan(stream, Loader=Loader):
"""
S... |
# firebird/__init__.py
# Copyright (C) 2005-2012 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from sqlalchemy.dialects.firebird import base, kinterbasdb
base.dialect = kinter... |
import copy, time, traceback, logging
import os
from typing import List
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
from collections import defaultdict
from ..constants import BINARY, MULTICLASS, REGRESSION
from ...utils.loaders import load_pkl
from ...utils.savers import save_pkl
from ... |
"""
Functionalities related to optimization (minimization, inversion), such as the
misfit function and its gradient.
DEPRECATED, will be removed from v1.4.0 onwards.
"""
# Copyright 2018-2021 The emsig community.
#
# This file is part of emg3d.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you ma... |
from pypy.interpreter.baseobjspace import Wrappable
from pypy.interpreter.argument import Arguments, Signature
from pypy.interpreter.gateway import NoneNotWrapped
from pypy.interpreter.gateway import interp2app, unwrap_spec
from pypy.interpreter.typedef import TypeDef, GetSetProperty
from pypy.interpreter.typedef impor... |
# ##################################################################################################
# Copyright (c) 2020. HuiiBuh #
# This file (test_rate_limit.py) is part of AsyncSpotify which is released under MIT. #
# You are not al... |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 Lice... |
# -*- coding: utf-8 -*-
"""
@author zangjinx
@date 2020-12-3
@brief 利用shp裁剪影像,影像需具有坐标信息
"""
import gdal
from osgeo import gdal_array,ogr
import gdalnumeric
from PIL import Image, ImageDraw
import os
import sys
import numpy as np
gdal.UseExceptions()
class Dataset:
def read_img(self, filename):
... |
#!/usr/bin/env python
import argparse
import common.config
import common.args
import time
def main():
"""
Poll Transactions for the active Account
"""
parser = argparse.ArgumentParser()
common.config.add_argument(parser)
parser.add_argument(
'id',
help="The ID of the Transa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Use text editor to edit the script and type in valid Instagram username/password
from InstagramAPI import InstagramAPI
import urllib
video_url = 'https://instagram.fmad3-2.fna.fbcdn.net/t50.2886-16/17157217_1660580944235536_866261046376005632_n.mp4' # a valid... |
from floodsystem.station import MonitoringStation
# import new MonitoringStation class
# -----------------------------------------------------------------------------
# EXERCISE 2B
def stations_level_over_threshold(stations, tol):
"""Returns a list of tuples, each holding i) a station (object) which is
ab... |
import sys
sys.path.append('/usr/users/oliverren/meng/check-worthy')
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Embedding, LSTM, Bidirectional, Dropout, Dense
from keras import Sequential
from src.data import debates
import numpy as np... |
from __future__ import division, print_function, absolute_import
import os
import copy
import numpy as np
from numpy.testing import (assert_equal, assert_almost_equal, run_module_suite,
assert_, dec, assert_allclose, assert_array_equal,
assert_raises)
from scipy.l... |
from collections import OrderedDict
from typing import Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1):
super().__init__()
# all conv layers have strid... |
#!/usr/bin/env python
# Copyright (c) 2013 Caleb Morse
# Released under the MIT license
# http://opensource.org/licenses/mit-license.php
# Repairs dted level 0, avg, min, and max files which are missing file
# headers or have invalid lat/lon origin values
import fnmatch
import os
import shutil
import sys
import optp... |
from .base import BaseTransform
from PIL import Image
import numpy as np
class VFlipTransform(BaseTransform):
"""Class used for creating a vertical flipped copies of images."""
def __init__(self):
"""Constructs an instance of VFlipTransform."""
BaseTransform.__init__(self)
def execute(self... |
#
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
#!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name="django-autologin",
url="https://chris-lamb.co.uk/projects/django-autologin",
version='0.5.1',
description="Token generator and processor to provide automatic login links for users",
author="Chris Lamb",
author_emai... |
from unittest import TestCase
from pya import *
import numpy as np
import logging
logging.basicConfig(level=logging.DEBUG)
class TestUgen(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_sine(self):
sine = Ugen().sine(freq=200, amp=0.5, dur=1.0, sr=44100 // 2, ... |
"""
The Yahoo finance component.
https://github.com/iprak/yahoofinance
"""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Final, Union
from homeassistant.const import CONF_SCAN_INTERVAL
from homeassistant.core import HomeAssistant
from homeassistant.helpers impor... |
demo_list = [1, 'hello', 1.34, True, [1,2,3]]
colors = ['red','green','blue']
#Se tiene que enviar en una tupla,
#ya que list solo acepta 1 parametro
number_list = list((9,8,7,6))
print(type(number_list))
#Genera numeros de x a y
range(50, 69)
#Pon los numeros en una lista
list(range(50, 69))
#Asigna la lista a una v... |
from django.utils.text import slugify
import string
import random
def generate_random_string(N):
res = ''.join(random.choices(string.ascii_uppercase +
string.digits, k = N))
return res
def generate_slug(text):
new_slug = slugify(text)
from home.models import BlogMod... |
# This file is part of the Data Cleaning Library (openclean).
#
# Copyright (C) 2018-2021 New York University.
#
# openclean is released under the Revised BSD License. See file LICENSE for
# full license details.
"""Implementation of stream operators that collect a random sampe of rows from
a data stream.
"""
from ra... |
from typing import List
class Solution:
def max_subarray(self, nums: List[int]) -> int:
current_max = nums[0]
max_so_far = nums[0]
for value in nums[1:]:
current_max = max(value, current_max + value)
max_so_far = max(current_max, max_so_far)
return max_so_... |
#!/usr/bin/env python3
import os
import sys
import argparse
import fiona
import multiprocessing
from shapely.geometry import shape, mapping
from functools import partial
from label_centerlines import get_centerline
def main(args):
parser = argparse.ArgumentParser()
parser.add_argument(
"input_shp",
... |
from abc import ABCMeta, abstractmethod
from xml.etree import ElementTree
from vmaf.tools.decorator import override
__copyright__ = "Copyright 2016-2020, Netflix, Inc."
__license__ = "BSD+Patent"
import re
import numpy as np
import ast
from vmaf import ExternalProgramCaller
from vmaf.core.executor import Executor
f... |
from __future__ import absolute_import, division, print_function
import inspect
import sys
import json
from terraform_validator.RuleDefinition import RuleDefinition
from collections import OrderedDict
from builtins import (str)
def lineno():
"""Returns the current line number in our program."""
return str(' ... |
# GENERATED BY KOMAND SDK - DO NOT EDIT
from .action import GetUserProfile
|
from .EasyTable import EasyTable
|
import os
import open3d
import numpy as np
def get_pcd(pcdpath, filename):
return open3d.read_point_cloud(os.path.join(pcdpath, filename + '.ply'))
def get_keypts(keyptspath, filename):
keypts = np.load(os.path.join(keyptspath, filename + f'.npy'))
return keypts
def get_desc(descpath, filename, desc_n... |
import json
import xml.etree.ElementTree as ET
if __name__=="__main__":
xml = '../input/writers.xml'
root = ET.parse(xml).getroot()
all_writers = root.findall('.//Writer')
writer_gender_mapping = {x.get("name"): 1 if x.get("Gender") == "Male" else 0 for x in all_writers}
with open('writer_gend... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.