text stringlengths 2 999k |
|---|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Developed by Shangchen Zhou <shangchenzhou@gmail.com>
import os
import torch.backends.cudnn
import torch.utils.data
import utils.data_loaders
import utils.data_transforms
import utils.network_utils
import torchvision
from losses.multiscaleloss import *
from time import t... |
from __future__ import absolute_import
from kaleido.scopes.base import BaseScope
from _plotly_utils.utils import PlotlyJSONEncoder
import base64
class PlotlyScope(BaseScope):
"""
Scope for transforming Plotly figures to static images
"""
_json_encoder = PlotlyJSONEncoder
_all_formats = ("png", "jp... |
# coding: utf-8
"""
anchore_engine.services.policy_engine
This is a policy evaluation service. It receives push-events from external systems for data updates and provides an api for requesting image policy checks # noqa: E501
OpenAPI spec version: 1.0.0
Contact: zach@anchore.com
Generated by: htt... |
# Copyright (c) 2013. Librato, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions a... |
# coding:utf8
import cv2
import sys
import numpy as np
try:
import pyscreenshot as ImageGrab
import pyautogui
import time
except Exception as e:
print(e)
class MovingDetector():
def __init__(self):
pass
def camera_detect(self, device=0, func=None):
self.camera = cv2.VideoCapt... |
from mtdownloader import MTDownloader
from mtdownloader import readable as readableSize
from phuburl import resolver as PageResolver
import requests
import json
import time
def readableTime(s):
s=int(s)
if(s<60):
return '{}s'.format(s)
elif(s<3600):
return '{}m{}s'.format(s//60,s%60)
el... |
# coding: utf-8
from sqlalchemy.testing import eq_
from sqlalchemy import *
from sqlalchemy import types as sqltypes, exc, schema
from sqlalchemy.sql import table, column
from sqlalchemy.sql.elements import quoted_name
from sqlalchemy.testing import fixtures, AssertsExecutionResults, AssertsCompiledSQL
from sqlalchem... |
# The month_list dictionary for month conversion
month_list = {1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August",
9: "September", 10: "October", 11: "November", 12: "December"}
# Names of Days in a Week
days_list = ["MON", "TUE", "WED", "THU", "FRI", "SAT", ... |
import matplotlib
import numpy as np
import pandas as pd
import pymc3 as pm
import scipy.optimize as opt
import theano.tensor as tt
import pytest
import theano
from pymc3.theanof import floatX
from .helpers import SeededTest
matplotlib.use('Agg', warn=False)
def get_city_data():
"""Helper to get city data"""
... |
# coding: utf-8
"""
axxell-api
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
... |
import numpy as np
import tensorflow as tf
def placeholder(dim=None):
return tf.placeholder(dtype=tf.float32, shape=(None, dim) if dim else (None,))
def placeholders(*args):
return [placeholder(dim) for dim in args]
def mlp(x, hidden_sizes=(32,), activation=tf.tanh, output_activation=None):
for h in h... |
#!/usr/bin/env nemesis
# This python script extracts the changes in fault tractions from
# step01 and combines them with background depth-dependent fault
# tractions to create initial fault tractions to drive frictional
# afterslip.
#
# PREREQUISITES: numpy, h5py, output from step01
#
# Run the script:
# python after... |
import numpy as np
from scipy.linalg import norm, solve, qr, solve_triangular
from scipy.sparse import csc_matrix, diags
from scipy.sparse.linalg import spsolve
import dill
from multiprocessing import Pool
from .derivatives import approx_jac
def fsolve(fun, x0, jac=None, method='nleqres', tol=1e-8, maxiter=100, disp=F... |
from setuptools import setup, find_packages
requirements = [
"requests",
"websocket-client==1.3.1",
"setuptools",
"json_minify",
"six",
"aiohttp",
"websockets"
]
with open("README.md", "r") as stream:
long_description = stream.read()
setup(
name="amino.fix",
license='MIT',
... |
# This source code is licensed under the MIT-style license found in the
# LICENSE file in the root directory of this source tree.
from setuptools import setup, find_packages
import re
__version__ = ""
exec(open('composed_trackers/version.py').read())
# from fastai:
# helper functions to make it easier to list depen... |
myFile=open("") |
# pyright: reportPropertyTypeMismatch=false
from __future__ import annotations
import collections
from datetime import timedelta
import functools
import gc
import json
import operator
import pickle
import re
from typing import (
TYPE_CHECKING,
Any,
Callable,
Hashable,
Literal,
Mapping,
Sequ... |
# coding: utf-8
from __future__ import unicode_literals
from bs4 import BeautifulSoup
import requests
from django.core.management.base import BaseCommand
from core.models import Hellspawn
class Command(BaseCommand):
def handle(self, *args, **options):
url = 'http://www.18183.com/yys/201609/706902.html'... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 8
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from isi_sdk_8_2_1.models.subnets... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.cancer_survival import cancer_survival
def test_cancer_survival():
"""Test module cancer_survival.py by downloading
cancer_survival.csv and t... |
# Copyright 2004-2008 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
import os
import sys
import unittest
import fundamental_tester_base
class tester_t(fundamental_tester_base.fundament... |
from django.shortcuts import render
from django.http import *
from .models import *
import utils
# Create your views here.
def index(res):
return utils.render(res, 'index', {
'jsData': {
'choices': choices
}
})
def about(res):
return utils.render(res, 'about')
def gallery(res):
return utils.render(res, 'g... |
# A GPS tracker library
# This is a neater and more useful implementation of Sixfab's demo code
import serial
import time
import pynmea2
import threading
class GPS(object):
"""An all-powerful GPS interface class"""
|
#!/usr/bin/python
#
# Copyright 2015 Google 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 required by... |
"""
Agglomerative clustering with and without structure
===================================================
This example shows the effect of imposing a connectivity graph to capture
local structure in the data. The graph is simply the graph of 20 nearest
neighbors.
Two consequences of imposing a connectivity can be s... |
import os
import time
import argparse
import random
import numpy as np
import torch
import torch.nn.functional as F
import tensorflow as tf
from lib.network import DeformNet
from lib.loss import Loss
from data.pose_dataset import PoseDataset
from lib.utils import setup_logger, compute_sRT_errors
from lib.align import e... |
# pylint: skip-file
'''
Contains banner for the application.
'''
class COLORS:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
LINK = '\033[94m'
PURPLE = '\033[95m'
CYAN = '\033[96m'
PRIMARY = '\033[97m'
SECONDARY = '\033[90m'
END = '\033[0m'
PINK = '\033[95m'
banner ... |
class Config(object):
def __init__(self):
# Learning Rates
self.lr = 5e-4
# Epochs
self.epochs = 200
self.lr_drop = 20
self.start_epoch = 0
self.weight_decay = 1e-4
# Backbone
self.backbone = 'resnet34'
self.position_embedding = 'sin... |
# qubit number=3
# total number=9
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
import networkx as nx
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collection... |
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import re
import codecs
import MySQLdb
import sys
reload(sys);
sys.setdefaultencoding("utf8")
chinese_set = []
img_set = []
img_h_set = []
img_w_set = []
book_set = []
situation = 0
def insert(img_id, chinese, book_num, img_addr, table_name, img_h, img_w):
db = ... |
"""Finance_Tracker URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Cla... |
# Copyright (c) 2018 PaddlePaddle 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 app... |
import os
import queue
import sys
import types
possible_topdir = os.path.normpath(
os.path.join(
os.path.abspath(os.path.dirname(__file__)),
os.pardir,
os.pardir,
)
)
base_path = os.path.join(possible_topdir, "iodict", "__init__.py")
if os.path.exists(base_path):
sys.path.insert(0... |
# Python program to illustrate a stop watch
# using Tkinter
#importing the required libraries
# source url : https://www.geeksforgeeks.org/create-stopwatch-using-python/
import tkinter as Tkinter
from datetime import datetime
counter = 66600
running = False
def counter_label(label):
def count():
... |
"""
Django settings for just_do_it project.
Generated by 'django-admin startproject' using Django 3.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os... |
import unittest
from dynamic_array import DynamicArray
import sys
class MyTestCase(unittest.TestCase):
def test_something(self):
arr = DynamicArray()
arr.append(5)
self.assertEqual(1, len(arr))
def test_dynamic_array(self):
arr = DynamicArray()
arr.append(5)
ar... |
from flask import Flask
import DiceBot
import Spells
app = Flask(__name__)
@app.route('/dieroll/<parsable>')
def roll_die(parsable):
parsed_text = DiceBot.parse_text(parsable)
return_text = []
for x in parsed_text:
return_text.append(f"you rolled {x[1]} and got {DiceBot.roll_by_array(x[0])} {x[2]... |
import sys
import os
def makeJob(n):
run = "runMW-A"
path = os.getcwd() +"/"+run+"/"+str(n)+"/"
print path
os.system("mkdir -p "+path)
fileOut = open(path+"jobScript", "w")
fileOut.write("#!/bin/bash \n")
fileOut.write("# Begin PBS directives \n")
fileOut.write("#PBS -A ast032 \n")
... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from .network import Network
__all__ = [
'Network'
]
|
"""Loan Qualifier Application.
This is a command line application to match applicants with qualifying loans.
Example:
$ python app.py
"""
import csv
import sys
import fire
import questionary
import pandas as pd
from pathlib import Path
from qualifier.utils.fileio import load_csv
from qualifier.utils.calculator... |
import csv
import json
from sys import argv
from random import randint
"""
Python 3.6
This script is not particularly robust, but there's not much point in making it perfect.
It reads the csv file received as an argument, then outputs its contents in JSON format to STDOUT.
CSV files must have the following structure:
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016-2022 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
import numpy as np
from scipy.stats import chi2
from pandapower.estimation.algorithm.base import (WLSAlgorithm,
... |
#
# 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... |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import scipy.signal
def signal_synchrony(signal1, signal2, method="hilbert", window_size=50):
"""Compute the synchrony (coupling) between two signals.
Compute a continuous index of coupling between two signals either using the ``"hilbert"``
m... |
from datetime import timedelta as delta
from tornado import stack_context
from tornado.ioloop import IOLoop
class Deferred(object):
'''
Deferred execution object.
It executes a `callback` at a given `deadline` of milliseconds.
Can be canceled, if not already executed, with :meth:`cancel`.
'''
... |
import tensorflow as tf
import tensorflow.contrib.slim as slim
class DQN_Network():
def __init__(self,
window_size,
channel_size,
num_goals,
num_actions,
history_steps,
scope='global'):
with tf.variable_sc... |
import json
import click
from agent.cli.prompt.pipeline.schemaless import SchemalessPrompter
from agent.modules.tools import infinite_retry
class ZabbixPrompter(SchemalessPrompter):
def prompt_config(self):
self.prompt_query_file()
self.prompt_batch_sizes()
self.prompt_days_to_backfill()
... |
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic.detail import DetailView
from django_filters.views import FilterView
from django_tables2 import SingleTableMixin
from .filters import MouFilter
from .models import Mou
from .tables... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server import util
class DeletionMethodUpdate(Model):
"""NOTE: This class is auto generated by th... |
from .convnext import ConvNeXtOperation # noqa
from .densenet import DenseNetOperation # noqa
from .efficientnet import EfficientNetOperation # noqa
from .mobilenet import MobileNetOperation # noqa
from .nfnet import NFOperation # noqa
from .regnet import RegnetOperation # noqa
from .resnet import ResNetOperation... |
import ujson
from io import StringIO
from itertools import count
from functools import lru_cache
from itertools import count
from typing import Any, ClassVar, List, Union, Dict
from .config import get_config
from .context import Context, insert
from .command import Position, Selector, Execute, ScoreCase, ConditionInst... |
"""WebSocket client for asyncio."""
import asyncio
from typing import Any, Optional
import async_timeout
from .client_exceptions import ClientError
from .client_reqrep import ClientResponse
from .helpers import call_later, set_result
from .http import (
WS_CLOSED_MESSAGE,
WS_CLOSING_MESSAGE,
... |
# squashBestOfN.py
# A program that calculates who will win best of n squash matches.
"""Revise the squash simulation so that it computes the results for best
of n game matches. First service alternates, so player A serves first in the
odd games of the match, and player B serves first in the even games."""
from rand... |
"""Classes for representing match statement patterns."""
from typing import TypeVar, List, Optional, Union
from mypy_extensions import trait
from mypy.nodes import Node, RefExpr, NameExpr, Expression
from mypy.visitor import PatternVisitor
# These are not real AST nodes. CPython represents patterns using the normal ... |
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
class L2Norm(nn.Module):
def __init__(self,n_channels, scale=1.0):
super(L2Norm,self).__init__()
self.n_channels = n_channels
self.scale = scale
self.eps = 1e-10
self.weigh... |
# -*- coding: utf-8 -*-
"""Tests for `cookiecutter.hooks` module."""
import os
import pytest
import stat
import sys
import textwrap
from cookiecutter import hooks, utils, exceptions
def make_test_repo(name):
"""Create test repository for test setup methods."""
hook_dir = os.path.join(name, 'hooks')
tem... |
from beir import util, LoggingHandler
from beir.retrieval import models
from beir.datasets.data_loader import GenericDataLoader
from beir.retrieval.search.dense import util as utils
import pathlib, os, sys
import numpy as np
import torch
import logging
import datetime
#### Just some code to print debug information to... |
import logging
from django.core.management.base import BaseCommand
from peering.models import AutonomousSystem
class Command(BaseCommand):
help = "Get prefixes of Autonomous Systems with IRR AS-SETs and store them in the database"
logger = logging.getLogger("peering.manager.peering")
def add_arguments(... |
# -*- coding: utf8 -*-
# Usage:
# python extract_ja_stopwords.py
# cat ja_stopword.txt | sort | uniq -c | sort -nr
# Then arbitrarily pick up those high frequency words
from nltk.corpus import knbc
import codecs
f = codecs.open('ja_stopword.txt', 'w', 'utf-8')
for k in knbc.tagged_words():
x = k[1].split()[2... |
from pathlib import Path
from typing import Tuple
import numpy as np
import pandas as pd
import torch
from .bandits import DataBasedBandit
from .utils import download_data
URL = "https://storage.googleapis.com/bandits_datasets/raw_stock_contexts"
class FinancialDataBandit(DataBasedBandit):
"""A contextual band... |
"""
Problem Statement:
A permutation can be specified by an array P,
where P[i] represents the location of the element at i in the permutation.
For example, [2, 1, 0] represents the permutation where elements at the index 0 and 2 are swapped.
Given an array and a permutation, apply the permutation to the arr... |
from math import ceil
from typing import Dict, Any, List, Optional
import gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import LambdaLR
from core.algorithms.onpolicy_sync.losses import PPO
from core.algorithms.onpolicy_sync.losses.ppo import PPOCon... |
import os, subprocess
from getpass import getpass
def is_root():
return os.geteuid() == 0
def test_sudo(pwd=""):
args = "sudo -S echo".split()
kwargs = dict(stdout=subprocess.PIPE,
encoding="ascii")
if pwd:
kwargs.update(input=pwd)
cmd = subprocess.run(args, **kwargs)
... |
from django.db import models
from wagtail.core.models import Page
from wagtail.admin.edit_handlers import FieldPanel
from wagtail.images.edit_handlers import ImageChooserPanel
class HomePage(Page):
"""Homepage Model"""
templates = "home/home_page.html"
max_count = 1 # Limits the number of homepages to 1
... |
# _*_ coding: utf-8 _*_
# Copyright (c) Nikita Kovaliov, maizy.ru, 2013
# See LICENSE.txt for details.
from __future__ import unicode_literals, absolute_import
from giiit.multi_version import uu
from giiit.parsers import WrongOutputError, ParserError
from giiit.models import obj
def format_raw(output, force_blob=Fal... |
import tensorflow as tf
from .flag import FlagAdder
from .estimator import def_estimator
from .inputs import def_def_train_input_fn, def_def_eval_input_fn
def def_def_experiment_fn(batch_inputs=True,
prepare_filename_queues=True,
distributed=False):
adder = Fla... |
#
# Copyright 2016 The BigDL 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 ... |
import os.path
import datetime
import dateutil.tz
import subprocess
from tempfile import NamedTemporaryFile
# from pyasn1.type import univ
from pyasn1.codec.der import encoder
import rfc3161ng_async
rfc3161ng = rfc3161ng_async
def _default_test(tsa_server, certificate, username=None, password=None, data='xx', nonce... |
import os
import numpy as np
import subprocess
from subprocess import call
from multiprocessing import Pool
################################################################################################
### read 2d array
def read2d_array(filename,dtype_used):
import numpy as np
data=open(filename,'r')
data0=[]
f... |
import pickle
import tensorflow as tf
import tflearn
import data
train_x, train_y, words, classes = data.get_training_data()
# Reset underlying graph data
tf.reset_default_graph()
def build_model():
# Init model
net = tflearn.input_data(shape=[None, len(train_x[0])])
net = tflearn.fully_connected(net,... |
import pytest
import click.types
# Common (obj, expect) pairs used to construct multiple tests.
STRING_PARAM_TYPE = (click.STRING, {"param_type": "String", "name": "text"})
INT_PARAM_TYPE = (click.INT, {"param_type": "Int", "name": "integer"})
BOOL_PARAM_TYPE = (click.BOOL, {"param_type": "Bool", "name": "boolean"})
... |
import os
import shutil
from jina.logging.predefined import default_logger
def fork_hello(args) -> None:
"""Fork the hello world demos into a new directory
:param args: the arg from cli
"""
from_path = os.path.join(os.path.dirname(__file__), args.project)
shutil.copytree(from_path, args.destina... |
#!python
import os
import sys
import re
sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
import util
def test_typename():
s = '\n'
s += util.typename('abc')
s += '\n'
s += util.typename(123)
s += '\n'
s += util.typename(True)
s += '\n'
s += util.typename(None)
s += '\n'
return s
... |
"""
Logger copied from OpenAI baselines to avoid extra RL-based dependencies:
https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/logger.py
"""
import os
import sys
import shutil
import os.path as osp
import json
import time
import datetime
import tempfile
import warnings
from c... |
"""
Sample Input:
A = [ 11, 5, 9, 21, 4, 76, 10]
Sample Output:
Sorted Array is:
4
5
9
10
11
21
76
"""
# To heapify subtree rooted at index i.
def heapify(A, n, i):
largest = i # Initialize largest as root
l = 2 * i + 1 # left child = 2*i + 1
r = 2 * i + 2 ... |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Macsio(CMakePackage):
"""A Multi-purpose, Application-Centric, Scalable I/O Proxy Applicat... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
from . import core
def test_unit_commitment_p1() -> None:
np.random.seed(0)
T = 10
N = 5
func = core.Un... |
# -*- coding: utf-8 -*-
#
# Sentiment Analysis of Twitter documentation build configuration file, created by
# sphinx-quickstart.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All confi... |
# 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 ... |
from django.apps import AppConfig
class BasketConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'basket'
|
from django import forms
from .models import Party, Member
class RequireInlineFormSet(forms.BaseInlineFormSet):
def __init__(self, *args, **kwargs):
super(RequireInlineFormSet, self).__init__(*args, **kwargs)
for form in self.forms:
form.empty_permitted = False
PartyFormSet = forms.inl... |
# Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//div[@class='product-name']/h1",
'price' : "//div[@class='price-box-content']/span[@class='regular-price']/span[@class='price']",
... |
# This an autogenerated file
#
# Generated with LibraryPaths
from typing import Dict,Sequence,List
from dmt.entity import Entity
from dmt.blueprint import Blueprint
from .blueprints.librarypaths import LibraryPathsBlueprint
from typing import Dict
from sima.sima.librarypathitem import LibraryPathItem
from sima.sima.mo... |
#!/usr/bin/env python3
# if a variable has not been defined or no longer exists,
# a NameError is raised.
a = 'variable a' # a variable(can change) piece of data, stored in ram.
print(a)
del a # delete variable from memory
try:
print("Trying to print(a)")
print(a)
except NameError:
print("Failed(on purpose): ... |
# -*- coding: utf-8 -*-
import numpy as np
from sparse_learning.proj_algo import head_proj
from sparse_learning.proj_algo import tail_proj
from sparse_learning.fast_pcst import fast_pcst
from sparse_learning.graph_utils import simu_graph
def test_proj_head():
print('-' * 100)
edges, weights = simu_graph(25) #... |
"""add new model
Revision ID: 301a679a98be
Revises: 28eb5afae162
Create Date: 2019-12-08 07:11:57.787590
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '301a679a98be'
down_revision = '28eb5afae162'
branch_labels = None
depends_on = None
def upgrade():
# ... |
#!/usr/bin/python3
import RPi.GPIO as GPIO
import time
import sys
in1 = 17
in2 = 18
in3 = 27
in4 = 22
# careful lowering this, at some point you run into the mechanical limitation of how quick your motor can move
step_sleep = 0.02
step_count = 4096*1 # 5.625*(1/64) per step, 4096 steps is 360°
step_count = 1000
dire... |
from setuptools import setup, find_packages
setup(
name='metalparser',
version='0.6.9b1',
description='Python library for heavy metal song lyrics, albums, song titles and other info.',
long_description=open("README.md").read(),
long_description_content_type="text/markdown",
license='MIT',
a... |
# -*- coding: utf-8 -*-
"""
Testing that functions from compat work as expected
"""
import pytest
import re
from pandas.compat import (range, zip, map, filter, lrange, lzip, lmap,
lfilter, builtins, iterkeys, itervalues, iteritems,
next, get_range_parameters, PY2, ... |
# -* coding: utf-8 -*-
"""Common enums, functions, and classes for the `contours` package."""
# Python 2 support
# pylint: disable=redefined-builtin,unused-wildcard-import,wildcard-import
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *... |
import stripe
from django.db import models
from .. import enums
from ..fields import JSONField, StripeDateTimeField, StripeEnumField
from .base import StripeModel
class ScheduledQueryRun(StripeModel):
"""
Stripe documentation: https://stripe.com/docs/api#scheduled_queries
"""
stripe_class = stripe.si... |
from typing import List, Any
import pytorch_lightning as pl
import torch
from pytorch_lightning import Trainer
from torch.optim import Adam
from torchmetrics import MetricCollection
from new.data.report import Report
from new.model.lstm_tagger import LstmTagger
from new.training.data import ReportsDataModule
from new... |
# Copyright 2018-2020 Xanadu Quantum Technologies 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 typing import (
TYPE_CHECKING,
Any,
Callable,
Collection,
Dict,
Iterator,
List,
Optional,
Sequence,
Tuple,
Union,
)
from eth_abi.codec import (
ABICodec,
)
from eth_abi.grammar import (
parse as parse_type_string,
)
from eth_typing import (
ChecksumAddress,
... |
# -*- coding: utf-8 -*-
"""
plot a pretty confusion matrix with seaborn
Created on Mon Jun 25 14:17:37 2018
@author: Wagner Cipriano - wagnerbhbr - gmail - CEFETMG / MMC
REFerences:
https://www.mathworks.com/help/nnet/ref/plotconfusion.html
https://stackoverflow.com/questions/28200786/how-to-plot-scikit-learn-clas... |
from .api_base_exception import ApiBaseException
class InvalidArgumentException(ApiBaseException):
pass
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ###############################################################################
# Copyright 2014 OCLC
#
# 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 Lic... |
from nose.tools import eq_, ok_
from ddtrace.context import Context
from ddtrace.contrib.tornado import TracerStackContext
from .utils import TornadoTestCase
from .web.compat import sleep
class TestStackContext(TornadoTestCase):
def test_without_stack_context(self):
# without a TracerStackContext, propa... |
#! /usr/bin/python
# Copyright 2015 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.
import argparse
import logging
import os
import sys
from processing import (SitesFromDir, WarmGraph, ColdGraph)
def main():
logging.b... |
from django.conf import settings
from django.conf.urls import include, url
from rest_framework import routers
from example.views import (
AuthorRelationshipView,
AuthorViewSet,
BlogRelationshipView,
BlogViewSet,
CommentRelationshipView,
CommentViewSet,
CompanyViewset,
EntryRelationshipV... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.