index
int64
0
10k
blob_id
stringlengths
40
40
code
stringlengths
13
1.2M
steps
listlengths
1
578
error
bool
2 classes
200
1a7e83fe9528b177246d6374ddaf2a76a0046e83
# coding:utf-8 import jieba import os import sys import math reload(sys) sys.setdefaultencoding('utf-8') from sklearn import feature_extraction from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import CountVectorizer #import csv #import pandas #import numpy sente...
[ "# coding:utf-8 \nimport jieba\nimport os \nimport sys\nimport math\nreload(sys)\nsys.setdefaultencoding('utf-8')\nfrom sklearn import feature_extraction \nfrom sklearn.feature_extraction.text import TfidfTransformer \nfrom sklearn.feature_extraction.text import CountVectorizer\n#import csv\n#import pandas\n#im...
false
201
7e7e96fb9377e4dc59a46a46951f5057ecae419a
# -*- coding: utf-8 -*- import random import gym import numpy as np from collections import deque from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam from simulation_utils import box, simulation from kinematics import pose3D a = np.log(2)/25 apdataX = np.random.random(...
[ "# -*- coding: utf-8 -*-\nimport random\nimport gym\nimport numpy as np\nfrom collections import deque\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\nfrom simulation_utils import box, simulation\nfrom kinematics import pose3D\n\na = np.log(2)/25\n\napdataX =...
false
202
b6183daa943cc63fd2959e3e54fc1e6af5d761de
# -*- coding: utf-8 -*- import math #COMECE SEU CÓDIGO AQUI f = float(input('Digite o valor de f: ')) L = float(input('Digite o valor de L: ')) Q = float(input('Digite o valor de Q: ')) DeltaH = float(input('Digite o valor de DeltaH: ')) v = float(input('Digite o valor de v: ')) g = 9.81 e = 0.000002 #PROCESSAMENTO D =...
[ "# -*- coding: utf-8 -*-\nimport math\n#COMECE SEU CÓDIGO AQUI\nf = float(input('Digite o valor de f: '))\nL = float(input('Digite o valor de L: '))\nQ = float(input('Digite o valor de Q: '))\nDeltaH = float(input('Digite o valor de DeltaH: '))\nv = float(input('Digite o valor de v: '))\ng = 9.81\ne = 0.000002\n#PR...
false
203
1490fecd6e983c0e3093a45d77d6fb8afdb54718
# ****************************************************************************** # main.py # # Date Name Description # ======== ========= ======================================================== # 6/5/19 Paudel Initial version, # ***********************************************************************...
[ "# ******************************************************************************\n# main.py\n#\n# Date Name Description\n# ======== ========= ========================================================\n# 6/5/19 Paudel Initial version,\n# ************************************************************...
false
204
e5d7cc65041d65f915d4882b4fdad5bebf79a067
from collections import defaultdict from typing import Union, Iterable, Sized import numpy as np from cached_property import cached_property from keras.utils import to_categorical from keras.preprocessing.sequence import pad_sequences from keras.preprocessing.text import Tokenizer, text_to_word_sequence class Source...
[ "from collections import defaultdict\nfrom typing import Union, Iterable, Sized\n\nimport numpy as np\nfrom cached_property import cached_property\nfrom keras.utils import to_categorical\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.preprocessing.text import Tokenizer, text_to_word_sequence\n\...
false
205
e221553f866de8b3e175197a40982506bf8c1ef9
import torch import torch.nn.functional as F import csv class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.predict = torch.nn.Linear(n_hidden, n_output) def forward(self, x...
[ "import torch\nimport torch.nn.functional as F\nimport csv\n\n\nclass Net(torch.nn.Module):\n\n def __init__(self, n_feature, n_hidden, n_output):\n super(Net, self).__init__()\n self.hidden = torch.nn.Linear(n_feature, n_hidden)\n self.predict = torch.nn.Linear(n_hidden, n_output)\n\n de...
false
206
39dda191ab2137b5f5538660f17e39b0a1358bf4
import numpy as np import cv2 import colorsys from matplotlib import pyplot as plt img = cv2.imread('coins.jpg') b,g,r = cv2.split(img) rgb_img = cv2.merge([r,g,b]) gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # Blurring image grayBlur = cv2.medianBlur(gray, 3) # Binary threshold ret, thresh = cv2.threshold(grayBl...
[ "import numpy as np\nimport cv2\nimport colorsys\nfrom matplotlib import pyplot as plt\n\nimg = cv2.imread('coins.jpg')\n\nb,g,r = cv2.split(img)\nrgb_img = cv2.merge([r,g,b])\n\ngray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n\n# Blurring image\ngrayBlur = cv2.medianBlur(gray, 3)\n\n# Binary threshold\nret, thresh =...
false
207
0e6e84a31b626639e2aa149fd1ef89f3ef251cd7
# -*- coding: utf-8 -*- ################################## # @program synda # @description climate models data transfer program # @copyright Copyright "(c)2009 Centre National de la Recherche Scientifique CNRS. # All Rights Reserved" # @license CeCILL (https://raw.g...
[ "# -*- coding: utf-8 -*-\n##################################\n# @program synda\n# @description climate models data transfer program\n# @copyright Copyright \"(c)2009 Centre National de la Recherche Scientifique CNRS.\n# All Rights Reserved\"\n# @license CeCILL (...
false
208
c0d71d970b2632dbf182a5ee8bad27d3e41578f6
#!/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 import sys def sumInput(text): f = open(text, 'r') sum = 0 count = 1 for line in f: count += 1 line = line.strip() if (line[0] == '+'): sum += int(line[1:]) else: sum -= int(line[1:...
[ "#!/Library/Frameworks/Python.framework/Versions/3.7/bin/python3\n\nimport sys\n\ndef sumInput(text):\n f = open(text, 'r')\n sum = 0\n count = 1\n for line in f:\n count += 1\n line = line.strip()\n if (line[0] == '+'):\n sum += int(line[1:])\n else:\n ...
false
209
f14d46bedd5f6e0081a982251ad45e95860ef310
class HashTable: def __init__(self): self.dados = [] def hash(self, chave): return int(chave) def __put(self, int, chave, valor): self.dados.append({chave: valor}) """ backup = dados dados = novo_array(t * 2) for elemento in backup: hash = hash(elemento.chave) __put(...
[ "class HashTable:\n def __init__(self):\n self.dados = []\n\n def hash(self, chave):\n return int(chave)\n \n def __put(self, int, chave, valor):\n self.dados.append({chave: valor})\n\n\n\"\"\"\nbackup = dados\ndados = novo_array(t * 2)\n\nfor elemento in backup:\n hash = hash(el...
false
210
21a41356fcedb36223498db0fe783e4a9e8e1ba6
# help from https://stackoverflow.com/questions/19007383/compare-two-different-files-line-by-line-in-python with open('Book1.txt', 'r') as file1: with open('20k.txt', 'r') as file2: same = set(file1).intersection(file2) same.discard('\n') with open('notin20kforBook1.txt', 'w') as file_out: for line i...
[ "# help from https://stackoverflow.com/questions/19007383/compare-two-different-files-line-by-line-in-python\n\nwith open('Book1.txt', 'r') as file1:\n with open('20k.txt', 'r') as file2:\n same = set(file1).intersection(file2)\n\nsame.discard('\\n')\n\nwith open('notin20kforBook1.txt', 'w') as file_out:\...
false
211
de7b5e44c5c213e4ab70b0f8c0c402edaf4926e0
from django.conf.urls import url from .import views app_name='user' # user子路由 urlpatterns = [ # user首页 url(r'^$',views.index,name='index'), # 用户登录 url('login/', views.login, name='login'), # 用户注册 url('regist/', views.regist, name='regist'), # 根据id判断用户是否存在 url(r'^getuser\w*/(?P<id>\...
[ "\nfrom django.conf.urls import url\nfrom .import views\n\napp_name='user'\n# user子路由\nurlpatterns = [\n\n # user首页\n url(r'^$',views.index,name='index'),\n\n # 用户登录\n url('login/', views.login, name='login'),\n\n # 用户注册\n url('regist/', views.regist, name='regist'),\n\n # 根据id判断用户是否存在\n url...
false
212
cc7f1f38efcd4d757c1d11e2bd53695fca44e15a
'For learning OWL and owlready2' 'From "https://qiita.com/sci-koke/items/a650c09bf77331f5537f"' 'From "https://owlready2.readthedocs.io/en/latest/class.html"' '* Owlready2 * Warning: optimized Cython parser module "owlready2_optimized" is not available, defaulting to slower Python implementation' '↑ This wartning mean...
[ "'For learning OWL and owlready2'\n'From \"https://qiita.com/sci-koke/items/a650c09bf77331f5537f\"'\n'From \"https://owlready2.readthedocs.io/en/latest/class.html\"'\n\n'* Owlready2 * Warning: optimized Cython parser module \"owlready2_optimized\" is not available, defaulting to slower Python implementation'\n'↑ Th...
false
213
a2e2528f560f6117d4ceeb9cd20d3f6f6b2a30a7
# -*- coding: utf-8 -*- def testeum(): a = 10 print(id(a)) def testedois(): a = 10 print(id(a))
[ "# -*- coding: utf-8 -*-\ndef testeum():\n a = 10\n print(id(a))\ndef testedois():\n a = 10\n print(id(a))", "def testeum():\n a = 10\n print(id(a))\n\n\ndef testedois():\n a = 10\n print(id(a))\n", "def testeum():\n a = 10\n print(id(a))\n\n\n<function token>\n", "<function toke...
false
214
e09af436f2fb37d16427aa0b1416d6f2d59ad6c4
#!/usr/bin/env python3 import argparse import os import sys,shutil from shutil import make_archive import pathlib from phpManager import execute,execute_outputfile from datetime import date,datetime import re import pymysql import tarfile def append_log(log,message): f = open(log, "a+") today = datetime.now()...
[ "#!/usr/bin/env python3\nimport argparse\nimport os\nimport sys,shutil\nfrom shutil import make_archive\nimport pathlib\nfrom phpManager import execute,execute_outputfile\nfrom datetime import date,datetime\nimport re\nimport pymysql\nimport tarfile\n\n\ndef append_log(log,message):\n f = open(log, \"a+\")\n ...
false
215
46adb1834f6013ca0f13a64f280182a805d76278
#!/usr/bin/python3 # encoding: utf-8 import sys import argparse import logging from pathlib import Path module = sys.modules['__main__'].__file__ __author__ = 'FFX' __version__ = '1.0' log = logging.getLogger(module) def parse_command_line(argv): """Parse command line argument. See -h option :param argv: ...
[ "#!/usr/bin/python3\n# encoding: utf-8\n\n\nimport sys\nimport argparse\nimport logging\nfrom pathlib import Path\n\n\nmodule = sys.modules['__main__'].__file__\n__author__ = 'FFX'\n__version__ = '1.0'\nlog = logging.getLogger(module)\n\n\ndef parse_command_line(argv):\n \"\"\"Parse command line argument. See -h...
false
216
c63e5a2178e82ec6e0e1e91a81145afb735bf7bf
__author__ = 'lei' import unittest from ch3.node import TreeNode as t import ch3.searchRange as sr class MyTestCase(unittest.TestCase): def test_1(self): a = t(2) b=t(1) a.left = b self.assertEqual(sr.searchRange(a,0,4), [1,2]) def test_2(self): a = t(20) b = ...
[ "__author__ = 'lei'\n\nimport unittest\nfrom ch3.node import TreeNode as t\nimport ch3.searchRange as sr\n\n\nclass MyTestCase(unittest.TestCase):\n def test_1(self):\n a = t(2)\n b=t(1)\n a.left = b\n self.assertEqual(sr.searchRange(a,0,4), [1,2])\n\n def test_2(self):\n a ...
false
217
b77da75b01e96ff89f873f4c5764a62cf68cd576
from rest_framework import serializers from .models import * __all__ = ( 'CatalogCoinListSerializer', 'CatalogCoinSerializer', 'SeriesListSerializer', 'CoinListSerializer', 'CoinSerializer', 'CountriesListSerializer', ) class CountriesListSerializer(serializers.ModelSerializer): class Meta: mode...
[ "from rest_framework import serializers\n\nfrom .models import *\n\n__all__ = (\n 'CatalogCoinListSerializer', 'CatalogCoinSerializer', 'SeriesListSerializer', 'CoinListSerializer',\n 'CoinSerializer', 'CountriesListSerializer',\n)\n\n\nclass CountriesListSerializer(serializers.ModelSerializer):\n class Me...
false
218
1f0695f0e9745912d8ee3a87e6c9b1272e9ebbae
""" Writes day of the week and time to a file. Script written for crontab tutorial. Author: Jessica Yung 2016 """ import time filename = "record_time.txt" # Records time in format Sun 10:00:00 current_time = time.strftime('%a %H:%M:%S') # Append output to file. 'a' is append mode. with open(filename, 'a') as hand...
[ "\"\"\"\nWrites day of the week and time to a file.\n\nScript written for crontab tutorial.\n\nAuthor: Jessica Yung 2016\n\n\"\"\"\nimport time\n\nfilename = \"record_time.txt\"\n\n# Records time in format Sun 10:00:00\ncurrent_time = time.strftime('%a %H:%M:%S')\n\n# Append output to file. 'a' is append mode.\nwit...
false
219
142a2ba3ec2f6b35f4339ed9fffe7357c1a85fa0
import requests import time import urllib import argparse from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys from fake_useragent import UserAgent from multiprocessing import Pool from lxml.html import fromstring import os, sys #text = 'chowchowbaby' #url='https...
[ "import requests\nimport time\nimport urllib\nimport argparse\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom fake_useragent import UserAgent\nfrom multiprocessing import Pool\nfrom lxml.html import fromstring\nimport os, sys\n\n#text = 'chowchow...
false
220
2a19c2d6e51e9c123236c58f82de1a39e5db40f4
import numpy as np # Copyright 2011 University of Bonn # Author: Hannes Schulz def cnan(x): """ check for not-a-number in parameter x """ if np.isnan(x).sum()>0: import pdb pdb.set_trace() def get_curve_3D(eig, alpha=0.25,g23=0.5,g12=0.5): # renumerated according to sato et al: l3 is smallest...
[ "import numpy as np\n\n# Copyright 2011 University of Bonn\n# Author: Hannes Schulz\n\ndef cnan(x):\n \"\"\" check for not-a-number in parameter x \"\"\"\n if np.isnan(x).sum()>0:\n import pdb\n pdb.set_trace()\n\ndef get_curve_3D(eig, alpha=0.25,g23=0.5,g12=0.5): # renumerated according to sato...
true
221
550f5ad4fef77d5795db0393ae0701f679143e72
#!/usr/bin/env python # @HEADER # ************************************************************************ # # TriBITS: Tribal Build, Integrate, and Test System # Copyright 2013 Sandia Corporation # # Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, # the U.S. Govern...
[ "#!/usr/bin/env python\n\n# @HEADER\n# ************************************************************************\n#\n# TriBITS: Tribal Build, Integrate, and Test System\n# Copyright 2013 Sandia Corporation\n#\n# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n# t...
false
222
4fa9d16f979acf3edce05a209e1c6636e50fc315
from jox_api import label_image,Mysql,Utils from jox_config import api_base_url import json class Menu(): def __init__(self): self.mysqlClass = Mysql.MySQL() self.timeClass = Utils.Time() def get_menu(self,type,openid): try: if type == 'mine': self.sql = "SEL...
[ "from jox_api import label_image,Mysql,Utils\nfrom jox_config import api_base_url\nimport json\nclass Menu():\n def __init__(self):\n self.mysqlClass = Mysql.MySQL()\n self.timeClass = Utils.Time()\n\n def get_menu(self,type,openid):\n try:\n if type == 'mine':\n ...
false
223
e5e012e40a71dee9f4dbd9913590aef125b758df
from classes.Board import Board class Visualiser: coordinate_map = ("a", "b", "c", "d", "e", "f", "g", "h") __dimensions = 8 def __init__(self): self.map = [] self.__build_map() def __build_map(self): """ Creates the array of the battlefield. Should never be used for ...
[ "from classes.Board import Board\n\n\nclass Visualiser:\n coordinate_map = (\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\")\n __dimensions = 8\n\n def __init__(self):\n self.map = []\n self.__build_map()\n\n def __build_map(self):\n \"\"\"\n Creates the array of the b...
false
224
c4e4e54ac93c2acdbd3a1cd22b200341a6e45688
import pyaudio import numpy as np from collections import OrderedDict import utils class MasterPlayer(object): def __init__(self, volume=1., samplesPerSecond=44100): self.p = pyaudio.PyAudio() self.volume = volume self.samplesPerSecond = samplesPerSecond self.individual_callbacks =...
[ "import pyaudio\nimport numpy as np\nfrom collections import OrderedDict\nimport utils\n\n\nclass MasterPlayer(object):\n def __init__(self, volume=1., samplesPerSecond=44100):\n self.p = pyaudio.PyAudio()\n self.volume = volume\n self.samplesPerSecond = samplesPerSecond\n self.indivi...
true
225
27e9e63338d422b5fca6f7a67fa3d255602a3358
from abstract_class_V import V import torch import torch.nn as nn class V_test_abstract(V): def __init__(self): super(V_test_abstract, self).__init__() def V_setup(self,y,X,nu): self.explicit_gradient = False self.need_higherorderderiv = True self.dim = X.shape[1] self...
[ "from abstract_class_V import V\nimport torch\nimport torch.nn as nn\n\n\nclass V_test_abstract(V):\n def __init__(self):\n super(V_test_abstract, self).__init__()\n\n def V_setup(self,y,X,nu):\n self.explicit_gradient = False\n self.need_higherorderderiv = True\n self.dim = X.shap...
false
226
ec4348c61cd1c9130543bb20f9ca199399e1caff
class Solution(object): def restoreIpAddresses(self, s): """ :type s: str :rtype: List[str] """ def helper(sb, string, level): if len(string) == 0: if level == 4: ans.append(sb[:-1]) return if level ...
[ "class Solution(object):\n def restoreIpAddresses(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n \"\"\"\n\n def helper(sb, string, level):\n if len(string) == 0:\n if level == 4:\n ans.append(sb[:-1])\n return...
true
227
d0a3f332e04627eb275168972bd92cd1ea9b9447
from board.ttt import TTT from mctsai.mcts import MCTS import unittest # skip = [0, 1] skip = [0] class TestTTT(unittest.TestCase): def test_mcts(self): if 0 in skip: print("Skipping ai self-play") return ttt = TTT() for i in range(1000): mcts = MCTS(tt...
[ "from board.ttt import TTT\nfrom mctsai.mcts import MCTS\nimport unittest\n\n# skip = [0, 1]\n\nskip = [0]\n\nclass TestTTT(unittest.TestCase):\n def test_mcts(self):\n if 0 in skip:\n print(\"Skipping ai self-play\")\n return\n ttt = TTT()\n for i in range(1000):\n ...
false
228
e95bda8be2294c295d89f1c035bc209128fa29c8
def merge_the_tools(string, k): # your code goes here num_sub_strings = len(string)/k #print num_sub_strings for idx in range(num_sub_strings): print "".join(set(list(string[idx * k : (idx + 1) * k])))
[ "def merge_the_tools(string, k):\n # your code goes here\n num_sub_strings = len(string)/k\n #print num_sub_strings\n\n for idx in range(num_sub_strings):\n print \"\".join(set(list(string[idx * k : (idx + 1) * k])))\n\n" ]
true
229
f85a703b47d981397ed6048e941030a3fbee7b6d
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2018-04-27 08:05 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('talk', '0023_auto_20180207_1121'), ] operations = [ migrations.AddField( ...
[ "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.8 on 2018-04-27 08:05\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('talk', '0023_auto_20180207_1121'),\n ]\n\n operations = [\n migra...
false
230
23375760c0943ca177b7009031d9d17a91165c5c
#!/usr/bin/env python #--coding: utf8-- import time if __name__ == '__main__': date = time.strftime('%m-%d') if date == '03-08': print '女神节' elif date == '02-14': print '情人节' else: print '发红包' print '这是一个测试题'
[ "#!/usr/bin/env python\n#--coding: utf8--\nimport time\n\nif __name__ == '__main__':\n date = time.strftime('%m-%d')\n if date == '03-08':\n print '女神节'\n elif date == '02-14':\n print '情人节'\n else:\n print '发红包'\n print '这是一个测试题'" ]
true
231
f8d815bcdc74452b66a1b3b33bf0fbe976e728c8
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. import tensorflow as tf from tensorflow.keras import datasets, layers, models import matplotlib.pyplot as plt import numpy ...
[ "# This is a sample Python script.\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\n\nimport tensorflow as tf\nfrom tensorflow.keras import datasets, layers, models\nimport matplotlib.pyplot as plt\n...
false
232
ef85f94282bfd7c9491c4e28bab61aaab5c792a5
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'src/ui_LibraryTab.ui' # # Created: Tue Jun 9 21:46:41 2015 # by: PyQt5 UI code generator 5.4 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Tab(object): def setupUi(se...
[ "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'src/ui_LibraryTab.ui'\n#\n# Created: Tue Jun 9 21:46:41 2015\n# by: PyQt5 UI code generator 5.4\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_Tab(object):\n ...
false
233
8c8bbbc682889c8d79c893f27def76ad70e8bf8d
DATABASE_NAME = "user_db"
[ "DATABASE_NAME = \"user_db\"", "DATABASE_NAME = 'user_db'\n", "<assignment token>\n" ]
false
234
9d904225afd4f4d0cf338ae16f031f8ab41639ad
# -*- coding=utf-8 -*- from mako.template import Template from xblock.fragment import Fragment from .lookup import TemplateLookup # xblock_ifmo.lookup from .utils import deep_update class FragmentMakoChain(Fragment): """ Класс, позволяющий последовательно оборачивать экземпляры Fragment друг в друга. ...
[ "# -*- coding=utf-8 -*-\n\nfrom mako.template import Template\nfrom xblock.fragment import Fragment\n\nfrom .lookup import TemplateLookup # xblock_ifmo.lookup\nfrom .utils import deep_update\n\n\nclass FragmentMakoChain(Fragment):\n \"\"\"\n Класс, позволяющий последовательно оборачивать экземпляры Fragment ...
false
235
8cc0393082448bb8f61068b5c96e89ef3aee77ed
#coding: utf-8 import logging from threading import Thread from ldap import SCOPE_BASE from seafevents.ldap_syncer.ldap_conn import LdapConn from seafevents.ldap_syncer.utils import bytes2str, add_group_uuid_pair from seaserv import get_group_dn_pairs logger = logging.getLogger(__name__) def migrate_dn_pairs(set...
[ "#coding: utf-8\nimport logging\nfrom threading import Thread\n\nfrom ldap import SCOPE_BASE\nfrom seafevents.ldap_syncer.ldap_conn import LdapConn\nfrom seafevents.ldap_syncer.utils import bytes2str, add_group_uuid_pair\n\nfrom seaserv import get_group_dn_pairs\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef m...
false
236
21af630bf383ee1bdd0f644283f0ddadde71620a
#!/bin/usr/python2.7.x import os, re, urllib2 def main(): ip = raw_input(" Target IP : ") check(ip) def check(ip): try: print "Loading Check File Uploader...." print 58*"-" page = 1 while page <= 21: bing = "http://www.bing.com/search?q=ip%3A" + \ ip + "+upload&count=50&first=" + str(...
[ "#!/bin/usr/python2.7.x\r\n\r\nimport os, re, urllib2\r\n\r\ndef main():\r\n\tip = raw_input(\" Target IP : \")\r\n\tcheck(ip)\r\n\r\ndef check(ip):\r\n\ttry:\r\n\t\tprint \"Loading Check File Uploader....\"\r\n\t\tprint 58*\"-\"\r\n\t\tpage = 1\r\n\t\twhile page <= 21:\r\n\t\t\tbing = \"http://www.bing.com/search?...
true
237
eb853e430b996a81dc2ef20c320979a3e04d956a
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- import hashlib import re from datetime import datetime import gevent import requests import scrapy from gevent.pool import Pool from lxml import etree from scrapy.http import HtmlResponse from sqlalchemy import create_engine, func from sqlalchemy.orm import sessionmaker ...
[ "#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\nimport hashlib\nimport re\nfrom datetime import datetime\n\nimport gevent\nimport requests\nimport scrapy\nfrom gevent.pool import Pool\nfrom lxml import etree\nfrom scrapy.http import HtmlResponse\nfrom sqlalchemy import create_engine, func\nfrom sqlalchemy.orm imp...
false
238
bc4684d255a46427f708d8ce8bda2e12fb8c8ffe
# -*- coding: utf-8 -*- from route4me import Route4Me API_KEY = "11111111111111111111111111111111" def main(): r4m = Route4Me(API_KEY) route = r4m.route response = route.get_routes(limit=1, offset=0) if isinstance(response, dict) and 'errors' in response.keys(): print('. '.join(response['err...
[ "# -*- coding: utf-8 -*-\n\nfrom route4me import Route4Me\n\nAPI_KEY = \"11111111111111111111111111111111\"\n\n\ndef main():\n r4m = Route4Me(API_KEY)\n route = r4m.route\n response = route.get_routes(limit=1, offset=0)\n if isinstance(response, dict) and 'errors' in response.keys():\n print('. '...
false
239
d015a1b27a3a9e7f5e6614da752137064000b905
#!/usr/bin/env python3 """Transfer learning with xception""" import tensorflow.keras as K from GPyOpt.methods import BayesianOptimization import pickle import os import numpy as np class my_model(): """A model bassed on xception""" def make_model(self, param): """makes the model""" self.lr = ...
[ "#!/usr/bin/env python3\n\"\"\"Transfer learning with xception\"\"\"\nimport tensorflow.keras as K\nfrom GPyOpt.methods import BayesianOptimization\nimport pickle\nimport os\nimport numpy as np\n\n\nclass my_model():\n \"\"\"A model bassed on xception\"\"\"\n\n def make_model(self, param):\n \"\"\"make...
false
240
ef6f55bf27982f53441215da6822cfcdc80706a5
# -*- coding: utf-8 -*- __author__ = 'Yun' __project__ = 'DjangoBookTest2' # from django.template import Template, Context # from django.template.loader import get_template # from django.http import HttpResponse from django.shortcuts import render_to_response import datetime def current_datetime(request): # now ...
[ "# -*- coding: utf-8 -*-\n__author__ = 'Yun'\n__project__ = 'DjangoBookTest2'\n\n# from django.template import Template, Context\n# from django.template.loader import get_template\n# from django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nimport datetime\n\n\ndef current_datetime(requ...
false
241
e8226ab6be5c21335d843cba720e66646a2dee4e
import os import requests import sqlite3 from models import analytics, jcanalytics def populate(): url = 'https://api.clicky.com/api/stats/4?site_id=100716069&sitekey=93c104e29de28bd9&type=visitors-list' date = '&date=last-30-days' limit = '&limit=all' output = '&output=json' total = url+date+limi...
[ "import os\nimport requests\nimport sqlite3\nfrom models import analytics, jcanalytics\n\n\ndef populate():\n url = 'https://api.clicky.com/api/stats/4?site_id=100716069&sitekey=93c104e29de28bd9&type=visitors-list'\n date = '&date=last-30-days'\n limit = '&limit=all'\n output = '&output=json'\n total...
true
242
e616d14827beaa08ab08219421cbf7990cf163fd
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.InsureAdmitDTO import InsureAdmitDTO class AlipayInsSceneEcommerceInsureCheckModel(object): def __init__(self): self._insure_admit_dto_list = None self._partn...
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\nfrom alipay.aop.api.domain.InsureAdmitDTO import InsureAdmitDTO\n\n\nclass AlipayInsSceneEcommerceInsureCheckModel(object):\n\n def __init__(self):\n self._insure_admit_dto_list = None\n ...
false
243
c4ca4b5c77c3c912b44a4853be30298ec845c4fd
#str owog="Delger" # len()- urt # lower()- jijigruuleh # upper()- tomruulah # capitalize()- ehnii useg tomruulah # replace()- temdegt solih print(owog.find("e")) print(owog.count("e")) print(owog[2:10]) a=21 b=21 if a>b: print("a too ih") elif a==b: print("tentsuu") else: print("b to...
[ "#str\r\nowog=\"Delger\"\r\n# len()- urt\r\n# lower()- jijigruuleh\r\n# upper()- tomruulah\r\n# capitalize()- ehnii useg tomruulah\r\n# replace()- temdegt solih\r\nprint(owog.find(\"e\"))\r\nprint(owog.count(\"e\"))\r\nprint(owog[2:10])\r\n\r\na=21\r\nb=21\r\nif a>b:\r\n print(\"a too ih\")\r\nelif a==b:\r\...
false
244
050e2207ac7331444d39305869c4b25bcbc53907
import pandas as pd from sklearn.preprocessing import MinMaxScaler #loading data from CSV training_data_df = pd.read_csv("sales_data_training.csv") test_data_df = pd.read_csv("sales_data_test.csv") #scaler scaler = MinMaxScaler(feature_range=(0,1)) #scale both inputs and outputs scaled_training = scaler.fit_transfor...
[ "import pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\n\n#loading data from CSV\ntraining_data_df = pd.read_csv(\"sales_data_training.csv\")\ntest_data_df = pd.read_csv(\"sales_data_test.csv\")\n\n#scaler\nscaler = MinMaxScaler(feature_range=(0,1))\n\n#scale both inputs and outputs\nscaled_training =...
false
245
df64d769ffba8cddac34282a526122e3c941249d
#!/usr/bin/env python import os import tempfile import shutil import math import sys import subprocess from irank.config import IrankOptionParser, IrankApp from irank import db as irank_db STATUS = 0 def main(): p = IrankOptionParser('%prog -d DEST playlist_name [playlist_name ...]') p.add_option('-d', '--dest', he...
[ "#!/usr/bin/env python\nimport os\nimport tempfile\nimport shutil\nimport math\nimport sys\nimport subprocess\n\nfrom irank.config import IrankOptionParser, IrankApp\nfrom irank import db as irank_db\nSTATUS = 0\n\ndef main():\n\tp = IrankOptionParser('%prog -d DEST playlist_name [playlist_name ...]')\n\tp.add_opti...
true
246
21b295e28a7e4443ea116df1b22ff5074dca955a
n =int(input("nhap gia tri")) for i in range(1,n+1): print(i)
[ "n =int(input(\"nhap gia tri\"))\nfor i in range(1,n+1):\n\n\n\n\n\n\n\n\n\n\n\n\n print(i)", "n = int(input('nhap gia tri'))\nfor i in range(1, n + 1):\n print(i)\n", "<assignment token>\nfor i in range(1, n + 1):\n print(i)\n", "<assignment token>\n<code token>\n" ]
false
247
93737e4c409d0efb1ae2263cb60d4b03d9aad0d8
import os import shutil import argparse ap = argparse.ArgumentParser() ap.add_argument('-D','--dir', required=False, help='Directory to sort') args = vars(ap.parse_args()) if args['dir'] == None: DIR = os.getcwd() elif os.path.exists(args['dir']): DIR = args['dir'] for file in os.listdir(DIR): if not os....
[ "import os\nimport shutil\nimport argparse\n\nap = argparse.ArgumentParser()\n\nap.add_argument('-D','--dir', required=False, help='Directory to sort')\n\nargs = vars(ap.parse_args())\nif args['dir'] == None:\n DIR = os.getcwd()\nelif os.path.exists(args['dir']):\n DIR = args['dir']\nfor file in os.listdir(DI...
false
248
b5611c668a40e1735c92d6d00867885023ad713f
target=[] with open('IntegerArray.txt','r') as f: target=f.readlines() for x in range(len(target)): target[x]=int(target[x]) def f(A): if len(A)==1: return 0 else: rightStart=len(A)//2 leftArray=A[0:rightStart] righArray=A[rightStart:] B,b=count_and_sort(leftArray) C,c=count_and_sort(righA...
[ "target=[]\r\nwith open('IntegerArray.txt','r') as f:\r\n\ttarget=f.readlines()\r\nfor x in range(len(target)):\r\n\ttarget[x]=int(target[x])\r\ndef f(A): \r\n\tif len(A)==1:\r\n\t\treturn 0\r\n\telse:\r\n\t\trightStart=len(A)//2\r\n\t\tleftArray=A[0:rightStart]\r\n\t\trighArray=A[rightStart:]\r\n\t\tB,b=count_and_...
false
249
09f032301fa9389f6b07687e0ee13844e0b4ddf3
from artichoke import DefaultManager, Config from artichoke.helpers import read, prompt from fabric.api import env, task, run import os chars = ''.join(chr(c) if chr(c).isupper() or chr(c).islower() else '_' for c in range(256)) class MagicDefaultManager(DefaultManager): def __init__(self, env): self.en...
[ "from artichoke import DefaultManager, Config\nfrom artichoke.helpers import read, prompt\nfrom fabric.api import env, task, run\nimport os\n\nchars = ''.join(chr(c) if chr(c).isupper() or chr(c).islower() else '_' for c in range(256))\n\n\nclass MagicDefaultManager(DefaultManager):\n\n def __init__(self, env):\...
true
250
68b967ecf18d576758cf05e889919944cfc34dcd
""" generalised behaviour for actors and vacancies """ from mesa import Agent from random import shuffle import numpy as np class Entity(Agent): """ superclass for vacancy and actor agents not intended to be used on its own, but to inherit its methods to multiple other agents """ def __init__(sel...
[ "\"\"\"\ngeneralised behaviour for actors and vacancies\n\"\"\"\n\nfrom mesa import Agent\nfrom random import shuffle\nimport numpy as np\n\n\nclass Entity(Agent):\n \"\"\"\n superclass for vacancy and actor agents\n not intended to be used on its own, but to inherit its methods to multiple other agents\n ...
false
251
46babde9c26a944c9d29121b6bbf89a32f242a81
import simple_draw as sd import random # sd.resolution = (1400, 900) # Prepare data for the sun function def sun_prepare(xpoint, ypoint, radius, color, angle): delta_list = [] radius_list = [] for delta in range(0, 360, angle): delta_list.append(delta) radius_list.append(random.randint(ra...
[ "import simple_draw as sd\nimport random\n\n\n# sd.resolution = (1400, 900)\n\n# Prepare data for the sun function\ndef sun_prepare(xpoint, ypoint, radius, color, angle):\n delta_list = []\n radius_list = []\n for delta in range(0, 360, angle):\n delta_list.append(delta)\n radius_list.append(...
false
252
e736991f364ba9ff709348e4b1f612b1e9673281
from flask import * app=Flask(__name__) from app import views from app import admin_views from app import usr_reg from app import cookie from app import db_connect
[ "from flask import *\napp=Flask(__name__)\n\nfrom app import views\nfrom app import admin_views\nfrom app import usr_reg\nfrom app import cookie\nfrom app import db_connect", "from flask import *\napp = Flask(__name__)\nfrom app import views\nfrom app import admin_views\nfrom app import usr_reg\nfrom app import c...
false
253
07215403750be53994ae36727b6f790202b88697
# Inspiration: [Fake Album Covers](https://fakealbumcovers.com/) from IPython.display import Image as IPythonImage from PIL import Image from PIL import ImageFont from PIL import ImageDraw import requests from xml.etree import ElementTree as ET def display_cover(top,bottom ): name='album_art_raw.png' alb...
[ "# Inspiration: [Fake Album Covers](https://fakealbumcovers.com/)\nfrom IPython.display import Image as IPythonImage\nfrom PIL import Image\nfrom PIL import ImageFont\nfrom PIL import ImageDraw\n\nimport requests\nfrom xml.etree import ElementTree as ET\n\ndef display_cover(top,bottom ):\n \n name='album_art_...
true
254
18d3f58048b7e5d792eb2494ecc62bb158ac7407
from flask import Flask from flask import render_template from flask import make_response import json from lib import powerswitch app = Flask(__name__) @app.route('/') def hello_world(): return render_template('index.html') @app.route('/on/') def on(): state = powerswitch.on() return json.dumps(state) ...
[ "from flask import Flask\nfrom flask import render_template\nfrom flask import make_response\n\nimport json\n\nfrom lib import powerswitch\n\napp = Flask(__name__)\n\n@app.route('/')\ndef hello_world():\n return render_template('index.html')\n\n@app.route('/on/')\ndef on():\n state = powerswitch.on()\n ret...
false
255
869284fa531a93c1b9812ed90a560d0bb2f87e97
# fonction pour voir quel est le plus grand entre l'energie limite et l'enerve potentiel def ep (m,h,el,g=9.8): E=m*h*g if E<el: print ("le plus grand est : el") else: print ("le plus grand est : E") ep(3,4,5) #fontion fibonaci 0 1 1 2 3 5 8 13 def fibonaci(n): for i in range(0,n,): ...
[ "# fonction pour voir quel est le plus grand entre l'energie limite et l'enerve potentiel\ndef ep (m,h,el,g=9.8):\n E=m*h*g\n if E<el:\n print (\"le plus grand est : el\")\n else:\n print (\"le plus grand est : E\")\n\nep(3,4,5)\n\n#fontion fibonaci 0 1 1 2 3 5 8 13\n\ndef fibonaci(n):\n f...
false
256
d126efa91b964a3a374d546bb860b39ae26dfa22
"""A tiny example binary for the native Python rules of Bazel.""" import unittest from bazel_tutorial.examples.py.lib import GetNumber from bazel_tutorial.examples.py.fibonacci.fib import Fib class TestGetNumber(unittest.TestCase): def test_ok(self): self.assertEqual(GetNumber(), 42) def test_fib(self): ...
[ "\"\"\"A tiny example binary for the native Python rules of Bazel.\"\"\"\n\nimport unittest\nfrom bazel_tutorial.examples.py.lib import GetNumber\nfrom bazel_tutorial.examples.py.fibonacci.fib import Fib\n\n\nclass TestGetNumber(unittest.TestCase):\n\n def test_ok(self):\n self.assertEqual(GetNumber(), 42)\n\n ...
false
257
e582787a912f479830ed99575b2c6adb8088b4e5
from flask import Flask, request from flask import jsonify from preprocessing import QueryProcessor from flask_cors import CORS app = Flask(__name__) CORS(app) qp = QueryProcessor() @app.route('/search_general', methods=['POST']) def query(): message = None searchQuery = request.json['searchQuery'] resul...
[ "from flask import Flask, request\nfrom flask import jsonify\nfrom preprocessing import QueryProcessor\nfrom flask_cors import CORS\n\napp = Flask(__name__)\nCORS(app)\nqp = QueryProcessor()\n\n\n@app.route('/search_general', methods=['POST'])\ndef query():\n message = None\n searchQuery = request.json['searc...
false
258
cf0cf028d5f67e8deca8ebd3ad76d9c1e3563002
#!/usr/bin/python2 import sys import argparse """ This program generates an extract table having the following format: <S1> <S2> <S3> ... <Sn> ||| <T1> <T2> <T3> ... <Tk> ||| 0-0 Each line is a mapping from a source sentence to target sentence with special delimiter characters. You can give the output of this s...
[ "#!/usr/bin/python2\n\nimport sys\nimport argparse\n\n\"\"\"\nThis program generates an extract table having the following format:\n <S1> <S2> <S3> ... <Sn> ||| <T1> <T2> <T3> ... <Tk> ||| 0-0\n\nEach line is a mapping from a source sentence to target sentence\nwith special delimiter characters.\n\nYou can give ...
true
259
f8bf7e2d8f06bbd00f04047153833c07bf483fd3
from django.apps import AppConfig class PyrpgConfig(AppConfig): name = 'PyRPG'
[ "from django.apps import AppConfig\n\n\nclass PyrpgConfig(AppConfig):\n name = 'PyRPG'\n", "<import token>\n\n\nclass PyrpgConfig(AppConfig):\n name = 'PyRPG'\n", "<import token>\n\n\nclass PyrpgConfig(AppConfig):\n <assignment token>\n", "<import token>\n<class token>\n" ]
false
260
48677d73f6489ce789884a9dff5d50c23f47d8b3
__author__ = 'simon.hughes' from sklearn.feature_extraction import DictVectorizer from WindowFeatures import compute_middle_index from collections import Counter class WindowFeatureExtractor(object): """ A simple wrapper class that takes a number of window based feature extractor functions and applies the...
[ "__author__ = 'simon.hughes'\n\nfrom sklearn.feature_extraction import DictVectorizer\nfrom WindowFeatures import compute_middle_index\nfrom collections import Counter\n\nclass WindowFeatureExtractor(object):\n \"\"\"\n A simple wrapper class that takes a number of window based feature extractor\n function...
false
261
65aa85675393efa1a0d8e5bab4b1dbf388018c58
indelCost = 1 swapCost = 13 subCost = 12 noOp = 0 def alignStrings(x,y): nx = len(x) ny = len(y) S = matrix(nx+1, ny+1) #?? for i in range (nx+1) for j in range (ny+1) if i == 0: #if the string is empty S[i][j] = j #this will put all the letters from j in i elif j == 0: #if the second string ...
[ "\nindelCost = 1\nswapCost = 13\nsubCost = 12\nnoOp = 0\n\t\ndef alignStrings(x,y):\n\t\n\tnx = len(x)\n\tny = len(y)\n\tS = matrix(nx+1, ny+1) #?? \n\t\n\tfor i in range (nx+1)\n\t\tfor j in range (ny+1)\n\t\t\tif i == 0:\t#if the string is empty\n\t\t\t\tS[i][j] = j\t\t\t#this will put all the letters from j in i...
true
262
47c1ad4bd1ceffa38eef467ea8eb59dbd2fc2ebb
from packet import Packet from packetConstructor import PacketConstructor import threading import time class PacketSender: """ Packet represents a simulated UDP packet. """ # The next seq num for sent packets seq_num = 0 # The next seq num for acks that we're waiting for next_seq_num = 0 ...
[ "from packet import Packet\nfrom packetConstructor import PacketConstructor\nimport threading\nimport time\n\n\nclass PacketSender:\n \"\"\"\n Packet represents a simulated UDP packet.\n \"\"\"\n # The next seq num for sent packets\n seq_num = 0\n # The next seq num for acks that we're waiting for...
false
263
24cdbbadc8ff1c7ad5d42eeb518cb6c2b34724a2
from openfermion import QubitOperator, FermionOperator from openfermion.transforms import jordan_wigner from src.utils import QasmUtils, MatrixUtils from src.ansatz_elements import AnsatzElement, DoubleExchange import itertools import numpy class EfficientDoubleExchange(AnsatzElement): def __init__(self, qubit_...
[ "from openfermion import QubitOperator, FermionOperator\nfrom openfermion.transforms import jordan_wigner\n\nfrom src.utils import QasmUtils, MatrixUtils\nfrom src.ansatz_elements import AnsatzElement, DoubleExchange\n\nimport itertools\nimport numpy\n\n\nclass EfficientDoubleExchange(AnsatzElement):\n def __ini...
false
264
2843845848747c723d670cd3a5fcb7127153ac7e
from flask import Flask from sim.toggle import ToggleSensor from sim.sensor import Sensor app = Flask(__name__) sensors = [ ToggleSensor(id="s-01", description="lampadina"), ToggleSensor(id="s-02", description="lampadina"), ToggleSensor(id="s-03", description="allarme atomico"), ToggleSensor(id="s-04...
[ "from flask import Flask\n\nfrom sim.toggle import ToggleSensor\nfrom sim.sensor import Sensor\n\napp = Flask(__name__)\n\nsensors = [\n ToggleSensor(id=\"s-01\", description=\"lampadina\"),\n ToggleSensor(id=\"s-02\", description=\"lampadina\"),\n ToggleSensor(id=\"s-03\", description=\"allarme atomico\")...
false
265
f5bd41f4aaff616a332d80ec44c364ffc91c58f0
# %load q03_skewness_log/build.py from scipy.stats import skew import pandas as pd import numpy as np data = pd.read_csv('data/train.csv') # Write code here: def skewness_log(df): df['SalePrice_New'] = np.log(df['SalePrice']) df['GrLivArea_New'] = np.log(df['GrLivArea']) skewed_slPri = skew(df['SalePrice...
[ "# %load q03_skewness_log/build.py\nfrom scipy.stats import skew\nimport pandas as pd\nimport numpy as np\n\ndata = pd.read_csv('data/train.csv')\n\n\n# Write code here:\ndef skewness_log(df):\n df['SalePrice_New'] = np.log(df['SalePrice'])\n df['GrLivArea_New'] = np.log(df['GrLivArea'])\n skewed_slPri = s...
false
266
d65f858c3ad06226b83d2627f6d38e03eae5b36c
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Phase transition module """ import utils import datetime import itertools import numpy as np import recovery as rec import sampling as smp import graphs_signals as gs import pathos.multiprocessing as mp from tqdm import tqdm ## MAIN FUNCTIONS ## def grid_evalua...
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"Phase transition module\n\n\"\"\"\n\n\nimport utils\nimport datetime\nimport itertools\n\nimport numpy as np\nimport recovery as rec\nimport sampling as smp\nimport graphs_signals as gs\nimport pathos.multiprocessing as mp\n\nfrom tqdm import tqdm\n\n\n## MA...
false
267
f97a892e6e0aa258ad917c4a73a66e89b0dc3253
# coding: utf-8 # In[1]: import sys sys.path.extend(['detection', 'train']) # from detection folder from MtcnnDetector import MtcnnDetector from detector import Detector from fcn_detector import FcnDetector # from train folder from model_factory import P_Net, R_Net, O_Net import config as config from preprocess.uti...
[ "\n# coding: utf-8\n\n# In[1]:\nimport sys\nsys.path.extend(['detection', 'train'])\n\n# from detection folder\nfrom MtcnnDetector import MtcnnDetector\nfrom detector import Detector\nfrom fcn_detector import FcnDetector\n\n# from train folder\nfrom model_factory import P_Net, R_Net, O_Net\nimport config as config\...
false
268
f19d8aa2104240cc93a0146f1b14c635e7cd3a41
#! /usr/bin/env python import ldac from numpy import * import shearprofile as sp import sys import os, subprocess import pylab if len(sys.argv) != 6: sys.stderr.write("wrong number of arguments!\n") sys.exit(1) catfile= sys.argv[1] clusterz=float(sys.argv[2]) center= map(float,sys.argv[3].split(',')) pixsc...
[ "#! /usr/bin/env python\n\nimport ldac\nfrom numpy import *\nimport shearprofile as sp\nimport sys\nimport os, subprocess\n\nimport pylab\n\n\nif len(sys.argv) != 6:\n sys.stderr.write(\"wrong number of arguments!\\n\")\n sys.exit(1)\ncatfile= sys.argv[1]\nclusterz=float(sys.argv[2])\ncenter= map(float,sys.a...
true
269
0e58834120c34b5152026bde6d089be19244e21a
import os from MdApi import MdApi class Adapter(MdApi): def __init__(self): super(Adapter, self).__init__() def connect(self): self.createFtdcMdApi(os.getcwd()) self.registerFront('tcp://180.168.146.187:10010') def onFrontConnected(self): print 'front succ...
[ "import os\n\nfrom MdApi import MdApi\n\nclass Adapter(MdApi):\n\n def __init__(self):\n \n super(Adapter, self).__init__()\n\n\n def connect(self):\n\n\n self.createFtdcMdApi(os.getcwd())\n\n self.registerFront('tcp://180.168.146.187:10010')\n\n\n def onFrontConnected(self):\n\...
true
270
df40b0628d6a180a98cd385145ee7c65ecb78256
import os import tensorflow as tf import torch from tqdm import tqdm from glob import glob import numpy as np from collections.abc import Iterable from utils.hparams import HParam #from utils.audio import Audio #import librosa #python encoder_inference.py --in_dir training_libri_mel/train/ --gpu_str 5 #python tfrecord...
[ "import os\nimport tensorflow as tf\nimport torch\nfrom tqdm import tqdm\nfrom glob import glob\nimport numpy as np\nfrom collections.abc import Iterable\nfrom utils.hparams import HParam\n#from utils.audio import Audio\n#import librosa\n\n#python encoder_inference.py --in_dir training_libri_mel/train/ --gpu_str 5\...
false
271
ed7b29a4d7f3a48884434373418c3528f2f397ac
#!/usr/bin/python3 import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2' os.environ['KERAS_BACKEND'] = 'tensorflow' import numpy as np import sys from util import load_model from keras.preprocessing.text import hashing_trick from keras.preprocessing.sequence import pad_sequences from southpar...
[ "#!/usr/bin/python3\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'\nos.environ['KERAS_BACKEND'] = 'tensorflow'\n\nimport numpy as np\nimport sys\n\nfrom util import load_model\nfrom keras.preprocessing.text import hashing_trick\nfrom keras.preprocessing.sequence import pad_sequences...
false
272
b6d8a918659f733919fe3bb4be9037e36ad32386
import queue import sys import logging from superai.common import InitLog logger = logging.getLogger(__name__) # 2维到1维 def hwToidx(x: int, y: int, weight: int): return y * weight + x # 1维到2维 def idxTohw(idx, weight: int): return [idx % weight, idx // weight] # 10x10 cell idx 到 [x,y] def idxToXY(idx, cel...
[ "import queue\nimport sys\nimport logging\n\nfrom superai.common import InitLog\n\nlogger = logging.getLogger(__name__)\n\n\n# 2维到1维\ndef hwToidx(x: int, y: int, weight: int):\n return y * weight + x\n\n\n# 1维到2维\ndef idxTohw(idx, weight: int):\n return [idx % weight, idx // weight]\n\n\n# 10x10 cell idx 到 [x...
false
273
7930bb813bd546747c7c65b661900939f5ba93f1
user_input = input() #abv>1>1>2>2asdasd exploded_str = user_input for n in range(len(user_input)): explosion_strength = 0 if user_input[n] == ">": explosion_strength += int(user_input[n+1]) if user_input[n+explosion_strength] != ">": exploded_str = user_input[:n] + user_input[n+ex...
[ "user_input = input() #abv>1>1>2>2asdasd\nexploded_str = user_input\n\nfor n in range(len(user_input)):\n explosion_strength = 0\n if user_input[n] == \">\":\n explosion_strength += int(user_input[n+1])\n if user_input[n+explosion_strength] != \">\":\n exploded_str = user_input[:n] ...
false
274
c6cf085330f47ffb139c5acc91d91e9758f5396a
from page_objects import PageObject, PageElement class MainPage(PageObject): level_menu_opened = False level_menu_created = False css_input = PageElement(css='input.input-strobe') level_text_span = PageElement(css='span.level-text') instruction_h2 = PageElement(css='h2.order') enter_button = P...
[ "from page_objects import PageObject, PageElement\n\n\nclass MainPage(PageObject):\n level_menu_opened = False\n level_menu_created = False\n css_input = PageElement(css='input.input-strobe')\n level_text_span = PageElement(css='span.level-text')\n instruction_h2 = PageElement(css='h2.order')\n en...
false
275
c2ddf31bce4a5f3ae2b0d5455bbc9942f92bff40
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' from keras.models import load_model from utils import resize_to_fit, clear_chunks, stack_windows from imutils import paths import numpy as np import imutils import cv2 as cv2 import pickle from tqdm import tqdm c1_correct = 0 c2_correct = 0 c3_correct = 0 c4_correct ...
[ "import os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nfrom keras.models import load_model\nfrom utils import resize_to_fit, clear_chunks, stack_windows\nfrom imutils import paths\nimport numpy as np\nimport imutils\nimport cv2 as cv2\nimport pickle\nfrom tqdm import tqdm\n\nc1_correct = 0\nc2_correct = 0\nc3_corr...
false
276
75e6554ea3c327c87a2a65710a7f1d55e9933bb0
# Author: BeiYu # Github: https://github.com/beiyuouo # Date : 2021/2/21 21:57 # Description: __author__ = "BeiYu" from utils.init_env import set_seed from utils.options import * import os import logging import torch from torch import nn from torch import optim from torch.optim.lr_scheduler import MultiStepLR from ...
[ "# Author: BeiYu\n# Github: https://github.com/beiyuouo\n# Date : 2021/2/21 21:57\n# Description:\n\n__author__ = \"BeiYu\"\n\nfrom utils.init_env import set_seed\nfrom utils.options import *\n\nimport os\nimport logging\nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torch.optim.lr_scheduler im...
false
277
58f3b8c5470c765c81f27d39d9c28751a8c2b719
"""Ex026 Faça um programa que leia uma frase pelo teclado e mostre: Quantas vezes aparece a letra "A". Em que posição ela aparece a primeira vez. Em que posição ela aparece pela última vez.""" frase = str(input('Digite uma frase: ')).strip().lower() n_a = frase.count('a') f_a = frase.find('a')+1 l_a= frase.rfind('a')-1...
[ "\"\"\"Ex026 Faça um programa que leia uma frase pelo teclado e mostre:\nQuantas vezes aparece a letra \"A\".\nEm que posição ela aparece a primeira vez.\nEm que posição ela aparece pela última vez.\"\"\"\nfrase = str(input('Digite uma frase: ')).strip().lower()\nn_a = frase.count('a')\nf_a = frase.find('a')+1\nl_a...
false
278
d83f2d9bb25a46bc7344b420ce65bf729165e6b9
from django.apps import AppConfig class FosAppConfig(AppConfig): name = 'fos_app'
[ "from django.apps import AppConfig\r\n\r\n\r\nclass FosAppConfig(AppConfig):\r\n name = 'fos_app'\r\n", "from django.apps import AppConfig\n\n\nclass FosAppConfig(AppConfig):\n name = 'fos_app'\n", "<import token>\n\n\nclass FosAppConfig(AppConfig):\n name = 'fos_app'\n", "<import token>\n\n\nclass F...
false
279
d2b05c5653ca6c6b7219f6c0393e81c9425b5977
""" HLS: Check if Twin Granule Exists """ from typing import Dict import os import re import boto3 from botocore.errorfactory import ClientError from datetime import date s3 = boto3.client("s3") bucket = os.getenv("SENTINEL_INPUT_BUCKET", None) print(bucket) if bucket is None: raise Exception("No Input Bucket set"...
[ "\"\"\"\nHLS: Check if Twin Granule Exists\n\"\"\"\nfrom typing import Dict\nimport os\nimport re\nimport boto3\nfrom botocore.errorfactory import ClientError\nfrom datetime import date\n\ns3 = boto3.client(\"s3\")\nbucket = os.getenv(\"SENTINEL_INPUT_BUCKET\", None)\nprint(bucket)\nif bucket is None:\n raise Ex...
false
280
c73a199d1c1c1867f3d53ceebf614bc9b65c0d5e
from django.contrib import admin from ticket.models import Ticket, UserTicket, AuxiliaryTicket @admin.register(Ticket) class TicketAdmin(admin.ModelAdmin): pass @admin.register(AuxiliaryTicket) class AuxiliaryTicketAdmin(admin.ModelAdmin): pass @admin.register(UserTicket) class UserTicketAdmin(admin.Mode...
[ "from django.contrib import admin\n\nfrom ticket.models import Ticket, UserTicket, AuxiliaryTicket\n\n\n@admin.register(Ticket)\nclass TicketAdmin(admin.ModelAdmin):\n pass\n\n\n@admin.register(AuxiliaryTicket)\nclass AuxiliaryTicketAdmin(admin.ModelAdmin):\n pass\n\n\n@admin.register(UserTicket)\nclass UserT...
false
281
e564e0d05c3c0e60f356422722803df510d9dd0b
import numpy as np import pandas as pd from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report from sklearn.metrics import precision_score, recall_score, f1_score from scipy.optimize import fsolve import numba from numba import njit,jit # @jit(parallel = True) def conventional_tes...
[ "import numpy as np\nimport pandas as pd\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import precision_score, recall_score, f1_score\nfrom scipy.optimize import fsolve\nimport numba\nfrom numba import njit,jit\n#\n@jit(parallel = True)\ndef c...
false
282
9bc13c608c079cbf23ed04f29edd1fd836214cde
from rest_framework import viewsets, mixins from .models import Comment, Post from .serializer import CommentSerializer, PostSerializer, AllCommentSerializer class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() class CommentViewSet(viewsets.GenericViewSet...
[ "from rest_framework import viewsets, mixins\nfrom .models import Comment, Post\nfrom .serializer import CommentSerializer, PostSerializer, AllCommentSerializer\n\n\nclass PostViewSet(viewsets.ModelViewSet):\n serializer_class = PostSerializer\n queryset = Post.objects.all()\n\n\nclass CommentViewSet(viewsets...
false
283
b11e2837d3ba9c14770b8039186a2175adc41ea1
from .server import CanvasServer try: from .jupyter import JupyterCanvas, create_jupyter_canvas HAS_JUPYTER = True except: HAS_JUPYTER = False JupyterCanvas = None # type: ignore def http_server( file: str = None, host: str = "localhost", port: int = 5050 ) -> CanvasServer: """Creates a new...
[ "from .server import CanvasServer\n\ntry:\n from .jupyter import JupyterCanvas, create_jupyter_canvas\n\n HAS_JUPYTER = True\nexcept:\n HAS_JUPYTER = False\n JupyterCanvas = None # type: ignore\n\n\ndef http_server(\n file: str = None, host: str = \"localhost\", port: int = 5050\n) -> CanvasServer:\...
false
284
2da7892722afde5a6f87e3bd6d5763c895ac96c9
import json import os import ipdb from tqdm import tqdm import argparse from os import listdir from os.path import isfile, join import pickle import joblib from collections import Counter from shutil import copyfile import networkx as nx import spacy import nltk import numpy as np nltk.download('stopwords') nltk_stopw...
[ "import json\nimport os\nimport ipdb\nfrom tqdm import tqdm\nimport argparse\nfrom os import listdir\nfrom os.path import isfile, join\nimport pickle\nimport joblib\nfrom collections import Counter\nfrom shutil import copyfile\nimport networkx as nx\nimport spacy\nimport nltk\nimport numpy as np\n\nnltk.download('s...
false
285
e38ae7f91deed1be00e60b7516210ea1feefe23e
import sys import os from configparser import ConfigParser import logging from mod_argparse import setup_cli from checkers.IndexFile import DocumentIndex, ProgressNoteIndex from checkers import source_files from utilities import write_to_file, strip # , write_to_db_isok # import pandas as pd logger = logging.getLogger...
[ "import sys\nimport os\nfrom configparser import ConfigParser\nimport logging\nfrom mod_argparse import setup_cli\nfrom checkers.IndexFile import DocumentIndex, ProgressNoteIndex\nfrom checkers import source_files\nfrom utilities import write_to_file, strip # , write_to_db_isok\n# import pandas as pd\n\nlogger = lo...
false
286
069338b188f3cf16357b2502cbb3130b69918bd9
from .cli import cli if __name__ == "__main__": exit(cli.main(prog_name="htmap"))
[ "from .cli import cli\n\nif __name__ == \"__main__\":\n exit(cli.main(prog_name=\"htmap\"))\n", "from .cli import cli\nif __name__ == '__main__':\n exit(cli.main(prog_name='htmap'))\n", "<import token>\nif __name__ == '__main__':\n exit(cli.main(prog_name='htmap'))\n", "<import token>\n<code token>\n...
false
287
b52269237d66ea50c453395b9536f25f1310bf2e
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import re from blessings import Terminal from validate_email import validate_email import requests import sys _site_ = sys.argv[1] _saida_ = sys.argv[2] _file_ = open(_saida_, "w") t = Terminal() r = requests.get(_site_, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6....
[ "#!/usr/bin/env python2.7\n# -*- coding: utf-8 -*-\nimport re\nfrom blessings import Terminal\nfrom validate_email import validate_email\nimport requests\nimport sys\n_site_ = sys.argv[1]\n_saida_ = sys.argv[2]\n_file_ = open(_saida_, \"w\")\nt = Terminal()\nr = requests.get(_site_, headers={'User-Agent': 'Mozilla/...
true
288
8c539dbbb762717393b9a71ddca8eb3872890854
import re import os import pandas as pd instruments_file = os.path.abspath("instruments.csv") input_names_file = os.path.abspath("names.txt") output_names_file = os.path.abspath("names.csv") inst_name_file = os.path.abspath("name_instrument.csv") reg_ex = '; |, |\\*|\n' name_header = ["first_name", "last_name"] def ...
[ "import re\nimport os\nimport pandas as pd\n\ninstruments_file = os.path.abspath(\"instruments.csv\")\ninput_names_file = os.path.abspath(\"names.txt\")\noutput_names_file = os.path.abspath(\"names.csv\")\ninst_name_file = os.path.abspath(\"name_instrument.csv\")\nreg_ex = '; |, |\\\\*|\\n'\nname_header = [\"first_...
false
289
0db0daf9bea254cffaec1280cd13b2d70368cd94
import numpy.random as rnd import numpy as np B=100000 N1=50 N2=50 p1mle=0.3 p2mle=0.4 taumle=p2mle-p1mle estimate=[] for i in range(B): p1=0.0 for j in range(N1): if(rnd.uniform(0,1)<p1mle): p1+=1 p1/=N1 p2=0.0 for j in range(N2): if(rnd.uniform(0,1)<p2mle): p2+=1 p2/=N2 estimate.append(p2-p...
[ "import numpy.random as rnd\nimport numpy as np\n\nB=100000\nN1=50\nN2=50\n\np1mle=0.3\t\np2mle=0.4\ntaumle=p2mle-p1mle\n\nestimate=[]\n\nfor i in range(B):\n\n\tp1=0.0\n\tfor j in range(N1):\n\t\tif(rnd.uniform(0,1)<p1mle):\n\t\t\tp1+=1\n\n\tp1/=N1\n\n\tp2=0.0\n\tfor j in range(N2):\n\t\tif(rnd.uniform(0,1)<p2mle)...
false
290
a90b7e44cc54d4f96a13e5e6e2d15b632d3c4983
import random import string import steembase import struct import steem from time import sleep from time import time from steem.transactionbuilder import TransactionBuilder from steembase import operations from steembase.transactions import SignedTransaction from resultthread import MyThread from charm.toolbox.pairingg...
[ "import random\nimport string\nimport steembase\nimport struct\nimport steem\nfrom time import sleep\nfrom time import time\nfrom steem.transactionbuilder import TransactionBuilder\nfrom steembase import operations\nfrom steembase.transactions import SignedTransaction\nfrom resultthread import MyThread\nfrom charm....
false
291
ee80169afd4741854eff8619822a857bbf757575
''' Created on 27 Mar 2015 @author: Jon ''' import matplotlib.pyplot as plt from numerical_functions import Timer import numerical_functions.numba_funcs.indexing as indexing import numpy as np import unittest class Test(unittest.TestCase): def test_take(self): x = np.linspace( 0, 100 ) ...
[ "'''\nCreated on 27 Mar 2015\n\n@author: Jon\n'''\n\nimport matplotlib.pyplot as plt\nfrom numerical_functions import Timer\nimport numerical_functions.numba_funcs.indexing as indexing\nimport numpy as np\nimport unittest\n\n\nclass Test(unittest.TestCase):\n \n def test_take(self):\n x = np.linspa...
false
292
ce6dba2f682b091249f3bbf362bead4b95fee1f4
""" .. currentmodule:: jotting .. automodule:: jotting.book :members: .. automodule:: jotting.to :members: .. automodule:: jotting.read :members: .. automodule:: jotting.style :members: """ from .book import book from . import style, to, read, dist
[ "\"\"\"\n.. currentmodule:: jotting\n\n.. automodule:: jotting.book\n :members:\n\n.. automodule:: jotting.to\n :members:\n\n.. automodule:: jotting.read\n :members:\n\n.. automodule:: jotting.style\n :members:\n\"\"\"\n\n\nfrom .book import book\nfrom . import style, to, read, dist\n", "<docstring to...
false
293
99c839eddcbe985c81e709878d03c59e3be3c909
#coding=utf-8 ######################################### # dbscan: # 用法说明:读取文件 # 生成路径文件及簇文件,输出分类准确率 ######################################### from matplotlib.pyplot import * import matplotlib.pyplot as plt from collections import defaultdict import random from math import * import numpy import datetime ...
[ "#coding=utf-8\n######################################### \n# dbscan: \n# 用法说明:读取文件\n# 生成路径文件及簇文件,输出分类准确率 \n######################################### \n\n\nfrom matplotlib.pyplot import *\nimport matplotlib.pyplot as plt\nfrom collections import defaultdict \nimport random\nfrom math import *\nimport nump...
true
294
bf8bbeb408cb75af314ef9f3907456036e731c0b
def solution(S): # write your code in Python 3.6 # Definitions log_sep = ',' num_sep = '-' time_sep = ':' # Initialization from collections import defaultdict # defaultdict initialize missing key to default value -> 0 bill = defaultdict(int) total = defaultdict(int) calls = S...
[ "def solution(S):\n # write your code in Python 3.6\n # Definitions\n log_sep = ','\n num_sep = '-'\n time_sep = ':'\n # Initialization\n from collections import defaultdict\n # defaultdict initialize missing key to default value -> 0\n bill = defaultdict(int)\n total = defaultdict(int...
false
295
35ae9c86594b50bbe4a67d2cc6b20efc6f6fdc64
#配置我们文件所在目录的搜寻环境 import os,sys #第一步先拿到当前文件的路径 file_path = os.path.abspath(__file__) #第二步 根据这个路径去拿到这个文件所在目录的路径 dir_path = os.path.dirname(file_path) #第三步:讲这个目录的路径添加到我们的搜寻环境当中 sys.path.append(dir_path) #第四步,动态设置我们的setting文件 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "gulishop.settings") #第五步,让设置好的环境初始化生效 ...
[ "#配置我们文件所在目录的搜寻环境\r\nimport os,sys\r\n#第一步先拿到当前文件的路径\r\nfile_path = os.path.abspath(__file__)\r\n#第二步 根据这个路径去拿到这个文件所在目录的路径\r\ndir_path = os.path.dirname(file_path)\r\n#第三步:讲这个目录的路径添加到我们的搜寻环境当中\r\nsys.path.append(dir_path)\r\n#第四步,动态设置我们的setting文件\r\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"gulishop.setti...
false
296
d34159536e860719094a36cfc30ffb5fcae72a9a
#API End Points by Mitul import urllib.error, urllib.request, urllib.parse import json target = 'http://py4e-data.dr-chuck.net/json?' local = input('Enter location: ') url = target + urllib.parse.urlencode({'address': local, 'key' : 42}) print('Retriving', url) data = urllib.request.urlopen(url).read() print('Retrive...
[ "#API End Points by Mitul\nimport urllib.error, urllib.request, urllib.parse\nimport json\n\ntarget = 'http://py4e-data.dr-chuck.net/json?'\nlocal = input('Enter location: ')\nurl = target + urllib.parse.urlencode({'address': local, 'key' : 42})\n\nprint('Retriving', url)\ndata = urllib.request.urlopen(url).read()\...
false
297
c382b298cce8d7045d6ce8a84f90b3800dba7717
# Generated by Django 3.0.7 on 2020-06-15 15:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0003_auto_20200615_1225'), ] operations = [ migrations.AlterField( model_name='product', name='harmoniza...
[ "# Generated by Django 3.0.7 on 2020-06-15 15:26\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('products', '0003_auto_20200615_1225'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='product',\n ...
false
298
3372d98ff91d90558a87293d4032820b1662d60b
from django.conf.urls import patterns, url from riskDashboard2 import views urlpatterns = patterns('', #url(r'getdata', views.vulnData, name='getdata'), url(r'appmanagement', views.appmanagement, name='appmanagement'), url(r'^.*', views.index, name='index'), )
[ "from django.conf.urls import patterns, url\n\nfrom riskDashboard2 import views\n\nurlpatterns = patterns('',\n #url(r'getdata', views.vulnData, name='getdata'),\n url(r'appmanagement', views.appmanagement, name='appmanagement'),\n url(r'^.*', views.index, name='index'),\n)\n", "from django.conf.urls imp...
false
299
0465e33d65c2ce47ebffeec38db6908826bf4934
people = 20 cats = 30 dogs = 15 if people < cats: print("Too many cats") elif people > cats: print("Not many cats") else: print("we cannnot decide")
[ "people = 20\ncats = 30\ndogs = 15\n\nif people < cats:\n print(\"Too many cats\")\nelif people > cats:\n print(\"Not many cats\")\nelse:\n print(\"we cannnot decide\")", "people = 20\ncats = 30\ndogs = 15\nif people < cats:\n print('Too many cats')\nelif people > cats:\n print('Not many cats')\nel...
false