content stringlengths 5 1.05M |
|---|
import warnings
from typing import Dict
import numpy as np
import aesara
from aesara.gradient import DisconnectedType
from aesara.graph.basic import Apply, Variable
from aesara.graph.op import COp
from aesara.graph.params_type import ParamsType
from aesara.misc.safe_asarray import _asarray
from aesara.scalar import i... |
# Copyright (c) 2013 OpenStack Foundation.
#
# 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... |
def orderCalculation(order):
basePrice, i = order.quantity * order.itemPrice, 3
print(basePrice)
return basePrice - max(0, order.quantity - 500) * order.itemPrice * 0.05 + min(basePrice * 0.1, 100)
|
from app.db import models, orm
if __name__ == '__main__':
orm.Base.metadata.create_all(orm.engine)
|
from unittest.mock import MagicMock
from PyAudioStream.audiostream import AudioStreamClient, AudioProperties, MessageCommand, MessageType, _compose_message
SAMPLING = 44100
CHANNELS = 2
LENGTH = 120
FRAMES_IN_AUDIO = 5292000
AUDIO_PROPERTIES = AudioProperties(sampling=SAMPLING, channels=CHANNELS, frames_in_audio=FRAME... |
#! /usr/bin/env python
import io
import logging
import sys
from setuptools import setup, find_packages, Command
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', 'Arguments to pass to py.test')]
test_args = []
def initialize_options(s... |
from django.contrib import admin
from models import Whitelist
# Register your models here.
class WhitelistAdmin(admin.ModelAdmin):
list_display = ['name', 'ip']
model = Whitelist
admin.site.register(Whitelist, WhitelistAdmin)
|
# (C) Copyright 2018-2021 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at... |
import collections
import contextlib
import os
import re
import signal
import subprocess
import sys
from pipenv.vendor import shellingham
from pipenv.vendor.vistir.compat import Path, get_terminal_size
from pipenv.vendor.vistir.contextmanagers import temp_environ
ShellDetectionFailure = shellingham.ShellDetectionFai... |
import logging
import os
import requests
import subprocess
import tempfile
import time
import zipfile
from collections import OrderedDict
from django.conf import settings
import memcache
logger = logging.getLogger(__name__)
def call(cmd, shell=False):
"""Spawn a new process and capture its output"""
logge... |
import numpy as np
from nhps.distance.utils.edit_distance import edit_distance_mt_mc
class Decoder(object):
"""
Abstract class
"""
def __init__(self, del_cost, trans_cost, n_types):
"""
:param np.ndarray del_cost: A series of floats.
:param float trans_cost:
:param in... |
import sys
sys.path.append("apt_plugin")
from environment_apt_plugin import AptPlugin
"""
Validate apt plugin behaviour when we use nonsense parameters
"""
class AptPluginWrongOption(AptPlugin):
def setup(self):
super().setup()
def execute(self):
self.plugin_cmd("nonsense", "outp", 1)
|
import numpy as np
class cntSpin(object):
r"""
Class for getting expected value of <S_vector> = (<Sx>, <Sy>, <Sz>) for
carbon nanotube states given a basis.
Currently, only fillings 1 and 3 are supported, that is, all matrices are
of size 4x4.
Notes
-----
Notation:
In this class th... |
'''
UFCG
PROGRAMAÇÃO 1
JOSE ARTHUR NEVES DE BRITO - 119210204
DESPESA CINEMA
'''
orcamento = float(input("Orçamento? R$ "))
num_adultos = int(input("Número de adultos? "))
num_criancas = int(input("Número de crianças? "))
pizza = float(input("Preço da pizza? R$ "))
refrigerante = float(input("Preço do refrigerante? R... |
import sys
from minecraft_data.v1_8 import blocks_list
from spockbot.mcdata import constants as const, materials
from spockbot.mcdata.utils import BoundingBox
from spockbot.mcdata.utils import camel_case, find_by
blocks = {}
blocks_name = {}
# Used for extra logic outside of minecraft_data
_block_exts = {}
def g... |
# Generated by Django 2.2.4 on 2020-07-11 17:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='CartBase',
fields=[
('id', mo... |
import matplotlib.pyplot as plt
import math
def estimate(func, init_cond: tuple, step=0.1, lower_x=-1, upper_x=1, prec=3):
"""
:param func: The differential equation in the form of f(x, y) => dy/dx
:param init_cond: The initial condition.
:param step: The step size. Defaults to 0.1.
:param lower_... |
"""Tests for the demo report plugin.
Copyright (c) 2020 The Valiant Authors
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 limitation the rights to
use, co... |
from strength_log.models import User
from strength_log import create_app, db
from strength_log.config import Config
from helium import start_firefox, kill_browser, click, Link, write
import pytest
HOME_PAGE = "https://www.strengthlog.app/"
class TestConfig(Config):
TESTING = True
BCRYPT_LOG_ROUNDS = 4
S... |
# SPDX-FileCopyrightText: 2021 SAP SE or an SAP affiliate company and Gardener contributors
#
# SPDX-License-Identifier: Apache-2.0
import dataclasses
import enum
from os import path
import typing
import yaml
import git
import tempfile
from urllib.parse import urlparse, ParseResult
import re
import logging
import ct... |
import textwrap
def strip_empty_lines(text: str) -> str:
"""
Remove empty lines from the start and end of `text`.
"""
lines = text.splitlines()
while lines and not lines[0].strip():
lines.pop(0)
while lines and not lines[-1].strip():
lines.pop()
return "\n".join(lines)
d... |
# Copyright (c) 2020 - The Procedural Generation for Gazebo authors
# For information on the respective copyright owner see the NOTICE file
#
# 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
#
#... |
"""
__init__.py
summary for
Hydropower in a community
"""
from summary import *
|
# Copyright (c) 2013, Libermatic and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from datetime import datetime
from functools import partial, reduce
from operator import add
from toolz import compose, assoc, get, concatv, merge, pluck
def execu... |
#!/usr/bin/env python3
from setuptools import setup
setup(
name='coursewatch',
version='1.2.4',
description='Discord bot to watch availability of courses on Ellucian Banner',
author='Rishov Sarkar',
url='https://github.com/ArkaneMoose/CourseWatch',
license='MIT',
packages=['coursewatch'],
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 11 17:56:24 2017
@author: sarah
"""
import numpy as np
from misc import *
import world
import environment as env
import agent as agt
import perception as prc
import action_selection as asl
import itertools
import matplotlib.pylab a... |
from django.shortcuts import render
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.http import JsonResponse
from backstage.models import Student, Teacher, College, Major, MajorPlan, ClassRoom, AdmClass
from courseScheduling.models import Course, MajorPlan, MajorCourses, T... |
#!/usr/bin/env python
from brish import z, zp
import gc
import numpy
np = numpy
def some_fn():
## Both of these will "leak" memory.
a = np.random.uniform(size=(n))
##
# a = np.ones(n, dtype=np.int64)
##
# return None
return a
z('''
function memory-free-get {{
local free_ram
free_ram=... |
#!/usr/bin/python
#
# Copyright (c) 2017, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
#
# All rights reserved.
#
# The Astrobee platform is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in comp... |
#
# Copyright (C) 2020 Arm Mbed. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
"""Code Snippet APIs."""
import textwrap
from snippet import workflow, config
from snippet._internal.logs import LOGGER
def extract_code_snippets(config: config.Config) -> None:
"""Extracts code snippets according to co... |
import traceback
import numpy as np
import os
import cv2
import tensorflow as tf
from time import time
from pathlib import Path
from facelib import FaceType
from facelib import LandmarksProcessor
class LandmarksExtractor(object):
def __init__(self, keras):
self.keras = keras
self.graph = tf.get_de... |
import tkinter as tk
import os.path
from PIL import ImageGrab
from datetime import datetime
desktop = os.path.expanduser("~/Desktop/")
class App(tk.Tk):
def __init__(self):
super().__init__()
w = self.winfo_screenwidth()
h = self.winfo_screenheight()
self.geometry(f"{w}x{h}")
... |
"""Test for time-based decoherence.
Since properly testing if the time-based decoherence gets applied correctly
needs many moving parts (difficult to do fine-grained unittesting), we do this
in its own file.
"""
import unittest
from world import World
from quantum_objects import Pair, Station
from libs.aux_functions ... |
import time
from multiprocessing import Process
from .server import app
class TestWebServer:
"""
Helper class to manage your flask test server.
"""
def __init__(self, port=5000, startup_wait=0.25):
"""
"""
self.server = None
self.port = port
self.startup_wait =... |
EXTRA_METRICS = [
"felix.active.local_endpoints",
"felix.active.local_policies",
"felix.active.local_selectors",
"felix.active.local_tags",
"felix.cluster.num_host_endpoints",
"felix.cluster.num_hosts",
"felix.cluster.num_workload_endpoints",
"felix.ipset.calls",
"felix.ipset.errors"... |
class Slot:
def __init__(self, start, end, open_time, close_time):
self.start = start
self.end = end
self.status = None
if start < 0:
raise ValueError("Slot start cannot be negative")
if end < 0:
raise ValueError("Slot end cannot be negative"... |
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from wagtail.wagtailadmin.edit_handlers import (FieldPanel, ObjectList,
TabbedInterface)
from wagtail.wagtailcore.fields im... |
import json
import os
import multiprocessing
import struct
import importlib
from socketserver import TCPServer, StreamRequestHandler
def plugin_module_import(name):
try:
return importlib.import_module(name)
except ModuleNotFoundError as e:
prompt = 'plugin {} not found, please install it first... |
from datetime import datetime, timedelta
import aiohttp
import discord
from dateutil import parser
from pytz import timezone
from sqlalchemy import asc
from bot import load_config
from .models import session, Follows
config = load_config()
async def twitch_api_call(ctx, endpoint, channel, params):
async with a... |
# =================================================================
#
# Authors: Bernhard Mallinger <bernhard.mallinger@eox.at>
#
# Copyright (C) 2020 EOX IT Services GmbH <https://eox.at>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# ... |
# -*- coding: utf-8 -*-
# @Author: 何睿
# @Create Date: 2018-12-21 11:18:38
# @Last Modified by: 何睿
# @Last Modified time: 2018-12-21 14:26:43
class Solution:
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place ... |
from .__init__ import *
from ..__init__ import Generator
def volumeSphereFunc(maxRadius=100):
r = random.randint(1, maxRadius)
problem = f"Volume of sphere with radius {r} m = "
ans = (4 * math.pi / 3) * r * r * r
solution = f"{ans} m^3"
return problem, solution
volumeSphere = Generator("Volume... |
import numpy as np
import plotly
import plotly.graph_objs as go
from HypeNet.Networks.FCNN_SoftmaxCE import FCNN_SoftmaxCE
from HypeNet.Core.loadData import loadFashionMnist
from HypeNet.Core.Trainer import Trainer
from HypeNet.Core.utils import *
import math
X_train, Y_train, X_val, Y_val, Y_train_label, Y_val_label ... |
import logging
import re
from typing import Dict, List
from airflow.hooks.S3_hook import S3Hook
from airflow.models import BaseOperator
from airflow.hooks.glue_presto_apas import GlueDataCatalogHook
OverwriteMode = "overwrite"
ErrorIfExistsMode = "error_if_exists"
SkipIfExistsMode = 'skip_if_exists'
AvailableModes ... |
#! /usr/bin/env python3
import logging
logger = logging.getLogger(__name__)
debug, info, warn, error, panic = logging.debug, logging.info, logging.warn, logging.error, logging.critical
import collections
import html.parser
import urllib.parse
import requests
from .util import *
class PastebinPaste:
def __init... |
import os
from flask import Flask
from routes.admin import bp as admin_bp
from routes.site import bp as site_bp
from routes.health import bp as health_bp
from routes.user import bp as user_bp
from database import db
def create_app():
app = Flask('example')
app.register_blueprint(admin_bp, url_prefix='/ad... |
from .discretize import *
from .statistics import * |
import os
import sys
import csv
from datetime import timezone
from datetime import datetime
import simplekml
"""
Create a google earth track from gopro gps file and a zoomin-effect for intro
"""
def _create_track(res, parent, iconTitle):
trk = parent.newgxtrack(name=iconTitle)
trk.lookat.gxtime... |
# Copyright (c) 2021 Jonas Thorsell
import sys
import numpy as np
from collections import defaultdict
p1start = int(sys.stdin.readline().strip()[-1])
p2start = int(sys.stdin.readline().strip()[-1])
# 3D3 3-9, 3:1 4:3 5:6 6:7 7:6 8:3 9:1
dice = [(3,1),(4,3),(5,6),(6,7),(7,6),(8,3),(9,1)]
gst = {(0,p1start,0,p2start):... |
from typing import Any, Dict, List, Type, TypeVar, cast
import attr
T = TypeVar("T", bound="MetadataDefinitionEntry")
@attr.s(auto_attribs=True)
class MetadataDefinitionEntry:
""" """
distinct_metadata_values: List[str]
is_editable: bool
is_multiple: bool
metadata_name: str
def to_dict(sel... |
from src.bsl_python.GUI.experiments.gui_experiment import GUIExperiment
import dash_bootstrap_components as dbc
from src.bsl_python.GUI.panels.panel import Panel
from src.bsl_python.GUI.visualizations.psth import PSTH
from src.bsl_python.GUI.visualizations.raster import Raster
class FMS(GUIExperiment):
units = N... |
"""Support for Audi Connect sensors."""
import logging
from homeassistant.components.binary_sensor import DEVICE_CLASSES, BinarySensorDevice
from homeassistant.const import CONF_USERNAME
from .audi_entity import AudiEntity
from .const import DOMAIN, CONF_CARNAME
_LOGGER = logging.getLogger(__name__)
async def asyn... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
import requests
from infra.services.builder_alerts import reasons_splitter
class MockJsonResponse(object):
def __init__(self, data=None... |
# coding=utf-8
import os
import cv2
import keras.backend as K
import numpy as np
import skimage
import tensorflow as tf
import time
from generator_dehaze import get_data, rgbf2bgr, flip_axis
from kf_util import mkdir_p
from predict_depth import Depth4Predictor
from keras_custom import init_seeds
from models_dehaze impo... |
#!/usr/bin/env python
import numpy as np
import rosbag
from tf.transformations import quaternion_from_euler as euler2quat
import tf
import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import TransformStamped
def get_path(data):
path = np.zeros((data2.shape[0], 3))
lat = data[:,1]*np.pi/18... |
#
#Name : Aditya Ramachandra Desai
#USC ID : 5246-4961-15
#Script : The following script activates the standard perceptron to classify the emails based on the learning model
#Dataset 100% : /home/aditya/CSCI544Corpus/dev
#
from GenericPerceptron import GenericPerceptron
import sys
if __name__ == "__main__":
clas... |
import numpy as np
from tqdm import tqdm
import pickle as pkl
import json
from nltk import word_tokenize
import re
from torch.utils.data.dataset import Dataset
import numpy as np
from copy import deepcopy
def process(input, output, dummy = True):
f = open(input, encoding='utf-8')
f2 = open(output, "a", encodi... |
import os
import unittest
from integration_tests.env_variable_names import (
SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN,
SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN,
)
from slack_sdk.web import WebClient
class TestWebClient(unittest.TestCase):
def setUp(self):
self.org_admin_token = os.environ[... |
#!/usr/bin/env python3
# -*- coding=utf-8 -*-
Version = "1.0.1"
|
#!/usr/bin/env python
# encoding: utf-8
# PYTHON_ARGCOMPLETE_OK
# this file exists to avoid circular dependencies
# from __future__ imports must occur at the beginning of the file
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
import os
import math
import... |
import datetime
import json
from aiommy import dateutils
def dumps(data, indent=None):
def handler(entity):
if isinstance(entity, datetime.datetime):
return dateutils.to_iso(entity)
elif isinstance(entity, bytes):
return entity.decode('utf-8')
raise NotImplementedE... |
import yaml
import TaggingUtils
def generate_soc_ranges(soc_file, range_file, policy_inits):
soc_cfg = yaml.load(soc_file.read(), Loader=yaml.FullLoader)
soc_ranges = {}
for elem in soc_cfg['SOC']:
elem_fields = soc_cfg['SOC'][elem]
name = elem_fields['name']
start = elem_fields['s... |
from .aux_functions import *
from .circle import Circle
from .cuboid import Cuboid
from .cylinder import Cylinder
from .line import Line
from .plane import Plane
from .point import Point
from .sphere import Sphere
# from pyRANSAC_3D import Cylinder, Cuboid, Plane
|
# coding=utf-8
# Copyright 2018 The Gin-Config Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
# -*- coding: utf-8 -*-
from pygments.lexer import words
from pygments.lexer import RegexLexer
from pygments.token import Text, Keyword, Literal, Name, Operator
from .index import AzureShellIndex, get_completions_commands_and_arguments
from .cache import AzureShellCache
class AzureShellLexer(RegexLexer):
index_da... |
import tensorflow as tf
from models.rnd import RND
from models.embedding_network import EmbeddingNetwork, EpisodicMemory
class IntrinsicMotivation(tf.keras.Model):
def __init__(self, params, batch_sizes):
super(IntrinsicMotivation, self).__init__()
self.rnd = RND(params['RND'])
self.embed... |
from .exquiro import create_app, VERSION, AUTHOR, RELEASE
__all__ = ['create_app']
__author__ = RELEASE
__version__ = VERSION
__release__ = RELEASE |
import os
import subprocess
# Takes files with provided names from data/raw (or all files if left blanck) and extracts text from them, using ghostscript
# Trims each text file such that only opinions are included
# ghostscript occasionally fails on certain files, reason unknown, cutting out the majority of pages
# scr... |
# Copyright The IETF Trust 2011-2020, All Rights Reserved
# -*- coding: utf-8 -*-
import io
import os
import re
import datetime
import email
import pytz
import sys
import tempfile
import xml2rfc
from contextlib import ExitStack
from email.utils import formataddr
from unidecode import unidecode
from django import fo... |
import base64
import functools
import logging
import os
from collections import namedtuple
import jwt
from flask import request
from jwt.exceptions import InvalidTokenError
from werkzeug.exceptions import BadRequest
from werkzeug.exceptions import Unauthorized as _Unauthorized
from yawc.db.query.user import get_user, ... |
"""Custom type aliases."""
from typing import Union
import numpy as np
import pandas as pd
PandasObject = Union[pd.Series, pd.Index, pd.DataFrame]
PandasExtensionType = pd.core.dtypes.base.ExtensionDtype
PandasDataType = Union[pd.core.dtypes.base.ExtensionDtype, np.dtype, type]
|
import cv2
import numpy as np
import sys
import time
import logging
import datetime
import numpy as np
import cv2
import tensorflow as tf
import tensorflow.contrib.tensorrt as trt
from utils.od_utils import read_label_map, load_trt_pb, detect
from utils.visualization import BBoxVisualization
from streamutils import ... |
'''
BSD Licence
Copyright (c) 2012, Science & Technology Facilities Council (STFC)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright n... |
from common import *
class TestBareTemplates(TestCase):
def assertTemplateFormat(self, format, output, **data):
tpl = Template(format)
value = tpl.format(**data)
self.assertEqual(value, output)
def assertTemplateMatch(self, format, input, **data):
tpl = Template(forma... |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.autograd import Function
from torch.nn import init
from torch.nn.init import kaiming_normal
#from correlation_package.modules.corr import Correlation1d # from PWC-Net
from networks.subm... |
"""
**The Voyager class takes advantage from the executable file voyager.exe to launch CUBE scripts using command lines.**
Launching a CUBE script with a command line requires the voyager folder that contains voyager.exe to belong to the
system(windows) path. In order to be able to launch CUBE scripts using command li... |
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from netfilterqueue import NetfilterQueue
import dpkt
import socket
import struct
key = b'.\xb4\x19\x839J"ys\nSvQ\x16$\xfb\xa0\xeb4w\x83\xf8{\x8bN\x93ii\x9b&\xa2\xca'
keyca = AESGCM(key)
sockfd = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.IPP... |
from ..value_set import ValueSet
class AcuteAndSubacuteIridocyclitis(ValueSet):
"""
**Clinical Focus:** This value set contains concepts that represent a diagnosis of acute and subacute iridocyclitis.
**Data Element Scope:** This value set may use the Quality Data Model (QDM) category related to Diagnosi... |
import functools
class Solution:
def hasGroupsSizeX(self, deck: List[int]) -> bool:
return functools.reduce(math.gcd, collections.Counter(deck).values()) > 1
|
# Generated by Django 3.1.3 on 2020-11-22 07:50
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('instagram', '0004_auto_20201122_1046'),
]
operations = [
migrations.RenameField(
model_name='image',
old_name='image_name',
... |
# 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... |
from tests.support.inline import inline
from tests.support.asserts import assert_error, assert_success
alert_doc = inline("<script>window.alert()</script>")
# 10.7.3 Maximize Window
def test_maximize_no_browsing_context(session, create_window):
# Step 1
session.window_handle = create_window()
session.clos... |
def safe_pawns(pawns: set) -> int:
board = {x: [] for x in range(1, 9)}
safes = 0
for pos in pawns:
pos_int = split_position(pos)
board[pos_int[1]].append(pos_int[0])
for row in range(2, 9):
for col in range(1, 9):
if col in board[row]:
if (col - 1 i... |
import unittest
from unittest.mock import Mock
import pytest
from flask import url_for
from tests.factories import (
job_factory,
file_factory,
file_annotation_factory
)
@pytest.mark.usefixtures('test_ctx', 'database')
class TestFiles:
def test_get_empty(self, client):
response = client.get(... |
from styx_msgs.msg import TrafficLight
import tensorflow as tf
import numpy as np
import time
from scipy.stats import norm, mode
import os
import rospy
class TLClassifier(object):
def __init__(self):
GRAPH_FILE = 'frozen_inference_graph.pb'
model_path = os.path.dirname(os.path.realpath... |
import asyncio
import websockets
from wsrpc import WebsocketRPC
class SampleHandler:
def __init__(self, rpc):
self.remote = rpc
async def add(self, a, b):
await asyncio.sleep(5)
return a + b
async def test(self):
return 23
async def go(ws, path):
await WebsocketRP... |
import sc2
from sc2 import run_game, maps, Race, Difficulty, PlayerType
from sc2.player import Bot, Computer, Player
from sc2.constants import NEXUS, PROBE, PYLON, ASSIMILATOR, GATEWAY, \
CYBERNETICSCORE, STALKER, STARGATE, VOIDRAY
import random
import cv2
import numpy as np
# about 165 iterations per minute
clas... |
class Account:
account_count = 0
total_balance = 0
def __init__(self, name, description, balance):
self.name = name
self.balance = balance
self.description = description
Account.account_count += 1
Account.total_balance += self.balance
def displayC... |
from django.contrib import admin
from django_base.admin import BaseModelAdmin
from .models import ExampleModel
@admin.register(ExampleModel)
class ExampleModelAdmin(BaseModelAdmin):
pass
|
#@author: Ashish Shetty
#@version: 2.0
from easygui import *
import sys
#start of GUI
msg = "Enter the message you to encrypt/decrypt and the key for the same"
title = "Simple cipher by AlphaSierraASH"
fieldNames = ["Message to encrypt/decrypt", "Key for encrypting/decrypting"]
fieldValues = multenterbox(msg, title, ... |
from fabric.api import cd, env, task
# from fabric.context_managers import cd
# from fabric.contrib.files import exists
from fabric.contrib.project import rsync_project
from fabric.operations import require # sudo, put
from .utils import w
from . import git
from . import releases
from . import virtualenv
import time... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: owefsad@huoxian.cn
# datetime: 2021/6/1 上午9:53
# project: dongtai-openapi
# -*- coding: utf-8 -*-
import base64
import logging
import oss2
from oss2.exceptions import NoSuchKey
from oss2.exceptions import RequestError
from AgentServer import settings
logger = l... |
# Copyright (c) 2021 Emanuele Bellocchia
#
# 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 limitation the rights
# to use, copy, modify, merge, publish,... |
# Time: O(n^2)
# Space: O(n)
class Solution(object):
# @param {character[][]} matrix
# @return {integer}
def maximalSquare(self, matrix):
if not matrix:
return 0
m, n = len(matrix), len(matrix[0])
size = [[0 for j in range(n)] for i in range(2)]
max_size = 0
... |
"""
DESAFIO 053: Detector de Palíndromo
Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços.
"""
acentos = {'á': 'a', 'à': 'a', 'ã': 'a', 'â': 'a', 'é': 'e', 'ê': 'e', 'í': 'i',
'ó': 'o', 'õ': 'o', 'ô': 'o', 'ú': 'u', 'ü': 'u', 'ç': 'c', "'": ""}
outros = ... |
# -*- coding: utf-8 -*-
import asyncio
import re
from typing import Union, TYPE_CHECKING
from .http import HTTPClient
if TYPE_CHECKING:
from .bot import Bot
from .client import Client
class WebhookClient:
def __init__(self, client: Union['Bot', 'Client'], bot: 'Bot', loop: asyncio.AbstractE... |
# 712. Minimum ASCII Delete Sum for Two Strings
# Runtime: 661 ms, faster than 85.11% of Python3 online submissions for Minimum ASCII Delete Sum for Two Strings.
# Memory Usage: 18.5 MB, less than 68.51% of Python3 online submissions for Minimum ASCII Delete Sum for Two Strings.
class Solution:
# Dynamic Progra... |
# Generated by Django 2.0.4 on 2018-04-05 12:55
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import enumfields.fields
import leasing.enums
class Migration(migrations.Migration):
dependencies = [
('leasing', '0011_rename_period_type_enum'),
]... |
# -*- coding: utf-8 -*-
"""PyKEEN is a Python package for reproducible, facile knowledge graph embeddings.
The fastest way to get up and running is to use the :func:`pykeen.pipeline.pipeline`
function.
It provides a high-level entry into the extensible functionality of
this package. The following example shows how t... |
from pathlib import Path
from os import path
from card_live_dashboard.service.GeographicRegionCodesService import GeographicRegionCodesService
region_codes = GeographicRegionCodesService(Path(path.dirname(__file__), 'data', 'UN-M49', 'UNSD-Methodology.csv')) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.