index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
10,900 | b45dc1c559852897bc792e0dc182cd56cace240b | from OpenGL.GL import *
from gcraft.core.scene import GCraftSceneManager
from gcraft.core.input_state import InputState
from gcraft.core.input_event import InputEvent
import gcraft.utils.state_manager as sm
class GCraftApp:
def __init__(self):
self.input_state = InputState()
self.mouse_warp = Non... |
10,901 | 1d88dbd3145dce2ea0364c49ef328ba6f62f2227 | from flask_restful import Resource
from flask import jsonify
import logging
class OpenCvConfigurationData(Resource):
def __init__(self, **kwargs):
self.matcher = kwargs['matcher']
self.extractor = self._get_object_name_with_package(kwargs['extractor'])
self.log = logging.getLogger('vse.Ope... |
10,902 | 60367f039cfb871492342f36815b89fcb18a71b0 | from tkinter import *
window = Tk()
canvas = Canvas(window, width=300, height=200)
# 캔버스를 생성함
canvas.pack()
canvas.create_line(0, 0, 300, 200)
# 라인을 그림 (0, 0) ~ (300, 200)
canvas.create_line(0, 0, 300, 100, fill="red")
# fill 매개변수는 선 색깔을 의미함
canvas.create_rectangle(50, 25, 200, 100, fill="blue")
# 사각형을 그림. create_... |
10,903 | 41b3b55ed2f76a47272f8a3ef79d808294a72965 | #__author__:"wanghui"
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
class VBoxLayout(QWidget):
def __init__(self):
super(VBoxLayout,self).__init__()
self.initUI()
def initUI(self):
#self.setWindowFlag(Qt.Frame... |
10,904 | 508c898ed5dc230a09f1ae5113069a1de6fcb467 | BUILD_VERSION = "1.50"
BUILD_AUTHORS = "Jack and Sam"
BUILD_CODENAME = "None as of yet"
BUILD_DATE = "November 29th, 2017 at 4:26 PM" |
10,905 | 2dfa16d951aee3336377a18ee1ae148ab0b1c7aa | # coding=utf-8
# Copyright 2023 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
10,906 | b4b9a51297bbc628c68d3dbf4fe026dc4fc5c64e | #! Python3
# Programming tutorial: While loop
condition = 1
while condition < 10:
print(condition)
condition += 1
while True:
print('Doing stuff')
|
10,907 | 9693ac029086cc719cc1b92ec469ef983854667c | import os
import json
import torch
from torch import nn, optim
from Helper.JsonDateHelper import DateTimeDecoder
from Helper.Timer import Timer
from Helper.DateHelper import DateHelper
from Predictor.LstmTA.TaModel import TaModel
from Predictor.LstmTA.TaDataReader import TaDataReader
from Managers.ExportManager.Export ... |
10,908 | d9554373abe9c04ef1dfa81df3dbe93a4d2fc074 | from odoo import fields, models, api
from odoo.exceptions import ValidationError
class QtyUpdateWizard(models.TransientModel):
_name = 'qty.update.wizard'
_description = 'Purchase Order Wizard'
@api.model
def default_get(self, fields_list):
record = super(QtyUpdateWizard, self).default_get(fi... |
10,909 | 4fcda76a43aa55455dc24fed379a4dbadb0c2a74 | from dataclasses import dataclass, field
from enum import Enum
from input_utils import get_input
from log_utils import log
import math
from typing import Dict, List, Optional, Set
@dataclass
class Element:
name: str
qty: int
@staticmethod
def from_string(elem_str: str) -> 'Element':
elem_data... |
10,910 | d39ae182c642b9e9adf64cae220aadcf601b4523 | # -*- coding: UTF-8 -*-
import random
class block:
#################################################################
# Initialize #
# btype: block type = 'normal' OR 'super' OR 'jail'(TODO) #
# bvalue: block value ... |
10,911 | acbea7f35650a0a27e90fd5e4f3da78f720ea13b | # Generated by Django 3.0.8 on 2020-11-07 14:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('aitojunction', '0004_cuisine'),
]
operations = [
migrations.AddField(
model_name='place',
name='congestion',
... |
10,912 | 4848432243b04cf93c94c78598f132b5c3f4afae | __version__ = "2.0.1a0"
|
10,913 | 3fd88e170c0da869193b7738640dbfa7cceb3451 | import time, uuid, threading, textwrap
from enum import Enum, auto
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import png
class StreamController():
def __init__(self, x_size, y_size):
self.event = threading.Event()
self.events = []
self.uuid = uuid.uuid4()
... |
10,914 | b19a3e77590931a3b07e9d2f0d14a25d5a337932 | ########################################################################
# trigger.py - command line application to manage the triggers
# checked every 30 minutes by agileTriggers.py the tool makes sqlite calls
# to the database to update the triggers table.
#
# Copyright 2020 Simon McKenna.
#
# Licensed under the Ap... |
10,915 | 03df31a020ddc80469564fb34de3ee5e988e63a2 | import decorators
def validate(input_year):
if len(str(input_year)) != 4:
raise Exception("Invalid year! Please enter year of 4 digits.");
def check_leap_year(input_year):
return input_year % 4 == 0 and (input_year % 100 != 0 or input_year % 400 == 0)
try:
input_year = int(input("Enter year to fi... |
10,916 | bec0a2635e39f89c76d81f23cabf653773fecf26 | import sys
sys.stdin = open('2382_input.txt')
# 맵 없이도 충분히 풀 수 있는 문제!
# 약품(테두리) 닿으면 방향 전환, 개체 수 반감
# 딕셔너리 활용하여 이동 위치가 중복될 때 흡수 시킬지 흡수 당할지를 결정
# 상 하 좌 우
dr = (0, -1, 1, 0, 0)
dc = (0, 0, 0, -1, 1)
# 방향 바꾸기
rev = (0, 2, 1, 4, 3)
# main
T = int(input())
for tc in range(T):
N, M, K = map(int, input().split())
r... |
10,917 | 4ad11aedde0a1dad5126c26c54dd694078993bb5 | #coding=utf-8
#在数组中,任选三个数,使该数的值靠近给定的target
class Solution(object):
def threeSumCloest(self,nums,target):
if len(nums)<3: return 0
nums=sorted(nums)
res=nums[0]+nums[1]+nums[2]
for i in range(len(nums)-2):
l,r=i+1,len(nums)-1
while l<r:
tmp=nums[i]+nums[... |
10,918 | d8da5c5165101f146bd6cd89275b6a5d7369f1bc | from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^book-create/', views.create_book, name="modelex-book-create"),
url(r'^author-create/', views.AuthorCreate.as_view(), name="modelex-author-create"),
url(r'^books/', views.latest_books , name="modelex-books-... |
10,919 | 0c1ac88bb3c994fef137dcafd868e5e6652ed916 | import vtk
import numpy
def to_str(string):
string=string[0:8]
i_str=numpy.fromstring(string, dtype="uint64")
return i_str[0]
def make_rect(coords):
xmin,ymin,xmax,ymax=coords
pts = vtk.vtkPoints()
pts.InsertPoint(0, xmin, ymin, 0)
pts.InsertPoint(1, xmax, ymin, 0)
pts.Insert... |
10,920 | 43034da988c6f09985d25e434407938d4257721c | from torch.utils.data import Dataset, DataLoader
import cv2
import torch
from project3.YOLOWithMobileNet.SET import Set
import numpy as np
from math import log
class Voc2012DataSet(Dataset):
def __init__(self, image_path='D:/data/object3/dataset', path='D:/data/object3/TrainMobile.txt'):
super(Voc2012Dat... |
10,921 | 54a31a54586fa90aec528d38cc39fecc514c9c24 | class HvorkaGlucoseModel(object):
"""Two compartment insulin model
Source and parameters: https://iopscience-iop-org.focus.lib.kth.se/
article/10.1088/0967-3334/25/4/010/meta
"""
def __init__(self):
"""Model params"""
self.t_G = 40 # Time of maximum glucose rate of appe... |
10,922 | 4e834addd04c7f05d3b48079913a96b4e57a6451 | def take_input():
var1 = eval(input("Guess the number"))
return var1
def compare_guess_number(guess_number, secret_number):
if (guess_number < secret_number):
print("Enter number is less than the secret number")
return False
elif (guess_number > secret_number):
print("Enter num... |
10,923 | 8846fba7d8196ce6fcffc92f0797d069f466fcbe | #Methods are a function closely related to a given type of data
example = "hello"
print(example.upper())
print(example.replace("o", "@"))
|
10,924 | 4d18d3a6e47b2dd6fa856e2ac5f4ab34912d5adb | # Generated by Django 2.2.12 on 2020-04-29 17:04
from django.db import migrations, models
import jlibrary.models
class Migration(migrations.Migration):
dependencies = [
('jlibrary', '0005_auto_20200420_0434'),
]
operations = [
migrations.AlterField(
model_name='booklease',
... |
10,925 | f98f65347c0206f97d8a3bb07128643d003c754a | from line_of_sight_simple_directional import LineOfSightSimpleDirectional
loss = LineOfSightSimpleDirectional()
loss.set_equation([1,1], [2,3])
loss.check_path()
|
10,926 | b4c9350d8f79de49f1b4e841aad3cb26c7faee38 |
def iterrows(arr):
for row in arr:
yield row
|
10,927 | fc270908351244f2742daabe8b678a5c49e048ae | import struct
from tensorflow.core.example import example_pb2
def transfer_binary2text(set_name):
article_list, abstract_list = [], []
file_name = "data/finished_files/{}.bin".format(set_name)
with open(file_name, 'rb') as reader:
while True:
len_bytes = reader.read(8)
if not len_bytes:
break
str_le... |
10,928 | 61e2991c723738a64688c536ca876b3ad565ad2b | from views.Builder import *
class configScreen():
def setScreen(self, posicion):
self.ii2 = Image.open(self.getBuilders(posicion))
self.ii2.thumbnail((465,365))
self.ii2 = ImageTk.PhotoImage(self.ii2)
return self.ii2
def getBuilders(self, posicion):
self.app = BuilderM... |
10,929 | e0ff15422c78e7220b4f731f8eac50244bcb08d3 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: Li... |
10,930 | a5f39899fc7a4ab55aa46813acd7f7d0935ff85a | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append('../')
from sklearn.cluster import KMeans
from sklearn.cluster import AgglomerativeClustering
from sklearn.cluster import Birch
import joblib
from sklearn import metrics
import libs.common
import libs.logger
import libs.db
import config
import ma... |
10,931 | 07d1955658757cc2329031bd89d5e5e7a26345cf | import os
from importlib import import_module
from StringIO import StringIO
from zope.interface import alsoProvides
from sparc.db.splunk import ISplunkResultsStream
def mock_result_stream():
"""Return a ISplunkResultsStream from sample data"""
response_file_path = os.path.join(import_module(__name__).__path__[... |
10,932 | c3bd7602872dfc22481692772eaf7b042c93deb9 | from django.shortcuts import render, get_object_or_404
from django.db.models import Q
from .models import Mineral
import random
# Create your views here.
def minerals(request):
minerals = Mineral.objects.all()
return render(request, 'minerals/minerals.html',{'minerals': minerals })
def mineral_detail(request, pk)... |
10,933 | 6eab49dbd703acfc9fe9e0e7532fd2b1db72be30 | import random
epTitles = {
(1,1) : "The Gang Gets Racist",(1,2) : "Charlie Wants an Abortion",(1,3) : "Underage Drinking: A National Concern",(1,4) : "Charlie Has Cancer",
(1,5) : "Gun Fever",(1,6) : "The Gang Finds a Dead Guy",(1,7) : "Charlie Got Molested",
(2,1) : "Charlie Gets C... |
10,934 | a6252403989450ad937d7d0d84e5629ac18ab271 | # -*- coding: utf8 -*-
#
# XSL - graphical interface for SL
# Copyright (C) 2007-2016 Devaev Maxim
#
# This file is part of XSL.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version ... |
10,935 | e319d07c36c2bb87faaed5ea9382a873a1cff04a | import smtplib
import time
import datetime
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
act = 1
GPIO.setup(17,GPIO.IN)
print("System Startup Successful")
time.sleep(1)
while act == 1 :
if (GPIO.input(17)):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login("gmail email", "gmail pas... |
10,936 | c65ce87c8df71bda08cdacde303369679024a92e | # coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import wrapt
from scout_apm.core.tracked_request import TrackedRequest
def trace_method(cls, method_name=None):
def decorator(info_func):
method_to_patch = method_name or info_func.__name__
@wrapt.... |
10,937 | 5c64f4ab0cb6af27ee1550c3c47dea5ba2dbce9d | from .MultiStepProbing import MultiStepProbing
from .NoLossUp import NoLossUp
from .LossDiffAvgMaximization import LossDiffAvgMaximization
from .LossDiffAvgMaximization_NoLossUp import LossDiffAvgMaximization_NoLossUp
|
10,938 | f295d6ac8a0449e8d7aefc61560177b8f1efa775 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 1 17:12:15 2019
@author: Stephan
"""
import pandas as pd
from processor.extractionAlgorithms import tfIdf_Vectorizer_getKeyWords,tfIdf_Vectorizer_train,getTextrankKeywords
from processor import preprocessing as pre
class Textprocessor:
def __init__(self, corpus,... |
10,939 | 2dd65eae729ca4b0b2b2d8d82629037260e7caa6 | # Generated by Django 2.1.4 on 2019-09-02 00:29
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('webapp', '0002_auto_20190831_0406'),
]
operations = [
migrations.AddField(
model_name='recipe',... |
10,940 | 9f344f806a664862b57ce527f4b678996b298422 | from django.contrib.auth.models import User
# from django.contrib.auth.models import AnonymousUser, User
from django.test import Client, RequestFactory, TestCase
from django.urls import reverse
# from mainpage import views
from mainpage.models import Status, Tag, Task
class TaskTest(TestCase):
def setUp(self):
... |
10,941 | 4cec73c54fa51d56cd8fb5e7d6a7e446a6cf8581 | import re
def createModFile(path):
inputFile = open(path, 'r')
outputFile = open('outputHw8.txt', 'w')
for line in inputFile:
line = line.replace('\n', '')
str_ = ''
letters = list(filter(None, re.split('\d+', line)))
digits = list(filter(None, re.split('[a-zA-Z]+', line)... |
10,942 | 2efee8be9d1e7fcea5f66cde807c0afff004d5b1 | # -*- coding: utf-8 -*-
from django import forms
from .models import Calendar, Website
import pytz
class CalendarForm(forms.ModelForm):
name = forms.CharField(required=True,
label='Name', help_text='Type in a calendar name.')
class Meta:
model = Calendar
fields = ['name']
class Websit... |
10,943 | 74ebd26a079b8016cfa9ed58a17c344f1aaa2e9d | from setuptools import setup
import pathlib
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
setup(
name = 'readme-preview',
description = 'jupyter extension for previewing readme.md files',
version = '0.4.1',... |
10,944 | cb8b4fb7155f99122e600c0aac22b7da959a0678 | from setuptools import setup
setup(name='pyshlist',
version='0.1',
description='Command-line tool for managing your wishlist',
url='http://github.com/32leaves/pyshlist',
author='Christian Weichel',
author_email='chris@32leav.es',
license='MIT',
py_modules = ['pyshlist'],
... |
10,945 | 1a536e7d0e764ca5a3b372eee49feb869b61e540 | # Generated by Django 3.0.3 on 2020-07-05 21:09
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
10,946 | 12ed594aadb10ad204d5701425c6e9f341ccdfbc | import sys
sys.path.append('..')
from quantum_circuit.gates import *
# FOR REVERSED GATE PRODUCTS
### With int,float,complex
first = I()
first.factor *= 2
assert first == 2*I()
sec = X()
sec.factor *= -0.5
assert sec == -0.5*X()
thrd = Creation()
thrd.factor *= complex(0,1)
assert thrd == complex(0,1)*Creation()
##... |
10,947 | 18e61b9fbba634f7863da89e000c2d01546e5803 | print "hello world!"
print "hola mundo"
print "ola mondo"
|
10,948 | 042f9de3a5e6dd66a33757defdcf432b8433c567 | import pandas as pd
import numpy as np
import os
import sys
import tensorflow as tf
import time
syspath = os.path.dirname(os.path.realpath(__file__)) + '/..'
sys.path.insert(0, syspath)
from vbsw_module.functions.basic_functions import fun_list
from vbsw_module.data_generation.samplers import tbs
from vbsw_module.mo... |
10,949 | 161638ca16372bc0781c6691364201034ed37a3a | import copy
import time
from typing import TypeVar, Generic, List
from GoodToolPython.mybaseclasses.selfdelete import SelfDelete
import wx
from nose.tools import *
T_Node = TypeVar('T_Node')
T_Tree = TypeVar('T_Tree')
rootNode = 'root' # 根节点标志 这个值不重要
class Node(Generic[T_Node],SelfDelete):
"""
树上的节点
节点实... |
10,950 | 946b2f76557777ccd14cc1fcf337c4e69daf6d5c | import os
import sys
import jwt
import requests
import random
import datetime as dt
this_folder = os.path.dirname(os.path.realpath(__file__))
sys.path.append(this_folder + '/../')
from shared_env import *
from settings import SECRET_JWT
from schemas import base_users
from models import *
from app import app, db_sess... |
10,951 | 47530be6c62dd6707570bc602d3fdb5841082e45 | def my_start(sty, stm, std):
start = datetime.datetime(sty, stm, std);
return start;
|
10,952 | 2145afc3fbd54df73d3f3e0093d25a54ac3f3236 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC, LinearSVC
from sklearn.model_selection import learning_curve
from sklearn.model_selection import ShuffleSplit
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import Xception, Ince... |
10,953 | 12845f9dceb836a8c5f395a89d266b458a782958 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
10,954 | aee7961dc6e089628bd2ba56c14799f549efbd56 | from flask import render_template, session, redirect, url_for, request
from app import app
from .forms import RegisterForm, LoginForm, BlogForm, SearchForm
from .models import db, User, Post
@app.errorhandler(404)
def not_found_error(error):
searchform = SearchForm()
return render_template('not_found.html', s... |
10,955 | 77bc3821a096f4736463c730a24ceb4027ea4841 | import logging
import argparse
import psycopg2
logging.basicConfig(format='%(asctime)s %(message)s', filename="snippets.log", level=logging.DEBUG)
logging.debug('Debug message for the log file')
logging.info('Info message for the log file')
logging.warning('Warning message for the log file')
logging.debug("Connectin... |
10,956 | d285dfeb9a3c4046ddd6da7d3fe073ad809a140f | #!/usr/bin/env python
# nlidataset.py
# Copyright 2018 Mengxiao Lin <linmx0130@gmail.com>
#
import mxnet.gluon.data as gdata
import json
class NLIDataItem:
"""
Natural Language Inference data item class.
Simply acces `gold_label`, `sentence1` and `sentence2`
"""
gold_label = None
sentence1 = ... |
10,957 | c4ba2864d790e1dca7864f1990971bdf618b2605 | import numpy as np
symhex = np.zeros([3, 3, 12])
a = np.sqrt(3.)/2.
# 1
symhex[0, 0, 0] = 1
symhex[1, 1, 0] = 1
symhex[2, 2, 0] = 1
# 2
symhex[0, 0, 1] = -.5
symhex[1, 1, 1] = -.5
symhex[2, 2, 1] = 1
symhex[0, 1, 1] = a
symhex[1, 0, 1] = -a
# 3
symhex[0, 0, 2] = -.5
symhex[1, 1, 2] = -.5
symhex[2, 2, 2] = 1
symhex[0... |
10,958 | 4dd7c0b0f48d01d518cbb8d3687e74cea86afcbc | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 11 22:24:49 2021
@author: dell
"""
import gym
import numpy as np
import cartpole_swingup_envs
from stable_baselines3 import DQN,PPO
from stable_baselines3.dqn import MlpPolicy
env = gym.make('CartPoleSwingUpDiscrete-v0')
#model = DQN(MlpPolicy, ... |
10,959 | d6c1ae75b33f07d305d44185918620eed881c374 | from . import exceptions
import logging
import os
import urllib
log = logging.getLogger(__name__)
def filename_from(url):
"""Get the name of the file based off of the URL."""
filename = url.split('/')[-1]
return filename
def stream_to_file(response, destination):
"""Write contents of response to a ... |
10,960 | 3c9aabde8fde15edaec9d7dfed1f9499e01d6fc7 | import torch.nn as nn
from torch.nn import init
def initialize_weights(m):
if isinstance(m, nn.Linear):
init.xavier_uniform_(m.weight.data)
|
10,961 | b3a76a24f9747686cc7b844dffffe690ef601d81 | import os
from rest_framework import exceptions
class EngineManager(object):
""" Class to create engine manager to manage engine endpoints. This work in 3 modes:
mode fixed: only one URI, multiples UID
mode docker api: call to docker api to create new container for each session
mode aws: ... |
10,962 | 813ab6af9247241d8912ef504008fff78cbacd89 | # !/usr/bin/python
# -*- coding: UTF-8 -*-
import pandas as pd
from program.python.com.caicongyang.financial.engineering.timing_strategy import Signals # 同一级目录直接import
from program.python.com.caicongyang.financial.engineering.utils import FinFunctions
from program.python.com.caicongyang.financial.engineering.timing_... |
10,963 | 2162a011a7f125d926cb7d962e6bf2574e219958 | "Loaded immediately after Tk GUI is started. Has stdout/stdin!"
print "boot/startup.py: hello world!"
|
10,964 | fbaded2d7679d1210481b595e9f6132d516c2cc7 | import numpy as np
class Grid:
def __init__(self, width, height, start):
self.width = width
self.height = height
self.x = start[0]
self.y = start[1]
def setRewardsActions(self, rewards, actions):
# (x,y) --> reward
self.rewards = rewards
# (x,y) --> list of actions which are allowed
self.actions... |
10,965 | dafa8eb07026194957410a0e088002777ee0cec2 | from datetime import date
from peewee import *
from html.parser import HTMLParser
from random import randint
import peewee
import requests
import telebot
import time
db = SqliteDatabase("database.sqlite")
TOKEN = "295118557:AAFBcBNtPpkVCdiXgeUzPeN2bUzLEEHDkmI"
hello_image = open(file="faq.jpg", mode="rb")... |
10,966 | e4111053a73175bbc7eb72ba76404ac49b524a1e | import numpy as np
from tensorflow.keras.callbacks import EarlyStopping, TensorBoard
from tensorflow.keras.datasets import fashion_mnist
from tensorflow.keras.layers import LSTM, Dense
from tensorflow.keras.models import Sequential
from tensorflow.keras.utils import to_categorical
(x_train, y_train), (x_test, y_test) ... |
10,967 | 383efba0da244472015b5cb54c75bb4d5737717b | from __future__ import unicode_literals
import pilo
class WebhookForm(pilo.Form):
commit = pilo.fields.String('ref')
@commit.filter
def commit(self, value):
if 'refs/tags' not in value:
return pilo.NONE
return value
name = pilo.fields.String('repository.name')
orga... |
10,968 | 4a32953aa9b2036a55748d6458a950635b23d4c2 | from random import randint
from operator import itemgetter
#dados = {'a':2,'b':1,'c':10,'d':5}
dados={}
ranking = []
for i in range(4):
dados[f'jogador {i+1}'] = randint(1,6)
print(dados)
ranking = sorted(dados.items(), key=itemgetter(1), reverse=True) #Se fosse 0 e não 1, seria por chave,
print(ranking)
for i, v i... |
10,969 | 1d88e23600607f595de0a11dc15f8659cf1413f7 | import requests, math
import json
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from openbounty.models import Challenge, BountyUser, Backing
from openbounty.forms import MoneyForm
from openbounty.views import get_base_context
def profile(request):
if request.user.i... |
10,970 | f65dba2f9d0f4028ba2281d002a23fe69547c871 | # -*- coding: utf-8 -*-
"""
tests.api.product_tests
~~~~~~~~~~~~~~~~~~~~~~~
api product tests module
"""
from ..factories import CategoryFactory, ProductFactory
from . import OverholtApiTestCase
class ProductApiTestCase(OverholtApiTestCase):
def _create_fixtures(self):
super(ProductApiTestC... |
10,971 | 1b9b08f0c6566f192d47ab4b98df8726cf0276df | import sys
from sqlalchemy import create_engine
from app.factory import create_app
import app.models
from app.extensions import db
from app.config import config, SELECTED_CONFIG
class DBManage(object):
def __init__(self):
self.host = config[SELECTED_CONFIG].POSTGRES_HOST
self.engine = create_engine... |
10,972 | 6e8f32cdf259b4b095b561e753697c0a8b739f54 | from abc import ABC
from typing import Any, Dict, Mapping, Union
from beanie.odm.operators.find import BaseFindOperator
class BaseFindLogicalOperator(BaseFindOperator, ABC):
...
class LogicalOperatorForListOfExpressions(BaseFindLogicalOperator):
operator: str = ""
def __init__(
self,
*... |
10,973 | d33b1b2a3cc9907e25e13ef6111c07cac9addf3a | import openpyxl
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
#Things that need to be updated before running:
#Month reporting
month = 'September'
monthnum = 9
#Open Excel Spread... |
10,974 | 46d743eb86e837ced3b61f09673023c2257aa9ca | main_dict = {"A" : "71.03711",
"C" : "103.00919",
"D" : "115.02694",
"E" : "129.04259",
"F" : "147.06841",
"G" : "57.02146",
"H" : "137.05891",
"I" : "113.08406",
"K" : "128.09496",
"L" : "113.08406",
"M" : "131.04049",
"N" : "114.04293",
"P" : "97.05276",
"Q" : "128.05858",
"R" : "156.10111",
"S" : "87.03203",
"T" : "... |
10,975 | c971405001ed5d4fb73aba399b81de8f55e2ee51 | import codecs
from random import shuffle
class Song:
def __init__(self, artist, name, album, position, year, duration):
self.artist = artist
self.name = name
self.album = album
self.position = position
self.year = year
self.duration = duration
def __r... |
10,976 | d596f163d5863cd905598bb282778b26c5849e5e | import numpy as np
import torch
import random
'''
The function is to deal the softmax data:
if data is smallest, the data is set to 0.
and, the sum of smallest value is average to others
'''
def deal_mindata(data_array):
m, n = data_array.shape
for i in range(m):
data = data_array[i]
a_min =... |
10,977 | 5ae75a7abbbcd8558105e60b081fb9268027a8d4 |
def addOne(l):
# Treat the array l as a number
i = len(l) - 1
while i >= 0:
if l[i] < 9:
l[i] += 1
break
i -= 1
else:
l.append(0)
for j in range(len(l) - 1):
l[j] = 0
l[0] = 1
nb = []
for k in range(10):
addOne(nb)
pr... |
10,978 | 77285f30cd9364db2482307799c6226d589d35f4 | N = input()
color_list = [i for i in input().split()]
print('Four') if 'Y' in color_list else print('Three') |
10,979 | 5f63f566249e2a51d45feca248c45e22da02239d | from genericpath import isfile, isdir
from itertools import izip, count, ifilterfalse, ifilter
from os import remove, getcwd
from os.path import basename, exists
from shutil import rmtree
import sqlite3
import subprocess
from db_connection import DbCursor
from mysql.connector import errorcode
import mysql
import confi... |
10,980 | d8b4bc4cb3b18fe4270523351ee8e05074b6bf06 | import pickle
import math
import numpy as np
from sklearn.manifold import TSNE
from scipy.spatial import KDTree
class NNRecommendation:
def __init__(self, path, dataSize, leafSize):
self.path = path
self.dataSize = dataSize
self.leafSize = leafSize
def preprocess(self):
self.id... |
10,981 | aaeae8cba2d1de38086e6412665d3029ee81d2b0 | import random
import string
import os.path
import sys
from os import path
import settings
""" Creates a list of potential passwords equal to num_words
that contains a random combination of lowercase letters,
uppercase letters, and digits. Only run if Possible_pws
doesn't exist. """
def create_pw_list()... |
10,982 | 7ce447dd2b9876afdba5c3d835efbedde6c1cda6 |
from random import randint
import json
a = []
for _ in range(1400):
a.append(randint(1000, 5000))
with open('testData2.json','a') as f:
for _ in range(100):
tempJson = {'pH':a.pop(0),'P':a.pop(0),'K':a.pop(0),
'Ca':a.pop(0),'Mg':a.pop(0),'Na':a.pop(0),
'Cl':a.pop(0),'C... |
10,983 | 40fed0a5e1ac613e96536550520bd8f9b6e7b91c | from sqlalchemy.orm import Session
from core.dto.user_dto import UserLoginDto
from core.repository.user_repository import UserRepository
from core.use_case_output import Failure, Success
from core.use_case_output.failure_type import FailureType
class LoginUserUseCase:
def __init__(self, session: Session):
... |
10,984 | b11c59e8672a7ca69ab54fa8038e08378f728145 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
10,985 | 2046192c8308cb8c9be7bd2435e8ddacbb30be21 | import numpy as np
input_data = np.array([2,3])
weights = {'node_0':np.array([1,1]),
'node_1':np.array([-1,1]),
'output':np.array([2,-1])}
node_0_value = (input_data * weights['node_0'].sum)
node_1_value = (input_data * weights['node_1'].sum)
hidden_layer_values = np.array([node_0_value , node_1_va... |
10,986 | b6cb1c2ef3695df3d3d51d63f95f8e0b2d516ad7 | # Generated by Django 2.2.3 on 2019-07-15 09:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('libraries', '0005_auto_20190715_1418'),
]
operations = [
migrations.RenameField(
model_name='document',
old_name='documents'... |
10,987 | 08f30432018a104743b0f002240ab468d13325e6 | from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Serie)
admin.site.register(Stagione)
admin.site.register(Episodio) |
10,988 | 8505deefb19b1835e3ee767177a79dffbde5667d | # Define your compute function here.
# run python -m unittest test.hamming_test to ensure the
# unit tests pass and your code meets all of the conditions.
#
def compute(first_str, second_str):
if len(first_str) != len(second_str):
raise ValueError('DNA strands must be of equal length.')
return sum(fir... |
10,989 | d0bc0cf432a7c7d84371c886cb6c07aa8327cead | import numpy as np
import pandas as pd
import sklearn, sys, gc, scipy
import functions
blood_atlas_colours = pd.read_csv('/Users/pwangel/Atlas/data/blood_atlas_colours.tsv', sep='\t').set_index('Sample Source')
blood_atlas_colours = {key:value[0] for key, value in zip(blood_atlas_colours.index.values, blood_atlas_colo... |
10,990 | ab54fe4d2670e6bc6af95e9451372e2eac7a80bb | import os
from tqdm import tqdm
import json
import numpy as np
import collections
class_name=["财经","房产","健康","教育","军事","科技","体育","娱乐","证券"]
folderpath=[os.getcwd()+"/new_weibo_text/"+x for x in class_name] # 各文件夹的路径
init_num_by_cls=np.array([2375, 1211, 670, 445, 791, 1397, 3325, 2255, 1167]) #
def... |
10,991 | 769f57ddf6a61e8dd1b2daaf52f6554adc11cc2f | def find(x):
if root[x] == x:
return x
return find(root[x])
V, E = map(int, input().split())
data = []
root = [i for i in range(V+1)]
S = [1]*(V+1)
for i in range(E):
A, B, C = map(int, input().split())
data.append((C, A, B))
data.sort()
cnt = 0
for d in data:
w, n1, n2 = d
A = find(n... |
10,992 | ed455b83c84b6582671be287c276a7cd56e4a094 | espaco = open ("espaco.txt", "w")
for i in range (1):
espaco.write('''ACME Inc. Uso do espaço em disco pelos usuários
------------------------------------------------------------------------
Nr. Usuário Espaço utilizado % do uso
1 alexandre 434,99 MB 16,85%
2 anderson 1187,99 MB 46,02%
3 antonio 117,73 MB 4,56%
4 c... |
10,993 | afe6ff37484e04b6bbfafc936b3fb57b612a2198 | from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'test'
USERNAME = 'admin'
PASSWORD = 'Root110qwe'
db_url = 'mysql+pymysql://{}:{}@{}/{}?charset=utf8'.format(
USERNAME,
PASSWORD,... |
10,994 | 3bc5187e23fa8f0763263ad07c4f8e3177c78478 | # @Time : 2019-04-09 23:52:49
# @Author : lemon_xiuyu
# @Email : 5942527@qq.com
# @File : url_comfig.py
# 拼接URL 0119课后作业 自己练习的
from configparser import ConfigParser
from common import contants
class ReadConfig:
def __init__(self, file):
self.cf = ConfigParser()
self.cf.read(file, encoding='u... |
10,995 | 441531a653ad3a59331eab4a3f50f37c20d4ef97 | def isBabyGin(array) :
container = [0 for _ in range(10)]
for i in array :
container[i] += 1
for i in range(10) :
if container[i] >= 3 : return True
for i in range(8) :
if container[i] > 0 and container[i+1] > 0 and container[i+2] > 0 : return True
... |
10,996 | 4de91e750f91ab3e80e617ce3412f63e2987cd89 | #!/usr/bin/python
def xor(str1, str2):
if len(str1) != len(str2):
raise "errno: strings are not of equal length"
s1 = bytearray(str1)
s2 = bytearray(str2)
result = bytearray()
for i in range(len(s1)):
result.append( s1[i] ^ s2[i] )
return str(result)
def single_byte_xor... |
10,997 | 7ac322bb9eb90d48fadbc91d3ed89a79ce5ebb27 | x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
if y1 < y2: # Движение вверх по полю
# проверка диагонали
if (x1 == y1 and x2 == y2) or (abs(x2-x1) == abs(y2-y1)):
print('YES')
elif (x2 - x1) % 2 == 0 and (y2 - y1) % 2 == 0:
print('YES')
else:
print('NO')
el... |
10,998 | 3748575bda53d35cdb47957b2825403bef63e018 | from django import forms
from .models import Image,Profile,Comment
# class LocationForm(forms.ModelForm):
# class Meta:
# model=Location
# fields='__all__'
class ImageForm(forms.ModelForm):
class Meta:
model=Image
exclude=['username','likes','profile_pic']
class ProfileForm(f... |
10,999 | 4c7349377966dc2467f92839000d49ce31382fe5 | from __future__ import print_function
from itertools import count
import os
import numpy as np
import argparse
import torch
import torch.autograd
import torch.nn.functional as F
from torch.autograd import Variable
class LinearRegression(object):
"""Liner Regression Model"""
def __init__(self, ckp="/input/regression... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.