text stringlengths 38 1.54M |
|---|
import os
import logging
import re
import yaml
import series_handler
import shutil
from yaml_helper import yaml_get
logging.basicConfig(level=logging.INFO)
localPathRoot = "/Users/Andrew/Movies/TV Shows/"
remotePathRoot = "/Volumes/videos/"
validExtension = "mp4"
destFile = 'dest.yaml'
SERIES = series_handler.serie... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Written by Willy
import matplotlib.pyplot as plt
import torch
import numpy as np
from skimage import transform as sk_transform
from skimage import io, color
import os,cv2
import scipy.io as scio
def show(image,dots,sigma):
_dots = dots.astype(np.int)
plt.imshow(i... |
x = int(input("enter the number"))
y = int(input("enter the number"))
z = int(input("enter the number"))
if x>y and x>z:
print("x is the largest number")
elif y >x:
print("y is the largest number")
else:
print(" z is the largest number") |
from simtk import unit
from msmbuilder.cluster.kcenters import KCenters
import mdtraj as md
from simtk.openmm.app.pdbfile import PDBFile
from foldamers.utilities.iotools import write_pdbfile_without_topology
def concatenate_trajectories(pdb_file_list,combined_pdb_file="combined.pdb"):
"""
Given a list ... |
class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalCuts = sorted(horizontalCuts)
verticalCuts = sorted(verticalCuts)
max_w = max(horizontalCuts[0],h-horizontalCuts[-1])
for i in range(len(horizontalCuts)):
... |
from typing import List
# merge 2 sorted Arrays - LC:88
def merge(nums1: List[int], m: int, nums2: List[int], n: int) -> None:
# if no elements are present in nums2
if n == 0:
return
if m == 0 and n != 0:
# copy elements from n to m
for i in range(n):
... |
# Generated by Django 3.0.8 on 2020-08-02 20:57
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('first_youtube', '0002_auto_20200802_1959'),
]
operations = [
migrations.AddField(
model_name='comment',
... |
import re
import sys
from collections import Counter
# for debugging/testing
TEST = True
if TEST:
import pdb
# import primary class, AlignerRun
from alignerrun import AlignerRun
def create_aligner_runs(args):
"""
Create an aligner run.
"""
aligner_runs = dict()
param_spaces = Counter()
f... |
import numpy as np
import time
from copy import deepcopy
import optim
from rpr import func_val, grad, stoc_grad, batch_grad, grad_lipshitz, linearized_grad, SimpleDataset
# SGD
def sgd(w, X, y, Xt, yt, rng, param_dict, num_epochs, avg=True, verbose=True):
w_avg = deepcopy(w)
n = y.shape[0]
fac = 1.0 / n
... |
from kartverket_tide_api.parsers import AbstractResponseParser
from kartverket_tide_api.exceptions import CannotFindElementException, NoTideDataErrorException
from kartverket_tide_api.tideobjects import WaterLevel
class LocationDataParser(AbstractResponseParser):
def _parsing_logic(self) -> {}:
"""Parse t... |
from django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from department.models import Strazacy, Pojazdy, Uslugi, Sprzet, PrzegladSprzet, PrzegladPojazdy
class FirefighterUpdateForm(forms.ModelForm):
first_name = forms.CharField(required=True, max_le... |
import MySQLdb
file = open("competitions.html","w")
header = """
<!DOCTYPE html>
<html lang="en">
<head>
<title>Cubing Kerala</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/b... |
#!/usr/env/python
#//taken from https://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
import numpy as np
def normalize(v):
norm = np.linalg.norm(v)
if norm == 0:
return v
return v / norm
resolution = [80,50]
maxsteps = 32
max_dist = 10
gl_FragCoord = [300,300]
# main
right =... |
import os
import shutil
import xlrd
import xlwt
import re
from flask import (
Blueprint, flash, g, redirect, render_template, request, url_for, send_file
)
from werkzeug.exceptions import abort
import manager
from manager.auth import login_required
from manager.db import get_db
bp = Blueprint('info', __name__)
... |
import sys
sys.path.insert(0,'.')
import torch
import torch.nn as nn
from torch.autograd import Variable
from convert import mgn_res
from torchsummary import summary
if __name__=='__main__':
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
net = mgn_res.MGN().to(device)
print(net)... |
# coding:utf-8
class PositionMyCourse:
# 课程
foot_course = "com.ruicheng.teacher:id/foot_course"
# 我的课程
my_course = "com.ruicheng.teacher:id/rl_myCourse"
# 我的课程数量
my_course_num = "com.ruicheng.teacher:id/tv_num"
# 我的课程小箭头
imageUser = "com.ruicheng.teacher:id/imageUser"
# =============... |
# 服务端
import socket
from winsound import Beep # 声音提示
from os.path import exists
host = "192.168.0.42"
port = 80
print("\n" + "=" * 80 + "\n")
print("服务器开启……" , end = " " * 4)
Beep(660, 500)
socketObj = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # socket对象
socketObj.bind((host, por... |
# import OpenCV module
import cv2
import os
import numpy as np
# there is no label 0 in our training data so subject name for index/label 0 is empty
subjects = ["", "Frank Ridder", "Liza de Graaf", "Vincent Kenbeek", "Robin Vonk", "Jurriaan Mulder", "Martijn Bakker",
"Bo Sterenborg", "Robin de Jong", "Mari... |
#Find the maximum and minimum element in an array
#Without Inbuilt Functions
def findminmax(arr)
max = arr[0]
min = arr[0]
for i in arr
if i>max
max=i
if i<min
min=i
print(max)
print(min)
#Using Inbuilt Function
def findminmax1(arr)
print(max(arr))
... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
# This function shows an image using the matplotlib functionality
def show_with_matplotlib(color_img, title, pos):
# pos - position in the figure plot
# First convert the BGR image to RGB
rgb = color_img[:, :, ::-1] # all items in the array, re... |
#!/usr/bin/env python
"""
OPV GUI
Written by Soo Park 2016 for Shaheen Group @ CU Boulder
Contact: soo.park@colorado.edu
"""
import sys
from PyQt4 import QtGui, QtCore
import pyqtgraph_modified as pg
import pyqtgraph_modified.opengl as gl
import numpy as np
from matplotlib.cm import *
import itertools
import xyzViz... |
# author: UBC Master of Data Science - Group 33
# date: 2020-11-26
"""Pre-processing wine quality data for red wine(https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv) and
wine quality data for white wine(https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality... |
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#from scipy import stats
#import Tkinter as tk
#import tkFileDialog
try:
import Tkinter as tk
from tkFileDialog import askopenfilename
from tkFileDialog import asksaveasfilename
except ImportErr... |
# Programa para hacer una media entre tres números
# Autor: David Galván Fontalba
# Fecha: 10/10/2019
#
# Algoritmo
#
# Pido tres números a, b y c.
# Cálculo de la media
# Muestro el resultado
#
print("Bienvenidos a este programa que hará la media de tres números")
print("-----------------------------------------------... |
#!/usr/bin/env python3
# Copyright (c) 2019 Bitcoin Association
# Distributed under the Open BSV software license, see the accompanying file LICENSE.
"""
We will test the following situation where block 1 is the tip and three blocks
are sent for parallel validation:
1
/ | \
2 3 4
Blocks 2,4 are hard to valid... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'd:\FacepalmProject\Library\Addbook.ui',
# licensing of 'd:\FacepalmProject\Library\Addbook.ui' applies.
#
# Created: Fri Oct 11 12:35:46 2019
# by: pyside2-uic running on PySide2 5.13.1
#
# WARNING! All changes made in this file will b... |
# 很多时候,系统是否要引发异常,可能需要根据应用的业务需求来决定,如果程序中的数据、执行与既定的业务需求不符,这就是一种异常。由于与业务需求不符而产生的异常,必须由程序员来决定引发,
# 系统无法引发这种异常。
#
# 如果需要在程序中自行引发异常,则应使用 raise 语句,该语句的基本语法格式为:
#
# raise [exceptionName [(reason)]]
#
# 其中,用 [] 括起来的为可选参数,其作用是指定抛出的异常名称,以及异常信息的相关描述。如果可选参数全部省略,则 raise 会把当前错误原样抛出;如果仅省略 (reason),则在抛出异常时,将
# 不附带任何的异常描述信息。
#
# 也就是说,... |
import socket
import sys
socketa = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host_name = sys.argv[1]
host_ip = socket.gethostbyname(host_name)
port = int(sys.argv[2])
if(len(sys.argv)>3):
usrename = sys.argv[3]
def parse_send_message(mess):
if(mess[0]!="@"):
return (False, [])
message_list ... |
import pymongo
from pymongo_pubsub import Publisher
connection = pymongo.Connection()
database = connection.pubsub_db
publisher = Publisher(database, 'test_event')
publisher.push({'message': 'hello world', 'answer': 42}) |
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# 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 Licen... |
import json
class Decoder(json.JSONDecoder):
def decode(self, s):
result = super().decode(s) # result = super(Decoder, self).decode(s) for Python 2.x
return self._decode(result)
def _decode(self, o):
if isinstance(o, str):
try:
return int(o)
ex... |
import gc
import sys
import time
import itertools
__all__ = ['Timer', 'timeit', 'repeat', 'default_timer']
dummy_src_name = '<timeit-src>'
default_number = 1000000
default_repeat = 5
default_timer = time.perf_counter
_globals = globals
template = '\ndef inner(_it, _timer{init}):\n {setup}\n _t0 = _timer()\n fo... |
#!/usr/bin/env python
"""
_RuntimeOfflineDQM_
Harvester script for DQM Histograms.
Will do one/both of the following:
1. Copy the DQM Histogram file to the local SE, generating an LFN name for it
2. Post the DQM Histogram file to a Siteconf discovered DQM Server URL
"""
import os
import sys
import httplib
import url... |
from django.urls import path
from mainapp import views
app_name = "mainapp"
urlpatterns = [
path('', views.mainpage, name='mainpage'),
path('info/<slug:category>/', views.articles, name='articles'),
path('info/<slug:category>/<slug:article>', views.article_page, name='article_page'),
path('administrator/create_ar... |
convert = { 'pa':'1','re':'2',
'ci': '3', 'vo':'4',
'mu':'5', 'xa':'6',
'ze':'7','bi':'8',
'so':'9','no':'0'}
lojban = input()
decimal = ''
for i in range(0,len(lojban),2):
decimal += convert[lojban[i:i+2]]
print(decimal) |
#!/usr/bin/env python
"""Zabbix command ligne tools"""
# Usage: zbx.py
# Summary: Zabbix commands line interface
# Help: Commands for Zabbix
# Dude, Chick, Read the f****** README.md for dependancy and compliance !!
try:
import configparser
except ImportError:
import ConfigParser as configparser
# from bac... |
##################################################
# The Best Kaggle Team
# - Woojin Kim (wk2246)
# - Carlos Espino Garcia (ce2330)
# - Yijing Sun (ys2892)
##################################################
# Description: Stacking prediction model for the Machine Learning
# Kaggle competition. Please see the write-up... |
from selenium import webdriver
import time
#load driver
driver = webdriver.Chrome()
def isMessageExist():
# click Load Older Threads to load all messages..one simple click is enough it will load rest automatically
#uiMore = driver.find_element_by_link_text('Load Older Threads')
#uiMore.click()
els = ... |
# TestSoma
from operacoes_aritmeticas import soma
import unittest
class TestSoma(unittest.TestCase):
def test_soma_inteiros(self):
self.assertEqual(soma(1,2),3)
def test_soma_reais(self):
self.assertEqual(soma(10.5,2),12.5)
def test_soma_string(self):
self.assertEqual(soma('abc','def'),'abcdef')
if __name... |
# coding:utf-8
import tweepy
CONSUMER_KEY="カスタマーキー"
CONSUMER_SECRET="カスタマーキーシークレット"
auth=tweepy.OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)
ACCESS_TOKEN="アクセストークン"
ACCESS_SECRET="アクセストークンシークレット"
auth.set_access_token(ACCESS_TOKEN,ACCESS_SECRET)
api=tweepy.API(auth,wait_on_rate_limit=True)
#自動で上限に達すると待ってくれ... |
class Solution:
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if not numRows:
return []
# elif numRows == 1:
# return [[1]]
# elif numRows == 2:
# return [[1], [1, 1]]
# res = [[1],... |
n=int(input())
f1=0
f2=1
c=2
if n==1:
print(f1)
elif n==2:
print(f1,f2)
while c<n:
f=f1+f2
print(f)
f1,f2=f2,f
c+=1
|
'''
Message Parser (msg_parse.py)
This module serves to parse messages received
by the telescope control. It extractsm, at minimum,
the following data from the message:
1. The name of the function to perform
The data is stored in a list in the following
manner:
[name, ..., parameter, ...]
In oth... |
"""
Copyright 2020 Google LLC
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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, so... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
__author__ = 'ufian'
import config
import telepot
import time
import mongoengine as me
import datetime
from telepot.loop import MessageLoop
from telepot.delegate import per_chat_id, per_callback_query_chat_id, create_open, pave_event_sp... |
"""
@todo #169:30min Write test for creating and editing Table model. To test
it correctly it's needed to create relations like `TableShape` and so on
in tests. There is`factory-boy` library in requirements added. It helps
to create instance with its relations automatically, look at
`tests/factories.py` and see
ht... |
from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = "Reset all access attempts and lockouts for given usernames"
def add_arguments(self, parser):
parser.add_argument("username", nargs="+", type=str)
def handle(self, *args, **option... |
""" Quick test to see what using a 3-bit colour palette looks like.
"""
from PIL import Image
palette = (
(0, 0, 0),
(0, 0, 255),
(0, 255, 0),
(0, 255, 255),
(255, 0, 0),
(255, 0, 255),
(255, 255, 0),
(255, 255, 255)
)
if __nam... |
# search index of a number in a list
# x: target no to search
# arr: given list
# l: length of list
def binary_search(arr,l, x, start_index=0):
# check list is not empty
arr.sort()
while start_index <= l:
# calculate middle of list
mid = 1 + (l-1)//2
# if x ... |
import matplotlib as mpl
mpl.use('Agg')
import numpy as np
import pandas as pd
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import scipy as sp
from scipy.interpolate import griddata
import seaborn as sns
from scipy.stats import norm
from scipy.stats import uniform
from scipy.stats import multivar... |
# -*- coding: utf-8 -*-
import concierge.core.lexer
import concierge.core.parser
def process(content):
content = content.split("\n")
content = concierge.core.lexer.lex(content)
content = concierge.core.parser.parse(content)
content = generate(content)
content = "\n".join(content)
return con... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.http import HttpResponse
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('fabric.urls')),
(r'^admin/', include('smuggler.urls')... |
import numpy as np
import tensorflow as tf
import matplotlib
import matplotlib.pyplot as plt
from tensorflow.contrib.factorization.python.ops import kmeans
def input_fn_1D(input_1D_):
input_t = tf.convert_to_tensor(input_1D_, dtype=tf.float32)
input_t = tf.expand_dims(input_t, 1)
return(input_t, N... |
#-*- coding: utf-8 -*-
from zope.component import getUtility
from Products.Five.browser import BrowserView
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from Products.CMFCore.utils import getToolByName
from Products.statusmessages.interfaces import IStatusMessage
from plone.memoize.instance ... |
print('Hello Word!\nSegundo print com Quebra linha')
print('Hello Word!\tSegundo print com Tab\n')
print('#' * 3, 'Variáveis', '#' * 3)
nome = 'Sandro Lucas'
idade = 23
altura = 1.72
print('A variável NOME tem o valor de {} é do tipo {}'.format(nome, type(idade)))
print('A variável IDADE tem o valor de {} é do tipo... |
import socket, pickle, struct, cv2.cv2
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host_ip = '176.53.65.237' # server ip adresi
port = 9999 #baglanilacak port
client_socket.connect((host_ip, port))
data = b""
payload_size = struct.calcsize("Q")
while True:
while len(data) < payload_... |
import tensorflow as tf
# TODO: this seems to be broken, compared to the Colab version.
def MeanAbsoluteErrorLabels(y_true, y_pred):
# Assume that y_pred is cumulative logits from our CoralOrdinal layer.
# Predict the label as in Cao et al. - using cumulative probabilities
#cum_probs = tf.map_fn(tf.math.sigmo... |
# Django settings for development environment.
import os
import dj_database_url
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': dj_database_url.config(default='sqlite:///db.sqlite3')
}
# Hosts/domain names that are valid for th... |
from bs4 import BeautifulSoup
import sqlite3
import re
import os
import getdata
import create_visuals
# inserts each artist's name with their unique Spotify Artist ID into a table in the database
def setIdTable(data):
try:
conn = sqlite3.connect('artists_info.db')
cur = conn.cursor()
cur.ex... |
from LuyckxFeatures import *
import personae
import numpy as np
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import os
import timblClassification as timbl
from collections import Counter
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
## for Pala... |
# Generated by Django 3.0.4 on 2020-07-22 18:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0032_auto_20200722_1821'),
]
operations = [
migrations.AddField(
model_name='photo',
name='visible',
... |
import json
import requests
import urllib.request
from bs4 import BeautifulSoup
from os import path
def scrape_photos():
with open("venues.json") as f:
data = json.load(f)
for key in data:
get_photo(key)
def get_response(url, filename):
response = requests.get(url)
with open(filename,... |
import cv2
def video_2_frame(video_path):
cap = cv2.VideoCapture(video_path)
# CV_CAP_PROP_FPS == 5
fps = cap.get(5)
frames = []
has_frame, frame = cap.read()
while has_frame:
frames.append(frame)
has_frame, frame = cap.read()
return frames, fps
|
import numpy as np
# Constants
H = 0.001
t_max = 70
t_0 = 0
ALPHA = -1
BETA = 1
GAMMA = 0.25
OMEGA = 1.4
A = 0.2
# DuffingPotenital
def potential(x):
return ALPHA / 2 * x * x + BETA / 4 * x * x * x * x
# Gibt Array mit allen x und V(x) Werten des DuffingPotenitials aus
def init_Potential(x_min, x_max):
x =... |
# Copyright 2020 Declarative Systems Pty Ltd
#
# 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... |
import os
import re
import string
import unicodedata
import jieba
from zhon.hanzi import punctuation
class Word_Segment:
def __init__(self, path='./resources/stopwords.txt'):
# from nltk.corpus import stopwords
# stop_words = stopwords.words('english')
self.stop_words = self.result = [line.... |
from collections import defaultdict
# write function that finds the first repeated character in a string
# Return the character or None
# def find_first_repeated_char(string):
# for i in range(len(string)):
# for j in range(len(string)):
# if i != j and string[i] == string[j]:
# return string[i]
# else:
# ... |
#!/usr/bin/python
# -*- coding : utf-8 -*-
"""
Factory method is a design pattern. It is spposed to design an interface for creating an object, but let subclasses decide which class to instantiate. It lets a class defer instantiation to subclasses.
In this file displays a typical usage of factory method: connecting pa... |
# 获取虎牙直播的真实流媒体地址。
# 现在虎牙直播链接需要密钥和时间戳了
import requests
import re
import base64
import urllib.parse
import hashlib
import time
def live(e):
i, b = e.split('?')
r = i.split('/')
s = re.sub(r'.(flv|m3u8)', '', r[-1])
c = b.split('&', 3)
c = [i for i in c if i != '']
n = {i.split('=')[0]: i.split... |
import re
from abc import ABC, abstractmethod
class BasePhoneticsAlgorithm(ABC):
_vowels = ''
_reduce_regex = re.compile(r'(\w)(\1)+', re.I)
def _reduce_seq(self, seq):
return self._reduce_regex.sub(r'\1', seq)
@abstractmethod
def transform(self, word):
"""
Converts a gi... |
# -*- coding: utf-8 -*-
""" Job class for Cms module """
import Queue
class CmsJob(Queue.Queue):
""" Job class for Cms module """
def get(self, block=True, timeout=None):
""" Get next item from queue """
return Queue.Queue.get(self, False, None)
|
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 15 11:35:41 2019
@author: jorge Guizar alfaro
ETH zurich
"""
"""
This is the inversion of an horizontal thin sheet
"""
import numpy as np
import matplotlib.pyplot as plt
import random
from numpy.linalg import inv
#%matplotlib auto
########################... |
# 爬取豆瓣电影
import time
import requests
import json
from lxml import etree
def getPage(url):
'''请求页面数据'''
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'
}
# 发起请求
... |
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions impo... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-05 08:22
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('website', '0016_auto_20170527_1719'),
... |
from __future__ import unicode_literals
import ast
import os
import nose
from nose.plugins import Plugin
def _iteritems(env_variables_to_override):
try:
return env_variables_to_override.iteritems()
except AttributeError:
return env_variables_to_override.items()
class SetEnvironmentVariable... |
# INSTITUTO POLITÉNICO NACIONAL
#
# ESCOM
#
# Análisis de Algoritmos
#
# Benjamín Luna Benoso
#
# Práctica No. 5
#
# Strassen
#
# Blancas Pérez Bryan Israel
#
# 3CV1
import numpy as np
import random as r
from time import time
cont=0
def stressen(a,b,n):
global cont
c=np.zeros((n,n),dtype=... |
#!/usr/bin/python3
"""
Script that generates a .tgz archive from the contents of the web_static
folder of your AirBnB Clone repo, using the function do_pack.
"""
from datetime import datetime
from fabric.api import local
def do_pack():
"""Packs a local web_static folder to .tgz format for deployment"""
... |
#!/usr/bin/env python
# author: Pankaj Sharma
# 11/14/2018
import tensorflow as tf
import featurizer
import task
import metadata
# ****************************************************************************************
# YOU MAY MODIFY THESE FUNCTIONS TO USE DIFFERENT ESTIMATORS OR CONFIGURE THE CURRENT ONES
# **... |
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from ..models import Task
from ..serializers import TaskModelSerializer
class TaskModelViewSet(viewsets.ModelViewSet):
"""
Task Model View Set
"""
... |
#area of a polygon
def herons(x1,y1,x2,y2,x3,y3):
a = ((x2 - x1)**2 + (y2 - y1)**2)**(1/2)
b = ((x2 - x3)**2 + (y2 - y3)**2)**(1/2)
c = ((x1 - x3)**2 + (y1 - y3)**2)**(1/2)
s = (a+b+c)/2
area = (s*(s-a)*(s-b)*(s-c))**(1/2)
return (area)
def area_polygon(xvert,yvert):
xc = round(sum(xve... |
from AESCipher import AESCipher
#Turns strings into dictionaries
def parse_routine(str):
result = {}
for x in str.split("&"):
parts = x.split("=")
if len(parts) == 2:
result[parts[0]] = parts[1]
return result
#Turns dictionaries into strings
def parse_to_string(dct):
return "email=" + dct['email'] + "&uid=... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###########################################
# (c) 2016-2018 Polyvios Pratikakis
# polyvios@ics.forth.gr
###########################################
"""
Utility functions used by twAwler
"""
import sys
import os
import time
import json
import twitter
from datetime import d... |
import sys
import xpath_extract
import regex_extract
import wrapper
if __name__ == '__main__':
if len(sys.argv) > 1:
arg = sys.argv[1]
if arg == "A":
xpath_extract.run_all()
elif arg == "B":
regex_extract.run_all()
else:
wrapper.run()
else:
... |
'''
diag: Return the diagonal (or off-diagonal) elements of a square matrix as a 1D array, or convert a 1D array into a square
matrix with zeros on the off-diagonal
dot: Matrix multiplication
trace: Compute the sum of the diagonal elements
det: Compute the matrix determinant
eig: Compute the eigenvalues and eigenvector... |
"""Table formats for the database and website post forms"""
# Standard library.
from datetime import datetime
from random import randint
# Third party.
from flask_login import UserMixin
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField, \
TextAreaField
from ... |
def draw_diamond(n):
if n % 2 != 0:
k = 1
while k <= n:
print(" " * int((n - k) / 2) + "*" * k + " " * int((n - k) / 2))
k += 2
j = 1
while (n - 2 * j) >= 1:
print(" " * j + "*" * (n - 2 * j) + " " * (j))
j += 1
else:
print... |
import os
import sys
import math
import http.client
import urllib
import requests
import json
import hashlib
import sha3
import colorama
from colorama import Fore
import settings
from utils import make_dir, is_img
def create_image_path(dir_path, url):
if not is_img(url):
print(Fore.RED + "Inappropriate fi... |
number=input("Enter number to send: ")
num_copy=number
new_num=0
i=0
reverse=0
while num_copy>0:
digit=num_copy%10
new_num=((digit+7)%10)*(10**i)+ new_num
num_copy=num_copy/10
reverse=(reverse*10)+new_num/(10**i)
i=i+1
print "Encryption process:",number,"==>",new_num,"==>", reverse |
#!/usr/bin/env python3
import argparse
import logging
import sys
from sqlalchemy import func
from util.color_logger import get_logger
import util.datamodel as dm
from util.datamodel_helper import create_db_session, load_file_in_db
logger = get_logger('stats')
def log_general_stats(session):
logger.info("numb... |
a=[]
s=int(input())
for i in range(0,s):
i=input("Your Value:")
a.append(i)
a.sort()
print(min(a),max(a)) |
l, timeDiana, timeHumper, n, slowdown = map(int,raw_input().split())
timeDiana *= l
timeHumper *= l
aps = []
a = 0
for i in range(n):
line = raw_input().split()
aps.append(tuple(map(int,line)))
def convert_to_time(apple):
return (apple[0]*slowdown*(l-apple[1]))
aps = sorted(aps, lambda x,y: convert_to_time(x)-conv... |
# conda activate wk_ecmwf
# cd "C:\Users\fan\pyfan\vig\getdata\envir\ecmwf_scripts\"
# python ecmef_pressure_utci_historical.py
import cdsapi
import urllib.request
# download folder
spt_root = "C:/Users/fan/downloads/_data/"
spn_dl_test_grib = spt_root + "test_utci.zip"
# request
c = cdsapi.Client()
res = c.retrieve(... |
import sys
import hmac
import hashlib
from datetime import date
from flask import current_app, g
from onelist.apps.accounts.models import UserModel
class PasswordResetTokenGenerator(object):
def make_token(self, user):
"""Returns a token that can be used once to do a password reset for the
given u... |
import logging
import queue
from Shopware.Request import Request, ThreadedRequest
from Shopware.Tasks import APITask, ExitTask
class SimpleClient(Request):
"""Interface to a shopware shop's API
:param endpoint: Endpoint of your shopware API,
e.g. http://www.myshop/api
:param user: Your backend ... |
from sys import argv
script, text = argv
x = raw_input("how many books do you have")
print "how many books do I have:"
my_fictional = 90
print "I have %d fictional books" % my_fictional
my_nonfictional = 60
print "I have %d nonfictional books" % my_nonfictional
y = raw_input("what are your fictional groups")
print ... |
def lineCutting(lines, length, N):
cnt = 0
for line in lines:
cnt += line // length
return cnt
def binary(lines, N):
start, end = 1, max(lines)
while start <= end:
mid = (start + end) // 2
cnt = lineCutting(lines, mid, N)
if cnt >= N:
start = mid + 1
... |
import csv
from collections import OrderedDict
from dao.hashtag_dao import search_hashtag_by_id
from dao.tweet_dao import n_tweets_feeling
from dao.tweet_hash_dao import n_tweets_hash
def save_data(data):
with open('data.csv', 'w') as new_file:
fieldnames = ['Hashtag', 'Tweets', 'Positivo', 'Negativo', '... |
# coding: utf-8
# In[ ]:
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import roc_auc_score, roc_curve, auc, mean_squared_error
from itertools import combinations
def softmax(array):
exp = np.exp(array)... |
import pandas as pd
csv_path = './follows.csv'
def get_data(path=csv_path):
duwei = 0
dd = 0
close = 0
follows = pd.read_csv(path)
list = follows.values.tolist()
for peo in list:
if peo[5] == 0:
close = close + 1
else:
sum = 0
for i in range(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.