text stringlengths 38 1.54M |
|---|
import random
def adn(n):
adn = ['a', 'c', 't', 'g']
return ''. join(random.choice(adn) for x in range(n))
|
count=0
i=2
while True:
n=int(input("Enter number: "))
while i <= n/2:
if n%i==0:
count +=1
break
i +=1
if n==1:
print("number is niether prime nor composite")
elif count==0:
print("number is prime")
else:
print("number is no... |
def followAndCountTheRedirect(url):
url = url.strip()
redirectionCount = 0
if( len(url) > 0 ):
indexOfLocation = 0
httpResponseCodes = ''
while indexOfLocation > -1:
co = 'curl -s -I ' + url
output = commands.getoutput(co)
indexOfFirstNewLine = output.find('\n')
if( indexOfFirstNewLine > -1 ):
... |
# 내부 함수
def knight(saying):
def inner():
return "We are the knights who say: '%s'" % saying
return inner()
print(knight('khs'))
# 내부 함수를 이용해 클로져처럼 행동
# 클로져(closure) : 외부 함수에 의해 동적으로 생성되고, 그 함수의 변수값을 알고 있는 함수
def knight2(saying):
def inner2():
return "We are the knights who say: '%s'" % s... |
class Neighborhood:
def __init__(self, myInfo, proximity, maxPoint):
self._me = myInfo
self._neighbor = [] #(근접도, values) 리스트
self.proximity = proximity #neighbor로 추가할 최소 근접도
self.max = maxPoint #value 점수의 최대값
self._S = set() #neighborKeys - mykeys
def getMyInfo(self):
... |
# FizzBuzz is a popular programming problem to test a developer's ability to think logically with code.
# The problem is simple but deceptive.
# Define a fizzbuzz function that accepts a single number as an argument. The function should print every number from 1 to that argument.
# There are a couple caveats.
# If... |
from zgui import models
from zgui.addons.point_of_sale.report.pos_details import pos_details
class PosDetailsCustom(pos_details):
def _pos_sales_details_custom(self, form):
user_obj = self.pool.get('res.users')
user_ids = form['user_ids'] or self._get_all_users()
company_id = user_obj.bro... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 2 12:40:52 2021
@author: Maxi
"""
# Some Basic Commands
x = 5
print(type(x))
pi_approx = 22/7
radius = 2.2
area = pi_approx*(radius**2)
radius = radius +1
print("The area of the circle is {}". format(float(area)))
## if - else basics
x = int(inpu... |
def sumProblem(x, y):
sum = x + y
sentence = 'The sum of {} and {} is {}.'.format(x, y, sum)
print(sentence)
def main():
sumProblem(1, 6)
sumProblem(670, 80)
a = int(input("Enter an integer: "))
b = int(input("Enter another integer: "))
sumProblem(a, b)
main()
person = input("Enter t... |
import scrapy
from mySpider.items import MyspiderItem
class GushiwenSpider(scrapy.Spider):
name = 'gushiwen'
allowed_domains = ['gushiwen.cn']
start_urls = ['https://www.gushiwen.cn/default_1.aspx']
def parse(self, response):
div_list = response.xpath('//div[@class="left"]/div[@class="sons"]')
for div in di... |
# -*- encoding: latin-1 -*-
import RPi.GPIO as GPIO
import time
import curses
# Konfigurer Raspberry PI's GPIO.
# Fortæl hvilken måde hvorpå vi fortolker GPIO pin's på.
GPIO.setmode(GPIO.BOARD)
# Lav en liste indeholdende pins der bruges til mortorne.
motorPins = [11, 12, 15, 16]
# Set pin nummerne i "motorPins" til... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author:maidou
@contact:QQ4113291000
@time:2018/6/14.上午10:15
'''
if __name__ == '__main__':
pass |
import nester
movies = ['The Simpsons','Eric',['Rick & Morty','Rick'],['South Park','2016','Kyel']]
nester.print_lol(movies,True,0)
|
def bucket_sort(alist, bucket_num):
max_num, min_num = max(alist), min(alist)
bucket_size = (max_num - min_num + 1) / bucket_num
bucket = []
for i in range(bucket_num):
bucket.append([])
# assign elements to buckets
for num in alist:
bucket[int((num - min_num) / bucket_size)].ap... |
from django.db import models
from django.contrib.auth.models import User
class Client(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Utilisateur associe")
default_shipping_address = models.ForeignKey("Address",on_delete=models.CASCADE,
... |
# Modules needed
import mysql.connector
import csv
import smtplib
from mysql.connector import errorcode
from datetime import date
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
# SQL host values
config = ... |
from abc import ABCMeta, abstractmethod
class :
__metaclass__ = ABCMeta
@abstractmethod
def compose(self): raise NotImplementedError |
from dsl.element import Html
from dsl.element import Input
class Form(Html):
tag = "form"
class CharField(Input):
default_attributes = {"type": "text"}
class EmailField(CharField):
pass
class PasswordField(Input):
default_attributes = {"type": "password"}
|
import argparse
from subprocess import call
import pandas as pd
from os.path import dirname, join
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--dry', dest='dry', action="store_true")
args = parser.parse_args()
dry = args.dry
base = "/lfs/l2/chec/userspace/jasonjw/Data/astr... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from builtins import dict, object
from future.utils import raise_from
import base64
import json
import boto3
import requests
from jose import jwk, jwt
from jose.utils import base64url_decode
from requests import Session
from requ... |
import sys
sys.path.insert(0, '/project')
from app import app as application
export http_proxy=
export https_proxy=
export no_proxy= |
import logging
from functools import reduce
def get_productionplans(data):
load, fuels, powerplants = data.values()
values = sorted(map(lambda powerplant : get_values(powerplant,fuels), powerplants), key=lambda k: k['price'])
def reducer(data, value):
name, price, pmax, pmin = value.values()
... |
# 100x100 matrix random floating points inside
# each row is a data point
# each column is a feature
# standardize each feature
import numpy as np
def standardize_features(array: np.array):
# for each column, (datapoint - mean) / std
mean_vector = np.mean(array, axis=0)
std_vector = np.std(array, axi... |
from django.contrib import admin
from .models import EmployeeModel
# Register your models here.
class EmployeeModelAdmin(admin.ModelAdmin):
pass
admin.site.register(EmployeeModel, EmployeeModelAdmin)
admin.site.site_header = 'Haritha Computers & Technology'
|
import getopt
import sys
def usage():
print(
"""
Usage:sys.args[0] [option]
-h or --help: 显示帮助信息
-c or --cache-disk: 缓存盘磁盘
-m or --meta-disk: 元数据磁盘
-b or --data-disks: 数据盘
-ws or --wal-disk-size: 日志盘大小
-ds or --db-disk-size: 数据库盘大小
-sid or --s... |
import scrapy
from scrapy.http import FormRequest
import sys
class FlaskSpider(scrapy.Spider):
name = 'flaskspider'
start_urls = []
count = 0
image_urls = []
depth = 0
def __init__(self, category=None, *args, **kwargs):
# print 'init method'
self.depth = int(sys.argv[-1].split(... |
from pyb import Pin
PIN_D1 = Pin("Y2", Pin.OUT_PP)
PIN_D2 = Pin("Y1", Pin.OUT_PP)
PIN_LAT = Pin("Y3", Pin.OUT_PP)
PIN_OE = Pin("Y4", Pin.OUT_PP)
PIN_A1 = Pin("Y5", Pin.OUT_PP)
PIN_A0 = Pin("Y6", Pin.OUT_PP)
PIN_CLK = Pin("Y7", Pin.OUT_PP)
def write_bit_to_both(bit):
PIN_D1.value(bit)
PIN_D2.value(bit)
PI... |
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
# Create your views here.
def index(request):
# return HttpResponse("calculator app is running")
return render(request, 'index.html')
def submitquery(request):
q = request.GET['query']
# return HttpResponse(q)
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import math
import networkx as nx
class Trajectoire():
def __init__(self,obstacle_1_x,obstacle_1_y,obstacle_2_x,obstacle_2_y):
self.obstacle_1_x = obstacle_1_x
self.obstacle_1_y = obstacle_1_y
self.obstacle_2_x = obstacle_2_x
self.obstacle... |
# To add a new cell, type '#%%'
# To add a new markdown cell, type '#%% [markdown]'
#%% [markdown]
# ## Integrantes
#
# 1. Gabriela Alfaro
# 2. Sebastian Guerraty
# 3. Maria Jose Jimenez
#%% [markdown]
# # Instrucciones
#
# El laboratorio tiene 6 ptos, donde obtener 6 ptos equivale a un 7.0 y 0 ptos un 1.0.
#
# El ... |
import graphics
from board import Board
from input import get_move_int
WELCOME_MESSAGE = "Welcome to 15 puzzle"
EXIT_MESSAGE = "WooHoo Genius!"
def main():
board = Board()
board.start()
graphics.display_message(WELCOME_MESSAGE)
graphics.display_board(board.get_board())
while not bo... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
import os, sys
from os.path import exists
from os import system
import tensorflow as tf
import numpy as np
import scipy.misc
import scipy.stats
from scipy.stats import stats
from utils import data_list_batch_1_30_4
np.set_printoptions(threshold='nan')
# Model
length = 30
filter_size = [3, 5, 7]
filter_num = [100, 70,... |
'''
https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem
'''
def sol(arr):
thisset = set()
for num in arr:
thisset.add(num)
thislist = list(thisset)
thislist.sort(reverse = True)
return thislist[1]
if __name__ == '__main__':
n = int(input())
arr =... |
# -*- coding: utf-8 -*-
'''
Created on 2019-May-02 04:48:56
TICKET NUMBER -AI_1083
@author: Prazi
'''
from scrapy.loader import ItemLoader
from scrapy.loader.processors import MapCompose
from w3lib.html import remove_tags, replace_escape_chars
from Data_scuff.spiders.AI_1083.items import IaJohnsonIowacityBuildingPermit... |
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (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.mozilla.org/MPL/
#
# Software distributed un... |
# pip install requests
# (or pip3 install requests)
import requests
# Generic way of saving a web file
def save(filename, rsp):
with open(filename, 'wb') as file:
for bytes in rsp.iter_content(10000):
file.write(bytes)
resp = requests.get('https://en.wikipedia.org/wiki/Main_Page')
# print(... |
import string
import random
import os
import re
def moveToBaseDir():
drivePrefix = os.path.splitdrive(os.getcwdu())[0]
os.chdir(drivePrefix+ '\\')
#get the input
moveToBaseDir()
os.chdir("programs")
text = open("input.txt", "r").read().split(' ')
puzzle_size = int(raw_input("dimensions"))
puzzle = []
a_word_... |
def solution(skill, skill_trees):
answer = 0
for word in skill_trees:
flag = 0
temp = ''
for i in range(len(word)):
if word[i] in skill:
temp += word[i]
print(temp)
for i in range(len(temp)):
if temp[i] != skill[i]:
... |
#!/usr/bin/python
import re
import subprocess
import serial
import time
import os
while True:
port = "";
while len(port) == 0:
port = re.sub('\n','',subprocess.check_output('/.../port.sh').decode())
os.system('beep')
time.sleep(0.5);
ser = serial.Serial("/dev/" + port,115200)
... |
from argparse import ArgumentParser
from struct import unpack, pack
import sys
import hashlib
from Crypto.Cipher import AES
#aes_key = b'2B63B478DC23D5692B63B478DC23D569'
#aes_key = b'2B63B478DC23D5692B63B478DC23D569'
aes_key = b'ylsuxfhy}w{mh{|k5nn\x86\x87}nmhmxujt|}'
#v9[0] = 0x5A5A3257;
#v9[1] = 0x66975412;
#v9[2]... |
# coding: utf-8
# In[41]:
dummy_list=[99, 1, 45, 1, 10, 15, 4]
# Number 2
# In[42]:
print(dummy_list)
# In[43]:
dummy_list.reverse()
# In[44]:
print(dummy_list)
# In[45]:
dummy_list_2 = [2, 200, 16, 4, 1, 0, 9.45, 45.67, 90, 12.01, 12.02]
# In[46]:
i = 0
while i < len(dummy_list_2):
dummy_... |
import pytest
@pytest.mark.asyncio
@pytest.mark.buvar_plugins("buvar.plugins.bg")
async def test_bg_error(log_output, Anything):
# TODO XXX FIXME without buvar_stage, I get
# --- Logging error ---
# Traceback (most recent call last):
# File "/home/olli/.pyenv/versions/3.7.4/lib/python3.7/logging/__i... |
"""
You are given a 0-indexed array nums consisting of positive integers, representing targets on a number line. You are also given an integer space.
You have a machine which can destroy targets. Seeding the machine with some nums[i] allows it to destroy all targets with values that can be represented as nums[i] + c *... |
import numpy as np
import pandas as pd
import random
from sklearn.metrics import confusion_matrix
import sys
import time
# np.random.seed(21)
# random.seed(21)
# Follows algo from https://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/icdm08b.pdf
class IsolationTreeEnsemble:
def __init__(self, sample_size, n_trees... |
import keras
import os
from keras.callbacks import ModelCheckpoint, TensorBoard
from load_hand_data import load_data, shuffle_data, preprocess_label, preprocess_feature
from keras.applications.mobilenet import MobileNet
from keras.applications.vgg16 import VGG16
from keras.applications.inception_v3 import InceptionV3... |
"""server URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based ... |
import re
specialSyllables_en = """
tottered 2
chummed 1
peeped 1
moustaches 2
shamefully 3
messieurs 2
satiated 4
sailmaker 4
sheered 1
disinterred 3
propitiatory 6
bepatched 2
particularized 5
caressed 2
trespassed 2
sepulchre 3
flapped 1
hemi... |
class Solution:
def search(self, nums: List[int], target: int) -> int:
if(len(nums) == 0):
return -1
if(len(nums) == 1):
if (nums[0] == target):
return 0
return -1
copy = nums
run = True
start = 0
cap = len(nums)-1
... |
from recmd.algorithm.CB import cb_recommend_by_items
from recmd.constants import user_activity
from recmd.database import get_id
def filter_user(item_ls, user_id):
if user_id is None or user_id < 0:
return item_ls
item_dict = user_activity[user_id]
return [obj for obj in item_ls if get_id(obj) not... |
# Programa 3.3: programa3_03.py
# Convertir un entero a una cadena en base 2-16
cadenaConversion = "0123456789ABCDEF"
def aCadena(n,base):
if n < base: return cadenaConversion[n]
else:
return aCadena(n / base,base) + cadenaConversion[n%base]
# Asignatura de Estructuras de Datos
# Dr.... |
class Message:
INFO=6
NOTICE=5
WARN=4
ERROR=3
CRITICAL=2
CHECKERROR=1
LEVELS=["","CHECKERROR","CRITICAL","ERROR","WARN","NOTICE","INFO"]
def __init__(self, module, level, text):
self.module=module
self.level=level
self.text=text
def __iter__(self):
yi... |
# coding:utf-8
# Author : microease
# Date : 2019/4/21
import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
import ssl
import requests
from bs4 import BeautifulSoup
response = requests.get("http://py4e-data.dr-chuck.net/comments_189317.xml")
soup = BeautifulSoup(response.text... |
#不带壳的Tree
#这里介绍一个很重要的思想:遍历
#tree的很多method都会用到遍历,包括深度优先搜索和广度优先搜索
#我已经get了tree的遍历(用到recursion)的题的诀窍了
#直接就对tree的左支和右支call当前function,把他当做已经得到了你要的结果了,再想之后要怎么办,再凑我们最终要的答案
#只做当前一层要做的事!
#还有!在class里面的function必须判断左支右支为不为空!
class BTNode():
def __init__(self, data, left = None, right = None):
self.data = dat... |
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def set_left(self, value):
self.left = Node(value)
def set_right(self, value):
self.right = Node(value)
def is_leaf(self):
if self.left ... |
from django.conf import settings
MEDIA_SERVER_HOST = getattr(settings, "MEDIA_SERVER_HOST", "")
MEDIA_SERVER_USER = getattr(settings, "MEDIA_SERVER_USER", "")
MEDIA_SERVER_PASSWORD = getattr(settings, "MEDIA_SERVER_PASSWORD", "")
MEDIA_SERVER_PORT = getattr(settings, "MEDIA_SERVER_PORT", 22)
MEDIA_SERVER_VIDEO_BUCKET ... |
# Rewrite the program that prompts the user for a list of numbers and prints out the maximum and minimum of the numbers at the end when the user enters “done”. Write the program to store the numbers the user enters in a list and use the max() and min() functions to compute the maximum and minimum numbers after the loop... |
import random
def generate_random_list(number_of_items):
random_items = []
for i in range(number_of_items):
random_items.append(random.randint(0,100))
return random_items
for i in range(10):
random_list = generate_random_list(i)
print(random_list)
|
# encoding: utf-8
# dp[i] 表示以i结尾的子数组的最大和,
# 那么, if dp[i] - 1 <= 0: dp[i] = array[i]
# if dp[i-1] > 0: dp[i] = dp[i-1] + array[i]
def findMaxSubArray(array):
dp = [None] * len(array)
for idx in range(0, len(array)):
if idx == 0 or dp[idx - 1] <= 0:
dp[idx] = array[idx]
else:
... |
#!/usr/bin/env python
__author__ = "Dihia BOULEGANE"
__copyright__ = ""
__credits__ = ["Dihia BOULEGANE"]
__license__ = "GPL"
__version__ = "0.1"
__maintainer__ = "Dihia BOULEGANE"
__email__ = "dihia.boulegane@telecom-paristech.fr"
__status__ = "Development"
from ade.arbitrated_ensemble_abstaining_threshold import Ar... |
from utils import equals, digits
def isGood( n ):
return equals( *map( lambda x : sorted( digits( x ) ),
( n * i for i in xrange( 1, 7 ) ) ) )
def find():
for e in xrange( 1, 10 ):
for x in xrange( 10 ** e, 10 ** ( e + 1 ) / 6 + 1 ):
if( isGood( x ) ):
... |
from collections import OrderedDict
from datetime import datetime, timedelta, timezone
from typing import Optional
# ############### DATETIME ############### #
TIMEDELTA_INTERVALS = (
(timedelta(days=365.2425), 'year'),
(timedelta(days=30.436875), 'month'),
# (timedelta(days=7), 'week'),
(timedelta(day... |
# 图
# 2020/08/07
# author : tanjiaxian
from abc import ABC, abstractmethod
from enum import Enum
from queue import Queue
from typing import Any, List
import numpy as np
from DataStructuresAndAlgorithms.stack import Stack
class VStatus(Enum):
# 顶点状态
UNDISCOVERD = 0
DISCOVERD = 1
VISI... |
# -*- coding: utf-8 -*-
from odoo import models, fields, api
#Modelo de los productos
class Producto(models.Model):
_name = 'inventario.producto'
name = fields.Char(string="Nombre", required=True)
#duration = fields.Integer(string="Cantidad", required=True)
#calculo_stock = fields.Integer(stri... |
#-------------------------------------------------------------------------------
# Name: DBSearchLoanBook
# Version: 1.0
# Purpose:
#
# Author: Matthew
#
# Created: 05/31/2014
# Copyright: (c) Matthew 2014
# Licence: <your licence>
# Modified: 05/31/2014
#-----------------------------------... |
from ibmcloudant import CloudantV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from dotenv import load_dotenv
import os
#getting dotenv file
load_dotenv(verbose=True)
class Db_coneection():
authenticator = IAMAuthenticator(os.getenv('IBM_CLOUDANT_API_KEY'))
service = CloudantV1(authenticator... |
#Implement a progam to convert the input string to lower case ( without using standard library)
str=input("string in uppercase letter\n")
new_string=''
for char in str:
#print(ch)
new_string+= chr(ord(char) + 32)
print("string in lowercase:",new_string) |
from django.urls import path
from webapp2.views import webapp2_view
urlpatterns = [
path('demo', webapp2_view),
]
|
''' #####################################################
''' # Auto Sell SBD in BitTrex v1
''' # by Murat Tatar
''' # January 2018
''' #####################################################
''' #####################################################
''' # --!-- WARNING! --!--
''' # YOU MUST, FIRST TRY WITH yesre... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
core.py
Created on `{% now 'local', '%Y-%m-%d' %}
by {{ cookiecutter.author_name }}
{{ cookiecutter.author_email }}
"""
import logging as log
def main():
# TODO:
# run its processes
pass
if __name__ == "__main__":
log.basicConfig(level=log.DEBUG,
... |
import unittest
from datetime import datetime
from oaipmh.formatters import oai_dc_openaire
class FetchPubTypeFromVocabularyTests(unittest.TestCase):
def test_research_article_returns_article(self):
self.assertEqual(oai_dc_openaire.fetch_pubtype_from_vocabulary('research-article'),
'info:... |
from flaskblog import create_app
# Used to inject debug to templates (http://flask.pocoo.org/docs/1.0/templating/#context-processors)
# @app.context_processor
# def inject_debug():
# return dict(debug=app.debug)
app = create_app()
# this allows you to run the app without "flask run"
# you can just type: "python ... |
#!/bin/python
S = raw_input().strip()
try:
i = int(S) # python will error if it can make the specified conversion
print i
except Exception as msg: # msg holds the exception description
#e = sys.exc_info()[0] # Gets the first line of the error message, may have to 'import sys'
#write_to_page( "<... |
# coding=utf-8
import math
#G(s)=400/(s^2+50s)
class ControlledObjectOne:
__Uk_1 = 0.0
__Uk_2 = 0.0
__Yk = 0.0
__Yk_1 = 0.0
__Yk_2 = 0.0
__Uk = 0.0
#从控制器获取控制量
def InputCv(self,Uk):
self.__Uk = Uk
return
#控制对象输出的过程值
def OutputPv(self,):
#self.__Yk = 1.95... |
# module1.py
def prog(n):
if n <= 1:
return 'gaegul'
return prog(n - 1) + ' gaegul'
maru = 'bulgom'
if __name__ == '__main__':
print('module1 starting')
print(prog(7))
|
# coding: utf-8
# flake8: noqa
"""
NBA v3 Scores
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_im... |
import streamlit as st
# To make things easier later, we're also importing numpy and pandas for
# working with sample data.
import numpy as np
import pandas as pd
st.title('My first app')
st.write("Here's our first attempt at using data to create a table:")
st.write(pd.DataFrame({
'first column': [1, ... |
def judge_score(in_score):
if in_score < 0:
print("Invalid score")
else:
if in_score > 100:
return "Invalid score"
elif in_score > 90:
return "Excellent"
elif in_score > 50:
return "Passable"
else:
return "Bad"
score = flo... |
from cgo import write_go_mod
import re
from suffix import get_version_type, get_major, get_revision_type
from glide import get_hash
import requests
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
import json
import random
import pymysql
import chardet
from dealdep import deal_local_repo_dir... |
import datetime
from django.http import HttpResponsePermanentRedirect
from django.conf import settings
from django.core.cache import cache
from django.core.files import storage
from django.core.xheaders import populate_xheaders
from django.shortcuts import render_to_response
from django.template import RequestContext
f... |
import os
import math
import pickle
import random
import argparse
from util import read_pickles
from sys import argv
import operator as op
from functools import reduce
def ncr(n, r):
r = min(r, n-r)
numer = reduce(op.mul, range(n, n-r, -1), 1)
denom = reduce(op.mul, range(1, r+1), 1)
return numer * 1.... |
from gamegrid import *
import random
class Dwarf(Actor):
def __init__(self, name, size):
Actor.__init__(self, "sprites/dwarf" + str(size) + ".png")
self.name = name
self.size = size
def __eq__(self, a): # ==
return self.size == a.size
def __ne__(self, a): # !=
ret... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Unit tests for the fielddetail servlet."""
from __future__ import print_function
from __futu... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import QHBoxLayout, QLabel
from commun.constants.colors import color_bleu_gris, color_blanc
from commun.constants.stylesheets import black_14_label_stylesheet, line_edit_stylesheet
from commun.ui.public.image import Image
from commun.ui.public.mondon... |
import os
import numpy as np
import pandas as pd
import geopandas as gpd
import shapely
import geohunter
class Data(object):
def __init__(self, folder_path, geodata=False, grid_resolution=1):
self.samples = pd.read_csv(os.path.join(folder_path,'samples.csv'),
index_col=0).set_... |
import requests
import wget
import os
import hashlib
import tarfile
def has_new_ver(ver_fname,ver_url):
if not os.path.isfile(ver_fname): #判断本地有没有版本文件
return True
with open(ver_fname) as fobj: #如果存在则打开
local_ver = fobj.read() #读取版本文件内容赋值给local_ver
r = requests.... |
# This function takes a list of lists, each with 2 positive integers [start,end] and returns the total sum of (end-start).
# Some of the starts/ends from different list elements may overlap.
# All list values are positive integers less than 2^30-1.
def answer(intervals):
# sort pairs low to high by start time (pai... |
#importing libraries
import argparse
def dataloader(X_train,y_train,X_test):
#importing libraries
import joblib
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
#loading the inputs
X_train = np.load(X_train)
X_test = np.load(X_test)
y_train = np.load... |
from betfair.api import API
from time import sleep, time
# Created by Birchy 06/02/2012
# bespokebots.com
# NOTE:
# To make this bot fully automated for use on a (Linux) VPS server, you will
# need to remove the "print" statements and write the data to a log file.
# This is because the "print" will fail after you logo... |
'''
######### Parallel Confusion Matrix #########
ang hap sad neu fea sur
^ang| 184 10 3 20 1 11
^hap| 4 232 7 16 1 1
^sad| 5 17 147 58 1 2
^neu| 53 45 64 244 3 8
... |
def transcription():
dna = open('rosalind_rna.txt' , 'r')
strand = ''
count = {}
for line in dna:
strand += line.strip()
for itme in strand:
print itme
ntcount()
|
# this file loads in text files
import os
import glob2
import datetime
my_path = '/Users/Bryan/Documents/Programming/Udemy_Python/Sample-Files'
os.chdir(my_path)
filenames = glob2.glob('*.txt')
def combine_file_data(files):
with open(datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S-%f') + '.txt', 'w') as ... |
import os
def getResult():
# Get all inputs
b, w = map( int, input().split() )
x, y, z = map( int, input().split() )
# Calculations
total = 0
if x > y + z:
total += ( y + z ) * b
total += y * w
elif y > x + z:
total += ( x + z ) * w
total += x * b
else:
total += b * x + w * y
print( total )
... |
import os
import sys
import itertools
import glob
sys.path.append('.')
import sphc
import commonlib.helpers
import commonlib.readconf
import conf_default
commonlib.helpers.setdefaultencoding()
config = commonlib.readconf.parse_config()
def sitecust(s):
return config.words.get(s, s)
commonlib.helpers.push_to_b... |
from ocelot.services.mappers.pipeline import PipelineMapper
from ocelot.tests import DatabaseTestCase
class TestPipelineMapper(DatabaseTestCase):
def setUp(self):
self.install_fixture('pipeline')
def test_to_entity(self):
"""Test that a record can be converted into an entity."""
self.... |
import json
from string import Template
import boto
from boto.mturk.question import Overview, QuestionContent, SelectionAnswer, Question, AnswerSpecification, QuestionForm
from gtd.turk import Task, get_mturk_connection, standard_quals
from gtd.utils import Config
from textmorph import data
"""
To review completed ... |
from django.db import models
from django.utils.safestring import mark_safe
import requests
class Student(models.Model):
COURSES = [
('B.A.', (
('BAHENG', 'B.A (Hons) English'),
('BAPENG', 'B.A. (Programme) compulsory English course'),
('BAHHIN', 'B.A (Hons) Hindi... |
#!/usr/bin/env python3
import sys
import krb_side_car
# Basic tests of utility functions in krb_side_car.py
got_exception = False
try:
krb_side_car.get_secret("us-west-1","non_secret_arn")
except:
got_exception = True
if not got_exception:
print("**ERROR** [Test] get_secret exception test failed")
sys.exi... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from subprocess import call
import random
import json
import os
from os import listdir
from os.path import isfile, join
import seaborn as sns
import pickle
from matplotlib import cm
seed_policy_adjust = json.load(open('nondom-tracker/seed_policy_ad... |
from celery.task import task
@task
def test():
print('This is print text')
return 'This is return text'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.