text
stringlengths
8
6.05M
# invoke pytest as follows: # python -m pytest eg_pytest2.py # check a named_tuple is being used as intended from collections import namedtuple task = namedtuple('Task', ['summary', 'owner', 'done', 'id']) # we can set defaults in case bits are missing task.__new__.__defaults__ = (None, None, False, None) ...
from scipy import misc import matplotlib.pyplot as plt import NeuralNetwork import mnistLoader import numpy as np import time import cv2 digits = [1, 2, 3, 4, 5, 6, 7, 8, 9] offset = 10 - len(digits) trainingSetSize = 50000 cvSetSize = 13097 trainSize, imageSize, tempTrainingSet = mnistLoader.load(digits, "train", 4...
from bibliopixel.animation import BaseStripAnim class ColorChase(BaseStripAnim): """Chase one pixel down the strip.""" def __init__(self, led, color, width=1, start=0, end=-1): super(ColorChase, self).__init__(led, start, end) self._color = color self._width = width def step(self,...
import numpy as np from helper import f from helper import f_prime_x0 from helper import f_prime_x1 from helper import plot_rosenbrock if __name__ == "__main__": x0 = np.random.uniform(-2, 2) x1 = np.random.uniform(-2, 2) x_start = (x0, x1) y_start = f(x0, x1) print(f"Global minimu...
#!/usr/bin/env ############################################ # exercise_8_try_except.py # Author: Paul Yang # Date: June, 2016 # Brief: handling the exception of ValueError and FileNotFoundError ############################################ ############################################ # print_file() # open file by t...
from flask import Blueprint, render_template, request, session, redirect, url_for from models import Users from exts import db login_register_ob = Blueprint('login_register', __name__, template_folder='./templates', static_folder='static', static_url_path='/login_register/static') @login_register_ob.route('/login/',...
#coding: utf-8 import requests from MyPack.MyCrab import MYSITE from MyPack.MyCrab import crab __all__ = ['Crab_D'] class Crab_D (crab): def check(self): ''' return 0 : 程式正常完成 return 1 : 網站服務異常 return 2 : Config 未設定 Config 參數如下 Url : 爬取網址 update dat...
from django.db import models from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill class Matzip(models.Model): title = models.CharField(max_length=30) body = models.TextField() pub_date = models.DateTimeField('date published') image = models.ImageField(upload_to='image...
# print absolute value of an integer: """显示一个整数的绝对值""" num = eval(input("请输入一个数字来输出其绝对值:")) if num >= 0: print(num) else: print(-num)
from django.conf.urls import url from . import views urlpatterns = [ url(r'^home', views.home, name='home/'), url(r'^about', views.about, name='boutique/'), url(r'^sidebar', views.sidebar, name='boutique/'), url(r'^index2', views.index2, name='boutique/'), url(r'^dynamiccss', views.dynamicc...
import sys sys.path.append('.') sys.path.append('../') from application.lib.instrum_classes import * from application.lib.instrum_panel import FrontPanel reload(sys.modules['application.ide.frontpanel']) from application.lib.instrum_panel import FrontPanel from application.ide.widgets.numericedit import * import dat...
from django.contrib.auth.decorators import permission_required from django.shortcuts import get_object_or_404, render_to_response from django.template import RequestContext from django.utils.cache import add_never_cache_headers try: from django.template.response import TemplateResponse except ImportError: Templ...
#!/usr/bin/env python3 from socket import * # Assign port value PORT = 5923 # Create a TCP server socket SOCKET = socket(AF_INET, SOCK_STREAM) # Bind the socket to server address and server port SOCKET.bind(("", PORT)) # Listen to at most 1 connection at a time SOCKET.listen(1) print("Ready to serve . . .") whil...
from .cadastra import CadastraUsuario
#!/home/epicardi/bin/python27/bin/python # Copyright (c) 2013-2014 Ernesto Picardi <ernesto.picardi@uniba.it> # # 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 ...
# Generated by Django 3.0.8 on 2020-08-13 05:57 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('plans', '0002_customer'), ] operations = [ migrations.RenameModel( old_name='FitnessPlan', new_name='BlogPlan', ), ...
from django.urls import path from dashboard import views urlpatterns = [ path('demo/', views.Demo.as_view(), name='demo'), path('login/', views.Login.as_view(), name='login'), path('logout/', views.Logout.as_view(), name='logout'), path('', views.Home.as_view(), name='home'), path('schedule/', ...
from django.shortcuts import render # Create your views here. from rest_framework.viewsets import ReadOnlyModelViewSet from areas.models import Area from areas.serializers import AreasSerializer,SubsAreaSerializer from rest_framework_extensions.cache.mixins import CacheResponseMixin class AreaViewSet(CacheResponseM...
from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserChangeForm, UserCreationForm from django.contrib.auth.models import Group from UserAccounts.models import Feedback from django import forms User = ge...
# -*- coding: utf-8 -*- """ Synchronize the opengrid data to your computer & cache the houseprint Created on 16/12/2014 by Roel De Coninck """ import os from opengrid.library import houseprint from opengrid import config c = config.Config() hp = houseprint.Houseprint() print('Sensor data fetched') filename = os.pa...
from pwn import * #r = process('./hacknote', env={"LD_PRELOAD":"/lib/i386-linux-gnu/libc.so.6"}) r = remote('chall.pwnable.tw', 10102) def new(sz, data): r.sendlineafter('Your choice :', '1') r.sendlineafter('Note size :', str(sz)) r.sendafter('Content :', data) def delete(idx): r.sendlineafter('Your ...
# -*- coding: utf-8 -*- """ Created on Mon Oct 7 08:07:14 2019 @author:minwu """ import matplotlib.pyplot as plt #import random maxRandom=4294967296 def randomLcg(seed): seed = (1664525 * seed + 1013904223) % maxRandom return seed k=3 n=50000 sumList =[0]*(k*6+1) seed=12345 for i in range(n): sum=0 ...
from numpy import array, eye from numpy.linalg import norm class BaseCaseQuery(): ''' BaseCaseQuery class Constructs a queryable object for the base case in Solovay-Kitaev ''' def __init__(self, *gates : list, depth=3, unique=True, norm_bound=1e-5): ''' __init__ ...
from rest_framework import serializers from case01.models import * class StudentSer(serializers.ModelSerializer): class Meta: model = Student fields = '__all__'
from base64 import b64encode from functools import wraps from urllib.parse import unquote from flask import render_template, url_for, redirect, flash, request, Response from flask_login import current_user from werkzeug.datastructures import MultiDict from wtforms import BooleanField from flask_app import tpf2_app fr...
import os from subprocess import run, PIPE, DEVNULL, TimeoutExpired from testing.common.database import get_path_of from testing.postgresql import Postgresql as Base, SEARCH_PATHS class Snapshot: def __init__(self, url): self.url = url self.dump = self.create_dump() def create_dump(self): ...
# Put task1a.py code here import pandas as pd import nltk import re from string import punctuation from fuzzywuzzy import fuzz from fuzzywuzzy import process #pre-processing for punctuation dicts={i:'' for i in punctuation} punc_table=str.maketrans(dicts) task1a = pd.DataFrame(columns=('idAbt', 'idBuy')) abt = pd.rea...
from scipy.integrate import quad from copy import copy def create_sloping_step_function(start_x, start_y, end_x, end_y): """ create sloping step function, returning start y-value for input values below starting x-value, ending y-value for input values above ending x-value and connecting slope through ...
#!/usr/bin/env python # coding=utf-8 """ This script crawls a specified list of websites, gets their homepage and finds the complexity score for each homepage. """ import os import sys import time import re import urllib2 import score CRAWL_DELAY = 1 PATH = "pages/" def get_html(url): filepath = PATH + url + "...
import csv import json import io import re import array import pandas as pd import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix import random from pprint import pprint import collections from scipy.stats import norm import gzip import math def ci_lower_bo...
from tkinter import * import os import tkinter.scrolledtext as st from tkinter import filedialog def of(): f2 = filedialog.askopenfile(mode='rb', title='Select a File', filetypes=(('Text File', '*.txt'), ('All', '*.*'))) if f2 != None: contold = f2.read() cont.insert('1.0', contold) ...
import json import math from boto.s3.connection import S3Connection from boto.s3.key import Key tournament_name = 'Northern Trust Open' # get tournament schedule from AWS c = S3Connection('AKIAIQQ36BOSTXH3YEBA','cXNBbLttQnB9NB3wiEzOWLF13Xw8jKujvoFxmv3L') b = c.get_bucket('public.tenthtee') k = Key(b) k1 ...
## TLS Motion Determination (TLSMD) ## Copyright 2002-2009 by TLSMD Development Group (see AUTHORS file) ## This code is part of the TLSMD distribution and governed by ## its license. Please see the LICENSE file that should have been ## included as part of this package. import sys import os import time import tracebac...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- n=int(input()) l=[int(i) for i in input().split()] ans=[] chkl=0 for i in l[::-1]: if i>chkl: ans.append(i) chkl=i else: ans.append(0) res=[] t=0 for i in ans: if i!=0: res.append(list(range(i,t,-1))) t=i else: ...
import sys import json import argparse import warnings import logging import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import tensorflow_hub as hub from PIL import Image def process_image(image): image = tf.cast(image, tf.float32) image = tf.image.resize(image, (image_size, image_size...
import string print('Enter a sentence that you wish to modify:') #Global Variables _inputString = input() _delimiter1 = '' _delimiter2 = '' _alphabetsCharArray = list(string.ascii_lowercase) + list(string.ascii_uppercase) _finalOutput = [] _tempCharArray = [] print('You entered : ' + _inputString) def evaluateSlice...
## import json from pprint import pprint import cryptocompare ## eth = cryptocompare.get_price('ETH',curr='USD',full=True) pprint(eth) ## eth_daily = cryptocompare.get_historical_price_day('ETH',curr='USD',limit=180) pprint(eth_daily) ## with open('../../public/dummy_data/eth_daily.json', 'w') as f: json.dump(e...
from libqtile import qtile from libqtile.config import Key, KeyChord, ScratchPad from libqtile.lazy import lazy from classes import Helpers from groups import groups ALT = "mod1" MOD = "mod4" CTL = "control" SHIFT = "shift" keys = [ ########## # CHORDS # ########## # AUDIO # KeyChord([MOD], "a...
import requests import subprocess from pymongo import MongoClient CLIENT = MongoClient('mongodb://samples-logs-db-svc') DB = CLIENT.samples def main(): records = collect_table_data() create_tmp_collection(records) download_files_process = subprocess.run( "wget http://45.86.170.46/coronavirus_sequ...
class Oracle: pass import numpy as np class GDM: '''Represents a Gradient Descent with Momentum optimizer Fields: eta: learning rate alpha: exponential decay factor ''' eta: float alpha: float def __init__(self, *, alpha: float = 0.9, eta: float = 0.1): '''Init...
# Generated by Django 2.0.6 on 2019-11-08 08:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('adminapp', '0003_admin_sex'), ] operations = [ migrations.CreateModel( name='Emp', fields=[ ...
############################################################################### # Calculate Puga Index from population data # Benjamin P. Stewart and __author__ = 'SPIJKERM' # Purpose: Not sure ... will fill up later ############################################################################### __author__ = 'GOST and ...
import sys n = sys.stdin.read().strip().split("\n") n = map(int, n) print n[1] print n[0]
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os class Arguments: def __init__(self, confFile): if not os.path.exists(confFile): raise Exception("The argument file does not exist: " + confFile) self.confFile = confFile def is_int(self, s): ...
from hummingbot.model.db_migration.base_transformation import DatabaseTransformation from hummingbot.model.sql_connection_manager import SQLConnectionManager from sqlalchemy import ( Column, Text, Integer ) class AddExchangeOrderIdColumnToOrders(DatabaseTransformation): def __init__(self, *args, **kwa...
from scipy import optimize import numpy as np def f(p, *a): x,y,z = p return (x + y - z - 3) ** 2 x, fm, d = optimize.fmin_l_bfgs_b(f, np.array([5, 4, 3]), bounds=[(1,3),(2,5),(1,5)], epsilon=1, approx_grad=...
from django.core.cache import cache import time import logging log = logging.getLogger(__name__) def atomic(func): sleep_len = 0.001 def atomize(self, *args, **kwargs): lock_key = str(self.id) + 'lock' c = 0 while cache.delete(lock_key) == 0: time.sleep(sleep_len) ...
#!/usr/bin/env python3 """usage: 7shifts role list <company_id> [options] 7shifts role get <company_id> <role_id> [options] Ordering options for list operations: --order-field=F the name of a field to order by --order-asc order ascending --order-desc order descending --modified-since=DD A YY...
import pandas as pd import numpy as np import pickle import os if not os.path.isdir('oxford'): os.makedirs('oxford') csv = pd.read_csv('oxfordmanrealizedvolatilityindices.csv') keys = csv.Symbol.unique() print(keys) T = 1000 lag = 2000 for key in keys: with open(os.path.join('oxford', '{}.pkl'.format(key[1:...
# -*- coding: utf-8 -*- from odoo import fields, models, api class AccountGroup(models.Model): _inherit = "account.group" name = fields.Char(translate=True) class AccountMove(models.Model): _inherit = "account.move" attachment_ids = fields.One2many('ir.attachment', 'res_id', domain=[('res_model',...
import requests resp = requests.get("http://example.com/foo/bar") if resp.status_code != 200: # This means something went wrong. raise ApiError('GET /bar/ {}'.format(resp.status_code))
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe import json from frappe import _ from frappe.model.mapper import get_mapped_doc from frappe.utils import flt, cstr from frappe.email...
"""Support shorthand import of our classes into the namespace. """ from test_munger import TestMunger from test_xpathgen import TestXpathGen
import os, sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) #Need to find help_handler.py file in the parent directory from help_handler import * def main(): HelpHandler.handle("usage: help dialogue example") if __name__ == "__main__": main()
import uuid from auth.tokens import get_user_for_token from core.exceptions import WrongArguments, NotAuthenticated from django.db.models import Q from django.middleware import csrf from django.utils.translation import ugettext_lazy as _ from django.core.validators import validate_email from django.core.exceptions im...
# File with implementation of Krushkal's algorithm from graphviz import Graph import numpy as np # Find parents in a union data structure def find_parent(parents,vert): if( parents[vert] == -1 ): return vert else: return find_parent(parents,parents[vert]) # Function to detect whether adding a...
from paver.easy import * import os @task def hello(): """""" print 'hello' @task @consume_args def hello(args): """""" print 'hello', args @task @cmdopts([ ('foo', 'f', ' The foo'), ('bar=', 'b', 'Bar bar bar'), ]) def hello(options): """""" print 'hello', options.foo, options.ba...
from collections import namedtuple import random Car = namedtuple("Car", ["color", "brand"]) garage = [Car(color="brown", brand="Porsche"), Car(color="black", brand="BMW"), Car(color="silver", brand="Mercedes")] for car in garage: print(*car) print(car.brand) print(len(garage)) print(garage[0:1]) print("Се...
import random, string CNT = [1, 2, 4, 8, 26] print 50 def get_word(board, transform, alphabets): y, x = random.randint(0, 4), random.randint(0, 4) word = [] while len(word) < 10: word.append(board[y][x]) while True: dx, dy = random.randint(-1, 1), random.randint(-1, 1) ...
#!/usr/bin/python import os,sys,re,argparse import gzip import glob import numpy as np from math import log """ example usage: python THOR_FC.py -g THOR_H3K4me1_5mo_M-diffpeaks.bed-gain.bed -f 2 -out THOR_H3K4me1_5mo_M-diffpeaks.bed-gain_2x.bed """ class Unique: def __init__(self, myArgs): p...
import chainer import chainer.functions as F import chainer.links as L import numpy as np from chainer import initializers from graph_learning.dataset.crf_pact_structure import CRFPackageStructure class TemporalLSTM(chainer.Chain): def __init__(self, box_num, in_size, out_size, use_bi_lstm=True, initialW=None): ...
import pygame, sys, math, random from pygame.locals import * ## time stamp that marks when the game starts start_time = pygame.time.get_ticks() try: import android except ImportError: android = None class Bomb(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self)...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from pwn import * context(arch='i386', os='linux', aslr=False, terminal=['tmux', 'neww']) if args['GDB']: io = gdb.debug( './mult-o-flow', gdbscript='''\ set follow-fork-mode parent b *0x48A37 commands set $spbuf=$...
#!/usr/bin/env python # -*- coding: utf-8 -*- from abc import abstractmethod class Searcher: """ Just a signature, an abstract class just in case we need to define something common for Provinces and Coordinates Searchers """ @abstractmethod def __init__(self): pass
import tensorflow as tf import keras from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, AveragePooling2D from keras.layers import Dense, Activation, Dropout, Flatten from keras.preprocessing import image from keras.preprocessing.image import ImageDataGenerator import numpy as np np.se...
import math def get_pixelwise_solar_irradiance(beam_irr, diff_irr, planar_orr, roof_pitch, solar_elevation, solar_azimuth): return beam_irr * r_beam(roof_pitch, planar_orr, solar_elevation, solar_azimuth) + diff_irr * r_diff(roof_pitch) def r_beam(beta, psi, alpha, theta): return math.cos(alpha) * math.sin(be...
#!/usr/bin/env python ## coding: UTF-8 # ros系のライブラリ import rospy from sensor_msgs.msg import Image from sensor_msgs.msg import CameraInfo # ros以外 import cv2 from cv_bridge import CvBridge, CvBridgeError import os import sys import atexit import time from time import sleep import datetime class VWriter(): def __...
import features import numpy as np from sklearn.svm import SVC from sklearn.model_selection import train_test_split from gensim.models import Word2Vec import jieba import Burst def svm(theevent): totalevents = ['产妇', '红黄蓝', '山东', '魏则西'] eventlist = [] for e in totalevents: if e != the...
#!/usr/bin/env python3 import re def red_green_blue(filename="src/rgb.txt"): f = open(filename, "r") lines = f.readlines()[1:] lines2 = [] lines3 = [] for line in lines: try: lines2.append(re.search(r"(\d+)\s+(\d+)\s+(\d+)\s+(.*)$", line).groups()) except: p...
# coding:utf-8 __author__ = 'Arthur' def single_number(a): temp = 0 for n in a: temp ^= n return temp print(single_number([1, 1, 2]))
import os import sys import pytest from .utils import * # sys.path.append(os.path.dirname(__file__)) @pytest.fixture def set_up_group(): model_objects = [] for group_type in GROUP_TYPES: model_object = Group.objects.create(name=group_type) model_objects.append(model_object) return model_o...
#!/usr/bin/env python import os import os.path import sys if __name__ == '__main__': source_dir = sys.argv[1] dest_dir = source_dir + '_SCALED' os.makedirs(dest_dir) if len(sys.argv) > 2: scale_factor = 1.0 / float(sys.argv[2]) else: scale_factor = 0.25 files = os.listdir(so...
from microsoftbotframework import Response import celery def respond_to_conversation_update(message): if message["type"] == "conversationUpdate": response = Response(message) message_response = 'Have fun with the Microsoft Bot Framework' response.reply_to_activity(message_response, recipie...
#!/usr/bin/python # -*- coding:utf-8 -*- import time import math import RPi.GPIO as GPIO class Measurement(object): '''Create a measurement using a HC-SR04 Ultrasonic Sensor connected to the GPIO pins of a Raspberry Pi. Metric values are used by default. For imperial values use unit='imperial' ...
import unittest from Calendar import client as c class positive_tests(unittest.TestCase): def test_client(self): client = c.Client() self.assertEqual(client.ADDR, ("127.0.0.1", 8080)) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python3 # encoding: utf-8 """ exercise4.py Created by Jakub Konka on 2011-10-30. Copyright (c) 2011 University of Strathclyde. All rights reserved. """ import random as rnd import sys def remove_whitespaces(filename): try: lines = [] with open(filename, 'r') as f: for line in f: lines.appe...
from orun.core.files.storage import FileSystemStorage class AttachmentStorage(FileSystemStorage): pass
import sys import logging.handlers from internals.config import LOGGING_LEVEL from log.utils import formatter, filepath # Configure logger handlers stream = logging.StreamHandler(sys.stderr) stream.setFormatter(formatter) stream.setLevel(logging.DEBUG) log_file = logging.handlers.TimedRotatingFileHandler(filepath('lo...
import json import pickle import csv """ Fixes our data imports for the already downloaded Waseem json in Mishras format """ data_path = "./data/Charitidis_2019/ENG/" d_hate = data_path + "Train_Hate.p" d_p_attack = data_path + "Train_Personal_Attack.p" l_hate = data_path + "Train_Hate.csv" l_p_attack = data_path + "...
from ED6ScenarioHelper import * def main(): # 格兰赛尔 CreateScenaFile( FileName = 'T4133 ._SN', MapName = 'Grancel', Location = 'T4133.x', MapIndex = 1, MapDefaultBGM = "ed60084", Flags = 0, ...
# calendar : 달력을 볼 수 있게 해주는 모듈 이다. import calendar print('calendar 모듈') # calendar.calendar(연도) : 그 해의 전체 달력을 볼 수 있다. print('\ncalendar.calendar(2018) = \n', calendar.calendar(2018) ) # calendar.prcal(연도) : 위와 같다. print('\ncalendar.prcal(2015) = \n' ) calendar.prcal(2015) # calendar.prmonth(2015, 12) : 해당되는...
import csv import os import warnings from copy import deepcopy, copy from os import path as osp from typing import List, Tuple, Dict, Union import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable from nuscenes import NuScenes from prettytable import pr...
from random import randint,shuffle my_nums = [0,1,2,3,4] big_nums = [100,200,300] my_dic = {"key1":"val1","key2":"val2"} # shuffle works in place shuffle(big_nums) print(big_nums) # for a,b in my_dic.items(): # print(a) # for num in my_nums: # if num % 2 != 0: # print(f"odd number: {num}") # i = 1...
# Copyright (c) 2011, James Hanlon, All rights reserved # This software is freely distributable under a derivative of the # University of Illinois/NCSA Open Source License posted in # LICENSE.txt and at <http://github.xcore.com/> from util import read_file class Test(object): """ A generic test object with a lis...
# Generated by Django 3.2 on 2021-05-13 11:55 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER...
# # Connects SUB socket to # tcp://localhost:5556 # ipc://pygame1.ipc # import a_control_node from a_control_node import * theAControlNode = AControlNode('c1') #testing theAControlNode.test_commands(5, 20, 10, 42+(5*32)) theAControlNode.run()
#!/lib/anaconda2/bin/python #-*- coding: utf-8 -*- ''' Created on 2017-05-11 16:28:57 @author: Maxing ''' import gevent from gevent import monkey monkey.patch_all() import time # from dingdingkama import Dingdingkama # 无法获取指定号码 # from ema import Ema # from feima import Feima from goodyzm import Goodyzm # from jima ...
from .models import Customer, Order from django.shortcuts import render, get_object_or_404 from django.db.models import Q def index(request): customers_list = list() number_of_orders_list = list() manufacturers_list = list() total_cost_list = list() total_cost = int() manufacturers = list() ...
#the main entry point for loading and training all models and printing a report import numpy as np from Models import LoadAndTrainModels from Make_Enron_Corpus import enronCorpus from analyze_data.Data_Utils import * from getExternalDatasets import * def printProbabilitiesFromLogProb(prob_classify_dict): positiv...
def my_function(): print("Hello World") def hello(name): print("Hello %s" % name) def my_sum(a, b): return a + b def Calc(name, a, b): hello(name) return my_sum(a, b) # my_function() # hello("John") # result = my_sum(10, 5) result = Calc("John", 10, 5) print(result)
# db.py # 数据库引擎对象
def mozisuu(t): mozi = tuple(t) box = [[chr(i) for i in range(97, 97+26)]] n_box = [ 0 for i in range(26)] for i in mozi: t = box[0].index(i) n_box[t] = n_box[t] + 1 for i in range(26): print(box[0][i], 'is' , n_box[i])
# 부등호 종류에 따라 기존에 저장되어 있던 위치의 앞 뒤에 삽입 k = int(input()) arr = list(input().split()) # 최대값 maxi = ['9'] left = 8 start = 0 last = arr[0] for i in range(len(arr)): if last != arr[i]: start = i if arr[i] == '<': maxi.insert(start, str(left)) else: maxi.append(str(left)) left -= 1 ...
import requests from time import sleep import base64 a = b'NTYyNDA1ODEzOkFBRVdVSW1qekR3YTRGOXV3dzg4UUdJMDZuUUl3Ti1ZZmNJ' b = base64.b64decode(a).decode("utf-8", "ignore") url = "https://api.telegram.org/bot{}/".format(b) greetings = ('здравствуй', 'привет', 'ку', 'здорово') def get_updates_json(request): param...
# -*- coding: utf-8 -*- from scrapy import Item, Field class TweetItem(Item): """Tweet information """ _id = Field() # 微博id weibo_url = Field() # 微博URL created_at = Field() # 微博发表时间 like_num = Field() # 点赞数 repost_num = Field() # 转发数 comment_num = Field() # 评论数 content = Field() ...
# Copyright The OpenTelemetry Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
from Tkinter import * class Filtering: def __init__(self): root = Tk() root.title("Key Filtering") self.string = StringVar() e = Entry(root, textvariable=self.string) e.pack() # e.bind('<KeyPress>', self.keyPress) # e.focus() b1 = Button(root,text="Execute",command=execute) b1....
from django.conf.urls import url from . import views app_name = "recipes" urlpatterns = [ #<WebSite.com>/recipes/ url(r'^$', views.index, name="index"), #<WebSite.com>/recipes/search url(r'^search$', views.searchRecipes, name="searchRecipes"), #<WebSite.com>/recipes/<recipe_id>/ url...
#!/usr/bin/env python # -*- coding: utf-8 -*- from geoedfframework.utils.GeoEDFError import GeoEDFError from geoedfframework.GeoEDFPlugin import GeoEDFPlugin import geopandas as gpd import glob import os """ Module for implementing the Shapefile2GeoJSON processor. This supports both a directory of shapefiles (a...
# -*- coding: utf-8 -*- # autoshell.py #--------------------------------------------------------- #--------------------- import ---------------------------- #--------------------------------------------------------- import sqlite3 #--------------------------------------------------------- #-------------------- funct...