content stringlengths 5 1.05M |
|---|
"""Helpers for script and condition tracing."""
from collections import deque
from contextvars import ContextVar
from typing import Any, Dict, Optional
from homeassistant.helpers.typing import TemplateVarsType
import homeassistant.util.dt as dt_util
def trace_stack_push(trace_stack_var: ContextVar, node: Any) -> Non... |
import numpy as np
from nose.tools import raises
from webdnn.graph.axis import Axis
from webdnn.graph.operators.abs import Abs
from webdnn.graph.operators.elementwise_add import ElementwiseAdd
from webdnn.graph.operators.elementwise_div import ElementwiseDiv
from webdnn.graph.operators.elementwise_mul import Elementwi... |
def sieve(n):
primes = []
is_prime = [1 for i in range(n+1)]
is_prime[0] = is_prime[1] = 0
for i in range(n+1):
if is_prime[i]:
primes.append(i)
m = 2
while i*m <= n:
is_prime[i*m] = 0
m += 1
print(primes)
sieve(10) |
# -*- coding:utf-8 -*-
"""
Verion: 1.0
Author: Helixcs
Site: https://github.com/Xarrow/weibo-scraper
File: __init__.py
Time: 6/9/18
"""
from .persistence import dispatch |
RPC_ERROR_BEGIN = 10000
RPC_ERROR_INTERFACE_INVALID = RPC_ERROR_BEGIN + 1
RPC_ERROR_IMPL_INVALID = RPC_ERROR_BEGIN + 2
RPC_ERROR_UNKNOWN = RPC_ERROR_BEGIN + 3
RPC_ERROR_ENTITY_NOT_FOUND = RPC_ERROR_BEGIN + 4
RPC_ERROR_METHOD_NOT_FOUND = RPC_ERROR_BEGIN + 5
RPC_ERROR_POSITION_CHANGED = RPC_ERROR_BEGIN + 6
class RpcEx... |
import pygame
import sys
import numpy as np
sys.path.append("game/")
import wrapped_flappy_bird as game
if __name__ == "__main__":
game_state = game.GameState(is_show_score = True)
R = 0
while(1):
action = np.zeros(2)
action[0] = 1
events = pygame.event.get()
for event in e... |
from random import randint
from random import uniform
class GenNumber:
@staticmethod
def rand_num(x, y):
if isinstance(x, float):
return GenNumber.rand_float(x, y)
return randint(x, y)
@staticmethod
def rand_float(x, y):
return uniform(x, y)
|
# -*- coding: utf-8 -*-
#!/usr/bin/env python
"""
This implementation does its best to follow the Robert Martin's Clean code guidelines.
The comments follows the Google Python Style Guide:
https://github.com/google/styleguide/blob/gh-pages/pyguide.md
"""
import psutil
from ina219 import INA219
from ina219 import ... |
#!/usr/bin/env python
import os
from pygecko import FileStorage
def test_yaml():
data = {
'bob': 1,
'tom': 2,
'sam': 3
}
fname = 'test.yaml'
fs = FileStorage()
fs.writeYaml(fname, data)
fs.clear()
fs.readYaml(fname)
# print fs.db
os.remove(fname)
assert fs.db == data
def test_json():
data = {... |
from django.template import Library, Node
register = Library()
"""
http://djangosnippets.org/snippets/889/
{% load convenient %}
{% list_to_columns people as list 3 %}
{% for l in list %}
<ul>
{%for p in l %}
<li>{{ p }}</li>
{% endfor %}
</ul>
{%... |
import asyncio
import pytest
class CustomSelectorLoopSession(asyncio.SelectorEventLoop):
"""A subclass with no overrides, just to test for presence."""
pass
loop = CustomSelectorLoopSession()
@pytest.fixture(scope="package")
def event_loop():
"""Create an instance of the default event loop for each ... |
"""Control regulators designs for oscillator-like systems"""
import control
import numpy as np
import kontrol.regulator.feedback
import kontrol.regulator.predefined
#FIXME find a better name
def pid(
plant, regulator_type="PID", dcgain=None,
integrator_ugf=None, integrator_time_constant=None,
return_gain... |
"""Generated client library for translate version v3."""
# NOTE: This file is autogenerated and should not be edited by hand.
from __future__ import absolute_import
from apitools.base.py import base_api
from googlecloudsdk.third_party.apis.translate.v3 import translate_v3_messages as messages
class TranslateV3(base... |
"""
Conditional random field
Some code are copied from AllenNLP
"""
from collections import namedtuple
from typing import List, Tuple, Dict
import numpy as np
import pandas as pd
from tf_crf_layer.exceptions import ConfigurationError
ConstraintType = namedtuple('ConstraintType', ["BIO", "IOB1", "BIOUL", "BMES"])
co... |
import os
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
csv_file = os.path.join(os.getcwd(), 'data', 'metrics.csv')
df = pd.read_csv(csv_file)
df = df[df['splits'] != 0]
df['type'] = df['inputfile'].map(lambda s: s.split(os.path.sep)[-2])
df = df[df['type'] != 'dimacs']
d... |
# The MIT License (MIT)
#
# Copyright (c) snkas
#
# 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, p... |
'''
1. 尝试写代码实现以下截图功能:
>>>
请输入一个整数:5
1
2
3
4
5
'''
def printnum():
try:
num = int(input('请输入一个整数:'))
while num:
print(num)
num -= 1
except ValueError:
print('请输入整数,憨憨')
printnum()
printnum()
|
__author__ = "Kynarth Alseif"
__email__ = "kynarth.alseif@gmail.com"
__version__ = "0.5.0"
|
# -*- coding: utf-8 -*-
# filename: handle.py
import hashlib
import reply
import receive
import web
from wenpl.divide import showReply
import json
class Handle(object):
def POST(self):
try:
webData = web.data()
recMsg = receive.parse_xml(webData)
if isinstance(recMsg, ... |
from . import parameter as param
from . import path
from . import stats
from scipy import linalg
import numpy as np
import pandas as pd
from pandas.tseries.holiday import USFederalHolidayCalendar
MARKET_SECONDS_PER_YEAR = 252.0*6.5*60.0*60.0
class MultiStockPath:
def __init__(self,
generator,
... |
"""UseCase for hard removing a smart list."""
import logging
from argparse import Namespace, ArgumentParser
from typing import Final
import jupiter.command.command as command
from jupiter.use_cases.smart_lists.remove import SmartListRemoveUseCase
from jupiter.domain.smart_lists.smart_list_key import SmartListKey
LOGG... |
from datetime import datetime
from b2stage.endpoints.commons import path
from restapi.env import Env
from restapi.rest.definition import EndpointResource
from seadata.endpoints.commons.seadatacloud import seadata_vars
# from restapi.utilities.logs import log
DEFAULT_IMAGE_PREFIX = "docker"
"""
These are the names o... |
from __future__ import absolute_import
from .baseplugin import BasePlugin
from .constants import (DUNNO, OK, NOT_OK)
import logging
logger = logging.getLogger(__name__)
class Uptime(BasePlugin):
def __init__(self, uptime=60, *args, **kwargs):
super(Uptime, self).__init__(args, kwargs)
self._uptim... |
# from breezycreate2 import Robot
import numpy as np
import cv2
from IRobotProcessing import IRobotProcessing
import matplotlib.pyplot as plt
import math
import time
# import math
"""
This class is about some openCV image processing.
"""
class OpenCVProcessing():
def __init__(self):
self.i... |
from ailment.expression import BinaryOp, Const, Convert
from .base import PeepholeOptimizationExprBase
_MASK_TO_BITS = {
0xff: 8,
0xffff: 16,
0xffff_ffff: 32,
}
class ExtendedByteAndMask(PeepholeOptimizationExprBase):
__slots__ = ()
NAME = "extended byte & 0xff..ff => extended byte"
expr_cl... |
import logging
import logging.handlers
import datetime # TODO: MongoHandler에 사용됨, 불필요하게 되면 삭제
# - [조금 더 체계적인 Python Logging](https://hwangheek.github.io/2019/python-logging/)
# - [LogRecord 어트리뷰트](https://docs.python.org/ko/3/library/logging.html#logrecord-attributes)
# - [logging.handlers — 로깅 처리기](https://docs.pyth... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: steammessages_clientserver_friends.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _messa... |
# -*- coding: utf-8 -*-
from tornado.web import URLSpec, RedirectHandler
from webspider.web.handlers import KeywordStatisticsApiHandler, KeywordStatisticsPageHandler
url_handlers = [
URLSpec(r"/", RedirectHandler, {'url': '/statistics?keyword_name=python'}),
URLSpec(r"/api/statistics", KeywordStatisticsApiHan... |
import unittest
import os
import numpy
import anuga
from anuga.structures import internal_boundary_functions
from anuga.structures.internal_boundary_functions import hecras_internal_boundary_function
from anuga.structures.internal_boundary_functions import pumping_station_function
from anuga.utilities.system_tools imp... |
# -*- coding: utf-8 -*-
"""
# @file name : main.py
# @author : zjgbz https://github.com/zjgbz
# @date : 2021-02-27
# @brief : 模型训练主代码
"""
import matplotlib
# matplotlib.use('agg')
import os
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(BASE_DIR, '..'))
fro... |
from django.contrib import admin
from profiles_api import models
admin.site.register(models.UserProfiles)
admin.site.register(models.ProfileFeedItem)
|
#!/usr/bin/env python27
#=========================================================#
# [+] Title: HeartLeak (CVE-2014-0160) #
# [+] Script: HeartLeak.py #
# [+] Twitter: https://twitter.com/OffensivePython #
# [+] Blog: http://pytesting.blogspot.com ... |
import PyPDF2 as p2
import pandas as pd
import numpy as np
na_list=[]
roll_list=[]
def roll_extract(a):
roll_no=''
for i in range(20,35):
if name[i][-10:]=='118College':
for j in name[i][:-10]:
if j in '1234567890':
roll_no=roll_no+str(j)
... |
num1 = 12
|
from datetime import datetime
from django.test import TestCase
# Create your tests here.
from django.utils import timezone
from django.test import TestCase
from .models import AbsenseRecord, Employee, Record
from django.utils import timezone
from authentication.models import CoreUser
# models test
class EmployeeCreat... |
from base64 import b64decode
import pytest
RED_DOT = """data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg=="""
BLUE_DOT = """data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA
oAAAAKAQMAAAC3/F3+AAAACXBIWXMAAA7DAAAOwwHHb6hkAA
AAAXN... |
def parse(rows, employees):
curr_row = 0
begin_row = 1
for row in rows:
if curr_row < begin_row:
curr_row += 1
continue
reg = float(row[0])
aux_adocao = float(row[4]) #AUXÍLIO-ADOÇÃO/VERBAS INDENIZATÓRIAS
aux_ali = float(row[5]) #AUXÍLIO-ALIMENTAÇÃO/... |
from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.template.defaultfilters import filesizeformat
from django.utils. module_loading import import_string
from draftjs_exporter.defaults import BLOCK_MAP
_exporter_config = None
def get_exporter_config():
global _e... |
import os
import sys
import itertools
from operator import ge, le, eq
import copy
import pandas as pd
import tqdm
import csv
import pickle
from pybkb import bayesianKnowledgeBase as BKB
from pybkb.core.common.bayesianKnowledgeBase import BKB_I_node, BKB_component, BKB_S_node
from pybkb.core.python_base.fusion import f... |
#!/usr/bin/python3
import cv2
# all functions of cv2 that is opencv model
#print dir(cv2)
# reading image
# image name , imaeg features
# we can write cv2.IMREAD_COLOR instead of 1
# we can write cv2.IMREAD_BGR2GRAY instead of 0
# we can write cv2.IMREAD_UNCHANGE_... |
THREE_D_ALGORITHM = 10 # The 3D algorithm for software mixed 3D channels
# BASS_SetConfig options
BUFFER = 0 # Playback buffer length.
UPDATEPERIOD = 1 # Update period of playback buffers
GVOL_SAMPLE = 4 # Global sample volume.
GVOL_STREAM = 5 # Global stream volume
GVOL_MUSIC = 6 # Global MOD music volume.
CURVE_VOL ... |
class RestError(Exception):
'''
Base rest error exception class. All other rest exceptions are derived from
RestError.
'''
def __init__(self, message, **info):
'''
:param message: string -- exception message
:param code: int -- error code, optional. used to be returned
... |
# coding=utf-8
"""
design:zyx
date:20170802
"""
import ctypes, datetime
import time, os
import logging
from xml.etree import ElementTree as ET
os.path.abspath('.')
from ctypes import *
import its_xlsx
import win32gui
iServerPort = 0
iClientPort = 6699
iWnd = 0
cProxy = ""
# ctypes.POINTER(c_char("/0")*2)
# cProxyn =c... |
from ... pyaz_utils import _call_az
from . import address_pool, auth_cert, client_cert, frontend_ip, frontend_port, http_listener, http_settings, identity, private_link, probe, redirect_config, rewrite_rule, root_cert, rule, ssl_cert, ssl_policy, ssl_profile, url_path_map, waf_config, waf_policy
def create(name, reso... |
from rpython.jit.backend.zarch.test.support import JitZARCHMixin
from rpython.jit.metainterp.test.test_dict import DictTests
class TestDict(JitZARCHMixin, DictTests):
# for the individual tests see
# ====> ../../../metainterp/test/test_dict.py
pass
|
#!/usr/bin/env python3
# Copyright (c) 2014-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test resurrection of mined transactions when the blockchain is re-organized."""
from decimal import De... |
import os
import os.path as osp
import json
import torch
import numpy as np
from torch_sparse import coalesce
from torch_geometric.data import (InMemoryDataset, Data, download_url,
extract_zip)
class PPI(InMemoryDataset):
r"""Protein-protein interaction networks from the `"Predi... |
import logging
import numpy as np
from .geometry import get_loc_from_timelist
def plot_results(
beampowers: np.ndarray,
settings: dict,
start_time: "obspy.UTCDateTime",
grid_lon_coords: np.ndarray,
grid_lat_coords: np.ndarray,
station_locations: np.ndarray,
plot_identifier: str = "empty"... |
from functools import reduce
from operator import mul
from ctypes import c_void_p
from devito.dimension import Dimension
from devito.mpi.utils import get_views
from devito.ir.equations import DummyEq
from devito.ir.iet import (ArrayCast, Call, Callable, Conditional, Expression,
Iteration, Li... |
from protocols.reports_2_1_0 import *
|
x = 0
for i in [0, 1, 2]:
x = 2 *i
|
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BCM)
Motor1Enable = 5
Motor1B = 24
Motor1A = 27
Motor2Enable = 17
Motor2B = 6
Motor2A = 22
#single shot script used as a warning shot
# Set up defined GPIO pins
GPIO.setup(Motor1A,GPIO.OUT)
GPIO.setup(Motor1B,GPIO.OUT)
GPIO.setup(Motor1Enable,GPIO.OUT)... |
# 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... |
# uninhm
# https://atcoder.jp/contests/abc208/tasks/abc208_c
# implementation
n, k = map(int, input().split())
a = list(map(int, input().split()))
x = sorted(a)[k%n]
for i in a:
if i < x:
print(k//n+1)
else:
print(k//n)
|
# coding=UTF-8
import torch
import torchvision
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from math import *
import os
import numpy as np
import torch
import argparse
import torch.nn as nn
import torch.nn.functional as F
class Flatten(nn.Module):
def forward(self, input):
ret... |
'''
update_prefixlist - update the prefixlist file with updates from message bus
using mqbgp to get BGP updates (advertisements/withdraws)
@author: Pim van Stam <pim@svsnet.nl>
Created on 25 Apr 2019
The MIT License (MIT)
Copyright (c) 2019 - Pim van Stam <pim@svsnet.nl>
Permissi... |
from django.core.urlresolvers import reverse
from django.test import TestCase, override_settings
from accounts.models import User
@override_settings(STATICFILES_STORAGE='django.contrib.staticfiles.storage.StaticFilesStorage')
class AccountUsersViewsTestCase(TestCase):
@classmethod
def setUpTestData(cls):
... |
import sys
def handle(event, context):
return "hello"
print(sys.path)
|
import aiml
import pyttsx
from gtts import gTTS
import subprocess
import time
def process_output(output):
if output[0:8] == '@COMMAND':
return True
def command_process(command):
if command[9:16] == 'GSEARCH':
bash_command("firefox http://www.google.com?q="+command[17:].replace(' ','+')+" &")
say("informat... |
from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.urls import include, path, re_path
from django.contrib import admin
from django.views.generic import RedirectView
from rest_framework.schemas import get_schema_view
from rest_framework.renderers import JSONOpenAPIRend... |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: proto
import flatbuffers
class AuthScramChallenge(object):
__slots__ = ['_tab']
@classmethod
def GetRootAsAuthScramChallenge(cls, buf, offset):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 12 14:15:13 2018
@author: assaf, ruth, katya, zach
Example function calls:
get_discrete_perim(df_statecds, df_vtds)
get_discrete_area(df_statecds, df_vtds)
"""
import geopandas as gpd
import pandas as pd
# Functions for calculating discrete area and perimete... |
#!/usr/bin/env python3
# system
import chain_reaction.game as chain_reaction_game
def main():
# parameters
shape = (9, 6)
backend = "python"
win_type = "animated"
# players
player1 = "random"
player2 = "minimax"
# configurations
config1 = {
"minimax": {"search_depth": 1... |
from reward import Reward
class HitReward(Reward):
def __init__(self, hit_reward=-1.):
self.hit_reward = hit_reward
def __call__(self, done, action, *args, **kwargs):
if not done:
reward = 0
else:
reward = self.hit_reward
return reward
|
import os
from typing import List
from ...package import Package
from ...util import Namespace, FatalError, run
from ..llvm import LLVM
class LLVMPasses(Package):
"""
LLVM passes dependency. Use this to add your own passes as a dependency to
your own instances. In your own passes directory, your Makefile ... |
"""
The MIT License (MIT)
Copyright (c) 2021-present Kae Bartlett
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... |
__author__ = 'feeltheajf'
import json
from dateutil import parser
from dojo.models import Finding
class BrakemanParser(object):
def get_scan_types(self):
return ["Brakeman Scan"]
def get_label_for_scan_types(self, scan_type):
return "Brakeman Scan"
def get_description_for_scan_types(... |
import flask
from flask import Blueprint, request, make_response
from kaos_backend.controllers.inference import InferenceController
from kaos_backend.util.flask import jsonify
from kaos_model.api import Response
def build_inference_blueprint(controller: InferenceController):
blueprint = Blueprint('inference', _... |
# combining box widgets
import tkinter as tk
from tkinter import ttk #ttk = themed tk
win = tk.Tk() # win is short for windows #constructor
win.title("Python GUI with label textbox widgets")
aLabel = ttk.Label(win, text="A Label")
aLabel.grid(column=0, row=0)
def clickMe(): #function to change label on click
act... |
"""create initial school table
Revision ID: 7debef0e3f50
Revises:
Create Date: 2020-02-01 16:18:24.795672
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7debef0e3f50'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### comm... |
#!/bin/python3
# Complete the minimumBribes function below.
def minimumBribes(q):
count = 0
for i in range(0, len(q)):
if (q[i] - (i + 1) > 2):
print("Too chaotic")
return
for j in range(max(0, q[i] - 2), len(q)):
if not (j < i):
break
... |
import numba as nb
import numpy as np
from dsalgo.type import F, S
# set range add, get range mininum.
# @nb.njit
def seg_op_s(a: S, b: S) -> S:
return min(a, b)
@nb.njit
def seg_e_s() -> S:
return 1 << 60
@nb.njit
def seg_op_f(f: F, g: F) -> F:
return f + g
@nb.njit
def seg_e_f() -> F:
return ... |
"""
welleng/exchange
----------------
Contains the importers and exporters for various survey formats.
"""
|
node_list = [26747,46490,46637,52720,52726,58996,67247,67250,67254,67255,67257,67263,67265,67266,67268,67270,67271,67272,
67274,67276,67277,67278,67279,67281,67283,67284,67288,67290,67291,67292,67294,67296,67297,67299,67300,67302,
67304,67307,67317,67319,67321,67322,67323,67324,67325,72311,72312] |
"""
Utility functions for testing values.
Written by Zachary Ferguson
"""
from bcolors import bcolors
def result_str(value):
""" Create a colored string for if the value is PASS or FAIL """
return "%s%s" % ((bcolors.OKGREEN + "PASS") if value
else (bcolors.FAIL + "Fail"), bcolors.ENDC)
def display... |
#!/usr/bin/env python3
"""
FIXME:add-doc
"""
#--- standard library imports
#
import sys
import os
#--- third-party imports
#
#/
#--- project specific imports
#
# add lib dir for this pipeline installation to PYTHONPATH
LIB_PATH = os.path.abspath(
os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "l... |
# from lxml import etree
from bs4 import BeautifulSoup
import urllib as request
from urlparse import urljoin
import re
import os
def getHtml(url):
res = request.urlopen(url)
try:
return url, res.read().decode("utf-8")
except Exception:
return url, res.read().decode("big5")
def extractLin... |
from django.test import TestCase
from rest_framework.test import APIClient
from rest_framework import status
from .models import Tweet
from django.urls import include, path, reverse
from .serializers import TweeTSerializer
# Create your tests here.
class APITEST(TestCase):
def setUp(self):
self.client = APICl... |
import io
from os.path import dirname, join
from setuptools import setup
def get_version(relpath):
"""Read version info from a file without importing it"""
for line in io.open(join(dirname(__file__), relpath), encoding="cp437"):
if "__version__" in line:
if '"' in line:
# __version__ = "0.9"
... |
import unittest
from unittest.mock import patch
from parameterized import parameterized
from fangfangfang.controllers.impl.models.homoglyph_fang_model\
import HomoglyphFangModel
from fangfangfang.controllers.impl.api_controller_impl import defang, refang
from fangfangfang.models.defang_request import DefangRequest
... |
from subprocess import PIPE, Popen
import telethon
from ciri.utils import eor
async def get_user(e):
args = e.text.split(maxsplit=1)
if e.reply_to_msg_id:
user = await e.get_reply_message()
user = user.sender_id
if len(args) > 1:
return user, args[1]
else:
... |
import unittest
from pyeventsystem.events import SimpleEventDispatcher
from pyeventsystem.interfaces import HandlerException
from pyeventsystem.interfaces import Middleware
from pyeventsystem.middleware import BaseMiddleware
from pyeventsystem.middleware import SimpleMiddlewareManager
from pyeventsystem.middleware imp... |
class Error(Exception):
"""
Base exception for manager errors.
"""
class BadConnectionIdentifier(Error, ValueError):
"""
Exception thrown when a bad connection spec is given to a client's
connection call.
"""
class ConnectionError(Error, IOError):
"""
Exception thrown when a connec... |
import json
import logging
import time
import numpy as np
from flask import Flask, request, jsonify
from inquire_sql_backend.query.db import retrieve_sent_metadata, retrieve_sent_metadata_many, retrieve_sent_context_metadata
from inquire_sql_backend.query.user_query import query_user_sents, retrieve_all_user_posts, q... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Linear Function Approximation for the game of easy21.
This module stores various helper functions for using linear function
approximation in the module easy21.
"""
import numpy as np
from core.base import HIT, STICK, StateAction
_ds_map = {}
_ps_map = {}
_a_map = {... |
#!/usr/bin/env python3
"""
Main program for templateme console.
"""
from templateme.console import main
if __name__ == "__main__":
main()
|
from __future__ import absolute_import
from _plotly_future_ import _chart_studio_error
_chart_studio_error("new_plotly")
|
"""
This module collects ec2 instance info from aws using boto3
"""
from models.aws_cloud.e2_resource import Ec2
class Ec2Info(Ec2):
"""Fetch the instance info using the ec2 service"""
def __init__(self, tags) -> None:
super().__init__()
self.tags = tags
def fetch_instance_info(se... |
from unittest.mock import MagicMock
import pytest
from config.enums import Network
from src.general_harvester import GeneralHarvester
from src.misc_utils import hours
@pytest.mark.parametrize("chain", [Network.Ethereum, Network.Fantom])
def test_time_to_harvest_true(mocker, chain: Network):
strategy = "0x123123... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'window.ui'
#
# Created by: PyQt5 UI code generator 5.7
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.s... |
def staircase(n: int):
space = " "
symbol = "*"
for i in range(1, n+1):
print("%s%s" %(space*(n - i), symbol*i))
if __name__ == '__main__':
n = int(input())
staircase(n) |
import requests
from bs4 import BeautifulSoup
from utils import write_data
import time
import datetime
from datetime import date, timedelta
def get_data(url):
html = requests.get(url).text
soup = BeautifulSoup(html, 'html.parser')
updated = soup.select('.timetable > .info > span')[0].text # 업데이트날짜
da... |
import player
test_data = {
"players":[
{
"name":"Player 1",
"stack":1000,
"status":"active",
"bet":0,
"hole_cards":[],
"version":"Version name 1",
"id":0
},
{
"name":"Player 2",
"stack":1000,
"status":"active",
"bet":0,
"hole_cards... |
import gooseLeader
from gooseLeader import gooseLeader
term = input('Enter a search term: ')
demoSearch = gooseLeader()
demoSearch.userHTMLReport(
demoSearch.getInfluUsers(
10,demoSearch.search(term, 1000000, "en", "mixed")),term)
|
# -*- coding: utf-8 -*-
from influxdb import InfluxDBClient
import pandas as pd
import matplotlib.pyplot as plt
#Default Influxdb connection detail. Update them to your connection detail.
HOST = '127.0.0.1'
PORT = 8086
USER = 'jmeter'
PASSWORD = 'jmeter'
DBNAME = 'jmeter'
'''
******************************Sample Que... |
from django.urls import include, path
from django.views.generic import TemplateView
from reports.views import ReportViewSet
from rest_framework.routers import DefaultRouter
from rest_framework.schemas import get_schema_view
urlpatterns = [
path(
"schema/",
get_schema_view(
title="Q&A re... |
# coding: utf-8
import numpy as np
import json
import sys
import os
class Utils(object):
"""
Util class to store all common method use in this project
"""
def __init__(self, arg):
super(Utils, self).__init__()
@staticmethod
def progress(count, total, suffix=''):
"""
... |
import math
import numpy as np
import scipy.special
def besinc(x):
"""The sombrero, jinc, or besinc function
(https://en.wikipedia.org/wiki/Sombrero_function --- note this
implementation follows the convention from Blahut, Theory of
Remote Image Formation, 2005, see p. 82).
"""
y = np.empty_... |
import ipdb
import numpy as np
import matplotlib.pyplot as plt
results = {
'Garbage': [
0.359357,
0.345487,
0.300246 ],
'Simple Features': [
0.344599,
0.422152,
0.390513 ],
'+ Physicochemical': [
0.527414,
0.625990,
0.506098 ],
... |
#!/usr/bin/env python
import os
import sys
import tutils
import IPython
def print_usage():
print '[i] usage:',os.path.basename(sys.argv[0]),'-f <file.root> [--keep-stats] [--keep-title] [--logy] [--pattern <something in the name>] [--dopt <draw option>] [--x <min:max>] [--titles]'
if __name__=="__main__":
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.