text stringlengths 1 927k |
|---|
# Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... |
#!/usr/bin/env python
"""Fake RDP Server"""
import socket
import time
def fake_server():
"""Start a socket on port 3389 and send init packets"""
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('0.0.0.0', 3389))
serversocket.listen(5)
while True:
try:
... |
import logging
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
class ChartIndicatorException(Exception):
pass
class PlottingExeception(ChartIndicatorException):
pass
class TraceCandlesException(ChartIndicatorException):
pass
class ErrorImplementingIndicator... |
import email
import jwt
import datetime
from models.users import User
from bson.objectid import ObjectId
from utils.email_util import sent_email
from flask import jsonify, make_response
from special_variables import _secret_key
from utils.token_util import token_required
from flask_bcrypt import generate_password_hash,... |
# -*- coding: utf-8 -*-
"""
@Author: lyzhang
@Date: 2018.5.23
@Description:
"""
from config import *
from parser_model.parser import Parser
from utils.file_util import *
from parser_model.form_data import form_data
from nltk.draw.util import CanvasFrame, TextWidget
from nltk.draw import TreeWidget
from nltk import Tre... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import Int32, Float32MultiArray
from std_msgs.msg import MultiArrayDimension, MultiArrayDimension
from geometry_msgs.msg import PoseStamped, Pose
from styx_msgs.msg import TrafficLightArray, TrafficLight
from styx_msgs.msg import Lane
from sensor_msgs.msg import Imag... |
# Copyright 2011 OpenStack Foundation
# Copyright 2013 IBM Corp.
#
# 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 ... |
##############################################################################
#
# An example of converting a Pandas dataframe to an xlsx file with a grouped
# column chart using Pandas and XlsxWriter.
#
# Copyright 2013-2019, John McNamara, jmcnamara@cpan.org
#
import pandas as pd
# Some sample data to plot.
farm_1 ... |
import databases
import pytest
import sqlalchemy
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.testclient import TestClient
DATABASE_URL = "sqlite:///test.db"
metadata = sqlalchemy.MetaData()
notes = sqlalchemy.Table(
"notes",
metadata,
sqlalche... |
from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
path('about/', TemplateView.as_v... |
# Generated by Django 4.0.2 on 2022-02-23 05:35
import django.core.files.storage
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recipes', '0002_remove_recipe_ingredients_and_more'),
]
operations = [
migrations.AddField(
mod... |
"""
Mps based function compression algorithm
"""
import numpy as np
import itertools
from typing import List
from .mps import Mps
from .plots import function_wfa_comparison_chart
def word2real(s : List[int], x0 : float = 0.0, x1 : float = 1.0) -> float:
"""
Convert the binary representation s of xϵ[x0,x1) i... |
"""BayesianTracker (`btrack`) is a multi object tracking algorithm,
specifically used to reconstruct trajectories in crowded fields. New
observations are assigned to tracks by evaluating the posterior probability of
each potential linkage from a Bayesian belief matrix for all possible
linkages. """
from setuptools im... |
#!/usr/bin/env python3
"""Command-line wrapper for stats.cli_percentageOfLinks."""
import loadPath # Adds the project path.
import linkograph.commandUtils
linkograph.commandUtils.cli_selectCommands() |
"""
Bigger scale simulation of a virus spread in a city.
This would have been the better opt for the project, as it uses geospatial visualisation (which is not in this code)
and data gathered from a a ride share, a specific city, their population, and their public transport data.
I still don't understa... |
# Copyright 2020-2021 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 9 18:12:29 2019
@author: Raneem
"""
from sklearn import cluster, metrics
from scipy.spatial.distance import pdist, cdist
import numpy
import sys
def getLabelsPred(startpts, points, k):
labelsPred = [-1] * len(points)
for i in range(len(points)):
di... |
import json
from datetime import datetime
from django.conf import settings
from response.core.models.incident import Incident
from response.slack.settings import INCIDENT_EDIT_DIALOG
from response.slack.dialog_builder import Dialog, Text, TextArea, SelectWithOptions, SelectFromUsers
from response.slack.models import ... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import log... |
import tensorflow as tf
from tensorflow.python.platform import gfile
# only for bugfix
tf.contrib.rnn
output_graph_path = './model.pb'
graph = tf.Graph()
with gfile.FastGFile(output_graph_path, 'rb') as f:
output_graph_def = tf.GraphDef()
output_graph_def.ParseFromString(f.read())
with graph.as_default():
... |
from flowy.swf.decision import task_key, timer_key
class SWFExecutionHistory(object):
def __init__(self, running, timedout, results, errors, order):
self.running = running
self.timedout = timedout
self.results = results
self.errors = errors
self.order_ = order
def is_r... |
class Record:
def __init__(self, record_id, parent_id):
self.record_id = record_id
self.parent_id = parent_id
def equal_id(self):
return self.record_id == self.parent_id
class Node:
def __init__(self, node_id):
self.node_id = node_id
self.children = []
def valida... |
""" tests chemkin_io.writer.mechanism.species_block
"""
from chemkin_io.writer.mechanism import species_block as writer
from chemkin_io.parser.species import names as parser
SPC_IDENT_DCT = {
'O': {'smiles': 'smiles_1',
'inchi': 'inchi_1',
'charge': '',
'mult': '',
'sens': ... |
from id_roles.roles import Roles
__all__ = ['Roles'] |
# -*- coding: UTF-8 -*-
"""
此脚本用于随机生成线性模型数据、定义模型以及其他工具
"""
import numpy as np
import tensorflow as tf
def generateLinearData(dimension, num):
"""
随机产生线性模型数据
参数
----
dimension :int,自变量个数
num :int,数据个数
返回
----
x :np.array,自变量
y :np.array,因变量
"""
np.random.seed(1024)... |
name=input('Enter your name to costomize your personal Maths quiz decathlon:')
print(name,"""'s Maths quiz decathlon
Answer as many questions as possible to attain the maximum points""")
print('''USERS MANUAL
OPERATORS:
+ ==- ADDITION
- ==- SUBSTRACTION
x ==- MULTIPLICATION
/ ==- DIVISION''')
respond=in... |
import time, os, json, time
import numpy as np
import torch
from torch._C import device
import torch.distributed as dist
from torch.autograd import Variable
def test_model(model, test_data, dev):
correct, total = 0, 0
model.eval()
with torch.no_grad():
for data, target in test_data:
d... |
"""Read errors output from a sphinx build and remove duplicate groups"""
import os
import pathlib
import sys
sys.tracebacklimit = 0
my_path = pathlib.Path(__file__).parent.resolve()
errors = set()
error_file = os.path.join(my_path, 'build_errors.txt')
if os.path.isfile(error_file):
with open(error_file) as fid:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 The SymbiFlow 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
from enum import Enum
from collections import ... |
# flake8: noqa
# There's no way to ignore "F401 '...' imported but unused" warnings in this
# module, but to preserve other warnings. So, don't check this module at all.
from .metrics import is_sklearn_available
from .processors import (
DataProcessor,
InputExample,
InputFeatures,
SingleSentenceClassif... |
# -*- coding: UTF-8 -*-
# A part of NonVisual Desktop Access (NVDA)
# Copyright (C) 2006-2020 NV Access Limited, Peter Vágner, Aleksey Sadovoy,
# Rui Batista, Joseph Lee, Heiko Folkerts, Zahari Yurukov, Leonard de Ruijter,
# Derek Riemer, Babbage B.V., Davy Kager, Ethan Holliger, Bill Dengler, Thomas Stivers
# This fil... |
'''API functions for partial updates of existing data in CKAN'''
import logging
from ckan.logic import get_action
from ckanext.harvest.utils import (
DATASET_TYPE_NAME
)
log = logging.getLogger(__name__)
def harvest_source_patch(context, data_dict):
'''
Patch an existing harvest source
This method ... |
""" Usage:
<file-name> --in=IN_FILE --out=OUT_FILE [--debug]
"""
# External imports
import logging
import pdb
from pprint import pprint
from pprint import pformat
from docopt import docopt
from collections import defaultdict
from operator import itemgetter
from tqdm import tqdm
# Local imports
#=-----
def get_pr... |
--- setup.py.orig Mon Feb 19 18:12:55 2007
+++ setup.py Wed Feb 21 16:34:28 2007
@@ -38,8 +38,7 @@
packages = [ 'Hellanzb', 'Hellanzb.NZBLeecher', 'Hellanzb.HellaXMLRPC',
'Hellanzb.external', 'Hellanzb.external.elementtree' ],
scripts = [ 'hellanzb.py' ],
- data_files = [ ... |
"""<internal>"""
'''
zlib License
(C) 2020-2022 DeltaRazero
All rights reserved.
'''
# ***************************************************************************************
class __:
'<imports>'
import abc
import pathlib as pl
import typing as t
from ._textstream_core import (
IText... |
#!/usr/bin/env python2.7
# -*- coding:UTF-8 -*-2
u"""install.py
Copyright (c) 2019 Yukio Kuro
This software is released under BSD license.
Linux用インストーラ。
"""
import os as __os
import sys as __sys
import shutil as __shutil
__shell_script = __os.path.join(__sys.exec_prefix, "games", "starseeker")
__icon = __os.path.join... |
# Copyright 2021 The gRPC Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.0.1',
description='to classify crime',
author='Adebayo',
license='',
) |
import contextlib
import shutil
import threading
import time
from .colors import CYAN, GREEN, RED, YELLOW
from ..utils.threading import ExceptionalThread
UP_ONE = "\033[A\033[1000D"
CLEAR_LINE = "\033[2K"
console_lock = threading.Lock()
class Task:
"""
Something that can be started (by being created), hav... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# IMU exercise
# Copyright (c) 2015-2020 Kjeld Jensen kjen@mmmi.sdu.dk kj@kjen.dk
# import libraries
from math import pi, sqrt, atan2
import matplotlib.pyplot as plt
from pylab import ion
# name of the file to read ##
fileName = 'imu_razor_data_pitch_55deg.txt'
## IMU type
... |
"""
ASGI config for PlagiarismChecker project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJ... |
#-*- coding: utf-8 -*-
import numpy as np
from scipy import io as spio
from matplotlib import pyplot as plt
from scipy import optimize
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14) # 解决windows环境下画图汉字乱码问题
from sklearn import datasets
from skle... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd #for pandas see http://keisanbutsuriya.hateblo.jp/entry/201\
import argparse
import numpy as np
import math
import subprocess
import glob
import os
#from matplotlib import pylab as plt
import matplotlib.pyplot as plt
from numpy.lib.stride_tricks import a... |
import os
import json
import errno
from httpie import __version__
from httpie.compat import is_windows
DEFAULT_CONFIG_DIR = str(os.environ.get(
'HTTPIE_CONFIG_DIR',
os.path.expanduser('~/.httpie') if not is_windows else
os.path.expandvars(r'%APPDATA%\\httpie')
))
class BaseConfigDict(dict):
name =... |
# encoding: utf-8
import six
from six import string_types
import ckan
from ckan.plugins import SingletonPlugin, implements, IPackageController
from ckan.plugins import IGroupController, IOrganizationController, ITagController, IResourceController
from ckan.common import request, config, c
from ckan.logic import get_... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from libcst._tabs import expand_tabs
from libcst.testing.utils import UnitTest, data_provider
class ExpandTabsTest(UnitTest):
@data_prov... |
from tkinter import *
import time
import os
from time import strftime
LARGE_FONT= ("Verdana", 12)
NORM_FONT = ("Helvetica", 10)
SMALL_FONT = ("Helvetica", 8)
global c
c = -1
global count
global solve
count = 0
counti = 0
def clicked():
global count
global secs
count += 1
secs=int(hms_to_seconds(te.get... |
# Test Exercise 4
import pytest
import math
from exercise_4 import extract_position
def test_extract_position():
assert extract_position(
'|error| numerical calculations could not converge.') == None
assert extract_position(
'|debug| numerical calculations could not converge.') == None
ass... |
from functools import partial
from openapi_core.deserializing.parameters.deserializers import (
CallableParameterDeserializer,
)
from openapi_core.deserializing.parameters.deserializers import (
UnsupportedStyleDeserializer,
)
from openapi_core.deserializing.parameters.util import split
from openapi_core.schem... |
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
# 服务器所在机房
class Cloud(models.Model):
name = models.CharField(max_length=50)
comments = models.CharField(max_length=255, null=True)
# def __unicode__(self):
# return u'%d %s %s'... |
from glob import glob
from os.path import basename, splitext
from setuptools import find_packages, setup
setup(
packages=find_packages("src"),
package_dir={"": "src"},
py_modules=[splitext(basename(path))[0] for path in glob("src/*.py")],
python_requires=">=3.5,",
) |
import torch
from torch.utils.data import Dataset, ConcatDataset, Sampler
import torch.distributed as dist
import math
import os
import sys
import shelve
from glob import glob
import numpy as np
import uuid
from termcolor import colored
from collections import Counter, OrderedDict
import random
from .. import util
fro... |
import pytest
from lib import part1, part2, sum_list
from snailfish import Parser, RootSnailFish, Snailfish, ValueSnailfish, parse
from functools import reduce
def test_part1():
assert part1(data) == 4140
def test_part2():
assert part2(data) == 3993
@pytest.mark.parametrize(["row", "expected"], (
("1"... |
from dataclasses import dataclass, field
from typing import List
import tensorflow as tf
from graph_networks.utilities import *
import logging
import os
ATOM_FEATURE_DIM = DGIN4_ATOM_FEATURE_DIM
EDGE_FEATURE_DIM = DGIN4_EDGE_FEATURE_DIM
@dataclass
class BasicModelConfig:
"""
Config for model1/2/3 run file.
... |
def test():
assert "spacy.load" in __solution__, "¿Estás llamando a spacy.load?"
assert nlp.meta["lang"] == "es", "¿Estás cargando el modelo correcto?"
assert nlp.meta["name"] == "core_news_sm", "¿Estás cargando el modelo correcto?"
assert "nlp(text)" in __solution__, "¿Procesaste el texto correctamente... |
#!python
from binarytree import *
def is_sorted(items):
"""Return a boolean indicating whether given items are in sorted order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
# TODO: Check that all adjacent items are in order, return ea... |
# Copyright 2018 Red Hat, 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, ... |
# -*- coding:utf-8 -*-
# Author: Xue Yang <yangxue-2019-sjtu@sjtu.edu.cn>
#
# License: Apache-2.0 license
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import sys
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
... |
from talon import Context, actions, Module
mod = Module()
ctx = Context()
# ctx.matches = r"""
# app.bundle: com.sublimetext.4
# """
# ctx.matches = r"""
# os: windows
# and app.name: Sublime Text
# """
ctx.matches = r"""
os: windows
and app.exe: sublime_text.exe
"""
@ctx.action_class("edit")
class edit_actions:
... |
def output(csv_data, environ, stats):
vulns = csv_data.vuln_to_hosts
sorted_vulns = sorted(vulns, key=csv_data.severity_to_key)
print
print csv_data.name
print "="*len(csv_data.name)
stats(csv_data)
for vuln in sorted_vulns:
print "~~~~~",
if environ['numeric_ids']:
... |
""" Tests related to connecing inputs to outputs."""
import unittest
import numpy as np
from io import StringIO
import openmdao.api as om
from openmdao.utils.assert_utils import assert_near_equal, assert_warning
from openmdao.utils.mpi import MPI
try:
from openmdao.vectors.petsc_vector import PETScVector
except... |
import random
from goldminer import settings, pgc, game, geom, texts, audio
from goldminer.camera import Camera
from goldminer.actor import Actor
from goldminer.worldmap import WorldMap
class World:
def __init__(self, world_map: WorldMap, player: Actor, seed):
self.world_map = world_map
self.actor... |
"""Setup script."""
import glob
import importlib
import os
import setuptools
import vt_police_tools
def components(path):
"""Split a POSIX path into components."""
head, tail = os.path.split(os.path.normpath(path))
if head == "":
return [tail]
elif head == "/":
return [head + tail]
... |
#!/usr/bin/python
"""
extractViewAngle.py
Scope: export points or raster of viewing incidences angles from a Theia L2A product (rasters are scaled by 100 as UInt16)
Author: simon.gascoin@cesbio.cnes.fr
"""
import csv
import gdal
import numpy as np
import ogr
import os
import osr
import sys
import xml.etree.ElementTr... |
# Generated by Django 2.2.24 on 2021-07-15 11:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='last_updated',
... |
import numpy as np
import torch
import pickle
import os
class ReplayBuffer_particles(object):
def __init__(self, obs_space, action_space, max_size=int(1e6), load_folder=None):
self.max_size = max_size
self.store_np = ["state_features","state_particles","action",
"next_state... |
import datetime
import hashlib
import time
from collections import namedtuple, OrderedDict
from copy import copy
from itertools import chain
import csv
import gevent
from .exception import StopUser, CatchResponseError
import logging
console_logger = logging.getLogger("locust.stats_logger")
STATS_NAME_WIDTH = 60
ST... |
import os
import copy
import re
import dill
import subprocess
from datetime import datetime
from collections import OrderedDict as odict
from .generator import Generator
from . import util, cmake, vsinfo
from .named_item import NamedItem
from .variant import Variant
from .build_flags import BuildFlags
from .compiler i... |
# MIT License
#
# (C) Copyright [2022] Hewlett Packard Enterprise Development LP
#
# 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 righ... |
from output.models.ms_data.datatypes.facets.negative_integer.negative_integer_total_digits003_xsd.negative_integer_total_digits003 import (
FooType,
Test,
)
__all__ = [
"FooType",
"Test",
] |
#!/usr/bin/env python3
import unittest
import networkit as nk
class TestGraphTools(unittest.TestCase):
def testLubyAlgorithm(self):
G = nk.Graph(4, False, False)
G.addEdge(0, 1)
G.addEdge(0, 2)
G.addEdge(1, 2)
G.addEdge(2, 3)
luby = nk.independentset.Luby()
res = luby.run(G)
count = sum(res)
# The ... |
from ibm_watson import TextToSpeechV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
def main(text,audio):
authenticator = IAMAuthenticator('7-KyTRyrBXQSuRQO7wazH5Q-Q_5QzDs6R0qOZqD1hyu6')
text_to_speech = TextToSpeechV1(
authenticator=authenticator
)
text_to_speech.set_service_u... |
import sys
import requests
import tempfile
import os
import json
#Select Url based on key provided (free keys always end in :fx)
baseurl = "https://api-free.deepl.com/v2/translate" if sys.argv[3].endswith(":fx") else "https://api.deepl.com/v2/translate"
url = "{}?auth_key={}&text={}&target_lang={}".format(baseurl, sy... |
from asyncio.exceptions import TimeoutError
from telethon.errors.rpcerrorlist import YouBlockedUserError
from telethon.tl.functions.contacts import UnblockRequest
from userbot import CMD_HANDLER as cmd
from userbot import CMD_HELP
from userbot.utils import edit_or_reply, man_cmd
@man_cmd(pattern="short(?: |$)(.*)")... |
# -*- coding: utf-8 -*-
from django.contrib import admin
from .models import SermepaResponse, SermepaIdTPV
class SermepaResponseAdmin(admin.ModelAdmin):
search_fields = ['Ds_Order']
list_display = ('creation_date', 'Ds_Order', 'Ds_Amount',
'Ds_Response', 'Ds_TransactionType', 'check_signat... |
import apricot
import numpy as np
import torch
import torch.nn.functional as F
from scipy.sparse import csr_matrix
from .dataselectionstrategy import DataSelectionStrategy
from torch.utils.data.sampler import SubsetRandomSampler
class SubmodularSelectionStrategy(DataSelectionStrategy):
"""
This class extends ... |
# qubit number=2
# total number=9
import cirq
import qiskit
from qiskit import IBMQ
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy as... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
# Copyright 2018 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
CONSTANTS = [
"SYS_EXIT equ 1",
"SYS_READ equ 3",
"SYS_WRITE equ 4",
"STDIN equ 0",
"STDOUT equ 1",
"True equ 1",
"False equ 0"
]
DATA_SEG = [
"segment .data"
]
BSS_SEG = [
"segment .bss",
" res RESB 1"
]
TEXT_SEG =[
"section .text",
" global _start"
]
PRINT_SUBROUTINE = [
"print:",
" PUSH EBP",
" MOV EBP, ... |
#!/usr/bin/env python2
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import hashlib
import sys
import os
from random import SystemRandom
import base64
import hmac
if len(s... |
from math import ceil
import numpy as np
from ..fixes import rfft, irfft, rfftfreq
from ..utils import logger, verbose
@verbose
def stft(x, wsize, tstep=None, verbose=None):
"""STFT Short-Term Fourier Transform using a sine window.
The transformation is designed to be a tight frame that can be
perfectly... |
# Problem 2
# @author: Ross
import sys # sys.exit()
import testif # testif module
import turtle # Part A
def draw_leaf_straight(length, level):
"""PART A: The draw_leaf_straight() function takes two arguments (length and level) and returns a graphic that depicts a leaf drawn in turtle graphics. """
if ... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import collections
import collections.abc
from dataclasses import dataclass
from functools import partial
from typing import Any, Dict, List, NoReturn, Optional, Tuple
from omegaconf import MISSING, DictConfig, ListConfig
from hydra.types import T... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This progra... |
"""Map Sentinel-1 data products to xarray.
References:
- Sentinel-1 document library: https://sentinels.copernicus.eu/web/sentinel/user-guides/sentinel-1-sar/document-library
- Sentinel-1 Product Specification v3.9 07 May 2021 S1-RS-MDA-52-7441-3-9 documenting IPF 3.40
https://sentinel.esa.int/documents/247904... |
import os
from dotenv import load_dotenv
# https://murhabazi.com/read-emails-python/
def read_credentails():
"""
Return user’s credentials from the environment variables file and
raise a an exception if the credentials are not present
Raises:
NotImplementedError: [description]
"""
load_dotenv()
USER_EMA... |
import itertools
import typing
def solve(s: str) -> typing.NoReturn:
n = 10
cand = []
must = 0
for i in range(n):
if s[i] == 'o':
cand.append(i)
must |= 1 << i
if s[i] == '?':
cand.append(i)
cnt = 0
for prod in itertools.product(cand, repeat=4):
res = 0
for i in prod:
... |
import skimage
import selective_search
image = skimage.data.astronaut()
# Propose boxes
boxes = selective_search.selective_search(image, mode='single', random_sort=True)
# Filter box proposals
boxes_filter = selective_search.box_filter(boxes, min_size=20, topN=80)
print(boxes_filter) |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@FileName : Agent.py
@Author : citang
@Date : 2021/7/27 5:46 下午
@Description : description the function of the file
"""
import sys
from framework import Model, Db, Log, Config, Common
class __Agent__:
"""模块功能"""
def __init__(self,... |
# flake8: noqa
import wirepas_messaging
from default_value import *
def test_generate_parse_request():
# Clear a scratchpad
request = wirepas_messaging.gateway.api.GetScratchpadStatusRequest(
SINK_ID, REQUEST_ID
)
request2 = wirepas_messaging.gateway.api.GetScratchpadStatusRequest.from_paylo... |
import os
import subprocess
def run_test_coverage():
"""
Simple run coverage and do:
- Runs the tests
- Check your test coverage
- Generates HTML coverage report under "htmlcov" directory.
"""
py_test_command = "coverage run -m pytest"
CURRENT_DIR = os.path.dirname(os.path.abspath(... |
import json
import os
import requests
def config():
with open(os.path.dirname(os.path.abspath(__file__)) + "/config.json") as config_file:
data = config_file.read()
return json.loads(data)
def request(api):
ynote_sess = config().get('YNOTE_SESS', '')
ynote_login = config().get('YNOTE_LOGIN',... |
artifacts = {
"io_bazel_rules_scala_scala_library": {
"artifact": "org.scala-lang:scala-library:2.11.12",
"sha256": "0b3d6fd42958ee98715ba2ec5fe221f4ca1e694d7c981b0ae0cd68e97baf6dce",
},
"io_bazel_rules_scala_scala_compiler": {
"artifact": "org.scala-lang:scala-compiler:2.11.12",
... |
import logging
import os
import re
import unittest.mock
# Default to turning off all but critical logging messages
logging.basicConfig(level=logging.CRITICAL)
def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None):
"""Open local files instead of URLs.
If it's a local file ... |
import pandas as pd
from pymethylprocess.MethylationDataTypes import MethylationArray
from sklearn.metrics import mean_absolute_error, r2_score
import warnings
warnings.filterwarnings("ignore")
from pybedtools import BedTool
import numpy as np
from functools import reduce
from torch.utils.data import Dataset, DataLoade... |
def auto_str(cls):
def __str__(self):
return '%s(%s)' % (
type(self).__name__,
', '.join('%s=%s' % item for item in vars(self).items())
)
cls.__str__ = __str__
return cls |
from cytoolz.dicttoolz import (
assoc,
)
def construct_formatting_middleware(request_formatters=None,
result_formatters=None,
error_formatters=None):
if request_formatters is None:
request_formatters = {}
if result_formatters ... |
import json
import numpy as np
class stride():
def __init__(self, size = 1):
self.size = size
self.list = self.init_list()
def init_list(self):
return []
def add(self, value):
self.list.append(value)
if len(self.list) > self.size:
self.list = self.list[1:... |
from datetime import datetime
from typing import List, Optional
import validators
from pydantic import BaseModel, validator
from sqlalchemy import Boolean, Column, DateTime, Integer, String, event, ForeignKey
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import relationship
# SQLAlchemy mo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.