index int64 0 100k | blob_id stringlengths 40 40 | code stringlengths 7 7.27M | steps listlengths 1 1.25k | error bool 2
classes |
|---|---|---|---|---|
1,100 | c4096cfae7182875a79ba7837187cd94b4379922 | from flask import render_template, request, current_app
from . import main
from .. import db, cache
from ..models import Content
from ..utils import make_cache_key
import requests
@main.route('/')
def index():
return render_template("templates/index.html")
@main.route('/link')
@cache.cached(key_prefix=make_cach... | [
"from flask import render_template, request, current_app\nfrom . import main\nfrom .. import db, cache\nfrom ..models import Content\nfrom ..utils import make_cache_key\nimport requests\n\n\n@main.route('/')\ndef index():\n return render_template(\"templates/index.html\")\n\n\n@main.route('/link')\n@cache.cached... | false |
1,101 | 5a59108084d943f6faa07ffea1467dc19c3dd790 | from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit
from django import forms
from django.forms import RadioSelect
from django.urls import reverse
from core.models import Person, Datapackage
from core.utils import cancel_button
... | [
"from crispy_forms.bootstrap import FormActions\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Div, Submit\nfrom django import forms\nfrom django.forms import RadioSelect\nfrom django.urls import reverse\n\nfrom core.models import Person, Datapackage\nfrom core.utils import can... | false |
1,102 | 8bf330dc7bee65ac9478722233477ebe5d0286c2 | import tkinter
import webbrowser
ventana = tkinter.Tk()
ventana.geometry("1920x1080")
def test():
webbrowser.open_new_tab('Test.html')
boton1 = tkinter.Button(ventana,text ="WEB", width = 10, height=5, command = test );
boton2 = tkinter.Button(ventana,text ="boton2", width = 10, height=5);
boton3 = tkint... | [
"import tkinter\r\nimport webbrowser\r\nventana = tkinter.Tk()\r\nventana.geometry(\"1920x1080\")\r\n\r\ndef test():\r\n webbrowser.open_new_tab('Test.html')\r\n\r\nboton1 = tkinter.Button(ventana,text =\"WEB\", width = 10, height=5, command = test );\r\nboton2 = tkinter.Button(ventana,text =\"boton2\", width = 1... | false |
1,103 | c6055c6b67ac28d304ed34ddc2f81e59da8e7f1b | # -*- coding: utf-8 -*-
# Copyright (c) 2018, HSCH and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils.nestedset import NestedSet
class GoalCategory(NestedSet):
nsm_parent_field = 'parent_goal_category';
de... | [
"# -*- coding: utf-8 -*-\n# Copyright (c) 2018, HSCH and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe import _\n\n\nfrom frappe.utils.nestedset import NestedSet\nclass GoalCategory(NestedSet):\n\tnsm_parent_field = 'parent_goa... | false |
1,104 | 84476e1793242bf3bae51263c2db28ff555c25d7 | import numpy
from PIL import Image, ImageDraw
def start():
# ----------------------------
# Set values
# ----------------------------
image_file = 'sample.png'
# Coordinates, where [0,0] is top left corner
top_left_corner = [100, 100] # [x, y]
bottom_right_corner = [200, 200] # [x, y]
... | [
"import numpy\nfrom PIL import Image, ImageDraw\n\n\ndef start():\n # ----------------------------\n # Set values\n # ----------------------------\n image_file = 'sample.png'\n # Coordinates, where [0,0] is top left corner\n top_left_corner = [100, 100] # [x, y]\n bottom_right_corner = [200, 2... | false |
1,105 | a35e86e474883d892a6ce8eb191a3a5f8a9558c8 | from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from .views import home, profile
from member.views import member
from publication.views import publication, pub_detail
from notice.views import list, notice_detail
from... | [
"from django.conf import settings\nfrom django.conf.urls import url, include\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\n\nfrom .views import home, profile\nfrom member.views import member\nfrom publication.views import publication, pub_detail\nfrom notice.views import list, notic... | false |
1,106 | ac178d4e009a40bde5d76e854edc6f6ae8422610 | # file with function to randomly select user from all of the data, all of the games
import ast
import csv
import numpy as np
import pandas as pd
import sys
from nba_api.stats.static import players
# some fun little work to get a random player
def get_random_player(file_name):
def need_s(num):
return 's' i... | [
"# file with function to randomly select user from all of the data, all of the games\nimport ast\nimport csv\nimport numpy as np\nimport pandas as pd\nimport sys\n\nfrom nba_api.stats.static import players\n\n# some fun little work to get a random player\ndef get_random_player(file_name):\n def need_s(num):\n ... | false |
1,107 | 91f83adbe01e2d8070f9286031b77eae71beb83e | def maths(num):
int(num)
if num % 5 == 0 and num % 3 == 0:
print("bizzfizz")
elif num % 3 == 0:
print("fizz")
elif num % 5 == 0:
print("bizz")
else:
print(num)
value=input("enter the value ")
maths(int(value)) | [
"def maths(num):\n int(num)\n if num % 5 == 0 and num % 3 == 0:\n print(\"bizzfizz\")\n elif num % 3 == 0:\n print(\"fizz\")\n elif num % 5 == 0:\n print(\"bizz\")\n else:\n print(num)\n\n\nvalue=input(\"enter the value \")\nmaths(int(value))",
"def maths(num):\n int(... | false |
1,108 | b874bfe9590a3eaff4298d6f9cc72be92000dc30 | """Unit test for int install
"""
import math
import pytest
ROUND_OFF_ERROR = 0.001
def int_installs(x):
try:
return int(x.replace(',', '').replace('+', ''))
except:
raise ValueError("Cannot transform to int.")
def test_int_install_1():
"""Unit test to showcase functionality of int... | [
"\"\"\"Unit test for int install\n\"\"\"\nimport math\nimport pytest\n\nROUND_OFF_ERROR = 0.001\n\ndef int_installs(x):\n try:\n return int(x.replace(',', '').replace('+', ''))\n except:\n raise ValueError(\"Cannot transform to int.\")\n \ndef test_int_install_1():\n \"\"\"Unit test to... | false |
1,109 | 54a705de2597140a72e47f5afe86614b619461b7 | from django.conf.urls import url
from . import views
from .views import ShopView, ShopListView
urlpatterns = [
url(r'^coffeeshops/(\d+)$', ShopView.as_view()),
url(r'^coffeeshops$', ShopListView.as_view()),
]
| [
"from django.conf.urls import url\n\nfrom . import views\nfrom .views import ShopView, ShopListView\n\nurlpatterns = [\n url(r'^coffeeshops/(\\d+)$', ShopView.as_view()),\n url(r'^coffeeshops$', ShopListView.as_view()),\n]\n",
"from django.conf.urls import url\nfrom . import views\nfrom .views import ShopVi... | false |
1,110 | 21d07c2b80aa00d0c75da342d37195b6829593b6 | #!/usr/bin/env python
import crawl
import logging
from elasticsearch import Elasticsearch
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
logging.getLogger("crawl").setLevel(logging.INFO)
logging.getLogger("elasticsearch").setLevel(logging.ERROR)
es = Elasticsearch()
crawl... | [
"#!/usr/bin/env python \nimport crawl\nimport logging\nfrom elasticsearch import Elasticsearch\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n logging.getLogger(\"crawl\").setLevel(logging.INFO)\n logging.getLogger(\"elasticsearch\").setLevel(logging.ERROR)\n \n es = Elast... | false |
1,111 | 01b9706966007c44aa19d8249fbcaee5b511786a | import urllib.request, urllib.parse, urllib.error
import json
import ssl
# Retrieve json data into Python dictionary
url = "http://py4e-data.dr-chuck.net/comments_147422.json"
handle = urllib.request.urlopen(url)
data = handle.read().decode()
data = json.loads(data)
# Calculate total sum of counts
sum = 0
for item in... | [
"import urllib.request, urllib.parse, urllib.error\nimport json\nimport ssl\n\n# Retrieve json data into Python dictionary\nurl = \"http://py4e-data.dr-chuck.net/comments_147422.json\"\nhandle = urllib.request.urlopen(url)\ndata = handle.read().decode()\ndata = json.loads(data)\n\n# Calculate total sum of counts\ns... | false |
1,112 | 3e84265b7c88fc45bc89868c4339fe37dcc7d738 | #!/usr/bin/env python
x *= 2
"""run = 0
while(run < 10):
[TAB]x = (first number in sequence)
[TAB](your code here)
[TAB]run += 1"""
| [
"#!/usr/bin/env python\r\n\r\nx *= 2\r\n\r\n\"\"\"run = 0\r\nwhile(run < 10):\r\n[TAB]x = (first number in sequence)\r\n[TAB](your code here)\r\n[TAB]run += 1\"\"\"\r\n\r\n",
"x *= 2\n<docstring token>\n",
"<code token>\n<docstring token>\n"
] | false |
1,113 | f15a0956c4aa27da861f9bccbeff7a6b6a909b73 | import datetime as dt
import json
import pandas as pd
import numpy as np
from sqlalchemy import Column, Integer, String, Float, DateTime, Boolean, func
from iotfunctions.base import BaseTransformer
from iotfunctions.metadata import EntityType
from iotfunctions.db import Database
from iotfunctions import ui
with open('... | [
"import datetime as dt\nimport json\nimport pandas as pd\nimport numpy as np\nfrom sqlalchemy import Column, Integer, String, Float, DateTime, Boolean, func\nfrom iotfunctions.base import BaseTransformer\nfrom iotfunctions.metadata import EntityType\nfrom iotfunctions.db import Database\nfrom iotfunctions import ui... | false |
1,114 | 3ac02308959749b8cd264e660c3d6334fd385fd4 | #!/usr/bin/env python
#-------------------------------------------------------------------------------
#
# Circle finder.
#
# Rowan Leeder
#
#-------------------------------------------------------------------------------
#
# Listens on the 'scan' and 'base_scan' topics. These are the pioneers SICK
# topic and Stage's ... | [
"#!/usr/bin/env python\n#-------------------------------------------------------------------------------\n#\n# Circle finder.\n#\n# Rowan Leeder\n#\n#-------------------------------------------------------------------------------\n#\n# Listens on the 'scan' and 'base_scan' topics. These are the pioneers SICK\n# top... | true |
1,115 | 2d7e3a70f1c25bbc7ad5eafa006ab12c978eaec4 | import random
import sys
import numpy
from gensim import corpora
from coherence.wn import WordNetEvaluator
from topic.topic import Topic
from nltk.corpus import wordnet as wn
from nltk.corpus import reuters
from nltk.corpus import brown
# python random_tc.py <dname> <word_count> <sample_times> <output>
# <word_count>... | [
"import random\nimport sys\n\nimport numpy\nfrom gensim import corpora\n\nfrom coherence.wn import WordNetEvaluator\nfrom topic.topic import Topic\nfrom nltk.corpus import wordnet as wn\nfrom nltk.corpus import reuters\nfrom nltk.corpus import brown\n# python random_tc.py <dname> <word_count> <sample_times> <output... | true |
1,116 | ec224924206c41cf8203c6aa8002ddf6b0e70e9b | from abc import ABC, abstractmethod, abstractproperty
from pytz import timezone
class EngageScraper(ABC):
def __init__(self, tz_string):
super().__init__()
self._agenda_locations = []
self._tz = timezone(tz_string)
@property
def agenda_locations(self):
return self._agenda_l... | [
"from abc import ABC, abstractmethod, abstractproperty\nfrom pytz import timezone\n\nclass EngageScraper(ABC):\n def __init__(self, tz_string):\n super().__init__()\n self._agenda_locations = []\n self._tz = timezone(tz_string)\n\n @property\n def agenda_locations(self):\n retur... | false |
1,117 | 92a50bcdbb4c03d1a4813a93c2e0986250516f14 |
#Aplicacion de la funcion super()
class Persona():
def __init__(self,nombre,edad,lugar_residencia):
self.nombre = nombre
self.edad = edad
self.residencia = lugar_residencia
def descripcion(self):
print("Nombre: ",self.nombre," Edad: ", self.edad," Lugar de residencia: ",s... | [
"\n\n#Aplicacion de la funcion super()\n\nclass Persona():\n def __init__(self,nombre,edad,lugar_residencia):\n self.nombre = nombre\n self.edad = edad\n self.residencia = lugar_residencia\n \n def descripcion(self):\n print(\"Nombre: \",self.nombre,\" Edad: \", self.edad,\" Lug... | false |
1,118 | 6553312c9655c821444ff5f60e4d68c7fc08bd08 | """Utils module."""
import click
import os.path
import pandas as pd
from tensorflow.keras.models import load_model
from tensorflow.keras.regularizers import l1_l2
from tensorflow.keras.callbacks import CSVLogger, ModelCheckpoint, TensorBoard
from zalando_classification.models import build_model
def get_basename(na... | [
"\"\"\"Utils module.\"\"\"\nimport click\nimport os.path\n\nimport pandas as pd\n\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.regularizers import l1_l2\nfrom tensorflow.keras.callbacks import CSVLogger, ModelCheckpoint, TensorBoard\n\nfrom zalando_classification.models import build_model\... | false |
1,119 | 5c291dbc241a80e7f2625ba338a4b9b3a3f3b2d0 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); y... | false |
1,120 | 6c5f60e7a122e3da5e6705bfacf73a361f6c1362 | #
# * Python 57, Correct Lineup
# * Easy
# * For the opening ceremony of the upcoming sports event an even number of
# * athletes were picked. They formed a correct lineup, i.e. such a lineup in
# * which no two boys or two girls stand together. The first person in the lineup
# * was a girl. As a part of the perfor... | [
"#\n# * Python 57, Correct Lineup\n# * Easy\n\n# * For the opening ceremony of the upcoming sports event an even number of \n# * athletes were picked. They formed a correct lineup, i.e. such a lineup in \n# * which no two boys or two girls stand together. The first person in the lineup \n# * was a girl. As a part o... | false |
1,121 | f91e1fdc31b2fe1aef15757576d847c617a86201 | from __future__ import absolute_import
from builtins import str
from builtins import object
import unittest
import sys, os, re
import forcebalance
import abc
import numpy
from __init__ import ForceBalanceTestCase
class TestImplemented(ForceBalanceTestCase):
def test_implemented_targets_derived_from_target(self):
... | [
"from __future__ import absolute_import\nfrom builtins import str\nfrom builtins import object\nimport unittest\nimport sys, os, re\nimport forcebalance\nimport abc\nimport numpy\nfrom __init__ import ForceBalanceTestCase\n\nclass TestImplemented(ForceBalanceTestCase):\n def test_implemented_targets_derived_from... | false |
1,122 | 374fbb986524f28cc86f6e579f504eeb8ddc9701 | from kafka import KafkaConsumer
import csv
users = set()
# returns string of title given a ConsumerRecord
def parse_cr(cr):
binary = cr.value
string = binary.decode('utf-8')
# [time, user id, GET request]
return string.split(',')
# returns string of title given a ConsumerRecord in name+name+year for... | [
"from kafka import KafkaConsumer\nimport csv\n\nusers = set()\n\n# returns string of title given a ConsumerRecord\ndef parse_cr(cr):\n binary = cr.value\n string = binary.decode('utf-8')\n # [time, user id, GET request]\n return string.split(',')\n\n\n# returns string of title given a ConsumerRecord in ... | false |
1,123 | bea90bbcd4d34b64c21f022b6f3af2bee2d978e4 | from app import create_app
from app.config import Config
app = create_app(Config)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)
| [
"from app import create_app\nfrom app.config import Config\n\n\napp = create_app(Config)\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5000, debug=True)\n",
"from app import create_app\nfrom app.config import Config\napp = create_app(Config)\nif __name__ == '__main__':\n app.run(host='0... | false |
1,124 | 6b7bc40ba842ff565e7141fb1d51def99d9ab96a | from torch.utils.data.sampler import Sampler
import torch
import random
class SwitchingBatchSampler(Sampler):
def __init__(self, data_source, batch_size, drop_last=False):
self.data_source = data_source
self.batch_size = batch_size
self.drop_last = drop_last
# Divide the indices into two indices groups
se... | [
"from torch.utils.data.sampler import Sampler\nimport torch\nimport random\n\nclass SwitchingBatchSampler(Sampler):\n\n\tdef __init__(self, data_source, batch_size, drop_last=False):\n\t\tself.data_source = data_source\n\t\tself.batch_size = batch_size\n\t\tself.drop_last = drop_last\n\n\t\t# Divide the indices int... | false |
1,125 | 68d37421b71d595510a1439c06cc31d00c23c277 | import numpy
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.cross_validation import cross_val_score
lag = 10
print "Loading train_data..."
train_data = numpy.loadtxt("../KddJavaToolChain/train_timelines_final.csv",
delimiter=",")
print... | [
"import numpy\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.cross_validation import cross_val_score\n\nlag = 10\n\nprint \"Loading train_data...\"\ntrain_data = numpy.loadtxt(\"../KddJavaToolChain/train_timelines_final.csv\",\n\t\t\t\t\t\... | true |
1,126 | c6502d6b589fa75dfbd5946a1097e77fc0b472c4 | import MySQLdb
from MySQLdb import escape_string as thwart
"""
"""
class DatabaseConnection:
def __init__(self, address, user, password, database):
self.address = address
self.user = user
self.password = password
self.database = database
"""
"""
def connect(self):
... | [
"import MySQLdb\nfrom MySQLdb import escape_string as thwart\n\"\"\"\n\"\"\"\nclass DatabaseConnection:\n\n def __init__(self, address, user, password, database):\n self.address = address\n self.user = user\n self.password = password\n self.database = database\n\n \"\"\"\n \n ... | false |
1,127 | d2972fb7cff08e15957f9baeaa6fd9a6f5bbb006 | # This file is part of the functional_calculator_oop.py Task
# Create a class called Calculator
class Calculator:
def Add(self, num1, num2):
return num1 + num2
def Subtract(self, num1, num2):
return num1 - num2
def Multiply(self, num1, num2):
return num1 * num2
def Divide(sel... | [
"# This file is part of the functional_calculator_oop.py Task\n# Create a class called Calculator\nclass Calculator:\n\n def Add(self, num1, num2):\n return num1 + num2\n\n def Subtract(self, num1, num2):\n return num1 - num2\n\n def Multiply(self, num1, num2):\n return num1 * num2\n\n... | false |
1,128 | 2a5d498a386190bdd2c05bc2b14db0fecd707162 | from .slinklist import SingleLinkedList
| [
"from .slinklist import SingleLinkedList\n",
"<import token>\n"
] | false |
1,129 | 6b45541c54f1a4ce94d6bd457701ecd1b90a4c4c | #!/usr/bin/env python
#_*_coding:utf-8_*_
#作者:Paul哥
from fabric.api import settings,run,cd,env,hosts
from fabric.colors import *
env.hosts=['192.168.75.130:22']
env.password='hello123'
env.user='root'
def test():
with cd('/home'):
print yellow(run('ls -l'))
test()
| [
"#!/usr/bin/env python\n#_*_coding:utf-8_*_\n#作者:Paul哥\n\n\n\nfrom fabric.api import settings,run,cd,env,hosts\nfrom fabric.colors import *\n\nenv.hosts=['192.168.75.130:22']\nenv.password='hello123'\nenv.user='root'\ndef test():\n\twith cd('/home'):\n\t\tprint yellow(run('ls -l'))\n\ntest()\n"
] | true |
1,130 | 37580939a0e58bdffb8cfad8252f339a7da4446e | from __future__ import print_function
from itertools import permutations
s, space, k = raw_input().partition(' ')
for t in sorted(list(permutations(s, int(k)))):
print(*t, sep='')
| [
"from __future__ import print_function\nfrom itertools import permutations\n\ns, space, k = raw_input().partition(' ')\n\nfor t in sorted(list(permutations(s, int(k)))):\n print(*t, sep='')\n\n",
"from __future__ import print_function\nfrom itertools import permutations\ns, space, k = raw_input().partition(' ... | false |
1,131 | 8197d918b86f0e38fb4320434b61aa4186853af9 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#
# Code generated by aaz-dev-tools
# --------------------------------... | [
"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n#\n# Code generated by aaz-dev-tools\n# ----------------------... | false |
1,132 | c10e1cf2f1ce5b11d19ddddbfc3dc9652d830a3c | # Generated by Django 3.0.4 on 2020-03-27 11:42
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('web', '0005_remove_product_image'),
]
operations = [
migrations.CreateMode... | [
"# Generated by Django 3.0.4 on 2020-03-27 11:42\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('web', '0005_remove_product_image'),\n ]\n\n operations = [\n mi... | false |
1,133 | 763c0baf919b48ff135f7aa18974da5b85ee40f5 | class Odwroc():
def __init__(self,dane):
self.dane = dane
self.indeks = len(dane)
def __iter__(self):
return self
def __next__(self):
if self.indeks == 0:
raise StopIteration
self.indeks -= 1
return self.dane[self.indeks]
for i in Odwroc('Martu... | [
"class Odwroc():\n def __init__(self,dane):\n self.dane = dane\n self.indeks = len(dane)\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.indeks == 0:\n raise StopIteration\n\n self.indeks -= 1\n return self.dane[self.indeks]\n\nfo... | false |
1,134 | ea646068d48a9a4b5a578a5fb1399d83a4812b02 | # -*- coding: utf-8 -*-
import os
import time
import pandas as pd
file_dir = os.getcwd() # 获取当前工作目录
file_list_all = os.listdir(file_dir) # 获取目录下的所有文件名
file_list_excel = [item for item in file_list_all if ('.xlsx' in item) or ('.xls' in item)] # 清洗非excel文件
new_list = [] # 空列表用于存放下面各个清洗后的表格
for file in file_list_ex... | [
"# -*- coding: utf-8 -*-\nimport os\nimport time\nimport pandas as pd\n\nfile_dir = os.getcwd() # 获取当前工作目录\nfile_list_all = os.listdir(file_dir) # 获取目录下的所有文件名\nfile_list_excel = [item for item in file_list_all if ('.xlsx' in item) or ('.xls' in item)] # 清洗非excel文件\n\nnew_list = [] # 空列表用于存放下面各个清洗后的表格\nfor file ... | false |
1,135 | 7be54b2bd99680beed3e8e9cb14225756a71a4ea | from ..core.helpers import itemize
from ..core.files import backendRep, expandDir, prefixSlash, normpath
from .helpers import splitModRef
from .repo import checkoutRepo
from .links import provenanceLink
# GET DATA FOR MAIN SOURCE AND ALL MODULES
class AppData:
def __init__(
self, app, backend, moduleRef... | [
"from ..core.helpers import itemize\nfrom ..core.files import backendRep, expandDir, prefixSlash, normpath\nfrom .helpers import splitModRef\nfrom .repo import checkoutRepo\nfrom .links import provenanceLink\n\n\n# GET DATA FOR MAIN SOURCE AND ALL MODULES\n\n\nclass AppData:\n def __init__(\n self, app, b... | false |
1,136 | 8109fcc136b967e0ed4ca06077b32612605d5e5f | from numpy import exp, array, dot
from read import normalized
class NeuralNetwork():
def __init__(self, layer1, layer2):
self.layer1 = layer1
self.layer2 = layer2
def __sigmoid(self, x):
return 1 / (1 + exp(-x))
def __sigmoid_derivative(self, x):
return x * (1 - x)
d... | [
"from numpy import exp, array, dot\n\nfrom read import normalized\n\nclass NeuralNetwork():\n def __init__(self, layer1, layer2):\n self.layer1 = layer1\n self.layer2 = layer2\n\n def __sigmoid(self, x):\n return 1 / (1 + exp(-x))\n\n def __sigmoid_derivative(self, x):\n return ... | false |
1,137 | 10a9437453371bd7472e93af1026c778b7983cf8 | """
Common, pure functions used by the D-BAS.
.. codeauthor:: Tobias Krauthoff <krauthoff@cs.uni-duesseldorf.de
"""
import hashlib
import locale
import os
import re
import warnings
from collections import defaultdict
from datetime import datetime
from enum import Enum, auto
from html import escape, unescape
from typi... | [
"\"\"\"\nCommon, pure functions used by the D-BAS.\n\n\n.. codeauthor:: Tobias Krauthoff <krauthoff@cs.uni-duesseldorf.de\n\"\"\"\nimport hashlib\nimport locale\nimport os\nimport re\nimport warnings\nfrom collections import defaultdict\nfrom datetime import datetime\nfrom enum import Enum, auto\nfrom html import e... | false |
1,138 | 850251338e8af841a5214b37610d1b6fba572aa5 | from platform_class import *
from player_class import *
from functions import *
delay = 3000
startOfGame = False
# def keyPressed():
# startOfGame = True
# print(startOfGame)
# if (keyCode == 'B'):
# print("I am pressed")
# startOfGame = True
def mousePressed():
global platforms
... | [
"from platform_class import *\nfrom player_class import *\nfrom functions import *\n\ndelay = 3000\nstartOfGame = False\n\n\n# def keyPressed():\n# startOfGame = True\n# print(startOfGame)\n# if (keyCode == 'B'):\n# print(\"I am pressed\")\n# startOfGame = True\n\ndef mousePressed():\n ... | false |
1,139 | 93ac8a1f795f7809a3e88b56ce90bf1d31706554 | # Copyright (c) 2021, Omid Erfanmanesh, All rights reserved.
import math
import numpy as np
import pandas as pd
from data.based.based_dataset import BasedDataset
from data.based.file_types import FileTypes
class DengueInfection(BasedDataset):
def __init__(self, cfg, development):
super(DengueInfectio... | [
"# Copyright (c) 2021, Omid Erfanmanesh, All rights reserved.\n\n\nimport math\n\nimport numpy as np\nimport pandas as pd\n\nfrom data.based.based_dataset import BasedDataset\nfrom data.based.file_types import FileTypes\n\n\nclass DengueInfection(BasedDataset):\n def __init__(self, cfg, development):\n s... | false |
1,140 | 22fe07a237f2c5f531d189c07596a22df191d038 | from vmgCommanderBase import CommanderBase
from vmgInstallerApt import InstallerApt
from vmgInstallerYum import InstallerYum
from vmgConfigLinux import ConfigLinux
from runCommands import *
import shutil
import os
import time
from vmgLogging import *
from writeFormat import *
from vmgControlVmware import *
from vmgUtil... | [
"from vmgCommanderBase import CommanderBase\nfrom vmgInstallerApt import InstallerApt\nfrom vmgInstallerYum import InstallerYum\nfrom vmgConfigLinux import ConfigLinux\nfrom runCommands import *\nimport shutil\nimport os\nimport time\nfrom vmgLogging import *\nfrom writeFormat import *\nfrom vmgControlVmware import... | true |
1,141 | af6dd7bde25453f25c0701e4ac246ff6bce29fa7 | k=0
for x in range(100,1000,2):
x=str(x)
if x[0] == x[1] or x[0] == x[2] or x[1] == x[2]:
k+=1
print(k)
| [
"k=0\r\nfor x in range(100,1000,2):\r\n x=str(x)\r\n if x[0] == x[1] or x[0] == x[2] or x[1] == x[2]:\r\n k+=1\r\nprint(k)\r\n \r\n",
"k = 0\nfor x in range(100, 1000, 2):\n x = str(x)\n if x[0] == x[1] or x[0] == x[2] or x[1] == x[2]:\n k += 1\nprint(k)\n",
"<as... | false |
1,142 | 38fceb57977cb792be1a63e8571cd222facdf656 | import turtle
red = range(4);
for i in red:
turtle.forward(200)
turtle.left(90)
turtle.done() | [
"import turtle\n\nred = range(4);\nfor i in red:\n\tturtle.forward(200)\n\tturtle.left(90)\n\nturtle.done()",
"import turtle\nred = range(4)\nfor i in red:\n turtle.forward(200)\n turtle.left(90)\nturtle.done()\n",
"<import token>\nred = range(4)\nfor i in red:\n turtle.forward(200)\n turtle.left(90... | false |
1,143 | f0a3778e74d113a5de778fa17ec321c6680c56c2 | import pytest
import problem22 as p22
def test_burst():
"""Test burst() in Cluster"""
print('\nTesting burst()')
cluster = p22.Cluster('..#\n#..\n...')
assert cluster.infected[p22.Position(0, 2)] == p22.State.Infected
assert cluster.infected[p22.Position(1, 0)] == p22.State.Infected
assert clus... | [
"import pytest\nimport problem22 as p22\n\ndef test_burst():\n \"\"\"Test burst() in Cluster\"\"\"\n print('\\nTesting burst()')\n cluster = p22.Cluster('..#\\n#..\\n...')\n assert cluster.infected[p22.Position(0, 2)] == p22.State.Infected\n assert cluster.infected[p22.Position(1, 0)] == p22.State.In... | false |
1,144 | 87df5481cf2dd5bb990a9b4bd5169d9293d6af79 | #%%
import numpy
import time
import scipy
import os
os.chdir('/home/bbales2/modal')
import pyximport
import seaborn
pyximport.install(reload_support = True)
import polybasisqu
reload(polybasisqu)
#from rotations import symmetry
#from rotations import quaternion
#from rotations import inv_rotations
# basis polynomial... | [
"#%%\nimport numpy\nimport time\nimport scipy\nimport os\nos.chdir('/home/bbales2/modal')\nimport pyximport\nimport seaborn\npyximport.install(reload_support = True)\n\nimport polybasisqu\nreload(polybasisqu)\n\n#from rotations import symmetry\n#from rotations import quaternion\n#from rotations import inv_rotations... | true |
1,145 | 600691b87f7776e96bbf439d7195b870ed86090b | #!/usr/bin/python
import sys,os
import argparse
import subprocess
from pprint import pprint
chroot_start_path="/srv/chroot"
chroots_conf="/etc/schroot/chroot.d"
build_pkgs = 'build-essential fakeroot devscripts apt-utils'
include = 'eatmydata,ccache,lintian'
distro_conf={
'debootstrap_mirror':None,
'componen... | [
"#!/usr/bin/python\n\nimport sys,os\nimport argparse\nimport subprocess\nfrom pprint import pprint\n\nchroot_start_path=\"/srv/chroot\"\nchroots_conf=\"/etc/schroot/chroot.d\"\n\nbuild_pkgs = 'build-essential fakeroot devscripts apt-utils'\ninclude = 'eatmydata,ccache,lintian'\ndistro_conf={\n 'debootstrap_mirro... | false |
1,146 | b44f75db652b3a40cd9475bfe44027724e845252 | import platform, sys, os, ensurepip
ensurepip.bootstrap()
try:
import pip
except ImportError:
print("Error: Failed to install pip, make sure you are running this script as admin.")
sys.exit()
arch = platform.architecture()[0]
wheelUrl = "https://raw.githubusercontent.com/Starfox64/pygame-installer/master/wheels... | [
"import platform, sys, os, ensurepip\r\n\nensurepip.bootstrap()\n\ntry:\n\timport pip\nexcept ImportError:\n\tprint(\"Error: Failed to install pip, make sure you are running this script as admin.\")\n\tsys.exit()\n\narch = platform.architecture()[0]\r\nwheelUrl = \"https://raw.githubusercontent.com/Starfox64/pygame... | false |
1,147 | 0cf5b009f384d2ca7162b5a88699afb3702ae1f6 | #!/usr/bin/env python
# coding: utf-8
import time
class Timer(object):
def __init__(self):
self.time_ = 0.
self.start_ = 0.
def reset(self):
self.time_ = 0.
self.start_ = 0.
def start(self):
self.start_ = time.clock()
def end(self):
self.time_ += time... | [
"#!/usr/bin/env python\n# coding: utf-8\nimport time\n\n\nclass Timer(object):\n def __init__(self):\n self.time_ = 0.\n self.start_ = 0.\n\n def reset(self):\n self.time_ = 0.\n self.start_ = 0.\n\n def start(self):\n self.start_ = time.clock()\n\n def end(self):\n ... | false |
1,148 | 65301be73bb56147609a103a932266013c3c0bd6 | """
Pide una cadena y un carácter por teclado y muestra cuantas veces aparece el carácter en la cadena.
Autor: David Galván Fontalba
Fecha: 27/10/2019
Algoritmo:
Pido un cadena
Pido un caracter
contador en 0
Hago una variable que empieza siendo 0, i
mientras i <= len(cadena)
si cadena[i] == caracter
... | [
"\"\"\"\r\nPide una cadena y un carácter por teclado y muestra cuantas veces aparece el carácter en la cadena.\r\n\r\nAutor: David Galván Fontalba\r\nFecha: 27/10/2019\r\n\r\nAlgoritmo:\r\nPido un cadena\r\nPido un caracter\r\ncontador en 0\r\nHago una variable que empieza siendo 0, i\r\nmientras i <= len(cadena)\r... | false |
1,149 | 96065e7e61b63f915561f117d71092e4bfb9a5da | from __future__ import absolute_import, unicode_literals
from django.db import DataError, IntegrityError, connection
import pytest
from .models import Page
pytestmark = pytest.mark.django_db
MYSQL_REASON = 'MySQL parses check constraints but are ignored by all engines'
def test_match():
Page.objects.create(u... | [
"from __future__ import absolute_import, unicode_literals\n\nfrom django.db import DataError, IntegrityError, connection\n\nimport pytest\n\nfrom .models import Page\n\npytestmark = pytest.mark.django_db\n\nMYSQL_REASON = 'MySQL parses check constraints but are ignored by all engines'\n\n\ndef test_match():\n Pa... | false |
1,150 | 833c8234d829dfa1937392f0ad4952aeffa4e26d | def is_balanced(tree_root):
# Determine if the tree is superbalanced
if tree_root is None:
return True
nodeQ = [(tree_root, 0)]
depths = []
while len(nodeQ):
last_node, depth = nodeQ.pop()
if( not last_node.left ) and (not last_node.right ):
... | [
"def is_balanced(tree_root):\n # Determine if the tree is superbalanced\n \n if tree_root is None:\n return True\n \n nodeQ = [(tree_root, 0)]\n depths = []\n \n while len(nodeQ):\n \n last_node, depth = nodeQ.pop()\n \n if( not last_node.left ) and (not la... | false |
1,151 | 6d5acaa4a60b646432feb59f4d8eb9c9d0dceb0f | #!/usr/bin/python
# -*- coding: utf-8 -*-
import phpserialize
import urllib2
from cache import cache
from config import config
def block(request, limit=None):
try:
links = cache.get_cache("sape", expire=3600).get(key="links", createfunc=load_links)
except:
links = cache.get_cache("sape", expi... | [
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport phpserialize\nimport urllib2\n\nfrom cache import cache\nfrom config import config\n\ndef block(request, limit=None):\n try:\n links = cache.get_cache(\"sape\", expire=3600).get(key=\"links\", createfunc=load_links)\n except:\n links = cache.... | false |
1,152 | aeab80e2d0006ffa938366ef046d2ab3d387f88c | import tkinter as tk
from tkinter import ttk, messagebox, Menu
ventana = tk.Tk()
EntryArr = []
Label = ["¿Que es la analisis psicologico?", "¿Como se lee la mente?", "¿Cuantas persepciones psicologicas existen?", "¿Padre de la Psicologia moderna?", "Parte del cuerpo donde esta la psyco"]
Arr3 = tk.IntVar()
opciones1 ... | [
"import tkinter as tk\nfrom tkinter import ttk, messagebox, Menu\n\n\nventana = tk.Tk()\nEntryArr = []\nLabel = [\"¿Que es la analisis psicologico?\", \"¿Como se lee la mente?\", \"¿Cuantas persepciones psicologicas existen?\", \"¿Padre de la Psicologia moderna?\", \"Parte del cuerpo donde esta la psyco\"]\nArr3 = ... | false |
1,153 | a2871585ce36888cf89c4dc5a6a7de6b212412bb | def geo_avg(x,lat,dim=2):
'''
geo_avg: to calculate weighting average according to latitude
input:
x: variable
lat: corresponding latittude
dim: the order of the lat dimension, two cases: 2:[time,lev,lat,*lon],or 1:[time or lev, lat, *lon]
output:
result: 1d or 2d avera... | [
"def geo_avg(x,lat,dim=2):\n '''\n geo_avg: to calculate weighting average according to latitude\n input: \n x: variable \n lat: corresponding latittude\n dim: the order of the lat dimension, two cases: 2:[time,lev,lat,*lon],or 1:[time or lev, lat, *lon]\n output:\n result: 1... | false |
1,154 | 3a6038cb80548b98fc7e4a328092f1dc1ffd6dfd | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020-2021 by Murray Altheim. All rights reserved. This file is part
# of the Robot Operating System project, released under the MIT License. Please
# see the LICENSE file included as part of this package.
#
# author: Murray Altheim
# created: 2020-04-15
# ... | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Copyright 2020-2021 by Murray Altheim. All rights reserved. This file is part\n# of the Robot Operating System project, released under the MIT License. Please\n# see the LICENSE file included as part of this package.\n#\n# author: Murray Altheim\n# created: ... | false |
1,155 | 34d3eebf6ccb19f891ccbb16db47cd6412f1cb0f | numbers = [3,4,6,7]
# 0 1 2 3
print(numbers)
print(numbers[1])
print(numbers[-1])
numbers[1] = 3
print(numbers)
del numbers[1]
print(numbers)
numbers.append(17)
print(numbers)
numbers.insert(2,5)
print(numbers)
numbers.sort()
print(numbers) | [
"numbers = [3,4,6,7]\n# 0 1 2 3\nprint(numbers)\nprint(numbers[1])\nprint(numbers[-1])\nnumbers[1] = 3\nprint(numbers)\ndel numbers[1]\nprint(numbers)\nnumbers.append(17)\nprint(numbers)\nnumbers.insert(2,5)\nprint(numbers)\nnumbers.sort()\nprint(numbers)",
"numbers = [3, 4, 6, 7]\nprint(numbers)\nprint(... | false |
1,156 | 05ced056bf2f59f85bef82e53803e7df7ff8c8df | #!/usr/bin/env python
import ROOT
ROOT.gROOT.SetBatch()
ROOT.gROOT.ProcessLine('gErrorIgnoreLevel = kError;')
import os
import time
import varial.tools
import varial.generators as gen
import itertools
from varial.sample import Sample
import varial.analysis as analysis
# import varial.toolinterface
dirname = 'VLQToHi... | [
"#!/usr/bin/env python\n\nimport ROOT\nROOT.gROOT.SetBatch()\nROOT.gROOT.ProcessLine('gErrorIgnoreLevel = kError;')\n\nimport os\nimport time\nimport varial.tools\nimport varial.generators as gen\nimport itertools\nfrom varial.sample import Sample\nimport varial.analysis as analysis\n# import varial.toolinterface\n... | false |
1,157 | 7c63abacce07ee9d4c2b3941d05f951b75c8d0ff | # Copyright (c) 2011-2020 Eric Froemling
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish,... | [
"# Copyright (c) 2011-2020 Eric Froemling\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, mer... | false |
1,158 | 243016b14f503a09147f434e7bec31dc204fafdf | # This script is for character creation.
print ("Welcome to the character wizard creation!")
# Here you will select your race from the list.
race = ["human", "ork", "elf"]
print race
race = raw_input("Please choose your race: ")
print "You have choosen %r" %race
# Here you will select your gender.
gender = ... | [
"# This script is for character creation.\r\nprint (\"Welcome to the character wizard creation!\")\r\n\r\n# Here you will select your race from the list.\r\nrace = [\"human\", \"ork\", \"elf\"]\r\nprint race\r\nrace = raw_input(\"Please choose your race: \")\r\nprint \"You have choosen %r\" %race\r\n\r\n# Here you ... | true |
1,159 | 2187f38dc9b14ecc355e98fe15d36fdefd548f04 | import re
from .models import ValidatedStudent
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
def get_token_from_request(request):
token_tuple = request.COOKIES.get('money_api_token')
matches = re.search(r'(<Token: (\S*)>)', token_tuple)
token = matches.group... | [
"import re\nfrom .models import ValidatedStudent\nfrom rest_framework.authtoken.models import Token\nfrom django.contrib.auth.models import User\n\n\ndef get_token_from_request(request):\n token_tuple = request.COOKIES.get('money_api_token')\n matches = re.search(r'(<Token: (\\S*)>)', token_tuple)\n token ... | false |
1,160 | 04487dce97231a7be2bf3b164e93f0ea4d01ba05 | # Write function that determines if a string a palindrome off of any permutation
def palinPerm(str):
# Create empty set
charSet = set()
# Loop through string, if character does not exist in set, add it. If it does, remove it.
for c in str:
if c not in charSet:
charSet.add(c)
else:
charSet.r... | [
"# Write function that determines if a string a palindrome off of any permutation\ndef palinPerm(str):\n # Create empty set\n charSet = set()\n\n # Loop through string, if character does not exist in set, add it. If it does, remove it.\n for c in str:\n if c not in charSet:\n charSet.add(c)\n else:\n... | false |
1,161 | 5e355732f07029aa644617ac9b5e9ad50ee9397f | from django.conf.urls import url
from django.contrib.auth.views import login,logout
from appPortas.views import *
urlpatterns = [
url(r'^porta/list$', porta_list, name='porta_list'),
url(r'^porta/detail/(?P<pk>\d+)$',porta_detail, name='porta_detail'),
url(r'^porta/new/$', porta_new, name='porta_new'),
... | [
"from django.conf.urls import url\nfrom django.contrib.auth.views import login,logout\n\nfrom appPortas.views import *\n\nurlpatterns = [\n url(r'^porta/list$', porta_list, name='porta_list'),\n url(r'^porta/detail/(?P<pk>\\d+)$',porta_detail, name='porta_detail'),\n url(r'^porta/new/$', porta_new, name='p... | false |
1,162 | 6bcddd1b2ec8653400f710e5cab552d4bec75b6b | #!/usr/bin/env python
"""
This code is fot testing the region growing.
"""
import os
import sys
import time
import nibabel as nib
import region_growing as rg
import matplotlib.pyplot as plt
import numpy as np
img = nib.load("zstat1.nii.gz")
data = img.get_data()
#test coor [36,60,28] [21,39,30] [23,38,30]
coor = [23,... | [
"#!/usr/bin/env python\n\"\"\"\nThis code is fot testing the region growing.\n\"\"\"\nimport os\nimport sys\nimport time\nimport nibabel as nib\nimport region_growing as rg\nimport matplotlib.pyplot as plt \nimport numpy as np\n\nimg = nib.load(\"zstat1.nii.gz\")\ndata = img.get_data()\n#test coor [36,60,28] [21,39... | true |
1,163 | e464b465c4bc90c250c0ea02c17b7398d975964b | #!/usr/bin/python
'''
** dmcalc **
Estimates the Dispersion Measure (DM) from the data in psrfits file format.
Returns the DM value with its uncertainty and reduced chi-square from tempo2
DM fit.
Dependencies
-------------
PSRCHIVE with python interface: http://psrchive.sourceforge.ne... | [
"#!/usr/bin/python\n'''\n ** dmcalc **\nEstimates the Dispersion Measure (DM) from the data in psrfits file format.\n\nReturns the DM value with its uncertainty and reduced chi-square from tempo2 \nDM fit.\n\nDependencies \n-------------\nPSRCHIVE with python interface: http://psrchive... | false |
1,164 | 307bb7461a729ba979f6a862fe7c292c42f96ce6 | # -*- coding: utf-8 -*-
elements = str(input("Type the elements of list: ")).split()
elements = list(map(float,elements))
times = int(input("How many times you wish shift to right: "))
for _ in range(times):
removed = elements.pop()
elements.insert(0,removed)
print(elements) | [
"# -*- coding: utf-8 -*-\n\nelements = str(input(\"Type the elements of list: \")).split()\nelements = list(map(float,elements))\n\ntimes = int(input(\"How many times you wish shift to right: \"))\n\nfor _ in range(times):\n\tremoved = elements.pop()\n\telements.insert(0,removed)\n\nprint(elements)",
"elements = ... | false |
1,165 | 83e2f9c56c45a288aabd777fb244089367649258 | import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
IS_TESTING = False
FOLDER_TO_ORGANIZE = ''
FOLDER_FOR_OTHERS = ''
FOLDER_TO_ORGANIZE_TEST = ''
LOG_FILE = ''
IGNORE_HIDDEN_FILES = True
FILES_DESTINATION = {
'images': ['.jpg', '.jpeg', '.png'],
'documents': ['.pdf', '.xlsx', '.... | [
"import os\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nIS_TESTING = False\nFOLDER_TO_ORGANIZE = ''\nFOLDER_FOR_OTHERS = ''\nFOLDER_TO_ORGANIZE_TEST = ''\nLOG_FILE = ''\nIGNORE_HIDDEN_FILES = True\n\nFILES_DESTINATION = {\n 'images': ['.jpg', '.jpeg', '.png'],\n 'documents': ['... | false |
1,166 | 8035f195cd01dc50691cd93ea91a6377b1d83f24 | import threading
import time
# import numpy as np
import pickle
from utils.ret_utils import error_info
from nodule_class.isnodule import LungIsncls
from preprocessing.location import lobe_locate_gmm
from detection.lung_detection import LungDetection
from func_timeout import FunctionTimedOut
from func_timeout import fu... | [
"import threading\nimport time\n\n# import numpy as np\nimport pickle\nfrom utils.ret_utils import error_info\nfrom nodule_class.isnodule import LungIsncls\nfrom preprocessing.location import lobe_locate_gmm\nfrom detection.lung_detection import LungDetection\nfrom func_timeout import FunctionTimedOut\nfrom func_ti... | false |
1,167 | def089c2749444797ac3079809c082dacab08554 | class ModelInfo:
def __init__(self, name: str, path: str, filter: str):
self.name: str = name
self.path: str = path
self.filter: str = filter
| [
"class ModelInfo:\n\n def __init__(self, name: str, path: str, filter: str):\n self.name: str = name\n self.path: str = path\n self.filter: str = filter\n",
"class ModelInfo:\n <function token>\n",
"<class token>\n"
] | false |
1,168 | 17505f5c14190df3311c04c19f687937481b920b | from flask import Flask, jsonify
import dataExtraction as dataEx
from flask_cors import CORS,cross_origin
from analyseSentiment import twitterDataExtaraction
from flask_pymongo import PyMongo
app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/scrapingDB"
mongo = PyMongo(app)
db = mongo.db
cors ... | [
"from flask import Flask, jsonify\nimport dataExtraction as dataEx\nfrom flask_cors import CORS,cross_origin\nfrom analyseSentiment import twitterDataExtaraction\nfrom flask_pymongo import PyMongo\n\napp = Flask(__name__)\napp.config[\"MONGO_URI\"] = \"mongodb://localhost:27017/scrapingDB\"\nmongo = PyMongo(app)\nd... | false |
1,169 | 5c1ce46f45da33acf75a7f47add811b14d58414d | '''
Function Description
Complete the extraLongFactorials function in the editor below. It should print the result and return.
extraLongFactorials has the following parameter(s):
n: an integer
Note: Factorials of
can't be stored even in a
long long variable. Big integers must be used for such calcu... | [
"'''\r\nFunction Description\r\n\r\nComplete the extraLongFactorials function in the editor below. It should print the result and return.\r\n\r\nextraLongFactorials has the following parameter(s):\r\n\r\n n: an integer\r\n\r\nNote: Factorials of\r\ncan't be stored even in a\r\n\r\nlong long variable. Big integer... | false |
1,170 | c6c13ab24e4907eecf1db4fded28d4fc8126c834 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-06-07 12:30
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependenc... | [
"# -*- coding: utf-8 -*-\n# Generated by Django 1.11 on 2018-06-07 12:30\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.sw... | false |
1,171 | ebe7c245e3e14116a37020971e67ada054e0b434 | import requests
import csv
from bs4 import BeautifulSoup
reservoirs = [["LVQ"], ["HTH"], ["APN"], ["KNT"], ["SHA"]]
for reservoir in reservoirs:
storageURL = "https://cdec.water.ca.gov/dynamicapp/QueryMonthly?s=" + reservoir[0]
storagePage = requests.get(storageURL)
storageSoup = BeautifulSoup(storagePage... | [
"import requests\nimport csv\nfrom bs4 import BeautifulSoup\n\nreservoirs = [[\"LVQ\"], [\"HTH\"], [\"APN\"], [\"KNT\"], [\"SHA\"]]\n\nfor reservoir in reservoirs:\n storageURL = \"https://cdec.water.ca.gov/dynamicapp/QueryMonthly?s=\" + reservoir[0]\n storagePage = requests.get(storageURL)\n storageSoup =... | false |
1,172 | abdedad2c2b42b54cdba0e61e095ba3df0783b81 | """
Contain meta-data related functions:
* accessing integration schema: fields, values, constraints on inputs/queries
* tracking fields available
* tracking known (input field) values
"""
# coding=utf-8
__author__ = 'vidma'
| [
"\"\"\"\nContain meta-data related functions:\n\n* accessing integration schema: fields, values, constraints on inputs/queries\n* tracking fields available\n* tracking known (input field) values\n\"\"\"\n# coding=utf-8\n__author__ = 'vidma'\n",
"<docstring token>\n__author__ = 'vidma'\n",
"<docstring token>\n<a... | false |
1,173 | 0de735647cf87f64ab64af081da6e11b0ed8a7a7 | """component URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')... | [
"\"\"\"component URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: url(r'^$', vi... | false |
1,174 | 96ac9088650490a7da00c7a20f634b76e673ca2d | """
WINRM Module to connect to windows host
"""
from winrm.protocol import Protocol
from lib import logger
class WINRM(object):
"""
WINRM Module to connect to windows host
"""
def __init__(self, host_ip, usr, pwd):
"""
- **parameters**, **types**, **return** and **return t... | [
"\"\"\"\r\nWINRM Module to connect to windows host\r\n\"\"\"\r\nfrom winrm.protocol import Protocol\r\nfrom lib import logger\r\n\r\n\r\nclass WINRM(object):\r\n \"\"\"\r\n WINRM Module to connect to windows host\r\n \"\"\"\r\n def __init__(self, host_ip, usr, pwd):\r\n \"\"\"\r\n - **para... | false |
1,175 | ae6a6f7622bf98c094879efb1b9362a915a051b8 | import luigi
import numpy as np
import tqdm
import os
from scipy import spatial
from kq import wordmat_distance
class QuestionVectorTask(luigi.Task):
resources = {'cpu': 1}
dataset = luigi.Parameter()
def requires(self):
#yield wordmat_distance.WeightedSentenceVecs()
yield wordmat_distan... | [
"import luigi\nimport numpy as np\nimport tqdm\nimport os\nfrom scipy import spatial\n\nfrom kq import wordmat_distance\n\n\nclass QuestionVectorTask(luigi.Task):\n resources = {'cpu': 1}\n dataset = luigi.Parameter()\n\n def requires(self):\n #yield wordmat_distance.WeightedSentenceVecs()\n ... | false |
1,176 | 37c03732ae52171fc24aec85c940848b02d76dc1 | from django.urls import reverse_lazy
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView,
)
from .models import Entry
class EntryListView(ListView):
model = Entry
queryset = Entry.objects.all().order_by("-date_created")
class EntryDetailView(Detai... | [
"from django.urls import reverse_lazy\nfrom django.views.generic import (\n ListView,\n DetailView,\n CreateView,\n UpdateView,\n DeleteView,\n)\n\nfrom .models import Entry\n\n\nclass EntryListView(ListView):\n model = Entry\n queryset = Entry.objects.all().order_by(\"-date_created\")\n\n\ncla... | false |
1,177 | 84a516e924252d897be7444e11acfecd66474090 | # -*- coding:UTF-8 -*-
from __future__ import print_function
import logging
import numpy as np
from optparse import OptionParser
import sys
from time import time
import matplotlib.pyplot as plt
import os
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from skl... | [
"# -*- coding:UTF-8 -*-\nfrom __future__ import print_function\nimport logging\nimport numpy as np\nfrom optparse import OptionParser\nimport sys\nfrom time import time\nimport matplotlib.pyplot as plt\nimport os\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.feature_extraction.text import TfidfVect... | false |
1,178 | be892250c31198e801836dba24fa8218dd50e811 | def func():
print("这是无参数的打印")
func()
def func1(a):
print(f"这是有参数的打印:{a}")
func1("有参数a")
def func2(a, b):
return a + b
print(f"有返回值打印:{func2(3, 2)}")
def func3(a, b):
return
print(f"无返回值打印:{func3(3, 2)}")
| [
"def func():\n print(\"这是无参数的打印\")\n\n\nfunc()\n\n\ndef func1(a):\n print(f\"这是有参数的打印:{a}\")\n\n\nfunc1(\"有参数a\")\n\n\ndef func2(a, b):\n return a + b\n\n\nprint(f\"有返回值打印:{func2(3, 2)}\")\n\n\ndef func3(a, b):\n return\n\n\nprint(f\"无返回值打印:{func3(3, 2)}\")\n",
"def func():\n print('这是无参数的打印')\n\n\... | false |
1,179 | dfe0ee5bbb906e5a23adcf06d2d704700fa1567d | file = open('../_datasets/moby_dick.txt', mode='r')
print(file.read())
print(file.closed)
file.close()
print(file.closed)
| [
"file = open('../_datasets/moby_dick.txt', mode='r')\n\nprint(file.read())\nprint(file.closed)\nfile.close()\n\n\nprint(file.closed)\n",
"file = open('../_datasets/moby_dick.txt', mode='r')\nprint(file.read())\nprint(file.closed)\nfile.close()\nprint(file.closed)\n",
"<assignment token>\nprint(file.read())\npri... | false |
1,180 | d61b04539295f6b25e7f6589d32f313e3c6df82f | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.lines import Line2D
np.random.seed(42)
n_samples = 5000
MU = np.array([0.5, 1.5])
COV = np.array([[1., 0.7], [0.7, 2.]])
def get_samples(n):
return np.random.multivariate_normal(me... | [
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom matplotlib.lines import Line2D\n\nnp.random.seed(42)\n\nn_samples = 5000\nMU = np.array([0.5, 1.5])\nCOV = np.array([[1., 0.7], [0.7, 2.]])\n\ndef get_samples(n):\n return np.random.mult... | false |
1,181 | 58385a7713a8f88925ced714d25f1522bc7e39d8 | import matplotlib.pyplot as plt
class Scatter:
def __init__(self, values, ylabel, title):
self.values = values
self.range = list(range(len(values)))
self.ylabel = ylabel
self.title = title
def plot(self):
fig = plt.figure()
ax = fig.add_axes([0, 0, ... | [
"import matplotlib.pyplot as plt\r\n\r\n\r\nclass Scatter:\r\n def __init__(self, values, ylabel, title):\r\n self.values = values\r\n self.range = list(range(len(values)))\r\n self.ylabel = ylabel\r\n self.title = title\r\n\r\n def plot(self):\r\n fig = plt.figure()\r\n ... | false |
1,182 | 70c78021a2544ea372545b037ed55298c26391d1 | #-*- coding:utf-8 -*-
'''
'''
from flask import Flask, jsonify
app = Flask(__name__)
app.debug = True
from datetime import timedelta
from flask import make_response, request, current_app, render_template
from functools import update_wrapper
import json
from subprocess import *
def crossdomain(origin=None, methods=No... | [
"#-*- coding:utf-8 -*-\n'''\n'''\nfrom flask import Flask, jsonify\napp = Flask(__name__)\napp.debug = True\nfrom datetime import timedelta\nfrom flask import make_response, request, current_app, render_template\nfrom functools import update_wrapper\nimport json\n\nfrom subprocess import * \n\ndef crossdomain(origi... | false |
1,183 | d0dfea27128ca6966c85da6529ead5c95c86c4cf | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-16 12:35
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0033_auto_20171016_1334'),
]
operations = [
migrations.AlterField(
... | [
"# -*- coding: utf-8 -*-\n# Generated by Django 1.11.6 on 2017-10-16 12:35\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0033_auto_20171016_1334'),\n ]\n\n operations = [\n migr... | false |
1,184 | 41006ff35299aa72b69c6dc1c71a45b44dca7d6c | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import seaborn as sb
import matplotlib as mp
data = pd.read_csv("/Users/stevenbaez/Desktop/train.csv")
# In[2]:
data.head()
# In[3]:
subset = data[['Survived','Age', 'Sex']]
# In[5]:
import numpy as np
import matplotli... | [
"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nimport seaborn as sb\nimport matplotlib as mp\n\ndata = pd.read_csv(\"/Users/stevenbaez/Desktop/train.csv\")\n\n\n# In[2]:\n\n\ndata.head()\n\n\n# In[3]:\n\n\nsubset = data[['Survived','Age', 'Sex']]\n\n\n# In[5]:\n\n\... | false |
1,185 | ebebdb0e79e9d78b818dab3f93d130ccddd2914e | import math
import os
import sys
import pandas
import numpy as np
import seaborn as sns
import tensorflow as tf
import logging
# from utils.simulation_functions import simulation_cox_gompertz
from utils.preprocessing import formatted_data, normalize_batch, event_t_bin_prob,risk_t_bin_prob,\
batch_t_categorize, next_b... | [
"import math\nimport os\nimport sys\nimport pandas\n\nimport numpy as np\nimport seaborn as sns\nimport tensorflow as tf\nimport logging\n\n# from utils.simulation_functions import simulation_cox_gompertz\nfrom utils.preprocessing import formatted_data, normalize_batch, event_t_bin_prob,risk_t_bin_prob,\\\nbatch_t_... | false |
1,186 | 0ac99816248e3306ca6340f7bee8a518877bc3e9 | # Patrick Vanegas - Final project
from tkinter import *
import frequency
import turtle
import math
import random
# intitalize a blank window
root = Tk()
# initialize turtle window
window = turtle.Screen()
# Create widgets to be viewed on the Tkinter window
label_1 = Label(root, text = "Enter a number less than 5... | [
"# Patrick Vanegas - Final project\n\nfrom tkinter import *\nimport frequency\nimport turtle\nimport math\nimport random\n\n# intitalize a blank window\nroot = Tk() \n\n# initialize turtle window\nwindow = turtle.Screen() \n\n# Create widgets to be viewed on the Tkinter window\nlabel_1 = Label(root, text = \"Enter... | false |
1,187 | 004a02f7ff49cb1b63ebedfcfcb4937377859099 | print('hello world123')
| [
"print('hello world123')\n",
"<code token>\n"
] | false |
1,188 | 44214492dd7283da4b9a77bd2a1fa9d9c0643ff2 | import json
import logging
import numpy as np
from python_speech_features import mfcc
from format_converters import get_segment
from schemas import *
from chains.mfcc import Mfcc
logger = logging.getLogger()
class MfccLocal(Mfcc):
"""
MfccLocal computes Mfcc features for each phoneme from the sample
tha... | [
"import json\nimport logging\n\nimport numpy as np\nfrom python_speech_features import mfcc\n\nfrom format_converters import get_segment\nfrom schemas import *\nfrom chains.mfcc import Mfcc\nlogger = logging.getLogger()\n\n\nclass MfccLocal(Mfcc):\n \"\"\"\n MfccLocal computes Mfcc features for each phoneme f... | false |
1,189 | 4e9fd3ee2a78fae164d9f38704443ac5b2f4c11c | #!/usr/bin/env python
# Standardised set up
import RPi.GPIO as GPIO # External module imports GPIO
import time # Library to slow or give a rest to the script
import timeit # Alternative timing library for platform specific timing
import sys # Library to access program arguments and call exits
import os # Library provi... | [
"#!/usr/bin/env python\n\n# Standardised set up\nimport RPi.GPIO as GPIO # External module imports GPIO\nimport time # Library to slow or give a rest to the script\nimport timeit # Alternative timing library for platform specific timing\nimport sys # Library to access program arguments and call exits\nimport os # L... | false |
1,190 | ee1ce3ea4b31246703530478d6550b0c8866197e | import http.client
from urllib.parse import urlencode
client = http.client.HTTPConnection("127.0.0.1:9000")
post_data = {
"usertag": "test",
"password": '123456',
'code': "print('Hello Web')"
}
head_dict = {'Content-Type': 'application/x-www-form-urlencoded'}
post_data = urlencode(post_data)
client.request(... | [
"import http.client\nfrom urllib.parse import urlencode\nclient = http.client.HTTPConnection(\"127.0.0.1:9000\")\npost_data = {\n \"usertag\": \"test\",\n \"password\": '123456',\n 'code': \"print('Hello Web')\"\n}\nhead_dict = {'Content-Type': 'application/x-www-form-urlencoded'}\npost_data = urlencode(po... | false |
1,191 | 7badb7c9f1e00dfc379468b7bd73a3f09bffe6de | """empty message
Revision ID: 6374505f9e6e
Revises: 9dc91bb7d2ba
Create Date: 2016-11-14 10:55:08.418923
"""
# revision identifiers, used by Alembic.
revision = '6374505f9e6e'
down_revision = '9dc91bb7d2ba'
from alembic import op
import sqlalchemy as sa
import sqlalchemy.types as ty
def upgrade():
### command... | [
"\"\"\"empty message\n\nRevision ID: 6374505f9e6e\nRevises: 9dc91bb7d2ba\nCreate Date: 2016-11-14 10:55:08.418923\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '6374505f9e6e'\ndown_revision = '9dc91bb7d2ba'\n\nfrom alembic import op\nimport sqlalchemy as sa\nimport sqlalchemy.types as ty\n\n\nde... | false |
1,192 | be894830bb0dde6bacaea6be823391e0445603c3 | # This handle the url for routing
from django.urls import path
from . import views
# Defines views to pass dynamic data to listings page
urlpatterns = [
path('', views.index, name='listings'),
path('<int:listing_id>', views.listing, name='listing'),
path('search', views.search, name='search')
] | [
"# This handle the url for routing\n\nfrom django.urls import path\nfrom . import views\n\n# Defines views to pass dynamic data to listings page\nurlpatterns = [\n path('', views.index, name='listings'),\n path('<int:listing_id>', views.listing, name='listing'),\n path('search', views.search, name='search')\n]",... | false |
1,193 | 89605ff723d2f78e85cae458d576494718b5d456 | # coding: utf-8
from __future__ import division, unicode_literals
import unittest
from monty.inspect import *
class LittleCatA(object):
pass
class LittleCatB(LittleCatA):
pass
class LittleCatC(object):
pass
class LittleCatD(LittleCatB):
pass
class InspectTest(unittest.TestCase):
def test_fu... | [
"# coding: utf-8\nfrom __future__ import division, unicode_literals\n\nimport unittest\n\nfrom monty.inspect import *\n\nclass LittleCatA(object):\n pass\n\nclass LittleCatB(LittleCatA):\n pass\n\nclass LittleCatC(object):\n pass\n\nclass LittleCatD(LittleCatB):\n pass\n\n\nclass InspectTest(unittest.Te... | false |
1,194 | 81573b4a57f540733ff2faaf82bab78381b9dd46 | from argparse import ArgumentParser, Namespace
def parse_arguments() -> Namespace:
"""
Parse arguments
:return: Arguments
"""
parser = ArgumentParser(description='DLP project: Stock Prediction using Transformer')
parser.add_argument('-e', '--epochs', default=10, type=int, help='Number of epoc... | [
"from argparse import ArgumentParser, Namespace\n\n\ndef parse_arguments() -> Namespace:\n \"\"\"\n Parse arguments\n :return: Arguments\n \"\"\"\n parser = ArgumentParser(description='DLP project: Stock Prediction using Transformer')\n\n parser.add_argument('-e', '--epochs', default=10, type=int,... | false |
1,195 | 6ebf6bdfc6a4a1fe49f4eed1a2c1802f8adeef08 | def progress_format(user):
json = dict()
json["progres_id"] = user[0]
json["percentage"] = user[1]
json["user_id"] = user[2]
json["technology"] = user[3]
return json
def progresses_format(users):
json = dict()
json["users_progresses"] = list()
for user in users:
... | [
"def progress_format(user):\r\n json = dict()\r\n json[\"progres_id\"] = user[0]\r\n json[\"percentage\"] = user[1]\r\n json[\"user_id\"] = user[2]\r\n json[\"technology\"] = user[3]\r\n return json\r\n\r\ndef progresses_format(users):\r\n json = dict()\r\n json[\"users_progresses\"] = list(... | false |
1,196 | 8334478c8b7fc7688477cdb837467e00e857c07c | from django.shortcuts import get_object_or_404
from rest_framework import generics
from .models import Duck
from .serializers import Duck_Serializer
class DuckList(generics.ListCreateAPIView):
queryset = Duck.objects.all()
serializer_class = Duck_Serializer
def get_object(self):
queryset = self.get_queryset()
... | [
"from django.shortcuts import get_object_or_404\nfrom rest_framework import generics\nfrom .models import Duck\nfrom .serializers import Duck_Serializer\n\nclass DuckList(generics.ListCreateAPIView):\n\tqueryset = Duck.objects.all()\n\tserializer_class = Duck_Serializer\n\n\tdef get_object(self):\n\t\tqueryset = se... | false |
1,197 | 18b73a06c80272aff5c0e4b10473e95bd58466f3 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 7 07:51:26 2017
@author: hcorrada
"""
from plagiarism_lib.article_db import ArticleDB
from plagiarism_lib.minhash import MinHash
from plagiarism_lib.lsh import LSH
import pandas as pd
import numpy as np
def _read_truthfile(filepath):
with op... | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 7 07:51:26 2017\n\n@author: hcorrada\n\"\"\"\n\nfrom plagiarism_lib.article_db import ArticleDB\nfrom plagiarism_lib.minhash import MinHash\nfrom plagiarism_lib.lsh import LSH\n\nimport pandas as pd\nimport numpy as np\n\ndef _read_truthf... | false |
1,198 | bdfd941be29a31d6c1bbedd270dadac844f49fc4 | from Player import Player
class GameSequence:
'''
GameSequence summary: Keeps track of player turn sequence and Game end
Functionalities
-start game
-must start turns
-change turns
-end turns
-end game
'''
def __init__(self, ArrayofPlaye... | [
"from Player import Player\r\n\r\n\r\n\r\n\r\nclass GameSequence:\r\n '''\r\n GameSequence summary: Keeps track of player turn sequence and Game end\r\n Functionalities\r\n -start game\r\n -must start turns\r\n -change turns\r\n -end turns\r\n -end game\r\n\r\n '''\r\n... | false |
1,199 | f9edbef46494cc2993c6a633fe35406524dbbf67 | from mtots.parser import base
from mtots.parser import combinator
from mtots.parser.combinator import All
from mtots.parser.combinator import Any
from mtots.parser.combinator import AnyTokenBut
from mtots.parser.combinator import Forward
from mtots.parser.combinator import Peek
from mtots.parser.combinator import Requi... | [
"from mtots.parser import base\nfrom mtots.parser import combinator\nfrom mtots.parser.combinator import All\nfrom mtots.parser.combinator import Any\nfrom mtots.parser.combinator import AnyTokenBut\nfrom mtots.parser.combinator import Forward\nfrom mtots.parser.combinator import Peek\nfrom mtots.parser.combinator ... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.