content stringlengths 5 1.05M |
|---|
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
bit = []
pre = x
while x > 0:
cur = x % 10
bit.append(cur)
x = x // 10
sum = 0
for b in... |
import requests
import json
# Basic Setup
PORT_NUMBER = 1234
BASE = 'http://localhost:' + str(PORT_NUMBER) + '/v1/'
# Header for posting data to the server as JSON
HEADERS = {'Content-Type': 'application/json'}
def print_version():
response = requests.get(BASE + 'version')
print(json.dumps(response.json(), ... |
import torch
model = torch.hub.load('pytorch/vision', 'mobilenet_v2', pretrained=True)
model.eval()
|
import pandas as pd
import talib
def macd(data: pd.DataFrame, fastperiod=12, slowperiod=26, signalperiod=9, column_name_prefix=None):
"""
Calculate macd indicator
:param data:
:param fastperiod:
:param slowperiod:
:param signalperiod:
:param column_name_prefix:
:return: Tuple(macd, sig... |
from functools import reduce
import numpy as np
from compalg.integers import IZ, ModuloIntegers
from compalg.multinomial import Multinomial
def solve_congruences(a, b, n=None):
"""
Solves the congruence system ax ≡ b mod n. Returns an integer x such that a_i x ≡ b_i mod n_i for all i. As a
requirement, ... |
# -*- coding: utf-8 -*-
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class Property(scrapy.Item):
property_key = scrapy.Field()
owner_name = scrapy.Field()
todays_date = scrapy.Field()
mailing_address = scrapy.Field()
municipal_district = scrapy.Field... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 24 15:10:06 2015
@author: funkyman
"""
for s in specs:
spectracer.remove_spec(s)
chart1 = add_spec()
origChart = chart1.addPlot("Original spectrum")
source = dataSourceFactory.randomStream(1000)
source.updated.connect(origChart.onInput)
source.start()
chart2 = add_sp... |
import sys
import os
sys.path.append('..')
from gscli.base import Object, InvalidInput, Completer
from prompt_toolkit.document import Document
from prompt_toolkit.completion import WordCompleter, Completion
class TestCompleter(Completer):
def __init__(self, word_dict):
self.word_dict = word_dict
... |
from django.test import TestCase
from dfirtrack_main.models import Os
class OsModelTestCase(TestCase):
""" os model tests """
@classmethod
def setUpTestData(cls):
# create object
Os.objects.create(os_name='os_1')
def test_os_string(self):
""" test string representation """
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2014 Dave Kludt
# 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... |
'''
Module to query registry and retrieve persistables from wherever they are
stored.
'''
__author__ = 'Elisha Yadgaran'
import logging
from typing import Any, Dict
from simpleml.persistables.base_persistable import Persistable
from simpleml.datasets.base_dataset import Dataset
from simpleml.pipelines.base_pipeline... |
# -*- coding: utf-8 -*-
"""
.. module:: __main__
:platform: Windows
:synopsis: Main program execution
.. moduleauthor:: Ryan Long <ryalong1004@gmail.com>
"""
import asyncio
from models.command import Command
async def run():
tasks = [
Command("cleanmgr.exe /sagerun:1"),
Command("wuauclt /d... |
from typing import Optional
from xml.dom.minidom import Document
from xml.parsers.expat import ExpatError
from scieldas.api import API
from scieldas.services import ServiceAPI
class PePy(ServiceAPI):
base_url = "https://pepy.tech/badge/"
deserializer = "xml"
@ServiceAPI.call
def downloads(self, proj... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from .monet import Monet
from .transformer import Transformer
from .build import MODEL_REGISTRY
import slowfast.utils.checkpoint as cu
from collections import namedtuple
config_options = [
# Training config
#'vis_every', # Visua... |
class Solution:
def XXX(self, n: int) -> int:
dp = [1, 2]
for i in range(2, n):
dp[i % 2] = dp [(i -1) % 2] + dp[(i - 2) % 2]
return dp[(n - 1) % 2]
|
#!/usr/bin/python
# comments.py
# Author Jan Bodnar
# ZetCode 2016
def main():
print("Comments example")
main()
|
#pylint: skip-file
import numpy as np
import theano
import theano.tensor as T
from utils_pg import *
from lstm import *
class SentEncoderLayer(object):
def __init__(self, cell, rng, layer_id, shape, X, mask, is_train = 1, batch_size = 1, p = 0.5):
prefix = "SentEncoder_"
self.in_size, self.out_siz... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-09-25 08:15
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('DevicesAPP', '0009_auto_20180918_1421'),
]
operations = [
mig... |
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.messages',
'django.contrib.admin',
'testapp',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
SECRET_KEY = "sec... |
import os.path as osp
import torchvision.transforms as transforms
from cvpods.configs.base_classification_config import BaseClassificationConfig
_config_dict = dict(
MODEL=dict(
WEIGHTS="",
AS_PRETRAIN=True,
PIXEL_MEAN=[0.4914, 0.4822, 0.4465], # RGB
PIXEL_STD=[0.2023, 0.1994, 0.2... |
"""
Template code for reading S2S data in netCDF format
Author: 2020, John Methven
"""
import matplotlib.pyplot as plt
import numpy as np
from netCDF4 import Dataset
import datetime
from datetime import date
from datetime import timedelta
def read_s2srunoff(fstem, fname):
'''
Read in the runoff data from ne... |
# generated by datamodel-codegen:
# filename: api.yaml
# timestamp: 2019-07-26T00:00:00+00:00
from typing import (
List,
Optional,
)
from pydantic import (
AnyUrl,
BaseModel,
Field,
)
class Pet(BaseModel):
id: int
name: str
tag: Optional[str]
class Pets(BaseModel):
__root_... |
import numpy as np
import math
class fCSA:
def __init__(self, init_mean, init_variance=1.0, noise_adaptation=False, popsize=None):
# variables of the normal distribution
self.mean = init_mean
self.variance = init_variance
# integer variables for population and dimensionality
... |
import numpy as np
import functions
from ssp_bayes_opt import agent
import matplotlib.pyplot as plt
# Generate a bunch of data
def make_data(func, bounds, num_samples=25):
# func, bounds, T = functions.factory('branin-hoo')
a = np.linspace(bounds[0,0], bounds[0,1], num_samples)
b = np.linspace(bounds[1,... |
#
# Example Script: Use the wrapper of this libaray for stable baselines policy
# creation. Can be used with any Gym environment.
#
import os
import gym
from definitions import ROOT_DIR
from stable_baselines_model_based_rl.sb_training.stable_baselines_policy_trainer import \
train_stable_baselin... |
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
# edge case
if not(grid): return 0
cnt = 0
n = len(grid)
if n == 0: return 0
m = len(grid[0])
for i in range(n):
... |
import random
from matplotlib import cm
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
fig = plt.figure(2,figsize=(13,9),dpi=150)
axi= fig.gca(projection='3d')
[x,y]=np.meshgrid(np.array(range(25))/24.0,
np.arange(0,505.5,0.5)/575*17*np.pi-2*np.pi)
a=... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 22 20:34:53 2020
@author: User
"""
import sys
import os
import platform
system = platform.system()
current_dir = os.getcwd()
if system == 'Windows':
path_dir = current_dir.split("\\Neurons")[0] + "\\Neurons"
else:
path_dir = current_dir.split("/Neurons")[0] + ... |
import logging.config
from pathlib import Path
from aiogram import Bot, Dispatcher
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from rich.logging import RichHandler
from app.misc import ModuleManager, parse_config, PhotoStorage
# Project directory
ROOT_DIRECTORY = Path(__file__).parent.parent
# Conf... |
import torch
import torch.nn as nn
from models.layers import CBL, CL, C
class ResidualBlock(nn.Module):
def __init__(self, input_channel, output_channel, kernel_size=3, stride=1, padding=1):
"""
A residual block contains a sequence of CBL and CL classes with same size of stride, padding and kernel... |
# Time: O(m + n), m is the number of queries, n is the length of s
# Space: O(n)
import itertools
class Solution(object):
def canMakePaliQueries(self, s, queries):
"""
:type s: str
:type queries: List[List[int]]
:rtype: List[bool]
"""
CHARSET_SIZE = 26
cur... |
#!/usr/bin/env python3
import argparse
import sys
from docker_image.reference import Reference
INVALID_DOMAINS = set([
'dtr.dev.cray.com',
])
NON_MIRRORED_DOMAINS = set([
'artifactory.algol60.net',
'arti.dev.cray.com',
])
parser = argparse.ArgumentParser(description="Resolves image repositories to cano... |
# -*- coding: utf-8 -*-
#import sys
import struct
#import datetime
#import numpy as np
#import matplotlib
#import types
#import time as tme
##############################################################################
class DataFile():
##############################################################################
... |
print('Contador de parede')
a = float(input('Qual a altura da sua parede?'))
l = float(input('Qual a largura da sua parede'))
print(f'A area da parede é {a*l} metros quadrados')
print(f'Considerando que uma lata de tinta consegue pintar dois metros quadrados você precisaria de {a*l / 2} latas de tinta') |
import argparse
import datetime
from functools import partial
import msgpack
import msgpack_numpy as mpn
from bluesky_kafka import RemoteDispatcher
parser = argparse.ArgumentParser(
description="monogo consumer process",
)
parser.add_argument(
"--kafka_server",
type=str,
help="bootstrap server to con... |
# coding=utf-8
from tastypie.api import Api
from resources import UserResource, GroupResource, RoleResource, OrganisationResource, AuthenticateResource
api = Api(api_name='2')
api.register(UserResource())
api.register(GroupResource())
api.register(RoleResource())
api.register(OrganisationResource())
api.register(Aut... |
#!/usr/bin/env python
import matplotlib
matplotlib.use('Agg')
import seaborn as sns
import click
import pandas as pd
import matplotlib.pylab as plt
BED_COL_NAMES = ['chrom', 'start', 'stop', 'name', 'signalValue' ,'strand',]
@click.command()
@click.option('--inbed', help='Input BED',required=True)
@click.option('--ou... |
import os
import sys
ABSPATH = os.path.abspath(os.path.realpath(os.path.dirname(__file__)) + "/..")
sys.path.append(ABSPATH)
import asposecellscloud
from asposecellscloud.rest import ApiException
from asposecellscloud.apis.cells_api import CellsApi
import AuthUtil
from asposecellscloud.models import CalculationOptions... |
import sys, os, argparse, textwrap
from common import *
def main():
parser = argparse.ArgumentParser(description = 'Predict outcomes from time-series data',
usage = 'use "python %(prog)s --help" for more information',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-... |
"""Helper functions for window creation in my toolset. I am going to want to
have some windows function from outside of Maya while others will work natively
from within Maya. An example of a window that will hopefully function in both
domains is my TestCodeUI class.
Example::
Todo:
- Add functions that can be use... |
"""
A pytest module to test the functions relating to integer factorization.
Sage:
N = 50
print(f"FACTORS_SMALL = [")
for _ in range(N):
n = randint(2, 1_000_000)
f, m = zip(*factor(n)[:])
print(f" ({n}, {list(f)}, {list(m)}),")
print("]\n")
print(f"FACTORS_MEDIUM = [")... |
from __future__ import absolute_import, division, print_function
# LIBTBX_SET_DISPATCHER_NAME prime.change_basis
import argparse
from iotbx import reflection_file_reader
from cctbx import sgtbx
import os
def main(mtz, index_basis):
# read in mtz
reflection_file = reflection_file_reader.any_reflection_file(m... |
"""
File name: test_view.py
Author: joeschmid
Date created: 4/17/17
"""
import os
import six
from lookmlgen import view
from lookmlgen import field
from lookmlgen import base_generator
test_format_options = base_generator.\
GeneratorFormatOptions(warning_header_comment=None)
def test_basic_view():
... |
import os
from copy import deepcopy
import torch.nn as nn
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torchvision.models import resnet50
from wilds.common.data_loaders import get_eval_loader
from wilds.datasets.iwildcam_dataset import IWildCamDataset
from .datasets import ... |
from flaml import AutoML
import pandas as pd
from sklearn.datasets import fetch_california_housing, fetch_openml
class TestScore:
def test_forecast(self, budget=5):
import pickle
# using dataframe
import statsmodels.api as sm
data = sm.datasets.co2.load_pandas().data["co2"].resam... |
"""A GeneratorProvider Service Provider"""
from masonite.provider import ServiceProvider
from app.commands.GeneratorCommand import GeneratorCommand
class GeneratorProvider(ServiceProvider):
def register(self):
self.app.bind('GeneratorCommand', GeneratorCommand())
def boot(self):
pass
|
def pytest_addoption(parser):
parser.addoption(
"--run-notebook", action="store_true", default=False, help="run notebook tests"
)
|
def total(a,b):
res=a+b
print("sum=",res)
a=int(input("enter a no"))
b=int(input("enter a no"))
total(a,b)
var="good"
def show():
global var1
var1="good morning"
print("inside function",var1)
show()
print("outside func",var1)
print("var is",var)
|
from glassio.dispatcher import ICommand
__all__ = [
"IAddCallToUnsortedCommand",
]
class IAddCallToUnsortedCommand(ICommand):
__slots__ = ()
async def __call__(
self,
unique_id: str,
caller_phone_number: str,
called_phone_number: str,
duration: int,
sour... |
'''
Created on 20.2.2010
@author: Kamil.Rezac
'''
from net.krezac.robot.irena.gps.GPGGAParser import GPGGAParser
import math
class NmeaReader():
def deg2rad(self, deg):
#print "deg", deg
rr = deg[0]*math.pi/180.0,deg[1]*math.pi/180.0
#print "rad",rr
return rr
... |
"""
Provides scripts for building and working with Mezzanine.
"""
from __future__ import unicode_literals
|
import importlib
class FactoryMixIn:
def _get_data_area(self, module, classname):
"""Helper function to instantiate a data area or return a cached instance."""
if hasattr(self, "_cache_" + module):
return getattr(self, "_cache_" + module)
da_mod = importlib.import_module(f"{sel... |
"""Config flow for Fibaro integration."""
from __future__ import annotations
import logging
from typing import Any
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_PASSWORD, CONF_URL, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.d... |
from WordMeaningClass import WordMeaningClass
import sys
if __name__ == "__main__":
if len(sys.argv) == 2:
filename = sys.argv[1]
meanings = WordMeaningClass(filename)
meanings.generate_meanings() |
# Return the cells dictionary of the sample hex beam. Note how
# there is only one key/value pair as the hex beam example is
# composed of only all hexahedral cells, which is
# ``vtk.VTK_HEXAHEDRON``, which evaluates to 12.
#
# Also note how there is no padding for the cell array. This
# approach may be more helpful ... |
from jinja2 import nodes, TemplateSyntaxError, Environment
from jinja2.ext import Extension
from jinja2.lexer import Token
def fail_template(stream, message):
raise TemplateSyntaxError(
message, stream.current.lineno, stream.name, stream.filename
)
class SqlvmExtension(Extension):
"""The SqlvmEx... |
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from core.config import settings
from tests.utils.item import create_random_item
def test_create_item(
client: TestClient, superuser_token_headers: dict, db: Session
) -> None:
data = {"title": "Foo", "description": "Fighters"}
... |
import click
from sqlalchemy import create_engine
import pandas as pd
from json import dumps, loads
def get_engine_string(dialect, username, password, endpoint, name, port):
if dialect == "sqlite":
engine = """sqlite:////{}""".format(name)
else:
engine = """{}://{}:{}@{}:{}/{}""".format(
... |
from .torch_crystal import TorchCrystal
from .intensities import IntensityCalculator, get_coords_atom_dict, get_cmf_dict, get_sf
from .rotations import orientation_rotation_matrix
from .lattice import lattice_vectors_from_parameters, calc_reciprocal_vectors
from .miller_indices import get_miller_indices
from .atom_fact... |
from __future__ import print_function
import random
import boto3
# --------------- Helpers that build all of the responses ----------------------
def build_speechlet_response(title, output, reprompt_text, should_end_session):
return {
'outputSpeech': {
'type': 'PlainText',
'text':... |
# Copyright (c) 2016 Daniel Kornhauser under The MIT License (MIT)
import copy
import os
import sys
import time
import unittest
rootDirectory = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if rootDirectory not in sys.path:
sys.path.insert(0, rootDirectory)
from oxford.emotion import Emotion
from ... |
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/<name>", methods=['GET'])
def home(name):
return jsonify({"message": f"Hello! {name}"})
if __name__ == "__main__":
app.run(debug=True) |
"""Form aggregate lookup objects
"""
class Lookups:
def __init__(self):
pass
def simple_lookup(self, _from, local_field, foreign_field, _as):
"""Simple look up operation (without `let` or `pipeline`).
Args:
_from(:obj:`str`): collection to join.
local_field(:o... |
"""publish: Run poetry publish (interactive)."""
from __future__ import annotations
import subprocess
from .utils import ANSI
def taskPublish(kwargs: list[str]) -> None:
"""Run the publish task.
Args:
kwargs (list[str]): additional args
"""
_ = kwargs # unused - silence pylint
print(f"{ANSI['B']}{ANSI['U'... |
# Generators
import sys
def gen(n):
for i in range(n):
yield i**2
# x = [1 ** 2 for i in range(100000)]
g = gen(100000)
# print(sys.getsizeof(x))
print(sys.getsizeof(g))
|
import io
import os
import time
from time import sleep
import picamera
import requests
import numpy as np
#from ard import QuadSerial
from base_camera import BaseCamera
numOfCommands = 0
timetotal = 0
class Camera(BaseCamera):
final_num = None
theframe = None
@staticmethod
def frames(self):
wi... |
import torch
import numpy as np
import torch.nn as nn
from quaternion import qeuler_np
from remove_fs import remove_fs
def PLU(x, alpha = 0.1, c = 1.0):
relu = nn.ReLU()
o1 = alpha * (x + c) - c
o2 = alpha * (x - c) + c
o3 = x - relu(x - o2)
o4 = relu(o1 - o3) + o3
return o4
def ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from .providers.BooksToScrape import BooksToScrape
from apps.base.models.Category import Category
from apps.base.models.Book import Book
def scrap_main(request):
... |
from unittest.mock import MagicMock, patch
import pytest
from black import NothingChanged
from mypy_boto3_builder.writers.utils import (
blackify,
insert_md_toc,
render_jinja2_template,
sort_imports,
)
class TestUtils:
@patch("mypy_boto3_builder.writers.utils.black")
def test_blackify(self, ... |
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
APP = ['client.py']
DATA_FILES = []
OPTIONS = {
"iconfile":"../../media/Icon.icns",##自定义app图标
'plist': {
'argv_emulation': True,
'CFBundleName': "TripleX",
'CFBundleD... |
from pymongo import MongoClient
import math
import time
class CalculateTopApp(object):
db_name = 'app_store'
app_info_coll_name = 'app_info'
user_download_history_coll_name = 'user_download_history'
client = None
db = None
app_info_coll = None
user_download_history_coll = None
appids =... |
soma = 0
cont = 0
for c in range(1, 501, 2):
# if c % 2 == 1 and c % 3 == 0:
if c % 3 == 0:
cont += 1
soma += c
print(f'A soma de todos os {cont} os valor impares é {soma}')
|
from typing import Dict, List, Any
from ..df.types import Definition
from ..df.base import op
from ..util.data import traverse_get
MAPPING = Definition(name="mapping", primitive="map")
MAPPING_TRAVERSE = Definition(name="mapping_traverse", primitive="List[str]")
MAPPING_KEY = Definition(name="key", primitive="str")
M... |
import os
import sys
from collections import defaultdict
from gen_data_parser import DataVisitor, parse_data, data_parse_error, check_test_exists
from util import run_bash_command
SUBTASKS_JSON = os.environ.get('SUBTASKS_JSON')
INTERNALS_DIR = os.environ.get('INTERNALS')
SINGULAR_TEST = os.environ.get('SINGULAR_TEST')... |
import sys
import os
sys.path.append(os.path.abspath("../"))
from unittest import TestCase
from unittest.mock import patch
from unit_test.util import Util
from icon_rapid7_intsights.actions.get_indicator_scan_status import GetIndicatorScanStatus
from icon_rapid7_intsights.actions.get_indicator_scan_status.schema impo... |
# coding=utf-8
# Copyright 2022 The Google Research 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 applicab... |
"""The tests for the MQTT Template light platform.
Configuration example with all features:
light:
platform: mqtt_template
name: mqtt_template_light_1
state_topic: 'home/rgb1'
command_topic: 'home/rgb1/set'
command_on_template: >
on,{{ brightness|d }},{{ red|d }}-{{ green|d }}-{{ blue|d }}
... |
# _*_ coding:utf-8 _*_
# __author__ = 'JiangKui'
# __date__ = '2020/11/23 10:03 上午'
import unittest
from unittest import mock
import configuration
# from read_configuration import load_access_conf
class TestConfigMethods(unittest.TestCase):
def test_load_access_conf(self):
rc_open = mock.MagicMock()
... |
from unittest import TestCase
from ddpclient import UserListSelector, Client
from oauth2client.client import OAuth2Credentials
import datetime
class TestUserListSelector(TestCase):
def setUp(self):
self.client = Client(OAuth2Credentials('token', 'clientid', 'secret',
... |
import bisect
import os
import os.path
import re
import time
from datetime import datetime
from os.path import join
def get_minutes_folder():
"""Returns the path to the folder containing minutes.
Note that bod (which is stored in public_html, as they are readable on the
Web) is symlinked in this folder.
... |
from dataclasses import asdict, dataclass, field
from typing import List, Optional, Tuple
import numpy as np
from ..aliases import DirectionVector, ParameterVector
@dataclass()
class HessianEigenobject:
"""Data structure for Hessian matrix.
Eigenvalues and Eigenvectors are automatically calculated and s... |
import logging
from sanic.response import json
from sanic import Blueprint
from sanic.exceptions import SanicException
ERRORS_BP = Blueprint('errors')
LOGGER = logging.getLogger(__name__)
DEFAULT_MSGS = {
400: 'Bad Request',
401: 'Unauthorized',
403: 'Forbidden',
404: 'Not Found',
501: 'Not Implem... |
#!/bin/env python
"""
Create a whitelist for HGAP assembly based on vector screening blacklist.
Based on code from:
https://github.com/PacificBiosciences/Bioinformatics-Training/wiki/HGAP-Whitelisting-Tutorial
"""
import argparse
import csv
import h5py
import os
import re
def get_hole_number_by_file(input_filename)... |
from django.db import models
from django.contrib.auth.models import User
from django.contrib.postgres import fields
# Create your models here.
class Host(models.Model):
hostname = models.CharField(max_length=100)
api_user = models.OneToOneField(to=User, on_delete=models.CASCADE)
class Data(models.Model):
... |
from .model import NPSN
from .sampler import mc_sample_fast as mc_sample
from .sampler import qmc_sample_fast as qmc_sample
from .sampler import purposive_sample_fast as purposive_sample
from .utils import box_muller_transform, inv_box_muller_transform
from .utils import generate_statistics_matrices, compute_batch_metr... |
a + b
a - b
a * b
a / b
a // b
a % b
a @ b
a << b
a >> b
a | b
a ^ b
a ** b
a == b
a < b
a <= b
a > b
a >= b
a != b
a & b
~a
(1, 2, 3)
["a", "b"]
{1, 2}
{a: a.b}
{**d, a: b}
not b
a if b else c
a or b
a and b
a in b
a not in b
a is b
a is not b
a * (+1)
a * (-1)
a * (~1)
(a)
(yield a) |
from dbnd._core.tracking.schemas.base import ApiObjectSchema
from dbnd._core.tracking.schemas.tracking_info_objects import TaskRunEnvInfo
from dbnd._vendor.marshmallow import fields, post_load
class TaskRunEnvInfoSchema(ApiObjectSchema):
uid = fields.UUID()
cmd_line = fields.String()
user = fields.String... |
from typing import List
from random import shuffle, randint
from time import sleep
def __is_sorted__(l: List[int]) ->bool:
'''
check the input list is sorted
'''
return all(a <= b for a, b in zip(l, l[1:]))
def bogo_sort(l: List[int]) -> List[int]:
'''
bogo sort: https://en.wikipedia.org/wi... |
from flask_mail import Message
recipient = None
mail = None
def init(param_mail, param_recipient):
global mail
global recipient
mail = param_mail
recipient = param_recipient
def email_user(subject, body):
if recipient is not None:
try:
msg = Message(subject, recipients=[rec... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Jonathan S. Prieto
import os
import tempfile as tmp
from encoding import encoding_path
from log_conf import Logger
import utils
log = Logger.log
class InfoFile(object):
"""
.path
.basename
.name
.extension
.dirna... |
import json
import requests
import csv
import sys
def polarity(s):
if s == 'Positive':
return 1
elif s == 'Negative':
return -1
elif s == 'Neutral':
return 0
with open(sys.argv[2], 'w') as fout:
writer = csv.writer(fout, delimiter='\t')
with open(sys.argv[1], 'r') as fin:
... |
(
ggplot(df_test)
+ aes(
x='Guesser',
fill='wiki',
ymin='mean_accuracy - std_dev', ymax='mean_accuracy + std_dev'
)
+ geom_bar(aes(y='best_accuracy'), stat='identity', position='dodge')
+ geom_errorbar(size=.5, width=.5, position=position_dodge(.9))
+ facet_wrap(['Metric'... |
# Copyright 2015, Aiven, https://aiven.io/
#
# This file is under the Apache License, Version 2.0.
# See the file `LICENSE` for details.
"""
Configurable parameters via environment variables
"""
import os
USER_HOME = os.path.expanduser("~")
AIVEN_CONFIG_DIR = os.environ.get("AIVEN_CONFIG_DIR", os.path.join(USER_HOME... |
"""Functions based on separable convolution found in scipy.ndimage
These functions are intended to operate exactly like their SciPy counterparts
aside from the following differences:
1.) By default, convolution computations are done in the nearest floating point
precision (single or double) for the input dtype.
... |
from fastapi import APIRouter
router = APIRouter(prefix="/form_element_input_types", tags=["form_element_input_types"])
# Assign a license to a product
# Get all form_element_input_types
# Update the form_element_input_type
# Delete the form_element_input_type if nothing assigned to it |
"""
The commands that actually write and move data provided by our "data"
"""
import re
import os
import time
import json
import sublime
import threading
import sublime_plugin
from copy import deepcopy
from .lib.utils import CppTokenizer, CppRefactorDetails
from .lib.utils import _BaseCppRefactorMeta, FunctionState
... |
#!/usr/bin/env python
"""
================================================
Pyrad: The MeteoSwiss Radar Processing framework
================================================
Welcome to Pyrad!
This program does the daily processing and post-processing over a period of \
time.
To run the processing framework type:
... |
#!/usr/bin/env python
# coding: utf-8
import os
import re
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
init_py = open(os.path.join(package, '... |
from amaranth.vendor.xilinx_7series import *
from amaranth.vendor.xilinx_7series import __all__
import warnings
warnings.warn("instead of nmigen.vendor.xilinx_7series, use amaranth.vendor.xilinx_7series",
DeprecationWarning, stacklevel=2)
|
#! /usr/bin/python
#-*-coding: utf8-*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import uic
import qtui.model
import os.path
class QuestionWidget(QWidget):
def __init__(self, parent=None):
super(QuestionWidget, self).__init__(parent)
self.ui = uic.loadUi(os.path.join(os.envi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.