text stringlengths 2 999k |
|---|
import pytest
ACTIVE_PROJECT = 'project1'
pytestmark = pytest.mark.usefixtures('reset_projects_dir', 'set_active_project')
def test_get_collections(api):
c = api.get_collections()
assert len(list(c)) == 3
def test_new_collection(api):
c = api.new_collection('test1')
assert len(list(api.get_collect... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
"""Base classes for all estimators."""
# Author: Gael Varoquaux <gael.varoquaux@normalesup.org>
# License: BSD 3 clause
import copy
import warnings
from collections import defaultdict
import platform
import inspect
import re
import numpy as np
from . import __version__
from ._config import get_config
from .utils im... |
import numpy as np
import pytest
from pandas.compat.numpy import _np_version_under1p16
import pandas as pd
from pandas.core.arrays.numpy_ import PandasArray, PandasDtype
import pandas.util.testing as tm
from . import base
@pytest.fixture(params=['float', 'object'])
def dtype(request):
return PandasDtype(np.dty... |
from django.conf import settings
from django.contrib.auth import login, get_backends
from django.dispatch import Signal
# A new user has registered.
user_registered = Signal(providing_args=["user", "request"])
# A user has activated his or her account.
user_activated = Signal(providing_args=["user", "request"])
de... |
"""
This file offers the methods to automatically retrieve the graph Lysinibacillus sp. BF4.
The graph is automatically retrieved from the STRING repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 2021... |
class DemoManager(object):
def __enter__(self):
pass
def __exit__(self, ex_type, ex_value, ex_tb):
if ex_type is IndexError:
print(ex_value.__class__)
return True
if ex_type is TypeError:
print(ex_value.__class__)
return # return None
w... |
data = {'logSums': [],
'powerSums': [
10500000.0,
171590.10344086567,
10600692.901931819,
3656024.1204772266,
27999983.535580769,
26085580.4679562,
112571037.57246359,
178035035.71434641,
597052564.3216269,
1272051754.8467662,
3862170673.2579589,
9736800905.3333244,
28892120151.48772,
80400... |
# Databricks notebook source
# MAGIC
# MAGIC %md-sandbox
# MAGIC
# MAGIC <div style="text-align: center; line-height: 0; padding-top: 9px;">
# MAGIC <img src="https://databricks.com/wp-content/uploads/2018/03/db-academy-rgb-1200px.png" alt="Databricks Learning" style="width: 600px">
# MAGIC </div>
# COMMAND ------... |
from rest_framework import viewsets
from rest_framework import mixins
from apps.endpoints.models import Endpoint
from apps.endpoints.serializers import EndpointSerializer
from apps.endpoints.models import MLAlgorithm
from apps.endpoints.serializers import MLAlgorithmSerializer
from apps.endpoints.models import MLAlg... |
"""
Created on Sat Nov 18 23:12:08 2017
@author: Utku Ozbulak - github.com/utkuozbulak
"""
import os
import numpy as np
import torch
from torch.optim import Adam
from torchvision import models
from baselines.misc_functions import preprocess_image, recreate_image, save_image
class CNNLayerVisualization():
"""
... |
#!/usr/bin/env python
# vim: set et sw=4 sts=4 fileencoding=utf-8:
#
# A library for reading Microsoft's OLE Compound Document format
# Copyright (c) 2014 Dave Jones <dave@waveform.org.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation fi... |
import win32gui
import pyautogui
import random
import math
import time
DEFAULT_TWEEN = pyautogui.easeInOutCubic
class Window:
def __init__(self, title, tween=DEFAULT_TWEEN, duration=0.5):
self.title = title
self.tween = tween
self.duration = duration
def getHandle(self):
retur... |
import argparse
from os.path import dirname, abspath, join, exists
import os
import torch
from torch.optim import Adadelta, Adam, lr_scheduler
from torch import nn
import numpy as np
from download_dataset import DATASETS
from preprocessors import DATASET_TO_PREPROCESSOR
import dictionaries
from dataloaders import Tex... |
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Eric Larson <larson.eric.d@gmail.com>
# Joan Massich <mailsik@gmail.com>
# Guillaume Favelier <guillaume.favelier@gmail.com>
#
# License: Simplified BSD
import pytest
import warnings
def has_vtki():
"""Check that... |
# -*- coding: utf-8 -*-
"""
:Module: khoros.utils.helper
:Synopsis: Module that allows the khoros library to leverage a helper configuration file
:Usage: ``from khoros.utils import helper``
:Example: ``helper_settings = helper.get_settings('/tmp/helper.yml', 'yaml')``
:Created ... |
#!/usr/bin/env python
import sys
import os
import re
import glob
import shutil
import argparse
from fractions import *
import common
log = common.get_log()
# Global paths
base_path = os.path.dirname(os.path.normpath(sys.argv[0]))
tmp_base_path = os.path.join(base_path, "tmp")
tmp_path = os.path.join(tmp_base_path,... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/component/bio/shared_bio_component_food_flavor_2.iff"
result.attrib... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/datastore/v1/datastore.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf impor... |
from __future__ import absolute_import, division, print_function
from os import path
import yaml
from .catalog_arr import load_blaze_array
def is_valid_bpath(d):
"""Returns true if it's a valid blaze path"""
# Disallow backslashes in blaze paths
if '\\' in d:
return False
# There should not b... |
#!/usr/bin/env python
from collections import defaultdict
import lxml
from lxml import html
def table_to_2d_dict(table):
result = defaultdict(lambda: defaultdict(unicode))
for row_i, row in enumerate(table.xpath('./tr')):
for col_i, col in enumerate(row.xpath('./td|./th')):
colspan = int(c... |
"""
Handling Superseded Functionality
The main mechanism in Sage to deal with superseded functionality is to
add a deprecation warning. This will be shown once, the first time
that the deprecated function is called.
Note that all doctests in the following use the trac ticket number
:trac:`13109`, which is where this ... |
class Keys(Enum,IComparable,IFormattable,IConvertible):
"""
Specifies key codes and modifiers.
enum (flags) Keys,values: A (65),Add (107),Alt (262144),Apps (93),Attn (246),B (66),Back (8),BrowserBack (166),BrowserFavorites (171),BrowserForward (167),BrowserHome (172),BrowserRefresh (168),BrowserSearch (170),... |
import numpy as np
import matplotlib.pyplot as plt
import librosa
import sys
import scipy.interpolate as interp
## TODO: Pre-multiply by Hamming window
## TODO: Get the hop size as small as possible with madmom to maximize frequency resolution
def get_dftacf_hadamard_blocks(X, win, hop, do_plot = False):
"""
... |
# Copyright 2020 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 collections
import logging
import os
import re
import subprocess
import test_runner as tr
LOGGER = logging.getLogger(__name__)
# WARNING: THESE DUPL... |
from keras.models import Model
from keras.layers import (Input, Flatten, Dense,
Conv2D, Conv2DTranspose, MaxPooling2D,
ZeroPadding2D,
Conv3D, Conv3DTranspose, MaxPooling3D,
ZeroPadding3D)
def create_vgg_model_2d(in... |
from importlib.util import module_from_spec, spec_from_file_location
from pathlib import Path
from setuptools import find_packages, setup
classifiers = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Framework :: aiohttp",
"Operating System :: MacOS",
"Operatin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# IkaLog
# ======
# Copyright (C) 2015 Takeshi HASEGAWA
#
# 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/l... |
from .base_trainer import BaseTrainer
from .. import accuracy_evaluator
class FineTuner(BaseTrainer):
def __init__(self, *args, **kwargs):
super(FineTuner, self).__init__(*args, **kwargs)
def single_epoch_compute(self, model, x, y, mask):
self.optimizer.zero_grad()
output = ... |
# 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 PyPythonRapidjson(PythonPackage):
"""Python wrapper around rapidjson."""
homepage = "... |
from setuptools import setup, find_packages
with open("README.txt", encoding='utf-8') as f:
long_description = f.read()
setup(
name="pyega3",
description="EGA python client",
long_description=long_description,
long_description_content_type="text/plain",
packages=find_packages(),
version = ... |
# -*- coding: utf-8 -*-
"""Tests for pyss3.util."""
from os import path
from pyss3 import SS3, InvalidCategoryError
from shutil import rmtree
from pyss3.util import Evaluation, Dataset, RecursiveDefaultDict, Print, VERBOSITY
import sys
import pytest
import pyss3
DATASET_FOLDER = "dataset_mr"
PY3 = sys.version_info[0]... |
# -*- coding: utf-8 -*-
# Copyright © 2017 Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
"""
Class definition and utilities for the evaluation of the image classification mo... |
import numpy as np
from numpy.testing import assert_array_equal, assert_array_almost_equal
import pytest
from acoustics.bands import (octave, octave_high, octave_low, third, third_low, third_high, third2oct, _check_band_type)
@pytest.fixture
def octave_real():
return np.array([16, 31.5, 63, 125, 250, 500, 1000,... |
import string
# Retomando clase pasada
# Estructura de datos
###########################
# Listas
#########################3
otra_lista = [ 1, 2, 3, 4, 5, 6]
# Accediendo a los elementos de una lista
print(otra_lista[0])
print(otra_lista[-1])
# Slicing
print(otra_lista[0:3])
print(otra_lista[:3])
print(otra_lista[3... |
# Data preprocessing for Supervised Learning model
# Import relevant libraries
import sys
import numpy as np
import pandas as pd
from pandas.api.types import infer_dtype
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import LabelEncoder
def... |
import click
import os
import requests
from colored import fg, attr
@click.group(invoke_without_command=True)
@click.pass_context
def main(ctx):
"""A simple command line tool to find Air Quality Indices (AQI)
from around the world."""
ctx.ensure_object(dict)
try:
api_token = os.environ["AQI... |
"""Tile generation restriction within a polygon
The GenToDirectory method generates tiles in a given zoom interval into a directory
Tile generation options:
- Remove tiles outside of the polygon from disk
- Create a Unix script to remove such tiles independently
- Visualize the ploygon, the generated super-til... |
#!/usr/bin/python
# Copyright (c) 2011 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.
"""Chromium presubmit script for src/chrome/common/net.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
fo... |
"""
author : Yuxuan Liu
github alias: L519159123
"""
import os
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
def plot_loss(experiment_name, model='pix2pix'):
"""Plot plg loss of the training process
Parameters:
experiment_name (string)
model (str... |
#!/usr/bin/env python
from __future__ import with_statement
from os import environ
import json
import yaml
import sys
class ConfigoNotExistingKeyError(Exception): pass
class Configo():
def __init__(self):
self.tmp_conf_name = environ.get('CONFIGO_CONF', None)
def load_config(self, config_path):
... |
from os import path
from setuptools import setup
from io import open
with open('README.md', encoding='utf-8') as f:
description = f.read()
setup(
name = 'messagebird',
packages = ['messagebird'],
version = '2.0.0',
description ... |
import globals
from globals import get_soup, job_insert
from job import Job
# SHARE! the Self Help And Recovery Exchange
organization = "SHARE! the Self Help And Recovery Exchange"
url = "https://shareselfhelp.org/programs-share-the-self-help-and-recovery-exchange/share-jobs-share-self-help-recovery-exchange/"
or... |
from floodsystem.plot import plot_water_levels
from floodsystem.stationdata import build_station_list
stations= build_station_list()
dates= 0
levels=0
print(plot_water_levels("Cam", dates, levels))
|
import operator
import functools
N = int(input())
def calc(first, last, digit, limit):
cnt = 0
if digit == 0:
if int(first + last) <= limit:
cnt += 1
return cnt
lst = []
fixed = []
for n in reversed(range(1, digit+1)):
pas = False
for d in reversed(range(0, 9+1)):
v = first
... |
from django.shortcuts import render
# Create your views here.
def hello_view(request):
return render(request, 'hello_django.html')
|
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
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, merg... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 10 10:11:34 2021
@author: houping
"""
import os
import re
import csv
import time
import json
import random
import requests
import pandas as pd
import numpy as np
from datetime import date, timedelta, datetime
from bs4 import BeautifulSoup
import ... |
from os.path import isdir, join
Import("env")
board = env.BoardConfig()
PROJ_DIR = "$PROJECT_DIR"
env.Replace(
ASFLAGS = ["-x", "assembler-with-cpp"],
CCFLAGS=[
"-Og",
"-g",
"-Wall",
"-march=%s" % board.get("build.march"),
"-mabi=%s" % board.get("build.mabi"),
... |
import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['RelativeDifference'] , ['PolyTrend'] , ['Seasonal_Second'] , ['AR'] ); |
# Copyright 2019 BlueCat Networks (USA) Inc. and its affiliates
#
# 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... |
"""Fixes common java command mistake
Example:
> java foo.java
Error: Could not find or load main class foo.java
"""
from thefuck.utils import for_app
@for_app('java')
def match(command, settings):
return command.script.endswith('.java')
def get_new_command(command, settings):
return command.script[:-5]
|
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module containing commands related to android"""
import asyncio
import math
import os
import re
import tim... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import metrics
import pandas as pd
def test_map(y_pred,y_test):
"""
Get accurracy, precision and recall and save png of true positive,
false positive, true negative and false negative for given prediction and test data
... |
# Copyright 2017-present Kensho Technologies, LLC.
"""Workaround for OrientDB query scheduling issue with eval() statements.
OrientDB <2.2.17 (and perhaps future versions as well) fail to pick up $matched
query dependencies if those dependencies are only used within an eval() statement.
The workaround pulls out all su... |
# A neural network -based model for predicting moral reasoning.
import time
import collections
import numpy as np
import ccobra
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
class MLP(nn.Module):
def __init__(self, input_size=15, hidden_size=... |
import sys
input = sys.stdin.readline
def run(n, p):
if n == 0:
return 0
d = [0] * (n+1)
p = [0] + p
for i in range(1, n+1):
for j in range(1, i+1 if (i+1 < len(p))else len(p)):
if d[i] == 0 or d[i-j]+p[j] > d[i]:
d[i] = d[i-j]+p[j]
return d[n]
n = in... |
###################################################################
## Test case for tasks ##
## ##
## How to run ? : ##
## $ python tests/integration/tes... |
r"""
Eta-products on modular curves :math:`X_0(N)`
This package provides a class for representing eta-products, which
are meromorphic functions on modular curves of the form
.. MATH::
\prod_{d | N} \eta(q^d)^{r_d}
where
:math:`\eta(q)` is Dirichlet's eta function
:math:`q^{1/24} \prod_{n = 1}^\infty(1-q^n)`. Th... |
# @unused
load(":b.bzl", "x")
|
import os, sys
import os.path as osp
from PIL import Image
import six
import string
import lmdb
import pickle
import torch
import torch.utils.data as data
from torch.utils.data import DataLoader
from torchvision.transforms import transforms
from torchvision.datasets import ImageFolder
from torchvision import transfor... |
# Copyright 2017 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 applicable law or ag... |
import pandas as pd
def add_data(df, algorithm, data, elapsed, metric):
time_col = (data.name, 'Time(s)')
metric_col = (data.name, data.metric)
try:
df.insert(len(df.columns), time_col, '-')
df.insert(len(df.columns), metric_col, '-')
except:
pass
df.at[algorithm, time_col... |
import synapse.common as s_common
import synapse.lib.socket as s_socket
from synapse.links.common import *
class TcpRelay(LinkRelay):
'''
Implements the TCP protocol for synapse.
tcp://[user[:passwd]@]<host>[:port]/<path>
'''
proto = 'tcp'
def _reqValidLink(self):
host = self.link[... |
import time
import pytest
@pytest.mark.parametrize("partition", ["normal", "debug"])
def test_partitions_are_up(host, partition):
partition_status = host.check_output(f"scontrol -o show partition {partition}")
assert "State=UP" in partition_status
def test_job_can_run(host):
host.run('sbatch --wrap="hos... |
"""Test the binascii C module."""
from test import support
import unittest
import binascii
import array
import sys
# Note: "*_hex" functions are aliases for "(un)hexlify"
b2a_functions = ['b2a_base64', 'b2a_hex', 'b2a_hqx', 'b2a_qp', 'b2a_uu',
'hexlify', 'rlecode_hqx']
a2b_functions = ['a2b_base64', ... |
# Copyright (c) 2003-2014 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, o... |
from probeinterface import Probe
import numpy as np
import pytest
def _dummy_position():
n = 24
positions = np.zeros((n, 2))
for i in range(n):
x = i // 8
y = i % 8
positions[i] = x, y
positions *= 20
positions[8:16, 1] -= 10
return positions
def test_probe():
... |
# Copyright 2017 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... |
# (size, board)
def pgmToBoard(file_loc: str) -> (int, [[int]]):
mapp = []
size = 0
with open(file_loc, 'rb') as f:
lines = f.readlines()
size = int(lines[1].split()[0])
bits = str(lines[3].split()[0])
# remove b
bits = bits[2:]
bits = bits.split('\\'... |
import rrPython
import os
rrPython.enableLogging()
rrPython.setTempFolder('C:\\RRTemp')
os.chdir('C:\\RoadRunner\\bin')
result = rrPython.loadSBMLFromFile('C:\\RoadRunner\\Models\\feedback.xml')
print result
simulation = rrPython.simulate()
print simulation
#insert known results, compare
PythonTestRes... |
neighborhood = [int(el) for el in input().split("@")]
command = input()
start_index = 0
Flag = True
while not command == "Love!":
jump = int(command.split()[1])
if not jump + start_index >= len(neighborhood):
if neighborhood[(jump + start_index)] >= 2:
neighborhood[(jump + star... |
from __future__ import annotations
import contextlib
import typing
import uuid
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.pagination import BasePagination
from rest_framework.utils.urls import replace_query_param, remove_query_param
from restdoctor.constants import DEFAULT_MAX_PAGE_SIZ... |
# Copyright The IETF Trust 2013-2020, All Rights Reserved
# -*- coding: utf-8 -*-
from pyquery import PyQuery
from django.urls import reverse
import debug # pyflakes:ignore
from ietf.utils.test_utils import TestCase
from ietf.group.factories import RoleFactory
from ietf.group.models impo... |
from chia.util.misc import format_bytes, format_minutes
def format_og_plot_count(plot_count: int) -> str:
return f"🌾 OG Plot Count: {plot_count}"
def format_og_plot_size(plot_size: int) -> str:
return f"🧺 OG Plot Size: {format_bytes(plot_size)}"
def format_portable_plot_count(plot_count: int) -> str:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# cardea documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# 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
# auto... |
from Cython.Compiler.Visitor import CythonTransform
from Cython.Compiler.ModuleNode import ModuleNode
from Cython.Compiler.Errors import CompileError
from Cython.Compiler.UtilityCode import CythonUtilityCode
from Cython.Compiler.Code import UtilityCode, TempitaUtilityCode
from Cython.Compiler import Options
from Cytho... |
from pathlib import Path
from shutil import rmtree
from fixtures import fixture
from virtool_workflow.data_model import Job
from virtool_workflow.api.client import authenticated_http
from virtool_workflow.api.jobs import acquire_job
@fixture
def results() -> dict:
return {}
@fixture
def work_path(config: dict)... |
# coding: utf-8
"""
Control-M Services
Provides access to BMC Control-M Services # noqa: E501
OpenAPI spec version: 9.20.220
Contact: customer_support@bmc.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class AiJobtypeL... |
from __future__ import absolute_import, division, print_function
import math
import copy
import mmtbx.model
from libtbx.utils import null_out
from collections import OrderedDict
from scitbx.array_family import flex
from mmtbx.conformation_dependent_library import generate_protein_fragments
from mmtbx.secondary_structur... |
from django.apps import AppConfig
class ReviewConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'APPS.REVIEW'
icon_name = 'create' |
#!/usr/bin/env python3
import glob
import smbus
from MCP342x import MCP342x
import numpy as np
addr = 0x68
def get_smbus():
candidates = []
prefix = '/dev/i2c-'
for bus in glob.glob(prefix + '*'):
try:
n = int(bus.replace(prefix, ''))
candidates.append(n)
except:
... |
class Solution(object):
def validTree(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: bool
"""
if len(edges) != n-1:
return False
d = {}
for i in range(n):
d[i] = {}
for e in edges:
u,v... |
from django.db import models
from django.conf import settings
from phonenumber_field.modelfields import PhoneNumberField
from django.contrib.gis.db import models as geomodels
CAR_BRAND = [('Audi', 'Audi'), ('Acura', 'Acura'), ('BMW', 'BMW'),
('Buick', 'Buick'), ('Cadillac', 'Cadillac'),
('Ch... |
"""Support for APCUPSd sensors."""
from __future__ import annotations
import logging
from apcaccess.status import ALL_UNITS
import voluptuous as vol
from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.const import (
CONF_RESOURCES... |
import csv
import decimal
import os
import threading
import time
from typing import List
import torch
import torch.distributed as dist
import torch.distributed.rpc as rpc
import torch.multiprocessing as mp
from torch.distributed import rpc
from .trpc_server import TRPCCOMMServicer
from ..base_com_manager import BaseC... |
# -*- coding: utf-8 -*-
# Copyright 2016 OpenMarket Ltd
# Copyright 2019 New Vector Ltd
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# 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
#
# ... |
"""The root view for the examples provided with Django REST framework"""
from django.core.urlresolvers import reverse
from djangorestframework.views import View
class Sandbox(View):
"""This is the sandbox for the examples provided with [Django REST framework](http://django-rest-framework.org).
These example... |
from logging import getLogger
from typing import Dict
from typing import Optional
from piperider.artifacts.aws.s3 import S3PrefixArtifact
from piperider.types import AwsCredentials
from piperider.utils.aws import athena
logger = getLogger(__name__)
class AthenaArtifact(S3PrefixArtifact):
"""
It represents a... |
# reading_cells_from_single_column.py
from openpyxl import load_workbook
def iterating_column(path, sheet_name, col):
workbook = load_workbook(filename=path)
if sheet_name not in workbook.sheetnames:
print(f"'{sheet_name}' not found. Quitting.")
return
sheet = workbook[sheet_name]
fo... |
from pyop2.codegen.node import traversal, reuse_if_untouched, Memoizer
from functools import singledispatch
from pyop2.codegen.representation import (Index, RuntimeIndex, Node,
FunctionCall, Variable, Argument,
NamedLiteral)
def colle... |
# -*- coding: utf-8 -*-
""" Sahana Eden Person Registry Model
@copyright: 2009-2017 (c) Sahana Software Foundation
@license: MIT
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 Softwa... |
import numpy as np
import scipy.stats as sp
from scipy.special import expit
from scipy.optimize import minimize
SMALL = np.finfo(float).eps
__all__ = ['logistic_regression']
def _logr_statistics(independent_vars, regression_coefficients):
"""Computes the significance tests for regression"""
# Compute the p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/5/13 17:05
# @Author : gao
# @File : perm.py
import re
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse, redirect
def reg(request, current_path):
# 校验权限(permission_list)
permission_list = request.... |
"""
WSGI config for mealmanager project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATIO... |
import module1
import sys
print('=================================')
print('Running main.py - module name: {0}'.format(__name__))
print('importing module1 again...')
del globals()['module1']
import module1
module.pprint('main.globals', globals())
print('=================================') |
from PLC.Method import Method
from PLC.Parameter import Parameter, Mixed
from PLC.Faults import *
from PLC.Filter import Filter
from PLC.Auth import Auth
from PLC.Slices import Slice, Slices
from PLC.Sites import Site, Sites
from PLC.Persons import Person, Persons
from PLC.Nodes import Node, Nodes
class SliceInfo(Meth... |
# Copyright (c) 2013, GreyCube Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import cint
import pandas as pd
import numpy as np
def execute(filters=None):
return get_data(filters)
def ... |
import factory
from django.contrib.auth.hashers import check_password
from django.urls import reverse
from faker import Faker
from rest_framework import status
from rest_framework.test import APITestCase
from src.users.models import User
from tests.users.factories import UserFactory
fake = Faker()
class TestUserList... |
"""
examples of how to search for events using different search criteria
"""
from eventregistry import *
import json
er = EventRegistry()
# get the concept URI that matches label "Barack Obama"
obamaUri = er.getConceptUri("Obama")
print("Concept uri for 'Obama' is " + obamaUri)
#
# USE OF ITERATOR
# example of usin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.