content stringlengths 5 1.05M |
|---|
"""
Tests for the DjangoXBlockUserService.
"""
import pytest
from django.test import TestCase
from opaque_keys.edx.keys import CourseKey
from openedx.core.djangoapps.user_api.preferences.api import set_user_preference
from openedx.core.djangoapps.external_user_ids.models import ExternalIdType
from common.djangoapps.s... |
"""
Simulate tumor growth under different spatial models. Inspired by Noble et al, 2019.
"""
from .cell import TumorCell
from .modes import *
import numpy as np
import pandas as pd
import click
import os
from pathlib import Path
import logging
MODE_LIST = [
simulate_nonspatial,
simulate_invasion,
simulat... |
"""
Application Settings for Python WorkLog w DB
DATE_FORMAT: Is the display format to be used for
display in the terminal when a Task is being shown.
COMPANY_NAME: Used for the company title prompts inside
the application. Also used as reference for database filename.
Ex:
COMPANY_NAME = 'MY_COMPANY'
will look for o... |
# --------------------------------------------------------
# Python Single Object Tracking Evaluation
# Licensed under The MIT License [see LICENSE for details]
# Written by Fangyi Zhang
# @author fangyi.zhang@vipl.ict.ac.cn
# @project https://github.com/StrangerZhang/pysot-toolkit.git
# Revised for SiamMask by f... |
from os import makedirs, getenv
from tensorflow.keras import backend as K
from tensorflow.keras import callbacks, initializers
from contextlib import redirect_stdout
def train(model, data_gen, save_dir, epochs, callbacks):
makedirs(save_dir, exist_ok=True)
model.fit(
data_gen.training_generator,
... |
# Copyright (c) 2019 ETH Zurich, Lukas Cavigelli, Georg Rutishauser, Luca Benini
import csv
import os
def readTable(tableName='totalComprRate-alexnet-after ReLU'):
filename = './results/%s.csv' % tableName
with open(filename, 'r') as csvfile:
cr = csv.reader(csvfile)
tbl = [row for row in cr]
... |
#!/usr/bin/env python3.6
"""Trains logistic regression models for abnormalities, ACL tears and meniscal
tears, by combine predictions from CNN models.
Usage:
train_lr_models.py <data_dir> <models_dir>
train_lr_models.py (-h | --help)
General options:
-h --help Show this screen.
Arguments:
<data_dir> ... |
import matplotlib
from .. import logger
try:
import matplotlib.pyplot as plt
except: # pylint: disable=bare-except
GUI_ENV = ['TKAgg', 'GTKAgg', 'Qt4Agg', 'WXAgg']
for gui in GUI_ENV:
try:
logger.debug(f'Testing {gui}')
matplotlib.use(gui, warn=False, force=True)
... |
#!/usr/bin/env python3
from tsdb import TSDBServer, DictDB
import timeseries as ts
identity = lambda x: x
schema = {
'pk': {'convert': identity, 'index': None}, # Will be indexed anyways
'ts': {'convert': identity, 'index': None},
'order': {'convert': int, 'index': 1},
'blarg': {'convert': int, 'index': 1},
... |
from functools import partial
import numpy as np
import torch.nn as nn
from dpipe.layers import PreActivationND
from dpipe.im.utils import identity
from dpipe.im.shape_ops import crop_to_shape
class ResBlock(nn.Module):
"""
Performs a sequence of two convolutions with residual connection (Residual Block).
... |
#!/usr/bin/env python
import load
from matplotlib import pyplot as plt
import matplotlib as mpl
import numpy as np
from gna.env import env
from gna.labelfmt import formatter as L
from mpl_tools.helpers import savefig, plot_hist, add_colorbar
from scipy.interpolate import interp1d
from argparse import ArgumentParser
im... |
# coding=utf-8
__author__ = "Gareth Coles"
"""
Replace the number below with your Discord user ID. Check out the README.md for this repository for more information
on how to find it.
If you don't have a Discord account, please set this to None instead.
"""
__learner__ = "140605665772175361"
# __learner__ = None
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2016-12-09 16:59
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('documents', '0002_auto_20161209_1658'),
]
operations =... |
#!/usr/bin/env python
# trajectory_file_handler.py
# Copyright (C) 2018 Niryo
# All rights reserved.
#
# 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 3 of the License, or
# (at ... |
class abstractModel:
def init_model(self):
raise NotImplementedError("Please implement init_model interface in your model class")
def run_model(self, data: {}, param: {}) -> {}:
raise NotImplementedError("Please implement run_model interface in your model class")
def delete_model(self):
raise NotImp... |
import os
DEBUG = True
TEMPLATES_AUTO_RELOAD = True
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
|
#!/bin/env python3
"""
A tool for painting and saving Game Boy tiles.
Usage: `python3 gb-tile-painter.py`
Please see: README.md.
"""
from sys import argv, exit
# If we got an argument and it is --help or -h
if len(argv) == 2 and (argv[1] == "--help" or argv[1] == "-h"):
print(__doc__) # Print the docstring
... |
#!/usr/bin/python
import serial
import time
ser = serial.Serial("/dev/ttyUSB0",baudrate=9600)
while True:
bytesToRead = ser.inWaiting()
data = ser.read(bytesToRead)
if(bytesToRead):
my_hex = data.decode('hex')
print " ".join(hex(ord(n)) for n in my_hex)
|
from clusto.drivers.base import Device
from clusto.drivers.devices.common import PortMixin, IPMixin
class BasicServer(IPMixin, PortMixin, Device):
"""
server
"""
_clusto_type = 'server'
_driver_name = 'basicserver'
_properties = {'model':None,
'manufacturer':None}
_por... |
#!/usr/bin/python
import pytest
import sys
import classes.user as U
def test_user_class_init():
user_object = U.User('testuser1@test.com')
assert user_object.user_id == 'testuser1@test.com'
def test_user_class_init_no_value():
with pytest.raises(Exception) as e_info:
obj = U.User()
|
import csv
from datetime import datetime
all_product = {}
PRODUCT_INXEX = 0
NAME_INDEX = 1
PRICE_INDEX = 2
QUANTITY_INDEX = 1
PRODUCT_REQUEST_INDEX = 0
def main():
read_product_store = read_product("/home/andredosreis/Documentos/Estudos/BYU-Programming-with-fuctions/week-9/Prove/products.csv",PRODUCT_INXEX, ... |
'''Iris
@author: Ethan Lew
'''
from sklearn.datasets import load_iris
import pandas as pd
import numpy as np
from classifier import PartitionData, SimpleClassifier, risk
def load_iris_data(s0, s1, ratio):
# Get Iris Data
iris_sk = load_iris()
species_lp = {'I. setosa': 0, 'I. versicolor': 1, 'I. virgini... |
from ..common import BaseModule
import json
class BaseOutput(BaseModule):
def render(self, event):
if "format" in self.options:
fmt = self.options["format"]
return fmt.format(**event)
else:
return json.dumps(event)
def __call__(self, event):
raise N... |
# -*- coding: utf-8 -*-
from django.conf.urls import include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
class AdminSite(admin.AdminSite):
def has_permission(self, request):
... |
import datetime
import numpy as np
def assign_learning_rate(optimizer, new_lr):
print("assigned lr: " + str(new_lr))
for param_group in optimizer.param_groups:
param_group["lr"] = new_lr
def cosine_lr(optimizer, args, **kwargs):
def _lr_adjuster(epoch, iteration):
if epoch < args.warmup_le... |
import pytest
from loan_calculator.schedule.price import (ProgressivePriceSchedule,
RegressivePriceSchedule)
def test_progressive_price_amortization_schedule():
"""Assert basic textbook scenario."""
principal = 8530.20
daily_interest_rate = 0.03
return_days ... |
# Import libraries for GDAL, SQL
import ogr,csv,sys
import pyodbc
## Use this only for Azure AD end-user authentication
#from azure.common.credentials import UserPassCredentials
## Use this only for Azure AD MFA
#from msrestazure.azure_active_directory import AADTokenCredentials
## Required for ADLS accoun... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import Int32
from geometry_msgs.msg import PoseStamped, Pose
from styx_msgs.msg import TrafficLightArray, TrafficLight
from styx_msgs.msg import Lane
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
from light_classification.tl_classifier import TLCla... |
from enum import IntEnum
from typing import Optional
from pydantic import Field
from swagger_doc import *
from swagger_doc.models import SecurityModel, SecurityType, SecuritySchema, SResponse200
class TQuery(SQuery):
__example__ = {"limit": 10, "offset": 20}
limit: int = Field(description="页限制", alias="Lim... |
# Copyright 2016 FUJITSU LIMITED
# (C) Copyright 2016-2017 Hewlett Packard Enterprise Development LP
#
# 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... |
#!/usr/bin/python3
# Copyright (c) 2017 NVIDIA CORPORATION. All rights reserved.
# See the LICENSE file for licensing terms (BSD-style).
from __future__ import print_function
import sys
import glob
from distutils.core import setup # , Extension, Command
scripts = glob.glob("dli-*[a-z]")
setup(
name='dlinputs',... |
import unittest
from unittest import mock
import dateutil.parser
import dateutil.tz
from togglsync.config import Entry
from togglsync.toggl import TogglEntry
class TogglEntryTests(unittest.TestCase):
sample_config = Entry("test", task_patterns=["SLUG-[0-9]+"])
def test_parse(self):
toggl_payload = ... |
import numpy as np
import time
from scipy.special import softmax
from solvers.simulated_annealing import return_mat
def update_probs_metropolis(H, attacker, hmms_old, value_old, z):
hmms = []
value = 0
for h in range(H):
hmm_sample = attacker.sample_hmm()
value += np.log(... |
import logging
import os
import typing as T
import pandas as pd
import pyspark
import pyspark.sql
from .config import DBConfig
|
#!/usr/bin/env python
import unittest
from selenium.common.exceptions import NoSuchElementException
from framework.lib.general import *
class URLLauncher(unittest.TestCase):
def __init__(self, selenium, base_url, vector_file):
self.Selenium = selenium
self.URLList = []
for vector in get... |
from .compute import run_full
from .compute import resume
from .compute import sample_run
from .compute import execute_list
from .compute import cleanup
from .compute import clean_s3
from .compute import get_logs
from .compute import update_environment
from .compute import delete_runs
from .compute import run_file
from... |
#from connect import *
print("definitions setup")
def LWheels(speed):
negative = False
speed = int(speed)
# I don't understand this condition here. Why are you excluding -10,9,...,-1,1,...,9,10?
if (speed > 10 and speed < 999) or (speed < -10 and speed > -999):
if speed < -10:
speed... |
import unittest
from jmetal.component.density_estimator import CrowdingDistance
from jmetal.core.solution import Solution
class CrowdingDistanceTestCases(unittest.TestCase):
def setUp(self):
self.crowding = CrowdingDistance()
def test_should_the_crowding_distance_of_an_empty_set_do_nothing(self):
... |
import json
import os
import pulumi
from pulumi import Output, ResourceOptions
from pulumi_azure.containerservice import KubernetesCluster, Registry
from pulumi_azure.core import ResourceGroup
from pulumi_azure.cosmosdb import Account, SqlContainer, SqlDatabase, Table
from pulumi_azure.network import Subnet, VirtualNe... |
from manipulator.manipulator import Manipulator
tor_cmd = "service tor restart"
reporter = Manipulator(tor_cmd)
reporter.test()
|
"""Here, we'll do a simple test where we vary the mass of hydrogen,
and see what this does to max stable timestep..."""
from pickle import dump
import numpy as np
from openmmtools.integrators import LangevinIntegrator, GHMCIntegrator
from openmmtools.testsystems import AlanineDipeptideVacuum
from simtk import unit
... |
from pyk4a import PyK4A
# Load camera with the default config
k4a = PyK4A()
k4a.start()
# Get the next capture (blocking function)
capture = k4a.get_capture()
img_color = capture.color
# Display with pyplot
from matplotlib import pyplot as plt
plt.imshow(img_color[:, :, 2::-1]) # BGRA to RGB
plt.show()
|
version_cmd = 'influxdb -v'
download_url = 'http://s3.amazonaws.com/influxdb/influxdb_latest_amd64.deb'
install_script = """
dpkg -i influxdb_latest_amd64.deb
service influxdb start
"""
|
"""Added relationship to the tables.
Revision ID: 72fa0ea05859
Revises: bcd0ac838ce7
Create Date: 2019-04-23 19:42:58.081658
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '72fa0ea05859'
down_revision = 'bcd0ac838ce7'
branch_labels = None
depends_on = None
d... |
import ply.yacc as yacc
import cmath
from mathpy.grammar.complex.lexer import tokens
precedence = (
('nonassoc', 'SINE', 'COSINE', 'SECANT', 'COSECANT', 'TANGENT', 'COTANGENT', 'LOG', 'EXP', 'ARCSINE', 'ARCCOSINE', 'ARCTANGENT', 'SINEH', 'COSINEH', 'TANGENTH', 'ARCSINEH', 'ARCCOSINEH', 'ARCTANGENTH'),
('left',... |
class Solution:
def XXX(self, n: int) -> str:
from collections import deque
init = "1"
for _ in range(n - 1):
ans = ""
j = 0
while j < len(init):
tmp = deque()
tmp.append(init[j])
j += 1
while... |
#!/usr/bin/python
#
# Copyright (c) 2019 Zim Kalinowski, (@zikalino)
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
#!/usr/bin/env python3
"""scapy-dhcp-listener.py
Listen for DHCP packets using scapy to learn when LAN
hosts request IP addresses from DHCP Servers.
Copyright (C) 2019 Shamiul Hasan
License MIT
"""
from __future__ import print_function
import argparse
import binascii
from scapy.all import *
from scapy.layers.dhcp im... |
'''
created 05/15/2014
by sperez
Contains skeletons of files needed to make hive panel files.
'''
parameters_file = ''' // ****************************************** //
// USER DEFINED PARAMETERS //
// ****************************************** //
var numAxes = {0} //number of axes p... |
from Database import Database
from Catalog.Schema import DBSchema
db = Database(dataDir='./data');
'''
exp 1
TPC-H Query 6: a 4-chain filter and aggregate query
select
sum(l_extendedprice * l_discount) as revenue
from
lineitem
where
l_shipdate >= 19940101
and l_shipdate < 19950101
... |
# Copyright (c) 2020 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 appli... |
#Encript Marshal By XVenom
#https://github.com/xvenom15
import marshal
exec(marshal.loads(b'\xe3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00@\x00\x00\x00s\x80\x00\x00\x00d\x00d\x01l\x00Z\x00d\x00d\x01l\x01Z\x01d\x00d\x01l\x02Z\x02d\x00d\x02l\x02m\x03Z\x03\x01\x00d\x00d\x03l\x04m\x05Z... |
import copy
import random
import sys
import numpy
from keras.models import Sequential
from keras import regularizers
from keras.layers import Dense, Dropout
from keras.layers import GlobalMaxPooling1D, GlobalAveragePooling1D
from keras.layers import Embedding, LSTM, Bidirectional, TimeDistributed
from keras.callbacks i... |
"""
Data models used by bookops-marc
"""
from collections import namedtuple
Order = namedtuple(
"Order",
[
"oid",
"audn",
"branches",
"copies",
"created",
"form",
"lang",
"shelves",
"status",
"venNotes",
],
defaults=[None,... |
import torch
import torch.nn as nn
from omegaconf import OmegaConf
from .lvcnet import LVCBlock
MAX_WAV_VALUE = 32768.0
class Generator(nn.Module):
"""UnivNet Generator"""
def __init__(self, hp):
super(Generator, self).__init__()
self.mel_channel = hp.audio.n_mel_channels
self.noise_d... |
#class - collection of attributes and methods
#idea of putting data and functions together in a class
class helloworld:
def sum(x,y):
c=x+y
return c
print(sum(10,15)) |
import logging
import sentry_sdk
from django.contrib.auth.models import AnonymousUser
from django.utils.functional import SimpleLazyObject
from atlas.models import User
from atlas.utils.auth import parse_token, security_hash
def get_user(header):
if not header.startswith("Token "):
return AnonymousUser(... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import re
import yaml
import argparse
import requests
import pyperclip
from datetime import datetime
from bs4 import BeautifulSoup
# ================== 命令行输入参数,默认值:0 ======================== #
parser = argparse.ArgumentParser(usage='参数说明')
parser.add_argument('-p', dest='p... |
import re
import csv
import StringIO
import datetime
from billy.scrape.bills import BillScraper, Bill
from billy.scrape.votes import Vote
import lxml.html
import scrapelib
def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
csv_re... |
import re
def flatten_white_space(input_string, expression=" +", replacement=" "):
return re.sub(expression, replacement, input_string)
def parse_rel_result_str(string, delimiter=' ', empty_start=True):
''' string : input string'''
''' delimiter : seperates results'''
'''empty_start : is first result ... |
# -*- coding: utf-8 -*-
from numpy import pi
from ....Methods.Slot.Slot.check import SlotCheckError
def check(self):
"""Check that the SlotW22 object is correct
Parameters
----------
self : SlotW22
A SlotW22 object
Returns
-------
None
Raises
-------
S22_A02CheckEr... |
#!/usr/bin/env python
from distutils.core import setup
from codemirror import __version__
setup(
name='django-codemirror',
version=__version__,
author='Andrey',
author_email='and@rey.im',
url='https://github.com/onrik/django-codemirror',
description='Django form widget for CodeMirror text edit... |
#%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import functools
# Part 2: Plotting
data = np.genfromtxt ('ex1data1.txt', delimiter=",")
X = np.matrix(data[:, 0]).T
y = np.matrix(data[:, 1]).T
m = len(y)
plt.scatter(X, y, alpha=0.7)
plt.show()
ones = np.ones((m, 1))
X = np.hs... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# CODE NAME HERE
# CODE DESCRIPTION HERE
Created on 2019-07-26 at 09:40
@author: cook
"""
import sys
from apero.lang.core import port_database
# =============================================================================
# Define variables
# ====================... |
from ..common import progress_bar, canonical
from ..types import Document, DocumentSet, DocumentIdentifier, Author, \
Affiliation
from collections import defaultdict
from datetime import date
from typing import Tuple, Optional
import logging
import random
import shelve
SCOPUS_CACHE = '.scopus'
cl... |
from toontown.toonbase.ToontownBattleGlobals import *
import DistributedBarrelBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.task import Task
class DistributedGagBarrelAI(DistributedBarrelBaseAI.DistributedBarrelBaseAI):
def __init__(self, level, entId):
x = y = z = h = 0
se... |
# gui.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
import brownie
from brownie import config, network, DuelPoints, JustaDuel, MockV3Aggregator
import numpy as np
ERR_MSG = ""
card_type ... |
# NOTE: loading the data manager (main source for queries).
from src.Managers import DataManager
# NOTE: doing some arbitary sanity checks.
print("1. Loading the data manager.")
dm = DataManager("data/users.json", "data/safe_users.json")
print("2. Check the number for each of the purchased items.")
print(" ", dm.que... |
# 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 applicable law or a... |
import glob
import json
from argparse import ArgumentParser
from logging import getLogger
from video_behavior_tracking import (convert_to_loren_frank_data_format,
detect_LEDs, extract_position_data,
make_video, position_dataframe,
... |
#!/usr/bin/env python
from __future__ import with_statement
try:
from setuptools import setup
except ImportError:
# Distribute is not actually required to install
from distutils.core import setup
__AUTHOR__ = 'David Halter'
__AUTHOR_EMAIL__ = 'davidhalter88@gmail.com'
readme = open('README.rst').read() +... |
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = []):
self.val = val
self.neighbors = neighbors
# # Correct, DFS Version
# class Solution:
# def __init__(self):
# self.map = dict()
# def cloneGraph(self, node: 'Node') -> 'Node':
# if not node: # ... |
import base64
import json
import os
import time
from PIL import Image
import requests
import cv2
import parameters
ENDPOINT = parameters.ENDPOINT
def send(timestamp, image, detections):
#base64 image string from image
retval, buffer = cv2.imencode('.jpg', image)
jpg_as_text = base64.b64encode(buffer)
... |
# BOJ 10282 해킹
import heapq
import sys
sys.stdin = open("../input.txt", "r")
si = sys.stdin.readline
INF = 987654321
def dijkstra(start, visited):
q = []
visited[start] = 0
heapq.heappush(q, (0, start))
while q:
dist, now = heapq.heappop(q)
if visited[now] < dist:
continue... |
from django.shortcuts import render
from django.views.generic import CreateView, UpdateView
from .models import Produto
from .forms import ProdutoForm
# Create your views here.
def produto_list(request):
template_name='produto_list.html'
objects= Produto.objects.all()
context={'object_list':objects}
re... |
import os
import sys
import glob
import numpy as np
import pandas as pd
sys.path.insert(1, os.path.dirname(os.getcwd()) + "/GenNet_utils/")
import matplotlib
matplotlib.use('agg')
import tensorflow as tf
import tensorflow.keras as K
import scipy
import tables
tf.keras.backend.set_epsilon(0.0000001)
tf_version = tf.__... |
# 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... |
from Controller import Controller
from Puzzle import Puzzle
controller = Controller()
|
"""
Train a LogisticRegression model
on the Titanic dataset
"""
import sys
from pathlib import Path
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
sys.path.append(str(Path(__file__).resolve().parents[1]))
from src.feature_engineering import get_datas... |
from sklearn.datasets import fetch_20newsgroups
newsgroups_train = fetch_20newsgroups(subset='train')
newsgroups_test = fetch_20newsgroups(subset='test')
x_train = newsgroups_train.data
x_test = newsgroups_test.data
y_train = newsgroups_train.target
y_test = newsgroups_test.target
print ("List of all... |
# -*- coding: utf-8 -*-
# perceptron_primal.py
"""
Created by jin.xia on May 09 2017
@author: jin.xia
"""
import os
import operator
import numpy as np
#
class perceptron_primal():
def __init__(self, learning_rate=1):
self.learning_rate = learning_rate
self.w = []
self.b = 0
def learning(self, training_... |
'''This file is a template for how to write tests for this library
The test are for the nonexistent 'DeadBeef' library, located in
spotifython/deadbeef.py
Note that this code doesn't compile as is because DeadBeef doesn't exist
'''
# These 2 statements are fine to include in your test file
#pylint: disable=missing-cl... |
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
n = len(nums2)
ans = []
for value in nums1:
index = nums2.index(value) + 1
while index < n:
if nums2[index] > value:
ans.append(nums2[ind... |
# coding: utf-8
from __future__ import unicode_literals
import pytest
from typecraft_python.integrations.obt.tagger import ObtTagger, obt_available
@pytest.mark.skipif(not obt_available, reason="Obt is not enabled.")
class TestObtTagger(object):
def test_parse_raw(self):
raw_text = "Han kunne ikke løpe ... |
"""Logging configuration."""
from django.template.base import VariableDoesNotExist
EXCLUDE_EXCEPTIONS = [
VariableDoesNotExist,
]
# Lowercase only
EXCLUDE_PHRASES = [
'invalid http_host header',
]
def filter_exc_by_type(record):
"""Exclude blacklisted exception types."""
if record.exc_info:
... |
# Copyright 2016 Quora, 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 agreed to in writing, so... |
# -*- coding: utf-8 -*-
"""This module exposes Annotator Auth as OAuthLib bearer tokens."""
from annotator.auth import DEFAULT_TTL, encode_token
from oauthlib import oauth2
def token_generator(request):
"""
Generate a token from a request.
The request must have the ``client`` and `extra_credentials`` pro... |
# Copyright 2019 Silverbackhq
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
#
# 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... |
####################################################################################
#
# HelloWorld.py
#
# Practice for git push and pull
#
# M. Brinkerhoff * UCSC, SIP2020 * 2020 July 14 (Tu)
#
####################################################################################
print("Hello World!") |
import json
from datetime import datetime, timedelta
from babel.dates import format_datetime, format_date
from odoo import models, api, _, fields
from odoo.osv import expression
from odoo.release import version
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT as DF, safe_eval
from odoo.tools.misc import formatLang
... |
import os
from toolchain import run_script
from commands import CMD_APP_INFO
package = os.getenv('package')
try:
run_script(CMD_APP_INFO.format(package))
print("App info of " + package + " shown")
except:
print("Failed to show app info of " + package) |
# print('Hello World!')
# print writes a mensage in your screen
nome = input('Whats your name? ')
idade = input('how old are you? ')
peso = input('whats your weight? ')
# The input means read the mensage
print(nome,idade,peso) |
#Copyright (C) 2020 The Sonia Roy companyy LLC.
#
# Licensed under theSonia Roy Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
"""Check if userbot alive. Codes by Nfx Phantom . Anybody if tries to change would be taken under serious custody and legal acti... |
def plus_minus(coll_int):
plus = minus = zero = 0
base = 1
per_base = base / len(coll_int)
for value in coll_int:
if value > 0:
plus += 1
per_plus = plus * per_base
if value < 0:
minus += 1
per_minus = minus * per_base
if value =... |
import pandas as pd
from urllib.request import urlopen
import requests
from bs4 import BeautifulSoup
import locale
locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )
from tqdm import tqdm
def GitHubStarsToCSV(GitHubUsername):
df_list = []
url1 = urlopen("https://github.com/{}?page=1&tab=stars".format(GitHubUser... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-11-12 13:44
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0001_initial'),
]
operations = [
m... |
'''The Cobol data model.'''
import sys
import os
from AST import AstType, PrimitiveType, ClassType, UnionType, ListType
# from AST import INT, BOOL, STRING
from ASTExt import NodeType
AstType.prefix = ""
AstType.ast_node_name = "AstNode"
STRING = PrimitiveType("string", "varchar(1)")
#STRING_LIST = ListType(STRING)
... |
# -*- coding: utf-8 -*-
"""
Editor de Spyder
Este es un archivo temporal
"""
print (tutorialcsv)
col0 col1 col2 col3
0 -0.722876 -1.330682 1.309208 0.232378
1 1.160396 -0.730879 0.677368 1.044722
2 -1.062870 -0.503704 -0.238536 -1.417937
3 0.437078 0.362640 -0.111228 -1.649853
tutorialcs... |
# 4.3.3 ポアソン混合分布における推論:変分推論
#%%
# 4.3.3項で利用するライブラリ
import numpy as np
from scipy.stats import poisson, gamma # ポアソン分布, ガンマ分布
from scipy.special import psi # ディガンマ関数
import matplotlib.pyplot as plt
#%%
## 観測モデル(ポアソン混合分布)の設定
# K個の真のパラメータを指定
lambda_truth_k = np.array([10.0, 25.0, 40.0])
# 真の混合比率を指定
pi_truth_k = np.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.