index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
1,500 | 6960fc6d949512ffc783b085041f86cb791160a3 | import tornado
import copy
class DjangoHandler(tornado.web.RequestHandler):
async def reroute(self):
http = tornado.httpclient.AsyncHTTPClient()
new_request = copy.deepcopy(self.request)
url_obj = copy.urlparse(new_request.url)
new_request.url = f"{url_obj.scheme}://localhost:9000... |
1,501 | 7ad5e803afa42790e878bfb923eddcfde2d21928 |
env = 'DEV' ## this had to be in uppercase
platform = 'hive'
from datahub.emitter.kafka_emitter import DatahubKafkaEmitter, KafkaEmitterConfig
from datahub.emitter.rest_emitter import DatahubRestEmitter
from datahub.ingestion.extractor.schema_util import *
from datahub.metadata.schema_classes import (
DatasetSn... |
1,502 | 6239cb08509b8e84a88db95479af05845876d9b6 | # Generated by Django 3.1.6 on 2021-02-15 12:13
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Book',
fields=[
... |
1,503 | 99ddc00bf1d0141118748aa98bcc3e7b8a0ff29e | # Generic function for updating Weblogic system resources
def update_system_resources(clusterName):
print "Cluster name is " + clusterName
startTransaction()
create_JMSSystemResource("/", "DummyJMSModule")
delete_JMSModule("/JMSSystemResources", "DummyJMSModule")
endTransaction()
print "update_s... |
1,504 | 69eb62ba47a63cf007334c777709b0513d75f396 | """
Looks up values in createresistorvaluesdbm.py.
Outputs string value ( cmd ).
"""
import dbm
# Open a DB. The c option opens in read/write mode and creates the file if needed.
db = dbm.open( 'resistorvalues', 'c' )
with open( "dummyoutput.txt", "r" ) as file_object:
#print (file_object.readli... |
1,505 | e36d2426fb8a268ab9ff4f3d6135aa72697e6326 | #%%
import numpy as np
import cv2
import matplotlib.pyplot as plt
import win32gui,win32ui,win32con,win32api
import pyautogui as pg
from PIL import ImageGrab
import time
import pandas as pd
# %%
def get_window(lpClassName='UnityWndClass', lpWindowName='炉石传说'):
handle_of_hearthstone=win32gui.FindWindow(... |
1,506 | d8fb5aeb5453b986cc698165749992e4a7677257 | from datetime import datetime
from logging import Logger
from pathlib import Path
from typing import Dict
import ignite
import ignite.distributed as idist
import torch
from omegaconf import OmegaConf
from config_schema import ConfigSchema
def log_metrics(
logger: Logger, epoch: int, elapsed: float, tag: str, me... |
1,507 | 0baa133bd9eb8a162a82b23ba4d26cdd34f701c4 | from flask import url_for
from bs4 import BeautifulSoup
from unittest.mock import ANY
import app
from app.notify_client.models import InvitedUser
from tests.conftest import sample_invite as create_sample_invite
from tests.conftest import mock_check_invite_token as mock_check_token_invite
def test_existing_user_acce... |
1,508 | 319af5232c043d77a9d63ab1efa62d857da6db23 | import matplotlib
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox
from matplotlib.path import Path
import json
def cLineGraph(j_file):
data = []
with open(j_file) as f:
for line in f:
data.append(json.loads(line))
data = data[0]
in_other = 0
in_picture =... |
1,509 | 4d87c3f70809bbd488159f0b55131af903c7e7b4 | print ("hello guys")
print ("hello everyone") |
1,510 | 71f9d9d7973809654db3ea613073f2d431f2d65f | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from datetime import datetime
try:
from unittest.mock import patch
except ImportError:
from mock import patch
import pytest
from django.test import TestCase
try:
from django.test import override_settings
except ImportError:
... |
1,511 | 05bd95966d72dd40b9b828932b0bf70e40ddb573 | '''
Created on 14 november 2015
@author: federico
'''
import paho.mqtt.client as mosquitto
import json
import urllib,urllib2
import datetime
import threading
import time
from pygame import mixer
from datetime import timedelta
#ALARM SOUND PATH
alarm_path="/home/pi/SmartBed/Smart_Bed/src/Rooster.wav"
#DWEET&FREEBOA... |
1,512 | 076d9f0c14a8070993039bbda2ffe4d52c8d2273 | # -*- coding: utf-8 -*-
"""
CST 383, measles simulation homework
# Here's a question. Suppose 1% of people have measles, that the
# test for measles if 98% accurate if you do have measles, and 98%
# accurate if you don't have measles. Then what is the probability
# that you have measles, given that you have... |
1,513 | c23bd136991bfb41f153321420c2fcfba0c843f4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, pickle, json, ast
import pandas as pd
from scipy import spatial
import numpy as np
from scipy import stats
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.svm import LinearSVC
from sklearn.metrics import preci... |
1,514 | 9fa534664056a8cf9e9a64ccc7d6dd4de2ec0936 | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditio... |
1,515 | e07bd4cd13209bff8bc1119a619a2954abd52592 | import time
class SequenceHeuristic(object):
def __init__(self, minChanges, minDuration, noMotionDelay):
self._minChanges = minChanges
self._minDuration = minDuration
self._noMotionDelay = noMotionDelay
self._duration = 0
def isValid(self, image, data):
numOfChanges... |
1,516 | 8e8c72362dfb1587150aadaa6b8a0aeb77c3641a | # Generated by Django 3.0.1 on 2020-01-11 09:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0005_auto_20200111_1513'),
]
operations = [
migrations.AlterField(
model_name='post',
name='photo',
... |
1,517 | b7007778ea9dfac3af8c31d66d32d8157dc0d69b | # -*- coding:utf-8 -*-
import os
import numpy as np
import tensorflow as tf
from translate import datautil
import seq2seq_model
_buckets = []
convo_hist_limit = 1
max_source_length = 1
max_target_length = 2
flags = tf.app.flags
FLAGS = flags.FLAGS
tf.reset_default_graph
max_train_data_size = 0
data_dir = 'datacn... |
1,518 | 943e8be7a9ee4e494c0a42e1368555f3df3de897 | import pathlib, random, cv2
import tensorflow as tf
import numpy as np
import tensorflow.keras.backend as K
import albumentations as A
from matplotlib import pyplot as plt
from functools import partial
from sklearn.model_selection import train_test_split
# GPU setup
gpus = tf.config.experimental.list_physical_devices(... |
1,519 | a238175c94764137bfc8fac1ce67436016b1591a | from django.contrib import admin
from orders.models import OrderModel
@admin.register(OrderModel)
class OrderAdmin(admin.ModelAdmin):
list_display = ['first_name', 'phone']
|
1,520 | 00531c5a7fdcd24204b0546c081bbe7d63d0a6b2 | # Create a program that will ask the users name, age, and reddit username.
# Have it tell them the information back, in the format:
#
# Your name is (blank), you are (blank) years old, and your username is (blank)
#
# For extra credit, have the program log this information in a file to be accessed later.
#
name = ... |
1,521 | 3024359710148bfbb15677973555f214b1f878b7 | from sklearn import svm, metrics, tree
from sklearn.ensemble import AdaBoostClassifier
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
my_data = np.loadtxt('edited_data/dataset_regression_edited.csv',delimiter=',', dtype='str')
training_data = my_data[:, 0:6]
validation_data = my_data[:, 6]
... |
1,522 | 20fe9b68e65f6f017897bfa8e99d0c21ba1617fb | print(input()in[str(i**i+i)for i in range(11)])
num = int(input())
suma = 0
x = 0
while(suma < num):
x += 1
suma = x**x + x
print(True if suma == num else False
|
1,523 | cf2bbe332237bd849df62be099f1719eaf1f2082 | import pyglet
import math
from lvl1_resources import fireball
class Fire(pyglet.sprite.Sprite):
def __init__( self, *args, **kwargs):
super(Fire, self).__init__(img= fireball, *args, **kwargs)
self.rotation= 45
self.rotate_speed= 5
self.velocity_x= 5
def check_bounds(self):
max_x= 1000 + self.image.width/... |
1,524 | 94f5fa411f8a41985caaf4eb7ab1cb4e45439405 | import abc
try:
import cPickle as pickle
except ImportError:
import pickle
from typing import *
T = TypeVar('T')
class BaseSerializer(Generic[T]):
"""
The serializer is responsible for converting complex python data types
into primitive types that can be sent over zmq ports via msgpack.
""... |
1,525 | 1a05817c4c16f2d9234e504b0c98f9c9ae2dc3f7 | #coding=utf-8
from django import template
from classytags.helpers import InclusionTag
from classytags.core import Tag, Options
from classytags.arguments import Argument
from ratings.models import RatedItem
from blogs.permissions import Permissions
class RatingBlock(InclusionTag):
name = 'rating'
template = '... |
1,526 | 9206e4c4eff8ca64266ce53705e88069912b80d8 | """
Process pair-end reads of barcode-guide-donor Step 1 cassette to generate a library reference table mapping barcodes to features.
Create dictionaries mapping barcodes to forward and reverse reads, split into sub-segments.
R1_dict: map barcodes to corresponding R1 sequences.
R2_dict: map barcodes to corresponding R... |
1,527 | 957db647500433fd73723fdeb3933037ba0641b1 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-01-26 05:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Discou... |
1,528 | 2d36ae916ad257615016ed6c0bc67e506ee313c9 | """
Authentication views.
login()
Flask view to log a user in.
"""
import functools
from typing import Any, Callable, cast, Dict
from flask import Blueprint, make_response, request, session
from werkzeug.security import check_password_hash as _check_password_hash
from .accesscontrol import PERMISSIONS
from .api... |
1,529 | 42be9077ec51a9be1d4923011a38cd64d829f876 | from selenium import webdriver
import time
with webdriver.Chrome() as browser:
browser.get("http://suninjuly.github.io/selects1.html")
time.sleep(1)
x = int(browser.find_element_by_id("num1").text)
y = int(browser.find_element_by_id("num2").text)
sum_xy = str(int(x)+int(y))
browser.find_element... |
1,530 | 4d35bb83378805daf4392a1752386ab1403404e0 | # Lists are sequence of objects
# Mutable
# Lists are represented within square brackets and items are seperated by commas
#-----------------------------------Lists-----------------------------------#
# Lists of Numbers
print("\n1. Lists of Numbers")
print("\t" + str([1,2,3]))
# Lists of Strings
print("\n2. Lists of ... |
1,531 | bbd50c40bc0897fe7a93f277bcfdcba3ba6d6f2a | # -*- coding: utf-8 -*-
import sys
import yaml
def add_sub_path(yaml_path):
file = open(yaml_path, "r", encoding="utf-8")
file_data = file.read()
file.close()
data = yaml.safe_load(file_data)
for p, p_info in data.get("paths", {}).items():
for method, m_info in p_info.items():
... |
1,532 | af40239551709eff02b8a1f034583ab80845d1d7 | import numpy as np
N, M = (int(x) for x in input().split())
x, y, z = np.zeros(N, dtype=int), np.zeros(N, dtype=int), np.zeros(N, dtype=int)
for i in range(N):
x[i], y[i], z[i] = (int(x) for x in input().split())
temp = []
for sx in (-1, 1):
for sy in (-1, 1):
for sz in (-1, 1):
_x, _y, _z =... |
1,533 | 0dad1937df39c012f7991c3897f27964bed1d5a0 | import numpy as np
from sklearn import model_selection
from iterstrat.ml_stratifiers import MultilabelStratifiedKFold
"""
- binary cross-validate
- multi-class cross-validate
- multi-label cross-validate
- holdout
- regression
"""
class CrossValidate(object):
def __init__(self, df,
target_cols... |
1,534 | 9c2cc5b993f020b8a1c96ea4cd5c2fb2da44a251 | from __future__ import absolute_import, division, print_function, unicode_literals
import os
from collections import defaultdict
from past.builtins import basestring
from pycolocstats.core.config import REF_COLL_GSUITES_PATH
__metaclass__ = type
class RefTrackCollectionRegistry(object):
PREBUILT = '__prebuilt_... |
1,535 | 951fafe9f1b9a3273f30d101831d1e59e26fe85d | from django.db import models
class ScggjyList(models.Model):
title = models.CharField(max_length=255)
pubData = models.CharField(db_column='pubData', max_length=255)
detailLink = models.CharField(db_column='detailLink', max_length=255)
detailTitle = models.CharField(db_column='detailTitle', max_length... |
1,536 | 81f0119f6f348f6d33e8d22f588fc8c2e0593d3c | from django.db import models
from django.utils.text import slugify
# Create your models here.
class SponsorType(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Sponsor(models.Model):
type = models.ForeignKey(SponsorType, on_delete=models.CASCADE, ... |
1,537 | f702cdef3782ddc96244f3cf8e2026581d60baa9 | ####
# This is the script for storing the schema of your TerminusDB
# database for your project.
# Use 'terminusdb commit' to commit changes to the database and
# use 'terminusdb sync' to change this file according to
# the exsisting database schema
####
from typing import List
from terminusdb_client.woqlschema impor... |
1,538 | 5c3bf49f88dec429ec85cceb8130cccf2691363b | if __name__ == '__main__':
print('--------------------------------------')
query = 'user=pilgrim&database=master&password=PapayaWhip'
a_list = query.split('&')
print(a_list)
print('--------------------------------------')
a_list_of_lists = [v.split('=', 1) for v in a_list if '=' in v]
prin... |
1,539 | a0ffb793650b0e911dd9bcbec0b7ba76f7829c12 | def minvalue(weight,Day):
maximum = 0
res = 0
for x in range(0, len(weight)):
if weight[x] > maximum:
maximum = weight[x]
res += weight[x]
Capitivity = max(res // Day, maximum)
while True:
sum=0
day=1
for t in range(0, len(weight)):
if ... |
1,540 | b46b9b086fc089e24cb39a0c2c4ac252591b2190 | import MySQLdb
import settings
import redis
import socket
import fcntl
import struct
import datetime
db = MySQLdb.connect(settings.host, settings.user, settings.pwd, settings.db)
cursor = db.cursor()
def connect_mysql():
try:
db.ping()
except:
db = MySQLdb.connect... |
1,541 | adae4f9ebcbbb775fc40278ceec9a0cc30c0a503 | import openpyxl
class TestXLUtility:
def __init__(self, driver):
self.driver = driver
def getRowCount(file, sheetname):
workbook = openpyxl.load_workbook(file)
#sheet = workbook.get_sheet_by_name(sheetname)
sheet = workbook[sheetname]
return(sheet.max_row)
def get... |
1,542 | c24bf42cfeaa1fb8ac188b9e08146762e0e86fed | #
# purpose: setup file to install the compiled-language python libraries
# usage: python setup.py config_fc --f90flags="-O2 -fopenmp" install --prefix=$PWD
#
from numpy.distutils.core import Extension
c_array_sqrt = Extension (name = "c_array_sqrt_omp",
sources = ["./src/c_array_sqrt_omp.... |
1,543 | d20b336c6588c3cfc4393256b660d6e4ff56b84e | #Uses python3
import sys
def lcs2(a, b):
dp_result = [[0 for j in range(b+1)] for i in range(a+1)]
for x in range(1, a+1):
for y in range(1, b+1):
if a[x-1] == b[y-1] and b[y-1] == c[z-1]:
dp_result[x][y] = dp_result[x-1][y-1] + 1
else:
dp_re... |
1,544 | 137e80b3bfdc0dba33a3108b37d21d298a8f251d | from plumbum import local, FG, ProcessExecutionError
import logging
import os.path
from task import app
kubectl = local["kubectl"]
@app.task
def create_kube_from_template(file_name, *aargs):
args = {}
for a in aargs:
args.update(a)
template = open(os.path.join('..', file_name)).read() % args
logging.info... |
1,545 | b20a8160ba455a39e990b8b37c5017645530ced3 | from .models import Video, VideoClass
from rest_framework import serializers
# Video 정보
class VideoSerializer(serializers.ModelSerializer):
class Meta:
model = Video
fields = ['videoURL','subTitle', 'numOfLike', 'numOfPlay']
# Video 분류
class VideoClassSerializer(serializers.ModelSerializer):
... |
1,546 | 63ee99012089dcb0e5b41860c95e13fff52c6731 | import ast
import datetime
import json
from base64 import b64encode
import requests
IMGUR_BASE = "https://api.imgur.com"
class Task:
"""
A class used to represent a job
...
Attributes
----------
queue : list
the list of all urls
pending : list
the name of all pending urls... |
1,547 | e7a283e0e0e16e9adb415b26d724b2ee84c4f4f8 | from django import forms
from django.forms import ModelForm
from .models import Noticia
class NoticiaForm(ModelForm):
class Meta:
model = Noticia
fields = ['idNoticia','resumen','titulo','categoria'] |
1,548 | 7d10fb58aa5213516c656c05966fcaad6868ae81 | import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Database Name
db = client["Test"]
# Collection Name
col = db["C100"]
x = col.find_one()
print(x) |
1,549 | b27913d2cd29f174d79652af6da2846e397373fc | # Generated by Django 2.0.4 on 2018-06-09 05:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lists', '0004_auto_20180608_1835'),
]
operations = [
migrations.AlterModelOptions(
name='todo',
options={'ordering':... |
1,550 | 0ec5d6ce11851a577046cf73cf98c91b6dfb9f67 | from concurrent import futures
import time
import math
import logging
import grpc
import tensorflow as tf
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2_grpc
import sys
sys.path.append('/home/yitao/Documents/fun-project/tensorflow-related/miniature-winner/')... |
1,551 | b4b4dad5cf630dc1a627e323ea63577583d1e1c3 | from pandas_datareader import data as pdr
from datetime import date
class YahooHelper:
"""
Class to fetch Yahoo data
"""
def __init__(self):
"""
Default constructor which initiates object
"""
pass
def get_data(self, symbol):
"""
Function to collect... |
1,552 | b6dbed95b321ac93c712c4735d601a00650b8dc4 | # Generated from /home/mridul/PycharmProjects/BTP_2k18-19/PlSql.g4 by ANTLR 4.7.2
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\u020e")
buf.write("\u... |
1,553 | c6357e6e0656388fc3fd849879aa6000e0bee1ee | #
# o o
# 8
# .oPYo. .oPYo. odYo. o8P o8 .oPYo. odYo. .oPYo. .oPYo.
# Yb.. 8oooo8 8' `8 8 8 8oooo8 8' `8 8 ' 8oooo8
# 'Yb. 8. 8 8 8 8 8. 8 8 8 . 8.
# `YooP' `Yooo' 8 8 8 ... |
1,554 | 193dcf7bd658f88afe0a1f2fa28605f262e45bc2 | # -*- coding: UTF-8 -*-
import lava
from lava.api.constants.vk import QueueType
from lava.api.device import Device
from lava.api.util import Destroyable
__all__ = ["Session"]
sessions = set()
class Session(Destroyable):
def __init__(self, physical_device, queue_index=None):
super(Session, self).__init... |
1,555 | 38e616e35f165d458d774dd0b6837a733b8402d7 | # -*- coding: utf-8 -*-
import sys
#from Constants import *
# start
import CrudMatrixDao
class CrudAccessValue:
def __init__(self):
self.crudAccessValue = {}
self.__run()
def __run(self):
aCrudMatrixDao = CrudMatrixDao.CrudMatrixDao()
# print aCrudMatrixDao.selectCrudAccessValueAction()
... |
1,556 | 385dccfab4d7c37d10d968658b51e231691a7b49 | #!/bin/python
import numpy as np
import os
from sklearn.svm.classes import SVC
import pickle
import sys
# Apply the SVM model to the testing videos; Output the score for each video
if __name__ == '__main__':
if len(sys.argv) != 5:
print("Usage: {0} model_file feat_dir feat_dim output_file".format(sys.ar... |
1,557 | cddd5deba0ddc59a604d2926bdc687716e08f226 | #!/usr/bin/python3
"""
@author : Chris Phibbs
@created : Sunday Aug 30, 2020 14:05:56 AEST
@file : q3
"""
class Solution:
def minDays(self, grid: List[List[int]]) -> int:
# bfs - find 1, run bfs. Then loop through - if any other ones found then disconnected
i, j = 0... |
1,558 | 06dd963b62c0a746438dcf01c67ef5de1a4c5e8f | from pytube import YouTube, Playlist
import json
import sys
import os
import urllib.request
p = os.path.abspath('appdata')
def collect(yt, dir):
code = yt.thumbnail_url
urllib.request.urlretrieve(code, os.path.join(dir, yt.title + '.jpg'))
out = yt.streams.filter(only_audio = True,
file_extension ... |
1,559 | 314f6cc97f53fa5bd8bf0ec0e1e305ca6384f1a2 | from django.apps import AppConfig
class DojoBookAppConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'dojo_book_app'
|
1,560 | 98bf0a332a6753e500b24bed2af16fe4a1cb9568 | from math import sqrt
from Engine.regulators.PID import PID
from Engine.regulators.regulator_base_class import RegulatorBaseClass
from Engine.robot import Robot, MAX_LINEAR_ACCELERATION, MAX_ANGULAR_SPEED
from Util import Pose
from Util.geometry import clamp, normalize
from Util.pose import Position
from config.config... |
1,561 | a486ec6b27a6b84e454a1bed096be9fe22d91612 | #!/usr/bin/env python2
import os
import sys
import textwrap
COMMAND = (
'convert -size 1920x1080 canvas:"rgb(149, 1, 1)" '
'-font Dejavu-Sans-Bold -pointsize {0} -gravity center -stroke none '
'-fill white -annotate 0 "{1}" -size 1920x1080 "{2}.png"'
)
def makeimage(text, point_size=100, width=30):
t... |
1,562 | 8cba57e3552e0072720fe42fa1949534f29d71b5 | from string import Template
import os
#-----template objects-----
#for putting a template inside an ifdef guard
TIfGuard = Template("""if(${condition})
${innerbody}
endif()\n""")
#For minimum cmake version and project name
TProjectSettings = Template("""cmake_minimum_required (VERSION ${MinCmakeVer})
project(${Name}... |
1,563 | 602d2c545c6e3eabe5c6285d2ab0c7f4216a00f5 | import common
import student_code
class bcolors:
RED = "\x1b[31m"
GREEN = "\x1b[32m"
NORMAL = "\x1b[0m"
def check_result(title, map1, map2):
result=True
print(title)
for y in range(0,common.constants.MAP_HEIGHT):
v=""
for x in range(0,common.constants.MAP_WIDTH):
if (map1[y][x]==map2[y]... |
1,564 | 27d5ff5b0253eea36d6b492e929c4220f4b4a5eb | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from collections import defaultdict
from typing import List, Dict, Optional, Tuple
import torch.jit
from torch import n... |
1,565 | 74aa93bf3731d4e3ddb920bedc7daced50b4f2c3 | import json
import joblib
import numpy as np
import datetime
import sqlalchemy as sa
import cx_Oracle
import pandas as pd
from flask import Flask, render_template, session, request, redirect, url_for
app = Flask(__name__)
oracle_engine = sa.create_engine('oracle://ft:1234@localhost:1522/xe')
@app.route("/")
def inde... |
1,566 | a6154c5d855dc53d73db08bbb5b5d7437056e156 | from keras.models import load_model
from DataManager import *
def loadModel(name):
model = load_model('./Model/%s.h5' % name)
return model
def predict(tag):
test = getPIData(tag, '2019-11-05', '2019-11-06')
test_arg = addFeature(test)
test_norm = normalize(test_arg)
X_test, Y_test = buildTr... |
1,567 | 09f2fabaf3c19aa0d4cb522c6dbf5fd8d720b4df | """
Problem Statement
You and Fredrick are good friends. Yesterday, Fredrick received N credit
cards from ABCD Bank. He wants to verify whether his credit card numbers are
valid or not. You happen to be great at regex so he is asking for your help!
A valid credit card from ABCD Bank has the following characteristics:... |
1,568 | 3a88ff479e3b01518d79e9930c29514863f96f9b | # -*- coding: utf-8 -*-
import itertools as itt
import random
import unittest
from collections import Counter
from uuid import uuid4
import numpy as np
from pybel import BELGraph
from pybel.constants import INCREASES, PROTEIN
from pybel.dsl import protein
from pybel_tools.selection import get_random_subgraph
from py... |
1,569 | b16c847912944e0563492d35768b5b5bf3a506c7 | """
Utilities used by other modules.
"""
import csv
import datetime
import hashlib
import json
import re
import string
import subprocess
import uuid
import xml.etree.ElementTree as ET
from alta import ConfigurationFromYamlFile
from pkg_resources import resource_filename
from ..__details__ import __appname__
from appd... |
1,570 | 9cb11c2bf032aa16abd3463ecdb8997addedc912 | import pygame
from Actor import Actor
import PlayerInput
class TestActor(Actor):
def __init__(self):
super(TestActor, self).__init__()
def act(self):
self.key_commands()
def key_commands(self):
if PlayerInput.is_key_down(pygame.K_LEFT):
self.set_location(self.x - 1, ... |
1,571 | fcc75550e1317a15c36bc8100c28af59b68e1381 | import boto3
import time
import datetime
from datetime import date
import sqlite3
import logging
import logging.handlers
from decimal import *
### LOGS CONFIGURATION ###
LOG_FILENAME = '/home/pi/Thermostat/alexaThermostat/logs/alexaThermostat.out'
# Set up a specific logger with our desired output level
my_logger = l... |
1,572 | 50fab726b90f65a82c1206a8c7df955a8b76da99 | #打印ckpt或pb模型的tensor
# ckpt模型
#第一种方法:
from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file
checkpoint_path="/your/path"
print_tensors_in_checkpoint_file(checkpoint_path,tensor_name='', all_tensors=True, all_tensor_names=True)
#第二种方法:
from tensorflow.python import pywrap... |
1,573 | 843df062702c9abf34cf14d911d927d786f1d912 | numbers = [1, 1, 1, 1, 1]
new_numbers = [2, 2, 2, 3, 3]
print(numbers + new_numbers)
print(numbers * 5)
|
1,574 | a58949d25a719dc9ce0626948ab0397814e9ea0e | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-11-21 00:43
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('analysis', '0018_relatorioquedadeconsumo_justificado'),
]
operations = [
mi... |
1,575 | 1ef1dcc8fdf4d813dad70c860e33778715d51b0c | #!/usr/bin/env python
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test support for the various "EMPTY" WKT geometry representations.
# Author: Frank Warmerdam <warmerdam@pobox.com>
#
#############################################... |
1,576 | be9972d899a167a8ca2728960e55cda538793cc5 | #!/usr/bin/env python3
import cgitb
import sys
from auth import is_admin
cgitb.enable()
sys.stdout.write('Content-Type: application/octet-stream\n\n')
sys.stdout.write('yes' if is_admin() else 'no')
sys.stdout.flush()
|
1,577 | 1e34087719f6fd0456d2722edbd0a7af68d37e4c | import pandas as pd
from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier
from sklearn.model_selection import train_test_split # Import train_test_split function
from sklearn import metrics #Import scikit-learn metrics module for accuracy calculation
from sklearn.tree import DecisionTreeRegr... |
1,578 | 30aa8405ccf64ce8a05204f3f9fa2ffab436ad3b | from classNinapro import Ninapro
import numpy as np
import tensorflow as tf
print(tf.__version__)
Debug = True # for tensor dimensionality checking
ninapro = Ninapro()
ninapro.splitImagesLabels()
# Train
print('ninapro.TrainImages shape: ', ninapro.TrainImages.shape) # m x 16 x 30
print('ninapro.TrainLabels shape... |
1,579 | 47be41bd5838b828acdc90c3ef5abdeec9da1e85 | import csv
import os
import requests
from bs4 import BeautifulSoup
# open html file and parsing lxml
with open ('/Users/neeraj.joshi/Downloads/index.html') as html_file:
soup = BeautifulSoup(html_file, 'lxml')
#row = soup.find_all('tr')
#column = row.find_all('td')
#print(soup)
# create a file by any name and in o... |
1,580 | e55fe845c18ff70ba12bb7c2db28ceded8ae9129 | SSMDocumentName ='AWS-RunPowerShellScript'
InstanceId = ['i-081a7260c79feb260']
Querytimeoutseconds = 3600
OutputS3BucketName = 'hccake'
OutputS3KeyPrefix = 'log_'
region_name ='us-east-2'
aws_access_key_id =''
aws_secret_access_key =''
workingdirectory =["c:\\"]
executiontimeout =["3600"] |
1,581 | cd34f9ef100ae6d116f02258d22c114ec3f3e3e6 | import os
import shutil
import configparser
beatmap_dir = os.path.abspath(os.environ['LOCALAPPDATA']+'\\osu!\\Songs\\')
beatmaps = []
bm_osu = []
with os.scandir(os.path.abspath(beatmap_dir)) as it:
for entry in it:
if entry.is_dir():
try:
beatmap_id = int(str(entry.name).split... |
1,582 | 6b138dabf57166ec971052fff7df89ae0346e083 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 1 19:16:16 2019
@author: pc
"""
from socket import *
import threading
import time
import cv2
import struct
import pickle
import zlib
import cartoon_edit
import face_capture_edit
import pencil_edit
class Video_Server(threading.Thread):
def __init__ (self, port, vers... |
1,583 | 9c251e0224979877b9ce244e4871fd4c403abb8e | def _make_key(*args, **kwargs):
all_args = [str(arg) for arg in args]
all_args += [str(arg) + '=' + str(value) for arg, value in kwargs.items()]
return '|'.join(all_args)
class DoubleLinked:
def __init__(self, prv, nxt, key):
self.prv = prv
self.nxt = nxt
self.key = key
class... |
1,584 | 78efe97d838774cb831ef205186db29f392e1953 | import socket
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(20,GPIO.OUT,initial=GPIO.LOW) #green
GPIO.setup(21,GPIO.OUT,initial=GPIO.LOW) #red
GPIO.setwarnings(False)
host = '192.168.87.191'
port = 5560
def setupServer():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Soc... |
1,585 | fbce185671267bd70cf7b91696867b72dfcc8d5b | conf = {
'PROJECT': 'WCCIA',
'NAS_FOLDER' : 'Q:\\GROUPS\\CORP_JGS_DSE\\ATI\\quotations',
'DB_SERVER' : '10.0.36.129',
'DB_PORT' : '34000/'
}
|
1,586 | ad88685e3f1cd5e0ddb42a5982a05ff8ee7b8111 | # content of conftest.py
import pytest
import sys
sys.path.insert(1, '../Generic')
import PQ9Client
def pytest_configure(config):
print("pytest_configure")
def pytest_collection_modifyitems(session, config, items):
print("sono qui", items)
def pytest_ignore_collect(path, config):
print(path)
... |
1,587 | 60354f25f55136d4e873d118cfe048cf08c06e39 | # This is a sample Python script.
# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
import weather_forecast
from weather_forecast import forecast
from googlesearch import search
from youtube_search import YoutubeSearch... |
1,588 | 749e6a1f807843c9e2591f51561174cc51668b11 | import cv2
import numpy as np
img1 = cv2.imread('img0008.jpg')
img2 = cv2.imread('img0009.jpg')
#img3 = cv2.imread('img0009.jpg')
img3 = np.zeros(img1.shape)
iter = 51
def sumas(ux, uy, wx, wy, dx, dy, img_i, img_j):
suma = 0
x = ux - wx
y = uy - wy
while x < ux + wx:
while y < uy + wy:
... |
1,589 | 166329c967e83806e3482179a56ac7e5541d5010 | import re
with open('input.txt') as f:
input_file = f.readlines()
input_file = [x.strip() for x in input_file]
def check_passport(text):
arr = text.split()
dct = {}
for elem in arr:
key = elem.split(":")[0]
val = elem.split(":")[1]
dct[key] = val
try:
if len(dc... |
1,590 | 5f24c5a21dc151e9efbbfaff0fe1e71e65d1eb67 |
class Box:
def __init__(self, id, capacity):
self.id = id
self.dogs = []
self.capacity = capacity
@property
def status(self):
return len(self.dogs)
def add_dog(self, dog):
if self.capacity > self.status:
self.dogs.append(dog)
return Tru... |
1,591 | 7fd89272d3d3584f35fd8f552cb7b14e57b7ed1b | import numpy as np
import cv2
import time
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
average_stack = np.float32(np.copy(frame))/255
frames = 1.0
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
frame = np.float32(frame)/255
average_stack = average_stack * frames + frame
frames... |
1,592 | 42ebd42801b7d1563c9f204f296afba5fa3c6d3c | from jaqsmds.server.repliers.basic import RegularReplier
from jaqsmds.server.repliers.handlers import JsetHandler, JsdHandler, JsiHandler
from queue import Queue, Empty
from threading import Thread
import logging
class FreeReplier(RegularReplier):
def __init__(self):
super(FreeReplier, self).__init__()
... |
1,593 | a74a880039bad030d665e001da74075bd61fcc23 | from behave import given, when, then
from pages.LoginPage import LoginPage
from pages.ProductsPage import ProductsPage
class ProductsListSteps:
@given("Prepare classes products list")
def prepare_class(context):
context.login = LoginPage(context.driver)
context.products = ProductsPage(context.... |
1,594 | 5b9f1b3ca4b50a4e9e8bd6715e73c62b4f778929 | import time
import pigpio
class Car:
def __init__(self, STBY, PWMA, AIN2, AIN1, BIN1, BIN2, PWMB, sensorTrig=0, sensors=[]):
self.pi = pigpio.pi()
if not self.pi.connected:
print("Pi not connected to pigpio.")
return
# GPIO Drive Pin locations
... |
1,595 | 3ab26612111e3df59f41f5b5e0bf23398e015a8a | """
统计飞船信息
"""
class GameStats:
def __init__(self, setting):
self.setting = setting
self.ships_left = self.setting.ship_limit
self.game_active = True
|
1,596 | e57680c9bd09866e68ade0cfea7ce83cd6d50f58 | import sys
import json
with open(__file__.replace('.py', '.txt')) as f:
problem = f.read()
data = {
'problem': problem,
'example': """COM)B
B)C
C)D
D)E
E)F
B)G
G)H
D)I
E)J
J)K
K)L""" # should give 42
}
def solve_problem(input):
parents = {}
for i, line in enumerate(input.split('\n')):
... |
1,597 | 74c875d00c665aabbcad4e23e6059c3445d5e7bd | import gc
import sys
import time
import warnings
import multiprocessing
import numpy as np
import pandas as pd
import lightgbm as lgb
from os import path, makedirs
from tqdm import tqdm
from utils import Logger
from datetime import datetime
from sklearn.metrics import roc_auc_score
from sklearn.model_s... |
1,598 | 94b1e0280eff165f63e117969d5e1bf9d1e35193 | """Identifying Antecedent Pronoun"""
from question import Question,Packet
qdict={
"correct pronoun-antecedent agreement":[
"<u>He</u> came home to <u>his</u> own car.",
"<u>He</u> found <u>his</u> sneakers in the garage.",
"<u>Harry</u> gave <u>himself</u> a baseball for Christmas.",
"<u>Jill</u> found <u>her</u> miss... |
1,599 | 9c35e64fd773c79dc20e6b388478e892bda85788 | quilogramas = float ( input ( "Insira o peso em Kg:" ))
libras = quilogramas / 0 , 45
print ( libras ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.