text stringlengths 38 1.54M |
|---|
from sqlalchemy import func
from application import db
class Favorite(db.Model):
__tablename__ = "Favorite"
source_id = db.Column(db.Integer, db.ForeignKey("Profile.id"), nullable=False)
target_id = db.Column(db.Integer, db.ForeignKey("Profile.id"), nullable=False)
date_created = db.Column(db.DateTime, default... |
#!/usr/bin/python
import socket
host = ''
port = 18000
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
s.listen(2)
conn,addr = s.accept()
print 'Got connection from:',addr
while 1:
data = conn.recv(4096)
if not data:break
conn.sendall(data)
conn.close()
|
"""
Provides the data structure for the degrees of freedom manager.
"""
# IMPORTS
import numpy as np
from scipy import sparse
# DEBUGGING
from IPython import embed as IPS
class DOFManager(object):
"""
Connects the finite element mesh and reference element
through the assignment of degrees of freedom to i... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 29 09:57:02 2016
@author: juliette
"""
from IPython.display import display
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from utils_preprocessing import date_format, date_to_str, fill_holidays, date_to_str_2
from challenge_constants import *
from ... |
# -*- coding: utf-8 -*-
import MySQLdb
star_info_list = [
'name',
'english_name',
'profession',
'zodiac',
'gender',
'height',
'weight',
'blood_group',
'birthday',
'birthplace',
'relationship',
'biography',
]
class Star(object):
def __init__(self):
self.inf... |
import json
import directories
from WorldConverter.itemMapping.convert import convertItem
blockEntityToIntermediate = json.load(open(directories.getFiltersDir()+'/WorldConverter/tileEntityMapping/_intermediate.json'))
blockEntityFromIntermediate = {}
blockEntityFromIntermediate['PC'] = json.load(open(directories.getFi... |
def CI(P, R, T):
i=1
while i<=T:
result = (P*R*1)/100
P = P + result
i+=1
print("CI = ", P)
print("Here is a program to find out the COMPOUND INTEREST :-\n")
P = float(input("Enter the Starting amount : ₹"))
R = float(input("Enter Rate : "))
T = int(input("Enter time in Year : "))... |
import sys
data = []
money = 100
shares = 0
for line in sys.stdin:
data.append(int(line))
prices = data[1:]
turningpoints = [0]
if len(prices) == 1:
money = 100
else:
if prices[0] < prices[1]:
shares = int(money/prices[0])
money -= shares*prices[0]
for i in range(1,len(price... |
# chapter 3
# Import package
# Definition of radius
r = 0.43
# Import the math package
import math
from math import radians
# Calculate C
C = 2*math.pi*r
Crad = radians(360)*r
# Calculate A
A = math.pi*r**2
Arad = radians(180)*r**2
# Build printout
print("Circumference: " + str(C))
print("Circumference using radia... |
# -*- coding: utf-8 -*-
import sys
import datetime
import os
import pygame
import pygame.locals
import time
import dMVC.remoteclient
import ocempgui.widgets
import GG.isoview.login
import GG.utils
import GG.isoview.guiobjects
#Constants
VERSION = "0.17.1-3"
VERSION_TITLE = "GenteGuada "+VERSION
CLEAR_CACHE_WEEKS = 4
... |
def convert_to_scream(text):
# A scream is all-caps and ends with an exclamation mark
return text.upper() + '!'
message = input('Wat wil je schreeuwen?: ')
loud_message = convert_to_scream(message)
print(loud_message)
|
# 5
# X S X X T
# T X S X X
# X X X X X
# X T X X X
# X X T X X
# https://www.acmicpc.net/problem/18428
from itertools import combinations
def dfs(teacher, room, d):
x, y = teacher
for i in range(4):
if i != d:
continue
nx = x + dx[i]
ny = y + dy[i]
if not (0 <= ... |
from tkinter import*
from PIL import Image, ImageTk
from customer import Customer_Window
class Hotel_Management_System:
def __init__(self, root):
self.root = root
self.root.title("Hotel Management System")
self.root.geometry("1920x1080+0+0")
# --------Header Image-------
... |
#coding:utf-8
import datetime
import web
import op_reader
import op_book
import op_borrow
from model_base import ModelBase
from model_giveback import ModelGiveback
from model_lost import ModelLost
class ModelRenew(ModelBase):
def check_borrexp(self, borrnow):
return borrnow.borrexpdt.date() >= ... |
from rest_framework import serializers
from Blog.models import MovieShots
class MovieShotsSerializer(serializers.ModelSerializer):
class Meta:
model = MovieShots
fields = '__all__' |
import unittest
from . import utils as TE
class TestReqifEnumValue(unittest.TestCase):
def setUp(self):
self.obj = TE.TReqz.reqif_enum_value()
def test_name(self):
self.assertEqual("ENUM-VALUE", self.obj.name)
def test_decode(self):
TE.utils.testDecodeIdentifiableAttributes(self,... |
# Django settings for mango project.
from django.utils.translation import ugettext_lazy as _
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME' : os.p... |
import logging
import os
from wikipedia import page
import word2vec.word2vec_utitlity as util
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
logger = logging.getLogger("TrainingDataImporter")
class WikipediaPageProcessor:
"""
"""
file_prefix = "wiki_"
... |
# -- coding: utf-8
x=int(input())
x1=x//1000
x2=x%1000//100
x3=x%1000%100//10
x4=x%1000%100%10
print ('У числа ', x, 'максимальная цифра равна ', max(x1, x2, x3, x4)) |
#! /usr/bin/python
"""
Phase recovery from two measured intensity distributions using Gerchberg Saxton.
.. :copyright: (c) 2017 by Fred van Goor.
:license: MIT, see License for more details.
"""
import matplotlib.pyplot as plt
import numpy as np
from LightPipes import *
print(LPversion)
#Parameters used for ... |
# Empty class sample
class EmpltyClass:
pass
# Sample var & Method declaration
class FirstLevelSample:
print('First Hello From FirstLevelSample Class')
f1 = FirstLevelSample()
e = EmpltyClass()
print(e) |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('realms', '0017_auto_20171213_1943'),
]
operations = [
migrations.AlterField(
model_name='page',
name... |
import torch
class Placeholder(torch.nn.Module):
"""
This model is used when doing predictions directly on embeddings.
It allows the training infrastructure to be used as normal, but
not pass data through the normal base_encoder.
Note that the out_shape is None.
"""
def __... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Alexander Maul
#
# Author(s):
#
# Alexander Maul <alexander.maul@dwd.de>
#
# 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, ... |
from math import *
import numpy as np
import random
import sys
def identity(x): return x
class Cost(object):
""" """
def __init__(self, type='Bernoulli'):
self.type = type
if type == 'Bernoulli':
self.F = Cost.Bernoulli_function
self.D = Cost.Bernoulli_derivative
... |
from typing import List
# The following 3 lines of codes are for UnitTest and you don't need them for your real applications!
global shopping_list
global stock
global prices
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"ba... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
CS671 - Deep Learning and Its Applications
Even Semester 2018
Assignment 1, Group 3
Input generation for Q1.
"""
import sys
from random import randint, uniform
# Integers.
file = open("../data/input/q1/input1.txt", "w")
sys.stdout = file
for _ in range(10):
p... |
import inspect
import time
import numpy as np
import matplotlib.pyplot as plt
from skimage import io
import tensorflow as tf
from app_global import FLAGS
from tensorflow.examples.tutorials.mnist import input_data
from rbm_engine import Rbm_Engine
from mlp_engine import Mlp_Engine
class Dbn_Engine(object):
# 采用习惯用法... |
import logging
from typing import List
from fastapi import APIRouter, Depends, HTTPException, Response, status, Request
from fastapi.param_functions import Body, Path
from ..models.embedding import DocumentEmbedding
from ..models.httperror import HTTPError
from ..models.index import Index, IndexRequest, IndexStatus
f... |
import os
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
import tempfile
try:
from misc import *
from decoder_generator_base import DecoderGenerator
except ImportError:
from .misc import *
from .decoder_generator_base import DecoderGenerator
class cDecoderGenerator(DecoderGene... |
# 616. Add Bold Tag in String
# Medium
# 35538FavoriteShare
# Given a string s and a list of strings dict, you need to add a closed pair of bold tag <b> and </b> to wrap the substrings in s that exist in dict. If two such substrings overlap, you need to wrap them together by only one pair of closed bold tag. Also, i... |
import numpy
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
return float(numpy.median(nums1+nums2))
if __name__ == "__main__":
num1 = [1, 2]
num2 = [3, 4]
s = Sol... |
from copy import deepcopy
import square
import queue
class Board:
def __init__(self):
self.MOVES = {
"up": self.get_valid_neighbor_up,
"down": self.get_valid_neighbor_down,
"left": self.get_valid_neighbor_left,
"right": self.get_valid_neighbor_right,
}
self.width = -1
self.he... |
#!/usr/bin/env python2.6
# -*- coding: utf-8 -*-
# db.py
# Pomodoro
#
# Created by Roman Rader on 20.08.11.
# New BSD License 2011 Antigluk https://github.com/antigluk/Pomodoro
"""
Data base controller.
"""
from singleton import Singleton
from options import PomodoroOptions, ConfigError
from pomodoro_entity impo... |
import pandas as pd
'''
df=pd.DataFrame([["jack",24],["rose",18]],columns=["name","age"])
df.to_csv("person.csv")
'''
url="https://github.com/venky14/Machine-Learning-with-Iris-Dataset/blob/master/Iris.csv"
columns=["Id","SepalLengthCm"]
df=pd.read_csv(url,delimiter="\n",names=columns)#index_col=["Id"])
print(df.head(2... |
# Imports ---------------
from guizero import App, Text, Waffle, Window , PushButton, TextBox, Picture, Box
from random import randint
import random
# ------------------------------
# Variables Flood IT
# ------------------------------
colours = ["red", "blue", "green", "yellow", "magenta", "purple"]
boar... |
def merge_array(arr1, arr2):
return ' '.join(map(str, sorted(arr1+arr2,reverse=True)))
t = int(input())
for i in range(t):
N = input()
arr1 = list(map(int, input().split()))
arr2 = list(map(int, input().split()))
print(merge_array(arr1, arr2))
|
from menu.interface_menu import InterfaceMenu
class SupportMenu(InterfaceMenu):
def __init__(self, bot, user):
super().__init__(bot, user)
self.msgs.append(self.lang.SUPPORT_MSG)
def handle_message(self, message):
return super().handle_message(message) |
import json
import urllib
from collections import Counter
from pprint import pprint
import tsne
import plsa
import numpy as np
import sys
#import pylab
import math
kimpath = "http://www.kimonolabs.com/api/8fxfaiu6?apikey=fb110eb5d4c1775fbf3e9840e88f4f3a"
#kimpath = "http://www.kimonolabs.com/api/9d6lg708?apikey=524... |
import os
import os.path
from codebuilder.utils import util
CONFIG_DIR = os.environ.get('CONFIG_DIR', '/etc/codebuilder')
CONFIG_FILES = []
LOG_LEVEL = 'debug'
LOG_DIR = '/var/log/codebuilder'
LOG_FILE = None
LOG_INTERVAL = 6
LOG_INTERVAL_UNIT = 'h'
LOG_FORMAT = (
'%(asctime)s - %(filename)s - %(lineno)d - %(lev... |
from nutritionix import Nutritionix
from logos import getlogo
# Application ID:
appid = 'ffb27ccd'
# API Key:
apikey = '516561556bb62da642a4824b86084d02'
nix = Nutritionix(app_id=appid, api_key=apikey)
def search_calls(searchTerm):
itemID=None
pizza2 = nix.search(searchTerm) # , results="0:1")... |
import numpy as np
from nltk import sent_tokenize
import json, requests
# java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -port 9000 -timeout 15000000
class StanfordCoreNLP:
"""
Modified from https://github.com/smilli/py-corenlp
"""
def __init__(self, server_url):
# TODO: ... |
import sys
import dicomsdl as dicom
def show(args):
if len(args) == 1:
dcmfn = args[0]
idx = 0
elif len(args) > 1:
dcmfn = args[0]
idx = int(args[1])
dset = dicom.open_file(dcmfn)
info = dset.getPixelDataInfo()
if idx >= info['NumberOfFrames']:
print('File have %d frames.'%(info['Num... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 13 19:47:44 2017
@author: cm
"""
import os
import numpy as np
import pandas as pd
from hyperparameters import Hyperparamters as hp
import string
pwd = os.path.dirname(os.path.abspath('__file__'))
#print(pwd)
def load_vocabulary():
word_dic = pd.read_csv('./dict/... |
"""
Runs reduction rules to generate data/preprocessed/ from data/sanitized/
"""
import networkx as nx
from pathlib import Path
import time
import datetime
from src.preprocessing.graphs import (
read_edgelist,
write_edgelist,
write_huffner,
write_snap,
open_path,
reset_labels,
names_in_dir... |
import dbInfo as di
import tfIdfCalc as idf
import numpy as np
def getActorTagMatrix():
tagIds = di.getAllTags()
tagLen = len(tagIds)
actorNames = di.getAllActorNames()
actorlist = di.getAllActors()
actorTags = np.zeros((len(actorlist),tagLen))
i=0
idfActVector = idf.idfActorTag()
for actor in acto... |
import unittest
from programy.storage.stores.nosql.mongo.dao.property import DefaultVariable
from programy.storage.stores.nosql.mongo.dao.property import Property
from programy.storage.stores.nosql.mongo.dao.property import Regex
class PropertyTests(unittest.TestCase):
def test_init_no_id(self):
propert... |
# -*- coding: utf-8 -*-
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from pandas import DataFrame
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from s... |
import numpy as np
import pandas as pd
from Sliding import *
from os import path
import os
from os import listdir
from os.path import isfile, join
def main(subject_directory):
path = get_path(subject_directory)
print path
label_matrix = load_file_as_matrix(path)
# What label occurs before
... |
def prediction_model(pclass, sex,age,sibsp,parch,fare,embarked,title):
import pickle
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
file_dir = os.path.join(BASE_DIR, 'titanic_model.sav')
x= [[pclass,sex,age,sibsp,parch,fare,embarked,title]]
randomforest = pickl... |
# otp_test.py - Unit tests for the OTP1 and OTP2.
#
# NOTE test1() requires a physical YubiKey with a specific configuration.
import otp
import sys
import yubico
from Crypto.Cipher import AES
from Crypto.Hash import HMAC, SHA, SHA256
from yubico.yubico_util import crc16
test_key = '\x00' * 32
test_id = 'fellas'
test_... |
from Crypto import Random
from Crypto.Cipher import AES
from sys import argv
def abre(i):
F = open(argv[i])
text = F.read()
F.close()
return text
chave = abre(1)
texto = abre(2)
IV = Random.new().read(AES.block_size)
try:
cipher = AES.new(chave, mode=AES.MODE_CFB, IV=IV)
except ValueError as error:
print error... |
import pytest
from takler.core import Flow
from takler.core.node import Node
from .util import get_node_tree_print_string
class ObjectContainer:
pass
@pytest.fixture
def child_case():
"""
|- flow1
|- container1
|- task1
|- task2
"""
result = ObjectContainer()
... |
import argparse
import os
import datetime
import numpy as np
from torch.utils.data import DataLoader
import model.trainer as trainer
from model.sunspots import SunspotData
from model.model_factory import Model
import torch
from utils.utils import SummaryHelper
# ------------------------------------------------------... |
import unittest
import ddt
import requests
from common.readCookie import get_cookie
testData1 = [{'assert':'SUCCESS'},
{'account':'2585683','assert':'SUCCESS'},
{'account': 'tester', 'assert': 'SUCCESS'},
{'account': '测试徐群节', 'assert': 'SUCCESS'},
{'account': '5555... |
import numpy as np
from sklearn import metrics
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data
import gzip
import inout as utils
from meter import AUCMeter
from sklearn.feature_extraction.text import TfidfVectoriz... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Windows Scheduled Task job file parser."""
import unittest
from plaso.lib import definitions
from plaso.parsers import winjob
from tests.parsers import test_lib
class WinJobTest(test_lib.ParserTestCase):
"""Tests for the Windows Scheduled Task job f... |
from nose.tools import eq_
import os, sys
mfile = u"""
@implementation ViewController
- (void)viewDidLoad {
self.label.text = @"Test String to Localize";
self.label.text = __LOCALIZE@"Test String to Auto Localize";
self.label.text = __LOCALIZE@"Test String to Auto %20@ Localize with %02d = 2 formatting argument... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import os
import sys
import shutil
import tempfile
from crossprocess.process import run_script
from crossprocess.objects import SimpleObject
class TestCrossprocess(object):
def get_script(self, name, extension='.py'):
"""
helper method... |
import json
from pprint import pprint
import requests
# Store your github API access credentials here to protect them from the interwebz.
import secret
ENV_FILE = '../data/envs.json'
ENV_OUT_FILE = '../data/envs.json'
def fetch_stars(json):
envs = json['envs']
for i in range(0, len(envs)):
... |
# -*- coding: utf-8 -*-
import pandas as pd
from pandas.api.types import is_number
import datetime
def format_date(dt):
"""
Returns formated date
"""
if dt is None:
return dt
return dt.strftime("%Y-%m-%d")
def sanitize_dates(start, end):
"""
Return (datetime_start, datetime_end) t... |
class Order():
def __init__(self,customer_name, item_name, order_date, quantity):
self.customer_name = customer_name
self.item_name = item_name
self.order_date = order_date
self.quantity = quantity
|
from sentiment import *
from search import *
import sys
import math
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
import matplotlib.pyplot as plt
import json
def formatdata(score):
return (score+1)/2
def getInput():
timeframe = "d"
keyword = ""
while True:
print("Usage: (d)ay, ... |
from flask import Flask
#from flask_sqlalchemy import SQLAlchemy
from .models import *
app = Flask(__name__)
#db = SQLAlchemy(app)
#db.init_app(app)
app.config.from_pyfile('config.py')
from app import views, models
|
import requests
import json
def quote_of_the_day():
try:
url = 'https://quotes.rest/qod/'
response = requests.get(url)
response_json = json.loads(response.text)
try: # Only 10 requests allowed per hour
quote = response_json[u'contents'][u'quotes'][0][u'quote']
... |
import os
import torch
import torch.nn as nn
from torch.autograd import Variable
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torch.nn.functional as F
import torch.optim as optim
from dataLoader import crypticLettersDataset
from torch.utils.data import DataLoader
from torch.u... |
import os
def sudo_run(password, command):
os.system("echo {pwd}|sudo -S {cmd}".format(pwd=password, cmd=command))
if __name__ == '__main__':
pwd = ""
sudo_run(pwd, command="docker stop /node1")
sudo_run(pwd, command="docker stop /node2")
sudo_run(pwd, command="docker stop /node3")
sudo_run(... |
a=int(input("Enter a num to check whether it's prime or not: "))
flag=True
for i in range(2,a):
if(a%i==0):
flag=False
break
if flag:
print("Num is prime")
else:
print("Num is not prime") |
import os
import cv2
import sys
import time
import ssim
import imageio
import tensorflow as tf
import scipy.misc as sm
import scipy.io as sio
import numpy as np
import skimage.measure as measure
from os import listdir, makedirs, system
from os.path import exists
from argparse import ArgumentParser
from skimage.draw i... |
from tkinter import *
from tkinter.ttk import *
import os
from tkinter import filedialog
from tkinter import messagebox
root=Tk()
root.config(bg="white")
root.geometry("800x480")
root.title("Add Image")
Label(root,text="Pick the Image location from the disk:",font=("Verdana",15),background="white").pack()
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from scipy import misc
import sys
import os
import argparse
import tensorflow as tf
import numpy as np
import mxnet as mx
import random
import sklearn
from sklearn.decomposition import PCA
from time import slee... |
import requests
import threading
import socket
import time
import random
import sys
global target
global server_block
global end_
end_ = False #method to stop threads
def load_pix():
from colorama import init
init()
from colorama import Fore, Back, Style
print(Fore.GREEN ... |
### Parte de leer los datos de hdfs ###
import pandas as pd
import numpy as np
import pydoop.hdfs as hd
from lxml import objectify
with hd.open("/user/datostrafico/20160526_1711.xml") as archivo:
parsed = objectify.parse(archivo)
DatosTrafico = parsed.getroot()
totalvehiculostunel = 0;
totalvehiculoscalle30 = 0;
... |
# coding=utf-8
from AutoInstall import *
from threading import Thread
from Manage import JobsManage
import HttpAPI
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers import interval
from config import log_File, PLUGIN, base_leve, HTTP
from BaseMetric import collect
from Repo import ... |
import subprocess
from zombie.window_operation import Window
class Program:
def __init__(self, program_path):
self.path = program_path
def run(self):
subprocess.Popen(self.path)
if __name__ == "__main__":
pg = Program("explorer.exe")
pg.run()
mes_main_window = Window("Github")... |
'''
Created on 2013-7-19
@author: Administrator
'''
import framework.model.DAO as DAO;
dal = DAO.DAO();
#sql = "delete from user where id=13";
result = dal.delete({'id':13});
print result |
# !/usr/bin/python
# -*- coding:utf8 -*-
# __author__ = c08762
"""learn numpy"""
# 基本属性
import numpy as np
# array = np.array([[1,2,3],[4,5,6]])
# print(array)
# print('number of dim(维数):', array.ndim)
# print('shape:', array.shape)
# print('size:', array.size)
# 创建矩阵,可指定矩阵type, 默认为64位
a1 = np.array([2,3,4])
a2 = np... |
class ResponseGenerator:
def __init__(self):
pass
@classmethod
def make_response(cls, clientRequest, selectedTemplate, params=None, training={}):
print("* * * * * * * * * * * * * * ")
print("# Make Response ")
if params:
clientRequest["response"]["responseText"] ... |
from numpy import*
m = array(eval(input("Vetor da media:")))
s = m**(-1)
s1 = sum(s)
n = size(m)
ss = (s1/n)**(-1)
print(round(ss,2))
|
import nltk
from nltk.stem.porter import PorterStemmer
from nltk.stem.lancaster import LancasterStemmer
def pos_tag(tokens):
nltk.download('averaged_perceptron_tagger')
tagged = nltk.pos_tag(tokens)
print(tagged)
def tokenize(sentence):
global tokens
nltk.download('punkt')
tokens = nltk.word_t... |
# coding=UTF-8
from django.conf import settings
def context_processor(request):
return {'CONTACT_LINK': settings.CONTACT_LINK}
|
"""
Copyright (c) 2019 Cypress Semiconductor Corporation
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 ... |
# -*- coding: utf-8 -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the reproman package for the
# copyright and license terms.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #... |
import os
class RecursiveImporterUtilities(object):
@staticmethod
def getDirCSVFiles(directory, verbose=True):
csvFileList = []
if (verbose):
print "\r\nGetting CSV files\r\n-----------"
#note: directory is a QString -> must be converted
for root, dirs, fileNames... |
# Generated by Django 2.0.1 on 2018-05-09 16:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0011_task_status'),
]
operations = [
migrations.AlterField(
model_name='task',
name='status',
fie... |
from methods import get_order, train_model
# get list
overall_list, _ = get_order()
# set i to the number of mosaics -1
num = 0
i = 21
# start model training with number of repetitions
# set all parameters
for num in range(5):
print("On repetition ", num)
train_model(train_path=overall_list[i], extra_... |
from getpass import getpass
from ncclient.transport.errors import AuthenticationError
from paramiko import AuthenticationException
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from dcim.models import Device, Module, Site
class C... |
from django import template
from ticker_app.models import ExchangeTicker
from tradeBOT.models import CoinMarketCupCoin, UserMainCoinPriority, Pair, ExchangeMainCoin, UserPair
from trade.models import UserBalance
register = template.Library()
@register.filter(name='user_have_coin')
def user_holdings(coin_symbol, use... |
"""NickJuliaOnlineJournal URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='hom... |
# 4.10.10.py
# This program displays information about a rectangle drawn by the user.
# import libraries
from graphics import *
from math import sqrt
def main():
win = GraphWin("Triangle Information",400, 400)
for i in range(1):
p1 = win.getMouse()
p2 = win.getMouse()
p3 = win.getMouse... |
#!/usr/bin/env python3
__author__ = 'Wei Mu'
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
if rowIndex == 0:
return [1]
ans = [1, 1]
for i in range(1, rowIndex+1):
temp = [None] * (i + 1)
temp[0... |
import RPi.GPIO as gpio
import time
import os
gpio.setmode(gpio.BCM)
gpio.setwarnings(False)
#gpio_setup
gpio.setup(4,gpio.OUT)
gpio.setup(15,gpio.IN,pull_up_down = gpio.PUD_UP)
#pwn_setup
pin = gpio.PWM(4,100)
pin.start(0)
try:
while True:
if gpio.input(15) == 0:
time.sleep(0.8)
... |
from django.shortcuts import render, get_object_or_404
from .models import Board
from django.contrib.auth.models import User
from django.shortcuts import redirect
from .forms import NewTopicForm
def home(request):
boards = Board.objects.all()
return render(request, 'home.html', {'boards': boards})
def board_topic... |
from django.db import models
from django.contrib.auth.models import User
from users.models import User_more_info
from DjangoUeditor.models import UEditorField
# content = models.TextField()
class Article_type(models.Model):
id = models.AutoField(primary_key=True)
# 分类名称
name = models.CharField(max_leng... |
#coding:utf-8
#引入函数
from utils import times
#调用函数
a = "itsource "
b = 10
s = times(a,b)
print "The multiplication of {0} and {1} is: \n{2}".format(a,b,s)
|
from heuristics.Generic_Heuristic import Generic_Heuristic
from heuristics.Single_Start_Greedy import Single_Start_Greedy
from math import ceil, factorial
import sys
from copy import deepcopy
import numpy as np
class Multi_Start_Greedy(Generic_Heuristic):
def __init__(self):
super().__init__()
self... |
# Afficher les instructions
import random, time, pygame
# défini le canvas d'affichage
pygame.init()
width = 500
height = 300
window_size = ( width, height )
game_surface = pygame.display.set_mode(window_size)
# couleurs
color_black = ( 0, 0, 0 )
color_white = ( 255, 255, 255 )
# textes
labelFont = pygame.font.SysFo... |
# -*- encoding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import sqlite3
import json
import datetime
import time
import calendar
import base64
import threading
memo_insert_sql = "insert into Memo (User, Date, Text, Image, medicine) values (?, ?, ?, ?, ?)"
memo_search_sql = "select * from Memo w... |
def update(sql_statement, cursor, db):
cursor.execute(sql_statement)
db.commit()
def query_all(sql_statement, cursor):
num_row = cursor.execute(sql_statement)
if num_row > 0:
return list(cursor)
else:
return list()
def query_one(sql_statement, cursor):
num_row = cursor.execut... |
from defaults import *
DEBUG=True
COMPRESS_ENABLED=True
ALLOWED_HOSTS=['127.0.0.1', 'localhost', 'crackit.com']
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'mocktest', 'templates_prod')],
'APP_DIRS': True,
'OPTIONS... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.