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 |
|---|---|---|---|---|---|---|---|---|
qrsforever/workspace | python/learn/base/atexit/autorm.py | Python | mit | 190 | 0.015789 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import atexit
import time
import os
def cleanup(fi | le):
print(file)
atexit.register(cleanup, "/tmp/a.txt")
time.sleep(100)
os.waitpi | d(0,0)
|
Shaswat27/sympy | sympy/stats/tests/test_finite_rv.py | Python | bsd-3-clause | 8,667 | 0.001961 | from sympy.core.compatibility import range
from sympy import (FiniteSet, S, Symbol, sqrt,
symbols, simplify, Eq, cos, And, Tuple, Or, Dict, sympify, binomial,
cancel, KroneckerDelta)
from sympy.concrete.expr_with_limits import AddWithLimits
from sympy.matrices import Matrix
from sympy.stats import (Disc... | y = X.symbol, Y.symbol
# Domains
d = where(X > Y)
assert d.condition == (x > y)
d = where(And(X > Y, Y > 3))
assert d.as_boolean() == Or(And(Eq(x, 5), Eq(y, 4)), And(Eq(x, 6),
Eq(y, 5)), And(Eq(x, 6), Eq(y, 4)))
assert len(d.elements) == 3
assert len(pspace(X + Y).domain.elements) ... | == FiniteSet(1, 2, 3, 4, 5, 6)**2
assert where(X > 3).set == FiniteSet(4, 5, 6)
assert X.pspace.domain.dict == FiniteSet(
*[Dict({X.symbol: i}) for i in range(1, 7)])
assert where(X > Y).dict == FiniteSet(*[Dict({X.symbol: i, Y.symbol: j})
for i in range(1, 7) for j in range(1, 7) if i... |
jiaphuan/models | research/object_detection/utils/np_mask_ops.py | Python | apache-2.0 | 4,214 | 0.005458 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | ric,
that is, IOA(mask1, mask2) != IOA(mask2, mask1).
Args:
masks1: a numpy array with shape [N, height, width] holding N masks. Masks
values are of type np.uint8 and values are in {0,1}.
masks2: a numpy array with shape [M, height, width] holding N masks. Masks
values are of type np.uint8 and ... | Returns:
a numpy array with shape [N, M] representing pairwise ioa scores.
Raises:
ValueError: If masks1 and masks2 are not of type np.uint8.
"""
if masks1.dtype != np.uint8 or masks2.dtype != np.uint8:
raise ValueError('masks1 and masks2 should be of type np.uint8')
intersect = intersection(masks... |
pombredanne/zero-install | zeroinstall/0launch-gui/browser.py | Python | lgpl-2.1 | 419 | 0.031026 | # Copyright (C) 2009, Thomas Leonard
# See | the README file for details | , or visit http://0install.net.
import os, sys
def open_in_browser(link):
browser = os.environ.get('BROWSER', 'firefox')
child = os.fork()
if child == 0:
# We are the child
try:
os.spawnlp(os.P_NOWAIT, browser, browser, link)
os._exit(0)
except Exception, ex:
print >>sys.stderr, "Error", ex
os._e... |
RagtagOpen/bidwire | bidwire/alembic/versions/b73811be5f44_add_all_basic_bid_fields.py | Python | mit | 1,068 | 0 | """add all basic bid fields
Revision ID: b73811be5f44
Revises: 72beaff4cf57
Create Date: 2017-04-03 00:53:50.692376
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b73811be5f44'
down_revision = '72beaff4cf57'
branch_label | s = None
depends_on = None
def upgrade():
op.add_column('bids', sa.Column('description', sa.Text))
op.add_column('bids', sa.Column('department', sa.Text))
op.add_column('bids', sa.Column('organization', sa.Text))
op.add_column('bids', sa.Column('location', sa.Text))
op.add_column('bids', sa.Column... | .drop_column('bids', sa.Column('department', sa.Text))
op.drop_column('bids', sa.Column('organization', sa.Text))
op.drop_column('bids', sa.Column('location', sa.Text))
op.drop_column('bids', sa.Column('open_date', sa.DateTime))
op.drop_column('bids', sa.Column('items', sa.JSON))
|
fiete201/qutebrowser | qutebrowser/__init__.py | Python | gpl-3.0 | 1,276 | 0 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2021 Florian Bruhin (The Compiler) <[email protected]>
#
# This file is part of qutebrowser.
#
# qutebrowser 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 S... | with qutebrowser. If not, see <https://www.gnu.org/licenses/>.
"""A | keyboard-driven, vim-like browser based on PyQt5."""
import os.path
__author__ = "Florian Bruhin"
__copyright__ = "Copyright 2014-2021 Florian Bruhin (The Compiler)"
__license__ = "GPL"
__maintainer__ = __author__
__email__ = "[email protected]"
__version__ = "2.0.0"
__version_info__ = tuple(int(part) for part in... |
HiSPARC/station-software | user/python/Lib/test/test_int.py | Python | gpl-3.0 | 20,013 | 0.000999 | import sys
import unittest
from test import test_support
from test.test_support import run_unittest, have_unicode
import math
L = [
('0', 0),
('1', 1),
('9', 9),
('10', 10),
('99', 99),
('100', 100),
('314', 314),
(' 314', 314),
('314 ', 314),
... | g)
x = int(-1e100)
self.assertIsInstance(x, long)
# SF bug 434186: 0x80000000/2 != 0x80000000>>1.
# Worked by accident in Windows release build, but failed in debug build.
# Failed in all Linux builds.
x = -1-sys.maxint
self.assertEqual(x >> 1, x//2)
s... | self.assertRaises(ValueError, int, '53', 40)
# SF bug 1545497: embedded NULs were not detected with
# explicit base
self.assertRaises(ValueError, int, '123\0', 10)
self.assertRaises(ValueError, int, '123\x00 245', 20)
x = int('1' * 600)
self.assertIsInstance(x, long)
... |
robinandeer/puzzle | puzzle/plugins/gemini/__init__.py | Python | mit | 78 | 0.012821 | f | rom .mixins import (CaseMixin, VariantMixin)
from .plugin import GeminiPlug | in |
Jaaga/mooc-tracker | web/mooctracker/mooctracker/settings.py | Python | mit | 3,176 | 0.001889 | """
Django settings for mooctracker project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...... | RITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'... | 'courses',
'projects',
'academics',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.message... |
spotify/pyeos | test/unit/config.py | Python | apache-2.0 | 730 | 0 | # Copyright 2014 Spotify AB. All rights reserved.
#
# The contents of this file are 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 CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
hostname = '192.168.76.10'
username = 'dbarroso'
password = 'this_is_not_a_secure_password'
use_ssl = True
|
previtus/MGR-Project-Code | Settings/set2_dataset-expansion/expand_dataset_forserver_minlen30_kfold_forcomparison.py | Python | mit | 4,101 | 0.014874 | def Setup(Settings,DefaultModel):
# set2_for_results/expand_dataset_forserver_minlen30_kfold_forcomparison.py
Settings["experiment_name"] = "ExpandDataset_5556x_minlen30_640px_kfold10_originalComparison"
Settings["graph_histories"] = ['together']
n=0
from keras.preprocessing.image import ImageD... | hear_range=0., # Shear Intensity (Shear angle in counter-clockwise direction as radians)
zoom_range=0., # Float or [lower, upper]. Range for random zoom. If a float, [lower, upper] = [1-zoom_range, 1+zoom_range].
channel_shift_range=0., # Range for random channel shifts.
fill_mode='nearest', # O... | "wrap"}. Points outside the boundaries of the input are filled according to the given mode.
cval=0., # Float or Int. Value used for points outside the boundaries when fill_mode = "constant".
horizontal_flip=False, # Randomly flip inputs horizontally.
vertical_flip=False, # Randomly flip inputs v... |
tiangolo/fastapi | docs_src/query_params/tutorial006b.py | Python | mit | 301 | 0 | from typing import Union |
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id | }")
async def read_user_item(
item_id: str, needy: str, skip: int = 0, limit: Union[int, None] = None
):
item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
return item
|
TheOtherOtherOperation/vdbsetup | vdbsetup.py | Python | mit | 34,423 | 0.003166 | #!/usr/bin/env python3
#
# vdbsetup.py - script for building Vdbench configurations
#
# Author: Ramon A. Lovato (ramonalovato.com)
# For: DeepStorage, LLC (deepstorage.net)
#
import argparse
import os.path
import os
import re
import statistics
import textwrap
import random
import numpy as np
import matplotlib as mpl
... | ": None, # Qeueue depth
"elapsed": None, # | Duration
"interval": None, # Update frequency
# Distribution
"hotspotnum": None, # Number of hotspots
"hotspotcap": None, # Total capacity percent for all hotspots
"hotspotiopct": None, # Percent of IO for ALL hotspots
"disttype": None # Distribut... |
neumerance/deploy | .venv/bin/rst2xml.py | Python | apache-2.0 | 619 | 0.001616 | #!/var/www/horizon/.venv/bin/python
# $Id: rst2xml.py 4564 2006-05-21 20:44:42Z wiemann $
# Author: David Goodger <[email protected]>
# Copyright: This module has been placed in the publi | c domain.
"""
A minimal front end to the Docutils Publisher, producing Docutils XML.
"""
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.core import publish_cmdline, default_description
description = ('Generates Docutils-native XML from standalone '
'reS... | ult_description)
publish_cmdline(writer_name='xml', description=description)
|
9929105/KEEP | keep_backend/api/serializers.py | Python | mit | 4,452 | 0.024259 | import re
import StringIO
import unicodecsv
from django.utils.text import slugify
from tastypie.serializers import Serializer
class CSVSerializer( Serializer ):
formats = [ | 'json', 'jsonp', 'csv' ]
content_types = {
'json': 'application/json',
'jsonp': 'text/javascript',
'csv': 'text/csv',
}
FLOAT_TYPE = re.compile(r'^(\d+\.\d*|\d*\.\d+)$')
INT_TYPE = re.compile(r'^\d+$')
LOCATION_TYPE = re.compile(r'^(\-?\d+(\. | \d+)?) \s*(\-?\d+(\.\d+)?) \s*(\d+) \s*(\d+)$')
def _sniff_type( self, val ):
'''
A really stupid and bare-bones approach to data type detection.
'''
if self.FLOAT_TYPE.match( val ):
return 'decimal'
elif self.INT_TYPE.match( val ):
return 'int'
... |
scraperwiki/stock-tool | tests.py | Python | agpl-3.0 | 5,818 | 0 | #!/usr/bin/env python
# encoding: utf-8
import datetime
import unittest
import mock
import pandas as pd
import pandas_finance
from pandas.util.testing import assert_frame_equal
from nose.tools import assert_equal
from freezegun import freeze_time
class GetStockTestCase(unittest.TestCase):
@mock.patch('pandas_fi... | isoformat string.
output_values['Date'] = '2014-04-29'
output_values['Stock'] = 'AAPL'
output_columns = ['Date'] + input_columns + ['Stock']
self.output_frame = pd.DataFrame(output_values, columns=output_columns)
@mock.patch('pandas_finance.write_frame_to_sql')
@mock.patch('pand... | mock_write_frame):
mock_get_stock.return_value = self.input_frame
pandas_finance.scrape_stock('AAPL', self.start, self.end)
# Hacky workaround:
# Can't seem to use mock.assert_called_with; problem when comparing
# dataframes, grab argument directly and compare it... |
steenzout/python-storj | tests/unit/exception_test.py | Python | mit | 2,882 | 0 | # -*- coding: utf-8 -*-
"""Test cases for the storj.exception module."""
from .. import AbstractTestCase
from storj.exception import \
BridgeError, \
ClientError, \
FarmerError, \
HashMismatchError, \
SuppliedTokenNotAcceptedError
class BridgeErrorTestCase(AbstractTestCase):
"""Test case for... | lf):
expected_code = 0
expected_message = 'error'
error = BridgeError(expected_code, expected_message)
self.assertBridgeError(error, expected_code, expected_message)
class ClientErrorTestCase(AbstractTestCase):
"""Test case for the C | lientError."""
@staticmethod
def assertClientError(error, message):
"""Assert ClientError expected conditions.
Args:
error (:py:class:`storj.exception.BridgeError`): result.
message (str): expected error message.
"""
assert message == error.message
... |
eoogbe/api-client-staging | generated/python/gapic-google-cloud-spanner-v1/google/cloud/gapic/spanner/v1/spanner_client.py | Python | bsd-3-clause | 38,513 | 0.001792 | # Copyright 2017, Google Inc. All rights reserved.
#
# 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 ... | 2
from google.cloud.proto.sp | anner.v1 import mutation_pb2
from google.cloud.proto.spanner.v1 import spanner_pb2
from google.cloud.proto.spanner.v1 import transaction_pb2
from google.protobuf import struct_pb2
class SpannerClient(object):
"""
Cloud Spanner API
The Cloud Spanner API can be used to manage sessions and execute
trans... |
ctuning/ck | ck/repo/module/soft.template/module.py | Python | bsd-3-clause | 826 | 0.001211 | #
# Collective Knowledge (Base soft templates to be reused via inheritance mechanism)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
##
# Developer: Grigori Fursin, [email protected], http://fursin.net
#
cfg = {} # Will be updated | by CK (meta description of this module)
work = {} # Will be updated by CK (temporal data)
ck = None # Will be updated by CK (initialized CK kernel)
# Local settings
#################################################################### | ##########
# Initialize module
def init(i):
"""
Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
return {'return': 0}
|
enovance/hardware | hardware/tests/test_matcher.py | Python | apache-2.0 | 21,360 | 0 | # Copyright (C) 2013-2015 eNovance SAS <[email protected]>
#
# 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 appl... | GB'),
('disk', '$disk7', 'size', '1000GB'),
('disk', '$disk8', 'size', '1000GB')]
arr = {}
self.assertTrue(matcher.match_all(lines, specs, arr, {}))
self.assertEqual(arr,
{'disk1': '2I:1:7',
'disk2': '2I:1:8',
... | '1I:1:4',
'disk7': '2I:1:5',
'disk8': '2I:1:6',
}
)
def test_already_bound(self):
lines = [
('disk', '1I:1:2', 'size', '100GB'),
('disk', '1I:1:1', 'size', '1000GB'),
... |
oscm/devops | docker/docker.py | Python | mit | 942 | 0.005308 | #!/usr/bin/env python3
import sys
sys.path.insert(0, '/Users/neo/workspace/devops')
from netkiller.docker import *
# from environment.experiment import experiment
# from environment.development import development
# from environment.production import production
from compose.devops import devops
from compose.demo impor... | p_count": "262144"})
# docker.environment(experiment)
# docker.environment(development)
# docker.environment(logging)
docker.environment(devops)
# docker.environment(portainer)
docker.environment(demo)
docker.main()
except Keyboa | rdInterrupt:
print("Crtl+C Pressed. Shutting down.") |
AsherYang/ThreeLine | server/ffstore/mgrsys/RandomPwd.py | Python | apache-2.0 | 580 | 0 | #! /usr/bin/python
# -*- coding:utf-8 -*-
| """
Author: AsherYang
Email: [email protected]
Date: 2018/6/29
Desc: 产生6位随机短信验证码类
"""
import random
class RandomPwd:
def __init__(self):
pass
def genPwd(self):
a_list = []
while le | n(a_list) < 6:
x = random.randint(0, 9)
# if x not in s:
a_list.append(x)
print a_list
string = ''.join(list(map(str, a_list)))
return string
if __name__ == '__main__':
randomPwd = RandomPwd()
print randomPwd.genPwd()
|
skibyte/gdblib | gdblib/util.py | Python | lgpl-3.0 | 864 | 0.006944 | #
# GdbLib - A Gdb python library.
# Copyright (C) 2012 Fernando Castillo
#
| # This program 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 Software Found | ation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for mo... |
vansky/meg_playground | scripts/tileRegressionSeeRSquared_EpochsBack.py | Python | gpl-2.0 | 11,071 | 0.029988 | import scipy
import pickle
import numpy
import sklearn.linear_model
import matplotlib #needed to avoid having to run an X-server just to output to a png
matplotlib.use('Agg') #needed to avoid having to run an X-server just to output to a png
import pylab
import re
def adjustR2(R2, numFeatures, numSamples):
#1/0
... | aka lasso/ridge)
trainX = mynormalise(explanatoryFeatures)
trainY = mynormalise(wordEpochs[:,t])
#trainX = explanatoryFeatures
#trainY = wordEpochs[:,t]
trainedLM = lm.fit(trainX,trainY)
modelParameters.append(lm)
#guessY = lm.predict(testX)
#guessTestSemantics[:,dim] = guessY
modelTrainingFit.append(... | TestSemantics[:,dim])[1,0])
#print '\t\tdone, explaining R^2 of',modelTrainingFit[-1],'reg param',trainedLM.alpha_,'betas',modelParameters[-1].coef_
#print '\t\tdone, explaining R^2 of',modelTrainingFit[-1],'betas',modelParameters[-1].coef_, lm.alpha_ #'chose reg param of',lm.best_alpha # lm.alphas_[0] # lm.best_... |
ericremoreynolds/fsiox | server.py | Python | mit | 559 | 0.007156 | import gevent
import gevent.monkey
gevent.monkey.patch_all()
from time import sleep
import flask
from flask_socketio import SocketIO, emit
app = flask.Fl | ask(__name__)
app.config['SECRET_KEY'] = 'secret!'
io = SocketIO(app, resource="/api/v1/socket")
@io.on('connect')
def on_connect():
print("Client connected")
@io.on('hello_f | rom_client')
def on_hello_from_client():
for i in range(3):
emit('message_from_server', str(i))
print("Sent %s" % i)
sleep(1)
if __name__ == '__main__':
io.run(app, port=9090, debug=True) |
mattmcd/PyAnalysis | mda/tutorial/__init__.py | Python | apache-2.0 | 107 | 0.009346 | # List | of modules exported by mda.tutorial
# from mda.tutorial import *
__all__ = ['t | imes2', 'pandastut']
|
torchingloom/edx-platform | pavelib/assets.py | Python | agpl-3.0 | 6,729 | 0 | """
Asset compilation and collection.
"""
from __future__ import print_function
import argparse
from paver.easy import sh, path, task, cmdopts, needs, consume_args, call_task
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
import glob
import traceback
from .utils.envs imp... | "static" / "sass"]
else:
return []
def coffeescript_files():
"""
return find command for paths containing coffee files
"""
dirs = " ".join([Env.REPO_ROOT / coffee | _dir for coffee_dir in COFFEE_DIRS])
return cmd('find', dirs, '-type f', '-name \"*.coffee\"')
def compile_coffeescript(*files):
"""
Compile CoffeeScript to JavaScript.
"""
if not files:
files = ["`{}`".format(coffeescript_files())]
sh(cmd(
"node_modules/.bin/coffee", "--compil... |
hyphenliu/cnminlangwebcollect | src/gui/about.py | Python | gpl-3.0 | 935 | 0.010989 | # -*- coding:utf-8 -*-
'''
Created on 2013年12月31日
@author: Hyphen.Liu
'''
import wx
import wx.html
import globalvar.guiGlobalVar as ggv
class About(wx.Dialog):
'''
:关于本软件的功能等信息界面
'''
text = ggv.aboutText
def __init__(self, parent):
'''
:创建窗口并显示软件功能相关信息
:param parent:主界面窗口
... |
html.SetPage(self.text)
button = wx.Button(self, wx.ID_OK, u"确认")
sizer = wx.BoxSizer(wx.VERTICAL) #使用容器包含部件
sizer.Add(html, 1, wx.EXPAND|wx.ALL, 0)
sizer.Add(button, 0, wx.ALIGN_CENTER|wx.ALL, 5)
self.SetS | izer(sizer) #添加容器到窗口
self.Layout() |
1986ks/chainer | chainer/functions/activation/clipped_relu.py | Python | mit | 1,839 | 0.002175 | from chainer import cuda
from chainer import function
from chainer import utils
from chainer.utils import type_check
import numpy
class ClippedReLU(function.Function):
"""Clipped Rectifier Unit function.
Clipped ReLU is written as :math:`ClippedReLU(x, z) = | \min(\max(0, x), z)`,
where :math:`z(>0)` is a parameter to cap return value of ReLU.
"""
def __init__(self, z):
if not isinstance(z, float):
raise TypeError('z must be float value')
# z must be positive.
assert z > 0
self.cap = z
def check_type_forward(sel... |
def forward_cpu(self, x):
return utils.force_array(numpy.minimum(
numpy.maximum(0, x[0]), self.cap)).astype(numpy.float32),
def backward_cpu(self, x, gy):
return utils.force_array(
gy[0] * (0 < x[0]) * (x[0] < self.cap)).astype(numpy.float32),
def forward_gpu(self... |
nkraft/educollections | test_educollections.py | Python | bsd-2-clause | 1,009 | 0.000991 | from educollections import ArrayList
def print_list_state(lst):
print('Size is', lst.size())
print('Contents are', lst)
print()
arr = ArrayList(10)
print('Capacity is', arr.capacity())
print_list_state(arr)
for i in range(10):
print('Prepend', i)
arr.prepend(i)
print_list_state(arr)
for i in ... | 'from index', i)
print_list_state(arr)
arr.clear()
pr | int_list_state(arr)
for i in range(5):
print('Append', i)
arr.append(i)
print_list_state(arr)
for i in [2, 3, 0, 7, 8]:
print('Insert', i + 10, 'at index', i)
arr.insert(i, i + 10)
print_list_state(arr)
|
ULHPC/modules | easybuild/easybuild-easyblocks/easybuild/easyblocks/q/quantumespresso.py | Python | mit | 14,580 | 0.003704 | ##
# Copyright 2009-2015 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (htt... |
repls.append(('%s_LIBS' % lib, val, False))
libs.append(val)
libs = ' '.join(libs)
repls.append(('BLAS_LIBS_SWITCH', 'external', False))
repls.append(('LAPACK_LIBS_SWITCH', 'external', False))
repls.append(('LD_LIBS', | os.getenv('LIBS'), False))
self.log.debug("List of replacements to perform: %s" % repls)
# patch make.sys file
fn = os.path.join(self.cfg['start_dir'], 'make.sys')
try:
for line in fileinput.input(fn, inplace=1, backup='.orig.eb'):
for (k, v, keep) in repls... |
spahan/unixdmoain | lib/test/dbmcache.py | Python | bsd-3-clause | 164 | 0.012195 |
import UniDomain.UniDomain as UniDomain
import UniDomain.dbmcache as dbmcache
host = UniDomain.host()
db = dbmcache | .dbmNode(dbpath=host.config["cachedir"])
| |
ales-erjavec/orange-bio | orangecontrib/bio/widgets3/OWMAPlot.py | Python | gpl-3.0 | 18,714 | 0.000641 | import sys
import os
from functools import partial, reduce
import numpy
from AnyQt.QtGui import QPainter
from AnyQt.QtCore import QObject, QSize, QThread, QThreadPool, Slot
import pyqtgraph as pg
import Orange.data
from Orange.widgets import widget, gui, settings
from Orange.widgets.utils import concurrent
from .... | self.redirect.pro | gressBarSet(value)
finally:
self._delay = False
def withexcepthook(func):
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except BaseException as ex:
sys.excepthook(*sys.exc_info())
raise
return wrapped
class OW... |
barseghyanartur/django-rest-framework-hstore | tests/drf_hstore_tests/urls.py | Python | mit | 492 | 0.010163 | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = pa | tterns('',
# Uncomment the next line to enable the admin:
url(r'^admin/', include | (admin.site.urls)),
)
from .views import urlpatterns as test_urlpatterns
urlpatterns += test_urlpatterns
if 'grappelli' in settings.INSTALLED_APPS:
urlpatterns += patterns('',
url(r'^grappelli/', include('grappelli.urls')),
) |
mhbu50/frappe | frappe/core/doctype/communication/communication.py | Python | mit | 17,315 | 0.027317 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from collections import Counter
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import validate_email_address, strip_html, cstr, time_diff_in_seconds
from frappe.core.doct... | page comment
frappe.publish_realtime('new_message', self.as_dict(),
user=self.reference_name, after_commit=True)
def on_update(self):
# add to _comment property of the doctype, so it shows up in
# comments count for the list view
update_comment_in_doc(self)
if self.comment_type != 'Updated':
upda... | r_mailid(self):
return parse_addr(self.sender)[1] if self.sender else ""
@staticmethod
def _get_emails_list(emails=None, exclude_displayname = False):
"""Returns list of emails from given email string.
* Removes duplicate mailids
* Removes display name from email address if exclude_displayname is True
"""... |
ministryofjustice/addressfinder | manage.py | Python | mit | 256 | 0 | #!/usr/bin/env python
import os |
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "addressfinder.settings")
from django.core.management import execute_from_command_line
execute_from_comman | d_line(sys.argv)
|
JasonLC506/CollaborativeFiltering | traintestSplit.py | Python | mit | 1,241 | 0.016116 | import numpy as np
def split(frac_training,frac_valid, datafile, file_train, file_valid, file_test):
f_train = open(file_train, "w")
f_valid = open(file_valid, "w")
f_test = open | (file_test, "w")
ntrain = 0
nvalid = 0
ntest = 0
with open(datafile, "r") as f:
for line in f:
setID = np.argmax(np.random.multinomial(1, [frac_training, frac_valid, 1-frac_training-frac_valid], size = 1))
if setID == 0:
f_train.write(line)
... | 1
elif setID == 1:
f_valid.write(line)
nvalid += 1
elif setID == 2:
f_test.write(line)
ntest += 1
else:
print "error"
print ntrain
print nvalid
print ntest
if __name__ == "__main__":
fr... |
kaushik94/sympy | sympy/core/decorators.py | Python | bsd-3-clause | 4,618 | 0.000217 | """
SymPy core decorators.
The purpose of this module is to expose decorators without any other
dependencies, so that they can be easily imported anywhere in sympy/core.
"""
from __future__ import print_function, division
from functools import wraps
from .sympify import SympifyError, sympify
from sympy.core.compatib... | def __sympifyit_wrapper(a, b):
return func(a, sympify(b, strict=True))
else:
@wraps(func)
def __sympifyit_wrapper(a, b):
try:
# If an external class has _op_priority, it knows how to deal
| # with sympy objects. Otherwise, it must be converted.
if not hasattr(b, '_op_priority'):
b = sympify(b, strict=True)
return func(a, b)
except SympifyError:
return retval
return __sympifyit_wrapper
def call_highest_priority(method... |
ma-renaud/Basement_Monitoring_GUI | state_machine.py | Python | gpl-3.0 | 218 | 0 | class StateMachine:
def __init__(self, initial_state):
self.currentState = initial_state
# Template method:
def proces | s(self, inputs):
for i in | inputs:
self.currentState.run(i)
|
Arno-Nymous/pyload | module/database/StorageDatabase.py | Python | gpl-3.0 | 1,952 | 0.005123 | # -*- coding: utf-8 -*-
"""
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 is distributed in ... | alue):
db.c.ex | ecute("SELECT id FROM storage WHERE identifier=? AND key=?", (identifier, key))
if db.c.fetchone() is not None:
db.c.execute("UPDATE storage SET value=? WHERE identifier=? AND key=?", (value, identifier, key))
else:
db.c.execute("INSERT INTO storage (identifier, key, value) VALUE... |
mattrobenolt/django-casscache | example/example/settings.py | Python | bsd-3-clause | 5,718 | 0.001224 | # Django settings for example project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '[email protected]'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', ... | pplication'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
... | contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'django_casscache',
)
CACHE... |
JiscPER/magnificent-octopus | octopus/modules/account/authorise.py | Python | apache-2.0 | 679 | 0.010309 | from octopus.core import app
class Authorise(object):
@classmethod
def has_role(cls, role, reference):
# if we are the super user we can do anything
| if app.config["ACCOUNT_SUPER_USER_ROLE"] in reference:
return True
# if the user's role list contains the role explicitly then do it
if role in reference:
return True
# later we will want to expand the user's roles to the full set and see if the r... | but for now, if we get here we have failed to authorise
return False
|
hanya/MRI | pythonpath/mytools_Mri/web.py | Python | apache-2.0 | 12,480 | 0.005849 | # Copyright 2011 Tsutomu Uchino
#
# 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 ... | ath)
def set_sdk_path(self, sdk_path):
"""set sdk directory path."""
if sdk_path.endswith('/'):
path = sdk_path
else:
path = "%s/" % sdk_path
self.sdk_path = path
def set_browser(self, browser):
"""set browser path."""
We | b.set_browser(self, uno.fileUrlToSystemPath(browser).replace("\\", '/'))
def open_url(self, url):
try:
Web.open_url(self, url)
except:
self.cast.error("Fix your browser configuration.")
def open_idl_reference(self, idltarget, word=''):
"""Open IDL Refere... |
aeklant/scipy | pavement.py | Python | bsd-3-clause | 23,552 | 0.003397 | """
This paver file is intended to help with the release process as much as
possible. It relies on virtualenv to generate 'bootstrap' environments as
independent from the user system as possible (e.g., to make sure the sphinx doc
is built against the built SciPy, not an installed one).
The release is assumed to be don... | installers=Bunch(releasedir="release",
installersdir=os.path.join("release", "installers")),
doc=Bunch(doc_root="doc",
sdir=os.path.join("doc", "source"),
bdir=os.path.join("doc", "build"),
bdir_latex=os.path.join("doc", "build", "latex"),
... | h.join("build_doc", "pdf")),
html=Bunch(builddir=os.path.join("build", "html")),
dmg=Bunch(python_version=PYVER),
bdist_wininst_simple=Bunch(python_version=PYVER),)
# Where we can find BLAS/LAPACK/ATLAS on Windows/Wine
SITECFG = {"sse3" : {'BLAS': 'None', 'LAPACK': 'None',
... |
jiaphuan/models | research/real_nvp/imnet_formatting.py | Python | apache-2.0 | 3,296 | 0 | # Copyright 2016 Google Inc. All Rights Reserved.
#
# 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 a... | n_64x64.tar valid_64x64.tar
do
curl -O http://image-net.org/small/$FILENAME
tar -xvf $FILENAME
done
Then use the script as follow:
for DIRNAME in train_32x32 valid_32x32 train_64x64 valid_64x64
do
python imnet_formatting.py \
--file_out $DIRNAME \
--fn_root $DIRNAME
done
"""
from __future... | FINE_string("file_out", "",
"Filename of the output .tfrecords file.")
tf.flags.DEFINE_string("fn_root", "", "Name of root file path.")
FLAGS = tf.flags.FLAGS
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
r... |
jdrusso/last_letter | uav_utils/setup.py | Python | gpl-3.0 | 307 | 0.003257 | ## | ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
# fetch values from package.xml
setup_args = generate_distutils_setup(
| packages=['uav_utils'],
package_dir={'': 'src'})
setup(**setup_args)
|
laonawuli/addrest | web2py/applications/admin/controllers/default.py | Python | mit | 73,035 | 0.003711 | # -*- coding: utf-8 -*-
EXPERIMENTAL_STUFF = True
MAXNFILES = 1000
if EXPERIMENTAL_STUFF:
if is_mobile:
response.view = response.view.replace('default/', 'default.mobile/')
response.menu = []
import re
from gluon.admin import *
from gluon.fileutils import abspath, read_file, write_file
from gluon... | db.app.insert(name=appname, owner=auth.user.id)
log_progress(appname)
session.flash = T('ne | w application "%s" created', appname)
redirect(URL('design' |
MakeHer/edx-platform | common/test/acceptance/tests/lms/test_lms_matlab_problem.py | Python | agpl-3.0 | 3,475 | 0.00259 | # -*- coding: utf-8 -*-
"""
Test for matlab problems
"""
import time
from ...pages.lms.matlab_problem import MatlabProblemPage
from ...fixtures.course import XBlockFixtureDesc
from ...fixtures.xqueue import XQueueResponseFixture
from .test_lms_problems import ProblemsTest
from textwrap import dedent
class MatlabProb... | Tests that verify matlab problem "Run Code".
"""
def get_problem(self):
"""
Create a matlab problem for the test.
"""
problem_data = dedent("""
<problem markdown="null">
<text>
<p>
Write MATLAB code to crea... | </p>
<table id="a0000000466" class="equation" width="100%" cellspacing="0" cellpadding="7" style="table-layout:auto">
<tr>
<td class="equation">[1 1 2 3 5 8 13]</td>
</tr>
</table>
... |
the-duck/launcher-next | src/duck/launcher/defaultConfig.py | Python | gpl-2.0 | 1,166 | 0.031732 | #! /usr/bin/python
# -*- coding: utf-8 -*-
#########
#Copyright (C) 2014-2015 Mark Spurgeon <[email protected]>
# 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 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warrant... |
LLNL/spack | var/spack/repos/builtin/packages/sirius/package.py | Python | lgpl-2.1 | 11,824 | 0.003298 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *
class Sirius(CMakePackage, CudaPackage):
"""Domain specific library for electronic st... | as')
depends_on('amdblis threads=openmp', when='+openmp ^amdblis')
depends_on('blis threads=openmp', when='+openmp ^blis')
depends_on('intel-mkl threads=openmp', when='+openmp ^intel-mkl')
depends_on('elpa+openmp', when='+elpa+openmp')
depends_on('elpa~openmp', when='+elpa~openmp')
# TODO:
... | for CRAY_LIBSCI, testing
patch("strip-spglib-include-subfolder.patch", when='@6.1.5')
patch("link-libraries-fortran.patch", when='@6.1.5')
patch("cmake-fix-shared-library-installation.patch", when='@6.1.5')
patch("mpi_datatypes.patch", when="@:7.2.6")
@property
def libs(self):
librari... |
static-code-generators/taskzilla | taskzilla/migrations/0001_initial.py | Python | mit | 949 | 0.003161 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Task',
fields=[
('id', models.AutoField(auto_cr... |
('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),
],
),
migrations.AddField(
model_name='task',
name='subscribers',
field=models.ManyToManyField(to='taskz | illa.User'),
),
]
|
openevacmap/openevac-back | src/routes/stat.py | Python | agpl-3.0 | 1,126 | 0.005329 | # -*- coding: utf-8 -*-
'''
Created on 21 janv. 2016
@author: christian
'''
import falcon
import os
import config
import db
class Stat(object):
'''
Get global statistics
'''
def on_get(self, req, resp):
'''Return global statistics
'''
dbc = db.conne... | nb_maps":%s,"nb_addr":%s,"last_map":"%s"}',
count(*),
count(distinct(address)),
left(max(time)::text,19)) as stats from maps;"""
cur.execute(query)
stats = cur.fetchone()[0]
resp.set_header('X-Powered-By', 'OpenEvacMap')
if... | else:
resp.status = falcon.HTTP_200
resp.set_header('Access-Control-Allow-Origin', '*')
resp.set_header('Access-Control-Allow-Headers',
'X-Requested-With')
resp.body = (stats)
cur.close()
db... |
pierg75/pier-sosreport | sos/plugins/nss.py | Python | gpl-2.0 | 1,276 | 0 | # 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 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but... | Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin
class NSS(Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin):
"""Network Security Services configuration
"""
plugin_name = "nss"
profiles = ('network', 'securit... | ('nss.*',)
def setup(self):
self.add_forbidden_path([
"/etc/pki/nssdb/cert*",
"/etc/pki/nssdb/key*",
"/etc/pki/nssdb/secmod.db"
])
self.add_copy_spec("/etc/pki/nssdb/pkcs11.txt")
# vim: set et ts=4 sw=4 :
|
makerbot/conveyor | virtualenv.py | Python | agpl-3.0 | 101,937 | 0.002953 | #!/usr/bin/env python
"""Crea | te a "virtual" Python installation
"""
# If you change the version here, change it in setup.py
# and docs/conf.py as well.
virtualenv_version = "1.7.1.2"
import base64
import sys
import os
import optparse
import re
| import shutil
import logging
import tempfile
import zlib
import errno
import distutils.sysconfig
from distutils.util import strtobool
try:
import subprocess
except ImportError:
if sys.version_info <= (2, 3):
print('ERROR: %s' % sys.exc_info()[1])
print('ERROR: this script requires Python 2.4 or... |
feigaochn/leetcode | p659_split_array_into_consecutive_subsequences.py | Python | mit | 1,129 | 0 | #!/usr/bin/env python
# coding: utf-8
class Solution:
def isPossible(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums:
return False
vcs = [[nums[0], 1]]
for n in nums[1:]:
if n == vcs[-1][0]:
| vcs[-1][1] += 1
else:
vcs.append([n, 1])
cur = [vcs[0][0], vcs[0][1], 0, 0, 0]
for v, c in vcs[1:]:
if v > cur[0] + 1:
if cur[1] > 0 or cur[2] > 0:
return False
else:
cur = [v, c, 0, 0... | ))),
cur[1],
cur[2] + min(cur[3], c - (cur[1] + cur[2]))]
return cur[1] == 0 and cur[2] == 0
if __name__ == '__main__':
sol = Solution().isPossible
print(sol([1, 2, 3, 3, 4, 5]))
print(sol([1, 2, 3, 4, 4, 5]))
print(sol([1, 2, 3, 3, 4, 4, 5, 5]))
|
avian2/unidecode | setup.py | Python | gpl-2.0 | 1,387 | 0.002163 | #!/usr/bin/python
# vi:tabstop=4:expandtab:sw=4
import os
from setuptools import setup
def get_long_description():
with open(os.path.join(os.path.dirname(__file__), "README.rst"), encoding='utf-8') as fp:
return fp.read()
setup(
name='Unidecode',
version='1.3.3',
description='ASCII translite... | = unidecode.util:main'
]
},
classifiers=[
"License :: OSI Approved :: GNU Gener | al Public License v2 or later (GPLv2+)",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: ... |
addition-it-solutions/project-all | addons/point_of_sale/controllers/main.py | Python | agpl-3.0 | 1,015 | 0.010837 | # -*- coding: utf-8 -*-
import logging
import werkzeug.utils
from openerp import http
from openerp.http import request
from openerp.addons.web.controllers.main import login_redirect, abort_and_redirect
_logger = logging.getLogger(__name__)
class PosController(http.Controller):
@http.route('/pos/web', type='htt... | t()
PosSession = request.registry['pos.session']
pos_session_ids = PosSession.search(cr, uid, [('state','=','opened'),('u | ser_id','=',session.uid)], context=context)
if not pos_session_ids:
return werkzeug.utils.redirect('/web#action=point_of_sale.action_pos_session_opening')
PosSession.login(cr, uid, pos_session_ids, context=context)
return request.render('point_of_sale.index')
|
slaff/attachix | server/core/provider/storages/meta/db.py | Python | mit | 8,100 | 0.005802 | # @todo: Refactor this method to work as the HBase meta class !!!
from copy import copy
from core.pattern import ActiveRecord, TableDataGateway
import time
NODE_COLLECTION = 1
NODE_FILE = 0
DEPTH_NODE = 0
DEPTH_CHILDREN = 1
DEPTH_INFINITY = -1
class Meta(ActiveRecord):
_definition = {
'loca... | = '%s%s/' % (parentNode.path, self.id)
else:
self.path = '/%s/' % self.id
ActiveRecord.save(self)
def getChildren(self, depth=1):
finder = Search()
nodes = finder.findByPat | h(self._data['path'], depth)
return nodes
def copy(self):
node = Node(self.db)
for (name, value) in self._data.items():
if name == 'id':
continue
setattr(node,name,value)
return node
def link(self, name, parentNode):
targetNode = ... |
overxfl0w/Grampus-Forensic-Utils | Metadata/Image/XMP/GIF/gifxmp.py | Python | gpl-2.0 | 1,117 | 0.046553 | from mmap import mmap
## exiftool -xmp-dc:subject=Metadatos XMP de prueba ./test.gif ##
class gifxmp:
def __init__(self,filename):
self.mmaped = self.__mmap(filename)
self.fst = self. | __checkxmp()
if self.fst != -1:
self.xml = self.__loadxmppacket()
print self.xml
## dict = ModuleXML.parsexmp(self.xml) ##
def __mmap(self,filename):
with open(filename,"r+b") as fd:
_ = mmap(fd.fileno(),0)
fd.close()
return _
## Comprueba que el header es correcto, solo se comprobara la ex... | n de XMP en la cabecera. Se pivotara a partir de aqui
def __checkxmp(self):
return self.mmaped.find("XMP Data")
## Leemos el paquete, boundary primera ocurrencia del header + 12 bytes de la comprobacion, hasta el mismo + 256
## 256 -> (258 - 2 bytes del block terminate)
def __loadxmppacket(self):
blcktrmt = ... |
vrai/gfmviewer-wx | setup.py | Python | gpl-2.0 | 953 | 0.023085 | from distutils.core import setup
setup (
name = 'gfmviewer',
version = '0.1.0',
description = 'View a Github Formatted Markdown file as formatted HTML',
scripts = [ 'gfmviewer' ],
author = 'Vrai Stacey',
author_email = '[email protected]',
url = 'http://github.com/vrai/gfmviewer-wx',
... | d to watch the file.
However if this is not available, or it is disabled with the --poll option,
the file's modification time will be checked once a second.
On most platforms (current not includi | ng OS X) the --fork option will cause
the viewer to run in the background, detached from the terminal used to start
it. """ )
# vim: ft=python:sw=4:ts=4:et
|
Greh/Project-Euler | euler5.py | Python | mit | 132 | 0.022727 | print ("project | eule | r problem 5 find the smallest number divisible by each number smaller than twenty")
print 16*9*5*7*11*13*17*19
|
matheuskiser/pdx_code_guild | django/tango_with_django_project/rango/migrations/0003_category_slug.py | Python | mit | 444 | 0 | # -*- coding: utf-8 -*-
| from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('rango', '0002_auto_20150401_0132'),
]
operations = [
migrations.AddField(
model_name='category',
name='slug',
fi... | unique=True),
preserve_default=False,
),
]
|
z-jason/anki | aqt/forms/setgroup.py | Python | agpl-3.0 | 2,025 | 0.003951 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'designer/setgroup.ui'
#
# Created: Sun Mar 30 10:19:30 2014
# by: PyQt4 UI code generator 4.10.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
exc... | def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Dialog(object):
def setupUi(self, Dialog):
... | setObjectName(_fromUtf8("Dialog"))
Dialog.resize(433, 143)
self.verticalLayout_2 = QtGui.QVBoxLayout(Dialog)
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.label = QtGui.QLabel(Dialog)
self.label.setObjectName(_fromUtf8("label"))
self.verticalLayo... |
geopython/pywps | tests/test_execute.py | Python | mit | 30,624 | 0.001404 | ##################################################################
# Copyright 2018 Open Source Geospatial Foundation and others #
# licensed under MIT, Please consult LICENSE.txt for details #
##################################################################
import unittest
import pytest
from pywps import xml... | outputs=[BoundingBoxOutput('outbbox', 'Output message', ["EPSG:4326"])])
def create_complex_proces(mime_type: str = 'gml'):
def complex_proces(request, r | esponse):
response.outputs['complex'].data = request.inputs['complex'][0].data_as_json()
return response
if mime_type == 'gml':
frmt = Format(mime_type='application/gml', extension=".gml") # this is unknown mimetype
elif mime_type == 'geojson':
frmt = FORMATS.GEOJSON
else:
... |
samowitsch/bCNC | bCNC/lib/python_utils/import_.py | Python | gpl-2.0 | 2,797 | 0 |
from __future__ import absolute_import
class DummyException(Exception):
pass
def import_global(
name, modules=None, exceptions=DummyException, locals_=None,
globals_=None, level=-1):
'''Import the requested items into the global scope
WARNING! this method _will_ overwrite your global s... | globals_[k] = getattr(module, k)
except exceptions as e:
| return e
finally:
# Clean up, just to be sure
del name, modules, exceptions, locals_, globals_, frame
|
teedoo/dotfiles | .sublime/Packages/PackageDev/completions_dev.py | Python | mit | 921 | 0.001086 | import sys
import s | ublime_plugin
if sys.version_info < (3,):
from sublime_lib.pa | th import root_at_packages, get_package_name
else:
from .sublime_lib.path import root_at_packages, get_package_name
PLUGIN_NAME = get_package_name()
COMPLETIONS_SYNTAX_DEF = ("Packages/%s/Syntax Definitions/Sublime Completions.tmLanguage"
% PLUGIN_NAME)
TPL = """{
"scope": "... |
tomv564/LSP | plugin/hover.py | Python | mit | 11,187 | 0.002414 | import mdpopups
import sublime
import sublime_plugin
import webbrowser
import os
from html import escape
from .code_actions import actions_manager, run_code_action_or_command
from .code_actions import CodeActionOrCommand
from .core.configurations import is_supported_syntax
from .core.popups import popups
from .core.pro... | self._diagnostics_by_config = filter_by_point(view_diagnostics(self.view),
| Point(*self.view.rowcol(hover_point)))
if self._diagnostics_by_config:
self.request_code_actions(hover_point)
self.request_show_hover(hover_point)
def request_symbol_hover(self, point: int) -> None:
# todo: session_for_view looks up w... |
cbernet/cpyroot | tools/fitter2d.py | Python | gpl-2.0 | 1,550 | 0.008387 | from ROOT import gDirectory, TH2F, TH1F, TFile
class Fitter2D(object):
def __init__(self, *args):
self.h2d = TH2F(*args)
def draw2D(self, *args):
self.h2d.Draw(*args)
self.hmean.Draw('psame')
def fit(self, bin, opt='0'):
hslice = self.h2d.ProjectionY("", bin, bin, ""... | SetXTitle(xtitle)
def write(self):
outfile = TFile(self.h2d.GetName()+'.root', 'recreate')
for hist in [self.hmean, self.hsigma, self.hchi2, self.h2d]:
hist.Clone()
his | t.SetDirectory(outfile)
outfile.Write()
outfile.Close()
|
ichung/karaoke-chan | kchan/timedtext.py | Python | mit | 2,694 | 0.00297 | #! /usr/bin/python2
import re
from kchan.lyrics import Lyrics
def load(lyricsData):
"""Parse text with timestamps into a Lyrics instance
Args:
lyricsData (str): String containing text and timestamps. There may be
any number of timestamps, in any order, at any locations, but they must
... | hey will just be [mm:ss] (rounded to the nearest second).
Defaults to False.
cr (bool): whether to use CRLF newlines. Defaults to False.
Returns:
str. A string containing phrases and timestamps.
"""
phrases = [[phrase.replace('\n', '\r\n') if crlf else phrase]
for... | dths = time % 100
if frac:
phrases[idx].insert(-1, "[{:02}:{:02}.{:02}]".format(minutes, seconds, hundredths))
else:
phrases[idx].insert(-1, "[{:02}:{:02}]".format(minutes, seconds + (1 if hundredths >= 50 else 0)))
return ''.join(''.join(l) for l in phrases)
|
agepoly/mezzanine | mezzanine/pages/migrations/0015_auto__add_field_page_title_fr_CH__add_field_page_title_en__add_field_p.py | Python | bsd-2-clause | 8,423 | 0.006174 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as 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 'Page.title_fr_CH'
db.add_column(u'pages_page', 'title_fr_... | _page', '_meta_title_en')
# Deleting field 'Page.description_fr_CH'
db.delete_column(u'pages_page', 'description_fr_CH')
# Deleting field 'Page.description_en'
db.delete_column(u'pages_page', 'description_en')
# Deleting field 'Page.titles_fr_CH'
db.delete_column(u'pag... | db.delete_column(u'pages_richtextpage', 'content_fr_CH')
# Deleting field 'RichTextPage.content_en'
db.delete_column(u'pages_richtextpage', 'content_en')
models = {
u'pages.link': {
'Meta': {'ordering': "(u'_order',)", 'object_name': 'Link', '_ormbases': [u'pages.Page']},
... |
barrazamiguel/pydrez | modelo/tuple.py | Python | gpl-3.0 | 157 | 0.025478 | # -*- encoding: utf-8 -*-
def tupleToString(t):
return reduce(lambda x, y: str(x) +" "+ st | r(y), t)
def stringTo | Tuple(s):
return tuple(s.split(" ")) |
chromium/chromium | tools/grit/grit/node/node_io_unittest.py | Python | bsd-3-clause | 6,562 | 0.004267 | #!/usr/bin/env python3
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''Unit tests for node_io.FileNode'''
from __future__ import print_function
import os
import sys
import unittest
if __name__ ==... | ations.AddChild(file_node)
root.EndParsing()
self.failUnless(root.ToRealPath(file_node.GetInputPath()) ==
util.normpath(
os.path.join(r'../resource', r'flugel/kugel.pdf')))
def VerifyCliquesContainEnglishAndFrenchAndNothingElse(self | , cliques):
self.assertEqual(2, len(cliques))
for clique in cliques:
self.assertEqual({'en', 'fr'}, set(clique.clique.keys()))
def testLoadTranslations(self):
xml = '''<?xml version="1.0" encoding="UTF-8"?>
<grit latest_public_release="2" source_lang_id="en-US" current_release="3" base_dir=".... |
mhugent/Quantum-GIS | python/plugins/processing/ProcessingPlugin.py | Python | gpl-2.0 | 6,571 | 0.002587 | # -*- coding: utf-8 -*-
"""
***************************************************************************
ProcessingPlugin.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
**********************... | e
Processing.initialize()
def initGui(self):
self.commander = None
self.toolbox = ProcessingToolbox()
interface.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox) |
self.toolbox.hide()
#Processing.addAlgListListener(self.toolbox)
self.menu = QMenu(interface.iface.mainWindow().menuBar())
self.menu.setObjectName( 'processing' )
self.menu.setTitle(QCoreApplication.translate('Processing',
'Processing'))
self... |
mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/lib/galaxy/webapps/galaxy/api/group_roles.py | Python | gpl-3.0 | 5,199 | 0.027313 | """
API operations on Group objects.
"""
import logging
from galaxy.web.base.controller import BaseAPIController, url_for
from galaxy import web
log = logging.getLogger( __name__ )
class GroupRolesAPIController( BaseAPIController ):
@web.expose_api
@web.require_admin
def index( self, trans, group_id, **k... | group = trans.sa_session.query( | trans.app.model.Group ).get( decoded_group_id )
role = trans.sa_session.query( trans.app.model.Role ).get( decoded_role_id )
for gra in group.roles:
if gra.role == role:
item = dict( id = role_id,
name = role.name,
... |
dknlght/dkodi | src/addons_xml_generator3.py | Python | gpl-2.0 | 8,998 | 0.005001 | #!/usr/bin/python
# *
# * Copyright (C) 2012-2013 Garrett Brown
# * Copyright (C) 2010 j48antialias
# *
# * 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 2, or (at y... | 3.0, 3.1 and 3.2 not supporting u"" literals
print(sys.version)
if sys.version < '3':
import codecs
def u(x):
return codecs.unicode_escape_decode(x)[0]
else:
def u(x):
return x
class Generator:
"""
Generates a new addons.xml file from each addons addon.xml file
and a n... | ngle depth folder structure.
"""
def __init__(self):
# generate files
self._generate_addons_file()
self._generate_md5_file()
# notify user
print("Finished updating addons xml and md5 files\n")
def _generate_addons_file(self):
# addon list
addons = so... |
fab13n/caracole | floreal/signals/__init__.py | Python | mit | 97 | 0 | imp | ort | django.dispatch
task_generate_pre_save = django.dispatch.Signal(providing_args=["task"])
|
Maistho/CouchPotatoServer | couchpotato/core/_base/_core.py | Python | gpl-3.0 | 13,193 | 0.00523 | from uuid import uuid4
import os
import platform
import signal
import time
import traceback
import webbrowser
import sys
from couchpotato.api import addApiView
from couchpotato.core.event import fireEvent, addEvent
from couchpotato.core.helpers.variable import cleanHost, md5, isSubFolder, compareVersions
from couchpot... | should NOT use your CouchPotato directory to save your settings in. Files will get overwritten or be deleted.')
return True
def cleanUpFolders(self):
only_clean = ['couchpotato', 'libs', 'init']
self.deleteEmptyFolder(Env.get('app_dir'), show_error = False, only_clean = only_clean)
de... | lse
def shutdown():
self.initShutdown()
if IOLoop.current()._closing:
shutdown()
else:
IOLoop.current().add_callback(shutdown)
return 'shutdown'
def restart(self, **kwargs):
if self.shutdown_started:
return False
de... |
briandrawert/molnsutil | run_ensemble_map_aggregate.py | Python | gpl-3.0 | 3,303 | 0.002725 | import pickle
def run_ensemble_map_and_aggregate(model_class, parameters, param_set_id, seed_base, number_of_trajectories, mapper,
aggregator=None, cluster_import=False):
""" Generate an ensemble, then run the mappers are aggregator. This will not store the results. """
if... | {0}: {1}\n".format(type(e), e)
notes += "type(mapper) = {0}\n".format(type(mapper))
notes += "type(aggregator) = {0}\n".format(type(aggregator))
notes += "dir={0}\n{1}".format(dir(), traceback.format_exc())
raise MolnsUtilException(notes)
return {'result': res, 'par... | id, 'num_successful': num_processed,
'num_failed': number_of_trajectories - num_processed}
if __name__ == "__main__":
try:
import molnsutil.constants as constants
import molnsutil.molns_cloudpickle as cloudpickle
with open(constants.job_input_file_name, "rb") as inp:
... |
jainaman224/zenodo | tests/unit/deposit/test_api_buckets.py | Python | gpl-2.0 | 9,093 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo 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 of the
# License, or (at your option) any later v... | hat all the buckets are different
assert len(set([rec_v1_bucket, dep_v1_bucket, dep_v2_bucket])) == 3
# Get file from old version deposit bucket
res = client.get(dep_v1_bucket + '/test.txt', headers=auth)
dep_v1_file_data = res.get_data(as_text=True)
# Get file from old version record bucket
r... | ersion deposit bucket
res = client.get(dep_v2_bucket + '/test.txt', headers=auth)
dep_v2_file_data = res.get_data(as_text=True)
# Assert that the file is the same in the new version
assert rec_v1_file_data == dep_v1_file_data == dep_v2_file_data
# Record bucket is unlocked.
res = client.put(
... |
bitcraft/pyglet | contrib/experimental/buffer/bars.py | Python | bsd-3-clause | 2,705 | 0 | #!/usr/bin/python
# $Id:$
import random
import sys
from pyglet.gl import *
from pyglet import clock
from pyglet import font
from pyglet import graphics
from pyglet import window
BARS = 100
if len(sys.argv) > 1:
BARS = int(sys.argv[1])
MIN_BAR_LENGTH = 4
MAX_BAR_LENGTH = 100
BAR_SEGMENT_HEIGHT = 10
UPDATE_PERIOD... | ces = bar.vertices
# Update new vertices (overwrite old degenerate)
for i in range((old_length - 1) * 2, length * 2):
if i & 1: # y
vertices[i] = BAR_SEGMENT_HEIGHT * (i // 4)
else: # x
vertices[i] = vertices[i - 4]
# Update top degener... | bar.colors[old_length * 3:length * 3] = \
bar.colors[:3] * (length - old_length)
stats_text = font.Text(font.load('', 12, bold=True), '',
x=win.width, y=0,
halign='right')
def update_stats(dt):
np = len(bars)
usage = bars[0].domain.allo... |
landlab/landlab | landlab/graph/structured_quad/__init__.py | Python | mit | 426 | 0 | from .dual_structured_quad import (
DualRectilinearGraph,
DualStructuredQuadGraph,
DualUniformRectilinearGraph | ,
)
from .structured_quad import (
RectilinearGraph,
StructuredQuadGraph,
UniformRectilinearGraph,
)
__all__ = [
"StructuredQuadGraph",
"RectilinearGraph",
"UniformRectilinearGraph",
"DualUniformRectilinearGraph",
"DualRectilinearGraph",
"DualStructuredQuadGra | ph",
]
|
apagac/cfme_tests | cfme/tests/services/test_provision_stack.py | Python | gpl-2.0 | 11,067 | 0.001626 | import fauxfactory
import pytest
from wait_for import wait_for
fr | om cfme import test_requirements
from cfme.cloud.provider import CloudProvider
from cfme.cloud.provider.azure import AzureProvider
from cfme.cloud.provider.ec2 import EC2Provider
from cfme.cloud.provider.openstack import OpenStackProvider |
from cfme.markers.env_markers.provider import ONE_PER_TYPE
from cfme.services.myservice import MyService
from cfme.services.service_catalogs import ServiceCatalogs
from cfme.utils.appliance.implementations.ui import navigate_to
from cfme.utils.conf import credentials
from cfme.utils.datafile import load_data_file
from... |
eevee/cocos2d-mirror | test/test_callfunc.py | Python | bsd-3-clause | 1,086 | 0.02302 | # This code is so you can run the samples without ins | talling the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#
testinfo = "s, t 1.1, s, q"
tags = "CallFunc, visible"
import cocos
from cocos.director import director
from cocos.actions import CallFunc, Delay
from cocos.sprite import Sprite
import pyglet
class TestLayer(... | t_window_size()
self.sprite = Sprite( 'grossini.png', (x/2, y/2) )
self.sprite.visible = False
self.add( self.sprite )
def make_visible( sp ):
sp.visible = True
self.sprite.do( Delay(1) + CallFunc( make_visible, self.sprite ) )
description = """Sprite grossini star... |
gongbudaizhe/bilib | demos/hash_it_out/solution.py | Python | mit | 541 | 0.007394 | def compute_single_digest(single_message, last_message):
return (129 * single_message ^ last_message) % 256
def | reverse_single_digest(single_digest, last_message):
for i in xrange(256):
if single_digest == compute_single_digest(i, last_message):
return i
def answer(x):
last_message = 0
message = []
for single_digest in x:
single_message = reverse_single_digest(single_digest, last_mes... | |
adrianco/cassandgo | aws.py | Python | apache-2.0 | 5,522 | 0.046903 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os,sys,logging,socket,collections,boto,boto.ec2
# Init
conf_HVM = [ # DataStax AMI in all regions
{'region':'us-east','zone':'1','ami':'ami-ada2b6c4','sg':'SG-Cassandra-us-east-1','key':'Key-us-east-1'},
{'region':'us-west','zone':'1','ami':'ami-3cf7c979','sg':'... | nst = ec2.get_all_instances()
for res in all_inst:
for instance in res.instan | ces:
instances.append(instance)
return instances
except Exception as e:
logError(e)
return None
def listInstancesRegionZone(region,zone):
"""
List all instances for a specific region and zone
"""
print "-"*80
print "# Region :",region," Zone", zone
print "-"*80
instances = getInstancesRegionZone(re... |
SeanEstey/Bravo | app/notify/sms_announce.py | Python | gpl-2.0 | 2,703 | 0.012579 | '''app.notify.sms_announce'''
import os
import twilio
from flask import g, request
from datetime import datetime, date, time, timedelta
from dateutil.parser import parse
from pymongo.collection import ReturnDocument
from app import get_keys, colors as c
from app.main.etapestry import call, get_prim_phone, EtapError, ge... | ) == '1':
notific = g.db['notifics'].find_one_and_update({
'tracking.sid': request.form['CallSid'],
}, {
'$set': {
'tracking.digit': request.form['Digits']
}},
return_document= | ReturnDocument.AFTER)
from twilio.twiml.messaging_response import MessagingResponse
response = MessagingResponse()
response.play(notific['on_answer']['audio_url'], voice='alice')
response.gather(
num_digits=1,
action="%s/notify/voice/play/interact.xml" % os.en... |
airbnb/superset | superset/migrations/versions/67a6ac9b727b_update_spatial_params.py | Python | apache-2.0 | 1,978 | 0 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | censes/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the Lic | ense 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.
"""update_spatial_params
Revision ID: 67a6ac9b727b
Revises: 4736ec66ce19
Create Date: 2017-12-08 ... |
ckaus/EpiPy | epipy/ui/view/plotwidget.py | Python | mit | 1,934 | 0 | # -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4 | \
import NavigationToolbar2QT as | NavigationToolbar
from matplotlib.backends.backend_qt4agg import \
FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class PlotWidget(QtGui.QWidget):
"""This class represents the plot view for plotting graphs.
:returns: an instance of *PlotWidget*
"""
def __init__(self):
... |
John-Colvin/clFFT | src/scripts/perf/fftPerformanceTesting.py | Python | apache-2.0 | 11,827 | 0.006426 | # ########################################################################
# Copyright 2013 Advanced Micro Devices, 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.apach... | r])
elif type(attr) == str:
setattr(args, x, attr.split(','))
return args
class Range:
def __init__(self, ranges, defaultStep='+1'):
# we might be passed in a single value or a list of strings
# if we receive a single value, we want to feed it right back
if type(rang... | self.expanded = []
for thisRange in ranges:
thisRange = str(thisRange)
if re.search('^\+\d+$', thisRange):
self.expanded = self.expanded + [thisRange]
elif thisRange == 'max':
self.expanded = self.expanded + ['... |
mfeit-internet2/pscheduler-dev | pscheduler-server/pscheduler-server/api-server/pschedulerapiserver/tests.py | Python | apache-2.0 | 4,144 | 0.003861 | #
# Test-Related Pages
#
import pscheduler
from pschedulerapiserver import application
from flask import request
from .dbcursor import dbcursor_query
from .json import *
from .response import *
#
# Tests
#
# All tests
@application.route("/tests", methods=['GET'])
def tests():
return json_query("SELECT json FR... | arry out test <name>
@application.route("/tests/<name>/tools", methods=['GET'])
def | tests_name_tools(name):
# TODO: Should probably 404 if the test doesn't exist.
# TODO: Is this used anywhere?
expanded = is_expanded()
cursor = dbcursor_query("""
SELECT
tool.name,
tool.json
FROM
tool
JOIN tool_test ON tool_test.tool = tool.id
JOIN test ... |
matachi/subdownloader | languages/Languages.py | Python | gpl-3.0 | 6,237 | 0.018919 | #!/usr/bin/env python
# Copyright (c) 2010 SubDownloader Developers - See COPYING - GPLv3
import languages.autodetect_lang as autodetect_lang
import re
import os.path
import logging
log = logging.getLogger("subdownloader.languages.Languages")
import __builtin__
__builtin__._ = lambda x : x
LANGUAGES = [{'locale':'sq... | e', 'SubLanguageID': 'ger', 'LanguageName': _('German')},
{'locale':'el', 'ISO639': 'el', 'SubLanguageID': 'ell', 'LanguageName': _('Greek')},
{'locale':'he', 'ISO639': 'he', 'SubLanguageID': 'heb', 'LanguageName': _('Hebrew')},
{'locale':'hu', 'ISO639': 'hu', 'SubLanguageID': 'hun', 'LanguageName': _('Hungarian')},... | 'id', 'SubLanguageID': 'ind', 'LanguageName': _('Indonesian')},
{'locale':'it', 'ISO639': 'it', 'SubLanguageID': 'ita', 'LanguageName': _('Italian')},
{'locale':'ja', 'ISO639': 'ja', 'SubLanguageID': 'jpn', 'LanguageName': _('Japanese')},
{'locale':'kk', 'ISO639': 'kk', 'SubLanguageID': 'kaz', 'LanguageName': _('Ka... |
luxnovalabs/enjigo_door | web_interface/keyedcache/utils.py | Python | unlicense | 281 | 0.003559 | import types
def is_string_like(maybe):
"""Test value to see if it acts like a string"""
try:
maybe+""
except TypeError:
r | eturn 0
else:
return 1
def is_list_or_tuple(maybe):
return isinstance(maybe | , (types.TupleType, types.ListType))
|
erikrose/parsimonious | parsimonious/__init__.py | Python | mit | 421 | 0 | """Parsimonious's public API. | Import from here.
Things may move around in modules deeper than this one.
"""
from parsimonious.exceptions import (ParseError, IncompleteParseError,
VisitationError, UndefinedLabel,
| BadGrammar)
from parsimonious.grammar import Grammar, TokenGrammar
from parsimonious.nodes import NodeVisitor, VisitationError, rule
|
locationtech/geowave | python/src/main/python/pygw/store/cassandra/__init__.py | Python | apache-2.0 | 739 | 0.00406 | #
# Copyright (c) 2013-2020 Contributors to the Eclipse Foundation
#
# See the NOTICE file distributed with this work for additional information regarding copy | right
# ownership. All rights reserved. This program and the accompanying materials are made available
# under the terms of the Apache License, Version 2.0 which accompanies this distribution and is
# available at http://www.apache.org/licenses/LICENSE-2.0.txt
# =========================================================... | assandra import CassandraOptions
```
"""
from .options import CassandraOptions
|
xkollar/spacewalk | client/rhel/rhn-client-tools/src/up2date_client/hardware.py | Python | gpl-2.0 | 29,568 | 0.005344 | #
# Copyright (c) 1999--2015 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a c... | lscpu command if available
if os.access("/usr/bin/lscpu", os.X_OK):
try:
lines = os.popen("/usr/bin/lscpu -p").readlines()
max_socket_index = -1
for line in lines:
| if line.startswith('#'):
continue
# get the socket index from the output
socket_index = int(line.split(',')[2])
if socket_index > max_socket_index:
max_socket_index = socket_index
if max_socket_index > -1:
... |
phiros/nepi | src/nepi/resources/linux/gretunnel.py | Python | gpl-3.0 | 3,088 | 0.006801 | #
# NEPI, a framework to manage network experiments
# Copyright (C) 2013 INRIA
#
# 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 ... | t):
# Return the command to execute to initiate the connection to the
# other endpoint
connection_run_home = self.run_home(endpoint)
| connection_app_home = self.app_home(endpoint)
data = endpoint.gre_connect(remote_endpoint,
connection_app_home,
connection_run_home)
return data
def establish_connection(self, endpoint, remote_endpoint, data):
pass
def verify_connection(self, endpo... |
hebaishi/pybullet | pybullet.py | Python | mit | 3,446 | 0.017702 | #!/usr/bin/python
import os
import json
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
import urllib
import mimetypes
def push_note(title = "Untitled", body = "Sample body", token = ""):
"""
Push note using pushbullet
"""
json_object = dict()... |
except:
return None
def push_file(file_path = "", file_name = "", file_desc="", token = ""):
"""
Push file using pushbullet
"""
json_object = dict()
json_object["file_name"] = file_name
url = urllib.pathname2url(file_path)
mime_type = mimetypes.guess_type(url)[0]
json_... | 'Content-Type', 'application/json')
request.add_header('Access-Token', token)
response = urllib2.urlopen(request)
upload_response = response.read()
except:
return None
upload_data = json.loads(upload_response)
register_openers()
try:
datagen, headers = mult... |
leanrobot/contestsite | team/models.py | Python | gpl-3.0 | 1,210 | 0.019835 | from __future__ import absolute_import
import os
from datetime import timedelta,datetime
import logging
import sys
from django.db import models as DjangoModels
from django.contrib.auth.models import User
from django.conf import settings
from django.db.models.query import EmptyQuerySet
from pytz import timezone
from c... | ngoModels.OneToOneField(User, primary_key=True)
teamName = DjangoModels.CharField(max_length=30)
def score(self):
problems = Problem.objects.all()
score = 0
for problem in problems:
correct = problem.getCorrectSolution(self.user)
if(co | rrect):
score += problem.possibleScore(self.user)
return score
def getCorrect(self):
correct = ProblemResult.objects.filter(user=self.user, graded=True, successful=True)
problems = [pr.problem for pr in correct]
return problems
def getFailed(self):
problems = Problem.objects.all()
failed = [pr for p... |
thusoy/blag | blag/migrations/versions/f7888bd46c75_add_hikes.py | Python | mit | 1,664 | 0.015625 | """add-hikes
Revision ID: f7888bd46c75
Revises: 820bb005f2c5
Create Date: 2017-02-16 07:36:06.108806
"""
# revision identifiers, used by Alembic.
revision = 'f7888bd46c75'
down_revision = 'fc92ba2ffd7f'
from alembic import op
import sqlalchemy as sa
import geoal | chemy2
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('hike_destination',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('altitude', sa.Integer() | , nullable=True),
sa.Column('high_point_coord', geoalchemy2.types.Geometry(geometry_type='POINT'), nullable=False),
sa.Column('is_summit', sa.Boolean(), server_default='t', nullable=False),
sa.Column('created_at', sa.DateTime(), server_default=sa.text(u'now()'), nullable=False),
sa.PrimaryKeyConstraint(... |
viktorTarasov/PyKMIP | kmip/tests/unit/core/misc/test_server_information.py | Python | apache-2.0 | 7,934 | 0 | # Copyright (c) 2015 The Johns Hopkins University/Applied Physics Laboratory
# All Rights Reserved.
# |
# 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 th... | ed 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.
from six import string_types
from testtools import TestCase
from kmip.core.misc import ServerInformation
from kmip.c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.