content stringlengths 5 1.05M |
|---|
import json
import os, sys
import markdown
from flask import Flask, render_template
from flask_flatpages import FlatPages
import urllib
from flask_frozen import Freezer
DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.md'
app = Flask(__name__)
app.config.from_object(__name__)
pages = FlatPages(app)
... |
import sys
from setuptools import setup
install_requires = ["h2>=2.2.0,<3.0.0"]
if sys.version_info < (3, 5):
install_requires.append("typing")
setup(
name='asyncio-apns',
version='0.0.1',
install_requires=install_requires,
packages=['asyncio_apns'],
url='https://github.com/etataurov/asyncio-a... |
from datahub.dataset.core.pagination import DatasetCursorPagination
class AdvisersDatasetViewCursorPagination(DatasetCursorPagination):
"""
Cursor Pagination for AdvisersDatasetView
"""
ordering = ('date_joined', 'pk')
|
from time import time
import struct
t0=time()
total = 0
with open('test_1m.bin','rb') as f:
while True:
raw = f.read(20*8)
if not raw: break
rec = struct.unpack('q'*20,raw)
for x in rec:
total += x
print(total)
print(time()-t0)
|
#!/usr/bin/env python
# File : tokenize.py
# Author : Douglas Anderson
# Description: Driver for my parser implementation
import os, sys
import csv
import subprocess
from Token import Token
scanner_path = "./scanner"
def scan_text(tweetid, label, intext):
tokens = []
tmp_f = os.tmpfile()
tmp_... |
import os
import pathlib
import subprocess
from typing import Sequence
import click
import virtualenv
from pygit2 import clone_repository
class InvalidName(ValueError):
"""
Name of sample project invalid.
"""
class AlreadyExists(KeyError):
"""
Sample project already exists.
"""
class Cant... |
"""
Tools for working with the bytecode for a module. This currently just
defines a function for extracting information about import statements
and the use of global names.
"""
import collections
import dis
import types
from typing import Deque, Dict, Iterator, List, Optional, Set, Tuple
from ._importinfo import Impor... |
def contact_card(name, age, car_model):
return f"{name} is {age} and drives a {car_model}"
#calling args in sequence
contact_card("owais", 28, "bonusCar")
#if calling out of order then you have to specify name and value
contact_card(age=28, car_model="f1", name="owais")
#Positional argument follows keyword argum... |
from threading import Thread
from os import system
def executar_rp(exe: str):
'''Função que executa um aplicativo externo
Parameters:
exe (str): String com aplicativo e parâmetros
'''
try:
system(exe)
except Exception as er:
print('executar_rp:')
print(er)
def outraRota(funcao, *args: tuple):
'''Função... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 18 00:06:28 2019.
@author: mtageld
"""
import pytest
import os
import numpy as np
import tempfile
import shutil
from pandas import read_csv
from histomicstk.saliency.tissue_detection import (
get_slide_thumbnail, get_tissue_mask,
get_tissue_... |
# -*- coding: utf-8 -*-
"""
Catch-up TV & More
Copyright (C) 2017 SylvainCecchetto
This file is part of Catch-up TV & More.
Catch-up TV & More 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 Foundat... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
定义类的属性
'''
class Programer(object):
hobby = 'Play computer'
def __init__(self,name,age,weight):
self.name = name #类的共有属性
self._age = age #私有属性和共有属性差不多
self.__weight = weight #私有属性 这个属性只有在类内部可以调用 对象是不可以直... |
import base64
import copy
import hashlib
import logging
import os
from datetime import datetime
from typing import Dict, Optional, Union
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from lxml import etree
from oscrypto.asymmetric import Certificate, load_certificate
from .exc... |
# -*- coding: utf-8 -*-
from PIL import Image
import os
CODE_LIB = r"@B%8&WM#ahdpmZOQLCJYXzcunxrjft/\|()1[]?-_+~<>i!I;:, "
count = len(CODE_LIB)
def transform_ascii(image_file):
image_file = image_file.convert("L")
code_pic = ''
for h in range(0,image_file.size[1]):
for w in range(0,image_f... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import string
def get_chars74k_label_map():
"""
This function generates a label map for the chars74K datasetselfself.
This will help to display the true label from the predicted class.
"""
# samples 1 through 10 are numbers '0' - '9'
# samples 11 ... |
# -*- coding: utf-8 -*-
import logging
import sys
from ._constants_ import LOGGERNAME
def create_log_handler(fmt='%(asctime)s| %(levelname)s |%(message)s', stream=sys.stderr):
formatter = logging.Formatter(fmt)
handler = logging.StreamHandler(stream=stream)
handler.setFormatter(formatter)
logging.g... |
# Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//div[@class='item-info']/h1",
'price' : "//div[@class='price-info']/div[@class='left']/p[@class='price']",
'category' : "",
'... |
import brother_ql
import brother_ql.backends.helpers
from bottle import get, post, run, static_file, template, request, response
import click
from base64 import b64decode
from PIL import Image
from io import BytesIO
LABEL_API_HOST = "0.0.0.0"
LABEL_API_PORT = 8765
BROTHER_QL_MODEL = "QL-800"
BROTHER_QL_BACKEND = None... |
import logging
logger = logging.getLogger(__name__)
uri = "/iam/access/v8/mmfa-config"
requires_modules = None
requires_version = None
def get(isamAppliance, check_mode=False, force=False):
"""
Retrieve MMFA endpoint details
"""
return isamAppliance.invoke_get("Retrieve MMFA endpoint details",
... |
import torch.utils.data.dataset as data
import pymia.data.transformation as tfm
import pymia.data.indexexpression as expr
from . import reader as rd
from . import indexing as idx
from . import extractor as extr
class ParameterizableDataset(data.Dataset):
def __init__(self, dataset_path: str, indexing_strategy: ... |
import socket
import threading
HOST, PORT = "127.0.0.1", 14900
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.connect((HOST, PORT))
name = input("Please enter ur name: ")
def listen():
while True:
msg = conn.recv(16384).decode()
if msg == "name":
conn.send(name.encode... |
import json
import stackx as sx
def main():
#Load config file
with open('config.json') as json_config_file:
config = json.load(json_config_file)
print(config)
#Connect to database
sxdb = sx.Connection(config=config["mysql"])
a = sx.Archive7z("/Users/ardeego/repos/stackx/tests/data/tes... |
import logging
import pytest
from ocs_ci.framework.testlib import ManageTest, tier1, acceptance
from ocs_ci.ocs import constants
from ocs_ci.ocs.exceptions import UnexpectedBehaviour
from ocs_ci.ocs.resources import pod
from ocs_ci.utility.retry import retry
from tests import helpers
logger = logging.getLogger(__name... |
#
# Python script using Power Manager API to get or set Power Manager - Settings.
#
# _author_ = Mahendran P <[email protected]>
#
#
# Copyright (c) 2021 Dell EMC Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You m... |
import bpy, bmesh, struct
import base64, hashlib
from time import strftime, gmtime
import speckle.schemas
def export_mesh(blender_object, scale=1.0):
return MeshObject_to_SpeckleMesh(blender_object, scale)
#return None
def SetGeometryHash(data):
code = hashlib.md5(data.encode('utf-8')).hexdigest()
retu... |
import urllib.request
import sys
from lxml import html
if len(sys.argv) < 2:
print('Usage example: python fetch_html.py https://github.com')
sys.exit(1)
url = sys.argv[1]
response = urllib.request.urlopen(url)
html_text = response.read().decode('UTF-8')
text = html.fromstring(html_text).text_content()
print(... |
import streamlit as st
from pyuba.calc.bayesian import Bayesian
from pyuba.calc.frequentist import Frequentist
from pyuba.calc.utils import create_plotly_table
def local_css(file_name: str) -> str:
with open(file_name) as f:
st.markdown("<style>{}</style>".format(f.read()), unsafe_allow_html=True)
def d... |
guest_name = input()
residence_host_name = input()
letters_in_pile = input()
def get_letters_count_dict(str):
letters_counts = dict()
for letter in str:
if letter in letters_counts:
letters_counts[letter] += 1
else:
letters_counts[letter] = 1
return letters_counts
... |
#Copyright (C) Practica Ana Sollars & Co.
#Permission is granted to copy, distribute and/or modify this document
#under the terms of the GNU Free Documentation License, Version 1.3
#or any later version published by the Free Software Foundation;
#with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Text... |
#!/usr/bin/env python
"""
From bluerov_ros_playground respository (https://github.com/patrickelectric/bluerov_ros_playground)
Credits: patrickelectric
"""
import cv2
import rospy
import time
try:
import pubs
import subs
import video
except:
import bluerov.pubs as pubs
import bluerov.subs as subs... |
# development
import cv2
from maskdetector.mask_detector import MaskDetector
from flask import Flask, render_template
from flask_socketio import SocketIO
from flask_cors import CORS, cross_origin
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
CORS(app)
socketio = SocketIO(app,cors... |
##!/usr/bin/env python3
from traceback import format_exception
def error_logging(path):
return ErrorLoggingContext(path)
class ErrorLoggingContext:
def __init__(self, path):
self.path = path
def __enter__(self):
return self
def __exit__(self,
exception_type,
exceptio... |
from itertools import permutations
def print_permutations(string):
for perm in permutations(string):
print("".join(perm))
def main():
print_permutations("asdf")
if __name__ == '__main__':
main()
|
import logging
import traceback
from functools import wraps
def try_catch_with_logging(default_response=None):
def out_wrapper(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
res = func(*args, **kwargs)
except Exception:
res = default_... |
#!/usr/bin/env python3
# coding=utf-8
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(6)
y = np.arange(5)
z = x * y[:, np.newaxis]
for i in range(5):
if i == 0:
p = plt.imshow(z)
fig = plt.gcf()
plt.clim() # clamp the color limits
plt.title("Boring slide show")
... |
from functools import partial
import logging
from multiprocessing import get_context, log_to_stderr
import numpy as np
import os
from ray_tracer.canvas import Canvas, overlay
from ray_tracer.rays import Ray
from ray_tracer.transformations import Transformation
from ray_tracer.tuples import Point, normalize
class Cam... |
# -*- coding: cp936 -*-
# -*- coding: utf-8 -*-
import sys
import os
import glob
import Engine
# package cmd
# pyinstaller -F ./ImageEngine.py
# gat image input path
inputPath = sys.argv[1] if len(sys.argv) > 1 else "/"
# get image.swift output path
outputPath = sys.argv[2] if len(sys.argv) > 2 else "/"
# move os wor... |
# Copyright 2019 Intel, 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 a... |
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import (
LoginRequiredMixin,
UserPassesTestMixin
)
from django.db.models import Exists, OuterRef
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from d... |
# coding: utf-8
import matplotlib.pyplot as plt
import matplotlib.image as image
class Person():
def __init__(self, name, img=None):
self.name = name
if img is not None:
self.img = img
self.partners = [self.name]
def add_partner(self,person):
if person.name not in ... |
"""
MIT License
Copyright (C) 2021 ROCKY4546
https://github.com/rocky4546
This file is part of Cabernet
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without lim... |
#!/usr/bin/env python
# coding: utf-8
# In[6]:
students = ["Ravi", "Anika", "Aniketh", "Chaitra", "Rashmi"]
print(students[4])
print(students[-2])
# In[9]:
#list slicing
print(students[2:4])
less_students = students[1:3]
print(less_students)
# In[11]:
#fetch except last value
print(students[0:-1])
print(... |
import platform
from typing import ClassVar, Dict, List
from .. import __version__, command, module, util
OFFICIAL_SUPPORT_LINK = "https://t.me/pyrobud"
class CoreModule(module.Module):
name: ClassVar[str] = "Core"
@command.desc("List the commands")
@command.usage("[filter: command or module name?]", o... |
"""
Portals: useful functions.
"""
from typing import Dict, List, Optional, Tuple, Union
from constants.memkeys import portal_segment_data_key_destination_room_name, portal_segment_data_key_xy_pairs
from empire import stored_data
from jstools.screeps import *
from utilities import movement, positions, robjs
__pragma_... |
class Queue:
def __init__(self):
self.data = []
def __str__(self):
values = map(str, self.data)
return ' <- '.join(values)
def enque(self, val):
self.data.append(val)
def deque(self):
return self.data.pop(0)
def peek(self):
return s... |
from pymysql_portable.converters import *
|
#Class List + Total Class List
c7A = ["Alice", "Bob", "Charlie"]
c8B = ["Ryu", "Ken", "Akuma"]
cTest = ["Rob", "Alex", "Ramzi"]
cBestClass = ["Ramzi", "Zoe"]
allClasses = {"7A": c7A, "8B": c8B, "TEST": cTest, "BESTCLASS": cBestClass}
#Booleans + initialisations
validClass = False
runProgram = True
validMainRunInputs... |
#!/usr/bin/env python
import threading, logging, time,random
from kafka import KafkaProducer
tempSensors = [['roomStudy:temp',17],['roomSleep1:temp',17],['roomSleep2:temp',17]]
binSensors = [['home:mailBox',0],['home:door',0],['kitchen:smoke',0]]
class Manual_Producer():
def start(self):
producer = K... |
# -*- coding: utf-8 -*-
"""generator.py
A module for generating lists of Vector2s. These can be generated randomly within a square, within a rectangle, within a
circle, withing an ellipse, or on an axis. They can also be generated as vertices distributed uniformly on a grid, but
this method is not random.
License:
... |
#!/usr/bin/env python
import unittest
import xml.etree.cElementTree as eTree
from latex2mathml import converter
__author__ = "Ronie Martinez"
__copyright__ = "Copyright 2016-2017, Ronie Martinez"
__credits__ = ["Ronie Martinez"]
__license__ = "MIT"
__maintainer__ = "Ronie Martinez"
__email__ = "[email protected]"
_... |
#
# Copyright (c) 2019 -2021 MINRES Technolgies GmbH
#
# SPDX-License-Identifier: Apache-2.0
#
import cppyy
import os.path
import site
from sysconfig import get_paths
import sys
import re
import logging
from contextlib import (redirect_stdout, redirect_stderr)
import io
lang_symbols = {
3: '199711L',
11:'2011... |
#!/usr/bin/env python
# coding: utf-8 -*-
# pylint: disable=bare-except
# pylint: disable=dangerous-default-value
# flake8: noqa: W503
# pylint: disable=logging-format-interpolation
# flake8: noqa: W1202
# pylint: disable = duplicate-code
# flake8: noqa: R0801
#
# GNU General Public License v3.0+
#
# Copyright 2019 Ari... |
"""
[x] terminate based on duality gap at 1e-3
[x] check against cvxpy
[x] experiment with mu; inner newton steps and total newton steps
[x] plot log duality gap vs total newton steps
- textbook format step plot
python -m ee364a.a11_8
"""
import fire
import numpy as np
import torch
import tqdm
from .a10_4 import... |
from .model import TreeNode
"""
Space : O(n)
Time : O(n)
"""
class Solution:
# preorder transversal
def getLeaf(self, root) -> List[int]:
ans = []
if root:
ans += self.getLeaf(root.left)
ans.append(root.val)
ans += self.getLeaf(root.right)
ret... |
from __future__ import absolute_import, division, print_function
import types
from numbers import Number
from typing import List, Tuple, Union, Sequence, Optional
import numpy as np
import tensorflow as tf
from sklearn.mixture import GaussianMixture
from sklearn.preprocessing import KBinsDiscretizer
from tensorflow i... |
from argparse import Namespace
import sys
import os
import numpy as np
# Data analysis.
from nasws.cnn.search_space.nasbench201.nasbench201_search_space import NASBench201Benchmark, NASBench201SearchSpace
from nasws.cnn.search_space.nasbench101.nasbench_search_space import NASBench_v2, NASbenchSearchSpace, NasBenchSe... |
import os
import pytest
import shutil
from mlflow import cli
from click.testing import CliRunner
from mlflow.utils import process
EXAMPLES_DIR = "examples"
def get_free_disk_space():
# https://stackoverflow.com/a/48929832/6943581
return shutil.disk_usage("/")[-1] / (2 ** 30)
@pytest.fixture(scope="function... |
#AULA 7: OPERADORES ARITMÉTICOS
nome = input('Qual é o seu nome?\n')
print('Prazer em te conhecer, {:20}.' .format(nome))
#Com :20, posso fazer 20 espaços (centralizado).
#Além disso, posso informar a direção desses espaços com :> (direita) ou :< (esquerda).
n1 = int(input('Um valor: '))
n2 = int(input('Outro número:... |
from .permission import InternalPermission
class CRUDPermissions:
@classmethod
def __init_defaults__(cls):
cls.create = InternalPermission(f"{cls.name}_create")
cls.delete = InternalPermission(f"{cls.name}_delete")
cls.read = InternalPermission(f"{cls.name}_read")
cls.update = ... |
import pandas as pd
import numpy as np
from sklearn.cluster import MeanShift
from collections import defaultdict
from .structure_extractor import StructureExtractor
TOP_LEFT_X, TOP_LEFT_Y, TOP_RIGHT_X, TOP_RIGHT_Y, \
BOTTOM_RIGHT_X, BOTTOM_RIGHT_Y, BOTTOM_LEFT_X, \
BOTTOM_LEFT_Y, TEXT = 'top_left_x', 'top_left_y', 't... |
from couchstore import CouchStore, DocumentInfo
from tempfile import mkdtemp
import os
import os.path as path
import struct
import unittest
class ChangeCountTest(unittest.TestCase):
def setUp(self):
self.tmpdir = mkdtemp()
self.dbname = path.join(self.tmpdir, "testing.couch")
self.db = Couc... |
import click
from flask.cli import with_appcontext
@click.command("init")
@with_appcontext
def init():
"""Create a new admin user"""
from {{cookiecutter.app_name}}.extensions import db
from {{cookiecutter.app_name}}.models import User
click.echo("create user")
user = User(username="{{cookiecutter... |
import matplotlib.pyplot as plt
import os
import torch
class EvaluateTask:
def __init__(self, mantra_model):
task = mantra_model.task
if task:
task.latest_loss = task.evaluate(mantra_model)
print('%s: %s' % (task.evaluation_name, task.latest_loss))
if hasat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of walt
# https://github.com/scorphus/walt
# Licensed under the BSD-3-Clause license:
# https://opensource.org/licenses/BSD-3-Clause
# Copyright (c) 2021, Pablo S. Blum de Aguiar <[email protected]>
"""storages provides entities responsible for writi... |
import json
import re
import redis
from model_mommy import mommy
from django.core.cache import cache
from django.conf import settings
from copy import deepcopy
from django.test.client import Client
from django.core.files.uploadedfile import SimpleUploadedFile
from django import forms
from django.forms import widgets
fr... |
from kit_dl.core import Scraper
from tests.base import BaseUnitTest
class TestCore(BaseUnitTest):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.scraper = Scraper(None, cls.dao, True)
def test_format_assignment_name_leading_zero(self):
format = "Blatt_$$"
self.... |
import multiprocessing
import threading
import time
import warnings
from collections import namedtuple
from dagster_postgres.utils import get_conn
from six.moves.queue import Empty
from dagster import check
from dagster.core.definitions.environment_configs import SystemNamedDict
from dagster.core.events.log import Ev... |
import discord
from discord.ext import commands
from bs4 import BeautifulSoup
class Define:
def __init__(self, bot):
self.bot = bot
self.aiohttp_session = bot.aiohttp_session
self.color = bot.user_color
self.url = 'https://google.com/search'
self.headers = {'User-Agent':
... |
import os
os.system("title Loading...")
os.system("python -m pip install pywin32")
os.system("python -m pip install pillow")
os.system("python -m pip install matplotlib")
os.system('cls')
import win32con
from win32api import keybd_event, mouse_event
import time
import random
import win32api
import time
... |
import copy
import posixpath
import re
from typing import Optional, Sequence, List, Dict, Any
from urllib.request import urlopen
from kubragen import KubraGen
from kubragen.builder import Builder
from kubragen.configfile import ConfigFile, ConfigFileRenderMulti, ConfigFileRender_Yaml, ConfigFileRender_RawStr, \
Co... |
import matplotlib.pyplot as plt
from matplotlib import style
import random
import datetime
from graphpkg.live.graph import LiveTrend,LiveScatter
style.use("dark_background")
def get_new_data():
return datetime.datetime.now(), [random.randrange(5, 10),random.randrange(1,5)]
# def get_new_data1():
# y_data =... |
from time import time
from bst.pygasus.core import ext
from bst.pygasus.session.interfaces import ISession
from bst.pygasus.session.interfaces import IClientIdentification
from bst.pygasus.session.interfaces import DEFAULT_EXPIRATION
class UserSessionData(dict):
def __init__(self):
self.reset_lastchange... |
def resolve():
'''
code here
'''
N, K = [int(item) for item in input().split()]
A_list = [int(item) for item in input().split()]
bit_k = bin(K)[2:]
telepo_list = [A_list]
for _ in range(len(bit_k)-1):
temp_list = telepo_list[-1]
new_telep = [temp_list[i-1] for i in tem... |
# -*- coding: utf-8 -*-
'''
File name: code\rudinshapiro_sequence\sol_384.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #384 :: Rudin-Shapiro sequence
#
# For more information see:
# https://projecteuler.net/problem=384
# Problem State... |
import cv2
import numpy as np
import sys
from pathlib import Path
###################
# Core Parameters #
###################
# Size of image to compact during preprocessing
adjust_size = 500
# Rho (distance from top-left corner) threshold for detecting duplicates
rho_threshold = 10
# Theta (angle from top horizon... |
import json
from django.utils.encoding import force_bytes, force_text
def load_json(data):
return json.loads(force_text(data))
def dump_json(data):
'''
Converts a Python object to a JSON formatted string.
'''
json_kwargs = {
'sort_keys': True,
'indent': 4,
'separators':... |
from numba.core.decorators import njit
import numpy as np
import os, shutil
from SuperSafety.Utils.utils import init_file_struct
class FollowTheGap:
def __init__(self, conf, agent_name):
self.name = agent_name
self.conf = conf
self.map = None
self.cur_scan = None
self.cur_o... |
from __future__ import absolute_import
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class NodeStoreConfig(AppConfig):
label = 'nodestore'
name = 'cobra.apps.nodestore'
verbose_name = _('NodeStore')
|
def hanoi(n,start,temp,end):
if n == 1:
print "move from " + start + " to " + end
else:
hanoi(n - 1,start,end,temp)
print "move from " + start + " to " + end
hanoi(n - 1,temp,start,end)
hanoi(2,"A","B","C")
print "fin"
hanoi(3,"X","temp","Y")
|
from selenium.webdriver import Remote as RemoteWebDriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.... |
from __future__ import annotations
import logging
from random import Random
from typing import TYPE_CHECKING
from ...models import (
Planning,
MAX_INT,
)
from ..abc import (
Algorithm,
)
from ..heuristics import (
InsertionAlgorithm,
)
if TYPE_CHECKING:
from typing import (
Type,
... |
from wolframclient.language import wl
from wolframclient.serializers import export, wolfram_encoder
# define a hierarchy of classes.
class Animal(object):
pass
class Fish(Animal):
pass
class Tuna(Fish):
pass
# will not have its own encoder.
class Salmon(Fish):
pass
# register a new encoder for Anim... |
import os
import glob
import json
import time
import pickle
import shutil
import random
import warnings
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
from multiprocessing import Process, cpu_count, Array
from omsdetector.mof import Helper
from omsdetector.mof import MofStructure
from omsdetecto... |
# Copyright (c) 2020, Huawei Technologies.All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law... |
# coding: utf-8
from __future__ import division, print_function, unicode_literals
import pytest
from formatcode.convert.errors import PartsCountError
from formatcode.convert.fc import FormatCode
from formatcode.convert.parts import NegativePart, PositivePart, StringPart, ZeroPart
def test_parts_from_tokens():
... |
# Jetfuel Game Engine- A SDL-based 2D game-engine
# Copyright (C) 2017 InfernoStudios
#
# 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/LI... |
# Databricks notebook source
dbutils.library.installPyPI("azureml-sdk", version = '1.8.0')
dbutils.library.installPyPI("azureml-train-automl-runtime", version = '1.8.0')
dbutils.library.installPyPI('azure-mgmt-resource', version="10.2.0")
dbutils.library.restartPython()
# COMMAND ----------
import azureml.core
from ... |
import os
import string
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from common.utils import DATA_DIR
pos_tags_features = [
'noun',
'verb',
'adjective',
'adverb'
]
cos_sim_features = [
'cos_sim'
]
sentiment_features = [
'positive_count',
'negative_count... |
from crownstone_core.protocol.BlePackets import ControlStateSetPacket, ControlPacket
from crownstone_core.protocol.BluenetTypes import StateType, ControlType
from crownstone_uart.core.UartEventBus import UartEventBus
from crownstone_uart.core.uart.uartPackets.UartMessagePacket import UartMessagePacket
from crownstone_... |
import hashlib
import six
# construct file path
def construct_file_path(base_path, scope, lfn):
hash = hashlib.md5()
hash.update(six.b('%s:%s' % (scope, lfn)))
hash_hex = hash.hexdigest()
correctedscope = "/".join(scope.split('.'))
dstURL = "{basePath}/{scope}/{hash1}/{hash2}/{lfn}".format(basePa... |
#!/usr/bin/env python
"""consistency tests
While many of the tests utilize similar trees and input data, the overlap
is not necessarily 100%. Many of these inputs are written with specific tests
in mind.
"""
__author__ = "Donovan Park"
__copyright__ = "Copyright 2014, The tax2tree project"
__credits__ = ["Donovan Pa... |
import json
import logging
import os
from deployer import conf
from deployer.components.deployment import Deployment
from deployer.connectors.okeanos import OkeanosConnector
__author__ = 'Giannis Giannakopoulos'
def configure_logger():
"""
Logging configuration
:return:
"""
logging.basicConfig()
... |
from __future__ import print_function, division
import os
import torch
from torch.autograd import Variable
from torch.utils.data import Dataset
from skimage import io
import pandas as pd
import numpy as np
from . import transformation as tf
import scipy.io
import matplotlib
import matplotlib.pyplot as plt
class Image... |
import pytest
import os
import json
@pytest.fixture(scope="function")
def stdio(cli, config, is_encrypted_test):
if not config.get("network.nano_node.rpc_url", None):
# Set the 'rpc_url' field even if we're not connecting to network
# to ensure configuration is complete
config.set("networ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = ['pandas']
setup_requirements = ['pan... |
from flask import Flask,json
import unittest
from app import app
from app.models import User, Favorites, db
class FavoritesUnit(unittest.TestCase):
app = Flask(__name__)
def test_getfavorites_401(self):
user="user1"
found = 0
teststring = "Health"
find_user = User.query.fi... |
from Statistics.standard_deviation import standard_deviation
from Statistics.mean import mean
from Calculator.division import division
from pprint import pprint
def z_score(data):
try:
z_mean = mean(data)
std_dev_result = standard_deviation(data)
z_list = []
for i in data:
... |
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import os
import sys
from typing import Iterator
import click
from jina import Flow, Document, DocumentArray
import logging
MAX_DOCS = int(os.environ.get("JINA_MAX_DOCS", 0))
cur_dir = os.path.dirname(os.path.abspat... |
import errno
import gzip
from os import path
from datetime import datetime
from django.core.files.storage import FileSystemStorage, get_storage_class
from django.utils.functional import LazyObject, SimpleLazyObject
from compressor.conf import settings
class CompressorFileStorage(FileSystemStorage):
"""
Stan... |
from collections import defaultdict
# Puzzle Input ----------
with open('Day15-Input.txt', 'r') as file:
puzzle = file.read().split('\n')
with open('Day15-Test01.txt', 'r') as file:
test01 = file.read().split('\n')
# Main Code ----------
# Memorize the lowest risk routes to this points
memory = defaultdict(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.