text stringlengths 38 1.54M |
|---|
# -*- coding:utf8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import scrapy
from tutorial.items import QiuShiItem
from scrapy.contrib.pipeline.images import ImagesPipeline
from scrapy.exception... |
import pymysql
# 打开数据库
try:
db = pymysql.connect(host="localhost",user="root",password="root",database="spider_1",charset='utf8')
except:
print("数据库连接失败") |
from .graph import Graph
from PIL import Image
import pydot
import tempfile
def display_graph(graph, graph_name=None):
"""
Generate graph image by using pydot and Graphviz
Display graph image by using PIL (Python Image Library)
"""
graph_type = "digraph" if graph.is_directed() else "graph"
pyd... |
db.define_table('images',
Field('represent', type='string', length=100, required=True),
Field('file_name', type='string', length=100, required=True)) |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2018-05-07 14:39:40
# Project: MTime
from pyspider.libs.base_handler import *
import re
class Handler(BaseHandler):
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.... |
import matplotlib.pyplot as pyplt
import numpy as np
import math
import sys
from scipy.signal import argrelmax, argrelmin
#this library contains different CFD methods that may be used for on-the-fly processing
###########################################
#Ave CFD section
###########################################
... |
# Generated by Django 2.1b1 on 2019-01-04 12:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('signup', '0007_auto_20190103_2016'),
]
operations = [
migrations.AddField(
model_name='profile',
name='profile_pic',... |
inventory = {'rope':1,'torch':6,'gold coin':42,'dagger':1,'arrow':12}
Alarm = {'rope':12,'gold coin':420,'arrow':12,'bottle':10}
def displayinventory(player):
liste = list(player)
print(liste)
total = 0
for i in range(len(player)):
print(str(player[liste[i]]) + ' ' + str(liste[i]))
tota... |
"""Google_Drive URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.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-... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'BookDistance'
db.create_table(u'books_bookdistance', (
... |
import sys
import main
from PyQt5 import QtGui, QtCore, QtMultimedia
from PyQt5.QtWidgets import *
from PyQt5.QtCore import qDebug, QTimer, QUrl, QFile, QFileInfo, QDir
from PyQt5.QtGui import QColor, QPixmap, QScreen
from PyQt5.QtMultimedia import *
from PIL.ImageQt import ImageQt
from PIL import Image
app = QApplica... |
import os
import json
import asyncio
import aio_pika
import datetime
from dateutil.parser import parse
from pyawad.request import RouteRequest, FareRequest, RequestException
RABBIT_URL = 'amqp://data:passx@127.0.0.1:5672'
REQUEST_QUEUE_NAME = os.environ.get('AMPQ-QUEUE-REQUEST', 'route-request')
RESPONSE_QUEUE_NAME ... |
import platform
import os
dirPathLst = ['..', '..','InOut']
# dirPathLst = ['..', 'InOut']
type = '.txt'
outPrefix = '_out'
dirPath = ''.join(s + os.sep for s in dirPathLst);
dirPath = os.sep + dirPath
def getFullPathInput(fileName):
return os.path.dirname(__file__) + dirPath + fileName + type
def getFullPathOut... |
from typing import List, Union
class Cell:
def __init__(self, x, y, cell_type: Union[int, str] = 0, food: int = 1):
'''cell_type: 0 или field для поля, 1 или wall для стены, по умолчанию 0\n
food: для еды 1, для энергии 10, по умолчанию 1, если клетка является полем'''
self.x, self.y = x, ... |
# #自定义函数体
# def my_abs(x):
# if not isinstance(x, (int, float)):
# raise TypeError('bad operand type')
# if x >= 0:
# return x
# else:
# return -x
channels_release = ("YYBA"
, "YYBM"
, "HUAWEIM"
, "JLGLWBM"
... |
from base import JiraBaseAction
class JiraRemoveVote(JiraBaseAction):
def _run(self, issue):
return self.jira.remove_vote(issue)
|
'''
5. Дан список чисел. Определите, сколько в этом списке элементов, которые
больше двух своих соседей, и выведите количество таких элементов. Крайние
элементы списка никогда не учитываются, поскольку у них недостаточно соседей.
'''
from random import randint
m = int(input('Enter the number of list item: '))
a = [rand... |
#Embedded file name: ACEStream\Core\CacheDB\Notifier.pyo
import sys
import threading
from traceback import print_exc, print_stack
from ACEStream.Core.simpledefs import *
class Notifier:
SUBJECTS = [NTFY_PEERS,
NTFY_TORRENTS,
NTFY_PLAYLISTS,
NTFY_COMMENTS,
NTFY_PREFERENCES,
NTFY_MYPREFERENC... |
def gcd(a,b):
if a==0:
return b;
return gcd(b%a,a);
def lcm(a,b):
return a*b/gcd(a,b);
ans=1;
for i in range(1,20):
ans=lcm(ans,i);
print ans;
|
a,b,c,d=map(int, input().split())
if b<=c or d<=a:
ans = 0
elif a<=c:
if b<=d:
ans = b-c
elif d<=b:
ans = d-c
elif c<=a:
if d<=b:
ans = d-a
elif b<=d:
ans = b-a
elif a==c and b==d:
ans = b-a
print(ans)
#############
#min(b,d)-max(a,c)と考えると簡潔... |
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta
# 몽고 DB에서 특정 데이터 보기
all_movies = list(db.movies.find())
#print(all_movies)
same_stars = list(db.users.find({'star':'9.60'}))
print(same_stars)
|
import os
import speak
import datetime as dt
import commands as cmd
from colorama import Fore, Style
# Time
def tell_time():
time = dt.datetime.now().strftime("%H:%M:%S")
print(Fore.GREEN + dt.datetime.now().strftime("%H:%M") + Style.RESET_ALL)
speak.speak_only(time)
# Date
def tell_date():
date = d... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Enterprise Management Solution
# GRP Estado Uruguay
# Copyright (C) 2017 Quanam (ATEL SA., Uruguay)
#
# This program is free software: you can redistribute it and/or modify
# it... |
import numpy as np
from .grad1D import grad1D
from scipy import sparse
from scipy.sparse import csr_matrix
def grad2D(k, m, dx, n, dy):
"""Computes a two-dimensional mimetic gradient operator
Arguments:
k (int): Order of accuracy
m (int): Number of cells along x-axis
dx (float): Step ... |
year = int(input("请输入一个年份"))
if(year%4 == 0 and year%100 != 0):
print("%d年是闰年"%year)
elif year%400 == 0:
print("%d年是闰年"%year)
else:
print("%d年是平年"%year)
|
from django.shortcuts import render, redirect
from .forms import UserRegistrationForm, ProfileForm
from django.contrib.auth import login, authenticate
from .models import Profile
from store.utils import cartData
def create(request):
form = UserRegistrationForm()
if request.method == "POST":
form = Us... |
def open_calculator(x: int, y: int, z: int, N: int) -> int:
count = 0
for digit in set(str(N)):
if int(digit) not in {x, y, z}:
count += 1
return count
x, y, z = map(int, input().split())
N = int(input())
print(open_calculator(x, y, z, N))
|
import math
import wave
import struct
import uuid
from apps.texthandler.models import TextBlock, Audio
FRAME_SIZE = 100000
def split_file(audio_uuid, file_dir):
audio = Audio.objects.filter(uuid=uuid.UUID(audio_uuid))[0]
filename = audio.filename
filename = filename.split(".")[0]
ifile = wave.open(f... |
# This file contains the Politician, Button, and Point classes
# A Choice has a name, Twitter username, party, boolean value chosen,
# and position coords
class Choice(object):
def __init__(self, name, username, party, x0, y0, x1, y1):
self.name = name
self.party = party # "red" or "blue"
... |
# To avoid trivial solutions, try to solve this problem without the
# function int(s, base=16)
import unittest
from hexadecimal import hexa
class HexadecimalTest(unittest.TestCase):
def test_valid_hexa1(self):
self.assertEqual(hexa('1'), 1)
def test_valid_hexa2(self):
self.assertEqual(hexa(... |
"""Error DTOs"""
import sys
from typing import Union
if sys.version_info < (3, 11): # pragma: no cover
from typing_extensions import TypedDict
else: # pragma: no cover
from typing import TypedDict
class MetisErrorErrorDTO(TypedDict):
"Error's error payload DTO"
message: str
class MetisErrorDTO(T... |
# 효율성 생각 안하고 생각난대로 바로 푼 버전
# n 최대값이 작기 때문에 시간, 공간 복잡도 생각보다 적음
# 값, 기존 인덱스, 정렬 후 인덱스 모두 저장해서 상황에 맞는 요소 선택해서 정렬
n = int(input())
arr = list(map(int, input().split()))
for i in range(n):
arr[i] = [arr[i], i]
arr.sort()
for i in range(n):
arr[i].append(i)
arr = sorted(arr, key=lambda x: x[1])
for i in range(n):
... |
#!/usr/bin/python3
def class_to_json(obj):
""" returs dictionary description with simple data structure list
for JSON serializaton of and object
obj: is an instance of a Class
"""
return obj.__dict__
|
from typing import List
# complexity is O(k * 2 ^ n')
def backtrack(nums: List[int], partialsol: List[int], target: int, currsum: int):
print(nums, partialsol, target, currsum)
if currsum == target:
yield tuple(sorted(partialsol))
else:
for num in nums:
if currsum + num <= targe... |
#!/usr/bin/env python3
import re
double_letter_matcher = re.compile(r"(.)\1")
def is_nice(name):
if len([c for c in name if c in 'aeiou']) < 3:
return False
if 'ab' in name or 'cd' in name or 'pq' in name or 'xy' in name:
return False
return double_letter_matcher.search(name)
def te... |
rules = []
my_ticket = []
nearby_tickets = []
data_type = 'rules'
for i in [i[:-1] for i in open('data.txt')]:
if i == '': continue
if i == 'your ticket:':
data_type = 'your ticket'
continue
if i == 'nearby tickets:':
data_type = 'nearby tickets'
continue
if data_type... |
from __future__ import print_function
import base64
import json
import logging
import cv2
import face_recognition
import grpc
import numpy as np
import cctv_stream_pb2
import cctv_stream_pb2_grpc
from core.face_recognition_lib import face_identification
def face_recognition_v1(stub):
response = stub.SendFrame(... |
#
# 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
# "License"); you may not... |
import tftables
import tensorflow as tf
with tf.device('/cpu:0'):
# This function preprocesses the batches before they
# are loaded into the internal queue.
# You can cast data, or do one-hot transforms.
# If the dataset is a table, this function is required.
def input_transform(tbl_batch):
... |
for item in ['Mosh', 'john', 'sarah', 'michel', 1, 2, 5.6, ]:
print(item)
# compteur
for i in range(0, 10, 2):
print(i)
# decompteur
for i in range(50, 5, -5):
print(i)
# dessin
numbers = [5, 2, 5, 2, 2]
for i in numbers:
print("x" * i)
# list
prices = [15, 20, 50] # prix des produits
total = 0
for... |
#!/usr/bin/env python
import sys
from EPPs.common import StepEPP
# the freezer location of the sample entering the step should be updated to match the step UDFs. The script checks
# if the sample is a submitted sample or aderived sample and updates the corresponding UDFs
class UpdateFreezerLocation(StepEPP):
de... |
from pprint import pprint
import logging
from flask import Flask, render_template
from flask_ask import Ask, question, statement, session
import yaml
import random
import boto3
import uuid
from datetime import datetime
logger = logging.getLogger("flask_ask")
logger.setLevel(logging.DEBUG)
app = Flask(__name__)
ask = ... |
import random
def test(t):
if t == 1:
b = '9am,12am,5pm,12pm'
else:
b = 'fuckpm,all,any,open,str'
return b
print(test(2))
|
"""
import baseclasses for pytraj
"""
from __future__ import absolute_import
from .datasets.cast_dataset import cast_dataset
from .frame import Frame
from .core.topology_objects import Atom, Residue, Molecule
from .datafiles.datafiles import DataFileList
from .c_action.actionlist import ActionList
from .core.c_core imp... |
import sys
import requests
import json
import threading
import time
from dcusb.driver import LEDMessageBoard
leds = LEDMessageBoard()
clock_on = True
note = {
1 : [1, 0, 0, 0, 0, 1, 1],
2 : [1, 0, 0, 0, 0, 1, 1],
3 : [1, 0, 1, 1, 0, 1, 1],
4 : [1, 0, 1, 1, 0, 1, 1],
5 : [1, 0, 1, 0, 0, 1, 1],
6 : [0, 0, 1, 0,... |
from django.db import models
DESIGNATIONS = (
('SE','Sales Executive'),
('MGR','Manager')
)
class Employee(models.Model):
name = models.CharField('Employee Name',max_length=64)
employee_ID = models.CharField(max_length=16)
dob = models.DateTimeField('Date Of Birth')
d... |
import sys
import cv2
import numpy as np
def main():
if len(sys.argv) < 7:
print(f'Error: Expect more arguments.\n'
f'Usage: python {__file__} -s source.jpg -t target.jpg -o output.jpg\n'
f'if output filename is not provided, \'output.jpg\' is default.')
exit()
out... |
# Generated by Django 2.2.13 on 2021-01-24 13:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('academics', '0012_auto_20210118_1633'),
]
operations = [
migrations.AlterField(
model_name='department',
name='batc... |
from app import db
from datetime import datetime
import mistune
class Post(db.Model):
post_title = db.Column(db.Text)
post_md = db.Column(db.Text)
post_html = db.Column(db.Text)
post_timestamp = db.Column(db.DateTime)
post_id = db.Column(db.Integer, primary_key=True,
... |
################################################################################
# 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... |
from sklearn.linear_model import LogisticRegression
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier,ExtraTreesClassifier,VotingClassifier, AdaBoostClassifier, GradientBoostingClassifier
from sklearn.metrics import log_loss
from sklearn.model_selection import train_test_split, ... |
import sys
N = int(input())
D = [list(map(int,input().split())) for _ in range(N)]
x = 0
for i in range(N):
if D[i][0] == D[i][1]:
x += 1
else:
x *= 0
if x == 3:
print("Yes")
sys.exit()
print("No")
|
from flask import render_template, redirect, url_for, request, flash, session
from flask_login import login_user, current_user, logout_user, login_required
from projectmanagement import app, db
from projectmanagement import bcrypt
from projectmanagement.forms import (LoginForm, RegistrationForm, ProjectForm, TaskForm,
... |
#Loading the required libraries
import pandas as pd
import numpy as np
import joblib
import seaborn as sns
import streamlit as st
import sklearn
# loading joblib files
asd_svm = joblib.load("asd_svm.joblib")
#Creating the UI for the application:
st.markdown("<h1 style='text-align: center; color: red;'>Analysis of... |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# Authour:Dreamer
# Tmie:2018.6.22
# 发行量避免程序出错
# 异常处理的目的就 代码可能出错,让程序出错后不要直接崩溃退出,而是提示错误信息,继续后续执行
# 如果用了try语法,后面必须跟except或finally,else可以不写。
try: # 如果代码很可能出错,就把此代码放在try里面
path = input("请输入文件路径:")
with open(path, "r") as f:
content = f.read
print(content)
... |
def stream_kline_to_struct_kline(bar):
klineList = [float(bar['t']), float(bar['o']), float(bar['h']), float(bar['l']), float(bar['c']), float(bar['v'])]
return klineList
|
#-*-coding:utf-8-*-
import time
import random
import sys
from multiprocessing import Process
#多线程
def run(name):
print('%s running' % name)
time.sleep(random.randrange(2, 6))
print('%s running end' % name)
# 必须加,号
p1 = Process(target=run, args=('anne',))
p2 = Process(target=run, args=('alice',))
p3 = Pro... |
import demistomock as demisto
from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import
from CommonServerUserPython import * # noqa
import asyncio
import urllib3
import traceback
from urllib.parse import urlparse
from ipaddress import ip_address
from typing import Dict, Tuple, Any
from jarm.sca... |
from werkzeug.utils import redirect
from books_app.config.mysqlconnection import connectToMySQL
from books_app.models import books
class Author:
def __init__(self, data):
self.id = data['id']
self.name = data['name']
self.created_at = data['created_at']
self.updated_at = data['updat... |
"""
Its pretty imprortant if multiple models are being used for Ensembling, Stacking / Blending
For each of them its very important to have the same folds
"""
import pandas as pd
from sklearn import model_selection
if __name__ == '__main__':
df = pd.read_csv('../input/labeledTrainData.tsv', sep="\t")
df.loc[... |
from django.contrib import admin
from blog.models import Article
from django.contrib.auth.models import User
# Register your models here.
class ArticleAdmin(admin.ModelAdmin):
list_display = ('title', 'decription', 'likes', 'views')
admin.site.register(Article)
|
fullTeam_shortCity_map = {
'49ers':'SFO',
'Bears':'CHI',
'Bengals':'CIN',
'Bills':'BUF',
'Broncos':'DEN',
'Browns':'CLE',
'Buccaneers': 'TAM',
'Cardinals': 'ARI',
'Chargers': 'LAC',
'Chiefs': 'KAN',
'Colts': 'IND',
'Cowboys': 'DAL',
'Dolphins': 'MIA',
'Eagles': '... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class MaxBlurPool(torch.nn.Module):
"""
Simplified implementation of MaxBlurPool based on Adobe's antialiased CNNs.
"""
def __init__(self, n):
super().__init__()
self.maxpool = nn.MaxPool2d(2, 1)
self.padding = n... |
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QVBoxLayout, QLCDNumber
import sys
from PyQt5 import QtGui
import random
class Window(QWidget):
def __init__(self):
super().__init__()
self.title = "This is first thing"
self.height = 700
self.width = 11... |
from django.contrib import admin
from .models import Article, Author
#adminka
#qwerty123
admin.site.register(Article)
admin.site.register(Author)
# Register your models here.
|
import numpy as np
from numpy import float32,int32
np.random.seed(42)
import tensorflow as tf
from keras.layers import TimeDistributed
from keras.layers import Bidirectional
tf.set_random_seed(42)
session_conf = tf.ConfigProto(
intra_op_parallelism_threads=1,
inter_op_parallelism_threads=1
)
from k... |
def has_cycle(head):
slow = fast = head
while slow and fast.next and fast.next.next:
if slow = fast.next:
return True
slow = slow.next
fast = fast.next.next
return False
def main():
pass
if __name__ == "__main__":
main()
|
from pymongo import MongoClient
import json
input_path = 'resources/mock_flights.json'
with open(input_path, 'r') as input_file:
snapshots = json.loads(input_file.read())['snapshots']
client = MongoClient('localhost', 27017)
db = client['recordings']
collection = db['mockFlights']
for snapshot in snapshots:
c... |
from __future__ import print_function
from model import *
flags = tf.app.flags
flags.DEFINE_integer('num_units', 24, 'Number of units in LSTM layer')
flags.DEFINE_integer('num_unrollings', 20, 'Input sequence length')
flags.DEFINE_integer('batch_size', 1000, 'The size of training batch')
flags.DEFINE_integer('train_s... |
from dipy.tracking.utils import length
from dipy.tracking.streamline import Streamlines, cluster_confidence
from FT.single_fascicle_vizualization import *
from dipy.viz import window, actor
from FT.all_subj import all_subj_folders, all_subj_names
import numpy as np
from FT.weighted_tracts import *
main_folder = r'C:... |
'''
Given a binary matrix, find there exists any
rectangle or square in the given matrix whose all
four corners are equal to 1.
'''
def find_rect(m):
x_edges = []
for i in range(len(m)):
y_corners = set()
for j in range(len(m[i])):
if m[i][j] == 1:
y_corners.add(j)
if len(y_corners)>1:
... |
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import JointState
from std_msgs.msg import UInt8MultiArray
# function that publishes a message on the topic ,on which the
# arduino is listening
def publish(msg):
pub = rospy.Publisher('servo_actuator', UInt8MultiArray, queue_size=10)
pub.publish(data=ms... |
from enum import IntEnum, unique
@unique
class HardestGameMove(IntEnum):
up = 0
down = 1
left = 2
right = 3
stay = 4
|
import urllib
import urllib2
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
file = open("print.txt",'w+');
page = 1
url = 'http://www.qiushibaike.com/hot/page/' + str(page)
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {"User-Agent" : user_agent}
try:
request = urlli... |
# encoding: utf-8
# Regular expressions and auxilary functions used in this script are taken from O'Connor et al.'s Tweetmotif
# see: https://github.com/brendano/tweetmotif
import re
def regex_or(*items):
r = '|'.join(items)
r = '(' + r + ')'
return r
def pos_lookahead(r):
return '(?=' + r + ')'
def neg_lo... |
#!/usr/bin/python
import datetime
import lugar
import Persona
#*****************************************************************************
# Clase : Evento
#
# Descripcion : Clase que implementa cada evento en el CLEI
#
# Autores :
# David Lilue # carnet: 09-10444
# Veronica Linayo # ... |
from pyphocorehelpers.DataStructure.dynamic_parameters import DynamicParameters # to replace simple PlacefieldComputationParameters
from pyphoplacecellanalysis.PhoPositionalData.analysis.interactive_placeCell_config import build_configs # TODO: should be replaced by a better and internal config
# ===================... |
#!/usr/bin/python
import sys
import glob
line = "%s\t" % (sys.argv[1])
files = glob.glob("*-server-memory.txt")
data = [int(x.strip()) for x in file(files[0]).readlines()]
data = max(data)
line = line + str(data) + "\t"
files = glob.glob("*-network.txt")
for f in files:
if not f.endswith("-server-network.txt... |
from Bateria import Bateria
from collections import defaultdict
import numpy as np
from matplotlib import pyplot as plt
load = True
angles = [0,3,6,9,12,15,18]
folderpath = "Domingo (31-03-2019)"
CL_dict = defaultdict(list)
CD_dict = defaultdict(list)
CM_dict = defaultdict(list)
test_number = 1
has_more_tests = Tr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.BatchRoyaltyDetail import BatchRoyaltyDetail
class AlipayTradeBatchTransferQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayTradeBatchTrans... |
# -*- coding: utf-8 -*-
# Description:
# Created: 邵鲁玉 2019/10/07
from _datetime import datetime, timedelta
import json
from test.test_model import update_cargo_management, test_end_window, test_allocation
import os
from config import ExperimentalConfig
def test_main(start_day, start_day_str, days, start_time, times)... |
from django.shortcuts import render, redirect
from posts.models import Post
from bugs.models import Bug
from features.models import Feature
from django.views.generic import ListView
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from django.contrib import message... |
from __future__ import division, absolute_import, print_function
from six.moves import range
__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to de... |
import numpy
import json
import cv2
import numpy as np
import os
import scipy.misc as misc
def show(Im):
cv2.imshow("show",Im.astype(np.uint8))
cv2.waitKey()
cv2.destroyAllWindows()
###############################################################################################
def FindIntersectio... |
"""
Error tests
The tests in this file should test errors occurring in log files. These
should be genuine error messages from LaTeX log files, possibly including
BLANK lines in the lines iterable.
"""
import pytest
import texoutparse
@pytest.fixture
def parser():
return texoutparse.LatexLogParser()
def test_p... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" a command line interface to the python tool for leap year check
"""
import click # pylint: disable=import-error
from is_leap import is_leap
from logger import LOGGER
@click.group()
def cli() -> None:
""" part of cli implementation via click"""
pass
@cli.... |
#!/usr/bin/env python
from TTAtom import Atom
import csv
def get_xyz(filename):
"""Given an Tinker XYZ coordinate file, this function will extract all of
the information and place it all within an Atom object.
"""
atoms = []
count = 0
for line in csv.reader(open(filename), delimiter=" ",
... |
pk=list(map(str,input()))
v=t=0
for i in range(0,len(pk)-1):
q=pk[i]
if int(q)!=0:
for j in range(i+1,i+2):
q=q+pk[j]
if int(q)<27 and int(q)>0: v=v+1
elif int(q)==0: v=v-1
else: break
if v!=1: t=v%2
print(v+t+1)
|
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index2(request):
var1 = {'helpvar':'Help Page fromhelp.html'}
return render(request,'second_app/help.html',context=var1) |
import dash_table
import data
table = dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in data.data.columns],
data = data.data.head().to_dict('records'),
page_size=10,
sort_action='native',
filter_action='native'
)
tab_table_children = [tab... |
import itertools
def create_new_lists(base_list):
result_list = []
for i in range(0, len(base_list)):
for j in range(i, len(base_list)):
if base_list[i] + base_list[j] > base_list[-1]:
aux = [x for x in base_list]
aux.append(base_list[i] + base_list[j])
... |
"""
For every binding event, it reports the minimum analyte-gold inter-COM distance and the binding residence time.
"""
XTC = "NP22sp-53_PRO1-10_FIX.xtc"
TPR = "NP22sp-53_PRO1.tpr"
NAME = XTC[:-8]
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist
from MDAnalysis im... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 22 11:32:40 2018
@author: mihan
"""
import json
#função para testar se uma strig é numero:
def isnumber(valor):
try:
float(valor)
except ValueError:
return False
return True
#abrindo arquivo JSON
with open ('estoque.json','r') as entrada:
... |
# pylint: disable=missing-docstring
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import numpy as np
import tensorflow as tf
from cleverhans.devtools.checks import CleverHansTest
from runner import ... |
import logging
from tqdm import tqdm
from src.commons.pytorch.evaluation.RecognizeCommands import RecognizeCommands
logger = logging.getLogger(__name__)
class StreamingAccuracyStats(object):
def __init__(self):
self.how_many_ground_truth_words = 0
self.how_many_ground_truth_matched = 0
... |
# Generated by Django 3.1.5 on 2021-02-22 13:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0054_auto_20210222_1842'),
]
operations = [
migrations.AddField(
model_name='employee',
name='address',
... |
from setuptools import setup
setup(
name='ilse',
version='0.6.0',
py_modules=['ilse'],
install_requires=[
'click',
'requests',
],
entry_points='''
[console_scripts]
ilse=ilse:cli
''',
)
|
# USAGE
# python index_images_parallel.py --images ..\..\datasets\caltech101 --output temp_output --hashes hashes.pickle
from pyimagesearch.parallel_hashing import process_images, chunk
from multiprocessing import Pool, cpu_count
from imutils import paths
import numpy as np
import argparse
import pickle
import ... |
#-----------------------------------------
# contructeur et accesseurs
#-----------------------------------------
def Matrice(nbLignes,nbColonnes,valeurParDefaut=0):
"""
crée une matrice de nbLignes lignes sur nbColonnes colonnes en mettant
valeurParDefaut dans chacune des cases
paramètres:
nbL... |
"""Tests for service.GiphySnapBot."""
import unittest
from unittest.mock import (
MagicMock,
patch,
)
import pytest
from slackclient import SlackClient
from service import base
from service.base import GiphySnapBotBase
TEST_CONFIG = {
"slack_bot_token": "baby shark",
"default_channel": "foo_channel"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.