content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import os
import sys
import time
import subprocess
ITERATIONS = 10
COUNT = 20000000
VERBOSE = False
NL = '\n'
INCLUDE = "../../../src"
CC = 'gcc'
CCPP = 'g++' # LoL
OPT = '-O3'
print(f'Using {CC} compiler')
def execute_command(commands):
print(' '.join(commands))
subprocess.run(commands, shell=True)
# C... | python |
# Copyright 2011-2013 Colin Scott
# Copyright 2011-2013 Andreas Wundsam
# Copyright 2012-2013 Sam Whitlock
# Copyright 2012-2012 Kyriakos Zarifis
#
# 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 ... | python |
# Songsheng YING
# coding=utf-8
# python3.6.7 Anaconda
import os, sys
import numpy as np
from progressbar import ProgressBar, Percentage, Bar
import xml.etree.ElementTree as ET
def data_file_reader_fr(file_name, lang):
print(" Working on " + file_name)
if lang == "French":
path = os.getcwd() + '/da... | python |
workflow_xml_start = """<workflow-app name="etk-april-2017" xmlns="uri:oozie:workflow:0.5">
<global>
<configuration>
<property>
<name>oozie.launcher.mapreduce.map.memory.mb</name>
<value>10000</value>
</property>
</configu... | python |
from matplotlib import pyplot as plt
from matplotlib_venn import venn3
def plot_confusion_matrix(cm, cmap=plt.cm.Blues):
"""
Args:
cm (np.ndarray): Confusion matrix to plot
cmap: Color map to be used in matplotlib's imshow
Returns:
Figure and axis on which the confusion matrix is ... | python |
from src import network
import numpy as np
from src.study.utils import downloader
from src.study.mnist_common import mnist_reader
items = ["T-shirt/top","Trouser","Pullover","Dress","Coat","Sandal","Shirt","Sneaker","Bag","Ankle","boot"]
def download_mnist_fashion_data():
downloader.download_data("http://fashio... | python |
import re
def modify_en_text(text, modify_mode='BASIC', keep_emoji=True):
""" Make your text easy to read and to translate.
Args:
text(str):
target dirty text.
modify_mode(str):
mode selection
keep_emoji(bool):
call back ... | python |
from functools import reduce
testcases = int(input())
for t in range(testcases):
n = int(input())
vals = list(map(int, input().split()))
missed = 0
for i in range(1, len(vals)):
x = abs(vals[i] - vals[i - 1])
if x > 0:
x -= 1
missed += x
prin... | python |
# Import Required Libraries
from flask import Flask, render_template, request
import pickle
# Initialise the object to run the flask app
app = Flask(__name__, static_folder='static', template_folder='templates')
# Load the pickled model file
model = pickle.load(open('model.pkl', 'rb+'))
@app.route('/', methods=['... | python |
# Copyright 2017 Cisco Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | python |
import functools
import operator
import unittest
from migen import *
def cols(rows):
"""
>>> a = [
... [1, 2],
... ['a', 'b'],
... [4, 5],
... ]
>>> for c in cols(a):
... print(c)
[1, 'a', 4]
[2, 'b', 5]
>>> a = [
... [1, 2, 3],
... ['a', 'b', 'c'],
... ]... | python |
# -*- coding: utf-8 -*-
"""
DTSA-II Script - J. R. Minter - 2016-10-12
massFractionsTheEasyWay.py
Date Who Comment
---------- --- -----------------------------------------------
2016-10-12 JRM Mass fractions the easy way...
Elapse: 0:00:00.0 ROCPW7ZC5C42
"""
import sys
sys.packageManager.makeJavaPackag... | python |
# Import Dependencies
import numpy as np
import pandas as pd
import datetime as dt
import sqlalchemy
from sqlalchemy import desc
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func, inspect... | python |
# Normals are for all puzzles where all 3 sides are the same
# 37 is Skewb
# 38 is Pyraminx main
# 39 is Pyraminx primary corners
# 40 is Pyraminx secondary corners
# 41 is Megaminx main
# 42 is Megaminx secondary
normals = {
2: {'moves': (('U', 'D'), ('F', 'B'), ('R', 'L')), 'directions': ('', "'", '2')},
3: {... | python |
from setuptools import setup
setup(
name="scripture-burrito",
version="0.0.2",
description="Python library for the Scripture Burrito data interchange format",
url="http://github.com/bible-technology/scripture-burrito-python",
author="BT Tech Consortium",
author_email="jtauber@jtauber.com",
... | python |
import pytest
import numpy as np
import pennylane as qml
from pennylane_qiskit import AerDevice, BasicAerDevice
from conftest import U, U2, A
np.random.seed(42)
THETA = np.linspace(0.11, 1, 3)
PHI = np.linspace(0.32, 1, 3)
VARPHI = np.linspace(0.02, 1, 3)
@pytest.mark.parametrize("theta, phi", list(zip(THETA, P... | python |
import argparse
import logging
import os
import sys
sys.path.insert(0, os.path.join(sys.path[0], ".."))
import development.configuration # pylint: disable = wrong-import-position
import development.environment # pylint: disable = wrong-import-position
logger = logging.getLogger("Main")
def main():
current_direct... | python |
import sys
import os
import json
import hashlib
import EVMfunction as EVMf
import EVMcompiler as EVMc
import EVMparse as EVMp
print('Kam1n0 script for EVM is now running...')
print('start persisting...')
args = sys.argv
sol_file_name = args[1].split('\\')[-1]
abs_file_name = os.path.abspath(args[1])
j... | python |
#!/usr/bin/env python3
"""Bank account without synchronization cause race condition """
class UnsyncedBankAccount:
"""Bank account without synchronization"""
balance: float
def __init__(self, balance: float = 0):
self.balance: float = balance
def deposit(self, amount: float) -> None:
... | python |
# import setuptools
# with open("README.md", "r") as fh:
# long_description = fh.read()
# setuptools.setup(
# #Here is the module name.
# name="TOPSIS-Shivansh-101803103",
# #version of the module
# version="0.0.1",
# #Name of Author
# author="Shivansh Kumar",
# #your Email add... | python |
from collections import defaultdict
from contextlib import contextmanager
from enum import Enum
import redis_lock
from passari_workflow.redis.connection import get_redis_connection
from rq import Queue
from rq.exceptions import NoSuchJobError
from rq.job import Job
from rq.registry import FailedJobRegistry, StartedJob... | python |
#!/usr/bin/env python
# coding: utf-8
# # 2. Τιμές, τύποι και μεταβλητές. Συμβολοσειρές
# ## Σταθερές (Constants)
#
# H Python δεν διαθέτει προκαθορισμένες *σταθερές* όπως άλλες γλώσσες προγραμματισμού.
# Όμως κατά σύμβαση και όχι κατά κανόνα έχει συμφωνηθεί οι *σταθερές* να ονοματίζονται με κεφαλαίους χαρακτήρες.
... | python |
import os,sys
import numpy as np
import torch
import torch.nn.functional as F
import h5py, time, itertools, datetime
from scipy.ndimage import label
from scipy.ndimage.morphology import binary_erosion
from torch_connectomics.utils.net import *
from torch_connectomics.utils.vis import visualize_aff
def test(args, test... | python |
import ML
import function.saveNewsList
import hook.hooks
import job
import json
from nose.tools import with_setup
from ML import Server
def setup_func():
ML.init(
"57f9edc887d4a7e337b8c231",
master_key="elhmazJfd29ZTFBhR0M3SmJ0R2N6UQ",
)
@with_setup(setup_func)
def test_saveNewsDetail():
... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-11 15:42
from django.db import migrations
import utilities.fields
class Migration(migrations.Migration):
dependencies = [
('dcim', '0017_rack_add_role'),
]
operations = [
migrations.AddField(
model_name='device',
... | python |
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
import datetime
from dateutil.relativedelta import relativedelta
from datetime import datetime
from sqlalchemy import desc... | python |
#!/usr/bin/env python
import networkx as nx
import sys
with open('soc-sign-bitcoinotc.csv', 'r') as fin:
with open('bitcoinotc.in', 'a') as fout:
G = nx.DiGraph()
fout.write("Relation Edges" + '\n')
fout.write("From To" + '\n')
for line in fin:
n1, n2, rating, time = line.split(',')
fout.write(str(n1) ... | python |
from __future__ import division
import copy
from Game.deck import *
from Game.column import *
from Game.heap import *
NB_CARDS_SUBDECK = 24
NB_HEAPS = 4
NB_COLUMNS = 7
IN_HEAP = 'heap'
IN_DECK = 'deck'
IN_COL = 'col'
UNDRAWN = 'undraw'
ACTIONS = ['draw', 'deck-heap', 'deck-col', 'col-heap', 'heap-col', 'col-col']
c... | python |
from .transformer_factory import function_transformer # noqa
| python |
import sys
import requests
import mysql.connector
import datetime
from mysql.connector import errorcode
from bs4 import BeautifulSoup
def get_link(argv):
hari = str(datetime.datetime.now().day)
bulan = str(datetime.datetime.now().month)
tahun = str(datetime.datetime.now().year)
url = "http://www.viva.... | python |
from ..registry_tools import iso_register
from .core import UnitedStates
@iso_register('US-NY')
class NewYork(UnitedStates):
"""New York"""
include_lincoln_birthday = True
include_election_day_every_year = True
| python |
"""jc - JSON CLI output utility `sfdisk` command output parser
Supports the following `sfdisk` options:
- `-l`
- `-F`
- `-d` (deprecated - only for older versions of util-linux)
- `-uM` (deprecated - only for older versions of util-linux)
- `-uC` (deprecated - only for older versions of util-linux)
- `-uS` (depre... | python |
from __future__ import print_function
# vim: set fileencoding= UTF-8
#!usr/bin/python
"""Word Spot
ENG: Enter string. Output. All world in order they came in, if any word have appired more then once, print index in (paranthesise)
input: qwe sdf tyu qwe sdf try sdf qwe sdf rty sdf wer sdf wer
output:qwe(7) sdf(12) ... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from typing import Dict, Tuple, Any, Set
from tabun_stat import utils
from tabun_stat.processors.base import BaseProcessor
class BirthdaysProcessor(BaseProcessor):
def __init__(self) -> None:
super().__init__()
# {(день, месяц): айдишники... | python |
#!/usr/bin/python
"""
This script provides a set of tools to parse the vector and scalar files dumped
out of omnet simulation and indexed data and stats for use of other modules.
"""
from numpy import *
from glob import glob
from optparse import OptionParser
from pprint import pprint
from functools import partial
fro... | python |
from Proxy import ProxyFactory, Proxy
from LRUCache import LRUCache
from utils import distance, stress, MAX_DISTANCE, LOWEST_STRESS
from typing import Hashable, List, Tuple, Dict, Any
class Origin:
def __init__(self, database, max_size_of_LRUCache : int, max_age_of_LRUCache: int, load_balancing_interval : int):
... | python |
from __future__ import print_function
from .client import Client
__title__ = 'Steamfront'
__author__ = 'Callum Bartlett'
__license__ = 'MIT'
__copyright__ = 'Copyright 2017 Callum Bartlett'
__version__ = '0.1.0'
if __name__ == '__main__':
from sys import argv
if len(argv) < 2:
print('Please give the name of a ga... | python |
import sys
from ctypes import *
sys.path.append('../')
#import vscp.udp as udp
#from vscp.vscp_class import *
#from vscp.vscp_type import *
from vscp import *
def makeClass2StrMeasurement( vscpclass, vscptype, strval ):
ex = vscp.vscpEventEx()
return ex
e = vscp.vscpEvent()
ex = vscp.vscpEventEx()
print(ty... | python |
"""
Test cases for linear programming based on CVXOPT
This case is an economic dispatch code
"""
from cvxopt import matrix
from cvxopt import solvers
class LinearProgramming():
def run(self, PG_MAX, PG_MIN, CG, PD):
"""
:param PG_MAX: maximal generator output
:param PG_MIN: minimal gene... | python |
import secrets
import redis
from app.core.config import settings
ok_status = {'detail': 'Ok'}
def generate_id():
return secrets.token_urlsafe(8)
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
instance = super().__call_... | python |
import json
import logging
import os
import pytest
from fhir2dataset.query import Query
from tests.tools import create_resource_test
log_format = "[%(asctime)s] [%(levelname)s] - %(message)s"
logging.basicConfig(level=logging.INFO, format=log_format)
@pytest.mark.parametrize(
"dirname, fhir_api_url",
[
... | python |
''' Tst cases fro get_names method '''
import unittest
from spydrnet import ir
from spydrnet_physical.util import get_names
from spydrnet_physical.util import get_attr
class TestGetNames(unittest.TestCase):
''' Test case class '''
def setUp(self):
''' Basic element setup '''
self.definitio... | python |
import random
from hashlib import sha256
def gen_password(user_password):
'''产生一个安全的密码'''
bin_password = user_password.encode('utf8') # 将密码转成 bytes 类型
hash_value = sha256(bin_password).hexdigest() # 计算用户密码的哈希值
salt = '%x' % random.randint(0x10000000, 0xffffffff) # 产生随机盐
safe_password = salt + h... | python |
__author__ = 'Eric Weast'
__copyright__ = "Copyright 2014, Eric Weast"
__license__ = "GPL v2"
from .exceptions import EncodingError
from .exceptions import DecodingError
from .decoder import decode
from .decoder import decode_from_file
from .encode import encode | python |
from copy import copy
from meerk40t.core.cutcode import RasterCut
from meerk40t.core.element_types import *
from meerk40t.core.node.node import Node
from meerk40t.core.parameters import Parameters
from meerk40t.core.units import Length
from meerk40t.image.actualize import actualize
from meerk40t.svgelements import Col... | python |
"""
training script
date: 10/4
author: arabian9ts
"""
# escape matplotlib error
import matplotlib
matplotlib.use('Agg')
# escape tensorflow warning
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import datetime
import tensorflow as tf
import numpy as np
import pickle
import threading
import matplotlib.pyplot as p... | python |
import unittest
from contiguous.structures import DataSection, Group
from contiguous.types import String
class TestContiguous(unittest.TestCase):
""" Test basic functionality with native Python types in schemas."""
def test_lengths(self):
data = DataSection(
String("name", 25),
... | python |
from typing import List
class ListNode:
def __init__(self, val=0):
self.val = val
self.next = None
def insert_at_tail(nodes: List[int]) -> ListNode:
head = ListNode(nodes[0])
for node in nodes[1:]:
insert_helper(head, node)
return head
def insert_helper(head: ListNode, node... | python |
import ast
import rest_framework.serializers as module_to_patch
from drf_jsonpatch.patcher import Patcher
from drf_jsonpatch.nodes.serialiazers import (
import_jsonpatch,
import_apply_json_patch,
if_apply_jsonpatch,
)
patch = Patcher(module_to_patch)
# ---- import jsonpatch ----
# added between django... | python |
begin_unit
comment|'# Copyright 2012 Red Hat, Inc.'
nl|'\n'
comment|'# All Rights Reserved.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'... | python |
#!/usr/bin/env python
import argparse
import os
import sys
from lib.config import enable_verbose_mode, get_target_arch
from lib.util import execute_stdout
SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
def main():
os.chdir(SOURCE_ROOT)
args = parse_args()
if args.verbose:
ena... | python |
from .pipenv_setup_comp import compare_deps
from ._version import (__title__, __description__, __url__, __version__,
__author__, __author_email__, __license__)
__all__ = ["compare_deps", "__title__", "__description__", "__url__",
"__version__", "__author__", "__author_email__", "__lic... | python |
"""
@file: This file contains the database helper class that manages both 'users' and 'contacts' collections
@Note: Calling this with python will do nothing
"""
#------------------------------STANDARD DEPENDENCIES-----------------------------#
import json
import pickle, copyreg, ssl # for serializing User obje... | python |
# https://leetcode.com/problems/keyboard-row
import re
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
match_r1 = lambda w: bool(re.match("^[qwertyuiop]*$", w.lower()))
match_r2 = lambda w: bool(re.match("^[asdf... | python |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config.from_object("app.config.Config")
db = SQLAlchemy(app) #database object
migrate = Migrate(app,db) #object responsible for tracking changes in DB
from app import routes, models | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2014 Junko Tsuji
# This script generates bed files as final outputs of
# DNA methylation pipeline by taking a CX_report file
# generated from bismark_methylation_extractor.
from optparse import OptionParser
import sys, os.path, string
# RGB strings and inte... | python |
# -*- coding: utf-8 -*-
import random
from source.tree.heap import MinHeap, MaxHeap
# region INSERTION SORT
# 直接插入排序
def straight_insertion_sort(a, reverse=False):
"""
直接插入排序
基本操作:将一个记录插入到已排好序的有序表中,从而得到一个新的,记录数增加1的有序表。
:param a:
:param reverse:
:return:
"""
# 从无序表的第二条记录开始
for i i... | python |
# Generated by Django 2.2.13 on 2021-02-25 16:22
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("data_refinery_common", "0063_auto_20210212_1855"),
]
operations = [
migrations.AlterModelOptions(name="dataset", options={"base_manager_name": "obj... | python |
from django.conf.urls import url
from views import FakeImageView
from . import views
urlpatterns = [
url(r'^', FakeImageView.as_view(),name='index.html'),
#url(r'^tweet_json/', FakeJSONView.as_view(),name='tweet_json.html')
] | python |
#!/usr/bin/env python
import logging
import unittest
from decimal import Decimal
import pandas as pd
from hummingbot.connector.exchange.paper_trade.paper_trade_exchange import QuantizationParams
from hummingbot.core.clock import (
Clock,
ClockMode
)
from hummingbot.core.data_type.common import TradeType
from ... | python |
class ClonedRepoExistedError(Exception):
"""Base class for other exceptions"""
pass
class BranchUpToDateException(Exception):
pass
class DefaultCommitToolException(Exception):
pass
class PotentialInfiniteLoopException(Exception):
pass | python |
import os
from pathlib import Path
output = Path(os.path.abspath(__file__)).parent.parent / "output"
| python |
# Copyright 2017 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... | python |
### list all installed fonts plus it's variations
for fontName in installedFonts():
variations = listFontVariations(fontName)
if variations:
print(fontName)
for axis_name, dimensions in variations.items():
print (axis_name, dimensions)
print ()
| python |
"""
Module for abstract serializer/unserializer base classes.
"""
from StringIO import StringIO
from django.core.serializers.base import SerializationError, DeserializationError
from django.core.exceptions import ObjectDoesNotExist
class Serializer(object):
"""
Abstract serializer base class.
"""
# ... | python |
import unittest
from validator import format
class TestFormat(unittest.TestCase):
def test_invalid_yaml(self):
invalid_yaml = """
key: value
- item#1
- item#2
"""
(parsed, err) = format.validate(invalid_yaml)
self.assertIsNone(parsed)
self.assertEq... | python |
# coding: utf-8
# # For Loops (2) - Looping through the items in a sequence
# In the last lesson we introduced the concept of a For loop and learnt how we can use them to repeat a section of code. We learnt how to write a For loop that repeats a piece of code a specific number of times using the <code>range()</code... | python |
from django.test import TestCase
from django.utils import timezone
from datetime import timedelta
from decimal import Decimal
from blackbook.models import Currency, CurrencyConversion
class CurrencyTest(TestCase):
def testString(self):
currency = Currency.objects.create(name="Test Currency", code="TEST"... | python |
import sys, string
import re
from ucscGb.gbData.ordereddict import OrderedDict
import collections
class RaStanza(OrderedDict):
'''
Holds an individual entry in the RaFile.
'''
@property
def name(self):
return self._name
def __init__(self, key=None, value=None):
OrderedDict.__i... | python |
import json
from parserutils.strings import camel_to_snake
from ..query.fields import RENDERER_ALIASES
from ..query.fields import DictField, ObjectField
from .geometry import Extent
def to_words(cls_instance_or_name, as_string=True):
if isinstance(cls_instance_or_name, type):
class_name = cls_instance... | python |
import sys
from typing import Optional, TextIO
from antlr4 import InputStream
from src.messages.message_lexer import message_lexer
class Lexer(message_lexer):
def __init__(self, key: str, inp: InputStream, output: TextIO = sys.stdout):
super().__init__(inp, output)
self._recent = None
self.... | python |
start_node = '0'
end_node = '8'
def a_star(start_node, end_node):
open_set = set(start_node)
closed_set = set()
g = {} # Store distance from start node.
parents = {} # Parents contain an adjacent map of all nodes.
# Distance of start node from itself is zero
g[start_node] = 0
parents[start_node] = start... | python |
import functools
import numpy as np
import jax
import jax.numpy as jnp
from jax import jit, vmap
from jax.ops import index, index_update
def get_ray_bundle(height, width, focal_length, tfrom_cam2world):
ii, jj = jnp.meshgrid(
jnp.arange(width, dtype=jnp.float32,),
jnp.arange(height, dtype=jnp.floa... | python |
# coding: utf-8
"""
Author:
Weichen Shen,wcshen1994@163.com
Reference:
[1] Feng Y, Lv F, Shen W, et al. Deep Session Interest Network for Click-Through Rate Prediction[J]. arXiv preprint arXiv:1905.06482, 2019.(https://arxiv.org/abs/1905.06482)
"""
from collections import OrderedDict
from tensorflow.python.... | python |
import pandas as pd
from ....Trade.Strategy.Cta.DyST_TraceFocus import *
from ....Trade.Strategy.DyStockCtaBase import *
from ....Trade.DyStockStrategyBase import *
class DyStockDataFocusAnalysisUtility(object):
"""
热点分析工具类
这个类有点特别,会借助DyST_FocusTrace类
"""
class DummyCtaEngine:
def... | python |
from pathlib import Path
from six.moves.urllib.parse import urlunparse
from six.moves.urllib.error import HTTPError
from six.moves.urllib.request import urlretrieve
import logging
logger = logging.getLogger(__name__)
class HiRISE_URL(object):
"""Manage HiRISE URLs.
Provide a storage path as calculated from... | python |
#!/usr/bin/env python
class Cart:
def __init__(self):
self.id = None
self.capacity = None
self.payload = None
self.last_known_location = None
| python |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Chrome()
browser.get('https://www.dan.me.uk/bgplookup')
count=6535#接着上一次继续跑的初值
while count<=64511:
browser.find_element_by_name('asn').clear()
browser.find_element_by_name('asn').send_keys(count)
... | python |
# hw06_03
import random
def makesentence():
subjects = ['Dog', 'Cat', 'Monkey', 'Pig', 'Fox']
verbs = ['walks', 'runs', 'jumps']
advs = ['slowly', 'quickly']
print('%s %s %s.' % (random.choice(subjects), random.choice(verbs), random.choice(advs)))
for i in range(5):
makesentence()
'''
Cat walk... | python |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from PyQt5.QtCore import QThread, pyqtSignal
from handlers import APIHandler, LoadMusicHandler
from config import config
from vkapi import VKLightError
from utils import save_json, stat
class LoadMusic(QThread):
music = pyqtSignal(list)
error = pyqtSignal(str)
... | python |
# Programa onde 4 jogadores jogam um dado e tem resultados aleatórios.
# Guarda esses resultados em um dicionário em Python. No final, coloca esse dicionário em ordem, sabendo que o
# vencedor tirou o maior número no dado.
from random import randint
from time import sleep
from operator import itemgetter
jogo = {'joga... | python |
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from .__about__ import __version__
from .kafka_consumer import KafkaCheck
__all__ = ['__version__', 'KafkaCheck']
| python |
import os
from multiprocessing.managers import BaseManager, BaseProxy
import numpy as np
import tensorflow as tf
from tensorflow.python.training import session_run_hook
from tensorflow.python.training.basic_session_run_hooks import SessionRunArgs
from rank_based import Experience
class sync_expericence(Experience):... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-03-21 08:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wildlifecompliance', '0147_merge_20190314_1451'),
]
operations = [
migratio... | python |
""" A module for getting the class names for a dataset, in a single canonical order.
"""
import json
from folder import datasets_path
def get_class_data(dataset):
path = datasets_path / dataset / 'classes.json'
with path.open('r') as f:
class_data = json.load(f)
class_data.sort(key=lambda d:... | python |
from .tell_os import is_linux
if is_linux():
import Xlib
import Xlib.display
from contextlib import contextmanager
from typing import Optional
from .abstract_desktop_monitor import AbstractDesktopMonitor
@contextmanager
def window_obj(display, win_id):
"""Simplify dealing with BadW... | python |
from io import open
import requests
def test_scene():
image_data = open("scene.jpg", "rb").read()
response = requests.post(
"http://localhost:80/v1/vision/scene",
files={"image": image_data},
data={"api_key": "Mojohn1"},
).json()
assert response["success"] ==... | python |
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def Hist(dataset, xlabel, filename): #Log Trip Duration His
sns.set_style("darkgrid")
sns.distplot(dataset, kde=True, rug=False)
plt.legend()
plt.xlabel(xlabel)
plt.ylabel('Frequency')
plt.tight_layo... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/1/30 下午12:10
# @Author : wook
# @File : db.py
import pymysql
db = pymysql.connect(host="localhost", user="root", passwd="123123", db="mysql", port=3306, charset="utf8") # 连接对象
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() ... | python |
import os
from flask import Flask
from flask_cors import CORS
from .extensions import db, bcrypt
from flask_socketio import SocketIO
from .models import users, messages
from .config import DevConfig, ProdConfig
socketio = SocketIO(cors_allowed_origins="*")
def create_app():
app = Flask(__name__)
app.config['... | python |
"""
Copyright 2020 The OneFlow 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 applicable law or agr... | python |
#!/usr/bin/env python3
import os
import random
import sys
import string
import random
if len(sys.argv) < 2:
print(f'Usage: {sys.argv[0]} <target>')
sys.exit(1)
ip = sys.argv[1]
print("Hello! I am a little sploit. I could be written on any language, but "
"my author loves Python. Look at my source - it... | python |
"""
IMPORT STEP
"""
import re
import datetime
import time
import traceback
import sys
import json
from math import ceil
from pyspark import SparkConf, SparkContext
from pyspark.sql import SQLContext, Row
from pyspark.sql.types import *
from pyspark.sql.functions import lit, col, udf
def save_txt(document, path):
... | python |
"""Tests for calculator.py."""
__author__ = 'Boris Polyanskiy'
import unittest
from party_calc.calculator import Person, PartyCalculator
class TestPerson(unittest.TestCase):
def test_init(self) -> None:
person = Person('mr.White')
self.assertEqual(person.name, 'mr.White')
self.assertEqu... | python |
from django.db import models
# Create your models here.
class Permission(models.Model):
"""
权限表
"""
hide_type_choices = (
(1, 'FALSE'),
(2, 'TRUE'),
)
route_url = models.CharField(max_length=64, verbose_name="路由路径", unique=True)
route_name = models.CharField(max_length=32,... | python |
from flask import Flask
from config import app_config
from app.database import create_tables
from app.api.views.user_endpoints import user
from app.api.views.meetup_endpoints import meetup
from app.api.utils.errors import err, bad_request, internal_server_error, not_found, method_not_allowed
def create_app(config_name... | python |
import unittest
from camera_trap_classifier.data.importer import DatasetImporter
class ImportFromCSVSingleImageTester(unittest.TestCase):
""" Test Import from CSV """
def setUp(self):
path = './test/test_files/dataset_single_image_multi_species.csv'
source_type = 'csv'
params = {'path... | python |
#! /usr/bin/env python
#
# Licensed to Elasticsearch under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
... | python |
import os
import pdb
from django import forms
from django.conf import settings
from django.contrib.auth import forms as auth_forms
from django.contrib.auth import password_validation
from django.core.files.uploadedfile import UploadedFile
from django.forms.widgets import FileInput
from django.utils import timezone
fro... | python |
'''
作者:邱少一
功能:
1.0功能:模拟投掷一个骰子
2.0新增功能:模拟投掷两个骰子
3.0新增功能:可视化投掷两个骰子的结果
4.0新增功能:=======直方图可视化作图和统计工具:matplotlib
5.0新增功能:=======科学计算工具:numpy
版本:1.0
日期:2017/12/1
学习:1、随机数:random():0到1的数;uniform(a,b):a到b的随机浮点数;randint(a,b):a到b的随机数
choice(<list>):随机从list中取一个元素 ;shuffle(<list>):将列表中元素打乱,sample(<list>,k):从列表... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.