content string |
|---|
from yambopy.flow import YambopyFlow, P2yTask, YamboTask
#from schedulerpy import Scheduler
from yambopy import yambopyenv
# Set list of task and dictionary of yambo variables
tasks = []
yamboin_dict = dict()
# Set origin of SAVE folder
p2y_task = P2yTask.from_folder('nscf_flow/t2')
print(p2y_task)
# Coulomb-cutoff... |
from sympy import (sin, cos, atan2, log, exp, gamma, conjugate, sqrt,
factorial, Piecewise, symbols, S, Float)
from sympy import Catalan, EulerGamma, GoldenRatio, I
from sympy import Function, Rational, Integer, Lambda
from sympy.core.relational import Relational
from sympy.logic.boolalg import And, Or, Not, ... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import logging
import numpy as np
import matplotlib.pyplot as plt
def plot_scatter_diagram(which_fig, x, y, x_label = 'x', y_label = 'y', title = 'title', style_list = None):
'''
Plot scatter diagram
Args:
which_fig : which sub plot
x : x array
y ... |
''' response_views
viewing responses to forms
'''
from flask import (render_template, request, flash, redirect, url_for, session
, abort)
from decorators import *
from models import *
import utilities
from ivrhub import app
response_route = '/organizations/<org_label>/forms/<form_label>/responses'
@app.route(res... |
import re
from itertools import combinations
from itertools import permutations
"""
Note:
Theese tools do reading, generating and writing tables from and to itp files.
However: NO PARAMETERS ARE SUPPORTED. I wrote this mainly to deal with opls
itp files.
"""
def get_section_lines(filepath, section):
"""
Pars... |
from copy import copy
from future.utils import raise_from, with_metaclass
import re
import rightshift.chains
from rightshift import Transformer, RightShiftException, Chain
from rightshift import extractors
__author__ = '<EMAIL>'
class MatcherException(RightShiftException):
"""
MatcherException is a base cla... |
#!/usr/bin/env python
"""
Get a sensor by hash
"""
# import the basic python packages we need
import os
import sys
import tempfile
import pprint
import traceback
# disable python from generating a .pyc file
sys.dont_write_bytecode = True
# change me to the path of pytan if this script is not running from EXAMPLES/PYT... |
import wx
from robotide.preferences import widgets
class SavingPreferences(widgets.PreferencesPanel):
location = ('Saving',)
title = 'Saving Preferences'
def __init__(self, settings, *args, **kwargs):
super(SavingPreferences, self).__init__(*args, **kwargs)
self._settings = settings
... |
import errno
import logging
import os
from odoo import api, fields, models
_logger = logging.getLogger(__name__)
try:
import cups
except ImportError:
_logger.debug('Cannot `import cups`.')
class PrintingPrinter(models.Model):
_inherit = 'printing.printer'
printer_options = fields.One2many(
... |
import time
from optparse import OptionParser
from multiprocessing import Process, freeze_support
# Red Sails modules
from rsRemote.rsConnections import ConnectionsHandler
from rsRemote.rsProxy import ProxyHandler
# Define services for spoofing connections
SMB_PROXY_MODE = {"PORT": 445, "SERVICE": "smb"}
RDP_PROXY_M... |
# Basic utilities for this package
import numpy as np
import pandas as pd
from collections import Counter
a = np.random.choice(['a', 'b', 'c'], 10)
b = np.random.choice(['a', 'b'], 10)
def gen_categorical(xtabs_df, x1):
n = len(x1)
x1_vals = xtabs_df.index.values
x2 = np.zeros(10, dtype='<U256')
... |
# -*- coding: utf-8 -*-
'''
Smoothtest
Copyright (c) 2014 Juju. Inc
Code Licensed under MIT License. See LICENSE file.
'''
import rel_imp
rel_imp.init()
import os
from .base import AutoTestBase
from collections import defaultdict
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observe... |
from ducktape.mark import matrix
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.services.kafka import KafkaService
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.console_consumer import ConsoleConsumer, is_int
from kafkatest.services.security.sec... |
import mock
import pytest
from f5.bigip.mixins import UnsupportedMethod
from f5.bigip.resource import UnsupportedOperation
from f5.bigip.tm.sys.performance import Performances
@pytest.fixture
def FakePerformance():
fake_sys = mock.MagicMock()
return Performances(fake_sys)
class TestPerformance(object):
... |
from django_rq import job
from django.apps import apps
import os
import shutil
import subprocess
import re
from pathlib import Path
import dateutil.parser
from interface.path_processor import PathProcessor
@job
def process_wiki(repo_id, file_change=None):
file_change = file_change or {}
Repo = apps.get_mo... |
r"""TensorFlow Eager Execution Example: RNN Colorbot.
This example builds, trains, and evaluates a multi-layer RNN that can be
run with eager execution enabled. The RNN is trained to map color names to
their RGB values: it takes as input a one-hot encoded character sequence and
outputs a three-tuple (R, G, B) (scaled ... |
import gbpservice.nfp.configurator.lib.schema as schema
import gbpservice.nfp.configurator.lib.schema_validator as sv
import unittest
"""SchemaResources is a helper class which contains all the dummy resources
needed for TestSchemaValidator class
"""
class SchemaResources(object):
resource_healthmonitor = 'h... |
# -*- coding: utf-8 -*-
import os
import shutil
from django.conf import settings
from django.contrib import messages
from django.utils.translation import ugettext as _
from .utils import run_in_server
from .models import Package, Store
def remove_repository_metadata(request, deploy, old_name=""):
name = old_na... |
from google.cloud import aiplatform
def create_dataset_video_sample(
project: str,
display_name: str,
location: str = "us-central1",
api_endpoint: str = "us-central1-aiplatform.googleapis.com",
timeout: int = 300,
):
# The AI Platform services require regional API endpoints.
client_options... |
"""Unit tests for the ``ptables`` paths.
A full API reference for patition tables can be found here:
http://theforeman.org/api/apidoc/v2/ptables.html
"""
from fauxfactory import gen_integer, gen_string
from nailgun import entities
from random import randint
from requests.exceptions import HTTPError
from robottelo.con... |
# Copyright (c) 2016, LE GOFF Vincent
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and th... |
import os
import argparse
import numpy as np
from model.one_hot_model import OneHotModel
from model.augmented_model import AugmentedModel
from model.data_processor import DataProcessor
from model.setting import ProposedSetting
DATA_ROOT = os.path.join(os.path.dirname(__file__), "data")
MODEL_ROOT = os.path.join(os.pa... |
#!/usr/bin/env python
import subprocess, re, random
# this script generates a training set of pacman runs.
# it randomly generates a coefficient between -4 and 4
# for each feature.
destfile = "/home/dan/classes/ai/training.txt"
def runPacman(c):
"runs pacman with the given constants, returns the score #"
... |
try:
from osgeo import gdal
from osgeo.gdalnumeric import *
except ImportError:
import gdal
from gdalnumeric import *
from optparse import OptionParser
import sys
import os
import simple_sel as ss
import fast_any_all as fa
# create alphabetic list for storing input layers
AlphaList=["A","B","C","D","E... |
import unittest2
# Scenario unit-testing
from scenariotest import ScenarioMeta, ScenarioTest
from bitcoin.address import *
from bitcoin.errors import Base58Error
# ===----------------------------------------------------------------------===
from bitcoin.script import *
BITCOIN_ADDRESS = [
# Valid addresses
... |
# generic imports
import django
from lxml import etree
import os
import sys
# pylint: disable=wrong-import-position
# check for registered apps signifying readiness, if not, run django.setup() to run as standalone
if not hasattr(django, 'apps'):
os.environ['DJANGO_SETTINGS_MODULE'] = 'combine.settings'
sys.pat... |
from __future__ import print_function
from shutil import rmtree
from hotcidr import state
import boto.ec2
import boto.vpc
import contextlib
import git
import hashlib
import json
import os
import requests
import shutil
import sys
import tempfile
import time
import yaml
#This function is different than isinstance(n,int)... |
import logging
import multiprocessing
import os
import psutil
import signal
import time
import unittest
from airflow.utils import helpers
class TestHelpers(unittest.TestCase):
@staticmethod
def _ignores_sigterm(child_pid, setup_done):
def signal_handler(signum, frame):
pass
sign... |
# -*- coding: utf-8 -*-
import pytest
from django.test import TestCase
from koalixcrm.crm.factories.factory_sales_document_position import StandardSalesDocumentPositionFactory
from koalixcrm.crm.factories.factory_currency import StandardCurrencyFactory
from koalixcrm.crm.factories.factory_quote import StandardQuoteFac... |
from __future__ import absolute_import, division, print_function
import os
from collections import OrderedDict
import numpy as np
from astropy.io import fits
from glue.config import subset_mask_importer, subset_mask_exporter
from glue.core.data_factories.fits import is_fits
@subset_mask_importer(label='FITS', exten... |
# coding=utf-8
import unittest
"""882. Reachable Nodes In Subdivided Graph
https://leetcode.com/problems/reachable-nodes-in-subdivided-graph/description/
Starting with an **undirected** graph (the "original graph") with nodes from
`0` to `N-1`, subdivisions are made to some of the edges.
The graph is given as foll... |
import unittest
import json
from decision import server
class DecisionTestCase(unittest.TestCase):
def setUp(self):
server.app.config['TESTING'] = True
self.client = server.app.test_client()
def test_server(self):
self.assertEquals((self.client.get('/')).status_code, 200)
self... |
import bpy
import os
import struct
import skeleton_pb2
import google.protobuf.text_format
class SKL_OT_exporter(bpy.types.Operator):
'''Exports an armature to an AeonGames Skeleton (SKL) file'''
bl_idname = "export_skeleton.skl"
bl_label = "Export AeonGames Skeleton"
filepath: bpy.props.StringProper... |
from collections import namedtuple
import contextlib
import logging
import unicodedata
logger = logging.getLogger(__name__)
# empty is here to disambiguate None and inexisting values from the cache
empty = object()
def _stringify(item):
"""Helper function to handle `call_key` params:
- it ensures unicode fo... |
""" This module contains the TypeHandler class """
from .handler import Handler
class TypeHandler(Handler):
"""
Handler class to handle updates of custom types.
Args:
type (type): The ``type`` of updates this handler should process, as
determined by ``isinstance``
callback (f... |
# -*- coding: utf-8 -*-
from django.core.management import call_command
from django.test import TestCase
from django.utils.six import StringIO
from models import TestModel
class TestBasicsEndToEnd(TestCase):
@classmethod
def setUpTestData(cls):
TestModel.objects.create(text_field="The quick brown fox... |
# -*- coding: utf-8 -*-
""" Auto Encoder Example.
Using an auto encoder on MNIST handwritten digits.
References:
Y. LeCun, L. Bottou, Y. Bengio, and P. Haffner. "Gradient-based
learning applied to document recognition." Proceedings of the IEEE,
86(11):2278-2324, November 1998.
Links:
[MNIST Dataset] ht... |
#!/usr/bin/env python3
"""
--- Day 7: Some Assembly Required ---
This year, Santa brought little Bobby Tables a set of wires and bitwise logic gates! Unfortunately, little Bobby is a little under the recommended age range, and he needs help assembling the circuit.
Each wire has an identifier (some lowercase letters) ... |
"""
Some very beta tools for IRIS
"""
import sunpy.io
import sunpy.time
import sunpy.map
__all__ = ['SJI_to_cube']
def SJI_to_cube(filename, start=0, stop=None, hdu=0):
"""
Read a SJI file and return a MapCube
.. warning::
This function is a very early beta and is not stable. Further work is
... |
import urllib2,json,time,datetime
from django.conf import settings
from django.core.cache import cache
from celery.decorators import periodic_task, task
from celery.result import AsyncResult
from kral.views import push_data, fetch_queries
@periodic_task(run_every = getattr(settings, 'KRAL_WAIT', 5))
def buzz(**kwargs)... |
class NodeLookup(object):
"""Converts integer node ID's to human readable labels."""
def __init__(self,
label_lookup_path=None,
uid_lookup_path=None):
if not label_lookup_path:
label_lookup_path = os.path.join(
FLAGS.model_dir, 'imagenet... |
'''
This module provides utilities to get the absolute filenames so that we can be sure that:
- The case of a file will match the actual file in the filesystem (otherwise breakpoints won't be hit).
- Providing means for the user to make path conversions when doing a remote debugging session in
... |
import unittest
import mock
from airflow.gcp.sensors.bigquery_dts import BigQueryDataTransferServiceTransferRunSensor
TRANSFER_CONFIG_ID = "config_id"
RUN_ID = "run_id"
PROJECT_ID = "project_id"
class TestBigQueryDataTransferServiceTransferRunSensor(unittest.TestCase):
@mock.patch("airflow.gcp.sensors.bigquery... |
from flask.ext.wtf import Form
from flask_wtf.file import FileField
from wtforms import TextField, HiddenField, RadioField, BooleanField, \
SubmitField, IntegerField, FormField, StringField, PasswordField, \
SelectField
from wtforms import validators, ValidationError
from wtforms.validators import Requi... |
import json
from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory
from .exceptions import NamespaceNotFound
class SocketServerProtocol(WebSocketServerProtocol):
def onConnect(self, request):
self.path = request.path
def getNamespace(self):
return self.facto... |
#!/usr/bin/python
"""
Test framework for web server function of arcom-server
"""
import logging
import optparse
import sys
import web_server
logFormat = '%(levelname)-7s %(asctime)s %(threadName)s %(message)s'
logging.basicConfig(
filename='arcom.log',
format=logFormat,
level=logging.DEBUG
)
log = logging... |
"""
Module that defines customized decorators
Authors: Gribouillis
"""
from functools import partial
class mixedmethod(object):
"""
This decorator mutates a function defined in a class into a 'mixed' class
and instance method.
Example
-------
class Spam:
@mixedmethod
def egg(se... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"Fully test this module's functionality through the use of fixtures."
import unittest2 as unittest
from megacosm.util.Seeds import set_seed
class TestSeeds(unittest.TestCase):
def setUp(self):
""" """
def test_int_seeds(self):
""" """
... |
import string
class NewsStory(object):
def __init__(self, guid, title, subject, summary, link):
self.guid=guid
self.title=title
self.subject=subject
self.summary=summary
self.link=link
def getGuid(self):
return self.guid
def getTitle(self):
re... |
__author__ = 'Mayur M'
import math
import ImgIO
def tan(image1): # computes tan of image values
return_red = []
return_green = []
return_blue = []
for i in range(0, len(image1.red)):
tmp_r = int(math.tan(image1.red[i]) * 255)
tmp_g = int(math.tan(image1.green[i]) * 255)
tmp_b... |
"""
.. versionadded:: 0.24.11-d
We use the excellent `Dash`_ app for documentation, but some documentation is nice to have on the local machine.
This may even be extended to cover training materials, e-books, etc.
.. _Dash: https://kapeli.com/dash
"""
# Imports
from collections import OrderedDict
import commands
i... |
class strings(object):
# Filesystem
FS_SRVR_CONF = '/etc/tyr/conf'
# Logging
LOG_DATE = '%m/%d/%Y %I:%M:%S %p'
LOG_FORMAT = '%(asctime)s %(levelname)s:%(message)s'
# Compilers
COMPILER_PYTHON = 'python'
COMPILER_C = 'gcc'
COMPILER_CPP = 'g++'
COMPILER_JAVA = 'javac'
# Lan... |
from __future__ import absolute_import
from cchloader import logger
from cchloader.utils import build_dict
from cchloader.adapters.p1 import P1Adapter
from cchloader.models.p1 import P1Schema
from cchloader.parsers.parser import Parser, register
class P1D(Parser):
patterns = ['^P1D_(\d{4})_(\d{4})_(\d{4})(\d{2}... |
import select as _select
# hey!!! did you know that you can have nested loops in list/dict/generator comprehensions????
# GUESS WHAT WE'RE DOING HERE
def select(select_read, select_write=(), select_exc=(), timeout=None):
"""
A select function which works for any netcat or simplesock object.
This function i... |
#!/usr/bin/env python
""" Aqui voy a calcular los parametros para un modelo basado
en las estadisticas de ATNF.
"""
###########################################################################################
# http://www.scipy.org/Cookbook/OptimizationAndFitDemo1?highlight=%28fit%29
# NO ES LO MISMO EL TIPO LIST Y... |
text = """\score {\n {\n aaaa <<\n testing \n>> \n abc = \Partlkjsdf { lkjsdfsjlkj sdf } \n lkjdlkfj lskdjf { \n lkjdsfl kj \n } \n }
"""
def format_text(s,indent=0):
import re
result = []
if not len(s) > 0:
return ''
for x in re.split(r' ', s):
if x.startswith('{'):
res... |
# -*- coding: utf-8 -*-
# All the views here
# Import app via circular imports
from . import application
# Import password and keygen junk
from . import gen
# Import flask stuff
from flask import Flask, render_template, request, send_from_directory
@application.route('/')
def entry():
newPasswd = gen.mkPasswordW... |
"""
Component to interface with various switches that can be controlled remotely.
For more details about this component, please refer to the documentation
at https://home-assistant.io/components/switch/
"""
from datetime import timedelta
import logging
import os
from homeassistant.config import load_yaml_config_file
... |
class Viehicle():
def __init__(self, x, y):
self.acceleration = PVector(0, 0)
self.velocity = PVector(0, 0)
self.location = PVector(x, y)
self.r = 8.0
self.maxspeed = 5
self.maxforce = 0.1
self.d = 25
def update(self):
self.velocity.add(s... |
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... |
from .partition_safety_check import PartitionSafetyCheck
class EnsureAvailabilitySafetyCheck(PartitionSafetyCheck):
"""Safety check that waits to ensure the availability of the partition. It
waits until there are replicas available such that bringing down this
replica will not cause availability loss for ... |
from . import kepmsg, kepstat
import math
import numpy as np
from matplotlib import pyplot as plt
def location(shape):
"""shape the window, enforce absolute scaling, rotate the labels"""
# position first axes inside the plotting window
ax = plt.axes(shape)
# force tick labels to be absolute rather tha... |
# -*- coding: utf-8 -*-
'''
Test the whole datapusher but mock the CKAN datastore.
'''
import os
import json
import unittest
import httpretty
import datapusher.main as main
import datapusher.jobs as jobs
import ckanserviceprovider.util as util
os.environ['JOB_CONFIG'] = os.path.join(os.path.dirname(__file__),
... |
"""Provide a way to connect entities belonging to one device."""
from asyncio import Event
from collections import OrderedDict
import logging
from typing import Any, Dict, List, Optional, cast
import uuid
import attr
from homeassistant.core import callback
from homeassistant.loader import bind_hass
from .typing impo... |
import asyncio
from typing import TYPE_CHECKING, Set, Collection, Mapping, Dict, Any, Optional
from itertools import chain
from ..const import Status
from ..utils import _service_name
from ..server import Stream
from .v1.health_pb2 import HealthCheckRequest, HealthCheckResponse
from .v1.health_grpc import HealthBase... |
"""@package src.wi.tests.groups_test
@author Piotr Wójcik
@author Krzysztof Danielowski
@date 05.03.2013
"""
from wi.tests import WiTestCase
import unittest
import random
class GroupsTests(WiTestCase, unittest.TestCase):
@staticmethod
def _test_create_group(self):
driver = self.driver
self.b... |
import os
import base64
from requests.exceptions import HTTPError
def _remove_prefix(prefix, s):
if s.startswith(prefix):
return s[len(prefix):]
def bootstrap_theme(github, theme='basic'):
blobs = []
prefix_path = 'themes/%s' % theme
try:
parent_sha, base_commit = current_commit(github)... |
"""Generate docs for the TensorFlow Python API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
import six
from tensorflow.python.util import tf_inspect
from tensorflow.tools.common import public_api
from tensorflow... |
import sys
import unittest
sys.path.append('./code')
from isa import GSM
from numpy import asarray, isnan, any, sqrt, sum, square, std, mean
from numpy.random import randn, rand
from scipy.stats import kstest, norm, laplace, cauchy
from scipy.optimize import check_grad
from pickle import dump, load
from tempfile impo... |
import os
from unittest import mock
import fixtures
from neutron_lib import constants
from neutron.agent.linux import ip_lib
from neutron.plugins.ml2.drivers.linuxbridge.agent import \
linuxbridge_neutron_agent as lb_agent
from neutron.tests import base as tests_base
from neutron.tests.common import config_fixtur... |
from __future__ import unicode_literals
import json
import pytest
from rest_framework import status
from rest_framework.test import APIClient
from shuup.core import cache
from shuup.core.models import Shipment
from shuup.testing.factories import (
create_random_order, create_random_person, get_shop
)
def setup... |
import os, pygame, sys, math, random
from pygame.locals import *
from euclid import *
from constants import *
class Rock(pygame.sprite.Sprite):
"""rock"""
def __init__(self, gameArea, pos = None, velocity = None,
radious = ROCK_RADIOUS_MAX):
"""initialize a Rock object
Keywor... |
"""
Module for formatting output data in Latex.
"""
from typing import IO, List, Optional, Tuple
import numpy as np
from pandas.core.dtypes.generic import ABCMultiIndex
from pandas.io.formats.format import DataFrameFormatter, TableFormatter
class LatexFormatter(TableFormatter):
"""
Used to render a DataFra... |
import logging, signal
from Modules.MainUIModules.AbstractUIModule import AbstractUIModule
from PyQt4.QtCore import *
from PyQt4 import uic, QtGui
from Defines import SIGNALS
from PyQt4.QtCore import SIGNAL
from Defines.MODULES import MODULES
from Modules.UIModules import ImagePlayer
import Modules.UIModules.RESOURCES... |
from __future__ import absolute_import
import json
from six.moves.urllib.parse import urlparse
from django.db import models
from django.db.models.sql.where import SubqueryConstraint, WhereNode
# Django 1.7 lookups
try:
from django.db.models.lookups import Lookup
except ImportError:
Lookup = None
from elast... |
from CIM15.CDPSM.Balanced.Element import Element
class NameType(Element):
"""Type of name. Possible values for attribute 'name' are implementation dependent but standard profiles may specify types. An enterprise may have multiple IT systems each having its own local name for the same object, e.g. a planning system... |
# coding: utf-8
from __future__ import division, unicode_literals
"""
TODO: Change the module doc.
"""
__author__ = "shyuepingong"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "<EMAIL>"
__status__ = "Beta"
__date__ = "5/2/13"
import unittest
import os
import json
import random
import numpy as ... |
'''
Cleanup all VMs (find from ZStack database). It is mainly for debuging.
@author: Youyk
'''
import zstackwoodpecker.operations.config_operations as con_ops
import zstackwoodpecker.operations.account_operations as acc_ops
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.clean_util as clean_u... |
from typing import Dict
from great_expectations.core import ExpectationConfiguration
from great_expectations.core.expectation_configuration import parse_result_format
from great_expectations.execution_engine import ExecutionEngine
from great_expectations.expectations.expectation import (
ColumnMapExpectation,
... |
import numpy as np
import pandas as pd
import pytest
from pvlib.ivtools.utils import _numdiff, rectify_iv_curve
from pvlib.ivtools.utils import _schumaker_qspline
from ..conftest import DATA_DIR
@pytest.fixture
def ivcurve():
voltage = np.array([0., 1., 5., 10., 25., 25.00001, 30., 28., 45., 47.,
... |
import sys
from webob import exc
from pytz import common_timezones as timezones
import time
from urlparse import urlparse
from akiri.framework.proxy import JSONProxy
from akiri.framework.route import Router
import akiri.framework.sqlalchemy as meta
from collections import OrderedDict
from controller.profile import U... |
def First_Part(prog):
i = 0
while i < len(prog):
inst = prog[i]
opMode = int(inst[-2:])
parmModes = inst[:-2]
parmModeApply = lambda parmMode, index: int(prog[index]) if parmMode == "1" else int(prog[int(prog[index])])
if opMode == 1:
addends = []
... |
from hubcheck.pageobjects.basepagewidget import BasePageWidget
from hubcheck.pageobjects.basepageelement import Button
from hubcheck.pageobjects.basepageelement import Select
from hubcheck.pageobjects.basepageelement import Text
from hubcheck.exceptions import NoSuchUserException
from selenium.common.exceptions import ... |
import ibus
import engine
import os
from gettext import dgettext
_ = lambda a : dgettext("ibus-anthy", a)
N_ = lambda a : a
class EngineFactory(ibus.EngineFactoryBase):
FACTORY_PATH = "/com/redhat/IBus/engines/Anthy/Factory"
ENGINE_PATH = "/com/redhat/IBus/engines/Anthy/Engine"
NAME = _("Anthy")
LAN... |
#!/usr/bin/env python
import re, os, sys, argparse, time, hmac, hashlib, base64
import logging as log
import traceback, json, requests
import urllib
import collections
from pprint import pprint
## REF error codes:
# Error 222 if you give it a bad path
# Error 220 if you give it a bad path e.g. no opening /
# Error 2... |
# coding: utf-8
import os
from uuid import uuid4
from werkzeug import secure_filename
from flask_restful import Resource, Api
from flask import request, abort, Blueprint
from gridfs import GridFS, NoFile
from app import mongo, app
from comments import CommentsWrapper
from .formatters import highlight
files_app = Bl... |
import nfldatatools as tools
import pandas as pd
import pymongo
def convert(playtype):
valid_play_types = {
'Field Goal':'fg',
'Pass':'pass',
'Run':'run',
'QB Kneel':'kneel',
'Punt':'punt',
}
if playtype in valid_play_types.keys():
return valid_play_types[pl... |
from django.core.urlresolvers import resolve, reverse
from django.test import TestCase
from django.test import Client
from django.utils import translation
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from resources import views
from api.models import Me, Badge
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.module_utils._text import to_text
from ansible.module_utils.connection import ConnectionError
from ansible.module_utils.network.common.utils import to_list
try:
from __main__ import display
except Imp... |
# -*- coding: utf-8 -*-
from wx import TextCtrl, TextAttr, PreTextCtrl
from stubs import to_hex, calc_char_range, clamp_range
from hachoir_wx.hex_view import get_width_chars, get_height_chars
class hex_view_t(TextCtrl):
default_style = TextAttr()
default_style.SetTextColour((0, 0, 0))
highlight_style = T... |
# 312. Burst Balloons
# DescriptionHintsSubmissionsSolutions
# Total Accepted: 25228
# Total Submissions: 59741
# Difficulty: Hard
# Contributor: LeetCode
# Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you... |
#!/usr/bin/env python
import sys
example_dir='../examples/documented'
target_dir='pages/'
if len(sys.argv) > 1:
sys.argv[1]
target_dir=sys.argv[1]
directories={
'python_modular' : ('Python Modular', 'ExamplesModularPython.mainpage',
'''\nTo run the examples issue
\\verbatim
python name_of_example.py
\\endverba... |
import pytest
import responses
from flask import Flask
from urlobject import URLObject
from flask_dance.consumer import OAuth2ConsumerBlueprint
from flask_dance.consumer.storage import MemoryStorage
from flask_dance.contrib.authentiq import make_authentiq_blueprint, authentiq
@pytest.fixture
def make_app():
"A c... |
"""Handle binary stream returns in NCStream format."""
from __future__ import print_function
from collections import OrderedDict
import itertools
import logging
import zlib
import numpy as np
from . import cdmrfeature_pb2 as cdmrf
from . import ncStream_pb2 as stream # noqa
MAGIC_HEADER = b'\xad\xec\xce\xda'
MAGI... |
from flask import Flask, request
from db import *
import json
app = Flask(__name__)
# app.config['DEBUG'] = True
# Note: We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.
"""`main` is the top level module for your Flask application."""
# Import the Flask ... |
from django.contrib.localflavor.ar.forms import (ARProvinceSelect,
ARPostalCodeField, ARDNIField, ARCUITField)
from utils import LocalFlavorTestCase
class ARLocalFlavorTests(LocalFlavorTestCase):
def test_ARProvinceSelect(self):
f = ARProvinceSelect()
out = u'''<select name="provincias">
<opt... |
"""
Here are some public functions for API communication
# Notes
Serializers (server => client)
* all data will pass-trough from model (no type conversion / default value)
* all serializer fields have to available in data or have to be None
Deserializer (client => server)
* define all fields with required, valida... |
""" Setup file for statscache """
from setuptools import setup
def get_description():
with open('README.rst', 'r') as f:
return ''.join(f.readlines()[2:])
requires = [
'statscache',
]
tests_require = [
'nose'
]
setup(
name='statscache_plugins',
version='0.0.2',
description='Plugins... |
import sys
from _redfishobject import RedfishObject
from redfish.rest.v1 import ServerDownOrUnreachableError
def ex19_reset_ilo(redfishobj):
sys.stdout.write("\nEXAMPLE 19: Reset iLO\n")
instances = redfishobj.search_for_type("Manager.")
if redfishobj.typepath.defs.isgen9:
for instance in... |
#Minecraft Turtle Example
import minecraftturtle
import minecraft
import block
import random
def tree(branchLen,t):
if branchLen > 6:
t.penblock(block.WOOL.id, random.randint(0,15))
#for performance
x,y,z = t.position.x, t.position.y, t.position.z
#draw branch
t.for... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.