content stringlengths 5 1.05M |
|---|
import requests
from bs4 import BeautifulSoup as bs
import time
from datetime import datetime
import pandas as pd
import os
def gshp_link_by_query(query):
# Find a researcher's Google Scholar homepage link by a query
kw = '+'.join(query.split())
search_link = 'https://scholar.google.com/citations?hl=en&vi... |
""" App widget functionalities """
from app_head import get_head
from app_body import get_body
from app_page import set_page
from app_loading import get_loading_head, get_loading_body
from app_ogp import set_ogp
from app_title import get_title
from app_metatags import get_metatags
from bootstrap import get_bootstrap
fr... |
"""
__/\\\\\\\\\\\\______________________/\\\\\\\\\\\____/\\\________/\\\_
_\/\\\////////\\\__________________/\\\/////////\\\_\/\\\_______\/\\\_
_\/\\\______\//\\\________________\//\\\______\///__\/\\\_______\/\\\_
_\/\\\_______\/\\\_____/\\\\\______\////\\\_________\/\\\_______\/\\\_
_\/\\\_______\/\\\___/... |
import sys
def load(f):
return f.read()
def build(f):
loaded = load(f)
loaded = loaded.replace('mov', '10')
loaded = loaded.replace('eax', '01')
loaded = loaded.replace(',', '')
loaded = loaded.replace('\t', ' ')
loaded = loaded.replace('0x', '')
loaded = loaded.replace... |
"""Contains classes to extract text data and to encode text corpora"""
import pdb
class CharEncoder():
"""
Contains data on an encoded text corpus with labelled characters, including unique characters and
mappings to/from characters to integers.
"""
def __init__(self, corpus):
"""
... |
"""
Created on 17 Apr 2017
@author: Bruno Beloff ([email protected])
"""
import optparse
# --------------------------------------------------------------------------------------------------------------------
class CmdControlReceiver(object):
"""unix command line handler"""
def __init__(se... |
import keras
from keras.preprocessing import image as image_utils
from imagenet_utils import decode_predictions
from imagenet_utils import preprocess_input
from vgg16 import VGG16
import numpy as np
import os
import argparse
#import cv2
# ap = argparse.ArgumentParser()
# ap.add_argument("-i", "--image", required=True... |
#!/usr/bin/env python
#
# Copyright (c) 2012, JT Olds <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... |
# This file is part of datacube-ows, part of the Open Data Cube project.
# See https://opendatacube.org for more information.
#
# Copyright (c) 2017-2021 OWS Contributors
# SPDX-License-Identifier: Apache-2.0
import os
from unittest.mock import patch
def test_fake_creds(monkeypatch):
from datacube_ows.startup_ut... |
from remi.gui import *
from os.path import basename, dirname, join, exists, isfile
from time import time
class LocalImage(Image):
def __init__(self, file_path_name=None, **kwargs):
super(LocalImage, self).__init__('/assets/please-select-image.png', **kwargs)
self.imagedata = None
self.mim... |
# Copyright (c) 2014, FTW Forschungszentrum Telekommunikation Wien
# 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... |
# 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.
import copy
import json
import os
from docs_server_utils import GetLinkToRefType
import compiled_file_system as compiled_fs
from file_system import File... |
place = input("Enter a place: ")
animal = input("Enter a animal:")
job = input("Enter the name of a job:")
badsmell = input("Enter a bad smell:")
print("We went to "+place)
print("To see a "+animal)
print("But a "+job)
print("Said go away")
print("So I said why?")
print("They said because you smell like "+badsmell) |
# Generated by Django 2.2.1 on 2019-10-06 01:00
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mainpage', '0002_auto_20191005_1923'),
]
operations = [
migrations.RemoveField(
model_name='coupons',
name='ca... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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, overload
from . import ... |
import re
import traceback
import urllib
import requests
from bs4 import BeautifulSoup as Soup
import scrapy
from scrapy import Request
from twisted.internet.error import TimeoutError, TCPTimedOutError, ConnectionRefusedError
from spider.items import DoubanItem, DoubanDetailsItem
from spider.settings import DOUBAN_F... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2017-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Pytest helpers."""
from __future__ import absolute_import, print_function
impor... |
expected_output = {
'application': 'ERROR MESSAGE',
'error_message': {
'11/11/2019 03:46:31': ['IOSXE-2-DIAGNOSTICS_PASSED : Diagnostics Thermal passed'],
'11/11/2019 03:46:41': ['IOSXE-2-DIAGNOSTICS_PASSED : Diagnostics Fantray passed'],
'11/11/2019 03:45:41': ['IOSXE-2-TRANSCEIVER_I... |
from .abc import (
EventRepository,
)
from .memory import (
InMemoryEventRepository,
)
from .pg import (
PostgreSqlEventRepository,
)
|
#!/bin/env python
import pytest
import re
import A_re as A
def test_pattern():
assert re.search(A.P_URL, 'http://www.npr.org')
assert not re.search(A.P_URL, 'Mr.DillonNiederhut')
def test_function():
with open('../../data/03_text.md', 'r') as f:
d = f.read()
r = A.get_urls(d)
assert len(... |
#!/usr/bin/env python
total = sum([n**n for n in range(1,1001)])
print str(total)[-10::]
|
import sys
from regenerate_configs import DELAY_BY_PITCH, SOUND_BY_PITCHES, REPS_PER_SECOND
IN_FILE = './in.txt'
OUT_FILE = './out.txt'
SHIFT_DOWN = {
'F#2': 'F2',
'G2': 'F#2',
'Ab2': 'G2',
'A2': 'Ab2',
'Bb2': 'A2',
'B2': 'Bb2',
'C3': 'B2',
'C#3': 'C3',
'D3': 'C#3',
'Eb3': 'D3'... |
import subprocess
from typing import List # noqa: F401
from libqtile import bar, layout, widget, hook
from libqtile.config import Click, Drag, Group, Key, Match, Screen
from libqtile.lazy import lazy
from libqtile.utils import guess_terminal
@hook.subscribe.startup_once
def autostart():
subprocess.Popen('/home/... |
# coding: utf-8
import numpy as np
import pandas as pd
from PredictBase import PredictBase
from keras.callbacks import EarlyStopping
class TestValidate(PredictBase):
def __init__(self):
super().__init__()
self.draw_graph = False
def set_draw_graph(self, v):
self.draw_graph = v
... |
# -*- coding: utf-8 -*-
import colander
import pytest
from mock import Mock
from pyramid.exceptions import BadCSRFToken
from itsdangerous import BadData, SignatureExpired
from h.accounts import schemas
from h.services.user import UserNotActivated, UserService
from h.services.user_password import UserPasswordService
fr... |
import RPi.GPIO as GPIO
import time
power_channel = 24
def blink(times):
print("start blink:" + str(times))
GPIO.setmode(GPIO.BCM)
GPIO.setup(power_channel, GPIO.OUT, initial=GPIO.HIGH)
GPIO.output(power_channel, GPIO.LOW)
time.sleep(times)
GPIO.output(power_channel, GPIO.HIGH)
time.sleep... |
# Copyright (c) 2013, Abhishek Balam and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
def execute(filters=None):
columns, data = [], []
columns = [
{
'label': 'Account',
'fieldname': 'account',
'fieldtype': 'Data',
'width': 200
... |
from __future__ import division # confidence high
from pyraf import iraf
from pyraf.iraf import stsdas, hst_calib, stis
from stistools import wx2d as WX
version = "1.2 (2010 April 27)"
def _wx2d_iraf (input, output="", wavelengths="",
helcorr="perform",
# algorithm="wavelet",
... |
# coding: utf-8
# In[78]:
#!/usr/bin/python
import time
start_time = time.time()
import sys
import pickle
import numpy as np
sys.path.append("../tools/")
from feature_format import featureFormat, targetFeatureSplit
from tester import dump_classifier_and_data
from tester import test_classifier
# In[79]:
#-------... |
# -*- coding: utf-8 -*-
"""Test fixtures."""
from os import environ, makedirs
from os.path import abspath, exists
from shutil import copyfile, rmtree
from tempfile import mkdtemp
from config import Config
from pytest import fixture
WRENTMPDIR = f"{mkdtemp(prefix='wren-pytest-')}"
for b in ("1111111", "2222222", "33... |
# coding: utf-8
from operator import itemgetter
''' 1. Responda: Dicionarios podem ser ordenados?'''
# Não é possível ordenar um dicionario, mas podemos criar uma representação do mesmo com as chaves ordenadas.
# No caso uma lista de tuplas
def ordena(dicionario):
L=dict.keys(dicionario)
L.sort()
D=[]
for i in ... |
#!/usr/bin/env python
#
# Public Domain 2014-present MongoDB, Inc.
# Public Domain 2008-2014 WiredTiger, Inc.
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a com... |
# The Grid Search
# Given a 2D array of digits, try to find a given 2D grid pattern of digits within it.
#
# https://www.hackerrank.com/challenges/the-grid-search/problem
#
def gridSearch(G, P):
# on cherche dans toute les lignes de G
i = 0
while i <= len(G) - len(P):
p0 = 0
while True:
... |
def build_iter_wise_lr_scheduler(optimizer, optimizer_config: dict, num_epochs, iterations_per_epoch: int):
lr_scheduler_config = optimizer_config['lr_scheduler']
lr_scheduler_type = lr_scheduler_config['type']
total_iterations = num_epochs * iterations_per_epoch
if lr_scheduler_type == 'MultiStepLR':
... |
from TASSELpy.utils.Overloading import javaOverload
from TASSELpy.utils.helper import make_sig
from TASSELpy.java.lang.Object import Object
from TASSELpy.java.lang.String import String
import javabridge
java_imports = {'Map':'java/util/Map',
'GeneralAnnotation':'net/maizegenetics/util/GeneralAnnotation... |
'''
JoyCursor
=========
.. versionadded:: 1.10.0
The JoyCursor is a tool for navigating with a joystick as if using a mouse
or touch. Most of the actions that are possible for a mouse user are available
in this module.
For example:
* left click
* right click
* double click (two clicks)
* moving the ... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ListFunctionTriggerResult:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): ... |
from django import forms
from django.forms import ModelForm
from .models import *
class GasPurchaseForm(ModelForm):
class Meta:
model = GasPurchase
fields = [
'vehicle',
'datetime',
'odometer_reading',
'cost_per_gallon',
'gallons',
... |
from System import *
from System.IO import *
from System.Windows import *
from Window1 import *
class $safeprojectname$App: # namespace
@staticmethod
def RealEntryPoint():
a = Application()
window1 = $safeprojectname$.Window1()
a.Run(window1.Root)
if __name__ == "Program":
... |
#!/usr/bin/env python3
import os
import math
import argparse
import subprocess as sub
from sys import stderr, exit
from datetime import timedelta
from tempfile import mkdtemp
from threading import Semaphore, Thread, Lock
MAJOR, MINOR, PATCH = 0, 1, 1
VERSION = f'{MAJOR}.{MINOR}.{PATCH}'
class EmptyConfig:
"""He... |
for i in range(1, 3):
print "The loop ran %d time%s" % (i, (lambda:'', lambda:'s')[i!=1]())
|
import math
import time
from simple_playgrounds.engine import Engine
from simple_playgrounds.playgrounds.layouts import SingleRoom
from simple_playgrounds.elements.collection.teleport import InvisibleBeam, VisibleBeamHoming, Portal, PortalColor
from simple_playgrounds.common.position_utils import CoordinateSampler
fr... |
# Klasse, die den Schrittzähler realisiert
class StepCounter:
# Initialisierung
# Alle Instanzvariablen werden im Konstruktor initialisiert
# Die Klasse kann nur mit der Angabe eines Schrittzählers
# initialisiert werden, wenn es sich bei diesem Konstruktor NICHT um
# einen Standardkonstruktor hande... |
import responses
import re
from ..common import (
HypoApiTest,
TEST_HYPOTHESIS_API_URL,
)
class ProfileTest(HypoApiTest):
@responses.activate
def test_get_users_profile(self):
responses.add(
method=responses.GET,
url=re.compile(f"{TEST_HYPOTHESIS_API_URL}/*"),
... |
import os
from functions.lib.manifest import JasmineFile
def test_get_matching_tests(test_resource_dir):
# get_matching_tests: returns a list of JasminTest Objects for every it('Block') in a passed file
# Test: pass file to jasmineFile object containing no it blocks. Expect: return empty jasmin_test_list
... |
import logging
from pathlib import Path
from nsft_cache_utils.dir import PyTestFixtureRequestT
from test_lib.gpg_ctx_fixture_gen import (
generate_gpg_encrypt_decrypt_basic_fixture_cached,
)
def test_generate_gpg_encrypt_decrypt_basic_fixture(
request: PyTestFixtureRequestT,
tmp_root_homes_dir: P... |
import gzip
import itertools
from typing import Set, Optional, Dict
from rdflib.plugins.parsers.ntriples import NTriplesParser
from rdflib.plugins.serializers.nt import NT11Serializer
from rdflib.term import URIRef, Literal
import networkx as nx
from kgx import RdfTransformer
from kgx.config import get_logger
from kg... |
# -*- coding: utf-8 -*-
""" VoicePlay database entities container """
from datetime import datetime
from pony.orm import Database, PrimaryKey, Required
from pony.orm.ormtypes import buffer
# pylint:disable=invalid-name
db = Database()
class Artist(db.Entity):
"""
Artist database entity container
"""
... |
import torch
import numpy as np
class NP(torch.nn.Module):
def __init__(self, x_dim, y_dim, r_dim, z_dim, encoder_specs, decoder_specs, init_func):
super().__init__()
self.x_dim = x_dim
self.y_dim = y_dim
self.r_dim = r_dim
self.z_dim = z_dim
self.encoder_specs = en... |
#!/usr/bin/env python
"""Find the last created file in a given directory."""
import os
import sys
import stat
folder = sys.argv[1] if len(sys.argv) > 1 else os.curdir
files = (os.path.join(folder, name) for name in os.listdir(folder))
entries = ((path, os.lstat(path)) for path in files) # don't follow symlinks
path, ... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maximumAverageSubtree(self, root: TreeNode) -> float:
self.max_avg = -math.inf
def posto... |
from io import StringIO
import inspect
from textwrap import wrap
import pygments
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.lexers.python import PythonLexer
from .filters import CallHighlightFilter, DecoratorOperatorFilter, TypeHighlightFilter
from .styles import Jellybeans
class... |
"""Unit test for Key class."""
import unittest
from shufflealgos.image.key import Key
class TestKey(unittest.TestCase):
"""TestCase class that will test Key class methods."""
def test_shift_to_range(self):
"""Test shift_to_range method of a Key object."""
absolute_minimum: int = 11
a... |
class SakuraIOBaseException(ValueError):
pass
class CommandError(SakuraIOBaseException):
def __init__(self, status):
self.status = status
def __str__(self):
return "Invalid response status '0x{0:02x}'".format(self.status)
class ParityError(SakuraIOBaseException):
def __init__(self... |
a1, b1, c1 = int(input()), int(input()), int(input())
a2, b2, c2 = int(input()), int(input()), int(input())
if b1 >= a1 >= c1:
(a1, b1, c1) = (b1, a1, c1)
elif c1 >= b1 >= a1:
(a1, b1, c1) = (c1, b1, a1)
elif b1 >= c1 >= a1:
(a1, b1, c1,) = (b1, c1, a1)
elif c1 >= a1 >= b1:
(a1, b1, c1) = (c1, a1, b1)
... |
from django.contrib import admin
from django.shortcuts import render_to_response
from rangefilter.filter import DateRangeFilter, DateTimeRangeFilter
from resid import views
# Register your models here.
from resid.models import Resid
class ResidAdmin(admin.ModelAdmin):
list_display = (
'id',
# 'ta... |
class Item:
def __init__(self, preset):
self.entity = None
self.name = preset.get('name', 'unnamed item')
self.desc = preset.get('name', '')
self.usable = preset.get('usable', False)
self.on_use = preset.get('on_use', lambda: None)
self.equippable = preset.get('equipp... |
import sys
import time
def stuff():
print('Doing stuff ...')
time.sleep(1)
if __name__ == '__main__':
if sys.argv[1] == 'manhole':
from hunter import remote
remote.install()
while True:
stuff()
|
import numpy as np
from .plot import Plot, Dashboard
from .single_outcome import DescriptionPlot
def index_color_outcome(convention, outcomes):
for i, (c, o) in enumerate(zip(convention.yield_colors(len(outcomes)),
outcomes)):
yield i, c, o
class MultiOutputPlot(Plot):
... |
#!/usr/bin/env python
#
# Copyright 2008-2012 NVIDIA Corporation
# Copyright 2009-2010 University of California
#
# 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... |
from tests.func.testfunction import test_function
@test_function
def package_a_func1():
pass |
import threading
import time
from src.optoforce.optoforce import *
class OptoforceThread(threading.Thread):
def __init__(self, optoforce, thread_rate=5000):
super(OptoforceThread, self).__init__()
assert isinstance(optoforce, OptoforceDriver), 'Must be using optoforcedriver'
self.opto = ... |
import checklist
import spacy
import itertools
import checklist.editor
#import checklist.text_generation
from checklist.test_types import MFT, INV, DIR
from checklist.expect import Expect
from checklist.test_suite import TestSuite
import numpy as np
import spacy
from checklist.perturb import Perturb
import collections... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .scale import scale
import brewer2mpl
def _number_to_palette(ctype, n):
n -= 1
palettes = sorted(brewer2mpl.COLOR_MAPS[ctype].keys())
if n < len(palettes):
return palettes[n]
def _ha... |
from PySide import QtCore, QtGui
from networkident_ui import Ui_NetworkIdent
import os, sqlite3
from datetime import datetime
PLUGIN_NAME = "Network Identification"
import plugins_utils
# retrieve modules from ipba root directory
import plistutils
class NetworkIdentWidget(QtGui.QWidget):
def __init__(self, curso... |
"""Data descriptors that provide special behaviors when attributes are
accessed."""
from enum import auto
from enum import Enum
from .exceptions import MarshallerBaseException
class MarshallingAttributeAccessError(MarshallerBaseException):
"""Generic error that arises from while accessing an attribute."""
clas... |
# taken from here:
# https://stackoverflow.com/a/42580137/4698227
import sys
def is_venv():
"""
Checks whether we are in a virtual environment or not.
:return: whether within a virtual environment
:rtype: bool
"""
return (hasattr(sys, 'real_prefix')
or (hasattr(sys, 'base_prefix... |
# -*- coding: utf-8 -*-
import argparse
import json
import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from keras import backend as K
from axelerate.networks.yolo.frontend import create_yolo
from axelerate.networks.yolo.backend.utils.box import draw_scaled_boxes... |
"""Test for our hash data structure."""
import pytest
import hash
PARAMS_TABLE = [
('donuts', 6),
('hashy', 'no'),
('firefly', 'canceled'),
('choochoo', [5, 6, 4, 3]),
("mylittlepony", {"isbrony": "ispony"})
]
PARAMS_TABLE_TYPE_ERRORS = [
(5, ),
([], ),
(True, ),
({}, ),
((), )
... |
import argparse
from pathlib import Path
import shutil
def parse_path(path_string: str) -> Path:
path_string = Path(path_string).resolve()
return path_string
if __name__ == '__main__':
save_help = 'File path to store the augmented training data and the '\
'original validation and test data... |
import json, os, logging, boto3, urllib.request, shutil
from datetime import datetime as dt
logger = logging.getLogger('InspectorQuickstart')
logger.setLevel(logging.DEBUG)
inspectorClient = boto3.client('inspector')
cloudformationClient = boto3.client('cloudformation')
s3Client = boto3.client('s3')
snsClient = boto3... |
from .kdtree import KDTree
__all__ = [
KDTree
]
|
import redis
import re
import requests
import json
import logging
import pandas as pd
import uuid
from datetime import datetime
from fastapi import FastAPI
# from sqlalchemy import create_engine
# from typing import Optional
###
### INIT
###
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)... |
from launch_ros.actions import Node
from launch.substitutions import LaunchConfiguration as LaunchConfig
from launch.actions import DeclareLaunchArgument as LaunchArg
from launch import LaunchDescription
from ament_index_python.packages import get_package_share_directory
camera_params = {
'serial_number': '19372266',... |
print('=ˆ= ' * 11)
print(' tria a l’atzar')
print('=ˆ= ' * 11)
from random import choice
alumnes = []
cicle = 0
while cicle < 5:
alumnes.append(int(input('triar un nombre: ')))
cicle = cicle + 1
print('el nombre triat va ser {}'.format(choice(alumnes)))
|
"""
Original Demo: http://js.cytoscape.org/demos/images-breadthfirst-layout/
Original Code: https://github.com/cytoscape/cytoscape.js/tree/master/documentation/demos/images-breadthfirst-layout
Note: Click Animation is not implemented.
"""
import dash_cytoscape
import dash
from dash.dependencies import Input, Output
i... |
from __future__ import print_function
import pytest_twisted as pt
import pytest
from twisted.internet import defer, reactor
from pprint import pprint
from controller.l4_loadbalancer import LoadBalancer
import time
from myutils.testhelpers import run_cmd, kill_with_children
from myutils import all_results
@pt.inline... |
from datetime import timedelta
from .helpers import make_command
from . import types as command_types
def comment(msg):
text = msg
return make_command(
name=command_types.COMMENT,
payload={
'text': text
}
)
def delay(seconds, minutes, msg=None):
td = timedelta(mi... |
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', )
if __name__ == '__main__':
from aiogram import executor
from handlers import dp
executor.start_polling(dp)
|
import numpy as np
class Gaussian:
def __init__(self, mean=np.zeros((3,1)), sigma=np.eye(3)):
# mean: mean for the gaussian
self.mean = np.array(mean)
# sigma: Covariance matrix
self.sigma = np.array(sigma) + np.eye(3)*1e-8
self.sigma_det = np.linalg.det... |
sexo = input("Digite seu sexo ").lower()
if (sexo == "masculino"):
print("M - Masculino")
elif (sexo == "feminino"):
print("F - Feminino")
else:
print("Valor invalido")
|
#!/usr/bin/python
def main():
# Test suite
test_remaining_balance = False
test_fixed_pmt = False
test_fixed_pmt_bisection = True
if test_remaining_balance:
balance, annualInterestRate, monthlyPaymentRate = (42, .2, .04)
remaining_balance(balance, annualInterestRate, monthlyPaymentR... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 KenV99
#
# 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) a... |
## This file is adapted from NNI project: https://github.com/microsoft/nni
'''
Evaluate pruning attack using auto-compress
'''
import argparse
import os
import json
import torch
from torchvision import datasets, transforms
import random
from nni.compression.torch import SimulatedAnnealingPruner
from nni.compression.to... |
#!/usr/bin/env python
"""
:file: 03_arrays.py
A review of the Array type.
:date: 11/06/2016
:authors:
- Gilad Naaman <[email protected]>
"""
from hydra import *
import binascii
class SomeHeader(Struct):
opcode = uint32_t()
timestamp = uint64_t()
class SomePacket(Struct):
header = NestedStruc... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import random
import time
import unittest
from tqsdk.ta import MA
from tqsdk.test.api.helper import MockInsServer, MockServer
from tqsdk import TqApi, utils
class TestWaitUpdateFunction(unittest.TestCase):
"""
功能函数 wait_update() 测试.
注:
1. 在本地运行... |
def get_set_lists(s: dict):
if s["set_list"] == True:
set_list = ["1"]
elif s["set_list"] == False:
set_list = ["0"]
elif isinstance(s["set_list"], int):
set_list = [str(s["set_list"])]
elif isinstance(s["set_list"], str):
set_list = s["set_list"].split(",")
else:
... |
import os
import pandas as pd
import psycopg2
from dotenv import load_dotenv, find_dotenv
from scipy import stats
from sklearn.linear_model import LinearRegression
from functions_and_classes import *
load_dotenv()
def populate_product_wholesale_bands():
# What markets are vialables?
pctwo_retail, pctwo_... |
#!/usr/bin/python
# coding=utf-8
import cv2, os
import numpy as np
# 获取数据集
# 参数: datadirs:数据目录, labels:数据目录对应的标签, descriptor:特征描述器, size:图片归一化尺寸(通常是2的n次方, 比如(64,64)), kwargs:描述器计算特征的附加参数
# 返回值, descs:特征数据, labels:标签数据
def getDataset(datadirs, labels, descriptor, size, **kwargs):
# 获取训练数据
# 参数: path:图片目录, l... |
import math
def parse_gps(data_str):
lines = data_str.split("\n")
nodes_count, _ = map(int, lines[0].split())
nodes = []
for line in lines[2 : nodes_count + 2]:
id_str, lat_str, lon_str, _, name = line.split("\t")
nodes.append((int(id_str), float(lat_str), float(lon_str), name))
r... |
import cv2
import os
#Read video
cam=cv2.VideoCapture("I&O//demo.mp4")
framecount=0
if not os.path.exists("I&O//frames"):
os.makedirs("I&O//frames")
os.chdir("I&O//frames")
print(os.getcwd())
ret,frame=cam.read()
while ret:
name=str(framecount)+".jpg"
cv2.imwrite(name,frame)
framecount=framecount+1
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import argparse
import numpy as np
import matplotlib
matplotlib.use('Agg')
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['svg.fonttype'] = 'none'
from deeptools import cm # noqa: F401
import matplotlib.pyplot as plt
import plotly.offli... |
from gym import spaces
import numpy as np
from .pybullet_evo.gym_locomotion_envs import HalfCheetahBulletEnv
import copy
from utils import BestEpisodesVideoRecorder
class HalfCheetahEnv(object):
def __init__(self, config = {'env' : {'render' : True, 'record_video': False}}):
self._config = config
s... |
from apps import db
class Describable(db.Model):
__abstract__ = True
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(255))
slug = db.Column(db.String(255))
description = db.Column(db.Text)
class Timestampable(db.Model):
__abstract__ = True
cr... |
import argparse
import pickle
import time
import pandas as pd
from sklearn.model_selection import train_test_split
from product_utils import *
from willump.evaluation.willump_executor import willump_execute
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--cascades", action="store_true", help="Cascade ... |
from __future__ import division
"""
Test cases for the colorClass definedColors module
"""
import colorClass.definedColors as dc
if 'COLORS' in dir(dc):
COLORS = dc.COLORS
a = COLORS.RED
a = 'fdsfds'
if a == COLORS.RED:
print 'I was able to change an enumerated value in the COLORS variable!'
... |
#!/usr/bin/env python3.5
from http.server import CGIHTTPRequestHandler, HTTPServer
import base64
import logging
import argparse
requestHandler = CGIHTTPRequestHandler
server = HTTPServer
class AuthHTTPRequestHandler(requestHandler):
KEY = ''
def do_HEAD(self):
self.send_response(200)
self.sen... |
from pwn import *
from sympy.ntheory.modular import crt
from gmpy2 import iroot
from Crypto.Util.number import long_to_bytes
ns = []
cs = []
for _ in range(3):
s = remote(sys.argv[1], int(sys.argv[2]))
s.recvuntil("n: ")
ns.append(int(s.recvline().decode()))
s.sendlineafter("opt: ", "2")
s.recvuntil("c: ")
... |
from flaskext.wtf import regexp
from flaskext.babel import lazy_gettext as _
USERNAME_RE = r'^[\w.+-]+$'
is_username = regexp(USERNAME_RE,
message=_("You can only use letters, numbers or dashes"))
|
# Generated by Django 2.2 on 2019-11-01 13:57
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import rmgweb.pdep.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.