text stringlengths 38 1.54M |
|---|
import gensim
import gensim.downloader as api
import numpy as np
import argparse
import tensorflow as tf
from util import DataManager
import os
from sys import argv
from keras.models import load_model
from keras.backend import set_session
gpu_options = tf.GPUOptions(allow_growth=True)
sess = tf.Session(config=tf.C... |
# -*- coding:utf-8 -*-
# Author:D.Gray
import pymysql
conn = pymysql.connect(host = 'localhost',port = 3306,user = 'root',password = 'admin1988',db = 'oldboy')
cursor = conn.cursor()
recount = cursor.execute('select * from student')
print(cursor.fetchall()) |
import math
def side(x1,y1,x2,y2):
x=math.sqrt(((x1-x2)**2+(y1-y2)**2))
return x
x1=eval(input("x1="))
y1=eval(input("y1="))
x2=eval(input("x2="))
y2=eval(input("y2="))
x3=eval(input("x3="))
y3=eval(input("y3="))
side1=side(x1,y1,x2,y2)
side2=side(x1,y1,x3,y3)
side3=side(x2,y2,x3,y3)
s=(side1+side2+side3)/2
ar... |
i=1
s=0
dec=int(input("Enter the number\n"))
while(dec>0):
rem=int(dec%2)
s=s+(i*rem)
dec=int(dec/2)
i=i*10
print(s)
input("Press 'Enter' Key to exit")
|
from Lesson_8_Dataclass.base_page import BaseTransport
from Lesson_8_Dataclass.transport.air import Air
if __name__ == "__main__": # тест для самолета
fuel = 26025
speed = 220
elevation = 5
echelon = 10600
landing_height = 400
permissible_speed = 300
print(Air.get_transport({}))
BaseT... |
import slack
import logging
import os
#import time
#import uuid
#import cloudwatch_metric
#from decimal import Decimal
#logger = logging.getLogger()
#logger.setLevel(logging.INFO)
def coffee_ready_handler(event, context):
coffee_ready(event, context)
return
def coffee_ready(event, context):
## ... |
# Assignes Behtsa to variable name
name = "Behtsa"
# Assignes 23 t age
age = 23
# Assignes 59 inches to variable height
height = 59 # inches
# Assignes 110 lbs to variable weight
weight = 110 # lbs
# Assignes dark brown to variable eyes color
eyes = 'Dark brown'
# Assignes white to variable teeth color
teeth = 'White'... |
s=[]
b=int(input())
for k in range(0,b):
n=input()
s.append(n)
st=""
count=0
t=[]
for l in s:
t.append(len(l))
t.sort()
m=t[0]
z=0
for j in range(0,m):
count=0
for i in range(1,b):
if s[i-1][j]==s[i][j]:
count+=1
else:
z=1
break
if count... |
#coding: utf-8
import math
import heapq
MOD = 10**9+7
a,b,x = map(int, input().split())
V = (a**2)*b
if x>=(V/2):
h = 2*b-2*x/(a*a)
htan = h/a
else:
h = 2*x/(a*b)
htan = b/h
ans = math.atan(htan)*180/(math.atan(1.0)*4)
print(ans) |
# coding=utf8
from flask import Flask, render_template, redirect, url_for,request,jsonify,current_app,make_response
from datetime import timedelta
from flask_cors import CORS,cross_origin
from flask import make_response
# import statements
import wikipedia
import random
import re
from summa import summarizer
import ope... |
#!/usr/bin/env python3
# coding: utf-8
#
import re
import os
import time
import argparse
import yaml
import bunch
import uiautomator2 as u2
from logzero import logger
CLICK = "click"
# swipe
SWIPE_UP = "swipe_up"
SWIPE_RIGHT = "swipe_right"
SWIPE_LEFT = "swipe_left"
SWIPE_DOWN = "swipe_down"
SCREENSHOT = "screensh... |
import re
import sys
import collections
import json
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
if __name__ == '__main__':
sizes_list = []
sizes = []
sizes_repo = collections.defaultdict(lambda: collections.defaultdict(lambda: []))
csv_file = sys.ar... |
from dagster_examples.intro_tutorial.custom_types import burger_time
from dagster import execute_pipeline_with_preset
def test_custom_types_example():
assert execute_pipeline_with_preset(burger_time, 'test').success
|
from classes.piece import Piece
from functions.pieces import Pieces
class Queen(Piece):
def __init__(self):
super().__init__('Q')
self.player = ''
self.id = ''
self.position = ''
def move(self, Queen):
self.moves = Pieces.moves(Queen)
return self.moves
|
import bottle
import wp
import json
import os
collection = wp.WikipediaCollection("./data/wp.db")
index = wp.Index("./data/indexWithTimes.db", collection)
analyse = wp.AnalyseQuery()
gameEnd = False
wordsState = []
@bottle.route('/action')
def action():
global wordsState, gameEnd
query = bottle.request.query... |
import pprint
import redis
import os
import datetime
import time
from multiprocessing import Pool
from elasticsearch import Elasticsearch
from redisearch import Client, TextField, NumericField, Query
from expbase import Experiment
from utils.utils import QueryPool
from pyreuse import helpers
from .Clients import *
f... |
def count_inversion(A, low, high):
inv_count = 0
if high > low:
mid = (low + high) / 2
inv_count = count_inversion(A, low, mid)
inv_count += count_inversion(A, mid + 1, high)
inv_count += merge_inversion(A, low, mid, high)
return inv_count
def merge_inversion(A, low, mid, h... |
__author__ = 'Marie Hoffmann ozymandiaz147@googlemail.com'
import timeit
import numpy as np
# idea 1: sort [(a_i, p_i), key=p], runtime: O(nlogn), space: O(n)
# A array of elements to permute, P index mapping
def permuteArray(A, P):
AP = zip(A, P)
AP.sort(key=lambda ap: ap[1])
return [ap[0] for ap... |
import pytest
from lightbus import commands
pytestmark = pytest.mark.unit
def test_commands_run():
"""make sure the arg parser is vaguely happy"""
args = commands.parse_args(args=['run'])
commands.command_run(args, dry_run=True)
|
def readInput():
n, p = [int(i) for i in input().split()]
arr = [None] * n
for i in range(n):
arr[i] = ([int(x) for x in input().split()])
arr[i].append(i + 1)
return n, arr
def getSol(n, arr):
count, h = 0, 0
sol = []
lastColor = -1
for x in arr:
... |
menu_name = "File browser"
from ui import PathPicker, Printer
import os
callback = None
i = None
o = None
def init_app(input, output):
global callback, i, o
i = input; o = output
callback = browse
def print_path(path):
if os.path.isdir(path):
Printer("Dir: {}".format(path), i, o, 5)
el... |
from unittest import TestCase
from unittest.mock import patch
import app
class AppTest(TestCase):
def test_print_header(self):
expected = '----------------------\n Password Validation \n----------------------\n'
with patch('builtins.print') as mocked_print:
app.print_header()
... |
from flask import Flask, session, redirect, url_for, escape, request, render_template, jsonify, json
from flaskext.mysql import MySQL
from yahoo_finance import Share
from lxml import html
import requests
from exceptions import ValueError
import json
from collections import OrderedDict
mysql = MySQL()
app = Flask(__... |
from django import forms
from django.forms import ModelForm
from django.core.exceptions import ValidationError
from campaigns.models import *
from django.forms.extras.widgets import SelectDateWidget
class CreateForm(ModelForm):
start= forms.DateField(initial=datetime.date.today,widget=SelectDateWidget)
end = forms... |
from pymongo import MongoClient
import os
import time
import datetime
class AtlasDB:
def __init__(self, season):
self.client = MongoClient(os.environ["PREDICTIZ_CREDENTIALS"])
dblist = self.client.list_database_names()
if "season_" + season in dblist:
#raise IOError("Cette base... |
# 버스 정류장 고유ID 검색법
'''
how to get stID + 저상버스
1. https://www.data.go.kr/subMain.jsp#/L3B1YnIvcG90L215cC9Jcm9zTXlQYWdlL29wZW5EZXZEZXRhaWxQYWdlJEBeMDgyTTAwMDAxMzBeTTAwMDAxMzUkQF5wdWJsaWNEYXRhRGV0YWlsUGs9dWRkaTozMjA1NjhiNS1jZDBmLTQyODAtOGI5Ny1iZjUxMmYxNWZlNDkkQF5wcmN1c2VSZXFzdFNlcU5vPTg5Njk3ODkkQF5yZXFzdFN0ZXBDb2RlPVNUQ0... |
from gi.repository import Gtk, GObject
# http://python-gtk-3-tutorial.readthedocs.org/en/latest/dialogs.html
class AddAccountWindow (Gtk.Dialog):
__gsignals__ = {
'sign-in': (GObject.SIGNAL_RUN_FIRST, None, ()),
'token-entered': (GObject.SIGNAL_RUN_FIRST, None, (str,)),
}
def __init__ (self, controller, paren... |
"""Unit tests for the Discord integration."""
import json
from urllib.request import urlopen
from django.contrib.auth.models import User
from djblets.conditions import ConditionSet, Condition
from djblets.testing.decorators import add_fixtures
from reviewboard.accounts.trophies import TrophyType, trophies_registry
fr... |
# -*- coding: utf-8 -*-
from ldapApi import LdapApi
import config
class Student:
"""Represent a Student of University"""
def __init__(self, uid=None, name=None, email=None):
self.name = name
self.uid = int(uid)
self.email = email
def getStudent(cn):
ldap = LdapApi(config.LDAP_URI)... |
import sys
human_list=[]
class human:
def __init__(self,name,phone,sex):
self.name = name
self.phone = phone
self.sex = sex
def print_infow(self):
print("이름은",self.name, "전화번호는",self.phone, "성별은",self.sex, "입니다")
def set_contact():
name =input("이름을 입력하세요: ")
if(name ... |
import json
import logging
import urllib
import urllib2
from secrets import TOKEN, WEBHOOK_URL, MAIN_ANDROID_ID
# standard app engine imports
from google.appengine.api import urlfetch
from google.appengine.ext import ndb
import webapp2
BASE_URL = 'http://api.tofusms.com/devices/send/' + MAIN_ANDROID_ID
JSON_HEADER =... |
import numpy as np
import lasagne
def iterator(inputs, batchsize, eta_d_shared, eta_g_shared, epoch):
if (epoch >= 500) and (epoch % 500 == 0):
eta_d_shared.set_value(lasagne.utils.floatX(0.5 * eta_d_shared.get_value()))
eta_g_shared.set_value(lasagne.utils.floatX(0.5 * eta_g_shared.get_value()))
... |
# -*- coding: utf-8 -*-
"""
飞行时间方法建模
@author: luowei
"""
import math
import numpy as np
import pandas as pd
from scipy import constants as scipy_cons
import matplotlib.pyplot as plt
###################################################################################
# 物理常数
neutron_m = scipy_cons.physical_constants['ne... |
from balance_item import BalanceItem
from collections import Counter
from helpers import DISPLAY_WIDTH, format_money
from enum import Enum
from typing import List
class Category(Enum):
VEGGIES = "Veggies"
DAIRY = "Dairy"
SNACKS = "Snacks"
FRUITS = "Fruits"
DRINKS = "Drinks"
KITCHEN = "Kitchen"
HEALTH = "... |
# -*- coding: utf-8 -*-
__author__ = 'Sun Fang'
import pickle
my_file = open('newNote.txt', 'r')
lines = my_file.readlines()
print(lines)
my_file.seek(0)
# 一次只读一行
first_line = my_file.readline()
second_line = my_file.readline()
print(first_line)
print(second_line)
# 回到起始位置
my_file.seek(0)
first_li... |
#!/bin/python
# -*- coding: utf-8 -*-
# extract_basic.py
# extract the basic patterns using brute-force
# 1 extract n-gram frequent set
#
# Author: Xing Shi
# contact: xingshi@usc.edu
from rcpe import settings
from multiprocessing import Process,Queue
from loader import Loader
import os
import operator
from coll... |
def drought_stage(month):
return {
1 : [40, 30, 25],
2 : [50, 35, 25],
3 : [65, 45, 30],
4 : [85, 60, 35],
5 : [75, 55, 35],
6 : [65, 45, 30],
7 : [55, 45, 25],
8 : [50, 40, 25],
9 : [45, 35, 25],
10: [40, 30, 25],
11: [35, 30, ... |
# File management
print("tony.txt is open. Write something to the file:")
content = str(input())
f = open('tony.txt', 'w')
f.write(content)
f.close()
f = open('tony.txt', 'r')
print(f.read())
f.close()
for i in range(10, 0, -1):
print(i)
|
def amountofds(x,d):
res = 0
for ch in str(x):
if ch == d:
res += 1
return res
def s(x):
sum = 0
amount = 0
in_i = 0
for i in range(0,100000000):
in_i += amountofds(i,x)
amount += in_i
#print str(i) + " " + str(in_i)
if i == in_i:
# print i
sum += i
return sum
def main():
print s("1")
... |
from collections import deque
import sys
from itertools import permutations
from random import *
# n = int(input())
# a = sorted(map(int, input().strip().split()))
def solve(a):
d = deque()
test = 0
for i in a:
if test:
d.appendleft(i)
test = 0
else:
d.a... |
#!/usr/bin/env python
# coding=utf-8
import numpy
import scipy
from numpy import *
import numpy as np
import scipy as sp
import pylab as pl |
import numpy as np
import h5py
import time
import os
from PIL import Image
from resizeimage import resizeimage
import matplotlib.pyplot as plt
RES = 100
NUM_PIX = RES * RES
RGB_LEN = NUM_PIX * 3
NUM_FLOWER_CLASSES = 4
THRESHOLD = 0.4 # Above this probabilty, declare True for that flower class
# Eventually, test diffe... |
#!/bin/python
# Head ends here
class Node:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def distTo(self, target):
return abs(target.x - self.x) + abs(target.y - self.y)
def nextMove(posx, posy, board):
# the input x and y were reversed in Hackerrank puzzles.
... |
from newton_raphson import *
import newton_raphson_test_base as tb
import numpy.linalg as la
# Vecteur colonne de test
f=np.matrix([[tb.f0], [tb.f1], [tb.f2]])
# Jacobienne de f
J=np.matrix([[tb.g00, tb.g01, tb.g02],[tb.g10, tb.g11, tb.g12],[tb.g20, tb.g21, tb.g22]])
# Conditions de test
U0=np.matrix([10., 10., 10.])... |
from manejoArchivos import *
from usuarioService import *
import mysql.connector
from datetime import *
class BaseDeDatosService:
def __init__(self, nombreBase, nombreTabla, host, user, password):
self.nombreBase = nombreBase
self.nombreTabla = nombreTabla
self.host = host
se... |
import unittest
import unittest.mock as mock
from imagemounter.exceptions import NoRootFoundError
from imagemounter.parser import ImageParser
from imagemounter.volume import Volume
class ReconstructionTest(unittest.TestCase):
def test_no_volumes(self):
parser = ImageParser()
parser.add_disk("..."... |
import ast
import pandas as pd
import requests
from io import BytesIO
from jinja2 import Template
from django.apps import apps
from . import code_templates
GDRIVE_BASE_URL = "https://docs.google.com/spreadsheet/ccc?key="
def model_fields_to_dict(sample):
"""
returns a list of dictionary fields from a gi... |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 17 12:36:19 2021
@author: gerry
"""
import random
def fleip_eller_fakta():
uttalelse = []
uttalelse.append(["Tigere har striper", "Fakta"])
uttalelse.append(["Jeg har 2 katter", "Fakta"])
uttalelse.append(["Jeg har 1 hund", "Fleip"])
uttalelse.app... |
from django import forms
from .models import sampledata
class formdata(forms.ModelForm):
class Meta:
model = sampledata
fields = '__all__' |
from arvore import Arvore
import sys
nome_arquivo = sys.argv[1]
with open(nome_arquivo, 'r') as arquivo:
genoma = ''
for linha in arquivo:
if not linha.startswith('>'):
genoma += linha.replace('\n', '')
arvore = Arvore(genoma)
arvore.maior_substring_repetida()
|
# get the number of marks
number_of_marks = int(input("Enter the number of marks: "))
# initialize total
total = 0
# compute the total of the marks
for i in range(number_of_marks):
# get a mark from the user and add to total
mark = float(input("Enter a mark: "))
total = total + mark
# compute average bas... |
# Пользователь вводит время в секундах. Переведите время в часы,
# минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк.
seconds_input = int(input('Введите время в секундах: '))
day = seconds_input // 86400
hours = (seconds_input // 3600) % 24
minutes = (seconds_input // 60) % 60
seconds ... |
from NTWebsite.improtFiles.processor_import_head import *
from NTWebsite.improtFiles.models_import_head import *
from NTWebsite.Config import AppConfig as AC
from NTWebsite.Config import DBConfig as DC
def indexView(request):
return HttpResponseRedirect("/Topic/List/0/LE/1")
def PaginatorInfoGet(objects, number... |
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.lang import Builder
Builder.load_file('driver_vote.kv')
class DriverVoteWindow(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def refresh(self):
pass
d... |
import argparse
from pathlib import Path
from server import base_path, redis_client
from server.modules.file_manager.dto import CommandResult
from server.modules.file_manager.services.actions import BaseCommand
class FilesCopyCommand(BaseCommand):
"""Command for copying files in directory"""
def __init__(se... |
# # Extending your Metadata using DocumentClassifiers at Index Time
#
# With DocumentClassifier it's possible to automatically enrich your documents
# with categories, sentiments, topics or whatever metadata you like.
# This metadata could be used for efficient filtering or further processing.
# Say you have some c... |
import os, sys
import arcpy
from TINcontours import tin_contours
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
self.label = "TIN Processing Toolbox"
self.alias = ""
# List of tool classes associa... |
import sys
import logging
if sys.version_info < (3, 0):
reload(sys)
sys.setdefaultencoding('utf8')
sys.path.append("../xmpp_bot")
logging.basicConfig(level=logging.DEBUG)
server = 'localhost'
port = 5222
from xmpp_bot.controllers.copernicus import DashboardController
if __name__ == '__main__':
if len(... |
# %%
import pandas as pd
from util import con, cfg, db, file
cfg_fname = "./config/config.json"
DailyOHLCmin_TB = cfg.getConfigValue(cfg_fname, "tb_mins")
rddb_con = db.mySQLconn(DailyOHLCmin_TB.split(".")[0], "read")
mins5_OHLC = pd.read_sql(f"""SELECT * FROM {DailyOHLCmin_TB} WHERE TradeTime <= '09:05:00' AND Tra... |
from sklearn import tree
from sklearn.metrics import accuracy_score
from scipy.spatial import distance
import scipy
from pylab import *
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
def euc(a,b):
return distance.euclidean(a,b)
class MyKNN():
def fit(self, x_train, y_train):
self.x_train =... |
import pdb
class Solution:
def __init__(self):
self.factors = [1]
for i in range(9):
self.factors.append(self.factors[i] * (i+1))
def getPermutation(self, n, k):
left = k
pointer = n
chosen = []
result = []
for i in range(n):
chosen.append(str(i+1))
#pdb.set_trace()
while pointer > 0:
if l... |
from Reporters.API.Reporter import Reporter
from Services.Logger.Implementation.Logging import Logging
from ResultData.ResultData import ResultData
class TextFileReporter(Reporter):
def __init__(self, path, file_service):
self.path = path
self.file_service = file_service
self.file = None
... |
import math
from typing import List
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
start = 0
end = len(nums)-1
middle = math.ceil(end/2)
#print(start, middle, end)
while not (middl... |
import tensorflow as tf
import os
import numpy as np
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
x = np.arange(0, 6000)
# print(x)
dataset = tf.data.Dataset.from_tensor_slices(x)
dataset = dataset.batch(32)
dataset = dataset.shuffle(buffer_size=10000)
dataset = dataset.repeat(5)
iterator = dataset.make_one_shot_iter... |
#######################################################################################################################
#
# caughtSpeeding
#
# You are driving a little too fast, and a police officer stops you. Write code to compute the
# result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticke... |
# check if a book is existing in your collection
collectionOfBooks = ["The Alchemist", "How to win friends and influence people", "The seven habits of highly effective people"]
print("Enter the name of the book: ")
bookToBeChecked = input()
for book in collectionOfBooks:
if book == bookToBeChecked:
print("... |
class UserGroup:
def __init__(self, id = -1, name = "", parent_groups = {}, protein_groups = []):
self.__id = id
self.__name = name
self.__parents = parent_groups
self.__proteins = protein_groups
def get_name(self):
return self.__name
def get_proteins(self):
proteins = dict()
for g... |
'''
Copyrights 2021
Work Done By Mike Zinyoni https://github.com/mikietechie
mzinyoni7@gmail.com (Do not spam please)
(Open to work)
''' |
from django.shortcuts import render
from rest_framework import status,generics
from user_watchlist.serializers import WatchListSerializer,WatchListCreateSerializer
from user_watchlist.models import UserWatchList as WatchList
class MovieListView(generics.ListCreateAPIView):
pagination_class = None
def get_quer... |
#!/usr/bin/env python
from sympy import symbols
import sympy.physics.mechanics as me
print("Defining the problem.")
# The conical pendulum will have three links and three bobs.
n = 3
# Each link's orientation is described by two spaced fixed angles: alpha and
# beta.
# Generalized coordinates
alpha = me.dynamicsym... |
import tensorflow as tf
def enum_each(enum_sizes, name="repeat_each"):
""" creates an enumeration for each repeat
and concatenates the results because we can't have
a tensor with different row or column sizes
Example:
enum_each([1,2,4])
Returns
[0,0,1,0,1,2,3]
the ... |
#coding:utf-8
from time import sleep
class Client():
def __init__(self, nom, prenom, numero_id, mdp):
self.nom = nom
self.prenom = prenom
self.numero_id = numero_id
self.mdp = mdp
### ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++###
### +++++++++++++... |
from script import send, send1, send2, send3, send4, send5
import schedule
import time
#Maths
schedule.every().monday.at("05:30").do(send)
schedule.every().tuesday.at("06:30").do(send)
schedule.every().wednesday.at("06:30").do(send)
schedule.every().friday.at("08:30").do(send)
#Formal Language & Automata th... |
from django.db import models
'''
By default, the django users model doesn't give the user the ability
to upload profile pictures, so we need to modify that by creating our own class and extending the default class
1. Extend the user model
2. create a new profile model, that has a one-to-one relationship with th... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import requests
import time
from flask import Flask
from flask import request
driver = webdriver.Firefox(executable_path = '/usr/local/bin/geckodriver')
driver.get("https://www.instagram.com/")
#login
time.sleep(5)
username = driver.find... |
# Generated by Django 2.1.1 on 2018-09-16 03:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lw2', '0015_profile_karma'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='display_name',
... |
from django.conf.urls import patterns, url
from albums import views
#Notes to self $ and ^ are regular expression characters that have special meaning
#The caret means that the pattern must match the start of the string eg rango/hisabout would still load the about page without it
#The dollar means that the pattern mus... |
import math
def num(s):
try:
return int(s)
except ValueError:
return float(s)
def get_divisor(n):
# max_try = int(math.floor(math.sqrt(n)))
max_try = 10
for k in range(2, max_try + 1):
if n % k == 0:
return k
return None
def num_of_base_x(n, x):
if l... |
from collections import defaultdict, Counter
from functools import reduce
class Solution:
def largestComponentSize(self, A: List[int]) -> int:
def find(i):
if uf.get(i, i) != i:
uf[i] = find(uf[i])
return uf.get(i, i)
def union(i, j):
uf[f... |
#
# DAPLink Interface Firmware
# Copyright (c) 2009-2016, ARM Limited, All Rights Reserved
# SPDX-License-Identifier: Apache-2.0
#
# 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... |
from kaizen.api import ZenRequest
from parse_this import parse_class, create_parser, Self
from pprint import pprint
from yaml.error import YAMLError
import os
import yaml
class KaizenConfigError(Exception):
"""Used when a configuration error occurs."""
def get_config(config_path):
"""Returns the configurati... |
import django_rq
def inflate_exception(job, exc_type, exc_value, traceback):
job.meta['exception'] = exc_value
job.save_meta()
return True
def move_to_failed_queue(job, *exc_info):
worker = django_rq.get_worker()
worker.move_to_failed_queue(job, *exc_info)
return True
|
import numpy as np
import torch
import torch.nn.functional as F
def softmax(scores):
es = np.exp(scores - scores.max(axis=-1)[..., None])
return es / es.sum(axis=-1)[..., None]
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset... |
from rest_framework import serializers
from tabelas.models import Publicacao
class PublicacaoSerializer(serializers.ModelSerializer):
class Meta:
model = Publicacao
fields = ['text', 'user', 'image'] |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-10-25 07:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('useraction', '0003_auto_20181025_1528'),
]
operations = [
migrations.AlterF... |
lst1 = [1, 2, 3, 4, 5]
lst2 = [10, 20, 30, 40, 50]
lst_zip = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50)]
print(lst_zip)
out = zip(lst1, lst2)
print(list(out))
tup1 = (1, 2, 3)
x, y, z = tup1
for x, y in zip(lst1, lst2):
print(x, y) |
def solution():
x=1
i=2
while numDivisors(x)<501:
x = x+i
i+=1
return x
def numDivisors(number):
i=2
divisors = [1,number] #array that will keep track of divisors
while i<((number**0.5)+1):
if number%i==0:
divisors += [i]
divisors += [number/i]
i+=1
else:
i+=1
return l... |
# office
# CAMERA_IP = "172.22.173.47"
# RASPBERRY_PI_IP = "172.22.150.239"
# home
CAMERA_IP = "192.168.2.41"
RASPBERRY_PI_IP = "192.168.2.50"
# thesis
# CAMERA_IP = ""
# RASPBERRY_PI_IP = ""
# camera uid
LOCK_DEVICE_UID = "da:device:ZWave:FD72A41B%2F5"
CAMERA_DEVICE_UID = "da:device:ONVIF:Bosch-FLEXIDOME_IP_4000i_I... |
BOARD_SIZE = 8
def move_rules_rook():
coor_deltas = []
for change in range(-BOARD_SIZE + 1, BOARD_SIZE):
new_position_horizontal = (0, change)
new_position_vertical = (change, 0)
if new_position_horizontal != (0, 0) and coor_deltas.count(new_position_horizontal) == 0:
coor_... |
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums == []:
return 0
result = len(nums)
new_len = 1
ptr = nums[0]
for i in range(1, len(nums)):
if ptr == nums[... |
import matplotlib
matplotlib.use("Agg")
import numpy as np
import matplotlib.pyplot as plt
import sys
n=500
mu=0
sigma=1
from scipy.stats import norm
d1=np.genfromtxt('sample_1.dat')
d2=np.genfromtxt('sample_2.dat')
d3=np.genfromtxt('sample_3.dat')
d4=np.genfromtxt('sample_4.dat')
x_axis = np.arange(-10, 10, 0.001)... |
from django.shortcuts import render, get_object_or_404, redirect, HttpResponseRedirect, HttpResponse
from .models import *
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.views import View
from .models import Patron
from django.contrib.auth.hashers import make_passwor... |
#!/usr/bin/env python
#
# -------------------------------------------------------------------------
# Copyright (c) 2015-2017 AT&T Intellectual Property
#
# 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 ... |
import numpy as np
def get_columns(i):
cates_map = {"blouse":0 ,"outwear":1,"trousers":2,"skirt":3,"dress":4 }
blouse_columns = np.array( [ 'neckline_left', 'neckline_right',\
'center_front', 'shoulder_left', 'shoulder_right', 'armpit_left',\
'armpit_right', 'cuff_left_in', 'cuff_left_out', 'c... |
import pytest
from applications.schema import BerthApplicationNode
from berth_reservations.tests.utils import (
assert_not_enough_permissions,
create_api_client,
)
from customers.schema import ProfileNode
from leases.schema import BerthLeaseNode
from resources.schema import BerthNode
from utils.relay import to... |
#
# Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/
# Written by Angelos Katharopoulos <angelos.katharopoulos@idiap.ch>,
# Apoorv Vyas <avyas@idiap.ch>
#
"""The weight mapper module provides a utility to load transformer model
weights from other implementations to a fast_transformers model.
NOTE: Th... |
import boto3
sqs = boto3.client("sqs")
s3 = boto3.resource("s3")
dynamodb = boto3.client("dynamodb")
def check_event_messages(queue_url):
messages = sqs.receive_message(QueueUrl = queue_url, MessageAttributeNames = ['Body',"ReceiptHandle"],MaxNumberOfMessages=10,WaitTimeSeconds=20)
if "Messages" in messages:... |
from django.shortcuts import render
def home(request):
return render(request, 'welcome/home.html', {'title':'HOME'})
def products(request):
return render(request, 'welcome/products.html', {'title':'PRODUCTS'})
def animals(request):
return render(request, 'welcome/animals.html', {'title':'ANIMALS'})
def culture(r... |
from django.contrib import admin
from django.urls import path,include
from django.conf.urls.static import static
from .views.index import index
from .views.mark import mark
from .views.login import Login
urlpatterns = [
path('',Login.as_view(), name='login'),
path('2',index,name='homepage'),
path('resul... |
import random
import numpy as np
from collections import namedtuple
from envs.mdp import StochasticMDPEnv
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import Adam
def meta_controller():
meta = Sequential()
meta.add(Dense(6, init='lecun_uniform', input_sha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.