text stringlengths 1 927k |
|---|
#
# Copyright (c) 2015 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
from rest_framework import serializers, fields
from rest_framework.reverse import reverse
from pdc.apps.common.models import Arch
from pdc.apps.common.serializers import StrictSerializerMixin, DynamicFieldsSeri... |
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from momochess.routes import create_routes
def create_app():
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/momochess'
db = SQLAlchemy(app)
return create_routes(app) |
"""
Programming for linguists
Interfaces for digits
"""
from typing import Union
from algorithms.calculator.reverse_polish_notation.element import Element
class Digit(Element):
"""
Interface for presenting a digit
"""
def __init__(self, digit_as_string: Union[float, str]):
print(digit_as_st... |
import tensorrt as trt
TRT_LOGGER = trt.Logger(trt.Logger.INTERNAL_ERROR)
def build_engine(onnx_path, shape = [1,224,224,3]):
"""
This is the function to create the TensorRT engine
Args:
onnx_path : Path to onnx_file.
shape : Shape of the input of the ONNX file.
"""
with trt.Builder(TRT_LO... |
"""Algorithms for generating synthetic data"""
from synthesis.synthesizers.marginal import MarginalSynthesizer, UniformSynthesizer
from synthesis.synthesizers.contingency import ContingencySynthesizer
from synthesis.synthesizers.privbayes import PrivBayes, PrivBayesFix
__all__ = [
'MarginalSynthesizer',
'Unif... |
#!/usr/bin/env python3
# Copyright (c) 2017-2018 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 RPC calls related to net.
Tests correspond to code in rpc/net.cpp.
"""
from test_framework.test_... |
from django.db import models
class ContactPage(models.Model):
name = models.CharField(max_length=50, unique=False)
email = models.EmailField()
message = models.CharField(max_length=500)
def __str__(self):
return "{0}'s Message".format(self.name) |
#/usr/bin/env python
# encoding: utf-8
import numpy as np
import sklearn.preprocessing as prep
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
def xavier_init(fan_in, fan_out, constant = 1):
low = -constant * np.sqrt(6.0 / (fan_in + fan_out))
high = constant * np.sqrt(6.0 /... |
import subprocess
import sys
import threading
class SubprocessThread(threading.Thread):
def __init__(
self,
args,
stdin_pipe=subprocess.PIPE,
stdout_pipe=subprocess.PIPE,
stderr_pipe=subprocess.PIPE,
timeout=2,
):
threading.Thread.__init__(self)
... |
_base_ = './fcn_hr18_512x1024_40k_cityscapes.py'
model = dict(
pretrained='open-mmlab://msra/hrnetv2_w48',
backbone=dict(
extra=dict(
stage2=dict(num_channels=(48, 96)),
stage3=dict(num_channels=(48, 96, 192)),
stage4=dict(num_channels=(48, 96, 192, 384)))),
decod... |
# Lint as: python2, python3
# Copyright 2019 Google LLC. 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 req... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
range = getattr(__builtins__, 'xrange', range)
# end of py2 compatability boilerplate
import os
import pytest
import nump... |
class Logger:
__environment = None
def __init__(self):
pass
def set_environment(self, environment: str):
"""
Log into the terminal.
:param environment:
:type environment: str
:return:
"""
self.__environment = environment
def log(self,... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 14 09:53:19 2021
@author: Lakhan Kumawat
"""
import string
import random
symbols=[]
symbols=list(string.ascii_letters)
card1=[0]*5
card2=[0]*5
pos1=random.randint(0,4)
pos2=random.randint(0,4)
#first lets declare same symbol and extract it out
samesymbol=random.choice(sy... |
def get_measure_data(meas_path):
with open(meas_path, 'r') as fs:
# useless lines
fs.readline()
fs.readline()
value = []
while True:
ln = fs.readline()
if ln == '':
break
ln = ln.strip()
column_splitter(value,... |
"""DataSet class for simlated matrix data"""
from pandas import DataFrame
from nudging.dataset.base import BaseDataSet
class MatrixData(BaseDataSet):
"""Class MatrixData"""
@classmethod
def from_data(cls, data, truth=None, names=None, **kwargs):
"""Initialize dataset from numpy arrays.
A... |
"""Functions and Command line Script for classifying hotspots"""
# Standard Inputs
import argparse
import os
import sys
import pickle
# Pip Inputs
import pandas as pd
import numpy as np
from PIL import Image
def square_crop(image, x_pos, y_pos, size=35):
"""Returns a square crop of size centered on (x_pos, y_pos)
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Frappe Technologies and Contributors
# See license.txt
from __future__ import unicode_literals
import unittest
import frappe
from frappe.core.doctype.data_import.importer import Importer
from frappe.utils import getdate, format_duration
doctype_name = 'DocType for Import'... |
from model.account import Account
from taskutils.ndbsharded import ndbshardedmap, futurendbshardedmapwithcount
import logging
# from taskutils.future import twostagefuture
from taskutils.ndbsharded import futurendbshardedpagemap, futurendbshardedmap
def IncrementAccountsWithShardedMapExperiment():
def Go():
... |
import torch
def rel_positions_grid(grid_sizes):
"""Generates a flattened grid of (x,y,...) coordinates in a range of -1 to 1.
sidelen: int
dim: int
"""
tensors = []
for size in grid_sizes:
tensors.append(torch.linspace(-1, 1, steps=size))
# tensors = tuple(dim * [torch.linspace(-1... |
'''
Uses stochastic variational inference (SVI) to scale to larger datasets with limited memory. At each iteration
of the VB algorithm, only a fixed number of random data points are used to update the distribution.
'''
import numpy as np
import logging
import scipy
from gp_classifier_vb import GPClassifierVB, sigm... |
from django.http import HttpResponseRedirect, HttpResponseNotFound, HttpResponse,Http404
from django.urls import reverse
from django.shortcuts import render
from datetime import datetime
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, logout
from openpyxl import load_wor... |
# Copyright 2012 Nicira Networks, 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 requ... |
# Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at
# the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights
# reserved. See files LICENSE and NOTICE for details.
#
# This file is part of CEED, a collection of benchmarks, miniapps, software
# libraries and APIs for efficient h... |
# https://pymotw.com/2/socket/tcp.html
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 11111)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.connect(server_address)
try:
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, Gaurav Naik and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
class TestConsignmentNoteDetail(unittest.TestCase):
pass |
import numpy as np
import datetime as dt
import tensorflow as tf
import os,csv
slim = tf.contrib.slim
def save_statistics(train_writer, episodes_reward_list, episodes_mean_max_q_value_list, episodes_mean_chosen_q_value_list=None, episodes_mean_batch_reward_list=None, episode_mean_action_q_value_list=None,step=1, act... |
'''OpenGL extension OES.read_format
This module customises the behaviour of the
OpenGL.raw.GL.OES.read_format to provide a more
Python-friendly API
Overview (from the spec)
This extension provides the capability to query an OpenGL
implementation for a preferred type and format combination
for use with reading ... |
import sys
from setuptools import setup, find_packages
with open('transitions/version.py') as f:
exec(f.read())
if len(set(('test', 'easy_install')).intersection(sys.argv)) > 0:
import setuptools
tests_require = ['dill', 'pygraphviz']
extra_setuptools_args = {}
if 'setuptools' in sys.modules:
tests_requ... |
from tqdm import tqdm
from time import sleep
for _ in tqdm(range(1500)):
# print('Ilkayyyyyyy')
sleep(.2) |
#!/usr/bin/env python
#
# Copyright (C) 2018 Nippon Telegraph and Telephone Corporation.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import grpc
import sys
import tai_pb2
import tai_pb2_grpc
from optparse import OptionParser
fro... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import multiprocessing
import random
from struct import pack, unpack_from
from av import VideoFrame
from ..mediastreams import VIDEO_CLOCK_RATE, VIDEO_TIME_BASE, convert_timebase
from ._vpx import ffi, lib
DEFAULT_BITRATE = 500000 # 500 kbps
MIN_BITRATE = 250000 # 250 kbps
MAX_BITRATE = 1500000 # 1.5 Mbps
... |
# To find the path on which we are working
import os
cwd = os.getcwd()
print('###cwd###', cwd)
filename = os.path.join(cwd, 'ec2-launch')
# Create the Ec2 instances
import boto3
ec2 = boto3.resource('ec2', region_name = 'us-east-1')
instances = ec2.create_instances(
ImageId='ami-035be7bafff33b6b6',
MinCount=1,... |
from msysutils import msysActive, msysShell
from os import environ
from shlex import split as shsplit
from subprocess import PIPE, Popen
def captureStdout(log, commandLine):
'''Run a command and capture what it writes to stdout.
If the command fails or writes something to stderr, that is logged.
Returns the captur... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ls
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self,*args,**kwargs):
self.write("Hello, world")
def main():
application = tornado.web.Application([
(r"/", MainHandler),
],debug=True... |
import numpy as np
NW = (52.58363, 13.2035)
SE = (52.42755, 13.62648)
NE = (NW[0], SE[1])
SW = (SE[0], NW[1])
def flatten_list(irregularly_nested_list):
"""Generator which recursively flattens list of lists
:param irregularly_nested_list: iterable object containing iterable and non-iterable objects as elemen... |
#!/usr/bin/env python
"""An interactive kernel that talks to frontends over 0MQ."""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from __future__ import print_function
# Standard library imports
i... |
from __future__ import print_function
from benchpress.benchmarks import util
import numpy as np
bench = util.Benchmark("LU decomposition on the matrix so that A = L*U", "<size>")
def lu(a):
"""
Perform LU decomposition on the matrix `a` so that A = L*U
"""
u = a.copy()
l = np.identity(a.shape[0],... |
class Solution:
def eraseOverlapIntervals(self, intervals: list[list[int]]) -> int:
intervals.sort()
n = len(intervals)
left, right = 0, 1
count = 0
while right < n:
if intervals[left][1] <= intervals[right][0]:
left = right
right ... |
from pathlib import Path
import os
from PIL import Image
from tensorflow.python.keras.layers import Conv2D, BatchNormalization, Activation
import logging
logging.getLogger("tensorflow").setLevel(logging.ERROR)
import tensorflow as tf
tf.get_logger().setLevel('ERROR')
import numpy as np
from tensorflow.python.keras.mod... |
import pygame
from random import randint
BLACK = (0,0,0)
import numpy as np
class Ball(pygame.sprite.Sprite):
def __init__(self, color , width ,height, twidth, theight):
super().__init__()
self.image = pygame.Surface([width,height])
self.image.fill(BLACK)
self.image.set_colorkey(... |
import argparse
import glob
import os
import time
import pandas as pd
from tqdm import tqdm
def generate_csv_file(data_dir: str, output_file: str):
"""Generates a csv file containing the image paths of the VGGFace2 dataset for use in triplet selection in
triplet loss training.
Args:
dataroot (st... |
# Generated by Django 2.0 on 2019-06-10 11:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('acheve_mgt', '0018_auto_20190610_1136'),
]
operations = [
migrations.AlterField(
model_name='myclass',
name='dept',
... |
# -*- coding: utf-8 -*-
'''
Provides RAET LaneStack interface for interprocess communications in Salt Raet
to a remote yard, default name for remote is 'manor' .
Usages are for RAETChannels and RAETEvents
This provides a single module global LaneStack to be shared by all users in
the same process. This combines into o... |
# 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 use ... |
import os
from pathlib import Path
import pytest
from flopy.utils import binaryfile as bf
import numpy as np
import fiona
import rasterio
from shapely.geometry import box
import pytest
from ..grid import load_modelgrid
from ..results import export_cell_budget, export_heads, export_drawdown, export_sfr_results
@pytest... |
import sys
import matplotlib.pyplot as plt
from matplotlib import rc
import cPickle
if len(sys.argv) < 2:
print 'Must provide a comma separated list of experiments.'
sys.exit(0)
results_base = 'results-'
root_dir = '../data/experiments/experiment-'
experiment_ids = sys.argv[1].split(',')
data = [
cPickle... |
# Elliptic position is governed by Kepler's equation
#
# M = E - e * sin E
#
# Aux equations for computing position from E assuming an axis aligned orbit.
#
# x = a * ( cos E - e )
#
# y = a * sqrt( 1 - e ^ 2 ) * sin E
#
# For computing M from an orbit.
#
# M = M_0 + ( 2 * pi * t / ... |
"""
Django settings for portal project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
imp... |
from wsgi_kerberos import KerberosAuthMiddleware, ensure_bytestring, _DEFAULT_READ_MAX
from webtest import TestApp, TestRequest
import kerberos
import mock
import unittest
def index(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
response_body = 'Hello %s' % environ.get('R... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from jitcode import jitcode_restricted_lyap, y
import numpy as np
from scipy.stats import sem
a = -0.025794
b1 = 0.01
b2 = 0.01
c = 0.02
k = 0.128
f = [
y(0) * ( a-y(0) ) * ( y(0)-1.0 ) - y(1) + k * (y(2) - y(0)),
b1*y(0) - c*y(1),
y(2) * ( a-y(2) ) * ( y(2)-1.0 )... |
from typing import List
from heapq import heappush, heappop
class Solution:
def minRefuelStopsDP(
self, target: int, startFuel: int, stations: List[List[int]]
) -> int:
dp = [startFuel] + [0] * len(stations)
for i in range(len(stations)):
for t in range(i + 1)[::-1]:
... |
from output.models.saxon_data.missing.missing003_xsd.missing003 import (
Bad,
Good,
)
__all__ = [
"Bad",
"Good",
] |
from pyswagger import SwaggerApp, utils
from pyswagger.spec.v2_0 import objects
from ..utils import get_test_data_folder
import unittest
import os
class ResolvePathItemTestCase(unittest.TestCase):
""" test for PathItem $ref """
@classmethod
def setUpClass(kls):
kls.app = SwaggerApp._create_(get_t... |
"""
Miscellaneous facial features detection implementation
"""
import cv2
import numpy as np
from enum import Enum
class Eyes(Enum):
LEFT = 1
RIGHT = 2
class FacialFeatures:
eye_key_indicies=[
[
# Left eye
# eye lower contour
33,
7,
163,
144,
... |
#!//opt/bin/lv_micropython -i
import time
import lvgl as lv
import display_driver
from imagetools import get_png_info, open_png
# Register PNG image decoder
decoder = lv.img.decoder_create()
decoder.info_cb = get_png_info
decoder.open_cb = open_png
# Create an image from the png file
try:
with open('../assets/img... |
from flask import Flask
from views import main
from views.custom_filters import format_time, format_size, socket_type, socket_family, format_addr_port
app = Flask(__name__)
app.add_template_filter(format_time)
app.add_template_filter(format_size)
app.add_template_filter(socket_type)
app.add_template_filter(socket_fami... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def main():
input_file = './input_2.txt'
with open(input_file, 'r') as ftr:
fishes = list(map(int, ftr.read().strip().split(',')))
for _ in range(80):
for fidx, fish in enumerate(fishes[:]):
if (fish == 0):
fishes[fidx] = 6
fishes.appen... |
"""
this code is modified from pyart.graph.cm file, developed by Helmus, J.J. & Collis, S.M.
https://github.com/ARM-DOE/pyart
==============
Radar related colormaps.
.. autosummary::
:toctree: generated/
revcmap
_reverser
_reverse_cmap_spec
_generate_cmap
Available colormaps, reversed versions ... |
import unittest
from . import *
class HomePageTest(unittest.TestCase):
def test_home_page(self):
pass |
import cv2 # working with, mainly resizing, images
import numpy as np # dealing with arrays
import os # dealing with directories
from random import shuffle # mixing up or currently ordered data that might lead our network astray in training.
path='data'
IMG_SIZE = 96
def crea... |
import time
from collections import deque
import numpy as np
from numpy import product
FILENAME="test4.txt"
if FILENAME=="test.txt":
D=True
else:
D=False
starttime=time.perf_counter()
print("\u001b[2J\u001b[0;0H")
with open(FILENAME,'r') as file:
msg='F'+file.readline()
print(msg[1:])
print(str(bin(in... |
import torch
import torch.nn as nn
from pytorch_pretrained_bert.modeling import BertEncoder, BertPooler, BertLayerNorm, BertPreTrainedModel
class BertEmbeddingsModified(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings.
"""
def __init__(self, config):
super(Bert... |
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and relat... |
from suds.client import Client
from suds import WebFault
class SoapHelper:
def __init__(self, app):
self.app = app
def can_login(self, username, password):
client = Client("http://localhost/mantisbt-1.2.20/api/soap/mantisconnect.php?wsdl")
try:
client.service.mc_login(use... |
from pyldapi.renderer import Renderer
from pyldapi.view import View
from flask import render_template, Response
from rdflib import Graph, URIRef, BNode
import skos
from skos.common_properties import CommonPropertiesMixin
from config import Config
class Method(CommonPropertiesMixin):
def __init__(self, uri):
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
# Export this package's modules as members:
from ._enums import *
from .database_account import *
from .database_account_cassandra_keyspace import *
fr... |
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Hello World\n(cl... |
from django.contrib import admin
from .models import Schedule
admin.site.register(Schedule) |
import struct
from bw_archive.bw_archive import BWArchive
if __name__ == "__main__":
import os
dir = "BattalionWars/BW1/Data/CompoundFiles"
files = os.listdir(dir)
out = "test.res"
sub_sections = [b"RXET", b"PRCS"]
for filename in files:
if not filename.endswith(".res"):
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Manipulate the global config file
"""
import json
import logging
config_file = "/etc/wlanpi-chat-bot/config.json"
logging.basicConfig(level=logging.INFO)
class_logger = logging.getLogger("Config")
class Config(object):
"""
Manipulate the global config file
... |
# -*- coding: utf-8 -*-
"""
@author: Adam Reinhold Von Fisher - https://www.linkedin.com/in/adamrvfisher/
"""
#This is a two asset portfolio/strategy tester with a brute force optimizer, lower max drawdown threshold in optimizer
#Import modules
import numpy as np
import random as rand
import pandas as pd
import tim... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 23 21:30:36 2020
:copyright:
Jared Peacock (jpeacock@usgs.gov)
:license: MIT
"""
# =============================================================================
# Imports
# =============================================================================
from mt_metada... |
# coding: utf-8
"""
validateapi
The validation APIs help you validate data. Check if an E-mail address is real. Check if a domain is real. Check up on an IP address, and even where it is located. All this and much more is available in the validation API. # noqa: E501
OpenAPI spec version: v1
Ge... |
'''
用于检测cuda运算错误
'''
import torch
import torch.nn as nn
from torch.backends import cudnn
import argparse
import time
import math
def ConvBnAct(in_ch, out_ch, ker_sz, stride, pad, act=nn.Identity(), group=1, dilation=1):
return nn.Sequential(nn.Conv2d(in_ch, out_ch, ker_sz, stride, pad, groups=group, bias=False, ... |
# Copyright (c) OpenMMLab. All rights reserved.
import mmcv
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
@mmcv.jit(derivate=True, coderize=True)
def ae_loss_per_image(tl_preds, br_preds, match):
"""Associative Embedding Loss in one image.
Associative Embedd... |
"""
The library contain functions related to NetBackup VM backup functionality.
"""
## The script can be run with Python 3.6 or higher version.
## The script requires 'requests' library to make the API calls.
import common
headers = {"Content-Type" : "application/vnd.netbackup+json;version=4.0"}
# Perform VM backu... |
import re
with open("words.txt", "w") as words_file:
words_file.write(input())
text_file = open("text.txt", "w")
while True:
line = input().lower()
if not line:
break
text_file.write(f"{line}\n")
text_file.close()
# Counting key words:
key_words = {}
with open("words.txt") as reading_words_... |
from setuptools import find_packages
from setuptools import setup
setup(
name='pre-commit-hooks',
description='Some out-of-the-box hooks for pre-commit',
url='https://github.com/Lucas-C/pre-commit-hooks',
version='1.1.9',
author='Lucas Cimon',
author_email='lucas.cimon@gmail.com',
platfor... |
"""Module for serializing ``ase.Atoms``."""
# TODO very recent versions of ase.Atoms have `todict` and `fromdict` methods, ands
# see: https://gitlab.com/ase/ase/atoms.py and
# https://gitlab.com/ase/ase/blob/master/ase/io/jsonio.py
import datetime
import json
import ase
from ase.constraints import dict2constraint
imp... |
#!/usr/local/bin/python3
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
# Setup, and create the data to plot
y = np.random.rand(100000)
y[50000:] *= 2
y[np.geomspace(10, 50000, 400).astype(int)] = -1
mpl.rcParams['path.simplify'] = True
mpl.rcParams['path.simplify_threshold'] = 0.0
plt.p... |
#
#Authors: Owen Levin, Dennis Melamed
#
import numpy as np
from sklearn import neighbors, datasets
import pickle
import glob
import os
import time
import rospy
import pprint
from leap_motion.msg import leapros
from std_msgs.msg import Int32
gesture_class_nums = { "0":0,#
"1":1,#
... |
r"""
Sets of morphisms between free modules
The class :class:`FreeModuleHomset` implements sets of homomorphisms between
two free modules of finite rank over the same commutative ring.
AUTHORS:
- Eric Gourgoulhon, Michal Bejger (2014-2015): initial version
REFERENCES:
- Chaps. 13, 14 of R. Godement : *Algebra*, He... |
# 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... |
track_width = 0.9143985009502611
track_original = [(1.3333835005760193, -2.8131200075149536), (1.183136522769928, -2.8104419708251953),
(1.0328985452651978, -2.8073339462280273), (0.8826694488525391, -2.8037965297698975),
(0.7324512302875519, -2.7998324632644653), (0.5822446346282959... |
# Copyright 2013 IBM Corp.
# 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 app... |
import cv2
import numpy as np
import dlib
import time
import matplotlib.pyplot as plt
from math import hypot,ceil
#cap = cv2.VideoCapture("projectvideo.mp4")
cap = cv2.VideoCapture(0)
liste=[]
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
def mid... |
from django.contrib import admin
from .models import Comment, Follow, Group, Post
admin.site.register(Post)
admin.site.register(Group)
admin.site.register(Comment)
admin.site.register(Follow) |
"""
This file offers the methods to automatically retrieve the graph Gemmatimonadetes bacterium KBS708.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: prote... |
# -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import io
import logging
import os
import re
import sys
from gunicorn._compat import unquote_to_wsgi_str
from gunicorn.six import string_types, binary_type, reraise
from gunicorn import SERVE... |
"""The following script holds the different high level functions for the
different propagators available at poliastro:
+-------------+------------+-----------------+-----------------+
| Propagator | Elliptical | Parabolic | Hyperbolic |
+-------------+------------+-----------------+-----------------+
| fa... |
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class ChallengeConfig(AppConfig):
name = "codershq.challenge"
verbose_name = _("Challenges")
def ready(self):
try:
import codershq.challenge.signals # noqa F401
except ImportError:
... |
"""
Customers endpoint wrapper class
Possible requests:
* get_by_query: get customers that respect passed in query parameters
* get_by_id: get customer with given customer ID
* get_by_email: get customer with given email
* get_by_creation_date: get customers created at specific date
* get_by_creation_dates: get custo... |
#!/usr/bin/python
from __future__ import print_function
import os, sys
from SimpleCV import *
from nose.tools import with_setup
testoutput = "sampleimages/cam.jpg"
def test_virtual_camera_constructor():
mycam = VirtualCamera(testoutput, 'image')
props = mycam.getAllProperties()
for i in props.keys():... |
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
#
# 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, ... |
from typing import Any, Dict, List, Optional
from chinilla.rpc.farmer_rpc_api import PlotInfoRequestData, PlotPathRequestData
from chinilla.rpc.rpc_client import RpcClient
from chinilla.types.blockchain_format.sized_bytes import bytes32
from chinilla.util.misc import dataclass_to_json_dict
class FarmerRpcClient(RpcC... |
import os
import numpy as np
import torch
import torch.utils.data as data
import random
import tqdm
from PIL import Image
class FaceDataset(data.Dataset):
def __init__(self, data_dir, ann_file, transforms=None, augmenter=None,im_info=[112,96]):
assert transforms is not None
self.root = data_dir
... |
from bottle import default_app, route, run, static_file, template, install, request, response, redirect
import bottle
from bottle_sqlite import SQLitePlugin
from datetime import date, datetime, timedelta
import random
import string
from parser import Parser
from functools import wraps
import logging
app=application=de... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.