text stringlengths 8 6.05M |
|---|
#2020F_hw5_submissions problem 1
#I pledge my honor that I have abided by the Stevens honor system -Maya O
def main():
def square(y):
return [y**2 for y in x]
n = int(input("How many numbers would you like to square? "))
x = []
for i in range(0,n):
list = float(input("Enter number: "))... |
# Generated by Django 2.1.2 on 2018-11-12 03:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('datawarehouse', '0008_auto_20181110_1606'),
]
operations = [
migrations.CreateModel(
... |
# @see https://adventofcode.com/2015/day/5
from lib.helper import filetolist
import re
words = filetolist('day5_input.txt')
def part1(w: list):
n = 0
for l in w:
if re.search(r'([aeiou].*){3,}', l) and re.search(r'([a-z])\1+', l) and not re.search(r'(?:ab|cd|pq|xy)+', l):
n += 1
return n
def part2(... |
from __future__ import annotations
import typing as T
from pathlib import Path
import subprocess
import shutil
import json
import os
import tempfile
import importlib.resources
from ..web import git_download
__all__ = ["exe", "build", "find_library"]
def exe() -> str:
cmake = shutil.which("cmake")
if not cm... |
# = [0,10,20,40]
#L[::-1]
#[40, 20, 10, 0]
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]
print (reverse("Alex"))
|
from __future__ import division
from Module3 import *
from Module1 import *
import math
import random
import sys
import os
import itertools
import operator
import random
import string
import nltk
from nltk.corpus import brown as bw # corpus for different genres
from nltk.corpus import wordnet as w... |
"""Tests for the `data_loader` module."""
import os
import pytest
import a2d2.data_loader as data_loader
@pytest.mark.skipif(not os.path.exists("a2d2.tfrecord"), reason="needs access to a tfrecord")
def test_simple():
"""Tests loading a local tfrecord file."""
batch_size = 16
reader = data_loader.A2D2TF... |
# coding: utf-8
# In[50]:
import cv2
import numpy as np
import matplotlib.pyplot as plt
# In[51]:
img = cv2.imread('/home/padmach/data/pyimagesearch/flower3.jpg')
#cv2.imshow('', img)
#cv2.waitKey(0)
# In[52]:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3,3),0)
#cv2.imshow(''... |
import itertools
import csv
import random
total_size = 500
from sparkpost_impl import send_email
def pick_one_person(combination, fields, csvFile):
fields = [3, 4]
for row in csvFile:
matched = False
for idx in xrange(len(fields)):
if row[fields[idx]] != combination[idx]:
continue
email = row[1]
del r... |
import numpy as np
import random
import torch
class RandomFault:
def __init__(self, layer_mask=None, seed=0, frac=0, random_addrs=False, fault_type="uniform", int_bits=2, frac_bits=6):
super(RandomFault,self).__init__()
self.frac = frac
self.random_addrs = random_addrs
self.random_seed = see... |
# Generated by Django 3.0.6 on 2020-05-31 20:33
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('research', '0006_remove_research_attended'),
]
o... |
epic_dict = {'Jack': 5, 'Bill': 14, 'Katy': 3, 'Jess': 33, 'Alex': 4}
# ordenando pela chave
# sorted_dict = sorted(epic_dict.items(), key = lambda t: t[0])
# ordenando pelos valores
sorted_dict = sorted(epic_dict.items(), key = lambda t: t[1])
from collections import OrderedDict
x = (OrderedDict(sorted_dict))
for... |
#a=list(map(int,input().split()))
a=[1,1,4,2,1,3]
b=sorted(a)
c=0
for i in range(len(a)):
if a[i]!=b[i]:
c+=1
print(c)
|
import sys
def main():
script = sys.argv[0]
option = sys.argv[1]
inputFile = sys.argv[2]
outputFile = sys.argv[3]
print(f' \n script {script} wird ')
print(f' \n mit option {option} \n ')
print(f' input file is "{inputFile}" ')
print(f' output file is "{outputFile}" ')
inf = ope... |
from django.shortcuts import render
from django.http import HttpResponse
from .models import Teacher, Student
def teacher_list(request):
teacher_list = Teacher.objects.all().order_by('full_name')
context = {
'teachers': teacher_list
}
return render(request, 'teacher/list.html', context)
|
# This file is part of beets.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribu... |
import math
x=float(input("x= "))
if((x>0)and(x<2)):
x=x*x
print("f(x): ",x)
elif(x<=0):
x=(-1)*x
print("f(x): ",x)
elif(x>=2):
x=4
print("f(x): ",x)
|
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import os
from dataclasses import dataclass
from pants.backend.helm.target_types import (
HelmChartFieldSet,
HelmChartMetaSourceField,
Helm... |
from django.shortcuts import render
# Create your views here.
def chatbotview(request):
question="Hello"
data={
'quest':question,
}
return render(request,"bot.html",data) |
newlist = [x for x in range(10)]
print(newlist) |
# Generated by Django 2.2.4 on 2019-09-07 08:20
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('residents', '0001_initial'),
('visitors', '0008_auto_20190907_1559'),
]
operations = [
migrations.A... |
#|default_exp p00_opencv_cl
# sudo pacman -S python-opencv rocm-opencl-runtime python-mss
import time
import numpy as np
import cv2 as cv
import mss
start_time=time.time()
debug=True
_code_git_version="eb9657d970d6d5e734ec4ea64a9209136d8c70bd"
_code_repository="https://github.com/plops/cl-py-generator/tree/master/examp... |
def reverse_digits(num):
reverse_list = []
still_have_digits = True
while still_have_digits:
digit = num % 10
if num <= 0:
still_have_digits = False
else:
reverse_list.append(digit)
num = num/10
for digit in reverse_list:
print digit... |
import sys
from assignment3 import ConfigDict
cc = ConfigDict('config_file.txt')
if len(sys.argv) == 3:
key = sys.argv[1]
value = sys.argv[2]
print('wrting data {} {}'.format(key,value))
cc[key] = value
else:
print('reading data')
for key in cc.keys():
print(' {} = ... |
# web评分服务端
# coding:utf-8
from flask import Flask, render_template, request, redirect, url_for, make_response, jsonify
import os
import cv2
from keras.models import Sequential
from keras.models import load_model
import numpy as np
import time
from datetime import timedelta
def sc(imagePath,current):
global model... |
# 错误、调试和测试:错误处理、调试、单元测试和文档测试
# 錯誤處理 try 。。except 。。finally
import unittest
import logging
try:
print('try ...')
r = 10 / 0
print('result:', r)
except ZeroDivisionError as e:
print('except:', e)
finally:
print('finally...')
print('end')
# 當我們任務某些代碼可能出錯時,就可以try來運行這段代碼
try:
print('try...')
r ... |
import time
localtime = time.localtime(time.time())
print(localtime)
print(type(localtime))
print(localtime.tm_year)
print(localtime.tm_mon)
print(time.localtime())
|
# Settings from
# Pajonk, Oliver, et al.
# "A deterministic filter for non-Gaussian Bayesian estimation—applications to dynamical system estimation with noisy measurements."
# Physica D: Nonlinear Phenomena 241.7 (2012): 775-788.
#
# More interesting settings: mods.Lorenz84.harder
from common import *
from mods.... |
# extract_overlapping_QME_data.py
# by Cody Moser (10/13/2014)
# cody.moser@amec.com
# AMEC
# Description: extracts overlapping QME (non-missing) data
#from two time series in a .csv file
#import script modules
import os
import csv
#USER INPUT SECTION
input_csv = r'P:\\NWS\\MBRFC\\QME\\MUSM8\\MUSM8_MSBM8_... |
from src.output.DefaultOutput import DefaultOutput
class CliOutput(DefaultOutput):
def frequencyUpdated(self, value):
print("Frequency updated: ", value, " kHz\n") |
"""
1 Кредитование
Создать прогшрамму которая посчитает кредит для потребителя по формуле
Month = (Summ * Proc * (1 + Proc)Years) / (12 * ((1 + Proc)Years – 1))
Где:
Month - размер месячной выплаты;
Summ - сумма займа (кредита);
Proc - процент банка, выраженный в долях единицы (т. е. если 20%, то будет 0.2).
Years - ко... |
# Generated by Django 3.0.6 on 2020-06-04 13:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('musicRun', '0003_auto_20200604_1334'),
]
operations = [
migrations.AddField(
model_name='song',
name='artists',
... |
from telegram.ext.filters import BaseFilter
from .models import Chat
class GroupFilters(object):
class _AllowedGroups(BaseFilter):
name = 'GroupFilters.allowed_groups'
def filter(self, message):
chat_id = message.chat.id
return True if Chat.objects.get_or_no... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
... |
import setuptools
from sdcli.config import Config
EXTENSIONS = {
'Click',
'colorama'
}
setuptools.setup(
name=Config.NAME,
version=Config.VERSION,
author=Config.AUTHOR,
author_email=Config.EMAIL,
packages=setuptools.find_packages(),
license=Config.LICENSE,
description=Config.DES... |
# Python3 default encoding is UTF-8
# 統一發票兌獎:
# 統一發票是一個八位數字(整數)的對獎方式,有一個特別獎號,一個特獎號及三個頭獎獎號,和數個增開六獎(三位數)
# 獎金則是根據下面規則給付:
# 特別獎:和特別獎號碼完全相同 獎金10000000 元
# 特獎:和特獎號碼完全相同 獎金 2000000 元
# 頭獎:和頭獎號碼完全相同 獎金 200000 元
# 二獎:和頭獎號碼最後 7 位數字相同,獎金 40000 元
# 三獎:和頭獎號碼最後 6 位數字相同,獎金 10000 元
# 四獎:和頭獎號碼最後 5 位數字相同,獎金 ... |
from flask import Blueprint
from flask import jsonify
from flask import request
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
from google.cloud import datastore
from google.cloud import bigquery
from google.cloud import storage
from google.cloud.exceptions import... |
import requests
# r = requests.get("http://www.amazon.cn/gp/product/B01M8L5Z3Y")
# print(r.status_code)
# print(r.encoding)
# print(r.request.headers)
# kv = {'user-agent': 'Mozilla/5.0'}
# r = requests.get("http://www.amazon.cn/gp/product/B01M8L5Z3Y", headers=kv)
# print(r.request.headers)
# print(r.text)
def get... |
import json
from elasticsearch import Elasticsearch
from elasticsearch import helpers
es_host = ''
index_name = 'terms-lookup'
def read_json_dump():
with open('/home/dandric/terms-lookup-1.json') as data_file:
print('Starting JSON Loading...')
data = json.load(data_file)
hits = data['hits... |
from flask import Flask, render_template
import os
import sys
from flask import request
from random import randint
import tact_util as t_util
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/result', methods=['POST'])
def result():
name = request.form.... |
"""
Result analysis.py
Observing results of the vowel elimination algorithm in different time bands. Results stored in file with _Analysis.csv
extension.
Author: Rishabh Brajabasi
Date: 2nd May 2017
"""
file_name_template_1 = 'F:\Projects\Active Projects\Project Intern_IITB\Vowel Evaluation PE V6\\Vowel_Evaluation_V6... |
# Generated by Django 3.0.3 on 2020-05-09 22:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cases', '0003_auto_20200509_2240'),
]
operations = [
migrations.AddField(
model_name='case',
name='short_description... |
import os
import sys
import subprocess
import shutil
import hashlib
import fam
sys.path.insert(0, 'scripts')
sys.path.insert(0, os.path.join("tools", "phyldog"))
sys.path.insert(0, os.path.join("tools", "trees"))
import experiments as exp
import link_file_from_gene_tree as phyldog_link
import sequence_model
import resc... |
#!/usr/bin/env python
# coding: utf-8
# In[195]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridSpec
get_ipython().run_line_magic('matplotlib', 'notebook')
plt.style.available
plt.style.use('seaborn-colorblind');
# In[196]:
#DATASET 1 - MAPUTO
df3=pd.re... |
# Generated by Django 3.2.9 on 2021-12-06 16:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('osmcal', '0028_user_home_location'),
]
operations = [
migrations.AlterField(
model_name='event',
name='description',... |
class Solution(object):
def bitwiseComplement(self, num):
"""
:type N: int
:rtype: int
"""
return (1 << len(bin(num)) >> 2) - num - 1
|
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import svm, neural_network, naive_bayes
from sklearn.linear_model import Perceptron
from sklearn import preprocessing
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
Attributes = pd.read_csv(... |
import rest_framework.urls
from django.contrib import admin
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from indig.views import IndicativosViewSet, index, sobre
router = DefaultRouter()
router.register('indicativos', IndicativosViewSet)
urlpatterns = [
path('', index, na... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""用来和数据库进行交互"""
import hashlib
import uuid
import web
db = web.database(dbn='mysql', db='mailserver',
host='192.168.56.101', port=3306,
user='root', pw='mdsmds', charset='utf8')
def create_virtual_user():
pass
def delete_virtual_user():
pass
d... |
#!/usr/bin/env python3
from flatactors import Actor
from interpretor import InterpretorActor
from irc import IRCMainActor
from logger import LoggerActor
class MasterActor(Actor):
def constructor(self):
self.daemon = False
def initialize(self):
self.make_babies(
('interpretor', Int... |
from django.core import signing
from django.views.generic import ListView, TemplateView, View
from django.http import Http404
from django.shortcuts import redirect, get_object_or_404
from django.contrib import messages
from django.utils.translation import ugettext as _
from trueskill import rate_1vs1
from ranking impo... |
from django.conf.urls import patterns, include, url
from django.contrib.auth.views import login, logout, password_change, password_change_done
urlpatterns = patterns('jaber.accounts.views',
url(r'^login', login, {'template_name': 'accounts/login.html', 'extra_context':{}}, name='login'),
)
|
from PIL import Image
img = Image.open('img.JPG')
print(img.format, "%dx%d" % img.size, img.mode)
img.show()
|
# -*- coding: utf-8 -*-
# @Author: zjx
# @Date : 2018/7/27
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
chrome_options = Options()
chrome_options.add_argument('--headless')
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get('http://ww... |
from sys import stdin
class Expression:
def __init__(self, n1, n2, result):
self.n1 = n1
self.n2 = n2
self.result = result
def main():
for line in stdin:
t = int(line)
ls = []
for _ in range(t):
vals, res = input().split('=')
n1, n2 = map... |
from django.db.models import Count
from rest_framework.viewsets import ModelViewSet
from rest_framework.filters import SearchFilter
from django_filters.rest_framework import DjangoFilterBackend
from .models import Dog, Breed
from .serializers import DogSerializer, CreateDogSerializer, BreedSerializer
from .permissions... |
#find a column that has a value given a database and a table
import cx_Oracle
import os
import re
import sys
# raw_input('Which databaese do you ')
os.environ['ORACLE_HOME'] = '/oracle_64/orahome11g/'
os.environ['LD_LIBRARY_PATH'] = '/oracle_64/orahome11g/lib'
construct = 'qad/mfg@ny-oracle-ts-01.Yurman.c... |
#! /usr/bin/env python3
# ---------------------------------------------------------------------------- #
# fn_c_heuristic_wrapper.py #
# #
# By - jacksonwb ... |
from django.contrib import admin
from .models import Position, Job
class PositionAdmin(admin.ModelAdmin):
list_display = ('id', 'name')
list_display_links = ('id', 'name')
search_fields = ['name']
list_per_page = 10
admin.site.register(Position, PositionAdmin)
admin.site.register(Job)
|
import os
import re
import shutil
from PIL import Image
from PIL import ImageOps
from tqdm import tqdm
import time
def ResizeToSquare(path):
newWidth = 1536
newHeight = 1536
shrinkImg = Image.open(path)
shrinkImg.thumbnail((768, 1024), Image.ANTIALIAS)
emptyImg = Image.new("RGB", (... |
import sys
import click
from ai.backend.cli.interaction import ask_yn
from ai.backend.client.session import Session
from ai.backend.client.func.domain import (
_default_list_fields,
_default_detail_fields,
)
# from ai.backend.client.output.fields import domain_fields
from . import admin
from ..pretty import p... |
from datetime import datetime
from db_config import db, ma
from models.probe_monitoring import probe_model
from sqlalchemy import Column, Integer, ForeignKey
class PerformanceAnalysis(db.Model):
__tablename__ = "performance_analysis"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
start_d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from twitter import *
CONSUMER_KEY = "X"
CONSUMER_SECRET = "X"
TOKEN_KEY = "X"
TOKEN_SECRET = "X"
def sendTweet(message):
try:
t = Twitter(auth=OAuth(TOKEN_KEY, TOKEN_SECRET,CONSUMER_KEY, CONSUMER_SECRET))
t.statuses.update(status=message)
except:
pass |
#!/usr/bin/env python
VERBOSE = False;
VVERBOSE = False;
import sys;
import time;
sys.setrecursionlimit(200000);
class Graph:
def __init__(self, num_vertices = 0):
if VERBOSE:
sys.stderr.write("Creating Graph instance with " + str(num_vertices) + " vertices\n");
self.p = [[0 for x ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Interfaz.ui'
#
# Created by: PyQt5 UI code generator 5.8
#
# WARNING! All changes made in this file will be lost!
from fractions import Fraction
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtWidgets import *
from crearSecuenciaRe... |
from pathlib import Path
import numpy as np
import pytest
from npe2 import DynamicPlugin
from npe2.manifest.contributions import SampleDataURI
import napari
from napari.layers._source import Source
from napari.viewer import ViewerModel
def test_sample_hook(builtins, tmp_plugin: DynamicPlugin):
viewer = ViewerMo... |
class Cat:
def __init__(self, name):
self.name = name
def eat(self):
print('%s 吃鱼' % self.name)
cat = Cat('TOM')
cat.eat()
jery = Cat('jery')
jery.eat() |
#!/usr/bin/enc pyton3
#This script is for going in every directory and concatenating all text files in that directory
import os
#import subprocess
#print("-----------------------------------------------------------Hello user------------------------------------------------------\n")
pwd=os.getcwd()
#print(pwd)
#print("\... |
import datetime
from django.db.models import Count
# Сериализаторы
from rest_framework import filters
from rest_framework import generics, viewsets
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from dataclasses import dataclass
from typing import Any
from pants.backend.codegen.protobuf.lint.buf.skip_field import SkipBufLintField
from pants.backend.codegen.protobuf.lint.buf.subsys... |
#This problem was asked by Airbnb.
#Given a list of integers, write a function that returns the largest
#sum of non-adjacent numbers. Numbers can be 0 or negative.
#For example, [2, 4, 6, 2, 5] should return 13, since
#we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5.
def largest_non_adjacent... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from twisted.enterprise import adbapi
import MySQLdb
import MySQLdb.cursors
# 导入时间处理库
import datetime
import time
# 导入json/c... |
import logging
from description import Description
from slipnet import slipnet
from workspaceStructure import WorkspaceStructure
class WorkspaceObject(WorkspaceStructure):
def __init__(self, workspaceString):
WorkspaceStructure.__init__(self)
self.string = workspaceString
#self.string.obj... |
# coding=utf-8
import os
import sys
import unittest
from time import sleep
from selenium import webdriver
from selenium.common.exceptions import NoAlertPresentException, NoSuchElementException
sys.path.append(os.environ.get('PY_DEV_HOME'))
from webTest_pro.common.initData import init
from webTest_pro.common.model.ba... |
import os
import boto3
import json
from boto3.dynamodb.types import TypeDeserializer
def lambda_handler(event, context):
"""
Takes a message from the DynamoDB stream, serializes it, and publishes the
message to the Topic for broadcast
"""
sns = boto3.resource("sns")
topic = sns.Topic(os.envi... |
#!/usr/bin/python
import json
import xlwt
from xlwt import *
import xlrd
## write the header row in the worksheet.
def writeHeaders(sheet,rubric):
##print "adding header for rubric type="+rubric
font = Font()
font.name = "Calibri"
font.bold = True;
style = XFStyle()
style.font = font
if (rubric == "CSW"):
sh... |
"""
inputFile = open("Day11_SeatingSystem/InputTest2.txt","r")
Lines = inputFile.readlines()
input_list = []
for line in Lines:
currentInput = line.strip()
input_list.append(currentInput)
for row_number in range(len(input_list)):
print(row_number)
for row_number in range(len(input_list[0])):
print(row... |
import requests
import json
import time
import queue
class Bot():
def __init__(self, name, port, mediator):
self.name = name
self.port = port
self.url = 'http://localhost:'+str(port)+'/webhooks/rest_custom/webhook'
self.mediator = mediator
if(name != "Scrum Master"):
... |
#Finding numbers that are not divisible by a particular number
n=int(input("Enter the number"))
print('The numbers between 1-100 that are divisible by %d are:'%n)
for i in range(1,100):
if i%n!=0:
continue
else:
print(i,end=" ")
|
#!/usr/bin/env python
import sys
import os
import matplotlib.pyplot as plt
import class_analyse_tools as tools
iteration = list()
nbr_pos_vect = list()
nbr_neg_vect = list()
if len(sys.argv) != 4 :
print("Usage : \narg1 : archive path")
print("arg2 : name of file with the scores")
print("arg3 : number ... |
def score(test):
rt, acc = 0, 0
for i in range(len(test)):
if test[i] == 1:
rt += test[i] + acc
acc += 1
else:
acc = 0
return rt
N = int(input())
test = list(map(int, input().split()))
print(score(test))
|
#!/usr/bin/python
import httplib2
import pprint
import time
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import OAuth2WebServerFlow
# Copy your credentials from the console
CLIENT_ID = '135248680417-jvna7sa41ae8vbfq5kgqb6q5ubfovkj9.apps.googleusercontent.... |
# public function to use
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseBadRequest
import os.path
from captcha.tools import GenCaptcha
from captcha.models import CaptchaStore
def set_captcha(key):
g = GenCaptcha()
ans, buffer = g.cre... |
DENSITY = {'H': 1.36, 'W': 1, 'A': 0.87, 'O': 0.8}
def separate_liquids(glass):
if not glass:
return []
column = len(glass[0])
liquids = sorted((b for a in glass for b in a), key=lambda c: DENSITY[c])
return [liquids[d:d + column] for d in xrange(0, len(liquids), column)]
|
def max(xs):
if len(xs) == 1:
return xs[0]
else:
sub_max = max(xs[1:])
return xs[0] if xs[0] > sub_max else sub_max
print max([1]) # => 1
print max([1,2,10,3,4]) # => 10
|
fout=open('/Users/alejo/Projects/ActiveLearning/Data/compiledv2_Headers.csv', 'w')
with open('/Users/alejo/Projects/ActiveLearning/Data/compiledv2.txt', 'r') as f:
for i,line in enumerate(f):
fout.write("{0},{1}".format(i,line))
fout.close()
|
import os
import pandas as pd
import numpy as np
import datetime
import gc
class Dataset(object):
def __init__(self, train_path = 'train.csv', test_path = 'test.csv', hist_trans_path = 'historical_transactions.csv', new_trans_path='new_merchant_transactions.csv',
new_merc_path='merchants.csv', ba... |
from rest_framework import serializers
from .models import Bike_model, Bike, Bike_rent
class Bike_modelSerializer(serializers.ModelSerializer):
class Meta:
model = Bike_model
fields = '__all__'
class BikeSerializer(serializers.ModelSerializer):
class Meta:
model = Bike
fields =... |
# This file will define our database structure and provide methods to
# access our database
# Sets up database
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from json import dumps
Base = declarative_base()
# Class for Races. Eac... |
import pandas as pd
print("Remove this")
name = "Ismet"
age = 29 |
from PIL import Image
import numpy as np
import random
import math
class DBSCAN():
def __init__(self, fileName, radis, less):
self.img = Image.open(fileName)
self.radis = radis
self.less = less
# --- Image
self.width, self.height = self.img.size
self.imgArr = np.arra... |
#!usr/bin/env python3
import csv
import os
import sys
from datetime import datetime
import db_secrets
import database as db
import google_drive as gd
def migrate_gd_to_db(file_id_list, table):
"""
Downloads data from Google Sheet and uploads it do database.
Argumnent passed to this function must be a Goog... |
try:
import Tkinter as tk
from Tkinter import *
except ImportError:
import tkinter as tk
from tkinter import *
from base_input import BaseInputPage
from utils.paths import isValidPath
class DirectoryInputPage(BaseInputPage, object):
def __init__(self, parent, controller, frame_number):
BaseInputPage.__init__(s... |
#!/usr/bin/env python
__author__ = "Alessandro Coppe"
'''
Create a single VCF from multiple VCFs from Mutect2, Strelka2 and Varscan2.
Parameters:
- v (--vcfs): the list of VCFs separated by ,
- d (--directory): the directory containing the VCFs
'''
import argparse
import os.path
import sys
def check_that_vc... |
import csv
import datetime as dt
import json
import logging
import math
import pickle
import sys
import traceback
from collections import defaultdict
import numpy as np
import luminometers
from fitResultReader import fitResultReader
from luminometers import *
from vdmUtilities import makeCorrString
im... |
import sys
sys.path.append('..')
import BTreeNode
"""
create tree
4
5 9
6 7 11
"""
root = BTreeNode.BTreeNode(4)
root.left = BTreeNode.BTreeNode(5)
root.left.left = BTreeNode.BTreeNode(6)
root.left.right = BTreeNode.BTreeNode(7)
root.right = BTreeNode.BTreeNode(9)
root.right.right = BTreeNode.... |
for i in range(10):
n=int(input("Enter the number"))
if n==0:
continue
print(n)
print("Thank you") |
n = int(input())
arr = list(map(int,input().strip().split()))[:n]
arr.sort()
if n % 2 == 0:
stor1 = []
stor2 = []
for i in range(n):
if i % 2 == 0:
stor1.append(arr[i])
else:
stor2.append(arr[i])
stor2.reverse()
res = stor1 + stor2
elif n % 2 ==... |
# Copyright 2022 Pulser Development Team
#
# 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 i... |
from django.shortcuts import render
from django.core.serializers import serialize
from django.views.generic import View
from django.http import HttpResponse
from django.http import JsonResponse
from .mixins import CSRFExempt,render_to_response,is_json
from .models import StuData
from .forms import StuForm
import json
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.