index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
3,700 | 816f4cfe98f5e5b23f2c8f9f42c5f3ed8458042f | #!/usr/bin/python
import platform
from numpy import ctypeslib,empty,array,exp,ascontiguousarray,zeros,asfortranarray
from ctypes import c_float,c_double,c_int
from time import time
def resize(img,scale):
"""
downsample img to scale
"""
sdims=img.shape
datatype=c_double
if img.dtype!=data... |
3,701 | 3089dba0956151bd43e443b679ec0b24da644d08 | import random
s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+=-/.,;'[]{}:<>?"
i = 0
fin = ""
while i == 0:
num = int(input("What length do you want? "))
password = "".join(random.sample(s, num))
print(password)
j = 0
while(j ==0):
want = input("Do you this ... |
3,702 | bc8bf06f1adedeb7b364308591bff09ac42d6c29 | from .dataset_readers import *
from .models import * |
3,703 | 1a09b38838f40c4c6049da8e6a72ba3d56806c07 | import tensorflow as tf
def data_rescale(x):
return tf.subtract(tf.divide(x, 127.5), 1)
def inverse_rescale(y):
return tf.round(tf.multiply(tf.add(y, 1), 127.5))
|
3,704 | b6dc29ae5661f84273ff91a124420bc10c7b6f6e | from .candles import CandleCallback
from .firestore import FirestoreTradeCallback
from .gcppubsub import GCPPubSubTradeCallback
from .thresh import ThreshCallback
from .trades import (
NonSequentialIntegerTradeCallback,
SequentialIntegerTradeCallback,
TradeCallback,
)
__all__ = [
"FirestoreTradeCallbac... |
3,705 | 224e13331ad93278f47a5582bbd24208d9ce5dcc | array = [1,2,3,4,5]
for x in array:
print (x)
|
3,706 | e4761c925643417f4fe906e8dd2c9356ae970d52 | # encoding = utf-8
"""
A flask session memcached store
"""
from datetime import timedelta, datetime
from uuid import uuid4
__author__ = 'zou'
import memcache
import pickle
from flask.sessions import SessionMixin, SessionInterface
from werkzeug.datastructures import CallbackDict
class MemcachedSession(CallbackDict, S... |
3,707 | 1adaca88cf41d4e4d3a55996022278102887be07 | from functools import wraps
from flask import request, abort
# Apply Aspect Oriented Programming to server routes using roles
# e.g. we want to specify the role, perhaps supplied
# by the request or a jwt token, using a decorator
# to abstract away the authorization
# possible decorator implementation
def roles_requ... |
3,708 | ce69f7b7cf8c38845bfe589c83fdd6e43ab50912 | #
# Copyright 2016 The BigDL 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 ... |
3,709 | 5430e1861a6244c25c00699323efa0921a5af940 | import grpc
import time
import json
import sys
import uuid
from arch.api.proto import inference_service_pb2
from arch.api.proto import inference_service_pb2_grpc
import threading
def run(address):
ths = []
with grpc.insecure_channel(address) as channel:
for i in range(1):
th = threading.T... |
3,710 | bb198978ffc799bb43acf870467496e1dcc54d4b | # template for "Stopwatch: The Game"
import math
import simplegui
# define global variables
successcount = 0;
totalstopcount = 0;
count = 0;
T = True;
F = True;
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
A = str(t // 600);
tem = (t /... |
3,711 | a5856e12c281ed6a252f499a380f9c51082ea740 | import os
import closet
import unittest
import tempfile
def in_response(response, value):
return value.encode() in response.data
def is_404(response):
response.status_code == 404
class ClosetTestBase(unittest.TestCase):
def setUp(self):
"""Set up test environment befor each test"""
se... |
3,712 | 05764d1cfd9573616fcd6b125280fddf2e5ce7ad | from collections import Counter, defaultdict
from random import randrange
from copy import deepcopy
import sys
def election(votes, message=True, force_forward=False):
votes = deepcopy(votes)
N = len(votes)
for i in range(N):
obtained = Counter([v[-1] for v in votes if len(v)]).most_common()
... |
3,713 | 67de51e2a176907fd89793bd3ec52f898130e104 | from django.shortcuts import render,redirect
from django.contrib.auth.decorators import login_required
from .form import UserForm, ProfileForm, PostForm
from django.contrib import messages
from .models import Profile, Projects
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
# ... |
3,714 | 02ddf213cd3f455f8d8fbde8621fc4788124d5a9 | from django.db import models
class Building(models.Model):
Number = models.CharField(max_length=60)
Description = models.CharField(max_length=120)
OSMWAYID = models.DecimalField(decimal_places=0, max_digits=15) # the osm way id
Lat = models.CharField(max_length=20) #lat/lon of then center
Lon = m... |
3,715 | 3a5c8ee49c50820cea201c088acca32e018c1501 | """
BCXYZ company has up to
employees.
The company decides to create a unique identification number (UID) for each of its employees.
The company has assigned you the task of validating all the randomly generated UIDs.
A valid UID must follow the rules below:
It must contain at least 2 uppercase English alphabet chara... |
3,716 | 9a665d126d7b48adbd876b48c3d8806eabea1108 | from .entity import EventBase, event_class
from .. import LOG as _LOG
LOG = _LOG.getChild('entity.event')
@event_class()
class FunctionCallEvent(EventBase):
"""
function call
"""
deferred = True
def parse_jsondict(self, jsdict):
assert 'func_name' in jsdict['option'], 'func_name required'
... |
3,717 | e6851e86fa86ab2096f059218b2b8a2994642807 | """
You have a map that marks the locations of treasure islands. Some of the map area has jagged rocks and dangerous reefs.
Other areas are safe to sail in. There are other explorers trying to find the treasure.
So you must figure out a shortest route to one of the treasure islands.
Assume the map area is a two dimens... |
3,718 | bed3d83f682404719a95be360cdd74be9dc87991 | # coding: utf-8
BOT_NAME = ['lg']
SPIDER_MODULES = ['lg.spiders']
NEWSPIDER_MODULE = 'lg.spiders'
DOWNLOAD_DELAY = 0.1 # 间隔时间
LOG_LEVEL = 'WARNING'
|
3,719 | 0345c3c2049c972370cd7bde5a6e0a1dfa5dfe66 | __path__.append('/cvmfs/cms.cern.ch/slc6_amd64_gcc481/cms/cmssw-patch/CMSSW_7_0_6_patch3/python/ggAnalysis')
|
3,720 | ff65e92699c6c9379ac40397b3318c3f6bf7d49a | # coding=UTF-8
from unittest import TestCase
from fwk.util.rect import Rect
class RectSizeTest(TestCase):
def test_sizes_from_coords(self):
rect = Rect(top=33,bottom=22,left=10,right=20)
self.assertEqual(rect.width,10)
self.assertEqual(rect.height,11)
def test_sizes_from_sizes(self):
rect = Rect(top=23,hei... |
3,721 | 612a3d168a09fc26530b95d258cbb4de6728419d | #!/usr/bin/env python
import psycopg2
DBNAME = "news"
query1 = """
select title, count(*) as numOfViews from articles,log
where concat('/article/', articles.slug) = log.path
group by title order by numOfViews desc limit 3;
"""
query2 = """
select authors.name, count(*) as numOfViews
from articles, authors, log
where... |
3,722 | 124ece8f2f4ecc53d19657e2463cc608befb1ce7 | from rest_framework import serializers
from users.models import bills, Userinfo
class billsSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = bills
fields = ('bname', 'bamount', 'duedate', 'user_id')
class UserinfoSerializer(serializers.HyperlinkedModelSerializer):
class ... |
3,723 | bc8d3a5e3ed845b4ab2d203bec47881be64ba3f8 | import discord
from discord.ext import commands
from os import path
import os
import datetime as dt
import numpy as np
import math
# client = commands.Bot(command_prefix = '.', case_insensitive=True)
# UTOPIA = 679921845671035034
# DEV_BOT_TOKEN = 'NzUzMzg1MjE1MTAzMzM2NTg4.X1laqA.vKvoV8Gz9jBWDWvIaBGDC4xbLB4'
# BO... |
3,724 | 45b20b57a3579c2527c674d0c2af88eedddadcae | from LinkedList import LinkedList
from LinkedListHelper import CreateLinkedList
class LinkedListMod(LinkedList):
def remove_allnode(self):
while self.head:
temp = self.head
self.head = self.head.next
del temp
def main():
l1 = LinkedListMod()
CreateLinkedList(l1)
... |
3,725 | c860c1fa6e7610c60077f0eab1572895a23393fd | #!/usr/bin/python
# Copyright (c) 2020 Maryushi3
import emoji_data_python as edp
import sys
import pyautogui
from Xlib import display
from PyQt5.QtWidgets import QApplication, QGridLayout, QLabel, QLineEdit, QScrollArea, QSizePolicy, QStackedLayout, QVBoxLayout, QWidget
from PyQt5.QtCore import QEvent, QSettings, Qt, ... |
3,726 | 1685a2c49bea14e6fcaffb03634f6875f8fa1049 | # encoding:utf-8
import tensorflow as tf
import p182.py as p182
# 创建文件列表,并通过文件列表创建输入文件队列。在调用输入数据处理流程前,需要
# 统一所有原始数据的格式并将它们存储到TFRcord文件中。下面给出的文件列表应该包含所
# 有提供训练数据的TFRcord文件
files = tf.train.match_filenames_once("/home/shenxj/tf-work/datasets/file_pattern-*")
filename_queue = tf.train.string_input_producer(files, shuffle=... |
3,727 | f0c621583caf6eea6f790649862a03a464f6574b | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import csv
from bookstoscrapy import settings
def write_to_csv(item):
writer = csv.writer(open(settings.csv_file_path, '... |
3,728 | 4fea9941defd6703be3cae034d979933262074e3 | with open("out.txt", "w", encoding = "utf_8") as file:
file.write("明日の天気です∖n")
file.write("関西地方はおおむね晴れ.")
file.write("紅葉を見るには絶好の日和でしょう∖n")
file.write(“映像は嵐山の様子です.")
file.write("今年も大変な数の観光客が訪れているようですね.∖n")
|
3,729 | c3967ab15b8278d958fa5ff6ff48bbfb0b086238 | """
app_dist_Tables00.py illustrates use of pitaxcalc-demo release 2.0.0
(India version).
USAGE: python app_dist_Tables00.py
"""
import pandas as pd
from taxcalc import *
import numpy as np
from babel.numbers import format_currency
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
... |
3,730 | d9f66cc3ba40292c49da08d7573d4c605a2771ae | def solution(record):
answer = []
arr = dict()
history = []
for i in record:
tmp = i.split()
if tmp[0] == "Enter" :
arr[tmp[1]] = tmp[2]
history.append([tmp[1], "님이 들어왔습니다."])
elif tmp[0] == "Leave" :
history.append([tmp[1], "님이 나갔습니다."])
... |
3,731 | 676ccbac9385a4b63d599c3f85f16e28d839e9b8 | import pysftp
import time
import threading
def sftp_connection():
while True:
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
try:
with pysftp.Connection('sb-emea.avl.com', username='abhishek.hingwasia@avl.com', password='AvlAvl2931!!',
... |
3,732 | f61e9e8069a0e90506c2f03a0cc4a25a16d71b85 | import pytest
import numpy as np
from dwave_qbsolv import QBSolv
from src.quantumrouting.solvers import partitionqubo
from src.quantumrouting.types import CVRPProblem
from src.quantumrouting.wrappers.qubo import wrap_vrp_qubo_problem
@pytest.fixture
def cvrp_problem():
max_num_vehicles = 1
coords = [
... |
3,733 | 9b4bc7f8f9c96f503a5ed79827430963e21718c4 | from django.conf.urls import url
from .views import LoginView, logout_user, delete_user
from .views import NewUserView
urlpatterns = [
url(r'newuser/', NewUserView.as_view(), name='newuser'),
url(r'login/', LoginView.as_view(), name='login'),
url(r'logout/', logout_user, name='logout'),
url(r'delete/$'... |
3,734 | 0eefae7e0d341d74154bbe480f5ed766829e3ce3 | import os
import h5py
import numpy as np
from keras import backend as K
from keras.layers import Activation, BatchNormalization, Conv2D, Dense, Dot, \
Dropout, Flatten, Input, MaxPooling2D, GlobalAveragePooling2D
from keras import regularizers
from keras.layers import Average as KerasAverage
from keras.models imp... |
3,735 | 2e041e33b5c34c2bddc72b36ff641817f1e21db2 | TTTSIZE = 4
def who_win_line(line):
elements = set(line)
if '.' in elements:
return '.'
elements.discard('T')
if len(elements) >= 2:
return 'D'
else:
return elements.pop()
def who_win_tic_tac_toe(original_rows):
#print('%s' % repr(original_rows))
board... |
3,736 | 87baaf4a1b48fa248c65d26cc44e819a2ede1140 | # Python library import
import asyncio, asyncssh, logging
# Module logging logger
log = logging.getLogger(__package__)
# Debug level
# logging.basicConfig(level=logging.WARNING)
# logging.basicConfig(level=logging.INFO)
logging.basicConfig(level=logging.DEBUG)
asyncssh.set_debug_level(2)
# Declaration of constant v... |
3,737 | 03d07f5f4647e904c288e828b8f8e7de35740054 | #!/usr/bin/env python
import errno
import logging
import os
import re
import sys
import argparse
def parse_map(map_str):
file_map = []
for line in map_str.split('\n'):
if not line:
continue
find, replace = line.split(' -- ', 1)
file_map.append((find, replace))
return f... |
3,738 | f614287a2a118484b67f2b16e429a3335416d186 | # Copyright (c) 2008 Johns Hopkins University.
# All rights reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose, without fee, and without written
# agreement is hereby granted, provided that the above copyright
# notice, the (updated) modification history ... |
3,739 | 9140da0b6c04f39a987a177d56321c56c01586e8 | import torch
import torch.nn as nn
import torch.nn.functional as F
class Encoder(nn.Module):
def __init__(self):
super(Encoder, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=5, stride=1)
self.bn1 = nn.BatchNorm2d(32)
self.conv2 = nn.Conv2d(32, 48, kernel_size=5, stride... |
3,740 | 5cb67e5fcedafca4ce124e4094cbd8e1e9d95bb4 | import logging
from unittest.mock import patch, Mock
from intake.tests.base_testcases import ExternalNotificationsPatchTestCase
from intake.tests import mock, factories
from intake.tests.mock_org_answers import get_answers_for_orgs
from intake.management.commands import send_followups
from user_accounts.models import O... |
3,741 | f0630d248cfa575ee859e5c441deeb01b68c8150 | # import sys
# class PriorityQueue:
# """Array-based priority queue implementation."""
#
# def __init__(self):
# """Initially empty priority queue."""
# self.queue = []
# self.min_index = None
# self.heap_size = 0
#
# def __len__(self):
# # Number of elements in the q... |
3,742 | f012f862ad064fc168bd5328b97c433164a3a36f | #from skimage import measure
#from svmutil import *
import cv2
import numpy as np
def inside(r, q):
rx, ry, rw, rh = r
qx, qy, qw, qh = q
return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh
def draw_detections(img, rects, thickness = 1):
for x, y, w, h in rects:
# the HOG detector returns ... |
3,743 | 830ae4b6a6b2c4e1bbe6928b3a4b0be86d2ec7a3 | """
This module contains the class definitions for all types of BankAccount
alongside BankAccountCreator as a supporting class to create an
appropriate bank account for a given user type.
"""
from abc import ABC
from abc import abstractmethod
from transaction import Transaction
from budget import Budget
from budget im... |
3,744 | 5d9afef2a748782659b82b329ea08d5815162cbc | # 作者:西岛闲鱼
# https://github.com/globien/easy-python
# https://gitee.com/globien/easy-python
# 用蒙特卡洛法计算圆周率,即,往一个正方形里扔豆子,计算有多少比例的豆子扔在了该正方形的内切圆中
import random
num_all = 0 #随机点总计数器
num_cir = 0 #随机点在圆内的计数器
num_halt = 10000000 #每产生这么多个随机点后,计算并打印一次目前的结果
print("将进行无限计算,请用Ctrl_C或其他方式强制退出!!!")
input("按回车(Enter... |
3,745 | 66c71111eae27f6e9fee84eef05cc1f44cc5a477 | from setuptools import setup
from Cython.Build import cythonize
setup(
ext_modules=cythonize("utils.pyx"),
) |
3,746 | 7399612f64eb8e500bc676e6d507be5fe375f40f | #!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Create the RenderWindow, Renderer and both Actors
#
ren1 = vtk.vtkRenderer()
ren2 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.SetMultiSamples(0)
renWin.AddRenderer(ren1)
renWin.AddRenderer(ren2)
i... |
3,747 | 8114d8162bab625854804d1df2b4a9c11818d35e | def somaSerie(valor):
soma = 0
for i in range(valor):
soma += ((i**2)+1)/(i+3)
return soma
a = int(input("Digite o 1º Numero :-> "))
result = somaSerie(a)
print(result) |
3,748 | 6b0081e829f9252e44fa7b81fbfcdd4115856373 | import sys
n = int(sys.stdin.readline().rstrip())
l = list(map(int,sys.stdin.readline().rstrip().split()))
m = int(sys.stdin.readline().rstrip())
v = list(map(int,sys.stdin.readline().rstrip().split()))
card = [0] * (max(l)-min(l)+1)
a = min(l)
b = max(l)
for i in l:
card[i-a]+=1
for j in v:
if ((j>=a)&(j<... |
3,749 | e3119979028d3dd4e1061563db4ec20607e744d1 | #! /usr/bin/python
from bs4 import BeautifulSoup
import requests
import sys
def exit(err):
print err
sys.exit(0)
def get_text(node, lower = True):
if lower:
return (''.join(node.findAll(text = True))).strip().lower()
return (''.join(node.findAll(text = True))).strip()
def get_method_signatu... |
3,750 | a4ccf373695b7df60039bc8f6440a6ad43d265c1 | # coding: utf-8
"""
MailSlurp API
MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more. ## Resources - [Homepage](https://ww... |
3,751 | 559bd0c1821f405d21cdacba55f129ee5220bb5d | import os
from django.conf import settings
from chamber.importers import BulkCSVImporter, CSVImporter
from .models import CSVRecord
class BulkCSVRecordImporter(BulkCSVImporter):
model_class = CSVRecord
fields = ('id', 'name', 'number')
csv_path = os.path.join(settings.PROJECT_DIR, 'data', 'all_fields_f... |
3,752 | 17ba6aaa9009c258136b184ca6a8660cec1cfe40 | from robot.libraries.BuiltIn import BuiltIn
from RoboGalaxyLibrary.utilitylib import logging as logger
import re
def block_no_keyword_warn():
pass
class Compare_hpMCTP(object):
def __init__(self):
self.fusionlib = BuiltIn().get_library_instance('FusionLibrary')
def do(self, expect, actual, ver... |
3,753 | e08b7a96c957895068e584a0564f02c52acd48ec | from django.apps import AppConfig
class AdminrequestsConfig(AppConfig):
name = 'adminRequests'
|
3,754 | 1b7b94a0331e2462f83f4f77bcfaefbeefdf24f4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 29 20:33:32 2013
@author: ste
"""
#Convert input file for graph from adjacency list version, where each line is
#vertex adjacent adjacent adjacent ...
#to edge representation where each line is
#tail head
edges=[]
with open("/Users/ste/Desktop/Ste/Python/AlgorithmsCours... |
3,755 | d00fa29c502cc0311c54deb657b37c3c3caac7ca | import pygame
import pygame.freetype
import sys
import sqlite3
from data.player_class import Player
from data.explosion_class import Explosion
from data.objects_class import Bullets, Damage
from data.enemy_class import Enemy
from data.enemy_class import Boss
from data.death_animation import Smallexplosions
from data.ex... |
3,756 | 6d359d987c50fd0d5e963d467a379eb245e3eb40 | import cv2 as cv
'''色彩空间介绍'''
'''
RGB:对于RGB的色彩空间是立方体的色彩空间 三通道 红 黄 蓝 每个灰度级为255
HSV:对于HSV的色彩空间是255度的圆柱体 三通道 高度 圆心角 半径分别是255
HIS
YCrCb
YUV
'''
'''常用的色彩空间转换函数***cvtColor'''
def colorSpaceConvert(image):
'''转换到灰度空间'''
res = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
cv.imshow("gray", res)
'''转换到HSV色彩空间'''
r... |
3,757 | 8c0bae9e49c5ea9fbdee7c5c864afff16cc9f8b8 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import linear_model
from features import calculateTargets
currency = 'EURUSD'
interval = '1440'
df = pd.read_csv(
r'../data/' + currency.upper() + interval + '.csv',
names=['date', 'time', 'open', 'high', 'low', 'close', 'volu... |
3,758 | 62bc8fec6833c5e8bc1598941eaad141ab6c9d5a | #
# -*- coding: utf-8 -*-
# Copyright 2019 Fortinet, Inc.
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
"""
The fortios firewall monitor class
It is in this file the runtime information is collected from the device
for a given resource, parsed, and the facts tree is popu... |
3,759 | 18e0ece7c38169d2de91a07dddd4f40b7427848f | # 4. Пользователь вводит целое положительное число.
# Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции.
income_number = int(input('Введите, пожалуйста, целое положительное число '))
max_number = 0
# в другую сторону решение, не так как Вы на вебинаре советовали, но тож... |
3,760 | a6d409b806dbd1e174cac65a26c5e8106a8b93ea | #!/usr/bin/env python3
"""Initiates connection to AWSIoT and provides helper functions
deviceshadowhandler.py
by Darren Dunford
"""
import json
import logging
import queue
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient
LOGGER = logging.getLogger(__name__)
class DeviceShadowHandler:
def status_pos... |
3,761 | 65b5db0bc6f23c342138060b7a006ff61e2dcf45 | # -*- coding: utf-8 -*-
"""Test(s) for static files
:copyright: Copyright (c) 2019 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
import pytest
import os
_TEST_ID = '__NO_SUCH_STRING_IN_PAGE__'
def s... |
3,762 | e75fb023e2e3d3fd258a316a6827b2601c9f4b2d | from selenium import selenium
class SharedSeleniumExecutionContext:
host =None
port =None
browserStartCommand =None
url = None
seleniumInstance=None
isInitialized=False
lastVisitedLocation=None
optionBeingHandled=None
itemToDrag=None
def __init__(self, host, port, brow... |
3,763 | da751e96c225ebc2d30f3cce01ba2f64d0a29257 | # Chris DeBoever
# cdeboeve@ucsd.edu
import sys, argparse, pdb, glob, os, re
import numpy as np
from bisect import bisect_left
from scipy.stats import binom
### helper functions ###
def find_lt(a,x):
"""
Find rightmost value less than x in list a
Input: list a and value x
Output: rightmost value les... |
3,764 | 98bc6e0552991d7de1cc29a02242b25e7919ef82 | # Generated by Django 3.0.4 on 2020-07-20 00:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0004_auto_20200720_0154'),
]
operations = [
migrations.DeleteModel(
name='Report',
),
migrations.AlterF... |
3,765 | 4afb556ceca89eb90ba800db4f383afad1cd42a5 | # Turn off bytecode generation
import sys
from asgiref.sync import sync_to_async
from django.core.wsgi import get_wsgi_application
sys.dont_write_bytecode = True
# Django specific settings
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
import django
django.setup()
from db import models
de... |
3,766 | a29f89750ef3a55116959b217b8c9100b294c66c | from nose.tools import *
from packt_offer import *
from bs4 import BeautifulSoup
class TestPacktOffer:
def setUp(self):
self.proper_soup = BeautifulSoup(
""""
<div id="deal-of-the-day" class="cf">
<div class="dotd-main-book cf">
<div class="section-inner">
... |
3,767 | a6ae4324580a8471969e0229c02ea1670728f25b | import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
# print(robjects.__file__)
import sys
sys.path.append('./')
import importlib
import json
import os
from web_app.function.WordCould import word_img
# importlib.reload(sys)
# #sys.setdefaultencoding('gbk')
class Ubiquitination():
def __ini... |
3,768 | e34e1e220c6d0fe2dc3d42caaefb04b178cdd120 | #!/usr/bin/python
import sys
import random
def has_duplicates(list) :
"""Returns True if there are duplicate in list, false otherwise"""
copy = list[:]
copy.sort()
for item in range(len(list)-1):
if copy[item] == copy[item + 1]:
return True;
return False;
def gen_birthdays(n):
"""returns a list ... |
3,769 | 10cb4b59d1e1e823c56ae5ceea0514b1c1904292 | ALPACA_KEY = 'Enter your apaca key here'
ALPACA_SECRET_KEY = 'Enter your apaca secret key here'
ALPACA_MARKET = 'enter alpaca market link here'
TWILIO_KEY = 'enter your twilio key here'
TWILIO_SECRET_KEY = 'enter your twilio secret key here'
YOUR_PHONE_NUMBER = 'Enter your phone number'
YOUR_TWILIO_NUMBER = 'Enter your... |
3,770 | e33aca56e4c9f82779278e836308c2e22d3356e2 | # coding=utf-8
class HtmlDownload(object):
"""docstring for HtmlDownload"""
def html_download(city, keyWords, pages):
# root URL
paras = {
'jl': city,
'kw': keyWords,
'pages': pages,
'isadv': 0
}
url = "http://sou.zhaopin.com/jobs/searchresult.ashx?" + urlencode... |
3,771 | 21dd3d1deb00e9bc09803d01f1c05673ea8d25d2 | from os import getenv
config_env = {
'api_port': int(getenv('API_PORT')),
'psg_uri': getenv('PSG_URI')
} |
3,772 | 09fb99a15c2727da2ef96028aca5513337449f62 | # Author: Lijing Wang (lijing52@stanford.edu), 2021
import numpy as np
import pandas as pd
import gstools as gs
import matplotlib.pyplot as plt
from matplotlib import patches
import seaborn as sns
plt.rcParams.update({'font.size': 15})
import os
path = os.path.dirname(os.getcwd())
subpath = '/examples/case2_nonline... |
3,773 | 24813e03de05058925a42847042157fa65450d21 | #!/usr/bin/env python
import os, sys, json
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'python_task_helper', 'files'))
from task_helper import TaskHelper
hosts_file = open("/etc/hosts", "r").read()
resolv_file = open("/etc/resolv.conf", "r").read()
output = hosts_file + resolv_file
class Gen... |
3,774 | b0f92b5e4cc972aca84a29b4568e85836f155273 | from app import db
class OrgStaff(db.Model):
__tablename__ = 'org_staff'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete="CASCADE"))
invited_by = db.Column(db.Integer, db.ForeignKey('users.id', ondelete="CASCADE"))
org_id = db.Column(... |
3,775 | 864e9063ec1ed80cd1da3128a38633cbeb2f8bba | #-*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.files import File as DjangoFile
from django.core.management.base import BaseCommand, NoArgsCommand
from filer.models.filemodels import File
from leonardo.module.media.models import *
from filer.settings import FILER_IS_PUBLIC_DEFAULT
from ... |
3,776 | 1568cf544a4fe7aec082ef1d7506b8484d19f198 | #exceptions.py
#-*- coding:utf-8 -*-
#exceptions
try:
print u'try。。。'
r = 10/0
print 'result:',r
except ZeroDivisionError,e:
print 'except:',e
finally:
print 'finally...'
print 'END'
try:
print u'try。。。'
r = 10/int('1')
print 'result:',r
except ValueError,e:
print 'ValueError:',e
... |
3,777 | cf7bd8aa9c92d1c3acb9ccc1658d66fa0e7a142d | class Job:
def __init__(self, id, duration, tickets):
self.id = id
self.duration = duration
self.tickets = tickets
def run(self, time_slice):
self.duration -= time_slice
def done(self):
return self.duration <= 0 |
3,778 | 29e54a9ec0d65965645ac4aabf8c247a8857a25f | from translit import convert_input
def openfile(name):
f = open(name, 'r', encoding = 'utf-8')
text = f.readlines()
f.close()
return text
def makedict(text):
A = []
for line in text:
if 'lex:' in line:
a = []
a.append(line[6:].replace('\n',''))
... |
3,779 | 08b13069020696d59028003a11b0ff06014a4c68 | from datetime import datetime, timedelta
from request.insider_networking import InsiderTransactions
from db import FinanceDB
from acquisition.symbol.financial_symbols import Financial_Symbols
class FintelInsiderAcquisition():
def __init__(self, trading_date=None):
self.task_name = 'FintelInsiderAcquisiti... |
3,780 | 4689ee7f7178cef16ac1f5375481a9ee8a48f924 | import json
import sys
from pkg_resources import resource_string
# Load a package data file resource as a string. This
_conf = json.loads(resource_string(__name__, 'conf.json'))
# Load a data file specified in "package_data" setup option for this pkg.
_pkg_data = resource_string(__name__, 'data/pkg1.dat')
# Load a d... |
3,781 | 795936dad7a9e51edf0df66207a43ac4d97e9023 | import pathlib
import shutil
import os
import glob
import pandas as pd
import sqlalchemy as sqla
"""
SCRIPT TO FILL THE DATABASE FROM CSV ON MEGA IF LOSE DATA IN PARTICULAR DATE
"""
PATH = "/home/thomas/Documents/TER/AJOUTER_CSV_BDD/"
folder = "test/"
files_used = []
totalFiles = 0
contents = pathlib.Path(PATH+folder... |
3,782 | 874ca60749dba9ca8c8ebee2eecb1b80da50f11f | from sqlalchemy.orm import Session
from fastapi import APIRouter, Depends, File
from typing import List
from ..models.database import ApiSession
from ..schemas.images_schema import ImageReturn
from . import image_service
router = APIRouter()
@router.get("/", response_model=List[ImageReturn])
def get_all_images(db: ... |
3,783 | 6475fd59ba2414ea9a174297a8d94e5a2e0a7d8f | from django.contrib import admin
from .models import StoreId
# Register your models here.
class StoreIdAdmin(admin.ModelAdmin):
list_display = ('userid', 'aladin_id', 'yes24_id', 'ridibooks_id', 'start_date', 'end_date')
search_fields = ['userid', 'aladin_id', 'yes24_id', 'ridibooks_id']
admin.site.register(S... |
3,784 | 734561c2f127418bdc612f84b3b1ba125b6a2723 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import Common.Common.GeneralSet as GeneralSet
import TestExample.Test as Test
from Common.Common.ProcessDefine import *
def MainRun():
Cmd()
Test.TestGo()
def Cmd():
if (len(sys.argv) != 3):
print('error cmdargument count!')
return... |
3,785 | a8f52772522d1efc097c3d17d9c08199816f1168 | class IndividualStack:
def __init__(self):
self.stack=[None]*5
class StackwithStacks:
def __init__(self):
self.stacks = []
self.stackcount=-1
self.count=0
self.st = None
def push(self, element):
if self.count%5==0:
self.stackcount = self.stackco... |
3,786 | 452f35fe2ae9609949a3f92ad7768fc37094a2f1 | import numpy as np
import pytest
import torch
from ignite.contrib.metrics.regression import MeanNormalizedBias
from ignite.engine import Engine
from ignite.exceptions import NotComputableError
def test_zero_sample():
m = MeanNormalizedBias()
with pytest.raises(
NotComputableError, match=r"MeanNormali... |
3,787 | d03f87b7dfa8fe2c63500effda1bea5e41f17ffc | #=======================================================================
__version__ = '''0.0.01'''
__sub_version__ = '''20130714221105'''
__copyright__ = '''(c) Alex A. Naanou 2011'''
#-----------------------------------------------------------------------
import os
import sha
import md5
import base64
... |
3,788 | 937711546271c145d0f0df2981bdd7d1e9297e3a | """
Test /cohort/:id/user/:id
"""
import re
from unittest.mock import patch
from django.urls.base import reverse_lazy
from rest_framework import status
from breathecode.tests.mocks import (
GOOGLE_CLOUD_PATH,
apply_google_cloud_client_mock,
apply_google_cloud_bucket_mock,
apply_google_cloud_blob_mock,
)... |
3,789 | 99154212d8d5fdb92cd972c727791158d09e3e2c | # -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2020-07-10 02:52
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('civictechprojects', '0036_auto_20200708_2251'),
]
operations = [
migration... |
3,790 | 7088f7233b67dcb855482a76d304aacc1a26abad | import json
import unittest
from music_focus.workflows.weibo_online import WeiboOnline
class Test(unittest.TestCase):
def setUp(self):
pass
def test(self):
workflow_input = {
'result_type': 'posts'
}
wf = WeiboOnline()
r = wf.run(workflow_input)
p... |
3,791 | a4f2ca3155f2bb4c17be5bb56dd889abb5d20293 | # Generated by Django 3.0.4 on 2020-04-04 11:07
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('product', '0003_cost'),
... |
3,792 | 086ee4de1d74654ef85bd0a169fdf49c8f52bef2 | import argparse
from figure import Figure
from figure.Circle import Circle
from figure.Square import Square
class FCreator(object):
__types = ['square', 'circle']
def createParser(self, line: str):
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--type', required=True, choices=... |
3,793 | c5d92ec592250d5bc896d32941364b92ff1d21e9 | #! py -3
# -*- coding: utf-8 -*-
import requests
from urllib.parse import quote
import logging
from urllib.parse import urlparse
logger = logging.getLogger(__name__)
logger = logging.getLogger()
# 配置日志级别,如果不显示配置,默认为Warning,表示所有warning级别已下的其他level直接被省略,
# 内部绑定的handler对象也只能接收到warning级别以上的level,你可以理解为总开关
logger.setLeve... |
3,794 | cd49230be3c418853aa2986ed727204e51a6b6ae | import numpy as np
import pandas as pd
from pathlib import Path
import matplotlib as mpl
from matplotlib import pyplot as plt
plt.style.use('seaborn-muted')
#from IPython import get_ipython
from IPython.display import HTML, Markdown
import air_cargo_problems as acp
problems = ['Air Cargo Problem 1',
'... |
3,795 | 4ef4e302304ccf2dc92cdebe134e104af47aae20 | from django.contrib import admin
from Evaluacion.models import Evaluacion
admin.site.register(Evaluacion)
|
3,796 | 92bbccfbfebf905965c9cb0f1a85ffaa7d0cf6b5 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 19 13:42:09 2019
@author: Administrator
"""
from config.path_config import *
import GV
def ReadTxtName(rootdir):
#读取文件中的每一行,转为list
lines = []
with open(rootdir, 'r') as file_to_read:
while True:
line = file_to_read.read... |
3,797 | 9f36b846619ca242426041f577ab7d9e4dad6a43 | import pandas as pd
import numpy as np
import geopandas as gp
from sys import argv
import os
import subprocess
n, e, s, w = map(int, argv[1:5])
output_dir = argv[5]
print(f'{(n, e, s, w)=}')
for lat in range(s, n + 1):
for lon in range(w, e + 1):
latdir = 'n' if lat >= 0 else 's'
londir = 'e' if ... |
3,798 | 9dddae5e85bda67bdbb6f0336a29949cb1f4d59e | """A twitter bot that retweets positive tweets from cool lists."""
import sys
import os
from random import choice
from random import shuffle
import twitter
import unirest
twitter = twitter.Api(
consumer_key=os.environ['TWITTER_CONSUMER_KEY'],
consumer_secret=os.environ['TWITTER_CONSUMER_SECRET'],
access_... |
3,799 | 29304bdbf93b0b1308025db1d35a92346c6dcbe0 | def sum_string(string):
list_chars = [zerone for zerone in string if zerone in ["0", "1"]]
return list_chars
def check_triads(trio, final_str):
list_occur_zero = [i for i in range(len(final_str)) if final_str.startswith(trio + '0', i)]
list_occur_one = [i for i in range(len(final_str)) if final_str.st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.