index int64 0 100k | blob_id stringlengths 40 40 | code stringlengths 7 7.27M | steps listlengths 1 1.25k | error bool 2
classes |
|---|---|---|---|---|
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... | [
"from django.test import TestCase\nfrom django.urls import reverse\nfrom django.utils import timezone\n\nfrom recensioni_site import settings\nfrom django.contrib.auth.models import User\nfrom forum.models import Sezione,Post,UserDataReccomandation\n\nclass testRegistrazione(TestCase):\n\n def setUp(self):\n ... | false |
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... | [
"from django.conf.urls.defaults import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'foo.views.home', name='home'),\n # url(r'^foo/', include('foo.foo.urls')),... | false |
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
... | [
"# This file is used to run a program to perform Active measuremnts\n\n\nimport commands\nimport SocketServer\nimport sys\n\n#Class to handle Socket request\nclass Handler(SocketServer.BaseRequestHandler):\n\n def handle(self):\n\n # Get the IP of the client\n IP = self.request.recv(1024)\n\n ... | true |
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
... | [
"#!/usr/bin/env python3\n\n\nfrom collections import deque\nfrom itertools import permutations\n\n\nINS_ADD = 1\nINS_MULTIPLY = 2\nINS_INPUT = 3\nINS_OUTPUT = 4\nINS_JUMP_IF_TRUE = 5\nINS_JUMP_IF_FALSE = 6\nINS_LESS_THAN = 7\nINS_EQUALS = 8\nINS_ADJUST_RELATIVE_BASE = 9\nIN... | false |
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
... | [
"class Node:\n def __init__(self, data):\n self.data = data\n self.prev = None\n self.next = None\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n\n def insertAtHead(self, newNode, curNode):\n newNode.next = curNode\n if curNode is not None: curN... | false |
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... | [
"from network.utility import *\nfrom entities.message import Message, BroadcastMessage, GroupMessage\nfrom entities.node import Node\nfrom entities.group import GroupBroadcast\nfrom entities.request import Request\nimport threading\nimport time\nimport logging\nimport random\nimport json\nimport socket\nfrom servic... | false |
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),
]
| [
"from . import views\nfrom django.conf.urls import url,re_path\n\nenquiryUrlPattern = [\n url(r'daily-rate-enquiry', views.daily_rate_enquiry_form),\n re_path(r'^contact-us-landing-page/$', views.contact_us_landing_page),\n]\n",
"from . import views\nfrom django.conf.urls import url, re_path\nenquiryUrlPatt... | false |
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... | [
"try:\n import RPi.GPIO as GPIO\n import time\n import numpy as np\n import matplotlib.pyplot as plt\n from os.path import dirname, join as pjoin\n from scipy.io import wavfile\n import scipy.io\nexcept ImportError:\n print (\"Import error!\")\n raise SystemExit\n \ntry:\n chan_list = ... | false |
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 ... | [
"# MegEngine is Licensed under the Apache License, Version 2.0 (the \"License\")\n#\n# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT ARRANTIES OR CON... | false |
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)
... | [
"from basetest import simtest\nimport testutil\nimport logging, random\nfrom nitro_parts.lib.imager import ccm as CCM\nimport numpy\n\n\n###############################################################################\nclass DotProductTest(simtest):\n\n def _set_coeff(self, c):\n cq = (c * 32).astype(numpy... | false |
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... | [
"from __future__ import annotations\n\nimport logging\nimport os\nimport sys\nfrom argparse import Namespace\nfrom pathlib import Path\nfrom uuid import uuid4\n\nimport pytest\n\nfrom virtualenv.discovery.builtin import Builtin, get_interpreter\nfrom virtualenv.discovery.py_info import PythonInfo\nfrom virtualenv.i... | false |
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:
... | [
"from data_structures.datacenter import Datacenter, urllib, json,\n\n\nURL = \"http://www.mocky.io/v2/5e539b332e00007c002dacbe\"\n\n\ndef get_data(url, max_retries=5, delay_between_retries=1):\n \"\"\"\n Fetch the data from http://www.mocky.io/v2/5e539b332e00007c002dacbe\n and return it as a JSON object.\n... | true |
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... | [
"from application.routes import pad_num, tracking_gen\nfrom flask import url_for\nfrom flask_testing import TestCase\n\nfrom application import app, db\nfrom application.models import Users, Orders\nfrom os import getenv\n\n\nclass TestCase(TestCase):\n def create_app(self):\n app.config.update(\n ... | false |
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))
| [
"#/usr/bin/env python3\n\ndef nth_prime(n):\n ans = 2\n known = []\n for _ in range(n):\n while not all(ans%x != 0 for x in known):\n ans += 1\n known.append(ans)\n return ans\n\nif __name__ == \"__main__\":\n n = int(input(\"Which one? \"))\n print(nth_prime(n))\n",
"de... | false |
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... | [
"from django.db import models\nfrom accounts.models import User\nfrom cmdb.models.base import IDC\nfrom cmdb.models.asset import Server, NetDevice\n\n\nclass CPU(models.Model):\n # Intel(R) Xeon(R) Gold 5118 CPU @ 2.30GHz\n version = models.CharField('型号版本', max_length=100, unique=True)\n speed = models.Po... | false |
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
... | [
"#!/usr/bin/env python3\n\"\"\"\nMain chat API module\n\"\"\"\n\nimport json\nimport os\nimport signal\nimport traceback\n\nimport tornado.escape\nimport tornado.gen\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.locks\nimport tornado.web\nfrom jsonschema.exceptions import ValidationError\n\nfrom... | false |
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... | [
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2020, Lukas Bestle <project-ansible@lukasbestle.com>\n# Copyright: (c) 2017, Michael Heap <m@michaelheap.com>\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, divis... | false |
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... | [
"from django import forms\n\nclass LoginForm(forms.Form):\n usuario=forms.CharField(label=\"Usuario\",max_length=20, required=True, widget=forms.TextInput(\n attrs={'class':'form-control'} \n ))\n contraseña=forms.CharField(label=\"Contraseña\",max_length=20, widget=forms.PasswordInput(\n att... | false |
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... | [
"def readfasta (fasta):\r\n input = open(fasta, 'r')\r\n seqs = {}\r\n for line in input:\r\n if line[0] == '>':\r\n name = line[1:].rstrip()\r\n seqs[name] = [] \r\n else:\r\n seqs[name].append(line.rstrip())\r\n for name in seqs:\r\n seqs[name] = '... | true |
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 _ ... | [
"#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nn_points = 100\nn_sims = 1000\n\ndef simulate_one_realisation():\n return np.random.normal(1, 2, size=n_points)\n\ndef infer(sample):\n return {'mean': np.mean(sample), 'std': np.std(sample)}\n\ninference = [infer(simulate_one_re... | false |
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... | [
"import logging\nfrom .const import (\n DOMAIN,\n CONF_SCREENS\n)\nfrom typing import Any, Callable, Dict, Optional\nfrom homeassistant.helpers.entity import Entity\nfrom homeassistant.helpers.typing import (\n ConfigType,\n DiscoveryInfoType,\n HomeAssistantType,\n)\nfrom homeassistant.core import c... | false |
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... | [
"from tkinter import *\n\n# Everything in tkinter is a widget\n# We start with the Root Widget\n\nroot = Tk()\n# Creating a Label Widget\nmyLabel1 = Label(root, text=\"Hello User!\")\nmyLabel2 = Label(root, text=\"Welcome to medBOT\")\n\n# Put labels onto the screen\nmyLabel1.grid(row=0, column=0)\nmyLabel2.grid(ro... | false |
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 _... | [
"# Generated by the protocol buffer compiler. DO NOT EDIT!\n# source: NVLGPSStatus.proto\n\nimport sys\n_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))\nfrom google.protobuf import descriptor as _descriptor\nfrom google.protobuf import message as _message\nfrom google.protobuf import ref... | false |
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"... | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n##########\n# websocket-client\n# https://pypi.python.org/pypi/websocket-client/\n# sudo -H pip install websocket-client\n#####\n\nfrom websocket import create_connection\nws = create_connection( \"ws://192.168.1.132:81/python\" )\n\nmsg = '#0000FF'\nprint \"Envoi ... | true |
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
... | [
"# -*- coding: utf-8 -*-\n#\n# Akamatsu CMS\n# https://github.com/rmed/akamatsu\n#\n# MIT License\n#\n# Copyright (c) 2020 Rafael Medina García <rafamedgar@gmail.com>\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Soft... | false |
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... | [
"import collections\nimport datetime\nimport os\nimport pickle\nimport random\nimport time\nfrom lastfm_utils import PlainRNNDataHandler\nfrom test_util import Tester\n\nreddit = \"subreddit\"\nlastfm = \"lastfm\"\ninstacart = \"instacart\"\n\n#\n# Choose dataset here\n#\ndataset = lastfm\n\n#\n# Specify the correc... | false |
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... | [
"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, so... | false |
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... | [
"# Generated by Django 3.0.3 on 2020-05-30 05:32\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('people', '0110_auto_20200530_0631'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='site',\n n... | false |
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:
... | [
"a,b,c,d=map(int,input().split())\nans=0\nif a>=0:\n if c>=0:\n ans=b*d\n elif d>=0:\n ans=b*d\n else:\n ans=a*d\nelif b>=0:\n if c>=0:\n ans=b*d\n elif d>=0:\n ans=max(b*d,a*c)\n else:\n ans=a*c\nelse:\n if c>=0:\n ans=b*c\n elif d>=0:\n ... | false |
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... | [
"from django.shortcuts import render, redirect\nfrom datetime import datetime\nfrom fichefrais.models import FicheFrais, Etat, LigneFraisForfait, LigneFraisHorsForfait, Forfait\n\n\ndef home_admin(request):\n \"\"\"\n :view home_admin: Menu principale des Administrateurs\n :template home_admin.html:\n ... | false |
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... | [
"from api.serializers.cart import CartSerializer\nfrom api.serializers.product import ProductSerializer, ProductPopular\nfrom api.serializers.type import TypeSerializer\nfrom api.serializers.user import UserCreationSerializer, UserSerializer\nfrom api.serializers.history import HistorySerializer\nfrom api.serialize... | false |
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... | [
"import os\nimport unittest\nimport tempfile\n\nfrom bpython import config\n\nTEST_THEME_PATH = os.path.join(os.path.dirname(__file__), \"test.theme\")\n\nclass TestConfig(unittest.TestCase):\n def test_load_theme(self):\n struct = config.Struct()\n struct.color_scheme = dict()\n config.load... | false |
4,932 | 2e5bbc8c6a5eac2ed71c5d8619bedde2e04ee9a6 | __version__ = '1.1.3rc0'
| [
"__version__ = '1.1.3rc0'\n",
"<assignment token>\n"
] | false |
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))
| [
"import re\n# Wordcount: count the occurrences of each word in that phrase.\ndef word_count(phrase):\n phrase = re.sub(r'\\W+|_', ' ', phrase.lower(), flags=re.UNICODE)\n word_list = phrase.split()\n wordfreq = [word_list.count(p) for p in word_list]\n return dict(zip(word_list, wordfreq))\n",
"import... | false |
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_... | [
"from tkinter import *\r\n\r\nroot = Tk()\r\nroot.title(\"Calculator\")\r\n\r\ne = Entry(root, width = 50, borderwidth = 5)\r\ne.grid(row = 0, column = 0, columnspan = 4, padx = 10, pady = 20)\r\n\r\ndef button_click(number):\r\n\tdigit = e.get()\r\n\te.delete(0, END)\r\n\te.insert(0, str(digit) + str(number))\r\n\... | false |
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) | [
"x = str(input(\"please input your name:\"))\ny = int(input(\"please input your age:\"))\n\np = int(2017-y+100)\n\nprint(\"your name is:\"+x)\nprint (p)",
"x = str(input('please input your name:'))\ny = int(input('please input your age:'))\np = int(2017 - y + 100)\nprint('your name is:' + x)\nprint(p)\n",
"<ass... | false |
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... | [
"import requests\n\nif __name__ == \"__main__\":\n\n # individual datacake webhook url\n # Change this to the webhook url of your datacake device/product\n datacake_url = \"https://api.datacake.co/integrations/api/ae6dd531-4cf6-4966-b5c9-6c43939aae90/\"\n\n # Serial number\n # Include Serial Number i... | false |
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")
| [
"import webbrowser\nimport time\nx=10\nwhile x > 0:\n print (x), time.sleep(1)\n x=x-1\nwhile x==0:\n print (\"MEOW\")\n webbrowser.open(\"https://www.youtube.com/watch?v=IuysY1BekOE\")\n",
"import webbrowser\nimport time\nx = 10\nwhile x > 0:\n print(x), time.sleep(1)\n x = x - 1\nwhile x == 0:... | false |
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()
| [
"from sys import stdin\n\ndef main():\n lines = stdin\n n, k = map(int, lines.next().split())\n\n if k > n:\n print -1\n else:\n arr = map(int, lines.next().split())\n arr.sort(reverse = True)\n print \"%d %d\" % (arr[k - 1], arr[k - 1])\n \n\nmain()\n\n"
] | true |
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 ... | [
"#상관분석\r\n\"\"\"\r\n유클리디안 거리 공식의 한계점: 특정인의 점수가 극단적으로 높거나 낮다면 제대로된 결과를 도출해내기 어렵다.\r\n=>상관분석:두 변수간의 선형적 관계를 분석하겠다는 의미\r\n\"\"\"\r\n#BTS와 유성룡 평점, 이황, 조용필\r\nimport matplotlib as mpl\r\nmpl.rcParams['axes.unicode_minus']=False #한글 깨짐 방지\r\nfrom matplotlib import font_manager, rc\r\nimport matplotlib.pyplot as plt\r\nfr... | false |
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... | [
"import json\nimport yaml\nimport argparse\nimport sys\n\ndef json2yaml(json_input, yaml_input):\n json_data = json.load(open(json_input, 'r'))\n yaml_file = open(yaml_input, 'w')\n yaml.safe_dump(json_data, yaml_file, allow_unicode=True, default_flow_style=False)\n\n yaml_data = yaml.load_all(open(yaml... | false |
4,941 | ec395b93cecf8431fd0df1aa0151ebd32244c367 |
class RetModel(object):
def __init__(self, code = 0, message = "success", data = None):
self.code = code
self.msg = message
self.data = data
| [
"\r\nclass RetModel(object):\r\n def __init__(self, code = 0, message = \"success\", data = None):\r\n self.code = code\r\n self.msg = message\r\n self.data = data\r\n",
"class RetModel(object):\n\n def __init__(self, code=0, message='success', data=None):\n self.code = code\n ... | false |
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... | [
"# Generated by Django 2.1.7 on 2019-03-23 17:14\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('currency_exchange', '0007_auto_20190323_1751'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='tasks',\n ... | false |
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):
... | [
"from typing import Tuple, List\nimport math\n\n\nclass Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n self.constraints = []\n\n def __str__(self):\n return f\"({self.x}, {self.y})\"\n\n\nclass Line:\n def __init__(self, point1, point2):\n if isinstance(... | false |
4,944 | 8917481957ecd4c9692cfa93df0b759feaa344af | while True:
print("running")
| [
"while True:\n print(\"running\")\n",
"while True:\n print('running')\n",
"<code token>\n"
] | false |
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... | [
"\"\"\"\nThis is the interface that allows for creating nested lists.\nYou should not implement it, or speculate about its implementation\n\nclass NestedInteger(object):\n def isInteger(self):\n # @return {boolean} True if this NestedInteger holds a single integer,\n # rather than a nested list.\n\... | false |
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',
'... | [
"# dates.py\n\n\"\"\"Date/time parsing and manipulation functions\n\"\"\"\n\n# Some people, when confronted with a problem, think\n# \"I know, I'll use regular expressions.\"\n# Now they have two problems.\n# -- Jamie Zawinski\n\nimport datetime as dt\nimport time\nimport re\n\n_mont... | true |
4,947 | 640eae824e43e394bf0624dd4cf7dcec78f43604 | #Eyal Reis - 203249354
from view import View
def main():
"""
primary game method
"""
view = View()
view.root.mainloop()
if __name__ == "__main__":
main()
| [
"#Eyal Reis - 203249354\n\nfrom view import View\n\ndef main():\n \"\"\"\n primary game method\n \"\"\"\n view = View()\n view.root.mainloop()\n \nif __name__ == \"__main__\":\n main()\n ",
"from view import View\n\n\ndef main():\n \"\"\"\n primary game method\n \"\"\"\n view =... | false |
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... | [
"# Counts number of dumbbell curls in the video \n\nimport cv2 \nimport mediapipe as mp \nimport base\nimport math\nimport numpy as np\n\nclass PoseEstimator(base.PoseDetector): \n def __init__(self, mode=False, upperBody = False, smooth=True, detectConf=.5, trackConf=.5, \n outFile=\"output.mp4\", ou... | false |
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... | [
"\"\"\"\nA module to generate simulated 2D time-series SOSS data\n\nAuthors: Joe Filippazzo\n\"\"\"\n\nimport os\nfrom pkg_resources import resource_filename\nimport multiprocessing\nimport time\nfrom functools import partial\nimport warnings\n\nimport numpy as np\nfrom astropy.io import fits\nfrom bokeh.plotting i... | false |
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)):
""... | [
"import mysql.connector\nimport hashlib\nimport time \nfrom datetime import datetime\nfrom datetime import timedelta\n\nfrom pymongo import MongoClient\nfrom pymongo import IndexModel, ASCENDING, DESCENDING\n\n\nclass MongoManager:\n\n def __init__(self, server_ip='localhost', client=None, expires=timedelta(days... | true |
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... | [
"\nimport os\n\nimport config\n\n\n############################\n# NMJ_RNAI LOF/GOF GENE LIST\n\ndef nmj_rnai_set_path():\n return os.path.join(config.datadir, 'NMJ RNAi Search File.txt')\n\n\ndef nmj_rnai_gain_of_function_set_path():\n return os.path.join(config.datadir, 'NMJ_RNAi_gain_of_function_flybase_id... | true |
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.... | [
"import asyncio\n\ndef callback():\n print('callback invoked')\n\ndef stopper(loop):\n print('stopper invoked')\n loop.stop()\n\nevent_loop = asyncio.get_event_loop()\ntry:\n print('registering callbacks')\n # the callbacks are invoked in the order they are scheduled\n event_loop.call_soon(callbac... | false |
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'))
... | [
"import os\nimport pickle\nfrom matplotlib import pyplot as plt\n\ncwd = os.path.join(os.getcwd(), 'DEDA_2020SS_Crypto_Options_RND_HD',\n 'CrypOpt_RiskNeutralDensity')\ndata_path = os.path.join(cwd, 'data') + '/'\n\nday = '2020-03-11'\nres = pickle.load(open(data_path + 'results_{}.pkl'.format(d... | false |
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... | [
"class Config:\n DEBUG = False\n TESTING = False\n # mysql+pymysql://user:password@host:port/database\n # SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://gjp:976431@49.235.194.73:3306/test'\n SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@127.0.0.1:3306/mydb'\n SQLALCHEMY_TRACK_MODIFICATIONS = Tr... | false |
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... | [
"__author__ = 'jacek gruzewski'\n\n#!/user/bin/python3.4\n\n\"\"\"\nTo do: throw exceptions rather than calling sys.exit(1)\n\"\"\"\n\n############################################################\n# IMPORTS\n############################################################\n\n# Python's libraries\nimport time\nimpo... | false |
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
| [
"import sys\nsys.path.append('../')\nfrom IntcodeComputer.intcode import Program\n\nif __name__ == '__main__':\n fn = 'input.txt'\n with open(fn) as f:\n program = Program([int(i) for i in f.readline().split(',')])\n program.run()\n result = program.instructions\n",
"import sys\nsys.pat... | false |
4,957 | 394ebfe25bbf8eaf427509f28a82a98b9b481b63 | from .dispatch import dispatch_expts | [
"from .dispatch import dispatch_expts",
"from .dispatch import dispatch_expts\n",
"<import token>\n"
] | false |
4,958 | ea25aedc4728c18ac3d5da22c76cb7f1ef65e827 | from tw.core import *
| [
"from tw.core import *\n",
"<import token>\n"
] | false |
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... | [
"import numpy as np\r\nfrom flask import Flask,request,render_template\r\nimport pickle\r\nfrom werkzeug.serving import run_simple\r\n\r\napp=Flask(__name__,template_folder='template')\r\nmodel=pickle.load(open(\"model.pkl\",'rb'))\r\n\r\n\r\n@app.route('/')\r\ndef home():\r\n return render_template('index.html'... | false |
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):
"""
... | [
"try:\n from zcrmsdk.src.com.zoho.crm.api.dc.data_center import DataCenter\nexcept Exception as e:\n from .data_center import DataCenter\n\n\nclass EUDataCenter(DataCenter):\n\n \"\"\"\n This class represents the properties of Zoho CRM in EU Domain.\n \"\"\"\n\n @classmethod\n def PRODUCTION(cl... | false |
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... | [
"\"\"\"\nbets.models\n\nModels relating to bets placed\n\"\"\"\nimport datetime\nfrom mongoengine import *\nfrom decimal import Decimal\n\nfrom app.groups.models import Group\nfrom app.users.models import User\nfrom app.matches.models import Match\nfrom app.project.config import CURRENCIES\n\nclass GroupMatch(Docum... | false |
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... | [
"import tensorflow as tf\nimport numpy as np\n\n\ndef safe_nanmax(x):\n with np.warnings.catch_warnings():\n np.warnings.filterwarnings('ignore',\n r'All-NaN (slice|axis) encountered')\n return np.nanmax(x)\n\n\ndef safe_nanargmax(x):\n try:\n return np.n... | false |
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... | [
"# %%\nimport pandas as pd\nimport numpy as np\n\nfrom dataprep.eda import plot\nfrom dataprep.eda import plot_correlation\nfrom dataprep.eda import plot_missing\n\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(style=\"whitegrid\", color_codes=True)\nsns.set(font_scale=1)\n\n# %%\n# Minimal Proc... | false |
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... | [
"#!/usr/bin/env python\n\nimport optparse\nimport os\nimport shutil\nimport sys\n\nfrom AutoCrab.AutoCrab2 import core\n\ndef main():\n\tparser = optparse.OptionParser()\n\tparser.add_option(\"-r\", \"--recursive\", dest=\"recursive\", action=\"store_true\", help=\"Recursively look for CRAB job files and directorie... | true |
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:])
... | [
"from itertools import count, islice\nfrom math import sqrt\n\ndef is_prime(x):\n if x<2:\n return False\n for i in range(2, int(sqrt(x)) + 1):\n if x%i == 0:\n return False\n return True\n\ndef primes(x):\n return islice((p for p in count() if is_prime(p)), x)\n\nprint(list(pri... | false |
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... | [
"from .base import * # noqa\nfrom .base import env\n\n# exemple https://github.com/pydanny/cookiecutter-django/blob/master/%7B%7Bcookiecutter.project_slug%7D%7D/config/settings/production.py\n\n# GENERAL\n# ------------------------------------------------------------------------------\n# https://docs.djangoproject.... | false |
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... | [
"import json\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nf = open('Maradona-goals.json')\njsonObject = json.load(f)\n\nf.close()\n\nl = []\nfor c, cl in jsonObject.items():\n for d in cl:\n d.update({'player' : c})\n l.append(d)\ndf = pd.DataFrame(l)\n\nlabels = df[\"year\"]\n\nwidth =... | false |
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... | [
"import pandas as pd\nimport numpy as np\n\n#I'm adding these too avoid any type of na value.\nmissing_values = [\"n/a\", \"na\", \"--\", \" ?\",\"?\"]\n\n # Name\t\tData Type\tMeas.\tDescription\n\t# ----\t\t---------\t-----\t-----------\n\t# Sex\t\tnominal\t\t\tM, F, and I (infant)\n\t# Length\t\tcontinuous\tm... | false |
4,969 | 38f7c529cd0a8d85de266c6a932e6c8342aee273 | # -*- coding: utf-8 -*-
'''
=======================================================================
AutoTest Team Source File.
Copyright(C), Changyou.com
-----------------------------------------------------------------------
Created: 2017/3/2 by ChengLongLong
----------------------------------------------------... | [
"# -*- coding: utf-8 -*-\n'''\n=======================================================================\nAutoTest Team Source File.\nCopyright(C), Changyou.com\n-----------------------------------------------------------------------\nCreated: 2017/3/2 by ChengLongLong\n----------------------------------------... | false |
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... | [
"\"\"\"These are views that are used for viewing and editing characters.\"\"\"\n\nfrom django.contrib import messages\nfrom django.contrib.auth.mixins import UserPassesTestMixin,\\\n LoginRequiredMixin, PermissionRequiredMixin\nfrom django.db import transaction\nfrom django.db.models import F\nfrom django.http i... | false |
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... | [
"import sys\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import KFold,cross_validate,GridSearchCV\nfrom data_prepr import data_preprocessing\nimport numpy as np\n\n\ndef main():\n\t#if dataset is not provided on call terminate\n\tif len(sys.argv)<2:\n\t\tprint(\"usage: python svm_parameter_tuning.py <... | true |
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:
... | [
"\"\"\"\n@author Lucas\n@date 2019/3/29 21:46\n\"\"\"\n\n\n# 二分查找\ndef search(nums, target):\n left = 0\n right = len(nums) - 1\n\n while left <= right:\n mid = int((left + right)/2)\n if target > nums[mid]:\n left = mid + 1\n elif target < nums[mid]:\n right = mi... | false |
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... | [
"from lredit import *\n\n\n# customization of MainWindow\ndef configure(window):\n\n\n #----------------------------------------------\n # Generic edit config\n\n # tab width and indent width\n Mode.tab_width = 4\n\n # make TAB character visible\n Mode.show_tab = True\n\n # make space characte... | true |
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) | [
"from django import forms\n\n\nclass SignupAliasForm(forms.Form):\n alias = forms.CharField(max_length=20, required=True)\n email_secret = forms.CharField(max_length=100, required=True)",
"from django import forms\n\n\nclass SignupAliasForm(forms.Form):\n alias = forms.CharField(max_length=20, required=T... | false |
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
"""
... | [
"import os\r\nimport re\r\nimport click\r\nimport pandas as pd\r\nfrom pymongo import MongoClient\r\nfrom pathlib import Path, PurePath\r\n\r\n\r\ndef extract_dir_name(input_file):\r\n \"\"\"\r\n creates a directory path based on the specified file name\r\n :param input_file: file bane\r\n :return: full... | false |
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... | [
"import subprocess\nimport logging\nimport time\nimport argparse\nimport threading\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport argparse\n\ndef runWeka(wekapath, modelpath, datapath):\n os.chdir(wekapath)\n proc = subprocess.Popen(['/usr/bin/java', '-classpath', 'weka.jar', 'weka.cl... | false |
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... | [
"import numpy as np\r\nimport cv2\r\nimport sys\r\nimport math\r\n\r\n\r\n\r\ncap = cv2.VideoCapture(0)\r\n\r\nwhile(True):\r\n _, img = cap.read()\r\n #gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n\r\n img = cv2.imread(\"zielfeld_mit_Zeugs_2.png\")\r\n #img = cv2.imread(\"zielfeld_mit_Zeugs_2.jpg\")\... | true |
4,978 | 0878bfa1151371ff3aaa59f8be5ea9af74ada331 | from django import forms
class UploadForm(forms.Form):
file = forms.FileField(label="Json с данными об отправлении")
| [
"from django import forms\n\n\nclass UploadForm(forms.Form):\n file = forms.FileField(label=\"Json с данными об отправлении\")\n",
"from django import forms\n\n\nclass UploadForm(forms.Form):\n file = forms.FileField(label='Json с данными об отправлении')\n",
"<import token>\n\n\nclass UploadForm(forms.Fo... | false |
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... | [
"from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer\nfrom asgiref.sync import async_to_sync\nfrom channels.layers import get_channel_layer\nimport json\n\n\nclass AsyncConsumer(AsyncWebsocketConsumer):\n\n chats = dict()\n\n async def connect(self): # 连接时触发\n\n self.room_... | false |
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... | [
"#adapted from https://github.com/DeepLearningSandbox/DeepLearningSandbox/tree/master/transfer_learning\n\nimport os\nimport sys\nimport glob\nimport argparse\nimport matplotlib.pyplot as plt\n\nfrom keras.applications.imagenet_utils import preprocess_input\nfrom keras.models import Model\nfrom keras.layers import ... | false |
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... | [
"# Generated by Django 2.2.7 on 2019-11-23 18:40\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ml', '0003_auto_20191123_1835'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='ml',\n name='f... | false |
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',
... | [
"# Generated by Django 3.0.5 on 2020-05-18 12:50\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('cart', '0010_auto_20200518_1718'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='order',\n na... | false |
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 ... | [
"from cryptography.exceptions import UnsupportedAlgorithm\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives.serialization import load_ssh_public_key\nfrom ingredients_http.schematics.types import ArrowType, KubeName\nfrom schematics import Model\nfrom schematics.exceptio... | false |
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... | [
"# encoding: utf-8\n'''\nCreated on Nov 26, 2015\n\n@author: tal\n\nBased in part on:\nLearn math - https://github.com/fchollet/keras/blob/master/examples/addition_rnn.py\n\nSee https://medium.com/@majortal/deep-spelling-9ffef96a24f6#.2c9pu8nlm\n\"\"\"\n\nModified by Pavel Surmenok\n\n'''\n\nimport argparse\nimport... | false |
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... | [
"# Copyright 2011 Isaku Yamahata\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# U... | false |
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") | [
"#Developer: Chritian D. Goyes \n'''\nthis script show your name and your age.\n'''\n\nmyName = 'Christian D. Goyes'\nmyDate = 1998\nyear = 2020\n\nage = year - myDate\n\nprint (\"yourname is: \", age, \"and your are\", \"years old\")",
"<docstring token>\nmyName = 'Christian D. Goyes'\nmyDate = 1998\nyear = 20... | false |
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)
... | [
"from django.db import models\nfrom django.core.validators import RegexValidator, MaxValueValidator\n# from Delivery.models import Delivery\n# from Customers.models import Customer, Address, Order, Item\n\n# Create your models here.\n\n\nclass Restaurant(models.Model):\n Restaurant_ID = models.AutoField(primary_... | false |
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 ... | [
"from django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.contrib.auth import get_user_model\nfrom .models import Profile\n\nUser = get_user_model()\n\n# this wan't run on creating superuser\n@receiver(post_save, sender=User)\ndef save_profile(sender, created, instance, **kw... | false |
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... | [
"# First, we'll import pandas, a data processing and CSV file I/O library\nimport pandas as pd\n\n# We'll also import seaborn, a Python graphing library\nimport warnings # current version of seaborn generates a bunch of warnings that we'll ignore\n\nwarnings.filterwarnings(\"ignore\")\nimport seaborn as sns\nimpor... | false |
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... | [
"# Written by Jagannath Bilgi <jsbilgi@yahoo.com>\n\nimport sys\nimport json\nimport re\n\n\"\"\"\nProgram accepts *.md document and converts to csv in required format\n\nProgram parse line by line and uses recursive method to traverse from leaf to root. \nSingle turn object (string, int etc) is used as point of re... | false |
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,... | [
"import torch\nfrom training import PointNetTrain, PointAugmentTrain, Model\n#from PointAugment.Augment.config import opts\nfrom data_utils.dataloader import DataLoaderClass\nfrom mpl_toolkits import mplot3d\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport yaml\n\ndef visualize_batch(pointclouds, pred_l... | false |
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() | [
"from flask import Flask\nfrom apis import api\n\napp = Flask(__name__)\napp.config.from_object('config')\napi.init_app(app)\n\nif __name__ == \"__main__\":\n app.run()",
"from flask import Flask\nfrom apis import api\napp = Flask(__name__)\napp.config.from_object('config')\napi.init_app(app)\nif __name__ == '... | false |
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... | [
"# -*- coding: utf-8 -*-\n\nimport urllib\nfrom urllib2 import HTTPError\nfrom datetime import datetime\nfrom flask.views import MethodView\nfrom flask.ext.login import current_user, login_required\nfrom flask.ext.paginate import Pagination as PaginationBar\nfrom flask import render_template, redirect, url_for, req... | false |
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... | [
"# Generated by Django 3.1.1 on 2020-10-10 07:38\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('socialap... | false |
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... | [
"from django.db import models\nimport string\nimport random\n\ndef id_generator(size=32, chars=string.ascii_uppercase + string.digits):\n\texists = True\n\twhile exists == True:\n\t\tran = ''.join(random.choice(chars) for _ in range(size))\n\t\tif len(Item.objects.filter(random_str=ran)) == 0:\n\t\t\texists = False... | false |
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, ... | [
"from ortools.sat.python import cp_model\nimport os\nimport math\nimport csv\nimport sys\n\ndef ortoolsSolverReduceVar(num, cap, refill, fun, goal):\n model = cp_model.CpModel()\n token = [model.NewIntVar(-2147483648, 2147483647, 't%i' % i)\n for i in range(1, num + 1)]\n play = [model.NewIntVa... | false |
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... | [
"import os\nimport time\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torchvision.datasets import SVHN\nfrom torchvision.transforms import ToTensor \nfrom lib.utils import Logger, normal_logpdf, sumflat, print_model_info, tanh_to_uint8, get_optimizer\nfrom lib.vae import VAE\n\n\ndef train(hp):\n ... | false |
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... | [
"import sys\nsys.stdin = open(\"input.txt\", \"r\")\nstick = input()\ncnt = 0\ntemp =[]\n\nfor i,s in enumerate(stick):\n #'('나오면 무조건 추가\n if s == '(':\n temp.append(s)\n \n else:\n #절단인 경우\n if stick[i-1] == '(':\n temp.pop()\n cnt += len(temp)\n\n ... | false |
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(... | [
"import os\nfrom os.path import join\nimport json\nimport pandas as pd\nimport time\nimport numpy as np\nimport torch \n\ndef str2bool(v):\n # convert string to boolean type for argparser input\n if isinstance(v, bool):\n return v\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.