index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
500
040942e2e09b5c2df5c08207b9c033471b117608
from flask import Flask, url_for, render_template, request import os import blescan import sys import requests import logging from logging.handlers import RotatingFileHandler import json from datetime import datetime import bluetooth._bluetooth as bluez app = Flask(__name__) @app.route('/sivut/') def default_...
501
9ab3dd87f17ac75a3831e9ec1f0746ad81fad70d
# Any object containing execute(self) method is considered to be IDE App # this is Duck typing concept class PyCharm: def execute(self): print("pycharm ide runnig") class MyIde: def execute(self): print("MyIde running") class Laptop: def code(self,ide): ide.execut...
502
6d61df9ac072100d01a1ce3cf7b4c056f66a163c
import pygame import sys import time import random from snake_gym.envs.modules import * from pygame.locals import * import numpy as np class SnakeGame(object): def __init__(self): self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) self.surface = pygame.Surface(self.screen....
503
d69bffb85d81ab3969bfe7dfe2759fa809890208
# Generated by Django 3.1.1 on 2020-10-07 04:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('articals', '0001_initial'), ] operations = [ migrations.AddField( model_name='artical', name='thumb', fi...
504
2ff85ac059f160fcc6b39b4298e8216cbad77ab3
import http.server import socketserver from http.server import BaseHTTPRequestHandler, HTTPServer import time import json import io import urllib import requests from lib.Emby_ws import xnoppo_ws from lib.Emby_http import * from lib.Xnoppo import * from lib.Xnoppo_TV import * import lib.Xnoppo_AVR import shutil import ...
505
33cc8814d9397bcb0041728407efef80a136f151
#!/usr/bin/env python import argparse import keyring import papercut import ConfigParser import getpass import time import os config = ConfigParser.ConfigParser() config.read([os.path.expanduser('~/.papercut')]) try: username = config.get('papercut','username') except ConfigParser.NoSectionError: username = No...
506
5dc8f420e16ee14ecfdc61413f10a783e819ec32
import sys def is_huge(A, B): return (A[0] > B[0]) and (A[1] > B[1]) if __name__ == '__main__': bulks = [] num = int(sys.stdin.readline()) for i in range(num): bulks.append(list(map(int, sys.stdin.readline().split()))) for i in range(len(bulks)): count = 0 for j in range...
507
d6a677ed537f6493bb43bd893f3096dc058e27da
# -*- coding: utf-8 -*- # # Copyright 2019 Google LLC. All Rights Reserved. # # 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 requir...
508
e6acc7b022001d8419095ad6364a6ae9504ec7aa
from __future__ import annotations from functools import cache class Solution: def countArrangement(self, n: int) -> int: cache = {} def helper(perm): digits = len(perm) if digits == 1: return 1 if perm in cache: return cache[per...
509
fd5fca0e9abbb669ddff4d676147acc4344cdd1c
from django import forms class RemoveProdutoDoCarrinhoForm(forms.Form): class Meta: fields = ('produto_id') produto_id = forms.CharField(widget=forms.HiddenInput()) class QuantidadeForm(forms.Form): class Meta: fields = ('quantidade', 'produto_id') # <input type="hidden" name="produt...
510
d654aea3da3e36ccde8a5f4e03798a0dea5aad8a
import pandas as pd import pyranges as pr import numpy as np import sys import logging from methplotlib.utils import file_sniffer import pysam class Methylation(object): def __init__(self, table, data_type, name, called_sites): self.table = table self.data_type = data_type self.name = name...
511
6ee36994f63d64e35c4e76f65e9c4f09797a161e
class Node: def __init__(self, info): self.info = info self.left = None self.right = None self.level = None def __str__(self): return str(self.info) class BinarySearchTree: def __init__(self): self.root = None def create(self, val): i...
512
207b6e56b683c0b069c531a4c6076c2822814390
file = open("yo.txt", "wr") file.write("Yo")
513
e6af221f1d6397d0fc52671cdd27d43549d0aecb
__author__ = 'jjpr' import pyrr import barleycorn as bc def test_xyz123(): cone_x = bc.primitives.Cone(1.0, 1.0)
514
ce75c23c6b0862dde797225f53c900b4ebc56428
from bbdd import * def usuario(): global usser usser=input("Introduce un usuario : ") if len(usser)<5 or len(usser)>15: print("El usuario debe tener entre 5 y 15 caracteres") usuario() elif usser.isalnum()==False: print("Los valores del usurio deben ser únicamente letras o números") usuario() ...
515
345967e2aeafda6ce30cbbbbacf976c97b17def7
myDict={'Friends': ['AP', 'Soham', 'Baba'], 'Likes': ['Math', 'Programming'], 'languages': ['C++', 'Python', 'Java']} myInt=123 myFloat=12.3333 myName='Somesh Thakur'
516
f70f66926b9e2bf8b387d481263493d7f4c65397
"""" articulo cliente venta ventadet """ class Articulo: def __init__(self,cod,des,pre,stoc): self.codigo=cod self.descripcion = des self.precio=pre self.stock=stoc class ventaDetalle: def __init__(self,pro,pre,cant): self.producto=pro sel...
517
b8fcd8e6dce8d210576bc4166dd258e5fd51278d
""" This module contains the logic to resolve the head-tail orientation of a predicted video time series. """ import logging import numpy as np import numpy.ma as ma from wormpose.pose.distance_metrics import angle_distance, skeleton_distance from wormpose.pose.results_datatypes import ( BaseResults, Shuffle...
518
ec90c731a0e546d9d399cbb68c92be1acca8cbe0
from package import * class mysql(MakePackage): dependencies = ["cmake"] fetch="http://dev.mysql.com/get/Downloads/MySQL-5.6/mysql-5.6.10.tar.gz/from/http://cdn.mysql.com/" config='cmake -G "Unix Makefiles" -DCMAKE_INSTALL_PREFIX=%(prefix)s -DWITH_READLINE=1'
519
372d8c8cb9ec8f579db8588aff7799c73c5af255
#!/home/nick/.virtualenvs/twitterbots/bin/python3.5 # -*- coding: utf-8 -*- import tweepy import sqlite3 from configparser import ConfigParser ''' A little OOP would be good later for authenticated user data, c, conn, api ''' def main(): Collector.collect() class Collector: # Main function def coll...
520
8dfef0a4525328be8dfb4723f0a168dc22eb5eb2
#!/usr/bin/env python """ This is a Cog used to display processes/ programs running on the client to a discord text channel Commented using reStructuredText (reST) ToDo create and use a database for multiple servers """ # Futures # Built-in/Generic Imports import os import sys import configparser import shutil ...
521
9c09309d23510aee4409a6d9021c2991afd2d349
################################################################################ # # titleStrip.py # # Generates an output file with the titles of the input stripped # Usage: # python titleStrip.py [input filename] [output filename] # ################################################################################ im...
522
8f3abc5beaded94b6d7b93ac2cfcd12145d75fe8
class Meta(type): def __new__(meta, name, bases, class_dict): print(f'* Running {meta}.__new__ for {name}') print("Bases:", bases) print(class_dict) return type.__new__(meta, name, bases, class_dict) class MyClass(metaclass=Meta): stuff = 123 def foo(self): pass cl...
523
6801d68ebcc6ff52d9be92efeeb8727997a14bbd
#!/usr/bin/env python import json import requests from requests.auth import HTTPBasicAuth if __name__ == "__main__": auth = HTTPBasicAuth('cisco', 'cisco') headers = { 'Accept': 'application/json', 'Content-Type': 'application/json' } url = "https://asav/api/interfaces/physical/Gigab...
524
6e3bb17696953256af6d8194128427acebf1daac
from random import randint, shuffle class Generator: opset = ['+', '-', '*', '/', '²', '√', 'sin', 'cos', 'tan'] @staticmethod def generate(level): """ 根据 level 生成指定等级的算术题 0:小学;1:初中;2:高中 """ """ 生成操作数序列以及二元运算符序列 """ length = randint(0 if le...
525
297b2ff6c6022bd8aac09c25537a132f67e05174
from PIL import Image source = Image.open("map4.png") img = source.load() map_data = {} curr_x = 1 curr_y = 1 #Go over each chunk and get the pixel info for x in range(0, 100, 10): curr_x = x+1 for y in range(0, 100, 10): curr_y = y+1 chunk = str(curr_x)+"X"+str(curr_y) if chunk not in map_data: map_data[...
526
83117000f5f34490cb14580a9867b1e871ccc2ae
from services.BureauActif.libbureauactif.db.Base import db, BaseModel class BureauActifCalendarDataType(db.Model, BaseModel): __tablename__ = "ba_calendar_data_type" id_calendar_data_type = db.Column(db.Integer, db.Sequence('id_calendar_data_type_sequence'), primary_key=True, ...
527
639669174435492f43bf51680c2724863017e9d2
import helpers import os import os.path import json import imp import source.freesprints from pygame.locals import * class PluginLoader: available_plugins = None def __init__(self): self.checkAvailablePlugins() def checkAvailablePlugins(self): print helpers.pluginsPath() ...
528
4462fec6e0edc25530c93ffeeae2372c86fef2cc
import numpy as np import imutils import cv2 image = cv2.imread("D:\\Github\\python-opencv\\images\\trex.png") cv2.imshow("Original", image) cv2.waitKey(0) (h, w) = image.shape[:2] # get height and width of the image center = (w/2, h/2) # which point to rotate around M = cv2.getRotationMatrix2D(center, 45, 1.0) # ro...
529
934921b22d036bd611134ce74f6eba3a2710018e
import cv2 import numpy as np result=cv2.VideoCapture(0) while True: ret,square=result.read() area=square[100:200,100:200] cv2.imshow("video",square) cv2.imshow("video2",area) print(square) if cv2.waitKey(25) & 0xff == ord('q'): break result.release() cv2.destroyAllWindows()
530
76d166bc227986863db77aa784be3de8110437ff
import logging, numpy as np, time, pandas as pd from abc import abstractmethod from kombu import binding from tqdm import tqdm from functools import lru_cache from threading import Thread from math import ceil from copy import copy from .pos import Position from .base import BaseConsumer from .event import SignalEven...
531
3ae0149af78216d6cc85313ebaa6f7cd99185c05
def postfix(expression): operators, stack = '+-*/', [] for item in expression.split(): if item not in operators: stack.append(item) else: operand_1, operand_2 = stack.pop(), stack.pop() stack.append(str(eval(operand_2 + item + operand_1))) return int(floa...
532
d95d899c6eae5a90c90d3d920ee40b38bf304805
#coding: utf-8 """ 1) Encontre em um texto os nomes próprios e os retorne em uma lista. Utilize o Regex (‘import re’) e a função findall(). Na versão básica, retorne todas as palavras que iniciam com maiúscula. 2) Apresente um plot de alguns segundos dos dados de acelerômetro do dataset: https://archive.ics.uci.edu/...
533
dd7ade05ef912f7c094883507768cc21f95f31f6
""" A module for constants. """ # fin adding notes for keys and uncomment KEYS = [ "CM", "GM" # , # "DM", # "AM", # "EM", # "BM", # "FSM", # "CSM", # "Am", # "Em", # "Bm", # "FSm", # "CSm", # "GSm", # "DSm", # "ASm", ] NOTES_FOR_KEY = { "CM": [...
534
0c68bd65cac3c8b9fd080900a00991b2d19260ee
from django.test import TestCase from core.factories import CompanyFactory, EmployeeFactory from core.pair_matcher import MaximumWeightGraphMatcher class PairMatcherTestCase(TestCase): def setUp(self): self.company = CompanyFactory.create() def test_simple(self): employees = EmployeeFactory....
535
32ed07a89a6f929a6c4b78fd79e687b85e01015b
from flask_wtf import FlaskForm from wtforms import StringField, SelectField,SubmitField, PasswordField, RadioField, MultipleFileField, SubmitField, TextAreaField from wtforms.fields.html5 import EmailField, TelField, DateField from wtforms.validators import DataRequired, Email, Length, InputRequired class SignUpForm(...
536
257f18db95e069c037341d2af372269e988b0a80
# Generated by Django 3.1.2 on 2021-07-02 05:38 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('asset', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='balance', name='title', ), ]
537
74cb06ffa41748af431b46c9ff98eb91771a5015
#Get roll numbers, name & marks of the students of a class(get from user) and store these details in a file- marks.txt count = int(input("How many students are there in class? ")) fileObj = open('marks.txt',"w") for i in range(count): print("Enter details for student",(i+1),"below:") rollNo = int(input("Rolln...
538
955cf040aaf882328e31e6a943bce04cf721cb11
#!/usr/bin/env python3 # # Copyright (C) 2011-2015 Codethink Limited # # This program 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; version 2 of the License. # # This program is distributed in the hope that...
539
68a503b2a94304530e20d79baf9fb094024ba67e
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from dajaxice.co...
540
81dec10686b521dc9400a209caabc1601efd2a88
# -*- coding: utf-8 -*- import abc import datetime import importlib import inspect import os import re import six from .library import HalLibrary @six.add_metaclass(abc.ABCMeta) class Hal(): def __init__(self, configpath): self.configpath = configpath # Find libraries inside the lib directory ...
541
66edf0d2f7e25e166563bdb1063a1ed45ecda0e6
Easy = [["4 + 12 = ?", 16], ["45 -34 = ?", 11], ["27 + 12 -18 = ?", 21], ['25 - 5 * 4 = ?', 5], ["18 + 45 / 5 - 3 * 2 = ?", 21], ["5! = ?", 120], ["3! + 2! = ?", 8], ["7 + 5! / 4! - 6 / 3 = ?", 10], ["(25 + 5) / 6 * 4 = ?", 20], ["4(3+c)...
542
7d099012584b84e9767bf0ce9d9df1596ca3bbab
# Set up path references and dependencies. import os, sys, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) sys.path.append(os.path.join(parentdir, "utils")) # Import important helper libraries. from fla...
543
169ad888e7629faff9509399ac7ead7a149a9602
import TryItYourSelf_9_8 as userObj print('\n\n\n\n') admin1 = userObj.Admin('john','deer',30) admin1.describe_user() print('\n') admin1.set_user_name('Reven10') print('\n') admin1.describe_user() admin1.privileges.show_privileges()
544
eb246beb05249f5dfde019b773698ba3bb1b1118
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Nirvana # # Created: 07/06/2014 # Copyright: (c) Nirvana 2014 # Licence: <your licence> #------------------------------------------------------------------------------- import r...
545
bcc4276ea240247519cabbf5fc5646a9147ee3be
import sublime import sublime_plugin class PromptSurrounderCommand(sublime_plugin.WindowCommand): def run(self): self.window.show_input_panel("Surround by:", "", self.on_done, None, None) def on_done(self, tag): try: if self.window.active_view(): self.window.active_...
546
07783921da2fb4ae9452324f833b08b3f92ba294
""" commands/map.py description: Generates a blank configuration file in the current directory """ from json import dumps from .base_command import BaseCommand class Map(BaseCommand): def run(self): from lib.models import Mapping from lib.models import Migration migration = Migration.load(self.options['MI...
547
2f8dff78f5bc5ed18df97e2574b47f0a7711d372
# encoding: utf-8 """ File: demo.py Author: Rock Johnson Description: 此文件为案例文件 """ import sys sys.path.append('../') try: from panicbuying.panic import Panic except: from panicbuying.panicbuying.panic import Panic def main(): ''' 公共参数: store: 商城或书店名称(小米|文泉), browser: 浏览器(目前只支持Chrome), versio...
548
03dd37346ed12bbd66cbebc46fadc37be319b986
import unittest from reactivex import interval from reactivex import operators as ops from reactivex.testing import ReactiveTest, TestScheduler from reactivex.testing.marbles import marbles_testing from reactivex.testing.subscription import Subscription on_next = ReactiveTest.on_next on_completed = ReactiveTest.on_co...
549
e8a36bd7826c5d71cf8012ea82df6c127dd858fc
from typing import Dict, Optional from collections import OrderedDict import torch import torch.nn as nn import torch.optim as optim import yaml def get_device() -> torch.device: if torch.cuda.is_available(): return torch.device("cuda") return torch.device("cpu") def load_yaml_config(config_path: s...
550
63c214d9e831356345ba2eee68634af36964dcff
# Overview file #import python classes import numpy as np import random as rn import math import matplotlib.pyplot as plt import pylab from mpl_toolkits.mplot3d import Axes3D #import self produced classes import forcemodule as fm import init_sys # independent parameters dt = 0.004 N=2048 lpnum = 1000 density = 0....
551
8bb39149a5b7f4f4b1d3d62a002ab97421905ea1
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 处理与合约名字有关的变量 """ import re # 上期所 PRODUCTS_SHFE = {'cu', 'al', 'zn', 'pb', 'ni', 'sn', 'au', 'ag', 'rb', 'wr', 'hc', 'fu', 'bu', 'ru'} # 中金所 PRODUCTS_CFFEX = {'IF', 'IC', 'IH', 'T', 'TF'} # 郑商所 PRODUCTS_CZCE = {'SR', 'CF', 'ZC', 'FG', 'TA', 'WH', 'PM', 'RI', 'LR', 'JR',...
552
58aa72588357b18ab42391dfffbf2a1b66589edd
# pyOCD debugger # Copyright (c) 2006-2013,2018 Arm Limited # SPDX-License-Identifier: Apache-2.0 # # 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/LICENS...
553
18c2fe40b51ad1489d55aa2be068a1c4f381a2a5
import datetime from django.db import models from django.utils import timezone class Acoount(models.Model): first_name = models.CharField("Ім\'я", max_length=50) last_name = models.CharField('Прізвище', max_length=50) username = models.CharField('Псевдонім', max_length=50) email = models.CharField('Е...
554
3f8c13be547099aa6612365452926db95828b9a0
from setuptools import setup setup(name='RedHatSecurityAdvisory', version='0.1', description='Script that automatically checks the RedHat security advisories to see if a CVE applies', author='Pieter-Jan Moreels', url='https://github.com/PidgeyL/RedHat-Advisory-Checker', entry_points={'con...
555
5ef65ace397be17be62625ed27b5753d15565d61
from abc import ABC, abstractmethod class DatasetFileManager(ABC): @abstractmethod def read_dataset(self): pass
556
236dd70dec8d53062d6c38c370cb8f11dc5ef9d0
import thinkbayes2 as thinkbayes from thinkbayes2 import Pmf import thinkplot class Dice2(Pmf): def __init__(self, sides): Pmf.__init__(self) for x in range(1, sides + 1): self.Set(x, 1) self.Normalize() if __name__ == "__main__": d6 = Dice2(6) dices = [d6] * 6 th...
557
b9bd1c0f4a5d2e6eeb75ba4f27d33ad5fb22530e
# coding: utf-8 """ Upbit Open API ## REST API for Upbit Exchange - Base URL: [https://api.upbit.com] - Official Upbit API Documents: [https://docs.upbit.com] - Official Support email: [open-api@upbit.com] # noqa: E501 OpenAPI spec version: 1.0.0 Contact: ujhin942@gmail.com Generated by: https:...
558
d1dc807ecc92d9108db2c9bd00ee9781e174a1aa
from datetime import datetime from django.core import mail from entity_event import context_loader from entity_emailer.models import Email from entity_emailer.utils import get_medium, get_from_email_address, get_subscribed_email_addresses, \ create_email_message, extract_email_subject_from_html_content class E...
559
7a1be5c9c48413ba1969631e99ecb45cf15ef613
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.core.validators class Migration(migrations.Migration): dependencies = [ ('Registration', '0015_auto_20150525_1815'), ] operations = [ migrations.AlterField( ...
560
34b23e80b3c4aaf62f31c19fee0b47ace1561a8c
# cor = input('Escolha uma cor: ') # print(f"Cor escolhida {cor:=^10}\n" # f"Cor escolhida {cor:>10}\n" # f"Cor escolhida {cor:<10}\n") n1 = 7 n2 = 3 #print(f'Soma {n1+n2}') s = n1 + n2 m = n1 * n2 d = n1 / n2 di = n1 // n2 e = n1 ** n2 print(f's = {s}\n m = {m}\n d = {d:.2f}\n di = {di}\n e = {e}', end=...
561
c52d1c187edb17e85a8e2b47aa6731bc9a41ab1b
print ("Hello Workls!")
562
de3a4053b5b0d4d2d5c2dcd317e64cf9b4faeb75
from urllib.parse import quote from top_model import db from top_model.ext.flask import FlaskTopModel from top_model.filesystem import ProductPhotoCIP from top_model.webstore import Product, Labo from unrest import UnRest class Hydra(FlaskTopModel): def __init__(self, *args, **kwargs): super().__init__(*...
563
5b91b7025b0e574d45f95a0585128018d83c17ea
something1 x = session.query(x).filter(y).count() something2 y = session.query( models.User, models.X, ).filter( models.User.time > start_time, models.User.id == user_id, ).count() def something3(): x = session.query( models.Review, ).filter( models.Review.time < end_time, ).coun...
564
fe12f6d3408ab115c5c440c5b45a9014cfee6539
from django.urls import path,include from .import views urlpatterns = [ path('',views.home,name='home'), path('category/',include('api.category.urls')), path('product/',include('api.product.urls')), path('user/',include('api.user.urls')), path('order/',include('api.order.urls')), path('payment...
565
bb7910af5334641fd2db7146112afaff7a2e42b9
#!/usr/bin/env python # coding: utf-8 from __future__ import print_function import uuid import cgi import squareconnect from squareconnect.rest import ApiException from squareconnect.apis.transactions_api import TransactionsApi from squareconnect.apis.locations_api import LocationsApi from squareconnect.apis.customers...
566
ea1d62c4a8c406dde9bb138ee045be5e682fdbfe
class Wspak: """Iterator zwracający wartości w odwróconym porządku""" def __init__(self, data): self.data = data self.index = -2 self.i=len(data)-1 def __iter__(self): return self def __next__(self): if self.index >= self.i: raise StopIteration ...
567
ec64ddd01034debadb6674e71125f673f5de8367
from redis3barScore import StudyThreeBarsScore from redisUtil import RedisTimeFrame def test_score1() -> None: package = {'close': 13.92, 'high': 14.57, 'low': 12.45, 'open': 13.4584, 'symbol': 'FANG', 'timestamp': 1627493640000000000, ...
568
235bb1b9d4c41c12d7667a6bac48737464c685c7
from colorama import init, Fore, Style import tempConv #============================================================================# # TEMP CONVERSION PROGRAM: # #============================================================================# #------------------------...
569
d9f586bbb72021ee0b37ff8660e26b50d7e6a2d3
from django.http import HttpResponse from django.shortcuts import render def index(request): return render(request, 'ALR1.html') def search(request): return render(request, 'ALR2.html') def home(request): return render(request, 'ALR3.html') def pdf(request): pdfId = request.GET['id'] # pdf_data=open...
570
3d737d0ee9c3af1f8ebe4c6998ad30fa34f42856
from django.shortcuts import render from .. login.models import * def user(request): context = { "users" : User.objects.all(), "user_level" : User.objects.get(id = request.session['user_id']) } return render(request, 'dashboard/user.html', context) def admin(request): context = { ...
571
937d01eaa82cbfe07b20fae9320c554a0960d7b1
import sys sys.stdin = open('input.txt', 'rt') BLOCK_0 = 1 BLOCK_1 = 2 BLOCK_2 = 3 N = int(input()) X, Y = 10, 10 # x: 행 , y: 열A GRN = 0 BLU = 1 maps = [[0]*Y for _ in range(X)] dx = [1, 0] dy = [0, 1] def outMaps(x, y): global X, Y if 0<=x<X and 0<=y<Y: return False else: return True def meetBlock(x, y, ...
572
ebe546794131eddea396bd6b82fbb41aeead4661
# -*- coding: utf-8 -*- """ This is a simple sample for seuif.py License: this code is in the public domain Author: Cheng Maohua Email: cmh@seu.edu.cn Last modified: 2016.4.20 """ from seuif97 import * import matplotlib.pyplot as plt import numpy as np p1,t1 = 16, 535 p2,t2 = 3.56,315 h1 = pt2h(p1, t1) s1 = ...
573
906265182a9776fec5bad41bfc9ee68b36873d1e
#예외처리 문법을 활용하여 정수가 아닌 숫자를 입력했을때 에러문구가나오도록 작성.(에러문구:정수가아닙니다) try: x = int(input('정수를 입력하세요: ')) print(x) except: print('정수가 아닙니다.')
574
b7aa99e9e4af3bef4b2b3e7d8ab9bf159a093af6
#!/usr/bin/env python # -*- coding: UTF-8 -*- # # Copyright (C) 2011 Lionel Bergeret # # ---------------------------------------------------------------- # The contents of this file are distributed under the CC0 license. # See http://creativecommons.org/publicdomain/zero/1.0/ # ----------------------------------------...
575
aa4d872c6a529d8acf18f1c3b477bc1816ac2887
adict ={'name':'bob','age':23} print('bob' in adict) print('name'in adict) for key in adict: print('%s:%s'%(key,adict[key])) print('%(name)s:%(age)s'%adict)
576
ebc050544da69837cc2b8977f347380b94474bab
import os import numpy as np from keras.models import Sequential, Model from keras.layers import Dense, Dropout, Flatten, concatenate from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, Activation from keras.layers.normalization import BatchNormalization from keras.optimizers import SGD from keras....
577
ed2f3bbc7eb0a4d8f5ccdb7a12e00cbddab04dd0
_method_adaptors = dict() def register_dist_adaptor(method_name): def decorator(func): _method_adaptors[method_name] = func def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator def get_nearest_method(method_name, parser): """ all candi...
578
837534ebc953dae966154921709398ab2b2e0b33
# © MNELAB developers # # License: BSD (3-clause) from .dependencies import have from .syntax import PythonHighlighter from .utils import count_locations, image_path, interface_style, natural_sort
579
29c630b56eb56d91d1e917078138a2bbf562e0bf
import pyhs2 import sys import datetime i = datetime.datetime.now() # args if len(sys.argv) < 2: print "Run with python version 2.6" print "Requires arg: <orgId>" sys.exit() orgId = sys.argv[1] print "\n\nCreating document external ID manifest for Org ID: " + orgId ## strings fileLine = "%s\...
580
ce26ad27b7729164e27c845e2803a670b506bad8
# -*- coding: utf-8 -*- import scrapy class QuoteesxtractorSpider(scrapy.Spider): name = 'quoteEsxtractor' allowed_domains = ['quotes.toscrape.com'] start_urls = ['http://quotes.toscrape.com/'] def parse(self, response): for quote in response.css('.quote') : # print(quote.getall()...
581
09788cf04ab5190a33b43e3756f4dbd7d78977a5
# Copyright 2019-2020 the ProGraML authors. # # Contact Chris Cummins <chrisc.101@gmail.com>. # # 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...
582
be1bfa3e366d715d32613284924cf79abde06d41
# -*- coding: utf-8 -*- """ ----------------------------------------- IDEA Name : PyCharm Project Name : HelloWorld ----------------------------------------- File Name : task_worker Description : Author : Edwin Date : 2018/1/4 23:38 ----------------------------------------- Cha...
583
63d9a0fa0d0747762e65f6f1e85e53090035454c
from mongoengine import Document, StringField, BooleanField, ListField, Q import exceptions class Category(Document): id = StringField(primary_key=True) name = StringField() is_base_expenses = BooleanField(default=False) aliases = ListField(StringField()) @classmethod def get_category_by_tex...
584
7163be250ae3a22931de037cb6896c2e6d5f00a8
''' Encontrar el valor mas alto el mas rapido, el mas lento para eso son los algoritmos de optimizacion Para eso debemos pensar en una funcion que queramos maximizar o minimizar Se aplican mas que todo para empresas como despegar, en donde se pueden generar buenas empresas Empresas a la optimizacion...
585
b5275fc068526063fd8baf13210052971b05503f
from matasano import * ec = EC_M(233970423115425145524320034830162017933,534,1,4,order=233970423115425145498902418297807005944) assert(ec.scale(4,ec.order) == 0) aPriv = randint(1,ec.order-1) aPub = ec.scale(4,aPriv) print("Factoring...") twist_ord = 2*ec.prime+2 - ec.order factors = [] x = twist_ord for...
586
aa4fd27382119e3b10d2b57c9b87deff32b5c1ab
from final import getMood import pickle def get_mood(username_t,username_i): mapping={'sadness':'0,0,255','angry':'255,0,0','happy':'0,255,0','surprise':'139,69,19','neutral':'189,183,107','fear':'255,165,0'} #Sad: Blue, Angry: Red, Happy: Green, Surprise: Brown, Neutral:Yellow,Fear:Orange ...
587
dee1ab3adb7f627680410c774be44ae196f63f6c
#!/usr/bin/env python3 import base64 from apiclient import errors import os from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders import mimetypes def Get_Attachments(service, userId, msg_id, store_dir): """Get and store...
588
c4b9fdba9e9eeccc52999dab9232302f159c882a
# Created by MechAviv # [Maestra Fiametta] | [9390220] # Commerci Republic : San Commerci if sm.hasItem(4310100, 1): sm.setSpeakerID(9390220) sm.sendSayOkay("You can't start your voyage until you finish the tutorial quest!") else: sm.setSpeakerID(9390220) sm.sendNext("What? You threw away the coins wi...
589
5a103a4f72b9cd3ea3911aeefeeb2194c8ad7df0
#coding: utf-8 import mmh3 from bitarray import bitarray BIT_SIZE = 1 << 30 class BloomFilter: def __init__(self): # Initialize bloom filter, set size and all bits to 0 bit_array = bitarray(BIT_SIZE) bit_array.setall(0) self.bit_array = bit_array def add(self, val): ...
590
59d04ebd9a45c6a179a2da1f88f728ba2af91c05
from django.contrib import admin from pharma_models.personas.models import Persona admin.site.register(Persona)
591
ed5653455062cb3468c232cf0fa3f1d18793626a
from python_logging.Demo_CustomLogger import CustomLogger CustomLogger.init_log() # CustomLogger.info() log_str = '%s/%s/%s\n' % ("demo1", "demo2", "demo3") CustomLogger.info('[main]', log_str)
592
a9f3d5f11a9f2781571029b54d54b41d9f1f83b3
from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from app.models import * # Register your models here. class ProfileInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'profile' clas...
593
a9b2a4d4924dcdd6e146ea346e71bf42c0259846
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Greger Update Agent (GUA) module for the Greger Client Module """ __author__ = "Eric Sandbling" __license__ = 'MIT' __status__ = 'Development' # System modules import os, sys import shutil import logging import subprocess from threading import Event from threading im...
594
9bd659bb3bf812e48710f625bb65a848d3a8d074
#THIS BUILD WORKS, BUT IS VERY SLOW. CURRENTLY YIELDS A DECENT SCORE, NOT GREAT alphabet = "abcdefghijklmnopqrstuvwxyz" def author(): return "" def student_id(): return "" def fill_words(pattern,words,scoring_f,minlen,maxlen): foundWords = find_words(pattern,words,scoring_f,minlen,maxlen) f...
595
3212bb7df990ad7d075b8ca49a99e1072eab2a90
from typing import Type from sqlalchemy.exc import IntegrityError from src.main.interface import RouteInterface as Route from src.presenters.helpers import HttpRequest, HttpResponse from src.presenters.errors import HttpErrors def flask_adapter(request: any, api_route: Type[Route]) -> any: """Adapter pattern for ...
596
3a65565af4c55fa5479e323a737c48f7f2fdb8ce
''' python open() 函数用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。 更多文件操作可参考:Python 文件I/O。 函数语法 open(name[, mode[, buffering]]) 参数说明: name : 一个包含了你要访问的文件名称的字符串值。 mode : mode 决定了打开文件的模式:只读,写入,追加等。所有可取值见如下的完全列表。这个参数是非强制的,默认文件访问模式为只读(r)。 buffering : 如果 buffering 的值被设为 0,就不会有寄存。如果 buffering 的值取 1,访问文件时会寄存行。如果将 buffering 的值设为大于 1 的...
597
c0348fc5f51e6f7a191fea6d0e3cb84c60b03e22
''' Условие Дано два числа a и b. Выведите гипотенузу треугольника с заданными катетами. ''' import math a = int(input()) b = int(input()) print(math.sqrt(a * a + b * b))
598
8ac84aa29e9e4f3b85f1b3c27819feb5f41e8d8e
import os import factorStatFileCreator dirName = 'NoPerms/' dirName2 = 'AllPerms/' freqAgentDic = dict() lenAgentDic = dict() contAgentDic = dict() def freqModAvgFunc(dirName): fullList = factorStatFileCreator.directoryFreq(dirName) UA = dirName.split("/")[1] avgList = [] sum = 0 i = 0 while ...
599
f733885eed5d1cbf6e49db0997655ad627c9d795
from django import template register = template.Library() @register.filter(name='range') def filter_range(start, end=None): if end is None: return range(start) else: return range(start, end)