text stringlengths 38 1.54M |
|---|
import time
from robot.api import logger
from collections import OrderedDict
class UIPerformanceTimer:
"""
UIPerformanceTimer
Purpose:
Track the UI Performance from multiple internal performance counters.
"""
def __init__(self):
self.ajax_wait = 0.0
self.navigationStart = 0.0
... |
from accounts.models import OneManagerUser as User, OneManagerUserProfile as UserProfile,\
OneManagerUserContact as UserContact
from rest_framework.serializers import ModelSerializer
class UserProfileSerializer(ModelSerializer):
class Meta:
model = UserProfile
class UserContactSerializer(ModelSerial... |
from eclcli.common import command
from eclcli.common import utils
from ..networkclient.common import utils as to_obj
class ListInternetGateway(command.Lister):
def get_parser(self, prog_name):
parser = super(ListInternetGateway, self).get_parser(prog_name)
parser.add_argument(
'--name... |
import numpy as np
from scipy.spatial.distance import pdist, squareform
from fastcluster import linkage
from itertools import product
import warnings
def seriation(Z, N, cur_index):
'''
input:
- Z is a hierarchical tree (dendrogram)
- N is the number of points given to the clusterin... |
from merge_k_sorted_lists.divide_and_conquer import ListNode, merge_k_lists
def list_to_ListNode(l):
next = None
for li in reversed(l):
next = ListNode(li, next=next)
return next
def ListNode_to_list(ln):
l = []
while ln:
l.append(ln.val)
ln = ln.next
return l
def t... |
from base import GoogleJamBaseClass
class D(GoogleJamBaseClass):
def read_case(self, input_file):
line = input_file.readline().strip()
length, complexity, positions = line.split(' ')
return int(length)
def solve(self, case):
positions = range(1, case + 1)
re... |
# 输入某年某月某日,判断这一天是这一年的第几天?
# 30day 4 6 9 11
# 28/29day 2
# 31day 1 3 5 7 8 10 12
month_s = [4, 6, 9, 11]
month_m = [2]
month_b = [1, 3, 5, 7, 8, 10, 12]
# 防止用户输入错误的值进行计算 比如 2/30 3/32 4/31
year = 0
month = 0
day = 0
calculateDay = 0
def my_get_year():
global year
year = int(input("please inpu... |
import pickle
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import tools
pathcore = 'D:\studia\II stopień\Praca Magisterska\wyniki\\'
folders = ['raw_map', 'averaging_filter_3-3', 'averaging_filter_5-5', 'gaussian_filter_k3', 'gaussian_filter_k5', 'gaussian_filter_k7', 'median_... |
class User:
"""
A class used to hold a User from the OSRM request.
User describes the user who added the charger or media.
"""
def __init__(self, ID, profileImageURL=None, reputationPoints=None, username=None):
self.ID=ID
self.ProfileImageURL=profileImageURL
self.... |
import nibabel as nib
import os
import numpy as np
import matplotlib.pyplot as plt
#=========================generate the npz data=================================
# data path
#low_path = r"D:\python\DPED-master\niidata\head_wire_dataset\raw_data\2nd\train\low"
#high_path = r"D:\python\DPED-master\niidata\head... |
from django.conf.urls import url
from .import views
urlpatterns = [
url(r'^daftar_siswa/$', views.daftar_siswa),
] |
import math
def next_move(posr, posc, board):
(posr_dirty, posc_dirty) = closest_dirty(posr, posc, board)
if posr_dirty == 15:
print "END"
elif(posr_dirty == posr and posc_dirty == posc):
print "CLEAN"
elif(posr_dirty < posr):
print "UP"
elif(posr_dirty > posr):
print "DOWN"
elif(posc_dirt... |
from torch import nn
class my_model(nn.Module):
def __init__(self, n_in=12, n_hid=6, n_out=1):
super(my_model, self).__init__()
self.n_in = n_in
self.n_hid = n_hid
self.n_out = n_out
# self.fc1=nn.Linear(n_in,n_hid)
self.linearlinear = nn.Sequential(
n... |
from django.views.generic import View
from django.views.decorators.cache import never_cache
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from gbe.models import StyleVersion
from gbe.functions import validate_perms
cl... |
import FWCore.ParameterSet.Config as cms
import GenNtuplizer.DibosonGenAnalyzer.ComLineArgs as ComLineArgs
options = ComLineArgs.getArgs()
genJetsLabel = "slimmedGenJets" if (options.isMiniAOD and not options.redoJets) else \
"ak4GenJetsNoNu" if not options.is8TeV else "ak5GenJetsNoNu"
selectJets = cms.Sequence()... |
import argparse
import glob
import os
"""
Check Dataset path with train/val folder
python checkDataset.py --dataset DATASET_DIR
"""
def main(image_dir, label_dir, dataset_mode):
if dataset_mode == "train":
image_mode_dir = image_dir + "/" + dataset_mode
im_fpath = glob.glob(image_mode_dir + "... |
from . import defaults
from . import models
from . import database
from . import make_json_serializable
|
import numpy as np
import pandas as pd
maxpower = 7
gmr = [None] * maxpower
count=2**(maxpower - 1)
# approach 1
for i in range(maxpower):
x=[j for j in range(2**maxpower) if j & 2**i == 2**i]
gmr[i] = pd.DataFrame(np.array(x).reshape(8,8))
gmr[i].to_excel('Card' + str(i+1) + 'xlsx')
print(gmr[i])
# ... |
"""
author:jjk
datetime:2019/3/29
coding:utf-8
project name:Pycharm_workstation
coding:utf-8
Program function:
20190619
用户随机输入 N 个大写字母,使用 dict 统计用户输入的每个字母的次数 。比如,输入:FUWAHUHSDFJYULFSDHJ
输出:{'F': 3, 'U': 3, 'W': 1, 'A': 1, 'H': 3, 'S': 2, 'D': 2, 'J': 2, 'Y': 1, 'L': 1}
"""
# -*- coding:utf-8 -*-
str =... |
#TCPServer.py
from socket import socket, SOCK_STREAM, AF_INET
#Create a TCP socket
#Notice the use of SOCK_STREAM for TCP packets
serverSocket = socket(AF_INET, SOCK_STREAM)
serverPort=1717
# Assign IP address and port number to socket
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print "Interrupt with C... |
class MoodBotError(Exception):
def __init__(self, message=None, http_status=None):
super(MoodBotError, self).__init__(message)
self.message = message
self.http_status = http_status
class AuthKeyError(MoodBotError):
"""
Auth Key Not Provided
"""
pass
class HttpMethodError... |
#!/usr/bin/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
# "Lice... |
# Hacky fix to remove top-level import errors
import sys
from timeit import default_timer as timer
from rake_new2 import Rake
from tfidf_vectorizer.extract_keywords_tfidf_scratch import TF_IDF_Scratch
sys.path.append("..")
docs = [
"Java is a class based, object oriented programming language that is designed to ... |
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(80), unique=False, nullable=False)
is_active = db.Column... |
# function to read all necessary info from mysql and return a dataframe
def read_from_mysql(spark, src_config, conf_secret_dir):
jdbc_params = {"url": get_mysql_jdbc_url(conf_secret_dir),
"lowerBound": "1",
"upperBound": "100",
"dbtable": src_config["mysql_co... |
import os
import tensorflow as tf
import numpy as np
from keras.layers import Dense
from keras.layers.normalization import BatchNormalization
from keras import backend as K
from deeplearningmodels.imagenet_utils import preprocess_input
from deeplearningmodels.vgg16 import VGG16
from keras.preprocessing.image im... |
# Copyright 2017-2023 Posit Software, PBC
#
# 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 ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 11 15:50:08 2018
@author: jsaavedr
This examples requires openCV
"""
import cv2
import numpy as np
img = cv2.imread('../images/stitching/caso_1/1b.jpg')
gray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
sift = cv2.xfeatures2d.SIFT_create()
kp = sift.det... |
#!/usr/bin/python
import itertools
import heapq
from Queue import Queue
class MyPriorityQueue(Queue):
HIGH=3
NORMAL=5
LOW=7
BLOCK=9
def _init(self,maxsize):
self.count = itertools.count()
self.queue = []
def _qsize(self,len=len):
return len(self.queue)
def peek(sel... |
# v0.10
# show client summary processing
# @author mcs
# 4/1/2018
import paramiko
import time
import re
# import json
import csv
from collections import defaultdict
def csv_reader(csvfile):
"""Read CSV file, return a list of devices."""
device_list = []
with open(csvfile, "r") as datafile:
datare... |
import pygame as pyg
import pygame.display as display
import time
import random
pyg.init()
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
font = pyg.font.Font('neuropol.ttf', 30)
font2 = pyg.font.Font('neuropol.ttf', 20)
display_width ... |
from pathlib import Path
import pytest
from pyscaffold.actions import discover, get_default_options
from pyscaffold.actions import init_git as orig_init_git
from pyscaffold.actions import register, unregister, verify_project_dir
from pyscaffold.api import bootstrap_options
from pyscaffold.exceptions import (
Acti... |
#coding=utf-8
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
#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... |
import subprocess
import settings
import common
import monitoring
class Benchmark(object):
def __init__(self, config):
self.config = config
self.tmp_dir = "%s/%08d" % (settings.cluster.get('tmp_dir'), config.get('iteration'))
self.archive_dir = "%s/%08d" % (settings.cluster.get('archive_di... |
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
# Create your models here.
class Texto(models.Model):
id=models.AutoField(primary_key=True)
tipoTexto=models.ForeignKey('Tipo_Texto',on_delete=models.CASCADE)
habilitado=models.BooleanField(default=True)
descripci... |
# input number and print output in string format with order number
n = int(input("Type the number : "))
array1 = []
i = 1
j = 1
x = ""
while i <= n:
array1.append(str(i))
i += 1
for j in range(len(array1)):
print(array1[j], end= "")
|
from google.appengine.ext import db
from google.appengine.api import memcache
import hashlib
def get_user(num):
if num:
user = memcache.get(str(num))
if not user:
user = User.get_by_id(int(num))
if user:
memcache.set(str(num), user)
return user
def up... |
#!/usr/bin/env python3
class rpcBase:
packetType = {
'request': 0,
'ping': 1,
'response': 2,
'fault': 3,
'working': 4,
'nocall': 5,
... |
import tensorflow as tf
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import sklearn
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import fetch_california_housing
import pandas as pd
from tensorflow import keras
import os
import pprint
housing = fetch_california_... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
... |
from __future__ import unicode_literals, print_function, division
from tqdm import tqdm
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from nltk.translate.bleu_score import SmoothingFunction, sentence_bleu
from os import system
import numpy as np
import matplotlib.ticker as ticker
from ... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2011 Eficent (<http://www.eficent.com/>)
# <contact@eficent.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero ... |
print("Welcome to Gabriel's Loop Playground")
myString = raw_input("Give me a string loop through: ")
for character in myString:
print("This is letter number %s" % (letterN))
print(character)
|
import os
net_dict={}
data=os.popen('ipconfig /all').readlines()
for line in data:
if "网适配器" in line:
#print line[line.index('器')+3:].split(':')[0],
interface=line[line.index('器')+3:].split(':')[0]
net_dict[interface]=''
if 'IPv4' in line:
#print line.split(":")[1]
ip=lin... |
from typing import List
class Solution:
def maxAbsoluteSum(self, nums: List[int]) -> int:
negative_sum = positive_sum = total_negative_sum = total_positive_sum = 0
for num in nums:
negative_sum += num
positive_sum += num
if positive_sum < 0:
posi... |
import urllib.request
url = r"http://placekitten.com/g/1000/1000"
response = urllib.request.urlopen(url)
cat_img = response.read()
fp = open("cat1.jpg","wb")
fp.write(cat_img)
fp.close()
print("ok")
|
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 09 16:21:46 2017
@author: Agathe Bucherie
"""
'''
The script is a test to try to read NCDF file and to plot timeline and maps
'''
#%%
import datetime as dt # Python standard library datetime module
import numpy as np
import pandas as pd
import matplotl... |
import zeit.cms.testing
class TestObjectDetailsJavascript(zeit.cms.testing.SeleniumTestCase):
layer = zeit.cms.testing.WEBDRIVER_LAYER
def test_drag_and_drop_to_sort_table_rows(self):
self.open(
'/@@/zeit.cms.browser.tests.fixtures/tabledrag.html')
s = self.selenium
s.dra... |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
from airbyte_cdk.models import SyncMode
from pytest import fixture
from source_rss.source import IncrementalRssStream
@fixture
def patch_incremental_base_class(mocker):
# Mock abstract methods to enable instantiating abstract class
mocker.patch.ob... |
import numpy as np
import matplotlib.pyplot as mp
t = np.linspace(0,2*np.pi,1000)
r_rose = 5 * np.sin(2*t)
r = 0.8*t
ax = mp.gca(projection='polar')
ax.set_xlabel('x')
ax.set_ylabel('y')
mp.title('3D')
n = 1000
mp.plot(t,r)
mp.plot(t,r_rose)
mp.grid(linestyle=':')
mp.show() |
# Python Type Hints
# typing — Support for type hints
# This module supports type hints as specified by PEP 484 and PEP 526.
# The most fundamental support consists of the types 'Any', 'Union', 'Tuple', 'Callable', 'TypeVar', and 'Generic'.
# When the type of a value is object, a type checker will reject almost all... |
"""
Interpolation Tools
===================
Wrappers around FITPACK functions
----------------------------------
splrep
find smoothing spline given (x,y) points on curve.
splprep
find smoothing spline given parametrically defined curve.
splev
evaluate the spline or its derivatives.... |
#!/usr/bin/env python
from __future__ import print_function, absolute_import, unicode_literals, division
import functools
import itertools
import numpy as np
def groupby(A, keyfunc):
return itertools.groupby(sorted(A, key=keyfunc), keyfunc)
def keyfromcols(row, columns):
return tuple(row[i] for i in column... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import cv2
import numpy as np
import sys
import rawpy
import png
import glob2
import matplotlib.pyplot as plt
from PIL import Image
from IPython.display import display
# In[2]:
def readImagesAndTimes(filenames):
images = []
for filename in filenames:
... |
import time
from datetime import date
class player:
def __init__(self, name,ind,mean,std,nmatch,lastplayed,nwins=0,nloss=0):
self.name = str(name)
self.ind = int(ind)
self.mean = int(mean)
self.std = float(std)
self.nmatch = int(nmatch)
self.nwins = int(nwins)
... |
from pyramid.exceptions import ConfigurationError
from yosai.web import WebYosai
from .webregistry import PyramidWebRegistry
def pyramid_yosai_tween_factory(handler, registry):
"""
This tween obtains the currently executing subject instance from Yosai and
makes it available from the request object.
"... |
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'users'
urlpatterns = [
path('available/', views.view_polls, name='view_polls'),
path('register/', views.register, name='register'),
path('login/', views.loginUser, name=... |
"""
Tests for the validation functionality in this module
"""
import pytest
from requests import Request, Response
# pylint: disable=import-error
import src.cisco_wlc_api.Exceptions as CiscoWLCAPIExceptions
import src.cisco_wlc_api.Validators as CiscoWLCAPIValidators
# Test data
length_test_a = [
"one",
"two... |
import sqlite3
conn = sqlite3.connect("project.db")
c = conn.cursor()
'''
c.execute ('''CREATE TABLE project (id integer PRIMARY KEY AUTOINCREMENT,
Fname varchar(30) NOT NULL,
LName varchar(30) NOT NULL,
score float(30) NOT NULL,
time float(30) NOT NULL,
sum float(30) NOT NULL)''')
conn.commit()
co... |
"""
This module provides static method to create
pdf report with option to save picture
"""
import datetime
import os, shutil
from fpdf import FPDF
from file_manipulation.visualization import IMAGE
OUTPUT_PDF = 'report.pdf' # pdf file name
def make_pdf_report(pic_opt, nmea_str, output):
"""
Creates PDF file... |
affiliation_properties = {
'user': {
'description': 'Unique integer identifying a user.',
'type': 'integer',
'minimum': 1,
},
'permission': {
'description': 'User permission level for the organization.',
'type': 'string',
'enum': ['Member', 'Admin'],
},
}
... |
import tensorflow as tf
def logloss(Ptrue,Pred,szs,eps=10e-10):
b,h,w,ch = szs
Pred = tf.clip_by_value(Pred,eps,1.)
Pred = -tf.log(Pred)
Pred = Pred*Ptrue
Pred = tf.reshape(Pred,(b,h*w*ch))
Pred = tf.reduce_sum(Pred,1)
return Pred
def l1(true,pred,szs):
b,h,w,ch = szs
res = tf.reshape(true-pred,(b,h*w*ch))... |
# Generated by Django 3.1.7 on 2021-03-05 14:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Users', '0023_auto_20210305_1409'),
]
operations = [
migrations.RemoveField(
model_name='createevent',
name='guests'... |
from datapoint import DataPoint
from fusionekf import FusionEKF
def parse_data(file_path):
"""
Args:
file_path
- path to a text file with all data.
- each line should have the following format:
[SENSOR ID] [SENSOR RAW VALUES] [TIMESTAMP] [GROUND TRUTH VALUES]
Whereas radar ... |
a,b,c=map(int,input().split())
k=''
if a>0:
k=k+str(a)
if b==1:
k=k+'+x'
elif b==-1:
k=k+'-x'
elif b>0:
k=k+'+'+str(b)+'x'
elif b<0:
k=k+str(b)+'x'
if c==1:
k=k+'+y'
elif c==-1:
k=k+'-y'
elif c>0:
k=k+'+'+str(c)+'y'
elif c<0:
k=k+str(c)+'y'
eli... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 13 14:08:17 2018
@author: Administrator
"""
import os
pwd = os.getcwd()
os.chdir(pwd)
os.environ['NLS_LANG']='SIMPLIFIED CHINESE _ CHINA . UTF8 '
from MyPasture_V1001 import caigou
caigou=caigou()
if __name__ == '__main__':
data,hms=caigou.welcome()
up=input("是... |
# Exercise 7: Rewrite the grade program from the previous chapter using a function called computegrade
# that takes a score as its parameter and returns a grade as a string.
def computegrade(score):
if score < 0 or score > 1:
return "score out of range"
elif score >= 0.9:
return "A"
elif sc... |
import os
import sys
import psycopg2
import datetime
import json
import logging
import pandas as pd
import numpy as np
from glob import glob
from ast import literal_eval
from Scripts.ConnectToDatabase import ConnectToDatabase
from Scripts.sql_queries import movies_metadata_copy_query
from Scripts.sql_queries import mov... |
import traceback
import sys
def format_exception(e):
exception_list = traceback.format_stack()
exception_list = exception_list[:-2]
exception_list.extend(traceback.format_tb(sys.exc_info()[2]))
exception_list.extend(traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1]))
ex... |
from django.shortcuts import render, redirect
from .form import MyUserCreationForm
from django.contrib import messages
def register(request):
if request.method == "POST":
form = MyUserCreationForm(
request.POST)
if form.is_valid():
form.save()
username = form.c... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-09 22:44
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('character', '0019_auto_20171029_1416'),
]
operatio... |
import praw, re, pokemon_finder
from collections import deque
from time import sleep
r = praw.Reddit("Pokedex by /u/Thirdegree")
done = deque(maxlen=300)
def _login():
USERNAME = raw_input("Username?\n> ")
PASSWORD = raw_input("Password?\n> ")
r.login(USERNAME, PASSWORD)
return USERNAME
def find_pokelink(body)... |
import pygame
import sys
import random
import math
import uuid
pygame.init()
pygame.display.set_caption('sim')
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255,255, 0)
BACKGROUND_COLOR = (0,0,0)
white = (255, 255, 255)
green = (0, 255, 0)
... |
#!/usr/bin/env python
#
# Copyright 2016-2018 Intel Corporation. All Rights Reserved.
#
# The source code contained or described herein and all documents related
# to the source code ("Material") are owned by Intel Corporation or its
# suppliers or licensors. Title to the Material remains with Intel
# Corporation or ... |
#----
# Строения, контейнеры, конструктивные элементы:
metadict_detail['Шахтная пусковая установка МБР'] = {
'Стратегические ядерные ракеты':1,
'Электрооборудование и средства связи комплекса межконтинентальных баллистических ракет':1,
'-Допустимая стоимость оборудования ($)':500000,
}
... |
# Fill in the Line class methods to accept coordinates as a
# pair of tuples and return the slope and distance of the line.
import math
class Line:
def __init__(self,coor1,coor2):
self.coor1 = coor1
self.coor2 = coor2
def distance(self):
sumX = (self.coor2[0] - self.coor1[0]... |
# -*- coding: utf-8 -*-
"""
@author: nur sultan bolel
"""
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Embedding, LSTM, SpatialDropout1D, Dropout,GRU
f... |
import os
import re ... |
import sys, time
sys.path.append('../common')
import intcode
# Delay time in ms.
ANIMATION_SPEED = 1
TILE_EMPTY = 0
TILE_WALL = 1
TILE_BLOCK = 2
TILE_PADDLE = 3
TILE_BALL = 4
W = 40
H = 20
ball = 0
paddle = 0
def save_tile(x,y,tile):
screen[(x,y)] = tile
def print_tile(x,y):
global screen, ball, paddle
if ... |
import sys
import glob
import os
import subprocess
from subprocess import check_output
#f=open('make_rois.sh', 'w')
def make_roi (region, cope_num):
for file in glob.glob('/corral-repl/utexas/poldracklab/data/sugar_brain/sb_00*/model/Lev2/lev2_taste_fnirt.gfeat/cope'+cope_num+'.feat/stats/cope1.nii.gz'):
y= r... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
from google.appengine.ext import db
from application import app
import config
import color
from messages import SPECIAL
from messages import BANNED
class Special(db.Model):
# key name = material str
spicy = db.FloatProperty(required=True)
kal... |
#!/usr/bin/python
PHONE='put-your-intertelecom-phone-num-here-you-use-to-login'
PASS='put-your-password-here'
UPDATE_DELAY_SECONDS=30*60*1000
# In most cases you don't need to change these:
proxy=None
DEBUG_ON=True
SHOW_ON=True
FETCH_TIMEOUT_SECS=120
|
import csv
import datetime
import json
import subprocess
import xml.etree.ElementTree as Et
from dateutil.parser import parse as dateparser
from pred_models.models import PredModels
from src.core.core import runtime_calculate
from src.encoding.encoding_container import ZERO_PADDING, ALL_IN_ONE
from src.jobs.ws_publis... |
from time import sleep
def sleep_decorator(function):
"""
Limits how fast the function is
called.
:param function:
"""
def wrapper(*args, **kwargs):
# print args
sleep(0.1)
return function(*args, **kwargs)
return wrapper
@sleep_decorator
def print_number(num1):
... |
#!/usr/bin/python3
waktu = int(input("Masukkan Detik :"))
jam = int(waktu/3600)
menit = int((waktu%3600)/60)
detik = int((waktu%3600)%60)
print("Detik :", waktu, "\n\nJam :", jam, "\nMenit :", menit, "\nDetik :", detik) |
# Problem Set 1, Problem 1
# Trevor T
import math # for sqrt()
def isprime(n):
'''check if integer n is prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not... |
__author__ = 'Geon'
from django import forms
from reto_taric.constants import SEARCH_TYPES
class SearchFormType(forms.Form):
search_type = forms.ChoiceField(choices=SEARCH_TYPES,
widget=forms.Select, label="Search filter")
class SearchFormValue(forms.Form):
search_value = for... |
import numpy as np
import pandas as pd
import statsmodels.api as sm;
df = pd.read_csv('C:/Users/Minji/Desktop/0701P.csv')
df['intercept']=1
lm=sm.OLS(df['RS40009'], df[['intercept', 'Alarm']])
result=lm.fit()
print(result.summary()) |
from photo_dl.config import headers
from photo_dl.config import timeout
from photo_dl.config import max_retries
import requests
from lxml import etree
from requests.adapters import HTTPAdapter
def request(url, html=True):
session = requests.Session()
session.mount('http://', HTTPAdapter(max_retries=max_retrie... |
abc = input().split()
A = float(abc[0])
B = float(abc[1])
C = float(abc[2])
a = (A * C) / 2
b = 3.14159 * C ** 2
c = (C * (A + B)) / 2
d = B ** 2
e = A * B
print('TRIANGULO: {:.3f}\nCIRCULO: {:.3f}\nTRAPEZIO: {:.3f}\nQUADRADO: {:.3f}\nRETANGULO: {:.3f}'.format(a, b, c, d, e))
|
#Web Scraping
import requests #call package
page = requests.get("http://dataquestio.github.io/web-scraping-pages/simple.html")
#page user defined object
print(page)
#our request, we get a Response object. This object has a status_code property,
#which indicates if the page was downloaded successfully:'''
pri... |
__author__ = 'blaise'
from utils import constants
from customIO.load import libsvm
from configs import configSpark
from models.spark import RF
config = configSpark.ConfigSpark()
loader = libsvm.Loader(config.sc,constants.LOCAL_DATA_PATH)
(trainingData, testData) = loader.data.randomSplit([0.7, 0.3])
learner = RF... |
from bv_meta import *
import random
import copy
def itr_ast(sz, ops):
for x in itr_ast0(sz - 1, ops, 1):
yield ['lambda', ['x_0'], x]
def itr_ast0(sz, ops, vs):
if 'tfold' in ops:
ops0 = [x for x in ops if ops != 'tfold']
for x in itr_ast1(sz - 4, ops0, vs + 1, True):
yie... |
def newtons_gravity(m1, m2, r):
G=6.67430e-11
return G * (m1 * m2) / (r * r)
print(newtons_gravity(10, 20, 30))
print(newtons_gravity(10, 40, 30))
print(newtons_gravity(100, 5, 10))
|
# Linear Search
list = [4,1,2,5,3,7,9, 12, 6] #set up array
search = int(input("Enter search number: ")) # Take input from User
for i in range(0,len(list)): # repeat for each item in list
if search==list[i]: #if item at position i is search time
print(str(search) + " found at position " + str(i)) #... |
# -*- coding: utf-8 -*-
import logging
from subprocess import call
from req_crawler.settings.base import APP_ROOT_PATH
class Logger(object):
def __init__(self, log_type):
self.__log_type = log_type
self.__name = ('req_crawler.log' if log_type == 'main' else
'tas... |
def format_bin(n, val1, val2):
binary = bin(val1 | val2)[2:]
return '0' * (n-len(binary)) + binary
def solution(n, arr1, arr2):
answer = []
for i in range(n):
binary = format_bin(n, arr1[i], arr2[i])
binary = binary.replace('1', '#')
binary = binary.replace('0', ' ')
an... |
from blogs.models import Artical,Artical_Tag,Tag
from django.contrib import admin
admin.site.register(Artical)
admin.site.register(Artical_Tag)
admin.site.register(Tag)
|
# import warnings
# warnings.filterwarnings('ignore')
import numpy as np
## Function
def gradient(machine, param):
if param.ndim == 1:
temp_param = param
delta = 0.00005
learned_param = np.zeros(param.shape)
for index in range(len(param)):
target_param = float(te... |
import cv2
import time
import datetime
import pyautogui
import numpy as np
import os, os.path
from PIL import Image
from settings import PASSWORD, NAME
############
# Settings #
PAUSE_TIME = 1.5
TIMING_MULT = 1.5
CLOSENESS_THRESHOLD = 0.8
ROLLS_FOLDER = 'rolls'
############
pyautogui.PAUSE = PAUSE_TIME
pyautogui.FAIL... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.