index int64 0 100k | blob_id stringlengths 40 40 | code stringlengths 7 7.27M | steps listlengths 1 1.25k | error bool 2
classes |
|---|---|---|---|---|
6,500 | fea0619263b081f60ed0a4e178ef777a8d5dc988 | from django.contrib import admin
from .models import TutorialsReview,TutorialsReviewComment
admin.site.register(TutorialsReview)
admin.site.register(TutorialsReviewComment) | [
"from django.contrib import admin\n\nfrom .models import TutorialsReview,TutorialsReviewComment\n\nadmin.site.register(TutorialsReview)\nadmin.site.register(TutorialsReviewComment)",
"from django.contrib import admin\nfrom .models import TutorialsReview, TutorialsReviewComment\nadmin.site.register(TutorialsReview... | false |
6,501 | 0779e516e35c41acf0529961e11541dfd1320749 | # funkcja usuwająca zera z listy
def remove_zeros(given_list):
list_without_zero = []
for element in given_list:
if element != 0:
list_without_zero.append(element)
return list_without_zero
# funkcja sortująca listę
def sort_desc(given_list):
# sorted_list = []
# for ... | [
"# funkcja usuwająca zera z listy \n\ndef remove_zeros(given_list):\n\n list_without_zero = []\n\n for element in given_list:\n if element != 0:\n list_without_zero.append(element)\n\n return list_without_zero\n\n# funkcja sortująca listę\n\ndef sort_desc(given_list):\n\n # sorted_list... | false |
6,502 | 1f0349edd9220b663f7469b287f796e4a54df88d | '''Finding Perfect Numbers
3/2/17
@author: Annalane Miller (asm9) and Ivanna Rodriguez (imr6)'''
num_perfect = 0
for value in range(2, 10000):
#set initial values
high= value
low = 1
divisors = []
#finding divisors
while low < high:
if value % low ==0:
high = value// low
... | [
"'''Finding Perfect Numbers\n3/2/17\n@author: Annalane Miller (asm9) and Ivanna Rodriguez (imr6)'''\n\n\nnum_perfect = 0\n\nfor value in range(2, 10000):\n#set initial values\n high= value\n low = 1\n divisors = []\n\n#finding divisors\n while low < high:\n if value % low ==0:\n high =... | false |
6,503 | b80deec4d3d3ab4568f37cc59e098f1d4af5504c | # Square-Root of Trinomials
import math
print("Έχουμε ένα τριώνυμο ax²+bx+c. Δώστε μία θετική ή αρνητική τιμή σε κάθε σταθερά!")
a=int(input("a:"))
b=int(input("b:"))
c=int(input("c:"))
D= b**2-4*a*c
print("Η Διακρίνουσα ειναι: " + str(D))
if D>0:
x1=(-b+math.sqrt(D))/(2*a)
print("Η πρώτη ρίζα ειναι: " + s... | [
"# Square-Root of Trinomials\nimport math\n\n\nprint(\"Έχουμε ένα τριώνυμο ax²+bx+c. Δώστε μία θετική ή αρνητική τιμή σε κάθε σταθερά!\")\na=int(input(\"a:\"))\nb=int(input(\"b:\"))\nc=int(input(\"c:\"))\n\nD= b**2-4*a*c\n\nprint(\"Η Διακρίνουσα ειναι: \" + str(D))\n\nif D>0:\n x1=(-b+math.sqrt(D))/(2*a)\n pr... | false |
6,504 | 7775d260f0db06fad374d9f900b03d8dbcc00762 | # -*- coding: utf-8 -*-
# @time : 2021/1/10 10:25
# @Author : Owen
# @File : mainpage.py
from selenium.webdriver.common.by import By
from homework.weixin.core.base import Base
from homework.weixin.core.contact import Contact
'''
企业微信首页
'''
class MainPage(Base):
#跳转到联系人页面
def goto_contact(self):
... | [
"# -*- coding: utf-8 -*-\n# @time : 2021/1/10 10:25\n# @Author : Owen\n# @File : mainpage.py\nfrom selenium.webdriver.common.by import By\n\nfrom homework.weixin.core.base import Base\nfrom homework.weixin.core.contact import Contact\n'''\n企业微信首页\n'''\n\nclass MainPage(Base):\n #跳转到联系人页面\n def goto_... | false |
6,505 | 071e3cf6b4337e0079bbb2c7694fff2468142070 | import pygame
class BackGround:
def __init__(self, x, y):
self.y = y
self.x = x
def set_image(self, src):
self.image = pygame.image.load(src)
self.rect = self.image.get_rect()
self.rect.y = self.y
self.rect.x = self.x
def draw(self, screen):
screen... | [
"import pygame\n\n\nclass BackGround:\n def __init__(self, x, y):\n self.y = y\n self.x = x\n\n def set_image(self, src):\n self.image = pygame.image.load(src)\n self.rect = self.image.get_rect()\n self.rect.y = self.y\n self.rect.x = self.x\n\n def draw(self, scre... | false |
6,506 | 784b51c05dc7b5e70016634e2664c9ec25b8a65a | import numpy as np
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from preprocessing import *
from utils import *
def find_optimal_param(lda, x_train, y_train):
probs_train = lda.predict_proba(x_train)[:, 1]
y_train = [x for _,x in sorted(zip(prob... | [
"import numpy as np\nfrom sklearn.decomposition import PCA\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\n\nfrom preprocessing import *\nfrom utils import *\n\n\ndef find_optimal_param(lda, x_train, y_train):\n\n probs_train = lda.predict_proba(x_train)[:, 1]\n\n y_train = [x for _,x i... | false |
6,507 | b0468e58c4d0387a92ba96e8fb8a876ece256c78 | import mmap;
import random;
def shuffle():
l_digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
random.shuffle(l_digits);
return "".join(l_digits);
with open("hello.txt", "r+") as f:
map = mmap.mmap(f.fileno(), 1000);
l_i = 0;
for l_digit in shuffle():
map[l_i] = l_digit;
... | [
"import mmap;\r\nimport random;\r\n\r\ndef shuffle():\r\n l_digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];\r\n random.shuffle(l_digits);\r\n\r\n return \"\".join(l_digits);\r\n\r\n\r\nwith open(\"hello.txt\", \"r+\") as f:\r\n map = mmap.mmap(f.fileno(), 1000);\r\n l_i = 0;\r\n\r\n for l_digit i... | false |
6,508 | 9cca73ebdf2b05fe29c14dc63ec1b1a7c917b085 | # Cutting a Rod | DP-13
# Difficulty Level : Medium
# Last Updated : 13 Nov, 2020
# Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is... | [
"# Cutting a Rod | DP-13\n# Difficulty Level : Medium\n# Last Updated : 13 Nov, 2020\n\n# Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of t... | false |
6,509 | 9061db3bb3aa3178262af58e56126302b9effdff | import pymel.all as pm
from collections import Counter
# example
# v.Create( sel[0], pm.datatypes.Color.red, sel[1], 'leftEye', 0.2 )
# select mesh 1st then the control
def Create( obj, targetColor, control, attr, offset ) :
shape = obj.getShape()
name = obj.name()
if( type(shape) == pm.Mesh ) :
outVerts = []
... | [
"import pymel.all as pm\nfrom collections import Counter\n\n# example\n# v.Create( sel[0], pm.datatypes.Color.red, sel[1], 'leftEye', 0.2 )\n# select mesh 1st then the control\n\ndef Create( obj, targetColor, control, attr, offset ) :\n\tshape = obj.getShape()\n\tname = obj.name()\n\tif( type(shape) == pm.Mesh ) :... | false |
6,510 | 89dfd9a32b008307eb4c456f2324804c29f3b68f | import numpy as np
class SampleMemory(object):
def __init__(self, item_shape, max_size):
self.memory = np.zeros((max_size,) + item_shape)
self.item_shape = item_shape
self.num_stored = 0
self.max_size = max_size
self.tail_index = 0
def sample(self, num_sampl... | [
"import numpy as np\r\n\r\n\r\nclass SampleMemory(object):\r\n def __init__(self, item_shape, max_size):\r\n self.memory = np.zeros((max_size,) + item_shape)\r\n self.item_shape = item_shape\r\n self.num_stored = 0\r\n self.max_size = max_size\r\n self.tail_index = 0\r\n\r\n ... | false |
6,511 | 30e4c4c5ef944b0cd2d36b2fe5f7eee39dff1d16 | alien_color = 'green'
if alien_color == 'green':
print('you earned 5 points')
alien_color2 = 'yellow'
if alien_color2 == 'green':
print ('your earned 5 points')
if alien_color2 == 'yellow':
print('Right answer')
# 5.4
alien_color = 'green'
if alien_color == 'green':
print('you earned 5 po... | [
"alien_color = 'green'\r\nif alien_color == 'green':\r\n print('you earned 5 points')\r\n\r\nalien_color2 = 'yellow'\r\nif alien_color2 == 'green':\r\n print ('your earned 5 points')\r\nif alien_color2 == 'yellow':\r\n print('Right answer')\r\n\r\n# 5.4\r\nalien_color = 'green'\r\nif alien_color == 'green'... | false |
6,512 | 3970c7768e892ad217c193b1d967c1203b7e9a25 | import math
def is_prime(n):
# Based on the Sieve of Eratosthenes
if n == 1:
return False
if n < 4:
# 2 and 3 are prime
return True
if n % 2 == 0:
return False
if n < 9:
# 5 and 7 are prime (we have already excluded 4, 6 and 8)
return True
if n %... | [
"import math\n\n\ndef is_prime(n):\n # Based on the Sieve of Eratosthenes\n if n == 1:\n return False\n if n < 4:\n # 2 and 3 are prime\n return True\n if n % 2 == 0:\n return False\n if n < 9:\n # 5 and 7 are prime (we have already excluded 4, 6 and 8)\n ret... | false |
6,513 | 76526bdff7418997ac90f761936abccbb3468499 | """
Array.diff
Our goal in this kata is to implement a difference function,
which subtracts one list from another and returns the result.
It should remove all values from list a, which are present in list b keeping their order.
"""
from unittest import TestCase
def list_diff(a, b):
return [x for x in a if x n... | [
"\"\"\"\nArray.diff\nOur goal in this kata is to implement a difference function,\n which subtracts one list from another and returns the result.\nIt should remove all values from list a, which are present in list b keeping their order.\n\"\"\"\nfrom unittest import TestCase\n\n\ndef list_diff(a, b):\n return... | false |
6,514 | 9fd985e9675514f6c8f3ac5b91962eb744e0e82c | import numpy
import matplotlib.pyplot as plt
numpy.random.seed(2)
# create datasets
x = numpy.random.normal(3, 1, 100)
y = numpy.random.normal(150, 40, 100) / x
# displaying original dataset
plt.scatter(x, y)
plt.title("Original dataset")
plt.xlabel("Minutes")
plt.ylabel("Spent money")
plt.show()
# train dataset wi... | [
"import numpy\nimport matplotlib.pyplot as plt\n\nnumpy.random.seed(2)\n\n# create datasets\nx = numpy.random.normal(3, 1, 100)\ny = numpy.random.normal(150, 40, 100) / x\n\n# displaying original dataset\nplt.scatter(x, y)\nplt.title(\"Original dataset\")\nplt.xlabel(\"Minutes\")\nplt.ylabel(\"Spent money\")\nplt.s... | false |
6,515 | 607700faebc2018327d66939419cc24a563c3900 | # Return min number of hacks (swap of adjacent instructions)
# in p so that total damage <= d.
# If impossible, return -1
def min_hacks(d, p):
# list containing number of shoot commands per
# damage level. Each element is represents a
# damage level; 1, 2, 4, 8, ... and so on.
shots = [0]
damage = 0
for c ... | [
"# Return min number of hacks (swap of adjacent instructions)\n# in p so that total damage <= d.\n# If impossible, return -1\ndef min_hacks(d, p):\n\n # list containing number of shoot commands per\n # damage level. Each element is represents a\n # damage level; 1, 2, 4, 8, ... and so on.\n shots = [0]\n damag... | false |
6,516 | 1634ae0e329b4f277fa96a870fbd19626c0ece81 | from sympy import *
import sys
x = Symbol("x")
# EOF
try:
in_str = input()
except Exception as e:
print("WRONG FORMAT!") # Wrong Format!
sys.exit(0)
in_str = in_str.replace("^", "**") #change '^'into'**' for recognition
# wrong expression
try:
in_exp = eval(in_str) # turn s... | [
"from sympy import *\nimport sys\nx = Symbol(\"x\")\n# EOF\ntry:\n in_str = input()\nexcept Exception as e:\n print(\"WRONG FORMAT!\") # Wrong Format!\n sys.exit(0)\n\nin_str = in_str.replace(\"^\", \"**\") #change '^'into'**' for recognition\n\n# wrong expression\ntry:\n in_exp = eval(in_... | false |
6,517 | 052824082854c5f7721efb7faaf5a794e9be2789 | L5 = [0]*10
print(L5)
L5[2] = 20
print(L5)
print(L5[1:4])
L5.append(30)
print(L5)
L5.remove(30) #Elimina la primera ocurrencia del objeto
print(L5)
L6 = [1,2,3,4,5,6]
print(L6[1::2])
print(L6[::2]) | [
"L5 = [0]*10\nprint(L5)\n\nL5[2] = 20\nprint(L5)\n\nprint(L5[1:4])\n\nL5.append(30)\nprint(L5)\n\n\nL5.remove(30) #Elimina la primera ocurrencia del objeto\nprint(L5) \n\nL6 = [1,2,3,4,5,6]\nprint(L6[1::2])\nprint(L6[::2])",
"L5 = [0] * 10\nprint(L5)\nL5[2] = 20\nprint(L5)\nprint(L5[1:4])\nL5.append(30)\nprint(L5... | false |
6,518 | e99d3ae82d8eea38d29d6c4f09fdb3858e36ca50 | import requests as r
from .security import Security, Securities
from .data import Data
url_base = 'https://www.alphavantage.co/query'
def _build_url(**kargs):
query = {
'function': 'TIME_SERIES_DAILY',
'symbol': 'SPY',
'outputsize': 'full',
'datatype': 'json',
'apikey': 'JPIO2GNGBMFRLGMN'
}
query.update(kar... | [
"import requests as r\n\nfrom .security import Security, Securities\nfrom .data import Data\n\n\nurl_base = 'https://www.alphavantage.co/query'\n\ndef _build_url(**kargs):\n\tquery = {\n\t'function': 'TIME_SERIES_DAILY',\n\t'symbol': 'SPY',\n\t'outputsize': 'full',\n\t'datatype': 'json',\n\t'apikey': 'JPIO2GNGBMFRL... | false |
6,519 | 4b14dee3625d5d0c703176ed2f0a28b2583fd84d | """
Creating flask server that response with a json
"""
from flask import Flask
from flask import jsonify
micro_service = Flask(__name__)
@micro_service.route('/') # http://mysite.com/
def home():
return jsonify({'message': 'Hello, world!'})
if __name__ == '__main__':
micro_service.run()
| [
"\"\"\"\nCreating flask server that response with a json\n\"\"\"\n\nfrom flask import Flask\nfrom flask import jsonify\n\nmicro_service = Flask(__name__)\n\n\n@micro_service.route('/') # http://mysite.com/\ndef home():\n return jsonify({'message': 'Hello, world!'})\n\n\nif __name__ == '__main__':\n micro_ser... | false |
6,520 | 430e971d2ae41bfd60e7416ecb2c26bb08e4df45 | import os
import os.path
import numpy as np
import pickle
import codecs
from konlpy.tag import Okt
from hyperparams import params
from gensim.models import FastText
#tokenizer
tokenizer = Okt()
def make_word_dictionary(word_dict_pkl_path=params['default_word_dict_pkl_path'], training_data_path = params['d... | [
"import os\r\nimport os.path\r\nimport numpy as np\r\nimport pickle\r\nimport codecs\r\nfrom konlpy.tag import Okt\r\nfrom hyperparams import params\r\nfrom gensim.models import FastText\r\n\r\n#tokenizer\r\ntokenizer = Okt()\r\n\r\ndef make_word_dictionary(word_dict_pkl_path=params['default_word_dict_pkl_path'], t... | false |
6,521 | 275f8b6ac31792a9e4bb823b61366f868e45ef4e | import datetime
from app.api.v2.models.db import Database
now = datetime.datetime.now()
db = Database()
cur = db.cur
class Meetup():
#meetup constructor
def __init__(self, topic, location, tags, happening_on):
self.topic = topic
self.location = location
self.tags = tags
self.h... | [
"import datetime\nfrom app.api.v2.models.db import Database\n\nnow = datetime.datetime.now()\ndb = Database()\ncur = db.cur\n\nclass Meetup():\n\n #meetup constructor\n def __init__(self, topic, location, tags, happening_on):\n self.topic = topic\n self.location = location\n self.tags = t... | false |
6,522 | 8804bfc5bed8b93e50279f0cbab561fe09d92a64 | from random import randint
import matplotlib.pyplot as plt
def generate_list(length: int) -> list:
"""Generate a list with given length with random integer values in the interval [0, length]
Args:
length (int): List length
Returns:
list: List generated with random values
"""
retu... | [
"from random import randint\nimport matplotlib.pyplot as plt\n\ndef generate_list(length: int) -> list:\n \"\"\"Generate a list with given length with random integer values in the interval [0, length]\n\n Args:\n length (int): List length\n\n Returns:\n list: List generated with random values... | false |
6,523 | cb2dd08a09d2e39bd83f82940c3d9a79a5a27918 | import logging
import subprocess
from pathlib import Path
from typing import Union
from git import Repo
def init_repo(metadata: str, path: str, deep_clone: bool) -> Repo:
clone_path = Path(path)
if not clone_path.exists():
logging.info('Cloning %s', metadata)
repo = (Repo.clone_from(metadata, ... | [
"import logging\nimport subprocess\nfrom pathlib import Path\nfrom typing import Union\nfrom git import Repo\n\n\ndef init_repo(metadata: str, path: str, deep_clone: bool) -> Repo:\n clone_path = Path(path)\n if not clone_path.exists():\n logging.info('Cloning %s', metadata)\n repo = (Repo.clone... | false |
6,524 | 7df55853d0f4f1bf56512c4427d7f91e9c1f2279 | """Initial migration
Revision ID: 1f2296edbc75
Revises: 7417382a3f1
Create Date: 2014-01-19 23:04:58.877817
"""
# revision identifiers, used by Alembic.
revision = '1f2296edbc75'
down_revision = '7417382a3f1'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from sqlalchemy i... | [
"\"\"\"Initial migration\n\nRevision ID: 1f2296edbc75\nRevises: 7417382a3f1\nCreate Date: 2014-01-19 23:04:58.877817\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '1f2296edbc75'\ndown_revision = '7417382a3f1'\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import pos... | false |
6,525 | 7eb4efb64a5a5b2e8c2dfa965411ff4c7aad6e35 | from soln import Solution
import pytest
@pytest.mark.parametrize(
["inp1", "inp2", "res"],
[
("112", 1, "11"),
("11000002000304", 4, "4"),
("9119801020", 6, "20"),
("111111", 3, "111"),
("1432219", 3, "1219"),
("10200", 1, "200"),
("10", 2, "0"),
... | [
"from soln import Solution\nimport pytest\n\n\n@pytest.mark.parametrize(\n [\"inp1\", \"inp2\", \"res\"],\n [\n (\"112\", 1, \"11\"),\n (\"11000002000304\", 4, \"4\"),\n (\"9119801020\", 6, \"20\"),\n (\"111111\", 3, \"111\"),\n (\"1432219\", 3, \"1219\"),\n (\"10200\... | false |
6,526 | 21c12aabfb21e84f3ea546842fb55c41d2129ff9 | import re
list = ["Protein XVZ [Human]","Protein ABC [Mouse]","go UDP[3] glucosamine N-acyltransferase [virus1]","Protein CDY [Chicken [type1]]","Protein BBC [type 2] [Bacteria] [cat] [mat]","gi p19-gag protein [2] [Human T-lymphotropic virus 2]"]
pattern = re.compile("\[(.*?)\]$")
for string in list:
match = re.se... | [
"import re\nlist = [\"Protein XVZ [Human]\",\"Protein ABC [Mouse]\",\"go UDP[3] glucosamine N-acyltransferase [virus1]\",\"Protein CDY [Chicken [type1]]\",\"Protein BBC [type 2] [Bacteria] [cat] [mat]\",\"gi p19-gag protein [2] [Human T-lymphotropic virus 2]\"]\npattern = re.compile(\"\\[(.*?)\\]$\")\nfor string in... | true |
6,527 | 9609f23463aa4c7859a8db741c7f3badd78b8553 | #!/usr/bin/python
'''Defines classes for representing metadata found in Biographies'''
class Date:
'''Object to represent dates. Dates can consist of regular day-month-year, but also descriptions (before, after, ca.). Object has attributes for regular parts and one for description, default is empty string.'''
... | [
"#!/usr/bin/python\n\n'''Defines classes for representing metadata found in Biographies'''\n\n\n\nclass Date:\n '''Object to represent dates. Dates can consist of regular day-month-year, but also descriptions (before, after, ca.). Object has attributes for regular parts and one for description, default is empty ... | true |
6,528 | f14b9373e9bf1ad7fe2216dfefc1571f5380fb27 | #!/usr/bin/python3
"""minimum time time to write operations of copy and paste"""
def minOperations(n):
"""
a method that calculates the fewest number of operations needed
to result in exactly n H characters in the file
"""
if n <= 1:
return 0
"""loop for n number of times"""
for i... | [
"#!/usr/bin/python3\n\"\"\"minimum time time to write operations of copy and paste\"\"\"\n\n\ndef minOperations(n):\n \"\"\"\n a method that calculates the fewest number of operations needed\n to result in exactly n H characters in the file\n \"\"\"\n if n <= 1:\n return 0\n\n \"\"\"loop fo... | false |
6,529 | 9c14f024b25c5014567405535dbe5a6c787cfe28 | from abc import ABC
from rest_framework import serializers
from shopping_cars.models import Order, ShoppingCart
class OrderSerializer(serializers.ModelSerializer):
class Meta:
model = Order
fields = '__all__'
class OrderProductSerializer(serializers.ModelSerializer):
class Meta:
mode... | [
"from abc import ABC\nfrom rest_framework import serializers\nfrom shopping_cars.models import Order, ShoppingCart\n\n\nclass OrderSerializer(serializers.ModelSerializer):\n class Meta:\n model = Order\n fields = '__all__'\n\n\nclass OrderProductSerializer(serializers.ModelSerializer):\n class M... | false |
6,530 | 02d4e1ddb0b4cf75c9902e13263c5a80417de01b | from tkinter import *
from tkinter import messagebox as mb
from tkinter.scrolledtext import ScrolledText
from tkinter import filedialog as fd
from child_window import ChildWindow
# from PIL import Image as PilImage
# from PIL import ImageTk, ImageOps
class Window:
def __init__(self, width, height, title="MyWindow... | [
"from tkinter import *\nfrom tkinter import messagebox as mb\nfrom tkinter.scrolledtext import ScrolledText\nfrom tkinter import filedialog as fd\nfrom child_window import ChildWindow\n# from PIL import Image as PilImage\n# from PIL import ImageTk, ImageOps\n\n\nclass Window:\n def __init__(self, width, height, ... | false |
6,531 | 76fbe055b53af9321cc0d57a210cfffe9188f800 | #
# PySNMP MIB module CISCO-LWAPP-CLIENT-ROAMING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-CLIENT-ROAMING-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:04:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ... | [
"#\n# PySNMP MIB module CISCO-LWAPP-CLIENT-ROAMING-MIB (http://snmplabs.com/pysmi)\n# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-CLIENT-ROAMING-MIB\n# Produced by pysmi-0.3.4 at Wed May 1 12:04:56 2019\n# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4\n# Usi... | false |
6,532 | 2c6dc4d55f64d7c3c01b3f504a72904451cb4610 | """
2. Schreiben Sie die Anzahl von symmetrischen Paaren (xy) und (yx).
"""
def symetrisch(x, y):
"""
bestimmt weder zwei zweistellige Zahlen x und y symetrisch sind
:param x: ein Element der Liste
:param y: ein Element der Liste
:return: True- wenn x und y symetrisch
False - sonst
... | [
"\"\"\"\n2. Schreiben Sie die Anzahl von symmetrischen Paaren (xy) und (yx).\n\"\"\"\n\n\ndef symetrisch(x, y):\n \"\"\"\n bestimmt weder zwei zweistellige Zahlen x und y symetrisch sind\n :param x: ein Element der Liste\n :param y: ein Element der Liste\n :return: True- wenn x und y symetrisch\n ... | false |
6,533 | 6afcb8f17f7436f0ae9fa3a8c2a195245a9801f1 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
class ZoomPanHandler:
"""
Matplotlib callback class to handle pan and zoom events.
"""
def __init__(self, axes, scale_factor=2, mouse_button=2):
"""
Default constructor for the ZoomPanHandler class.
Parameters... | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\n\n\nclass ZoomPanHandler:\n \"\"\"\n Matplotlib callback class to handle pan and zoom events.\n \"\"\"\n\n def __init__(self, axes, scale_factor=2, mouse_button=2):\n \"\"\"\n Default constructor for the ZoomPanHandler... | false |
6,534 | 3852ff2f3f4ac889256bd5f4e36a86d483857cef | from pyspark.sql import SparkSession, Row, functions, Column
from pyspark.sql.types import *
from pyspark.ml import Pipeline, Estimator
from pyspark.ml.feature import SQLTransformer, VectorAssembler
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml.tuning import TrainValidationSplit, ParamGridBuild... | [
"from pyspark.sql import SparkSession, Row, functions, Column\nfrom pyspark.sql.types import *\n\nfrom pyspark.ml import Pipeline, Estimator\nfrom pyspark.ml.feature import SQLTransformer, VectorAssembler\nfrom pyspark.ml.evaluation import RegressionEvaluator\nfrom pyspark.ml.tuning import TrainValidationSplit, Par... | false |
6,535 | d292de887c427e3a1b95d13cef17de1804f8f9ee | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
#led = 21
pins = [21, 25, 18]
# 0 1 2 3 4
names = ["First", "Second", "Third"]
for x in range(len(pins)):
GPIO.setup(pins[x], GPIO.IN, pull_up_down=GPIO.PUD_UP)
#GPIO.setup(led, GPIO.OUT)
while True:
input_state = 0
for i in ran... | [
"import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\n\n#led = 21\n\npins = [21, 25, 18]\n# 0 1 2 3 4\nnames = [\"First\", \"Second\", \"Third\"]\n\nfor x in range(len(pins)):\n GPIO.setup(pins[x], GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\n#GPIO.setup(led, GPIO.OUT)\n\n\nwhile True:\n inp... | false |
6,536 | 21ef8103a5880a07d8c681b2367c2beef727260f | import random
def take_second(element):
return element[1]
import string
def get_random_name():
name = ""
for i in range(random.randint(5, 15)):
name += random.choice(string.ascii_letters)
return name
imenik = [(777, "zejneba"), (324, "fahro"), (23, "fatih"), (2334, "muamer"), (435, "keri... | [
"import random\n\n\ndef take_second(element):\n return element[1]\n\n\nimport string\n\n\ndef get_random_name():\n name = \"\"\n for i in range(random.randint(5, 15)):\n name += random.choice(string.ascii_letters)\n return name\n\n\nimenik = [(777, \"zejneba\"), (324, \"fahro\"), (23, \"fatih\"),... | false |
6,537 | 93909ab98f1141940e64e079e09834ae5ad3995f | import requests
import time
import csv
import os
import pandas as pd
col_list1 = ["cardtype","username_opensea", "address", "username_game"]
df1 = pd.read_csv("profiles.csv", usecols=col_list1)
#
for j in range(0,len(df1) ): #usernames in opensea
print(j)
user=[]
proto=[]
purity=[]
... | [
"import requests\r\nimport time\r\nimport csv\r\nimport os\r\nimport pandas as pd\r\n\r\ncol_list1 = [\"cardtype\",\"username_opensea\", \"address\", \"username_game\"]\r\ndf1 = pd.read_csv(\"profiles.csv\", usecols=col_list1)\r\n\r\n\r\n\r\n#\r\nfor j in range(0,len(df1) ): #usernames in opensea\r\n print(j)\r\... | false |
6,538 | ee57e6a1ccbec93f3def8966f5621ea459f3d228 | from distutils.core import setup
setup(
name='json_config',
version='0.0.01',
packages=['', 'test'],
url='',
license='',
author='craig.ferguson',
author_email='',
description='Simple Functional Config For Changing Environments'
)
| [
"from distutils.core import setup\n\nsetup(\n name='json_config',\n version='0.0.01',\n packages=['', 'test'],\n url='',\n license='',\n author='craig.ferguson',\n author_email='',\n description='Simple Functional Config For Changing Environments'\n)\n",
"from distutils.core import setup\n... | false |
6,539 | f60d02fb14364fb631d87fcf535b2cb5782e728f | from typing import Any, Dict
from django.http import HttpRequest, HttpResponse
from zerver.decorator import REQ, has_request_variables, webhook_view
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import check_send_webhook_message, get_setup_webhook_message
from zerver.models import UserP... | [
"from typing import Any, Dict\n\nfrom django.http import HttpRequest, HttpResponse\n\nfrom zerver.decorator import REQ, has_request_variables, webhook_view\nfrom zerver.lib.response import json_success\nfrom zerver.lib.webhooks.common import check_send_webhook_message, get_setup_webhook_message\nfrom zerver.models ... | false |
6,540 | 40d08bfa3286aa30b612ed83b5e9c7a29e9de809 | # -*- coding: utf-8 -*-
from euler.baseeuler import BaseEuler
from os import path, getcwd
def get_name_score(l, name):
idx = l.index(name) + 1
val = sum([(ord(c) - 64) for c in name])
return idx * val
class Euler(BaseEuler):
def solve(self):
fp = path.join(getcwd(), 'euler/resources/names.t... | [
"# -*- coding: utf-8 -*-\n\nfrom euler.baseeuler import BaseEuler\nfrom os import path, getcwd\n\n\ndef get_name_score(l, name):\n idx = l.index(name) + 1\n val = sum([(ord(c) - 64) for c in name])\n return idx * val\n\n\nclass Euler(BaseEuler):\n def solve(self):\n fp = path.join(getcwd(), 'eule... | false |
6,541 | 0069a61127c5968d7014bdf7f8c4441f02e67df0 | # Copyright 2021 QuantumBlack Visual Analytics Limited
#
# 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
#
# THE SOFTWARE IS PROVIDED "AS IS",... | [
"# Copyright 2021 QuantumBlack Visual Analytics Limited\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# THE SOFTWARE IS PR... | false |
6,542 | 4f81eb7218fa1341bd7f025a34ec0677d46151b0 | from setuptools import find_packages, setup
NAME = 'compoelem'
VERSION = "0.1.1"
setup(
name=NAME,
packages=['compoelem', 'compoelem.generate', 'compoelem.compare', 'compoelem.visualize', 'compoelem.detect', 'compoelem.detect.openpose', 'compoelem.detect.openpose.lib'],
include_package_data=True,
versio... | [
"from setuptools import find_packages, setup\nNAME = 'compoelem'\nVERSION = \"0.1.1\"\nsetup(\n name=NAME,\n packages=['compoelem', 'compoelem.generate', 'compoelem.compare', 'compoelem.visualize', 'compoelem.detect', 'compoelem.detect.openpose', 'compoelem.detect.openpose.lib'],\n include_package_data=Tru... | false |
6,543 | b090e92fe62d9261c116529ea7f480daf8b3e84e | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
'''This function will compute the square root of all integers in
a matrix. '''
new_matrix = []
for index in matrix:
jndex = 0
new_row = []
while jndex < len(index):
... | [
"#!/usr/bin/python3\ndef square_matrix_simple(matrix=[]):\n\n '''This function will compute the square root of all integers in\n a matrix. '''\n\n new_matrix = []\n\n for index in matrix:\n jndex = 0\n new_row = []\n while jndex < l... | false |
6,544 | 207bb7c79de069ad5d980d18cdfc5c4ab86c5197 | def slices(series, length):
if length <= 0:
raise ValueError("Length has to be at least 1")
elif length > len(series) or len(series) == 0:
raise ValueError("Length has to be larger than len of series")
elif length == len(series):
return [series]
else:
result = []
... | [
"def slices(series, length):\n if length <= 0:\n raise ValueError(\"Length has to be at least 1\")\n elif length > len(series) or len(series) == 0:\n raise ValueError(\"Length has to be larger than len of series\")\n elif length == len(series):\n return [series]\n else:\n res... | false |
6,545 | b3f72bc12f85724ddcdaf1c151fd2a68b29432e8 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
MQTT handler for Event subscriptions.
"""
import json
import time
import tornado.gen
import tornado.ioloop
from hbmqtt.mqtt.constants import QOS_0
from tornado.queues import QueueFull
from wotpy.protocols.mqtt.handlers.base import BaseMQTTHandler
from wotpy.protocol... | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nMQTT handler for Event subscriptions.\n\"\"\"\n\nimport json\nimport time\n\nimport tornado.gen\nimport tornado.ioloop\nfrom hbmqtt.mqtt.constants import QOS_0\nfrom tornado.queues import QueueFull\n\nfrom wotpy.protocols.mqtt.handlers.base import BaseMQTTH... | false |
6,546 | 829e23ce2388260467ed159aa7e1480d1a3d6045 | """I referred below sample.
https://ja.wikipedia.org/wiki/Adapter_%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3#:~:text=Adapter%20%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3%EF%BC%88%E3%82%A2%E3%83%80%E3%83%97%E3%82%BF%E3%83%BC%E3%83%BB%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3%EF%BC%89,%E5%A4%89%E6%9B%B4%E3%81%99%E3%82%8B%E3%81%93%E3%81%A... | [
"\"\"\"I referred below sample.\n\nhttps://ja.wikipedia.org/wiki/Adapter_%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3#:~:text=Adapter%20%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3%EF%BC%88%E3%82%A2%E3%83%80%E3%83%97%E3%82%BF%E3%83%BC%E3%83%BB%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3%EF%BC%89,%E5%A4%89%E6%9B%B4%E3%81%99%E3%82%8B%E3%81%... | false |
6,547 | 6ee71cf61ae6a79ec0cd06f1ddc7dc614a76c7b9 | import os
_basedir = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
SECRET_KEY = '06A52C5B30EC2960310B45E4E0FF21C5D6C86C47D91FE19FA5934EFF445276A0'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(_basedir, 'app.db')
SQLALCHEMY_ECHO = True
DATABASE_CONNECT_OPTIONS = {}
THREADS_PER_PAGE = 8
CSRF_ENABL... | [
"import os\n_basedir = os.path.abspath(os.path.dirname(__file__))\n\nDEBUG = True\n\nSECRET_KEY = '06A52C5B30EC2960310B45E4E0FF21C5D6C86C47D91FE19FA5934EFF445276A0'\n\nSQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(_basedir, 'app.db')\nSQLALCHEMY_ECHO = True\nDATABASE_CONNECT_OPTIONS = {}\n\nTHREADS_PER_PAGE... | false |
6,548 | 253804644e366382a730775402768bc307944a19 | import unittest
'''
시험 문제 2) 장식자 구현하기
- 다수의 인자를 받아, 2개의 인자로 변환하여 함수를 호출토록 구현
- 첫번째 인자 : 홀수의 합
- 두번째 인자 : 짝수의 합
모든 테스트가 통과하면, 다음과 같이 출력됩니다.
쉘> python final_2.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK
'''
def divider(fn):
def wrap(*args):
o... | [
"import unittest\n\n\n'''\n시험 문제 2) 장식자 구현하기\n\n- 다수의 인자를 받아, 2개의 인자로 변환하여 함수를 호출토록 구현\n- 첫번째 인자 : 홀수의 합\n- 두번째 인자 : 짝수의 합\n\n모든 테스트가 통과하면, 다음과 같이 출력됩니다.\n\n\n쉘> python final_2.py\n...\n----------------------------------------------------------------------\nRan 3 tests in 0.000s\n\nOK\n'''\n\n\ndef divider(fn):\n ... | false |
6,549 | 0d37b6f0ea8854f9d4d4cd2ff235fa39bab7cc12 | import sys
def digit_sum(x):
sum = 0
while x != 0:
sum = sum + x % 10
x = x // 10
return sum
for i in sys.stdin:
test_num = int( i )
if test_num == 0:
break
count = 11
while digit_sum(test_num) != digit_sum(count * test_num):
count = count + 1
print('{... | [
"import sys\n\ndef digit_sum(x):\n sum = 0\n while x != 0:\n sum = sum + x % 10\n x = x // 10\n return sum\n\nfor i in sys.stdin:\n test_num = int( i )\n\n if test_num == 0:\n break\n\n count = 11\n while digit_sum(test_num) != digit_sum(count * test_num):\n count = ... | false |
6,550 | bcc76e4dbcc191e7912085cbb92c5b0ebd2b047b | from datetime import datetime
from pymongo import MongoClient
from bson import ObjectId
from config import config
class Database(object):
def __init__(self):
self.client = MongoClient(config['db']['url']) # configure db url
self.db = self.client[config['db']['name']] # configure db name
de... | [
"from datetime import datetime\nfrom pymongo import MongoClient\nfrom bson import ObjectId\n\nfrom config import config\n\n\nclass Database(object):\n def __init__(self):\n self.client = MongoClient(config['db']['url']) # configure db url\n self.db = self.client[config['db']['name']] # configure ... | false |
6,551 | 326f1b5bee8f488382a76fcc5559f4ea13734f21 | from scrapy import cmdline
cmdline.execute("scrapy crawl rapo.com".split())
| [
"from scrapy import cmdline\ncmdline.execute(\"scrapy crawl rapo.com\".split())\n",
"from scrapy import cmdline\ncmdline.execute('scrapy crawl rapo.com'.split())\n",
"<import token>\ncmdline.execute('scrapy crawl rapo.com'.split())\n",
"<import token>\n<code token>\n"
] | false |
6,552 | e364ba45513167966fe50e31a01f552ccedec452 | from ethereum.common import mk_transaction_sha, mk_receipt_sha
from ethereum.exceptions import InsufficientBalance, BlockGasLimitReached, \
InsufficientStartGas, InvalidNonce, UnsignedTransaction
from ethereum.messages import apply_transaction
from ethereum.slogging import get_logger
from ethereum.utils import enco... | [
"from ethereum.common import mk_transaction_sha, mk_receipt_sha\nfrom ethereum.exceptions import InsufficientBalance, BlockGasLimitReached, \\\n InsufficientStartGas, InvalidNonce, UnsignedTransaction\nfrom ethereum.messages import apply_transaction\nfrom ethereum.slogging import get_logger\nfrom ethereum.utils ... | false |
6,553 | deaaf7620b9eba32149f733cd543399bdc2813a1 |
import os
import requests
import json
from web import *
from libs_support import *
from rss_parser import *
from database import *
class Solr_helper:
""" Ho tro He thong tu dong cap nhat du lieu - su dung post.jar de tu dong cap nhat du lieu moi vao he thong theo
tung khoang thoi gian nhat dinh """
de... | [
"\nimport os\nimport requests\nimport json\n\nfrom web import *\nfrom libs_support import *\nfrom rss_parser import *\nfrom database import *\n\nclass Solr_helper:\n\n \"\"\" Ho tro He thong tu dong cap nhat du lieu - su dung post.jar de tu dong cap nhat du lieu moi vao he thong theo\n tung khoang thoi gian ... | true |
6,554 | 268c36f6fb99383ea02b7ee406189ffb467d246c | import re
import requests
def download_image(url: str) -> bool:
img_tag_regex = r"""<img.*?src="(.*?)"[^\>]+>"""
response = requests.get(url)
if response.status_code != 200:
return False
text = response.text
image_links = re.findall(img_tag_regex, text)
for link in image_links:
... | [
"import re\n\nimport requests\n\n\ndef download_image(url: str) -> bool:\n img_tag_regex = r\"\"\"<img.*?src=\"(.*?)\"[^\\>]+>\"\"\"\n\n response = requests.get(url)\n if response.status_code != 200:\n return False\n\n text = response.text\n image_links = re.findall(img_tag_regex, text)\n\n ... | false |
6,555 | d35d26cc50da9a3267edd2da706a4b6e653d22ac | import subprocess
class Audio:
def __init__(self):
self.sox_process = None
def kill_sox(self, timeout=1):
if self.sox_process is not None:
self.sox_process.terminate()
try:
self.sox_process.wait(timeout=timeout)
except subprocess.TimeoutExpir... | [
"import subprocess\n\nclass Audio:\n def __init__(self):\n self.sox_process = None\n\n def kill_sox(self, timeout=1):\n if self.sox_process is not None:\n self.sox_process.terminate()\n try:\n self.sox_process.wait(timeout=timeout)\n except subproc... | false |
6,556 | afe63f94c7107cf79e57f695df8543e0786a155f | def getGC(st):
n = 0
for char in st:
if char == 'C' or char == 'G':
n += 1
return n
while True:
try:
DNA = input()
ln = int(input())
maxLen = 0
subDNA = ''
for i in range(len(DNA) - ln + 1):
sub = DNA[i : i + ln]
if getG... | [
"def getGC(st):\n n = 0\n for char in st:\n if char == 'C' or char == 'G':\n n += 1\n return n\nwhile True:\n try:\n DNA = input()\n ln = int(input())\n maxLen = 0\n subDNA = ''\n for i in range(len(DNA) - ln + 1):\n sub = DNA[i : i + ln]\n... | false |
6,557 | a8c59f97501b3f9db30c98e334dbfcffffe7accd | import simple_map
import pickle
import os
import argparse
import cv2
argparser = argparse.ArgumentParser()
argparser.add_argument("--src", type=str, required=True,
help="source directory")
argparser.add_argument("--dst", type=str, required=True,
help="destination directory")
ar... | [
"import simple_map\nimport pickle\nimport os\nimport argparse\nimport cv2\n\nargparser = argparse.ArgumentParser()\n\nargparser.add_argument(\"--src\", type=str, required=True,\n help=\"source directory\")\nargparser.add_argument(\"--dst\", type=str, required=True,\n help=\"des... | false |
6,558 | 94560d8f6528a222e771ca6aa60349d9682e8f4b | from pig_util import outputSchema
@outputSchema('word:chararray')
def reverse(word):
"""
Return the reverse text of the provided word
"""
return word[::-1]
@outputSchema('length:int')
def num_chars(word):
"""
Return the length of the provided word
"""
return len(word) | [
"from pig_util import outputSchema\n\n@outputSchema('word:chararray')\ndef reverse(word):\n \"\"\"\n Return the reverse text of the provided word\n \"\"\"\n return word[::-1]\n\n\n@outputSchema('length:int')\ndef num_chars(word):\n \"\"\"\n Return the length of the provided word\n \"\"\"\n return le... | false |
6,559 | e6bd9391a5364e798dfb6d2e9b7b2b98c7b701ac | # coding:utf-8
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from multiprocessing import Pool
"""
用户id,时间戳,浏览行为数据,浏览子行为编号
"""
names = ['userid','time','browser_behavior','browser_behavior_number']
browse_history_train = pd.read_csv("../../pcredit/train/browse_history_train.txt",header=None)
... | [
"# coding:utf-8\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom multiprocessing import Pool\n\n\"\"\"\n 用户id,时间戳,浏览行为数据,浏览子行为编号\n\"\"\"\nnames = ['userid','time','browser_behavior','browser_behavior_number']\nbrowse_history_train = pd.read_csv(\"../../pcredit/train/browse_history_t... | true |
6,560 | 146cae8f60b908f04bc09b10c4e30693daec89b4 | import imgui
print("begin")
imgui.create_context()
imgui.get_io().display_size = 100, 100
imgui.get_io().fonts.get_tex_data_as_rgba32()
imgui.new_frame()
imgui.begin("Window", True)
imgui.text("HelloWorld")
imgui.end()
imgui.render()
imgui.end_frame()
print("end")
| [
"import imgui\nprint(\"begin\")\nimgui.create_context()\nimgui.get_io().display_size = 100, 100\nimgui.get_io().fonts.get_tex_data_as_rgba32()\n\n\nimgui.new_frame()\nimgui.begin(\"Window\", True)\nimgui.text(\"HelloWorld\")\nimgui.end()\n\nimgui.render()\nimgui.end_frame()\nprint(\"end\")\n",
"import imgui\nprin... | false |
6,561 | 31a5bf0b275238e651dcb93ce80446a49a4edcf4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 11 13:25:03 2020
@author: Dr. Michael Sigmond, Canadian Centre for Climate Modelling and Analysis
"""
import matplotlib.colors as col
import matplotlib.cm as cm
import numpy as np
def register_cccmacms(cmap='all'):
"""create my ... | [
"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 11 13:25:03 2020\n\n@author: Dr. Michael Sigmond, Canadian Centre for Climate Modelling and Analysis\n\"\"\"\n\n\nimport matplotlib.colors as col\n\n\nimport matplotlib.cm as cm\n\nimport numpy as np\n\n\ndef register_cccmacms(cmap='all'):... | false |
6,562 | b9b113bdc5d06b8a7235333d3b3315b98a450e51 | import random
s = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
t = True
while t:
a = random.randint(1, 10)
if a not in s:
t = False
s[a] = a
print(s)
| [
"import random\ns = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5}\nt = True\nwhile t:\n a = random.randint(1, 10)\n if a not in s:\n t = False\ns[a] = a\nprint(s)\n",
"import random\ns = {(1): 1, (2): 2, (3): 3, (4): 4, (5): 5}\nt = True\nwhile t:\n a = random.randint(1, 10)\n if a not in s:\n t = Fals... | false |
6,563 | 10a7c1827abb8a87f5965453aa2d8f5e8b4914e5 | import matplotlib.pyplot as plt
def xyplot(xdata,ydata,title):
fname = "/Users/nalmog/Desktop/swa_equipped_cumulative_"+title+".png"
#plt.figure(figsize=(500,500))
plt.plot(xdata, ydata)
plt.ylabel('some numbers')
# plt.savefig("/Users/nalmog/Desktop/swa_equipped_cumulative_"+title+".png", format... | [
"import matplotlib.pyplot as plt\n\ndef xyplot(xdata,ydata,title):\n fname = \"/Users/nalmog/Desktop/swa_equipped_cumulative_\"+title+\".png\"\n #plt.figure(figsize=(500,500))\n plt.plot(xdata, ydata)\n plt.ylabel('some numbers') \n# plt.savefig(\"/Users/nalmog/Desktop/swa_equipped_cumulative_\"+ti... | false |
6,564 | 1190e802fde6c2c6f48bd2720688bd9231b622e0 | """
PROYECTO : Portal EDCA-HN
NOMBRE : ZipTools
Descripcion : Clase utilitaria para descomprimir archivos ZIP.
MM/DD/YYYY Colaboradores Descripcion
05/07/2019 Alla Duenas Creacion.
"""
import zipfile
from edca_mensajes import EdcaErrores as err, EdcaMensajes as msg
from edca_logs.EdcaLogger... | [
"\"\"\"\r\nPROYECTO : Portal EDCA-HN\r\nNOMBRE : ZipTools\r\nDescripcion : Clase utilitaria para descomprimir archivos ZIP.\r\n\r\nMM/DD/YYYY Colaboradores Descripcion\r\n05/07/2019 Alla Duenas Creacion. \r\n\"\"\"\r\n\r\nimport zipfile\r\nfrom edca_mensajes import EdcaErrores as err, EdcaMensajes as... | false |
6,565 | 71503282e58f60e0936a5236edc094f1da937422 | from django.utils.text import slugify
from pyexpat import model
from django.db import models
# Create your models here.
from rest_framework_simplejwt.state import User
FREQUENCY = (
('daily', 'Diario'),
('weekly', 'Semanal'),
('monthly', 'Mensual')
)
class Tags(models.Model):
name = models.CharField(m... | [
"from django.utils.text import slugify\nfrom pyexpat import model\nfrom django.db import models\n# Create your models here.\nfrom rest_framework_simplejwt.state import User\n\nFREQUENCY = (\n ('daily', 'Diario'),\n ('weekly', 'Semanal'),\n ('monthly', 'Mensual')\n)\n\nclass Tags(models.Model):\n name = ... | false |
6,566 | b7038ad73bf0e284474f0d89d6c34967d39541c0 | from .auth import Auth
from .banDetection import BanDetectionThread
from .botLogging import BotLoggingThread
from .clientLauncher import ClientLauncher
from .log import LogThread, Log
from .mainThread import MainThread
from .nexonServer import NexonServer
from .tmLogging import TMLoggingThread
from .worldCheckboxStatus... | [
"from .auth import Auth\nfrom .banDetection import BanDetectionThread\nfrom .botLogging import BotLoggingThread\nfrom .clientLauncher import ClientLauncher\nfrom .log import LogThread, Log\nfrom .mainThread import MainThread\nfrom .nexonServer import NexonServer\nfrom .tmLogging import TMLoggingThread\nfrom .worldC... | false |
6,567 | 6928ff58ddb97883a43dfd867ff9a89db72ae348 | from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
import urllib
from flask import Flask
########################################################################################DataBase@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2
#connection string
params = urllib.parse.quote_plus('Driv... | [
"from flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\nimport urllib\nfrom flask import Flask\n########################################################################################DataBase@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2\n#connection string\nparams = urllib.parse.quote... | false |
6,568 | dc5b9600828857cc5ea434a7b010cd8aa2589d22 | from math import log2
from egosplit.benchmarks.data_structures.cover_benchmark import *
from egosplit.benchmarks.evaluation.utility import create_line
from networkit.stopwatch import clockit
# Analyse the result cover of a benchmark run
@clockit
def analyze_cover(benchmarks, result_dir, calc_f1, append):
if not app... | [
"from math import log2\n\nfrom egosplit.benchmarks.data_structures.cover_benchmark import *\nfrom egosplit.benchmarks.evaluation.utility import create_line\nfrom networkit.stopwatch import clockit\n\n\n# Analyse the result cover of a benchmark run\n@clockit\ndef analyze_cover(benchmarks, result_dir, calc_f1, append... | false |
6,569 | 94a84c7143763c6b7ccea1049cdec8b7011798cd | #!/usr/bin/python
#_*_ coding: utf-8 _*_
import MySQLdb as mdb
import sys
con = mdb.connect("localhost","testuser","testdB","testdb")
with con:
cur = con.cursor()
cur.execute("UPDATE Writers SET Name = %s WHERE Id = %s ",
("Guy de manupassant", "4"))
print "Number of rows updated: %d "% cur.... | [
"#!/usr/bin/python\n#_*_ coding: utf-8 _*_\n\nimport MySQLdb as mdb\nimport sys\n\ncon = mdb.connect(\"localhost\",\"testuser\",\"testdB\",\"testdb\")\n\nwith con:\n cur = con.cursor()\n\n cur.execute(\"UPDATE Writers SET Name = %s WHERE Id = %s \",\n (\"Guy de manupassant\", \"4\"))\n print \"N... | true |
6,570 | b2c0ef4a0af12b267a54a7ae3fed9edeab2fb879 | import torch
import torch.nn as nn
from model.common import UpsampleBlock, conv_, SELayer
def wrapper(args):
act = None
if args.act == 'relu':
act = nn.ReLU(True)
elif args.act == 'leak_relu':
act = nn.LeakyReLU(0.2, True)
elif args.act is None:
act = None
else:
rais... | [
"import torch\nimport torch.nn as nn\nfrom model.common import UpsampleBlock, conv_, SELayer\n\ndef wrapper(args):\n act = None\n if args.act == 'relu':\n act = nn.ReLU(True)\n elif args.act == 'leak_relu':\n act = nn.LeakyReLU(0.2, True)\n elif args.act is None:\n act = None\n e... | false |
6,571 | b984dc052201748a88fa51d25c3bd3c22404fa96 |
# import draw as p
# ако няма __init__.py
# from draw.point import Point
from draw import Rectangle
from draw import Point
from draw import ShapeUtils
if __name__ == '__main__':
pn1 = Point(9,8)
pn2 = Point(6,4)
print(f'dist: {pn1} and {pn1} = {ShapeUtils.distance(pn1,pn2)}')
rc1 = Rectangle(4... | [
"\n# import draw as p\n\n# ако няма __init__.py\n# from draw.point import Point \n\nfrom draw import Rectangle\nfrom draw import Point\nfrom draw import ShapeUtils\n\n\n\nif __name__ == '__main__':\n pn1 = Point(9,8)\n pn2 = Point(6,4)\n\n print(f'dist: {pn1} and {pn1} = {ShapeUtils.distance(pn1,pn2)}')\n... | false |
6,572 | 6c9f9363a95ea7dc97ccb45d0922f0531c5cfec9 | import re
_camel_words = re.compile(r"([A-Z][a-z0-9_]+)")
def _camel_to_snake(s):
""" Convert CamelCase to snake_case.
"""
return "_".join(
[
i.lower() for i in _camel_words.split(s)[1::2]
]
)
| [
"import re\n\n\n_camel_words = re.compile(r\"([A-Z][a-z0-9_]+)\")\n\n\ndef _camel_to_snake(s):\n \"\"\" Convert CamelCase to snake_case.\n \"\"\"\n return \"_\".join(\n [\n i.lower() for i in _camel_words.split(s)[1::2]\n ]\n )\n",
"import re\n_camel_words = re.compile('([A-Z]... | false |
6,573 | fd41e6d8530d24a8a564572af46078be77e8177f | SQL_INSERCION_COCHE = "INSERT INTO tabla_coches(marca, modelo, color, motor, precio) VALUES (%s,%s,%s,%s,%s);"
SQL_LISTADO_COCHES = "SELECT * FROM tabla_coches;"
| [
"SQL_INSERCION_COCHE = \"INSERT INTO tabla_coches(marca, modelo, color, motor, precio) VALUES (%s,%s,%s,%s,%s);\"\n\nSQL_LISTADO_COCHES = \"SELECT * FROM tabla_coches;\"\n",
"SQL_INSERCION_COCHE = (\n 'INSERT INTO tabla_coches(marca, modelo, color, motor, precio) VALUES (%s,%s,%s,%s,%s);'\n )\nSQL_LISTADO_C... | false |
6,574 | 2ee4b31f880441e87c437d7cc4601f260f34ae24 | from sys import getsizeof
# using parenthesis indicates that we are creating a generator
a = (b for b in range(10))
print(getsizeof(a))
c = [b for b in range(10)]
# c uses more memory than a
print(getsizeof(c))
for b in a:
print(b)
print(sum(a)) # the sequence has disappeared
| [
"from sys import getsizeof\n\n# using parenthesis indicates that we are creating a generator\na = (b for b in range(10))\n\nprint(getsizeof(a))\n\nc = [b for b in range(10)]\n\n# c uses more memory than a\nprint(getsizeof(c))\n\nfor b in a:\n print(b)\n\nprint(sum(a)) # the sequence has disappeared\n",
"from s... | false |
6,575 | 9376d697158faf91f066a88e87d317e79a4d9240 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This is a collection of monkey patches and workarounds for bugs in
earlier versions of Numpy.
"""
from ...utils import minversion
__all__ = ['NUMPY_LT_1_10_4', 'NUMPY_LT_1_11',
'NUMPY_LT_1_12', 'NUMPY_LT_1_13', 'NUMPY_LT_1_14',
... | [
"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"\nThis is a collection of monkey patches and workarounds for bugs in\nearlier versions of Numpy.\n\"\"\"\nfrom ...utils import minversion\n\n\n__all__ = ['NUMPY_LT_1_10_4', 'NUMPY_LT_1_11',\n 'NUMPY_LT_1_12', 'NUMPY_LT_1_13', 'NUMPY_L... | false |
6,576 | 539523f177e2c3c0e1fb0226d1fcd65463b68a0e | # -*- coding: utf-8 -*-
from __future__ import print_function
"""phy main CLI tool.
Usage:
phy --help
"""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
import sys
import os.path as op
im... | [
"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\n\"\"\"phy main CLI tool.\n\nUsage:\n\n phy --help\n\n\"\"\"\n\n#------------------------------------------------------------------------------\n# Imports\n#------------------------------------------------------------------------------\n\nimport s... | false |
6,577 | 31b109d992a1b64816f483e870b00c703643f514 | def resolve_data(raw_data, derivatives_prefix):
derivatives = {}
if isinstance(raw_data, dict):
for k, v in raw_data.items():
if isinstance(v, dict):
derivatives.update(resolve_data(v, derivatives_prefix + k + '_'))
elif isinstance(v, list):
deriva... | [
"def resolve_data(raw_data, derivatives_prefix):\n derivatives = {}\n if isinstance(raw_data, dict):\n for k, v in raw_data.items():\n if isinstance(v, dict):\n derivatives.update(resolve_data(v, derivatives_prefix + k + '_'))\n elif isinstance(v, list):\n ... | false |
6,578 | 09850f0d3d295170545a6342337e97a0f190989a | import plotly.express as px
import pandas as pd
def fiig(plan):
df = pd.DataFrame(plan)
fig = px.timeline(df, x_start="Начало", x_end="Завершение", y="РЦ", color='РЦ', facet_row_spacing=0.6,
facet_col_spacing=0.6, opacity=0.9, hover_data=['Проект', 'МК', 'Наменование', 'Номер', 'Минут'],... | [
"import plotly.express as px\nimport pandas as pd\n\n\ndef fiig(plan):\n df = pd.DataFrame(plan)\n fig = px.timeline(df, x_start=\"Начало\", x_end=\"Завершение\", y=\"РЦ\", color='РЦ', facet_row_spacing=0.6,\n facet_col_spacing=0.6, opacity=0.9, hover_data=['Проект', 'МК', 'Наменование', ... | false |
6,579 | d261efa72e1ab77507a1fd84aa2e462c6969af56 | from django.shortcuts import render, Http404, HttpResponse, redirect
from django.contrib.auth import authenticate, login
from website.form import UserForm
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from website.models import UserProfile
from website.form import UserForm
import pandas as ... | [
"from django.shortcuts import render, Http404, HttpResponse, redirect\nfrom django.contrib.auth import authenticate, login\nfrom website.form import UserForm\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom website.models import UserProfile\nfrom website.form import UserForm\nimport... | false |
6,580 | f8e6f6e1be6c4ea306b7770c918b97808a0765b2 | import random
import time
import unittest
from old import dict_groupby
class TestDictGroupBy(unittest.TestCase):
def setUp(self):
random.seed(0)
self.sut = dict_groupby
def generate_transaction(self):
return {
'transaction_type': random.choice(['a', 'b', 'c']),
... | [
"import random\nimport time\nimport unittest\n\nfrom old import dict_groupby\n\n\nclass TestDictGroupBy(unittest.TestCase):\n\n def setUp(self):\n random.seed(0)\n self.sut = dict_groupby\n\n def generate_transaction(self):\n return {\n 'transaction_type': random.choice(['a', '... | false |
6,581 | 0229783467b8bcd0361baf6be07e3261f34220c7 |
from numpy.testing import assert_almost_equal
from fastats.maths.norm_cdf import norm_cdf
def test_norm_cdf_basic_sanity():
assert_almost_equal(0.5, norm_cdf(0.0, 0, 1))
def test_norm_cdf_dartmouth():
"""
Examples taken from:
https://math.dartmouth.edu/archive/m20f12/public_html/matlabnormal
s... | [
"\nfrom numpy.testing import assert_almost_equal\n\nfrom fastats.maths.norm_cdf import norm_cdf\n\n\ndef test_norm_cdf_basic_sanity():\n assert_almost_equal(0.5, norm_cdf(0.0, 0, 1))\n\n\ndef test_norm_cdf_dartmouth():\n \"\"\"\n Examples taken from:\n https://math.dartmouth.edu/archive/m20f12/public_ht... | false |
6,582 | f14a8d0d51f0baefe20b2699ffa82112dad9c38f | no_list = {"tor:", "getblocktemplate", " ping ", " pong "}
for i in range(1, 5):
with open("Desktop/"+str(i)+".log", "r") as r:
with open("Desktop/"+str(i)+"-clean.log", "a+") as w:
for line in r:
if not any(s in line for s in no_list):
w.write(line)
| [
"no_list = {\"tor:\", \"getblocktemplate\", \" ping \", \" pong \"}\nfor i in range(1, 5):\n\twith open(\"Desktop/\"+str(i)+\".log\", \"r\") as r:\n\t\twith open(\"Desktop/\"+str(i)+\"-clean.log\", \"a+\") as w:\n\t\t\tfor line in r:\n\t\t\t\tif not any(s in line for s in no_list):\n\t\t\t\t\tw.write(line)\n",
"n... | false |
6,583 | aa6464c53176be9d89c6c06997001da2b3ee1e5c | from django import forms
from .models import Diagnosis, TODOItem
class DiagnosisForm(forms.ModelForm):
class Meta:
model = Diagnosis
fields = ['name', 'Rostered_physician', 'condition', 'details', 'date_of_diagnosis', 'content']
class TODOItemForm(forms.ModelForm):
class Meta:... | [
"from django import forms\r\nfrom .models import Diagnosis, TODOItem\r\n\r\n\r\nclass DiagnosisForm(forms.ModelForm):\r\n\r\n class Meta:\r\n model = Diagnosis\r\n fields = ['name', 'Rostered_physician', 'condition', 'details', 'date_of_diagnosis', 'content']\r\n\r\n\r\nclass TODOItemForm(forms.Mod... | false |
6,584 | 2fdbf418b5cec50ee6568897e0e749681efeef6b | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'find_result_window.ui'
#
# Created by: PyQt5 UI code generator 5.12.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_FindResultWindow(object):
def setupUi(self, FindResultW... | [
"# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'find_result_window.ui'\n#\n# Created by: PyQt5 UI code generator 5.12.2\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_FindResultWindow(object):\n def setupUi(... | false |
6,585 | eb891341488e125ae8c043788d7264fff4018614 | #!/usr/bin/env python
from http.client import HTTPConnection
import pytest
from circuits.web import Controller
from circuits.web.client import Client, request
from .helpers import urlopen
class Root(Controller):
def index(self):
return "Hello World!"
def request_body(self):
return self.r... | [
"#!/usr/bin/env python\n\nfrom http.client import HTTPConnection\n\nimport pytest\n\nfrom circuits.web import Controller\nfrom circuits.web.client import Client, request\n\nfrom .helpers import urlopen\n\n\nclass Root(Controller):\n\n def index(self):\n return \"Hello World!\"\n\n def request_body(self... | false |
6,586 | c5b40b373953a2375eeca453a65c49bdbb8715f1 | '''import math
x = 5
print("sqrt of 5 is", math.sqrt(64))
str1 = "bollywood"
str2 = 'ody'
if str2 in str1:
print("String found")
else:
print("String not found")
print(10+20)'''
#try:
#block of code
#except Exception l:
#block of code
#else:
#this code executes if except block is executed
try... | [
"'''import math\nx = 5\nprint(\"sqrt of 5 is\", math.sqrt(64))\n\nstr1 = \"bollywood\"\n\nstr2 = 'ody'\n\nif str2 in str1:\n print(\"String found\")\nelse:\n print(\"String not found\")\n\n print(10+20)'''\n\n#try:\n #block of code\n#except Exception l:\n #block of code\n#else:\n #this code executes... | false |
6,587 | bd0530b6f3f7b1a5d72a5b11803d5bb82f85105d | import numpy as np
import math
a = [
[0.54, -0.04, 0.10],
[-0.04, 0.50, 0.12],
[0.10, 0.12, 0.71]
]
b = [0.33, -0.05, 0.28]
# Метод Гаусса
def gauss(left, right, prec=3):
# Создаем расширенную матрицу
arr = np.concatenate((np.array(left), np.array([right]).T), axis=1)
print('\nИсходная матриц... | [
"import numpy as np\nimport math\n\n\na = [\n [0.54, -0.04, 0.10],\n [-0.04, 0.50, 0.12],\n [0.10, 0.12, 0.71]\n]\nb = [0.33, -0.05, 0.28]\n\n# Метод Гаусса\ndef gauss(left, right, prec=3):\n # Создаем расширенную матрицу\n arr = np.concatenate((np.array(left), np.array([right]).T), axis=1)\n prin... | false |
6,588 | 68f8b301d86659f9d76de443b0afe93fd7f7e8c2 | # getting a sample of data to parse for the keys of the players
import requests
import xml.etree.ElementTree as ET
currentPlayerInfoUrl="http://stats.nba.com/stats/commonallplayers?IsOnlyCurrentSeason=1&LeagueID=00&Season=2015-16"
r=requests.get(currentPlayerInfoUrl)
if r.status_code == requests.codes.ok:
with open(... | [
"# getting a sample of data to parse for the keys of the players\nimport requests\nimport xml.etree.ElementTree as ET\n\ncurrentPlayerInfoUrl=\"http://stats.nba.com/stats/commonallplayers?IsOnlyCurrentSeason=1&LeagueID=00&Season=2015-16\"\n\nr=requests.get(currentPlayerInfoUrl)\nif r.status_code == requests.codes.o... | false |
6,589 | 38f6700b283bdc68a0271cb3ec397ce72aa2de3c | # uncompyle6 version 3.2.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
# Embedded file name: filecmp
import os, stat
from itertools import ifilter, ifilterfalse, imap, izip
__all__ = [
'cmp', 'dircmp', 'cmpfiles']
_cache = {}
BU... | [
"# uncompyle6 version 3.2.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]\n# Embedded file name: filecmp\nimport os, stat\nfrom itertools import ifilter, ifilterfalse, imap, izip\n__all__ = [\n 'cmp', 'dircmp', 'cmpfiles']\n_... | true |
6,590 | ac19ae96d8262cadd43314c29198fccbc008c1b5 | #!/usr/bin/env python
from __future__ import print_function, division, unicode_literals
import os
import sys
import json
import logging
import tempfile
import itertools
import traceback
import subprocess as sp
from os.path import basename
from datetime import datetime
from argparse import ArgumentParser, FileType
PRE... | [
"#!/usr/bin/env python\n\nfrom __future__ import print_function, division, unicode_literals\nimport os\nimport sys\nimport json\nimport logging\nimport tempfile\nimport itertools\nimport traceback\nimport subprocess as sp\nfrom os.path import basename\nfrom datetime import datetime\nfrom argparse import ArgumentPar... | true |
6,591 | 501b8a9307a1fd65a5f36029f4df59bbe11d881a | from LAMARCK_ML.data_util import ProtoSerializable
class NEADone(Exception):
pass
class NoSelectionMethod(Exception):
pass
class NoMetric(Exception):
pass
class NoReproductionMethod(Exception):
pass
class NoReplaceMethod(Exception):
pass
class ModelInterface(ProtoSerializable):
def reset(self):
... | [
"from LAMARCK_ML.data_util import ProtoSerializable\n\n\nclass NEADone(Exception):\n pass\n\n\nclass NoSelectionMethod(Exception):\n pass\n\n\nclass NoMetric(Exception):\n pass\n\n\nclass NoReproductionMethod(Exception):\n pass\n\n\nclass NoReplaceMethod(Exception):\n pass\n\n\nclass ModelInterface(ProtoSerial... | false |
6,592 | 37804c92b69d366cc1774335b6a2295dfd5b98f3 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import codecs
import Levenshtein
import logging
import random
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
import time
from sklearn.model_selection import KFold
import numpy as np
import s... | [
"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\nimport json\r\nimport codecs\r\nimport Levenshtein\r\nimport logging\r\nimport random\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.model_selection import cross_val_score\r\nimport time\r\nfrom sklearn.model_selection import KFold\r\... | false |
6,593 | cd0b55e163851344273ad020d434cc8662083d19 | import math
class Rank:
class Stats(object):
'''Holds info used to calculate amount of xp a player gets'''
post_likes = 0
post_dislikes = 0
comment_likes = 0
comment_dislikes = 0
usage = 0
class Interval(object):
'''A class representing an interval. It ... | [
"import math\n\nclass Rank:\n\n class Stats(object):\n '''Holds info used to calculate amount of xp a player gets'''\n post_likes = 0\n post_dislikes = 0\n comment_likes = 0\n comment_dislikes = 0\n usage = 0\n\n class Interval(object):\n '''A class representin... | false |
6,594 | fc5d0dd16b87ab073bf4b054bd2641bdec88e019 | def descending_order(num):
return int(''.join(sorted(str(num), reverse=True)))
import unittest
class TestIsBalanced(unittest.TestCase):
def test_is_balanced(self):
self.assertEquals(descending_order(0), 0)
self.assertEquals(descending_order(15), 51)
self.assertEquals(descending_order(1... | [
"def descending_order(num):\n return int(''.join(sorted(str(num), reverse=True)))\n\nimport unittest\nclass TestIsBalanced(unittest.TestCase):\n\n def test_is_balanced(self):\n self.assertEquals(descending_order(0), 0)\n self.assertEquals(descending_order(15), 51)\n self.assertEquals(desc... | false |
6,595 | 1f3e20e7fe597a88cddacf6813250f1ede6c6ee0 | #!/usr/bin/python3
"""Prints the first State object from the database specified
"""
from sys import argv
import sqlalchemy
from sqlalchemy import create_engine, orm
from model_state import Base, State
if __name__ == "__main__":
engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'
... | [
"#!/usr/bin/python3\n\"\"\"Prints the first State object from the database specified\n\"\"\"\nfrom sys import argv\nimport sqlalchemy\nfrom sqlalchemy import create_engine, orm\nfrom model_state import Base, State\n\n\nif __name__ == \"__main__\":\n engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'\n ... | false |
6,596 | d13f06afeac938fc2cf4d3506b3f68c6de9de210 | import cv2
img = cv2.imread('imgs/1.png')
pixel = img[100, 100]
img[100, 100] = [57, 63, 99] # 设置像素值
b = img[100, 100, 0] # 57, 获取(100, 100)处, blue通道像素值
g = img[100, 100, 1] # 63
r = img[100, 100, 2] # 68
r = img[100, 100, 2] = 99 # 设置red通道
# 获取和设置
piexl = img.item(100, 100, 2)
img.itemset((100, 100, 2), 99)
| [
"import cv2\nimg = cv2.imread('imgs/1.png')\npixel = img[100, 100]\nimg[100, 100] = [57, 63, 99] # 设置像素值\nb = img[100, 100, 0] # 57, 获取(100, 100)处, blue通道像素值\ng = img[100, 100, 1] # 63\nr = img[100, 100, 2] # 68\nr = img[100, 100, 2] = 99 # 设置red通道\n# 获取和设置\npiexl = img.item(100, 100, 2)\nimg.itemset((100, 100... | false |
6,597 | 79f4ede16628c6fbf37dfb4fe5afb8489c120f5a | class Solution(object):
def lexicalOrder(self, n):
"""
:type n: int
:rtype: List[int]
"""
acc = []
self.backtrack(acc, 1, n)
return acc
def backtrack(self, acc, counter, n):
if counter > n:
return
elif len(acc) == n:
... | [
"class Solution(object):\n def lexicalOrder(self, n):\n \"\"\"\n :type n: int\n :rtype: List[int]\n \"\"\"\n\n acc = []\n self.backtrack(acc, 1, n)\n return acc\n\n def backtrack(self, acc, counter, n):\n if counter > n:\n return\n elif... | false |
6,598 | 37969899aa646f4cdd7a5513f17d26b334870f1b | import pymongo
import redis
import json
from time import time
user_timeline_mongodb = "mongodb://user-timeline-mongodb.sdc-socialnetwork-db.svc.cluster.local:27017/"
user_timeline_redis = "user-timeline-redis.sdc-socialnetwork-db.svc.cluster.local"
def handle(req):
"""handle a request to the function
Args:
... | [
"import pymongo\nimport redis\nimport json\nfrom time import time\n\nuser_timeline_mongodb = \"mongodb://user-timeline-mongodb.sdc-socialnetwork-db.svc.cluster.local:27017/\"\nuser_timeline_redis = \"user-timeline-redis.sdc-socialnetwork-db.svc.cluster.local\"\n\n\ndef handle(req):\n \"\"\"handle a request to th... | false |
6,599 | 2c43ede960febfb273f1c70c75816848768db4e5 | a,b,c,y=4.4,0.0,4.2,3.0
print(c+a*y*y/b) | [
"a,b,c,y=4.4,0.0,4.2,3.0\r\nprint(c+a*y*y/b)",
"a, b, c, y = 4.4, 0.0, 4.2, 3.0\nprint(c + a * y * y / b)\n",
"<assignment token>\nprint(c + a * y * y / b)\n",
"<assignment token>\n<code token>\n"
] | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.