content string |
|---|
import os
from selenium.common import exceptions
from selenium.webdriver.common import by
from selenium.webdriver.common import desired_capabilities as dc
from selenium.webdriver.remote import webelement
# Select the WebDriver to use based on the --selenium-phantomjs switch.
if os.environ.get('SELENIUM_PHANTOMJS'):
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb as mdb
import sys
import subprocess
import time
#Make sure you have run the 'scan_music_dir.php' script before running this
db_host = 'localhost'
db_user = 'root'
db_name = 'web_jukebox'
db_password = 'blizzard'
def shellquote(s):
return "'" + s.replace("... |
import struct
from constants import TYPE_TO_SIZE, TYPE_TO_STRUCT
class VMStack(object):
""" Stack of 4-byte works
"""
def __init__(self):
self._stack = []
def push_4(self, word):
assert(type(word) == str)
assert(len(word) == 4)
self._stack.append(word)
def pop_4(s... |
import robocup
import standard_play
import behavior
import constants
import main
import skills.move
import skills.capture
import enum
import evaluation
import tactics.coordinated_pass
import tactics.defense
class TwoSideAttack(standard_play.StandardPlay):
# Try to pass to the better target
# Soccer/gameplay/e... |
#!/usr/bin/python
import pygame
import tmx
import enemy
import sys
import flag
import kezmenu
import time
class ColorDisplay(pygame.sprite.Sprite):
tile_width = 28
tile_height = 28
tile_dimensions = (tile_width, tile_height)
tile_space = tile_width // 2
tile_enlargement = tile_space // 2
enlarg... |
"""
Tutorial Diagrams
-----------------
This script plots the flow-charts used in the scikit-learn tutorials.
"""
import numpy as np
import pylab as pl
from matplotlib.patches import Circle, Rectangle, Polygon, Arrow, FancyArrow
def create_base(box_bg = '#CCCCCC',
arrow1 = '#88CCFF',
... |
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Jayesh Kariya <<EMAIL>>`
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.mock import (
MagicMock,
patch,
NO_MOCK,
NO_MOCK_REASON
)
# Import Salt Li... |
from CIM15.IEC61970.Core.IdentifiedObject import IdentifiedObject
class ErpSiteLevelData(IdentifiedObject):
"""For a utility, general information that describes physical locations of organizations or the location codes and their meanings. This enables ERP applications to ensure that the physical location identifie... |
from mock.mock import patch, MagicMock
import os
import ca_common
import pytest
fake_container_binary = 'podman'
fake_container_image = 'docker.io/ceph/daemon:latest'
class TestCommon(object):
def setup_method(self):
self.fake_binary = 'ceph'
self.fake_cluster = 'ceph'
self.fake_containe... |
from __future__ import unicode_literals
import logging
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django.http import HttpResponse
from django.utils import six
from djblets.util.http import get_http_requested_mimetype, set_last_modified
from djblets.webapi.decorators import (webapi_lo... |
from django.db import models
from django.contrib.auth.models import User
from thumbs import ImageWithThumbsField
from django.template.defaultfilters import slugify
from froala_editor.fields import FroalaField
# Skills models
class Skills_categories(models.Model):
title = models.CharField(max_length=128)
slug = mode... |
"""
Compare performance of CatBoost internal categorical encoding with our categorical encoding.
Conclusion: CatBoost beats our encoders by large margin.
"""
import os
import pandas as pd
import numpy as np
from catboost import Pool, cv, CatBoostClassifier
import category_encoders
from examples.benchmarking_large imp... |
# -*- coding: utf-8 -*-
from docpool.doksys import _
from docpool.doksys.testing import DOCPOOL_DOKSYS_INTEGRATION_TESTING # noqa
from plone.app.testing import setRoles
from plone.app.testing import TEST_USER_ID
from zope.component import getUtility
from zope.schema.interfaces import IVocabularyFactory
from zope.schem... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Executes a subprocess on every page. Sends either the current page, or
# everything but the current page, to the child's standard input. The subprocess
# should score the text based on perplexity or similar measure.
#
# http://users.marjaniemi.com/seppo/
import argpar... |
from Motor import Motor
from Sensor import Sensor
import BrickPi as BP
from Scheduler import Scheduler
class BrickPiWrapper(Scheduler):
'''
This extends the Scheduler with functionality specific to the BrickPi
The constructor takes a map giving the class for the sensor connected to each port: 1 through 5.... |
"""Build and train mobilenet_v1 with options for quantization."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf
import tf_slim as slim
from tensorflow.contrib import quantize as contrib_quantize
from datasets import dat... |
from .loop import EventLoop
from .serialize import SType
from .base import weak_method
class ServerSubscription(EventLoop):
def __init__(self, device, ename=None, send=None, timeout=None):
name = "ServerSubscription.{}".format(device.name)
if ename is not None:
name += "." + ename
... |
__doc__ = """Submodule with handy utilities used throughout the package.
"""
# -------------------------------------------------------
# Miscellaneous Python functions for random task
# -------------------------------------------------------
import abc
import itertools as it
import numpy as np
from scipy.special impor... |
# coding=utf-8
"""Unittest for Earthquake Report."""
import os
import io
import shutil
import unittest
from jinja2.environment import Template
from qgis.core import QgsCoordinateReferenceSystem
from safe.definitions.constants import ANALYSIS_SUCCESS, INASAFE_TEST
from safe.definitions.reports.components import (
... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import subprocess
import sys
from textwrap import dedent
from pants.base.cmd_line_spec_parser import CmdLineSpecParser
from pants.binaries import binary_uti... |
"""
Native Microsoft Windows sockets (L3 only)
## Notice: ICMP packets
DISCLAIMER: Please use Npcap/Winpcap to send/receive ICMP. It is going to work.
Below is some additional information, mainly implemented in a testing purpose.
When in native mode, everything goes through the Windows kernel.
This firstly requires ... |
from paramiko.common import (
linefeed_byte_value, crlf, cr_byte, linefeed_byte, cr_byte_value,
)
from paramiko.py3compat import BytesIO, PY2, u, b, bytes_types
from paramiko.util import ClosingContextManager
class BufferedFile (ClosingContextManager):
"""
Reusable base class to implement Python-style fi... |
import os
import sys
import logging
import base64
import time
from radiator import Broker
from radiator.reactor import GeventReactor
def getenv(key, default):
if os.environ.has_key(key):
return os.environ[key]
else:
return default
class ScenarioLogHandler(logging.Handler):
errors = []
... |
#!/usr/bin/python3
#
# implementation of equations found on this post about lens distortion
# https://math.stackexchange.com/questions/302093/how-to-calculate-the-lens-distortion-coefficients-with-a-known-displacement-vect
#
import sys
import math
import numpy as np
#import lmfit
def compute_r(x,y):
# functio... |
{
'name': "Equivalent products",
'version': '1.0',
'category': 'Sales Management',
'description': """This module adds tags an equivalent products for sales""",
'author': 'Pexego Sistemas Informáticos',
'website': '',
"depends" : ["base",
"product",
"sale",
... |
from axelrod import Player
class AntiCycler(Player):
"""
A player that follows a sequence of plays that contains no cycles:
C CD CCD CCCD CCCCD CCCCCD ...
"""
name = 'AntiCycler'
classifier = {
'memory_depth': float('inf'),
'stochastic': False,
'inspects_source': False... |
# -*- coding: utf-8 -*-
""""
ProjectName: pydemi
Repo: https://github.com/chrisenytc/pydemi
Copyright (c) 2014 Christopher EnyTC
Licensed under the MIT license.
"""
# Dependencies
from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper
def cors(origi... |
# coding: utf-8
#
# Make some XML for great profit.
#
# cf.
# * http://examples.akomantoso.org/
# * http://examples.akomantoso.org/usage.html
# * http://examples.akomantoso.org/alphabetical.html
#
import os
import csv
import sys
from unicodecsv import DictReader
import unicodedata
from lxml import etree
DATA_PATH = o... |
import os
import time
import gzip
import tarfile
import zipfile
import subprocess
from collections import OrderedDict
import lpms
from lpms import out
from lpms import utils
class Archive:
def __init__(self, location, partial):
self.location = location
self.partial = partial
def extr... |
"""System plugin."""
import os
import platform
import re
from io import open
from glances.compat import iteritems
from glances.plugins.glances_plugin import GlancesPlugin
# SNMP OID
snmp_oid = {'default': {'hostname': '1.3.6.1.2.1.1.5.0',
'system_name': '1.3.6.1.2.1.1.1.0'},
'neta... |
"""
10-19-15
"""
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty, ListProperty
from kivy.lang import Builder
class Arrow(Widget):
start = ObjectProperty(None)
end = ObjectProperty(None, allownone=True)
start_pos = ListProperty([0, 0])
end_pos = ListProperty([0, 0])
... |
import os, sys, signal
import benchchildren
import modules
# Set the signal handler
def close(*args):
benchchildren.terminate()
print
print 80 * '-'
print "INTERRUPT TRIGGERED"
print "Exiting"
exit(0)
signal.signal(signal.SIGINT, close)
def print_help():
print """\
Usage: numbench conffil... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, print_function
from arpeggio.cleanpeg import ParserPEG
from arpeggio import visit_parse_tree
from visitor import Visitor
import sys
#Used finder.py module to recursively finding php tokens
def parse(filename,... |
class PathSet:
def __init__(self, pathset):
pathset.sort()
self.pathset = set(tuple(path) for path in pathset)
self.hash = hash(tuple(self.pathset))
def __eq__(self, other):
return self.pathset == other.pathset
def __hash__(self):
return self.hash
def conj(sel... |
"""Bootstrap a buildout-based project
Simply run this script in a directory containing a buildout.cfg.
The script accepts buildout command-line options, so you can
use the -c option to specify an alternate configuration file.
"""
import os, shutil, sys, tempfile, urllib2
from optparse import OptionParser
tmpeggs = t... |
import json
import mock
import os
import StringIO
import glance_store
from oslo_concurrency import processutils
from oslo_config import cfg
from glance.async.flows import convert
from glance.async import taskflow_executor
from glance.common.scripts import utils as script_utils
from glance.common import utils
from gla... |
import davivienda_format
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
"""
Django settings for bookmarks project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
... |
"""
Module for highlighting picked atoms/defects
@author: Chris Scott
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import vtk
################################################################################
class AtomHighlighter(vtk.vtkActor):
"""
Atom highlighter
... |
import json
import mock
import testtools
from openstack.message.v1 import message
CLIENT = '3381af92-2b9e-11e3-b191-71861300734c'
QUEUE = 'test_queue'
FAKE = {
'ttl': 300,
'body': {'key': 'value'}
}
FAKE_HREF = {
'href': '/v1/queues/test_queue/messages/1234',
'ttl': 300,
'body': {'key': 'value'}
... |
# -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis import gui
class IdentifyTool(gui.QgsMapToolIdentify):
avalableChanged = pyqtSignal(bool)
identified = pyqtSignal(list)
def __init__(self, iface):
gui.QgsMapToolIdentify.__init__(self, iface.mapCanvas())
... |
import os
from whoosh.qparser import QueryParser
from whoosh.index import create_in, open_dir
from schema import MovieSchema
class HamsterIndex(object):
def __init__(self, path):
if not os.path.exists(path):
os.mkdir(path)
self.index = create_in(path, MovieSchema)
self.inde... |
"""This module represents the N'Ko language.
.. seealso:: http://en.wikipedia.org/wiki/N'Ko_language
"""
import re
from translate.lang import common
def reverse_quotes(text):
def convertquotation(match):
return u"”%s“" % match.group(1)
return re.sub(u'“([^”]+)”', convertquotation, text)
class nqo... |
import os, sys, multiprocessing, subprocess
from build_util import *
if __name__ == "__main__":
cfg = cfg_from_argv(sys.argv)
bi = build_info(cfg.compiler, cfg.archs, cfg.cfg)
print("Starting build project: " + build_cfg.project_name + " ...")
additional_options = "-DCFG_PROJECT_NAME:STRING=\"%s\"" % build_cfg.pr... |
# coding: utf-8
"""Videoplayer and Radio."""
import logging
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from threading import Thread
logger = logging.getLogger('oxo')
def inline_keyboard(options):
"""Return an inline Keyboard given a dictionary of callback:display pairs."""
rv = InlineK... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from . import models
from .utils import add_prefix_to_path, default_reverse
class TemplatePrefixMixin(object):
... |
import time
from core.logger import Logger
class ModelDal(object):
def __init__(self, connection_pool):
self.logger = Logger(self.__class__.__name__).get()
self.connection_pool = connection_pool
def model_exists(self, model):
ret_model = self.get_model(model['style'], model['name'], m... |
#!/usr/bin/env python3
"""
Some analysis tasks produce an interleaved FASTA or FASTQ file (such as digital normalization).
Use this script to split that interleaved file back out into R1, R2 and singleton files.
The read mates will be kept in pairwise order within the R1 and R2 files.
The -o option defines the base ... |
import logging
logger = logging.getLogger('UWOshSuccess: setuphandlers')
import os
import transaction
from config import product_globals
from Globals import package_home
from Products.ATVocabularyManager.config import TOOL_NAME as ATVOCABULARYTOOL
from Products.CMFCore.utils import getToolByName
from Products.Externa... |
from distutils.core import setup
from setuptools import find_packages
# versioning
MAJOR = 1
MINOR = 0
MAINT = 8
ISRELEASED = True
VERSION = '%d.%d.%d' % (MAJOR, MINOR, MAINT)
PACKAGES = find_packages()
# falass setup
setup(
name='falass',
version=VERSION,
description='Neutron and X-ray Reflectometry f... |
# -*- coding: utf-8 -*-
"""
Result: https://www.youtube.com/watch?v=Qu7HJrsEYFg
This is how we can imagine knights dancing at the 15th century, based on a very
serious historical study here: https://www.youtube.com/watch?v=zvCvOC2VwDc
Here is what we do:
0- Get the video of a dancing knight, and a (Creative Commons... |
# coding=utf-8
"""Definitions about earthquake."""
import numpy
from safe.utilities.i18n import tr
from safe.utilities.settings import setting
__copyright__ = "Copyright 2016, The InaSAFE Project"
__license__ = "GPL version 3"
__email__ = "<EMAIL>"
__revision__ = '$Format:%H$'
def earthquake_fatality_rate(hazard_... |
import imp
import os
import json
from setuptools import setup, find_packages
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
PACKAGE_DIR = os.path.join(BASE_DIR, 'caravel', 'static', 'assets')
PACKAGE_FILE = os.path.join(PACKAGE_DIR, 'package.json')
with open(PACKAGE_FILE) as package_file:
version_string = j... |
from django.contrib import admin
from audit_log.models import AuditLogEntry, AuditLogEntryPermission
class AuditLogEntryAdmin(admin.ModelAdmin):
def get_action_flag(self, obj):
if obj.action_flag == 1: # additon
return "<span style='color: green;'>ADDED</span>"
elif obj.action_flag =... |
from test.support.integration import SoledadTestBase, MailBuilder
from twisted.internet import defer
import json
import pkg_resources
class ContactsTest(SoledadTestBase):
@defer.inlineCallbacks
def test_TO_CC_and_BCC_fields_are_being_searched(self):
input_mail = MailBuilder().with_tags(['important'])... |
from Screens.Screen import Screen
from Screens.Standby import TryQuitMainloop
from Screens.MessageBox import MessageBox
from Components.ActionMap import NumberActionMap
from Components.Pixmap import Pixmap
from Components.Sources.StaticText import StaticText
from Components.MenuList import MenuList
from Componen... |
#!/bin/env python
import psync
import argparse
import pprint
def inspect_workers():
workers = {}
i = psync.app.control.inspect()
a = i.active()
if a:
for k, activelist in a.iteritems():
if k not in workers:
workers[ k ] = { 'num_active': 0, 'num_reserved': 0 }
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from autoslug import AutoSlugField
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from simple_history.models import HistoricalRecords
from com... |
"""
This module include the cost sensitive Bayes minimum risk method.
"""
# Authors: Alejandro Correa Bahnsen <<EMAIL>>
# License: BSD 3 clause
import numpy as np
from sklearn.base import BaseEstimator
from ..probcal import ROCConvexHull
from ..metrics import cost_loss
class BayesMinimumRiskClassifier(BaseEstimato... |
# -*- coding: utf-8 *-*
import math, random
def center_image(image):
"""Sets an image's anchor point to its center"""
image.anchor_x = image.width / 2
image.anchor_y = image.height / 2
return image
def random_pos(screensize=(800, 600)):
"""
returns a random position between 0 and screensize... |
import os.path
import collections
import urllib.parse
import pkg_resources
import itertools
import tempfile
import subprocess
import skbio
import skbio.diversity
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from statsmodels.sandbox.stats.multicomp import multipletests
import qiime2
import ... |
import src
"""
a dummy for an interface with the mech communication network
bad code: this class is dummy only and basically is to be implemented
"""
class Commlink(src.items.Item):
type = "CommLink"
"""
call superclass constructor with modified paramters
"""
def __init__(self):
super()... |
# Import the function for downloading web pages
from urllib import urlopen
# Import the regular expression function
from re import findall
# Import the Tkinter functions
from Tkinter import *
# Import a constructor for converting byte data to character strings
from StringIO import StringIO
# Import the Python Im... |
from redis import Redis
from rq_scheduler import Scheduler
from datetime import datetime
import app.controller
import os, argparse, sys
from utils.common import PageType
#documentation at
#https://github.com/ui/rq-scheduler
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
def main():
parser = argparse.Arg... |
from traits.api import List, Str
from traitsui.qt4.basic_editor_factory import BasicEditorFactory
from traitsui.qt4.editor import Editor
from pychron.core.ui.qt.dag import DAGraphView
class _DAGEditor(Editor):
selected_commits = List
def init(self, parent):
self.sync_value(self.factory.selected, 'se... |
import theano
import theano.tensor as T
import lasagne as nn
from lasagne.layers import batch_norm as bn, Conv2DLayer, MaxPool2DLayer
from lasagne.layers import Upscale2DLayer, InputLayer
import os
import utils as u
def build_fcn_segmenter(input_var, shape, version=2):
ret = {}
if version == 2:
ret[... |
"""
Describes additional properties of cobbler fields otherwise
defined in item_*.py. These values are common to all versions
of the fields, so they don't have to be repeated in each file.
Copyright 2009, Red Hat, Inc and Others
Michael DeHaan <michael.dehaan AT gmail>
This program is free software; you can redistri... |
from __future__ import print_function
import sys
from lxml import etree
from argparse import ArgumentParser
from androguard.core import androconf
from androguard.core.bytecodes import apk
from androguard.util import read
def main(inp, outp=None):
ret_type = androconf.is_android(inp)
if ret_type == "APK":
... |
import unittest2 as unittest
from keystone.test.functional import common
class ValidateToken(common.FunctionalTestCase):
def setUp(self, *args, **kwargs):
super(ValidateToken, self).setUp(*args, **kwargs)
self.tenant = self.create_tenant().json['tenant']
self.user = self.create_user_with_... |
from polyaxon.utils.list_utils import to_list
from polyaxon.utils.string_utils import strip_spaces
def get_container_command_args(config):
def sanitize_str(value):
if not value:
return
value = strip_spaces(value=value, join=False)
value = [c.strip().strip("\\") for c in value i... |
from openerp import _, models, fields, api, exceptions
import logging
_logger = logging.getLogger(__name__)
try:
import ldap
import ldap.modlist
except ImportError:
_logger.debug('Can not `from ldap.filter import filter_format`.')
class ResUsers(models.Model):
_inherit = 'res.users'
ldap_entry_... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
This is for formatting and validating phone numbers, etc. in Taxidi.
"""
emailRegex = "^[a-zA-Z0-9._%-+]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$"
import re
import string
from wx import NullColour
def Translator(frm='', to='', delete='', keep=None):
"""
Wrapper around... |
from setuptools import setup
from pip.req import parse_requirements
install_reqs = parse_requirements("requirements.txt", session=False)
reqs = [str(ir.req) for ir in install_reqs]
POST="DEV"
BUILD="0"
VERSION="0.7"
setup(
# Application name:
name="sparktk",
version="{0}-{1}{2}".format(VERSION, POST, ... |
from typing import Dict, Any, List, Optional
import logging
from eve.auth import BasicAuth
from flask_babel.speaklater import LazyString
from typing_extensions import Literal
import superdesk
from eve.utils import config
log = logging.getLogger(__name__)
# elastic mapping helpers
not_indexed = {"type": "string", "i... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import markitup.fields
import mptt.fields
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('sites', '0001_initial'),
('au... |
'''
Created on 11.04.2015
@author: marscher
'''
from pyemma.coordinates.data.interface import ReaderInterface
import numpy as np
import csv
class _csv_chunked_numpy_iterator:
"""
returns numpy arrays by combining multiple lines to chunks
"""
def __init__(self, reader, chunksize=1, skiprows=None, he... |
import unittest
import mixture
import ghmm
import numarray
import copy
import random
import mixtureHMM
class HMMTests(unittest.TestCase):
def setUp(self):
# building generating models
self.DIAG = mixture.Alphabet(['.','0','8','1'])
A = [[0.3, 0.6,0.1],[0.0, 0.5, 0.5],[0.4,0.2,0.4]]
... |
# encoding: utf-8
'''
Sublime text de-Compressor
View compressed files ( gzip, bzip2 ) content in sublime text
Support verified for
- gzip (Sublime Text 2)
- bzip (Sublime Text 3)
- lzma (Sublime Text 4)
'''
from os import remove, rmdir, stat, rename
from os.path import basename, join, dirname, exists
import sys
impo... |
import numpy as np
import theano
import theano.tensor as T
import gzip, cPickle
import sys
import matplotlib.pyplot as plt
f = gzip.open('mnist.pkl.gz', 'rb')
train_set, valid_set, test_set = cPickle.load(f)
f.close()
X_train = np.array(train_set[0])
y_train = np.array(train_set[1])
X_test = np.array(test_set[0])
y_t... |
"""IP pool related commands"""
# pylint: disable=W0401,W0614
# W0401: Wildcard import ganeti.cli
# W0614: Unused import %s from wildcard import (since we need cli)
import textwrap
import itertools
from ganeti.cli import *
from ganeti import constants
from ganeti import opcodes
from ganeti import utils
from ganeti im... |
"""
Python argparse helper for shell script.
"""
import argparse
def main():
"""
This function enables flexible argument parsing and outputs proper
parameters that can be processed easily be the dank shell script.
"""
parser = argparse.ArgumentParser(prog='./danker.sh',
... |
from elemental_core import NO_VALUE
from elemental_core.util import process_elemental_class_value
from ._resource_type import ResourceType
from ._property_changed_hook import PropertyChangedHook
from ._resource_reference import ResourceReference
class FieldType(ResourceType):
@property
def value_resolution_o... |
from devilry.apps.core import models
from devilry.simplified import FieldSpec, FilterSpec, FilterSpecs, ForeignFilterSpec
class SimplifiedCandidateMetaMixin(object):
""" Defines the django model to be used, resultfields returned by
search and which fields can be used to search for a Candidate object
using... |
from __future__ import print_function
from __future__ import unicode_literals
from localization import N_
from outputable import Outputable
import terminal
import textwrap
DEFAULT_EXTENSIONS = ["java", "c", "cc", "cpp", "h", "hh", "hpp", "py", "glsl", "rb", "js", "sql"]
__extensions__ = DEFAULT_EXTENSIONS
__located_e... |
# -*- coding: utf-8 -*-
'''
Manage groups on Mac OS 10.7+
'''
# Import python libs
from __future__ import absolute_import
try:
import grp
except ImportError:
pass
# Import Salt Libs
import salt.utils
import salt.utils.itertools
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.m... |
from _datetime import datetime
from base64 import b64decode
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.shortcuts import render
# Pour importer du html ou du json
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_e... |
"""Module for handling server-side-include formatted files
This module is quite incomplete. I might complete it with more
features as I need them. It will probably never be entirely compliant
with Apache's version due to architectural differences.
"""
import sys, os, io, time, logging, functools
from . import wsgiuti... |
from flask import *
import pandas as pd
from application import *
from application.default_settings import _basedir
roteiro = pd.read_excel('Roteiro_Mob_Urb_16_05_04.xlsx')
roteiro = roteiro.fillna('')
videos_info = pd.read_csv('../video_all_info.csv', quotechar='"')
videos_info = videos_info.fillna('')
db.create_al... |
#!/usr/bin/env python
"""
Upload random values to non-repeating forms in order to force Redcap autocalc.
DO NOT USE THIS ON REPEATING FORMS.
"""
import argparse
import pdb
import sibispy
from sibispy import sibislogger as slog
from sibispy import bulk_operations as bulk
import random
import redcap as rc
from typing im... |
import pytest
from django.test import Client
from django.urls import reverse
from model_bakery import baker
from pythonpro.django_assertions import dj_assert_contains
@pytest.fixture
def resp(client: Client):
return _resp(client)
def _resp(client):
"""Plain function to avoid _pytest.warning_types.RemovedIn... |
from subprocess import check_output, CalledProcessError
from tempfile import TemporaryDirectory
from zipfile import ZipFile
import argparse
import os
import re
import sys
def check_log(logfile):
"""
Read and check logfile in search for the pattern 'Benchmark_Score'.
Returns:
False if the pattern ... |
"""
This code solves the problem based on a need vs availability.
Ranking is based on distance of cities (takers) from resources.
As far as I remember the algorithm was ranking all the points in the first round and then each city
starts taking the closest resources in each round until there is nothing left!
args:
... |
#!/usr/bin/env python
import click
import os
import tempfile
from werkzeug.serving import run_simple
def make_app():
from shorty.application import Shorty
filename = os.path.join(tempfile.gettempdir(), "shorty.db")
return Shorty('sqlite:///{0}'.format(filename))
def make_shell():
from shorty import ... |
# -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext_lazy as _
from markedit.widgets import MarkEdit
from symposion.proposals.kinds import register_proposal_form
from .models import (PyConProposalCategory, PyConTalkProposal,
PyConTutorialProposal, PyConP... |
"""
Identifier Class for always
"""
import pscheduler
def data_is_valid(data):
"""Check to see if data is valid for this class. Returns a tuple of
(bool, string) indicating valididty and any error message.
"""
if isinstance(data, dict) and len(data) == 0:
return True, "OK"
return False... |
from zds.tutorialv2.models.models_versioned import Extract, VersionedContent, Container
from django.core.management.base import BaseCommand
from zds.utils.models import Licence
from uuslug import slugify
import os
try:
import ujson as json_reader
except ImportError:
try:
import simplejson as json_reade... |
import numpy as np
import re
import itertools
from collections import Counter
import unicodedata
def strip_accents(text):
"""
Strip accents from input String.
:param text: The input string.
:type text: String.
:returns: The processed String.
:rtype: String.
"""
try:
text = uni... |
from tests.test_integration_create_helper import TestCreateObject
class TestCreateTilstand(TestCreateObject):
def setUp(self):
super(TestCreateTilstand, self).setUp()
def test_create_tilstand(self):
# Create tilstand
tilstand = {
"attributter": {
"tilstand... |
version_no=3
class KTestError(Exception):
pass
class KTest:
@staticmethod
def fromfile(path):
if not os.path.exists(path):
print("ERROR: file %s not found" % (path))
sys.exit(1)
f = open(path,'rb')
hdr = f.read(5)
if len(hdr)!=5 or (hdr!=b'KTEST' and hdr != b"BOUT\n"):
raise KTestError('unreco... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Very basic tool to generate a binary font from a TTF. Currently
# hardcodes a lot of things, so it's only really suitable for this demo.
#
# Assumes every glyph fits in an 8x8 box. Each glyph is encoded as
# an uncompressed 8-byte bitmap, preceeded by a one-byte escapem... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.