text stringlengths 8 6.05M |
|---|
from __future__ import annotations
from datetime import datetime
import json
from pathlib import Path
import secrets
import subprocess
import sys
from typing import IO, Literal, Sequence
import uuid
import click
from humanize import naturalsize
from tabulate import tabulate
from .main import main
from .pretty import... |
# Generated by Django 2.1.2 on 2018-12-23 16:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('systemoptions', '0008_auto_20181223_1630'),
]
operations = [
migrations.AlterField(
model_name='emailwebservice',
na... |
class First:
def __init__(self,a,b):
self.a = a
self.b = b
print("iam constructor")
def sum(self):
res=self.a+self.b
print(res)
'''def __str__(self):
print("a="+str(self.a)+"b="+str(self.b))'''
def __del__(self):
print("iam destructor")
... |
import unittest2
from Trees.bst import BinarySearchTree, Node
"""
Test for binary search tree
"""
class BstTestClass(unittest2.TestCase):
def setUp(self):
self.tree = BinarySearchTree()
def testInsert(self):
node = Node()
node.key = 10
node.value = "tor"
self.tree.insert(node)
result = self.tree.search... |
# Generated by Django 3.2.7 on 2021-09-07 03:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
... |
from fastapi import FastAPI
from calc import Calc
app = FastAPI()
calc = Calc()
@app.get("/")
def read_root():
return {"Nombre": "ELADIO JUNIOR RODRIGUEZ RODRIGUEZ", "Matricula": "1085776"}
@app.get("/sumar")
def read_sumar(num1: int = 0, num2: int = 0):
return {
"total": calc.sumar(num1, num2)
... |
"""
Constants of services that can be discovered.
"""
BELKIN_WEMO = "belkin_wemo"
DLNA = "DLNA"
GOOGLE_CAST = "google_cast"
PHILIPS_HUE = "philips_hue"
PMS = 'plex_mediaserver'
NETGEAR_ROUTER = "netgear_router"
SONOS = "sonos"
|
import pandas as pd
import numpy as np
import os
import webbrowser
# Read the dataset into a data table using Pandas
df = pd.read_csv("ratings.csv", dtype={'userId': np.int32, 'movieId': np.int32, 'rating': np.uint8})
# Convert the running list of user ratings into a matrix using the 'pivot table' function
ratings_df... |
import unittest
from katas.kyu_7.simple_template import create_template
class TemplateTestCase(unittest.TestCase):
def setUp(self):
self.template = create_template('{{name}} likes {{animalType}}')
self.template2 = create_template('{{first}} {{last}}')
def test_equals(self):
self.asse... |
from enum import Enum, unique
import subprocess
import platform
import sys
import restic.parser
from restic.core import version
from restic.config import restic_bin
from restic.snapshot import Snapshot
from restic.key import Key
@unique
class RepoKind(Enum):
Local = 0
SFTP = 1
REST = 2
S3 = 3
Swi... |
#-*-coding:utf-8-*-
#__author__='maxiaohui'
import subprocess
import time,random,os
import datetime
from config import config
fail_date=datetime.date.today().strftime('%m%d')
fail_time=time.strftime('%H%M%S')
timeTag=fail_date+fail_time
def getLogcat(deviceID=config.deviceId,deviceName='',keyword=''):
filename =... |
#!/usr/bin/env python3
"""
desc: demonstration of write functions for chunks with sample scraped data
"""
from chunk import Chunk
if __name__ == '__main__':
link_0 = "http://samplelink00.com"
title_0 = "Hello 0"
html_0 = "<html>" \
"<body><h1>Enter the main heading, usually the same as the... |
import unittest
from katas.kyu_7.sum_factorial import sum_factorial
class SumFactorialTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(sum_factorial([4, 6]), 744)
def test_equals_2(self):
self.assertEqual(sum_factorial([5, 4, 1]), 145)
|
import PySimpleGUI as sg
import pyaudio
import numpy as np
"""PyAudio PySimpleGUI Blocking Stream for Microphone"""
# VARS CONSTS:
# We hold a reference to the PySimpleGUI window
# so we can update it later.
_VARS = {'window': False}
# pysimpleGUI INIT:
AppFont = 'Any 16'
sg.theme('DarkTeal3')
layout = [[sg.Progr... |
first_name = ["John","Jason","Gerry","Mark"]
last_name = ["Snow", "White","Henry","Waugh"]
name_generated = []
for first in first_name:
for last in last_name:
name = first + " " + last
name_generated.append(name)
print(name)
print(name_generated) |
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
i, j = 0, 0
while i < len(nums1) an... |
BITS = 16 # format 2's complement binary
def to_bin_str(n):
s = bin(n & int("1" * BITS, 2))[2:]
return ("{0:0>%s}" % BITS).format(s)
|
from django.shortcuts import render, redirect
from plotly.offline import plot
import plotly.graph_objects as go
from django.contrib import messages
# Create your views here.
def home(request):
def scatter():
#x1 = [1,2,3,4]
#y1 = [30, 35, 25, 45]
import pymongo
from pymongo import ... |
import sys
if len(sys.argv) < 2:
print 'Usage: python %s filename' % sys.argv[0]
sys.exit(0)
with open(sys.argv[1], 'rb') as f:
shellcode = ''
for line in f:
for c in line:
shellcode += '\\x' + c.encode('hex')
print shellcode
|
"""
This program is for building a twitter bot . Which can retweet and fav the tweets about COVID meds and essential items.
"""
# Import the necessary modules...
import tweepy
import time
import logging
from random import choice, randint
import sqlite3
import glob
import c
# For logging informations
logging.basicConfi... |
#!/usr/bin/env python
import wx
import .diffpads_dialog
class DiffPadsApp(wx.App):
def __init__(self, board):
self.board = board
super(DiffPadsApp, self).__init__()
def OnInit(self):
diffpads_dialog.init_diffpads_dialog(self.board)
return True
|
import aiofiles
from aiofiles import os as async_os
from sanic import Sanic, response
from sanic.response import file_stream
app = Sanic(__name__)
@app.post('/upload')
async def ProcessUpload(request):
item = request.files.get("file")
print("name: ", item.name)
print("type: ", item.type)
async with a... |
# coding: utf-8
import os
# SlackのAPIを利用するためのトークン
# Botの設定ページから「OAuth & Permissions」のページに遷移し、
# 「Bot User OAuth Access Token」をコピーして貼り付ける
API_TOKEN = os.environ["SLACK_API_TOKEN"]
# 対応するメッセージがなかった場合に反応するメッセージ
DEFAULT_REPLY = "I dont't understand you."
# Botが実行するスクリプトを配置するディレクトリパスのリスト
PLUGINS = ['plugins'] |
#!/usr/bin/env python
# -*- coding::utf-8 -*-
# Author :GG
# 给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。
#
# 不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。
#
# 元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
#
#
#
# 示例 1:
#
# 给定 nums = [3,2,2,3], val = 3,
#
# 函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。
#
# 你不需要考虑数组中超出新长度后面的元素。
#
#... |
import os,sys
from numpy import median
from ..FeatureExtractor import FeatureExtractor, InterExtractor
sys.path.append(os.path.abspath(os.environ.get("TCP_DIR")+'/Algorithms'))
from qso_fit import qso_fit
#class qso_extractor(FeatureExtractor): # Using this will add a 'qso' feature in vosource xml whose value is a ... |
from matplotlib import pyplot as plt
jobs = [25,34,43,23,46,13,24,34,45,29]
aht = [15,12,23,8,17,14,7,10,14,12]
plt.plot(jobs, aht)
plt.title("Production")
plt.xlabel("Jobs-Completed")
plt.ylabel("Average-Handling-Time")
plt.show()
#py_dev_x = [10,20,30,40,50,60,70]
#py_dev_y = [12345,14541,14145,98758,74571,115... |
# 7-1 A function that determines whether an input string is in the format
# filename.ext. Returns True if so, and False if not.
def check_filename(string):
if string[-4] != '.':
return False
else:
fname, ext = string.split('.')
if len(ext) != 3:
return False
else:
... |
# -*- coding:utf8 -*-
from lxml import etree
import requests
url = "https://www.appannie.com/apps/ios/app/idle-heroes/reviews/?order_by=date&order_type=desc&date=2019-04-29~2019-05-29&translate_selected=false&granularity=weekly&stack&percent=false&series=rating_star_1,rating_star_2,rating_star_3,rating_star_4,rating_... |
#! /usr/bin/python3
from lyrics import *
if __name__ == "__main__":
running = True
while running:
searched_song = input(">> Enter a song name : ")
if searched_song == "" or searched_song is None:
print("Error : You must enter string ..")
continue
searched_song ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
delete_location_type_element_query = """
UPDATE public.location_type AS ltp SET deleted = TRUE,
active = FALSE WHERE ltp.id = $1::BIGINT RETURNING *;
"""
|
import numpy as np
def testData():
otest = open('test.txt', 'r')
test = otest.readlines()
oanswer = open('answer.txt', 'r')
answer = oanswer.readline()
status = False
print("Runs test data")
result = runCode(test)
if result == int(answer): #not always int
status = True
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Architecture',
fields=[
('id', models.AutoField... |
# -*- coding: utf-8 -*-
# metodIsmi(veri)
# alanHesapla(genislik, yukseklik)
genislik = float(input('Genişlik?\n'))
yukseklik = float(input('Yükseklik?\n'))
alan = genislik * yukseklik
print("Girdiğiniz genişlik " + str(genislik) + " metredir.\n")
print("Girdiğiniz yükseklik " + str(yukseklik) + " metredir.\n")
prin... |
# Classify data using a basic TF model
print("CLASSIFYING...")
import tensorflow as tf
from tensorflow import keras
# Build the Model
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
... |
import numpy as np
from matplotlib import pyplot as plt
#from Ground_Function_File import Ground_Function
"""
This is a simulation of a six wheel rover diluted to a 2D model with inaccurate values.
"""
__author__="David Canosa Ybarra"
def Ground_Function(z):
if z<2:
x=0
elif z>=2:
x=0.05*(np.co... |
def pinta_ala(pituus, leveys = None):
if leveys == None:
pinta_ala =(pituus ** 2)
return pinta_ala
else:
ala = pituus * leveys
return ala
def main():
print("Neliön pinta-ala on {:.1f}".format(pinta_ala(3)))
print("Suorakaiteen pinta-ala on {:.1f}".format(pinta_ala(4,3)))... |
import sys
import gym
import os
import tensorflow as tf
os.sys.path.insert(0, os.path.abspath('../../../settings_folder'))
import settings
import msgs
from gym_airsim.envs.airlearningclient import *
import callbacks
from multi_modal_policy import MultiInputPolicy
from stable_baselines.common.policies import MlpPolicy
... |
# created by Ryan Spies
# 2/19/2015
# Python 2.7
# Description: parse through a summary file of NHDS site info obtained from website
# and split out individual cardfiles for each site. Also creates a summary csv file
# with calculated valid data points and percent of total. Used to display in arcmap
import os
import ... |
import math
REFERENCE_TEXTS = []
def clean_tokenize_corpus(texts: list) -> list:
test_objects = "qwertyuioplkjhgfdsazxcvbnm "
corpus = []
if isinstance(texts, list) and texts != []:
for text in texts:
if isinstance(text, str) and text != []:
text_clean = ''
... |
import inspect
def get_props(c, filter_values = []):
props = {}
query_key = None
for (k, v) in c.__dict__.items():
if k == 'key':
query_key = v
if k[:2] != '__' and not inspect.isroutine(v) and k not in filter_values:
props[k] = c.__dict__[k]
return (query_key... |
from .base import BaseEventTestCase
class QueryEventTestCase(BaseEventTestCase):
"""
Test queries on events endpoint
"""
def test_query_deactivated_event(self):
query = """
query {
eventsList {
edges {
node {
id
... |
# coding: utf-8
#same as achybg.py, but if stopped before, can restart from the output files
#of the analytic contiunation.
import numpy as np
from mea import acon
from mea.model import green
import shutil
from mea.tools import kramerskronig as kk
from copy import deepcopy
import json
from scipy import linalg
t=1.0... |
from django import forms
# Models
from service.models import Category, Service, Comment, Contractor, Rating, CommentContract
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['text']
widgets = {'text': forms.Textarea(attrs={'rows': 1, 'cols': 50})}
class Serv... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 14 21:59:46 2020
@author: thomas
"""
import numpy as np
import pandas as pd
import os, sys
import time as t
import subprocess
from shutil import copyfile
#CONSTANTS
cwd_PYTHON = os.getcwd() + '/'
# constructs a filepath for the pos data of Re = $... |
# @author: Bogdan Hlevca 2012
''' x = gaussElimin(a,b).
Solves [a]{b} = {x} by Gauss elimination.
'''
from numpy import dot
def gaussElimin(a, b):
n = len(b)
# Elimination phase
for k in range(0, n - 1):
for i in range(k + 1, n):
if a[i, k] != 0.0:
lam = a [i, k] / ... |
import requests
import lxml.html as lh
from bs4 import BeautifulSoup
import pandas as pd
import openpyxl
import time
from others import create_excel_file, print_df_to_excel
workingpapers = []
workingpapersauthors = []
articles = []
articlesauthors = []
URL = 'https://ideas.repec.org/f/pba300.html'
#Create a handle, pa... |
class RandomizedSet:
def __init__(self):
self.nums = []
self.indices = {}
def insert(self, val: int) -> bool:
if val in self.indices:
return False
self.indices[val] = len(self.nums)
self.nums.append(val)
return True
# 思路是将最后一个元素与被删的元素调换位置
# 然... |
# Generated by Django 3.1.3 on 2020-11-16 00:26
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),
('rest_api', '0005_auto_20... |
# coding=utf-8
# @Author: wjn
import requests
import random
import time
class TYRequest():
def getInterfaceRes_no_token(self, url, body):
'''
发送post请求,没有前置cookie登录的需要。
目前只支持post登录,后续优化加入get功能,把method作为入参传进方法。
:return: 返回Response对象,例如:ret.status_code,ret.json()
'''
... |
def star(pa):
for i in range(pa):
print("*"*pa)
print("*"+(pa-2)*" "+"*")
print("*"+(pa-2)*" "+"*")
print("*"*pa)
star(5)
print("update") |
# Generated by Django 3.2.5 on 2021-07-31 05:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('master_file', '0016_product_category'),
]
operations = [
migrations.AlterModelOptions(
name='category',
options={'or... |
# coding: utf-8
# iprPy imports
from .ElasticConstantsStatic import ElasticConstantsStatic
__all__ = ['ElasticConstantsStatic']
|
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/jyk/stomp_ws/src/4.1/src/ur5_demo_descartes/include".split(';') if "/home/jyk/stomp_ws/src/4.1/src/ur5_demo_descartes/include" != "" else []
PROJECT_CATKIN_DEPENDS = "moveit_core;descartes_moveit... |
def to_base(integer, base_list=None):
"""
Convert an integer to an arbitrarily-represented arbitrary-base number
system.
The base representation must be defined in the `base list` parameter.
The base is taken from the length of the list.
:param integer: Base 10 int()
:type integer: int()
... |
class DigiMap(object):
def __init__(self):
self.map = {
'koromon home': {
'pos': (0, 0, 600, 600),
'color': 'red',
'constraint': None
},
'tanemon home': {
'pos': (0, 0, 600, 600),
'color': 'bl... |
import os
import sqlalchemy
import string
import oauth2client
import httplib2
from flask import Flask, render_template, request, redirect, url_for, flash, send_from_directory
from datetime import datetime
import sys
import json
import requests
import codecs
from datetime import datetime
from datetime impo... |
#!/usr/bin/env python
import gzip
import FileUtilities as fu
ACCEPTED_CHR = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20","21","22", "X", "Y", "MT"]
def count_alt(strng):
strng = strng.upper()
lst = list(strng)
a=0
c=0
t=0
g=0
... |
# pylint: disable=invalid-name,too-few-public-methods
'''
Module contains classes relevant to plotting maps. The Map class handles all the
functionality related to a Basemap, and adding airports to a blank map. The
DataMap class takes as input a Map object and a DataHandler object (e.g.,
UPPData object) and creates a ... |
def foo (stopwords=None):
with open('stopwords.txt') as s:
lines = s.readlines()
print(lines)
foo(stopwords=None) |
import discord
from random import shuffle
import re
import emoji
import sys
import json
import string
from copy import deepcopy
from datetime import datetime
token = ""
client = discord.Client()
@client.event
async def on_message(message):
if message.content != "hi": return
await message.channel.send(file=dis... |
from django.conf.urls import patterns, url
from fashion import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^load_lattes/$', views.load_lattes, name='load_lattes'),
url(r'^researcher/$', views.researcher, name='researcher'),) |
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from projects.models import Project, Person
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.auth.models import User
from projects.forms import NameForm
fr... |
#Logan Wang 51603232
'''
* Project#3 Try Not to Breathe
* ICS 32A
* 11/13/20
* Handles search and reverse searching with Nominatim API
* @author Logan Wang
'''
import urllib.request
import urllib.parse
import json
import math
import time
class NominatimAPIHandler:
def __init__(self, query_string: str):
... |
from browser import document, ajax
import json
def get_input_data():
age = document['age'].value
gender = 0
race = document['race'].value
height = document['height'].value
weight = document['weight'].value
pulse = document['pulse'].value
heaviest = document['heaviest'].value
smoke = document['smoke'].v... |
from django.contrib.auth.models import PermissionsMixin
from django.utils.translation import templatize
from django.views.generic import TemplateView
from django.http import HttpResponse
from django import http
from django.shortcuts import render
from rest_framework import viewsets,permissions
from .models import Produ... |
# @see https://adventofcode.com/2015/day/13
import re
from itertools import permutations
def parse_line(s: str):
r = re.match(r'([A-Z][a-z]+) would (gain|lose) ([\d]+) happiness units by sitting next to ([A-Z][a-z]+).', s.strip())
# Parse happiness change...
h = int(r[3]) if 'gain' == r[2] else int(r[3]) * -1... |
#!/usr/bin/python
# Copyright 2014 Google.
#
# 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... |
def sieve(N):
s = [0,0,1]+[1,0]*(N/2)
i = 3
while i*i < N:
if s[i]:
for itr in xrange(i*2,N,i):
s[itr] = 0
i += 2
return [i for i in range(N) if s[i]==1]
def palidrome(n):
s = str(n)
l = len(s)
for i in xrange(0,l/2):
if s[i] != s[l-1]:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 27 16:11:12 2020
@author: adeela
"""
'''
BFS(G, s)
for each v ∈ G: color[v] = WHITE; d[v] = ∞ color[s] ← GRAY; d[s] ← 0
Q←∅
ENQUEUE(Q, s)
while Q ≠ ∅
u ← DEQUEUE(Q)
for each v ∈ Adj[u]
if color[v] = WHITE then color[v] ← GRAY d[v] ← d[u] + 1
ENQUE... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('games', '0008_auto_20141108_1436'),
]
operations = [
migrations.AddField(
model_name='game',
name='s... |
import requests
from lxml import etree
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
'Referer': 'http://i.jzj9999.com/quoteh5/',
}
url = 'http://i.jzj9999.com/quoteh5/'
session = requests.Session()
s = session.get(ur... |
inputX = input("x = ?")
inputY = input("y = ?")
x = float(inputX)
y = float(inputY)
a = "PはR1とR2の両方の円の内側にある。"
b = "PはR1の内側にある。"
c = "PはR2の内側にある。"
d = "PはR1の内側でもなく、R2の内側でもない。"
if x**2 + y**2 < 10**2 and (x-10)**2 + y**2 < 10**2:
print(a)
elif x**2 + y**2 < 10**2:
print(b)
elif (x-10)**2 + y**2 < 10**2:
prin... |
from socket import *
import asyncio
import pickle
all_connections = []
all_addresses = []
async def echo_server(address, loop):
sock = socket(AF_INET, SOCK_STREAM)
sock.bind(address)
sock.listen(1)
sock.setblocking(False)
for c in all_connections:
c.close()
del all_connec... |
from flask import Flask
from flask_restful import Api
from resources.users import UsersList, Me
from resources.properties import PropertiesList, PropertyResource
app = Flask(__name__)
app.debug = True
api = Api(app, catch_all_404s=True)
api.add_resource(UsersList, '/landlords', endpoint='landlords', resource_class_kw... |
from .Action import Action
# A group of actions that are performed/reversed together, treated as a single action.
class ActionGroup(Action):
def __init__(self, actions):
Action.__init__(self)
self.actions = actions
def add(self, action):
if action not in self.actions:
self... |
"""
Student: Karina Jonina - 10543032
Module: B8IT110
Module Name: HDIP PROJECT
Project Objective: Time Series Forecasting of Cryptocurrency
Task: Scraping Yahoo Finance so that the user can select the crypto currency
based on Market Cap
"""
#importing important packages
import re
i... |
import socket
import sys
import select
import subprocess
import argparse
import time
import re, uuid
parser = argparse.ArgumentParser(description='Display WLAN signal strength.')
parser.add_argument(dest='interface', nargs='?', default='wlan0',
help='wlan interface (default: wlan0)')
args = pars... |
from django.db import models
from loginsignup.models import Beaver
# Create your models here.
class Post(models.Model):
post_creator = models.ForeignKey(
Beaver,
related_name="posts",
related_query_name="post",
on_delete=models.CASCADE,
)
posted_on = models.DateField(auto_... |
from django.shortcuts import render
from Segment.models import forecastol_img
from django.http import HttpResponse
import MySQLdb
import collections
import json
from PIL import Image
from Segment.leaf_predict import predict, count, count2
import os
import base64
import cv2
def get_data(sql):
conn = MySQLdb.connec... |
import tkinter as tk
import threading
from functools import partial
from app_sub1.service_Student_Member import StudentMember
import time
def remove_ent(app):
app.entry1.delete(0, 'end')
app.entry2.delete(0, 'end')
app.entry3.delete(0, 'end')
app.entry4.delete(0, 'end')
def btn1_clicked(app,service,... |
from datetime import datetime
import logging
import requests
import tweepy
from secrets import A_TOKEN, A_TOKEN_SECRET, C_KEY, C_SECRET
logging.basicConfig(
filename='sun_will_rise.log',
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=log... |
# Generated by Django 2.1.5 on 2019-10-14 12:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Product', '0002_auto_20191014_1045'),
]
operations = [
migrations.AddField(
model_name='category',
name='parent',
... |
import os
import time
STORAGE_ROOT = '/mnt/usb-sd'
def filename(capture_time):
name = capture_time.isoformat().replace(':', '_')
return f'{name}.jpg'
def image_path(folder, capture_time):
base_path = os.path.join(STORAGE_ROOT, folder)
os.makedirs(base_path, exist_ok=True)
return os.path.join(ba... |
import sys
import urllib2
import urllib
def Aggregation_Transit_Centralized(conf,inputs,outputs):
start_point = inputs["StartPoint"]["value"]
walkshed_collection = inputs["WalkshedCollection"]["value"]
walkshed_union = inputs["WalkshedUnion"]["value"]
poi = inputs["POI"]["value"]
crime = inputs["Crime"]["value"]... |
import torch
class CNN(torch.nn.Module):
def __init__(self):
super(CNN, self).__init__()
def forward(self, x):
batch_size = x.shape[0]
conv = self._model_conv(x)
linear_in = conv.view(batch_size, -1)
linear_out = self._model_linear(linear_in)
output = self._... |
from vcenter_connect import update_virtual_disk_capacity, get_all_disknumbers
virtualmachine_name = 'Nexii2' #raw_input("enter virtual machine name:")
all_disks_numbers = get_all_disknumbers(virtualmachine_name)
print "All disks number avaliable:"
print ",".join(map(str,all_disks_numbers))
selected_disk_number = int(r... |
import tweepy
import pymysql
import dotenv
import logging
import json
import string
import os
import time
from config import create_api
from misinformation_model import calculate_validity_score
logging.basicConfig(filename='app.log', filemode='w',
format='%(name)s - %(levelname)s - %(message)s')
#... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from models.reg import Registry
from models.permissions import Role
from storage.impl.deserialize import Deserializer
from storage.schema.deserialize import SchemaDeserializer
from pprint import pprint
import json
if __name__ == '__main__':
impl_reg = Registry()
... |
import numpy as np
import pandas as pd
from pandas import DataFrame
from sqlalchemy import create_engine
f = open("D:\\python_code\\sample\\猫眼\\movieComments.csv",'rb')
data = pd.read_csv(f, names = ['id', 'city', 'comment', 'ranking', 'time'])
df = data.drop_duplicates() # 去掉重复行
df1 = df.dropna(how = 'any', inplace = ... |
import os
import sys
import unittest
import pytorch_lightning as pl
import pytorch_lightning.loggers
from deep_depth_transfer import DepthNetResNet
from deep_depth_transfer.data import TumValidationDataModuleFactory
from deep_depth_transfer.models import DepthEvaluationModel
from deep_depth_transfer.utils import Dept... |
from .factory import create
|
#!/usr/bin/python
import sys
import os
import struct
if len(sys.argv) != 2:
print "Usage: " + sys.argv[0] + " filename"
sys.exit(1)
filename = sys.argv[1]
filesize = os.stat(filename).st_size
#tty = open("/dev/ttyS0", "w")
tty = open("/dev/ttyUSB0", "w")
f = open(filename)
# call 'load' command
tty.write("L")
# ... |
#!/usr/bin/env python
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that rules which use built dependencies work correctly.
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('use-built-... |
# coding: utf-8
from nltk.corpus import brown
brown.categories()
print("Numero de categorias ",len(brown.categories()))
print("Numero de archivos ",len(brown.fileids()))
print("Numero de caracteres en cr09 ",len(brown.raw(fileids=['cr09'])))
print("Numero de palabras en cr09 ",len(brown.words(fileids=['cr09'])))
print(... |
# Напишите reducer, который объединяет элементы из множества A и B. На вход в reducer приходят пары key / value, где key - элемент множества, value - маркер множества (A или B)
# Sample Input:
# 1 A
# 2 A
# 2 B
# 3 B
# Sample Output:
# 1
# 2
# 3
import sys
prev = ''
for line in sys.stdin:
key, value ... |
import weakref
def doStuff():
def meth():
pass
wr = weakref.ref(meth)
return wr
def recurse(f, n):
if n:
return recurse(f, n-1)
return f()
w = recurse(doStuff, 100)
# Try creating a large object to make sure we can handle them:
def f():
class C(object):
# Adding a __slots__ d... |
def strik(lista,x):
i = 0
j = x
soma = 0
while i < 3:
soma = soma +lista[j]
i += 1
j += 1
return soma
#---------------------------------------
def spare(lista,x):
i = 0
j = x
soma = 0
while i <= 2:
soma = soma +lista[j]
i += 1... |
from __future__ import print_function
import sys
import cplex
from cplex.callbacks import UserCutCallback, LazyConstraintCallback
import numpy as np
def powerset(A):
if A == []:
return [[]]
a = A[0]
incomplete_pset = powerset(A[1:])
rest = []
for set in incomplete_pset:
res... |
import json
import logging
import sys
from io import BytesIO
from os import chdir, environ, path, remove
from pathlib import Path
from socket import gethostname
from subprocess import check_output, CalledProcessError, STDOUT
from time import strftime, time
from traceback import format_exc
import graphyte
from geoip im... |
import numpy as np
# for reproducibility
np.random.seed(1337)
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import RMSprop
"""
在回归网络(regressor_example)中用到的是 model.add 一层一层添加神经层,这里的方法是直接在模型的里面加多个... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.