index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
2,900
67a76f1f1dad4b7e73359f04ca8f599c8d32dc92
#encoding:UTF-8 from numpy import * #---------------------------------------------------------------------- def differences(a, b): """""" c = a[a!=b] d = b[a!=b] nums = nonzero(a!=b)[0] return concatenate((mat(nums), c, d)).T
[ "#encoding:UTF-8\n\nfrom numpy import *\n\n#----------------------------------------------------------------------\ndef differences(a, b):\n \"\"\"\"\"\"\n c = a[a!=b]\n d = b[a!=b]\n nums = nonzero(a!=b)[0]\n return concatenate((mat(nums), c, d)).T", "from numpy import *\n\n\ndef differences(a, b)...
false
2,901
d5cb875dc31ca3dd7b165206415c346a076dd6e4
import db data = {'python book': ['10.09.2019', 200, 50, False]} def test_insert_and_get_db(data): db.insert(data) result = db.get_db() return result == data if __name__ == '__main__': print(f' Test insert dict in to db, and get dict from db is {test_insert_and_get_db(data)}') print(...
[ "import db\r\n\r\ndata = {'python book': ['10.09.2019', 200, 50, False]}\r\n\r\ndef test_insert_and_get_db(data):\r\n db.insert(data)\r\n result = db.get_db()\r\n return result == data\r\n\r\n\r\nif __name__ == '__main__':\r\n print(f' Test insert dict in to db, and get dict from db is {test_insert_and_...
false
2,902
332c530d221c9441d6ff3646f8e9226dc78067f9
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2020 sungminoh <smoh2044@gmail.com> # # Distributed under terms of the MIT license. """ You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that a...
[ "\n#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n# Copyright © 2020 sungminoh <smoh2044@gmail.com>\n#\n# Distributed under terms of the MIT license.\n\n\"\"\"\nYou are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations t...
false
2,903
7613dde4f49044fbca13acad2dd75587ef68f477
import time import argparse import utils from data_loader import DataLoader from generate_model_predictions import sacrebleu_metric, compute_bleu import tensorflow as tf import os import json from transformer import create_masks # Since the target sequences are padded, it is important # to apply a padding mask when c...
[ "import time\nimport argparse\nimport utils\nfrom data_loader import DataLoader\nfrom generate_model_predictions import sacrebleu_metric, compute_bleu\nimport tensorflow as tf\nimport os\nimport json\nfrom transformer import create_masks\n\n\n# Since the target sequences are padded, it is important\n# to apply a pa...
false
2,904
45cdf33f509e7913f31d2c1d6bfada3a84478736
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER # Copyright (c) 2018 Juniper Networks, Inc. # All rights reserved. # Use is subject to license terms. # # Author: cklewar import os import threading import time from jnpr.junos import Device from jnpr.junos import exception from jnpr.junos.utils.config im...
[ "# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER\n# Copyright (c) 2018 Juniper Networks, Inc.\n# All rights reserved.\n# Use is subject to license terms.\n#\n# Author: cklewar\n\nimport os\nimport threading\nimport time\n\nfrom jnpr.junos import Device\nfrom jnpr.junos import exception\nfrom jnpr.jun...
false
2,905
3d5d88edca5d746b830363cc9451bda94c1d7aa4
# -*- coding: utf-8 -*- from plone import api from plone.dexterity.content import Container from sc.microsite.interfaces import IMicrosite from zope.interface import implementer @implementer(IMicrosite) class Microsite(Container): """A microsite.""" def getLocallyAllowedTypes(self): """ By no...
[ "# -*- coding: utf-8 -*-\nfrom plone import api\nfrom plone.dexterity.content import Container\nfrom sc.microsite.interfaces import IMicrosite\nfrom zope.interface import implementer\n\n\n@implementer(IMicrosite)\nclass Microsite(Container):\n \"\"\"A microsite.\"\"\"\n\n def getLocallyAllowedTypes(self):\n ...
false
2,906
33464f19c42d1a192792a73297f4d926df78ab71
# -*- coding: utf-8 -*- """ Created on 11/03/2020 @author: stevenp@valvesoftware.com """ import sys from PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QRadioButton, QVBoxLayout, QCheckBox, QProgressBar, QGroupBox, QComboBox, QLineEdit, QPushButton, QMessageBox, QInputDialog, QDialog, QDialogButton...
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on 11/03/2020\r\n\r\n@author: stevenp@valvesoftware.com\r\n\"\"\"\r\nimport sys\r\nfrom PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QRadioButton, QVBoxLayout, QCheckBox, QProgressBar,\r\n QGroupBox, QComboBox, QLineEdit, QPushButton, QMessageBox, QInputDia...
false
2,907
6c3f60f05adbebe521ba08d7a7e9fc10b1cc914f
import html import logging import re import pyarabic.araby as araby ACCEPTED_MODELS = [ "bert-base-arabertv01", "bert-base-arabert", "bert-base-arabertv02", "bert-base-arabertv2", "bert-large-arabertv02", "bert-large-arabertv2", "araelectra-base", "araelectra-base-discriminator", "...
[ "import html\nimport logging\nimport re\n\nimport pyarabic.araby as araby\n\nACCEPTED_MODELS = [\n \"bert-base-arabertv01\",\n \"bert-base-arabert\",\n \"bert-base-arabertv02\",\n \"bert-base-arabertv2\",\n \"bert-large-arabertv02\",\n \"bert-large-arabertv2\",\n \"araelectra-base\",\n \"ara...
false
2,908
8baf61a20a64f296304b6a7017a24f1216e3d771
from django.db import models from django.contrib.auth.models import User as sUser TYPES = ( ('public', 'public'), ('private', 'private'), ) #class GroupManager(models.Manager): # def get_all_users(self): # return self.extra(where=['users']) class Group(models.Model): name = models.CharField(max...
[ "from django.db import models\nfrom django.contrib.auth.models import User as sUser\n\nTYPES = (\n ('public', 'public'),\n ('private', 'private'),\n)\n\n#class GroupManager(models.Manager):\n# def get_all_users(self):\n# return self.extra(where=['users'])\n\nclass Group(models.Model):\n name = mo...
false
2,909
605e088beed05c91b184e26c4a5d2a97cb793759
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 10 11:08:59 2020 @author: rishi """ # --------- Global Variables ----------- # Will hold our game board data board = ["-" for i in range(1,26)] # Lets us know if the game is over yet game_still_going = True # Tells us who the winner is winner = ...
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 10 11:08:59 2020\n\n@author: rishi\n\"\"\"\n\n# --------- Global Variables -----------\n\n# Will hold our game board data\nboard = [\"-\" for i in range(1,26)]\n\n# Lets us know if the game is over yet\ngame_still_going = True\n\n# Tells u...
false
2,910
5cdedce5f984f53b8e26d1580a9040b26023f247
import shutil total, used, free = shutil.disk_usage("/") print("Total: %d MiB" % (total // (2**20))) print("Used: %d MiB" % (used // (2**20))) print("Free: %d MiB" % (free // (2**20))) from Camera import Camera import time import cv2 devices = Camera.getDevicesList() print(devices) i=0 Cameras = [] for device in...
[ "import shutil\n\ntotal, used, free = shutil.disk_usage(\"/\")\n\nprint(\"Total: %d MiB\" % (total // (2**20)))\nprint(\"Used: %d MiB\" % (used // (2**20)))\nprint(\"Free: %d MiB\" % (free // (2**20)))\n\n\n\nfrom Camera import Camera\nimport time\nimport cv2\n\ndevices = Camera.getDevicesList()\nprint(devices)\n\n...
false
2,911
889d465ceeac57a600b2fa3bd26632edcd90a655
import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import QIcon, QFont from PyQt5.QtCore import QCoreApplication import pymysql import requests from twisted.internet import reactor, defer from scrapy.crawler import CrawlerRunner, CrawlerProcess from scrapy.utils.project import get_project_settings from spider....
[ "import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import QIcon, QFont\nfrom PyQt5.QtCore import QCoreApplication\n\nimport pymysql\nimport requests\n\nfrom twisted.internet import reactor, defer\nfrom scrapy.crawler import CrawlerRunner, CrawlerProcess\nfrom scrapy.utils.project import get_project_settin...
false
2,912
34947b7ed300f2cbcbf9042fee3902458921d603
a = list(range(1,501)) b = list(range(1,501)) c = list(range(1,501)) for i in a: for j in b: for k in c: if i+k+j == 1000 and i<j<k and j**2+i**2==k**2 : print(i) print(j) print(k) break
[ "a = list(range(1,501))\nb = list(range(1,501))\nc = list(range(1,501))\nfor i in a:\n for j in b:\n for k in c:\n if i+k+j == 1000 and i<j<k and j**2+i**2==k**2 :\n print(i)\n print(j)\n print(k)\n break\n", "a = list(range(1, 501))...
false
2,913
6e56c7792d88385cc28c48a7d6dd32b9d6917c64
# Generated by Django 2.1.7 on 2019-03-24 07:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('adminsite', '0005_auto_20190324_0706'), ] operations = [ migrations.RenameField( model_name='district', old_name='District',...
[ "# Generated by Django 2.1.7 on 2019-03-24 07:08\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('adminsite', '0005_auto_20190324_0706'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='district',\n o...
false
2,914
fab3e524edf6783775fabf402f9148bf31ac06d6
import smtplib from email.message import EmailMessage from functools import wraps from threading import Thread import flask_login from flask import flash, current_app from togger import db from togger.auth.models import User, Role from togger.calendar.models import Calendar def get_user(username): if username i...
[ "import smtplib\nfrom email.message import EmailMessage\nfrom functools import wraps\nfrom threading import Thread\n\nimport flask_login\nfrom flask import flash, current_app\n\nfrom togger import db\nfrom togger.auth.models import User, Role\nfrom togger.calendar.models import Calendar\n\n\ndef get_user(username):...
false
2,915
b7a8e4105f1c1c532eaae27afae14e9a4f2ddfba
# Generated by Django 3.2.3 on 2021-06-19 11:27 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='BillDetail', ...
[ "# Generated by Django 3.2.3 on 2021-06-19 11:27\r\n\r\nimport django.core.validators\r\nfrom django.db import migrations, models\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n initial = True\r\n\r\n dependencies = [\r\n ]\r\n\r\n operations = [\r\n migrations.CreateModel(\r\n ...
false
2,916
44cbe1face91d3ac7edcd93d0b470bce90c8b674
# myapp/serializers.py from rest_framework import serializers from rest_framework.authtoken.models import Token from .models import * # Serializers define the API representation. class GeneralSerializer(serializers.ModelSerializer): class Meta: model = None fields = '__all__' class V2OfUsersSeri...
[ "# myapp/serializers.py\nfrom rest_framework import serializers\nfrom rest_framework.authtoken.models import Token\nfrom .models import *\n\n\n# Serializers define the API representation.\nclass GeneralSerializer(serializers.ModelSerializer):\n class Meta:\n model = None\n fields = '__all__'\n\n\nc...
false
2,917
2a37d02c7a0840e855a80adced4794fd757e353a
import ssl import urllib from urllib import request, response, error, parse, robotparser context = ssl._create_unverified_context() url = 'https://oauth.51job.com/get_login.php?client_id=000001&redirect_uri=https%3A%2F%2Funion.yingjiesheng.com%2Fapi_login.php&from_domain=yjs_web&display=default&state=7c893ec1be7b355a91...
[ "import ssl\nimport urllib\nfrom urllib import request, response, error, parse, robotparser\ncontext = ssl._create_unverified_context()\nurl = 'https://oauth.51job.com/get_login.php?client_id=000001&redirect_uri=https%3A%2F%2Funion.yingjiesheng.com%2Fapi_login.php&from_domain=yjs_web&display=default&state=7c893ec1b...
false
2,918
5433e75bdc46d5a975969e7ece799174dc9b8713
# # 8/19/2020 # Of course, binary classification is just a single special case. Target encoding could be applied to any target variable type: # For binary classification usually mean target encoding is used # For regression mean could be changed to median, quartiles, etc. # For multi-class classification with N classe...
[ "# # 8/19/2020\n# Of course, binary classification is just a single special case. Target encoding could be applied to any target variable type:\n\n# For binary classification usually mean target encoding is used\n# For regression mean could be changed to median, quartiles, etc.\n# For multi-class classification wit...
false
2,919
db159cfb198311b0369f65eb9e10947c4d28c695
#finding optimal betting strategy for the blackjack game using Monte Carlo ES method import random class Player(): def __init__(self) -> None: q = None policy = None returns = None cards = 0 dealer = 0 def hit(self): self.cards += random.randint(1,11) def d...
[ "#finding optimal betting strategy for the blackjack game using Monte Carlo ES method\nimport random\n\nclass Player():\n def __init__(self) -> None:\n q = None\n policy = None\n returns = None\n cards = 0\n dealer = 0\n\n def hit(self):\n self.cards += random.randint...
false
2,920
6a4585e0e2f5ebbd0f9a7fa203f76bb88ff9c2a0
from django.apps import AppConfig class ProjectrolesConfig(AppConfig): name = 'projectroles'
[ "from django.apps import AppConfig\n\n\nclass ProjectrolesConfig(AppConfig):\n name = 'projectroles'\n", "<import token>\n\n\nclass ProjectrolesConfig(AppConfig):\n name = 'projectroles'\n", "<import token>\n\n\nclass ProjectrolesConfig(AppConfig):\n <assignment token>\n", "<import token>\n<class tok...
false
2,921
50a5d3431693b402c15b557357eaf9a85fc02b0b
# -*- coding: utf-8 -*- import sys, io,re import regex from collections import defaultdict import datetime import json def update_key(data_base, url,kkey): keys_saved = regex.get_data('<key>\s(.+?)\s<',data_base[url]['key']) if kkey not in keys_saved: data_base[url]['key'] = data_base[url...
[ "# -*- coding: utf-8 -*-\r\nimport sys, io,re\r\nimport regex\r\nfrom collections import defaultdict\r\nimport datetime\r\nimport json\r\n\r\n\r\ndef update_key(data_base, url,kkey):\r\n keys_saved = regex.get_data('<key>\\s(.+?)\\s<',data_base[url]['key'])\r\n\r\n if kkey not in keys_saved:\r\n data_b...
false
2,922
c6fd848bb3d845a50b928c18a51f296a500e7746
import socket def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 8886) sock.connect(server_address) data = "TCP" length = len(data) ret = bytearray([]) for byte in data.encode("utf-8"): ret.append(byte) sock.sendall(ret) if __na...
[ "import socket\n\ndef main():\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_address = ('localhost', 8886)\n sock.connect(server_address)\n\n data = \"TCP\"\n length = len(data)\n ret = bytearray([])\n for byte in data.encode(\"utf-8\"):\n ret.append(byte)\n sock....
false
2,923
ccedca543fc4dee284a9243317d028ffdeac229d
import pandas import numpy as np train_set = pandas.read_csv("./dataset/train.csv") test_set = pandas.read_csv("./dataset/test.csv") print(train_set) train_set = train_set.drop('id',axis=1) print(train_set.describe()) train_set['type'], categories = train_set['type'].factorize() import matplotlib.pyplot as plt print...
[ "import pandas\nimport numpy as np\n\ntrain_set = pandas.read_csv(\"./dataset/train.csv\")\ntest_set = pandas.read_csv(\"./dataset/test.csv\")\nprint(train_set)\ntrain_set = train_set.drop('id',axis=1)\nprint(train_set.describe())\n\ntrain_set['type'], categories = train_set['type'].factorize()\n\nimport matplotlib...
false
2,924
03ce69924c885e59e40689dc63e50d54b89649f7
import _thread import os from queue import Queue from threading import Thread import random import io import vk_api from vk_api.longpoll import VkLongPoll, VkEventType from datetime import datetime, timedelta import time from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords from wordcloud import W...
[ "import _thread\nimport os\nfrom queue import Queue\nfrom threading import Thread\nimport random\nimport io\nimport vk_api\nfrom vk_api.longpoll import VkLongPoll, VkEventType\nfrom datetime import datetime, timedelta\nimport time\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.corpus import stopwords\nfrom w...
false
2,925
eab45dafd0366af8ab904eb33719b86777ba3d65
import random from .action import Action from ..transition.step import Step from ..value.estimators import ValueEstimator def greedy(steps: [Step], actions: [Action], value_estimator: ValueEstimator) -> int: estimations = [value_estimator(steps, action) for action in actions] return actions[estimations.index...
[ "import random\n\nfrom .action import Action\nfrom ..transition.step import Step\nfrom ..value.estimators import ValueEstimator\n\n\ndef greedy(steps: [Step], actions: [Action], value_estimator: ValueEstimator) -> int:\n estimations = [value_estimator(steps, action) for action in actions]\n return actions[est...
false
2,926
56157aaf3f98abc58572b45111becb91cb93f328
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-02-24 11:30 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Create...
[ "# -*- coding: utf-8 -*-\n# Generated by Django 1.11 on 2018-02-24 11:30\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n ...
false
2,927
b5581be044013df9ff812f285f99ca67c4f96a62
import requests import json def get(): market = 'Premium' url = 'https://coinpremiums.herokuapp.com/json' try: result = "" premiums = requests.get(url).json() for exchange, exchange_currencies in premiums['premium'].items(): result += '[[{} | '.format(exchange.title()...
[ "import requests\nimport json\n\n\ndef get():\n market = 'Premium'\n url = 'https://coinpremiums.herokuapp.com/json'\n\n try:\n result = \"\"\n premiums = requests.get(url).json()\n\n for exchange, exchange_currencies in premiums['premium'].items():\n result += '[[{} | '.for...
false
2,928
6a6a7cc6d4f601f4461488d02e03e832bc7ab634
""" quiz materials for feature scaling clustering """ # FYI, the most straightforward implementation might # throw a divide-by-zero error, if the min and max # values are the same # but think about this for a second--that means that every # data point has the same value for that feature! # why would you rescale it? O...
[ "\"\"\" quiz materials for feature scaling clustering \"\"\"\n\n# FYI, the most straightforward implementation might\n# throw a divide-by-zero error, if the min and max\n# values are the same\n# but think about this for a second--that means that every\n# data point has the same value for that feature!\n# why would ...
true
2,929
8fed95cf809afca7b6008d5abcdcf697367a33c2
""" Supreme bot???? """ import os import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait import selenium.webdriver.support.expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.webdriver.ch...
[ "\"\"\"\nSupreme bot????\n\n\"\"\"\nimport os\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport selenium.webdriver.support.expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\nfrom...
true
2,930
8ebc11f4b9e28254ef40175b26744f2a5ab0c831
import os from registration import Registration from login import Login def login(): """ redirect to login page""" login_page = Login() login_page.login_main_page() def registration(): """Register the new user""" registration_page = Registration() registration_page.registration_main_page() ...
[ "import os\n\nfrom registration import Registration\nfrom login import Login\n\n\ndef login():\n \"\"\" redirect to login page\"\"\"\n login_page = Login()\n login_page.login_main_page()\n\n\ndef registration():\n \"\"\"Register the new user\"\"\"\n registration_page = Registration()\n registratio...
true
2,931
337311c3fbb6a8baab7a237d08152f0db9822527
def assert_shapes(shape, other): assert len(shape) == len(other), "Dimensions are different" for s, o in zip(shape, other): if s is not None and o is not None: assert s == o, "Shapes {} and {} are not equal".format(shape, other)
[ "\ndef assert_shapes(shape, other):\n assert len(shape) == len(other), \"Dimensions are different\"\n for s, o in zip(shape, other):\n if s is not None and o is not None:\n assert s == o, \"Shapes {} and {} are not equal\".format(shape, other)\n", "def assert_shapes(shape, other):\n ass...
false
2,932
bcc24d5f97e46433acb8bcfb08fe582f51eb28ce
class Coms: def __init__(self, name, addr, coord): self.name = name self.addr = addr self.coord = coord def getString(self): return "회사명\n"+self.name+"\n\n주소\n"+self.addr def getTeleString(self): return "회사명 : " + self.name + ", 주소 : " + self.addr class Jobs: d...
[ "class Coms:\n def __init__(self, name, addr, coord):\n self.name = name\n self.addr = addr\n self.coord = coord\n\n def getString(self):\n return \"회사명\\n\"+self.name+\"\\n\\n주소\\n\"+self.addr\n\n def getTeleString(self):\n return \"회사명 : \" + self.name + \", 주소 : \" + s...
false
2,933
5d654c056e6ef01e72821427c4f8dcb285755ee9
from .data_processing import make_request_data, clear_request_data, get_token_from_text from .review import Review
[ "from .data_processing import make_request_data, clear_request_data, get_token_from_text\nfrom .review import Review", "from .data_processing import make_request_data, clear_request_data, get_token_from_text\nfrom .review import Review\n", "<import token>\n" ]
false
2,934
ec604aea28dfb2909ac9e4b0f15e6b5bbe1c3446
from email.mime.text import MIMEText import smtplib def init_mail(server, user, pwd, port=25): server = smtplib.SMTP(server, port) server.starttls() server.login(user, pwd) return server def send_email(mconn, mailto, mailfrom, mailsub, msgbody): msg = MIMEText(msgbody) msg['Subject'] = mailsub msg['To'] = ma...
[ "from email.mime.text import MIMEText\nimport smtplib\n\n\ndef init_mail(server, user, pwd, port=25):\n\tserver = smtplib.SMTP(server, port)\n\tserver.starttls()\n\tserver.login(user, pwd)\n\treturn server\n\n\ndef send_email(mconn, mailto, mailfrom, mailsub, msgbody):\n\tmsg = MIMEText(msgbody)\n\tmsg['Subject'] =...
false
2,935
009be282e45d191eb8f4d7d2986a2f182d64c1dd
from layers import TrueSkillFactorGraph from math import e, sqrt from numerics import atLeast, _Vector, _DiagonalMatrix, Matrix from objects import SkillCalculator, SupportedOptions, argumentNotNone, \ getPartialPlayPercentage, sortByRank class FactorGraphTrueSkillCalculator(SkillCalculator): def __init__(self): s...
[ "from layers import TrueSkillFactorGraph\nfrom math import e, sqrt\nfrom numerics import atLeast, _Vector, _DiagonalMatrix, Matrix\nfrom objects import SkillCalculator, SupportedOptions, argumentNotNone, \\\n\tgetPartialPlayPercentage, sortByRank\n\nclass FactorGraphTrueSkillCalculator(SkillCalculator):\n\tdef __in...
false
2,936
0a5570ef17efa26ef6317930df616c8326f83314
# Generated by Django 3.0.1 on 2020-02-01 16:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shopUser', '0024_order_contact'), ] operations = [ migrations.AddField( model_name='order', name='location', ...
[ "# Generated by Django 3.0.1 on 2020-02-01 16:38\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('shopUser', '0024_order_contact'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='order',\n name=...
false
2,937
cf4582f4d0c6c94e617270a45425fe0b770142e0
# coding: utf-8 """ 最简单的计数器,仅仅为了展示基本方式 """ import tensorflow as tf # 创建一个变量, 初始化为标量 0 state = tf.Variable(0, name="counter") # 创建一个operation, 其作用是使state 增加 1 one = tf.constant(1) new_value = tf.add(state, one) update = tf.assign(state, new_value) # 这样才能重复执行+1的操作,实际上就代表:state=new_value # 启动图后, 变量必须先经过`初始化` (init) o...
[ "# coding: utf-8\n\"\"\"\n最简单的计数器,仅仅为了展示基本方式\n\"\"\"\nimport tensorflow as tf\n\n# 创建一个变量, 初始化为标量 0\nstate = tf.Variable(0, name=\"counter\")\n\n# 创建一个operation, 其作用是使state 增加 1\none = tf.constant(1)\nnew_value = tf.add(state, one)\nupdate = tf.assign(state, new_value) # 这样才能重复执行+1的操作,实际上就代表:state=new_value\n\n# ...
false
2,938
1cc9c89182f69a5f1eb9a0e7f3433dc30c8d7035
print("calificacion de los alumnos") lista2_calificaciones=[] for i in range (0,5): lista2_calificaciones.append(int(input(f"ingrese la calificacion corresponfiente al alumno"))) print(lista2_calificaciones) for n in range(0,len(lista2_calificaciones)): if lista2_calificaciones[i] >=0 and lista2_calific...
[ "\n\nprint(\"calificacion de los alumnos\")\n\nlista2_calificaciones=[]\nfor i in range (0,5):\n lista2_calificaciones.append(int(input(f\"ingrese la calificacion corresponfiente al alumno\")))\n print(lista2_calificaciones)\n\nfor n in range(0,len(lista2_calificaciones)):\n if lista2_calificaciones[i] >=0...
false
2,939
fef1273552350bfaf075d90279c9f10a965cae25
# Accepted def bubble_sort(a_list, n): num_reverse = 0 for i in range(n): for j in range(n - i - 1): # With a for roop (reversed order), # index starts -1, -2 ,..., # NOT -0, -1, ... if a_list[-j - 2] > a_list[-j - 1]: tmp_elem = a_list[-...
[ "# Accepted\ndef bubble_sort(a_list, n):\n num_reverse = 0\n for i in range(n):\n for j in range(n - i - 1):\n # With a for roop (reversed order), \n # index starts -1, -2 ,...,\n # NOT -0, -1, ...\n if a_list[-j - 2] > a_list[-j - 1]:\n tmp_e...
false
2,940
d4b01b015723950a4d8c3453d736cd64f306d27b
# Game Tebak Angka from random import randint nyawa = 3 angka_rahasia = randint(0,10) limit = 0 print(f"Selamat datang di Game Tebak angka") while nyawa > limit: print(f"Percobaan anda tersisa {nyawa}") jawaban = int(input("Masukkan angka 0-10 = ")) if jawaban == angka_rahasia: ...
[ "# Game Tebak Angka \r\n\r\nfrom random import randint \r\n\r\nnyawa = 3 \r\nangka_rahasia = randint(0,10) \r\nlimit = 0 \r\n\r\nprint(f\"Selamat datang di Game Tebak angka\")\r\nwhile nyawa > limit: \r\n print(f\"Percobaan anda tersisa {nyawa}\")\r\n jawaban = int(input(\"Masukkan angka 0-10 = \"))\r\n if...
false
2,941
1255a9df2fbe11d92991f3f0f7054b92cb017628
# -*- coding: utf-8 -*- """ Created on Tue Mar 12 20:29:49 2019 @author: kzx789 """ from PIL import Image import os, glob, numpy as np import pandas as pd import matplotlib.pyplot as plt import math import cv2 import pymysql import MySQLdb as mysql """ #csv를 읽어서 영양정보 출력 def get_Nutrition(str) : nutrition = pd.r...
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 12 20:29:49 2019\n\n@author: kzx789\n\"\"\"\n\nfrom PIL import Image\nimport os, glob, numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport math\nimport cv2\nimport pymysql\nimport MySQLdb as mysql\n\n\"\"\"\n#csv를 읽어서 영양정보 출력\ndef get_Nutrit...
false
2,942
051544f41cc3c7d78210076cb9720866924ea2a1
# Print list of files and directories import os def file_list(dir): subdir_list = [] for item in os.listdir(dir): fullpath = os.path.join(dir,item) if os.path.isdir(fullpath): subdir_list.append(fullpath) else: print(fullpath) for d in subdir_list: f...
[ "# Print list of files and directories\nimport os\n\ndef file_list(dir):\n subdir_list = []\n for item in os.listdir(dir):\n fullpath = os.path.join(dir,item)\n if os.path.isdir(fullpath):\n subdir_list.append(fullpath)\n else:\n print(fullpath)\n\n for d in subdi...
false
2,943
95021cc01c0b85b512fd466797d4d128472773c3
import shelve arguments = ["self", "info", "args", "world"] minlevel = 2 helpstring = "moneyreset" def main(connection, info, args, world) : """Resets a users money""" money = shelve.open("money-%s.db" % (world.hostnicks[connection.host]), writeback=True) money[info["sender"]] = {"money":100000, "maxmoney"...
[ "import shelve\narguments = [\"self\", \"info\", \"args\", \"world\"]\nminlevel = 2\nhelpstring = \"moneyreset\"\n\ndef main(connection, info, args, world) :\n \"\"\"Resets a users money\"\"\"\n money = shelve.open(\"money-%s.db\" % (world.hostnicks[connection.host]), writeback=True)\n money[info[\"sender\...
false
2,944
5a0702dd869862ebc27c83d10e0b1f0575de68a7
import itertools import numpy import math import psycopg2 import podatki baza = podatki.baza dom = podatki.preberi_lokacijo() seznam_trgovin =["spar", "mercator", "tus", "hofer", "lidl"] id_in_opis = podatki.id_izdelka_v_opis() seznam_izdelkov = [el[0] for el in id_in_opis] #['cokolada', 'sladoled', ...] mnozica_izdel...
[ "import itertools\nimport numpy\nimport math\nimport psycopg2\nimport podatki\n\nbaza = podatki.baza\ndom = podatki.preberi_lokacijo()\nseznam_trgovin =[\"spar\", \"mercator\", \"tus\", \"hofer\", \"lidl\"]\nid_in_opis = podatki.id_izdelka_v_opis()\nseznam_izdelkov = [el[0] for el in id_in_opis] #['cokolada', 'slad...
false
2,945
6c88e55a76cbd84cee0ebd6c51d930cc2da100d2
print("hello world") print("lol") print("new changes in vis")
[ "print(\"hello world\")\nprint(\"lol\")\nprint(\"new changes in vis\")", "print('hello world')\nprint('lol')\nprint('new changes in vis')\n", "<code token>\n" ]
false
2,946
bdbeebab70a6d69e7553807d48e3539b78b48add
# SymBeam examples suit # ========================================================================================== # António Carneiro <amcc@fe.up.pt> 2020 # Features: 1. Numeric length # 2. Pin # 3. Two rollers # 4. Numeric distributed...
[ "# SymBeam examples suit\n# ==========================================================================================\n# António Carneiro <amcc@fe.up.pt> 2020\n# Features: 1. Numeric length\n# 2. Pin\n# 3. Two rollers\n# 4. Numeric ...
false
2,947
ba808d23f6a8226f40e1c214012a1535ee1e9e98
import os import json import librosa # Constants # Dataset used for training DATASET_PATH = "dataset" # Where the data is stored JSON_PATH = "data.json" # Number of samples considered to preprocess data SAMPLES_TO_CONSIDER = 22050 # 1 sec worth of sound # Main function to preprocess the data def prepare_dataset(dat...
[ "import os\nimport json\nimport librosa\n\n# Constants\n# Dataset used for training\nDATASET_PATH = \"dataset\"\n# Where the data is stored\nJSON_PATH = \"data.json\"\n# Number of samples considered to preprocess data\nSAMPLES_TO_CONSIDER = 22050 # 1 sec worth of sound\n\n\n# Main function to preprocess the data\n...
false
2,948
1593280a29b13461b13d8b2805d9ac53ce94c759
import turtle import random import winsound import sys """ new_game = False def toggle_new_game(): global new_game if new_game == False: new_game = True else: new_game = False """ wn = turtle.Screen() wn.title("MaskUp") wn.bgcolor("green") wn.bgpic("retro_city_title...
[ "\r\nimport turtle\r\nimport random\r\nimport winsound\r\nimport sys\r\n\r\n\r\n\r\n\"\"\" new_game = False\r\n\r\ndef toggle_new_game():\r\n global new_game\r\n if new_game == False:\r\n new_game = True\r\n else:\r\n new_game = False \"\"\"\r\n\r\nwn = turtle.Screen()\r\nwn.title(\"MaskUp\")...
false
2,949
1f1677687ba6ca47b18728b0fd3b9926436e9796
#Voir paragraphe "3.6 Normalizing Text", page 107 de NLP with Python from nltk.stem.snowball import SnowballStemmer from nltk.stem.wordnet import WordNetLemmatizer # Il faut retirer les stopwords avant de stemmer stemmer = SnowballStemmer("english", ignore_stopwords=True) lemmatizer = WordNetLemmatizer() source = ...
[ "#Voir paragraphe \"3.6 Normalizing Text\", page 107 de NLP with Python\n\n\nfrom nltk.stem.snowball import SnowballStemmer\nfrom nltk.stem.wordnet import WordNetLemmatizer\n\n# Il faut retirer les stopwords avant de stemmer\n\nstemmer = SnowballStemmer(\"english\", ignore_stopwords=True)\nlemmatizer = WordNetLemma...
false
2,950
aa79d5cbe656979bf9c228f6a576f2bbf7e405ca
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import copy import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload fr...
[ "# coding=utf-8\n# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***\n# *** Do not edit by hand unless you're certain you know what you are doing! ***\n\nimport copy\nimport warnings\nimport pulumi\nimport pulumi.runtime\nfrom typing import Any, Mapping, Optional, Sequence, Union...
false
2,951
613b060ee50b49417342cfa70b36f77d112dcc58
from collections import Counter import pandas as pd import string from collections import namedtuple, defaultdict import csv import sys import torch import numpy as np from sklearn.preprocessing import LabelEncoder from scipy.sparse import coo_matrix from tqdm import tqdm device = torch.device('cuda' if torch.cuda.is_...
[ "from collections import Counter\nimport pandas as pd\nimport string\nfrom collections import namedtuple, defaultdict\nimport csv\nimport sys\nimport torch\nimport numpy as np\nfrom sklearn.preprocessing import LabelEncoder\nfrom scipy.sparse import coo_matrix\nfrom tqdm import tqdm\n\ndevice = torch.device('cuda' ...
false
2,952
6d974580ff546bda17caa1e61e2621b4bc705f3f
from flask import jsonify from flask_restful import Resource from flask_apispec.views import MethodResource import pandas as pd import jellyfish df = pd.read_csv('data/trancotop1m.csv') df_dict = df.to_dict('records') class StrComparison(MethodResource,Resource): # @requires_auth def get(self, domain): ...
[ "from flask import jsonify\nfrom flask_restful import Resource\nfrom flask_apispec.views import MethodResource\nimport pandas as pd\nimport jellyfish\n\ndf = pd.read_csv('data/trancotop1m.csv')\ndf_dict = df.to_dict('records')\n\nclass StrComparison(MethodResource,Resource):\n # @requires_auth\n def get(self,...
false
2,953
7bcbcbe51217b2ea9044a7e4a4bebf315069c92d
""" Create a function that takes two number strings and returns their sum as a string. Examples add("111", "111") ➞ "222" add("10", "80") ➞ "90" add("", "20") ➞ "Invalid Operation" Notes If any input is "" or None, return "Invalid Operation". """ def add(n1, n2): if n1 == "" or n2 == "": return "Invali...
[ "\"\"\"\nCreate a function that takes two number strings and returns their sum as a string.\n\nExamples\nadd(\"111\", \"111\") ➞ \"222\"\n\nadd(\"10\", \"80\") ➞ \"90\"\n\nadd(\"\", \"20\") ➞ \"Invalid Operation\"\nNotes\nIf any input is \"\" or None, return \"Invalid Operation\".\n\"\"\"\n\n\ndef add(n1, n2):\n ...
false
2,954
f5b8d8c291d18c6f320704a89985acbcae97ca2f
from ImageCoord import ImageCoord import os import sys from folium.features import DivIcon # Chemin du dossier ou l'on recupere les images racine = tkinter.Tk() racine.title("listPhoto") racine.directory = filedialog.askdirectory() cheminDossier = racine.directory dirImage = os.listdir(cheminDossier) listImage = [] ...
[ "from ImageCoord import ImageCoord\nimport os\nimport sys\nfrom folium.features import DivIcon\n\n# Chemin du dossier ou l'on recupere les images\n\nracine = tkinter.Tk()\nracine.title(\"listPhoto\")\nracine.directory = filedialog.askdirectory()\ncheminDossier = racine.directory\ndirImage = os.listdir(cheminDossier...
false
2,955
bce794616889b80c152a8ebec8d02e49a96684e9
import csv, io from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import permission_required from django.views import generic from itertools import chain from .models import Player, League, Team class IndexView(generic.ListView): templ...
[ "import csv, io\r\nfrom django.shortcuts import render, redirect\r\nfrom django.contrib import messages\r\nfrom django.contrib.auth.decorators import permission_required\r\nfrom django.views import generic\r\nfrom itertools import chain\r\n\r\nfrom .models import Player, League, Team\r\n\r\n\r\nclass IndexView(gene...
false
2,956
3146775c466368c25c92bd6074abb97408533500
import logging loggers = {} def create_logger( log_level:str ='INFO', log_name:str = 'logfile', export_log: bool = True, save_dir:str = ''): if log_name in loggers.keys(): logger = loggers.get(log_name) else: # create logger logger = logging.getLogger(log_name) ...
[ "import logging\n\nloggers = {} \n\ndef create_logger(\n log_level:str ='INFO', \n log_name:str = 'logfile',\n export_log: bool = True,\n save_dir:str = ''):\n if log_name in loggers.keys():\n logger = loggers.get(log_name)\n else:\n # create logger\n logger = logging.getLogge...
false
2,957
6cb97e6f3c7ba312ec1458fd51635508a16f70dd
from mysql import connector def get_db_connection(): try: return connector.connect(host="server_database_1", user="root", password="password1234", database="SMARTHOUSE") except connector.errors.DatabaseError: connection = connector.connect(host="server_database_1", user="root", password="pass...
[ "from mysql import connector\n\n\ndef get_db_connection():\n try:\n return connector.connect(host=\"server_database_1\", user=\"root\", password=\"password1234\", database=\"SMARTHOUSE\")\n except connector.errors.DatabaseError:\n connection = connector.connect(host=\"server_database_1\", user=...
false
2,958
919f1746bfdec61f5e81e6ce0e17bb3bf040230a
# square environment. there are the wall at the edge from environment import super_environment class SquareNormal(super_environment.Environment): def __init__(self, size_x, size_y): super().__init__(size_x, size_y) @staticmethod def environment_type(): return 'square' def get_convert...
[ "# square environment. there are the wall at the edge\nfrom environment import super_environment\n\n\nclass SquareNormal(super_environment.Environment):\n def __init__(self, size_x, size_y):\n super().__init__(size_x, size_y)\n\n @staticmethod\n def environment_type():\n return 'square'\n\n ...
false
2,959
d9bdf466abecb50c399556b99b41896eead0cb4b
from flask import Flask, request, g from flask_restful import Resource, Api from sqlalchemy import create_engine from flask import jsonify import json import eth_account import algosdk from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import scoped_session from sqlalchemy.orm import load_only from datetime im...
[ "from flask import Flask, request, g\nfrom flask_restful import Resource, Api\nfrom sqlalchemy import create_engine\nfrom flask import jsonify\nimport json\nimport eth_account\nimport algosdk\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.orm import scoped_session\nfrom sqlalchemy.orm import load_only\nf...
false
2,960
7c53c7bec6b6b2d4d6be89b750eeef83ca9115cc
from typing import List class CourseSchedule: """ Problem: Course Schedule (#207) Key Insights: 1. Create adjaceny list of courses to prerequisites. 2. Use DFS and visited set to detect a cycle. If there is a cycle, cannot finish all the courses. 3. Remember to remove a course (node) from visi...
[ "from typing import List \n\nclass CourseSchedule:\n \"\"\"\n Problem: Course Schedule (#207)\n Key Insights:\n 1. Create adjaceny list of courses to prerequisites.\n 2. Use DFS and visited set to detect a cycle. If there is a cycle, cannot finish all the courses.\n 3. Remember to remove a course ...
false
2,961
d0f2d47a786b85367f96897e7cd8c2ef8c577e2b
import datetime from flask import Flask, render_template, request import database import database1 import database2 import getYoutubeVideoLinks as getYT import os os.environ["EAI_USERNAME"] = 'pitabi1360@pashter.com' os.environ["EAI_PASSWORD"] = 'Testqwerty1!' from expertai.nlapi.cloud.client import ExpertAiClient cl...
[ "import datetime\nfrom flask import Flask, render_template, request\nimport database\nimport database1\nimport database2\nimport getYoutubeVideoLinks as getYT\n\nimport os\nos.environ[\"EAI_USERNAME\"] = 'pitabi1360@pashter.com'\nos.environ[\"EAI_PASSWORD\"] = 'Testqwerty1!'\n\nfrom expertai.nlapi.cloud.client impo...
false
2,962
605c78795b5a072d330d44a150f26ad410d9d084
import bluetooth import serial import struct # Definition of Bluetooth rfcomm socket bd_addr = "98:D3:37:00:8D:39" # The address from the HC-05 sensor port = 1 sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) sock.connect((bd_addr,port)) # Definition of Serial port ser = serial.Serial("/dev/ttyACM0", 57600) def BT...
[ "import bluetooth\nimport serial\nimport struct\n\n# Definition of Bluetooth rfcomm socket\nbd_addr = \"98:D3:37:00:8D:39\" # The address from the HC-05 sensor\nport = 1\nsock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\nsock.connect((bd_addr,port))\n\n# Definition of Serial port\nser = serial.Serial(\"/dev/ttyAC...
true
2,963
e9a4ea69a4bd9b75b8eb8092b140691aab763ae4
from collections import Counter from collections import deque import os def wc(argval): bool = False if("|" in argval): bool = True del argval[len(argval)-1] hf=open("commandoutput.txt","r+") open("commandoutput.txt","w").close() hf=open("commandoutput.txt","w") numoflines = 0 ...
[ "from collections import Counter\nfrom collections import deque\nimport os\ndef wc(argval):\n bool = False\n if(\"|\" in argval):\n bool = True\n del argval[len(argval)-1] \n hf=open(\"commandoutput.txt\",\"r+\")\n open(\"commandoutput.txt\",\"w\").close()\n hf=open(\"commandoutput.txt\",...
true
2,964
7e20c61fa30ea93e69a2479e70449638eb52b7bb
#!/usr/bin/env python """ Update the expected test outputs and inputs for rsmsummarize and rsmcompare tests. This script assumes that you have already run `nose2 -s tests` and ran the entire test suite. By doing so, the output has been generated under the given outputs directory. And that is what will be used to gener...
[ "#!/usr/bin/env python\n\"\"\"\nUpdate the expected test outputs and inputs for rsmsummarize and rsmcompare tests.\n\nThis script assumes that you have already run `nose2 -s tests` and ran the entire\ntest suite. By doing so, the output has been generated under the given outputs\ndirectory. And that is what will be...
false
2,965
173b8e66ead62e3aa70805e42e06ea05257d5ee2
class Tool: def __init__(self, name, weight): self.name = name self.weight = weight def __repr__(self): return f'Tool({self.name!r},{self.weight})' tools = [ Tool('수준계', 3.5), Tool('해머', 1.25), Tool('스크류드라이버', .5), Tool('끌', .25) ] print(repr(tools)) tools.sort(reverse...
[ "class Tool:\n def __init__(self, name, weight):\n self.name = name\n self.weight = weight\n\n def __repr__(self):\n return f'Tool({self.name!r},{self.weight})'\n\n\ntools = [\n Tool('수준계', 3.5),\n Tool('해머', 1.25),\n Tool('스크류드라이버', .5),\n Tool('끌', .25)\n]\nprint(repr(tools)...
false
2,966
4f91c57ad42759654a87328d5c92de8da14ca5ea
import os from CTFd.utils.encoding import hexencode def generate_nonce(): return hexencode(os.urandom(32))
[ "import os\r\n\r\nfrom CTFd.utils.encoding import hexencode\r\n\r\n\r\ndef generate_nonce():\r\n return hexencode(os.urandom(32))\r\n", "import os\nfrom CTFd.utils.encoding import hexencode\n\n\ndef generate_nonce():\n return hexencode(os.urandom(32))\n", "<import token>\n\n\ndef generate_nonce():\n re...
false
2,967
a24ab93983546f8ae0fab042c121ac52388e62e8
users = {1: "Tom", 2: "Bob", 3: "Bill"} elements = {"Au": "Oltin", "Fe": "Temir", "H": "Vodorod", "O": "Kislorod"}
[ "users = {1: \"Tom\", 2: \"Bob\", 3: \"Bill\"}\n\nelements = {\"Au\": \"Oltin\", \"Fe\": \"Temir\", \"H\": \"Vodorod\", \"O\": \"Kislorod\"}", "users = {(1): 'Tom', (2): 'Bob', (3): 'Bill'}\nelements = {'Au': 'Oltin', 'Fe': 'Temir', 'H': 'Vodorod', 'O': 'Kislorod'}\n", "<assignment token>\n" ]
false
2,968
1c01fbf7eafd49ada71cb018a62ead5988dcf251
from prediction_model import PredictionModel import util.nlp as nlp import re class NLPPredictionModel(object): def getPasswordProbabilities(self, sweetwordList): # can not deal with sweetword that contains no letters result = [] for s in sweetwordList: words = re.findall(r"[...
[ "from prediction_model import PredictionModel\nimport util.nlp as nlp\nimport re\n\n\nclass NLPPredictionModel(object):\n\n def getPasswordProbabilities(self, sweetwordList):\n # can not deal with sweetword that contains no letters\n\n result = []\n for s in sweetwordList:\n words...
false
2,969
30a2e4aa88b286179e2870205e90fab4a7474e12
#!/usr/bin/env python # -*-coding:utf-8-*- __author__ = '李晓波' from linux import sysinfo #调用相应收集处理函数 def LinuxSysInfo(): #print __file__ return sysinfo.collect() def WindowsSysInfo(): from windows import sysinfo as win_sysinfo return win_sysinfo.collect()
[ "#!/usr/bin/env python\n# -*-coding:utf-8-*-\n__author__ = '李晓波'\n\nfrom linux import sysinfo\n\n\n#调用相应收集处理函数\n\ndef LinuxSysInfo():\n #print __file__\n return sysinfo.collect()\n\n\ndef WindowsSysInfo():\n from windows import sysinfo as win_sysinfo\n return win_sysinfo.collect()\n", "__author__ = '...
false
2,970
a74d27d9e31872100b4f22512abe9de7d9277de7
# -*- coding: GB18030 -*- import inspect import os,sys import subprocess from lib.common.utils import * from lib.common.loger import loger from lib.common import checker from lib.common.logreader import LogReader import shutil from lib.common.XmlHandler import * from lib.common.Dict import * class baseModule(object): ...
[ "# -*- coding: GB18030 -*-\nimport inspect\nimport os,sys\nimport subprocess\nfrom lib.common.utils import *\nfrom lib.common.loger import loger\nfrom lib.common import checker\nfrom lib.common.logreader import LogReader\nimport shutil\nfrom lib.common.XmlHandler import *\nfrom lib.common.Dict import *\n\nclass bas...
true
2,971
0d565c9f92a60d25f28c903c0a27e7b93d547a4f
#Create Pandas dataframe from the DarkSage output G[''] import pandas as pd import numpy as np # This is a way to converte multi dimensional data into pd.Series and then load these into the pandas dataframe Pos = [] for p in G['Pos']: Pos.append(p) Pos_df = pd.Series(Pos, dtype=np.dtype("object")) Vel = [] for ...
[ "#Create Pandas dataframe from the DarkSage output G['']\n\nimport pandas as pd\nimport numpy as np\n\n\n# This is a way to converte multi dimensional data into pd.Series and then load these into the pandas dataframe\nPos = []\nfor p in G['Pos']:\n Pos.append(p)\nPos_df = pd.Series(Pos, dtype=np.dtype(\"object\"...
false
2,972
c581d9714681e22c75b1eeb866ea300e87b883f1
def domain_sort_key(domain): """Key to sort hosts / domains alphabetically, by domain name.""" import re domain_expr = r'(.*\.)?(.*\.)(.*)' # Eg: (www.)(google.)(com) domain_search = re.search(domain_expr, domain) if domain_search and domain_search.group(1): # sort by domain name and then...
[ "def domain_sort_key(domain):\n \"\"\"Key to sort hosts / domains alphabetically, by domain name.\"\"\"\n import re\n domain_expr = r'(.*\\.)?(.*\\.)(.*)' # Eg: (www.)(google.)(com)\n domain_search = re.search(domain_expr, domain)\n\n if domain_search and domain_search.group(1):\n # sort by d...
false
2,973
a29cf9e7006d52cea8f5ccdcbc2087983ffa3ef3
from modules.core.logging.logging_service import LoggingService from modules.core.logging.models import LogLevel, LogEntry import pytest from .setup import register_test_db, register_test_injections, teardown,\ drop_all_collections @pytest.fixture(autouse=True) def setup(): register_test_db() ...
[ "from modules.core.logging.logging_service import LoggingService\nfrom modules.core.logging.models import LogLevel, LogEntry\nimport pytest\nfrom .setup import register_test_db, register_test_injections, teardown,\\\n drop_all_collections\n\n\n@pytest.fixture(autouse=True)\ndef setup():\n regi...
false
2,974
19888c998e8787533e84413272da1183f16fcdb1
# 8-7. Album: Write a function called make_album() that builds a dictionary # describing a music album. The function should take in an artist name and an # album title, and it should return a dictionary containing these two pieces # of information. Use the function to make three dictionaries representing # di...
[ "# 8-7. Album: Write a function called make_album() that builds a dictionary\n# describing a music album. The function should take in an artist name and an\n# album title, and it should return a dictionary containing these two pieces\n# of information. Use the function to make three dictionaries representin...
false
2,975
e40b34f0ee51cc14615c6225a7676929e6d2876a
#!/usr/bin/env python3 import datetime, random class State(object): def __init__(self, name): self.name = name def __str__(self): return self.name class State_New(State): def __init__(self): super(State_New, self).__init__("New") class State_Underway(State): def __init__(sel...
[ "#!/usr/bin/env python3\n\nimport datetime, random\n\nclass State(object):\n def __init__(self, name):\n self.name = name\n\n def __str__(self):\n return self.name\n\nclass State_New(State):\n def __init__(self):\n super(State_New, self).__init__(\"New\")\n\nclass State_Underway(State)...
false
2,976
4dd71d01e499f3d0ee49d3bf5204fb3bbb03ede5
from email import encoders from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr,formataddr import smtplib def _format_addr(s): name, addr = parseaddr(s) return formataddr((Header(name,'UTF-8').encode(), addr)) from_addr='gaofeng4280@163.com' to_addr='10713802...
[ "from email import encoders\nfrom email.header import Header\nfrom email.mime.text import MIMEText\nfrom email.utils import parseaddr,formataddr\n\nimport smtplib\n\ndef _format_addr(s):\n name, addr = parseaddr(s)\n return formataddr((Header(name,'UTF-8').encode(), addr))\n\nfrom_addr='gaofeng4280@163.com'\n...
false
2,977
5d55c586c57de8f287d9f51f0cb1f188c8046c29
#!/bin/python3 def solveMeFirst(a,b): return a + b print(solveMeFirst(int(input()),int(input())))
[ "#!/bin/python3\n\ndef solveMeFirst(a,b):\n return a + b\n\nprint(solveMeFirst(int(input()),int(input())))\n", "def solveMeFirst(a, b):\n return a + b\n\n\nprint(solveMeFirst(int(input()), int(input())))\n", "def solveMeFirst(a, b):\n return a + b\n\n\n<code token>\n", "<function token>\n<code token>\...
false
2,978
34f3212b0254cbcb5e1ca535a29d4fe820dcaad8
from .hacker import HackerRegistrationPage from .judge import JudgeRegistrationPage from .mentor import MentorRegistrationPage from .organizer import OrganizerRegistrationPage from .user import UserRegistrationPage
[ "from .hacker import HackerRegistrationPage\nfrom .judge import JudgeRegistrationPage\nfrom .mentor import MentorRegistrationPage\nfrom .organizer import OrganizerRegistrationPage\nfrom .user import UserRegistrationPage\n", "<import token>\n" ]
false
2,979
57490e56833154d3ed3a18b5bf7bc4db32a50d69
import numpy as np import json from netCDF4 import Dataset,stringtochar,chartostring,Variable,Group def is_json(myjson): try: json_object = json.loads(myjson) except: return False return True def getType(type): t=np.dtype(type).char if t=="S":return 'S1' if t=="U":return 'U1' return t def get...
[ "import numpy as np\nimport json\nfrom netCDF4 import Dataset,stringtochar,chartostring,Variable,Group\n\ndef is_json(myjson):\n try:\n json_object = json.loads(myjson)\n except:\n return False\n return True\n\ndef getType(type):\n t=np.dtype(type).char\n if t==\"S\":return 'S1'\n if t==\"U\":return 'U1...
false
2,980
863bae04a90143ed942a478c4b71a2269e123bb5
from compass import models from compass.models.MetabolicModel import MetabolicModel def test_sbml_3(): model = models.load_metabolic_model("RECON1_xml") assert isinstance(model, MetabolicModel) assert len(model.reactions) == 3742 assert len(model.species) == 2766 def test_sbml_2(): model = model...
[ "from compass import models\nfrom compass.models.MetabolicModel import MetabolicModel\n\n\ndef test_sbml_3():\n model = models.load_metabolic_model(\"RECON1_xml\")\n assert isinstance(model, MetabolicModel)\n assert len(model.reactions) == 3742\n assert len(model.species) == 2766\n\n\ndef test_sbml_2():...
false
2,981
ed2ae166c4881289b27b7e74e212ba2d6164998b
import numpy as np class Element(object): def __init__(self): self.ndof = 0 self.nn = 0 self.ng = 0 self.element_type = 0 self.coord_position = np.array([]) self.setup() def setup(self): pass def shape_function_value(self): ...
[ "\r\nimport numpy as np \r\n\r\n\r\nclass Element(object):\r\n\r\n def __init__(self):\r\n self.ndof = 0\r\n self.nn = 0\r\n self.ng = 0\r\n self.element_type = 0\r\n self.coord_position = np.array([])\r\n\r\n self.setup()\r\n\r\n def setup(self):\r\n pass\r\n\...
false
2,982
b109568c4dba05b16cbed1759a2b9e0a99babc67
import pandas as pd import numpy as np from scipy import misc from sklearn.model_selection import train_test_split from sklearn.utils import shuffle import time import math import cv2 import matplotlib matplotlib.use("TkAgg") from matplotlib import pyplot as plt from keras.models import Sequential from keras.layers im...
[ "import pandas as pd\nimport numpy as np\nfrom scipy import misc\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nimport time\nimport math\nimport cv2\nimport matplotlib\nmatplotlib.use(\"TkAgg\")\nfrom matplotlib import pyplot as plt\n\nfrom keras.models import Sequential\n...
false
2,983
6d0cfc9d5bbc45bfa356c45a7cdb9f4822b03e0a
# Visit 2.12.3 log file ScriptVersion = "2.12.3" if ScriptVersion != Version(): print "This script is for VisIt %s. It may not work with version %s" % (ScriptVersion, Version()) visit.ShowAllWindows() visit.ShowAllWindows() visit.OpenDatabase("test.vtk", 0) # The UpdateDBPluginInfo RPC is not supported in the VisIt...
[ "# Visit 2.12.3 log file\nScriptVersion = \"2.12.3\"\nif ScriptVersion != Version():\n print \"This script is for VisIt %s. It may not work with version %s\" % (ScriptVersion, Version())\nvisit.ShowAllWindows()\nvisit.ShowAllWindows()\nvisit.OpenDatabase(\"test.vtk\", 0)\n# The UpdateDBPluginInfo RPC is not supp...
true
2,984
0bb2a6ebbf75fae3466c34a435a531fabdc07f62
#!/usr/bin/env python ''' State Machine for the Flare task ''' import roslib import rospy import actionlib from rospy.timer import sleep import smach import smach_ros from dynamic_reconfigure.server import Server import math import os import sys import numpy as np from bbauv_msgs.msg import * from bbauv_msgs.srv...
[ "#!/usr/bin/env python\n'''\nState Machine for the Flare task\n'''\n\nimport roslib\nimport rospy\nimport actionlib\nfrom rospy.timer import sleep\n\nimport smach\nimport smach_ros\n\nfrom dynamic_reconfigure.server import Server\n\nimport math\nimport os\nimport sys\n\n\nimport numpy as np\n\nfrom bbauv_msgs.msg i...
false
2,985
76e1f811d06af0e6e83ae989a236a5cd22c55e01
# -*- coding: utf-8 -*- import argparse import redis from Tkinter import * import ttk import json import time import thread R = None NAME = {} PROBLEM_NAME = {} CONTEST_ID = None QUEUE_NAME = None BACKUP_QUEUE_NAME = None RUNID_FIELD = "runid" SUBMIT_TIME_FIELD = "submit_time" STATUS_FIELD = "status" STATUS_FINISHED...
[ "# -*- coding: utf-8 -*-\n\nimport argparse\nimport redis\nfrom Tkinter import *\nimport ttk\nimport json\nimport time\nimport thread\n\nR = None\nNAME = {}\nPROBLEM_NAME = {}\nCONTEST_ID = None\n\nQUEUE_NAME = None\nBACKUP_QUEUE_NAME = None\nRUNID_FIELD = \"runid\"\nSUBMIT_TIME_FIELD = \"submit_time\"\nSTATUS_FIEL...
false
2,986
d4d8d800b81a50f2c520f0394412935738d1a8ee
class Queue(object): def __init__(self, val_list=None): self.stack_one = [] self.stack_two = [] if val_list: for item in val_list: self.stack_one.append(item) def push(self, val=None): if val: self.stack_one.append(val) def pop(self):...
[ "class Queue(object):\n def __init__(self, val_list=None):\n self.stack_one = []\n self.stack_two = []\n if val_list:\n for item in val_list:\n self.stack_one.append(item)\n\n def push(self, val=None):\n if val:\n self.stack_one.append(val)\n\n ...
false
2,987
00f62fec7f5372c5798b0ebf3f3783233360581e
#!/usr/bin/env python3 import sys import csv import math import collections import argparse import fileinput import lp parser = argparse.ArgumentParser(description="Takes an input of *.lp format and sets all radii to the same value") parser.add_argument("inputfile", help="if specified reads a *.lp formatted file oth...
[ "#!/usr/bin/env python3\nimport sys\nimport csv\nimport math\n\nimport collections\nimport argparse\nimport fileinput\n\nimport lp\n\nparser = argparse.ArgumentParser(description=\"Takes an input of *.lp format and sets all radii to the same value\")\nparser.add_argument(\"inputfile\", help=\"if specified reads a *...
false
2,988
a6a5fddb8e1eda4cc8e9c79ad83019f55d149a80
import numpy as np from sklearn.model_selection import train_test_split from sklearn.datasets import load_digits from sklearn.metrics import confusion_matrix, classification_report from sklearn.preprocessing import LabelBinarizer def tanh(x): return np.tanh(x) def tanh_deriv(x): return 1.0 - np.tanh(x) * np...
[ "import numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import load_digits\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.preprocessing import LabelBinarizer\n\n\ndef tanh(x):\n return np.tanh(x)\n\n\ndef tanh_deriv(x):\n return 1.0 ...
false
2,989
524b6ebd0be4c2285fac540627bb48baca71452e
g#https://www.acmicpc.net/problem/9461 ''' 1. Divide 2 case △ and ▽ d[0] is △ sequence d[1] is ▽ sequence 2. find a role between d[0] and d[1] ''' import math t = int(input()) n = [] for _ in range(t): n.append(int(input())) index = math.ceil(max(n)/2) d = [[0 for _ in range(52)] for _ in range(2)] d[0][1],d[0][2],...
[ "g#https://www.acmicpc.net/problem/9461\n'''\n1. Divide 2 case △ and ▽\nd[0] is △ sequence\nd[1] is ▽ sequence\n2. find a role between d[0] and d[1]\n'''\nimport math\nt = int(input())\nn = []\nfor _ in range(t):\n n.append(int(input()))\nindex = math.ceil(max(n)/2)\nd = [[0 for _ in range(52)] for _ in range(2)...
false
2,990
47dc9212a1059cbca8ec6732deaa835fa9967fd8
from leapp.models import Model, fields from leapp.topics import TransactionTopic class TargetRepositoryBase(Model): topic = TransactionTopic repoid = fields.String() class UsedTargetRepository(TargetRepositoryBase): pass class RHELTargetRepository(TargetRepositoryBase): pass class CustomTargetRe...
[ "from leapp.models import Model, fields\nfrom leapp.topics import TransactionTopic\n\n\nclass TargetRepositoryBase(Model):\n topic = TransactionTopic\n repoid = fields.String()\n\n\nclass UsedTargetRepository(TargetRepositoryBase):\n pass\n\n\nclass RHELTargetRepository(TargetRepositoryBase):\n pass\n\n...
false
2,991
d18c45c08face08ce8f7dad915f1896c24c95cbf
from django.contrib import admin from main.models import Assignment, Review, Sample, Question, SampleMultipleFile # Register your models here. admin.site.register(Assignment) admin.site.register(Review) admin.site.register(Question) class MultipleFileInline(admin.TabularInline): model = SampleMultipleFile class S...
[ "from django.contrib import admin\nfrom main.models import Assignment, Review, Sample, Question, SampleMultipleFile\n\n# Register your models here.\nadmin.site.register(Assignment)\nadmin.site.register(Review)\nadmin.site.register(Question)\n\n\nclass MultipleFileInline(admin.TabularInline):\n\tmodel = SampleMultip...
false
2,992
d3f6fb612e314ee2b86f6218719ecac2cc642c59
# 홍준이는 요즘 주식에 빠져있다. 그는 미래를 내다보는 눈이 뛰어나, 날 별로 주가를 예상하고 언제나 그게 맞아떨어진다. 매일 그는 아래 세 가지 중 한 행동을 한다. # 1. 주식 하나를 산다. # 2. 원하는 만큼 가지고 있는 주식을 판다. # 3. 아무것도 안한다. # 홍준이는 미래를 예상하는 뛰어난 안목을 가졌지만, 어떻게 해야 자신이 최대 이익을 얻을 수 있는지 모른다. 따라서 당신에게 날 별로 주식의 가격을 알려주었을 때, 최대 이익이 얼마나 되는지 계산을 해달라고 부탁했다. # 예를 들어 날 수가 3일이고 날 별로 주가가 10, 7, 6일 때, 주...
[ "# 홍준이는 요즘 주식에 빠져있다. 그는 미래를 내다보는 눈이 뛰어나, 날 별로 주가를 예상하고 언제나 그게 맞아떨어진다. 매일 그는 아래 세 가지 중 한 행동을 한다.\n\n# 1. 주식 하나를 산다.\n# 2. 원하는 만큼 가지고 있는 주식을 판다.\n# 3. 아무것도 안한다.\n\n# 홍준이는 미래를 예상하는 뛰어난 안목을 가졌지만, 어떻게 해야 자신이 최대 이익을 얻을 수 있는지 모른다. 따라서 당신에게 날 별로 주식의 가격을 알려주었을 때, 최대 이익이 얼마나 되는지 계산을 해달라고 부탁했다.\n\n# 예를 들어 날 수가 3일이고 날 별로 주가가 1...
false
2,993
6a09311b5b3b876fd94ed0a9cce30e070528f22c
#manual forward propagation #based on a course I got from Datacamp.com 'Deep Learning in Python' #python3 ~/Documents/pyfiles/dl/forward.py #imports import numpy as np #we are going to simulate a neural network forward propagation algorithm #see the picture forwardPropagation.png for more info #the basics are it mov...
[ "#manual forward propagation\n#based on a course I got from Datacamp.com 'Deep Learning in Python'\n#python3 ~/Documents/pyfiles/dl/forward.py\n\n\n#imports\nimport numpy as np\n\n#we are going to simulate a neural network forward propagation algorithm\n#see the picture forwardPropagation.png for more info\n#the ba...
false
2,994
f882589729d74a910d20856d4dc02546fe316e0d
from Graph import create_random_graph def find_accessible_vertices_backwards(graph, end_vertex): if end_vertex not in graph.parse_vertices(): raise ValueError("The end vertex is not in the graph.") visited = [] queue = [] next_vertex = {} distance_to_end = {} queue.append...
[ "from Graph import create_random_graph\r\n\r\n\r\ndef find_accessible_vertices_backwards(graph, end_vertex):\r\n if end_vertex not in graph.parse_vertices():\r\n raise ValueError(\"The end vertex is not in the graph.\")\r\n\r\n visited = []\r\n queue = []\r\n next_vertex = {}\r\n distance_to_e...
false
2,995
8443d208a6a6bef82240235eeadbf6f8eaf77bcb
from __future__ import print_function, unicode_literals import sys import ast import os import tokenize import warnings from io import StringIO def interleave(inter, f, seq): """Call f on each item in seq, calling inter() in between. """ seq = iter(seq) try: f(next(seq)) except StopIteratio...
[ "from __future__ import print_function, unicode_literals\nimport sys\nimport ast\nimport os\nimport tokenize\nimport warnings\nfrom io import StringIO\n\ndef interleave(inter, f, seq):\n \"\"\"Call f on each item in seq, calling inter() in between.\n \"\"\"\n seq = iter(seq)\n try:\n f(next(seq))...
false
2,996
7430e17d1c424362399cf09a0c3ecae825d04567
import datetime count = 0 for y in xrange(1901,2001): for m in xrange(1,13): if datetime.date(y,m,1).weekday() == 6: count += 1 print count
[ "import datetime\ncount = 0\nfor y in xrange(1901,2001):\n\tfor m in xrange(1,13):\n\t\tif datetime.date(y,m,1).weekday() == 6:\n\t\t\tcount += 1\n\nprint count\n" ]
true
2,997
03b2b722832eb46f3f81618f70fd0475f1f08c94
from selenium import webdriver from time import sleep from bs4 import BeautifulSoup """ With selenium we need web driver for our browser. If you use google chrome, you can download chrome driver from here: http://chromedriver.chromium.org/downloads In linux (my OS) I extracted downloaded zip file and pla...
[ "\n\n\nfrom selenium import webdriver\nfrom time import sleep\nfrom bs4 import BeautifulSoup\n\n\n\n\n\"\"\"\n\nWith selenium we need web driver for our browser.\nIf you use google chrome, you can download chrome driver from here:\n \nhttp://chromedriver.chromium.org/downloads\n\n\nIn linux (my OS) I extracted d...
false
2,998
1f49d2341f0bcc712baede28f41c208a01b92e6d
class Rover(object): DIRECTIONS = 'NESW' MOVEMENTS = { 'N': (0, 1), 'E': (1, 0), 'S': (0, -1), 'W': (-1, 0) } def __init__(self, init_string, plateau_dimensions): ''' give the rover a sense of the plateau it's on ''' max_x, max_y = p...
[ "class Rover(object):\n\n DIRECTIONS = 'NESW'\n MOVEMENTS = {\n 'N': (0, 1),\n 'E': (1, 0),\n 'S': (0, -1),\n 'W': (-1, 0)\n }\n\n def __init__(self, init_string, plateau_dimensions):\n ''' \n give the rover a sense of the plateau it's on\n '''\n ...
true
2,999
e9b9f87a18a5788ac86b1e85c0f3d7858946e03a
from lib import gen, core Shellcode = gen.Varname_Creator() Hide_Window = gen.Varname_Creator() def Start(): Start_Code = "#include <windows.h>\n" Start_Code += "#include <tlhelp32.h>\n" Start_Code += "#include <stdio.h>\n" Start_Code += "#include <stdlib.h>\n" Start_Code += "#include <string....
[ "from lib import gen, core\n\n\n\nShellcode = gen.Varname_Creator()\nHide_Window = gen.Varname_Creator()\n\n\n\ndef Start():\n Start_Code = \"#include <windows.h>\\n\"\n Start_Code += \"#include <tlhelp32.h>\\n\"\n Start_Code += \"#include <stdio.h>\\n\"\n Start_Code += \"#include <stdlib.h>\\n\"\n S...
false