repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
menglewis/roast-log | manage.py | Python | bsd-3-clause | 857 | 0.001167 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from flask_script import Manager, Shell, Server
from flask_migrate import MigrateCommand
from app import create_app, db
from app.models import User
from app.settings import DevConfig, ProdConfig
if os.environ.get("ENV") == 'prod':
app = create_app(ProdConfi... | PATH = os.path.join(HERE, 'tests')
manager = Manager(app)
def _make_context():
"""Return context dict for a shell session so you can access
app, db, and the User model by default.
"""
return {'app': app, 'db': db, 'User': User}
manager.add_co | mmand('server', Server())
manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run() |
CloudServer/nova | nova/virt/libvirt/guest.py | Python | apache-2.0 | 9,019 | 0 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright (c) 2010 Citrix Systems, Inc.
# Copyright (c) 2011 Piston Cloud Computing, Inc
# Copyright (c) 2012 University Of Minho
# Copyright (c) 2013 Hewlett-Pa... | main.undefineFlags(
libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE)
except libvirt.libvirtE | rror:
LOG.debug("Error from libvirt during undefineFlags. %d"
"Retrying with undefine", self.id)
self._domain.undefine()
except AttributeError:
# Older versions of libvirt don't support undefine flags,
# trying to remove managed image
... |
dischinator/pyload | module/plugins/hooks/JustPremium.py | Python | gpl-3.0 | 2,420 | 0.015289 | # -*- coding: utf-8 -*-
import re
| from module.plugins.internal.Addon import Addon
class JustPremium(Addon):
__name__ = "JustPremium"
__type__ = "hook"
__version__ = "0.26"
__status__ = "testing"
__config__ = [("activated", "bool", "Activated" , False),
("excluded" , "str" , "Exc | lude hosters (comma separated)", "" ),
("included" , "str" , "Include hosters (comma separated)", "" )]
__description__ = """Remove not-premium links from added urls"""
__license__ = "GPLv3"
__authors__ = [("mazleu" , "mazleica@gmail.com"),
("Walt... |
bigoldboy/repository.bigoldboy | plugin.video.VADER/lib/urlresolver/lib/net.py | Python | gpl-3.0 | 12,303 | 0.003007 | '''
common XBMC Module
Copyright (C) 2011 t0mm0
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Th... | se:
return self._cj._cookies
def save_cookies(self, cookie_file):
'''
| Saves cookies to a file.
Args:
cookie_file (str): Full path to a file to save cookies to.
'''
self._cj.save(cookie_file, ignore_discard=True)
def set_proxy(self, proxy):
'''
Args:
proxy (str): Proxy setting (eg.
``'http://user:pas... |
roatienza/Deep-Learning-Experiments | versions/2020/transformer/code/ui.py | Python | mit | 3,932 | 0.002035 | '''Some helper functions for PyTorch, including:
- get_mean_and_std: calculate the mean and std value of dataset.
- msr_init: net parameter initialization.
- progress_bar: progress bar mimic xlua.progress.
'''
import os
import sys
import time
import math
import torch
_, term_width = os.popen('stty size', '... | f += str(days) + 'D'
i += 1
| if hours > 0 and i <= 2:
f += str(hours) + 'h'
i += 1
if minutes > 0 and i <= 2:
f += str(minutes) + 'm'
i += 1
if secondsf > 0 and i <= 2:
f += str(secondsf) + 's'
i += 1
if millis > 0 and i <= 2:
f += str(millis) + 'ms'
i += 1
if f == ''... |
xiaoyongaa/ALL | 函数和常用模块/61函数的递归思考题.py | Python | apache-2.0 | 80 | 0.05 | def f(n):
if n==1:
| return 1
| return n * f(n-1)
x=f(7)
print(x)
|
nylas/sync-engine | migrations/versions/152_add_message_id_to_event.py | Python | agpl-3.0 | 867 | 0.005767 | """add message column to event
Revision ID: 211e93aff1e1
Revises: 2493281d621
Create Date: 2015-03-20 18:50:29.961734
"""
# revision identifiers, used by Alembic.
revision = '211e93aff1e1'
down_revision = '2f3c8fa3fc3a'
from alembic import op
f | rom sqlalchemy.sql import text
def upgrade():
conn = op.get_bind()
conn.execute(text("SET FOREIGN_KEY_CHECKS=0;"))
conn.execute(text("ALTER TABLE event ADD COLUMN message_id int(11) DEFAULT NULL"))
conn.execute(text("ALTER TABLE event ADD CONSTRAINT message_ifbk FOREIGN KEY "
"(`... | xt("ALTER TABLE event DROP FOREIGN KEY message_ifbk"))
conn.execute(text("ALTER TABLE event DROP COLUMN message_id"))
|
mitodl/edx-sga | edx_sga/test_settings.py | Python | agpl-3.0 | 1,989 | 0 | """
Django settings for edx_sga project.
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
DEFAULT_FILE_STORAGE = "django.core.files.storage.FileSystemStorage"
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = "k(g$9p*x^a=t_lf$%=b*3$$ipg1g0tm!^pws... | equest",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages | .context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "edx_sga.wsgi.application"
# Database
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
}
}
# Internationalization
LANGUAGE_CODE = "en-us"
TIME_Z... |
Atrac613/KanjiReading-iOS | KanjiReading/Resources/build_db.py | Python | mit | 1,536 | 0.014323 | # -*- coding: utf-8 -*-
import os
import sqlite3
import csv
def build(table_name, csv_file):
print 'Creating for %s.' % table_name
# Database Connect
con = sqlite3.connect(DATABASE_FILE)
con.text_factory = str
# Load File
data = []
with open(csv_file,'r') as f:
next(f) # ... | ow in reader:
data.append(row)
# Create Table
con.execute('CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY AUTOINCREMENT, new_character TEXT, old_character TEXT, total_strokes INTEGER, grade TEXT, add_year INTEGER, reading TEXT);' % table_name)
# Insert Data
for row in data:
... | okes, grade, add_year, reading) VALUES (?, ?, ?, ?, ?, ?)' % table_name, (row[0],row[1],row[2],row[3],row[4],row[5]))
# Results
c = con.cursor()
c.execute('SELECT count(*) FROM %s' % table_name)
print 'Counts: %d' % c.fetchone()[0]
c = con.cursor()
c.execute('SELECT * FROM %s ORDER BY ... |
DrMeers/django | django/apps/config.py | Python | bsd-3-clause | 7,859 | 0.000127 | from importlib import import_module
import os
from django.core.exceptions import ImproperlyConfigured
from django.utils.module_loading import module_has_submodule
from django.utils._os import upath
MODELS_MODULE_NAME = 'models'
class AppConfig(object):
"""
Class representing a Django application and its co... | from_module(self, module):
"""Attempt to determine app's filesystem path from its module."""
# See #21 | 874 for extended discussion of the behavior of this method in
# various cases.
# Convert paths to list because Python 3.3 _NamespacePath does not
# support indexing.
paths = list(getattr(module, '__path__', []))
if len(paths) != 1:
filename = getattr(module, '__file__... |
pegasus-isi/pegasus-metrics | pegasus/metrics/__init__.py | Python | apache-2.0 | 298 | 0.010067 | import os
i | mport sys
import logging
import threading
from flask import Flask
app = Flask(__name__)
app.config.from_envvar("PEGASUS_METRICS_CONFIG")
# This is required for sessions and message flashing
app.secret_key = os.urandom( | 24)
import pegasus.metrics.views
import pegasus.metrics.filters
|
ebakan/Python | heighway.py | Python | gpl-3.0 | 1,354 | 0.032496 | #!/usr/bin/env python
class heighway:
def __init__(self,d,steps):
self.position=[0,0]
self.directions=['u','r','d','l']
self.direction=0
self.d=d
self.steps=steps
self.count=0
self.depth=0
self.checker('Fa')
def checker(self,text):
... | xt:
if self.count<self.steps and self.depth<self.d:
if i=='F':
if self.direction==0:
self.position[1]+=1
elif self.direction==1:
self.position[0]+=1
elif self.direction==2:
... | self.position[1]-=1
elif self.direction==3:
self.position[0]-=1
self.count+=1
elif i=='R':
self.direction=(self.direction+1)%4
elif i=='L':
self.direction=(self.direction+4-1)... |
unioslo/cerebrum | Cerebrum/modules/bofhd/config.py | Python | gpl-2.0 | 2,808 | 0.000356 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2002-2018 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 ... | eturn u'{0}/{1}'.format(module, name)
class BofhdConfig(object):
""" Container for parsing and keeping a bofhd config. """
def __init__(self, filename=None):
""" Initialize new config. """
self._exts = list() # NOTE: Must keep order!
if filename:
self.load_from_file(file... | e in enumerate(f, 1):
line = line.strip()
if not line or line.startswith('#'):
continue
try:
mod, cls = line.split("/", 1)
except:
mod, cls = None, None
if not mod or not cls:
... |
peterhinch/micropython-async | v3/as_drivers/htu21d/__init__.py | Python | mit | 25 | 0 | from .htu | 21d_mc import | *
|
m87/pyEM | lda.py | Python | mit | 696 | 0.005747 | from mnist import MNIST
import numpy as np
from thirdparty import log_mvnpdf, log_mvnpdf_diag
data = MNIST(' | ./data/mnist')
data.load_training()
data.load_testing()
train = np.array(data.train_images)/255.0
test = np.array(np.array(data.test_images)/255.0)
dataset = {i: [] for i in range(10) }
for it, x in enumerate(data.train_labels):
dataset[x].append(train[it])
mu = []
cov = []
for k in dataset | :
mu.append(np.average(np.array(dataset[k])))
cov.append(np.cov(np.array(dataset[k]).T))
es = log_mvnpdf(train, np.array(mu), np.array(cov))
results = {i: [] for i in range(10) }
for it,e in enumerate(es):
results[np.argmax(e)].append(data.train_labels[it])
print(results)
|
arpitn30/open-event-orga-server | app/api/events.py | Python | gpl-3.0 | 15,239 | 0.001312 | from flask import g
from flask.ext.restplus import Namespace, reqparse, marshal
from app.api.attendees import TICKET
from app.api.microlocations import MICROLOCATION
from app.api.sessions import SESSION
from app.api.speakers import SPEAKER
from app.api.sponsors import SPONSOR
from app.api.tracks import TRACK
from app.... | f.fix_payload(data)
# get event
event = self.get(event_id)
# update copyright if key exists
if 'copyright' in payload:
CopyrightDAO.update(event.copyright.id, payload['copyright']
if payload['copyright'] else {})
payload.pop('copyright')
# upda... |
cfs_data = payload.get('call_for_papers')
if event.call_for_papers:
if cfs_data: # update existing
CFSDAO.update(event.call_for_papers.id, cfs_data)
else: # delete if null
CFSDAO.delete(event.call_for_papers.id)
... |
SupermanScott/Redboy | redboy/key.py | Python | bsd-3-clause | 1,232 | 0.000812 | # -*- coding: utf-8 -*-
#
# © 2012 Scott Reynolds
# Author: Scott Reynolds | <scott@scottreynolds.us>
#
"""Redboy: Key representation"""
# @TODO: Really this class is silly. Its really just an __init__ and a
# str(). Seems obtuse and useless.
import uuid
class Key(object):
"""
A key determines how to extract the data from Redis. Maintains binary
safe representation
"""
def... | ring key. The key can be None and the a uuid will be
used in its place."""
key = key or uuid.uuid4().hex
self.pool_name = pool_name
self.prefix = prefix
self.key = key
def _attrs(self):
"""Get attributes of this key."""
return dict((attr, getattr(self, attr))... |
google-research/google-research | rl4circopt/rules.py | Python | apache-2.0 | 30,401 | 0.005718 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | ans a circuit for transformations.
The circuit is represented by an instance of CircuitScanner and not
circuit.Circuit. This has the advantage that various TransformationRules can
be called with the same CircuitScanner, and in this way it allow | s to reuse
results of the scanning process. In particular, class TransformationRuleSet
is making use of this.
For most users of this class, it might be more convenient to call the method
scan(...) which takes an instance of Circuit.
Args:
scanner: the scanner over the input circuit.
R... |
desihub/desispec | py/desispec/pipeline/__init__.py | Python | bsd-3-clause | 637 | 0.00471 | #
# See top-level LICENSE.rst file for Copyright information
#
# -*- coding: utf-8 -*-
"""
desispec.pipeli | ne
====================
Tools for pipeline creation and running.
"""
from __future__ import absolute_import, division, print_function
from . import tasks
from .defs import (task_states, prod_options_name,
task_state_to_int, task_int_to_state)
from .db import (all_task_types, DataBaseSqlite, DataBasePostgres, ch... | tasks,
load_db)
from .prod import (update_prod, load_prod)
from .run import (run_task, run_task_simple, run_task_list, run_task_list_db,
dry_run)
from .scriptgen import (batch_shell, batch_nersc)
|
jstacoder/basehead | basehead/basecamp.py | Python | bsd-3-clause | 4,557 | 0.008997 | from core import send_request
from people import get_me
from projects import get_all_active_projects, get_project
from todo_lists import get_todo_list, get_todo, get_all_active_todo_lists
from stars import get_starred_projects
try:
from MY_BC import BC
except ImportError:
from core import MY_BC_NUMBER as BC
cl... | lf.starred_projects = send_request(url=self._starred_projects['url'])
self.events = send_request(url=self._events['url'])
#self.active_projects = send_request(url=self._active_projects['url'])
def get_avatar(self,filename):
| fp = open(filename,'wb')
data = send_request(url=self.avatar_url,json=False)
fp.write(data.content)
fp.close()
class BaseCampPerson(object):
BC_ACCOUNT_NUM = BC
class BaseCamper(BaseCampPerson):
def __init__(self,bc_account_number=None,**kwargs):
if bc_account_number is ... |
hifly/connector-magento | magentoerpconnect/tests/test_related_action.py | Python | agpl-3.0 | 3,591 | 0 | # -*- coding: utf-8 -*-
import mock
import openerp
import openerp.tests.common as common
from openerp.addons.connector.queue.job import (
Job,
OpenERPJobStorage,
)
from openerp.addons.connector.session import (
ConnectorSession)
from .common import mock_api
from .data_base import magento_base_responses
fro... | kend']
self.session = ConnectorSession(self.env.cr, self.env.uid,
context=self.env.context)
warehouse = self.env.ref('stock.warehouse0')
self.backend = backend_model.create(
{'name': 'Test Magento',
| 'version': '1.7',
'location': 'http://anyurl',
'username': 'username',
'warehouse_id': warehouse.id,
'password': '42'})
# import the base informations
with mock_api(magento_base_responses):
import_batch(self.session, 'magento.website', ... |
vntarasov/openpilot | common/gpio.py | Python | mit | 568 | 0.010563 | GPIO_HUB_RST_N = 30
GPIO_UBLOX_RST_N = 32
GPIO_UBLOX_SAFEBOOT_N = 33
GPIO_UBLOX_PWR_EN = 34
GPIO_STM_RST_N = 124
GPIO_STM_BOOT0 = 134
def gpio_init(pin, output):
| try:
with open(f"/sys/class/gpio/gpio{pin}/direction", 'wb') as f:
f.write(b"out" if ou | tput else b"in")
except Exception as e:
print(f"Failed to set gpio {pin} direction: {e}")
def gpio_set(pin, high):
try:
with open(f"/sys/class/gpio/gpio{pin}/value", 'wb') as f:
f.write(b"1" if high else b"0")
except Exception as e:
print(f"Failed to set gpio {pin} value: {e}")
|
marshallmcdonnell/interactive_plotting | TraitsUI/build_camera_application/code_snippet_3.py | Python | mit | 172 | 0.011628 | #!/usr/bin/env python
from traits.api import *
import wx
c | lass Counter(HasTraits):
value = Int()
counter = Counter()
counter.edit_traits()
counter.configure_traits | ()
|
shankari/e-mission-server | emission/tests/netTests/TestBuiltinUserCacheHandlerInput.py | Python | bsd-3-clause | 12,374 | 0.005495 | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
# Standard imports
from future import standard_library
standard_library.install_aliases()
from builtins import range
from builtins import *
import unittest
import datetime... | try types, so 30 entries
# First all the entries are in the usercache
self.assertEqual(len(self.uc1. | getMessage()), 30)
self.assertEqual(len(list(self.ts1.find_entries())), 0)
self.assertEqual(len(self.uc2.getMessage()), 30)
self.assertEqual(len(list(self.ts2.find_entries())), 0)
self.assertEqual(len(self.ucios.getMessage()), 30)
self.assertEqual(len(list(self.tsios.fi... |
hsolbrig/SNOMEDToOWL | SNOMEDCTToOWL/RF2Files/DirectoryWalker.py | Python | apache-2.0 | 2,104 | 0.004278 | import csv
import os
from typing import Callable, Dict
from SNOMEDCTToOWL.RF2Files.RF2DictWriter import RF2DictWriter
class DirectoryWalker:
def __init__(self, indir: str, outdir: str, init: bool):
"""
Directory walking utility
:param indir: directory root to walk from
:param outd... | ing content in output files
"""
self._indir = indir if indir.endswith(os.path.sep) else indir + os.path.sep
self._outdir = outdir if outdir.endswith(os.path.sep) else outdir + os.path.sep
self._init = init
def walk(self, filtr: Callable[[str], bool], | processor: Callable[[Dict], bool]) -> None:
"""
Walk the directory testing the file against filtr and invoking processor with contents if true
:param filtr: file name tester
:param processor: content row processor
"""
for filedir, _, files in os.walk(self._indir):
... |
jcfr/girder | girder/api/api_main.py | Python | apache-2.0 | 1,856 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2013 Kitware Inc.
#
# Licensed under the Apache License, Version 2.0 ( the "License" );
# you may | not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CON... | #############################################################################
import cherrypy
from . import describe
from v1 import assetstore, file, collection, folder, group, item, resource,\
system, token, user, notification
class ApiDocs():
exposed = True
def GET(self):
# Since we only have... |
winklerand/pandas | pandas/tests/series/test_api.py | Python | bsd-3-clause | 14,504 | 0 | # coding=utf-8
# pylint: disable-msg=E1101,W0612
from collections import OrderedDict
import pytest
import numpy as np
import pandas as pd
from pandas import Index, Series, DataFrame, date_range
from pandas.core.indexes.datetimes import Timestamp
from pandas.compat import range
from pandas import compat
import panda... | r x in _d])) |
self._assert_series_equal(result, expected)
d['z'] = 111.
_d.insert(0, ('z', d['z']))
result = self.series_klass(d)
expected = self.series_klass([x[1] for x in _d],
index=pd.Index([x[0] for x in _d],
... |
MrKiven/Takayi | tests/test_typing.py | Python | bsd-2-clause | 1,333 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import pytest
from takayi.typing import Any, List, Mapping, Callable, Sequence, is_type,\
String, AnyObject
def test_types():
assert str(Any) == 'Typing.Any'
assert str(List) == 'Typing.List'
assert str(Mapping) == 'Typing.Mapping'
... | t, Any) is True
assert is_type(a_mapping, Any) is True
assert is_type(a_list, Mapping) is False
assert is_type( | a_mapping, Mapping) is True
assert is_type(a_str, String) is True
assert is_type(a_str, Any) is True
assert is_type(a_str, List) is False
|
phenoxim/cinder | cinder/objects/qos_specs.py | Python | apache-2.0 | 7,943 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | s:
# For specs, we only want what has changed in the di | ctionary,
# because otherwise we'll individually overwrite the DB value for
# every key in 'specs' even if it hasn't changed
specs_changes = {}
for key, val in self.specs.items():
if val != self._init_specs.get(key):
specs_changes[key] ... |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/graphy/graphy/util.py | Python | bsd-3-clause | 420 | 0.021429 | def _IsColor(color):
"""Try to determine if color is a hex color string.
Labels that | look like hex colors will match too, unfortunately."""
if not isinstance(color, basestring):
return False
color = color.strip('#')
if len(color) != 3 and len(color) != 6:
return False
hex_letters = '0123456789abcdefABCDEF'
for letter in color:
if | letter not in hex_letters:
return False
return True
|
JRBANCEL/Chromagnon | chromagnonHistory.py | Python | bsd-3-clause | 6,714 | 0.001639 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2012, Jean-Rémy Bancel <jean-remy.bancel@telecom-paristech.org>
# 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 o... | copyright
# notice, this list of conditions and the | following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Chromagon Project nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#... |
CodeSheng/LPLHW | ex09.py | Python | apache-2.0 | 378 | 0.005291 | # Here's some new strange stuff, remember type it exactly.
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here ar | e th | e days: ", days
print "Here are the months: ", months
print """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
""" |
pombredanne/PyGithub | scripts/compare_to_api_ref_doc.py | Python | gpl-3.0 | 6,149 | 0.006342 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ########################## Copyrights and license ############################
# #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# ... | #
# | http://pygithub.github.io/PyGithub/v1/index.html #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free ... |
Erotemic/ibeis | ibeis/algo/verif/pairfeat.py | Python | apache-2.0 | 20,369 | 0.000393 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import utool as ut
import vtool_ibeis as vt
import numpy as np
import ubelt as ub
import pandas as pd
import dtool_ibeis as dt
from os.path import join
from ibeis.algo.graph import nx_utils as nxu
from ibeis.core_... | r database to enrich the matches with database-level
distinctiveness.
"""
from ibeis.algo.hots import nn_weights
raise NotImplementedError('havent tested since the re-work. '
'Need to ensure that things work correctly.')
ibs = extr.ibs
cf... | 'can_match_sameimg': True,
'K': 3,
'Knorm': 3,
'prescore_method': 'csum',
'score_method': 'csum'
}
custom_nid_lookup = ut.dzip(other_aids, other_nids)
aids = [m.annot2['aid'] for m in matches]
qreq_ = ibs.new_query_request(aids, other_aid... |
vpetersson/docker-py | docker/api/build.py | Python | apache-2.0 | 13,266 | 0.000075 | import json
import logging
import os
import re
from .. import auth
from .. import constants
from .. import errors
from .. import utils
log = logging.getLogger(__name__)
class BuildApiMixin(object):
def build(self, path=None, tag=None, quiet=False, fileobj=None,
nocache=False, rm=False, stream=Fal... | lse,
forcerm=False, dockerfile=None, container_limits=None,
decode=False, buildargs=None, gzip=False, shmsize=None,
labels=None, cache_from=None, target=None, network_mode=None,
squash=None, extra_hosts=None):
"""
Similar to the ``docker build`` co... | ` can be a local path (to a directory
containing a Dockerfile) or a remote URL. ``fileobj`` must be a
readable file-like object to a Dockerfile.
If you have a tar file for the Docker build context (including a
Dockerfile) already, pass a readable file-like object to ``fileobj``
... |
foobarbazblarg/stayclean | stayclean-2017-january/checkin.py | Python | mit | 427 | 0.002342 | #!/ | usr/bin/python
import sys
from participantCollection import ParticipantCollection
names = sys.argv[1::]
participants = ParticipantCollection()
for name in names:
if participants.hasParticipantNamed(name):
parti | cipants.participantNamed(name).hasCheckedIn = True
print "just checked in " + name
else:
print "*** WARNING: " + name + " is not present in participants.txt"
participants.save()
|
zalf-lsa/carbiocial-project | monica/monica-cluster-mpi/test-mpi.py | Python | mpl-2.0 | 1,331 | 0.019534 | #!/usr/bin/python
# -*- coding: ISO-8859-15-*-
import sys
import os
import datetime
import time
from mpi4py import MPI
# MPI related initialisations
comm = MPI.COMM_WORLD
rank = comm.Get_rank() # number of the processor
size = comm.Get_size() # number of all participating processes
name = MPI.Get_... | int "processor #", rank
w | ork = None
if (rank == 0):
work = createWork(size)
###################################################
# parallel part
##################################################
# send each sublist of the splitted list to on processor
workPerNode = comm.scatter(work, root=0)
# each processor received a sp... |
SonicFrog/jdrpoly | svz/views.py | Python | gpl-2.0 | 6,684 | 0.00015 | # coding: utf-8
from __future__ import unicode_literals
from django.conf import settings
from django.core.mail import send_mass_mail
from django.db import IntegrityError
from django.forms import (Form, CharField, TextInput, Textarea, Select,
ChoiceField)
from django.views.generic import Temp... | ayer(**validated_data)
def update(self, instance, validated_data):
instance.token_spent += validated_data.get('token_spent', 0)
instance.zombie = validated_data.get('zombify', instance.zombie)
instance.save()
return instance
class Meta:
model = Player
fields = (... | , )
permission_classes = (IsAdminUser, )
def post(self, request, *args, **kwargs):
try:
return super(PlayerCreateView, self).post(request, *args, **kwargs)
except IntegrityError:
content = {"detail": _("Ce sciper existe déjà !")}
return Response(content, stat... |
chiotlune/ext | gnuradio-3.7.0.1/docs/sphinx/gnuradio_sphinx.py | Python | gpl-2.0 | 7,553 | 0.007017 | """
Customizations of sphinx for gnuradio use.
"""
from sphinx.ext.autodoc import py_ext_sig_re
from sphinx.ext.autodoc import ClassDocumenter, FunctionDocumenter, members_option
from sphinx.ext.autodoc import bool_option, members_set_option, identity
from sphinx.ext.autodoc import ALL
# A dictionary of the number of... | for give low priority.
priority = -10
def __init__(self, *args, **kwargs):
super(BlockDocumenter, self).__init__(*args, **kwargs)
# Get class name
sptr_name = self.name + '_sptr'
# Create a Class Documenter to create documentation for the classes members.
self.clas... | assdoccer.real_modname = self.classdoccer.get_real_modname()
self.classdoccer.options.members = ALL
self.classdoccer.options.exclude_members = common_block_members
self.classdoccer.parse_name()
self.classdoccer.import_object()
def document_members(self, *args, **kwargs):
ret... |
noutenki/descriptors | descriptors/utils/__init__.py | Python | mit | 54 | 0 | from descr | iptors.utils.Prepareable import Prepareable | |
mahabs/nitro | nssrc/com/citrix/netscaler/nitro/resource/config/aaa/aaagroup_vpnurl_binding.py | Python | apache-2.0 | 6,287 | 0.03722 | #
# Copyright (c) 2008-2015 Citrix Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | red(cls, service, groupname, filter_) :
""" Use this API to count the filtered set of aaagroup_vpnurl_binding resources.
Filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
"""
try :
obj = aaagroup_vpnurl_binding()
obj.groupname = groupname
option_ = options()
option_.count = True... | Exception as e:
raise e
class aaagroup_vpnurl_binding_response(base_response) :
def __init__(self, length=1) :
self.aaagroup_vpnurl_binding = []
self.errorcode = 0
self.message = ""
self.severity = ""
self.sessionid = ""
self.aaagroup_vpnurl_binding = [aaagroup_vpnurl_binding() for _ in range(length)]... |
diego-d5000/MisValesMd | env/lib/python2.7/site-packages/distribute-0.6.24-py2.7.egg/setuptools/tests/test_upload_docs.py | Python | mit | 1,950 | 0.002564 | """build_ext tests
"""
import sys, os, shutil, tempfile, unittest, site, zipfile
from setuptools.command.upload_docs import upload_docs
from setuptools.dist import Distribution
SETUP_PY = """\
from setuptools import setup
setup(name='foo')
"""
class TestUploadDocsTest(unittest.TestCase):
def setUp(s... | zip_file = cmd. | create_zipfile()
assert zipfile.is_zipfile(zip_file)
zip_f = zipfile.ZipFile(zip_file) # woh...
assert zip_f.namelist() == ['index.html']
|
KhronosGroup/COLLADA-CTS | StandardDataSets/collada/library_images/image/imageindifferentdir/imageindifferentdir.py | Python | mit | 3,904 | 0.007428 |
# Copyright (c) 2012 The Khronos Group Inc.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publ... | reference test
if ( self.__assistant.CompareRenderedImages(context) ):
self.__assistant.CompareImagesAgainst(context, "image_2_texture_same_effect")
self.status_baseline = self.__assistant.DeferJudgement(context)
return self. | status_baseline
# To pass intermediate you need to pass basic, this object could also include additional
# tests that were specific to the intermediate badge.
def JudgeSuperior(self, context):
self.status_superior = self.status_baseline
return self.status_superior
... |
koyi2016/sample | conf.py | Python | apache-2.0 | 9,767 | 0.005954 | # -*- coding: utf-8 -*-
#
# Nablarch解説書 documentation build configuration file, created by
# sphinx-quickstart on Fri Jan 08 09:45:59 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#... | call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be a... | unc: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#sho... |
UManPychron/pychron | pychron/tx/registry.py | Python | apache-2.0 | 5,634 | 0.000355 | # ===============================================================================
# Copyright 2015 Jake Ross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses... | n running command {}. {}'.format(cmd, e))
return r
return wr | apper
registered_function = RegisteredFunction
def make_wrapper(func, postprocess):
def wrapper(obj, manager, *args, **kw):
"""
handler signature is self, manager, args, sender
"""
ret = func(*args[1:], **kw)
if postprocess:
ret = postprocess(ret)
ret... |
vinodpanicker/scancode-toolkit | etc/configure.py | Python | apache-2.0 | 13,838 | 0.000506 | #!/usr/bin/python
# Copyright (c) 2015 nexB Inc. http://www.nexb.com/ - All rights reserved.
"""
This script a configuration helper to select pip requirement files to install
and python and shell configuration scripts to execute based on provided config
directories paths arguments and the operating system platform. T... | base config script for all platforms
mac.py : mac-only config script
"""
from __future__ import print_function
import os
import stat
import sys
import shutil
import subprocess
# platform-specific file base names
sys_platform = str(sys.platform).lower()
on_win = False
if 'linux' in sys_platform:
plat... | rm_names = ('win',)
on_win = True
elif 'darwin' in sys_platform:
platform_names = ('posix', 'mac',)
else:
raise Exception('Unsupported OS/platform')
platform_names = tuple()
# common file basenames for requirements and scripts
base = ('base',)
# known full file names with txt extension for requiremen... |
vetlehjelmtvedt/TranscriptApp | sttClient.py | Python | mit | 13,934 | 0.001077 | #
# Copyright IBM Corp. 2014
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | onnected: {0}".format(response.peer)
def onOpen(self):
print "onOpen"
data = {"action": "start", "content-type": str(self.contentType),
| "continuous": True, "interim_results": True,
"inactivity_timeout": 600}
data['word_confidence'] = True
data['timestamps'] = True
data['max_alternatives'] = 3
print "sendMessage(init)"
# send the initialization parameters
self.sendMessage(json.dum... |
gmathers/iii-addons | iii-phonecall/iii_phonecall.py | Python | agpl-3.0 | 417 | 0.009592 | # -*- coding: u | tf-8 -*-
from openerp import models, fields, api
class crm_phonecall(models.Model):
_inherit = 'crm.phonecall'
repair_id = fields.Many2one(comodel_name="mrp.repair", string="Repair", required=False, )
class mrp_repair(models.Model):
_inherit = 'mrp.repair'
phonecalls = f | ields.One2many(comodel_name="crm.phonecall", inverse_name="repair_id", string="Phonecalls", required=False, )
|
ph1l/halo_radio | WebRoot/UserList.py | Python | gpl-2.0 | 2,144 | 0.044776 | import HaloRadio | .TopWeb as TopWeb
class plugin(TopWeb.TopWeb):
def GetReqs(self):
return "amv"
def handler(self, context):
import HaloRadio.UserListMaker as UserListMaker
import HaloRadio.User as User
ulm = UserListMaker.UserListMaker()
ulm.GetAll()
users = []
is_admin=0
enable=0
wall_enable=0... | e(self.user.rights, "a")):
is_admin=1
enable=1
wall_enable=1
elif self.do_authorize(self.user.rights, "m"):
is_admin=0
enable=0
wall_enable=0
if self.configdb.GetConfigItem('moderator_enable_access') == "1":
enable=1
if self.configdb.GetConfigItem('moderator_wall_enable_access') == "1":
... |
sk364/N_by_N_Tic_Tac_Toe | cpu.py | Python | mit | 5,851 | 0.000684 | """Script to execute CPU and get a best move using Minimax algorithm"""
import copy
from common import board_full, win
OPP = [1, 0]
def eval_rc(board, player, glength, roc):
"""Returns row or column score"""
score_sum = 0
clone_board = board
if roc == "c":
clone_board = [[board[j][i] for j ... | j] == 1:
check += 1
if check > 1:
return False
return True
def minimax(board, player, depth, glength):
"""Returns the best move for the CPU by traversing
all best CPU and worst user moves with depth
"""
moves = get_moves(board, glength)
if not moves... | return moves[0]
best_move = moves[0]
best_score = 0.0
for move in moves:
clone_board = gen_board(board, player, move)
if win(clone_board, player, glength):
return move
for move in moves:
clone_board = gen_board(board, OPP[player], move)
if win(clone_boa... |
MickSandoz/compassion-modules | partner_communication/models/communication_config.py | Python | agpl-3.0 | 4,257 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __openerp__.p... | ield = fields.Char(
'Part | ner preference field',
help='Name of the field in res.partner in which to find the '
'delivery preference'
)
print_if_not_email = fields.Boolean(
help="Should we print the communication if the sponsor don't have "
"an e-mail address"
)
email_template_id = fields... |
singhdev/streamparse | streamparse/bolt.py | Python | apache-2.0 | 16,210 | 0.000308 | """Base Bolt classes."""
from __future__ import absolute_import, print_function, unicode_literals
from collections import defaultdict
import os
import signal
import sys
import threading
import time
import warnings
import logging
from six import iteritems, reraise, PY3
from .base import Component
from .ipc import (re... | auto_ack = True
"""A ``bool`` indicating whether or not the bolt should automatically
acknowledge tuples after ``process()`` is called. Default is ``True``.
"""
auto_fail = True
"""A ``bool`` indicating whether or not the bolt should au | tomatically fail
tuples when an exception occurs when the ``process()`` method is called.
Default is ``True``.
"""
# Using a list so Bolt and subclasses can have more than one current_tup
_current_tups = []
def initialize(self, storm_conf, context):
"""Called immediately after the init... |
grzes/djangae | djangae/contrib/security/tests.py | Python | bsd-3-clause | 347 | 0 | import logging
from djangae.test import TestCase
from djangae.contrib.security.management.co | mmands import dumpurls
class DumpUrlsTests(TestCase):
def test_dumpurls(self):
""" Test that the `dumpurls` command runs without dying. " | ""
logging.debug('%s', "*" * 50)
command = dumpurls.Command()
command.handle()
|
atmb4u/django-console | setup.py | Python | bsd-3-clause | 1,061 | 0.01131 | from distutils.core import setup
from setuptools import find_packages
setup(
name='django-console',
description='bash console in the browser for django admins',
keywords='django, bash',
packages=find_packages(),
include_package_data=True,
version="0.4.8",
author="Anoop Thomas Mathew",
a... | 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Intern... | :: WSGI',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: Software Development :: Libraries :: Python Modules',
],
license="BSD License",
platforms=["all"],
zip_safe=False
)
|
oblique/pygments-style-behelit | pygments_style_behelit/__init__.py | Python | bsd-3-clause | 1,190 | 0 | # -*- coding: utf-8 -*-
"""
behelit
~~~~~~~~~~
Port of the behelit color scheme.
:copyright: Copyright 2011 oblique
:license: BSD, see LICENSE for details.
"""
from pygments.style import Style
from pygments.token import Comment, Error, Keyword, Name, Number, Operator, \
... | '#ff6a6a',
Name: '#66ff66',
Name.Function: '#af87ff',
Name.Constant: '#af87ff',
Name.Label: '#af87ff',
Numb | er: '#af87ff',
String: '#ffff87',
}
|
mvdwoord/PyGNS3 | tools/api_gen/_source/__init__.py | Python | mit | 1,086 | 0 | #!/usr/bin/env python
#
# Copyright (C) 2016 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
... | . If not, see <http://www.gnu.org/licenses/>.
from .compute_handler import ComputeHandler
from .project_handler import ProjectHandler
from .node_handler import NodeHandler
from .link_handler import LinkHandler |
from .server_handler import ServerHandler
from .drawing_handler import DrawingHandler
from .symbol_handler import SymbolHandler
from .snapshot_handler import SnapshotHandler
from .gns3_vm_handler import GNS3VMHandler
|
AASHE/python-membersuite-api-client | membersuite_api_client/exceptions.py | Python | mit | 1,095 | 0 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.utils import python_2_unicode_compatible
@python_2_unicode_compatible
class MemberSuiteAPIError(Exception):
def __init__(self, result):
self.result = result
self.exception_type... | def get_concierge_error(self):
try:
return (self.result["body"][self.result_type]
["Errors"]["ConciergeError"])
except KeyError:
return (self.result["Errors"])
class LoginToPortalError(MemberSuiteAPIError):
pass
class LogoutError(MemberSuiteAPIError... | ery(MemberSuiteAPIError):
pass
|
secimanaliz/kurmaylar | laflar/models.py | Python | gpl-2.0 | 3,387 | 0.010924 | from django.db import models
#from django.db.models import Q
from django.utils.encoding import smart_unicode
import time
from datetime import datetime
import random
#import pytz
class Kurmay(models.Model):
name = models.CharField(max_length='100',unique=True)
def __str__(self):
return self.name
de... | e.strptime(line[2],"%d.%m.%Y")))
kayitli_laf.s | ave()
else:
laf = Laf(text = line[0],
source = line[1],
kurmay = current_kurmay)
if line[2]:
laf.created = datetime.fromtimestamp(
time.mktime(
time.strptime(line[2],"%d.%m... |
odtvince/APITaxi | APITaxi/forms/user.py | Python | agpl-3.0 | 716 | 0.001397 | # -*- coding: utf-8 -*-
from ..utils.model_form import ModelForm
from ..models import security
from wtforms import HiddenField, SubmitField
from wtforms.fields import FormField
from wtforms_alchemy import ModelFormField
from wtforms.widgets import ListWidget
from wtforms.ext.sqlalchemy.fields import QuerySelectField
fr... | ons import images
class UserFormRaw(ModelForm):
class Meta:
model = security.User
exclude = ['password', 'email', 'active', 'apikey', 'confirmed_at']
class UserForm(UserFormRaw):
logo = FileField('image', validators=[
FileAllowed(images, 'Images only!')
])
submit = SubmitField... | u'Modifier')
|
acarl123/acuity | portal/apps.py | Python | mit | 207 | 0 | from importlib impo | rt import_module
from django.apps import AppConfig as BaseAppConfig
class | AppConfig(BaseAppConfig):
name = "portal"
def ready(self):
import_module("portal.receivers")
|
ioniATX/DHT_oblivion | Blocs/III_Shamirs_Block/Code/demomodif.py | Python | gpl-2.0 | 705 | 0 | from secret_sharing_modif import secret_sharing
from secret_sharing_c_modif import secret_sharing_c
S = secret_sharing("The quick brown fox jumps over the lazy dog", 100, 15)
s = secret_sharing_c()
print S.share_random()
s.add_share(S.share_random())
s.add_share(S.share_random())
s.add_share(S.share_random())
s.add_s... | hare | _random())
s.add_share(S.share_random())
s.add_share(S.share_random())
s.add_share(S.share_random())
print S
print s.reconstruct()
|
ergodicbreak/evennia | evennia/server/evennia_launcher.py | Python | bsd-3-clause | 44,636 | 0.000717 | #!/usr/bin/env python
"""
EVENNIA SERVER LAUNCHER SCRIPT
This is the start point for running Evennia.
Sets the appropriate environmental variables and launches the server
and portal through the evennia_runner. Run without arguments to get a
menu. Run the script with the -h flag to see usage information.
"""
from __f... | Web: http://www.eve | nnia.com
Irc: #evennia on FreeNode
Forum: http://www.evennia.com/discussions
Maintainer (2010-): Griatch (griatch AT gmail DOT com)
Maintainer (2006-10): Greg Taylor
Use -h for command line options.
"""
HELP_ENTRY = \
"""
Enter 'evennia -h' for command-line options.
Use option (... |
vpramo/contrail-controller | src/config/svc-monitor/svc_monitor/tests/test_svc_monitor.py | Python | apache-2.0 | 2,660 | 0.002632 | import mock
import unittest
from mock import patch
from svc_monitor.svc_monitor import SvcMonitor
from pysandesh.sandesh_base import Sandesh
from svc_monitor.logger import ServiceMonitorLogger
from svc_monitor.config_db import *
from cfgm_common.vnc_cassandra import VncCassandraClient
from cfgm_common.vnc_kombu import... | self.rabbit_port = '5672'
self.rabbit_user = 'guest'
self.rabbit_password = 'guest'
self.rabbit_vhost = None
self.rabbit_ha_mode = False
self.reset_config = False
self.cassandra_user = None
self.cassandra_password = None
self.cassandra_server_list = N... | def test_svc_monitor_init(self):
self.args = Arguments()
VncCassandraClient.__init__ = mock.MagicMock()
VncCassandraClient._cf_dict = {'service_instance_table':None, 'pool_table':None}
VncKombuClient.__init__ = mock.MagicMock(return_value=None)
ServiceMonitorLogger.__init__ =... |
teeple/pns_server | work/install/Python-2.7.4/Lib/test/test_ioctl.py | Python | gpl-2.0 | 3,311 | 0.003322 | import array
import unittest
from test.test_support import run_unittest, import_module, get_attribute
import os, struct
fcntl = import_module('fcntl')
termios = import_module('termios')
get_attribute(termios, 'TIOCGPGRP') #Can't run tests without this feature
try:
tty = open("/dev/tty", "r")
except IOError:
ra... | fcntl.ioctl(tty, termios.TIOCGPGRP, buf, 1)
rpgrp = buf[0]
self.assertEqual(r, 0)
self.assertIn(rpgrp, ids)
def test_ioctl_mutate(self):
self._check_ioctl_mutate_len()
def test_ioctl_mutate_1024(self):
# Issue #9758: a mutable buffer of exactly 1024 bytes wouldn't be
... | t for the record.
self._check_ioctl_mutate_len(2048)
def test_ioctl_signed_unsigned_code_param(self):
if not pty:
raise unittest.SkipTest('pty module required')
mfd, sfd = pty.openpty()
try:
if termios.TIOCSWINSZ < 0:
set_winsz_opcode_maybe_ne... |
ElliotVilhelm/IZII | engine/move.py | Python | mit | 5,236 | 0.002101 | from engine.constants import BOARD_INDEX, C_PERM_INDEX, WK_SQ_INDEX, BK_SQ_INDEX, EN_PAS_INDEX, NORTH, SOUTH, \
RANK2, RANK7, WKC_INDEX, WQC_INDEX, BKC_INDEX, BQC_INDEX, CASTLE_VOIDED, CASTLED, A1, A8, E1, E8, C1, C8, G1, \
G8, H1, H8, WHITE, BLACK, HALF_MOVE_INDEX, FULL_MOVE_INDEX, TURN_INDEX, B8, B1, D1, D8, ... | DEX, CASTLED)
castle_perm = update(castle_perm, WQC_INDEX, CASTLED)
elif from_tile_n == E1 and to_tile_n == C1 and board[from_tile_n] == 'K': # queen side castle
board = update(board, A1, 'o')
board = update(board, B1, 'o')
board = update(board, C1, 'K')
board = update(board... | STLED)
castle_perm = update(castle_perm, WQC_INDEX, CASTLED)
elif from_tile_n == E8 and to_tile_n == G8 and board[from_tile_n] == 'k': # king side castle
board = update(board, E8, 'o')
board = update(board, F8, 'r')
board = update(board, G8, 'k')
board = update(board, H8, 'o... |
fyffyt/pylearn2 | pylearn2/sandbox/nlp/linear/tests/test_matrixmul.py | Python | bsd-3-clause | 1,494 | 0 | """
Sandbox tests for the projection operator
"""
import numpy as np
import theano
from pylearn2.sandbox.nlp.linear.matrixmul import MatrixMul
from pylearn2.utils import sharedX
from theano import tensor
def test_matrixmul():
"""
Tests for projection
"""
rng = np.random.RandomState(222)
dtypes = ... | tensor.lmatrix(),
tensor.wvector(),
tensor.ivector(),
tensor.lvector()
]
np_W, np_x = [], []
for dtype in dtypes:
np_W.append(rng.rand(10, np.random.randint(1, 10) | ))
np_x.append(rng.randint(
0, 10, (rng.random_integers(5),
rng.random_integers(5))
).astype(dtype))
for dtype in dtypes:
np_W.append(rng.rand(10, np.random.randint(1, 10)))
np_x.append(
rng.randint(0, 10, (rng.random_integers(5),)).astype(... |
mrkulk/text-world | evennia/server/serversession.py | Python | bsd-3-clause | 11,791 | 0.001866 | """
This defines a the Server's generic session object. This object represents
a connection to the outside world but don't know any details about how the
connection actually happens (so it's the same for telnet, web, ssh etc).
It is stored on the Server side (as opposed to protocol-specific sessions which
are stored o... | d_total += 1
# Player-visible idle time, not used in idle timeout calcs.
self.cmd_last_visible = time()
def data_in(self, text=None, **kwargs):
"""
Send User->Evennia. This will in effect
execute a command string on the server.
| Note that oob data is already sent to the
oobhandler at this point.
"""
#explicitly check for None since text can be an empty string, which is
#also valid
if text is not None:
# this is treated as a command input
#text = to_unicode(escape_control_sequence... |
oli-kester/advanced-av-examples | amp-osc-lv2/.waf-1.8.5-3556be08f33a5066528395b11fed89fa/waflib/Tools/javaw.py | Python | gpl-2.0 | 10,068 | 0.053735 | #! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file
import os,re,tempfile,shutil
from waflib import TaskGen,Task,Utils,Options,Build,Errors,Node,Logs
from waflib.Configure import conf
from waflib.TaskGen import feature,before_m... | le(n.abspath())
self.generator.bld.task_sigs[self.uid()]=self.cache_sig
@feature('javadoc')
@after_method('process_rule')
def create_javadoc(self):
tsk=self.create_task('javadoc')
tsk.classpath=getattr(self,'classpath',[])
self.javadoc_package=Uti | ls.to_list(self.javadoc_package)
if not isinstance(self.javadoc_output,Node.Node):
self.javadoc_output=self.bld.path.find_or_declare(self.javadoc_output)
class javadoc(Task.Task):
color='BLUE'
def __str__(self):
return'%s: %s -> %s\n'%(self.__class__.__name__,self.generator.srcdir,self.generator.javadoc_output)
... |
eSpaceEPFL/marsissharadviewer | filters_marsis_viewer_dialog.py | Python | gpl-2.0 | 3,357 | 0.000596 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
FiltersMarsisViewerDialog
A QGIS plugin
MARSIS radargram viewer
-------------------
begin : 2015-08-14
git sha ... | bitnumber'))
# if orbits.has_key(key) == False:
# orbits[key] = []
# orbits[key].append((featur | e.attribute('point_id')))
#
# r_read = rr.PngReader(orbits.keys()[0], base_dir = "/home/federico/Documents/iMars/MARSIS_data_L2/L2_Data/BROWSE/")
#
self.set_active_layer(self.iface.activeLayer())
self.set_orbit_num(self.orbit)
self.set_data(self.data)
self.set_region(self.region[0... |
airspeed-velocity/asv | asv/extern/minify_json.py | Python | bsd-3-clause | 4,081 | 0.00294 | '''
Created on 20/01/2011
v0.2 (C) Gerald Storer
MIT License
Based on JSON.minify.js:
https://github.com/getify/JSON.minify
Contributers:
- Pradyun S. Gedam (conditions and variable names changed)
'''
import re
def json_minify(string, strip_space=True):
tokenizer = re.compile(r'"|(/\*)|(\*... | elif val == '*/' and in_multi and not (in_string or in_single):
in_multi = False
elif val in '\r\n' and not (in_multi or in_string) and in_single:
in_single = False
elif not ((in_multi or in_single) or (val in ' \r\n\t' and strip_space)):
new_str.append(val)
... | return ''.join(new_str)
if __name__ == '__main__':
# Python 2.6+ needed to run tests
import json
import textwrap
import unittest
class JsonMinifyTestCase(unittest.TestCase):
"""Tests for json_minify"""
def template(self, in_string, expected):
in_dict = json... |
ejhumphrey/osr-intro | midi_tools.py | Python | mit | 2,374 | 0 | """Compute statistics over midi files.
Usage
-----
# Run with default parameters
$ python midi_tools.py "data/*.mid" stats.json
# Run with full verbosity
$ python midi_tools.py "data/*.mid" stats.json --verbose 50
# Run with only one CPU
$ python midi_tools.py "data/*.mid" stats.json --n_jobs 1
# Run with two CPUs ... | urns
-------
counts : dict
Pitch counts over the file, keyed by pitch class.
"""
pitch_counts = {pc: 0 for pc in range(12)}
name = os.path.split(filename)[-1]
try:
midi = pretty_midi.PrettyMIDI(filename)
for inst in midi.instruments:
if inst.is_drum:
... | )
except IOError as derp:
print("woah buddy, {} died: {}".format(name, derp))
finally:
return {'name': name,
'pitches': pitch_counts}
def process_many(filenames, n_jobs, verbose):
pool = Parallel(verbose=verbose, n_jobs=n_jobs)
fx = delayed(compute_pitch_histogram)
... |
googleapis/python-dialogflow | samples/generated_samples/dialogflow_generated_dialogflow_v2beta1_intents_update_intent_sync.py | Python | apache-2.0 | 1,566 | 0.000639 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 ( | the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Lice | nse is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for UpdateIntent
# NOTE: This snippet has been automatica... |
jlaine/python-netfilter | netfilter/parser.py | Python | gpl-3.0 | 4,548 | 0.00352 | # -*- coding: utf-8 -*-
#
# python-netfilter - Python modules for manipulating netfilter rules
# Copyright (C) 2007-2012 Bolloré Telecom
# Copyright (C) 2013-2016 Jeremy Lainé
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
... | main_opt.match(bits[pos]):
opt_bits.append(bits[ | pos])
pos += 1
return opt_bits, pos
def pull_main_opt(bits, pos):
val = bits[pos]
pos += 1
if val == '!':
val += ' ' + bits[pos]
pos += 1
return val, pos
def parse_rule(spec):
rule = netfilter.rule.Rule()
bits = split_words(spec)
pos = 0
while pos < len(bits... |
MatKallada/nbgrader | nbgrader/tests/nbextensions/test_nbextension.py | Python | bsd-3-clause | 14,022 | 0.000998 | import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import Time... | (name)
def _select_none(browser, index=0):
select | = Select(browser.find_elements_by_css_selector('.celltoolbar select')[index])
select.select_by_value('')
def _select_manual(browser, index=0):
select = Select(browser.find_elements_by_css_selector('.celltoolbar select')[index])
select.select_by_value('manual')
def _select_solution(browser, index=0):
... |
dejay313/dojostreams | script.module.urlresolver/lib/urlresolver/plugins/vidspot.py | Python | gpl-2.0 | 2,031 | 0.005416 | '''
Allmyvideos urlresolver plugin
Copyright (C) 2013 Vinnydude
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program i... | s = ["vidspot.net"]
pattern = '(?://|\.)(vidspot\.net)/(?:embed-)?([0-9a-zA-Z]+)'
def __init__(self):
self. | net = common.Net()
def get_media_url(self, host, media_id):
url = self.get_url(host, media_id)
html = self.net.http_GET(url).content
data = helpers.get_hidden(html)
html = self.net.http_POST(url, data).content
r = re.search('"sources"\s*:\s*\[(.*?)\]', html, re.DOTALL)
... |
platinhom/ManualHom | Coding/Python/numpy-html-1.10.1/reference/generated/numpy-random-standard_t-1.py | Python | gpl-2.0 | 1,068 | 0.002809 | # From Dalgaard page 83 [R267]_, suppose the daily energy intake for 11
# women in Kj is:
intak | e = np.array([5260., 5470, 5640, 6180, 6390, 6515, 6805, 7515, \
7515, 8230, 8770])
# Does their energy intake deviate systematically from the recommended
# value of 7725 kJ?
# We have 10 degrees of freedom, so is the sample mean within 95% of the
# recommended value?
s = np.random.standard_t(10, ... | stic, setting the ddof parameter to the unbiased
# value so the divisor in the standard deviation will be degrees of
# freedom, N-1.
t = (np.mean(intake)-7725)/(intake.std(ddof=1)/np.sqrt(len(intake)))
import matplotlib.pyplot as plt
h = plt.hist(s, bins=100, normed=True)
# For a one-sided t-test, how far out in the ... |
Alexoner/web-crawlers | scripts/b-europe/processLog.py | Python | gpl-2.0 | 814 | 0.002457 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
def generateCode():
with open('./cityCode.log', mode='r') as fin:
for line in fin:
if len(line) > 0:
# print('processing {}'.format(line))
pass
| try:
codeObjs = json.loads(line)[0]
print(
'"{}|{}|{}|{}",'.format(
| codeObjs['Title'],
codeObjs['DisplayTitle'],
codeObjs['RCode'],
codeObjs['Synonyms'])
)
except Exception as e:
# raise e
# print(e.args)
pass
if __nam... |
ongardie/ramcloudfs | common_ancestor.py | Python | isc | 3,207 | 0 | #!/usr/bin/env python
# Copyright (c) 2010 Stanford University
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND ... | raise NotImplemented
def find_common_ancestor(root, left, right):
"""Find the paths to the lowest common ancestor of two L{Node}s in a tree.
This algorithm assumes that calling L{Node.get_parent} may be expensive but
testing L{Node} equality is cheap. It also assumes that the caller has no
know... | f the nodes in the tree (though it slightly favors
C{left} being deeper). The number of L{Node.get_parent} operations required
is on the order of twice the distance to the lowest common ancestor from
the node that is deeper in the tree.
@precondition: C{root} is a common ancestor of both C{left} and C{... |
wilvk/ansible | contrib/inventory/infoblox.py | Python | gpl-3.0 | 3,883 | 0.000773 | #!/usr/bin/env python
#
# (c) 2018, Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later v... | \n')
sys.exit(-1)
CONFIG_FILES = [
'/etc/ansible/infoblox.yaml',
'/etc/ansible/infoblox.yml'
]
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--list', action='store_true',
help='List host records from NIOS for use in Ansible')
parser.add_a... | le host (not used)')
return parser.parse_args()
def main():
args = parse_args()
for config_file in CONFIG_FILES:
if os.path.exists(config_file):
break
else:
sys.stdout.write('unable to locate config file at /etc/ansible/infoblox.yaml\n')
sys.exit(-1)
try:
... |
projectcalico/calico-neutron | neutron/tests/unit/agent/linux/test_ip_link_support.py | Python | apache-2.0 | 7,147 | 0 | # Copyright 2014 Mellanox Technologies, Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | ip_link
from neutron.tests import base
class TestIpLinkSupport(base.BaseTestCase):
IP_LINK_HELP = """Usage: ip link add [link DEV] [ name ] NAME
[ txqueuelen PACKETS ]
[ address LLADDR ]
[ broadcast LLADDR ]
[ mtu MTU ] [index | IDX ]
[ numtxqueues QUEUE_COUNT ]
[ numrxqueues QUEUE_COUNT ]
type TYPE [ ARGS ]
ip link delete DEV type TYPE [ ARGS ]
ip link set { dev DEVICE | group DEVGROUP } [ { up | down } ]
[ arp { on | off } ]
... |
tsnoam/python-telegram-bot | examples/legacy/echobot.py | Python | gpl-3.0 | 1,437 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Simple Bot to reply to Telegram messages
# This program is dedicated to the public domain under the CC0 license.
import logging
import telegram
from telegram.error import NetworkError, Unauthorized
from time import sleep
def main():
# Telegram Bot Authorization T... | over it in case
# we get an "Unauthorized" exception.
try:
update_id = bot.getUpdates()[0].update_id
except IndexError:
update_id = None
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' | )
while True:
try:
update_id = echo(bot, update_id)
except NetworkError:
sleep(1)
except Unauthorized:
# The user has removed or blocked the bot.
update_id += 1
def echo(bot, update_id):
# Request updates after the last update_id
fo... |
asajeffrey/servo | tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/manifestexpected.py | Python | mpl-2.0 | 15,420 | 0.001038 | import os
from collections import deque
from six import string_types, text_type
from six.moves.urllib.parse import urljoin
from .wptmanifest.backends import static
from .wptmanifest.backends.base import ManifestItem
from . import expected
"""Manifest structure used to store expected results of a test.
Each manifes... | ems, text_type):
node_items = [node_items]
for item in node_items:
process, value = item.rsplit(":", 1)
rv[process.strip()] = int(value.strip())
except KeyError:
pass
return rv
def fuzzy_prop(node):
"""Fuzzy reftest match
This can either be a list o... | ral format is
fuzzy = [key ":"] <prop> ";" <prop>
key = <test name> [reftype <reference name>]
reftype = "==" | "!="
prop = [propName "=" ] range
propName = "maxDifferences" | "totalPixels"
range = <digits> ["-" <digits>]
So for example:
maxDifferences=10;totalPixels=10-20
spec... |
ArcticWarriors/scouting-app | ScoutingWebsite/Scouting2011/model/validate_match.py | Python | mit | 2,608 | 0.008819 | '''
Created on Mar 4, 2017
@author: preiniger
'''
def __validate_alliance(alliance_color, teams, official_sr):
team1sr = None
team2sr = None
team3sr = None
# TODO: there has to be a better way... but I'd rather not touch the DB
for sr in teams[0].scoreresult_set.all():
if sr.match.matchN... | _srs:
tele_high_tubes += sr.high_tubes_hung
tele_mid_tubes += sr.mid_tubes_hung
tele_lo | w_tubes += sr.low_tubes_hung
total_score = tele_high_tubes * 3 + tele_mid_tubes * 2 + tele_low_tubes
if total_score != official_sr.total_score:
warning_messages.append((alliance_color + " total score", official_sr.total_score, total_score))
return warning_messages, error_mess... |
tommyjasmin/polar2grid | py/polar2grid_core/polar2grid/core/constants.py | Python | gpl-3.0 | 5,811 | 0.01153 | #!/usr/bin/env python
# encoding: utf-8
"""Module to store all constants. Any constant needed in more than one
component, or potentially more than one part, of polar2grid should be
defined here.
Rules/Preferences:
- All values lowercase
- strings
- user-legible (assume that they may be printed in log mess... | D_M = "m"
BKIND_I_ADAPTIVE = "iadapt"
BKIND_M_ADAPTIVE = "madapt"
BKIND_DNB = "dnb"
BKIND_VIS = "visible"
BKIND_IR = "infrared"
BKIND_IR_ADAPTIVE = "iradapt"
BKIND_CMASK = "cloud_mask"
BKIND_LSMSK = "land_sea_mask"
BKIND_SST = "sea_surface_temp"
BKIND_LST = "land_surface_temp"
BKIND_SLST = "summer_land_... | ace_temp"
BKIND_SZA = "solar_zenith_angle"
BKIND_CTT = "cloud_top_temperature"
BKIND_IST = "ice_surface_temperature"
BKIND_INV = "inversion_strength"
BKIND_IND = "inversion_depth"
BKIND_ICON = "ice_concentration"
BKIND_NDVI = "ndvi"
BKIND_TPW = "total_precipitable_water"
BKIND_CREFL = "crefl"
BKIND_TCOLOR... |
wbg-optronix-lab/emergence-lab | d180/models.py | Python | mit | 9,986 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from collections import OrderedDict
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from core.models import ActiveStateMixin, Process
@... | t(self.name, self.serial)
class D180GrowthInfo(models.Model):
"""
Stores info | rmation related to a growth on the d180 including tagging for
material and device properties.
"""
process = models.OneToOneField(Process, related_name='info')
platter = models.ForeignKey(Platter,
limit_choices_to={'is_active': True})
# layer materials
has_gan = m... |
mattihappy/mtibattery | mtibattery/helper.py | Python | gpl-3.0 | 1,265 | 0.002372 | """Helper functions
"""
import numpy as np
import datetime as dt
def bstr2seconds(data):
""" Converts a byte string to a timedelta object
Parameters
----------
data : bytestring
Contains a bytestring representing a timedelta
Returns
-------
dt.timedelta
timedelta object
... | ime = dt.timedelta(hours=int(hours), minutes=int(
minutes), seconds=int(seconds)).total_seconds()
return time
#return np.timedelta64(int(time), 's')
def str2timedelta(data):
""" Converts a string to a timedelta object
Parameters
----------
data : string
Contains a string repre... | dt.timedelta
timedelta object
"""
string = str(data)
# Use string starting from character 2 in order to remove
# the "b'" preceding the string in a byte string
hours, minutes, seconds = string.split(':')
time = dt.timedelta(hours=int(hours), minutes=int(
minutes), seconds=int(sec... |
yanggao1119/pylast | tests/unicode_test.py | Python | apache-2.0 | 727 | 0 | # -*- coding: utf-8 -* | -
import mock
import pytest
import six
import pylast
def mock_network():
return mock.Mock(
_get_ws_auth=mock.Mock(return_value=("", "", ""))
)
@pytest.mark.parametrize('artist', [
u'\xe9lafdasfdsafdsa', u'ééééééé',
pylast.Artist(u'B\xe9l', mock_network()),
'fdasfdsafsaf not unicode',
])... | work(), 'some_method',
params={'artist': artist})
request._get_cache_key()
@pytest.mark.parametrize('obj', [pylast.Artist(u'B\xe9l', mock_network())])
def test_cast_and_hash(obj):
assert type(six.text_type(obj)) is six.text_type
assert isinstance(hash(obj), int)
|
linkhub-sdk/popbill.cashbill.example.py | cancelIssue.py | Python | mit | 1,363 | 0.001771 | # -*- coding: utf-8 -*-
# code for console Encoding difference. Dont' mind on it
import sys
import imp
imp.reload(sys)
try:
sys.setdefaultencoding('UTF8')
except Exception as E:
pass
import testValue
from popbill import Ca | shbillService, PopbillException
cashbillService = CashbillSer | vice(testValue.LinkID, testValue.SecretKey)
cashbillService.IsTest = testValue.IsTest
cashbillService.IPRestrictOnOff = testValue.IPRestrictOnOff
cashbillService.UseStaticIP = testValue.UseStaticIP
cashbillService.UseLocalTimeYN = testValue.UseLocalTimeYN
'''
[발행완료] 상태의 현금영수증을 [발행취소] 합니다.
- 발행취소는 현금영수증을 국세청 신고하기 전까지만 ... |
mangaki/mangaki | mangaki/mangaki/tests/test_mal.py | Python | agpl-3.0 | 9,246 | 0.003677 | # SPDX-FileCopyrightText: 2014, Mangaki Authors
# SPDX-License-Identifier: AGPL-3.0-only
import os
import re
import xml.etree.ElementTree as ET
from unittest.mock import patch
import responses
from django.conf import settings
from django.contrib. | auth.models import User
from hypothesis.extra.django import TestCase
from mangaki import tasks
from mangaki.models import UserBackgroundTask, Work, WorkTitle
from mangaki.utils.mal import MALClient, MALWorks, MALUserWork, MALEntry
from hypothesis import given
from hypothesis import strategies as st
class MALTes | t(TestCase):
@staticmethod
def read_fixture(filename):
with open(os.path.join(settings.TEST_DATA_DIR, filename), 'r') as f:
return f.read()
def setUp(self):
self.mal = MALClient('test_client', 'test_client')
self.search_fixture = self.read_fixture('mal/code_geass_search.... |
orville-wright/EPL-datanalytics | eplda/eplda/spiders/myteam_spider.py | Python | gpl-3.0 | 2,760 | 0.021377 | import sys
import re
#
import scrapy
from scrapy.spider import Spider
from scrapy.selector import Selector
from scrapy.http import Request
from scrapy.http import HtmlResponse
from eplda.items import FixtureItem
#
import logging
class geteamnameSpider(scrapy.Spider):
name = "geteamname"
allowed_domains = ["premi... | ...")
user_uuid = response.url.split('/')
#logging.info('**** url splits - 0:%s 1:%s 2:%s 3:%s 4:%s' % (user_uuid[0], user_uuid[1], user_uuid[2], user_uuid[3], user_uuid[4]) )
print "Player unique uid: %s" % (user_uuid[4])
print | "Player name; %s" % (sel0.xpath('//*[@id="ism"]/section[2]/h1/text()').extract())
print "Team name; %s" % (sel0.xpath('//*[@id="ism"]/section[2]/div[1]/h2/text()').extract())
print "Gameweek points: %s" % (sel0.xpath('//*[@id="ism"]/section[2]/div[2]/div[2]/dl/dd[4]/a/text()').extract())
ret... |
PaulWay/insights-core | insights/parsers/cib.py | Python | apache-2.0 | 2,109 | 0.003319 | """
Pacemaker configuration - file ``/var/lib/pacemaker/cib/cib.xml``
=================================================================
This parser reads the XML in the Pacemaker configuration file and provides a
standard ElementTree interface to it. It also provides a ``nodes`` property
that lists all the nodes.
Sa... | >>> cib.nodes
['odchw1', 'pyatt', 'ford']
"""
from .. import Parser, parser
import xml.etree.ElementTree as ET
@parser("cib.xml")
class CIB(Parser):
"""
Wraps a DOM of cib.xml
self.dom is an instance of ElementTree.
"""
def parse_content(self, content):
self.dom = ET.fromstring(... | h the list of nodes and return their unames as a list.
"""
return [n.get("uname").lower() for n in self.dom.findall(".//nodes/node")]
|
yugangw-msft/azure-cli | src/azure-cli/azure/cli/command_modules/synapse/tests/latest/test_synapse_scenario.py | Python | mit | 144,042 | 0.004297 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | '
'--database-name "{database}" '
'--kusto-pool-name "{kustoPool}" '
'--location "{location}" '
'--consumer-group "$Default" '
'--event-hub-resource-id "{ehresourceid}" '
'--storage-account-resource-id "/subscriptions... | e-name "{workspace}"',
checks=[
self.check('name', "{workspace}/{kustoPool}/{database}/{dataConnectionName}"),
self.check('type', 'Microsoft.Synapse/workspaces/kustoPools/Databases/DataConnections'),
self.check('provisioningState', 'Succ... |
kivy/python-for-android | pythonforandroid/recipes/scipy/__init__.py | Python | mit | 2,185 | 0.004577 | from pythonforandroid.recipe import CompiledComponentsPythonRecipe, Recipe
from multiprocessing import cpu_count
from os.path import join
class ScipyRecipe(CompiledComponentsPythonRecipe):
version = '1.5.4'
url = f'https://github.com/scipy/scipy/releases/download/v{version}/scipy-{version}.zip'
site_pack... |
LIB = 'lib64' if '64' in arch.arch else 'lib'
prefix = env['TOOLCHAIN_PREFIX']
lapack_dir = join(Recipe.get_recipe('lapack', self.ctx).get_build_dir(arch.arch), 'build', 'install')
sysroot = f"{self.ctx.ndk_dir}/platforms/{env['NDK_API']}/{arch.platform_dir}"
sysroot_include = ... | ST}/{prefix}/{LIB}'
numpylib = self.ctx.get_python_install_dir(arch.arch) + '/numpy/core/lib'
LDSHARED_opts = env['LDSHARED'].split('clang')[1]
env['LAPACK'] = f'{lapack_dir}/lib'
env['BLAS'] = env['LAPACK']
env['F90'] = f'{prefix}-gfortran'
env['CXX'] += f' -Wl,-l{self.... |
wadda/Lunacy | lunacy.py | Python | gpl-2.0 | 10,999 | 0.025548 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from time import gmtime, strftime
import ephem
import wx.calendar
# Test
# here = ephem.Observer()
# here.lat = '-17.576166667'
# here.lon = '-149.618575000'
class App(wx.App):
def OnInit(self):
self.frame = MyFrame("Lunacy", (50, 60), (640, 220))
self.frame.Show()
... | lf.sntime = wx.StaticText(self, wx.ID_ANY, u"solar noon", wx.DefaultPosition, wx.DefaultSize, 0 | )
self.sntime.Wrap(-1)
fgSizer2.Add(self.sntime, 0, 0, 5)
self.snaltitude = wx.StaticText(self, wx.ID_ANY, u"altitude", wx.DefaultPosition, wx.DefaultSize, 0)
self.snaltitude.Wrap(-1)
fgSizer2.Add(self.snaltitude, 0, 0, 5)
self.staticText_Sunset = wx.StaticText(self, wx.ID_ANY, u"Sunset", wx.DefaultPositi... |
DESHRAJ/Audio-Scraper | djangoaudio/manage.py | Python | gpl-2.0 | 254 | 0 | #!/usr/ | bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoaudio.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv | )
|
itf/track | track_qt/qt_common.py | Python | apache-2.0 | 1,714 | 0.002334 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
from PyQt4 import QtCore #, Qt, uic, QtGui
class change_emitter:
def __init__(self, emitter):
self._emitter = emitter
def __enter__(self):
self._emitter.layoutAboutToBeChanged.emit()
return self
def __exit__(self, type, value, tb):
... | def data(self, index, role):
if not index.isValid():
return None
elif role != Q | tCore.Qt.DisplayRole:
return None
return self._data(index.row(), index.column())
def _data(self, row, column):
return self._mylist[row][column]
def headerData(self, col, orientation, role):
if (orientation == QtCore.Qt.Horizontal and
role == QtCore.Qt.Dis... |
cysuncn/python | spark/crm/PROC_O_IBK_WSYH_ECACCT.py | Python | gpl-3.0 | 6,823 | 0.012771 | #coding=UTF-8
from pyspark import SparkContext, SparkConf, SQLContext, Row, HiveContext
from pyspark.sql.types import *
from datetime import date, datetime, timedelta
import sys, re, os
st = datetime.now()
conf = SparkConf().setAppName('PROC_O_IBK_WSYH_ECACCT').setMaster(sys.argv[2])
sc = SparkContext(conf = conf)
sc.... | CCT.registerTempTable("O_CI_WSYH_ECACCT")
#任务[12] 001-01::
V_STEP = V_STEP + 1
#先删除原表所有数据
ret = os.system("hdfs dfs -rm -r /"+dbname+"/F_CI_WSYH_ECACCT/*.parquet")
#从昨天备表复制一份全量过来
ret = os.system("hdfs dfs -cp -f /"+dbname+"/F_CI_WSYH_ECACCT_BK/"+V_DT_LD+".parquet | /"+dbname+"/F_CI_WSYH_ECACCT/"+V_DT+".parquet")
F_CI_WSYH_ECACCT = sqlContext.read.parquet(hdfs+'/F_CI_WSYH_ECACCT/*')
F_CI_WSYH_ECACCT.registerTempTable("F_CI_WSYH_ECACCT")
sql = """
SELECT A.CIFSEQ AS CIFSEQ
,A.ACSEQ AS ACSEQ
,A.DEPTSEQ AS DEPTSEQ
... |
sahat/bokeh | bokeh/__init__.py | Python | bsd-3-clause | 8,912 | 0.005274 | from __future__ import absolute_import, print_function
from ._version import get_versions
import os
try:
from .__conda_version__ import conda_version
__version__ = conda_version.replace("'","")
del conda_version
except ImportError:
__version__ = get_versions()['version']
del get_versions
_notebook... | and 2 prints the test names while testing.
xunitfile : string, optional
If provided, writes the test results to an xunit
style xml file. This is useful for running the tests
| in a CI server such as Jenkins.
exit : bool, optional
If True, the function will call sys.exit with an
error code after the tests are finished.
"""
import nose
import os
import sys
argv = [' |
MOA-2011/enigma2 | lib/python/Plugins/SystemPlugins/Satfinder/plugin.py | Python | gpl-2.0 | 10,493 | 0.028305 | from enigma import eDVBResourceManager,\
eDVBFrontendParametersSatellite, eDVBFrontendParameters
from Screens.Screen import Screen
from Screens.ScanSetup import ScanSetup
from Screens.ServiceScan import ServiceScan
from Screens.MessageBox import MessageBox
from Plugins.Plugin import PluginDescriptor
from Components.... | tend():
self.fron | tend = None # in normal case this should not happen
self.tuner = Tuner(self.frontend)
self.retune(None)
def __onClose(self):
self.session.nav.playService(self.session.postScanService)
def createSetup(self):
self.list = []
self.satfinderTunerEntry = getConfigListEntry(_("Tuner"), self.satfinder_scan_nims)
... |
vispeal/VoteHelper | weibonews/weibonews/utils/image.py | Python | gpl-2.0 | 2,495 | 0.003607 | '''
Created on Dec 31, 2011
@author: fli
'''
import logging
import base64
import urllib
import simplejson
from urllib2 import urlopen, URLError, Request
from weibonews.utils.decorators import perf_logging
_LOGGER = logging.getLogger('weibonews.external')
_ACCESS_URL_FORMAT = "http://%s/image/%s/%s"
_INFO_URL_FORMAT ... |
return None
result = simplejson.loads(page)
_LOGGER.info("[Image Compress Service] Get | %d result from %d request from %s" % (len(result['data']), len(urls), server_url))
return result['data']
return None
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.