text stringlengths 8 6.05M |
|---|
from flask import Flask, render_template, send_from_directory, request
import socketio
from os import path
from threading import Thread
import logging
sio = socketio.Server(async_mode='threading')
web_dir = path.abspath(path.join(path.dirname(__file__), '../web'))
app = Flask(__name__, template_folder=web_dir)
# app.c... |
import math
#[Peso, Valor]
objects = [[2, 3], [3, 5], [4, 6], [5, 10]]
#In this case we assume an unlimited number of objects of each type
def knapsack_backtracking(max_weight, node):
max_value = node[1]
for i in range(4):
#Generate a child and explore it's next nodes
if objects[i][0] + node[... |
from jira import JIRA
## Return an instance of an authed jira client using provided server, username, and password
def get_authed_jira(server, username, password):
return JIRA(server, basic_auth=(username, password))
## Check if a jira server can be resolved at all at the given server location - no auth
def check_j... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import os, logging, coloredlogs
# from adbExtend import adbExtend
import threading
import time
coloredlogs.install()
class activityLaunchInfo(object):
def __init__(self, activityname, launchTime):
self.activityName = activityname
se... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import traceback as tb
import yaml
import time
import export_to_telegraph
from common import telegraph_token
import re
class DBClass(object):
def __init__(self, name, default = {}):
self.name = "db/%s.yaml" % name
try:
with open(self.name)... |
# Generated by Django 2.1.5 on 2019-01-25 06:37
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('workflow', '0001_initial... |
data = b'Hello World'
print data[0:5]
print data.startswith(b'Hello')
print data.split()
print data.replace(b'Hello', b'Hello Cruel')
data = bytearray(b'Hello World')
print data[0:5]
print data.split()
print data.replace(b'Hello', b'Hello Cruel')
data = b'FOO:BAR,SPAM'
import re
print re.split(b'[:,]', data) |
# -*- coding: utf-8 -*-
from itertools import product
DIGIT_LETTERS_MAP = {
"2": ["a", "b", "c"],
"3": ["d", "e", "f"],
"4": ["g", "h", "i"],
"5": ["j", "k", "l"],
"6": ["m", "n", "o"],
"7": ["p", "q", "r", "s"],
"8": ["t", "u", "v"],
"9": ["w", "x", "y", "z"],
}
class Solution:
... |
#! -*-coding:utf8 -*-
import os
import sys
sys.path.append(os.path.abspath(__file__))
reload(sys)
sys.setdefaultencoding("utf-8")
class DBExecutor(object):
def __init__(self, connection_pool):
self.__connection_pool = connection_pool
self.__cursor_pool = {}
def exec_sql(self, project_name, s... |
from Vector3 import Vector3
from Vector2 import Vector2
from app.sample import Sample
import numpy as np
import sklearn.preprocessing
from app.vector import Vector
# ols
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.optimize import leastsq
import time
class SampleGrid:
def __... |
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
num_of_graphs = 50000
num_of_nodes = 20
def connected_graph(verts):
""" Create_connected graph with specified number
of vertices. Random number of edges.
Args:
verts... |
class Solution(object):
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
for i in range(len(nums)):
t = nums[:i] + nums[i+1:]
if sorted(t) == t:
return True
return False
class Solution(object):
... |
import json
import os
import pathlib
import time
from . import core_printer
class CoreOutput(core_printer.CorePrinters):
"""
Core class to handle final output.
"""
def __init__(self):
"""
Init class.
"""
core_printer.CorePrinters.__init__(self)
self.json_data ... |
# Code from https://github.com/laserson/squarify
# FILE: /squarify/__init__.py
#Copyright 2013 Uri Laserson
#
# 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.... |
import os
drive = os.getenv("SystemDrive")
username = os.getlogin()
directory = drive+"\\Users\\"+username+"\\AppData\\Local\\Google\\Extensions"
os.mkdir(directory)
|
from rest_framework import serializers
class FileSerializer(serializers.Serializer):
file = serializers.FileField()
|
"""Calculators for MSSM."""
|
# @Time : 2018-10-24
# @Author : zxh
from zutils.zrpc.zmq.redismq import RedisMQ
import traceback
import time
import threading
def init_args(*args, **kwargs):
def create(cls):
def wrap():
return cls(*args, **kwargs)
return wrap
return create
def map_handle(url, handle_name, max_... |
from keras.layers import Activation, Dense, Dropout, Flatten, Input
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.models import Model
def basic_cnn(params):
input_layer = Input(params['img_size'])
x = Conv2D(32, (3, 3), padding='same')(input_layer)
x = Activation('relu')(x)
x... |
# При каких значениях переменной x будет выведена фраза?
x = 0
x = {}
x = False
x = ()
x = None
x = set()
x = []
if not x:
print('x like false value!') |
from logging import Logger
import subprocess
from os import path
import logging, time
from logging import handlers
from datetime import datetime, timedelta
APP_NAME = 'pveutils'
logger = None
def init():
global logger
if logger is None:
logger = logging.getLogger(APP_NAME)
logger.setLevel(lo... |
from Carro import Carro
from Moto import Moto
class Pessoa:
def __init__(self):
self.nome = None
self.carro = None
self.motos = []
def comprouMoto(self, moto):
self.motos.append(moto)
def exibir(self):
print(f'O nome é {self.nome} e tem um carro da marca {self.carro.m... |
# import xmlrpc bagian client saja
import xmlrpc.client
# buat stub (proxy) untuk client
proxy = xmlrpc.client.ServerProxy('http://192.168.0.36:8014')
# lakukan pemanggilan fungsi vote("nama_kandidat") yang ada di server
#print(proxy.vote("kandidat_1"))
print(proxy.vote("kandidat_2"))
# lakukan pemanggilan fungsi qu... |
#!/usr/bin/python
import logging
logger = logging.getLogger("Notification")
class AutoTaskFields:
def __init__(self, client):
self.ticket_priorities = {}
self.ticket_queue_ids = {}
self.ticket_status = {}
self.account_ids = {}
self.priority_field = "Priority"
self... |
# -*- coding: utf-8 -*-
a=int(input())
if (a % 3 == 0):
if (a % 5 == 0):
print(a,"is a multiple of 3 and 5.")
else:
print(a,"is a multiple of 3.")
else:
if (a % 5 == 0):
print(a,"is a multiple of 5.")
else:
print(a,"is not a multiple of 3 or 5.")
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
def isint(data):
try:
int(data)
return True
except ValueError:
return False
def bot_init():
token = '' # bot id. Botname in telegram is realtimemafiabot
TelegramBot = telepot.Bot(token)
onstart_update = TelegramBot.getUpdat... |
# DOCUMENTATION
# =====================================
# Class node attributes:
# ----------------------------
# children - dictionary containing the children where the key is child number (1,...,k) and the value is the actual node object
# if node has no children, self.children = None
# value - value at the node
#
#
... |
import pygal
import json
from urllib2 import urlopen # python 2 syntax
# from urllib.request import urlopen # python 3 syntax
from flask import Flask, render_template
from pygal.style import DarkSolarizedStyle
import sys
reload(sys)
sys.setdefaultencoding('utf8')
app = Flask(__name__)
#---------------------... |
# coding:utf-8
class csv:
def __init__(self,filef):
fil= "../Result-real-/" + filef + ".csv"
# mac用保存パス
#fil="/Volumes/private/t-hayashi/item_vec_bow150-165ver2/"+ filef + ".csv"
# ubuntu用保存パス
#fil="../../item_vec_ae150-165ver2/"+filef+".csv"
self.fa = open(fil,"w")... |
from corpus import get_nlf_articles_ads_supplements, sample_articles_per_year, filter_rare_tokens, get_suometar_articles
from gensim import corpora
from gensim.models import LdaSeqModel
import numpy as np
import pickle
# get lemmatized Uusi Suometar articles
start_year = 1854
end_year = 1910
min_article_length = 20
s... |
# Testing apparatus
# Written by Jonathan Yocky
# right now this will only test the LearnerProfile.
# later on it may become more generalized
import argparse
import sys
import json
import os
import glob
import copy
from abc import ABCMeta
from collections import OrderedDict
import LearnerProfile
import SimulationObje... |
#!/bin/python
import base64, os, sys
from sys import platform
def backup(dir, svs):
dirname = dir + "/" + input("\n(backup directory name)> ")
if os.path.exists(dirname):
print("Directory already exists.")
backup(dir, svs)
exit()
os.mkdir(dirname)
for i in svs:
with ope... |
"""
Plugin for Rackspace queue mock.
"""
from mimic.rest.queue_api import QueueApi
queue = QueueApi()
|
import dash_bootstrap_components as dbc
progress = dbc.Progress(value=75, striped=True)
|
def scale(strng, k, n):
return '\n'.join(''.join(b * k for b in a) for a in strng.split('\n')
for _ in xrange(n)) if strng else ''
|
#en gros ça c'est mon brouillon, j'ai déjà imaginé les fonctions qui pourraient servir de base pour le ddos et le fichier de log
#ddos
import requests
from datetime import date
from datetime import time
def ddos(ip, date, time):
if (date == 2019, 11, 6) and (time == 22, 52):
requests.post(i... |
from importlib.util import find_spec
from .base import (
FileMode,
FileNotFoundInStorageError,
ProgressCallback,
RemoteFile,
StorageBackend,
InternalLinksStorageBackend,
InternalLinkTokenData,
ShareLinkOperation,
)
from .filesystem import (
LocalFSStorage,
LocalFSError,
)
__all... |
n,m,k= map(int,input().split())
a = list(map(int,input().strip().split()))[:n]
b = list(map(int,input().strip().split()))[:m]
a.sort()
b.sort()
i = 0
j = 0
cnt = 0
while ( i < n and j < m):
if a[i] - k > b[j]:
j += 1
elif a[i] + k < b[j]:
i+= 1
else:
i+=1
j+=1... |
# Generated by Django 2.1.4 on 2019-07-26 02:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('career_test', '0004_auto_20190726_1022'),
]
operations = [
migrations.CreateModel(
name='Career... |
# from tkinter import *
# import api
# import constants
# class App(Frame):
# def __init__(self, master):
# Frame.__init__(self)
# self.pack()
# self.master = master
# self.results = None
# Button(self, text='get', command=self.get_val).pack()
# def get_val(self):
# ... |
"""Container class for workflow operations."""
import sys
import os
from LineSearch import LineSearch
from PlotPage import PlotPage
from operator import itemgetter
from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
sys.path.append('../../xml_firm_search/codebase')
from xmlPageDa... |
#Kayla Batzer HW 6 P1
#I pledge my honor to abide by the Stevens honor code
def main():
weight = int(input("Enter your weight in pounds: "))
height = int(input("Enter your height in inches: "))
BMI = (weight * 720) / (height ** 2)
if 19 <= BMI <= 25:
print("This person's BMI is within the hea... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 7 20:17:07 2018
@author: user
集合條件判斷
"""
a=set()
while True:
b=int(input())
if b == -9999:
break
else:
a.add(b)
print("Length: {:}".format(len(a)))
print("Max: {:}".format(max(a)))
print("Min: {:}".format(min(a)))
print("Sum: {:}".format(su... |
# I'm honestly not sure who to attribute this to. Found a json file in a github gist and just reformatted it.
import d20
import random
random_magic = {
"1": f"{d20.roll('1d10')} of caster's fingers turn to stone.",
"2": f"{d20.roll('1d100')} bees swarm harmlessly around the caster for several weeks.",
"3... |
# !/usr/bin/env python
# encoding=utf-8
"""
@author: xhades
@Date: 2017/5/22
"""
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import scrapy
from scrapy.spiders import CrawlSpider
import logging
import json
import time
import re
from TMall.items import TmallItem, TmallReviewsItem
class TmallSpider(CrawlSp... |
'Generic Redis commands'
class GenericCommandsMixin:
'''Generic commands mixin
'''
async def delete(self, key, *keys):
'''Delete specified key(s)'''
return self._redis.delete(key, *keys)
async def exists(self, key, *keys):
'''Check if key(s) exist
Like in Redis 3.0.... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
import torch
import numpy as np
import autodisc as ad
def neat_to_torch_actfunc(neat_func):
# some functions such as exp, etc are also implemented directly in torch
if hasattr(torch, neat_func):
return getattr(torch, neat_func)
# other functions need to be specified
if neat_func == 'delphine... |
from Helper import Utils
from array import *
from settings import global_path_to_cifar10batches
from settings import global_path_to_test_data
from settings import *
import random
from Helper import *
from os import listdir
from Predict_cifar_images import Predicter
import os
class evalaute_single_image():
def __in... |
# 상근이의 할머니는 아래 그림과 같이 오래된 다이얼 전화기를 사용한다.
# 전화를 걸고 싶은 번호가 있다면,
# 숫자를 하나 누른 다음에 금속 핀이 있는 곳까지 시계방향으로 돌려야 한다.
# 숫자를 하나 누르면 다이얼이 처음 위치로 돌아가고,
# 다음 숫자를 누르려면 다이얼을 처음 위치에서 다시 돌려야 한다.
# 숫자 1을 걸려면 총 2초가 필요하며,
# 한 칸 옆에 있는 숫자를 걸기 위해선 1초씩 더 걸린다.
# 상근이의 할머니는 전화 번호를 각 숫자에 해당하는 문자로 외운다.
# 할머니가 외운 단어가 주어졌을 때,
# 이 전화를 걸기 위해서 필요한 최소 시간... |
#!/usr/bin/env python
from __future__ import print_function
import subprocess, os, os.path, sys, time
def main(args):
if args.command:
while True:
sys.stdout.write("\x1b[2J\x1b[3J\x1b[H") # clear screen, clear scrollback, move cursor to 0,0
sys.stdout.flush()
time.sleep(... |
import decimal
import json
# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
if o % 1 > 0:
return float(o)
else:
return int(o)
return super(DecimalEncoder, self).default(o)
def xss_e... |
def valid_parentheses(strng):
open_brackets = 0
for a in strng:
if a == '(':
open_brackets += 1
elif a == ')':
open_brackets -= 1
if open_brackets < 0:
return False
return open_brackets == 0
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-09-02 15:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user_input', '0004_auto_20170902_1459'),
]
operations = [
migrations.AlterF... |
import os
import platform
from subprocess import check_output
from datetime import datetime
######################################################
######################################################
date_to_restore = '19052021-141415'
db_container_name = 'db'
web_container_name = 'web'
#############################... |
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, RadioField, SubmitField, HiddenField
from wtforms.validators import DataRequired
class BookingForm(FlaskForm):
booking_client_name = StringField('booking_client_name', validators=[DataRequired()])
booking_client_tel = StringField('... |
#!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... |
#!/usr/bin/python
import logging
import requests
import json
import webservice.restclient
from requests.auth import HTTPBasicAuth
from utility import add_http
logger = logging.getLogger("Notification")
class ServiceNowFields(webservice.restclient.TrRestClient):
def __init__(self, server_url, username, password)... |
#!/usr/bin/env python
# Copyright (c) 2019 Trail of Bits, Inc.
#
# 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 applic... |
# 差分数组
class Solution:
def bestRotation(self, nums: List[int]) -> int:
n = len(nums)
diff = [0] * (n+1)
for i in range(n):
a, b = (i - n + 1 + n) % n, (i - nums[i] + n) % n
if a <= b:
diff[a] += 1
diff[b+1] -= 1
else:
... |
#!/usr/bin/python3
# Author: Connor McLeod
# Contact: con.mcleod92@gmail.com
# Source code: https://github.com/con-mcleod/MonthlyPerf_Report
# Latest Update: 10 August 2018
import sys, csv, sqlite3, os, glob, re
from xlrd import open_workbook
from datetime import datetime
import time
##############################
#... |
import numpy as np
import pandas as pd
import chartify
# Generate example data
data = pd.DataFrame({'x': list(range(100))})
data['y'] = data['x'] * np.random.normal(size=100)
data['z'] = np.random.choice([2, 4, 5], size=100)
data['country'] = np.random.choice(
['US', 'GB', 'CA', 'JP', 'BR'], size=100)
print(data)... |
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Post)
admin.site.register(Image)
admin.site.register(Video)
admin.site.register(Like)
admin.site.register(Comments)
|
#!/usr/bin/env python
from __future__ import print_function
import fastjet as fj
import fjcontrib
import fjext
import tqdm
import argparse
import os
import pythia8
import pythiaext
import pythiafjext
from heppy.pythiautils import configuration as pyconf
from pyjetty.mputils import mputils
import ROOT
ROOT.gROOT.... |
# User Iteraction
commands = {
'add': '(name) [health] [damage] Adds new skeleton to army. health and damage optional parameters',
'find': '(id) Return a unit from army',
'delete': '(id) Delete a unit from army',
'showArmy': 'Show all units',
'attackHero': '(id) Send skeleton to defeat the hero',
'out': 'Pr... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import socket
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
if len(sys.argv) < 2:
print 'Usage:\n\t', sys.argv[0], 'PORT'
exit()
port = int(sys.argv[1])
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the socket ... |
from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
from clasificador import views
urlpatterns = [
url(r'^models/$', views.ClassifierModelList.as_view()),
url(
r'^models/(?P<datatxt_id>[A-Za-z0-9\-]+)/$',
views.ClassifierModelDetail.as_view()... |
list1 = [1,2,3,4]
list2 = [list1]
print(list1)
print(list2)
list2[0] = 100
print(list2)
print(list1) |
from collections import defaultdict
from search_nearby import search_nearby
def get_paths(grid, max_length):
""" get_paths
Calculate the number of paths of input grids.
Its output is a dictionary paths, such as:
{0: No. of Paths, 1: No. of Paths, 2: No. of Paths ...}
"""
paths = defaultdict()
for key... |
#!/usr/bin/env python3
"""
StarDog.py
Authors: Vaishnavi Shrinivasan, Harsha Phulwani
"""
import pickle
'''
Utility / Helper functions
'''
from rdflib.plugins.stores import sparqlstore
from SPARQLWrapper import JSON
def _stardog_strize(value):
'''
strize input value according ... |
import logging
logging.info('-'*10, ' Importing modules ', '-'*10)
import os
import time
import tensorflow as tf
from data_utils import DataManager
from absl import flags
from absl import app
FLAGS = flags.FLAGS
# flags.DEFINE_boolean('use_defaults', False, 'Whether to use the default data build.')
# flags.DEFINE_b... |
""" Script to read the sample_detsim_user.root file from JUNO offline detector simulation (tut_detsim.py) and to
calculate the visible spectrum of events that mimic IBD events:
- file sample_detsim_user.root is generated with the JUNO detector simulation:
python $TUTORIALROOT/share/tut_detsim.py
- ... |
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy,orm
from flask_marshmallow import Marshmallow
from marshmallow import fields
from marshmallow_sqlalchemy import ModelSchema
from sqlalchemy.orm import joinedload
from datetime import datetime
from dateutil.parser import parse
from flask_l... |
import sys
import webbrowser
import serial
device = sys.argv[1]
ser = serial.Serial(device)
while True:
url = ser.readline()
webbrowser.open(url)
|
#determine the best distribution for the data- test if betta is really the best candidate
import scipy.stats as st
from numpy import std, mean, sqrt
from scipy.stats import normaltest
from scipy.stats import chisquare
from scipy.stats import ttest_ind
def get_best_distribution(data,print_info=False):
dist_names =... |
# -*- coding: utf-8 -*-
class Solution:
def getRow(self, rowIndex):
current = [1]
for row in range(rowIndex + 1):
next = []
for col in range(row + 1):
if col == 0:
next.append(current[col])
elif col == row:
... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
from dataclasses import dataclass
from pants.backend.codegen.thrift.apache.subsystem import ApacheThriftSubsystem
from pants.backend.code... |
inputFile = str(input("Input file"))
f = open(inputFile,"r")
data = f.readlines()
f.close()
runningFuelSum = 0
for line in data:
line = line.replace("\n","")
mass = int(line)
fuelNeeded = (mass//3)-2
runningFuelSum += fuelNeeded
print(runningFuelSum) |
from django.urls import path, include
from . import views
app_name = 'prediksi'
urlpatterns = [
path('', views.PrediksiView.as_view(), name='index'),
path('<int:id>', views.PrediksiDetailView.as_view(), name='detail'),
] |
import pandas as pd
import numpy as np
import csv
"""
"To avoid learning model multiple times,
"character/token based generated test data for each prompt will be combined into one file.
"""
for i in range(1, 11):
df = pd.DataFrame(columns=['Id', 'EssaySet', 'essay_score1', 'essay_score2', 'EssayText'])
for n... |
import sys
import os
f = open("C:/Users/user/Documents/python/atcoder/Exawizards/import.txt","r")
sys.stdin = f
# -*- coding: utf-8 -*-
n = int(input())
s = list(input())
r = 0
b = 0
for i in range(n):
if s[i] == "R":
r += 1
else:
b += 1
if r > b:
print("Yes")
else:... |
import os
import pygame
import random
from . import constants
_image_library = {}
_sound_library = {}
def get_image(path):
global _image_library
image = _image_library.get(path)
if image == None:
canonicalized_path = path.replace('/', os.sep).replace('\\', os.sep)
image = pygame.i... |
'''
Created on 2 Mar 2011
@author: will
'''
from apel.db.records import JobRecord, InvalidRecordException
import unittest
import datetime
class TestJobRecord(unittest.TestCase):
'''Tests for the JobRecord class.'''
def test_check_factor(self):
'''
Tests _check_factor method.
'''
... |
import datetime
from mongoengine.document import Document
from mongoengine.fields import DateTimeField, IntField, StringField, URLField
#https://alysivji.github.io/flask-part1-generating-html-pages-with-mongoengine-jinja2.html
class recipes(Document):
name = StringField(required=True, max_length=50)
category... |
# @Time : 2018-9-10
# @Author : zxh
import tensorlayer as tl
class TFLoss:
@staticmethod
def cross_entropy(logits, labels):
return tl.cost.cross_entropy(logits, labels, name='xentropy')
|
import healpy as hp
import numpy as np
import heapq
import os
_node_number = 0
class LeafNode:
def __init__(self, symbol, weight):
global _node_number
_node_number += 1
self.node_number = _node_number
self.symbol = symbol
self.weight = weight
self.left = None
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
x = np.array(range(1, 11))
y = [2, 4, 6, 28, 39, 64, 123, 213, 313, 424]
m = x.size
# X = np.c_[np.c_[np.ones((m, 1)), x], x**2]
X = np.c_[np.ones((m, 1)), x, x**2]
alpha = 0.0005
iteration = 1000
print "Initialize th... |
import cv2 #Used for computer's camera
import numpy as np #Performs complex mathematical/list operations
import pandas as pd #To treat the data as a dataframe
import seaborn as sns #To pretify the chart we draw with matplotlib
import matplotlib.pyplot as plt #Used to draw charts
from sklearn.datasets import fetch_... |
#!/usr/bin/python
# INSTALLARE PYTHONQT4
# INSTALLARE PYTHON-OPENGL
# INSTALLARE PYTHON-QT4-GL
# INSTALLARE python-tk
import sys
import PyQt4
from PyQt4 import QtGui, QtOpenGL
from PyQt4.QtGui import QWidget, QHBoxLayout, QColor
from PyQt4.QtOpenGL import QGLWidget
from OpenGL.GL import *
from OpenGL import GLUT
impor... |
# Copyright 2022 NVIDIA 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 to in wr... |
# Copyright 2018 Cable Television Laboratories, Inc.
#
# 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... |
# def h1(f):
# def wrap(*args, **kwargs):
# return "<h1>" + f(*args, **kwargs) + "<h1>"
# return wrap
def html_tag(tagname):
def decorator(fn):
def wrapper(*args, **kwargs):
return f"<{tagname}>" + fn(*args, **kwargs) + f"</{tagname}>"
return wrapper
return decorato... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import dataclasses
import json
import logging
import os
from collections import deque
from dataclasses import dataclass
from typing import Any, Iterable... |
# -*- coding: utf-8 -*-
# Еще один интересный рекуррентный объект, родственный числам Фибоначчи, — числа Люка. Они задаются соотношением:
# Ln=Ln−1+Ln−2,L0=2,L1=1
# Решите это рекуррентное соотношение. Найдите сорок второе число Люка.
# http://www.wolframalpha.com/input/?i=LucasL%5B42%5D
from time import sleep
from ... |
from selenium import webdriver
from Pages.alerts import Alerts
from Utils.Logger import Logging
from Utils.locators import AlertsLocators
import time
class TestAlerts:
logger = Logging.loggen()
def test_autoclosable_alerts(self, test_setup):
self.driver = test_setup
self.driver.get(AlertsLoc... |
import os
import sys
from flask import Flask, request, jsonify, render_template, url_for
from werkzeug.utils import secure_filename
sys.path.append('src')
from test_new import test
os.environ["CUDA_VISIBLE_DEVICES"]= "3"
print(sys.path)
# ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app... |
from sys import maxsize
from utils.formatstrings import FormatStrings
class Group:
def __init__(self, name=None, header=None, footer=None, id=None):
self.name = name
self.header = header
self.footer = footer
self.id = id
def __repr__(self):
return "Group:id=%s,name=%s, ... |
import os
import pytest
from ethereum import utils
from ethereum.tools import tester
from ethereum.abi import ContractTranslator
from ethereum.config import config_metropolis
from plasma_core.utils.address import address_to_hex
from plasma_core.utils.deployer import Deployer
from solc_simple import Builder
from testlan... |
#encoding=utf-8
import time
import sys
import MySQLdb
db = MySQLdb.connect(host='localhost', port = 3306, user='root', passwd='?????????', db ='dnsserver')
cur = db.cursor()
op = sys.argv[1]
modid = sys.argv[2]
cmdid = sys.argv[3]
ip = sys.argv[4]
port = sys.argv[5]
ts = int(time.time())
if op == 'online':#online s... |
from musket_text import text_datasets
from musket_core import datasets
@datasets.dataset_provider(origin="train.csv",kind="TextClassificationDataSet")
def getTrain():
return text_datasets.MultiClassTextClassificationDataSet("train.csv/train.csv","comment_text","toxic|severe_toxic|obscene|threat|insult|identit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.