content stringlengths 4 20k |
|---|
"""Define a browser view for the Quiz content type. In the FTI
configured in profiles/default/types/*.xml, this is being set as the default
view of that content type.
"""
#import random
from Acquisition import aq_inner
from Products.Five.browser import BrowserView
from Products.Five.browser.pagetemplatefile import Vie... |
import search
from math import(cos, pi)
dallas_map = search.UndirectedGraph (dict(
Dallas=dict(Rockwall=25, Fortworth = 35),
Rockwall=dict (Dallas = 25, Richardson = 24),
Richardson=dict (Rockwall = 24, Coppell = 21),
Fortworth=dict (Dallas = 35, Azle = 17, Garland = 33, Frisco = 45),
Azle=dict (... |
#!/usr/bin/env python
from numpy import *
from numpy.random import *
from pylab import *
from pylab import rcParams
rcParams['text.usetex']=True
rcParams['text.latex.unicode']=True
rc('font',**{'family':'serif','serif':['Computer Modern Roman']})
c = 299792458
R = 10
f = array(arange(1e6,3e9+1e6,1e6))
M=500
#measur... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Provide interface to AFNI commands."""
from builtins import object
import os
import warnings
from ...utils.filemanip import split_filename
from ..base import (
CommandLine, traits, CommandLineInp... |
import gobject
import os
import re
class File(gobject.GObject):
def __init__(self, pathfilename, suffix):
if not pathfilename.endswith(suffix):
pathfilename = "%s%s" % (pathfilename, suffix)
gobject.GObject.__init__(self)
self.pathfilename = pathfilename
def readFile(self)... |
import re
from typing import Any, Dict, Mapping, Optional
import redis
import ujson
from django.conf import settings
from zerver.lib.utils import generate_random_token
# Redis accepts keys up to 512MB in size, but there's no reason for us to use such size,
# so we want to stay limited to 1024 characters.
MAX_KEY_LEN... |
import optparse, datetime, multiprocessing, os, signal, sys, threading, time
#------------------------------------------------------------------------------
# Lux imports
#------------------------------------------------------------------------------
try:
import pylux
except ImportError as err:
print('This script ... |
from gpu_tests import gpu_integration_test
import sys
class InfoCollectionTest(gpu_integration_test.GpuIntegrationTest):
@classmethod
def Name(cls):
return 'info_collection'
@classmethod
def AddCommandlineArgs(cls, parser):
super(InfoCollectionTest, cls).AddCommandlineArgs(parser)
parser.add_opti... |
import argparse
import os
import sys
from sgenlib import pdb
from sgenlib import gmx
if __name__ == "__main__":
# Setup a parser of the command-line arguments
parser = argparse.ArgumentParser(description="Program sort a structure file according to topology")
parser.add_argument('-f','--file',help="the input gr... |
# -*- coding: utf-8 -*-
class StrictDict(dict):
"""
A simple :class:`dict` subclass. It prevents overriding existing keys and lazy deletion.
"""
def __init__(self, seq=None, **kwargs):
super().__init__(seq=seq, **kwargs)
def __setitem__(self, key, value):
"""
Sets a key/va... |
# -*- coding: utf-8 -*-
"""'Framework' for edge-tpu devices.
TL;DR: install the `libedgetpu-max` library and add yourself to the
`plugdev`. Something like
sudo apt-get install libedgetpu1-max
sudo usermod -aG plugdev $(whoami)
Don't forget to login/logout and plug-out/plug-in the egde-tpu device
(or restart the... |
"""
A Python module for reading/writing/manipulating
SEG-Y formatted files
segy.readSegy : Read SEGY file
segy.read_reel_header : Get SEGY header
segy.read_trace_header : Get SEGY Trace header
segy.read_all_trace_headers : Get all SEGY Trace headers
segy.getSegyTrace : Get SEG... |
try:
import Queue as queue
except ImportError:
import queue
from helpers import Struct
class uiParameter(Struct):
"""uiParameter represents a single GUI element that is used to build a parameter window
in the UI (simulator event "make_param_window").
It has one parameter, ``type``, t... |
import logging
import os
from subscription_manager.cli import system_exit
from subscription_manager.cli_command.cli import CliCommand, conf
from subscription_manager.i18n import ugettext as _
from subscription_manager.release import ReleaseBackend, MultipleReleaseProductsError
from subscription_manager.repolib import ... |
from __future__ import absolute_import, division, print_function
import os
import os.path
import WatchmanTestCase
@WatchmanTestCase.expand_matrix
class TestMatch(WatchmanTestCase.WatchmanTestCase):
def test_match(self):
root = self.mkdtemp()
self.touchRelative(root, "foo.c")
self.touchRe... |
import squeakspace.common.util as ut
import squeakspace.common.util_http as ht
import squeakspace.server.db_sqlite3 as db
import squeakspace.common.squeak_ex as ex
import config
def post_handler(environ):
query = ht.parse_post_request(environ)
timestamp = ht.convert_int(ht.get_required(query, 'timestamp'), '... |
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from settings import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^accounts/login/$', 'django.contrib... |
from rest_framework import permissions
from django.conf import settings
import urlparse
class IsAuthorOrReadOnly(permissions.BasePermission):
"""
Object-level permission to only allow authors of an object to edit it.
Assumes the model instance has an `author` attribute.
This is the default class for... |
#!/usr/bin/env python
# coding:utf8
"""
Django settings for one_finger project.
Generated by 'django-admin startproject' using Django 1.8.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com... |
import functools
import hashlib
import time
import warnings
from oslo_log import log as logging
import requests
import six
from stevedore import driver as stevedore_driver
# from octavia_lib.amphorae.driver_exceptions import exceptions as driver_except
# from octavia_lib.amphorae.drivers import driver_base as driver_... |
import click
from tower_cli import models, resources
from tower_cli.cli import types
class Resource(models.Resource):
cli_help = 'Manage organizations within Ansible Tower.'
endpoint = '/organizations/'
deprecated_methods = ['associate_project', 'disassociate_project']
name = models.Field(unique=Tru... |
from MLE import *
data_path = '../Data/US/'
output = '../Paper/Result/ModelResult/'
############## US Credit Spread ##############
# past quarter only
# M1 xt1~xt
N = number_banks = 35
file_name = data_path+"DRISCFLM.csv"
dat = pd.read_csv(file_name)
dat.columns = ["DATE","DICSxt0"]
year = dat['DATE']
dat... |
# -*- coding: utf-8 -*-
"""
Testing that functions from compat work as expected
"""
from pandas.compat import (range, zip, map, filter, lrange, lzip, lmap,
lfilter, builtins, iterkeys, itervalues, iteritems,
next)
class TestBuiltinIterators(object):
@classme... |
### Slack JSON Processing
### v0.0.1
import json
import os
import datetime
import glob
settings = {
"source" : "",
"users" : "",
"output" : "",
"title" : "Example Title",
"keepChannelJoins" : False
}
class User(object):
''' User object used for ... |
"""
General testing utilities.
"""
import sys
from contextlib import contextmanager
import moto
from django.dispatch import Signal
from markupsafe import escape
from mock import Mock, patch
@contextmanager
def nostderr():
"""
ContextManager to suppress stderr messages
http://stackoverflow.com/a/1810086/8... |
"""
Integration tests for gated content.
"""
import ddt
from crum import set_current_request
from completion import waffle as completion_waffle
from edx_django_utils.cache import RequestCache
from milestones import api as milestones_api
from milestones.tests.utils import MilestonesTestCaseMixin
from lms.djangoapps.cou... |
# -*- coding: utf-8 -*-
"""
Created on Sep 25, 2012
@author: moloch
Copyright 2012 Root the Box
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/licen... |
'''
@date: 18/7/2017
@author: Universidad de Costa Rica
@maintainer: Luis Zarate Montero
@contact: <EMAIL>
@license: GPLv3
'''
from django.forms import modelform_factory
from corebase.rsa import get_hash_sum, decrypt
from corebase.models import ALGORITHM
from rest_framework import serializers
from django.core.excepti... |
__all__ = ["modify"]
import fileinput, sys, os
try:
from lxml import etree as ET
except:
print "Module lxml not found..."
sys.exit()
try:
from blessings import Terminal
except:
print "Module blessings not found..."
sys.exit()
t = Terminal()
## this method checks if the file has already been modified
# by ch... |
#most of this file was taken from turbogears default template
from hashlib import sha1
import os
try:
from hashlib import md5, sha1 as sha
except ImportError:
import md5
import sha
from datetime import datetime
from datetime import datetime
from sqlalchemy import *
from sqlalchemy.orm import relation, back... |
import imp
import logging
import time
from contextlib import contextmanager
from random import randint
import requests
from ...common.interfaces import AbstractPlugin
logger = logging.getLogger(__name__)
requests_logger = logging.getLogger('requests')
requests_logger.setLevel(logging.WARNING)
requests.packages.urll... |
import json
from twisted.trial.unittest import TestCase
from twisted.internet import reactor, defer, protocol
from twisted.web.client import Agent
from txstatsd.metrics.timermetric import TimerMetricReporter
from txstatsd.server import httpinfo
from txstatsd import service
class Dummy:
flush_interval = 10
... |
"""
Worker that receives input from Piped RDD.
"""
import os
import sys
import time
import socket
import traceback
# CloudPickler needs to be imported so that depicklers are registered using the
# copy_reg module.
from pyspark.accumulators import _accumulatorRegistry
from pyspark.broadcast import Broadcast, _broadcastR... |
"""
Author: Ron Lockwood-Childs
Licensed under LGPL v2.1 (see file COPYING for details)
Convert infix token stack into postfix (aka RPN) form.
Taken from the wikipedia page describing RPN:
https://en.wikipedia.org/wiki/Reverse_Polish_notation#Postfix_algorithm
While there are tokens to be read:
Read a token.
If ... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.sparse import csr_matrix, csc_matrix
from exceptions import NotImplementedError, StopIteration
class ESN(object):
"""Methods for training and running an echo state network
"""
def __init__(self, n_neurons, n_input, n_output):
self.n_neu... |
# -*- coding: utf-8 -*-
"""
sphinx.util.i18n
~~~~~~~~~~~~~~~~
Builder superclass for all builders.
:copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import gettext
from os import path
from collections import namedtuple
from babel.messages... |
from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='jsreport',
version='0.2.5',
description='Simple tool to pull basic reporting data out of JustServe (https://www.justserve.org/).',
long_description=readme(),
classifiers=[
... |
"""API for interfacing with Solum Conductor."""
from oslo_config import cfg
from solum.common.rpc import service
class API(service.API):
def __init__(self, transport=None, context=None):
cfg.CONF.import_opt('topic', 'solum.conductor.config',
group='conductor')
super(A... |
from lib.cuckoo.common.abstracts import Signature
class ModifiesUACNotify(Signature):
name = "modify_uac_prompt"
description = "尝试更改UAC提示行为"
severity = 3
categories = ["stealth"]
authors = ["Kevin Ross"]
minimum = "1.2"
def run(self):
reg_indicators = [
".*\\\\SOFTWARE\... |
"""Downloads comments web feed"""
from bibcrawl.utils.ohpython import *
from feedparser import parse as feedparse
from scrapy.contrib.pipeline.media import MediaPipeline
from scrapy.http import Request
from scrapy import log
class DownloadFeeds(MediaPipeline):
"""Downloads comments web feed"""
def get_media_reque... |
import zmq.green as zmq
from .protocol import Message
from locust.util.exception_handler import retry
class BaseSocket(object):
def __init__(self, sock_type):
context = zmq.Context()
self.socket = context.socket(sock_type)
self.socket.setsockopt(zmq.TCP_KEEPALIVE, 1)
self.socket.s... |
'''
Created on Jun 6, 2012
@author: Mark V Systems Limited
(c) Copyright 2012 Mark V Systems Limited, All rights reserved.
'''
from arelle import XPathContext, XbrlConst, XmlUtil
from arelle.ModelFormulaObject import (aspectModels, aspectStr, Aspect)
from arelle.ModelRenderingObject import (CHILD_ROLLUP_FIRST, CHILD_R... |
import logging
import traceback
from telegram import ParseMode, TelegramError
from telegram.ext import CommandHandler, Dispatcher, Updater
from model import init_database
from modules.admin import Admin
from modules.block_stickerpack import BlockStickerpack
from modules.forward import Forward
from modules.kto_zloy im... |
import numpy as np
from dynamic import Dynamic
class RawVolume(Dynamic):
"""Dynamic with manually-specified volume multiplier array"""
def __init__(self, segment, volume_frames):
"""Create a dynamic that manually specifies the volume
multiplier array.
:param segment: Segment ... |
import sqlite3
from plexpy import logger, helpers, monitor, users, plextv
from xml.dom import minidom
import plexpy
def extract_plexwatch_xml(xml=None):
output = {}
clean_xml = helpers.latinToAscii(xml)
try:
xml_parse = minidom.parseString(clean_xml)
except:
logger.warn("Error parsing... |
__version__ = "0.6"
import re, string
import Image, ImageFile
# XBM header
xbm_head = re.compile(
"\s*#define[ \t]+[^_]*_width[ \t]+(?P<width>[0-9]+)[\r\n]+"
"#define[ \t]+[^_]*_height[ \t]+(?P<height>[0-9]+)[\r\n]+"
"(?P<hotspot>"
"#define[ \t]+[^_]*_x_hot[ \t]+(?P<xhot>[0-9]+)[\r\n]+"
... |
"""Composite multiple naming schemes by chaining them together."""
# =============================================================================
# CONTENTS
# -----------------------------------------------------------------------------
# abdt_compositenaming
#
# Public Classes:
# Naming
# .make_tracker_branch_fr... |
from a10sdk.common.A10BaseClass import A10BaseClass
class Stats(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param session_created: {"description": "Session created", "format": "counter", "type": "number", "oid": "1", "optional": true, "size": "8"}
:param DeviceP... |
#! /usr/bin/env python
import os
import threading
import datetime
import json
import pickle
import flask
from functools import wraps
import httplib2
from apiclient.discovery import build
from oauth2client.file import Storage
# using Storage for a web app is high undesirable, but used for convenience at the moment
fr... |
try:
import unittest2 as unittest
except ImportError:
import unittest # noqa
from datetime import datetime, timedelta, date, tzinfo
from decimal import Decimal as D
from uuid import uuid4, uuid1
from cassandra import InvalidRequest
from cassandra.cqlengine.columns import TimeUUID
from cassandra.cqlengine.col... |
from re import compile
from django.conf import settings
from django.contrib.auth import logout
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.utils.deprecation import MiddlewareMixin
from geonode import geoserver
from geonode.utils import check_ogc_backend
from geonode.base.a... |
import os
import sys
here = os.path.dirname(__file__)
root = os.path.abspath(os.path.join(here, "..", "..", ".."))
sys.path.insert(0, root)
from tools.wpt import markdown
def test_format_comment_title():
assert '# Browser #' == markdown.format_comment_title("browser")
assert '# Browser (channel) #' == markdo... |
__all__ = [
"CmdParserNi.py",
"CmdParserNiCmd.py",
"CmdQuit",
"CmdReadCtlReg",
"CmdReadFpRegI",
"CmdReadFpRegX",
"CmdReadReg",
"CmdRtlCycle",
"CmdRtlData",
"CmdStep",
"CmdWriteCtlReg",
"CmdWriteFpRegI",
"CmdWriteFpRegX",
"CmdWriteReg",
"CmdWriteRegHi",
"C... |
from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtWidgets import QMainWindow
from gui.ui_gui import Ui_MainWindow
from gui.teleopWidget import TeleopWidget
from gui.cameraWidget import CameraWidget
from gui.communicator import Communicator
from gui.sensorsWidget import SensorsWidget
class MainWindow(QMainWindow, U... |
''' -- imports from installed packages -- '''
from django.shortcuts import render_to_response
from django.template import RequestContext
# from django.core.urlresolvers import reverse
from mongokit import paginator
try:
from bson import ObjectId
except ImportError: # old pymongo
from pymongo.objectid import Objec... |
#!/usr/bin/python
# vim: set fileencoding=utf-8 :
import unittest
import math
#import logging
#logging.basicConfig(level = logging.DEBUG)
import gi
gi.require_version('Vips', '8.0')
from gi.repository import Vips
Vips.leak_set(True)
unsigned_formats = [Vips.BandFormat.UCHAR,
Vips.BandFormat.U... |
#!/usr/bin/env python
import nici as nc # Load the nici package
import glob, os, sys
def run_nici(datadir=None, outputdir=None):
"""
Run the nici script.
datadir: Directory pathname holding the raw Flats and
object FITS files.
outputdir: Directory to put logs and output files.... |
"""
This code is directly derived from Eric Chio's (log0) solution
you can find the original code here:
https://github.com/log0/higgs_boson/blob/master/cleaned_model.py
"""
import csv;
import math;
import os;
import random;
import numpy as np;
### Metrics
def ams(s, b, br=10):
"""
Calculates approximate med... |
import urllib.request
import shutil
import zipfile
import os
import pickle
from collections import Counter
import numpy as np
url = 'http://mattmahoney.net/dc/text8.zip'
filename = 'text8.zip'
train_size = 99000000
if not os.path.isfile(filename):
print('Downloading text8 dataset...')
with url... |
import pathlib
import codecs
from django.conf import settings
import app_resources.models as models
from django.core.exceptions import ObjectDoesNotExist
import sharkdata_core
@sharkdata_core.singleton
class ResourcesUtils(object):
""" Singleton class. """
def __init__(self):
""" """
# ... |
"""add participant summary last modified
Revision ID: adb4ea532f1a
Revises: e4518d7d1af1
Create Date: 2018-03-08 13:23:40.782964
"""
import model.utils
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "adb4ea532f1a"
down_revision = "e4518d7d1af1"
branch_labels = None... |
import urllib
from dmlib.utils import webutils as web
from twisted.internet import reactor
import tempfile
from twisted.internet import defer
from twisted.internet import utils as twutils
import os, struct
import json, unicodedata
import logging
try:
log = logging.getLogger('Core').getChild('Clouds.Google.Speech')
... |
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import re
import os
import sys
try:
import IDF
except ImportError:
# This environment variable is expected on the host machine
test_fw_path = os.getenv("TEST_FW_PATH")
if test_fw_path and test_... |
"""
Shared code between AMQP based openstack.common.rpc implementations.
The code in this module is shared between the rpc implementations based on
AMQP. Specifically, this includes impl_kombu and impl_qpid. impl_carrot also
uses AMQP, but is deprecated and predates this code.
"""
import collections
import logging
i... |
import datetime
from copy import copy
from syscore.objects import (
missing_order,
success,
failure,
no_order_id,
no_children,
)
from syslogdiag.log_to_screen import logtoscreen
from sysexecution.orders.list_of_orders import listOfOrders
from sysexecution.orders.base_orders import Order, overFilled... |
from typing import Mapping, Tuple, Union
from uqbar.containers import UniqueTreeList
from .Attributes import Attributes
class Table(UniqueTreeList):
"""
A Graphviz HTML table.
::
>>> import uqbar.graphs
>>> table = uqbar.graphs.Table([
... uqbar.graphs.TableRow([
..... |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HSS1_then_CompleteLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HSS1_then_CompleteLHS
"""
# Flag this instance as compiled now
self.is_compiled = True
sup... |
# coding=utf-8
import tkinter as tk # 2
from tkinter import ttk # 3
win = tk.Tk()
# Modified Button Click function
def clickMe():
action.configure(text='Hello, ' + name.get() + ' ' +
numberChosen.get())
# Adding a Button
action = ttk.Button(win, text="Click Me!", command=clickMe)
... |
"""Train a LSTM on the IMDB sentiment classification task.
The dataset is actually too small for LSTM to be of any advantage
compared to simpler, much faster methods such as TF-IDF+LogReg.
"""
import numpy as np
import tensorflow as tf
from tensorflow_model_optimization.python.core.sparsity.keras import prune
from t... |
'''
Copyright (c) 2014-2015, The University of Sheffield.
This file is part of the SDQ rumour classification software
(see https://github.com/mlukasik/rumour-classification),
and is free software, licenced under the GNU Library General Public License,
Version 2, June 1991 (in the distribution as file LICENSE).
Crea... |
#! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
credit to: blog.hartleygroup.org/2015/11/08/numbering-figures-schemes-and-charts-in-pandoc... |
from html.parser import HTMLParser
from urllib.request import urlopen
from urllib import parse
class LinkParser (HTMLParser):
def handle_starttag(self,tag,attrs):
if tag=='a':
for(key,value) in attrs:
if key=='href':
newUrl=parse.urljoin(self.baseUrl, value)
... |
from tuned import exports
import tuned.logs
import tuned.exceptions
from tuned.exceptions import TunedException
import threading
import tuned.consts as consts
from tuned.utils.commands import commands
from tuned.utils.profile_recommender import ProfileRecommender
__all__ = ["Controller"]
log = tuned.logs.get()
class... |
# coding:utf-8
"""
DCRM - Darwin Cydia Repository Manager
Copyright (C) 2017 WU Zheng <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your o... |
'''craigslist blob package.
Purpose
=======
The blob service handles simple blob storage operations over HTTP and a
few other features such as TTLs for expiring blobs after some time. It is
designed with smart clients to remove any proxy nodes or blob location
lookups. It is multi-master with no single point of failu... |
from __future__ import unicode_literals
from __future__ import absolute_import
import tempfile
import mock
from bson import ObjectId
from alluratest.tools import assert_equal
from allura.lib.spam.stopforumspamfilter import StopForumSpamSpamFilter
class TestStopForumSpam(object):
def setUp(self):
self.... |
# -*- coding: utf-8 -*-
"""
https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-16.html#%_thm_2.60
"""
from Chapter2.themes.lisp_list_structured_data import car, cdr, cons, lisp_list, nil, print_lisp_list
from Chapter2.themes.sequences_as_conventional_interfaces import accumulate
def element_of_set(x, set):
"""... |
#Imports
import RPi.GPIO as GPIO
import time
import os
#variables
steeringPin = 15
motorPin = 18
GPIO.cleanup()
#Setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(steeringPin, GPIO.OUT)
GPIO.setup(motorPin, GPIO.OUT)
steeringPWM = GPIO.PWM(steeringPin, 50)
motorPWM = GPIO.PWM(motorPin, 50)
currentDut... |
"""
WSGI config for project_index project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICAT... |
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
# Used when printing objects as well as in Django admin
# __str__ in Python 3
def __unicod... |
import re
from lxml.cssselect import CSSSelector
from zope.testbrowser.browser import Browser, ListControl
from splinter.element_list import ElementList
from splinter.exceptions import ElementDoesNotExist
from splinter.driver import DriverAPI, ElementAPI
from splinter.cookie_manager import CookieManagerAPI
import mim... |
def can_read(user, world):
from yourworld.ywot.models import Whitelist
if world.public_readable:
return True
if not user.is_authenticated():
return False
if world.owner_id == user.id:
return True
if user.is_superuser:
return True
try:
Whitelist.objects.get... |
from numpy import (linspace, zeros, meshgrid, abs, empty, arange, int32,
unravel_index, dtype)
from multiprocessing import Pool
from ..solvers import solver_dict, get_solver_name
# attempt to import plotting libraries
try:
from matplotlib import pyplot
from mpl_toolkits.mplot3d import axes3... |
import os, time
from datetime import datetime, timedelta
from pytz import timezone
from flask import Flask
from flask import render_template
from flask import request
app = Flask(__name__)
app.debug = True
@app.route('/')
def main():
# Device gets passed through as mi_type
device = request.args.get('mi_type'... |
from base import Setting, SettingSet
from django.forms.widgets import Textarea, Select
from django.utils.translation import ugettext_lazy as _
from static import RENDER_CHOICES
SIDEBAR_SET = SettingSet('sidebar', 'Sidebar content', "Enter contents to display in the sidebar. You can use basic html tags.", 10, True)
S... |
from collections import defaultdict
from ..generic import file_get_content, StrThatIgnoreCase, ToStrMixin, \
file_sha1
DEFAULT_FILE_PATH = '/usr/portage/profiles/license_groups'
def first_and_other(lst):
return (lst[0], lst[1:]) if len(lst) > 0 else (None, [])
def split_without_comment(lic_str):
ci = ... |
# -*- coding: utf-8 -*-
import 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 'Peering'
db.create_table('app_peering', (
('id', self.gf('django.db.models.field... |
#!/usr/bin/python3
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, Job
from telegram import ReplyKeyboardMarkup, ParseMode
import logging
import os
import json
import logging
import functools
import yaml
import requests
import urllib.request
import io
import emoji
import socket
from datetime... |
from BaseWorker import *
class GooglePlusWorker(BaseWorker):
def __init__(self, parent = None):
super(GooglePlusWorker, self).__init__(parent)
def run(self):
self.progressSignal.emit(self.stampConfig)
if not self.filesModel.count():
return
client = self.stampCon... |
import subutai
import subuco
if subutai.GetOS() == 'w':
import subuw as subup
elif subutai.GetOS() == 'l':
import subul as subup
elif subutai.GetOS() == 'd':
import subud as subup
from time import sleep
def subutaistart():
coreFile = "core.ova"
vboxFile = subup.GetVirtualBoxName()
ubuntuFile =... |
import os
import subprocess
import pytest
from flexmock import flexmock
from devassistant import actions, exceptions
from devassistant.dapi import dapicli
from test.logger import LoggingHandler
class TestActions(object):
def setup_class(self):
self.ha = actions.HelpAction
def test_get_help_contain... |
# -*- coding: UTF-8 -*-
"""
Name: epilogue.py
Porpose: show dialog box before start process
Compatibility: Python3, wxPython Phoenix
Author: Gianluca Pernigotto <<EMAIL>>
Copyright: (c) 2018/2021 Gianluca Pernigotto <<EMAIL>>
license: GPL3
Rev: May.15.2020
Code checker:
flake8: --ignore F821, W504
pylint: --ign... |
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2016-2017 GiovanniMCMXCIX
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 without limitation the rights
to us... |
#!/usr/bin/env python
# encoding: utf-8
import os
import argparse as ap
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.ticker import MaxNLocator
from LibThese import Models as m
def king_temp_cmd(args):
fig = plt.figure(figsize=args.figsize)
ax = fig.add_subplot(111)
plt.setp(a... |
class glue_test:
callerName = "not set"
failCount = 0
testCount = 0
def __init__(self, callerName):
self.callerName = callerName
self.failCount = 0
self.testCount = 0
def check_fail(self, didFail):
self.testCount = self.testCount + 1
if didFail:
... |
import sys
from eventlet import patcher
from eventlet.hubs.hub import READ, WRITE, noop
from eventlet.hubs.poll import EXC_MASK, READ_MASK, WRITE_MASK
from eventlet.hubs.poll import Hub as _pollHub
from eventlet.hubs.epolls import Hub as _epollHub
from eventlet.hubs.selects import BAD_SOCK
from eventlet.hubs.selects im... |
import re
import urllib.parse
from datetime import timedelta
from pyramid.httpexceptions import HTTPFound
def get_current_profile(request):
"""
Return the currently selected :term:`Profile`.
First, parameters in the request are considered. If no parameter is
set, the profile cookie is used. As a fal... |
"""Utility script to install APKs from the command line quickly."""
import argparse
import glob
import logging
import os
import sys
import devil_chromium
from devil import devil_env
from devil.android import apk_helper
from devil.android import device_blacklist
from devil.android import device_errors
from devil.andro... |
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from builtins import range
from future import standard_library
standard_library.install_aliases()
import sys
PYTHON_VERSION = sys.version_info[:3]
PY2 = (PYTHON_VERSION[0... |
"""Runs hello_world.py, through hello_world.isolate, locally in a temporary
directory.
"""
import datetime
import getpass
import hashlib
import os
import shutil
import subprocess
import sys
import tempfile
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
def run(cmd):
print('Running: %s' % ' '.join(cmd))
c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.