text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python
import argparse
import numpy
import os
def main():
argument_parser = argparse.ArgumentParser()
argument_parser.add_argument('--source_sentences_file_path', default='lorem_ipsum.txt')
argument_parser.add_argument('--line_count', type=int, required=True)
argument_parser.add_argumen... |
from abc import ABCMeta
from abc import abstractmethod
import numpy as np
from torch.utils.data import Dataset
class DatasetBase(Dataset):
"""
Base class for all datasets.
"""
__metaclass__ = ABCMeta
@abstractmethod
def test(self, *args):
"""
Sets the dataset in test mode.
... |
from industry import IndustrySecondary, TileLocationChecks
industry = IndustrySecondary(id='smithy_forge',
processed_cargos_and_output_ratios=[('METL', 8)],
prod_cargo_types=['ENSP', 'FMSP'],
prob_in_game='2',
... |
# Generated by Django 3.1.4 on 2021-06-29 15:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('movies', '0005_auto_20210629_2040'),
]
operations = [
migrations.AlterField(
model_name='movie',
name='actors',
... |
from datetime import timedelta
from django.utils.timezone import localtime, now
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from care.facility.api.serializers import TIMESTAMP_FIELDS
from care.facility.api.serializers.facility import FacilityBasicInfoSerializer
from ca... |
from django.shortcuts import render
from django.http import request
# ccb
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.views.generic.edit import DeleteView, UpdateView, CreateView
from django.urls import reverse_lazy
#requerir login
from django.contrib.... |
from django.db import models
from Students.models import Student
# Create your models here.
class Parents(models.Model):
name = models.CharField(max_length=50)
plot_flatno = models.CharField(max_length=50)
addr_line1 = models.CharField(max_length=200)
addr_line2 = models.CharField(max_length=200)
city = models.C... |
import tensorflow as tf
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Dropout
from tensorflow.keras.callbacks import ReduceLROnPlateau, ModelCheckpoint, EarlyStopping
from tensorflow.keras.metrics import BinaryAccuracy, Precision, Recall, AUC
from tensorflow.keras.models import Model, load_model
fr... |
# -*- coding: utf-8 -*-
import calculadora_indices as cal
peso = float(input('Ingrese el peso de la persona (en kg): '))
altura = float(input('Ingrese la altura de la persona (en m): '))
IMC = round(cal.calcular_IMC(peso,altura),2)
print('El IMC de la persona es de:',IMC)
if IMC <16:
print('La persona tiene delg... |
from django import template
register = template.Library()
@register.filter
def cut(value):
if len(value) > 55:
return value[:55]+"..."
else:
return value |
from AlphaGomoku.mcts.rollout_mcts import RolloutMCTS
from AlphaGomoku.neural_networks import get_network
from AlphaGomoku.neural_networks.keras.weights import get_weight_file
from AlphaGomoku.board import Board
from AlphaGomoku.play import Human, Game
policy = get_network('policy', 'resnet', 'keras', stack_nb=2)
poli... |
from wtforms import FieldList
from wtforms.utils import unset_value
# override process func of FieldList to make it unordered
class UnorderedFieldList(FieldList):
def process(self, formdata, data=unset_value, extra_filters=None):
if extra_filters:
raise TypeError(
"FieldList do... |
# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.template import Context, Template, loader
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.core.context_processors import csrf
from ... |
import pytest
from streamsets.testframework.decorators import stub
@stub
@pytest.mark.parametrize('stage_attributes', [{'add_unsupported_fields_to_records': False},
{'add_unsupported_fields_to_records': True}])
def test_add_unsupported_fields_to_records(sdc_builder, sdc_... |
from django.shortcuts import render, get_object_or_404, redirect
from django.views.decorators.http import require_GET, require_POST
from django.http import JsonResponse
from .order import Order
from .forms import OrderAddProductForm, OrderForUserForm, OrderForAnonymUserFrom
from . import models
from productApp.models ... |
import main
import sys
from tkinter import messagebox
import tkinter as tk
from BikeGUI.ADDSTOCK import add_stock_support
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Add_to_stock (root)
add_stock_support.init(root, top)
root... |
def model_function1(x, a):
"""
The estimated model function for the CPU extrapolation method. This is the version for CPU computing and Memory Bandwidth.
"""
y = a/x
return y
def model_function2(x, a, b):
"""
The estimated model function for the CPU extrapolation method. This is the versi... |
from SVR_class import SVR
import numpy as np
data_2016 = np.array([[10], [9], [17], [10]])
data_2017 = np.array([[10], [10], [19], [10]])
data_2018 = np.array([[10], [11], [16], [12]])
data_2019 = np.array([[10], [11], [16], [12]])
data_2016 = np.array([[10], [11], [9], [11], [10], [8], [14], [13], [10], [11]... |
"""
A script to create the dataset c4l-16x16_550.tar.gz
Author: Jimut
20-03-2020
# 550 is the minimum number
"""
import glob
import cv2
import os
import string
from tqdm import tqdm
png_files = glob.glob('resized_data/*.png')
index_var = "0123456789"+string.ascii_lowercase+string.ascii_uppercase
index = {}
for... |
'''
Copyright (C) 2018 Jean Da Costa Machado.
Created by Jean Da Costa Machado
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 3 of the License, or
(at your op... |
__author__ = 'christopherrivera'
from pandas import DataFrame
from data_functions import *
from sklearn import metrics
def predict_random_category(y_test, n=1000):
""" Uses boostrapping to compute the expected prediction by chance for each category.
Parameters:
y_test (array): Labels
n (int):... |
#! /usr/bin/python3
from configparser import ConfigParser
from helpers import cmd
from helpers import setup_logger
from helpers import game_config
from server_game import GameServer
import signal
logger = setup_logger("settings.conf", "server")
port = game_config.get("connection", "port")
server = GameServer("", int(... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-03 15:32
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('... |
from threading import Thread
import socket
import SocketServer
import argparse
import signal
import logging
import subprocess
import sys
import time
ACTIVE = 'ACTIVE'
BACKUP = 'BACKUP'
state = BACKUP
params = {}
class requestHandler(SocketServer.BaseRequestHandler):
def handle(self):
global state
... |
#!/usr/bin/env python3
def palindrome(obj):
return obj == obj[::-1]
if __name__ == "__main__":
print (palindrome("\"abba_abba"))
|
# Generated by Django 3.2.4 on 2021-06-23 09:19
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... |
import re
from nltk import word_tokenize
import nltk
nltk.download('punkt')
not_punc = re.compile('.*[A-Za-z0-9].*')
def preprocess(t):
t = t.lower().strip("';.:()").strip('"')
t = 'not' if t == "n't" else t
return re.split(r'[-]', t)
def sent2words_nltk_usif(sentence):
tokens = []
for token in ... |
import numpy as np
s = np.random.binomial(100, .5, 100000)
from scipy.stats import norm
import matplotlib.pyplot as plt
# Generate some data for this demonstration.
data = s
# Fit a normal distribution to the data:
avg, standard_dev = norm.fit(data)
# Plot the histogram.
plt.hist(data, bins=20, normed=True, alpha=0.... |
'''
Ryan Lim
Web Crawler
'''
import requests
from bs4 import BeautifulSoup
'''
Web Crawler
This web crawler will crawl through the
main site and get all the urls of the scripts
'''
def main_spider(url):
# get the source code from the url
source_code = requests.get(url)
#convert source code to plain text... |
from controllers.menu_controller import menu
from controllers.auth_controller import auth
from controllers.order_controller import order
from controllers.routes_controller import routes
registerable_controllers = [
menu,
auth,
order,
routes,
] |
from moviepy.video.io.ffmpeg_tools import *
import sys
import os
def to_audio(source, ext, fname):
ffmpeg_extract_audio(source, fname+'.'+ ext, bitrate=3000, fps=44100)
def dlvideo(url):
os.system('rm -rf tmp')
os.system('mkdir tmp')
os.system('youtube-dl -o \'tmp/%(title)s.%(ext)s\' ' + url)
pri... |
# -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth.hashers import *
from apps.security.models import Usuario
class UserForm(forms.ModelForm):
usu_ced=forms.CharField(label="Cedula",widget=forms.TextInput(attrs={
'class':'form-control'}))
usu_nom=forms.CharField(label="Nom... |
import numpy as np
from numpy import matmul
import random
#Matrix dimention:
x=8
m1 = np.random.randint(0,10,(x,x))
m2 = np.random.randint(0,10,(x,x))
print (np.matmul(m1,m2)) |
#!/usr/bin/env python
import sys
import string
import numpy
for line in sys.stdin:
line = line.strip()
# split the line into words
words = line.split(",")
violation_code = words[2]
# print(violation_code)
try:
violation_code = int(violation_code)
# increase counters
if viol... |
#!/usr/bin/python
# ---------------------------------------
# File Name : deparser.py
# Creation Date : 08-03-2017
# Last Modified : Sun Mar 12 19:50:52 2017
# Created By : wdd
# ---------------------------------------
import minpy.numpy as np
from minpy.nn import layers
from minpy.nn.model import ModelBase
from min... |
"""we know we are the best, thank you"""
# should never question other's methods
# UpperLeft 0,0
global running
running = True
global clientDup
clientDup = None
global channel1
channel1 = None
global directions
directions = {
"up": 1,
"down": 2,
"left": 3,
"right": 4,
"upRight": 5,
"downRig... |
from toolbox.models import *
from toolbox.dataset import *
from toolbox.data import *
from toolbox.image import *
from toolbox.layers import *
import tensorflow as tf
import numpy as np
import keras.backend as K
from keras.utils import plot_model
from keras.losses import get
def mse_calc():
from keras.applications... |
import numpy as np
class MarkovChain(object):
def __init__(self, states, t_matrix=None):
self.states = states
self.index_dict = {self.states[index]: index for index in range(len(self.states))}
#If we have a transition matrix, we can add it here
if t_matrix:
self.tran... |
"""
step01 箱としての変数
"""
import numpy as np
# 変数の定義
class Variable:
def __init__(self, data):
self.data = data
|
# Generated by Django 3.2.3 on 2021-05-18 09:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20210517_1411'),
]
operations = [
migrations.CreateModel(
name='RoadCondition',
fields=[
... |
import collections
import csv
from loguru import logger
import json
import os
import cv2
import pandas as pd
import app
class LabelMapper:
def __init__(self):
self.path_prodigy_labeled = app.app.config['PATH_PRODIGY_LABELED']
self.output_root = app.app.config['UPLOAD_FOLDER']
self.Rectan... |
lista = input("Insira a lista: ").split()
lista = [int(i) for i in lista]
par_impar = (lambda x: "Par" if (x % 2 == 0) else "Impar")
novaLista = list(map(par_impar, lista))
print(lista)
print(novaLista) |
from flask import render_template
from app import app
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404 |
# !/usr/bin/python
# Filename: fourier_for_real.py
"""
We shortly adapt the Fourier transform modulus of numpy to be used in
combination with analytical calculus under the 'mathematician' Fourier
transform convention:
Run the modulus as main to have an example !
DETAILS:
Indeed we start from the definitions:
$\hat... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# File Name: save_ticks.py
# Author: Jason. Yao
# Date: 2021/07/29
# -----------------------------------------------------------------------------
# --------------------------------------------------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.ExpenseConsumeInfo import ExpenseConsumeInfo
from alipay.aop.api.domain.ExpenseInvoiceInfo import ExpenseInvoiceInfo
from alipay.aop.api.domain.ExpenseVoucherInfo impor... |
# coding:utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import parseaddr, formataddr
class MailUtil():
def __init__(self, content, subject):
self.content = content
self.subject = subject
def sendMail(self):
from_addr = '18545... |
"""
stft_harmonic_melody.py
Investigation on using scipy's Short-Time Fourier Transform,
on a synthesized clarinet melody.
@author: DoraMemo
"""
from scipy import signal
from scipy.fft import fft, fftfreq
import aumix.music.notes as notes
import aumix.signal.stationary_signal as sts
import aumix.signa... |
class LinkedList:
def __init__(self):
self.head = Node()
def insert(self, node):
current = self.head
while current.link is not None:
current = current.link
current.link = node
def __len__(self):
return self.__len_aux(self.head)
def __len_aux(self, c... |
from django.http import JsonResponse, HttpResponse, request
from django.views.generic import FormView, RedirectView
from django.urls import reverse, reverse_lazy
from django.contrib import messages
from COS.core.decorators import logged_user_view
from room_options.conf import Description
from room_options.models import... |
from networkx import DiGraph
class AlphaBeta():
def __init__(self, graph, valueMarix, root=1, infinity=100000):
self.INFINITY = infinity
self.closedList = set()
self.root = root
self.abvalue = valueMarix # alpha beta value
self.graph = graph
self.pruninedNodes = []
def getUnvisitedChild(self, node):
... |
def nearestNeighbor(randNode, tree):
bestNode = tree[0]
bestDistance = randNode.dist(tree[0])
for node in tree:
distance = randNode.dist(node)
if distance < bestDistance:
bestDistance = distance
bestNode = node
#Vid hinder, kontrollera om det är hinder ivägen, ... |
from __future__ import unicode_literals
from optparse import make_option
from calaccess_raw.management.commands import CalAccessCommand
custom_options = (
make_option(
"--skip-download",
action="store_false",
dest="download",
default=True,
help="Skip downloading of the ZIP ... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides parameter validation tools.
"""
import numpy as np
def as_pair(name, value, lower_bound=None, upper_bound=None, check_odd=False):
"""
Define a pair of integer values as a 1D array.
Parameters
----------
name... |
def Policy():
business_name = input("business name:")
site_name = input("website: ")
street_address = input("street address:")
city = input("city:")
state = input("state:")
zipcode = input("zipcode:")
email = input("email:")
if __name__ == '__main__':
Policy()
... |
from django.db import models
# Create your models here.
class PatientLab(models.Model):
id_number = models.CharField(max_length=200, unique=True)
patient_name = models.CharField(max_length=200)
phone_mobile = models.CharField(max_length=200, null=True)
gender = models.CharField(max_length=200)
date... |
class Solution(object):
def generateParenthesis(self, n):
prev = ['()']
for i in xrange(1,n):
prev = self.generateStrings(prev, i)
return prev
def generateStrings(self, prevResult, n):
uniqueSolutions = set()
for str in prevResult:
... |
N, M = map(int, input().split())
cnt_block = 1
if N == 1:
cnt_block = 1
elif N == 2:
if (M >= 7):
cnt_block = 4
else:
cnt_block = (M+1) // 2
elif N >= 3:
if(M >= 7):
cnt_block = (M - 2)
elif(M >= 4):
cnt_block = 4
else:
cnt_block = M
print(cnt_block)
|
from django.urls import path, re_path
from . import views
app_name = 'course_app'
urlpatterns = [
path('', views.index, name='index'),
path('<slug:slug>/', views.details, name='details'),
re_path('^(?P<slug>[-a-zA-Z0-9_]+)/activity/(?P<activity_uuid>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]... |
BAD_WORDS = [
'abbo',
'abo',
'abortion',
'abuse',
'addict',
'addicts',
'adult',
'africa',
'african',
'alla',
'allah',
'alligatorbait',
'amateur',
'american',
'anal',
'analannie',
'analsex',
'angie',
'angry',
'anus',
'arab',
'arabs',... |
# https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
class Solution:
'''
只要某节点满足下面条件,则为正确答案
(f_lson && f_rson) ∣∣ ((x = p ∣∣ x = q) && (f_lson ∣∣ f_rson))
^ ^
| |
此处表示一个在左子树 此... |
import numpy as np
import tensorflow as tf
from typing import List, Tuple
from nn.interface import IOperator
from nn.layer.abstract import AbsLayer
from nn.activation.interface import IActivation
class MaxPool(AbsLayer):
def __init__(self, strides: [List[int], Tuple[int]], padding: [List[int], Tuple[int], str],... |
from app import app
from app import tf,clf
import json
import pandas as pd
from flask import render_template,url_for, request, jsonify
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
@app.route('/prediksi',methods=["GET", "POST"])
def prediksi():
if request.method == "POST":... |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Marcus de Assis Angeloni <marcus@liv.ic.unicamp.br>
# Thu 14 Apr 2016 18:02:45
import numpy
import os
from datetime import datetime
import argparse
import metrics
#################
# main block
#################
# Get arguments
parser = argparse.ArgumentParser(... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 16 12:53:43 2019
@author: sheva
"""
import datetime
import cv2
import pandas as pd
import numpy as np
import PnP_func
import os
import yaml
from matplotlib import pyplot as plt
import bucket_PnP
start_id = 84
end_id = 85
#Get the ground truth of the v... |
#!/usr/bin/python3
""" Exports data into CSV format """
import csv
import requests
import sys
if __name__ == "__main__":
""" If second argument is an integer, then it's an employee id """
empl_id = sys.argv[1]
if empl_id.isdigit():
""" Gets EMPLOYEE_NAME """
empl_url = "https://jsonplac... |
# Copyright (c) OpenMMLab. All rights reserved.
import mmcv
from . import voxel_generator
def build_voxel_generator(cfg, **kwargs):
"""Builder of voxel generator."""
if isinstance(cfg, voxel_generator.VoxelGenerator):
return cfg
elif isinstance(cfg, dict):
return mmcv.runner.obj_from_dict... |
"""Provide a model for a log message event."""
from typing import List, Literal, Optional, TypedDict, Union
class LogMessageDataType(TypedDict, total=False):
"""Represent a log message data dict type."""
source: Literal["driver"] # required
event: Literal["logging"] # required
message: Union[str, L... |
def migrate(cr, version):
cr.execute('''
ALTER TABLE hr_rfid_card_type
DROP CONSTRAINT hr_rfid_card_type_rfid_card_type_unique;
''')
|
from urllib.parse import unquote_plus
import boto3
import time
sm = boto3.client("sagemaker")
def lambda_handler(event, context):
bucket = event["Records"][0]["s3"]["bucket"]["name"]
key = unquote_plus(event["Records"][0]["s3"]["object"]["key"])
input_loc = "s3://" + bucket + "/" + key
batch_job_name = key[key.... |
N, K = [int(x) for x in input().split()]
ways = [[1 for _ in range(K+1)] for _ in range(N+1)]
for n in range(1, N+1):
for k in range(2, K+1):
if n == 1: ways[n][k] = k
elif k == 2: ways[n][k] = n+1
else:
for m in range(1, n+1):
ways[n][k] += ways[m][k-1]
print(w... |
'''
Author: Nicholas Bright
Created Date: 2019-10-20
Last Updated: 2019-12-03
Version: 1.0.0
Purpose:
Defines a class used to access a cheese table in a mysql database
'''
from CheeseModel import CheeseModel
import mysql.connector
import time
class CheeseDAO:
"""A DataAccessObject for accessing and executing on the ... |
import random
import os
def cls():
os.system('cls' if os.name=='nt' else 'clear')
def get_rank(tried):
if tried == 0 or tried == 1:
reward = 'the Golden Crown!\n👑\n'
elif tried == 2:
reward = 'the Silver Ring!\n💍\n'
elif tried == 3 or tried == 4:
reward = 'the Bronze Medal!\n... |
#https://blog.csdn.net/lpp5406813053/article/details/89788108
#数据预处理以及绘制图形需要的模块
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#构建长短时神经网络需要的方法
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential,save_model,load_model
from keras.layers import Dense, LSTM, BatchNorm... |
# Import the following modules
import os
import time
import shutil
import datetime
import glob
# Change the directory and jump to the location
# where you want to arrange the files
os.chdir(r"C:\Users\Dell\Downloads\FireShot")
# List the directories and make a list
all_files = list(os.listdir())
# Get the c... |
from datetime import date
import pandas as pd
import optopsy as op
pd.options.display.width = None
vxx_struct = (
('symbol', 0),
('underlying_price', 1),
('option_symbol', 3),
('option_type', 4),
('expiration', 5),
('quote_date', 6),
('strike', 7),
('bid', 9),
('ask', 10),
('... |
# -*- coding = utf-8 -*-
import logging
from flask.views import MethodView
from flask import render_template, request, url_for, redirect
from flask_login import current_user
class IndexView(MethodView):
def get(self, *args, **kwargs):
return render_template("index.html")
def not_found_handler(e):
... |
# -*- coding: utf-8 -*-
"""
AUC calculation
@author: Kushal
"""
import pandas as pd
def calculate_auc(x_range, a, b, c):
t1 = x_range[0]
t2 = x_range[len(x_range)-1]
print("t1 = ",t1)
print("t2 = ",t2)
auc = (a/(1-b)) * (pow(t2, 1-b) - pow(t1, 1-b)) + c * (t2 - t1)
return auc... |
{
"downloads" : [
"https://github.com/imageworks/OpenShadingLanguage/archive/Release-1.11.11.0.tar.gz"
],
"url" : "https://github.com/imageworks/OpenShadingLanguage",
"license" : "LICENSE.md",
"dependencies" : [ "OpenImageIO", "LLVM", "PugiXML" ],
"environment" : {
# Needed because the build process r... |
ONES = ["zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
TENS = ["", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "nine... |
import YOLO_v1.yolo_v1 as yolo
from scipy.misc import imread, imsave, imresize
import tensorflow as tf
import keras
from keras import layers
import numpy as np
def test_conv2d_LeakyReLU():
"""
Test conv2d_LeakyReLU function
:return:
"""
rst = yolo.conv2d_LeakyReLU(img, 3, 0.1)
init = tf.global... |
import os
optimizations = ["0","1","2","3","s"]
# optimizations = ["0"]
files = ["ackermann.x", "array.x", "fib.x", "lists.x", "matrix.x", "sieve.x", "heapsort.x", "random.x"]
# files = ["a.x"]
count = 1
for o in optimizations:
for f in files:
filename1 = "tests/" + f + ".stack.o" + o
filename2 = ... |
#coding:utf-8
import wave
import math
import numpy as np
import csv
'''
Name: readWave.py
Function: Be used to read the wave file and transform the wave file to an identified data structure
说明:本程序用于读取录音文件,并且将录音文件转化为csv文件的格式。
CSV文件格式可以直接在excel中打开,便于数据可视化
'''
'''
Function: wave2csv(inputname,outputname)
说明:用于读取录音得到的WA... |
from tornado.web import RequestHandler
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
from tornado.gen import coroutine, Return
from tornado.ioloop import IOLoop
import os
import json
class PagerDutyHandler(RequestHandler):
def initialize(self):
"""
This is actually important. :D
... |
import torch
import torch.nn as nn
import torchvision.models as m
import sys
sys.path.insert(0, "/home/nduginec/ml3/ml-diplom")
sys.path.insert(0, "/home/ubuntu/ml3/ml-diplom")
import model.connection_block as cb
"""
Давайте разобьем модель на 4 + части
1 -- та что до бранчевания
2 -- левай ветка
3 -- правая ветка
... |
#!usr/bin/env python
# coding:utf-8
import re
import os
import time
import xlwt
def reSearch( parten, content, num=1):
resault = ''
if re.search(parten, content):
resault = re.search(parten, content).group(num)
return resault
def strFormat(arg):
#arg = ''.join(arg.split())
arg = ''.join(a... |
import sched
import time
from datetime import datetime, timedelta
import mongoengine
import settings
from dal import get_all_users_to_track, save_user_activity
from instagram_api_adapter import InstagramAdapter
from instagram_managers.instagram_activity_manager import ActivityManager
mongoengine.connect(
db=sett... |
from turtle import Turtle, Screen
import random
timmy = Turtle()
screen = Screen()
# changing the shape of turtle
timmy.shape('turtle')
timmy.color('blue')
# drawing square
# for i in range(4):
# timmy.forward(100)
# timmy.right(90)
for i in range(20):
timmy.forward(15)
timmy.penup()
timmy.forw... |
"""
test_fact_manager.py
Tests for the logging module
Copyright (c) 2018 The Fuel Rat Mischief,
All rights reserved.
Licensed under the BSD 3-Clause License.
See LICENSE.md
"""
import pendulum
import psycopg2
import pytest
from psycopg2 import sql
from psycopg2 import DatabaseError
from src.packages.fact_manager.... |
from KMP import KMP
if __name__ == '__main__':
print('-' * 50)
kmp = KMP(P='aab', T='aababaabbaab', print_occurrences=True)
print(f'P = {kmp.P}')
print(f'T = {kmp.T}')
print(f'm = {kmp.m}')
print(f'n = {kmp.n}')
num_of_occurrences = kmp.run()
print(f'num_of_occurrences = {num_of_occ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-05-07 18:16
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0002_remove_camera_qa_tests'),
]
operat... |
#!/usr/bin/env python
# -------------------------------- WebLogo --------------------------------
# Copyright (c) 2003-2004 The Regents of the University of California.
# Copyright (c) 2005 Gavin E. Crooks
# Copyright (c) 2006-2011, The Regents of the University of California, through
# Lawrence Berkeley Nationa... |
# -*- coding:utf-8 -*-
# @Time :2020/5/27 23:48
# @Author :小栗旬
from django import forms
from my_blog import models
class AddTagForm(forms.Form):
name = forms.CharField(max_length=30, required=True,
error_messages={
"max_length": "用户名不能超过30",
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-20 17:34
from __future__ import unicode_literals
import archivos.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('archivos', '0001_initial'),
]
operations = [
migrati... |
#!/usr/bin/env python
# coding: utf-8
# In[4]:
# To improve your control flow statement skills and to raise your awareness of some algebraic knowledge.
# Task : Write a program that takes a number from the user and prints the result to check if it is a prime number.
# The examples of the desired output are as follow... |
# Import required libraries and assign root directory of blobs to root
root = "/home/jiajun/Desktop/blobs"
import os
os.chdir(root)
print os.getcwd()
import blobs
import numpy as np
import pandas as pd
import pysal as ps
import matplotlib as mpl
shp_link = root + '/blocks/CensusBlockTIGER2010.shp'
dbf = ps.open(root +... |
import serial
import dbm
from collections import OrderedDict
# open a DB. The c option opens in read/write mode and creates the file if needed.
db = dbm.open('resistorvalues', 'c')
# initialize a dict of keys and values
data = dict.fromkeys([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29... |
"""
Merge function for 2048 game.
"""
def slide_left(line):
"""
To make all non-zero integers to be at the left of the list
"""
length = len(line)
count = 0
output = [0] * length
for i in range(length):
if line[i] != 0:
output[i - count] = line[i]
els... |
"""Carbon Black shared functionality."""
import saq
import logging
from cbapi.psc import threathunter
from cbinterface.psc.intel import get_report, is_ioc_ignored
from saq.proxy import proxies
CBC_API = None
if 'carbon_black' in saq.CONFIG:
cbc_token = saq.CONFIG['carbon_black'].get('cbc_token')
cbc_url = ... |
import logging
from django.template.loader import render_to_string
logger = logging.getLogger(__name__)
class ProviderBase:
"""
Base object for providers.
"""
code: str = None
def _publish(self, tpl: str):
"""
Method must be override for each provider.
"""
raise... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.