index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
4,900 | cf9339659f49b4093c07e3723a2ede1543be41b8 | from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from recensioni_site import settings
from django.contrib.auth.models import User
from forum.models import Sezione,Post,UserDataReccomandation
class testRegistrazione(TestCase):
def setUp(self):
self.credent... |
4,901 | 266ce1aaa3283cf2aaa271a317a80c3860880a49 | from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'foo.views.home', name='home'),
# url(r'^foo/', include('foo.foo.urls')),
# Uncomm... |
4,902 | c853f922d1e4369df9816d150e5c0abc729b325c | # This file is used to run a program to perform Active measuremnts
import commands
import SocketServer
import sys
#Class to handle Socket request
class Handler(SocketServer.BaseRequestHandler):
def handle(self):
# Get the IP of the client
IP = self.request.recv(1024)
#print 'IP=' + IP
... |
4,903 | 121fddf022c4eed7fd00e81edcb2df6a7a3b7510 | #!/usr/bin/env python3
from collections import deque
from itertools import permutations
INS_ADD = 1
INS_MULTIPLY = 2
INS_INPUT = 3
INS_OUTPUT = 4
INS_JUMP_IF_TRUE = 5
INS_JUMP_IF_FALSE = 6
INS_LESS_THAN = 7
INS_EQUALS = 8
INS_ADJUST_RELATIVE_BASE = 9
INS_DONE = 99
... |
4,904 | a3cbdecbbfc49e8ac045f4aabbea6b9f54ed3d5f | class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insertAtHead(self, newNode, curNode):
newNode.next = curNode
if curNode is not None: curNode.prev = newNode
... |
4,905 | 67446f50d1c062eddcad282d3bf508967c5192fc | from network.utility import *
from entities.message import Message, BroadcastMessage, GroupMessage
from entities.node import Node
from entities.group import GroupBroadcast
from entities.request import Request
import threading
import time
import logging
import random
import json
import socket
from services.user import U... |
4,906 | ccf1710cff972eaa06e1ccb5ebedc70d946e3215 | from . import views
from django.conf.urls import url,re_path
enquiryUrlPattern = [
url(r'daily-rate-enquiry', views.daily_rate_enquiry_form),
re_path(r'^contact-us-landing-page/$', views.contact_us_landing_page),
]
|
4,907 | 675d564ad60870f49b88dece480d5a50a30491df | try:
import RPi.GPIO as GPIO
import time
import numpy as np
import matplotlib.pyplot as plt
from os.path import dirname, join as pjoin
from scipy.io import wavfile
import scipy.io
except ImportError:
print ("Import error!")
raise SystemExit
try:
chan_list = (26, 19, 13, 6, 5, 1... |
4,908 | a83230e71cc1bcc843d00487746f16114d304eec | # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY ... |
4,909 | 53110d6e7923cf65c514d54950a0be165582e9a0 | from basetest import simtest
import testutil
import logging, random
from nitro_parts.lib.imager import ccm as CCM
import numpy
###############################################################################
class DotProductTest(simtest):
def _set_coeff(self, c):
cq = (c * 32).astype(numpy.uint8)
... |
4,910 | 55d4f4bba2b72ec93cb883527d2a9c2ebe8ec337 | from __future__ import annotations
import logging
import os
import sys
from argparse import Namespace
from pathlib import Path
from uuid import uuid4
import pytest
from virtualenv.discovery.builtin import Builtin, get_interpreter
from virtualenv.discovery.py_info import PythonInfo
from virtualenv.info import fs_supp... |
4,911 | e56a7912b9940b1cab6c19d0047f1f60f0083f66 | from data_structures.datacenter import Datacenter, urllib, json,
URL = "http://www.mocky.io/v2/5e539b332e00007c002dacbe"
def get_data(url, max_retries=5, delay_between_retries=1):
"""
Fetch the data from http://www.mocky.io/v2/5e539b332e00007c002dacbe
and return it as a JSON object.
Args:
... |
4,912 | eeece3bf423f85f05ef11db47909215578e64aec | from application.routes import pad_num, tracking_gen
from flask import url_for
from flask_testing import TestCase
from application import app, db
from application.models import Users, Orders
from os import getenv
class TestCase(TestCase):
def create_app(self):
app.config.update(
SQLALCHEMY_DA... |
4,913 | 21fb9622add4d19b2914118e3afd3867b2368a50 | #/usr/bin/env python3
def nth_prime(n):
ans = 2
known = []
for _ in range(n):
while not all(ans%x != 0 for x in known):
ans += 1
known.append(ans)
return ans
if __name__ == "__main__":
n = int(input("Which one? "))
print(nth_prime(n))
|
4,914 | 6bd423223e1ec2bb3a213158ac6da3a6483b531f | from django.db import models
from accounts.models import User
from cmdb.models.base import IDC
from cmdb.models.asset import Server, NetDevice
class CPU(models.Model):
# Intel(R) Xeon(R) Gold 5118 CPU @ 2.30GHz
version = models.CharField('型号版本', max_length=100, unique=True)
speed = models.PositiveSmallInt... |
4,915 | 9f8d79d141d414c1256e39f58e59f97711acfee4 | #!/usr/bin/env python3
"""
Main chat API module
"""
import json
import os
import signal
import traceback
import tornado.escape
import tornado.gen
import tornado.httpserver
import tornado.ioloop
import tornado.locks
import tornado.web
from jsonschema.exceptions import ValidationError
from db import DB, DatabaseError
... |
4,916 | 8b965fd91396735e0153390b4eff540d3aac3aff | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2020, Lukas Bestle <project-ansible@lukasbestle.com>
# Copyright: (c) 2017, Michael Heap <m@michaelheap.com>
# 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_f... |
4,917 | 7da5a7476c807619bed805cb892774c23c04c6f7 | from django import forms
class LoginForm(forms.Form):
usuario=forms.CharField(label="Usuario",max_length=20, required=True, widget=forms.TextInput(
attrs={'class':'form-control'}
))
contraseña=forms.CharField(label="Contraseña",max_length=20, widget=forms.PasswordInput(
attrs={'class':'for... |
4,918 | 6072fc22872ee75c9501ac607a86ee9137af6a5d | def readfasta (fasta):
input = open(fasta, 'r')
seqs = {}
for line in input:
if line[0] == '>':
name = line[1:].rstrip()
seqs[name] = []
else:
seqs[name].append(line.rstrip())
for name in seqs:
seqs[name] = ''.join(seqs[name])
r... |
4,919 | 6e8ef901fc614ecbba25df01f84a43c429f25cf6 | #!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
n_points = 100
n_sims = 1000
def simulate_one_realisation():
return np.random.normal(1, 2, size=n_points)
def infer(sample):
return {'mean': np.mean(sample), 'std': np.std(sample)}
inference = [infer(simulate_one_realisation()) for _ ... |
4,920 | 6f1b08a5ae1a07a30d89f3997461f4f97658f364 | import logging
from .const import (
DOMAIN,
CONF_SCREENS
)
from typing import Any, Callable, Dict, Optional
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.typing import (
ConfigType,
DiscoveryInfoType,
HomeAssistantType,
)
from homeassistant.core import callback
from home... |
4,921 | 93fe16e5a97ec2652c4f6b8be844244d9776ea2e | from tkinter import *
# Everything in tkinter is a widget
# We start with the Root Widget
root = Tk()
# Creating a Label Widget
myLabel1 = Label(root, text="Hello User!")
myLabel2 = Label(root, text="Welcome to medBOT")
# Put labels onto the screen
myLabel1.grid(row=0, column=0)
myLabel2.grid(row=1, column=0)
# Grid... |
4,922 | 98d2196439a8dc3d511d176e61897aa67663a0b5 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: NVLGPSStatus.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _... |
4,923 | 3b26181097025add5919e752aa53e57eea49c943 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
##########
# websocket-client
# https://pypi.python.org/pypi/websocket-client/
# sudo -H pip install websocket-client
#####
from websocket import create_connection
ws = create_connection( "ws://192.168.1.132:81/python" )
msg = '#0000FF'
print "Envoi d’un message à l’ESP"... |
4,924 | cde62c5032109bb22aa81d813e30097dad80a9c3 | # -*- coding: utf-8 -*-
#
# Akamatsu CMS
# https://github.com/rmed/akamatsu
#
# MIT License
#
# Copyright (c) 2020 Rafael Medina García <rafamedgar@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
... |
4,925 | 9e8ddf6c35ebad329e1f5a48513e4bfaae0d9a6f | import collections
import datetime
import os
import pickle
import random
import time
from lastfm_utils import PlainRNNDataHandler
from test_util import Tester
reddit = "subreddit"
lastfm = "lastfm"
instacart = "instacart"
#
# Choose dataset here
#
dataset = lastfm
#
# Specify the correct path to the dataset
#
datase... |
4,926 | 9fa1dab7cb0debf363ae0864af1407c87aad063a | # 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, software
# d... |
4,927 | 795f936423965063c44b347705c53fd1c306692f | # Generated by Django 3.0.3 on 2020-05-30 05:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('people', '0110_auto_20200530_0631'),
]
operations = [
migrations.AlterField(
model_name='site',
name='password_reset... |
4,928 | be37a7596850050af58f735e60bdf13594715caf | a,b,c,d=map(int,input().split())
ans=0
if a>=0:
if c>=0:
ans=b*d
elif d>=0:
ans=b*d
else:
ans=a*d
elif b>=0:
if c>=0:
ans=b*d
elif d>=0:
ans=max(b*d,a*c)
else:
ans=a*c
else:
if c>=0:
ans=b*c
elif d>=0:
ans=a*c
else:
... |
4,929 | b453c8e9cc50066d1b5811493a89de384a000f37 | from django.shortcuts import render, redirect
from datetime import datetime
from fichefrais.models import FicheFrais, Etat, LigneFraisForfait, LigneFraisHorsForfait, Forfait
def home_admin(request):
"""
:view home_admin: Menu principale des Administrateurs
:template home_admin.html:
"""
if not re... |
4,930 | f0ff15a2392b439a54c5ec304192117c08978755 | from api.serializers.cart import CartSerializer
from api.serializers.product import ProductSerializer, ProductPopular
from api.serializers.type import TypeSerializer
from api.serializers.user import UserCreationSerializer, UserSerializer
from api.serializers.history import HistorySerializer
from api.serializers.order i... |
4,931 | d5efbbb6e818e797652f304f3d022e04be245778 | import os
import unittest
import tempfile
from bpython import config
TEST_THEME_PATH = os.path.join(os.path.dirname(__file__), "test.theme")
class TestConfig(unittest.TestCase):
def test_load_theme(self):
struct = config.Struct()
struct.color_scheme = dict()
config.load_theme(struct, TEST... |
4,932 | 2e5bbc8c6a5eac2ed71c5d8619bedde2e04ee9a6 | __version__ = '1.1.3rc0'
|
4,933 | e12905efa0be7d69e2719c05b40d18c50e7e4b2e | import re
# Wordcount: count the occurrences of each word in that phrase.
def word_count(phrase):
phrase = re.sub(r'\W+|_', ' ', phrase.lower(), flags=re.UNICODE)
word_list = phrase.split()
wordfreq = [word_list.count(p) for p in word_list]
return dict(zip(word_list, wordfreq))
|
4,934 | 59a75f78c7a146dcf55d43be90f71abce2bcf753 | from tkinter import *
root = Tk()
root.title("Calculator")
e = Entry(root, width = 50, borderwidth = 5)
e.grid(row = 0, column = 0, columnspan = 4, padx = 10, pady = 20)
def button_click(number):
digit = e.get()
e.delete(0, END)
e.insert(0, str(digit) + str(number))
def button_add():
global first_... |
4,935 | 929f580e8e559f8309e19f72208bf4ff0d537668 | x = str(input("please input your name:"))
y = int(input("please input your age:"))
p = int(2017-y+100)
print("your name is:"+x)
print (p) |
4,936 | 00af9627242648a5a16a34a18bfc117945f1bc08 | import requests
if __name__ == "__main__":
# individual datacake webhook url
# Change this to the webhook url of your datacake device/product
datacake_url = "https://api.datacake.co/integrations/api/ae6dd531-4cf6-4966-b5c9-6c43939aae90/"
# Serial number
# Include Serial Number in Payload so Datac... |
4,937 | 4d31357936ce53b2be5f9a952b99df58baffe7ea | import webbrowser
import time
x=10
while x > 0:
print (x), time.sleep(1)
x=x-1
while x==0:
print ("MEOW")
webbrowser.open("https://www.youtube.com/watch?v=IuysY1BekOE")
|
4,938 | fc04623db0d07f3a0a55ad49a74643a74e5203a6 | from sys import stdin
def main():
lines = stdin
n, k = map(int, lines.next().split())
if k > n:
print -1
else:
arr = map(int, lines.next().split())
arr.sort(reverse = True)
print "%d %d" % (arr[k - 1], arr[k - 1])
main()
|
4,939 | b377a652eec55b03f689a5097bf741b18549cba0 | #상관분석
"""
유클리디안 거리 공식의 한계점: 특정인의 점수가 극단적으로 높거나 낮다면 제대로된 결과를 도출해내기 어렵다.
=>상관분석:두 변수간의 선형적 관계를 분석하겠다는 의미
"""
#BTS와 유성룡 평점, 이황, 조용필
import matplotlib as mpl
mpl.rcParams['axes.unicode_minus']=False #한글 깨짐 방지
from matplotlib import font_manager, rc
import matplotlib.pyplot as plt
from math import sqrt
font_name ... |
4,940 | 5c15252611bee9cd9fbb5d91a19850c242bb51f1 | import json
import yaml
import argparse
import sys
def json2yaml(json_input, yaml_input):
json_data = json.load(open(json_input, 'r'))
yaml_file = open(yaml_input, 'w')
yaml.safe_dump(json_data, yaml_file, allow_unicode=True, default_flow_style=False)
yaml_data = yaml.load_all(open(yaml_input, 'r'), L... |
4,941 | ec395b93cecf8431fd0df1aa0151ebd32244c367 |
class RetModel(object):
def __init__(self, code = 0, message = "success", data = None):
self.code = code
self.msg = message
self.data = data
|
4,942 | 1f63ce2c791f0b8763aeae15df4875769f6de848 | # Generated by Django 2.1.7 on 2019-03-23 17:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('currency_exchange', '0007_auto_20190323_1751'),
]
operations = [
migrations.AddField(
model_name='tasks',
name='hour... |
4,943 | e59a51641dc2966b0170678de064e2845e170cf5 | from typing import Tuple, List
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
self.constraints = []
def __str__(self):
return f"({self.x}, {self.y})"
class Line:
def __init__(self, point1, point2):
if isinstance(point1, Point):
... |
4,944 | 8917481957ecd4c9692cfa93df0b759feaa344af | while True:
print("running")
|
4,945 | bb81027ed5311e625591d98193997e5c7b533b70 | """
This is the interface that allows for creating nested lists.
You should not implement it, or speculate about its implementation
class NestedInteger(object):
def isInteger(self):
# @return {boolean} True if this NestedInteger holds a single integer,
# rather than a nested list.
def getInteg... |
4,946 | 458bc2b5f843e4c5bb3f9180ab2cbec7409b8d3e | # dates.py
"""Date/time parsing and manipulation functions
"""
# Some people, when confronted with a problem, think
# "I know, I'll use regular expressions."
# Now they have two problems.
# -- Jamie Zawinski
import datetime as dt
import time
import re
_months = [
'january',
'... |
4,947 | 640eae824e43e394bf0624dd4cf7dcec78f43604 | #Eyal Reis - 203249354
from view import View
def main():
"""
primary game method
"""
view = View()
view.root.mainloop()
if __name__ == "__main__":
main()
|
4,948 | 4a886437727ed6b48206e12b686a59a1d2a1c489 | # Counts number of dumbbell curls in the video
import cv2
import mediapipe as mp
import base
import math
import numpy as np
class PoseEstimator(base.PoseDetector):
def __init__(self, mode=False, upperBody = False, smooth=True, detectConf=.5, trackConf=.5,
outFile="output.mp4", outWidth=720, outHe... |
4,949 | 9f478df4ff19cfe6c6559b6489c874d49377b90e | """
A module to generate simulated 2D time-series SOSS data
Authors: Joe Filippazzo
"""
import os
from pkg_resources import resource_filename
import multiprocessing
import time
from functools import partial
import warnings
import numpy as np
from astropy.io import fits
from bokeh.plotting import figure, show
from ho... |
4,950 | 4cb5dcf0d943ef15421bb6bced65804533d232e3 | import mysql.connector
import hashlib
import time
from datetime import datetime
from datetime import timedelta
from pymongo import MongoClient
from pymongo import IndexModel, ASCENDING, DESCENDING
class MongoManager:
def __init__(self, server_ip='localhost', client=None, expires=timedelta(days=30)):
""... |
4,951 | 6a9d64b1ef5ae8e9d617c8b0534e96c9ce7ea629 |
import os
import config
############################
# NMJ_RNAI LOF/GOF GENE LIST
def nmj_rnai_set_path():
return os.path.join(config.datadir, 'NMJ RNAi Search File.txt')
def nmj_rnai_gain_of_function_set_path():
return os.path.join(config.datadir, 'NMJ_RNAi_gain_of_function_flybase_ids.txt')
def get_n... |
4,952 | 3b96cc4ef538a06251958495e36fe5dbdf80c13d | import asyncio
def callback():
print('callback invoked')
def stopper(loop):
print('stopper invoked')
loop.stop()
event_loop = asyncio.get_event_loop()
try:
print('registering callbacks')
# the callbacks are invoked in the order they are scheduled
event_loop.call_soon(callback)
event_loop.... |
4,953 | a01f812584e4cee14c9fe15e9fb6ede4ae3e937a | import os
import pickle
from matplotlib import pyplot as plt
cwd = os.path.join(os.getcwd(), 'DEDA_2020SS_Crypto_Options_RND_HD',
'CrypOpt_RiskNeutralDensity')
data_path = os.path.join(cwd, 'data') + '/'
day = '2020-03-11'
res = pickle.load(open(data_path + 'results_{}.pkl'.format(day), 'rb'))
... |
4,954 | d89f0ef24d8e8d23a77cbbb0ae8723c7dec8c00a | class Config:
DEBUG = False
TESTING = False
# mysql+pymysql://user:password@host:port/database
# SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://gjp:976431@49.235.194.73:3306/test'
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@127.0.0.1:3306/mydb'
SQLALCHEMY_TRACK_MODIFICATIONS = True
SECR... |
4,955 | dc928da92dc7e8a37a7f32dd4a579fd09b89eb01 | __author__ = 'jacek gruzewski'
#!/user/bin/python3.4
"""
To do: throw exceptions rather than calling sys.exit(1)
"""
############################################################
# IMPORTS
############################################################
# Python's libraries
import time
import sys
import logging
imp... |
4,956 | a54c8ab63c1e0f50d254d6c97ca3f167db7142e9 | import sys
sys.path.append('../')
from IntcodeComputer.intcode import Program
if __name__ == '__main__':
fn = 'input.txt'
with open(fn) as f:
program = Program([int(i) for i in f.readline().split(',')])
program.run()
result = program.instructions
|
4,957 | 394ebfe25bbf8eaf427509f28a82a98b9b481b63 | from .dispatch import dispatch_expts |
4,958 | ea25aedc4728c18ac3d5da22c76cb7f1ef65e827 | from tw.core import *
|
4,959 | 02b760b16cdcd42f8d8d7222b439da87fb8076a3 | import numpy as np
from flask import Flask,request,render_template
import pickle
from werkzeug.serving import run_simple
app=Flask(__name__,template_folder='template')
model=pickle.load(open("model.pkl",'rb'))
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict',me... |
4,960 | 27c364ccf4a6703f74c95ebb386f8ced38b1eafd | try:
from zcrmsdk.src.com.zoho.crm.api.dc.data_center import DataCenter
except Exception as e:
from .data_center import DataCenter
class EUDataCenter(DataCenter):
"""
This class represents the properties of Zoho CRM in EU Domain.
"""
@classmethod
def PRODUCTION(cls):
"""
... |
4,961 | 0e8a11c5b5a95929c533597d79ee4f3d037c13e0 | """
bets.models
Models relating to bets placed
"""
import datetime
from mongoengine import *
from decimal import Decimal
from app.groups.models import Group
from app.users.models import User
from app.matches.models import Match
from app.project.config import CURRENCIES
class GroupMatch(Document):
"""Associate ea... |
4,962 | 16bf4583b872f038edccbac4e567c1854d65e216 | import tensorflow as tf
import numpy as np
def safe_nanmax(x):
with np.warnings.catch_warnings():
np.warnings.filterwarnings('ignore',
r'All-NaN (slice|axis) encountered')
return np.nanmax(x)
def safe_nanargmax(x):
try:
return np.nanargmax(x)
ex... |
4,963 | 79e8ed64058dda6c8d7bacc08727bc978088ad2d | # %%
import pandas as pd
import numpy as np
from dataprep.eda import plot
from dataprep.eda import plot_correlation
from dataprep.eda import plot_missing
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="whitegrid", color_codes=True)
sns.set(font_scale=1)
# %%
# Minimal Processing
wines = pd.read... |
4,964 | d1fe06766958e8532c49d33e887d6c4996573c22 | #!/usr/bin/env python
import optparse
import os
import shutil
import sys
from AutoCrab.AutoCrab2 import core
def main():
parser = optparse.OptionParser()
parser.add_option("-r", "--recursive", dest="recursive", action="store_true", help="Recursively look for CRAB job files and directories.")
(opts, args) = parser... |
4,965 | 0f1bad350faaff6aab339944b4d24c4801fa8c64 | from itertools import count, islice
from math import sqrt
def is_prime(x):
if x<2:
return False
for i in range(2, int(sqrt(x)) + 1):
if x%i == 0:
return False
return True
def primes(x):
return islice((p for p in count() if is_prime(p)), x)
print(list(primes(1000))[-10:])
... |
4,966 | 836df02495ee581f138050be6b7a7a076ea899eb | from .base import * # noqa
from .base import env
# exemple https://github.com/pydanny/cookiecutter-django/blob/master/%7B%7Bcookiecutter.project_slug%7D%7D/config/settings/production.py
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/r... |
4,967 | 33e9e45fbe0e3143d75d34c1db283c01e2693f68 | import json
import pandas as pd
import matplotlib.pyplot as plt
f = open('Maradona-goals.json')
jsonObject = json.load(f)
f.close()
l = []
for c, cl in jsonObject.items():
for d in cl:
d.update({'player' : c})
l.append(d)
df = pd.DataFrame(l)
labels = df["year"]
width = 0.75
fig = plt.figure(f... |
4,968 | 1b773f2ca01f07d78d2d7edc74cd2df6630aa97a | import pandas as pd
import numpy as np
#I'm adding these too avoid any type of na value.
missing_values = ["n/a", "na", "--", " ?","?"]
# Name Data Type Meas. Description
# ---- --------- ----- -----------
# Sex nominal M, F, and I (infant)
# Length continuous mm Longest shell measurement
# Diameter con... |
4,969 | 38f7c529cd0a8d85de266c6a932e6c8342aee273 | # -*- coding: utf-8 -*-
'''
=======================================================================
AutoTest Team Source File.
Copyright(C), Changyou.com
-----------------------------------------------------------------------
Created: 2017/3/2 by ChengLongLong
----------------------------------------------------... |
4,970 | 55ea522b096b189ff67b0da0058af777b0a910e3 | """These are views that are used for viewing and editing characters."""
from django.contrib import messages
from django.contrib.auth.mixins import UserPassesTestMixin,\
LoginRequiredMixin, PermissionRequiredMixin
from django.db import transaction
from django.db.models import F
from django.http import HttpResponseR... |
4,971 | c5842b17b2587149cd13448593a6ed31b091ba77 | import sys
from sklearn.svm import SVC
from sklearn.model_selection import KFold,cross_validate,GridSearchCV
from data_prepr import data_preprocessing
import numpy as np
def main():
#if dataset is not provided on call terminate
if len(sys.argv)<2:
print("usage: python svm_parameter_tuning.py <input_file> ")
sys... |
4,972 | 3eeed39bf775e2ac1900142b348f20d15907c6e6 | """
@author Lucas
@date 2019/3/29 21:46
"""
# 二分查找
def search(nums, target):
left = 0
right = len(nums) - 1
while left <= right:
mid = int((left + right)/2)
if target > nums[mid]:
left = mid + 1
elif target < nums[mid]:
right = mid - 1
else:
... |
4,973 | d8e2613b45b3f4a24db0b07a01061c6057c9feed | from lredit import *
# customization of MainWindow
def configure(window):
#----------------------------------------------
# Generic edit config
# tab width and indent width
Mode.tab_width = 4
# make TAB character visible
Mode.show_tab = True
# make space character visible
Mode.sh... |
4,974 | 953186a330ae9dff15c037b556746590d748c7ad | from django import forms
class SignupAliasForm(forms.Form):
alias = forms.CharField(max_length=20, required=True)
email_secret = forms.CharField(max_length=100, required=True) |
4,975 | f831b77850dfe22232092f66705e36970828a75b | import os
import re
import click
import pandas as pd
from pymongo import MongoClient
from pathlib import Path, PurePath
def extract_dir_name(input_file):
"""
creates a directory path based on the specified file name
:param input_file: file bane
:return: full path, minus extension
"""
... |
4,976 | a1f0eced5d122fe8557ebc4d707c87b4194513e3 | import subprocess
import logging
import time
import argparse
import threading
import os
import matplotlib.pyplot as plt
import numpy as np
import argparse
def runWeka(wekapath, modelpath, datapath):
os.chdir(wekapath)
proc = subprocess.Popen(['/usr/bin/java', '-classpath', 'weka.jar', 'weka.classifiers.functio... |
4,977 | 3f5ae2b25fc506b980de3ee87c952ff699e10003 | import numpy as np
import cv2
import sys
import math
cap = cv2.VideoCapture(0)
while(True):
_, img = cap.read()
#gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img = cv2.imread("zielfeld_mit_Zeugs_2.png")
#img = cv2.imread("zielfeld_mit_Zeugs_2.jpg")
#imS = cv2.resize(img, (480, 480... |
4,978 | 0878bfa1151371ff3aaa59f8be5ea9af74ada331 | from django import forms
class UploadForm(forms.Form):
file = forms.FileField(label="Json с данными об отправлении")
|
4,979 | 7955479c70de679cfb7575c8bd9208d00a4893df | from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
import json
class AsyncConsumer(AsyncWebsocketConsumer):
chats = dict()
async def connect(self): # 连接时触发
self.room_name = self.scope... |
4,980 | 39b9106a3b0305db8cc7316be3b76e58e5577b92 | #adapted from https://github.com/DeepLearningSandbox/DeepLearningSandbox/tree/master/transfer_learning
import os
import sys
import glob
import argparse
import matplotlib.pyplot as plt
from keras.applications.imagenet_utils import preprocess_input
from keras.models import Model
from keras.layers import GlobalAveragePo... |
4,981 | 2bf5ec4b4c0f0eed8364dcc9f1be599a804846f2 | # Generated by Django 2.2.7 on 2019-11-23 18:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ml', '0003_auto_20191123_1835'),
]
operations = [
migrations.AlterField(
model_name='ml',
name='file',
f... |
4,982 | da783355c5f888a66f623fa7eeeaf0e4e9fcfa48 | # Generated by Django 3.0.5 on 2020-05-18 12:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cart', '0010_auto_20200518_1718'),
]
operations = [
migrations.AlterField(
model_name='order',
name='fianl_code',
... |
4,983 | a521220ac287a840b5c69e2d0f33daa588132083 | from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_ssh_public_key
from ingredients_http.schematics.types import ArrowType, KubeName
from schematics import Model
from schematics.exceptions import ... |
4,984 | 572a098053ebae4f42cd020d1003cc18eceb6af0 | # encoding: utf-8
'''
Created on Nov 26, 2015
@author: tal
Based in part on:
Learn math - https://github.com/fchollet/keras/blob/master/examples/addition_rnn.py
See https://medium.com/@majortal/deep-spelling-9ffef96a24f6#.2c9pu8nlm
"""
Modified by Pavel Surmenok
'''
import argparse
import numpy as np
from keras.l... |
4,985 | d56e313318635788ae5b3d3a3f767450ab2f2296 | # Copyright 2011 Isaku Yamahata
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
4,986 | f5331b56abea41873bd3936028471d0da1c58236 | #Developer: Chritian D. Goyes
'''
this script show your name and your age.
'''
myName = 'Christian D. Goyes'
myDate = 1998
year = 2020
age = year - myDate
print ("yourname is: ", age, "and your are", "years old") |
4,987 | 7ea1ee7c55cd53f7137c933790c3a22957f0ffea | from django.db import models
from django.core.validators import RegexValidator, MaxValueValidator
# from Delivery.models import Delivery
# from Customers.models import Customer, Address, Order, Item
# Create your models here.
class Restaurant(models.Model):
Restaurant_ID = models.AutoField(primary_key=True)
... |
4,988 | 4f93af104130f5a7c853ee0e7976fd52847e588a | from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth import get_user_model
from .models import Profile
User = get_user_model()
# this wan't run on creating superuser
@receiver(post_save, sender=User)
def save_profile(sender, created, instance, **kwargs):
if ... |
4,989 | 0125abab0312d8f007e76ee710348efc9daae31e | # First, we'll import pandas, a data processing and CSV file I/O library
import pandas as pd
# We'll also import seaborn, a Python graphing library
import warnings # current version of seaborn generates a bunch of warnings that we'll ignore
warnings.filterwarnings("ignore")
import seaborn as sns
import matplotlib.py... |
4,990 | 739921a6a09edbb81b442f4127215746c601a69a | # Written by Jagannath Bilgi <jsbilgi@yahoo.com>
import sys
import json
import re
"""
Program accepts *.md document and converts to csv in required format
Program parse line by line and uses recursive method to traverse from leaf to root.
Single turn object (string, int etc) is used as point of return from recursio... |
4,991 | 0ced42c8bfaad32fc2b397326150e6c7bc5cedab | import torch
from training import PointNetTrain, PointAugmentTrain, Model
#from PointAugment.Augment.config import opts
from data_utils.dataloader import DataLoaderClass
from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
import numpy as np
import yaml
def visualize_batch(pointclouds, pred_labels, labels,... |
4,992 | f4ea36c3154f65c85647da19cfcd8a058c507fe1 | from flask import Flask
from apis import api
app = Flask(__name__)
app.config.from_object('config')
api.init_app(app)
if __name__ == "__main__":
app.run() |
4,993 | 1a561ca0268d084c8fdde5de65ce0c7e68154eec | # -*- coding: utf-8 -*-
import urllib
from urllib2 import HTTPError
from datetime import datetime
from flask.views import MethodView
from flask.ext.login import current_user, login_required
from flask.ext.paginate import Pagination as PaginationBar
from flask import render_template, redirect, url_for, request, jsonify... |
4,994 | 38751da57ad7c786e9fc0722faf065380e5f7e60 | # Generated by Django 3.1.1 on 2020-10-10 07:38
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),
('socialapp', '0004_mesage... |
4,995 | efba815fe64cddb5315b17b2cbaf1d3fc38c11ee | from django.db import models
import string
import random
def id_generator(size=32, chars=string.ascii_uppercase + string.digits):
exists = True
while exists == True:
ran = ''.join(random.choice(chars) for _ in range(size))
if len(Item.objects.filter(random_str=ran)) == 0:
exists = False
return ran
# Crea... |
4,996 | da98835e48a759cbe7bd29ddba1fac20c006827d | from ortools.sat.python import cp_model
import os
import math
import csv
import sys
def ortoolsSolverReduceVar(num, cap, refill, fun, goal):
model = cp_model.CpModel()
token = [model.NewIntVar(-2147483648, 2147483647, 't%i' % i)
for i in range(1, num + 1)]
play = [model.NewIntVar(-2147483648, ... |
4,997 | 43db8ed10face1c668aeadd3cbc5b13f87fb0126 | import os
import time
import torch
from torch.utils.data import DataLoader
from torchvision.datasets import SVHN
from torchvision.transforms import ToTensor
from lib.utils import Logger, normal_logpdf, sumflat, print_model_info, tanh_to_uint8, get_optimizer
from lib.vae import VAE
def train(hp):
os.makedirs(hp.o... |
4,998 | 9f38148c19f0cb9522725d9eb27c91f70055cba1 | import sys
sys.stdin = open("input.txt", "r")
stick = input()
cnt = 0
temp =[]
for i,s in enumerate(stick):
#'('나오면 무조건 추가
if s == '(':
temp.append(s)
else:
#절단인 경우
if stick[i-1] == '(':
temp.pop()
cnt += len(temp)
#길이가 짧아 아웃
els... |
4,999 | a9302dbf724f9548411fbf2959f36b4cc5742ff8 | import os
from os.path import join
import json
import pandas as pd
import time
import numpy as np
import torch
def str2bool(v):
# convert string to boolean type for argparser input
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.