content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
"""
References:
https://fdc.nal.usda.gov/api-guide.html#food-detail-endpoint
https://fdc.nal.usda.gov/portal-data/external/dataDictionary
"""
import datetime
from typing import List, Dict, Union
from datatrans import utils
from datatrans.fooddata.detail.base import IdMixin
from datatrans.fooddata.detail.nutri... | python |
import sys
sys.modules['pkg_resources'] = None
import pygments.styles
import prompt_toolkit | python |
# --
# File: aelladata/aelladata_consts.py
#
# Copyright (c) Aella Data Inc, 2018
#
# This unpublished material is proprietary to Aella Data.
# All rights reserved. The methods and
# techniques described herein are considered trade secrets
# and/or confidential. Reproduction or distribution, in whole
# or in part, is f... | python |
from typing import Dict, List
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.fields import empty
from rest_framework.reverse import reverse
from rest_framework_nested import serializers as nested_serializers
from api.helpers import uuid_helpers
from be... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-07 07:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tasks', '0002_auto_20160607_1133'),
]
operations = [
migrations.AddField(
... | python |
from os import path
import numpy as np
import torch
import torch.utils.data as td
import torchvision.datasets as dsets
import torchvision.transforms as tt
import vsrl_utils as vu
from faster_rcnn.datasets.factory import get_imdb
import faster_rcnn.roi_data_layer.roidb as rdl_roidb
import faster_rcnn.fast_rcnn.config a... | python |
#Client name: Laura Atkins
#Programmer name: Griffin Cosgrove
#PA purpose: Program to determine net pay check of employees and provide new access codes.
#My submission of this program indicates that I have neither received nor given unauthorized assistance in writing this program
#Creating the prompts for the use... | python |
"""VBR ContainerType routes"""
from typing import Dict
from fastapi import APIRouter, Body, Depends, HTTPException
from vbr.api import VBR_Api
from vbr.utils.barcode import generate_barcode_string, sanitize_identifier_string
from ..dependencies import *
from .models import ContainerType, CreateContainerType, GenericR... | python |
n1 = int(input("qual o salario do funcionario?"))
s = 15 * n1
des = s/100
prom = n1 + des
print("O salario atual do funcionario é de {} e com o aumento de 15% vai para {}".format(n1,prom)) | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-11-03 20:19
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('query', '0023_auto_20181101_2104'),
]
operations = [... | python |
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, print_function, unicode_literals
import collections
import re
from textwrap import dedent
import pytablewriter as ptw
import pytest
import six # noqa: W0611
from pytablewriter.style imp... | python |
class Game:
def __init__(self):
self.is_active = True
self.LEVEL_CLASSES = [Level_1, Level_2, Level_3]
self.curr_level_index = 0
self.curr_level = self.LEVEL_CLASSES[self.curr_level_index](
self.go_to_next_level
)
def go_to_next_level(self):
self.curr... | python |
#!/usr/bin/python
from my_func3 import hello3
hello3()
| python |
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
from ros_rover.msg import Rover
from numpy import interp
from PanTilt import PanTilt
pt = PanTilt()
def callback(data):
#rospy.loginfo(rospy.get_caller_id() + 'I heard %s', data.speed)
pan=int(interp(data.camera_pan_axis,[-255,255],[-90... | python |
# Copyright 2018 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... | python |
"""Trivial filter that adds an empty collection to the session."""
# pylint: disable=no-self-use,unused-argument
from typing import TYPE_CHECKING, Any, Dict
import dlite
from oteapi.models import FilterConfig
from pydantic import Field
from pydantic.dataclasses import dataclass
from oteapi_dlite.models import DLiteSe... | python |
from ..serializers import ClienteSerializer
from ..models import Cliente
class ControllerCliente:
serializer_class = ClienteSerializer
def crearcliente(request):
datosCliente= request.data
try:
ClienteNuevo = Cliente()
ClienteNuevo.cliente = datosCliente['client... | python |
from random import randint
from typing import Tuple
from pymetaheuristics.genetic_algorithm.types import Genome
from pymetaheuristics.genetic_algorithm.exceptions import CrossOverException
def single_point_crossover(
g1: Genome, g2: Genome, **kwargs
) -> Tuple[Genome, Genome]:
"""Cut 2 Genomes on index p (ra... | python |
from src.floyd_warshall import (floyd_warshall,
floyd_warshall_with_path_reconstruction, reconstruct_path)
def test_floyd_warshall(graph1):
dist = floyd_warshall(graph1)
assert dist[0][2] == 300
assert dist[0][3] == 200
assert dist[1][2] == 200
def test_floyd_warshall_with_path_reconstruction(g... | python |
# Generated by Django 2.0.8 on 2019-08-18 19:16
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('tasks', '0022_auto_20190812_2145'),
]
operations = [
migrations.AddField(
model_name='task',... | python |
"Genedropping with IBD constraints"
from pydigree.common import random_choice
from pydigree.genotypes import AncestralAllele
from .simulation import GeneDroppingSimulation
from pydigree.exceptions import SimulationError
from pydigree import paths
from pydigree import Individual
import collections
class ConstrainedMe... | python |
# The parameters were taken from the ReaxFF module in lammps:
#! at1; at2; De(sigma); De(pi); De(pipi); p(be1); p(bo5); 13corr; p(bo6), p(ovun1); p(be2); p(bo3); p(bo4); n.u.; p(bo1); p(bo2)
# 1 1 156.5953 100.0397 80.0000 -0.8157 -0.4591 1.0000 37.7369 0.4235 ... | python |
#codeby : Dileep
#Write a Python program to simulate the SSTF program disk scheduling algorithms.
num=int(input("Enter the Number:"))
print("Enter the Queue:")
requestqueue=list(map(int,input().split()))
head_value=int(input("Head Value Starts at: "))
final=[]
for i in requestqueue:
emptylist=[]
for j in reques... | python |
# -*- coding: utf8 -*-
from nose.tools import *
from mbdata.api.tests import with_client, assert_json_response_equal
@with_client
def test_label_get(client):
rv = client.get('/v1/label/get?id=ecc049d0-88a6-4806-a5b7-0f1367a7d6e1&include=area&include=ipi&include=isni')
expected = {
u"response": {
... | python |
import datetime
import logging
import os
import traceback
import flask
import google.auth
from google.auth.transport import requests as grequests
from google.oauth2 import id_token, credentials
import googleapiclient.discovery
from typing import Optional, NamedTuple
from app.util.exceptions import BadPubSubTokenExce... | python |
from TunAugmentor import transformations
def test_transform1():
assert transformations.transform1('mahdi')=='mahdi' | python |
from sqlalchemy import Integer, String, Column, Float
from api.db.base_class import BaseLayerTable
from geoalchemy2 import Geometry
class CommunityLocations(BaseLayerTable):
"""
https://catalogue.data.gov.bc.ca/dataset/first-nation-community-locations
"""
__tablename__ = 'fn_community_locations'
... | python |
import csv
def find_labels(xmap, contig_start_label, contig_end_label, contig_orientation):
"""
this does not account for split mapped molecules
i.e., assumes one molecule ID per line in XMAP
fix later
"""
# swap if -:
#print(contig_start_label, contig_end_label)
if contig_orientation == "-":
conti... | python |
####################
# Gui V3 16 Sept. 2017 Malacophonous
#####################
'''
API for Gui v3
guiAPP
guiWIN
guiWID
'''
from buildingblocks import guiRectangle,guiLines
import random as r
class Widget():
def __init__(self,_x,_y,_w,_h):
self.x = _x
self.y = _y
... | python |
# coding: utf-8
# ======================================================================
# DZI-IIIF
# DeepZoom(dzi)形式のファイルをIIIF Image APIでアクセスできるようにする
# ======================================================================
# 2020-05-21 Ver.0.1: Initial Version, No info.json handling.
# 2020-05-22 Ver.0.2: Add info.js... | python |
# Returns the upper triangular part of a matrix (2-D tensor)
# torch.triu(input, diagonal=0, *, out=None) → Tensor
# The argument 'diagonal' controls which diagonal to consider.
import torch
source_tensor = torch.ones((10, 10))
# print(source_tensor)
tensor = (torch.triu(source_tensor) == 1).transpose(0, 1)
print(te... | python |
import cant_utils as cu
import numpy as np
import matplotlib.pyplot as plt
import glob
import bead_util as bu
import tkinter
import tkinter.filedialog
import os, sys
from scipy.optimize import curve_fit
import bead_util as bu
from scipy.optimize import minimize_scalar as minimize
import pickle as pickle
import time
#... | python |
import logging
import time
import cv2 as cv
import numpy as np
from scipy.sparse import lil_matrix
from scipy.optimize import least_squares
def project(points, camera_params, K, dist=np.array([])):
"""
Project 2D points using given camera parameters (R matrix and t vector), intrinsic matrix,
... | python |
# Copyright (c) 2010-2019 openpyxl
import pytest
from openpyxl.xml.functions import fromstring, tostring
from openpyxl.tests.helper import compare_xml
@pytest.fixture
def Marker():
from ..marker import Marker
return Marker
class TestMarker:
def test_ctor(self, Marker):
marker = Marker(symbol=N... | python |
from telegram import InlineKeyboardButton
def generate_buttons(labels):
buttons = [[InlineKeyboardButton(labels[0], callback_data=labels[0]),
InlineKeyboardButton(labels[1], callback_data=labels[1])],
[InlineKeyboardButton(labels[2], callback_data=labels[2]),
Inline... | python |
import base64
from authlib.common.encoding import to_bytes, to_unicode
import fence.utils
def create_basic_header(username, password):
"""
Create an authorization header from the username and password according to
RFC 2617 (https://tools.ietf.org/html/rfc2617).
Use this to send client credentials i... | python |
# ywo queue to stack
import queue
class ArrayQueue(object):
def __init__(self):
self.queue1 = queue.Queue(5)
self.help = queue.Queue(5)
def push(self, data):
"""模仿压栈"""
if self.queue1.full() == True:
raise RuntimeError('the stack is full')
self.queue1.put(... | python |
'''
Written by Jinsung Yoon
Date: Jul 9th 2018 (Revised Oct 19th 2018)
Generative Adversarial Imputation Networks (GAIN) Implementation on MNIST
Reference: J. Yoon, J. Jordon, M. van der Schaar, "GAIN: Missing Data Imputation using Generative Adversarial Nets," ICML, 2018.
Paper Link: http://medianetlab.ee.ucla.edu/pap... | python |
import datetime
import names
from django.contrib.auth import get_user_model
from usersetting.models import UserSetting
User = get_user_model()
def initialize_usersetting(email):
while(True):
try:
nickname = names.get_first_name()
UserSetting.objects.get(nickname=nickname)
e... | python |
import numpy as np
import pandas as pd
def create_rolling_ts(
input_data,
lookback=5,
return_target=True,
apply_datefeatures=True,
return_np_array=False
):
"""
Make flat data by using pd.concat instead, pd.concat([df1, df2]).
Slow function.
Save data as preprocessed?
"""
... | python |
import time
def merge(data, low, high, middle, drawData, timetick):
color=[]
for i in range (len(data)):
color.append('sky blue')
left = data[low:middle+1]
right = data[middle+1:high+1]
i = 0
j = 0
for k in range(low, high+1):
if i< len(left) and j<len(right):
... | python |
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
from pyrogram import Client, emoji
from datetime import datetime, timedelta
from shamil.voicechat import mp
@Client.on_callback_query()
async def cb_handler(client: Client, query: CallbackQuery):
if query.data == "replay":
... | python |
#!/usr/bin/env python
import yaml
import json
def main():
my_list = range(8)
my_list.append('0 through 7 are cool numbers')
my_list.append({})
my_list[-1]['subnet_mask'] = '255.255.255.0'
my_list[-1]['gateway'] = '192.168.1.1'
with open("first_yaml_file.yml", "w") as f:
f.write(yaml.... | python |
import os
import glob
import sys
class CAPSProfile:
def __init__(self):
self.streams = [] # List of strings, e.g. XY.ABCD.*.*
self.stations = [] # List of network, station tuples, e.g. (XY,ABCD)
self.oldStates = [] # Content of old state file
'''
Plugin handler for the CAPS plugin.
'''
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import time
import xlrd
from public import saveScreenshot
from core import LoginPage
from test import support
from public.log import logger
from public.pyse import Pyse
class LoginTest(unittest.TestCase):
def setUp(self):
self.driver = Pyse("ch... | python |
import os
import pprint
import random
import collections
from ai_list_common import (
ListInterface,
ListBase,
ListTypeNgram,
TestRunnerCheckNgram,
)
class NgramList(ListTypeNgram, ListBase, ListInterface):
def check_num_of_gram(self, num_of_gram):
if super().check_num_of_gram(num_of_gram)... | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import six
from aiida import orm
from aiida.common.lang import classproperty
from aiida.plugins import factories
from aiida_quantumespresso.calculations import BasePwCpInputGenerator
class PwCalculation(BasePwCpInputGenerator):
"""`CalcJob... | python |
# -*- coding: utf-8 -*-
from com.pnfsoftware.jeb.client.api import IClientContext
from com.pnfsoftware.jeb.core import IRuntimeProject
from com.pnfsoftware.jeb.core.units import IUnit
from com.pnfsoftware.jeb.core.units.code import IDecompilerUnit, DecompilationOptions, DecompilationContext
from com.pnfsoftware.jeb.cor... | python |
#!/usr/bin/env python
#
# ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University of Chicago
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://ge... | python |
# coding=utf-8
import sys
from enum import Enum
from typing import List
class VarType(Enum):
INVALID = -1
EXIT = 0
OPERATION = 1
CONDITION = 2
SUBROUTINE = 3
START = 4
END = 5
SELECTED = 6 # 包含选择的条件语句 即yes分支或者no分支
class ConnectType(Enum):
NONE = 0,
NORMAL = 1,
YSE = 2,
... | python |
def lcm(*values):
values = set([abs(int(v)) for v in values])
if values and 0 not in values:
n = n0 = max(values)
values.remove(n)
while any( n % m for m in values ):
n += n0
return n
return 0
lcm(-6, 14)
42
lcm(2, 0)
0
lcm(12, 18)
36
lcm(12, 18, 22)
396
| python |
from GTDLambda import *
from TileCoder import *
import numpy
class DirectStepsToLeftDemon(GTDLambda):
def __init__(self, featureVectorLength, alpha):
GTDLambda.__init__(self, featureVectorLength, alpha)
def gamma(self, state, observation):
encoder = observation['encoder']
if (encoder ... | python |
import os
import numpy as np
from tqdm import tqdm
from PIL import Image
from imagededup.methods import PHash
def run(root: str):
phasher = PHash()
img = Image.open("/home/huakun/datasets/meinv/anime/IMG_0903.PNG")
size = np.asarray(img.size)
scale = 0.1
new_size = (size * scale).astype(int)
i... | python |
#!python
"""
Keras implementation of CapsNet in Hinton's paper Dynamic Routing Between Capsules.
The current version maybe only works for TensorFlow backend. Actually it will be straightforward to re-write to TF code.
Adopting to other backends should be easy, but I have not tested this.
Usage:
python capsulen... | python |
# Copyright 2016 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... | python |
import configparser
import collections
import os
import json
import copy
from .utils import parse_timedelta
from .scrape import get_all_scrapers
import argparse
# Configuration handling
class AltJobOptions(collections.UserDict):
"""
Wrap argparse and configparser objects into one configuration dict object
... | python |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from multi_var_gradient_decent import LinearRegressionUsingGD
from mpl_toolkits.mplot3d import axes3d
from sklearn.metrics import mean_squared_error, r2_score
def create_mesh_grid(start, end):
theta_1 = np.linspace(start, end, 30)
th... | python |
import mxnet as mx
import utils
from model_utils import validate_model
from gluon_zoo import save_mobilenet1_0
from from_tensorflow import tf_dump_model
from os import path
def test_tf_resnet50_v1():
sym_path = "./data/tf_resnet50_v1.json"
prm_path = "./data/tf_resnet50_v1.params"
# if not path.exists(sy... | python |
import click
import reader
from reader._cli import setup_logging
def make_add_response_headers_middleware(wsgi_app, headers):
def wsgi_app_wrapper(environ, start_response):
def start_response_wrapper(status, response_headers, exc_info=None):
response_headers.extend(headers)
return... | python |
from collections import defaultdict
"""
Block
"""
class Block:
def __init__(self, author, round, payload, qc, id, txn_id):
self.author = author
self.round = round
self.payload = payload
self.qc = qc
self.id = id
self.txn_id = txn_id
self.children = []
... | python |
try:
from webdriver_manager.chrome import ChromeDriverManager
except: raise ImportError("'webdriver-manager' package not installed")
try:
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
except: raise ImportError("'selenium' package not installed")
from bs4 import BeautifulSoup... | python |
import requests
user = 'alexey'
password = 'styagaylo'
base_url = 'http://httpbin.org/'
def test_my_first_api():
r = requests.post(base_url + 'post', data={'user': user, 'password': password})
assert r.status_code == 200, "Unexpected status code: {}".format(r.status_code)
assert r.json()['url'] == base_ur... | python |
import plotly.graph_objects as go
import dash
import dash_core_components as dcc
import dash_html_components as html
from matplotlib import pylab
import matplotlib.pyplot as plt
import networkx as nx
# read results from the file
docs = eval(open('final_out_dupe_detect.txt', 'r').read())
final_docs = [[i[0], list(set(... | python |
import re
import os
import math
import subprocess
from MadGraphControl.MadGraphUtils import *
nevents = 10000
mode = 0
mass=0.500000e+03
channel="mumu"
gsmuL=-1
gseL=-1
gbmuL=-1
gbeL=-1
JOname = runArgs.jobConfig[0]
matches = re.search("M([0-9]+).*\.py", JOname)
if matches is None:
raise RuntimeError("Cannot fi... | python |
# coding: utf-8
import sys
import utils
# python .github/workflows/scripts/override_version.py example/tools/analyzer_plugin/pubspec.yaml 1.1.0
pubspec_yaml = sys.argv[1]
version = sys.argv[2]
utils.override_version(pubspec_yaml, version) | python |
"""Define a version number for turboPy"""
VERSION = ('2020', '10', '14')
__version__ = '.'.join(map(str, VERSION))
| python |
from django.db import models
# Create your models here.
class TimeStampedModel(models.Model):
created_at = models.DateTimeField(_(""), auto_now=False, auto_now_add=True)
updated_at = models.DateTimeField(_(""), auto_now=True, auto_now_add=False)
class Meta:
abstract = True
class Image(TimeStampe... | python |
#
# Copyright 2018 Jaroslav Chmurny
#
#
# This file is part of Python Sudoku Sandbox.
#
# Python Sudoku Sandbox is free software developed for educational and
# experimental purposes. It is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with the
# Licens... | python |
# _ __
# | |/ /___ ___ _ __ ___ _ _ ®
# | ' </ -_) -_) '_ \/ -_) '_|
# |_|\_\___\___| .__/\___|_|
# |_|
#
# Keeper Commander
# Copyright 2022 Keeper Security Inc.
# Contact: ops@keepersecurity.com
#
import abc
import json
import logging
from typing import Optional, List, Set, Tuple
from google.protobu... | python |
"""
Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.
Example:
Input:
[1,2,3]
Output:
3
Explanation:
Only three moves are needed (remember each move increments two elements):
[1,2,3] =>... | python |
from __future__ import annotations
import os
import warnings
from datetime import datetime
from pathlib import Path
from typing import (
Any,
Dict,
List,
Optional,
Tuple,
Union,
Sequence,
Iterable,
)
import pydantic
from .managers import ManagerQueryBody, ComputeManager
from .metadata... | python |
import sys
import jinja2
import tdclient
import tdclient.version
from .version import __version__
import logging
logger = logging.getLogger(__name__)
class Context(object):
'''High-level wrapper for tdclient.Client.'''
def __init__(self, module=None, config=None):
if config is None:
conf... | python |
import agama
mass_unit = (1.0/4.3)*(10.0**(6.0))
agama.setUnits(mass=mass_unit, length=1, velocity=1)
pot = agama.Potential(type='Spheroid', gamma=1.0, beta=3.1, scaleRadius=2.5, outerCutoffRadius=15.0)
df = agama.DistributionFunction(type='QuasiSpherical',potential=pot)
model = agama.GalaxyModel(pot,df)
M = model.s... | python |
# Developed for the LSST System Integration, Test and Commissioning Team.
# This product includes software developed by the LSST Project
# (http://www.lsst.org).
# See the LICENSE file at the top-level directory of this distribution
# for details of code ownership.
#
# Use of this source code is governed by a 3-clause ... | python |
# Import the toolkit specific version.
from pyface.toolkit import toolkit_object
TaskWindowBackend = toolkit_object(
'tasks.task_window_backend:TaskWindowBackend')
| python |
# Based on
# https://www.paraview.org/Wiki/Python_Programmable_Filter#Generating_Data_.28Programmable_Source.29
#This script generates a helix curve.
#This is intended as the script of a 'Programmable Source'
def _helix(self, numPts):
import math
#numPts = 80 # Points along Helix
length = 8.0 # Length of Hel... | python |
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth import authenticate, login, logout
from Propylaea.forms import LoginForm, SignUpForm
from django.template import loader
from django.contrib.auth.decorators import login_required
de... | python |
#!/usr/bin/env python
import numpy as np
import h5py as h
import matplotlib
import matplotlib.pyplot as plt
import sys, os, re, shutil, subprocess, time
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--file", action="store", type="string", dest="inputFile", help="Input H5 file with... | python |
import numpy as np
import math
# from mxnet import nd
from mxnet.gluon import nn
class Augmentation(nn.HybridBlock):
def __init__(self, angle_range, zoom_range, translation_range, target_shape, orig_shape, batch_size,
aspect_range = None, relative_angle = 0, relative_scale = (1, 1), relative_translation = 0):
sup... | python |
from __future__ import absolute_import
import os
import sys
import pytest
from collections import defaultdict
myPath = os.path.abspath(os.getcwd())
sys.path.insert(0, myPath)
from salt.exceptions import ArgumentValueError
import hubblestack.extmods.fdg.process
class TestProcess():
"""
Class used to test th... | python |
from pprint import pprint
def sort_with_index(arr):
arr_with_index = []
for i, item in enumerate(arr):
arr_with_index.append((i, item))
arr_with_index.sort(key=lambda it: -it[1])
return arr_with_index
def assign(jobs_with_index, n_not_fulfilled_jobs, n_machines):
assignment = {}
assi... | python |
'''
Copyright 2022 Airbus SAS
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 writing, sof... | python |
#!python
"""
ANNOTATE FUNCTIONS WITH TIME AND SPACE COMPLEXITY!!!!!
"""
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
return linear_search_iterative(array, item)
# return linear_search_recursive(array, item)
def linear_search_iterative(ar... | python |
import json
import sys
import os
from time import sleep
import wxpy
class Greeting:
def __init__(self, name, puid, greeting='{name}新年快乐!狗年大吉!'):
self.name = name
self.puid = puid
self._greeting = greeting
def toJSON(self):
# return str(self.__dict__)
return json.d... | python |
# ----------------------------------------------------------------------
# |
# | CentOsShell.py
# |
# | David Brownell <db@DavidBrownell.com>
# | 2019-08-30 19:25:23
# |
# ----------------------------------------------------------------------
# |
# | Copyright David Brownell 2019-22.
# | Distributed ... | python |
class ReasonCode:
"""Default server reason codes."""
# General error
GENERAL_ERROR = 1
# General session error
SESSION_ERROR = 11
# The session resource is already registered
SESSION_REGISTRATION_ERROR = 12
# An authentication error occurred
SESSION_AUTHENTICATION_FAILED = 13
# ... | python |
from django.db import models
from subscribers import mailchimp
class AbstractSubscriber(models.Model):
email = models.EmailField(blank=True, null=True)
created_on = models.DateField(auto_now_add=True)
objects = models.Manager()
class Meta:
abstract = True
def __str__(self):
retur... | python |
from possum import *
spec = possum()
spec._generateParams(N=30000, fluxMin=0.1, noiseMax=0.2, pcomplex=0.5, seed=923743)
spec._simulateNspec(save=True, dir='data/train/V2/', timeit=True)
| python |
from django.db import models
from djangae.tasks.deferred import defer
from djangae.test import TestCase, TaskFailedError
def test_task(*args, **kwargs):
pass
def assert_cache_wiped(instance):
field = DeferModelA._meta.get_field("b")
assert(field.get_cached_value(instance, None) is None)
class DeferMod... | python |
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | python |
"""
MSX SDK
MSX SDK client. # noqa: E501
The version of the OpenAPI document: 1.0.9
Generated by: https://openapi-generator.tech
"""
import unittest
import python_msx_sdk
from python_msx_sdk.api.workflow_events_api import WorkflowEventsApi # noqa: E501
class TestWorkflowEventsApi(unittest.TestC... | python |
# coding: utf-8
__author__ = 'Paul Cunningham'
__email__ = 'pjcunningham@borsuk.co.uk'
__copyright = 'Copyright 2017, Paul Cunningham'
__license__ = 'MIT License'
__version__ = '0.1'
from .select2 import Select2
| python |
import numpy as np
import pandas as pd
returns = prices.pct_change()
returns.dropna()
returns.std()
deviations = (returns - returns.mean())**2
squared_deviations = deviations ** 2
variance = squared_deviations.mean()
volatility = np.sqrt(variance)
me_m = pd.read_csv('./Data/Portfolios_Formed_on_ME_monthly_EW.csv',... | python |
import logging
from django.contrib.auth.backends import (
RemoteUserBackend,
get_user_model,
)
from django.contrib.auth.models import (
Group,
)
from django.utils.translation import ugettext as _
from rest_framework import exceptions
from rest_framework_auth0.settings import (
auth0_api_settings,
)
fro... | python |
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectUD import DistributedObjectUD
class AccountUD(DistributedObjectUD):
notify = DirectNotifyGlobal.directNotify.newCategory("AccountUD")
| python |
from turtle import color
import matplotlib.pyplot as plt
from matplotlib import patches
import numpy as np
import math
th = np.linspace(0, 2*np.pi, 1000)
r=1
c=r*np.cos(th)
d=r*np.sin(th)
figure, axes = plt.subplots(1)
axes.plot(c,d)
axes.set_aspect(1)
plt.title("sensor position")
plt.plot(1,0,'o',color="blue",)
plt... | python |
#!/usr/bin/python3
import itertools
import os
import re
_RE_INCLUDE = re.compile('#include ([<"])([^"<>]+)')
_LIB_BY_HEADER = {
'curl/curl.h': 'curl',
're2/re2.h': 're2',
'sqlite3.h': 'sqlite3',
}
def dfs(root, get_children):
todo = [root]
visited = {id(root)}
while todo:
item = todo.pop()
yiel... | python |
from django.contrib import admin
from django.urls import path
from .views import IndexClassView, index
urlpatterns = [
path("", index, name="home"),
path(
"class", IndexClassView.as_view(template_name="index.html"), name="home_class"
),
path(
"class2",
IndexClassView.as_view(te... | python |
# -*- coding:utf-8 -*-
from __future__ import print_function
import math
import numpy as np
import os
import sys
sys.path.insert(0, '../facealign')
sys.path.insert(0, '../util')
from caffe_extractor import CaffeExtractor
def model_centerface(do_mirror):
model_dir = './models/centerface/'
model_proto = mod... | python |
from raytracer.tuple import (
tuple,
point,
vector,
magnitude,
normalize,
dot,
cross,
reflect,
Color,
)
from raytracer.rays import Ray
from raytracer.spheres import Sphere
from raytracer.intersections import Intersection, intersections, hit, prepare_computations
from raytracer.lights... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.