code stringlengths 1 199k |
|---|
from representatives.management.remove_command import RemoveCommand
from representatives_votes.models import Dossier
class Command(RemoveCommand):
manager = Dossier.objects
conditions = {'proposals': None} |
"""test fetch_topic_posts."""
import datetime
from mediawords.db import DatabaseHandler, connect_to_db
from mediawords.test.db.create import create_test_topic
from mediawords.util.log import create_logger
from topics_mine.fetch_topic_posts import POST_FIELDS, fetch_topic_posts
from topics_mine.posts.csv_generic import ... |
{
'name': 'Telegram input',
'version': '0.1',
'category': 'Intervention',
'description': '''
Fast input of intervent via Telegram
''',
'author': 'Micronaet S.r.l. - Nicola Riolini',
'website': 'http://www.micronaet.it',
'license': 'AGPL-3',
'depends': [
'base',
... |
"""
PairDistributionConstraints contains classes for all constraints related
to experimental pair distribution functions.
.. inheritance-diagram:: fullrmc.Constraints.PairDistributionConstraints
:parts: 1
"""
from __future__ import print_function
import itertools, inspect, copy, os, re
import numpy as np
from pdbpa... |
import math
from io import StringIO, BytesIO
from contextlib import contextmanager
from . import cos
from .reader import PDFReader, PDFPageReader
from .filter import FlateDecode
from .xobject.jpeg import JPEGReader
from .xobject.png import PNGReader
from ...font.type1 import Type1Font
from ...font.opentype import OpenT... |
from datetime import datetime
from pathlib import Path
from typing import List, Optional
from uuid import UUID
import pydantic
from sslyze import (
ServerNetworkConfiguration,
HttpProxySettings,
ProtocolWithOpportunisticTlsEnum,
ServerScanStatusEnum,
ServerConnectivityStatusEnum,
ClientAuthRequi... |
{"name": "Logistics Budget",
"version": "2.3.1",
"author": "Camptocamp,Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Purchase Management",
'complexity': "normal",
"images": [],
"website": "http://www.camptocamp.com",
"depends": ["logistic_requisition",
"sale_exceptions",
... |
{
"name": "Suggest to create user account when buying",
"summary": "Suggest users to create an account when buying in the website",
"version": "8.0.1.0.0",
"category": "Website",
"website": "https://odoo-community.org/",
"author": "Antiun Ingeniería, S.L., Odoo Community Association (OCA)",
... |
from tastypie.resources import ModelResource
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from tastypie import fields
from social.models import *
class FeedResource(ModelResource):
class Meta:
queryset = Feed.objects.all()
resource_name = 'social_feed'
excludes = ['update_error_cou... |
from nose.tools import eq_
import inflect
def test_ancient_1():
p = inflect.engine()
# DEFAULT...
eq_(p.plural_noun("error", 0), "errors", msg="classical 'zero' not active")
# "person" PLURALS ACTIVATED...
p.classical(zero=True)
eq_(p.plural_noun("error", 0), "error", msg="classical 'zero' activ... |
from openerp import api, models
from openerp.tools.float_utils import float_compare
class StockQuantRemovalFromPacks(models.Model):
_inherit = 'stock.quant'
@api.multi
def apply_rss(self, product, location, quantity, domain):
packs = self.env['stock.quant.package'].search([('location_id', '=', locat... |
{
"name": "移动时检查输入的产品、库位、批次、包装、数量是否足够",
"description":
"""
原有逻辑是在仓库移动产品时输入任意数量的产品(与移库单数量不符合)都可以正常移动通过,
此模块增加对移动产品数量的逻辑判断,输入移动的产品数量大于移库数量或者大于库存数量应弹出警告阻止程序继续运行。
""",
'author': "jacky@osbzr.com",
'website': "http://www.osbzr.com",
"category": "osbzr",
"versio... |
{
"name": "HR Expense Extended",
"version": "2.8.17.10",
"author": "Didotech SRL",
"website": "http://www.didotech.com",
"category": 'Human Resources',
"description": """
Module extends functionality of the hr_expense module:
- expense line will also create account_analytic_l... |
import nltk.classify.util
from synt.utils.db import get_samples, RedisManager
from synt.utils.text import normalize_text
from synt.utils.extractors import get_extractor
from synt.guesser import Guesser
def test_accuracy(db_name='', test_samples=0, neutral_range=0, offset=0):
"""
Returns two accuracies and class... |
from openerp import api, fields, models, _
class CamposActivityType(models.Model):
_name = 'campos.activity.type'
_description = 'Campos Activity Type' # TODO
name = fields.Char() |
__metaclass__ = type
from doctest import DocTestSuite
import unittest
from lp.testing import reset_logging
def tearDown(test):
reset_logging()
def test_suite():
suite = unittest.TestSuite()
suite.addTest(DocTestSuite(
'lp.services.scripts.logger', tearDown=tearDown
))
suite.addTest(DocTe... |
import logging
import threading
from mirte.core import Manager
__names__ = ['get_a_manager']
try:
import prctl
except ImportError:
prctl = None
__singleton_manager = None
def get_a_manager(threadPool_settings=None):
""" On first call, creates and returns a @mirte.core.Manager. On
subsequent calls, ... |
"""
Testing asn_lookup.
TODO: IPv6
"""
from __future__ import unicode_literals
import json
import os
import unittest
import intelmq.lib.test as test
from intelmq.bots.experts.tor_nodes.expert import TorExpertBot
TOR_DB = '/opt/intelmq/var/lib/bots/tor_nodes/tor_nodes.dat'
EXAMPLE_INPUT = {"__type": "Event",
... |
import random
from persistent.list import PersistentList
from pyramid.view import view_config
from deform.compat import uppercase, string
from substanced.util import get_oid
from dace.objectofcollaboration.principal.util import get_current
from dace.objectofcollaboration.entity import Entity
from dace.util import get_o... |
"""
These views handle all actions in Studio related to import and exporting of
courses
"""
import logging
import os
import tarfile
import shutil
import re
from tempfile import mkdtemp
from path import path
from django.conf import settings
from django.http import HttpResponse
from django.contrib.auth.decorators import ... |
"""
Test models, managers, and validators.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from django.core.exceptions import ValidationError
from django.test import TestCase
from opaque_keys.edx.keys import UsageKey, CourseKey
from student.tests.factories import UserFactory, Cour... |
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_POST
from organization.models.capability import Capability
from organization.views.proposal import capability_success
from organization.views.decorator import capability_required_decorator
fro... |
import grafos
class CIUDAD:
def __init__(self, id, nombre, longitud, latitud, provincia, habitantes)
self.nombre = nombre
self.lingitud = longitud
self.latitud = latitud
self.provincia = provincia
self.habitantes = habitantes
self.mapa = GRAFOS() |
"""
Test the access control framework
"""
import datetime
import itertools
from unittest.mock import Mock, patch
import pytest
import ddt
import pytz
from ccx_keys.locator import CCXLocator
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.test import TestCase
f... |
from collections import Counter
from django.core.management.base import BaseCommand
from apps.landmatrix.models import HistoricalActivity, HistoricalInvestor, Deal
from apps.landmatrix.models.deal import DealVersion
from apps.landmatrix.models.gndinvestor import InvestorVersion
class Command(BaseCommand):
def handl... |
"""Implementation classes for Account and associates."""
__metaclass__ = type
__all__ = [
'Account',
'AccountSet',
]
from sqlobject import StringCol
from storm.locals import ReferenceSet
from zope.interface import implements
from lp.services.database.constants import UTC_NOW
from lp.services.database.dateti... |
from xml.etree import ElementTree as ET
import math
class GPX2SVG(object):
xml = '''<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg... |
from . import orderpoint_template
from . import product |
{
'name': 'Excel report for stock valutaion',
'version': '8.0.1.0.1',
'depends': [
'mrp',
'purchase',
'report_xls',
'stock_account',
],
'author': 'Elico Corp',
'license': 'AGPL-3',
'website': 'https://www.elico-corp.com',
'data': [
'report/report.x... |
import os
import sys
from tempfile import mkstemp
import unittest
sys.path.insert(0, ".")
from coalib.results.result_actions.ApplyPatchAction import ApplyPatchAction
from coalib.results.Diff import Diff
from coalib.results.Result import Result
from coalib.settings.Section import Section
class ApplyPatchActionTest(unitt... |
import os
import numpy as np
from s2plib import common
from s2plib.config import cfg
def rectify_secondary_tile_only(algo):
if algo in ['tvl1_2d']:
return True
else:
return False
def compute_disparity_map(im1, im2, disp, mask, algo, disp_min=None,
disp_max=None, extra_p... |
import xmlrpclib, csv, sys, ConfigParser, os, pdb
path=os.path.expanduser("~/ETL/minerals/")
cfg_file=path + "openerp.cfg"
config = ConfigParser.ConfigParser()
config.read([cfg_file]) # if file is in home dir add also: , os.path.expanduser('~/.openerp.cfg')])
dbname=config.get('dbaccess','dbname')
user=config.get('dbac... |
import zmq
import time
import os
import re
import sys
context = zmq.Context()
socket = context.socket(zmq.REQ)
serveurport = "tcp://172.17.0.30:%s"%sys.argv[1]
socket.connect(serveurport)
print "Demarrage de lenregistrement des sondes cpu memoire ... pour une duree de 2 fois 150 secondes "
os.system("nmon -f -s2 -c 150... |
import pandas as pd
import MySQLdb
class DBConnection:
def __init__(self,db_host,db_name,db_user,db_pass):
"""Connect to database and query tables.
:param:
db_host: The database host
db_name: The database name
db_user: The database user
db_pass: The user's password
"""
# Create con... |
from odoo import fields, models
class FiscalDocumentMixin(models.AbstractModel):
_inherit = "l10n_br_fiscal.document.mixin"
def _get_default_incoterm(self):
return self.env.user.company_id.incoterm_id
# Esta sendo implementado aqui para existir nos objetos herdados
incoterm_id = fields.Many2one(... |
import csv
from flask.cli import with_appcontext
import click
import markdown
from . import models
@click.group('setup')
def setup_cli():
"""Various setup commands."""
pass
@setup_cli.command('orgs')
@click.argument('orgs_file', type=click.File('r'))
@with_appcontext
def import_orgs(orgs_file):
"""Import a ... |
import superdesk
from bs4 import BeautifulSoup
from superdesk.metadata.item import ITEM_TYPE, CONTENT_TYPE
from flask import render_template
from jinja2 import Template
def getTemplate(highlightId):
"""Return the string template associated with highlightId or none """
if not highlightId:
return None
... |
from shuup.core.models import OrderLineType
def update_order_line_from_product(
pricing_context, order_line, product, quantity=1, supplier=None):
"""
Update OrderLine data from a product.
This is a convenience method for simple applications.
:type pricing_context: shuup.core.pricing.PricingConte... |
from hitchcli.command_line_steps import CommandLineStepLibrary |
'''
Copyright (c) 2012 Alexander Abbott
This file is part of the Cheshire Cyber Defense Scoring Engine (henceforth
referred to as Cheshire).
Cheshire 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 Softw... |
from datetime import datetime
from openerp import models, fields, api, _
class livestock_embryo(models.Model):
_name = 'livestock.embryo'
_description = "Livestock Embryo model"
_order = "id desc"
def _phase_embryo_selection(self):
return(('mo', _("Morula")),
('cm', _("Compact Mor... |
import shtest, sys, common
from common import *
def neg(p, types=[]):
if is_array(p):
result = [-a for a in p]
else:
result = [-p]
return shtest.make_test(result, [p], types)
def insert_into(test):
test.add_test(neg((0.0, 0.0, 0.0)))
test.add_test(neg((1.0, 2.0, 3.0)))
test.add_t... |
import os
from docutils.parsers.rst import roles, directives
from docutils import nodes, utils
from sphinx.environment import NoUri
from sphinx.locale import _
from sphinx.util.compat import Directive, make_admonition
from sphinx.util.osutil import copyfile
CSS_FILE = 'cindex.css'
class cmd_node(nodes.Admonition, nodes... |
import ipf.ipfblock.processing
from ipf.ipfblock.arithmetic import Arithmetic
class Division(Arithmetic):
""" Divide two images
"""
type = "Division"
is_abstract_block = False
def __init__(self):
super(Division, self).__init__()
self.processing_function = ipf.ipfblock.processing.divi... |
import ctypes
import cpylmnl.linux.netlinkh as netlink
import cpylmnl.linux.rtnetlinkh as rtnetlink
class RtnlLinkStats(ctypes.Structure):
"""struct rtnl_link_stats
"""
_fields_ = [("rx_packets", ctypes.c_uint32), # __u32 rx_packets /* total packets received */
("tx_packets", ctypes.c_ui... |
import unittest
import uuid
from xapi.storage.libs.libvhd import metabase
class StubVHDMetabase(metabase.VHDMetabase):
def __init__(self):
metabase.VHDMetabase.__init__(self, ":memory:")
def schema_check(self):
with self._conn:
tables = self._conn.execute("PRAGMA table_info('VDI')")
... |
from gi.repository import Cogl, GObject
from pyclut.basics import Shape
class SixBranchStar (Shape):
"""Simple star shape with six branches.
"""
__gtype_name__ = 'SixBranchStar'
def do_draw_shape(self, width, height):
Cogl.path_move_to(0, height/4)
Cogl.path_line_to(width, height/4)
Cogl.path_line_to(width/2,... |
from spack import *
class Lwgrp(AutotoolsPackage):
"""Thie light-weight group library provides process group
representations using O(log N) space and time."""
homepage = "https://github.com/hpc/lwgrp"
url = "https://github.com/hpc/lwgrp/releases/download/v1.0.2/lwgrp-1.0.2.tar.gz"
version('1... |
import unittest
import sys
import os
import math
from libavg import avg, player
def almostEqual(a, b, epsilon):
try:
bOk = True
for i in range(len(a)):
if not(almostEqual(a[i], b[i], epsilon)):
bOk = False
return bOk
except:
return math.fabs(a-b) < eps... |
import datetime as dt
import time
TIMEFORMAT = '%Y/%m/%d - %H:%M:%S'
def strftime(d):
"""convert given datetime to a string"""
return d.strftime(TIMEFORMAT)
def strptime(s):
"""convert a string to a datetime"""
return dt.datetime.strptime(s, TIMEFORMAT)
def gettime():
"""returns the local time_struc... |
from casadi import *
import casadi as c
import numpy
from numpy import eye, linalg, arange, matrix
import unittest
from types import *
from helpers import *
import numpy
from itertools import *
class Matrixtests(casadiTestCase):
def test_constructorlol(self):
self.message("List of list constructor")
a=DM(arra... |
from taj.core import RelationListener, StreamListener
from taj.operator.common import StreamRelationOperator
import logging
class UnboundWindow(StreamRelationOperator):
'''
this implements the unbound window [RANGE UNBOUND] and [ROWS UNBOUND]
'''
def __init__(self):
super(UnboundWindow, self).__... |
"""
Created on Sun May 14 20:27:32 2017
"""
from collections import abc
from osconfeed import load
class FrozenJSON:
"""
只读接口,使用属性表示法访问JSON类对象
"""
def __init__(self, mapping):
self.__data = dict(mapping)
def __getattr__(self, name):
if hasattr(self, name):
return geta... |
"""
Simple parser ... of cf playground :)
"""
from __future__ import print_function
import sys
import pymzml
import get_example_file
def main(verbose = False):
file_n = 0
successful = dict()
for example_file in get_example_file.SHA256_DICT.keys():
file_n += 1
n = 1
if verbose:
... |
"""
Satellite observation messages from the device.
"""
from construct import *
import json
from sbp.msg import SBP, SENDER_ID
from sbp.utils import fmt_repr, exclude_fields, walk_json_dict, containerize, greedy_string
from sbp.gnss_signal import *
class ObsGPSTime(object):
"""ObsGPSTime.
A wire-appropriate GPS tim... |
import time
import sys
sys.path.append('..')
from taskit.backend import BackEnd, ADMIN_TASKS
def add(x, y):
return x + y
def echo(s):
return s
tasks = dict(ADMIN_TASKS)
tasks.update(dict(add=add, echo=echo))
backend = BackEnd(tasks)
def main():
backend.main()
if __name__ == '__main__':
main() |
import os
from tempfile import mkstemp
from tribler_common.simpledefs import DLSTATUS_SEEDING
from tribler_core.modules.libtorrent.download_config import DownloadConfig
from tribler_core.modules.libtorrent.stream import (FOOTER_SIZE, HEADER_SIZE, NoAvailableStreamError,
... |
from django.contrib.auth.mixins import AccessMixin
from django.contrib import messages
from django.core.exceptions import PermissionDenied, ImproperlyConfigured
from django.shortcuts import redirect
from django.contrib.auth.views import redirect_to_login
class ActiveOnlyMixin(AccessMixin):
"""
A view mixin that... |
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
class Stack(object):
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def top(self):
if le... |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migra... |
"""
A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence "The quick brown fox jumps over the lazy dog" is a pangram, because it uses the letters A-Z at least once (case is irrelevant).
Given a string, detect whether or not it is a pangram. Return True if it ... |
class Configuration:
_morgue_path = ""
@property
def morgue_path(self):
return self._morgue_path or _(u"<unnamed>")
@morgue_path.setter
def morgue_path(self, value):
if not value:
return
self._morgue_path = value |
"""Classes and supporting functions to manipulate ordering columns and extract
keyset markers from query results."""
from copy import copy
from warnings import warn
import sqlalchemy
from sqlalchemy import asc, column
from sqlalchemy.orm import Bundle, Mapper, class_mapper
from sqlalchemy.orm.attributes import Queryabl... |
"""distutils.ccompiler
Contains CCompiler, an abstract base class that defines the interface
for the Distutils compiler abstraction model."""
__revision__ = '$Id$'
import sys
import os
import re
from distutils.errors import CompileError, LinkError, UnknownFileError, DistutilsPlatformError, DistutilsModuleError
from dis... |
__author__ = 'Bruno Konrad'
import nltk
from oliver.data_sentence import MongoSentence
class SentimentAnalysis(object):
def __init__(self):
self._sentence = MongoSentence()
self._pos_tweets = [('I love this car', 'positive'),
('This view is amazing', 'positive'),
... |
u"""Hellweg execution template.
:copyright: Copyright (c) 2017 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern import pkio
from pykern.pkcollections import PKDict
from pykern.pkdebug import pk... |
from ncclient.operations.retrieve import *
import unittest
try:
from unittest.mock import patch # Python 3.4 and later
except ImportError:
from mock import patch
from ncclient import manager
import ncclient.manager
import ncclient.transport
from ncclient.capabilities import Capabilities
from ncclient.xml_ impo... |
from pcgrandom.pcg_common import PCGCommon
def _rotate32(v, r, _multiplier=2**32 + 1, _mask=2**32 - 1):
"""
Unsigned 32-bit bitwise "clockwise" rotation.
Extract the least significant 32 bits of *v*, shift them right
by *r* bits, and move any bits shifted out into the vacated
most significant bits o... |
__author__ = 'Docker Registry Contributors'
__copyright__ = 'Copyright 2014 Docker'
__credits__ = []
__license__ = 'Apache 2.0'
__version__ = '0.9.0'
__maintainer__ = __author__
__email__ = 'docker-dev@googlegroups.com'
__status__ = 'Production'
__title__ = 'docker-registry'
__build__ = 0x000000
__url__ = 'https://gith... |
"""
test_baremetal_node
----------------------------------
Tests for baremetal node related operations
"""
import uuid
from testscenarios import load_tests_apply_scenarios as load_tests # noqa
from shade import exc
from shade.tests import fakes
from shade.tests.unit import base
class TestBaremetalNode(base.IronicTestC... |
import logging
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon.utils import fields
from horizon.utils.validators import validate_port_range
from horizon import workflows
from openstack_dashboard import api
LOG = logging.getLogger(__name__)
cl... |
import os
import sys
program = "python"
print("Process calling")
arguments = ["called_Process.py"]
os.execvp(program, (program,)+ tuple(arguments)) |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_42cc.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import unittest
import numpy.testing as testing
import numpy as np
import healpy as hp
import os
import esutil
from redmapper.utilities import get_healsparse_subpix_indices
class SubpixIndexTestCase(unittest.TestCase):
"""
Tests for get_healsparse_subpix_indices
"""
def test_subpix_nside_lt_cov_nside(se... |
from scipy.stats import beta
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
x = np.linspace(0, 1, num = 100)
plt.plot(x, beta(1, 1).pdf(x), label = "Prior = beta(1,1)", color = cm.get_cmap('Blues_r')(100))
plt.plot(x, beta(1.4, 2.3).pdf(x), label = "Prior = beta(1.4,2.3)", color = cm.get_c... |
"""Update encrypted deploy password in Travis config file
"""
from __future__ import print_function
import base64
import json
import os
from getpass import getpass
import yaml
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from cryptography.hazmat.backends import default_backend
from crypt... |
from ..remote import RemoteModel
from infoblox_netmri.utils.utils import check_api_availability
class EffectivePolicyRemote(RemoteModel):
"""
The policies, as they were defined at the time of policy evaluation. The policies described in here correspond to the policy results expressed in the DevicePolicy and oth... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('tocayoapp', '0010_auto_20151213_0438'),
]
operations = [
migrations.AlterField(
model_name='onto',
... |
from __future__ import unicode_literals
import re
from collections import namedtuple
from botocore.utils import merge_dicts
from moto.compat import OrderedDict
FilterDef = namedtuple(
"FilterDef",
[
# A list of object attributes to check against the filter values.
# Set to None if filter is not ... |
"""TF implementation of the activation transformations used in DKS/TAT."""
from dks.base import activation_transform
import tensorflow as tf
def _get_tf_activation_function(name):
"""Get activation function by name in TensorFlow."""
if name == "bentid":
return lambda x: (tf.sqrt(tf.square(x) + 1.) - 1.) / 2. + ... |
"""
.. _recipes.rasterio_rgb:
============================
imshow() and map projections
============================
Using rasterio's projection information for more accurate plots.
This example extends :ref:`recipes.rasterio` and plots the image in the
original map projection instead of relying on pcolormesh and a map... |
'''
Unit tests for surgery type application. Assumes django server is up
and running on the specified host and port
'''
import unittest
import getopt, sys
import json
from tschartslib.service.serviceapi import ServiceAPI
from tschartslib.tscharts.tscharts import Login, Logout
class CreateSurgeryType(ServiceAPI):
de... |
"""
Preiffer Vacuum Protocol
http://mmrc.caltech.edu/Vacuum/Pfeiffer%20Turbo/Pfeiffer%20Interface%20RS@32.pdf
TC 110 Electronic Drive Unit
http://mmrc.caltech.edu/Optical%20Furnace/Manuals/Pfeiffer%20TC%20110%20Elec.%20Drive%20Unt.pdf
"""
from __future__ import absolute_import
from pychron.hardware.core.communicators.s... |
import proto # type: ignore
from google.cloud.recommender_v1beta1.types import insight
from google.cloud.recommender_v1beta1.types import (
insight_type_config as gcr_insight_type_config,
)
from google.cloud.recommender_v1beta1.types import recommendation
from google.cloud.recommender_v1beta1.types import (
re... |
import pytest
from shells_kitchen.element import Element
from shells_kitchen.exceptions import CallError
from shells_kitchen.group import Group
def test_class_content_without_name():
class MyGroup(Group):
el0 = Element()
grp = MyGroup()
el, args = grp.get_element("el0")
assert isinstance(el, Ele... |
import socket,sys
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.settimeout(1)
try:
sk.connect((sys.argv[1],int(sys.argv[2])))
print 'ok'
except Exception:
print 'no'
sk.close() |
from pathlib import Path
from pants.core.goals.check import CheckResult, CheckResults
from pants.core.goals.style_request import write_reports
from pants.core.util_rules.distdir import DistDir
from pants.engine.fs import EMPTY_DIGEST, Workspace
from pants.testutil.rule_runner import RuleRunner
def test_write_reports() ... |
import os
class LangParser(object):
"""This is the base class for all the parser plugins"""
def __init__(self, path, content=None, parse=True):
"""Initialize the language parser plugin
:param path: The path of the file that is being parsed
:param content: The content of the file
:param parse: Whethe... |
import time
import os, sys
class BaseCollector(list):
def __init__(
self, path = '/tmp/yams', limit_execution_seconds = 0
):
self.path = path
self.start = time.time()
self.limit_execution_seconds = limit_execution_seconds
if not os.path.exists(self.path):
os.m... |
import sys
reload(sys)
sys.setdefaultencoding('utf8')
from django.shortcuts import render
from city import *
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from happybase import Connection, ConnectionPool
from collections import Counter
import random
import itertools
import pa... |
from django.shortcuts import render
from django.http import HttpResponse,HttpRequest
import hashlib
from models import Wishes,Friend
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login,logout
from django.contrib.auth.decorators import login_required
from django.db import Inte... |
import time
from itertools import chain
from .connection import Urllib3HttpConnection
from .connection_pool import ConnectionPool, DummyConnectionPool
from .serializer import JSONSerializer, Deserializer, DEFAULT_SERIALIZERS
from .exceptions import ConnectionError, TransportError, SerializationError, \
... |
from __future__ import division
from blockdiag.noderenderer import NodeShape
from blockdiag.noderenderer import install_renderer
from blockdiag.utils import Box, XY
class Square(NodeShape):
def __init__(self, node, metrics=None):
super(Square, self).__init__(node, metrics)
r = min(metrics.node_width... |
if name == '__main__':
pass |
from external_urls.signals import external_click
from django.dispatch import receiver
from django.utils import timezone
from mmg.jobtrak.links.models import *
@receiver(external_click)
def external_click_fallback(sender, url, ip, **kwargs):
link = JobBoard.objects.get(url=url)
link.last_click = timezone.now()
... |
from ggrc.models.reflection import AttributeInfo
from . import Record
class RecordBuilder(object):
def __init__(self, tgt_class):
self._fulltext_attrs = AttributeInfo.gather_attrs(
tgt_class, '_fulltext_attrs')
def as_record(self, obj):
properties = dict([(attr, getattr(obj, attr)) \
for att... |
"""Utilities dealing with nested structures."""
import collections
import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.internal import prefer_static as ps
from tensorflow.python.util import nest # pylint: disable=g-direct-tensorflow-import
__all__ = [
'broadcast_structure',
... |
import re
def test_phones_on_my_page(app):
contact_from_home_page = app.contact.get_contacts_list()[0]
contact_from_edit_page = app.contact.get_contact_info_from_edit_page(0)
assert contact_from_home_page.all_phones_from_home_page == merge_phones_like_on_home_page(contact_from_edit_page)
def test_phones_on_... |
"""Add keyvalue table
Revision ID: bcf3126872fc
Revises: f18570e03440
Create Date: 2017-01-10 11:47:56.306938
"""
revision = 'bcf3126872fc'
down_revision = 'f18570e03440'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('ke... |
import mock
from neutron_lib.api.definitions import portbindings
from neutron_lib import context
from neutron_lib.plugins import constants as plugin_const
from neutron_lib.plugins import directory
from oslo_utils import uuidutils
from sqlalchemy.orm import exc as orm_exc
from neutron.objects import ports
from neutron.o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.