content stringlengths 5 1.05M |
|---|
import numpy as np
from randnn.topologies import dilute_connectivity
from .gaussian_nn import GaussianNN
class SparseRandNN(GaussianNN):
def __init__(self,
sparsity: float = 0.,
normalize_strength: bool = False,
**kwargs) -> None:
"""
TODO: Do I... |
#!/usr/bin/python3
from application import db
from application.models import Questions, Employees, Answers
db.session.remove()
db.drop_all()
db.create_all()
question1 = Questions(question='When I am working, I think about nothing else.')
question2 = Questions(question='I get carried away by my work.')
question3 = Qu... |
import functools
import time
from typing import Optional
def on_interval(seconds: int): # in seconds
def wrapper(fn):
_last_called_time: Optional[float] = None
@functools.wraps(fn)
def inner(*args, **kwargs):
nonlocal _last_called_time
now = time.time()
... |
import itertools
def main():
all_words = set()
test_word = 'dontaskmofoskatepunk'
ceiling = len(test_word) + 1
words = load_dictionary(ceiling)
for i in range(2, ceiling):
valid_words = None
valid_words = check_word(words, test_word, i)
if valid_words:
all_words ... |
# SORTA_SUM
def sorta_sum(a, b):
return a+b if(a+b<10 or a+b>19) else 20 |
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
def run_cnn():
mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)
learning_rate = 0.0001
epochs = 10
batch_size = 50
x = tf.placeholder(tf.float32, [None, 784])
x_shaped = tf.resha... |
from django.test import TestCase
from django.shortcuts import reverse
from users.models import User
from unittest import mock
class MockResponse:
def __init__(self, json_data, status_code, content=None):
self.json_data = json_data
self.status_code = status_code
self.content = content
... |
# -*- encoding:utf-8 -*-
# Copyright (c) Alibaba, Inc. and its affiliates.
import json
import logging
import sys
import tensorflow as tf
from google.protobuf import text_format
from easy_rec.python.protos.dataset_pb2 import DatasetConfig
from easy_rec.python.protos.feature_config_pb2 import FeatureConfig
from easy_re... |
#!/usr/bin/python
# coding: utf-8 -*-
#
# Copyright 2021 Arista Networks Thomas Grimonet
#
# 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
#
... |
# runTurbSim.py
# 2013 12 17
# TurbSim model - called by ???
# Runs TurbSim
# - does not use OpenMDAO
"""
This module is a simple wrapper for `TurbSim <https://wind.nrel.gov/designcodes/preprocessors/turbsim/>`_
"""
import sys, os
import numpy as np
import subprocess
import platform
import random
class runTurbS... |
"""
Config Reader:
This module is used to read JSON config file populated by Azure Notebooks API.
"""
import json
class ConfigReader:
def read_config_values(filePath):
with open(filePath) as json_file:
if json_file:
json_config = json.load(json_file)
return (json... |
# -*- coding: utf-8 -*-
class trainTag:
trainSents = [] # sentences array
sentsNum = 0 # sentences num
wordNum = 0 # words num
wordPosFreq = {} # wordPosFreq[word] = {pos1:fre1,pos2:fre2}. word and its pos:frequency
posFreq = {} # posFreq[pos] = fre.... |
import numpy as np
from feats import get_mfcc
from getlist import get_list
def get_data(dirname):
wavlist, train, test = get_list(dirname)
train, test = sorted(train), sorted(test)
train_data = [get_mfcc(name) for name in train]
test_data = [get_mfcc(name) for name in test]
label = np.ar... |
#!/usr/bin/python
import os, sys # low level handling, such as command line stuff
import string # string methods available
import re # regular expressions
import getopt # comand line argument handling
from low import * # custom functions, written by myself
from Bio import SeqIO # biopython stuff, to parse fa... |
#
# Copyright 2017 The E2C 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 applicable l... |
res_x = 25
res_y = 6
layers = []
min_num_zeroes = None
min_ix = -1
ix = -1
with open("input", "r") as img_file:
eof = False
while not eof:
layer = img_file.read(res_x * res_y)
if layer is None or not layer.strip():
eof = True
else:
layers.append(layer)
... |
# alias common names
from sqlalchemy import UniqueConstraint, orm
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.ext.hybrid import hybrid_method, hybrid_property
from backend.extensions import db
from backend.magic import Bundle
from ... |
"""Utility functions for dealing with various parts of the library.
E.g. creating SAML client, creating user, exception handling, etc.
"""
import logging
import base64
from functools import wraps
from typing import Any, Callable, Iterable, Mapping, Optional, Tuple, Union
from django.http import HttpRequest, HttpRespo... |
from datetime import datetime
from lxml import etree
import iso8601
import pytz
import xml2json
from corehq.apps.tzmigration.api import phone_timezones_should_be_processed
from corehq.form_processor.interfaces.processor import XFormQuestionValueIterator
from corehq.form_processor.models import Attachment
from corehq.... |
# Copyright (c) Shopkick 2017
# See LICENSE for details.
from __future__ import absolute_import, division, print_function
import setuptools
with open('README.rst') as fp:
long_description = fp.read()
setuptools.setup(
name='seashore',
maintainer='Shopkick',
maintainer_email='dev@shopkick.com',
ur... |
import argparse
import math
parser = argparse.ArgumentParser(description='Calculate annuity or differentiated payments and related quantities.')
parser.add_argument('--type', help='diff for differentiated and annuity for annuity')
parser.add_argument('--principal', type=float, help='principal loan amount')
parser.add_... |
from fastapi import HTTPException
from fastapi.responses import PlainTextResponse, JSONResponse
import databases
import string
import json
from .main import app
from .config import METABOTNIK_DATABASE
DATABASE_URL = f"sqlite:///{METABOTNIK_DATABASE}"
metabotnik_database = databases.Database(DATABASE_URL)
def escape... |
import asyncio
import configparser
import json
import os
import time
import pathlib
from concurrent.futures import ThreadPoolExecutor
from os.path import join, dirname
import aiohttp
from memepack_builder import JEPackBuilder, BEPackBuilder, ModuleChecker
from aiohttp import web
app = web.Application()
executor = Th... |
# Generated by Django 2.2.9 on 2019-12-24 22:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('picker', '0011_team_notes'),
]
operations = [
migrations.CreateModel(
name='GameSetPicks',
fields=[
],
... |
# coding: utf-8
from flask import url_for, current_app
from .base import BaseTestCase
from . import utils
class FooterTestCase(BaseTestCase):
def test_collection_open_access_home(self):
"""
Testa se os links e o conteúdo da licença esta de acordo com a licença
cadastrada na coleção.
... |
from __future__ import division
import math
import numpy as np
import pyviennacl as p
import scipy.sparse.linalg as spspla
from _common import *
from itertools import product
size, sparsity = 20, 0.1
if double_support:
dtype_tolerances = [('float32', 1.0E-3), ('float64', 1.0E-8)]
else:
dtype_tolerances = [('... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
#
# Copyright (C) 2021 Graz University of Technology.
#
# Invenio-Records-Marc21 is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""Routes for general pages provided by Inveni... |
import pytest
import random
import string
def random_string(string_length=15):
letters = string.ascii_letters
return ''.join(random.choice(letters) for _ in range(string_length))
@pytest.fixture
def vk_sid():
return random_string()
class MockResponseGET:
@staticmethod
def json():
asser... |
"""
Motion sensor data logger for BBC micro:bits.
This is sample code from Stephen Simmons' PyCon UK 2016 talk
"Where am? What am I doing? Motion Sensor Data Fusion with Python".
With one micro:bit:
- stream sensor data as csv strings to host computer via USB [mode='log']
Format is: "Time,AccX,AccY,AccZ,MagX,Ma... |
"""LaneStateMachine keeps track of where the car drives.
See :mod:`simulation.src.simulation_evaluation.src.state_machine.states.lane`
for implementation details of the states used in this StateMachine.
"""
from typing import Callable
from simulation.src.simulation_evaluation.src.state_machine.states.lane import (
... |
# Check to see if the characters from first string can be rearranged
# to form the second string.
def scramble(s1, s2):
for letter in set(s2):
if s1.count(letter) < s2.count(letter):
return False
return True
if __name__ == "__main__":
print(scramble('rkqodlw', 'world'))
print(scram... |
#! /usr/bin/env python
# coding=utf-8
# =======================================================================
#
# Copyright (C) 2018, Hisilicon Technologies Co., Ltd. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following... |
from __future__ import print_function
import os
from skimage.transform import resize
from skimage.io import imsave
import numpy as np
from scipy import ndimage
img_rows_orig = 600
img_cols_orig = 800
def crop_resize(img, cols, rows, Resize=False):
"""
Crop the center 400 pixels in the x direction,
and th... |
#!/usr/bin/env python2
"""
braces.py - Implementation of {andy,bob}@example.com
NOTE: bash implements brace expansion in the braces.c file (835 lines). It
uses goto!
Possible optimization flags for Compound:
- has Lit_LBrace, LitRBrace -- set during word_parse phase
- it if has both, then do _BraceDetect
- has Bra... |
###############################################################################
###############################################################################
## ##
## _____ ___ ___ ___ _____ __ __ ##
... |
# Copyright 2018 U.C. Berkeley RISE Lab
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... |
from public import * # noqa
def init():
array = []
base_url = "https://www.proxmox.com/downloads"
mirror_url = "http://download.proxmox.com/iso"
html = bs(requests.get(base_url).text, "html.parser")
for filename in html.find_all("a", {"class": "element-download-type-iso"... |
# coding:utf-8
import numpy as np
import tensorflow as tf
from sklearn.datasets import load_iris, load_digits
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
'''
author: heucoder
email: 812860165@qq.com
date: 2019.6.13
'''
def reset_graph(seed=42):
'''
reset deafault graph
:param see... |
import inspect
from stepist.flow.steps.next_step import call_next_step
from stairs.core.session.project_session import get_project
from stairs.core.utils import signals
from stairs.core import app_components
from stairs.core.pipeline import data_pipeline
class PipelineInfo:
"""
User interface for pipeline... |
# coding=utf8
import unittest
from borax.patterns.proxy import Proxy
class MockPoint(object):
def __init__(self, x, y):
self.x = x
self.y = y
def get_distance(self):
return self.x ** 2 + self.y ** 2
class ProxyTestCase(unittest.TestCase):
def test_proxy(self):
proxy = ... |
#import cal
# from cal import add
# from cal import sub
#from cal import * # 不推荐
# def add(x,y):
# return x+y+100
#from cal import * # 不推荐
# print(add(3,6))
# print(add(3,5))
# print(sub(3,5))
# from my_module import cal
#
# import xxxx
# print(cal.add(1,3))
from my_module import main
def looger():
pas... |
"""
Description: remove_bg_api example
Author: Anodev (OPHoperHPO)[https://github.com/OPHoperHPO]
License: MIT
"""
from remove_bg_api import RemoveBg
from config import API_TOKEN
def main():
"""
Shows full account information.
"""
removebg = RemoveBg(API_TOKEN) # Initialize api wrapper
info = remo... |
# coding: utf-8
# # Data Preprocessing
# This notebook is used to clean, reduce, transform, integrate and discretize the final data set.
# In[1]:
import pandas as pd
import numpy as np
from math import sin, cos, sqrt, atan2, radians
import pickle
# ## Methods
# In[2]:
def discretizeTime(time):
'''
fu... |
from __future__ import absolute_import, division, print_function, unicode_literals
import imp
import numpy as np
import os
import warnings
from mirnylib.h5dict import h5dict
from os.path import join, exists
from os import listdir
import re
from mirnylib.systemutils import setExceptionHook
from hiclib.hicShared import f... |
# Generated by Django 2.0.6 on 2018-10-05 16:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('marketplace', '0076_auto_20181002_1702'),
]
operations = [
migrations.AlterField(
model_name='projecttask',
name='ty... |
"""
Sage Intacct Dimensions
"""
from typing import Dict
from .api_base import ApiBase
class Dimensions(ApiBase):
"""Get all the Dimension from Sage Intact
Returns:
List of Dict of dimensions
"""
def get_all(self):
data = {
'getDimensions': {}
}
return self... |
from __future__ import print_function
from flask_qrcode import QRcode
import re
import pandas as pd
import gspread
import os
from oauth2client.service_account import ServiceAccountCredentials
import uuid
from flask_sqlalchemy import SQLAlchemy
from flask_sessionstore import Session
from flask_session_captcha import ... |
import spacy
# 读取en_core_web_md模型
nlp = ____
# 处理文本
doc = nlp("Two bananas in pyjamas")
# 获取词符"bananas"的向量
bananas_vector = ____.____
print(bananas_vector)
|
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.spm.model import ThresholdStatistics
def test_ThresholdStatistics_inputs():
input_map = dict(contrast_index=dict(mandatory=True,
),
extent_threshold=dict(usedefault=True,
),
height_t... |
import socket
import random
import sys
import time
import json
import os
import re
from datetime import datetime
from collections import defaultdict
msgsPerMinute = {}
msgsPerMinute = defaultdict(int)
# --------------------------------------------- Start Settings -----------------------------------------... |
#!/usr/bin/env python
from setuptools import setup, find_packages
from distutils.core import Extension
with open('skrf/__init__.py') as fid:
for line in fid:
if line.startswith('__version__'):
VERSION = line.strip().split()[-1][1:-1]
break
LONG_DESCRIPTION = """
sckit-rf is an o... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import os
import matplotlib.pyplot as plt
import numpy as np
import torch
from nuscenes.nuscenes import NuScenes
from custom_lidar_api import CustomLidarApi
from custom_map_api_expansion import CustomNuScenesMap
plt.style.use('seaborn-bright')
class NusceneDataHelper():
def __init__(self, version,
... |
import pytest
from galaxy.api.types import Achievement
OSU = 'osu!'
@pytest.mark.asyncio
async def test_achievements_no_achievements(api_mock, plugin):
api_mock.get_me.return_value = {}
context = await plugin.prepare_achievements_context([OSU])
await plugin.get_unlocked_achievements(OSU, context) == [... |
from sys import stdin
stdin = open("input.txt", "r")
a = sorted([int(v) for v in stdin.readlines()])
a.append(a[-1] + 3)
a.insert(0, 0)
dp = [0] * len(a)
dp[0] = 1
for idx in range(len(a)):
for idx2 in range(max(idx - 3, 0), idx):
diff = a[idx] - a[idx2]
if 0 < diff and diff <= 3:
dp[i... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import panel as pn
pn.extension("katex", "mathjax")
# ## Lecture 3- Groundwater as a reservoir ##
#
# _(The contents presented in this section were re-developed principally by [Prof. Peter Dietr... |
import pytest
from _wheel2deb.pyvers import Version, VersionRange
def test_python_version():
v2 = Version.from_str("2")
v36 = Version.from_str("3.6")
v37 = v36.inc()
assert v2.minor == 0
assert v36.major == 3 and v36.minor == 6
assert str(v36) == "3.6"
assert str(v2) == "2.0"
assert v... |
#coding:utf-8
#
# id: functional.basic.db.15
# title: Empty DB - RDB$INDEX_SEGMENTS
# decription:
# Check for correct content of RDB$INDEX_SEGMENTS in empty database.
# Checked on:
# 2.5.9.27126: OK, 0.531s.
# 3.0.5.3308... |
real = float(input('Digite o quantos reais você tem: R$'))
dolar = real / 5.60
print('Com R${:.2f} você consegue comprar US${:.2f}. '.format(real, dolar))
|
import math
import sys
sys.path.append('../')
from mlab_tools.animation import Animation, StopAnimation
from mlab_tools.polyline import AnimatedPolyLine
from mlab_tools.polyhedron import Polyhedron
from mlab_tools.point import Point
class HelixInDetector(Animation):
"""A more complex animation that shows a ... |
name = "ilmbase"
version = "2.2.0"
description = \
"""
IlmBase
"""
variants = [
["platform-linux"]
]
requires = [
"python-2.7",
"boost-1.54+"
]
def commands():
env.PATH.append("{root}/bin")
env.LD_LIBRARY_PATH.append("{root}/lib")
env.PYTHONPATH.append("{root}/lib/python2.7/site... |
from discord.ext.commands import Cog
from discord.ext.commands import command
class Ping(Cog):
def __init__(self, bot):
self.bot = bot
# ctx is a context ctx.send == ctx.channel.send
@command(name="ping")
async def ping(self, ctx):
await ctx.send("pong! {0:.2f}ms".format(self.b... |
from flask import Flask, render_template, jsonify
from flask_bootstrap import Bootstrap
from datetime import datetime, timedelta
from flask_moment import Moment
import os
from flask import Flask, request
from flask import Flask,redirect
app = Flask(__name__)
moment = Moment(app)
bootstrap = Bootstrap(app)
@app.erro... |
# -*- coding: utf-8 -*-
"""
/dms/eventitem/views_show.py
.. zeigt den Inhalt eines Termins an
Django content Management System
Hans Rauch
hans.rauch@gmx.net
Die Programme des dms-Systems koennen frei genutzt und den spezifischen
Beduerfnissen entsprechend angepasst werden.
0.01 04.06.2007 Beginn der Arbe... |
from pathlib import Path
import pandas as pd
from shapely.geometry import Point
from gisutils import df2shp, project, get_values_at_points
from mfsetup.units import convert_length_units, convert_volume_units
from mapgwm.utils import cull_data_to_active_area
def read_te_water_use_spreadsheet(xlsx_file, date='2010', ... |
from contact_form import *
from contact_controller import *
|
"""
Read wheel forging config
"""
from __future__ import absolute_import
try:
from collections import OrderedDict
except:
from ordereddict import OrderedDict
import yaml
from six import iteritems
DEFAULT_C_IMAGESET = 'default-wheel'
DEFAULT_PUREPY_IMAGESET = 'purepy-wheel'
DEFAULT_CONFIG_FILE = 'wheels.yml'... |
import cv2
import os
from math import sin, cos, radians
import ctypes
import time
import pygame
black = (255,255,255)
ix = 960
iy = 960
scl=1600
scb=900
ge = None
eye = None
kb = None
usage=""" python yuriblush.py <options>
--blush-file <filename> : file of image to show when blushing
--eyes-f... |
import sys
from subprocess import call
def main():
"""
Platform agnostic wrapper script for towncrier.
Fixes the issue (#7251) where windows users are unable to natively run tox -e docs to build pytest docs.
"""
with open("doc/en/_changelog_towncrier_draft.rst", "w") as draft_file:
return ... |
def solve():
n = int(input())
total = set()
for i in range(n):
email = input()
at = 0
for i in range(len(email)):
if email[i] == '@':
at = i
new = str()
plus_flag = False
for i in range(len(email)):
if email[i] == '+':
plus_flag = True
elif i < at... |
#!/usr/bin/env python
from setuptools import setup
setup(
name='progress_tracker',
version='1.0.0',
description='A utility that wraps an Iterable and regularly prints out progress on the processing of that Iterable',
long_description="A utility that wraps an Iterable and regularly prints out progress o... |
"""
Ax_Metrics - Test servant package
------------------------------------------------------------------------------
Author: Dan Kamins <dos at axonchisel dot net>
Copyright (c) 2014 Dan Kamins, AxonChisel.net
"""
# ----------------------------------------------------------------------------
import pytest
import l... |
# Before we do anything else, get some default settings built into Arkestra.
# They are not just Arkestra settings, but settings for other applications
# that Arkestra requires to be just so.
from arkestra_utilities.settings import *
# These are the only settings you really need.
# If you need to modify other aspect... |
"""
AWS Lambda function.
Need to review this code. It's ugly.... :(
"""
from cwexporter import generate_metrics_data, generate_metrics_querys, listmetrics, formater
import json, base64
def lambda_handler(event, context):
if 'path' in event:
if 'proxy' in event['resource']:
p=event['path'].s... |
#!/usr/bin/env python
###############################################################################
#
# $Id$
#
# This file contains constants used in several enstore modules.
#
###############################################################################
DEFAULT_CONF_FILE = "/pnfs/enstore/.(config)(flags)/enstore... |
# Copyright (c) 2012 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.
"""Mock pref pane for testing purpose on Mac."""
import Foundation
import os
import signal
import subprocess
import sys
import tempfile
import time
cl... |
from data_access.data_config import TRIAL_CONFIG_TABLE, SURVEY_COMPLETION_TABLE, LOG_LEVEL, parse_date_from_str, \
format_date_to_str, OUTREACH_WORKFLOW
from data_access.ddb_util import get_item_ddb, DDBUpdateBuilder, scan_item_ddb
from data_access import user_profile
from data_access.survey_completion import initi... |
# Copyright 2020 MIT Probabilistic Computing Project.
# See LICENSE.txt
from fractions import Fraction
from math import log
import pytest
import numpy
from sppl.distributions import choice
from sppl.distributions import gamma
from sppl.distributions import norm
from sppl.math_util import allclose
from sppl.math_uti... |
a=[-1,1,9,2,8,3,7,4,5,6,0,12]
n= len(a)
for i in range(n-1):
for j in range(n-i-1):
if a[j+1]<a[j]:
a[j+1],a[j]=a[j],a[j+1]
print(a) |
import os
import json
from compas_ags.diagrams import FormDiagram
from compas_ags.diagrams import ForceDiagram
from compas_ags.ags import graphstatics
from compas_ags.viewers import Viewer
HERE = os.path.dirname(__file__)
FILE = os.path.join(HERE, '../data/forms/howe_modified.ags')
with open(FILE, 'r') as f:
dat... |
import sys, os, psycopg2, mysql.connector
def get_db_interface(config):
if not config.no_password:
if not config.password_file:
print('please provide a password file using --password-file')
sys.exit(1)
try:
f = open(config.password_file, 'r')
line = ... |
from django import forms
from .models import Course_Registration,Student_Registration
class CourseForm(forms.ModelForm):
class Meta:
model = Course_Registration
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def clean_form(sel... |
import torch
import torch.nn as nn
import numpy as np
from typing import Tuple
def weight_init(m):
if isinstance(m, nn.Linear):
nn.init.kaiming_normal_(m.weight)
nn.init.constant_(m.bias, 0)
class Swish(nn.Module):
def __init__(self):
super(Swish, self).__init__()
def forward(se... |
import logging
import logging.handlers
import os
import wandb
root_logger = logging.getLogger()
# Some libraries attempt to add their own root logger handlers. This is
# getting rid of those
for handler in list(root_logger.handlers):
root_logger.removeHandler(handler)
# Choose log format
logfmt_str = "%(asctime... |
from __future__ import annotations
import ast
from typing import (
Any,
AsyncIterator,
Generator,
Iterator,
List,
Optional,
Protocol,
Tuple,
runtime_checkable,
)
from ...common.lsp_types import Position, Range
from .async_ast import walk
def iter_nodes(node: ast.AST) -> Generator... |
#
# 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 us... |
from .trialyield.trialyieldviews import trial_yield_views
from .plot.plotviews import plot_views
from .treatment.treatmentviews import treatment_views
trial_yield_views = trial_yield_views()
plot_views = plot_views()
treatment_views = treatment_views()
|
"""
File: draw_line.py
Name: Jennifer Chueh (1.5hr)
-------------------------
This program creates lines on an instance of GWindow class.
There is a circle indicating the user’s first click. A line appears
at the condition where the circle disappears as the user clicks
on the canvas for the second time.
"""
... |
import numpy as np
import matplotlib.pyplot as plt
from datafunctions import load_data
from kernels import RBF_kernel
def calc_cov_K(X, param, kernel_func):
"""
Parameters
-----------
X : numpy.ndarray, shape(N, D)
input
param : dict
valid parameters for kernel
kernel_func : ca... |
## Shorty
## Copyright 2009 Joshua Roesslein
## See LICENSE
## @url snipurl.com snipr.com sn.im snurl.com
class Snipurl(Service):
def __init__(self, user=None, apikey=None):
self.user = user
self.apikey = apikey
def _test(self):
# prompt for username and apikey
self.user = raw... |
import random
def isCorrect(number):
t = number / 1000000000000000000
if t < 1:
return -1
if t > 1:
return 1
t = (number / 10000000000000000) % 10
if t < 2:
return -1
if t > 2:
return 1
t = (number / 100000000000000) % 10
if t < 3:
... |
from ea_interop_service_source.b_code.i_dual_objects.attributes.i_attribute import IAttribute
from ea_interop_service_source.b_code.i_dual_objects.attributes.i_dual_attribute import IDualAttribute
from ea_interop_service_source.b_code.i_dual_objects.attributes.i_null_attribute import INullAttribute
from ea_interop_serv... |
"""
BaseEmoji
Copyright (c) 2019 tjado <https://github.com/tejado>
anybase codec
Emoji encoding/decoding by base conversion
"""
from .BaseEmojiAbstract import BaseEmojiAbstract
class anybase(BaseEmojiAbstract):
def __init__(self, emojis):
super(anybase, self).__init__(emojis)
def init(self):
... |
from sqlalchemy import MetaData
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import declarative_base, sessionmaker
from bot.settings.config import DEBUG, DATABASE_URL
metadata = MetaData()
Base = declarative_base(metadata=metadata)
engine = create_async_engine(DATABASE_URL... |
# Generated by Django 3.2.7 on 2021-10-07 08:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0003_portfolio_image'),
]
operations = [
migrations.AlterField(
model_name='portfolio',
name='image',
... |
"""add uploaded_report to template_jasper
Revision ID: 7a404c3a7c50
Revises: bd0e98ef10bd
Create Date: 2018-10-22 16:23:03.950524
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7a404c3a7c50'
down_revision = 'bd0e98ef10bd'
branch_labels = None
depends_on = Non... |
import asyncio
import aiohttp
from sanic import Blueprint
from sanic.request import RequestParameters
from sanic import response
import os
from .utils import __parse
from errors_module.errors import APIBadRequest
from loguru import logger
from sanic import response
import json
import base64
from io import BytesIO
from... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe.utils.data import evaluate_filters
class DocumentNamingRule(Document):
def ... |
from django.conf import settings
from django.contrib import admin
from django.urls import include, path, re_path
from django.views.generic import TemplateView
from django.views.static import serve
import web.apps.web_copo.views as views
from web.landing import views as landing_views
urlpatterns = [
path('admin/',... |
"""
This example demonstrates the use of RGB and stereo cameras to obtain the
spatial location of a human pose.
The RGB frame is passed to a pose estimation worker, the obtained body
landmarks are then passed to a spatial calculator worker to obtain the
spatial locations.
"""
import numpy as np
from curt.command... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.