content stringlengths 5 1.05M |
|---|
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
from tempeh.configurations import datasets, models
# Helpers to restrict execution to single combinations via environment variables
# to parallelize execution through devops system.
def get_selected_datasets():
... |
from ost import io, seq
from promod3 import modelling, loop
from pathlib import Path
from sys import argv
# this will work to fetch the pdb file, with the name of the pdb passed in the dommand line
def get_id(dir):
path = dir+'/var/pdbID.txt'
pdb = ''
with open(path,'r') as p:
pdb=p.read()
pdb = ... |
from drain.step import *
from drain import step
import numpy as np
import tempfile
class Scalar(Step):
def __init__(self, value):
Step.__init__(self, value=value)
def run(self):
return self.value
class Add(Step):
def run(self, *values):
return sum(values)
class Divide(Step):
... |
from flask import render_template
from app import app, db
from werkzeug.exceptions import HTTPException
@app.errorhandler(404)
def not_found_error(error):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_error(error):
db.session.rollback()
return render_template('500.html'), 5... |
import wikipedia
from birdy.models import Bird
a = Bird.objects.all()
for i in a:
b = wikipedia.page(i.name)
i.url = b.url
|
from model import photoshop
import os
from PIL import Image
if __name__ == "__main__":
ps1 = photoshop.Photoshop()
#path = '/Users/dennisping/Documents/image-processor-mvc/res/lowfi.jpg'
#path = '/Users/dennisping/Documents/image-processor-mvc/res/city_nezuko_by_eternal_s.jpg'
path = '/Users/dennisping... |
from django.shortcuts import render_to_response
from django.template import RequestContext
from livesettings import config_value
from satchmo_ext.productratings.queries import highest_rated
def display_bestratings(request, count=0, template='product/best_ratings.html'):
"""Display a list of the products with the b... |
"""
methods to probe a WAV file for various kinds of production metadata.
Go to the documentation for wavinfo.WavInfoReader for more information.
"""
from .wave_reader import WavInfoReader
from .riff_parser import WavInfoEOFError
__version__ = '1.6.3'
__author__ = 'Jamie Hardt <jamiehardt@gmail.com>'
__license__ = "... |
thinkers = ['Plato','PlayDo','Gumby']
while True:
try:
thinker = thinkers.pop()
print(thinker)
except IndexError as e:
print("We tried to pop too many thinkers")
print(e)
break |
import datetime
import asyncio
import gzip
import json
import urllib.parse
import bisect
from urllib.parse import parse_qs
import yarl
import pendulum
from ccxt import huobipro
from uxapi import register_exchange
from uxapi import UXSymbol
from uxapi import WSHandler
from uxapi import UXPatch
from uxapi import Queue
... |
import typing as _t
from pathlib import Path as _Path
from .dependency import dependency as _dep
class NotPossibleToMinify(Exception): pass
class Minifier:
HTML = 'https://html-minifier.com/raw'
CSS = 'https://cssminifier.com/raw'
JS = 'https://javascript-minifier.com/raw'
EXTENSIONS = ('.html', '.... |
import os
from datetime import datetime, timedelta
import uuid
from .file_manager import FileManager
from .validation import file_exists
class Events(object):
def __init__(self, filename):
self.file_manager = FileManager(filename)
self.events = []
self.specific_events = []
def get_e... |
import math
from piecewise_polynomial_fitting import *
from normal_distribution import *
class semi_analytic_domain_integrator(object):
def __create_cached_moments(self, x, f):
n = x.shape[0]
self.__ys = numpy.zeros([n, 4])
self.__ys[2] = f.moments(4, x[2]) # cubic
for j in range(2, n-2)... |
import os
import glob
import nibabel as nib
import numpy as np
import shutil
from nipype.interfaces.ants import N4BiasFieldCorrection
from sklearn.feature_extraction.image import extract_patches as sk_extract_patches
from sklearn.utils import shuffle
import scipy.misc
num_mod = 2
def get_filename(set_name, case_idx, ... |
import os
from datetime import datetime
from http import HTTPStatus
from json import JSONDecodeError
from math import floor
from typing import Callable, Type, Union
import inject
from flask import Flask, session, Response, request
from flask_sockets import Sockets
from geventwebsocket.websocket import WebSocket
from s... |
# -*- coding: utf-8 -*-
# from evaluate import strict, loose_macro, loose_micro
import logging
def f1(p, r):
if r == 0.:
return 0.
return 2 * p * r / float(p + r)
def strict(true_and_prediction):
num_entities = len(true_and_prediction)
correct_num = 0.
for true_labels, predicted_labels i... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
from .mnist import MNIST_Dataset
from .fmnist import FashionMNIST_Dataset
from .cifar10 import CIFAR10_Dataset
from .odds import ODDSADDataset
def load_dataset(dataset_name, data_path, normal_class, known_outlier_class, n_known_outlier_classes: int = 0,
ratio_known_normal: float = 0.0, ratio_k... |
import tensorflow as tf
import tensorflow_text as text
import tensorflow_hub as hub
raw_bert = hub.load('./kcbert-base/model/0')
raw_preprocess = hub.load('./kcbert-base/preprocess/0')
bert = hub.KerasLayer(raw_bert, trainable=True)
preprocess = hub.KerasLayer(raw_preprocess, arguments={"seq_length": 48})
input_node... |
from kivy.lang.builder import Builder
from kivymd.uix.card import MDCard
Builder.load_string(
"""
<RoundButton>:
width: '55dp'
size_hint_x: None
elevation: 0
md_bg_color: app.theme_cls.opposite_bg_normal
radius: '10dp'
text: ''
ripple_behavior: True
theme_text: 'Custom'
... |
#%%
# First read in the datasets. One Graduate school admission dataset, one Titanic survival dataset
# need to load api_dsLand
# from turtle import color
import dm6103 as dm
dfadmit = dm.api_dsLand('gradAdmit')
# dm.dfChk(dfadmit, True)
#%%
# quick plots
import matplotlib.pyplot as plt
# add color
import numpy as np... |
from ft_map import ft_map
from ft_filter import ft_filter
from ft_reduce import ft_reduce
iterable = [1, 2, 3, 4, 5]
functions = {
"map": ft_map,
"filter": ft_filter,
"reduce": ft_reduce,
}
def unit_test(message, function_to_test, function_to_apply, iterable):
try:
print("\n=> ", message)
... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import datetime
import typing as t
import json
from dataclasses import dataclass, field
from mypy_boto3_dynamodb.service_resource import Table
from boto3.dynamodb.conditions import Attr, Key, And
from botocore.exceptions import ClientError
"""
Dat... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author: Fang Zhang <thuzhf@gmail.com>
import sys,os,json,gzip,math,time,datetime,random,copy
import functools,itertools,requests,pickle,configparser
import argparse,logging,uuid,shutil,collections
from urllib.parse import urlparse, parse_qs
from collections import defa... |
import numpy as np
import pandas as pd
import datetime
import argparse
def readCSV(dt):
"""
Read the CSV file into a dataframe for a YYYY-MM (dt)
Do preliminary cleaning
arg: dt -- string with format YYYY-MM
return df: dataframe containing data from csv
"""
folder = 'raw_da... |
import numpy as np
from glacier.physics import GlacierParameters
from glacier.solvers import Solver
L = 500
n_x = L + 1
xs = np.linspace(0, L, n_x)
H = 25
alpha = np.radians(3)
t_end = 10
h_0 = 50
upwind_scheme = False
steady_state = False
plot_initial = False
if steady_state:
q_0 = 1
glacier = GlacierParam... |
import cv2
o = cv2.imread(r"..\lena.jpg")
g = cv2.GaussianBlur(o, (55, 55), 0, 0)
b = cv2.bilateralFilter(o, 55, 100, 100)
cv2.imshow("original", o)
cv2.imshow("Gaussian", g)
cv2.imshow("bilateral", b)
cv2.waitKey()
cv2.destroyAllWindows()
|
import os
import torchvision.transforms as transforms
import flow_transforms
from imageio import imread, imsave
from skimage import img_as_ubyte
from loss import *
def vis(img_path, csv_path, save_path):
input_transform = transforms.Compose([
flow_transforms.ArrayToTensor(),
transforms.Normalize(m... |
from collections import OrderedDict
from concurrent import futures
from datetime import datetime, timedelta
import ftplib
import math
import os
from os import PathLike
from pathlib import Path
from typing import Collection
import fiona.crs
import numpy
import rasterio
from rasterio.crs import CRS
from rasterio.enums i... |
#!/usr/bin/env python
"""
ViperMonkey: VBA Grammar - Library Functions
ViperMonkey is a specialized engine to parse, analyze and interpret Microsoft
VBA macros (Visual Basic for Applications), mainly for malware analysis.
Author: Philippe Lagadec - http://www.decalage.info
License: BSD, see source code or documentati... |
# sigtools - Collection of Python modules for manipulating function signatures
# Copyright (C) 2013-2021 Yann Kaiser
#
# 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, inc... |
"""
In training deep networks, it is usually helpful to anneal the learning rate over time. Good intuition to have in mind
is that with a high learning rate, the system contains too much kinetic energy and the parameter vector bounces around
chaotically, unable to settle down into deeper, but narrower parts of the lo... |
# -*- coding: utf-8 -*-
"""Activate venv for current interpreter:
Use `import venv` along with a `--venv path/to/venv/base`
This can be used when you must use an existing Python interpreter, not the venv bin/python.
"""
import os
import site
import sys
if "--venv" in sys.argv:
# Code inspired by virutal-env::bin... |
#!/usr/bin/env python3
# Importing computational model
import sys
sys.path.append('./model')
sys.path.append('./helpers')
from model import *
from helpers import *
# Starting Korali's Engine
import korali
####### Bayesian Problems
##### No NUTS
e = korali.Experiment()
e["Console Output"]["Frequency"] = 100
e["Fil... |
import logging
import os
from docserver.api import schemas
logger = logging.getLogger(__name__)
HTML_LATEST_REDIRECT = """
<!DOCTYPE HTML>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="1; url=latest/">
<script>
window.location.href = "latest/"
</script>
<title>Page Redirection</title>
If you are n... |
#
# Copyright 2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later version.
#
#... |
#author: akshitac8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os,sys
pwd = os.getcwd()
sys.path.insert(0,pwd)
print('-'*30)
print(os.getcwd())
print('-'*30)
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from model i... |
#!/usr/bin/env python3
import bird_view
import binary_filter
import camera_calibration
import cv2
from line_finder import LineFinder
import numpy as np
class Pipeline:
def __init__(self):
self.camera_model = camera_calibration.Model()
self.camera_model.load()
self.bird_view_model = bird_v... |
data = input()
unique_el = []
for index in range(len(data)):
if index + 1 < len(data):
if data[index] == data[index + 1]:
continue
else:
unique_el.append(data[index])
else:
unique_el.append(data[index])
print("".join(unique_el)) |
from myglobals import *
import urllib.request
import re
import pprint
def step1_pypi_index_raw():
url = "https://pypi.org/simple"
with urllib.request.urlopen(url) as f:
open(PYPI_INDEX_RAW, "wb").write(f.read())
def step2_pypi_index_py():
d = dict()
re_href = re.compile('<a href="(?P<href>... |
import logging
from typing import List
from weaverbird.backends.mongo_translator.steps.types import MongoStep
from weaverbird.pipeline import Pipeline, steps
from weaverbird.pipeline.steps import AppendStep, DomainStep
logger = logging.getLogger(__name__)
def translate_append(step: AppendStep) -> List[MongoStep]:
... |
# An assortment of utilities.
from contextlib import contextmanager
@contextmanager
def restoring_sels(view):
old_sels = list(view.sel())
yield
view.sel().clear()
for s in old_sels:
# XXX: If the buffer has changed in the meantime, this won't work well.
view.sel().add(s)
def has_dir... |
import unittest
from os.path import join
from pydantic import ValidationError
from tempfile import NamedTemporaryFile
import numpy as np
import rasterio
from rasterio.enums import ColorInterp
from rastervision.core import (RasterStats)
from rastervision.core.box import Box
from rastervision.core.utils.misc import sav... |
import typing
import inspect
from . import task
class App:
def __init__(
self, task_classes: typing.List[typing.Type[task.Task]], watchdog_duration: float = 0.1
) -> None:
self._validate_app_args(task_classes=task_classes, watchdog_duration=watchdog_duration)
self.task_classes = task... |
from can_tools.scrapers.official.TX.tx_state import Texas
|
import numpy as np
import matplotlib.pyplot as plt
import sys
import caffe
from PIL import Image
import cv2
# IMAGE_WIDTH = 200
# IMAGE_HEIGHT = 66
#
# def transform_img(img, img_width=IMAGE_WIDTH, img_height=IMAGE_HEIGHT):
#
# #Histogram Equalization
# img[:, :, 0] = cv2.equalizeHist(img[:, :, 0])
# img[:... |
class ToolStripSeparatorRenderEventArgs(ToolStripItemRenderEventArgs):
"""
Provides data for the System.Windows.Forms.ToolStripRenderer.RenderGrip event.
ToolStripSeparatorRenderEventArgs(g: Graphics,separator: ToolStripSeparator,vertical: bool)
"""
def Instance(self):
""" This function has been arbit... |
from __future__ import print_function
import pychromecast
if __name__ == "__main__":
chromecasts = pychromecast.get_chromecasts()
print(chromecasts) |
from visci.app import generate_vis_index
from glob import glob
import os
base = os.path.abspath("../")
template_files = glob("%s/gallery/*.html" %base)
generate_vis_index(template_files,base)
|
# Copyright 2022 @ReneFreingruber
#
# 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... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""This library is an attempt to implement the LSV2 communication protocol used by certain
CNC controls.
Please consider the dangers of using this library on a production machine! This library is
by no means complete and could damage the control or cause injuries!... |
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import os
from profile import work_path
def get_count_with_gene(position_dict, base_count):
# gene_list = []
count = []
for key in position_dict:
array_ = np.array([])
for (x,y) in position_dict[key]:
# p... |
import random
import numpy as np
import ImagesManager as imageManager
class GeneticAlgorithm:
def initRandomPopulation(self, amountPopulation, amountClusterings):
population = [[0 for personCluster in range(amountClusterings)] for personInPopulation in
range(amountPopulation)]
... |
import os
import numpy as np
import pennylane as qml
import pytest
from qiskit import IBMQ
from qiskit.providers.ibmq.exceptions import IBMQAccountError
from pennylane_qiskit import IBMQDevice
from pennylane_qiskit import ibmq as ibmq
from pennylane_qiskit import qiskit_device as qiskit_device
@pytest.fixture
def ... |
# this file normalize the pure data
import pandas as pd
import numpy as np
import math
def normalize(srcName, targetName, mode):
"""
normalize the pure data
:param srcName: pure csv name
:param targetName: norm csv name
:param mode: the mode of normalize
:return: None
"""
dataDf = pd.r... |
from django.urls import path, re_path
from . import views
urlpatterns = [
# coachings basic urls
re_path(r'^coachings/create/$', view=views.SimpleCoachingCreateAPIView.as_view()),
re_path(r'^coachings/detail/(?P<id>[\w\-]+)/$', view=views.SimpleCoachingDetailView.as_view()),
re_path(r'^coachings/all/... |
#writing a program that is event based and also use continue.
Denominator=0;
Numerator=0;
while(Denominator!=-1):
print("Enter the Numerator");
Numerator=float(input());
print(("Enter the Denominator:"));
Denominator=float(input());
if(Denominator==0):
continue;
print(Numerator/Denominat... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 19:31:48 2019
@author: hsauro
"""
import math, numpy as np, time
import pylab, scipy.stats
np.random.seed (1232)
# Generate some synthetic data
dx=[]
dy=[]
theta = [20, 6, 0.4]
for x in np.arange (0, 40, 0.5):
dx.append (x)
dy.append (np.random.normal(theta[... |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QModelIndex, QVariant
from gui.main_window.docks.properties.property_widgets.data import *
from gui.main_window.docks.properties.property_widgets.types import *
class PropertiesDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self, parent=Non... |
"""
Configuration file for capturing TD Ameritrade data into PostgreSQL database
@author: Nick Bultman, August 2021
"""
import numpy as np
import pandas as pd
import os
import copy
# Define symbol lookup path - make sure 'symbol' is a column name
symbolpath = '/path/to/symbols.csv'
# Define chrome webdriver path
webd... |
#-*- coding: utf-8 -*-
import logging
import os
import sys
import scrapydo
import time
import utils
import config
from sqlhelper import SqlHelper
from ipproxytool.spiders.proxy.xicidaili import XiCiDaiLiSpider
from ipproxytool.spiders.proxy.sixsixip import SixSixIpSpider
from ipproxytool.spiders.proxy.ip181 import Ip... |
class Solution:
def isAdditiveNumber(self, num: str) -> bool:
n = len(num)
def dfs(firstNum: int, secondNum: int, s: int) -> bool:
if s == len(num):
return True
thirdNum = firstNum + secondNum
thirdNumStr = str(thirdNum)
return num.find(thirdNumStr, s) == s and dfs(secondNum... |
# PyAgent.py
import random
from enum import Enum
import Action
import Orientation
class knowledge(Enum):
Unkown = 0
Safe = 1
Stench = 2
PossibleWumpus = 3
Wumpus = 4
x = 1
y = 1
gold = False
arrow = True
orientation = Orientation.RIGHT
width = None
height = None
knowledgeBase = {}
visited = {}
wu... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -------------------------------------------------------------------... |
import uuid
from django.test import TestCase
from core.tests import utils_fixtures
from conventions.models import Convention
from comments.models import Comment, CommentStatut
from users.models import User
class ConventionModelsTest(TestCase):
@classmethod
def setUpTestData(cls):
utils_fixtures.creat... |
# Copyright 2019-2020 Stanislav Pidhorskyi
#
# 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 i... |
from django.conf import settings
from django.core import checks
E001 = checks.Error(
"Missing 'CDN_CACHE_ENDPOINT' setting.",
hint="It should be set to CDN 'cache' endpoint or set to None.",
id='django_rt_cdn.E001',
)
E002 = checks.Error(
"Missing 'CDN_IMAGE_ENDPOINT' setting.",
hint="It should ... |
from test.slurm_assertions import (assert_job_canceled, assert_job_polled,
assert_job_submitted)
from test.slurmoutput import completed_slurm_job
from test.testdoubles.executor import (CommandExecutorStub, RunningCommandStub,
SlurmJobExecutorSpy)... |
"""Extract a frame from the initial state of an environment for illustration purposes.
Lets user interactively move the camera, then takes a screenshot when ready."""
import argparse
import select
import sys
import time
import imageio
import mujoco_py
import numpy as np
from aprl.envs.wrappers import make_env
from ... |
from telegram import Update
from src.config import bc
from src.log import log
def log_command(update: Update) -> None:
title = update.message.chat.title or "<DM>"
log.info("(" + title + ") " + update.message.from_user.username + ": " + update.message.text)
def check_auth(update: Update) -> bool:
if upd... |
import torch
import torch.nn as nn
class Autoencoder_FC(nn.Module):
def __init__(self, in_shape):
super().__init__()
bs,w,tracks = in_shape
self.encoder = nn.Sequential(
nn.Linear(w * tracks, 512),
nn.ReLU(),
nn.Linear(512, 128),
nn.ReLU(),
... |
from . import optimize_variational_circuit_with_proxy
from zquantum.core.interfaces.mock_objects import MockOptimizer
from .client_mock import MockedClient
import http.client
import unittest
import random
import subprocess
class TestOptimizationServer(unittest.TestCase):
def setUp(self):
self.port = "123... |
from lollipop.compat import iteritems, string_types
__all__ = [
'SCHEMA',
'ValidationError',
'ValidationErrorBuilder',
'merge_errors',
]
#: Name of an error key for cases when you have both errors for the object and
#: for it's fields::
#:
#: {'field1': 'Field error', '_schema': 'Whole object er... |
"""Common utility functions shared across classes"""
def convert_layers_to_string(layers: list) -> str:
"""Given Card or View layers, convert the grid layers to a string"""
string_conversion = ""
for layer in layers:
string_conversion += "\n" + "".join(layer)
return string_conversion
|
from locintel.core.datamodel.geo import Geometry, GeoCoordinate
from locintel.graphs.datamodel.jurbey import Path
from tests.base_fixture import coordinates, graph
graph = graph
expected_paths_edges = [
[(4, 6), (6, 7), (7, 8), (8, 9), (9, 10), (10, 0)],
[(6, 7), (7, 8), (8, 9), (9, 10), (10, 0), (0, 1), (1,... |
# -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""
spyderlib.plugins
=================
Here, 'plugins' are widgets designed specifically for Spyder
These plugins inherit the following classes
(SpyderP... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('correctiv_justizgelder', '0004_auto_20150429_0959'),
]
operations = [
migrations.AlterField(
model_name='fine',
... |
#!/usr/bin/env python
import sys
def main(number):
a_1 = 1
a_2 = 2
a = a_1 + a_2
result = 2
while a < number:
a_1 = a_2
a_2 = a
a = a_1 + a_2
if a % 2 == 0:
result += a
return result
if __name__ == '__main__':
print(main(int(sys.argv[1])))
|
#
#
# Takes the structs required for the udp data and turns them into json objects to
# pass through our websocket to the webpage for viewing
#
# Author: Kristian Nilssen
import json
def MotionData(packet):
players_car = packet.m_header.m_playerCarIndex
motion_data_json = {
'header': {
'packetFor... |
#!/usr/bin/env python3
import json
import os
from io import BytesIO
from flask import Flask, request, json as json_flask
from vosk import Model, KaldiRecognizer
MODEL_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'model')
if not os.path.exists(MODEL_PATH):
print('Model folder not found ({}), by... |
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
for b in basket:
print(b)
|
#!/usr/bin/env python
ONLINE_RETAIL_XLSX = 'OnlineRetail.xlsx'
ONLINE_RETAIL_CSV = 'OnlineRetail.csv'
ONLINE_RETAIL_JSON = 'OnlineRetail.json'
ONLINE_RETAIL_CUSTOMERS = 'OnlineRetailCustomers.csv'
def download_spreadsheet():
print('Starting download_spreadsheet() ...')
# support python 2 and 3
try:
... |
import unittest
import utils
import datetime
import random
from _base import BaseTestCase
from app.models import User, Session
from app import create_app
class UserModelTestCase(BaseTestCase):
def test_to_json(self):
now = datetime.datetime.now()
session = utils.generate_session(
words = 100,
ch... |
#coding: utf-8
#------------------------------------------------------------
# Um programa que calcula o valor a ser pago por um produto
# considerando o seu preço normal e condição de pagamento:
#------------------------------------------------------------
# • à vista dinheiro/cheque: 10% desconto
# • à vista no ... |
from flask import Flask
from dash import Dash
def create_app(config_object='{}.settings'.format(__package__)):
server = Flask(__package__)
# load default settings
server.config.from_object(config_object)
# load additional settings that will override the defaults in settings.py. eg
# $ export... |
import allel
from collections import Counter, OrderedDict
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import numpy as np
from operator import itemgetter
import os
import sys
import re
from Admixture.utils import *
def write_founders_bcf(reference_file_bcf, sample_file, output_path, verb=True)... |
""" Contains upgrade tasks that are executed when the application is being
upgraded on the server. See :class:`onegov.core.upgrade.upgrade_task`.
"""
from libres.db.models import Allocation, Reservation
from onegov.core.upgrade import upgrade_task
from onegov.reservation import LibresIntegration
from onegov.reservatio... |
def checkIfPossibleRec(x, isPossible, n):
if x > n:
return
if isPossible[x]:
return
isPossible[x] = True
checkIfPossibleRec(x + num1, isPossible, n)
checkIfPossibleRec(x + num2, isPossible, n)
num1, num2, res = 2020, 2021, []
for i in range(int(input())):
n = int(input())
i... |
# -*- coding: utf-8 -*-
#
# Copyright 2020 Google LLC
#
# 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... |
# Importing library
import qrcode
# Data to be encoded
data = 'nah bro you clownin'
# Encoding data using make() function
img = qrcode.make(data)
# Saving as an image file
img.save('MyQRCode1.png') |
def for_E():
"""printing capital 'E' using for loop"""
for row in range(5):
for col in range(4):
if row==0 or col==0 or row==2 or row==4:
print("*",end=" ")
else:
print(" ",end=" ")
print()
def while_E():
"""printing c... |
#!/usr/bin/python3
import subprocess
import shlex
import time
import sys
import os
import socket
pull_command = 'pull-images'
STDOUT = subprocess.STDOUT
FNULL = open(os.devnull, 'w')
def pullImage(image):
pull = 'docker pull '
pull_result = subprocess.call(shlex.split(pull + image))
if(pull_result > 0):... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-01-29 16:50
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0019_delete_filter'),
('home', '00... |
# -*- coding:utf-8 -*-
# !/usr/bin/env python
import argparse
import json
import matplotlib.pyplot as plt
import skimage.io as io
# from pycocotools.coco import COCO
import cv2
from labelme import utils
import numpy as np
import glob
import PIL.Image
import os
class MyEncoder(json.JSONEncoder):
def default(self,... |
import sys
import os
import cv2
import numpy as np
# import imutils
from four_point_transform import four_point_transform
fullpath=os.path.dirname(os.path.realpath(__file__))
timestamp = sys.argv[1]
file_ext = sys.argv[2]
def func(image):
bordersize=100
image_padded=cv2.copyMakeBorder(image, top=bordersize, botto... |
"""
get_symbols.py
Date Created: March 13th, 2020
Author: georgefahmy
Description: Generate the list of stock symbols used for searching the stocks.
"""
# Base Python #
import ftplib
import logging
import os
import re
logger = logging.getLogger(__name__)
LOGGER_FORMAT = "[%(asctime)s] %(levelname)s: %(message)s"
... |
from datetime import datetime
from typing import Union
from .const import PAGE, PAGE_SIZE
from .request_handler import RequestHandler
class BaseArrAPI(RequestHandler):
"""Base functions in all Arr API's"""
def __init__(self, host_url, api_key, ver_uri="/"):
self.ver_uri = ver_uri
super().__... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import pythonizame.apps.website.models
class Migration(migrations.Migration):
dependencies = [
('website', '0001_initial'),
]
operations = [
migrations.AddField(
model_na... |
#
# General-purpose Photovoltaic Device Model - a drift diffusion base/Shockley-Read-Hall
# model for 1st, 2nd and 3rd generation solar cells.
# Copyright (C) 2008-2022 Roderick C. I. MacKenzie r.c.i.mackenzie at googlemail.com
#
# https://www.gpvdm.com
#
# This program is free software; you can redist... |
"""Sigmoid function"""
import numpy as np
def sigmoid(matrix):
"""Applies sigmoid function to NumPy matrix"""
return 1 / (1 + np.exp(-matrix))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.