text
string
size
int64
token_count
int64
from ..core import test
23
6
from my_app import app app.run(debug=True)
43
17
''' calculate the hamming or the bit diff useful in deciding the key length for repeating XOR ''' def str_to_bytes(str,base): byte_array = bytearray() byte_array.extend([ord(ch) for ch in str]) return byte_array def calc_hamming(str1,str2): bits1 = str_to_bytes(str1,1) bits2 = str_to_bytes(str2,1)...
722
278
#!/usr/bin/env python import sys import os import ast import json import math from collections import OrderedDict from .configuration import VMOverlayCreationMode from operator import itemgetter import logging LOG = logging.getLogger(__name__) _process_controller = None stage_names = ["CreateMemoryDeltalist", ...
23,486
7,962
from gnomic.types import Feature as F, Fusion def test_fusion_contains(): assert Fusion(F('a'), F('b'), F('c'), F('d')).contains(Fusion(F('b'), F('c'))) is True assert Fusion(F('a'), F('b'), F('c'), F('d')).contains(Fusion(F('a'), F('c'))) is False assert Fusion(F('a'), F('b'), F('c'), F('d')).contains(F(...
410
167
from twisted.internet import protocol from twisted.python import log from twisted.words.protocols import irc class TalkBackBot(irc.IRCClient): def connectionMade(self): """ called when a connection is made to a channel """ self.nickname = self.factory.nickname self.realname = self.factory....
2,540
698
""" Run like: python -m bluesky_widgets.examples.headless_figures and it will print to stdout the names of the figures that it creates, one per line """ import tempfile from bluesky import RunEngine from bluesky.plans import scan from ophyd.sim import motor, det from bluesky_widgets.utils.streaming import stream_do...
1,034
361
######## # Copyright (c) 2016 GigaSpaces Technologies Ltd. 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...
3,273
1,040
from dagster.core.test_utils import instance_for_test from docs_snippets.deploying.dask_hello_world import ( # pylint: disable=import-error local_dask_job, ) def test_local_dask_pipeline(): with instance_for_test() as instance: result = local_dask_job.execute_in_process( instance=instanc...
435
138
from numpy import * def debugInitializeWeights(fan_out, fan_in): W = zeros((fan_out, 1 + fan_in)) W = reshape(sin(arange(size(W))+1.0), W.shape ) / 10. return W
176
76
from math import inf # Range is a pair, inclusive, min to max def rangeIntersects(a, b): return a[0] <= b[1] and b[0] <= a[1] assert(rangeIntersects((1,2), (3, 4)) == False) assert(rangeIntersects((0,10), (2, 8)) == True) assert(rangeIntersects((2, 8), (0,10)) == True) assert(rangeIntersects((0,10), (5, ...
3,138
1,241
# Dicitionary: dic = { "one": 1, "two": 2, "three": 3, } print(dic["one"]) dic["four"] = 4 dic[5] = 6 print(dic) print(6 in dic) print(5 in dic) print(dic.get("one")) print(dic.get(7, "do not exists")) print(8*"-") # Tubles: tup = (1, 2, 3, 4) print(tup[1]) tup = 1, 2, 3, 4, 4 print(tup) tup = (1,) pri...
1,496
779
from datetime import datetime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import Column, Integer, String, Boolean, ForeignKey, Enum, DateTime from sqlalchemy import Table from sqlalchemy.dialects.postgresql import UUID Base = declarative_base() ...
8,568
2,850
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2018, Doron Chosnek # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 's...
13,699
3,939
# Author : Relarizky # Github : https://github.com/relarizky # File Name : controller/auth/admin.py # Last Modified : 01/30/21, 14:00 PM # Copyright © Relarizky 2021 from app.model import Admin from flask import render_template, request, url_for, redirect, session, flash from flask_login import login_user, log...
1,699
555
def load_ground_truth(gt_file: str): ground_truth = [] with open(gt_file, 'r') as f: for idx, line in enumerate(f): ground_truth.append(int(line)) return ground_truth def load_imagenet_meta(meta_file: str): import scipy.io mat = scipy.io.loadmat(meta_file) return mat['...
2,034
755
import argparse import csv, os, time import MySQLdb # http://sourceforge.net/projects/mysql-python/ import result from result import Result import gspread, getpass # https://pypi.python.org/pypi/gspread/ (v0.1.0) # Get command line arguments parser = argparse.ArgumentParser(description='Load SNP and locus data') pars...
12,117
4,009
#!/usr/bin/env python3 import sys import os import random import string from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('srv_file') parser.add_argument('client_file') parser.add_argument('value_size', type=int) parser.add_argument('n_keys', type=int) parser.add_argument('n_reqs', type...
1,108
405
# (Name, Drunkfactor, Subs=[]) from typing import Dict, List, Optional class Person: def __init__(self, name: str, drunk_factor: int, leader_name: Optional[str]): self.name = name self.drunk_factor = drunk_factor self.leader_name = leader_name self.subs: List["Person"] = [] ...
3,638
1,157
from ts_charting import *
26
9
#!/usr/bin/env python3 scores = { "John": 75, "Ronald": 99, "Clarck": 78, "Mark": 69, "Newton": 82, } grades = {} for name in scores: score = scores[name] if score > 90: grades[name] = "Outstanding" elif score > 80: grades[name] = "Exceeds Expectations" elif score ...
471
199
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads_v4/proto/resources/product_bidding_category_constant.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 g...
12,031
4,517
from ray.ml.preprocessors.batch_mapper import BatchMapper from ray.ml.preprocessors.chain import Chain from ray.ml.preprocessors.encoder import OrdinalEncoder, OneHotEncoder, LabelEncoder from ray.ml.preprocessors.imputer import SimpleImputer from ray.ml.preprocessors.scaler import StandardScaler, MinMaxScaler __all__...
485
164
from django.urls import path from . import views urlpatterns = [ path('', views.WebHookViewSet.as_view({'post': 'receiveHook'}), name='receiveHook'), ]
157
56
import sys import six from .base import Broker from ..job import JobResult class Eager(Broker): """ Broker to execute jobs in a synchronous way """ def __repr__(self): return 'Broker(Eager)' def add_job(self, job_class, *args, **kwargs): job_id = self.gen_job_id() eager...
712
227
import datetime import peewee db = peewee.SqliteDatabase("db.db") class Match(peewee.Model): id = peewee.PrimaryKeyField() match_id = peewee.IntegerField(unique=True) comp = peewee.CharField() matchday = peewee.IntegerField() date_utc = peewee.CharField() status = peewee.CharField() stag...
2,947
1,071
import sys import psutil from global_modules import logs if sys.platform == "win32": import ctypes from ctypes import wintypes elif sys.platform == "linux" or sys.platform == "linux2": import subprocess proc = subprocess.Popen(["/bin/bash", "-c", "which xdotool"], stdout=subprocess.PIPE, stderr=sub...
1,589
495
import json import requests from zhixuewang.exceptions import LoginError, UserNotFoundError, UserOrPassError from zhixuewang.tools.password_helper import base64_encode, encode_password from zhixuewang.urls import Url def get_basic_session() -> requests.Session: session = requests.Session() session.headers[ ...
3,987
1,462
resp = str(input('Informe seu sexo [M/F]: ')).strip().upper()[0] while resp not in 'MmFf': resp = str(input('Dados inválidos! Informe seu sexo: ')).strip().upper()[0] print('Sexo {} registrado com sucesso'.format(resp))
228
90
import time import requests import re import pymysql import urllib3 from lxml import etree from fake_useragent import UserAgent # from scrapy import Selector from requests.adapters import HTTPAdapter urllib3.disable_warnings() db = pymysql.connect("localhost", "root", "", "miraihyoka") cursor = db.cursor() def sp...
6,031
2,019
import lib.tf_silent import numpy as np import matplotlib.pyplot as plt from lib.pinn import PINN from lib.network import Network from lib.optimizer import L_BFGS_B def theoretical_motion(input, g): """ Compute the theoretical projectile motion. Args: input: ndarray with shape (num_samples, 3) for...
1,637
606
import cv2 import numpy as np import math def transform(frame): #frame = resize(frame) try: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) except: pass frame = threshold(frame) frame = get_contours(frame) frame = resize(frame,100) return frame def resize(frame,size): return cv2.resize(frame,(size,size)) ...
1,889
858
import cv2 import numpy as np def dog(img,size=(0,0),k=1.6,sigma=0.5,gamma=1): img1 = cv2.GaussianBlur(img,size,sigma) print("img:") print(np.max(img1)) img2 = cv2.GaussianBlur(img,size,sigma*k) return (img1-gamma*img2) def xdog(img,sigma=0.5,k=1.6, gamma=1,epsilon=1,phi=1): img = dog(img,sigm...
2,357
1,111
def main(): N, Q = map(int, input().split()) import collections tree = collections.defaultdict(list) for _ in range(N - 1): a, b = map(int, input().split()) a -= 1 b -= 1 tree[a].append(b) tree[b].append(a) RED = 1 BLACK = 2 colors = [None] * N ...
803
288
"""Define a SimpliSafe lock.""" from __future__ import annotations from enum import Enum from typing import TYPE_CHECKING, Any, Awaitable, Callable, cast from simplipy.const import LOGGER from simplipy.device import DeviceTypes, DeviceV3 if TYPE_CHECKING: from simplipy.system import System class LockStates(Enu...
4,483
1,383
import requests class ListProvidersC: def list_all(self, args, daemon): r = requests.get(daemon+"/providers/list") return r.text
150
49
# In[1]: import mxnet as mx import numpy as np import time # In[2]: # Basic Info dev = mx.gpu() batch_size = 128 dshape = (batch_size, 3, 224, 224) lshape = (batch_size) num_epoch = 100 # Mock data iterator tmp_data = np.random.uniform(-1, 1, dshape).astype("float32") train_iter = mx.io.NDArrayIter(data=tmp_data,...
4,291
1,786
# Copyright (c) 2015-2016 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import json import pecan import six from six.moves import http_client as httplib from wsme import types as wsme_types import wsmeext.pecan as wsme_pecan from nfv_common import debug from nfv_common import validate from nfv_vim...
23,213
6,896
def taxonomy_term_facet(field, order='desc', size=100): return { "nested": { "path": field }, "aggs": { "links": { "terms": { "field": f"{field}.links.self", 'size': size, ...
426
110
# -*- coding: utf-8 -*- import sys if __name__ == '__main__': sys.path.append('./pythonx') def wrap(): from ncm2_core import ncm2_core from ncm2 import getLogger import vim import ncm2_lsp_snippet.utils as lsp_utils from ncm2_lsp_snippet.parser import Parser import re import json ...
5,219
1,777
from .Candle import Candle from .Ticker import Ticker from .Exchange import Exchange from .Order import Order from .Position import Position from .Route import Route from .CompletedTrade import CompletedTrade from .utils import store_candle_into_db, store_ticker_into_db, store_trade_into_db, store_orderbook_into_db
317
95
from canvasapi import Canvas import json import os # Do `pip install canvasapi` first before running this script! DEFAULT_CANVAS_URL = 'https://eur.instructure.com' DEFAULT_REMOVE_PATTERN = 'groep' DEFAULT_ADD_PREFIX = 'Tutorial ' DEFAULT_IGNORE = 'Default section' print('Please enter the Canvas base URL you want to...
4,385
1,441
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import torch from transformers import AutoModel, AutoTokenizer, BertTokenizer, BertForSequenceClassification from torch.utils.data import TensorDataset import transformers from tqdm.notebook import tqdm census10 = pd.read_csv(...
7,219
2,443
#----------------------------------------------------- # Mimas: conference submission and review system # (c) Allan Kelly 2016-2020 http://www.allankelly.net # Licensed under MIT License, see LICENSE file # ----------------------------------------------------- # schedule_lib/schedexport.py # # system imports import da...
2,771
905
import pytest import peewee async def test_select(TestModel, schema): await TestModel.delete() inst = await TestModel.create(data='data') assert [inst] == await TestModel.select().where(TestModel.id == inst.id) async for data in TestModel.select(): assert data == inst assert await TestM...
2,748
894
"""Functions to query ESI with simple caching.""" import logging import json from typing import Dict, Any from async_lru import alru_cache from unchaind.http import HTTPSession log = logging.getLogger(__name__) _ESI = "https://esi.evetech.net/latest/" @alru_cache(maxsize=8192) async def character_details(characte...
1,102
419
from unittest import TestCase from functools import reduce from operator import mul from ..get_kth_combination import get_kth_combination class GetKthCombinationTestCase(TestCase): def test_get_kth_combination(self): iterables = [[1, 2, 3], ['A', 'B', 'C'], ['I', 'II']] expected_outputs = [ ...
1,460
485
"""Admin backend for editing some admin details.""" from django.contrib import admin from .models import (RegPerson, RegOrgUnit, RegOrgUnitsAuditTrail, RegPersonsAuditTrail, RegPersonsTypes, RegPersonsGeo, RegPersonsOrgUnits) from cpovc_auth.models import AppUser class Per...
3,191
1,053
# # Copyright 2019-2020 Lukas Schmelzeisen # # 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 t...
15,605
4,341
# Copyright (c) 2012 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. { 'variables': { 'chromium_code': 1, }, 'targets': [ { 'target_name': 'googleurl', 'type': 'none', 'dependencies': [ ...
459
167
# -*- coding: utf-8 -*- # @Time : 2021/5/13 22:53 # @Author : 咸鱼型233 # @File : __init__.py.py # @Software: PyCharm # @Function: # @ChangeLog
149
85
# Generated by Django 3.2.6 on 2021-08-25 10:29 from django.db import migrations from django.db.models.signals import post_migrate def assing_permissions(apps, schema_editor): def on_migrations_complete(sender=None, **kwargs): Group = apps.get_model("auth", "Group") Permission = apps.get_model("au...
1,411
419
from __future__ import print_function import idaapi def PLUGIN_ENTRY(): from Payload2Std.plugin import Payload2StdPlugin return Payload2StdPlugin()
165
61
# This imports the CMMC pdf as distributed by OUSD(A&S). from django.core.management.base import BaseCommand, CommandError from django.db.models import IntegerField, Case, Sum, Value, When from cmmcdb.models import * import argparse import camelot import re import pprint def remove_prefix(text, prefix): if tex...
7,242
2,117
# ============================================================ # Title: Keep Talking and Nobody Explodes Solver: Keypad # Author: Ryan J. Slater # Date: 4/3/2019 # ============================================================ def solveKeypad(keypadSymbols): # Symbols on the player's keypad # List of the 6 columns...
1,834
526
#!<<PYTHON>> import time counter = 0 while 1: time.sleep(0.01) print(("more spewage %s" % counter)) counter += 1
138
67
import json from . import env, packer_dir, packer_templates, workspace from ...commands.types.target import Target from ..terraform.driver import TerraformDriver from ..terraform.routing import routing_targets # Supported packer sub-commands packer_commands = [ 'validate', 'build', 'console', ] class ...
2,385
746
import ast import argparse import inspect from collections import OrderedDict from functools import partial from tfi.base import _GetAttrAccumulator as _GetAttrAccumulator from tfi.data import file as _tfi_data_file from tfi.resolve.model import resolve_auto as _resolve_auto def _split_list(l, delim): for ix in ...
3,776
1,176
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class Task(db.Model): id = db.Column(db.Integer, primary_key=True) description = db.Column(db.Text, nullable=False) solutions = db.relationship('Solution', backref='task', lazy=True) def __repr__(self): return 'Task({},"{}...")'.forma...
691
241
# DO NOT EDIT THIS FILE! # # This code is generated off of PyCDP modules. If you need to make # changes, edit the generator and regenerate all of the modules. from __future__ import annotations import typing from ..context import get_connection_context, get_session_context import cdp.animation from cdp.animation imp...
3,941
1,146
import numpy as np import pyrosetta import pytest from cg_pyrosetta.CG_monte_carlo import SequenceMoverFactory import os import sys import warnings current_path = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.abspath(current_path + '/../PyRosetta4.modified')) @pytest.fixture def pose(): r...
954
390
import streamlit as st import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import plotly.express as px import os from datetime import datetime from fbprophet import Prophet from fbprophet.plot import plot_plotly, plot_components_plotly import pickle st.set_page_config(layout="wide") # or "c...
6,337
2,313
import os def FlagsForFile(filename, **kwargs): os.chdir(os.path.dirname(os.path.abspath(__file__))) flags = os.popen('scons -Q ycm=1').read().split() # Force YCM to recognize all files as C++, including header files flags.extend(['-x', 'c++']) return { 'flags': flags, 'do_cache':...
332
116
from .defender import TabooDefender
35
10
# -*- coding: utf-8 -*- import os import pytest @pytest.fixture(autouse=True) def mock_fetch_next_version(mocker): """Mock 'nomenclator.utilities.fetch_next_version' function.""" import nomenclator.utilities return mocker.patch.object( nomenclator.utilities, "fetch_next_version", return_value=2 ...
28,824
8,359
## # Copyright (c) 2010-2015 Apple 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 applicab...
1,168
396
import os import pickle import cv2 as cv from PIL import Image from torch.utils.data import Dataset from torchvision import transforms from Arc_coll_config import IMG_DIR from Arc_coll_config import pickle_file from image_aug import image_aug # Data augmentation and normalization for training # Just normalization fo...
1,599
593
from .barcode import * from .face import *
43
14
import sys import h5py import pdb import scipy as SP import scipy.stats as ST import scipy.linalg as LA import time as TIME import copy import warnings import os import csv def splitGeno( pos, method='slidingWindow', size=5e4, step=None, annotation_file=None, cis=1e4, ...
4,813
1,628
import os import signal import subprocess import time import argparse #--------------Argument Parser-----------------------# parser = argparse.ArgumentParser(description = "NVIDIA JETSON GSTREAMER VIDEO CONTROLLER") parser.add_argument("-f", "--format", type=str, default="mp4",help="Select video format: mp4 or avi") p...
4,021
1,610
from textual.widget import Widget from datetime import datetime, timedelta import threading from rich.panel import Panel from rich.align import Align class StatusBar(Widget): delta_time: timedelta = timedelta(seconds=0) last_updated: datetime = datetime.now() auto_refresh: bool = False def __init__(s...
1,301
409
import os import re def setIDFormat(idFormat): filePath = os.path.join(os.path.expanduser('~'), r".cnki2bib.cfg") with open(filePath, "w", encoding="utf-8") as f: f.write("[settings]\nid_format = {}".format(idFormat)) def getIDFormat(): filePath = os.path.join(os.path.expanduser('~'), r".cnki2bi...
550
199
"""Provide data file to the package."""
40
13
from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='Tentative pour repondre au challenge psh lincoln', author='fvi', license='MIT', )
226
73
from django.conf.urls import url from django.views.generic.base import TemplateView from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^dashboard$', views.dashboard, name='dashboard'), url(r'^shorten$', views.link_shortener, name='link_shortener'), url(r'^shorten/(?P<cod...
679
264
import cv2 import numpy as np from unittest import TestCase from arithmetics import basic_arithmetics as ba class TestBasicArithmetic(TestCase): def setUp(self): self.image_path = '../asserts/images/elena.jpg' def test_add_gray_success(self): gray = cv2.imread(self.image_path, 0) gray...
2,008
735
# # PySNMP MIB module XYLAN-CSM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XYLAN-CSM-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:44:56 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
217,622
83,591
import sys from flask import Flask, request from flask_cors import * def create_app(): app = Flask(__name__) app.config['JSON_AS_ASCII'] = False # server端支持跨域访问 CORS(app, supports_credentials=True) from libraryuir.web.book_view import views as book_view app.register_blueprint(book_view) r...
329
121
from ..protocol import Protocol, Variable, Struct, NUMERIC_TYPE_SIZES from ..writer import Writer from .. import LIB_NAME, LIB_VERSION LANGUAGE_NAME = "Swift" class SwiftWriter(Writer): language_name = LANGUAGE_NAME default_extension = ".swift" def __init__(self, p: Protocol, extra_args: dict[str,any] =...
14,354
4,448
import requests # Vuln Base Info def info(): return { "author": "cckuailong", "name": '''Apache Flink Unauth RCE''', "description": '''''', "severity": "critical", "references": [ "https://www.exploit-db.com/exploits/48978", "https://adamc95.medium....
2,006
745
import joblib from joblib import Parallel, delayed from joblib import parallel_backend import contextlib from tqdm import tqdm from itertools import product from functools import cmp_to_key from more_itertools import unique_everseen import pandas as pd import random import time @contextlib.contextmanager def tq...
6,506
1,865
from typing import Any, Dict from ....models.models import Speaker from ....permissions.permissions import Permissions from ....shared.patterns import FullQualifiedId from ...generics.delete import DeleteAction from ...util.default_schema import DefaultSchema from ...util.register import register_action @register_ac...
829
230
import math s = 0 for i in range(1, 11): s += 1/(i*i) print(math.sqrt(6*s))
76
42
import requests from testtools import TestCase from ..network import FakeNetwork class FakeGroupsTest(TestCase): def setUp(self): super(FakeGroupsTest, self).setUp() self.network = self.useFixture(FakeNetwork()) def test_get(self): self.network.get('http://test.com', text='data') ...
418
127
"""Test ready-to-use decorators.""" import typing as t from logging import getLogger from time import sleep from unittest.mock import Mock, call import pytest from pydecor.caches import FIFOCache, LRUCache, TimedCache from pydecor.constants import LOG_CALL_FMT_STR from pydecor.decorators import ( log_call, i...
8,054
2,743
import smart_imports smart_imports.all() TIME_TO_LVL_DELTA: float = 7 # разница во времени получения двух соседних уровней TIME_TO_LVL_MULTIPLIER: float = 1.02 # множитель опыта, возводится в степень уровня INITIAL_HP: int = 500 # начальное здоровье героя HP_PER_LVL: int = 50 # бонус к здоровью на уровень MO...
33,973
15,389
"""Base module of pyissues package This module provides data model for issues and comments from the Python Issue Tracker (https://bugs.python.org) with methods to save the issue in base64-encoded XML format. """ from __future__ import annotations import base64 import warnings from typing import List import lxml.etre...
5,485
1,647
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Feb 16 19:48:03 2018 @author: fabrizio OLD: it is only a parser of dataset metadata """ import numpy as np import random as rd file='cullpdb+profile_6133_filtered.npy' dataset = np.load('data/'+file) print(('-'*10)+'dataset: '+file+('-'*10)) print('s...
1,387
572
# Copyright (C) 2016-2018 Virgil Security Inc. # # Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # (1) Redistribution...
5,399
1,870
#!usr/bin/python import configparser; config = configparser.ConfigParser();config.read('config.cfg') if __name__=="__main__": print type(config['web-server']['port'])
171
56
# Configuration file for the Sphinx documentation builder. from usps_client.version import VERSION as version release = version project = "usps-client" copyright = "2019, macro1" author = "macro1" extensions = ["sphinx.ext.autodoc", "sphinxcontrib.apidoc"] templates_path = ["_templates"] exclude_patterns = [] html_...
428
151
""" This module contains functions to generate simulation parameters. """ import numpy as np from numpy import sqrt import math def random_position_uav(number_UAV, radius_UAV, uav_height): """Returns a random UAV position based on 3D Cartesian coordinates. x_r: x-axis | y_r: y-axis | z_r: height...
4,578
1,514
import os, gzip, struct import numpy as np class cwbqpe: '''Class for processing CWB pre-QC QPE data.''' def __init__(self, file=None, data=None): self.uri = file self.header = None self.data = data def help(self): print("This toolset provides functions accessing CW...
6,888
2,578
import time import uasyncio from machine import Pin import driver FRAMERATE = 30 BOUNCE_DELAY = 0.05 DISPLAY = driver.Display(0x3C) last_bounce_time = 0 DISPLAY.draw_bitmap(0, 0, '/title.pbm') pointer_spr = driver.Sprite(DISPLAY, 30, 42) pointer_spr.load_from_pbm('/pointer.pbm') DISPLAY.on() A_PIN = Pin(0, Pin.IN...
676
294
# coding: utf-8 from setuptools import find_packages, setup from vidtoch import AUTHOR, EMAIL, NAME, VERSION, WEBSITE description = "一个帮你将视频转为字符视频的模块。" try: with open("README.md", "r", encoding="utf-8") as mdfile: long_description = mdfile.read() except Exception: long_description = description setu...
1,098
375
class Solution: def isCompleteTree(self, root: TreeNode) -> bool: q = [root] i = 0 while q[i]: q.append(q[i].left) q.append(q[i].right) i += 1 return not any(q[i:])
237
83
usernames = ["rx","bb123","admin","helloooo","lolbro","uvvv"] for name in usernames: if name == "admin": print("Hello admin, would you like to see a status report?") else: print("Hello "+name+", thank you for logging in again.")
259
87
from protorpc import messages import endpoints class Greeting(messages.Message): """Greeting that stores a message.""" message = messages.StringField(1) class GreetingCollection(messages.Message): """Collection of Greetings.""" items = messages.MessageField(Greeting, 1, repeated=True) STORED_GREETI...
433
130
#Source: https://facebook.github.io/prophet/docs/quick_start.html import pandas as pd from fbprophet import Prophet df = pd.read_csv('./example_wp_log_peyton_manning.csv') df = df.rename(columns={df.columns[0]:"ds", df.columns[1]:"y"}) df.head() m = Prophet() m.fit(df) future = m.make_future_dataframe(periods=365) ...
508
219
from lib.extensions import db
29
7