text stringlengths 8 6.05M |
|---|
###########################
# project_euler number 3
# by 김승현
###########################
# Q. 가장 큰 소인수 구하기
N = 600851475143
div = 2
# 소수 찾기
while N != 1:
if N % div == 0:
N = N / div
else:
div = div + 1
print(div) |
def double_every_other(lst):
return [x if c%2==0 else x*2 for c,x in enumerate(lst)]
'''
Write a function, that doubles every second integer in a list starting from the left.
'''
|
# -*- coding:utf-8 -*-
import os
import glob
current_path = os.path.dirname(os.path.realpath(__file__))
def storage_path(file_path=""):
return os.path.join(base_path("storage"), file_path)
def base_path(file_path=""):
return os.path.join(current_path, file_path)
def get_faces():
retur... |
from django.http.response import HttpResponse
from django.shortcuts import redirect, render
from meetups.admin import MeetupAdmin
from .forms import RegistrationForm
from .models import Meetup, Participant
# Create your views here.
def index(request):
meetups = Meetup.objects.all()
return render(request, 'm... |
'''
1. 首先需要丢弃字符串前面的空格;
2. 然后可能有正负号(注意只取一个,如果有多个正负号,那么说这个字符串是无法转换的,返回0 比如测试用例里就有个“+-2”);
3. 字符串可以包含0~9以外的字符,如果遇到非数字字符,那么只取该字符之前的部分,如“-00123a66”返回为“-123”;
4. 如果超出int的范围,返回边界值(2147483647或-2147483648)。
5. 注意字符转化为整数的方法, digit = ord(str[i]) - ord('0') 此点一定要记住
'''
class Solution:
def myAtoi(self, str: str) -> int:
... |
import sys, os
from socket import *
if(len(sys.argv)>2):
host=sys.argv[1]
port=int(sys.argv[2])
else:
print("Unable to create connection, required parameters 'Host' and/or 'Port' where not provided")
sys.exit(1)
server_address=gethostbyname(host)
connection_socket=socket(AF_INET,SOCK_STREAM)
connection_socket.conn... |
from flask import Flask, g, current_app
from flask_sqlalchemy import SQLAlchemy
from . import config
app = Flask(__name__)
db = SQLAlchemy()
def create_app():
app.config.from_object(config.Config)
db.init_app(app)
with app.app_context():
# Imports
from resourse.api import courseBp, fileBp, authBp, checkBp
... |
# coding=utf-8
from mongo_YouKu import MongoUrlManager
from crawler_YouKu import Crawler_YouKu
import time
import os
mongo_mgr = MongoUrlManager()
root_url = "https://list.youku.com/category/show/c_100.html"
mongo_mgr.enqueueUrl(root_url, 0)
while True:
record = mongo_mgr.dequeueUrl()
if record == N... |
# Generated by Django 3.0.6 on 2020-05-24 16:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0003_auto_20200521_1203'),
]
operations = [
migrations.AddField(
model_name='keyword',
name='today',
... |
# 一维排序后,转换为LIS问题
class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
pairs.sort(key=lambda x : (x[0], x[1]))
n = len(pairs)
dp = [1]*n
for i in range(n):
for j in range(i):
if pairs[i][0] > pairs[j][1]:
dp[i] = m... |
class Solution:
def minimalKSum(self, nums: List[int], k: int) -> int:
nums.sort()
cnt, res = 0, 0
left = 0
for item in nums:
if cnt == k:
break
if item > (left + 1):
temp = min(item - left - 1, k - cnt)
cnt += t... |
#!/usr/bin/env python
import logging
import theano
from argparse import ArgumentParser
from theano import tensor
from blocks.algorithms import GradientDescent, Adam
from blocks.bricks import MLP, Identity, Sigmoid, Softmax
from blocks.bricks.cost import CategoricalCrossEntropy, MisclassificationRate
from blocks.init... |
from __future__ import unicode_literals
from django.db import models
from .member import Member
from rest_framework.exceptions import NotFound
# Create your models here.
class Item(models.Model):
uploaded_by = models.ForeignKey(Member, on_delete=models.CASCADE)
item_name = models.CharField(max_length=200, nul... |
"""Tests for ``tinyflow.ops``."""
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
import inspect
import operator as op
import os
import pytest
from tinyflow import _testing, exceptions, ops, Pipeline, tools
def test_default_description():
tform = ops.flatten()
assert repr(tform) == ... |
from django.db.models.signals import post_save #apps ability to save new users
from django.contrib.auth.models import User
from django.dispatch import receiver #making receiver
from .models import Profile #when we make a user, make a profile
@receiver(post_save, sender=User)
def create_profile(sender, instance, create... |
def check(string):
count = 0
for i in range(len(string)-6):
if string[i] == 'a' and string[i+1] == 'b' and string[i+2] == 'a' and string[i+3] == 'c' and string[i+4] == 'a' and string[i+5] == 'b' and string[i+6] == 'a':
count += 1
return count
t = int(input())
while t > 0:
... |
import unittest
from Data_work import *
class tests(unittest.TestCase):
def test_grade_func(self):
self.assertEquals(0, test_grades(['A', 'A', 'A', 'A']))
self.assertEquals(-1, test_grades(['A', 'B', 'C']))
self.assertEquals(1, test_grades(['C', 'A', 'B']))
self.assertEquals(0, test... |
import uuid
from django.db import models
from django.contrib.auth.models import User
from basketball.models import GAME_TYPES, SCORE_TYPES, Season
PERMISSION_TYPES = [
('read', 'Read'),
('edit', 'Edit'),
('admin', 'Admin')
]
class Group(models.Model):
name = models.CharField(max_length=60, blank=False... |
# -*- coding: utf-8 -*-
import base64
import hmac
import hashlib
import json
import urllib
import urllib2
from datetime import datetime as dt
from logger import Logger
class SmsClient(object):
"""
通过电信 API 发送短信
"""
def __init__(self, app_id=None, app_secret=None, grant_type='client_credentials'):
... |
# Modules
import os
import csv
# Path to collect data from the Resources folder
elections = os.path.join('Resources', 'election_data.csv')
electionDataCsv = csv.reader(open(elections))
header = next(electionDataCsv)
# Define Variables
totalVotes = 0
khanVotes = 0
correyVotes = 0
liVotes = 0
otooleyVotes = 0
# Define ... |
# https://sensepost.com/blog/2017/linux-heap-exploitation-intro-series-used-and-abused-use-after-free/
import socket
import re
import struct
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('46.101.80.6', 10000)
sock.connect(server_address)
try:
# hello
data = sock.recv(1024)
p... |
from django.shortcuts import render
from course_management_app.forms import StudentProfileInfoForm , CourseForm
def index(request):
return render(request,'course_management_app/index.html')
# Create your views here.
def userdetails(request):
stude_form = StudentProfileInfoForm()
course_form = C... |
"""(a) Write a function to print the first N numbers of the Fibonacci sequence.
(b) Write a function to print the Nth number of the sequence."""
def fibonacci_sequence(n_series):
term_1 , term_2 = 1, 1
n_term = 0
count = n_series
while count >= 0:
n_term = term_1 + term_2
term_2 = term... |
import unittest
from katas.kyu_7.calculate_meal_total import calculate_total
class CalculateTotalTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(calculate_total(5.00, 5, 10), 5.75)
def test_equal_2(self):
self.assertEqual(calculate_total(36.97, 7, 15), 45.10)
def t... |
import wx
serverMsgAttr = wx.TextAttr(wx.Colour(128, 0, 0))
clientMsgAttr = wx.TextAttr(wx.Colour(0, 0, 128))
plainMsgAttr = wx.TextAttr(wx.Colour(0, 0, 0))
class MSSPInfo(wx.Dialog):
def __init__(self, conn):
worldname = conn.world.get('name')
wx.Dialog.__init__(self, conn, title = "MSSP Inf... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
data = np.loadtxt('../../data/data-01.csv', delimiter=",")
# print(data)
# 2차원 데이터로 뽑아오기
# matrix 연산을 하기 위해서는 2차원 텐서로 되어야 한다.
x_data = data[:, :-1]
# y_data = data[:, -1:]
y_data = data[:, [-1... |
from collections import defaultdict
instances = defaultdict(list)
instances['InsLocation'].append('roomA')
instances['InsLocation'].append('roomB')
print(instances)
for key, value in instances.items():
print(key)
print(value)
print('---')
|
'''Редактирование строк'''
my_array = [14, 92, 13, 58, 25, 61, 26]
my_string = '14, 92, 13,'
my_array[2] = 'тринадцать'
print(my_array)
'''Чтобы заменить символ в строке, используем
метод
⭐️ - .replace('x', 'y', n) - меняем х на у n раз'''
clean_string = my_string.replace(',', '', 2)
print(clean_string)
|
import os
import sys
import getopt
def walkDir(dir):
generator_ = os.walk(dir)
for rootDir, pathList, fileList in generator_ :
for f in fileList:
#print(os.path.join(rootDir, f))
write2file_2(os.path.join(rootDir, f), ["blablablabla\n", "xxxxx\n"])
#def displayDir2(dir):
# for i in os.listdir(dir):
# ... |
#Test loading in training data
import os
import sys
#Path hack
dir_path = os.path.dirname(os.path.realpath(__file__))
parent_path = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
sys.path.append(parent_path)
#Load modules
from DeepForest.utils.generators import create_NEON_generator, load_training_data, load_r... |
from django.urls import path
from . import views
urlpatterns=[
path("",views.index,name='index'),
path("<int:fid>",views.flight,name='flight'),
path("<int:fid>/book",views.book,name="book"),
]
|
from gensim.models import word2vec
import numpy as np
import pandas as pd
import os
import re
import pickle
import copy
import sys
from time import sleep
max_length = 50 #max nr of words in sentence
vec_length = 100 #dimensions in word vector
#track movie characters, to differentiat speaker and listener
def init_mov... |
import os
import sys
def split_file(path, neighbourhood):
# splitLen = 4
f = open(f'{path}\{neighbourhood[0]}.txt','r').read().split('\n')
length = len(neighbourhood) - 1
print(length)
linetotal = len(f)
print(linetotal)
splitLen = int(linetotal / length)
print(splitLen)
... |
from django.contrib import admin
from .models import Submission, Conference
admin.site.register(Submission)
admin.site.register(Conference) |
from unittest import TestCase
from mdat import core
__author__ = 'pbc'
class TestChoquetIntegral(TestCase):
def test_get_criteria_keys_sorted_by_value(self):
criteria = {'c1': .6, 'c2': .8, 'c3': .9, 'c4': .2}
expected_key_order = ['c4', 'c1', 'c2', 'c3']
ci = core.ChoquetIntegral(criteria=criteria)
... |
from dataStore import dataStore
fileAccess = ["/home/anushabangi/test1.py", "/home/anushabangi/test2.py"]
inodes = ["testnode1", "testnode2"]
computationTime = [19.00, 20.00]
dataObject = dataStore(fileAccess,inodes,computationTime)
print("Printing Object Values ...")
dataObject.showData()
print("Printing file dict... |
from flask import Blueprint, request
from sqlalchemy.exc import SQLAlchemyError
import json
from app.models import Loan, db
from app.utils.error_handling import make_error, check_types, check_types_with_none
loan_routes = Blueprint("loan", __name__)
@loan_routes.route("/<int:id>", methods=["GET"])
def get_loan(id)... |
'''
Created on Mar 28, 2015
@author: anthonydito
'''
import cPickle
import logging
import psycopg2
import socket
import threading
from Tkinter import *
logging.basicConfig(level=logging.DEBUG,
format='[%(levelname)s] (%(threadName)-15s) %(message)s',
)
class aiUser(Frame):
... |
import math
import numpy as np
import numba as nb
from numpy import array
@nb.njit(fastmath=True)
def distance(p1: array, p2: array) -> array:
return np.sqrt((p1[0]- p2[0]) ** 2 + (p1[1]- p2[1]) ** 2)
def right_or_left(p0, p1, vec0):
vec1 = p1 - p0
return 1 if np.cross(vec0, vec1) >= 0 else -1
@nb.nji... |
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
mid, left, right, left_num, right_num = self.partition(self, nums)
print("---")
while right_num != k - 1:
print("---")
... |
from apps.games import models
from django.core.management.base import BaseCommand
from django.db import IntegrityError
from django.utils.text import slugify
import rethinkdb as r
class Command(BaseCommand):
help = 'Get count for all extra data'
def handle(self, **options):
r.connect().repl()
... |
import os
import helpers
import matplotlib.pyplot as plt
import numpy as np
import pytest
import disba
if not os.environ.get("DISPLAY", ""):
plt.switch_backend("Agg")
@pytest.mark.parametrize(
"mode, wave, algorithm",
[
(0, "rayleigh", "dunkin"),
(0, "rayleigh", "fast-delta"),
(... |
"""
剑指 Offer 65. 不用加减乘除做加法
写一个函数,求两个整数之和,要求在函数体内不得使用 “+”、“-”、“*”、“/” 四则运算符号。
"""
def add1(a, b):
return sum(a, b)
# 哈哈哈哈,只是用来搞笑的。
def add(a, b):
"""
计算过程不让用最简单的加减乘除,那么就只能用位运算了,位运算其实并不简单。
:param a:
:param b:
:return:
"""
x = 0xffffffff
a = a&x
b = b&x
# 这个地方分为加和位和进位计算,加和位直接做异或运算,进位是当前位的与运算。
... |
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
title = "Мир дверей"
heading = "МЕЖКОМНАТНЫЕ СТЕКЛЯННЫЕ ДВЕРИ"
return render_template('index.html', page_title=title, heading=heading)
@app.route('/delivery')
def delivery():
title = "Мир дверей"
head... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, with_statement
from functools import wraps
from fabric.decorators import (task, hosts, roles, runs_once, serial,
parallel, with_settings)
from fabric.network import needs_host
from revolver.core import env
from ... |
import os
import shapefile
import time
from constants import KEY
from geometry import Polyline
from geometry import Point
from dataset import SERVICE, SERVICES
from dataset import BAD_STOP_IDS_BRT
from dataset import DATASETS
from dataset import OPEN_DATA_ROUTE_FILTER
from stop_updates import STOP_UPDATES, NEW_STOP... |
def f(x: int):
return x
def g(y: str):
return y
x = f(4)
g(x)
|
"""A class to represent an RSVP label-switched-path in the network model """
import random
from .exceptions import ModelException
class RSVP_LSP(object):
"""A class to represent an RSVP label-switched-path in the network model
source_node_object: Node where LSP ingresses the network (LSP starts here)
d... |
from pegasos import *
from sgdqn import *
from asgd import *
from olbfgs import * |
# *** Bank Database Management System ***
# A simple terminal application coded in python is used as frontend.
# Oracle’s MySQL is used as the backend database system
# Import pymysql package to provide a simple interface to MySQL Database.
import pymysql
# Take the credentials to MySQL as user input
username = input... |
class Weighable():
def __init__(
self,
sensor,
channel,
name,
weight_data,
location = None,
size = None,
tare_wt = None,
net_wt = None
):
self.sensor = sensor # this is a Sensor() instance, already set up
self.set_cha... |
import time
from crtsh import crtshAPI
from simplydomain.src import core_serialization
from simplydomain.src import module_helpers
from simplydomain.src import core_scrub
class DynamicModule(object):
"""
Dynamic module class that will be loaded and called
at runtime. This will allow modules to easily b... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/9/30 14:59
# @Author : Jason
# @Site :
# @File : test_xmltree2.py
# @Software: PyCharm
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
print(root)
for neighbor in root.iter('neighbor'):
print(nei... |
#!/usr/bin/python3
'''write and append a text in a file module'''
def append_write(filename="", text=""):
'''Write a function that appends a string at the end of a text file
(UTF8) and returns the number of characters added'''
with open(filename, mode="a", encoding="utf-8") as f:
lenght = f.write(... |
# Generated by Django 2.2.1 on 2019-05-19 00:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0005_auto_20190518_0511'),
]
operations = [
migrations.AlterField(
model_name='post',
name='modification_da... |
from bs4 import BeautifulSoup
html_doc="""
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a h... |
from flask import Flask
from flask_restful import Resource, Api
from resource.hotel import Hoteis, Hotel
#pip freeze -> Para saber quais pacotes instalados
app = Flask(__name__)
api = Api(app)
api.add_resource(Hoteis, "/hoteis")
api.add_resource(Hotel, "/hoteis/<int:hotel_id>")
if __name__ == '__main__':
app.r... |
def coin_tosses(nums):
print "Starting the program..."
head_count=0
tail_count=0
import random
for i in range(0,nums+1):
print "Attempt #"+str(i)+": Throwing a coin...",
if round(random.random())==1:
print "It's a head! ...",
head_count+=1
else:
... |
#!/usr/bin/env python
__author__ = 'Ronie Martinez'
class DidYouMeanError(AttributeError):
def __init__(self, class_name, attribute_name, close_matches):
self.message = "\n".join(["AttributeError: '%s' object has no attribute '%s'." % (class_name, attribute_name),
"Did y... |
#
# Class diary
#
# Create program for handling lesson scores.
# Use python to handle student (highscool) class scores, and attendance.
# Make it possible to:
# - Get students total average score (average across classes)
# - get students average score in class
# - hold students name and surname
# - Count total attend... |
n = int(input())
s = input()
es,ws = [],[]
if s[0] == 'E':
es.append(1)
ws.append(0)
else:
es.append(0)
ws.append(1)
for i in range(1,n):
if s[i] == 'E':
es.append(es[i-1]+1)
ws.append(ws[i-1])
else:
es.append(es[i-1])
ws.append(ws[i-1]+1)
ans = 9999999
for i i... |
from .models import ExtraInfo
from django.forms import ModelForm
class ExtraInfoForm(ModelForm):
"""
The fields on this form are derived from the ExtraInfo model in models.py.
"""
def __init__(self, *args, **kwargs):
super(ExtraInfoForm, self).__init__(*args, **kwargs)
self.fields['your... |
#!/usr/bin/env python
import time, struct, sys, logging, socket
import katcp_wrapper, log_handlers
import argparse
import pyqtgraph as pg
import numpy as np
from pyqtgraph.Qt import QtCore, QtGui
#bitstream = 'sb1k_2016_Oct_21_1640.bof.gz'
#bitstream = 'sb2k_2017_Jan_21_1219.bof.gz'
bitstream = 'sb4k_2017_Jan_21_193... |
from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path="C:\\Users\\ABHAY\\Selenium\\chromedriver.exe")
driver.implicitly_wait(30)
driver.maximize_window()
driver.get("https://opensource-demo.orangehrmlive.com/index.php/auth/login")
#time.sleep(3)
driver.find_element_by_xpath("//... |
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
... |
import asyncio
import logging
import os
from aiogram import Bot, Dispatcher, executor, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Text
from aiogram.dispatcher.filters.state import State, StatesGroup
from graph_uti... |
#1. List có nhiều từ
#2. random -> ra word
#3. word -> '------'
#4. guess -> 'đúng hay sai' l = list(word)
#5. 'vodka' -> " _ _ _ _ _ a" enumrate
#6. thắng thua
statues = [
"""
|------
| o
| |
|
|
"""
,
"""
|------
| o
| |-
|
|
"""
,
"""
|------
| o
| -|-
|
|
"""
,
"""
|------
| o
| -|-
| ... |
class AddHeader:
def response(self, flow):
flow.response.headers["newheader"] = "foo"
def load(l):
return l.boot_into(AddHeader())
|
# coding:utf8
from flask_wtf import FlaskForm
from wtforms import StringField, RadioField, SubmitField, PasswordField, FileField
from wtforms.validators import DataRequired, ValidationError
from wtforms import validators, widgets
class UserBaseForm(FlaskForm):
"""用户基本信息表单 """
# 个性签名
signature ... |
"""ZKSync API."""
|
__author__ = 'hamid'
from .models import MyUser
from django.contrib.auth.forms import UserCreationForm
class SignUpForm(UserCreationForm):
def __init__(self, *args, **kwargs):
super(UserCreationForm, self).__init__(*args, **kwargs)
for fieldname in ['username', 'password1', 'password2']:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 6 03:07:16 2020
@author: lifecell
"""
'''
Question 1
Write code that asks the user to input a number between 1 and 5 inclusive.
The code will take the integer value and print out the string value. So for
example if the user inputs 2 the code will ... |
#!/usr/bin/python
import zmq
import json
from keyczar.keys import AesKey
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5099")
file = open('shared_secret.junk')
key = AesKey.Read(file.read())
while True:
data = socket.recv()
data = key.Decrypt(data)
data = json.loads(dat... |
start = "Hello, "
name = input("What is your name? ")
end = ". How are you today?"
sentence = start + name + end
print(sentence)
|
import torch
import math
import numpy as np
try:
from . import constants as c
except ValueError:
import constants as c
import torch.nn as nn
from torch.autograd import Function
from torch.nn.functional import pairwise_distance, cosine_similarity
PairwiseDistance = nn.PairwiseDistance
CosineSimila... |
import scrapy.cmdline
def main():
# -o ['json', 'jsonlines', 'jl', 'csv', 'xml', 'marshal', 'pickle']
scrapy.cmdline.execute(['scrapy','crawl','mysina'])
if __name__ == '__main__':
main() |
import os
import math
import scipy
import numpy as np
from astropy.io import ascii
from astropy.io import fits
import matplotlib.pyplot as plt
import matplotlib as mpl
########################################
#~ print "#Give the ObIds in a text-file"
#~ font = {
#~ 'weight' : 'bold',
#~ 'size' : 15}
... |
def plot_gallery(title, images, n_col, n_row):
n = n_col*n_row
plt.figure(figsize=(2. * n_col, 2.26 * n_row))
plt.suptitle(title, size=16)
####!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! shen qi
for i, comp in enumerate(images[:n]):
plt.subplot(n_row, n_col, i + 1)
vmax = max(comp.ma... |
from setuptools import setup
setup(
name = 'sje',
version = '1.0.0',
description = 'Schema JSON Extractor.',
author = 'Ryan Yuan',
author_email = 'ryan.yuan@outlook.com',
packages = ['sje'],
install_requires = [
'pytest==5.0.0',
'PyYAML==5.1.1',
'sqlparse==0.3.0'
... |
import math
from matrix import Matrix
class GrayscaleMatrix(Matrix):
def __init__(self, width, height, value_type=int):
super().__init__(width, height)
x = 0 if value_type is int else 0.0
self.values = [[x] * height for _ in range(width)]
self.value_type = value_type
def app... |
import os,sys, time, re
from main.page.base import BasePage
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from main.page.desktop_v3.inbox_m... |
import tensorflow as tf
def inicializar_tensor_array(tensors, session):
for neural in tensors:
for tensor in neural:
session.run(tensor.initializer)
def pad_up_to(t, max_in_dims, constant_values):
s = tf.shape(t)
paddings = [[0, m-s[i]] for (i,m) in enumerate(max_in_dims)]
return tf... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 25 22:24:38 2020
@author: wanta
"""
# Tkinterライブラリのインポート
import tkinter as tk
import tkinter.ttk as ttk
# webbrowserライブラリのインポート
import webbrowser
BROWSER_EDGE = "Microsoft Edge"
BROWSER_CHROME = "Google Chrome"
BROWSER_IE = "Internet Explorer"
SITE_G = "Google"
SITE_Y ... |
from page.account.account_page import AccountPage
from page.account.bankcard_manage_page import BankcardManagePage
from page.account.add_bankcard_page import AddBankcardPage
from page.account.bankcard_info import BankcardInfo
from logic import bankcard_manage_page as bankcard
import allure
import pytest
import random... |
import ModuleDirectory.Module2
print(ModuleDirectory)
ModuleDirectory.Module2.say_hi() |
class GenericComponent:
def __init__(self, name: str):
pass
class Sensor(GenericComponent):
def __init__(self):
super().__init__("Sensor")
class Motor(GenericComponent):
def __init__(self):
super().__init__("Motor") |
'''
Dual share class pairs trading
Viacom Class A and B shares - both refers to the same company, and in fact they both give you ownership in the same underlying firm and in the same underlying firm and the same share of the profits.
Assumption:
- In theory, these two stocks ought to have exacly the same value.
... |
from evaluation.Nodes.Node import Node
from typing import List, Tuple
from datetime import timedelta, datetime
from base.Event import Event
from base.Formula import Formula, AtomicFormula, TrueFormula
from evaluation.PartialMatch import PartialMatch
from base.PatternStructure import SeqOperator, QItem
from misc.Utils i... |
from flask import Flask,render_template,jsonify,request
from werkzeug import secure_filename
from werkzeug.datastructures import ImmutableMultiDict
import base64
import re
import cv2
import numpy as np
app=Flask(__name__)
def convert_to_diff_text(text):
print(text)
converted_text = 'treek'
return converted_text
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
import getWidget
from drawPic import drawPic
from adbExtend import adbExtend
from deviceMonitor import AppPerformanceInfo
from bugDetect import BugDetect
import os, logging, coloredlogs
import time,threading
coloredlogs.install()
# view... |
#!/usr/bin/env python
'''
**********************************************************************
* Filename : camIncoming.py
* Description : receives the message for an image and processes it.
* Author : Joe Kocsis
* E-mail : Joe.Kocsis3@gmail.com
* Website : www.github.com/jkocsis3/tanis
************... |
from .models import StuData
from django import forms
class StuForm(forms.ModelForm):
class Meta:
model=StuData
fields=["name","score","type"]
def clean(self,*args,**kwargs):
data=self.cleaned_data
f=["name","score","type"]
for i in f:
var1=data.get(i,None)
... |
from distutils.core import setup
setup(
name='easygl',
version='0.1.0a1',
packages=['easygl', 'easygl.arrays', 'easygl.display', 'easygl.prefabs', 'easygl.shaders', 'easygl.textures',
'easygl.structures'],
url='https://github.com/overdev/easygl-0.1.0-alpha1',
license='MIT',
classi... |
import numpy as np
from rpy2.robjects import numpy2ri
numpy2ri.activate()
from rpy2.robjects.packages import importr
stats = importr('stats')
# x : np.ndarray
# ar_order : int
# ma_order : int
# diff_order : int
# -> (np.ndarray, np.ndarray, float, int)
def arima_r(x, ar_order, ma_order, diff_order):
fit = stats.ari... |
import sys
import os
import shutil
import random
import glob
sys.path.insert(0, 'scripts')
sys.path.insert(0, 'tools/families')
sys.path.insert(0, 'tools/database')
import experiments as exp
import fam
from find_diff_datasets_julia import get_diff_and_propmax
def get_ali_from_logs(logfile):
lines = open(logfile).r... |
#!/usr/bin/env python
import weather
from geopy.geocoders import Nominatim
import sys, getopt
import mytime
# User should be able to type:
# weather [weather for current date/location]
# weather on [date]
# weather in [location]
# weather [tomorrow]
# weather on [date] in [location]
# weather in [location... |
import numpy as np
from netCDF4 import Dataset, num2date # to work with NetCDF files
from os.path import expanduser
import matplotlib.pyplot as plt
home = expanduser("~") # Get users home directory
import statsmodels.api as sm
from scipy import stats
import xarray as xr
import pytz
import glob, os
import numpy as np
i... |
#!/usr/bin/python
"""
notifyMe: allows the user to execute a program
and when it ends show up a dialog with a title and message
in order to notify that it is ended.
"""
__author__ = "Alessandro Pischedda"
__email__ = "alessandro.pischedda@gmail.com"
import sys
from subprocess import call
def setup_pynotify():
... |
IMAGE_SIZE = 128
|
a=int(input())
n=list(map(int,input().split()))
for x in n:
if n.count(x)==1:
print(x)
break
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.