content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# -*- coding: utf-8 -*-
"""
Lacework ContractInfo API wrapper.
"""
from laceworksdk.api.base_endpoint import BaseEndpoint
class ContractInfoAPI(BaseEndpoint):
def __init__(self, session):
"""
Initializes the ContractInfoAPI object.
:param session: An instance of the HttpSession class
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##
# Translated source for Order.
##
# Source file: Order.java
# Target file: Order.py
#
# Original file copyright original author(s).
# This file copyright Troy Melhase, troy@gci.net.
#
# WARNING: all changes to this file will be lost.
from ib.lib import Double, Integer... | python |
"""
Wrap around the bottleneck distance executable from Dionysus, and provide
some utility functions for plotting
"""
import subprocess
import numpy as np
import matplotlib.pyplot as plt
import os
def plotDGM(dgm, color = 'b', sz = 20, label = 'dgm'):
if dgm.size == 0:
return
# Create Lists
# set a... | python |
# foreign-state
| python |
import tensorflow as tf
from tensorflow.python.platform import flags
import pandas as pd
import numpy as np
from pprint import pprint
from sklearn.model_selection import train_test_split
from data_postp.similarity_computations import transform_vectors_with_inter_class_pca
FLAGS = tf.python.platform.flags.FLAGS
METADA... | python |
'''
bibtutils.slack.message
~~~~~~~~~~~~~~~~~~~~~~~
Enables sending messages to Slack.
'''
import os
import json
import logging
import requests
import datetime
logging.getLogger(__name__).addHandler(logging.NullHandler())
def send_message(webhook, title, text, color):
'''Sends a message to Slack.
.. code... | python |
# -*- coding: utf-8 -*-
from datetime import timedelta
import re
import pymorphy2
import collections
def calc_popular_nouns_by_weeks(articles_info, nouns_count=3):
morph = pymorphy2.MorphAnalyzer()
words_by_weeks = _group_words_by_weeks(articles_info)
nouns_by_week = {}
for week in sorted(words_by_we... | python |
"""
@UpdateTime: 2017/12/7
@Author: liutao
"""
from django.db import models
# Create your models here.
#产品表
class Product(models.Model):
p_id = models.AutoField(primary_key=True)
p_name = models.CharField(max_length=150)
p_money = models.IntegerField()
p_number = models.IntegerField()
p_info = mo... | python |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import sys
import json
import pytest
from awsiot.greengrasscoreipc.model import (
JsonMessage,
SubscriptionResponseMessage
)
sys.path.append("src/")
testTokenJson = [
{
"id": "0895c16b9de9e... | python |
from .property import LiteralProperty
import packaging.version as pv
import rdflib
class VersionProperty(LiteralProperty):
def convert_to_user(self, value):
result = str(value)
if result == '':
# special case, empty strings are equivalent to None
return None
return... | python |
from __future__ import print_function, absolute_import
from os import getenv
from time import sleep
import click
import json
import getpass
from datetime import datetime, timedelta, timezone
from ecs_deploy import VERSION
from ecs_deploy.ecs import DeployAction, DeployBlueGreenAction, ScaleAction, RunAction, EcsCli... | python |
"""helpers"""
import mimetypes
import os
import pkgutil
import posixpath
import sys
import time
import socket
import unicodedata
from threading import RLock
from time import time
from zlib import adler32
from werkzeug.datastructures import Headers
from werkzeug.exceptions import (BadRequest, NotFound,
... | python |
import os
import numpy as np
from argparse import ArgumentParser
from pathlib import Path
from matplotlib import pyplot as plt
from matplotlib import colors
from mpl_toolkits.axes_grid1 import make_axes_locatable
from pytorch_lightning import Trainer
from models.unet.unet import UNet
from configure import get_config
... | python |
import datetime
import pymongo
client = pymongo.MongoClient('127.0.0.1', 27017)
db = client['qbot']
db.drop_collection('increase')
db.drop_collection('welcome')
db.create_collection('welcome')
db.welcome.insert_many([
{
'group_id': 457263503,
'type': 'card',
'icon': 'https://sakuyark.com/s... | python |
import torch
import torch.nn as nn
from torch import optim
import mask_detector.trainer as trainer
from mask_detector.dataset import DatasetType, generate_train_datasets, generate_test_datasets
from mask_detector.models import BaseModel
from mask_detector.combined_predictor import Predictor_M1, submission_label_recalc
... | python |
import logging
import os
import subprocess
import abc
from Bio.Sequencing import Ace
from .fasta_io import write_sequences
# compatible with Python 2 *and* 3:
ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()})
try:
from tempfile import TemporaryDirectory
except ImportError:
from backports.tempfile import ... | python |
import copy
from ..core.api import BaseFLKnowledgeDistillationAPI
class FedMDAPI(BaseFLKnowledgeDistillationAPI):
def __init__(
self,
server,
clients,
public_dataloader,
local_dataloaders,
validation_dataloader,
criterion,
client_optimizers,
... | python |
import numpy as np
from pathfinding.core.diagonal_movement import DiagonalMovement
from pathfinding.core.grid import Grid
from pathfinding.finder.a_star import AStarFinder
def max_pool(map, K):
# First, trim the map down such that it can be divided evenly into K by K square sections.
# Try to keep the trimmi... | python |
import numpy as np
import os
from LoadpMedian import *
from LoadData import *
from gurobipy import *
from sklearn.metrics.pairwise import pairwise_distances
def kmedian_opt(distances, IP, k1, k2):
model = Model("k-median")
n = np.shape(distances)[0]
y,x = {}, {}
if IP:
var_type = GRB.BINARY
... | python |
#!/usr/bin/env python3
"""
Created on 2 Mar 2019
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
from scs_core.data.duplicates import Duplicates
from scs_core.data.json import JSONify
from scs_core.data.path_dict import PathDict
# ---------------------------------------------------------------------... | python |
import validator.validator as validator
from validator.test.fixtures import Fixtures
class TestGetSchemaInfoFromPointer(object):
fxt = Fixtures('get_schema_info_from_pointer')
def do_fxt_test(self, fxt_path):
fixture = self.fxt.get_anymarkup(self.fxt.path(fxt_path))
obj = validator.get_schem... | python |
#!/usr/bin/python
#####################################
### CIS SLOT FILLING SYSTEM ####
### 2014-2015 ####
### Author: Heike Adel ####
#####################################
import sys
import os
sys.path.insert(1, os.path.join(sys.path[0], '../../cnnScripts'))
import cPickle
import ... | python |
from celery.schedules import crontab
from datetime import timedelta
from decimal import Decimal
import logging
DEBUG = True
TESTING = False
ASSETS_DEBUG = True
CSRF_SESSION_KEY = "blahblahblah"
SECRET_KEY = "blahblahblah"
GEOCITY_DAT_LOCATION = "/scout/scout/libs/GeoLiteCity.dat"
LOGGING_LEVEL = logging.DEBUG
LOGGING_... | python |
import logging
import os
import csv
from typing import List
from ... import InputExample
import numpy as np
logger = logging.getLogger(__name__)
class CEBinaryAccuracyEvaluator:
"""
This evaluator can be used with the CrossEncoder class.
It is designed for CrossEncoders with 1 outputs. It ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2019/8/6
@Author : AnNing
"""
import os
import h5py
import matplotlib.pyplot as plt
import numpy as np
from lib.lib_read_ssi import FY4ASSI, FY3DSSI
from lib.lib_database import add_result_data, exist_result_data
from lib.lib_proj import fill_points_2d_nan... | python |
# Problem: https://docs.google.com/document/d/1B-bTbxNllKj0wbou5h4iaLyzgW3EbF3un0-5QKLVcy0/edit?usp=sharing
h=int(input())
w=int(input())
for _ in range(h):
for _ in range(w):
print('O',end='')
print()
| python |
import lit.formats
from lit.llvm import llvm_config
config.name = 'Nacro'
config.test_format = lit.formats.ShTest(True)
config.suffixes = ['.c', '.cpp', '.cc']
config.excludes = ['CMakeLists.txt']
config.test_source_root = os.path.dirname(__file__)
config.test_exec_root = os.path.join(config.nacro_obj_root, 'test')... | python |
import requests
from dhooks import Webhook
def banner():
print("""
Fuck Off Loggers
Input Webhook URL
""")
def deleter():
start = input(">")
hook = Webhook(start)
hook.send("Stop logging shit whore")
x = requests.delete(start)
banner()
deleter()
# Simple shit can be used for anything... | python |
#!/usr/bin/env python3
'''
This script reads program files and concatenates the beginning of
all files to create a input prompt which is then fed to OpenAI
Codex to generate a README.
'''
import sys
# Check if the openai module is installed.
try:
import openai
except ImportError:
print('openai module not foun... | python |
"""
Connects to a given SP3 instance and sends the given packets.
"""
import argparse
import asyncio
import binascii as bi
import colors
import json
import netifaces
import time
from scapy.all import IP, TCP, Raw
import websockets
def get_packets(public_ip, victim_ip, protocol, sport):
"""
Returns a list of ... | python |
from .psg_extractors import extract_psg_data
from .hyp_extractors import extract_hyp_data
from .header_extractors import extract_header
| python |
from flask import Flask
app = Flask(__name__)
app.config['DEBUG'] = True
# Note: We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.
import sys
sys.path.insert(0, 'lib')
import json
import urllib, urllib2
import httplib
import time
from BeautifulSoup import ... | python |
from flask import Flask
def create_app(**config_overrides):
app = Flask(__name__)
# Load default config then apply overrides
app.config.from_object('config.config')
app.config.update(config_overrides)
app.url_map.strict_slashes = False
from .views import views
app.register_blueprint(vie... | python |
#******************************************************************************************
# Copyright (c) 2019 Hitachi, Ltd.
# All rights reserved. This program and the accompanying materials are made available under
# the terms of the MIT License which accompanies this distribution, and is available at
# https://ope... | python |
from typing import List
class Solution:
@staticmethod
def two_sum(nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(1, len(nums)):
if (nums[i] + nums[j]) == target:
return [i, j]
if __name__ == '__main__':
twoSum... | python |
#!/usr/bin/env python3
import os
import pathlib
import re
import ssl
import time
from enum import Enum
from typing import Dict, Optional
import mutagen
import mutagen.easyid3
import requests
import requests.exceptions
from podcastdownloader.exceptions import EpisodeException
class Status(Enum):
blank = 0
p... | python |
#!/usr/bin/python3
import argparse
import csv
import os
import re
import sqlite3
from sqlite3 import Error
#import sys
DB_FOLDER = "database"
DB_FILE = "boxiot.db"
DB_SCHEMA = "schema.sql"
CSV_FOLDER = "database/csv"
CSV_ACTIONS = "actions.csv"
CSV_COMBINATIONS = "combinations.csv"
# DB_TABLE_ACTION_TYPES = "ActionTy... | python |
from django.test import TestCase
from recipe import models
class ModelTests(TestCase):
def test_recipe_str(self):
"""Test that the string representation of recipe is correct"""
recipe = models.Recipe.objects.create(
name='Test Recipe',
description='A recipe used for tests... | python |
from AzureRiskyUsers import Client
import json
BASE_URL = 'https://graph.microsoft.com/v1.0/'
ACCESS_TOKEN_REQUEST_URL = 'https://login.microsoftonline.com/organizations/oauth2/v2.0/token'
def load_mock_response(file_name: str) -> dict:
"""
Load one of the mock responses to be used for assertion.
Args:
... | python |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from .operations import mesh_split_face
__all__ = [
'mesh_quads_to_triangles',
]
def mesh_quads_to_triangles(mesh, check_angles=False):
"""Convert all quadrilateral faces of a mesh to triangles by ... | python |
from .rpg_object import RPGObject
class Class(RPGObject):
config_filename = "classes.yaml"
| python |
from unittest import TestCase
from dragonfly.template.template import Converter
import importlib
class TestTemplate(TestCase):
def test_convert(self):
res = Converter('test.html').convert()
def test_erroneous_if(self):
res = Converter('if_error.html').convert()
with open('if_error.p... | python |
from checkio.electronic_station.roman_numerals import checkio
def test_checkio():
assert checkio(6) == "VI", "6"
assert checkio(76) == "LXXVI", "76"
assert checkio(499) == "CDXCIX", "499"
assert checkio(3888) == "MMMDCCCLXXXVIII", "3888"
def test_checkio_extra_all_small():
assert checkio(1) == "... | python |
# Copyright (c) 2016-2019 Renata Hodovan, Akos Kiss.
#
# Licensed under the BSD 3-Clause License
# <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
# This file may not be copied, modified, or distributed except
# according to those terms.
import logging
from ...listener import EventListener
logger = lo... | python |
#!/usr/bin/python3
def magic_string(repit=[-1]):
repit[0] += 1
return "Holberton, " * repit[0] + "Holberton"
| python |
def flip_word(s, start, end):
l = (end - start) // 2
for i in range(l):
s[start + i], s[end - i - 1] = s[end - i - 1], s[start + i]
def solution(s):
l = len(s)
for i in range(len(s) // 2):
s[i], s[l - 1 - i] = s[l - 1 - i], s[i]
start = 0
for i in range(len(s) + 1):
if... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 The Project U-Ray Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
""" Database files available for a tile ty... | python |
"""
Vishnu... Thank you for electronics.
Author: Manas Kumar Mishra
Task:- D(3) D--> Decimal number system.
"""
"""
Task :Apply the optical flow algorithm with shi-tumasi to define the motion path and
print that is there any change in the person or image is is motion or not.
"""
"""
Theory:-
Optical flow t... | python |
import os
import yaml
import shlex
import re
def get_gputree_config():
"""Fetch host config from gputree configuration file if found.
Returns:
dict: The configuration dictionnary.
"""
if os.environ.get("GPUTREE_CONFIG_FILE"):
config_path = os.environ["GPUTREE_CONFIG_FILE"]
elif o... | python |
from django.shortcuts import render
from httptest2.testmodule import tasks
from httptest2.testmodule.forms import TestModuleForm, DisplayModuleForm
import time
import json
# Create your views here.
def display_all(request):
if request.method == 'POST':
form = DisplayModuleForm(request.POST)
if form... | python |
import pytest
@pytest.fixture(autouse=True)
def xray(mocker):
"""
Disables AWS X-Ray
"""
mocker.patch('aws_xray_sdk.core.xray_recorder')
mocker.patch('aws_xray_sdk.core.patch_all')
@pytest.fixture(autouse=True)
def mock_boto3_client(mocker):
"""
Patches Boto3
"""
mocker.patch('bo... | python |
import essentia
import numpy as np
from essentia.standard import *
import os
import re
class FeatureExtractor():
def __init__(self, train_folders=None, test_folders=None):
self.train_path = os.environ['IRMAS_TRAIN']
self.test_path = os.environ['IRMAS_TEST']
self.train_folders = train_... | python |
# DRUNKWATER TEMPLATE(add description and prototypes)
# Question Title and Description on leetcode.com
# Function Declaration and Function Prototypes on leetcode.com
#407. Trapping Rain Water II
#Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volu... | python |
"""
Track Atmosphere transactions across our system.
"""
from django.db import models
from uuid import uuid1
from django.utils import timezone
class T(models.Model):
"""
Track Atmosphere transactions across our system.
"""
# A unique UUID (V)alue for the transaction.
V = models.CharField(max_len... | python |
from collections import deque
N, Q = map(int, input().split())
city = [[] for _ in range(N + 1)]
for i in range(N - 1):
a, b = map(int, input().split())
city[a].append(b)
city[b].append(a)
n_city = [-1] * (N + 1)
q = deque([])
q.append(1)
n_city[1] = 0
while q:
x = q.pop()
p = n_city[x]
for i i... | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... | python |
# -*- coding: utf-8 -*-
"""driver drowsiness detection
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Yjex8oAKte4yIZu91YXjJLsZLlR7pa0y
"""
from keras.models import Sequential
from keras.layers import MaxPool2D,Dropout,BatchNormalization,Dense,Conv2D,... | python |
# Construtores
'''
class carro:
def __init__(self,portas,preço,):
self.numero_portas = portas
self.preço = preço
print("Objeto instanciado com sucesso")
def get_numero_portas(self):
return self.numero_portas
carro1 = carro(6,50000,)
portas_carro1 = carro1.get_numero_portas()
pr... | python |
import torch
import torch.nn as nn
from torch.nn import init
import torch.nn.functional as F
from library.text.modules.base.rnn import lstm_encoder
INI = 1e-2
class ConvSentEncoder(nn.Module):
"""
Convolutional word-level sentence encoder
w/ max-over-time pooling, [3, 4, 5] kernel sizes, ReLU activation
... | python |
from django.contrib import admin
from django.contrib import messages
from django.utils.translation import ngettext
from .models import Category, Product
# Register your models here.
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = ('name', 'slug')
prepopulated_fields = {'slug':... | python |
#
# Copyright (c) 2021 Intel Corporation
#
# 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... | python |
# -*- coding: utf-8 -*-
from odoo import models, fields, api, exceptions
class LibraryBook(models.Model):
_name = "library.book"
name = fields.Char(string="Name")
active = fields.Boolean("Is active", default=True)
image = fields.Binary()
pages = fields.Integer(string="# Pages")
isbn = fields... | python |
# Copyright 2010 Chet Luther <chet.luther@gmail.com>
#
# 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 o... | python |
import frappe
import json
import frappe.utils
from frappe import _
from frappe.model.naming import make_autoname
import frappe.defaults
import phonenumbers
from frappe.utils import encode
# from erpnext.selling.doctype.customer.customer import get_customer_outstanding
@frappe.whitelist(allow_guest=True)
def get_custom... | python |
from PyQt5 import QtGui,QtWidgets,QtCore
from PyQt5.QtWidgets import QApplication,QRadioButton,QPushButton,QListWidget,QDial,QSpinBox,QLCDNumber,QMessageBox,QLabel
from PyQt5.QtGui import QPixmap
import sys
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import numpy as np
from matplotlib.ba... | python |
#!/usr/bin/env python3
import csv
import os
import re
from glob import glob
from unittest import TestCase, main
from g2p.app import APP
from g2p.cli import convert, doctor, generate_mapping, scan, update
from g2p.log import LOGGER
from g2p.tests.public.data import __file__ as data_dir
class CliTest(TestCase):
"... | python |
from cli import banner, list_files, menu, device_monitor
from cli import access
import os
def main():
os.system('clear')
print("\n")
banner.display()
print("\n")
###
device_monitor.display()
print("\n")
# password check
# password_check = access.password_check()
# if password_ch... | python |
time=[]
while True:
gols = []
dic={}
dic['nome']=input('nome do jogador: ')
dic['jogos']=int(input(f'numero de partidas de {dic["nome"]}: '))
for l in range(0,dic['jogos']):
gols.append(int(input(f'quantos gols na partida {l+1}: ')))
dic['gols']=gols[:]
dic['total']=sum(gols)
tim... | python |
from torch.nn.modules.loss import _Loss
__all__ = ['JointLoss', 'WeightedLoss']
class WeightedLoss(_Loss):
"""Wrapper class around loss function that applies weighted with fixed factor.
This class helps to balance multiple losses if they have different scales
"""
def __init__(self, loss, weight=1.0)... | python |
import os
import hashlib
from urllib.parse import parse_qs #系统的查询参数解析方法
import jinja2
from DBHelper import DBHelper
from Response import *
# 处理模块
# 读取文件
def load_file(fileName):
try:
with open(fileName, 'rb') as fp:
return fp.read() # 文件存在
except Exception as e:
return b"File n... | python |
from repl import start
def main() -> None:
print("Hello! This is the Monkey programming language!")
print("Feel free to type in commands")
start()
if __name__ == "__main__":
main()
| python |
"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... | python |
from tests.package.test_perl import TestPerlBase
class TestPerlDBDmysql(TestPerlBase):
"""
package:
DBD-mysql XS
direct dependencies:
DBI XS
"""
config = TestPerlBase.config + \
"""
BR2_PACKAGE_PERL=y
BR2_PACKAGE_PERL_DBD_MYSQL=y
"""
def te... | python |
MIXNODE_CONFIG = {
'api_key': 'your api key' # available at https://www.mixnode.com/account/api
};
| python |
from rest_framework import serializers
# from rest_framework_recursive.fields import RecursiveField
from . import models
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = models.Tag
fields = ('title', )
class ExperienceSerializer(serializers.ModelSerializer):
user = seri... | python |
import csv
from urllib.request import Request, urlopen
import urllib.error
import dateutil.parser
import re
from os import system
from sys import argv
from bs4 import BeautifulSoup
import scrape_util
default_sale, base_url, prefix = scrape_util.get_market(argv)
temp_raw = scrape_util.ReportRaw(argv, prefix)
#report_... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-07 13:59
from __future__ import unicode_literals
from django.db import migrations, models
import sendinblue.forms
import wagtail.wagtailcore.blocks
import wagtail.wagtailcore.fields
import wagtail.wagtailembeds.blocks
import wagtail.wagtailimages.blocks
... | python |
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import pdb
def init_weights(m):
if isinstance(m, nn.Conv2d):
torch.nn.init.xavier_uniform_(m.weight)
m.bias.data.fill_(0.01)
class UNet(nn.Module):
def __init__(self, init_weights=True):
... | python |
from .. import ssl
from . import base
class LocalCa(base.CaManager):
"""Class implementing a certificate authority based on a private key retrieved from CA storage
"""
def __init__(
self,
ca_config,
staging=True,
storage_api=None,
ca_private_key=... | python |
from autode.transition_states.ts_guess import TSguess
from autode.transition_states.transition_state import TransitionState
__all__ = ['TSguess',
'TransitionState']
| python |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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.... | python |
from .c_distribution_gaussian import CDistributionGaussian
from .c_density_estimation import CDensityEstimation
| python |
#!/usr/bin/env python
import json
import sys
# http://docs.python.org/2/library/urlparse.html
from urlparse import urlparse
if len(sys.argv) < 2:
print "Usage:", sys.argv[0], "<file.json>"
raise SystemExit
data = open(sys.argv[1]).read()
har = json.loads(data)
domain_map = {}
for e in har['log']['entries']:
ur... | python |
"""Audio Overlay Tool
Usage:
aot.py <input_dir> <output_dir> <num_generate> <samples_per_sample> [options]
Options:
-f RGX --filter=RGX a filter for selecting the input files from the input directory.
-o FMT --outfmt=FMT Output format of the files (file a information in {a+cg} file b inform... | python |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | python |
# Copyright 2015 PerfKitBenchmarker 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 appli... | python |
import unittest
from http import HTTPStatus
from test.flask_test_app import create_app
class TestRequestArg(unittest.TestCase):
def assertInHTML(self, value, response):
HTML_text = response.data.decode("utf-8")
self.assertIn(value, HTML_text)
def setUp(self) -> None:
_app = create_ap... | python |
#%%
## command-line arguments
import argparse
parser = argparse.ArgumentParser(description="Runner script that can take command-line arguments")
parser.add_argument("-i", "--input", help="Path to a FASTA file. Required.", required=True)
parser.add_argument("-o", "--output_dir", default="", type=str,
... | python |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="migeo", # Replace with your own username
version="v0.0.1",
author="Projeto EM UFPA/Petrobrás",
author_email="isadora.s.macedo@gmail.com",
description="Modelagem e inversão eletromagnética ... | python |
# Author: Mohammad Samani
# Date: 1.12.2021
# Place: Basel, Switzerland
import time, platform, struct, binascii, asyncio
from config import conf
from error import RecordError
from bleak import BleakClient
from bleak.backends.winrt.client import BleakClientWinRT
import db
ADDRESS = conf['mac_address']
TEMP_UUID = co... | python |
from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime
from app.db.session import Session
from app.models import Base
class Captcha(Base):
__tablename__ = 'covid_captcha'
id = Column(Integer, autoincrement=True, primary_key=True, comment="主键")
create_time = Column(DateTim... | python |
from migen import *
from photonsdi.constants import *
class FrameExtractor(Module):
def __init__(self, elementary_stream_count=2):
assert elementary_stream_count in [2]
datapath_width = elementary_stream_count * SDI_ELEMENTARY_STREAM_DATA_WIDTH
self.i_data = Signal(datapath_width)
... | python |
from typing import NamedTuple, Dict, Generator
import re
CommandArgs = NamedTuple('CommandArgs',
[('command', str), ('args', list[str])])
def variable_expansion(word: str, environment: Dict[str, str]) -> str:
"""Подставляет значения из окружения вместо переменных."""
return re.sub(... | python |
# coding=utf-8
from contracts import contract, describe_value, describe_type
from geometry import logger
import numpy as np
from .manifolds import DifferentiableManifold
#
# def array_to_lists(x):
# return x.tolist()
#
# def packet(space, rep, value):
# return {'space': space, 'repr': rep, 'value': value}
#
# ... | python |
from manga_py.provider import Provider
from .helpers import tapas_io
from .helpers.std import Std
class TapasIo(Provider, Std): # TODO: Login\Password
helper = None
def get_archive_name(self) -> str:
ch = self.chapter
return self.normal_arc_name([
ch['scene'],
ch['tit... | python |
import logging
from collections import namedtuple
from io import StringIO
from typing import List
from urllib.parse import quote_plus
from aiohttp import ClientSession, ClientTimeout
from lxml import etree
from lxml.html import HtmlElement
CourtInfo = namedtuple("CourtAddress", ["name", "address", "note"])
def to_... | python |
import json
import logging
import os
import sys
import boto3
import domovoi
from botocore.exceptions import ClientError
pkg_root = os.path.abspath(os.path.join(os.path.dirname(__file__), 'domovoilib')) # noqa
sys.path.insert(0, pkg_root) # noqa
from dss import stepfunctions
from dss.stepfunctions import SFN_TEMPLA... | python |
import py
from pypy.lang.prolog.interpreter.parsing import parse_file, TermBuilder
from pypy.lang.prolog.interpreter import engine, helper, term, error
from pypy.lang.prolog.builtin import builtins, builtins_list
from pypy.rlib.objectmodel import we_are_translated
class Builtin(object):
_immutable_ = True
def... | python |
import argparse
import errno
import json
import os
import shutil
import sys
import tempfile
import bdbag.bdbag_api
from galaxy.datatypes import sniff
from galaxy.datatypes.registry import Registry
from galaxy.datatypes.upload_util import (
handle_sniffable_binary_check,
handle_unsniffable_binary_check,
Up... | python |
from concurrent.futures import ThreadPoolExecutor
import lib.HackRequests as HackRequests
task_status = 0
def uploadfile(data):
global task_status
if task_status==1:
return 'Success'
hack = HackRequests.hackRequests()
hack.httpraw(data)
def requestfile(url):
global task_status
if task... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.