text string | size int64 | token_count int64 |
|---|---|---|
class Function():
def __init__(self, func):
self.function = func
self.color = (50, 50, 155)
class LinearFunction(Function):
def __init__(self, k, m): # y = kx + m
self.color = (50, 50, 155)
self.k = k
self.m = m
def function(self, x):
return x ... | 750 | 287 |
import numpy as np
box = np.load('./data/obj/000090_3d.npy')
id = np.load('./data/obj/000090_id.npy')
print(box)
print(len(box))
print(id) | 139 | 72 |
from rest_framework import status
from rest_framework.test import APITestCase
from core_model.models import Patient, Physician, Appointment
from api.views import AppointmentsViewSet
from datetime import timedelta
def create_item(client):
patient = Patient.objects.create(first_name='Orane', last_name='Brousse')
... | 3,361 | 1,113 |
__author__ = 'Maxim Dutkin (max@dutkin.ru)'
from enum import IntEnum
class M2CoreIntEnum(IntEnum):
@classmethod
def get(cls, member_value: int or str):
"""
Returns enum member from `int` ID. If no member found - returns `None`
:param member_value:
:return: enum member or `N... | 838 | 237 |
# -*- coding: utf-8 -*-
import time
import sys
import socket
import subprocess
import random
family_addr = socket.AF_INET
host = 'esp_server.local'
PORT = 3333
def getdata(sock, send_bytes, max_speed_hz):
start_time = time.time()
# Send data
sock.sendall(bytes(bytearray(send_bytes)))
# Receive data
result... | 1,811 | 756 |
import itertools
import sys
import builtins
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
PY37 = sys.version_info[0] == 3 and sys.version_info[1] == 7
if PY2:
string_classes = basestring
else:
string_classes = (str, bytes)
if PY2:
import collections
container_abcs = collections
elif ... | 388 | 142 |
def invoke(_bas_vars, _bas_api, _bas_print):
bas_print = _bas_print
bas_vars = _bas_vars
bas_api = _bas_api
from src.testa import testa as test_a
from src.testb import testb as test_b
bas_print(test_a())
bas_print(test_b())
| 255 | 101 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | 1,200 | 336 |
from .impl import algorithms
from .portfolio import portfolio, schemas
from .module import modules, limit, tuner, evolution
from util import load_modules
algorithms = {
**portfolio,
**algorithms,
}
modules = {
**modules,
**schemas,
}
def Algorithm(configuration, **kwargs):
slug = configuration.... | 528 | 164 |
import torch.nn.functional as F
def nll_loss(model, data, reduction='mean', weights=1):
data, target = data[0].cuda(), data[1].cuda()
model.zero_grad()
output = model(data)
loss = F.nll_loss(output, target, reduction=reduction)*weights
return loss
| 270 | 95 |
import psycopg2
from shapely.geometry import Polygon
import traceback
from multiprocessing import Process, Queue, Event
import time
def database_connect(**kwargs):
try:
if kwargs.get('type', 'postgres') == 'postgres':
db_conn = psycopg2.connect(host=kwargs['db_host'],
... | 12,802 | 3,954 |
# Tkinter class structure
import tkinter as tk
from tkinter import ttk, messagebox, font
from datetime import *
import sqlite3 as sq
import GoogleCal
class Scheduler(tk.Frame):
def __init__(self, root, task):
tk.Frame.__init__(self, root)
self.root = root
self.task = task
self.selec... | 11,536 | 3,704 |
#!/usr/bin/python
# encoding: utf-8
#
# Copyright (c) 2016 Dean Jackson <deanishe@deanishe.net>
#
# MIT Licence. See http://opensource.org/licenses/MIT
#
# Created on 2016-03-22
#
"""dfx.py [-t <type>...] [<query>]
Usage:
dfx.py [-t <type>...] [<query>]
dfx.py -u
dfx.py -h | --help
dfx.py --version
O... | 5,848 | 1,941 |
from django.core.files.uploadedfile import SimpleUploadedFile
from test_plus.test import TestCase as PlusTestCase
from ..exceptions import DuplicateDocumentNameError, DuplicateFolderNameError
from ..models import Document, Folder
class BaseTest(PlusTestCase):
def setUp(self):
self.user = self.make_user... | 2,477 | 776 |
import cv2
import copy
cap = cv2.VideoCapture(0)
name=input("Please Enter Your First Name : ")
while(True):
ret,frame = cap.read()
frame1=copy.deepcopy(frame)
frame1 = cv2.putText(frame1, 'Press \'k\' to click photo', (200,200), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,255), 3, cv2.LINE_AA)
cv2.imshow('im... | 488 | 206 |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# author:Darksoul
# datetime:11/24/2018 22:02
# software: PyCharm
from network import *
from torch import optim
from torch.nn.utils import clip_grad_norm_
from random import randint
from tqdm import tqdm
# import loss func
import masked_cross_entropy
import numpy as np
de... | 5,409 | 1,901 |
def start():
print("finish the file : terminal.py")
import time
time.sleep(0.1)
print("finish the file : setoollin.py")
time.sleep(0.1)
print("finish the file : set.py")
time.sleep(0.1)
print("finish the optioning : start the optioning files ")
time.sleep(0.1)
print("finish the o... | 764 | 232 |
import numpy as np
import tensorflow as tf
from config import MovieQAPath
from legacy.input import Input
_mp = MovieQAPath()
hp = {'emb_dim': 300, 'feat_dim': 512,
'learning_rate': 10 ** (-3), 'decay_rate': 0.83, 'decay_type': 'exp', 'decay_epoch': 2,
'opt': 'adam', 'checkpoint': '', 'dropout_rate': 0.1, ... | 7,453 | 2,974 |
#!/usr/bin/env python3.5
# -*- coding: utf-8 -*-
""" This is the finance module, controlling all the money commands.
The data is stored in data/owed.json, which is loaded using some of the helper
functions.
"""
from telegram.ext import (ConversationHandler, MessageHandler, CommandHandler,
F... | 12,010 | 3,919 |
"""
This file loads sentences from a provided text file. It is expected, that the there is one sentence per line in that text file.
TSDAE will be training using these sentences. Checkpoints are stored every 500 steps to the output folder.
Usage:
python train_tsdae_from_file.py path/to/sentences.txt
"""
from sentence... | 3,174 | 983 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
from conversationinsights.policies.keras_policy import KerasPolicy
logger = logging.getLogger(__name__)
class ConcertPolicy(KerasPolicy):
def _buil... | 1,315 | 374 |
import sys
import os
import json
sys.path.append('.')
sys.path.append('..')
import src.Settings # noqa: E402
def test_Settings_1():
os.makedirs('tests', exist_ok=True)
settingsPath = './tests/test_Settings_1.json'
settings = src.Settings.Settings(settingsPath)
with open(settingsPath, 'r', encoding='u... | 1,057 | 323 |
import sys
import os
sys.path.append('../org_to_anki')
# Anki deck
from org_to_anki.ankiClasses.AnkiDeck import AnkiDeck
from org_to_anki.ankiClasses.AnkiQuestion import AnkiQuestion
def testGettingDeckNames():
# Create deck with subdeck
parent = AnkiDeck("parent")
child = AnkiDeck("child")
subChild ... | 3,730 | 1,213 |
'''
script para calcular o gasto com carro alugado
usando como base os quilômetros
e também os dias que permaneceu alugado
'''
km = float(input('quantos quilômetros percorridos? '))
dias = int(input('quantos dias o veiculo permaneceu alugado? '))
preco = (dias * 60) + (km * 0.15)
print(f'você pagará R${preco:.2f}') | 320 | 132 |
"""
Software PWM.
Hardkernel doesn't support hardware PWM on the Odroid C2.
This should work fine on the Raspberry Pi GPIO as well, though.
"""
import time
try:
import wiringpi2 as wp
except ImportError:
import wiringpi as wp
from multiprocessing import Process, Value
class SoftwarePWM:
"""
Software ... | 1,452 | 489 |
import logging
from .base import BaseInventory
logger = logging.getLogger('zentral.contrib.inventory.backends.dummy')
DUMMY_MACHINES = [
{'serial_number': '0123456789',
'groups': [{'reference': 'dummy_group_1',
'name': 'Dummy Group 1'}],
'os_version': {'name': 'OSX',
... | 1,807 | 627 |
# """Tests common to all integrator implementations."""
import os
import mitsuba
import pytest
import enoki as ek
import numpy as np
from enoki.dynamic import Float32 as Float
from mitsuba.python.test.scenes import SCENES
integrators = [
'int_name', [
"depth",
"direct",
"path",
]
]
d... | 6,293 | 2,030 |
import os
import sys
import csv
import re
#Creazione di script congiunto
#modificare i path in base alla revisione
def getFirstLetter(s):
return s[0].capitalize()
def listaPresenti():
lista=[]
with open('presenti.txt', 'r') as presenti:
lista = presenti.read().splitlines()
return lista
d... | 4,476 | 1,572 |
from txtferret.cli import prep_config, bootstrap, get_totals
def test_prep_config():
def stub_loader(yaml_file=None):
return {"yaml_file": yaml_file}
fake_cli_kwargs = {"config_file": "my_test_file"}
final_config = {"cli_kwargs": {**fake_cli_kwargs}, "yaml_file": "my_test_file"}
assert prep... | 942 | 340 |
def fibonnacci(n):
"""returns the nth fibonnacci number"""
if n <= 1:
return n
else:
return(fibonnacci(n-2) + fibonnacci(n-1))
if __name__ == '__main__':
print(fibonnacci(6)) | 212 | 84 |
from django.test import Client
from django.test import TestCase
class ViewsTest(TestCase):
fixtures = ['test_basic_data.yaml']
def setUp(self):
pass
def tearDown(self):
pass
def test_homepage(self):
c = Client()
response = c.get('/')
self.assertEqual(respon... | 1,325 | 429 |
from .SendEmail import SendEmail
from .Data_base.Data_base import Usuarios
from PyQt5.QtWidgets import QMainWindow, QApplication
from .Verifications_and_Responses.Verifications import Verifications
from .Verifications_and_Responses.Responses import Responses
from .RequestConfirmationCode import Request_Confirmation_Cod... | 2,471 | 682 |
import turtle
import random
import os
def turtle_in_lead(list_of_turtles, list_of_turtles_str):
x_coordinates = []
for turtle in list_of_turtles:
x_coordinates.append(turtle.xcor())
max_index = x_coordinates.index(max(x_coordinates))
return list_of_turtles_str[max_index]
screen = turtle.Scree... | 2,093 | 866 |
"""
5G linear array antenna
-----------------------
This example shows how to use HFSS 3D Layout to create and solve a 5G linear array antenna.
"""
# sphinx_gallery_thumbnail_path = 'Resources/5gantenna.png'
###############################################################################
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | 7,746 | 2,767 |
# Copyright (C) 2013 Evan Ochsner, R. O'Shaughnessy
#
# 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 2 of the License, or (at your
# option) any later version.
#
# This program ... | 89,972 | 31,891 |
"""This module defines a serializer for the transaction model."""
from rest_framework import serializers
from polaris.models import Transaction
class PolarisDecimalField(serializers.DecimalField):
@staticmethod
def strip_trailing_zeros(num):
if num == num.to_integral():
return round(num, ... | 2,144 | 611 |
import logging
from pylons import app_globals, request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from hola.lib.base import BaseController, render
import hola.lib.helpers as h
log = logging.getLogger(__name__)
class HelloController(BaseController):
def index... | 946 | 283 |
#envio4
# -*- coding: utf-8 -*-
"""
Created on Fri May 31 10:52:39 2019
@author: Leon
"""
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy
from scipy import stats
import pandas as pd
import random
bw = []
with open('bodyweight.txt') as inputfile:
for line in inputfile:
... | 1,589 | 706 |
# exercise 11.2.2
import numpy as np
from matplotlib.pyplot import figure, subplot, hist, title, show, plot
from scipy.stats.kde import gaussian_kde
# Draw samples from mixture of gaussians (as in exercise 11.1.1)
N = 1000; M = 1
x = np.linspace(-10, 10, 50)
X = np.empty((N,M))
m = np.array([1, 3, 6]); s = np.array([1... | 895 | 413 |
from os import getcwd, path
import yaml
# pylint: disable=too-few-public-methods
class Custom:
def __init__(self, tag, value):
self.tag = tag
self.value = value
def __eq__(self, other):
return self.tag == other.tag and self.value == other.value
def custom_constructor(loader, node):
... | 1,903 | 675 |
#
# image.py
# Created by pira on 2017/07/28.
#
#coding: utf-8
u"""For image processing."""
import sys
import numpy as np
import cv2
RED = 2
GREEN = 1
BLUE = 0
def readGrayImage(filename):
u"""Read grayscale image.
@param filename : filename
@return img : 2 dimension np.ndarray[Height][Width]
"""
#imr... | 6,132 | 2,582 |
import numpy as np
import basis
from utils.molecule import Molecule
from basis.basis import Basis
from basis.gaussian import Gaussian
# STO-NG fitted parameters from Table I of doi:10.1063/1.1672392
sto_alpha_1s = [
# pad with two empty lists so index corresponds to sto_ng
[],[],[],
# sto_3g
[3.2078312... | 5,399 | 2,140 |
"""
A utility to ease grading.
"""
from setuptools import find_packages, setup
package = 'grader_toolkit'
version = '0.1.0'
dependencies = [
'click',
'click-repl',
'ruamel.yaml',
'six',
'sqlalchemy',
'typing'
]
setup(
name=package,
version=version,
package_dir={'': 'src'},
pac... | 508 | 185 |
# Copyright 2014 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... | 2,399 | 769 |
from basicts.metrics.mae import masked_mae as masked_l1_loss
from basicts.utils.misc import check_nan_inf
import torch
import torch.nn.functional as F
def L1Loss(input, target, **kwargs):
return F.l1_loss(input, target)
def MSELoss(input, target, **kwargs):
check_nan_inf(input)
check_nan_inf(target)
r... | 351 | 134 |
import flask
import psycopg2
import json
from ..authenticated_blueprint_preparator import AuthenticatedBlueprintPreparator
import werkzeug.exceptions
from .user_action import add_user_action
from .decorators import rest_endpoint
name = 'person'
app = AuthenticatedBlueprintPreparator(name, __name__, template_folder=... | 5,175 | 1,671 |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 28 01:14:13 2020
@author: ghanta
"""
import webbrowser
webbrowser.open('http://localhost:1000/CrimeReport/addtodb') | 165 | 80 |
#!/usr/bin/python3
import struct
import sys
if len(sys.argv) < 2:
sys.stderr.write("Usage: <hex>\n")
sys.stderr.flush()
exit(1)
CHUNKSIZE = 4
hex_data = []
hex_string = ""
for i in sys.argv[1:]:
hex_string += i.replace("0x", "")
while len(hex_string) >= CHUNKSIZE:
hex_data.append(hex_string[... | 715 | 295 |
#!/usr/bin/python
"""Submodules for supporting judge systems.
"""
| 67 | 22 |
#!/usr/bin/env python3
# Copia files nel .bak
# Serve per controllare i files
import os
# Serve per il formato dati, il file di configurazione e`
# in struttura "json"
import json
# Serve per la parte di gestione html in python
import cgi
import cgitb
import time
# Abilita gli errori al server web/http
cgitb.enabl... | 2,614 | 945 |
import argparse
import os
import lpips
import torch
from tqdm import tqdm
if __name__ == "__main__":
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-d0','--dir0', type=str, default='~/DDPM/stylegan2-pytorch/datasets/CelebA-HQ-img/')
parser.add_a... | 1,898 | 731 |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... | 2,843 | 739 |
import time
from selenium import webdriver
# 仮想ブラウザ起動、URL先のサイトにアクセス
driver = webdriver.Chrome()
driver.get('https://www.google.com/')
time.sleep(2)
# サイト内から検索フォームを探す。
# Googleでは検索フォームのNameが「q」です。
el = driver.find_element_by_name("q")
# 検索フォームに文字を入力
el.send_keys('Qiitaで記事投稿楽しいぞ!!!')
time.sleep(2)
# 検索フォーム送信(Enter)
el... | 467 | 255 |
# Standard Library Imports
# None
# 3rd-Party Imports
from mongoengine import Document
# App-Local Imports
from app.models.product import Product
class Base(Document):
pass
| 181 | 55 |
"""
Utilities related to timezones
"""
from datetime import datetime
from pytz import common_timezones, timezone, utc
def _format_time_zone_string(time_zone, date_time, format_string):
"""
Returns a string, specified by format string, of the current date/time of the time zone.
:param time_zone: Pytz ti... | 1,737 | 606 |
"""
Designed and Developed by-
Udayraj Deshmukh
https://github.com/Udayraj123
"""
# In[62]:
import re
import os
import sys
import cv2
import glob
import argparse
from time import localtime,strftime,time
from random import randint
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import imutils ... | 12,049 | 3,973 |
# Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
import tempfile
import zipfile
import mmcv
import numpy as np
from mmcv.utils import print_log
from mmdet.datasets import DATASETS
from mmtrack.core import results2outs
from .coco_video_dataset import CocoVideoDataset
@DATASETS.register_module()
... | 6,354 | 1,865 |
# from argparse_prompt import PromptParser
import argparse
import code
import getpass
from web3 import Web3
from theo.version import __version__
from theo.scanner import exploits_from_mythril
from theo.file import exploits_from_file
from theo import *
def main():
parser = argparse.ArgumentParser(
descript... | 4,551 | 1,430 |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | 6,026 | 1,747 |
import os
from core.utils.command_helpers import (
CommandUpload,
)
from forecast.import_actuals import upload_trial_balance_report
from upload_file.models import FileUpload
class Command(CommandUpload):
help = "Upload the Trial Balance for a specific month"
def add_arguments(self, parser):
pa... | 1,148 | 336 |
"""Generalized half-logistic distribution."""
import numpy
from scipy import special
from ..baseclass import Dist
from ..operators.addition import Add
from .deprecate import deprecation_warning
class generalized_half_logistic(Dist):
"""Generalized half-logistic distribution."""
def __init__(self, c=1):
... | 2,070 | 777 |
import asyncio
from typing import Optional
from tests import APITestCase, MAINNET_WS_URI, WEBSOCKET_TIMEOUT_GET_REQUEST
from tradehub.websocket_client import DemexWebsocket
class TestWSGetRecentTrades(APITestCase):
def test_get_recent_trades_structure(self):
"""
Check if response match expected ... | 2,343 | 623 |
#!/usr/bin/python
import sys
import os
import sqlite3
import commands
sys.path.append("../../src/")
import cxxtags_util as cxxtags
sys.path.append("../util/")
import clang.cindex # for kind types
import common as test_util
err = 0
#test_util.DebugOn()
if len(sys.argv) != 2:
print "usage: cmd db_file"
exit(1)... | 9,175 | 4,407 |
#! /usr/bin/env python
# Author: Srinivasa Rao Zinka (srinivas . zinka [at] gmail . com)
# Copyright (c) 2014 Srinivasa Rao Zinka
# License: New BSD License.
import numpy as np
import matplotlib.pyplot as plt
from scipy import special as sp
from scipy import optimize
a = 111e-3
b = 74e-3
e = np.sqrt(1 - b ** 2 / a... | 1,466 | 730 |
# Copyright (C) 2013 Lindley Graham
"""
This subpackage contains
* :class:`domain` a container object for a data specific to a particular
mesh(es), grid(s)
* :mod:`~polyadcirc.run_framework.random_manningsn` a class and associated set
of methods to run a set of ADCIRC simulations with varying parameters
"""
__a... | 428 | 139 |
from app.models.usuario_dao import Usuario
class Proprietario(Usuario):
def __init__(self, cpf, nome, data_de_nascimento, sexo, fk_endereco, fk_login):
super().__init__(cpf, nome, data_de_nascimento, sexo, fk_endereco, fk_login)
# Proprietario Padrao Data Access Object
class ProprietarioDAO:
def __ini... | 2,483 | 826 |
from .Population import Population as Population
from .Genome import Genome as Genome
from .operadores.CurrentToRand import CurrentToRand as Mutation
from .operadores.Arithmetic import Arithmetic as Crossover
from .operadores.Uniform import Uniform as Selection
from .operadores.Elitist import Elitist as Replacement
imp... | 2,398 | 683 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This is a temp script
'''
# Console colors
W = '\033[0m' # white (normal)
R = '\033[31m' # red
G = '\033[32m' # green
O = '\033[33m' # orange
B = '\033[34m' # blue
P = '\033[35m' # purple
C = '\033[36m' # cyan
GR = '\033[37m' # gray
print G + "hello" + W
prin... | 376 | 195 |
import json
from django.core.management.base import BaseCommand
from django.db import connection, transaction
import amo
from addons.models import Webapp
from files.models import File
from versions.models import Version
class Command(BaseCommand):
help = 'Collapse versions for hosted apps'
def handle(self,... | 9,041 | 2,277 |
import selfcord as discord
from selfcord.ext import commands
import time
from cli import check
"""
This is an example cog of basic ping command.
You can create more commands in this folder.
Don't forget to add them in config file (eg. commands.Ban).
"""
class Ping(commands.Cog):
def __init__(self, client):
... | 1,075 | 343 |
from MBSTOI.stft import stft
from MBSTOI.thirdoct import thirdoct
from MBSTOI.remove_silent_frames import remove_silent_frames
from MBSTOI.mbstoi import mbstoi
from MBSTOI.ec import ec
from MBSTOI.ec_dbstoi import ec_dbstoi
from MBSTOI.mbstoi_beta import mbstoi_beta, create_internal_noise
__all__ = [
"stf... | 468 | 193 |
#!/usr/bin/python
import pylinux.pylinux as pylinux
## Static Information
print 'Distribution:: ', pylinux.distro_name() + ' ' + \
pylinux.distro_release() + ' ' + \
pylinux.distro_nickname()
print 'OS Architecture:: ' + pylinux.arch()
print 'Kernel:: ', pylinux.kernel()
print 'Total Memory:: ' + pylinux.to... | 1,426 | 489 |
import os
import tempfile
from configparser import ConfigParser
from typing import Generator
from unittest.mock import patch
import pytest
from eqcharinfo import route_handler
from eqcharinfo.controllers import CharacterClient
from eqcharinfo.controllers import CharfileIngest
from eqcharinfo.controllers import LucyIt... | 3,804 | 1,109 |
import datetime
import sys
import threading
from types import MethodType
from django.db import models
from django.utils import timezone
from lock_tokens.settings import TIMEOUT
LESS_THAN_PYTHON3 = sys.version_info[0] < 3
def get_oldest_valid_tokens_datetime():
return timezone.now() - datetime.timedelta(seconds... | 2,358 | 703 |
# 增删改查,insert,pop
# 方法:list(p), + , in,enumerate
# append 和 extend
# list.index(obj),sort
# 浅复制 和 深度复制
# 倒序删除
import copy
# pytest -vs .\cainiao1\test_list.py
def test_1():
# 增删改查,增和删
list1 = ['a', 'b', 'c']
list1.append('d')
assert ['a', 'b', 'c', 'd'] == list1, 'append error'
del list1[0]
... | 4,367 | 2,043 |
from __future__ import absolute_import
# import apis into api package
from .fake_api import FakeApi
| 101 | 31 |
from __future__ import division
import itertools
import numpy as np
from six.moves import zip
from bokeh.plotting import ColumnDataSource, figure, show, output_file
from bokeh.models import TapTool
xx, yy = np.meshgrid(range(0,101,4), range(0,101,4))
x = xx.flatten()
y = yy.flatten()
N = len(x)
inds = [str(i) for i ... | 1,258 | 517 |
import re
health_pattern = r"[^\d+\.\*\+/-]"
nums_pattern = r"(?P<nums>[+|-]?\d+(\.\d+)?)"
multiply_divide_pattern = r"[\*/]"
demons_info = [demon.strip() for demon in input().split(",")]
for demon in sorted(demons_info):
nums = []
health = 0
damage = 0
for char in re.findall(health_pattern, demon):... | 678 | 259 |
"""
init.py
Starting script to run NetPyNE-based model.
Usage: python init.py # Run simulation, optionally plot a raster
MPI usage: mpiexec -n 4 nrniv -python -mpi init.py
Contributors: salvadordura@gmail.com
"""
from netpyne import sim
cfg, netParams = sim.readCmdLineArgs() # read cfg and netParams from c... | 409 | 145 |
from typing import List, TextIO
class PuzzleInputParser(object):
"""
Parser for puzzle state where two input types exist
1. Dictionary like formatted input
2. Plain text input format
"""
HEURISTIC_LABEL = 'heuristic_function'
ROW_LABEL = 'row'
COLUMN_LABEL = 'column'
BLOCKS_LABEL ... | 2,672 | 826 |
#!/usr/bin/env python
import re
match = re.match('Hello[ \t].(.*)world', 'Hello Python world')
print match.group(1)
| 120 | 43 |
"""
Continuous interactions
=======================
"""
import numpy as np
import pandas as pd
import seaborn as sns
sns.set(style="darkgrid")
rs = np.random.RandomState(11)
n = 80
x1 = rs.randn(n)
x2 = x1 / 5 + rs.randn(n)
b0, b1, b2, b3 = .5, .25, -1, 2
y = b0 + b1 * x1 + b2 * x2 + b3 * x1 * x2 + rs.randn(n)
df ... | 419 | 209 |
import requests
def request(url):
try:
#requests.request("GET")
return requests.get("http://" + url)
except requests.exceptions.HTTPError:
pass
target_url = "google.com"
with open("subdomain-wordlist.txt", "r") as wordlist:
for line in wordlist:
stripped_line = line.strip... | 520 | 167 |
from functools import wraps
from flask import g, request
from binascii import hexlify
import os
import logging
_log = logging.getLogger(__name__)
debug = False
b3_trace_id = 'X-B3-TraceId'
b3_parent_span_id = 'X-B3-ParentSpanId'
b3_span_id = 'X-B3-SpanId'
b3_sampled = 'X-B3-Sampled'
b3_flags = 'X-B3-Flags'
b3_heade... | 9,058 | 2,770 |
"""
Functions for staging tables from CSVs to the Postgres database.
Used by /ferry/stage.py.
"""
import csv
from io import StringIO
import pandas as pd
class DatabaseStagingError(Exception):
"""
Object for import exceptions.
"""
# pylint: disable=unnecessary-pass
pass
def copy_from_stringio(... | 1,310 | 405 |
from example_player.player import ExamplePlayer as Player | 57 | 12 |
from typing import List
from unittest.mock import MagicMock
import pytest
from pytest_mock import MockFixture
from questionary import Question
from create_github_project.commands.init.parameters.select import Select
class TestSelect:
@pytest.fixture(autouse=True)
def question(self, mocker: MockFixture) -> ... | 1,498 | 439 |
# -*- encoding: UTF-8 -*-
from __future__ import absolute_import, unicode_literals
from mongorest.errors import PyMongoError
from mongorest.testcase import TestCase
class TestPyMongoError(TestCase):
def test_pymongo_error_sets_correct_fields(self):
self.assertEqual(
PyMongoError('error_messa... | 648 | 183 |
def swap_case(s):
string = ""
for i in s:
if i >= 'a' and i <= 'z':
i = i.upper()
elif i >= 'A' and i <= 'Z':
i = i.lower()
string += i
return string
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result) | 297 | 107 |
from __future__ import absolute_import, print_function
from django.core.urlresolvers import reverse
from django.db import transaction
from django.views.decorators.cache import never_cache
from django.contrib import messages
from sentry.auth.helper import AuthHelper
from sentry.constants import WARN_SESSION_EXPIRED
fr... | 2,674 | 687 |
"""
Created on July 2021
@author: Nadia Brancati
"""
import torch.nn.functional as F
from min_max_layer import *
class AttentionModel(nn.Module):
def __init__(self,num_classes,filters_out,filters_in,dropout,device):
super(AttentionModel, self).__init__()
self.filters_out=filters_out
self.... | 2,485 | 882 |
import requests
from bs4 import BeautifulSoup
url = 'http://tieba.baidu.com/p/4178314700'
def GetHtml(url):
html = requests.get(url).text
return html
def GetImg(html):
soup = BeautifulSoup(html, 'html.parser')
imglist = []
for photourl in soup.find_all('img'):
imglist.app... | 587 | 237 |
values = {" ": "%50", "%20": "%50", "SELECT": "HAVING", "AND":
"&&", "OR": "||"}
originalstring = "' UNION SELECT * FROM Users WHERE username ='admin' \
OR 1=1 AND username = 'admin';#" #could be set to sys.argv[1]
for item in values :
if item in originalstring :
originalstring = originalstring.replace(item,value... | 370 | 128 |
from JumpScale import j
import os
import importlib
def find_model_specs(basepath):
modelbasepath = os.path.join(basepath, 'models', 'osis')
fullspecs = dict()
for type_ in ('mongo', 'sql'):
modelpath = os.path.join(modelbasepath, type_)
specs = dict()
if os.path.exists(modelpath):
... | 1,620 | 460 |
import cv2
import numpy as np
import matplotlib.pyplot as plt
# histogram manipulation
def hist_mani(img, m0=128, s0=52):
m = np.mean(img)
s = np.std(img)
out = img.copy()
# normalize
out = s0 / s * (out - m) + m0
out[out < 0] = 0
out[out > 255] = 255
out = out.astype(np.uint8)
... | 650 | 293 |
import os
import pandas as pd
# from entity_embeddings.network.assembler import ModelAssembler
# from entity_embeddings.processor.processor import TargetProcessor
from entity_embeddings.network import ModelAssembler
from entity_embeddings.processor.processor import TargetProcessor
def check_csv_data(csv_path: str) ... | 2,132 | 605 |
from pathlib import Path
from configurations import Configuration
import environ
env = environ.Env()
environ.Env.read_env(env.str('ENV_PATH', '../.env'))
BASE_DIR = Path(__file__).resolve().parent.parent
class Development(Configuration):
# ---------------------
# Host
# ---------------------
SECRET_... | 4,168 | 1,410 |
import datetime
import pandas as pd
import matplotlib.pyplot as plt
import plotly.express as px
plt.style.use("bmh")
plt.rcParams['axes.facecolor'] = 'white'
plt.rcParams['axes.grid'] = False
plt.rcParams['axes.spines.right'] = False
plt.rcParams['axes.spines.top'] = False
class CompartmentStates(pd.DataFrame):
d... | 4,734 | 1,461 |
# Copyright (c) 2020 The Khronos Group 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 ... | 2,425 | 740 |
# Generated by Django 3.2.6 on 2021-08-24 06:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('processes', '0154_task_aws_ecs_service_tags'),
]
operations = [
migrations.AlterField(
model_name='task',
... | 1,586 | 480 |