index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
10,400
8db3a0e8a4d36176e9d8593226b6a883d688d03e
import requests from multiprocessing import Pool import math import logging import os import pickle import clip PROCESS_NUM = 20 RETRY_TIME = 5 MAGIC_CLIENT_ID = "jzkbprff40iqj646a697cyrvl0zt2m6" def init_directory_structure(): if not os.path.exists('data'): os.mkdir('data') if not os.path.exists('da...
[ "import requests\nfrom multiprocessing import Pool\nimport math\nimport logging\nimport os\nimport pickle\nimport clip\n\nPROCESS_NUM = 20\nRETRY_TIME = 5\nMAGIC_CLIENT_ID = \"jzkbprff40iqj646a697cyrvl0zt2m6\"\n\n\ndef init_directory_structure():\n if not os.path.exists('data'):\n os.mkdir('data')\n if...
false
10,401
bedd53d964519e5424447a9af0449abf31ab5eee
from typing import List, Tuple, Union, Dict, Any import matplotlib.pyplot as plt import numpy as np import pandas as pd from manual_ml.base import BaseModel from manual_ml.helpers.metrics import accuracy class Tree(BaseModel): """ Binary classification tree """ def __init__(self, mi...
[ "from typing import List, Tuple, Union, Dict, Any\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nfrom manual_ml.base import BaseModel\nfrom manual_ml.helpers.metrics import accuracy\n\n\nclass Tree(BaseModel):\n \"\"\"\n Binary classification tree\n \"\"\"\n def __init__(...
false
10,402
4c294684d97014057fe4953779e166e64ea8a98b
from mutagen.mp3 import MP3 from mutagen import MutagenError import os from stat import * path = input("path to directory with mp3: ") path = os.path.abspath(path) def iterate_in_folder(path): ln = 0 num = 0 for item in os.listdir(path): if S_ISDIR(os.stat(os.path.join(path,item))[ST_MODE]): ...
[ "from mutagen.mp3 import MP3\nfrom mutagen import MutagenError\nimport os\nfrom stat import *\n\npath = input(\"path to directory with mp3: \")\npath = os.path.abspath(path)\n\ndef iterate_in_folder(path):\n ln = 0\n num = 0\n for item in os.listdir(path):\n if S_ISDIR(os.stat(os.path.join(path,item...
false
10,403
16e315113a61fdab87ee67f4ffca38101e9d09d6
# Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICEN...
[ "# Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/...
false
10,404
30126431bc014950669f552b430c6626c6e32c9a
from django import template from ..models import Post from ..forms import SearchForm from django.db.models import Count register = template.Library() @register.simple_tag def total_posts(): return Post.published.count() # Tag to display the latest posts (default nimber of posts 5) @register.inclusion_tag('bl...
[ "from django import template\nfrom ..models import Post\nfrom ..forms import SearchForm\n\nfrom django.db.models import Count\n\n\nregister = template.Library()\n\n\n@register.simple_tag\ndef total_posts():\n return Post.published.count()\n\n\n# Tag to display the latest posts (default nimber of posts 5)\n@regis...
false
10,405
b88b46b5789d08bdad07f7ee14d570f02cecaa37
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # pip install console-menu from consolemenu import * from consolemenu.items import * from converter import * def cm_hexadecimal2decimal(): Screen().println(str(hexadecimal2decimal(Screen().input('Enter a hexadecimal without Ox : ').input_string))) Screen().input...
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# pip install console-menu\nfrom consolemenu import *\nfrom consolemenu.items import *\n\nfrom converter import *\n\ndef cm_hexadecimal2decimal():\n Screen().println(str(hexadecimal2decimal(Screen().input('Enter a hexadecimal without Ox : ').input_string)))\n ...
false
10,406
139d129ce1220cf0b78416b12f813e15f313139d
''' Created on 19 apr 2017 @author: Conny ''' from FunctionalLayer.PDS import PDS class LIGHT(PDS): def __init__(self,dev_id="+",dev_type="LightSensor",dev_location="+",shadow=True,starter=None,remote=True): super(LIGHT, self).__init__(dev_id,dev_type,dev_location,shadow,starter,remote)
[ "'''\nCreated on 19 apr 2017\n\n@author: Conny\n'''\nfrom FunctionalLayer.PDS import PDS\n\nclass LIGHT(PDS):\n def __init__(self,dev_id=\"+\",dev_type=\"LightSensor\",dev_location=\"+\",shadow=True,starter=None,remote=True):\n super(LIGHT, self).__init__(dev_id,dev_type,dev_location,shadow,starter,remote...
false
10,407
f20c1057d85210fed30923dbf467e6f8f442b79b
import os from setuptools import setup, find_packages from setuptools.command.install import install class CustomInstall(install): def run(self): install.run(self) for filepath in self.get_outputs(): if os.path.expanduser('~/.lw') in filepath: os.chmod(os.path.dirname...
[ "import os\nfrom setuptools import setup, find_packages\nfrom setuptools.command.install import install\n\n\nclass CustomInstall(install):\n\n def run(self):\n install.run(self)\n\n for filepath in self.get_outputs():\n if os.path.expanduser('~/.lw') in filepath:\n os.chmo...
false
10,408
48ab70febf4c0ab898ae58a96e6a95cb4566c21b
#!/bin/python3 # copyright Lauri K. Friberg 2021 """System module.""" import sys def is_even(number): """Find out if number is even.""" return (number%2)==0 def is_odd(number): """Find out if number is odd.""" return (number%2)==1 print ("©2021 Lauri K. Friberg. Weird algorithm. Look at https://cses.fi/...
[ "#!/bin/python3\n# copyright Lauri K. Friberg 2021\n\"\"\"System module.\"\"\"\nimport sys\ndef is_even(number):\n \"\"\"Find out if number is even.\"\"\"\n return (number%2)==0\ndef is_odd(number):\n \"\"\"Find out if number is odd.\"\"\"\n return (number%2)==1\nprint (\"©2021 Lauri K. Friberg. Weird a...
false
10,409
349f47e053cc529018782e6b05b975ba8c0431ff
numList = list(map(int, input().split())) first = True for i in numList: if i % 2 != 0: if first: first = False minOdd = i else: if i < minOdd: minOdd = i print(minOdd)
[ "numList = list(map(int, input().split()))\r\n\r\nfirst = True\r\nfor i in numList:\r\n if i % 2 != 0:\r\n if first:\r\n first = False\r\n minOdd = i\r\n else:\r\n if i < minOdd:\r\n minOdd = i\r\n\r\nprint(minOdd)\r\n", "numList = list(map(int, inp...
false
10,410
65833e4e9f17b32fd00f27bc62d38ff06a16b5e7
import os import re import sys import numpy import netCDF4 import rasterio from glob import glob from datetime import datetime from collections import namedtuple from osgeo import osr TileInfo = namedtuple('TileInfo', ['filename', 'datetime']) def parse_filename(filename): fields = re.match( ( ...
[ "import os\nimport re\nimport sys\nimport numpy\nimport netCDF4\nimport rasterio\nfrom glob import glob\nfrom datetime import datetime\nfrom collections import namedtuple\nfrom osgeo import osr\n\n\n\nTileInfo = namedtuple('TileInfo', ['filename', 'datetime'])\n\ndef parse_filename(filename):\n fields = re.match...
true
10,411
0da06cefb231e9f2d4a910310966eb6cac752136
# 修改串列中的元素 motorcycle = ["honda", "yamaha", "suzuki"] print(motorcycle) motorcycle[0] = 'ducati' print(motorcycle) # 在串列尾端新增元素 motorcycle.append('honda') print(motorcycle) # 在空串列中新增元素 motorcycle = [] motorcycle.append('honda') motorcycle.append('yamaha') motorcycle.append('suzuki') print(motorcycle) # 在串列中插入元素 m...
[ "# 修改串列中的元素\nmotorcycle = [\"honda\", \"yamaha\", \"suzuki\"]\nprint(motorcycle)\n\nmotorcycle[0] = 'ducati'\nprint(motorcycle)\n\n# 在串列尾端新增元素\nmotorcycle.append('honda')\nprint(motorcycle)\n\n# 在空串列中新增元素\n\nmotorcycle = []\n\nmotorcycle.append('honda')\nmotorcycle.append('yamaha')\nmotorcycle.append('suzuki')\n\np...
false
10,412
b187884e63b485c5cb62abdc787adef4bb73b20b
import numpy as np class Clue: def __init__(self, x_pos, y_pos, num, _direction, _length): self.x_position = x_pos self.y_position = y_pos self.number = num self.direction = _direction self.length = _length self.clue = "" self.answer = np.ndarray(self.le...
[ "import numpy as np\n\nclass Clue:\n \n def __init__(self, x_pos, y_pos, num, _direction, _length):\n self.x_position = x_pos\n self.y_position = y_pos\n self.number = num\n self.direction = _direction\n self.length = _length\n self.clue = \"\"\n self.answer = ...
false
10,413
65a7b71fc54fe0f6a06b13053517929daa5054fc
import cv2 as cv image_path = "C:/Users/xwen2/Desktop/109.JPG" image = cv.imread(image_path) image_size = image.shape print(image_size)
[ "import cv2 as cv\n\nimage_path = \"C:/Users/xwen2/Desktop/109.JPG\"\n\n\nimage = cv.imread(image_path)\nimage_size = image.shape\n\nprint(image_size)", "import cv2 as cv\nimage_path = 'C:/Users/xwen2/Desktop/109.JPG'\nimage = cv.imread(image_path)\nimage_size = image.shape\nprint(image_size)\n", "<import token...
false
10,414
f615ef8645204075d4157c1eb1ba471a550ba165
def divisors(num): sum = 1; for i in range(2,int(num/2)+1): if(num%i==0): sum = sum +i; return sum; def is_abundant(num): if(divisors(num)>num): return True; return False; def do_loop(list,abundants,num,MAX): res_list = list; for i in range(num+1): if(ab...
[ "def divisors(num):\n sum = 1;\n for i in range(2,int(num/2)+1):\n if(num%i==0):\n sum = sum +i;\n return sum;\n\ndef is_abundant(num):\n if(divisors(num)>num):\n return True;\n return False;\n\ndef do_loop(list,abundants,num,MAX):\n res_list = list;\n for i in range(nu...
false
10,415
dfcc47eb3b83816855612bd0ee99c0171d47ef8d
import pdfquery import xml.etree.ElementTree as et from django.conf import settings import os import pandas as pd from .models import Image import json from wand.image import Image as wi import cv2 from .face_api import face_detect, face_verify def processPdf(filename): pdfPath = settings.UPLOAD_DIR + '/' + filena...
[ "import pdfquery\nimport xml.etree.ElementTree as et\nfrom django.conf import settings\nimport os\nimport pandas as pd\nfrom .models import Image\nimport json\nfrom wand.image import Image as wi\nimport cv2\nfrom .face_api import face_detect, face_verify\n\ndef processPdf(filename):\n pdfPath = settings.UPLOAD_D...
false
10,416
5d6fc5369a6c9514e8d386d37e0c02281a46da7f
# -*- coding: utf-8 -*- """ Created on Mon Oct 24 21:59:06 2016 @author: Eirik """ import numpy as np import matplotlib.pyplot as plt import pylab as p import mpl_toolkits.mplot3d.axes3d as p3 e = 1.6e-19 m_p = 1.672621637e-27 #Reference Pearson r_D = 50.0E-03# radius D = 90.0E-06 #valleygap c = 3.0E...
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Oct 24 21:59:06 2016\r\n\r\n@author: Eirik\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pylab as p\r\nimport mpl_toolkits.mplot3d.axes3d as p3\r\n\r\ne = 1.6e-19\r\nm_p = 1.672621637e-27 #Reference Pearson\r\nr_D = 50.0E-03# ra...
true
10,417
832caa8c3e815782b98143a08c3f8226f8db8536
dicionario = {"um": 1, "dois": 2, "tres": 3, "quatro": 4, "cinco": 5, "seis": 6, "sete": 7, "oito": 8, "nove": 9, "dez": 10, "onze": 11, "doze": 12, "treze": 13, "catorze": 14, "quatorze": 14, "quinze": 15, "dezesseis": 16, "dezessete": 17, "dezoito": 18, "dezen...
[ "dicionario = {\"um\": 1, \"dois\": 2, \"tres\": 3, \"quatro\": 4, \"cinco\": 5, \"seis\": 6,\n \"sete\": 7, \"oito\": 8, \"nove\": 9, \"dez\": 10, \"onze\": 11, \n \"doze\": 12, \"treze\": 13, \"catorze\": 14, \"quatorze\": 14, \n \"quinze\": 15, \"dezesseis\": 16, \"dezesset...
false
10,418
c737a456cc6c0c35418221bc39b84721fafe20df
from rest_framework import viewsets from rest_framework.response import Response from rest_framework import status from rest_framework.decorators import detail_route, list_route from django.contrib.auth.models import User from rest_framework import serializers from jose import jwt from rest_framework.views import APIVi...
[ "from rest_framework import viewsets\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.decorators import detail_route, list_route\nfrom django.contrib.auth.models import User\nfrom rest_framework import serializers\nfrom jose import jwt\nfrom rest_framework.views ...
false
10,419
b6d7654052b94d3282fb19872e575b7c104ceb7f
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
[ "#!/usr/bin/env python\n# Licensed to Cloudera, Inc. under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. Cloudera, Inc. licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"Licen...
false
10,420
225d65394029d91972a9c65d82180a8c48b6657e
from Factories.FirebaseFactory.FirebaseClient import FirebaseClient class WalletFirebaseRepository(FirebaseClient): def __init__(self): super().__init__() self.collection = "wallets"
[ "from Factories.FirebaseFactory.FirebaseClient import FirebaseClient\n\n\nclass WalletFirebaseRepository(FirebaseClient):\n\n def __init__(self):\n super().__init__()\n self.collection = \"wallets\"\n", "from Factories.FirebaseFactory.FirebaseClient import FirebaseClient\n\n\nclass WalletFirebase...
false
10,421
90371d77c7c43381281c301fdac05bd3412a7eac
from tkinter import * root = Tk() def f(): root.geometry("20x20") print("A") root.after(50, f) root.mainloop()
[ "from tkinter import *\nroot = Tk()\ndef f():\n root.geometry(\"20x20\")\n print(\"A\")\n\nroot.after(50, f)\nroot.mainloop()", "from tkinter import *\nroot = Tk()\n\n\ndef f():\n root.geometry('20x20')\n print('A')\n\n\nroot.after(50, f)\nroot.mainloop()\n", "<import token>\nroot = Tk()\n\n\ndef f(...
false
10,422
e4c7195fc2eb653bcb52843761209b0141e6b259
import os, unittest, argparse, json, client import xml.etree.ElementTree as ET class TestPerson(unittest.TestCase): test_data = ('first_name,surname,age,nationality,favourite_color,interest\n' 'John,Keynes,29,British,red,cricket\n' 'Sarah,Robinson,54,,blue,badminton\n') def test_json_file(s...
[ "import os, unittest, argparse, json, client\nimport xml.etree.ElementTree as ET\n\nclass TestPerson(unittest.TestCase):\n\n test_data = ('first_name,surname,age,nationality,favourite_color,interest\\n'\n 'John,Keynes,29,British,red,cricket\\n'\n 'Sarah,Robinson,54,,blue,badminton\\n')\n \n def...
false
10,423
0091a099e73fd55adfc7899bbdb86d7ae6171854
import cv2 rect_width = 10 rect_height = 5 def get_vertical_lines_2(image, line_count): row = image.shape[0] col = image.shape[1] vertical_lines = [] for i in range(col): count = 0 for j in range(row): px = image[j, i] if px == 255: count += 1 ...
[ "import cv2\n\nrect_width = 10\nrect_height = 5\n\n\ndef get_vertical_lines_2(image, line_count):\n row = image.shape[0]\n col = image.shape[1]\n vertical_lines = []\n for i in range(col):\n count = 0\n for j in range(row):\n px = image[j, i]\n if px == 255:\n ...
false
10,424
a2a0c4db2cce39bc3426f3bd6d39957dcb8df655
from __future__ import absolute_import, unicode_literals from django.contrib.auth.models import User, Group from rest_framework.viewsets import ReadOnlyModelViewSet from .serializers import UserSerializer, GroupSerializer class UserViewSet(ReadOnlyModelViewSet): queryset = User.objects.all() serializer_clas...
[ "from __future__ import absolute_import, unicode_literals\n\nfrom django.contrib.auth.models import User, Group\nfrom rest_framework.viewsets import ReadOnlyModelViewSet\n\nfrom .serializers import UserSerializer, GroupSerializer\n\n\nclass UserViewSet(ReadOnlyModelViewSet):\n queryset = User.objects.all()\n ...
false
10,425
b27879a5677a2108f02ea41fecededc280c04162
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange # the angles of rotations theta1 = 3*2*pi/31 theta2 = 7*2*pi/31 theta3 = 11*2*pi/31 # we read streams of length from 1 to 30 for i in range(1,31): # quantum circuit with three qubit...
[ "from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer\nfrom math import pi\nfrom random import randrange\n\n# the angles of rotations\ntheta1 = 3*2*pi/31\ntheta2 = 7*2*pi/31\ntheta3 = 11*2*pi/31\n\n# we read streams of length from 1 to 30\nfor i in range(1,31):\n # quantum circuit ...
false
10,426
f032da298207c0e38945f673148cd92dc6d50c5e
from numpy import * def predict_ratings(US, SV, m, u, v, tt, num_test): pr = [0]*num_test for j in range(num_test): user_id = tt[j, 0] movie_id = tt[j, 1] r = u[user_id] c = v[movie_id] pr[j] = float("{0:.4f}".format(dot(US[r, :], SV[:, c]) + m[0, c])) re...
[ "from numpy import *\r\n\r\n\r\ndef predict_ratings(US, SV, m, u, v, tt, num_test):\r\n pr = [0]*num_test\r\n for j in range(num_test):\r\n user_id = tt[j, 0]\r\n movie_id = tt[j, 1]\r\n r = u[user_id]\r\n c = v[movie_id]\r\n pr[j] = float(\"{0:.4f}\".format(dot(US[r, :], SV...
false
10,427
fbb94abedcccc82c76cbbd6fc1c98414cd1f7050
# Python from __future__ import annotations # Internal from server import server
[ "# Python\nfrom __future__ import annotations\n# Internal\nfrom server import server\n\n", "from __future__ import annotations\nfrom server import server\n", "<import token>\n" ]
false
10,428
8efd15dc91886dc5418852bad00e4455298e3044
''' split.py Split Data into train (80%) and validate (20%) Run from root of project as python scripts/split.py ''' import os import glob import shutil def mkdir(dirname): if not os.path.isdir(dirname): os.mkdir(dirname) VALIDATE_DIR = "data/validate" mkdir(VALIDATE_DIR) TRAIN_DIR = "data/train" mkdir(T...
[ "''' split.py\nSplit Data into train (80%) and validate (20%)\nRun from root of project as\npython scripts/split.py\n'''\n\nimport os\nimport glob\nimport shutil\n\ndef mkdir(dirname):\n if not os.path.isdir(dirname):\n os.mkdir(dirname)\n\nVALIDATE_DIR = \"data/validate\"\nmkdir(VALIDATE_DIR)\n\nTRAIN_DI...
true
10,429
5baae0826b0f6f57ce43b17ec73dd30e15dbc46a
#!/usr/bin/python2 from stadium import ui import pytest import mock class TestListDialogController: def test_cancel_calls_callback(self): # Cancel should call cancel_func a = [] def cancel_func(): a.append('cancelled') def select_func(): a.append('s...
[ "#!/usr/bin/python2\nfrom stadium import ui\nimport pytest\nimport mock\n\nclass TestListDialogController:\n def test_cancel_calls_callback(self):\n # Cancel should call cancel_func\n a = []\n\n def cancel_func():\n a.append('cancelled')\n \n def select_func():\n ...
false
10,430
8fb696d63c786d144c157d5678b55b80f171d98d
#!/usr/bin/python2 import pygame.joystick class Joystick: def __init__(self): print "Creating Joystick" self.errors = [] self.init() self.set_buttons(0, 1, 2, 3,8) def init(self): print "Initialising joysticks" if(pygame.joystick.get_init()): print "Joystick module active - restarting" pygame...
[ "#!/usr/bin/python2\n\nimport pygame.joystick\n\nclass Joystick:\n\tdef __init__(self):\n\t\tprint \"Creating Joystick\"\n\t\tself.errors = []\n\t\tself.init()\n\t\tself.set_buttons(0, 1, 2, 3,8)\n\t\t\n\t\n\tdef init(self):\n\t\tprint \"Initialising joysticks\"\n\t\tif(pygame.joystick.get_init()):\n\t\t\tprint \"J...
true
10,431
19000b8c3d8e3f5bebaa32c98cf694332d2a0f12
import os import sys # 부모디렉토리 참조를 위한 설정추가 sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from user import User user = User('test123','홍길동') # 초기패스워드 조회 print(user.get_passowrd()) # get full name if user.get_full_name() == '홍길동': print('pass => get full name : ', user.get_full_na...
[ "import os\nimport sys\n\n# 부모디렉토리 참조를 위한 설정추가\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom user import User\n\nuser = User('test123','홍길동')\n\n\n# 초기패스워드 조회 \nprint(user.get_passowrd())\n\n\n# get full name\nif user.get_full_name() == '홍길동':\n print('pass => get full name ...
false
10,432
38b701c0715ecd70c326c13f97505879c8a2c2c6
# Generated by Django 2.0.10 on 2019-04-30 11:24 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Alertas', fields=[ ...
[ "# Generated by Django 2.0.10 on 2019-04-30 11:24\n\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Alertas',\n ...
false
10,433
5e7273c8f9f5ba54c3f9469612df271c40918a2c
import glob import os import numpy as np from chainer import dataset from chainer.dataset import download from chainercv.datasets.cityscapes.cityscapes_utils import cityscapes_labels from chainercv.utils import read_image class CityscapesSemanticSegmentationDataset(dataset.DatasetMixin): """Semantic segmentati...
[ "import glob\nimport os\n\nimport numpy as np\n\nfrom chainer import dataset\nfrom chainer.dataset import download\nfrom chainercv.datasets.cityscapes.cityscapes_utils import cityscapes_labels\nfrom chainercv.utils import read_image\n\n\nclass CityscapesSemanticSegmentationDataset(dataset.DatasetMixin):\n\n \"\"...
false
10,434
b5d218b2cd0f1222144e02367aa6cd4700044eea
"""Module containing base class for lookup database tables. LookupDBObject defines the base class for lookup tables and defines relevant methods. LookupDBObject inherits from DBObjectUnsharded and extends the functionality for getting, creating, updating and deleting the lookup relationship. """ from vtdb import db_o...
[ "\"\"\"Module containing base class for lookup database tables.\n\nLookupDBObject defines the base class for lookup tables and defines\nrelevant methods. LookupDBObject inherits from DBObjectUnsharded and\nextends the functionality for getting, creating, updating and deleting\nthe lookup relationship.\n\"\"\"\n\nfr...
false
10,435
8b4887e22726f0cf571ebea0174fcef42681a3ce
''' Abril 17 Autor: Vitoya ''' theBoard = {'7': ' ', '8': ' ', '9': ' ', '4': ' ', '5': ' ', '6': ' ', '1': ' ', '2': ' ', '3': ' '} boardKeys = [] for key in theBoard: boardKeys.append(key) def printBoard(board): print(board['7']+'|'+board['8']+'|'+board['9']) print('------') ...
[ "'''\nAbril 17\nAutor: Vitoya\n'''\n\ntheBoard = {'7': ' ', '8': ' ', '9': ' ',\n '4': ' ', '5': ' ', '6': ' ',\n '1': ' ', '2': ' ', '3': ' '}\n\nboardKeys = []\n\nfor key in theBoard:\n boardKeys.append(key)\n\ndef printBoard(board):\n print(board['7']+'|'+board['8']+'|'+board['9'])\n ...
false
10,436
35be3e3d4596a80cf26a3c1e47da41d85a9efc86
import requests import json import csv from os.path import dirname def sendMessage(jsonId): baseURLDir = dirname(__file__) json_open = open(baseURLDir + '/tmp/json/' + jsonId + '.json', 'r') json_load = json.load(json_open) with open(baseURLDir + '/data/webhookURL.csv') as f: reader = csv....
[ "import requests\n\nimport json\nimport csv\n\nfrom os.path import dirname\n\n\ndef sendMessage(jsonId):\n baseURLDir = dirname(__file__)\n\n json_open = open(baseURLDir + '/tmp/json/' + jsonId + '.json', 'r')\n json_load = json.load(json_open)\n\n with open(baseURLDir + '/data/webhookURL.csv') as f:\n ...
false
10,437
e1b547b86f286e57f948dc3f7ec5b068ab63b75e
from flask import Flask from flask import render_template, request, url_for, jsonify import pickle import numpy as np import pandas app = Flask(__name__,template_folder="templates") model = pickle.load(open("rf_model.pkl","rb")) label = pickle.load(open("label_encoder.pkl","rb")) columns = ["age","workclass","fnlgwt...
[ "from flask import Flask\nfrom flask import render_template, request, url_for, jsonify\nimport pickle\nimport numpy as np\nimport pandas\n\napp = Flask(__name__,template_folder=\"templates\")\n\nmodel = pickle.load(open(\"rf_model.pkl\",\"rb\"))\nlabel = pickle.load(open(\"label_encoder.pkl\",\"rb\"))\n\ncolumns = ...
false
10,438
9049371a4c88edf184c6f83ad164bb4e1f50c0d4
from pyBuilder import * class MyGUIBuilder(BuildCMakeTarget): def __init__(self): self.initPaths() def extract(self): res = self.unzip('files/mygui-*.zip') # unpack dependencies, needed for freetype res |= self.unzip('files/OgreDependencies_MSVC_*.zip', self.path+'/mygui-*') return res def configur...
[ "from pyBuilder import *\n\nclass MyGUIBuilder(BuildCMakeTarget):\n\tdef __init__(self):\n\t\tself.initPaths()\n\t\t\n\tdef extract(self):\n\t\tres = self.unzip('files/mygui-*.zip')\n\t\t# unpack dependencies, needed for freetype\n\t\tres |= self.unzip('files/OgreDependencies_MSVC_*.zip', self.path+'/mygui-*')\n\t...
false
10,439
0b847c67efc34cd2e4673f611bf337dd62fabe1f
# coding: utf-8 # @Time : 2020/7/10 11:00 # @Author : Liu rucai # @Software : PyCharm import random import pandas as pd import numpy as np import os import datetime import sys isGO = True list = [] def sum_list(bool_list, n, now_sum): global isGO global list if isGO == False: return list ...
[ "# coding: utf-8\n\n# @Time : 2020/7/10 11:00\n# @Author : Liu rucai\n# @Software : PyCharm\nimport random\nimport pandas as pd\nimport numpy as np\nimport os\nimport datetime\nimport sys\n\nisGO = True\nlist = []\n\n\ndef sum_list(bool_list, n, now_sum):\n global isGO\n global list\n if isGO == False:\...
false
10,440
adf7ab792f7539dfe6ff90ed2d5d18b6ddd7398c
def wrap_around(string, offset): offset = offset % len(string) return string[offset:] + string[:offset]
[ "\ndef wrap_around(string, offset):\n offset = offset % len(string)\n return string[offset:] + string[:offset]\n\n", "def wrap_around(string, offset):\n offset = offset % len(string)\n return string[offset:] + string[:offset]\n", "<function token>\n" ]
false
10,441
cfe897ed9651a3bc8eae8c0c739d353e0106f461
"""import smtplib import email.utils #from smtplib import SMTP massge = "this is just letter from python" import smtplib try: server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() except: print ("Something went wrong...") mail.starttls() mail.login('boooooo.2018@gmail.com','adgjmpw12345') mail.sen...
[ "\"\"\"import smtplib\nimport email.utils\n#from smtplib import SMTP\n\nmassge = \"this is just letter from python\"\n\nimport smtplib\n\ntry:\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.ehlo()\nexcept:\n print (\"Something went wrong...\")\nmail.starttls()\n\nmail.login('boooooo.2018@gmail.com...
false
10,442
6bece2b738cab259221b05dd4df1ad247f2d6d83
#!/usr/bin/env python __author__ = "Alberto Riva, ICBR Bioinformatics Core" __contact__ = "ariva@ufl.edu" __copyright__ = "(c) 2019, University of Florida Foundation" __license__ = "MIT" __date__ = "Mar 19 2019" __version__ = "1.0" import sys import gzip import os.path import subprocess as sp # Global ...
[ "#!/usr/bin/env python\n\n__author__ = \"Alberto Riva, ICBR Bioinformatics Core\"\n__contact__ = \"ariva@ufl.edu\"\n__copyright__ = \"(c) 2019, University of Florida Foundation\"\n__license__ = \"MIT\"\n__date__ = \"Mar 19 2019\"\n__version__ = \"1.0\"\n\nimport sys\nimport gzip\nimport os.path\nimpor...
false
10,443
e3aa7c9485f02828bd969a5dc9bdd72b8e47f050
# This is the weather module. import keys from urllib.request import urlopen from twilio.rest import Client import json def is_valid(number, digits): if len(number) != digits or not number.isdigit(): return False def get_degree(zip_code): if not is_valid(zip_code, 5): return False url = ...
[ "# This is the weather module.\nimport keys\nfrom urllib.request import urlopen\nfrom twilio.rest import Client\nimport json\n\n\ndef is_valid(number, digits):\n if len(number) != digits or not number.isdigit():\n return False\n\n\ndef get_degree(zip_code):\n if not is_valid(zip_code, 5):\n retu...
false
10,444
fb3c3cdab3e7e304e685afa3d226ace324d59bc5
# Generated by Django 2.1.5 on 2019-01-09 00:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('django_db_logger', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='statuslog', options={'order...
[ "# Generated by Django 2.1.5 on 2019-01-09 00:52\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('django_db_logger', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='statuslog',\n ...
false
10,445
3bb5e10459e633a57993be7fb33377c48bdf769b
from flask import Flask, render_template from game_of_life import GameOfLife app = Flask(__name__) game_of_life = None @app.route('/') def index(): GameOfLife(20, 20) return render_template('index.html') @app.route('/live') def live(): life = GameOfLife() if life.counter > 0: life.form...
[ "from flask import Flask, render_template\nfrom game_of_life import GameOfLife\n\napp = Flask(__name__)\n\ngame_of_life = None\n\n@app.route('/')\ndef index():\n GameOfLife(20, 20)\n return render_template('index.html')\n\n@app.route('/live')\ndef live():\n life = GameOfLife()\n if life.counter > 0:\n...
false
10,446
8072c709f042a0be7a05b727bd0f32fae852eb78
from gensim.models import Word2Vec import gensim.downloader as api corpus = api.load('text8') model = Word2Vec(corpus) model.wv.save("text8vectors.wordvectors")
[ "from gensim.models import Word2Vec\nimport gensim.downloader as api\n\ncorpus = api.load('text8')\nmodel = Word2Vec(corpus)\nmodel.wv.save(\"text8vectors.wordvectors\")\n", "from gensim.models import Word2Vec\nimport gensim.downloader as api\ncorpus = api.load('text8')\nmodel = Word2Vec(corpus)\nmodel.wv.save('t...
false
10,447
205ac6e49769dabdd0ab09cd58606005f040e43e
# to read in an integer and double it # python script.py user_input = int(input('Type in an integer ')) # converts user input to int double = user_input * 2 # multiply user input by 2 # print('User input = {}'.format(double)) print('You entered {}: Result doubled = {}'.format(user_input, double))
[ "# to read in an integer and double it\r\n# python script.py\r\n\r\nuser_input = int(input('Type in an integer ')) # converts user input to int\r\ndouble = user_input * 2 # multiply user input by 2\r\n# print('User input = {}'.format(double))\r\nprint('You entered {}: Result doubled = {}'.format(user_input, double)...
false
10,448
9810e045fefda259ba17ba3db90a162bfd92d553
#!/usr/bin/python """ This is the code to accompany the Lesson 1 (Naive Bayes) mini-project. Use a Naive Bayes Classifier to identify emails by their authors authors and labels: Sara has label 0 Chris has label 1 """ import sys from time import time sys.path.append("../tools/") from to...
[ "#!/usr/bin/python\n\n\"\"\" \n This is the code to accompany the Lesson 1 (Naive Bayes) mini-project. \n\n Use a Naive Bayes Classifier to identify emails by their authors\n \n authors and labels:\n Sara has label 0\n Chris has label 1\n\"\"\"\n \nimport sys\nfrom time import time\nsys.path.ap...
true
10,449
2de35309d010027f3fdcedc5f0b42493a6ce6809
import os import logging import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from collections import defaultdict from time import time class DataLoader: """ Utility class for loading various types of data from CSV files """ def __init__(self, id_prefix='', header_file=Non...
[ "import os\nimport logging\nimport pandas as pd\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom collections import defaultdict\nfrom time import time\n\n\nclass DataLoader:\n \"\"\"\n Utility class for loading various types of data from CSV files\n \"\"\"\n\n def __init__(self, id_p...
false
10,450
18bbe7d9961aeac2db08d8115f575cabd756b559
""" Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. For example, There is one obstacle in the middle of a 3x3 grid as illustrated below. [ [0,0,0], [0,1,0], [0,...
[ "\"\"\"\nFollow up for \"Unique Paths\":\n\nNow consider if some obstacles are added to the grids. How many unique paths would there be?\n\nAn obstacle and empty space is marked as 1 and 0 respectively in the grid.\n\nFor example,\nThere is one obstacle in the middle of a 3x3 grid as illustrated below.\n\n[\n [0,0...
false
10,451
dd70fe2c48b9f094ecea75f1426ac453fba7e3cf
# Generated by Django 3.1.2 on 2020-10-09 08:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('product', '0002_product_product_id'), ] operations = [ migrations.AlterField( model_name='product', name='detail', ...
[ "# Generated by Django 3.1.2 on 2020-10-09 08:48\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('product', '0002_product_product_id'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='product',\n ...
false
10,452
77e53110f7585128f08dfe2ba76176035530af57
# -*-coding:utf8-*- ################################################################################ # # # ################################################################################ """ 模块用法说明: 登录的引导页 Authors: turinblueice Date: 2016/7/26 """ from base import base_frame_view from util import log from gui_widg...
[ "# -*-coding:utf8-*-\n\n################################################################################\n#\n#\n#\n################################################################################\n\"\"\"\n模块用法说明: 登录的引导页\n\nAuthors: turinblueice\nDate: 2016/7/26\n\"\"\"\n\nfrom base import base_frame_view\nfrom uti...
false
10,453
fd98dc891bdee68eb0d26638d91493da43a2d6f5
#!/usr/bin/python # Version 0.05 # # Copyright (C) 2007 Adam Wolk "Mulander" <netprobe@gmail.com> # Slightly updated by Mikael Berthe # # To use this script, set the "events_command" option to the path of # the script (see the mcabberrc.example file for an example) # # This script is provided under the terms of the G...
[ "#!/usr/bin/python\n# Version 0.05\n#\n# Copyright (C) 2007 Adam Wolk \"Mulander\" <netprobe@gmail.com>\n# Slightly updated by Mikael Berthe\n#\n# To use this script, set the \"events_command\" option to the path of\n# the script (see the mcabberrc.example file for an example)\n#\n# This script is provided under ...
false
10,454
f54bc661b9400206bafe571051f4fe4721e27cf2
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc import ngraph.op_graph.hetr_grpc.hetr_pb2 as ngraph_dot_op__graph_dot_hetr__grpc_dot_hetr__pb2 class HetrStub(object): def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.Build...
[ "# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!\nimport grpc\n\nimport ngraph.op_graph.hetr_grpc.hetr_pb2 as ngraph_dot_op__graph_dot_hetr__grpc_dot_hetr__pb2\n\n\nclass HetrStub(object):\n\n def __init__(self, channel):\n \"\"\"Constructor.\n\n Args:\n channel: A grpc.Channel.\n ...
false
10,455
aa497969a588e15beb447df88a90b8ab1e6e7af4
listdata = list(range(5)) ret1 = reversed(listdata) print('원본 리스트 ', end='');print(listdata); print('역순 리스트 ', end='');print(list(ret1)) ret2 = listdata[::-1] print('슬라이싱 이용 ', end='');print(ret2)
[ "listdata = list(range(5))\r\nret1 = reversed(listdata)\r\nprint('원본 리스트 ', end='');print(listdata);\r\nprint('역순 리스트 ', end='');print(list(ret1))\r\n\r\nret2 = listdata[::-1]\r\nprint('슬라이싱 이용 ', end='');print(ret2)\r\n", "listdata = list(range(5))\nret1 = reversed(listdata)\nprint('원본 리스트 ', end='')\nprint(list...
false
10,456
35f07233857de4103826fe132654c3814cf65d02
from Qt import *
[ "from Qt import *", "from Qt import *\n", "<import token>\n" ]
false
10,457
6b3934c1a1e7db09a524005485ced8b1a218dc0d
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ OpenNebula Driver for Linstor Copyright 2019 LINBIT USA LLC 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/LICEN...
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nOpenNebula Driver for Linstor\nCopyright 2019 LINBIT USA LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apach...
false
10,458
7413ffdb53524a72e59fae9138e1b143a9a2e046
import os import curses import random class CaroBoard(object): """A class handle everything realted to the caro board""" def __init__(self, width, height): self.width = width self.height = height self.board = [[' ' for x in range(self.width)] for y in range(self.height)] self._turnCount = 0 def ConfigBoar...
[ "import os\nimport curses\nimport random\n\nclass CaroBoard(object):\n\t\"\"\"A class handle everything realted to the caro board\"\"\"\n\tdef __init__(self, width, height):\n\t\tself.width = width\n\t\tself.height = height\n\t\tself.board = [[' ' for x in range(self.width)] for y in range(self.height)]\n\t\tself._...
false
10,459
6ef8f6ab961db2cd66cdf90f7cd254bce23e9434
""" pyeventhub - a CLI that sends messages to an Azure Event Hub. """ import asyncio import random import time import json from itertools import count from datetime import datetime, timedelta from argparse import ArgumentParser from azure.eventhub.aio import EventHubProducerClient from azure.eventhub import EventData...
[ "\"\"\"\n pyeventhub - a CLI that sends messages to an Azure Event Hub.\n\"\"\"\n\nimport asyncio\nimport random\nimport time\nimport json\nfrom itertools import count\nfrom datetime import datetime, timedelta\nfrom argparse import ArgumentParser\nfrom azure.eventhub.aio import EventHubProducerClient\nfrom azure.ev...
false
10,460
65b4f90ee9b19c1a6406ab99f370a01aa9a8b79c
from itertools import product def primes(n): """ Returns a list of primes < n """ sieve = [True] * n for i in xrange(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1) return [2] + [i for i in xrange(3,n,2) if sieve[i]] P = primes(1000000) def num (n, ba...
[ "from itertools import product\n\ndef primes(n):\n \"\"\" Returns a list of primes < n \"\"\"\n sieve = [True] * n\n for i in xrange(3,int(n**0.5)+1,2):\n if sieve[i]:\n sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)\n return [2] + [i for i in xrange(3,n,2) if sieve[i]]\n\nP = primes(100...
true
10,461
3bcf4f4a4cfcb83fc088f60c119bd4f6c0320d48
# -*- coding: utf-8 -*- import rivescript import interaction import re import diccs import pickle import os def give_card(text,card_options): buttons=[] for option in card_options: buttons.append({ "type":"postback", "title":option, "payload":"DEVELOPER_DEFINED_PAYLO...
[ "\n# -*- coding: utf-8 -*-\nimport rivescript\nimport interaction\nimport re\nimport diccs\nimport pickle\nimport os\ndef give_card(text,card_options):\n buttons=[]\n for option in card_options:\n buttons.append({\n \"type\":\"postback\",\n \"title\":option,\n \"payload...
true
10,462
ea552e4771c4fec4b9992a96bf0996b2f76b46cc
""" Entradas compra-->int-->c salidas Descuento-->flot-->d """ c=float(input("digite compra")) #caja negra d=(c*0.15) total=(c-d) #Salidas print("el total a pagar es de :"+str(total))
[ "\"\"\"\nEntradas \ncompra-->int-->c\nsalidas \nDescuento-->flot-->d\n\"\"\"\nc=float(input(\"digite compra\"))\n#caja negra\nd=(c*0.15)\ntotal=(c-d)\n#Salidas \nprint(\"el total a pagar es de :\"+str(total))\n", "<docstring token>\nc = float(input('digite compra'))\nd = c * 0.15\ntotal = c - d\nprint('el total a...
false
10,463
6237ba43195b7b69706e5d46b0627423177c12e3
from django.contrib import admin from .models import * # Register your models here. admin.site.register(Localite) admin.site.register(User) admin.site.register(Groupe) admin.site.register(Membre) admin.site.register(Alerte) admin.site.register(SuiviAlerteGroupe) admin.site.register(SuiviAlertePerso) admin.site.registe...
[ "from django.contrib import admin\nfrom .models import *\n\n# Register your models here.\nadmin.site.register(Localite)\nadmin.site.register(User)\nadmin.site.register(Groupe)\nadmin.site.register(Membre)\nadmin.site.register(Alerte)\nadmin.site.register(SuiviAlerteGroupe)\nadmin.site.register(SuiviAlertePerso)\nad...
false
10,464
2e039c917d6c8267ad71fd88085122aa7759cd79
import os import requests import re def main(): print('start download test') with requests.get('http://tedisfree.github.io/abcdef', stream=True) as r: if r.status_code!=200: print('failed to download file (code=%d)' % r.status_code) if 'Content-Disposition' not in r.headers: ...
[ "import os\nimport requests\nimport re\n\ndef main():\n print('start download test')\n with requests.get('http://tedisfree.github.io/abcdef', stream=True) as r:\n if r.status_code!=200:\n print('failed to download file (code=%d)' % r.status_code)\n\n if 'Content-Disposition' not in r....
false
10,465
f5f21e75a61dab08f6efb88b0e6d47b39617378d
import logging from urllib.request import urlopen, Request, HTTPError, URLError import json logger = logging.getLogger() class CustomResourceResponse: def __init__(self, event): self.event = event self.response = { "StackId": event["StackId"], "RequestId": event["RequestId"...
[ "import logging\nfrom urllib.request import urlopen, Request, HTTPError, URLError\nimport json\n\nlogger = logging.getLogger()\n\nclass CustomResourceResponse:\n def __init__(self, event):\n self.event = event\n self.response = {\n \"StackId\": event[\"StackId\"],\n \"RequestI...
false
10,466
5a3e8d74198a054ca3a259ec5826bdb7b40f8672
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'main.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QTableWidgetItem import Estate import login ...
[ "# -*- coding: utf-8 -*-\r\n\r\n# Form implementation generated from reading ui file 'main.ui'\r\n#\r\n# Created by: PyQt5 UI code generator 5.11.3\r\n#\r\n# WARNING! All changes made in this file will be lost!\r\n\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\nfrom PyQt5.QtWidgets import QTableWidgetItem\r\nimpo...
false
10,467
4ca92509dcea2fb058f1278be4269f85939db5b3
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on @author: a.mikkonen@iki.fi """ import time import scipy as sp from matplotlib import pyplot as plt def power_law_profile(nn): n = 7 yperR = sp.linspace(0,1, 1000) u_rat = (yperR)**(1/n) # plt.plot(yperR, u_rat, 'k:', label=r"$\frac{\over...
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on\n\n@author: a.mikkonen@iki.fi\n\"\"\"\nimport time\nimport scipy as sp\nfrom matplotlib import pyplot as plt\n\ndef power_law_profile(nn):\n n = 7\n yperR = sp.linspace(0,1, 1000)\n u_rat = (yperR)**(1/n) \n# plt.plot(yperR, u_rat, ...
false
10,468
f510b19b9cd2b13fb7cf6033c3180622c2e410da
# q2b.py # Name: # Section: # TODO: fill sv_recursive # m is a matrix represented by a 2D list of integers. e.g. m = [[3, 0, 2, 18],[-1, 1, 3, 4],[-2, -3, 18, 7]] # This function returns the Special Value of the matrix passed in. def sv_recursive(m): # your code here return 0 # change
[ "# q2b.py\n# Name:\n# Section: \n\n# TODO: fill sv_recursive\n# m is a matrix represented by a 2D list of integers. e.g. m = [[3, 0, 2, 18],[-1, 1, 3, 4],[-2, -3, 18, 7]]\n# This function returns the Special Value of the matrix passed in.\ndef sv_recursive(m):\n # your code here\n return 0 # change \n\n", "def ...
false
10,469
a5f5cf0a0965e5bafc578a0c4bf0dad9d4714e00
# # * The Plan class for the <i>groupby</i> operator. # * @author Edward Sciore # from simpledb.materialize.GroupByScan import GroupByScan from simpledb.materialize.SortPlan import SortPlan from simpledb.plan.Plan import Plan from simpledb.record.Schema import Schema class GroupByPlan(Plan): # # * Crea...
[ "#\n# * The Plan class for the <i>groupby</i> operator.\n# * @author Edward Sciore\n#\nfrom simpledb.materialize.GroupByScan import GroupByScan\nfrom simpledb.materialize.SortPlan import SortPlan\nfrom simpledb.plan.Plan import Plan\nfrom simpledb.record.Schema import Schema\n\n\nclass GroupByPlan(Plan):\n\n #...
false
10,470
6618c741754d4dcc209e95a3a9e56814ac9243c4
#!/usr/local/bin/python3 from lib import * if __name__ == '__main__': input = [str.split("\t") for str in open('./input.txt', 'r').read().strip().split("\n")] print("solution: {}".format(Solver().solve(input)))
[ "#!/usr/local/bin/python3\n\nfrom lib import *\n\nif __name__ == '__main__':\n input = [str.split(\"\\t\") for str in open('./input.txt', 'r').read().strip().split(\"\\n\")]\n\n print(\"solution: {}\".format(Solver().solve(input)))\n", "from lib import *\nif __name__ == '__main__':\n input = [str.split('...
false
10,471
c372dc232f0a7e10145d1b15e6457373ce2f9abb
from dataChest import * import matplotlib.pyplot as plt # import os file_path = 'GapEngineer\\Nb_GND_Dev01\\Leiden_2020Feb\\LIU\\Q1\\03-16-20\\QP_Tunneling_PSD\\HDF5Data' file_name = 'cvd2133wum_QP_Tunneling_PSD.hdf5' # ftag = file_name.split('_')[0] print(file_path.split('\\')) dc = dataChest(file_path.split('\\')) ...
[ "from dataChest import *\nimport matplotlib.pyplot as plt\n# import os\n\nfile_path = 'GapEngineer\\\\Nb_GND_Dev01\\\\Leiden_2020Feb\\\\LIU\\\\Q1\\\\03-16-20\\\\QP_Tunneling_PSD\\\\HDF5Data'\nfile_name = 'cvd2133wum_QP_Tunneling_PSD.hdf5'\n\n# ftag = file_name.split('_')[0]\nprint(file_path.split('\\\\'))\ndc = dat...
false
10,472
b51705afbfedb1f8b33fa0457c98262670a151a2
pattern = {'N':(1,5,2,3,0,4),'S':(4,0,2,3,5,1),'E':(3,1,0,5,4,2),'W':(2,1,5,0,4,3)} dice_num = input().split() for x in input(): dice_num = [dice_num[i] for i in pattern[x]] print(dice_num[0])
[ "pattern = {'N':(1,5,2,3,0,4),'S':(4,0,2,3,5,1),'E':(3,1,0,5,4,2),'W':(2,1,5,0,4,3)}\ndice_num = input().split()\nfor x in input():\n dice_num = [dice_num[i] for i in pattern[x]]\nprint(dice_num[0])\n", "pattern = {'N': (1, 5, 2, 3, 0, 4), 'S': (4, 0, 2, 3, 5, 1), 'E': (3, 1, 0,\n 5, 4, 2), 'W': (2, 1, 5, 0...
false
10,473
446ce06b97ac1183d73546eb376cb79a71ac9176
from flask import Flask, abort, make_response, jsonify, render_template from util.utils import Member,getSchedules app = Flask(__name__) app.config['JSON_AS_ASCII'] = False app.config['JSON_SORT_KEYS'] = False @app.route('/', methods=['GET']) def index(): api_list = ['/members', '/member/20','/schedules'] r...
[ "from flask import Flask, abort, make_response, jsonify, render_template\n\nfrom util.utils import Member,getSchedules\n\napp = Flask(__name__)\napp.config['JSON_AS_ASCII'] = False\napp.config['JSON_SORT_KEYS'] = False\n\n\n@app.route('/', methods=['GET'])\ndef index():\n api_list = ['/members', '/member/20','/s...
false
10,474
a29022140fd7603594c802b27b442c676ab167b7
__author__ = 'sunary' from time import sleep from multiprocessing import Process class StreamEachId(): ''' Each stream listen each id ''' def __init__(self): self.list_process = [] def run(self): list_ids = [i for i in range(10)] for id in list_ids: self.lis...
[ "__author__ = 'sunary'\n\n\nfrom time import sleep\nfrom multiprocessing import Process\n\n\nclass StreamEachId():\n '''\n Each stream listen each id\n '''\n def __init__(self):\n self.list_process = []\n\n def run(self):\n list_ids = [i for i in range(10)]\n\n for id in list_ids...
true
10,475
02026c1c6f3de9d2b0ce9dcd0c438dfaf8ef8a56
#Read in the data import pandas as pd import numpy as np dete_survey = pd.read_csv('D:\\dataquest\\projects\\dete_survey.csv') #Quick exploration of the data pd.options.display.max_columns = 150 # to avoid truncated output dete_survey.head() #Read in the data tafe_survey = pd.read_csv("D:\\dataquest\\proje...
[ "#Read in the data\r\nimport pandas as pd\r\nimport numpy as np\r\ndete_survey = pd.read_csv('D:\\\\dataquest\\\\projects\\\\dete_survey.csv')\r\n\r\n#Quick exploration of the data\r\npd.options.display.max_columns = 150 # to avoid truncated output \r\ndete_survey.head()\r\n\r\n#Read in the data\r\ntafe_survey = pd...
false
10,476
de39e4dd694431a279c829b01de68084773403c1
from invoke import task, run @task(aliases=["sh"]) def shell(ctx): """ Runs django's interactive shell :return: """ run("./manage.py shell_plus", pty=True) @task(aliases=["mg"]) def migrate(ctx): """ Runs the migrations :return: """ run("./manage.py migrate", pty=True) @tas...
[ "from invoke import task, run\n\n\n@task(aliases=[\"sh\"])\ndef shell(ctx):\n \"\"\"\n Runs django's interactive shell\n :return:\n \"\"\"\n run(\"./manage.py shell_plus\", pty=True)\n\n\n@task(aliases=[\"mg\"])\ndef migrate(ctx):\n \"\"\"\n Runs the migrations\n :return:\n \"\"\"\n ru...
false
10,477
6174ea75dd183ccef94441f055397f0e3e9dca8d
import sys import json import numpy as np # import tensorflow as tf from scipy import sparse from sklearn.metrics import f1_score from sklearn import svm import random def print_request(r): """Print a request in a human readable format to stdout""" def fmt_token(t): return t['shape'] + t['after'] ...
[ "import sys\nimport json\nimport numpy as np\n# import tensorflow as tf\nfrom scipy import sparse\nfrom sklearn.metrics import f1_score\nfrom sklearn import svm\nimport random\n\n\ndef print_request(r):\n \"\"\"Print a request in a human readable format to stdout\"\"\"\n def fmt_token(t):\n return t['s...
false
10,478
b90d6c878b312820f3b4da10d47ec93a7fd27057
# -*- coding: utf-8 -*- """ Created on Mon Aug 18 20:03:29 2014 3. Faça um programa que crie dois vetores com 10 elementos aleatórios entre 1 e 100. Gere um terceiro vetor de 20 elementos, cujos valores deverão ser compostos pelos elementos intercalados dos dois outros vetores. Imprima os três vetores. @author: portela...
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 18 20:03:29 2014\n3. Faça um programa que crie dois vetores com 10 elementos aleatórios entre 1 e 100. Gere um\nterceiro vetor de 20 elementos, cujos valores deverão ser compostos pelos elementos\nintercalados dos dois outros vetores. Imprima os três vetores.\n@a...
false
10,479
a94dc128ab45088bd205ce6cd334eb1a05898a18
import cv2 import numpy as np from tensorflow.keras.utils import Sequence import pydicom from rle2mask import rle2mask class DataGenerator(Sequence): 'Generates data for Keras' def __init__(self, all_filenames, batch_size, input_dim, n_channe...
[ "import cv2\nimport numpy as np \nfrom tensorflow.keras.utils import Sequence\nimport pydicom\nfrom rle2mask import rle2mask\n\nclass DataGenerator(Sequence):\n 'Generates data for Keras'\n def __init__(self,\n all_filenames,\n batch_size,\n input_dim,\n ...
false
10,480
98d2a9b7f4b143fc875e7d14267b02aee7930c12
from .declaration_parser import DeclarationParser class ModelParser: def __init__(self, model): self.model = model def parse_model(self): dp = DeclarationParser(self.model) for decl in self.model.declarations: dp.parse_declaration(decl, type(decl).__name__) return ...
[ "from .declaration_parser import DeclarationParser\n\nclass ModelParser:\n def __init__(self, model):\n self.model = model\n\n def parse_model(self):\n dp = DeclarationParser(self.model)\n for decl in self.model.declarations:\n dp.parse_declaration(decl, type(decl).__name__)\n\...
false
10,481
80026f6fa46b3c73aa80ae34745b90719af95e41
import utilities as ut import numpy as np from skimage import data, io, color, transform, exposure from pprint import pprint import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import sys def listToRows(x) : X = np.array([x]) r = X.shape return np.reshape(x, (r[1], -r[1]+1)) def addCol...
[ "import utilities as ut\nimport numpy as np\nfrom skimage import data, io, color, transform, exposure\nfrom pprint import pprint\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport sys\n\ndef listToRows(x) :\n X = np.array([x])\n r = X.shape\n return np.reshape(x, (r[1], -r[1]...
false
10,482
1ab8a7c2bd7a5eab94986675ac8d6bb429618150
def recite(start_verse, end_verse): days = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth'] presents = ['a Partridge', 'two Turtle Doves', 'three French Hens', 'four Calling Birds', ...
[ "def recite(start_verse, end_verse):\n days = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth']\n presents = ['a Partridge',\n 'two Turtle Doves',\n 'three French Hens',\n 'four Calling Birds',\n ...
false
10,483
73fb3fc8f7bee256475e7e28db9e98d71565f9b2
import json import logging import logging.config import logging.handlers from .agent import Agent from .log import Log from .profile import Profile, Snmp with open("/monitor/config/python_logging_configuration.json", 'r') as configuration_file: config_dict = json.load(configuration_file) logging.config.dictConfig...
[ "import json\nimport logging\nimport logging.config\nimport logging.handlers\n\nfrom .agent import Agent\nfrom .log import Log\nfrom .profile import Profile, Snmp\n\nwith open(\"/monitor/config/python_logging_configuration.json\", 'r') as configuration_file:\n config_dict = json.load(configuration_file)\nlogging...
false
10,484
83a1153e25ecedf23d081afb3508764cf4101432
# configuring PYTHONPATH (By default, this will add the src and lib directory for each of your dependencies to your PYTHONPATH) import roslib; roslib.load_manifest('sap_pkg') # import client library import rospy # import messages import auction_msgs.msg # import services import auction_srvs.srv import auction_commo...
[ "# configuring PYTHONPATH (By default, this will add the src and lib directory for each of your dependencies to your PYTHONPATH)\nimport roslib; roslib.load_manifest('sap_pkg')\n\n# import client library\nimport rospy\n\n# import messages\nimport auction_msgs.msg\n\n# import services\nimport auction_srvs.srv\n\nimp...
true
10,485
7dcf4c203debfd0eee120597d760a799daf074c6
#%% load dataset import numpy as np import DL # change the directory Label_Train, Features_Train, Label_Test, Features_Test = DL.ReadFile("H:\\4th comp\\NN\\cifar-10-batches-py") # features dimensions (m, c, h, w) #%% training batch_size = 128 num_epochs = 20 num_classes = 10 hidden_units = 100 input_dimensions =...
[ "#%% load dataset\n\nimport numpy as np\nimport DL\n\n# change the directory\nLabel_Train, Features_Train, Label_Test, Features_Test = DL.ReadFile(\"H:\\\\4th comp\\\\NN\\\\cifar-10-batches-py\")\n\n# features dimensions (m, c, h, w)\n\n#%% training\n\nbatch_size = 128\nnum_epochs = 20\nnum_classes = 10\nhidden_uni...
false
10,486
2d080d53d3f88bcb1a4cfe8040fe015e950b8b54
import socket, json, sqlite3, threading, time from datetime import datetime RegCount = 12 #bytesToSend = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) bytesToSend = (255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255) #bytesToSend = (170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170) #bytesToSend = (255, 255, ...
[ "import socket, json, sqlite3, threading, time\nfrom datetime import datetime\n\nRegCount = 12\n#bytesToSend = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)\nbytesToSend = (255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255)\n#bytesToSend = (170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170)\n#bytesToSend =...
false
10,487
a7cec4b8152740086e40d37c303eccab4e485641
# Generated by Django 3.1 on 2020-10-29 13:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0046_stream'), ] operations = [ migrations.AlterField( model_name='stream', name='ss', field=model...
[ "# Generated by Django 3.1 on 2020-10-29 13:58\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('home', '0046_stream'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='stream',\n name='ss',\n ...
false
10,488
6c4db2f9f02bd3d1975509bd47efe0067da03735
from functools import reduce numTestCases = int(input()) def go(): global opt,p,s numParties = int(input()) parties = [] for i in range(numParties): si, pi = [int(x) for x in input().split(' ')] pi = float(pi)/100 parties.append((pi,si)) p,s = zip(*parties) # arranged in descending...
[ "from functools import reduce\n\nnumTestCases = int(input())\n\ndef go():\n global opt,p,s\n numParties = int(input())\n parties = []\n for i in range(numParties):\n si, pi = [int(x) for x in input().split(' ')]\n pi = float(pi)/100\n parties.append((pi,si))\n p,s = zip(*parties) # arran...
false
10,489
53c2b4434cd9b843bab99d1a48e36942f5d35a09
#!/usr/bin/python3 # ------------------------------------------------ # Honas state rotation script. Run regularly to # automatically archive Honas state information. # ------------------------------------------------ import datetime import glob import os import argparse import shutil import logging import logging.han...
[ "#!/usr/bin/python3\n# ------------------------------------------------\n# Honas state rotation script. Run regularly to\n# automatically archive Honas state information.\n# ------------------------------------------------\n\nimport datetime\nimport glob\nimport os\nimport argparse\nimport shutil\nimport logging\ni...
false
10,490
e60fb6412fecc8d0b4978799a6b6fd822d12c533
#!/usr/bin/env python __author__ = "Pedro Heleno Isolani" __copyright__ = "Copyright 2019, QoS-aware WiFi Slicing" __license__ = "GPL" __version__ = "1.0" __maintainer__ = "Pedro Heleno Isolani" __email__ = "pedro.isolani@uantwerpen.be" __status__ = "Prototype" " Python script for making graphs from CSV output" impor...
[ "#!/usr/bin/env python\n__author__ = \"Pedro Heleno Isolani\"\n__copyright__ = \"Copyright 2019, QoS-aware WiFi Slicing\"\n__license__ = \"GPL\"\n__version__ = \"1.0\"\n__maintainer__ = \"Pedro Heleno Isolani\"\n__email__ = \"pedro.isolani@uantwerpen.be\"\n__status__ = \"Prototype\"\n\n\" Python script for making g...
false
10,491
b6bc2cc268adeb29cf8d916661c13141d4b1f8e9
""" Script to Query ArangoDB. See README.md. Author: Volker Hoffman <volker.hoffmann@sintef.no> Update: 06 June 2018 """ from __future__ import print_function import pyArango.connection import json import time import argparse def connect_to_database(): conn = pyArango.connection.Connection(arangoURL='http://192...
[ "\"\"\"\nScript to Query ArangoDB. See README.md.\n\nAuthor: Volker Hoffman <volker.hoffmann@sintef.no>\nUpdate: 06 June 2018\n\"\"\"\n\nfrom __future__ import print_function\nimport pyArango.connection\nimport json\nimport time\nimport argparse\n\n\ndef connect_to_database():\n conn = pyArango.connection.Connec...
false
10,492
95942c9e825639385c7d4b1f73ee615215053478
"""Services Module.""" import shell def run_service_command(serviceName, command='status'): """Run Service Command.""" command = "sudo service %s %s" % (serviceName, command) shell.run_shell_cmd(command) def stop_service(serviceName): """Stop Service.""" run_service_command(serviceName, 'stop'...
[ "\n\"\"\"Services Module.\"\"\"\n\nimport shell\n\n\ndef run_service_command(serviceName, command='status'):\n \"\"\"Run Service Command.\"\"\"\n command = \"sudo service %s %s\" % (serviceName, command)\n shell.run_shell_cmd(command)\n\n\ndef stop_service(serviceName):\n \"\"\"Stop Service.\"\"\"\n ...
false
10,493
62273a72af52cea2659a7139fc702a49cd05d4d9
#!/usr/bin/env python import os from setuptools import setup with open('README.rst', encoding='utf-8') as readme_file: readme = readme_file.read() try: # Might be missing if no pandoc installed with open('CHANGELOG.rst', encoding='utf-8') as history_file: history = history_file.read() except IOEr...
[ "#!/usr/bin/env python\n\nimport os\nfrom setuptools import setup\n\nwith open('README.rst', encoding='utf-8') as readme_file:\n readme = readme_file.read()\n\ntry:\n # Might be missing if no pandoc installed\n with open('CHANGELOG.rst', encoding='utf-8') as history_file:\n history = history_file.re...
false
10,494
b6774fa2338acc8cf754dc1cd1511743236c9b17
#coding=utf8 import sys,os,os.path reload(sys) sys.setdefaultencoding('utf8') from doclib import doclib from numpy import * import nmf def getarticlewords(): dl=doclib('data/doclib/') dl.load() return dl.allwords,dl.articlewords,dl.articletitles def makematrix(allw,articlew): wordvec=[] for w,c in...
[ "#coding=utf8\nimport sys,os,os.path\nreload(sys)\nsys.setdefaultencoding('utf8')\nfrom doclib import doclib\nfrom numpy import *\nimport nmf\n\ndef getarticlewords():\n dl=doclib('data/doclib/')\n dl.load()\n return dl.allwords,dl.articlewords,dl.articletitles\n\ndef makematrix(allw,articlew):\n wordve...
true
10,495
48d91936f900dadae69629e1b48d581c32f47534
#!/usr/bin/env python3 """" Model that uses standard machine learning method - linear regression It can be used for whole molecules or their fragments, but it has to be consistent. If we use fragments then the similarity is computed as average similarity of the descriptors. input model_configuration should look li...
[ "#!/usr/bin/env python3\r\n\"\"\"\"\r\nModel that uses standard machine learning method - linear regression\r\nIt can be used for whole molecules or their fragments, but it has to be consistent.\r\nIf we use fragments then the similarity is computed as average similarity of the descriptors.\r\ninput model_configura...
false
10,496
10f0d1eee2cf39fc6e07662c6efc230020daa10b
from pymongo import MongoClient from bson.raw_bson import RawBSONDocument from bson.codec_options import CodecOptions import requests import json client = MongoClient() codec_options = CodecOptions(document_class=RawBSONDocument) client = MongoClient('mongodb://localhost:27017') db = client['jacaranda-db'] def pr...
[ "from pymongo import MongoClient\nfrom bson.raw_bson import RawBSONDocument\nfrom bson.codec_options import CodecOptions\nimport requests\nimport json\n\nclient = MongoClient()\n\ncodec_options = CodecOptions(document_class=RawBSONDocument)\n\nclient = MongoClient('mongodb://localhost:27017')\n\ndb = client['jacara...
false
10,497
597bda36405f8e362256e108a5ad017fd8cd0ce8
from cgml.constants import SCHEMA_IDS as SID from cgml.validators import validateSchema def makeSchema(n_in=None, n_out=None, nLayers=1, inputDropRate=2, modelType=None, costFunction=None, activationFunction="tanh", ...
[ "\nfrom cgml.constants import SCHEMA_IDS as SID\nfrom cgml.validators import validateSchema\n\ndef makeSchema(n_in=None,\n n_out=None,\n nLayers=1,\n inputDropRate=2,\n modelType=None,\n costFunction=None,\n activationFunction=\"tan...
false
10,498
b3b25c18a4af5c6d83c0f935aba1b074519b15a3
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import login, authenticate from django.contrib.auth.views import logout from django.contrib.auth.mixins import PermissionRequiredMixin from .forms import StudentRegisterForm, TeacherRegisterForm, NewGroupForm, NewAssignmentForm f...
[ "from django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth import login, authenticate\nfrom django.contrib.auth.views import logout\nfrom django.contrib.auth.mixins import PermissionRequiredMixin\n\nfrom .forms import StudentRegisterForm, TeacherRegisterForm, NewGroupForm, NewAssign...
false
10,499
f8512db4b717612e06515a617592384039aec9ad
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, chardet, codecs, math, pymongo, Queue, os, re from foofind.utils import u, logging from threading import Thread from multiprocessing import Pool class EntitiesFetcher(Thread): def __init__(self, server, results): super(EntitiesFetcher, self).__init...
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys, chardet, codecs, math, pymongo, Queue, os, re\nfrom foofind.utils import u, logging\nfrom threading import Thread\nfrom multiprocessing import Pool\n\nclass EntitiesFetcher(Thread):\n def __init__(self, server, results):\n super(EntitiesFetche...
false