index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
17,000 | 3dc43940957aa79137a2404c34b250e4af9d4ee6 | #base Namer class
class Namer():
def __init__(self):
self.last=""
self.first=""
#derived namer class for First <space> Last
class FirstFirst(Namer):
def __init__(self, namestring):
super().__init__()
i = namestring.find(" ") #find space between names
if i > 0 :
... |
17,001 | 2fa8dfcb6ffec8003bda378ae12f2d0aaaf64cf8 | """
Dataset loading
"""
import numpy
from app import app
def load_captions(captions_dataset_path):
app.logger.info('Loading Captions from {}'.format(captions_dataset_path))
captions = list()
with open(captions_dataset_path, 'rb') as f:
captions = [line.strip() for line in f]
app.logger.inf... |
17,002 | 207e87b6c0c18bdcfd9ad34b0cf84d5d0b6c7ed6 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated,IsAdminUser
from .models import *
from .serializers import *
# Create your views here.
class ProductoLista(viewsets.ModelView... |
17,003 | dab06b6c9bcd509c44852853ba9684357be486b3 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2017-04-27 04:05
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('HealthNet', '0006_auto_20170426_2052'),
]
operations = [
mig... |
17,004 | 0e9d961b92f32eb014d26629ddf39cb4f9de864f | from __future__ import print_function, division
from builtins import range
import numpy as np
import theano
import theano.tensor as T
import q_learning
# deep neural networks are easier to write with frameworks like theano and tensorflow
# because you don't have to derive any of the gradients yourself
# f... |
17,005 | 908ed27edf0441fd2f3361f42ac70ed5790d999e | # Enumerate a python list and try to print the counter with the list value
list1= ['ananya','pooja','harshitha','anu','nithin']
print(list(enumerate(list1)))
print(enumerate(list1))
# Enumerate a python tuple and try to print the counter with the tuple value
tuple1=('anusha','shravya','priya','karthik','sa... |
17,006 | 349370446a9006b5ecd64a3a0b6d5526a8c8233a | # -*- coding: utf-8 -*-
#
# Copyright: (c) 2018, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
import sys
if sys.version_info < (2... |
17,007 | a8ff887345054f2c9b48a17470296b995299221a | isbn12 = input("enter isbn:")
sum1 = 0
sum2 = 0
for index in range(0,12,2):
tem[ = int()] |
17,008 | acb33dc09c8ba893a47fca2d23cb2339d87e13ef | import commands
import requests
import sys
import unittest
class TestCase(unittest.TestCase):
def setUp(self):
self.email_0 = "alice@example.com"
self.email_1 = "bob@example.com"
self.email_2 = "carol@example.com"
self.email_3 = "david@example.com"
self.auth_token_0 = ""
... |
17,009 | cccaca0ecb1dc6331423425849c9b8767d065dd7 | from django.contrib.auth import get_user_model
from django.db import models
from django.urls import reverse
from django.utils.text import slugify
from django.utils.timezone import now
from unidecode import unidecode
from phonenumber_field.modelfields import PhoneNumberField
User = get_user_model()
class Tour(models.... |
17,010 | a26608c6c2db3af8d94515bec2067e043402305c | # -*- coding:utf-8 -*-
import scrapy
import re
import os
import urllib
import sys
import time
import urllib2
#from XiaMei_Crawler.items import XiaMeiPhotoAlbum
from ..items import XiaMeiPhotoAlbum
from scrapy.selector import Selector
from scrapy.http import HtmlResponse,Request
from urllib2 import URLError, HTTPError
p... |
17,011 | 976bbc1c7c1a362337a6802b8ffa07985ba140c9 | '''To run these, run the following
pip install pytest
pytest (this file name)
'''
import os
import tensorflow as tf
import pytest
import numpy as np
from data_loader_wrapper import DataSplits
from run_from_config import EarlyStoppingHelper
from run_from_config import SAVE_EARLY_STOPPING_ACTION
from run_from_config ... |
17,012 | 1669fd7dac22aac2d84f002f09c5c8a07ae241a5 | from lib.database import db
import lib.security as security
from lib.common_engine_functions import get_next_available_id, property_is_unique, save_document, get_all_documents
from datetime import datetime
def create(room, payer, receiver, amount, method):
id = get_next_available_id('transactions')
post = {
... |
17,013 | ef04bc9afbdb5f96806d281376c5b6de46a3a7a0 | import pickle
import cv2
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D,MaxPooling2D,Dense,Flatten
from tensorflow.keras.optimizers import Adam
from sklearn.utils import shuffle
files=["sci.pkl","pal.pkl","roc.pkl"]
features=[]
labels=[]
for i ... |
17,014 | 19aa1a5ab3918daa3c1571262064a920435e1863 | #!/usr/bin/env python
from distutils.core import setup, Extension
EXTENSIONS = [dict(name="donuts.emd",
sources=["donuts/emd/pyemd.c", "donuts/emd/emd.c"],
extra_compile_args=['-g'])]
opts = dict(name='donuts',
packages=['donuts',
'donuts.emd',
... |
17,015 | b20ccbe5cb9a2151fc2fc83310b9d17eb768a223 | import pandas as pd
from torch.utils.data import Dataset
from torchvision.datasets.folder import default_loader as read_image
from pathlib import Path
import torch
class FrameWindowDataset(Dataset):
"""
Just like FrameFolderDataset, but its output is different.
Here, for every frame t, we return a 4D ten... |
17,016 | 76f02f903b216362565b8c29fa257a158a8b3869 | """empty message
Revision ID: f0538225efd3
Revises: 4b4604d66bb5
Create Date: 2021-08-22 21:36:12.376499
"""
# revision identifiers, used by Alembic.
revision = 'f0538225efd3'
down_revision = '4b4604d66bb5'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic ... |
17,017 | 29e50fb67816182be02a57e61a27fab0235ff457 | INVALID_JSON = "INVALID_JSON"
HANDLER_CRASHED = "HANDLER_CRASHED"
SMS_NOT_CONFIGURED = "SMS_NOT_CONFIGURED"
SMS_COULD_NOT_BE_SENT = "SMS_COULD_NOT_BE_SENT"
TWILIO_NOT_SETUP = "TWILIO_NOT_SETUP"
|
17,018 | 39a417e4ad8fd441c397f34f7e3db37796633ee6 | from django.contrib import admin
from .models import Access, SetCtarl
@admin.register(Access)
class AccessAdmin(admin.ModelAdmin):
# 设置模型字段,用于Admin后台数据的表头设置
list_display = ['id', 'date', 'num']
# 过滤器
list_filter = ['id', 'date', 'num']
# 设置可搜索的字段并在Admin后台数据生成搜索框,如有外键应使用双下划线连接两个模型的字段
search_fie... |
17,019 | 95ccd702e35801a80409c2f9ee6804cd9f722e3d | import sys
import time
from functools import reduce
import database_connector
import movie
import numpy as np
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import train_test_split
import ratingPredictor
def mltesting(movies):
nn = MLPRegressor(hidden_layer_sizes=100, activation="lo... |
17,020 | 501cd02f8182b73496e07204edc8687c273bf91e | """
5703. Maximum Average Pass Ratio
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students wil... |
17,021 | e368bff8795aba317cbcfceacefd294264f3c6e9 | #%%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from agent import Agent
#%% Q-table
# Plot max Q for each position
q = np.load('qtables/agent1.npy')
q = np.max(q, axis=2)
fig, ax = plt.subplots(1, 1)
sns.heatmap(np.flip(q, 1).transpose(), annot=True)
plt.show()
#%% Be... |
17,022 | 956303d1b427a0771f717dd69241457eb23cdf20 | #!/usr/bin/python
#coding=utf-8
class Test():
def prt(self):
print(self);
print(self.__class__);
t=Test();
t.prt();
|
17,023 | e512a842799a0785c5a31ffa2b69460af33d6338 | import numpy as np
import matplotlib.pyplot as plt
def mergeA_with_average(lab_A, lab_B):
laba_hash = {}
labb_hash = {}
lab_a_list = list()
lab_b_list = list()
laba_handler = open(lab_A, "r")
labb_handler = open(lab_B, "r")
for line in laba_handler.readlines():
... |
17,024 | 653bae7ee9ecf5a27c7194a1e81fa634d97844ae | # -*- coding: utf-8 -*-
import os
import c4d
import operator
class Utility(object):
@staticmethod
def __is_texture_relative(texture_path):
if not len(os.path.split(texture_path)[0]):
return False
else:
if texture_path[:1] == "." or texture_path[:1] == os.path.sep or te... |
17,025 | 4fa17fe040037a32fe8012f10646999eec392dc5 | # The function of this script is to use the Google Cloud API to download reports from the Google play store. This script will download the monthly reports
# that Google provides from the Google Play Store, then those csv's are parsed in order to grab relevent data, and then all of the relevent data
# that is to be put ... |
17,026 | 09afb51dc12af086973656eed625debbae0d2efb | from pubnub.pnconfiguration import PNConfiguration
from pubnub.enums import PNReconnectionPolicy
from pubnub.pubnub import PubNub
from pubnub.callbacks import SubscribeCallback
import logging
import configparser
import os
log = logging.getLogger(__name__)
class FeederPublisher(object):
def __init__(self, channe... |
17,027 | fcb85c0dbcebafe1034aaf830e34fa6310d8ab7d | class FirstClass:
def setdata(self,value1, value2):
self.data1=value1
self.data2=value2
def display(self):
print(self.data1, '\n', self.data2, '\n')
x = FirstClass()
x.setdata("King Arthur", -5)
x.display()
x.data1="QQ"
x.data2=-3
x.display()
x.anothername="spam"
x.display()
print(x.... |
17,028 | cc8235bf09c92256578c67bdef263e8aff190a86 | import openpyxl
workbook = openpyxl.Workbook()
sheet = workbook.active
sheet.title = '蔡徐坤篮球'
sheet.cell(row=1, column=1, value='名称')
sheet.cell(row=1, column=2, value='地址')
sheet.cell(row=1, column=3, value='描述')
sheet.cell(row=1, column=4, value='观看次数')
sheet.cell(row=1, column=5, value='弹幕数')
sheet.cell(row=1, co... |
17,029 | 56de33af5931c7e8bf2a421fcb5e06917f1b19a7 | # -*- coding: utf-8 -*-
# Django
from django.shortcuts import render
from django.contrib.auth.decorators import login_required, user_passes_test
from django.db.models import Count
from django.forms.models import model_to_dict
from django_filters import rest_framework as filters
# REST
from rest_framework import status
... |
17,030 | 714ac71b4ee944cfeb6e6e3d0848394d1eb91ee2 | from django.shortcuts import render_to_response, render
from worksheet.models.models import WorkSheet
# Create your views here.
def count(request):
clients = []
types = []
return render(request, 'worksheet/count.html', {'client': clients, 'type': types})
def count_result(request):
start_date = req... |
17,031 | e3a9fd96544ea0bece3c30299412dfb1967c8d13 | '''
Created on 2017/01/31
@author: Brian
'''
import sqlite3
from os.path import isfile, getsize
defaultDatabase = "textToolStrings.db"
def create_table():
conn = sqlite3.connect(defaultDatabase)
curs = conn.cursor()
curs.execute('CREATE TABLE IF NOT EXISTS textStrings(strings TEXT)')
curs.close()
... |
17,032 | e39c98eb6f80eeae7f5b295fe0b70b041b45ed09 | # Python Program - Find ncR and nPr
import math;
print("Enter 'x' for exit.");
nval = input("Enter value of n: ");
if nval == 'x':
exit();
else:
rval = input("Enter value of r: ");
n = int(nval);
r = int(rval);
npr = math.factorial(n)/math.factorial(n-r);
ncr = npr/math.factorial(r);
print(... |
17,033 | 06b40f9ac6d42c19555cd6068b39bce430fa7337 | # Ch6Ex132.py
# Author: Parshwa Patil
# ThePythonWorkbook Solutions
# Exercise No. 132
# Title: Postal Codes
def postalCodeParser(code):
charToProvince = {'A': 'Newfoundland', 'B': 'Nova Scotia', 'C': 'Prince Edward Island', 'E': 'New Brunswick', 'G': 'Quebec', 'H': 'Quebec', 'J': 'Quebec', 'K': 'Ontario', 'L'... |
17,034 | f6a510565162549c10bddf770a0198985c7c8de6 | from math import fabs
from typing import Union
import numpy as np
from numpy.lib.stride_tricks import sliding_window_view
from jesse.helpers import get_candle_source
from jesse.helpers import get_config
def fwma(candles: np.ndarray, period: int = 5, source_type: str = "close", sequential: bool = False) -> Union[
... |
17,035 | c6a60f6eeec562785b8aa6f9d8523b39f93c9a25 | from src.manoeuvringModel import manoeuverShip
import math
from matplotlib import patches
class Simulation:
""" The class in which the simulation is created """
activeShips = {}
def __init__(self, world):
self.world = world
self.env = world.env
module = __import__("Scenarios.%s"... |
17,036 | 5947c6ae02f621ce913b8355891214f2be233765 | dicionario = dict()
dicionario = {1: "oi", 2: "olá", 3: "hello", "C": 9}
print(dicionario)
print(dicionario.keys())
print(dicionario.values())
dicionario[2] = "oláá"
print(dicionario)
for chave in dicionario:
print(dicionario[chave])
for chave, valor in dicionario.items():
print(chave,"-",valor)
... |
17,037 | ae2a17bd00ff747a401320bdde016444c84602ab | import datetime
import json
import re
import pytz
from .dungeon_types import DUNGEON_TYPE_COMMENTS
def strip_colors(message: int) -> str:
return re.sub(r'(?i)[$^][a-f0-9]{6}[$^]', '', message)
def ghmult(x: int) -> str:
"""Normalizes multiplier to a human-readable number."""
mult = x / 10000
if in... |
17,038 | ddf18ac8eed85cf890e0465d7b58268354848eec | import datetime
from myflaskapp import celery
from models.model import Auction
from controllers.auction_controller import AuctionController
from celery import chain
from celery.result import AsyncResult
def set_countdown(id, delay):
return chain(set_active.si(id).set(eta=delay), deactivate.si(id).set(countdown=10)... |
17,039 | 63ef831df8ea4c5053e0112e70ab41244d7c775f | import pickle
from sklearn.cross_validation import KFold
import numpy as np
import svm_classify as svm
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.preprocessing import normalize
import load_data as ld
import load_data as Tokenizer
from sklearn.metrics import accuracy_score
DESIGN_MATRIX_P... |
17,040 | 316557081de965fd39f17460ff7d2165c75618a1 | import numpy as np
import random
a=[1,2,4,5,3,4,5,6,7,6,5,2,1]
li=np.random.choice(range(1,2))
print(li) |
17,041 | 5ab105aebd33987f1da198ffa0e15533eb4ca434 | # Auto generated configuration file
# using:
# Revision: 1.207
# Source: /cvs_server/repositories/CMSSW/CMSSW/Configuration/PyReleaseValidation/python/ConfigBuilder.py,v
# with command line options: l1test -s DIGI,L1,DIGI2RAW,HLT:HIon --conditions auto:mc --no_exec
import FWCore.ParameterSet.Config as cms
process =... |
17,042 | 2895bbc82b9099f7251ab83b7298c786bb658387 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''=================================================
@Project -> File :locust -> test.py
@IDE :PyCharm
@Author :Mr. XieYueLv
@Date :2021/8/15 1:04
@Desc :
=================================================='''
# import time
#
# now_time_stamp = time.time()
# print(... |
17,043 | f31bb5e56bbec825426f15fc9e4664b4811f2488 | import numpy as np
import matplotlib.pyplot as plt
front1 = np.load('solutions-off-resonance/prelim-1a-front.npy')
front2 = np.load('solutions-off-resonance/prelim-1b-front.npy')
front3 = np.load('solutions-off-resonance/prelim-1c-front.npy')
fig, ax = plt.subplots()
ax.scatter(-front1[:,0]*1e-3, front1[:,1], c='b'... |
17,044 | 354542acfe1a0d7543b8f6386fddd1bf6f982397 | # -*- coding:utf-8 -*-
# !/usr/bin/env python
import re
import traceback
from lib.common import HttpReq, CheckDomainFormat
def get_subdomains(domain):
subdomains = []
try:
url = 'http://alexa.chinaz.com/?domain={}'.format(domain)
_, content = HttpReq(url)
regex = re.compile(r'(?<="\>\... |
17,045 | e392a65ba10bcc3cc18156bf57d4d23dd18c6c91 | from chat import create_app
# 创建App实例
app = create_app() |
17,046 | e6ba343434ef2d1285775e7d4e598fb5882ff02e | print'LAB02, Question 4'
print''
i = 0
while i > 10:
i += 1
if i%2 == 0:
print i
print 'this is an infinite loop'
|
17,047 | 0049ed90bbd78398412f64c19d1cbfeaa418f327 | #!/usr/bin/env python3
""" EPO Managed Endpoint Inject - Script to demonstrate weakness in EPO managed endpoint registration mechanism to allow arbitrary managed endpoint registration.
By design, McAfee ePO server exposes server public key and server registration key via Master Repository. These two keys can be downloa... |
17,048 | be8166d3a9bdad64e979687dc9a2d4e111c38421 | n = int(input())
maior = 0
for i in range(n):
m,nota = map(float,input().split())
if(nota>maior):
maior = nota
id = m
if(maior>=8):
print(int(id))
else:
print("Minimum note not reached")
|
17,049 | ae46d65298453577458eea8854505749cbde0ae4 | # Generate the Fibonacci sequence
def find_primes(num):
primes = []
non_primes = []
for i in range(2, num + 1):
if i % 2 == 0 and i > 2:
non_primes.append(i)
elif i % 3 == 0 and i > 3:
non_primes.append(i)
elif i % 5 == 0 and i > 5:
non_primes.appe... |
17,050 | 2339567a9db89b09b50608ee14ff5ab12613cffd | #!/usr/bin/env python
import os
import subprocess
from rpyc import Service
from rpyc.utils.server import ThreadedServer
class TestService(Service):
""" Test Service """
def exposed_start_listen(self):
subprocess.Popen("ib_send_lat -d rxe0 -a -F", shell = True)
def exposed_start_send(self):
... |
17,051 | eccd1337ae3e56c58cbbe7b74bd1d0753736f398 | import socket
def run():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("localhost", 8081)) # 连接服务器
sock.sendall(bytes("hello from client","utf-8")) # 将消息输出到发送缓冲 send buffer
print(sock.recv(1024)) # 从接收缓冲 recv buffer 中读响应
sock.close() # 关闭套接字...
if __name__=="__main__":... |
17,052 | 24f071da834dfbcec3a595991101d0503a5c8181 | def day1(fileName):
floor = 0
firstBasement = None
with open(fileName) as infile:
chars = infile.readline()
for position, char in enumerate(chars):
if char == '(':
floor += 1
elif char == ')':
floor -= 1
if floor < 0 and firstBasement is None:
firstBasement = position + 1
print(f"Floor:... |
17,053 | 1054139f7e7df8dd12d9f249bf354cc38d00a006 | import tushare as ts
import pandas as pd
class SHSZData(object):
"""docstring for SHSZData"""
def __init__(self, data_folder):
super(SHSZData, self).__init__()
stocks = ts.get_stock_basics()
self.stocks = stocks[stocks['timeToMarket'] != 0]
self.DATA_FOLDER = data_folder
d... |
17,054 | b2ff6973060a9d18c4ad7dd7a133e3f4c2f19bb2 |
def armstrong(i):
t = i
s = 0
while t > 0:
d = t % 10
s = s + d*d*d
t = t // 10
if s == i:
print('YES')
else:
print('NO')
number = int(input())
armstrong(number) |
17,055 | f8c33b3de56964e00d7f8e76e50d4b1a057c36ca | import urllib
import json
import requests
import urllib.request
import pandas as pd
import time
import datetime
from time import localtime, strftime
import numpy as np
import statsmodels.api as sm
df = pd.read_csv('./종단기상관측소.csv',encoding='cp949')
df.columns = df.columns.str.replace(' ','')
def get_Weather_xml():... |
17,056 | a8ae9946f55679b2b3aace8e92ab69c16ffd4dae | Start_Block=Besiege.GetBlock("5c19343b-d7d5-4913-b78f-b1c5b63ba54b")
Front_Left_Wheel=Besiege.GetBlock("ef13b691-c552-45ac-a4aa-1cd578d3f440")
Front_Right_Wheel=Besiege.GetBlock("b2c35c71-a60f-4757-b9c8-a5f39fec1079")
Rear_Left_Wheel=Besiege.GetBlock("b2b8eda7-affb-4020-8294-3b1ccc1e811a")
Rear_Right_Wheel=Besiege.Get... |
17,057 | 893c7c897103cb88b6d3c44ba6a332847fcff708 | import discord
import asyncio
from discord.ext import commands
import random
class Poll(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True, aliases=['poll'])
async def sondage(self, ctx, question, options: str, emojis: str):
await ctx.message.delete(... |
17,058 | ed3b0bbe062a526fa9845cb6fce7093f1981da76 | # =============== For Translator ================================
from googletrans import Translator
sentence = str(input("The sectence: "))
translator = Translator()
tr_sen = translator.translate(sentence, src='ur', dest='en')
s = tr_sen
print(tr_sen.text)
x = translator.translate(str(s), src='en', de... |
17,059 | 11794690df0fc439535f88b1fafc7d2cdedeb7cd | class Solution:
def summaryRanges(self, nums):
result = []
if len(nums) == 0:
return result
temp = str(nums[0])
for i in xrange(1,len(nums)):
if nums[i] != nums[i-1]+1:
if temp == str(nums[i-1]):
result.append(temp)
... |
17,060 | 7709289bd2511b66cca64b62d03b3eda7f992886 | # Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
from typing import Optional
import attr
from marshmallow3_annotations.ext.attrs import AttrsSchema
@attr.s(auto_attribs=True, kw_only=True)
class GenerationCode:
key: Optional[str]
text: str
source: Optional[str]
... |
17,061 | 8448c024c1bb5ba3b227d03545a78e744067300c | omim = {'omim': {
'version': '1.0',
'searchResponse': {
'search': '*',
'expandedSearch': '*:*',
'parsedSearch': '+*:* ()',
'searchSuggestion': None,
'searchSpelling': None,
'filter': '',
'expandedFilter': None,
'fields': '',
'searchReport': None,
'totalResults': 7368,
'startIndex': 6200,
'endIndex': 6219, ... |
17,062 | 47c21a53740132c5adc3c4f490bad8655493ffda | #!/usr/bin/env python
# coding: UTF-8
"""Usage: %prog [OPTIONS] host:<DISPLAY#>
View the NX session <DISPLAY#> on host. If it is not running, it will be
started, and ~/.nxstartup will be executed by the shell.
See the source code for more information.
"""
# This script handles starting and reconnecting to an NX ses... |
17,063 | d10761791ca285a68a7d3479b6ae9b4506004142 | from sdk.types import TypeUuid, TypeString, TypeBase, TypeInteger
class UserId(TypeUuid):
pass
class UserName(TypeString):
def validate(self, value_name=''):
super().validate('Nombre de usuario')
if self.is_required() and self._value.__len__() < 3:
raise Exception("El nombre debe... |
17,064 | 75ab687a036a1a0ccfe27e43d5508ed1c3933a8b | import uuid
from django.shortcuts import resolve_url
from rest_framework.test import APITestCase
from channels.models import Channel, Category
class ChannelApiTest(APITestCase):
def setUp(self):
self.channel = Channel.objects.create(name='market')
def test_list(self):
url = resolve_url('cha... |
17,065 | cbe85a40a6fcf48b8d7a424c3fd955a7bde58e97 | from detec.dete import subway_det
from class_n.class_n_model import model_n
from class_2.class_2_model import model_2
from data import data_detile
from config import Config
import cv2
import numpy as np
from PIL import Image
class detector(object):
def __init__(self,config):
self.config=config
... |
17,066 | 75f16e1df266b41924ea2e2e04c9c0561712d329 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york': 'new_york_city.csv',
'washington': 'washington.csv' }
# my_list
cities = ["chicago", "new york", "washington"]
filters = ["month", "day", "both", "none"]
months = ["all", "january", "f... |
17,067 | 78d312dc52e14a7338e47e9f38620b476aba774b | from random import randint
import random
import sys
num_nodes = sys.argv[1]
topo_type = sys.argv[2]
gain_low = sys.argv[3]
gain_max = sys.argv[4]
num_nodes = int(num_nodes)
gain_low = float(gain_low)
gain_max = float(gain_max)
nodes = {}
print num_nodes
print topo_type
print gain_low
print gain_max
for i in range(1,... |
17,068 | c0611899d28595d8d7e87bbafe8466917e926d36 | import requests
import csv
import json
from datetime import datetime
# from datetime import timezone
# from datetime import date
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
s = requests.Session()
payload = {'username_or_email':'<insert username>', 'password':'<insert passw... |
17,069 | 0a7c77c9d2582c323108f3606ed74d7420d3f109 | import numpy as np
def right_shift(binary, k=1, axis=-1):
''' Right shift an array of binary values.
Parameters:
-----------
binary: An ndarray of binary values.
k: The number of bits to shift. Default 1.
axis: The axis along which to shift. Default -1.
Returns:
--------
Returns an ndarray w... |
17,070 | b63fe5898f0dbc1d6d2c1ca4c6659dfde829399e | fruits=["cherry","banana","apple"]
for x in fruits:
print(x)
|
17,071 | f70f624e705c365acd5b309f07e3ddf821b55856 | # Add your code below for question 7.
|
17,072 | 6e65269ddd1dade7fa437c33592ebb11ac2f025b | from django import forms
from django.forms import inlineformset_factory
from .models import Buy, BuyItem, BuyStock
class BuyItemForm(forms.ModelForm):
class Meta:
model = BuyItem
fields = 'item', 'buy_amount', 'force_end',
def __init__(self, *args, **kwargs):
super(BuyItemForm, self).__init__(*args, **k... |
17,073 | ca7f556d37d48e85038ee00e02613f9cd3000670 | # 잃어버린 괄호 : https://www.acmicpc.net/problem/1541
numbers_str = input().split('-')
numbers = []
for expr in numbers_str:
expression = ''
for num_str in expr.split('+'):
expression += '+' + num_str.lstrip('0')
numbers.append(eval(expression))
total = numbers[0]
for i in range(1, len(numbers)):
t... |
17,074 | febd10cd03cc8ca995827e428bba982e237f0d95 | sm=input()
for i in range(0,len(sm)):
if(sm[i].isalpha() and sm[i].isdigit()):
print("No")
else:
print("Yes")
|
17,075 | d06ad2a8dd8fb473e9580ab0276b9e39729e004a | '''
Created on Mar 22, 2020
@author: Kratika Maheshwari
'''
from project import TempSensorAdaptorTask
'''
This Example sends harcoded data to Ubidots using the Paho MQTT
library.
Please install the library using pip install paho-mqtt
'''
import paho.mqtt.client as mqttClient
import time
import json
import random
''... |
17,076 | 297155b606d71e244cc4391a117019ebc2720e8d | #!/usr/bin/env python
# encoding: utf-8
"""
@version: 0.0
@author: hailang
@Email: seahailang@gmail.com
@software: PyCharm
@file: mnist_utils.py
@time: 2017/12/13 10:48
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tenso... |
17,077 | 181cd9c22f5a4b0d5254b49c2ee31bd88a4fcaa0 |
#def tempConvert(celcius, fahrenheit=((9/5)+32)):
# return(celcius*fahrenheit)
#tempConvert(float(input("Celcius? "))
def cel_to_fahr(c):
f = c * 9/5 + 32
return f
print(cel_to_fahr(10))
|
17,078 | 8af4caba9050dd8e7ce95759ae754e3224810d17 | import matchzoo as mz
import os
class DRMMConfig():
# preprocessor = mz.preprocessors.DRMMPreprocessor()
optimizer = 'SGD'
model = mz.models.DRMM
generator_flag = 1
name = 'DRMM'
num_dup = 1
num_neg = 4
shuffle = True
###### training config ######
batch_size = 2... |
17,079 | 5dd11dab08e51de8ee4cde5766ea17a95af97a41 | from main.data.get_users import GetUsersRepoImpl
from main.domain.get_users_repo import GetUsersRepo
from main.domain.use_cases.get_users import GetUsersUseCase
def provide_use_case():
return GetUsersUseCase()
def provide_repo():
return GetUsersRepoImpl()
def get_users_binder(binder):
binder.bind_to_p... |
17,080 | 6c196c0df5347c02dcbae407582344fee5a4e6a5 | import findspark
findspark.init()
from pyspark import SparkConf, SparkContext
from pyspark.sql import SparkSession
def add1(a, b):
print("*"*55)
print(a)
print(b)
return a + b+100
def remove_outliers(nums):
stats = nums.stats()
stddev = stats.stdev()
return nums.filter(... |
17,081 | 4068d200036c6d401171f2a037998621fc8ae44f | import argparse
import logging
from datetime import datetime
from api.proto import engine_pb2
from consumers.consumer import Consumer
from third_party.python.defectdojo_api import defectdojo
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class DefectDojoConsumer(Consumer):
def __in... |
17,082 | 6279a17da2e37352e530ec49984e335483ebe572 | from matplotlib.patches import Circle, Rectangle, Arc
import matplotlib.pyplot as plt
def draw_pitch(ax=None, color='white', bg_color=None, lw=0.75, x_label='', y_label=''):
pitch_width = 68.0
pitch_length = 105.0
goal_size = 7.32
# if no axes is provided, set standard
if ax is None:
ax = ... |
17,083 | 28925551bb7ada722830bd1c198a952d77857e58 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
"""
-------------------------------------
File name: Py01_regression.py
Author: Ruonan Yu
Date: 18-1-27
-------------------------------------
"""
import torch
import matplotlib.pyplot as plt
from torch.autograd import Variable
import torch.nn.funct... |
17,084 | 7ec33be17897e2a769b69f52abf1b09f751ed351 | import os, glob
dirname = os.path.dirname(__file__)
__all__ = [ os.path.basename(f)[:-3] for f in glob.glob(dirname+"/*.py")]
try: __all__.remove('__init__')
except: pass
__import__(os.path.basename(dirname), globals(), locals(), ('*',), 2)
|
17,085 | 16beb4ebd8b17f3e416ee94b667d3b22185ea6bd | # Copyright 2020 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
17,086 | 8730e15d45b3a976808d2eaec9ced06478e8141c | class Calculator:
C = 10
def add(self, a, b):
return a + b
@staticmethod
def info():
print("This is info class")
cal = Calculator()
# print(cal.add(10, 30))
# cal.info()
Calculator.info()
|
17,087 | 3623eb889f2f46e64d5c20f1a2b78118b9b28118 | import gdal
import subprocess
import psycopg2
import glob
import shutil
inputFolder = "/media/lancer/TOSHIBA/MODIS Terra/"
cutFolder = "/media/lancer/TOSHIBA/MODIS Terra Cut/"
def re_griding(inputfile, resx, resy, ouputfile):
regrid_command = "gdalwarp -t_srs '+proj=longlat +datum=WGS84' -tps -ot Float32 -wt Float32... |
17,088 | d8e83733147204c89654aad7afb86fb42e758763 | import json
from time import sleep
from typing import Dict, List
from selenium import webdriver
from selenium.webdriver.common.by import By
class Test_one():
def setup(self):
option = webdriver.ChromeOptions()
option.debugger_address = "127.0.0.1:9222"
self.driver = webdriver.Chrome(opti... |
17,089 | 80479066ebca14b499142ee81878bc24b4c73b32 | from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.core.cache import cache
from api.serializers import IPAddressSerializer, IPAddressGetSerializer
from api.models import IPAddress
ACCESS_KEY = '0a2d26de06ac50376c6e9508e00ffbe5'
# ... |
17,090 | 2176af4275e2a38b52b7f1d90f06350c8aefe520 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 6 15:38:12 2016
compare the telemetered data with raw data for each profile
@author: yifan
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from turtleModule import str2ndlist,np_datetime
from gettopo import gettopo
def find_start(a,List):
st... |
17,091 | d5e2df78c84ae4e248cd6d7b6b034820edbee623 | import json
from oandapyV20 import API
import pandas as pd
import numpy
from oandapyV20.contrib.factories import InstrumentsCandlesFactory
import csv
client = API(access_token='49c68257ae0870c5b76bbe63d4c79803-bc876dfcc6b0ebcc31ef73e45ebdbab8')
instrument, granularity = "GBP_USD", "H1"
_from = "2019-01-01T00:00:00Z"
_... |
17,092 | 101c6e6f7d08f57b2bdd9b0a57b45c30bd06aec2 | # Natural Language Toolkit: GLEU Score
#
# Copyright (C) 2001-2023 NLTK Project
# Authors:
# Contributors: Mike Schuster, Michael Wayne Goodman, Liling Tan
# URL: <https://www.nltk.org/>
# For license information, see LICENSE.TXT
""" GLEU score implementation. """
from collections import Counter
from nltk.util impor... |
17,093 | bc6c4875c1f5eb5369db0c312c5b8c540a5bad69 | """
URLs for the wagtail admin dashboard.
"""
from django.urls import path
from wagtailcache.views import clear
from wagtailcache.views import index
urlpatterns = [
path("", index, name="index"),
path("clearcache", clear, name="clearcache"),
]
|
17,094 | 92827a868d83caefbe42437b46c5916eaf0fce7b | from typing import List
from omtools.core.variable import Variable
from omtools.core.input import Input
def collect_input_exprs(
inputs: list,
root: Variable,
expr: Variable,
) -> List[Variable]:
"""
Collect input nodes so that the resulting ``ImplicitComponent`` has
access to inputs outside ... |
17,095 | 67fe5fded35c9a5d4209de75e6c5cecf967cf4e9 | import os, argparse
import tensorflow as tf
from tensorflow.python.framework import graph_util
from tensorflow import keras
from os import listdir
from os.path import isfile, isdir, join
if __name__ == '__main__':
mypath = "I:\dataSet/training dataset"
# 取得所有檔案與子目錄名稱
dfiles = listdir(mypa... |
17,096 | ef7fb657938868481371ad34c6b52f291464a6a5 | B'''
Created on Nov 15, 2010
@0;278;0cauthor: surya
'''
import os
import sys
import time
import json
import email
import rfc822
import pycurl
import imaplib
import logging
import cStringIO
import string
from ImageUtils.ImageCache import ImageCache
from ImageUtils.sampleExifN80 import get_original_datetime_N80
from Lo... |
17,097 | 2d844dad3a8931b8da6946c3502cef466e0f0b80 | from tensorflow.keras.optimizers import Adam, SGD, RMSprop
from config import emotion_config as config
from hdf5datasetgenerator import HDF5DatasetGenerator
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from emotionModel import EmotionDetectModel
from... |
17,098 | 2091b82c86dd0683df3a4604338f540a3259cf3e | from itertools import permutations
def possible_permutations(elements):
perm = permutations(elements)
for p in perm:
yield list(p)
[print(n) for n in possible_permutations([1, 2, 3])]
|
17,099 | d59da234469146b33a081d70e8ff2deff22292f4 | from detection_api import Detector
from detection_api.utils.parse_config import *
from detection_api.utils.utils import *
import cv2
import os
import os.path as osp
import numpy as np
from PIL import Image
from settings import Settings
import utils
from lxml import etree as Element
class BBoxClass:
def __init__(se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.