text stringlengths 38 1.54M |
|---|
# Data Preprocessing Template
# Importing the libraries
# Contains mathematical tools
import numpy as np
# Helps us plot nice chart
import matplotlib.pyplot as plt
# Best library for importing and managing data sets
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Data.csv')
# Matrix of feature... |
# Config file for tests/measure.py; previously tests/MeasureSources.paf.
# 'root' should be an instance of lsst.meas.algorithms.SourceMeasurementConfig (defined in measurement.py)
root.slots.centroid = "centroid.naive"
root.slots.apFlux = "flux.naive"
root.slots.modelFlux = "flux.gaussian"
root.slots.psfFlux = "flux.... |
import numpy as np
# 造伪样本
X = np.linspace(0, 100, 100)
X = np.c_[X, np.ones(100)]
w = np.asarray([3, 2])
Y = X.dot(w)
X = X.astype('float')
Y = Y.astype('float')
X[:, 0] += np.random.normal(size=(X[:, 0].shape)) * 3 # 添加噪声
Y = Y.reshape(100, 1)
from ml_models.linear_model import LinearRegression
impor... |
#!/usr/bin/env python3
from ev3dev.ev3 import *
from time import sleep
from random import choice
import pickle
import socket as socket_library
HOST = ""
PORT = 9999
LEGO_SLOPE = 3.6
QUEUE_CONTROL = 0
MANUAL_CONTROL = 1
A_STAR = 2
CELEBRATE = 3
OFF = 0
ON = 1
LEFT_MOTOR = 0
RIGHT_MOTOR = 1
# Messages sent to the... |
from django.conf.urls.defaults import patterns, include
urlpatterns = patterns('django.contrib.auth.views',
(r'^accounts/login/$', 'login', {'template_name': 'ui/login.html'}),
(r'^accounts/logout/$', 'logout', {'template_name': 'ui/logout.html'}),
)
urlpatterns += patterns('geppetto.ui.views.general',
('... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 8 17:33:23 2017
@author: jagan
"""
#*arg(Simple Argument) & **kwarg(Keyword Argument)
#* - Non Keyword variables ; args is idiom and not enforced
def normal_function(var1,var2):
print("var1:",var1)
print("var2:",var2)
def normal_funtion_one_var(var1,*arg... |
# Part of the implementation is borrowed and modified from BMT and video_features,
# publicly available at https://github.com/v-iashin/BMT
# and https://github.com/v-iashin/video_features
import argparse
import os
import os.path as osp
from copy import deepcopy
from typing import Dict, Union
import numpy as np
import... |
#/user/bin/python
# -*- coding: utf-8 -*-
import os
import sys
from qgis.core import *
import subprocess # pour utiliser subprocess.call()
import time
from PyQt4.Qt import *
def CreateFile(self):
"""creer un fichier"""
# open(self, 'parametre') permet en fonction du parametre de creer un fichier
create = open(sel... |
# Generated by Django 3.1.3 on 2020-12-12 16:23
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='About',
fields=[
('id', models.AutoField(au... |
from flask import Flask, request, jsonify, make_response
from flask_cors import cross_origin
from datetime import datetime
from dateparser import parse
import holiday_controller as hc
app: Flask = Flask(__name__)
@app.route('/holiday', methods=['POST'])
@cross_origin()
def calculate_pay():
body = request.json
... |
#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import String
from geometry.msgs import Twist,Vector3
from sensor.msgs import LaserScan
def getch():
""" Return the next character typed on the keyboard """
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings =... |
import os
import sys
import re
import subprocess
import shlex
import fcntl
import time
class Parser:
def __init__(self, data, debug=False):
self.data = data
self.line_number = 0
self.pipes = {}
self.main = []
self.capture_pipes = False
self.capture_main = False
... |
import ComputerPlayer as cp
class HumanPlayer(cp.ComputerPlayer):
"""
Human player - interpret events from game
"""
def __init__(self, game, board):
super().__init__(game, board)
def __str__(self):
return (self.__class__.__name__ + ": WhatStrategy Dunno")
def taketurn(self, ev... |
import json
import pickle
import matplotlib.pyplot as plt
import numpy as np
with open(snakemake.input.units_file,'r') as infile:
units_file = json.load(infile)
with open(snakemake.input.first_passage_times_v2,'rb') as infile:
passage_times = pickle.load(infile)
no_contact_intervals = passage_times['n... |
#Write a function rev_string(my_str) that uses a stack to reverse the characters in a string.
class Stack:
def __init__(self):
self.item=[]
def push(self,item):
self.item.insert(0,item)
def __str__(self):
return str(''.join(self.item))
def rev_string(my_str):
reverse=Stack()
for i in my_... |
import torch
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
from params import *
class EncoderCNN(nn.Module):
def __init__(self, input_size, hidden_size):
super(EncoderCNN, self).__init__()
self.hidden_size=hidden_size
self.embedding = nn.Embedding(input_size, 2*hidden_size)
sel... |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
from datetime import datetime
from unittest import mock
import pendulum
import pytest
import requests
from pydantic import BaseModel
from source_klaviyo.streams import Events, IncrementalKlaviyoStream, KlaviyoStream, ReverseIncrementalKlaviyoStream
START_D... |
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
'pkg-config': 'pkg-config',
'variables': {
'version_py_path': 'tools/build/version.py',
'v... |
# we are trying to get an input from the user - we need the number of month and it has to be an integer
def my_input(prompt=''):
try:
return input(prompt)
except NameError:
return input(prompt)
def time_frame():
try: # this is going to ask for the months to be inputted - but we will conve... |
import copy
import celery
from src.constants import Platform
from src.models import Playlist
from src.message_formatters import SlackMessageFormatter
from src.music_services import TrackInfo
from src.utils import (
add_track_to_playlists,
fuzzy_search_from_string,
fuzzy_search_from_track_info,
get_tra... |
from django import forms
from django.db.models import fields
from .models import Participant
# model form
# class RegistrationForm(forms.ModelForm):
# class Meta:
# model=Participant
# fields=['email']
# form object
class RegistrationForm(forms.Form):
email=forms.EmailField(label='your email') |
"""
###################################
Random (``methods.seeding.random``)
###################################
Random is the simplest MF initialization method.
The entries of factors are drawn from a uniform distribution over
[0, max(target matrix)). Generated matrix factors are sparse matrices with the
default den... |
# O(n) time | O(1) space
def maxSubsetSumNoAdjacent(array):
if not len(array):
return
elif len(array) == 1:
return array[0]
second = array[0]
first = max(array[0], array[1])
for i in range(2, len(array)):
current = max(first, second + array[i])
second = first
first = current
return first
print(maxSubse... |
from rest_framework.response import Response
from rest_framework.views import APIView
from store.api.serializers import ProductSerializer, CategorySerializer
from store.models import Product, Category
class ProductList(APIView):
def get_products(self):
return Product.objects.filter(in_stock=True)
d... |
"""
Title: Prosfora : Social Media for Artists
Author: Gagan Deep Singh, Mayank Setia, Ritik Bhatnagar
Languages: Python, HTML, CSS, JavaScript, jQuery
"""
from flask import (Flask, render_template,
jsonify, request,
redirect, flash, send_file)
from flask_bootstrap impo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 13. Faça um Programa que leia um número e exiba o dia correspondente da semana. (1 - Domingo, 2 - Segunda, etc.), se digitar outro valor deve aparecer valor inválido.
dias_da_semana = ["Inválido", "Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"]
print... |
from django.shortcuts import render
from myapp.models import *
# Create your views here.
def index(request):
return render(request, "index.html")
# Display all()
def display(request):
data_topic = Topic.objects.all() # Topic is the Class name / Table name
data_webpage = Webpage.objects.all() # Webpage i... |
##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2011-2012, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... |
import argparse
import os
import imageio
def main():
parser = argparse.ArgumentParser()
parser.add_argument("folder", help="Pasta com ppms para converter para JPG")
args = parser.parse_args()
# images.append(imageio.imread(filename))
folder = os.path.abspath(args.folder)
onlyfiles = [f for f ... |
import os
from PyQt5.QtWidgets import QDialog, QMessageBox
from ui.patch import Ui_PatchDialog
from utils import AsmUtil
class patchForm(QDialog,Ui_PatchDialog):
def __init__(self, parent=None):
super(patchForm, self).__init__(parent)
self.setupUi(self)
self.setWindowOpacity(0.93)
... |
from future import standard_library
standard_library.install_aliases()
from builtins import object
import operator
import array
import urllib.request, urllib.parse, urllib.error
import urllib.request, urllib.error, urllib.parse
import json
import uservoice
from requests_oauthlib import OAuth1
from urllib.parse import p... |
# Copyright 2011 OpenStack Foundation
#
# 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 l... |
import ConfigParser
from config.server import ServerConfig
from net.server import TerrariaServer
def load_config():
config = ConfigParser.RawConfigParser()
config.read('server.cfg')
return ServerConfig().from_config(config)
def main():
config = load_config()
server = TerrariaServer(config)
server.run()
... |
#coding=utf-8
__author__ = '冬冬'
from CheckOnline.ping import ping
import threading
lock = threading.Lock()
ipAddressDict={}
def scan(ip,timeout = 0.1):
global ipAddressDict
if ping(ip,timeout) != None:
lock.acquire()
ipAddressDict[ip] = 'YES'
lock.release()
else:
lock.acquire()
ipAddressD... |
# Ano 2018
# exercício realizado durante o curso
# @jadilson12
#escreva um programa para aprovar o emprestimo bancario para comprar uma casa.
casa = float(input("Valor da casa: R$"))
salario = float(input("Salário do comprador : R$"))
anos = int(input("Quantos anos de finaciamento: "))
pestacao = casa / (anos ... |
import cv2
import mss
import imutils
import os
import sys
import time
import datetime
from imutils import contours
import numpy as np
def referenceGrabber(n=0):
return
def grabber(pair_title,n,sct):
top, left = 20, 4
width, height = 72, 119
monitor_number = 2
mon = sct.monitors[mo... |
from airflow import models
from airflow.contrib.operators.dataproc_operator import DataprocClusterCreateOperator, DataprocClusterDeleteOperator, DataProcPySparkOperator
from datetime import datetime, timedelta
from operators.http_to_gcs import HttpToGcsOperator
default_args = {
'owner': 'AirFlow',
'start_date'... |
#coding=utf-8
import time,json,hashlib,os,rsa
import sys,re,base64,requests
from config import config
class rsaEncryption:
def __init__(self):
pass
#方法名称:RSA公钥加密函数
def PublicRSA(self,PartJsonParameter):
publicKey =b"""-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ... |
##########
#Question#
##########
'''
URL: https://leetcode.com/problems/search-insert-position/
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
Example 1:
Input: nums = [1,3,5,6], target ... |
#!/usr/bin/python3.8
# This is a Proof of concept about BufferOverflow vulnerability in MiniShare 1.4.1
# Part 2 of proof of concept by Vry4n
# This script is intended send all the buffer size in one packet, we need to see if EIP value gets overwritten 41414141 (AAAA)
import socket
FUZZ = "A" * 1800
print("Fuzzing w... |
import logging
import asyncio
import pickle
import ssl
from message_types import measurement_msg
_logger = logging.getLogger(__name__)
def create_ssl_context(ssl_dict):
"""
loads the ssl certificate for secure communication
:param ssl_dict: dictionary consisting of certification file, key
... |
from pythonforandroid.recipes.setuptools import SetuptoolsRecipe
assert SetuptoolsRecipe._version == "51.3.3"
assert SetuptoolsRecipe.depends == ['python3']
assert SetuptoolsRecipe.python_depends == []
class SetuptoolsRecipePinned(SetuptoolsRecipe):
sha512sum = "5a3572466a68c6f650111448ce3343f64c62044650bb8635e... |
# Generated by Django 3.1.5 on 2021-02-03 11:10
from django.db import migrations, models
import django.db.models.expressions
class Migration(migrations.Migration):
dependencies = [
('api', '0003_auto_20210203_1106'),
]
operations = [
migrations.RemoveConstraint(
model_name='... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def printL(head):
while(head!=None):
print head.val,
head = head.next
print ''
class Solution(object):
def confire(self, head, k):
if (head == None)... |
import datetime as dt
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
#################################################
# Database Setup
###############################... |
def distance_from_zero(number):
if type(number) == int or type(number) == float :
positive = abs(number)
print("The number :\n", positive , "true")
else:
print("Nope")
distance_from_zero("dfkk")
|
from cards_and_decks import *
from base_set import *
class Loan(Treasure):
def cost(self):
return 3
def value(self):
return 1
def text(self):
return [
"When you play this, reveal cards from your deck until you " + \
"reveal a Treasure. Discard or it trash i... |
number = 0
while number < 100:
number = number + 1
if number / 10 == 3:
print("짝!!!")
elif number / 10 == 6:
print("짝!!!")
elif number / 10 == 9:
print("짝!!!")
elif number % 10 == 3:
print("짝!!")
elif number % 10 == 6:
print("짝!!")
elif number % 10 == 9:
print("짝!!")
else:
print(number)
|
import sys
import numpy as np
from numpy.lib.function_base import delete
def gridToGraph(n,m):
# Created vertice grid of n x m size
grid = [(i,j) for j in range(m) for i in range(n)]
gridVer = np.zeros((n,m), dtype=int)
# Create mapping from each grid coords to vertice id (0..n)
names = dict()
... |
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
import string
import random
from utils import str_to_date
class Doctor(models.Model):
user = models.OneToOneField(User, primary_key=True)
token = models.CharField(max_length=200)
current_pat... |
from spectrum import arma2psd, arburg # pip install spectrum
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
from pandas import DataFrame
from pandas import Series
from pandas import concat
from pandas impo... |
import esp
import dht
import time
import json
import machine
import network
from umqtt.simple import MQTTClient
p = machine.Pin(2, machine.Pin.OUT)
p.on()
p2 = machine.Pin(4, machine.Pin.PULL_UP)
d = dht.DHT11(machine.Pin(2))
BLINK_DELAY=0.1
MEASR_DELAY=2
def blink():
p.off()
time.sleep(BLINK_DELAY)
p... |
"""
Solution for 50. Pow(x, n)
https://leetcode.com/problems/powx-n/
"""
class Solution:
"""
Runtime: 28 ms, faster than 64.49% of Python3 online submissions for Pow(x, n).
Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Pow(x, n).
"""
def myPow(self, x: float, n: int) -> float:
... |
import logging
logging.basicConfig(filename='logloglog.log', level=logging.INFO)
logging.INFO('lalala')
|
from distutils.version import LooseVersion
from . codes import CMDTYPE, LEDTYPE, SPIChipsets, BufferChipsets
from bibliopixel.drivers.return_codes import RETURN_CODES, print_error
from bibliopixel.util import log, util
from bibliopixel.project.importer import import_symbol
class Devices(object):
"""Manage a list ... |
import matplotlib.pyplot as plt
import math
import os.path
def plot(plot_star=1, plot_gas=1, plot_mid=0, x_axis="dynamical", SFE=[0.5, 0.5], SFEN=[], log_SFR=[7, 8], IMF="Kroupa"):
# SFR = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8] # log_10 star formation rate [solar mass/yr]
# SFD = [2.65, 1.77, 1.24, 0.93, 0.67, 0.4... |
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django_auth_sgf.backend import SGFBackend
class Command(BaseCommand):
help = 'Syncs the RA and Hall Staff users'
def handle(self, *args, **options):
## Find all HallStaff and RAs to update them fir... |
'''
Time O(n)
Space O(1)
'''
def isOneEditAway(str1, str2):
if abs(len(str1) - len(str2)) > 1:
return False
if len(str1) == len(str2):
return isOneReplaceAway(str1, str2, "edit")
if len(str1) > len(str2):
return isOneReplaceAway(str1, str2, "add")
if len(str1) < len(str2):
return isOneReplaceAway(str2, s... |
# I decided to convert Jupyter notebook to ordinary python script for straightforward evaluation
import numpy as np
import pandas as pd
import json
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from lightgbm.sklearn import LGBMClass... |
from tkinter import *
import tkinter.messagebox as msgbox
def savetofile():
f = open("telefonnummer.txt", "a")
f.write(entName.get() + " " + entTele.get() + "\n")
f.close()
root = Tk()
lblName = Label(root, text="Namn : ")
lblName.grid(row=0, column=0)
lblTele = Label(root, text="Tele: ")
lblTele.grid(r... |
from django.db import router
from django.urls import path
from django.urls.conf import include
from .views import eliminar_juego, index, modificar_juego
from .views import formulario
from .views import galeria
from .views import listado_juegos
from .views import nuevo_juego
from .views import JuegoViewSet
from rest_... |
from .firefighter_views import *
from .home_view import *
from .vehicle_views import *
from .equipment_views import *
from .service_views import *
from .history_equipment_views import *
from .history_vehicle_views import *
from .users_management_views import *
|
# mnist.py
import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Input, UpSampling2D
from keras.models impo... |
import random
#1.---CREATE PLAYER---
# 1.1 --Create Player Class--
class Player:
def __init__ (self, vitals, measurements, traits,
threepoint_scoring, midrange_scoring, close_scoring, scoring_instincts, free_throw, driving_finesse,
driving_strong, onballD_perimeter, onballD_post, team_defense, stealing,... |
#longitud25
cadena ="La única discapacidad en la vida es una mala actitud"
msg ="la longitud del tex es {}"
tex = cadena[19:-21]
print(msg.format(len(tex)))
|
# -- coding: utf-8 --
name = 'Yay Shin'
age = 19 # not a lie
height = 64 # inches
weight = 110 # lbs
eyes = 'Brown'
teeth = 'White'
hair = 'Brown'
print "Let's talk about %s." % name
print "She's %d inches tall." % height
print "She's %d pounds heavy." % weight
print "Actually that's not too heavy."
print "She's got %... |
deep_learning = [
"('deep', 'learn')",
"kera",
"('neural', 'network')",
"tensorflow",
]
machine_learning = [
"classif",
"cluster",
"ensembl",
"('gradient', 'boost')",
"graph",
"knn",
"machin",
"model",
"('mont', 'carlo')",
"('natur', 'languag')",
"('parallel'... |
# [Classic, Coloring-Bipartition]
# https://leetcode.com/problems/is-graph-bipartite/
# 785. Is Graph Bipartite?
# History:
# Facebook
# 1.
# Mar 19, 2020
# 2.
# May 8, 2020
# Given an undirected graph, return true if and only if it is bipartite.
#
# Recall that a graph is bipartite if we can split it's set of nodes ... |
# -*- coding: utf-8 -*-
# 时间 : 2018/10/14 22:36
# 作者 : xcl
#属性变换
import pandas as pd
#参数初始化
discfile = 'C:\\Users\\Administrator\\Desktop\\DiskCapacityPrediction\\data\\discdata.xls' #磁盘原始数据
transformeddata = 'C:\\Users\\Administrator\\Desktop\\discdata_processed.xls' #变换后的数据
data = pd.read_excel(discfile)
dat... |
import sys
sys.path.append("/home/whyjay/caffe/python")
sys.path.append("/usr/lib/python2.7/dist-packages/")
import cv2
import numpy as np
import skimage
from IPython import embed
def crop_image(x, target_height=227, target_width=227):
image = skimage.img_as_float(skimage.io.imread(x)).astype(np.float32)
if l... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class TiebaBnItem(scrapy.Item):
keyword = scrapy.Field()
url = scrapy.Field()
title = scrapy.Field()
tz_id = scrapy.Field()
source ... |
C1, C2, C3, C4 = input().split(" ")
if int(C1) == 1:
print(1)
elif int(C2) == 1:
print(2)
elif int(C3) == 1:
print(3)
else:
print(4) |
# -*- coding: UTF-8 -*-
# https://blog.csdn.net/tian_123456789/article/details/78914692
import os
import re
import numpy as np
class Student: #定义一个学生类
def __init__(self):
self.name = ''
self.ID =''
self.score1 = 0
self.score2 = 0
self.score3 = 0
self.sum = 0
def s... |
import numpy as np
import matplotlib.pylab as pl
x = np.loadtxt('./data/x.txt')
y = np.loadtxt('./data/y.txt')
p = np.loadtxt('./data/p.txt')
print(sum(p))
pl.figure(figsize=(10.,10.), dpi=1000)
pl.xlim((300,500))
pl.ylim((250,450))
pl.tricontourf(x,y,p, 300,cmap='hot')
#pl.tricontour(x,y,p, 300,cmap='hot')... |
import time
import schedule
import tweepy
from argparse import ArgumentParser
from src.generator import Generator
import logging
from logging import getLogger
from src.log import init_logging
init_logging(level = logging.INFO)
logger = getLogger(__name__)
def gen_api(CK, CS, AK, AS):
auth = tweepy.OAuthHandler(CK,... |
import os
import json
import requests
import zipfile
from django.db import models
from django.utils.functional import cached_property
import pygame
from common.models import ModelBase
from mapper import consts
pygame.mixer.init()
class Mapper(ModelBase):
# 取り込みデータ
id = models.CharField(verbose_name="Mapper... |
#https://leetcode.com/problems/power-of-three/
def isPowerOfThree(n):
if n < 1: return False
while n % 3 == 0:
n = n/3
return n == 1
def isPowerOfThree(n):
#check if log(n, 3) is an integer
return n > 0 and abs(math.log(n, 3) - round(math.log(n, 3))) < 1e-10
def isPower... |
import os
def run(DATA_DIR, INCEPTION_CHECKPOINT, MODEL_DIR, TRAIN_STEPS, GPU_DEVICE = 0, VOCAB_FILE=""):
'''
:param DATA_DIR: str, Path to the directory containing TF Records files
:param INCEPTION_CHECKPOINT: str, Path to the directory containing the checkpoint file
:param MODEL_DIR: str, Path to dir... |
import sys
from collections import defaultdict
pair_record = set()
sequence = defaultdict(int)
for line in sys.stdin:
vid1, vid2 = map(int, line.split())
sequence[vid1]+=1
sequence[vid2]+=1
try:
n = int(sys.argv[1])
for v in range(n):
k = sequence[v]
print('{} {}'.format(v, k)... |
from django import forms
from cloudinary.forms import CloudinaryJsFileField, CloudinaryUnsignedJsFileField
from cloudinary.forms import CloudinaryFileField
from django.contrib.auth.forms import UserCreationForm,UserChangeForm
from django.contrib.auth import (
authenticate,
get_user_model,
login,
logou... |
import cards as c
def run_sim(scores, times):
#---------------------------------------------------
# Data Dictionary
#---------------------------------------------------
# deck to hold the cards
deck = c.Deck()
# loop invariant
busted = False
# Player
player = c.Player()
# g... |
import argparse
import sys
import numpy as np
import pickle
from multiprocessing import Process, Queue, cpu_count
from puzzle_maker import build_new_puzzle, display_grid
from solve_puzzle import search, await_solution
from typing import Dict
def _solve(puzzle: np.ndarray, p: int) -> None:
q = Queue()
processe... |
# encoding=utf-8
##############################################################################################
# @file:doubanComments.py
# @author:Liyanrui
# @date:2016/11/17
# @version:Ver0.0.0.100
# @note:豆瓣电影选“电影”获取评论的文件
###############################################################################################... |
#Guess the number game
import random
secretNumber = random.randint(1,100)
print("I am thinking of a number between 1 and 100.")
#Ask for a guess
x = range(1,7,1)
for guessTally in x:
print("Make a guess:")
guess = int(input())
if guess < secretNumber:
print("Too Low!")
elif guess > secretNum... |
from django.contrib.auth import authenticate, login as django_login
from django.shortcuts import render, redirect
# Create your views here.
from django.contrib.auth.hashers import make_password, check_password
from django.http import JsonResponse
from django.urls import reverse
from .models import UserToken, Info
fro... |
try:
from PIL import Image
except ImportError:
import Image
import pytesseract
print (pytesseract.image_to_string(Image.open("solved.jpg")))
output = ''
for i in range(1, 577):
name = "%s.jpg" % i
c = pytesseract.image_to_string(Image.open(name))
print ("%s - %s" % (name, c))
output += c
print... |
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
if len(arr) == 0:
return 0
left_end, right_end = 0, len(arr)-1
while left_end < len(arr)-1:
if left_end+1 < len(arr) and arr[left_end+1] < arr[left_end]:
break
... |
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import pandas as pd
df_visual_data = pd.read_csv('visualize_I258_2015_inaccuracy.csv')
df_visual_data_2018 = pd.read_csv('visualize_radius_group_indices_frame_2018.csv')
sign_to_plot = int(input("Please enter the sign you want to plot"))... |
# 3. A client sends to the server a string. The server returns the reversed string to the client (characters from the end to begging)
import socket, struct
def read_string(source):
c = ''
s = ''
while( c != '\n'):
c = source.recv(1)
s+=c
return s[:-1]
def solve_client(client):
string = read_string(client)... |
'''
- Methods (functions):
def function(**kwargs, *args):
-actions-
-checkers-
-loggers-
-returns-
-exceptions-
''' |
from django import forms
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q, Count
from django_serializer.base_views import (ListView, DetailsView,
CreateView, DeleteView, BaseView)
from django_serializer.exceptions import ServerError
from... |
x=[]
max=0
for i in range(9):
x.append(int(input()))
if x[i]>=max:
max = x[i]
count = i+1
print(max)
print(count)
# print((x.index(max))+1) ##list에서 index 사용 |
from mpi4py import MPI
rank = MPI.COMM_WORLD.Get_rank()
size = MPI.COMM_WORLD.Get_size()
name = MPI.Get_processor_name()
msg = ("Hello, World! "
"I am process %d of %d on %s\n" %
(rank, size, name))
import sys
sys.stdout.write(msg)
|
MODULE_NAME = 'close-session'
MODULE_DESC = "Remove an account's session"
MODULE_VER = '1.0'
def START(db, *args):
"""Remove Darkstar account sessions"""
import argparse
AP = argparse.ArgumentParser('ffxi-tools ' + MODULE_NAME,
description='Removes a session')
AP.add_argume... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
# loading image
img0 = cv2.imread('gaussian 1.png')
# converting to gray scale
gray = cv2.cvtColor(img0, cv2.COLOR_BGR2GRAY)
# remove noise
#img = cv2.GaussianBlur(gray,(3,3),0)
sobelx = cv2.Sobel(img0,cv2.CV_64F,1,0,ksize=3) # x
sobely = cv2.Sob... |
class Node(object):
def __init__(self, value):
self.value = value
self.right = None
self.left = None
class BinaryTree(object):
def __init__(self, root):
self.root = root
def preorder_search(self, start, value):
if start:
if start.value == value:
... |
from typing import List
from typing import Tuple
from typing import Union
from typing import Dict
import torch
import syft as sy
from syft.workers.abstract import AbstractWorker
class State(object):
"""The State is a Plan attribute and is used to send tensors along functions.
It references Plan tensor or p... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 3 11:57:11 2019
@author: emilyhoward
"""
import math
import numpy as np
quad = np.zeros ([0,2])
negativeone = np.zeros ([0,2])
P = 30
def primecheck(x):
if x==1:
return False
for ii in range(2,math.floor(np.sqrt(x))+1):
if x... |
from django.db import models
# Create your models here.
# Model for an Errand that includes the name of the errand and whether it has been finished
class Errand(models.Model):
name = models.CharField(max_length=250)
finished = models.BooleanField(default=False, blank=True, null=True)
def __str__... |
import json
def main():
with open('county_demographics.json') as demographics_data:
counties = json.load(demographics_data)
print(alphabetically_first_county(counties))
print(county_most_under_18(counties))
print(percent_most_under_18(counties))
print(most_under_18(counties))
p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.