code
stringlengths
1
199k
from django.conf.urls import include from django.contrib import admin from django.urls import path app_name = "transmission" urlpatterns = [ path("admin/", admin.site.urls), path("torrents/", include("torrents.urls", namespace="torrents")), path("shows/", include("shows.urls", namespace="shows")), ]
"""Added a table for timed commands Revision ID: 4db5dc4bc98 Revises: 514f4b9bc74 Create Date: 2015-12-23 00:00:59.156496 """ revision = '4db5dc4bc98' down_revision = '514f4b9bc74' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql def upgrade(): ...
from colorama import Fore from rtxlib import info, error, debug from rtxlib.preprocessors.SparkPreProcessor import SparkPreProcessor def init_pre_processors(wf): """ we look into the workflows definition and run the required preprocessors """ if hasattr(wf, "pre_processors"): pp = wf.pre_processors ...
import ctypes import os STD_INPUT_HANDLE = -10 STD_OUTPUT_HANDLE= -11 STD_ERROR_HANDLE = -12 FOREGROUND_BLACK = 0x0 FOREGROUND_BLUE = 0x01 # text color contains blue. FOREGROUND_GREEN= 0x02 # text color contains green. FOREGROUND_RED = 0x04 # text color contains red. FOREGROUND_INTENSITY = 0x08 # text color is intensif...
""" Handling signals of the `core` app """ from django.dispatch import receiver from core import signals from reader import actions @receiver(signals.app_link_ready) def app_link_ready(sender, **kwargs): actions.create_app_link()
from nose.tools import * from dateutil.parser import parse as time_parse import yawhois class TestWhoisRegistryOmStatusReserved(object): def setUp(self): fixture_path = "spec/fixtures/responses/whois.registry.om/status_reserved.txt" host = "whois.registry.om" part = yawhois.r...
""" This modle will help you put your local file to QiNiu cloud storage, I use it to share files and pictures in my blog. """ import argparse try: import ConfigParser except ImportError: import configparser import os import qiniu.config import sys from qiniu import Auth from qiniu import BucketManager conf_file...
from flask import redirect, request from indico.modules.categories.compat import compat_category from indico.modules.categories.controllers.admin import RHManageUpcomingEvents from indico.modules.categories.controllers.display import (RHCategoryCalendarView, RHCategoryIcon, RHCategoryInfo, ...
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-usuario', version='0.4', packages=['usuario'], include_package_...
"""Helpful routines for regression testing.""" from base64 import b64encode from binascii import hexlify, unhexlify from decimal import Decimal, ROUND_DOWN import json import logging import os import random import re import time from . import coverage from .authproxy import AuthServiceProxy, JSONRPCException logger = l...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isBalanced(self, root: TreeNode) -> bool: def dfs(root): if root is None: return (True, 0) lb, lh = dfs(root.left) rb, rh...
"""List iSCSI Snapshots.""" import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import formatting from SoftLayer.CLI import helpers from SoftLayer import utils import click @click.command() @click.argument('iscsi-identifier') @environment.pass_env def cli(env, iscsi_identifier): """List iSCSI ...
""" This code is the correct implementation about constant. """ from const.base import Base class Apple(Base): __attrs__ = ["id", "name"] def __init__(self, id=None, name=None): self.id = id self.name = name class Banana(Base): __attrs__ = ["id", "name"] def __init__(self, id=None, name=...
import glob import os class File(object): def __init__(self, path): self.original = path self.abspath = os.path.abspath(path) def __str__(self): prefix = '' if self.isfile: prefix = 'file: ' elif self.isdir: prefix = 'dir: ' return prefix +...
from django.template.loader import render_to_string from tasks.const import STATUS_SUCCESS from .base import library @library.register('coverage') def coverage_violation(data): """Coverage violation parser :param data: task data :type data: dict :returns: dict """ data['status'] = STATUS_SUCCESS...
from .pypvwatts import PVWatts from .pvwattserror import PVWattsValidationError
from __future__ import absolute_import import datetime import decimal from io import BytesIO from openpyxl.xml.functions import tostring, xmlfile from openpyxl.utils.indexed_list import IndexedList from openpyxl.utils.datetime import CALENDAR_WINDOWS_1900 from openpyxl.styles import Style from openpyxl.styles.styleabl...
class Queue: def __init__(self): self.queue = [] def enqueue(self, item): self.queue.append(item) def dequeue(self, item): return self.queue.pop(0)
''' 第一种方式:使用os模块中的fork方式实现多进程 import os if __name__ == '__main__': print 'current Process (%s) start ...'%(os.getpid()) pid = os.fork() if pid < 0: print 'error in fork' elif pid == 0: print 'I am child process(%s) and my parent process is (%s)',(os.getpid(),os.getppid()) else: ...
import collections import itertools from marnadi.utils import cached_property, CachedDescriptor class Header(collections.Mapping): __slots__ = 'value', 'params' def __init__(self, *value, **params): assert len(value) == 1 self.value = value[0] self.params = params def __hash__(self):...
from folium.plugins.marker_cluster import MarkerCluster from folium.utilities import if_pandas_df_convert_to_numpy, validate_location from jinja2 import Template class FastMarkerCluster(MarkerCluster): """ Add marker clusters to a map using in-browser rendering. Using FastMarkerCluster it is possible to ren...
from django.core import validators from django.utils.deconstruct import deconstructible from django.utils.translation import gettext_lazy as _ @deconstructible class UsernameValidator(validators.RegexValidator): regex = r'^[\w.]+$' message = _( 'Enter a valid username. This value may contain only letter...
from __future__ import print_function, absolute_import, division import sys sys.path.append('../') import numpy as np import tt from tt.eigb import * import time """ This code computes many eigenvalus of the Laplacian operator """ d = 8 f = 8 A = tt.qlaplace_dd([d]*f) n = [2] *(d * f) r = [8] *(d * f + 1) r[0] = 1 r[d ...
from argparse import ArgumentParser from ansible_playbook_wrapper.command.play import PlayCommand def main(): parser = ArgumentParser() sub_parsers = parser.add_subparsers(help='commands') play_parser = sub_parsers.add_parser('play', help='play playbook') for arg_info in PlayCommand.ARGUMENT_INFO: ...
from logbook import Logger from ..core.local import get_current_conf from ..core.connection import autoccontext from .. import db from datetime import timedelta, datetime log = Logger(__name__) def del_inactive_queries(): conf = get_current_conf() with autoccontext(commit=True) as conn: before = db.get_...
import os import re import codecs import subprocess import tempfile import shutil from .tylogger import logger DEFAULT_ENCODING = 'utf16' class Strings(object): def __init__(self, encoding=DEFAULT_ENCODING, aliases=None): self.encoding = encoding if encoding else DEFAULT_ENCODING self.__references =...
from import_export import fields, resources class GamesPlayedResource(resources.Resource): game = fields.Field(attribute='game__name', column_name='game') time = fields.Field(attribute='time', column_name='time (hours)') num_players = fields.Field(attribute='num_players', column_name='num_players') clas...
"""linter_test_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home...
"""Main urls.py for the ``pythonsingapore.com`` project.""" from django.conf import settings from django.conf.urls.defaults import patterns, include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from cms.sitemaps impo...
"""anagram_solver.__main__: executed when directory is called as script.""" from .anagram_solver import main main()
import constants as c from gui.windows import VideoStream import socket import cv2 import urllib import numpy as np class Robot(object): def __init__(self, connection): self.connection = connection """ @type : Connections.ConnectionProcessEnd.RobotConnection """ self.socket = None se...
import re import os.path from io import open from setuptools import find_packages, setup PACKAGE_NAME = "azure-mgmt-servicefabric" PACKAGE_PPRINT_NAME = "Service Fabric Management" package_folder_path = PACKAGE_NAME.replace('-', '/') namespace_name = PACKAGE_NAME.replace('-', '.') with open(os.path.join(package_folder_...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wordproject', '0001_initial'), ] operations = [ migrations.AlterField( model_name='wordrecord', name='description', f...
from django.contrib import admin from polls.models import Question,Choice class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fields = ["question_text", "pub_date"] inlines = [ChoiceInline] list_display = ('question_text', 'pub_date', 'was_published_recent...
""" Django settings for webserver project. Generated by 'django-admin startproject' using Django 1.11.5. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os, ...
import datetime import queue import multiprocessing import pytest from honcho.printer import Message from honcho.manager import Manager from honcho.manager import SYSTEM_PRINTER_NAME HISTORIES = { 'one': { 'processes': {'foo': {}}, 'messages': (('foo', 'start', {'pid': 123}), ('...
from Tkinter import * import os import pdb import datetime lday = 04 lmonth = 10 class myDate: def __init__(self, year, month, day): self.date = datetime.datetime(year, month, day) self.updateString() def getMonthDay(self): lday = format(self.date.day, '02') lmonth = format(self....
import pytest @pytest.fixture def dns_sd(): from pymachinetalk import dns_sd return dns_sd @pytest.fixture def sd(): from pymachinetalk import dns_sd sd = dns_sd.ServiceDiscovery() return sd def test_registeringServicesFromServiceContainerWorks(dns_sd, sd): service = dns_sd.Service() discove...
import typing import twittback TweetSequence = typing.Sequence[twittback.Tweet] UserSequence = typing.Sequence[twittback.User]
from scrapyproject.models import (Cinema, Showing, ShowingBooking, Movie, db_connect, drop_table_if_exist, create_table, Session) from scrapyproject.items import (CinemaItem, ShowingItem, ShowingBookingItem, MovieItem) ...
"""Test methods for `zcode/math/math_core.py`. Can be run with: $ nosetests math/tests/test_math_core.py $ nosetests math/tests/test_math_core.py:TestMathCore.test_around $ python math/tests/test_math_core.py """ from __future__ import absolute_import, division, print_function, unicode_literals import numpy...
''' Unit tests for MergeTracker.py Verification tracking of which comps have been merged already works as expected and produces valid models. ''' import numpy as np import unittest from bnpy.learnalg import MergeTracker class TestMergeTracker(unittest.TestCase): def shortDescription(self): return None def setU...
""" A pretty lame implementation of a memoryview object for Python 2.6. """ from collections import Iterable from numbers import Integral import string from future.utils import istext, isbytes, PY3, with_metaclass from future.types import no, issubset class newmemoryview(object): # with_metaclass(BaseNewBytes, _builti...
import argparse import pickle import os import types import requests import json from importlib.machinery import SourceFileLoader import unittest TOKEN_PICKLE_FILE_NAME = "access_token" HOST = "theteamlab.io" ASSIGNMENT_NAME = "product_mix_problem.py" def getArgumentsParser(argv=None): parser = argparse.ArgumentPar...
import json import os import time from rottentomatoes import RT BOX_OFFICE_COUNTRIES = [ "us", "in", "uk", "nl", ] LIMIT = 50 # max allowed by rotten tomatoes OUTPUT_FILE = "download/more_movies.json" def main(): assert os.environ["RT_KEY"], "Your Rotten Tomatoes API key should ...
from msrest.serialization import Model class StorageProfile(Model): """Specifies the storage settings for the virtual machine disks. :param image_reference: Specifies information about the image to use. You can specify information about platform images, marketplace images, or virtual machine images. T...
import hashlib from typing import BinaryIO def get_fp_sha256(fp: BinaryIO) -> str: """ Get the SHA-256 checksum of the data in the file `fp`. :return: hex string """ fp.seek(0) hasher = hashlib.sha256() while True: chunk = fp.read(524288) if not chunk: break ...
from setuptools import setup setup(name='decision_tree', version='0.04', description='Practice implementation of a classification decision tree', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', ...
import os from redlib.api.system import sys_command, CronDBus, CronDBusError, is_linux, is_windows from ..util.logger import log from . import Desktop, DesktopError from . import gnome_desktop from . import feh_desktop if is_windows(): from .windows_desktop import WindowsDesktop def load_optional_module(module, packag...
try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='lkd', version='2', packages=['lkd', 'tests'], author='Karan Goel', author_email='karan@goel.im', maintainer='Karan Goel', maintainer_email='karan@goel.im', url='http://www.goel.im/...
""" http://adventofcode.com/day/17 Part 1 ------ The elves bought too much eggnog again - 150 liters this time. To fit it all into your refrigerator, you'll need to move it into smaller containers. You take an inventory of the capacities of the available containers. For example, suppose you have containers of size 20, ...
from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np class Unicorn(object): def __init__(self): import unicornhathd as unicorn unicorn.rotation(180) unicorn.brightness(0.75) def write_pixels(self, data): import unicornhathd as unic...
from unittest import TestCase, main from pitchpx.mlbam_util import MlbamUtil, MlbAmHttpNotFound __author__ = 'Shinichi Nakagawa' class TestMlbamUtil(TestCase): """ MLBAM Util Class Test """ def setUp(self): pass def tearDown(self): pass def test_get_content_200(self): """...
from django.conf.urls.defaults import patterns, url from . import tasks from . import views urlpatterns = patterns('', url(r'^$', views.index, name='layoutdemo_index'), )
import sys sys.path.append("..") from hackathon import ( RequiredFeature, Component, Context, ) from hackathon.database.models import ( Experiment, DockerContainer, HackathonAzureKey, PortBinding, DockerHostServer, ) from hackathon.constants import ( EStatus, PortBindingType, ...
""" Support for deprecation warnings when importing names from old locations. When software evolves, things tend to move around. This is usually detrimental to backwards compatibility (in Python this primarily manifests itself as :exc:`~exceptions.ImportError` exceptions). While backwards compatibility is very importan...
import sys sys.path.append("..") from data_mining.association_rule.base import rules, lift, support from data_mining.association_rule.apriori import apriori from data_mining.association_rule.liftmin import apriorilift from pat_data_association_rules import compare LE = "leite" PA = "pao" SU = "suco" OV = "ovos" CA = "c...
from django.conf import settings BACKEND_CLASS = getattr( settings, "COURRIERS_BACKEND_CLASS", "courriers.backends.simple.SimpleBackend" ) MAILCHIMP_API_KEY = getattr(settings, "COURRIERS_MAILCHIMP_API_KEY", "") MAILJET_API_KEY = getattr(settings, "COURRIERS_MAILJET_API_KEY", "") MAILJET_CONTACTSLIST_LIMIT = getatt...
import numpy as np import logic from unittest import TestCase import graphs import sympy from collections import namedtuple import random from attractors import find_num_attractors_onestage, \ vertex_model_impact_scores, stochastic_vertex_model_impact_scores, find_num_steady_states, \ find_attractors_dubrova, f...
import sys import os import warnings import ruamel.yaml as yaml from fnmatch import fnmatch __author__ = "Pymatgen Development Team" __email__ ="pymatgen@googlegroups.com" __maintainer__ = "Shyue Ping Ong" __maintainer_email__ ="shyuep@gmail.com" __version__ = "2019.7.2" SETTINGS_FILE = os.path.join(os.path.expanduser(...
from __future__ import unicode_literals import math import re from hub.formats import Format, Formatter from hub.structures.file import File from hub.structures.frame import OdhType class InterlisModelFormat(Format): name = 'INTERLIS1Model' label = 'INTERLIS 1 Modell' description = """ Modell für INTERL...
import json import os import glob import sys import logging from watson_developer_cloud import WatsonException if '__file__' in globals(): sys.path.insert(0, os.path.join(os.path.abspath(__file__), 'scripts')) else: sys.path.insert(0, os.path.join(os.path.abspath(os.getcwd()), 'scripts')) from discovery_setup_u...
row_key = "Rows" column_key = "Cols" special_keywords = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec', 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december', 'q1', 'q2', 'q3',...
import sys from PyQt4 import QtGui from PyQt4 import QtCore from PyQt4.QtGui import * import os class Window(QtGui.QMainWindow): def __init__(self): super(Window, self).__init__() self.filename = None self.initUI() def initUI(self): self.italic_flag = False self.underline...
from unittest import TestCase from PyProjManCore.task import Task class TestTaskOperationsExceptions(TestCase): """Test Exceptions for Task operations""" def test_append_duplicate_prereq(self): """Test appending duplicate prerequisites to a task, it should be unique""" root = Task("Root Task") ...
""" https://leetcode.com/explore/interview/card/top-interview-questions-hard/116/array-and-strings/827/ """ from unittest import TestCase from kevin.leet.product_except_self import Solution, SolutionOptimized class TestProductExceptSelf(TestCase): def _base_test_product_except_self(self, nums, expected): fo...
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('discussions', '0004_post_author'), ] operations = [ migrations.AlterField( ...
from pywps import Process from pywps.inout import LiteralInput, LiteralOutput from pywps.inout.literaltypes import ValuesReference class SimpleProcess(Process): identifier = "simpleprocess" def __init__(self): self.add_input(LiteralInput()) class UltimateQuestion(Process): def __init__(self): ...
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CMS.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
from RGT.XML.SVG.basicSvgNode import BasicSvgNode from RGT.XML.SVG.Attribs.conditionalProcessingAttributes import ConditionalProcessingAttributes from RGT.XML.SVG.Attribs.xlinkAttributes import XlinkAttributes from RGT.XML.SVG.Attribs.animationTimingAttributes import AnimationTimingAttributes class BaseAnimationNode(Ba...
from __future__ import unicode_literals from django.apps import AppConfig from django.db.models import signals from django.contrib.auth import get_user_model def populate_users(sender, **kwargs): User = get_user_model() for i in range(10): username = "user_{}".format(i+1) email = "{}@example.com...
import json import numpy as np import pytest import requests from mipframework.testutils import get_test_params from tests import vm_url from tests.algorithm_tests.test_logistic_regression import expected_file headers = {"Content-type": "application/json", "Accept": "text/plain"} url = vm_url + "LOGISTIC_REGRESSION" @p...
from ...highlevel.Environment import ContextEnvironment, Environment from . import r _default_bridges = { "r": { "code": r.bridge_r, "params": r.default_bridge_parameters, "environment": { "which": ["R", "Rscript"], "conda": """ dependencies: -...
r""" Utilities and helper classes/functions ====================================== This module contains two very important classes (Project and Workspace) as well as a number of helper classes. """ import logging as logging from .misc import * from ._settings import * from ._workspace import * from ._project import * l...
import logging from pajbot.apiwrappers.response_cache import ListSerializer from pajbot.apiwrappers.twitch.base import BaseTwitchAPI from pajbot.models.emote import Emote log = logging.getLogger(__name__) class TwitchKrakenV5API(BaseTwitchAPI): authorization_header_prefix = "OAuth" def __init__(self, client_cre...
import os from .input import VaspInput __author__ = "Guillermo Avendano-Franco" __copyright__ = "Copyright 2016" __version__ = "0.1" __maintainer__ = "Guillermo Avendano-Franco" __email__ = "gtux.gaf@gmail.com" __status__ = "Development" __date__ = "May 13, 2016" def read_incar(filename='INCAR'): """ Load the f...
import _plotly_utils.basevalidators class OpacitysrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="opacitysrc", parent_name="scattercarpet.marker", **kwargs ): super(OpacitysrcValidator, self).__init__( plotly_name=plotly_name, pare...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('umibukela', '0001_initial'), ] operations = [ migrations.CreateModel( name='SurveyType', fields=[ ('id', models.A...
import os from invoke import task @task def test(): os.system('coverage run --source tryagain -m py.test') os.system('coverage report') @task def register(production=False): target = 'pypi' if production else 'pypitest' os.system('python3 setup.py register -r %s' % target) @task def upload(production=Fa...
import os site_title = 'plum.J' site_description = '\'s blog' site_url = 'http://plumj.com' static_url = 'static' theme_name = 'sealscript' google_analytics = '' catsup_path = os.path.dirname(__file__) posts_path = os.path.join(catsup_path, '_posts') theme_path = os.path.join(catsup_path, 'themes', theme_name) common_t...
from kaneda.backends import LoggerBackend, ElasticsearchBackend from kaneda.queues import CeleryQueue from django_kaneda import settings # NOQA class TestDjango(object): def test_django_kaneda_with_backend(self, mocker, django_settings_backend): mocker.patch('django_kaneda.settings', django_settings_backen...
""" /properties/ /properties/:id/ /properties/groups/ /properties/groups/:id/ /properties/groups/:name/ """ from django.test import TestCase from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase from ..models import Property, PropertyGroup from ..defa...
""" Forms for the votes application. """ from django import forms from .models import Vote from base.forms import BaseModelForm class VoteForm(BaseModelForm): """ Form Vote model. """ score = forms.IntegerField(required=True) class Meta: model = Vote widgets = { 'user': f...
''' Usage: manager puzzle_load (--file <filename>) [--url <url>] manager puzzle_del (--name <name>) [--url <url>] manager puzzles [--url <url>] manager puzzleboards_clear [--url <url>] manager puzzleboard_consume [--async-url <url>] (--name <name>) [--size <size>] manager puzzleboard_pop (--name...
__author__ = 'Jason Mehring' BIND = None import os import sys import shutil import subprocess import logging if BIND is not None: import salt.config import salt.fileclient import salt.fileserver import salt.loader import salt.modules.saltutil import salt.pillar try: from subprocess i...
import json, codecs, re from abc import ABCMeta, abstractmethod from PIL import Image, ExifTags from witica.util import throw, sstr, suni RE_METAFILE = r'^meta\/[^\n]+$' RE_FIRST_ITEMID = r'(?!meta\/)[^\n?@.]+' RE_ITEMFILE_EXTENSION = r'[^\n?@\/]+' RE_ITEMID = r'^' + RE_FIRST_ITEMID + '$' RE_ITEMFILE = r'^' + RE_FIRST_...
import pytest from tinyrpc.protocols.jsonrpc import JSONRPCProtocol from tinyrpc import RPCErrorResponse @pytest.fixture(params=['jsonrpc']) def protocol(request): if 'jsonrpc': return JSONRPCProtocol() raise RuntimeError('Bad protocol name in test case') def test_protocol_returns_bytes(protocol): r...
''' Nonlinear optimization by use of Affine DualAveraging @author: Maximilian Balandat @date: May 13, 2015 ''' import numpy as np from .Domains import nBox class NLoptProblem(): """ Basic class describing a Nonlinear Optimization problem. """ def __init__(self, domain, objective): """ Constructor for th...
from celery.task import Task from ..notifications.contextmanagers import BatchNotifications class AsyncBadgeAward(Task): ignore_result = True def run(self, badge, state, **kwargs): # from celery.contrib import rdb; rdb.set_trace() with BatchNotifications(): badge.actually_possibly_aw...
class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ from collections import Counter nums2 = Counter(nums2) nums1 = Counter(nums1) ret = [] for i in nums1: ...
from PyQt5 import Qt class ViewportRectItem(Qt.QGraphicsObject): size_changed = Qt.pyqtSignal(Qt.QSizeF) def __init__(self): super().__init__() self.setFlags( Qt.QGraphicsItem.ItemIgnoresTransformations | Qt.QGraphicsItem.ItemSendsGeometryChanges | Qt.QGraphic...
''' usage: scrapy runspider recursive_link_results.py (or from root folder: scrapy crawl scrapy_spyder_recursive) ''' from scrapy.selector import Selector from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from scrapy.http import Request from scrapy_spider.items import ...
import gpiozero as GPIO from PiBlynk import Blynk from mytoken import * blynk = Blynk(token2) # <<<<<<<<<<<<<<<<<<<< USE DIFFERENT TOKED FROM OTHER END !!! def gpioOut_h(val, pin, gpioObj): gpioObj.value = val # control the LED print("Incoming GPIO OUT command:", pin, val) ledR = GPIO.LED(21) # gpiozero...
class Solution: """ @param n: An integers. @return: An integer which is the first bad version. """ def findFirstBadVersion(self, n): # write your code here start, end = 1, n if (n == 1): return 1 while (start <= end): i = (start + end) / 2 ...
import socket import time import random import threading import re import json import sys import os import platform import notify2 from urllib import request g_rid= b'265352' g_username= b'visitor42' g_ip= b'danmu.douyutv.com' g_port= 8601 g_gid= b'0' g_exit= False sysinfo = platform.system() def notify(title, message)...
import aaargh from app import Negi app = aaargh.App(description="Jinja2+JSON powered static HTML build tool") @app.cmd(help='Parse JSON and build HTML') @app.cmd_arg('-d','--data_dir',default='./data',help='JSON data dirctory(default:./data') @app.cmd_arg('-t','--tmpl_dir',default='./templates',help='Jinja2 template di...
from django.conf import settings from . import defaults __title__ = 'fobi.contrib.plugins.form_elements.fields.' \ 'select_multiple_with_max.conf' __author__ = 'Artur Barseghyan <artur.barseghyan@gmail.com>' __copyright__ = '2014-2017 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('get_settin...
import logging from queue import Queue from gi.repository import GObject from lib.commands import ControlServerCommands from lib.tcpmulticonnection import TCPMultiConnection from lib.response import NotifyResponse class ControlServer(TCPMultiConnection): def __init__(self, pipeline): '''Initialize server an...
from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Prof...
from gameinfo import * from porkglobals import * def genGameMap(): """This is an "abstract function" to hold this docstring and information. A GameMap function defines Places and connects all the Places it defines in a graph, but simpler graph than CommandGraph. It simply uses Place.nextnodes. A GameMap...