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 |
|---|---|---|---|---|---|---|---|---|
codemeow5/vehiclenet-python | web.py | Python | gpl-2.0 | 2,732 | 0.027086 | #!/usr/bin/python
import sys, os
import tornado.ioloop
import tornado.web
import logging
import logging.handlers
import re
from urllib import unquote
import config
from vehiclenet import *
reload(sys)
sys.setdefaultencoding('utf8')
def deamon(chdir = False):
try:
if os.fork() > 0:
os._exit(0)
except OSError,... | ,
(r"/carlink//music/findMusic.htm", MusicSearchHandler),
(r"/carlink/music/findMusicTop.htm", MusicTopHandler),
(r"/ca | rlink/music/findMusicLrc.htm", LrcSearchHandler),
(r"/carlink/news/findNews.htm", NewsHandler),
]
if config.Mode == 'DEBUG':
routes.append((r"/log", LogHandler))
application = tornado.web.Application(routes, **settings)
if __name__ == "__main__":
if '-d' in sys.argv:
deamon()
logdir = 'logs'
if not os.path.ex... |
yanjinbin/learnPython | chapter_7/chapter7.py | Python | gpl-3.0 | 3,243 | 0.000699 | """映射 集合 ... 高级数据结构类型"""
from string import Template
val_dict = {1: 'a', 2: 'b', 3: 'c'}
print(val_dict)
print(val_dict.keys())
print(val_dict.items())
print(val_dict.values())
factory_dict = dict((['x', 1], ['y', 2]))
print(factory_dict)
ddcit = {}.fromkeys(('x', 'y', 'z'), -24)
ddcit.update(val_dict) # 新值覆盖旧值
prin... | set))
print(var_set)
print("frozensetr ")
var_frozen_set = frozenset('aaddk2u9m3pq40aiwoe27na')
print(var_frozen_set)
print('a' in var_set)
print('2' in var_frozen_set) # True 数字被当做字符处理
print(2 in var_frozen_set) # False
# 可变集合 的 CRUD
var_set.update("anddipwq")
print(var_set)
var_se | t.discard("n")
print(var_set)
var_set.remove("a")
print(var_set)
var_set.pop()
print(var_set)
var_set.clear()
print(var_set)
var_set.add("$")
print(var_set)
var_set1 = set('rtyufghvb')
print(var_set1)
var_set2 = set('qwertyuiop')
print(var_set2)
var_set3 = set('qwertyuiop')
print(var_set3)
var_set4 = var_set1
print(va... |
welch/seasonal | tests/adjust_seasons_test.py | Python | mit | 1,815 | 0.007163 | # test seasonal.adjust_seasons() options handling
#
# adjust_seasons() handles a variety of optional arguments.
# verify that adjust_trend() correctly calledfor different option combinations.
#
# No noise in this test set.
#
from __future__ import division
import numpy as np
from seasonal import fit_trend, adjust_seaso... | ns(DATA, trend="line")
assert adjusted.std() < DATA.std()
def test_explicit_trend():
trend = fit_trend(DATA, kind="line")
adjusted = adjust_seasons(DATA, trend=trend)
assert adjusted.std() < DATA.std()
def test_trend_period():
adjusted = adjust_seasons(DATA, trend="line", period=PERIOD)
assert... | test_trend_seasons():
adjusted = adjust_seasons(DATA, trend="line", seasons=SEASONS)
assert adjusted.std() < DATA.std()
def test_trend_spline():
adjusted = adjust_seasons(DATA, trend="spline")
assert adjusted.std() < DATA.std()
def test_period():
adjusted = adjust_seasons(DATA, period=PERIOD)
... |
foobarbazblarg/stayclean | stayclean-2020-july/serve-challenge-with-flask.py | Python | mit | 12,690 | 0.003546 | #!/usr/bin/env python
import subprocess
import praw
import datetime
import pyperclip
from hashlib import sha1
from flask import Flask
from flask import Response
from flask import request
from cStringIO import StringIO
from base64 import b64encode
from base64 import b64decode
from ConfigParser import ConfigParser
impor... | it('pornfree').get_hot(limit=5)
# print [str(x) for x in submissions]
return redditSession
def loginOAuthAndReturnRedditSession():
redditSession = praw.Reddit(user_agent='Test Script by /u/foobarbazblarg')
# New version of praw does not require explicit use of the OAuth2Util object. Presumably becaus... | , configfile="../reddit-oauth-credentials.cfg")
# TODO: Testing comment of refresh. We authenticate fresh every time, so presumably no need to do o.refresh().
# o.refresh(force=True)
return redditSession
def getSubmissionForRedditSession(redditSession):
# submission = redditSession.get_submission(su... |
lutianming/leetcode | reverse_bits.py | Python | mit | 321 | 0.003115 | class Solution:
# @param n, | an integer
# @return an integer
def reverseBits(self, n):
reverse = 0
r = n
for i in range(32):
bit = r % 2
reverse += bit << (32-i-1)
r = r / 2
return reverse
s = So | lution()
r = s.reverseBits(43261596)
print(r)
|
shearern/rsync-usb | src/rsync_usb_tests/ChunkLocationTests.py | Python | gpl-2.0 | 4,596 | 0.001958 | import unittest
from rsync_usb.ChunkLocation import ChunkLocation
class ChunkLocationTests(unittest.TestCase):
'''Test TargetHashesWriter and TargetHashesReader'''
def testProperties(self):
pos = ChunkLocation('dummy', 100, 10)
self.assertEqual(pos.path, 'dummy')
self.... | ocation('dummy', 6, 10)
self.assertOverlaping(pos_a, pos_b)
def testOverlapInsideSameEnd(self):
# 0000000000111111111112
# 012345 | 6789001234567890
# A: ------|=======|-------
# B: -----|========|-------
pos_a = ChunkLocation('dummy', 6, 9)
pos_b = ChunkLocation('dummy', 5, 10)
self.assertOverlaping(pos_a, pos_b)
def testOverlapEndsAfter(self):
# 0000000000111111111112
# ... |
wenottingham/ansible | lib/ansible/plugins/lookup/subelements.py | Python | gpl-3.0 | 4,311 | 0.002784 | # (c) 2013, Serge van Ginderachter <serge@vanginderachter.be>
#
# 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)... | eck number of terms
if not isinstance(terms, list) or not 2 <= len(terms) <= 3:
_raise_terms_error()
| # first term should be a list (or dict), second a string holding the subkey
if not isinstance(terms[0], (list, dict)) or not isinstance(terms[1], string_types):
_raise_terms_error("first a dict or a list, second a string pointing to the subkey")
subelements = terms[1].split(".")
i... |
ntt-pf-lab/backup_keystone | keystone/middleware/remoteauth.py | Python | apache-2.0 | 4,006 | 0.00025 | #!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (c) 2010 OpenStack, 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/... | ed 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.
"""
Auth Middleware that handles auth for a... | omes from an untrusted source, it will
redirect it back to be properly authenticated. This is done by sending our a
305 proxy redirect response with the URL for the auth service.
The auth service settings are specified in the INI file (keystone.ini). The ini
file is passed in as the WSGI config file when starting the ... |
audantic/smartystreets.py | smartystreets/client.py | Python | bsd-3-clause | 6,663 | 0.002852 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Client module for connecting to and interacting with SmartyStreets API
"""
import json
import numbers
import requests
from .data import Address, AddressCollection
from .exceptions import SmartyStreetsError, ERROR_CODES
def validate_args(f):
"""
Ensures that... | eturn AddressCollection(self.post('street-address', data=addresses))
def street_address(self, address):
"""
Geocode one and only address, get a single Address object back
>>> client.street_address("100 Main St, Anywhere, USA")
>>> client.street_address({"street": "100 Main St, anyw... | ess information
:return: an Address object or None for no match
"""
address = self.street_addresses([address])
if not len(address):
return None
return Address(address[0])
def zipcode(self, *args):
raise NotImplementedError("You cannot lookup zipcodes yet"... |
m45t3r/i3pystatus | i3pystatus/spotify.py | Python | mit | 183 | 0 | from i3pystatus.playerctl import Playerctl
class Spotify(Playerctl):
"""
Get Spotify info using playerct | l. Based | on `Playerctl`_ module.
"""
player_name = "spotify"
|
liuqr/edx-xiaodun | cms/djangoapps/models/settings/course_grading.py | Python | agpl-3.0 | 9,046 | 0.003869 | from datetime import timedelta
from contentstore.utils import get_modulestore
from xmodule.modulestore.django import loc_mapper
from xblock.fields import Scope
class CourseGradingModel(object):
"""
Basical | ly a DAO and Model combo for CRUD operations pertaining to grading policy.
"""
# Within this class, allow access to protected members of client classes.
# This comes up when accessing kvs data and caches during kvs saves and modulestore writes.
def __init__(self, course_descriptor):
self.graders... | .jsonize_grader(i, grader) for i, grader in enumerate(course_descriptor.raw_grader)
] # weights transformed to ints [0..100]
self.grade_cutoffs = course_descriptor.grade_cutoffs
self.grace_period = CourseGradingModel.convert_set_grace_period(course_descriptor)
@classmethod
def fetch(cl... |
hehongliang/tensorflow | tensorflow/python/util/tf_export_test.py | Python | apache-2.0 | 6,573 | 0.005021 | # 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... | ort_decorator(_test_function)
def testRaisesExceptionIfInvalidSymbolName(self):
# TensorFlow code is not allowed to export symbols under package
| # tf.estimator
with self.assertRaises(tf_export.InvalidSymbolNameError):
tf_export.tf_export('estimator.invalid')
# All symbols exported by Estimator must be under tf.estimator package.
with self.assertRaises(tf_export.InvalidSymbolNameError):
tf_export.estimator_export('invalid')
with se... |
Joccalor/PFunc | PFunc.py | Python | gpl-3.0 | 130,625 | 0.000322 | #!/usr/bin/env python3
# sudo apt-get install python3-tk
# This file is part of PFunc. PFunc provides a set of simple tools for users
# to analyze preference functions and other function-valued traits.
#
# Copyright 2016-2022 Joseph Kilmer
#
# PFunc is free software: you can redistribute it and/or modify
# it under th... | curr.func$strict.tol')).split()[1]
self.broad_tolerance_points = r('curr.func$broad.tol.points')
self.strict_tolerance_point | s = r('curr.func$strict.tol.points')
self.tolerance_height = ('%s' % r('curr.func$tol.height')).split()[1]
self.hd_strength = ('%s' % r('curr.func$hd.strength')).split()[1]
self.hi_strength = ('%s' % r('curr.func$hi.strength')).split()[1]
self.responsiveness = ('%s' % r('curr.func$respon... |
datamade/dedupe | dedupe/labeler.py | Python | mit | 15,590 | 0.000513 | import random
from abc import ABC, abstractmethod
import logging
import numpy
import rlr
from typing import List
from typing_extensions import Protocol
import dedupe.sampling as sampling
import dedupe.core as core
import dedupe.training as training
import dedupe.datamodel as datamodel
from dedupe._typing import Train... | data)
random_sample_size = sample_size - len(blocked_sample_keys)
random_sample_keys = set(core.randomPairs(len(data),
random_sample_size))
data = dict(data)
return [(data[k1], data[k2])
... | ocked_proportion, sample_size) -> List[TrainingExample]:
offset = len(data_1)
blocked_sample_size = int(blocked_proportion * sample_size)
predicates = list(self.data_model.predicates(index_predicates=False))
deque_1 = sampling.randomDeque(data_1)
deque_2 = sampling.randomDeque(... |
rbong/gimptools | preview.py | Python | gpl-2.0 | 2,246 | 0.01959 | #!/usr/bin/env python2
from gimpfu import *
import time
import re
def preview (image, delay, loops, force_delay, ignore_hidden, restore_hide):
if not image:
raise "No image given."
layers = image.layers
nlayers = len (layers)
visible = []
length = []
i = 0
while i < nlayers:
... | 2, "delay", "The default length in ms of each frame", 100),
(PF_INT32, "loops", "The number of times to loop the animation", 1),
(PF_BOOL, "force-delay", "Force the default length on every frame", 0),
(PF_BOOL, "ignore-hidden", "Ignore currently hidden items", 0),
(PF_BOOL, "restore-hide... | mage>/Filters/Animation")
main()
|
LumPenPacK/NetworkExtractionFromImages | win_build/nefi2_win_amd64_msvc_2015/site-packages/networkx/algorithms/hybrid.py | Python | bsd-2-clause | 6,084 | 0.010355 | # coding: utf-8
"""
Provides functions for finding and testing for locally `(k, l)`-connected
graphs.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)\nDan Schult (dschult@colgate.edu)"""
# Copyright (C) 2004-2015 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <sw... | aph
prev=u
for w in path:
if prev!=w:
| G2.remove_edge(prev,w)
prev=w
# path=shortest_path(G2,u,v,k) # ??? should "Cutoff" be k+1?
try:
path=nx.shortest_path(G2,u,v) # ??? should "Cutoff" be k+1?
except nx.NetworkXNoPath:
path = False
... |
mogui/pyorient | tests/test_raw_messages_2.py | Python | apache-2.0 | 12,897 | 0.016283 | __author__ = 'Ostico <ostico@gmail.com>'
import sys
import os
import unittest
from pyorient.exceptions import *
from pyorient import OrientSocket
from pyorient.messages.database import *
from pyorient.messages.commands import *
from pyorient.messages.cluster import *
from pyorient.messages.records import *
from pyori... | .prepare( ( cluster, rec_position._rid, rec ) )\
.send().fetch_response()
assert update_success[0] != 0
if connection.protocol <= 21:
return unittest.skip("Protocol {!r} does not works well".format(
connection.protocol )) # ski | p test
res = ( CommandMessage( connection ) )\
.prepare( [ QUERY_SYNC, "select from " + rec_position._rid ] )\
.send().fetch_response()
# res = [ ( RecordLoadMessage(connection) ).prepare(
# [ rec_position._rid ]
# ).send().fetch_response() ]
print(... |
clarkperkins/stackdio | stackdio/api/formulas/exceptions.py | Python | apache-2.0 | 753 | 0 | # -*- coding: utf-8 -*-
# Copyright 2017, Digital Reasoning
#
# 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... | S OF ANY KIND, either express or i | mplied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import unicode_literals
class InvalidFormula(Exception):
pass
class InvalidFormulaComponent(InvalidFormula):
pass
|
facebookresearch/ParlAI | parlai/tasks/dialog_babi/build.py | Python | mit | 1,182 | 0 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in | the
# LICENSE file in the root directory of this source tree.
# Download and build the data if it does not exist.
from parlai.core.build_data import DownloadableFile
import parlai.core.build_data as build_data
import os
RESOURCES = [
DownloadableFile(
'http://parl.ai/downloads/dialog_babi/dialog_babi.tar.... | join(opt['datapath'], 'dialog-bAbI')
version = None
if not build_data.built(dpath, version_string=version):
print('[building data: ' + dpath + ']')
if build_data.built(dpath):
# An older version exists, so remove these outdated files.
build_data.remove_dir(dpath)
... |
barrachri/epcon | microblog/views.py | Python | bsd-2-clause | 7,631 | 0.003014 | # -*- coding: UTF-8 -*-
from django.conf import settings as dsettings
from django.contrib.auth import models as authModels
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.http import HttpResponse, Http404
from django.shortcuts import render, render_to_response, get_object_or_404
from dja... | age):
posts = paginator.page(1)
else:
paginator = Paginator(post_list, len(post_list) or 1)
posts = paginator.page(1)
return posts
def _posts_list(request, featured=False):
if settings.MICROBLOG_LANGUAGE_FALLBACK_ON_POST_LIST:
lang = None
else:
lang = reques... |
def _post_detail(request, content):
if not settings.MICROBLOG_POST_FILTER([content.post], request.user):
raise Http404()
return render_to_response(
'microblog/post_detail.html',
{
'post': content.post,
'content': content
},
context_instance=Reques... |
nick-monto/SpeechRecog_CNN | create_spectrograms_16k.py | Python | mit | 6,802 | 0.002205 | #!/usr/bin/env python
import os
import numpy as np
import math
import fnmatch
from my_spectrogram import my_specgram
from collections import OrderedDict
from scipy.io import wavfile
import matplotlib.pylab as plt
from pylab import rcParams
from sklearn.model_selection import train_test_split
rcParams['figure.figsize']... | h)
data = data / data.max()
center = data.mean() * 0.2
data = data + np.random.normal(center, abs(center * 0.5), len(data))
NFFT = pow(2, int(math.log(int(fs*NFFT_window), 2) + 0.5)) # 25ms window, nearest power of 2
noverlap = int(fs*noverlap_window)
fc = int(np.sqrt(freq_min*freq | _max))
# Pxx is the segments x freqs array of instantaneous power, freqs is
# the frequency vector, bins are the centers of the time bins in which
# the power is computed, and im is the matplotlib.image.AxesImage
# instance
Pxx, freqs, bins, im = my_specgram(data, NFFT=NFFT, Fs=fs,
... |
cypreess/csvkit | csvkit/cli.py | Python | mit | 15,243 | 0.007479 | #!/usr/bin/env python
import argparse
import bz2
import gzip
import os.path
import sys
from csvkit import CSVKitReader
from csvkit.exceptions import ColumnIdentifierError, RequiredHeaderE | rror
def lazy_opener(fn):
def wrapped(self, *args, **kwargs): |
self._lazy_open()
fn(*args, **kwargs)
return wrapped
class LazyFile(object):
"""
A proxy for a File object that delays opening it until
a read method is called.
Currently this implements only the minimum methods to be useful,
but it could easily be expanded.
"""
def __... |
szaydel/psutil | test/_sunos.py | Python | bsd-3-clause | 1,322 | 0.000756 | #!/usr/bin/env python
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Sun OS specific tests. These are implicitly run by test_psutil.py."""
import psutil
from test_psutil import *
class SunOSSpec... | if not lines:
raise ValueError('no swap device(s) configured')
total = free = 0
for l | ine in lines:
line = line.split()
t, f = line[-2:]
t = t.replace('K', '')
f = f.replace('K', '')
total += int(int(t) * 1024)
free += int(int(f) * 1024)
used = total - free
psutil_swap = psutil.swap_memory()
self.assertEqual... |
akkana/pi-zero-w-book | ch2/blink-rpigpio.py | Python | gpl-2.0 | 468 | 0 | #!/usr/bin/env python
# Blink an LED using the RPi.GPIO library.
import RPi.GPIO as GPIO
from time import sleep
# Use GPIO numbering:
GPIO.setmode(GPIO.BCM)
# Set pin GPIO | 14 to be output:
GPIO.setup(14, GPIO.OUT)
try:
while True:
GPIO.output(14, GPIO.HIGH)
sleep(.5)
GPIO.output(14, GPIO.LOW)
sleep(.5)
# If we get a Ctrl-C, clean up so | we don't get warnings from other programs:
except KeyboardInterrupt:
GPIO.cleanup()
|
RobLoach/lutris | tests/check_prefixes.py | Python | gpl-3.0 | 1,465 | 0.002048 | #!/usr/bin/python3
import os
import sys
import subprocess
sys.path.insert(0, | os.path.dirname(os.path.d | irname(os.path.abspath(__file__))))
from lutris.util.wineregistry import WineRegistry
PREFIXES_PATH = os.path.expanduser("~/Games/wine/prefixes")
def get_registries():
registries = []
directories = os.listdir(PREFIXES_PATH)
directories.append(os.path.expanduser("~/.wine"))
for prefix in directories:
... |
zrhans/python | exemplos/Examples.lnk/bokeh/glyphs/dateaxis.py | Python | gpl-2.0 | 1,293 | 0 | from __future__ import print_function
from numpy import pi, arange, sin
import numpy as np
import time
from bokeh.browserlib import view
from bokeh.document import Document
from bokeh.embed import file_html
from bokeh.models.glyphs import Circle
from bokeh.models import (
Plot, DataRange1d, DatetimeAxis,
Colu... | axis.html"
with open(filename, "w") as f:
f.write(file_html(doc, INLINE, "Date Axis | Example"))
print("Wrote %s" % filename)
view(filename)
|
joeymeyer/raspberryturk | raspberryturk/core/vision/chessboard_frame.py | Python | mit | 371 | 0.002695 | import numpy as np
from square import Square
from constants import SQUARE_SIZE, BOARD_SIZE
class ChessboardFrame():
def __init__(self, | img):
self.img = img
def square_at(self, i):
y = BOARD_SIZE - ((i / 8) % 8) * SQUARE_SIZE - SQUARE_SIZE
x = (i % 8) * SQUARE_SIZE
return Square(i, self.img[y:y+SQUARE_SIZE, x:x+SQUA | RE_SIZE, :])
|
Mlieou/leetcode_python | leetcode/python/ex_402.py | Python | mit | 405 | 0.002469 | class Solution(object):
| def removeKdigits(self, num, k):
"""
:type num: str
:type k: int
:rtype: str
"""
stack = []
length = len(num) - k
for c in num:
while k and stack and stack[-1] > c:
stack.pop()
k -= 1
stack.append... | return ''.join(stack[:length]).lstrip('0') or '0' |
liulion/mayavi | tvtk/plugins/scene/scene_manager.py | Python | bsd-3-clause | 2,756 | 0.002177 | """ Manage the TVTK scenes. """
# Enthought library imports.
from tvtk.pyface.tvtk_scene | import TVTKScene
from | pyface.workbench.api import WorkbenchWindow
from traits.api import HasTraits, List, Instance, Property
from traits.api import implements, on_trait_change
from tvtk.plugins.scene.scene_editor import SceneEditor
# Local imports.
from i_scene_manager import ISceneManager
class SceneManager(HasTraits):
""" Manage t... |
vbeffara/Simulations | tools/massage-box.py | Python | gpl-3.0 | 341 | 0.01173 | #! /usr/bin/env python
import sys
| g = {}
n = {}
for line in sys.stdin:
(n1, n2, p, | q, t, tg, x) = line.strip().split(' ')
t = int(t)
x = float(x)
key = ' '.join((n1,n2,p,q))
if not key in n:
n[key] = 0
g[key] = 0
n[key] += t
g[key] += x*t
for key in n:
print key, n[key], g[key]/n[key]
|
jsexauer/networkx_viewer | networkx_viewer/viewer.py | Python | gpl-3.0 | 17,151 | 0.005073 | try:
# Python 3
import tkinter as tk
import tkinter.messagebox as tkm
import tkinter.simpledialog as tkd
except ImportError:
# Python 2
import Tkinter as tk
import tkMessageBox as tkm
import tkSimpleDialog as tkd
import networkx as nx
from networkx_viewer.graph_canvas import GraphCan... | self.filter_list.bind('<Delete>',self.remove_filter)
flsb.config(command=self.node_list.yview)
flsb.grid(row=r, column=4, sticky='NWS')
r += 1
tk.Button(self, text='Clear',command=self.remove_filter).grid(
row=r, column=1, sticky='W')
tk.Button(self, text=... | r += 1
line2 = tk.Canvas(self, height=15, width=200)
line2.create_line(0,13,250,13)
line2.create_line(0,15,250,15)
line2.grid(row=r, column=1, columnspan=4, sticky='NESW')
r += 1
self.lbl_attr = tk.Label(self, text='Attributes',
wr... |
open-mmlab/mmdetection | mmdet/datasets/coco_panoptic.py | Python | apache-2.0 | 24,271 | 0 | # Copyright (c) OpenMMLab. All rights reserved.
import itertools
import os
from collections import defaultdict
import mmcv
import numpy as np
from mmcv.utils import print_log
from terminaltables import AsciiTable
from mmdet.core import INSTANCE_OFFSET
from .api_wrappers import COCO, pq_compute_multi_core
from .builde... | mport CocoDataset
try:
import panopticapi
from panopticapi.evaluation import VOID
from panopticapi.utils import id2rgb
except ImportError:
panopticapi = None
id2rgb = None
VOID = None
__all__ = | ['CocoPanopticDataset']
class COCOPanoptic(COCO):
"""This wrapper is for loading the panoptic style annotation file.
The format is shown in the CocoPanopticDataset class.
Args:
annotation_file (str): Path of annotation file.
"""
def __init__(self, annotation_file=None):
if panop... |
windskyer/k_nova | paxes_nova/compute/notify_messages.py | Python | apache-2.0 | 4,325 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# =================================================================
# =================================================================
# NOTE: notify message MUST follow these rules:
#
# - Messages must be wrappered with _() for translation
#
# - Replacement va... | e_name} on host "
"{host_name} was successful."))
DEPLOY_ERROR = (_("Deploy of virtual machine {instance_name} on host "
"{host_name} failed with exception: {error}"))
START_SUCCESS = (_("Start of virtual machine {instance_name} on host "
"{host_name} was succe... | } failed with exception: {error}"))
STOP_SUCCESS = (_("Stop of virtual machine {instance_name} on host "
"{host_name} was successful."))
STOP_ERROR = (_("Stop of virtual machine {instance_name} on host "
"{host_name} failed with exception: {error}"))
RESTART_SUCCESS = (_("Restart of... |
codeaudit/ampcrowd | ampcrowd/crowd_server/wsgi.py | Python | apache-2.0 | 399 | 0.002506 | """
WSGI config for crowd_server pr | oject.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "crowd_server.settings")
from django.core. | wsgi import get_wsgi_application
application = get_wsgi_application()
|
Alfredx/django-db2charts | db2charts/router.py | Python | mit | 619 | 0.003231 | # -*- coding: utf-8 -*-
# author: Alfred
import os
import re
DB_MODULE_PATTERN = re.compile(r'db2charts_models\.(?P<module>.*)_models')
class DB2ChartsRouter(object):
def db_for_module(self, module):
mat | ch = DB_MODULE_PATTERN.match(module)
if match:
return match.groupdict()['module']
return None
def db_for_read(self, model, **hints):
return self.d | b_for_module(model.__module__)
def db_for_write(self, model, **hints):
return self.db_for_module(model.__module__)
def allow_migrate(self, db, app_label, model=None, **hints):
return False |
SickGear/SickGear | lib/apprise/plugins/NotifyD7Networks.py | Python | gpl-3.0 | 16,906 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Chris Caron <lead2gold@gmail.com>
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files(the "Software"), to deal
# in th... | emplate_tokens = dict(NotifyBase.template_tokens, **{
'user': {
'name': _('Username'),
'type': 'string',
'required': True,
},
'password': {
'name': _('Password'),
| 'type': 'string',
'private': True,
'required': True,
},
'target_phone': {
'name': _('Target Phone No'),
'type': 'string',
'prefix': '+',
'regex': (r'^[0-9\s)(+-]+$', 'i'),
'map_to': 'targets',
},
'targets... |
schreiberx/sweet | mule/platforms/50_cheyenne_intel/JobPlatform.py | Python | mit | 8,312 | 0.006136 | import platform
import socket
import sys
import os
from mule_local.JobGeneration import *
from mule.JobPlatformResources import *
from . import JobPlatformAutodetect
def _whoami(depth=1):
"""
String of function name to recycle code
https://www.oreilly.com/library/view/python-cookbook/0596001673/ch14s08.h... | p.core_affinity)+"' not supported")
else:
#raise Exception("Please specify core_affinity!")
content += "# No core affinity selected\n"
if p.core_affinity != None:
content += "export KMP_AFFINITY=\"verbose,$KMP_AFFINITY\"\n"
return content
def ... | ring
multiline text for scripts
"""
content = ""
content += jg.runtime.get_jobscript_plan_exec_prefix(jg.compile, jg.runtime)
content += """
EXEC=\""""+jg.compile.getProgramPath()+"""\"
PARAMS=\""""+jg.runtime.getRuntimeOptions()+"""\"
"""
return content
def jobscript_get_exec_comma... |
sandervenema/netzpolitik | petitions/urls.py | Python | gpl-2.0 | 251 | 0 | from django.conf.urls import url
from . import view | s
urlpatterns = [
url(r'^(?P<lang>[a-z]{2})?$', views.index, name='index'),
url(r'^sign/$', views.sign, name='sign'),
url(r'^co | nfirm/([0-9a-z]{64})/$', views.confirm, name='confirm'),
]
|
tkaitchuck/nupic | examples/opf/experiments/spatial_classification/base/description.py | Python | gpl-3.0 | 14,847 | 0.002694 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This pro... | ore inhibition falls below minDutyCycleBeforeInh
# will have their own internal synPermConnectedCell
# threshold set below this default value.
# (This concept applies to both SP and TP and so 'cells'
# is correct here as opposed to 'columns')
'synPermConnected... | d or disabled;
# TP is necessary for making temporal predictions, such as predicting
# the next inputs. Without TP, the model is only capable of
# reconstructing missing sensor inputs (via SP).
'tpEnable' : False,
'tpParams': {
# TP diagnostic output ver |
tensorflow/benchmarks | scripts/tf_cnn_benchmarks/variable_mgr_util.py | Python | apache-2.0 | 26,469 | 0.005743 | # 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... | e_normal_steps.
def update_op_if_no_nan_or_inf():
"""Apply gradients, and update loss scaling."""
return tf.group(
get_loss_scale_update_op(loss_scale, loss_scale_normal_steps,
inc_loss_scale_every_n),
*get_apply_gradients_ops_func())
# T | ODO(tanmingxing): Add support for independent and distributed all_reduce.
assert grad_has_inf_nan is not None
update_op = tf.cond(
grad_has_inf_nan,
update_op_if_nan_or_inf,
update_op_if_no_nan_or_inf,
name='cond_if_grad_has_inf_nan'
)
training_ops.append(update_op)
# T... |
att-comdev/deckhand | deckhand/context.py | Python | apache-2.0 | 1,765 | 0 | # Copyright 2017 AT&T Intellectual Property. All other 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... | self.project = project
super(RequestContext, self).__init__(**kwargs)
| def to_dict(self):
out_dict = super(RequestContext, self).to_dict()
out_dict['roles'] = self.roles
if out_dict.get('tenant'):
out_dict['project'] = out_dict['tenant']
out_dict.pop('tenant')
return out_dict
@classmethod
def from_dict(cls, values):
... |
UFRB/chdocente | cadastro/migrations/0001_initial.py | Python | agpl-3.0 | 11,352 | 0.007488 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Docente'
db.create_table('cadastro_docente', (
('id', self.gf('django.db.models.... | self.gf('django.db.models.fields.related.ForeignKey')(to=orm['cadastro.Docente'])),
('afastamento', self.gf('django.db.models.fields.BooleanField')(default=True)),
('cargo', self.gf('django.db.models.fields.CharField')(max_length=100, blank=True)),
('comissoes', self.gf('django.db.mo... |
('semestre', self.gf('django.db.models.fields.CharField')(max_length=6)),
))
db.send_create_signal('cadastro', ['Atividade'])
# Adding M2M table for field disciplinas on 'Atividade'
m2m_table_name = db.shorten_name('cadastro_atividade_disciplinas')
db.create_table(m... |
GoogleCloudPlatform/ml-on-gcp | example_zoo/tensorflow/models/ncf_main/official/recommendation/ncf_main.py | Python | apache-2.0 | 17,012 | 0.006348 | # Copyright 2018 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... | cluster_resolver.TPUClusterResolver(
tpu=params["tpu"],
zone=params["tpu_zone"],
project=params["tpu_gcp_project"],
coordinator_name="coordinator"
)
tf.logging.info("Issuing reset command to TPU to ensure a clean state.")
tf.Session.reset(tpu_cluster_resolver.get_mast | er())
# Estimator looks at the master it connects to for MonitoredTrainingSession
# by reading the `TF_CONFIG` environment variable, and the coordinator
# is used by StreamingFilesDataset.
tf_config_env = {
"session_master": tpu_cluster_resolver.get_master(),
"eval_session_master": tpu_... |
eyeofhell/parabridge | parabridge/settings.py | Python | gpl-3.0 | 3,770 | 0.032891 | #!/usr/bin/env python
# coding:utf-8 vi:et:ts=2
# parabridge persistent settings module.
# Copyright 2013 Grigory Petrov
# See LICENSE for details.
import xmlrpclib
import socket
import sqlite3
import uuid
import info
SQL_CREATE = """
CREATE TABLE IF NOT EXISTS task (
guid TEXT UNIQUE,
name TEXT UNIQUE,
... | connect( info.FILE_CFG ) as oConn:
oConn.row_factory = sqlite3.Row
try:
mArgs = { 'name': s_name }
oRow = oConn.execute( SQL_TASK_GUID_BY_NAME, mArgs ).fetchone()
if oRow is None:
return False
mArgs[ 'guid' ] = oRow[ 'guid' ]
oRet = oConn.execute( SQL_TASK_D... | finally:
self.notifyIfNeeded()
def taskList( self ):
with sqlite3.connect( info.FILE_CFG ) as oConn:
try:
oConn.row_factory = sqlite3.Row
return oConn.execute( SQL_TASK_LIST ).fetchall()
finally:
self.notifyIfNeeded()
instance = Settings()
|
stan-cap/bt_rssi | test/main_test.py | Python | mit | 1,713 | 0.010508 | from bt_proximity import BluetoothRSSI
import time
import sys
import datetime
#////////////////////////////////
BT_ADDR = 'xx:xx:xx:xx:xx:xx'#/// Enter your bluetooth address here!
#////////////////////////////////
# ----------------------- DO NOT EDIT ANYTHING BELOW THIS LINE --------------------------- #
def ... | ):
f = open("test_records.txt", "a+") # open records for append. If not present create
for i in range(count): # write out each record
f.write(str(records[i][0]) + "," + str(records[i][1]) + '\n')
f.close()
def time_diff(start_time):
current_time = dat... | .datetime.now() # get current time
diff = (current_time - start_time).total_seconds() # get difference of startime and current time
return str(round(diff,2))
def main(start_time):
records = [] # initialize array of records
count = 0 ... |
atvcaptain/enigma2 | lib/python/Plugins/SystemPlugins/FrontprocessorUpgrade/plugin.py | Python | gpl-2.0 | 2,732 | 0.032211 | from Screens.Screen import Screen
from Components.ActionMap import ActionMap
from Components.Label import Label
from Plugins.Plugin import PluginDescriptor
def getUpgradeVersion():
import os
try:
r = os.popen("fpupgrade --version").read()
except IOError:
return None
if r[:16] != "FP update tool v":
return No... | gs):
from Tools.StbHardware import getFPVersion
version = getFPVersion()
newversion = getUpgradeVersion() or 0
list = []
if version is not None and version < newversion:
| list.append(PluginDescriptor(name=_("FP Upgrade"), where = PluginDescriptor.WHERE_WIZARD, needsRestart = True, fnc=(8, FPUpgrade)))
try:
msg = open("/proc/stb/message").read()
list.append(PluginDescriptor(name=_("System Message Check"), where = PluginDescriptor.WHERE_WIZARD, needsRestart = True, fnc=(9, SystemM... |
schakrava/rockstor-core | src/rockstor/scripts/pwreset.py | Python | gpl-3.0 | 2,030 | 0.00197 | """
Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor 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 la... | TNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import sys
import pwd
from django.db import transaction
from django.co | ntrib.auth.models import User as DjangoUser
from storageadmin.models import User
from system import users
@transaction.atomic
def change_password(username, password):
try:
duser = DjangoUser.objects.get(username=username)
duser.set_password(password)
duser.save()
except:
sys.ex... |
reinbach/django-machina | example_projects/demo/demo_project/urls.py | Python | bsd-3-clause | 1,208 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include
from django.conf.urls import url
from django.contrib import admin
from django.views.i18n import JavaScriptCatalog
from demo.apps.app import application
js_info_dict = {
'package... | ase', ),
}
urlpatterns = [
url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript_catalog'),
# Admin
url(r'^' + settings.ADMIN_URL, admin.site.urls),
# Apps
url(r'', include(application.urls)),
]
if settings.DEBUG:
# Ad | d the Debug Toolbar’s URLs to the project’s URLconf
import debug_toolbar
urlpatterns += [url(r'^__debug__/', include(debug_toolbar.urls)), ]
# In DEBUG mode, serve media files through Django.
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views import static
url... |
persandstrom/home-assistant | homeassistant/components/switch/netio.py | Python | apache-2.0 | 5,530 | 0 | """
The Netio switch component.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.netio/
"""
import logging
from collections import namedtuple
from datetime import timedelta
import voluptuous as vol
from homeassistant.core import callback
from home... | urn_on(self, **kwargs):
"""Turn switch on."""
self._set(True)
def turn_off(self, **kwargs):
"""Turn switch off."""
self._set(False)
def _set(self, value):
val = list('uuuu')
val[self.outlet - 1] = '1' if value else '0'
self.netio.get('port list %s' % ''.... | .outlet - 1] = value
self.schedule_update_ha_state()
@property
def is_on(self):
"""Return the switch's status."""
return self.netio.states[self.outlet - 1]
def update(self):
"""Update the state."""
self.netio.update()
@property
def state_attributes(self):
... |
MakersLab/Farm-server | server/main.py | Python | gpl-3.0 | 3,234 | 0.002474 | #!/usr/bin/env python3.7
from multiprocessing import Process
import time
import os
from printerState import main as printerStateMain
from server import main as serverMain
from websocket import main as websocketServerMain
servicesTemplate = {
'server': {
'name': 'Server',
'run': serverMain,
... | ess(target=self.services[serviceName]['run'])
self.services[serviceName]['proc | ess'].start()
self.log('Creating and starting process for {0} with pid {1}'.format(
self.services[serviceName]['name'],
self.services[serviceName]['process'].pid))
self.services[serviceName]['running'] = True
def loop(self):
while True:
se... |
DaVinAhn/EPubMaker | EPubMaker.py | Python | mit | 16,500 | 0.030364 | # -*- coding: utf-8 -*-
import sublime, sublime_plugin
import os
import shutil
import subprocess
import zipfile
import glob
import sys
import codecs
import re
import json
import xml.etree.ElementTree
###
### Global Value
###
PACKAGE_NAME = 'EPubMaker'
OPEN_COMMAND = 'epub_maker_open'
SAVE_COMMAND = 'epub_maker_s... | .ZIP_STORED)
# 이후 디렉토리와 파일을 추가
for root, dirs, files in os.walk(workpath):
| if root == workpath:
continue
epub.write(root, root[len(workpath + os.sep):], zipfile.ZIP_STORED)
for f in files:
if is_ignore_file(f) or f == 'mimetype' or f.startswith(PREVIEW_PREFIX):
continue
f = os.path.join(root, f)
epub.write(f, f[len(workpath + os.sep):], zipfile.ZIP_DEFLATED)
epub... |
BRAINSia/ITK | Modules/Core/Common/wrapping/test/itkVariableLengthVectorTest.py | Python | apache-2.0 | 1,870 | 0 | # ==========================================================================
#
# Copyright NumFOCUS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with t | he License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0.txt
#
# 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 exp... | nd
# limitations under the License.
#
# ==========================================================================*/
import itk
itk.auto_progress(2)
n_channels = 31
# Verify UC addition operation
vector_type = itk.VariableLengthVector[itk.UC]
vector1 = vector_type(n_channels)
vector2 = vector_type(n_channels)
asse... |
drewrobb/marathon-python | marathon/_compat.py | Python | mit | 173 | 0 | """
Support for python 2 & 3, ripped pieces from si | x.py
"""
import sys
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
else:
string_types | = basestring,
|
DIT524-V17/group-7 | TCP raspberry/server.py | Python | gpl-3.0 | 181 | 0.005525 | # Author: Pontus Laestadius.
# Since: 2nd of March, | 2017.
# Maintained since: 17th of April 2017.
from receiver import Receiver
print("Version 2.2")
R | eceiver("172.24.1.1", 9005)
|
KonradBreitsprecher/espresso | doc/tutorials/06-active_matter/SOLUTIONS/rectification_geometry.py | Python | gpl-3.0 | 5,253 | 0.008186 | ################################################################################
# #
# Copyright (C) 2010,2011,2012,2013,2014, 2015,2016 The ESPResSo project #
# ... | er 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. #
# | #
# ESPResSo 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 General Public License for more details. ... |
everyevery/programming_study | lgecodejam/2014-mar/c/c.py | Python | mit | 1,284 | 0.010125 | def process(target, other):
result = [[] for ch in target]
ret = []
for xi, xv in enumerate(target):
for yi, yv in enumerate(other):
if xv != yv:
result[xi].append(0)
elif 0 == xi or 0 == yi:
result[xi].append(1)
else:
... | h, sub_map):
for l in range(1, word_length+1):
# print "LEN: ", l
for pos in range(l-1, word_length):
# print "POS: ", pos
flag = True
for other in sub_map:
# | print l, other[pos]
if l <= other[pos]:
flag = False
break
if flag:
return l
def solve(n, word_list):
for (xi, xv) in enumerate(word_list):
result = []
for (yi, yv) in enumerate(word_list):
if (x... |
tobikausk/nest-simulator | pynest/nest/tests/test_sp/test_enable_multithread.py | Python | gpl-2.0 | 2,237 | 0 | # -*- coding: utf-8 -*-
#
# test_enable_multithread.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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... | URPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along | with NEST. If not, see <http://www.gnu.org/licenses/>.
import nest
import unittest
__author__ = 'sdiaz'
# Structural plasticity currently does not work with multiple threads.
# An exception should be rised if structural plasticity is enabled
# and multiple threads are set, or if multiple threads are set and
# the ... |
cnvogelg/fs-uae-gles | launcher/fs_uae_launcher/editor/XMLControl.py | Python | gpl-2.0 | 2,828 | 0.001061 | from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import xml.etree.ElementTree
from xml.etree.cElementTree import ElementTree, Element, SubElement
from xml.etree.cElementTree import fromstring, tostring
import ... | e.text = info["name"]
self.set_tree(tree)
def find_or_create_node(self, element, name):
node = element.find(name)
if node is None:
node = SubElement(element, name)
return node
def set_path(self, path):
if not os.path.exists(path):
path = ""
... | et_tree(self):
text = self.get_text().strip()
try:
root = fromstring(text.encode("UTF-8"))
except Exception:
# FIXME: show message
import traceback
traceback.print_exc()
return
tree = ElementTree(root)
indent_tree(root)
... |
gwq5210/litlib | thirdparty/sources/protobuf/python/google/protobuf/descriptor.py | Python | gpl-3.0 | 37,400 | 0.006364 | # Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# https://developers.google.com/protocol-buffers/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redi... | ocol "package" name and the name of any
enclosing types.
containing_type: (Descriptor) Reference to the descriptor of the
type containing us, or None if this is top-level.
fields: (list of FieldDescriptors) Field descriptors | for all
fields in this type.
fields_by_number: (dict int -> FieldDescriptor) Same FieldDescriptor
objects as in |fields|, but indexed by "number" attribute in each
FieldDescriptor.
fields_by_name: (dict str -> FieldDescriptor) Same FieldDescriptor
objects as in |f |
hlmnrmr/liveblog | server/liveblog/syndication/exceptions.py | Python | agpl-3.0 | 199 | 0 | class APIConnectionError(Exception):
pass
class DownloadErro | r(Exception):
pass
class ProducerAPIError(APIConnectionError):
pass
class ConsumerAPIError(APIConnectionE | rror):
pass
|
libor-m/scrimer | scrimer/primer3_connector.py | Python | agpl-3.0 | 7,094 | 0.006061 | """
A Python interface to the primer3_core executable.
TODO: it is not possible to keep a persistent primer3 process
using subprocess module - communicate() terminates the input
stream and waits for the process to finish
Author: Libor Morkovsky 2012
"""
# This file is a part of Scrimer.
# See LICENSE.t... | "
else:
print "Failed!"
print "Testing BoulderIO, two records:",
two_records = record + record_no_res
record_dp = BoulderIO.deparse(two_records)
record_reparsed = BoulderIO.parse(record_dp)
if two_records == record_reparsed:
print "OK"
else:
print "Failed!"
... | Primer3, single record:",
p3 = Primer3(**default_params)
# test for single record
res = p3.call(record)
if res[0]['RIGHT'][0]['SEQUENCE'] == 'GTCGGGATCGAATGGCCC':
print "OK"
else:
print "Failed!"
# test for multiple records
print "Testing Primer3, two records:",
res... |
EricssonResearch/scott-eu | robot-emulator/main.py | Python | apache-2.0 | 3,749 | 0.005346 | import paho.mqtt.client as mqtt
import os,binascii
import logging
import time
from enum import Enum
from threading import Timer
import json
import random
import math
ID_STRING = binascii.hexlify(os.urandom(15)).decode('utf-8')[:4]
CLIENT_ID = "robot-emulator-" + ID_STRING
BROKER_HOST = "mosquitto"
TOPIC_STATUS = "twin... | the twin '%s'", t)
# TODO do we really need this status?
| status = TwinStatus.SELECTED
register_with_twin(t)
def register_with_twin(t):
logging.warning("Not implemented yet")
status = TwinStatus.CONNECTED
twin = t
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelnam... |
auth0/auth0-python | auth0/v3/test/management/test_resource_servers.py | Python | mit | 3,056 | 0.000327 | import unittest
import mock
from ...management.resource_servers import ResourceServers
class TestResourceServers(unittest.TestCase):
def test_init_with_optionals(self):
t = ResourceServers(domain='domain', token='jwttoken', telemetry=False, timeout=(10, 2))
self.assertEqual(t.client.options.timeo... | in/api/v2/resource-servers',
data={'name': 'TestApi', 'identifier': 'https://test.com/api'}
)
@mock.patch('auth0.v3.management.resource_servers.RestClient')
def test_get_all(self, mock_rc):
mock_instance = mock_rc.return_value
r = ResourceServers(domain='domain', token='jwt... | default params
r.get_all()
mock_instance.get.assert_called_with(
'https://domain/api/v2/resource-servers',
params={
'page': None,
'per_page': None,
'include_totals': 'false'
}
)
# with pagination params... |
wandec/grr | client/client_actions/plist.py | Python | apache-2.0 | 2,452 | 0.008564 | #!/usr/bin/env python
# Copyright 2012 Google Inc. All Rights Reserved.
"""Client actions related to plist files."""
import cStringIO
import types
from grr.client import actions
from grr.client import vfs
from grr.lib import plist as plist_lib
from grr.lib import rdfvalue
from grr.parsers import binplist
class ... | key values are places under a dictionary
key called "key".
Whether you've specified a key or not, the query parameter allows you to
filter based on the
"""
in_rdfvalue = rdfvalue.PlistRequest
out_rdfvalue = rdfvalue.RDFValueArray
MAX_PLIST_SIZE = 1024 * 1024 * 100 # 100 MB
def Run(self, args):
... | hspec, progress_callback=self.Progress) as fd:
data = fd.Read(self.MAX_PLIST_SIZE)
plist = binplist.readPlist(cStringIO.StringIO(data))
# Create the query parser
parser = plist_lib.PlistFilterParser(self.filter_query).Parse()
filter_imp = plist_lib.PlistFilterImplementation
matcher ... |
renalreg/radar | radar/models/patient_addresses.py | Python | agpl-3.0 | 8,540 | 0.000117 | #! -*- coding: utf-8 -*-
from collections import OrderedDict
from sqlalchemy import Column, Date, ForeignKey, Index, String
from sqlalchemy import Integer
from sqlalchemy.orm import relationship
from radar.database import db
from radar.models.common import MetaModelMixin, patient_id_column, patient_relationship, uuid... | ('MA', 'Morocco'),
('MZ', 'Mozambique'),
('MM', 'Myanmar'),
('NA', 'Na | mibia'),
('NR', 'Nauru'),
('NP', 'Nepal'),
('NL', 'Netherlands'),
('NC', 'New Caledonia'),
('NZ', 'New Zealand'),
('NI', 'Nicaragua'),
('NE', 'Niger'),
('NG', 'Nigeria'),
('NU', 'Niue'),
('NF', 'Norfolk Island'),
('MP', 'Northern Mariana Islands'),
('NO', 'Norway'),
(... |
erangre/Dioptas | dioptas/model/util/smooth_bruckner_python.py | Python | gpl-3.0 | 2,059 | 0.004371 | # -*- coding: utf-8 -*-
# Dioptas - GUI program for fast processing of 2D X-ray diffraction data
# Principal author: Clemens Prescher (clemens.prescher@gmail.com)
# Copyright (C) 2014-2019 GSECARS, University of Chicago, USA
# Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany
... | ibute it and/or modify
# it under the terms of the GNU General Publ | ic 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 warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.... |
RedHatInsights/insights-core | examples/rules/stand_alone.py | Python | apache-2.0 | 2,746 | 0 | #!/usr/bin/env python
"""
Standaone Rule
==============
This is a customer spec, parser and rule and can be run
against the local host using the following command::
$ insights-run -p examples.rules.stand_alone
or from the examples/rules directory::
$ ./stand_alone.py
"""
from __future__ import print_functio... | "])
def parse_content(self, content):
"""
Method to pars | e the contents of file ``/etc/hosts``
This method must be implemented by each parser.
Arguments:
content (list): List of strings that are the contents
of the /etc/hosts file.
"""
self.hosts = []
for line in get_active_lines(content):
# re... |
sdrogers/ms2ldaviz | ms2ldaviz/ms2ldaviz/views.py | Python | mit | 936 | 0.013889 | from django.shortcuts import render
from django.template.loader import render_to_string
def home(request):
context_dict = {}
return render(request,'ms2ldaviz/index.h | tml',context_dict)
def people(request):
context_dict = {}
return render(request,'ms2ldaviz/people.html',context_dict)
def api(request):
context_dict = {}
return render(request,'ms2ldaviz/api.html',context_dict)
def user_guide(request):
markdown_str = render_to_str | ing('markdowns/user_guide.md')
return render(request, 'markdowns/user_guide.html', {'markdown_str':markdown_str})
def disclaimer(request):
markdown_str = render_to_string('markdowns/disclaimer.md')
return render(request, 'markdowns/disclaimer.html', {'markdown_str':markdown_str})
def confidence(request)... |
walterbender/speak | sleepy.py | Python | gpl-3.0 | 2,928 | 0.000683 | # Speak.activity
# A simple front end to the espeak text-to-speech engine on the XO laptop
# http://wiki.laptop.org/go/Speak
#
# Copyright (C) 2008 Joshua Minor
# Copyright (C) 2014 Walter Bender
# This file is part of Speak.activity
#
# Parts of Speak.activity are based on code from Measure.activity
# Copyright (C) ... |
pixbuf = self._pixbuf.scale_simple(w, h, GdkPixbuf.InterpType.BILINEAR)
cr.translate(x + w / 2., y + h / 2.)
cr.translate(-x - w / 2., -y - h / 2.)
Gdk.cairo_set_source_pixbuf(cr, pixbuf, x, y)
cr.rectangle(x, y, w, h)
cr.fill()
return True
def eye_svg():
... | lns="http://www.w3.org/2000/svg"\n' + \
' version="1.1"\n' + \
' width="300"\n' + \
' height="300">\n' + \
' <path\n' + \
' d="m 260.26893,151.09803 c -6.07398,14.55176 -15.05894,27.89881 -26.27797,39.03563 -11.21904,11.13683 -24.66333,20.05466 -39.32004,26.08168 ... |
NicovincX2/Python-3.5 | Algorithmique/Algorithme/Algorithme de tri/Tri par tas (Heapsort)/maxheap.py | Python | gpl-3.0 | 1,134 | 0.000882 | # -*- coding: utf-8 -*-
from minheap import minheap
class maxheap(minheap):
"""
Heap class - made of keys and items
methods: build_heap, heappush, heappop
"""
MAX_HEAP = True
def __str__(self):
return "Max-heap with %s items" % (len(self.heap))
def heapify(self, i):
l =... | [int(parent)]:
self.heap[int(i)], self.heap[int(parent)] = self.heap[
int(parent)], self.heap[int(i)]
| i = parent
parent = self.parent(i)
|
vejmelkam/emotiv-reader | albow/grid_view.py | Python | gpl-3.0 | 1,254 | 0.039075 | from pygame import Rect
from widget import Widget
class GridView(Widget):
# cell_size (width, height) size of each cell
#
# Abstract methods:
#
# num_rows() --> no. of rows
# num_cols() --> no. of columns
# draw_cell(surface, row, col, rect)
# click_cell(row, col, event)
def __init__(se... |
self.draw_cell(surface, r | ow, col, r)
def cell_rect(self, row, col):
w, h = self.cell_size
d = self.margin
x = col * w + d
y = row * h + d
return Rect(x, y, w, h)
def draw_cell(self, surface, row, col, rect):
pass
def mouse_down(self, event):
x, y = event.local
w, h = self.cell_size
W, H = self.size
d = self.margin
... |
zhaowenxiang/chisch | vod/views.py | Python | mit | 446 | 0 | # -*- cod | ing: utf-8 -*-
import logging
from chisch.common.retwrapper import RetWrapper
import cores
logger = logging.getLogger('django')
def signature_url(request):
params_query_dict = request.GET
params = {k: v for k, v in params_query_dict.items()}
try:
url = cores.get_url()
except Exception, e:
... | result)
|
AdrianGaudebert/socorro | webapp-django/crashstats/crashstats/urls.py | Python | mpl-2.0 | 3,962 | 0.000252 | from django.conf.urls import patterns, url
from django.views.generic import RedirectView
from django.conf import settings
from . import views
products = r'/products/(?P<product>\w+)'
versions = r'/versions/(?P<versions>[;\w\.()]+)'
version = r'/versions/(?P<version>[;\w\.()]+)'
perm_legacy_redirect = settings.PERMA... |
urlpatterns = patterns(
'', # prefix
url('^robots\.txt$',
views.robots_txt,
name='ro | bots_txt'),
url(r'^status/json/$',
views.status_json,
name='status_json'),
url(r'^status/revision/$',
views.status_revision,
name='status_revision'),
url(r'^crontabber-state/$',
views.crontabber_state,
name='crontabber_state'),
url('^crashes-per-day/$',
... |
mindcube/mindcube-django-cookiecutter | {{cookiecutter.repo_name}}/project/apps/geo_locator/views.py | Python | mit | 265 | 0.003774 | """Main view for geo locator application"""
from dja | ngo.shortcuts import render
def index(request):
if request.location:
location = request.location
else:
| location = None
return render(request, "homepage.html", {'location': location})
|
gcobos/rft | app/primitives/__init__.py | Python | agpl-3.0 | 1,163 | 0.029235 | # Generated file. Do not edit
__author__="drone"
from Abs import Abs
from And import And
from Average import Average
from Ceil import Ceil
from Cube import Cube
from Divide import Divide
from Double import Double
from Equal import Equal
from Even import Even
from Floor import Floor
from Greaterorequal import Greateror... | Min import Min
from Modu | le import Module
from Multiply import Multiply
from Negate import Negate
from Not import Not
from Odd import Odd
from One import One
from Positive import Positive
from Quadruple import Quadruple
from Sign import Sign
from Sub import Sub
from Sum import Sum
from Two import Two
from Zero import Zero
__all__ = ['Abs', 'A... |
sheagcraig/python-jss | jss/misc_endpoints.py | Python | gpl-3.0 | 13,525 | 0.000074 | #!/usr/bin/env python
# Copyright (C) 2014-2017 Shea G Craig
#
# 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 ... | deviceapplicationsipa
Disk Encryption
diskencryptionconfigurations
diskencryptions (synonymous)
PPD |
printers
id_type:
String of desired ID type:
id
name
_id: Int or String referencing the identity value of the
resource to add the FileUpload to.
resource: String path to the file to uploa... |
CanonicalLtd/landscape-client | landscape/client/upgraders/tests/test_monitor.py | Python | gpl-2.0 | 317 | 0 | from landscape.client.tests.helpers import LandscapeTest
from landscape.client.patch import UpgradeManager
from landscape.client.upgraders import monitor
c | lass TestMonitorUpgraders(LandscapeTest):
def test_monitor_upgrade_manager(self):
self.assertEqual(type(monitor.upgrade_ | manager), UpgradeManager)
|
stryder199/RyarkAssignments | Assignment2/web2py/gaehandler.py | Python | mit | 3,279 | 0.005489 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo D | i Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
"""
##############################################################################
# Configuration parameters for Google App Engine
##############################################################################
KEEP_CACHED = Fal... | evel log statistics
APPSTATS = True # GAE level usage statistics and profiling
DEBUG = False # debug mode
AUTO_RETRY = True # force gae to retry commit on failure
#
# Read more about APPSTATS here
# http://googleappengine.blogspot.com/2010/03/easy-performance-profiling-with.html
# can be accesse... |
wolvespack/alcor | alcor/services/plots/velocity_clouds.py | Python | mit | 7,567 | 0.000793 | from typing import (Tuple,
List)
import matplotlib
# More info at
# http://matplotlib.org/faq/usage_faq.html#what-is-a-backend for details
# TODO: use this: https://stackoverflow.com/a/37605654/7851470
matplotlib.use('Agg')
from matplotlib import pyplot as plt
from matplotlib.patches import Ellips... | ylim=w_limits,
x=vw_cloud_stars['v_velocity'],
y=vw_cloud_stars['w_velocity'],
x_avg=AVERAGE_POPULATION_VELOCITY_V,
y_avg=AVERAGE_POPULATION_VELOCITY_W,
x_std=STD_POPULATION_V,
y_std=STD_POPULATION_W)
... | figure.subplots_adjust(hspace=spacing)
plt.savefig(filename)
def draw_subplot(*,
subplot: Axes,
xlabel: str,
ylabel: str,
xlim: Tuple[float, float],
ylim: Tuple[float, float],
x: List[float],
y: ... |
pisskidney/leetcode | medium/16.py | Python | mit | 1,070 | 0 | #!/usr/bin/python
from typing import List, Optional
"""
16. 3Sum Closest
https://leetcode.com/problems/3sum-closest/
"""
def bsearch(nums, left, right, res, i, j, target):
while left <= right:
middle = (left + righ | t) // 2
| candidate = nums[i] + nums[j] + nums[middle]
if res is None or abs(candidate - target) < abs(res - target):
res = candidate
if candidate == target:
return res
elif candidate > target:
right = middle - 1
else:
left = middle + 1
return re... |
pwollstadt/IDTxl | test/generate_test_data.py | Python | gpl-3.0 | 8,187 | 0.000733 | """Generate test data for IDTxl network comparison unit and system tests.
Generate test data for IDTxl network comparison unit and system tests. Simulate
discrete and continous data from three correlated Gaussian data sets. Perform
network inference using bivariate/multivariate mutual information (MI)/transfer
entropy... | (res):
res.adjacency_matrix.print_matrix()
tp = 0
| fp = 0
if res.adjacency_matrix._edge_matrix[0, 1] == True: tp += 1
if res.adjacency_matrix._edge_matrix[1, 2] == True: tp += 1
if res.adjacency_matrix._edge_matrix[0, 2] == True: fp += 1
fn = 2 - tp
print('TP: {0}, FP: {1}, FN: {2}'.format(tp, fp, fn))
if __name__ == '__main__':
analyse_disc... |
rusiv/BSScript | bsscript/bsscriptSblm/Spinner.py | Python | mit | 784 | 0.034392 | import sublime
from . import SblmCmmnFnctns
class Spinner:
SYMBOLS_ROW = u'←↑→↓'
SYMBOLS_BOX = u'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
def __init__(self, symbols, view, startStr, endStr):
self.symbols = symbols
self.length = len(symbols)
self.position = 0
self.stopFlag = False
self.view = view
self.startStr = startStr
self.... | .position + 1
return self.startStr + self.symbols[self.position % self.length] + self.endStr
def start(self):
if not self.stopFlag:
self.view.set_status(SblmCmmnFnctns.SUBLIME_STATUS_SPINNER, self.__next__())
sublime.set_timeout(lambda: self.start(), 300)
def stop(self):
self.view.erase_status(SblmCm... | E_STATUS_SPINNER)
self.stopFlag = True
|
uliss/quneiform | tests/py/lpod/rst2odt.py | Python | gpl-3.0 | 22,265 | 0.00265 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2009 Ars Aperta, Itaapy, Pierlis, Talend.
#
# Authors: David Versmisse <david.versmisse@itaapy.com>
#
# This file is part of Lpod (see: http://lpod-project.org).
# Lpod is free software; you can redistribute it and/or modify it under
# the terms of either:... | mport from imaging
from PIL import Image
# Import from lpod
from document import odf_new_document_from_type
from frame import odf_create_image | _frame, odf_create_text_frame
from heading import odf_create_heading
from link import odf_create_link
from list import odf_create_list, odf_create_list_item
from note import odf_create_note
from paragraph import odf_create_paragraph, odf_create_line_break
from paragraph import odf_create_undividable_space
from span imp... |
lk-geimfari/elizabeth | mimesis/data/int/address.py | Python | mit | 20,986 | 0 | """Provides all the generic data related to the address."""
COUNTRY_CODES = {
"a2": [
"AD",
"AE",
"AF",
"AG",
"AI",
"AL",
"AM",
"AN",
"AO",
"AQ",
"AR",
"AS",
"AT",
"AU",
"AW",
"AX",
... |
"BDI",
"BEL",
"BEN",
"BER",
"BFA",
"BHR",
"BHU",
"BIH",
"BLR",
"BLZ",
"BOE",
"BOL",
"BOT",
"BRA",
"BRB",
"BRU",
"BUL",
"CAM",
"CAN",
"CAY",
"CGO",
... | ,
"CUB",
"CUW",
"CYP",
"CZE",
"DEN",
"DJI",
"DMA",
"DOM",
"ECU",
|
a358003542/python-guide-book | codes/ch12/asyncio_get_poetry2.py | Python | gpl-2.0 | 1,899 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import argparse
import asyncio
def parse_args():
usage = """usage: %prog [options] [hostname]:port ...
python3 select_get_poetry3.py port1 port2 port3 ...
"""
parser = argparse.ArgumentParser(usage)
parser.add_argument('port', nargs='+')... | nsport
self.transport.write(b'poems')
def data_received(self, data):
if data:
print(data)
print('writing to {}'.format(self.infile.name))
self.infile.write(data)
self.tr | ansport.write(b'poems')
def eof_received(self):
print('end of writing')
self.infile.close()
def main():
addresses = parse_args()
eventloop = asyncio.get_event_loop()
for address in addresses:
host, port = address
filename = str(port) + '.txt'
infile = open(fil... |
samcoveney/GP_emu_UQSA | gp_emu_uqsa/design_inputs/__init__.py | Python | gpl-3.0 | 29 | 0 | from | .design_inputs import *
| |
dhermes/project-euler | python/complete/no121.py | Python | apache-2.0 | 2,079 | 0.000481 | #!/usr/bin/env python
# A bag contains one red disc and one blue disc. In a game of chance a player
# takes a disc at random and its colour is noted. After each turn the disc is
# returned to the bag, an extra red disc is added, and another disc is
# taken at random.
# The player... wins if they have taken more blue ... | min_blue, n + 1):
count += numerators[(blue, n)]
return count
def max_payout(n):
# Integer division precludes floor operation
return factorial(n + 1) / iterative_numerator(n)
def main(verbose=False):
return max_pay | out(15)
if __name__ == '__main__':
print euler_timer(121)(main)(verbose=True)
|
CompassionCH/compassion-modules | message_center_compassion/tests/test_onramp_controller.py | Python | agpl-3.0 | 2,068 | 0.000484 | ##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Nicolas Bornand
#
# The licence is in the file __manifest__.py
#
########################################... | d if token is not provided
"""
del self.opener.headers["Authorization"]
response = self._send_post({"nothing": "nothing"})
self.assertEqual(response.status_code, 401)
error = response.json()
self.assertEqual(error["ErrorMethod"], "ValidateToken")
def test_bad_token(s... | ess denied if token is not valid
"""
self.opener.headers["Authorization"] = "Bearer notrealtoken"
response = self._send_post({"nothing": "nothing"})
self.assertEqual(response.status_code, 401)
@patch(mock_oauth)
def test_wrong_client_id(self, oauth_patch):
""" Check that... |
CNS-OIST/STEPS_Example | publication_models/API_2/Chen_FNeuroinf_2014/AD/AD_single.py | Python | gpl-2.0 | 2,125 | 0.004706 | ########################################################################
# #
# Anomalous Diffusion #
# #
############################... | , 'shaft').X, color=[1.0, 0.0, 0. | 0, 1.0], spec_size=0.1)
with SimDisplay('Hide Spine Species'):
ElementDisplay(rs.dend, color=[0, 0, 1, 0.2])
ElementDisplay(rs.shaft.X, color=[1.0, 0.0, 0.0, 1.0], spec_size=0.1)
with PlotDisplay('Plots'):
SpatialPlot(rs.TETS(tetmesh.shaft.tets).X.Count, axis=[0, 0, 1], nbins=100)
... |
Poom1997/GMan | sendMessageForm.py | Python | mit | 2,434 | 0.012736 | from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtUiTools import *
import plugin.databaseConnect as database
from datetime import datetime
class sendMessageUI(QMainWindow):
def __init__(self, id = None, bulk = None, parent = None):
QMainWindow.__init__(self,None)
self.setMinimum... | self.parent.showOK("Message Sent", "The message has been sent to the user!")
self.closeWindow()
else:
self.parent.showERROR("UserID Not Found", "The UserID you entered does not exists.")
else:
data = self.parent.parent.getCurrentUser()
... | id in self.bulk:
val = db.sendMessage(id, fromUser, message, time)
if (val):
db.disconnect()
self.parent.parentshowOK("All Message Sent to user.", "The message has been sent to all user!")
self.closeWindow()
else:
se... |
wiltonlazary/arangodb | 3rdParty/iresearch/external/text/scripts/generate_unicode_break_tests.py | Python | apache-2.0 | 22,214 | 0.002206 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2020 T. Zachary Laine
#
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
prop_lookup_test_form = decls = '''\
// Copyright (C) 2020 T. Zachary Laine
//
... | s.hpp"
#include <gtest/gtest.h>
#include <algorithm>
TEST(bidi_character, bidi_character_{1:03}_000)
{{
{0}
}}
'''
bidi_character_test_form = '''
{{
// line {4}
std::vector<uint32_t> cons | t cps = {{ {0} }};
std::vector<int> const expected_levels =
{{ {2} }};
std::vector<int> const levels =
bidi_levels(cps.begin(), cps.end(), {1});
int i = 0;
for (int l : expected_levels) {{
if (0 <= l) {{
EXPECT_EQ(levels[i], l) << "i=" ... |
linzhaolover/myansible | openstackfile/getgpulocked.py | Python | apache-2.0 | 696 | 0.027299 | #!/usr/bin/env python
path="/var/lib/gpu/gpu_locked.txt"
import os,sys
import ast
import socket
def getHost():
return socket.gethostname()
def getlocked():
hostname=getHost()
#print path
fp=open(path, "r")
info=fp.read()
#print info
d=ast.literal_eval(info)
#print len(d)
prin... | %s,nvidia1,%d" % (hostname, (9999 - d['nvidia1']['available_count']))
print "%s,nvidia2,%d" % (hostname, (9999 - d['nvidia2']['available_count']))
print "%s,nvidia3,%d" % (hostname, (9999 - d['nvidia3']['available_count']))
fp.cl | ose()
if __name__ == "__main__":
getlocked()
|
AnsonShie/system_monitor | messages_monitor.py | Python | apache-2.0 | 2,645 | 0.003403 | #!/usr/bin/python
__author__ = 'anson'
import optparse
import re
import sys
from utils.utils_cmd import execute_sys_cmd
from lib_monitor.monitor_default_format import nagios_state_to_id
class messages_check():
def __init__(self, rex, config, type):
self.rex = rex
self.config = config
self.t... | 2000000) as rex_all:
for rex_split in rex_all:
rex_dict.append(rex_split)
with open('/tmp/' + v_protocol, buffering=2000000) as file_to_check:
for pa | rt in file_to_check:
for rex_rule in rex_dict:
m_iface = re.search(rex_rule, part)
v_dev = m_iface.group(1) if m_iface else 'none'
print v_dev
sys.exit(exit_state)
def main():
"""
messages_monitor.py
unit... |
C2SM-RCM/testsuite | tools/comp_table.py | Python | mit | 5,041 | 0.026384 | #!/usr/bin/env python2
"""
COSMO TECHNICAL TESTSUITE
General purpose script to compare two files containing tables
Only lines with given table pattern are considered
"""
# built-in modules
import os, sys, string
# information
__author__ = "Xavier Lapillonne"
__maintainer__ = "xavier.lapillonne@meteoswiss.ch"
... | ose>1:
print('Warning: %s and %s have different size, comparing commun set only \n' %(file1,file2))
ncdata=min(nd1,nd2)
if (maxcompline>0):
ncdata=min(ncdata,maxcomp | line)
# Iterates through the lines
for il in range(ncdata):
l1=data1[il].split()
l2=data2[il].split()
l1match=matchColPattern(l1,colpattern)
l2match=matchColPattern(l2,colpattern)
# compare values if both lines are compatible
if l1match and l2match:
... |
neilLasrado/erpnext | erpnext/accounts/doctype/sales_invoice/pos.py | Python | gpl-3.0 | 21,154 | 0.02496 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import json
import frappe
from erpnext.accounts.party import get_party_account_currency
from erpnext.controllers.accounts_controller import get_taxes_a... | t_custo | mers_list(pos_profile)
doc.plc_conversion_rate = update_plc_conversion_rate(doc, pos_profile)
return {
'doc': doc,
'default_customer': pos_profile.get('customer'),
'items': items_list,
'item_groups': get_item_groups(pos_profile),
'customers': customers,
'address': get_customers_address(customers),
'co... |
JetChars/vim | vim/bundle/python-mode/pymode/autopep8.py | Python | apache-2.0 | 120,700 | 0.000033 | #!/usr/bin/env python
# Copyright (C) 2010-2011 Hideo Hattori
# Copyright (C) 2011-2013 Hideo Hattori, Steven Myint
# Copyright (C) 2013-2015 Hideo Hattori, Steven Myint, Bill Wendling
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files... | .op | en(filename, mode=mode, encoding=encoding,
newline='') # Preserve line endings
def detect_encoding(filename):
"""Return file encoding."""
try:
with open(filename, 'rb') as input_file:
from lib2to3.pgen2 import tokenize as lib2to3_tokenize
encoding = lib2to3_... |
e-gob/plataforma-kioscos-autoatencion | scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/cloud/amazon/rds.py | Python | bsd-3-clause | 56,122 | 0.002441 | #!/usr/bin/python
# 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 version.
#
# Ansible is distributed... | en command=create or
command=modify.
required: false
default: null
zone:
description:
- availability zone in which to launch the instance. Used only when command=create, command=replicate or command=restore.
| required: false
default: null
aliases: ['aws_zone', 'ec2_zone']
subnet:
description:
- VPC subnet group. If specified then a VPC instance is created. Used only when command=create.
required: false
default: null
snapshot:
description:
- Name of snapshot to take. When command=... |
sauloal/PiCastPy | sqlalchemy/orm/interfaces.py | Python | mit | 28,330 | 0.000671 | # orm/interfaces.py
# Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
Contains various base classes used throughout the ORM.
Defines the now depreca... | urn True if this ``MapperProperty``'s mapper is the
primary mapper for its class.
This flag is used to indicate that the ``MapperProperty`` can
define attribute instrumentation for the class at the class
level (as opposed to the individual instance level).
"""
return no... | the attribute represented by this ``MapperProperty``
from source to destination object"""
|
lahwaacz/tvnamer | tvnamer/renamer.py | Python | unlicense | 4,157 | 0.001203 | #!/usr/bin/env python
import os
import shutil
import logging
from unicode_helper import p
__all__ = ["Renamer"]
def log():
"""Returns the logger for current file
"""
return logging.getLogger(__name__)
def same_partition(f1, f2):
"""Returns True if both files or directories are on the same partit... | shutil.copyfile(old, new)
shutil.copystat(old, new)
def symlink_file(target, name):
"""Create symbolic | link named 'name' pointing to 'target'.
"""
p("Creating symlink %s to %s" % (name, target))
log().debug("Creating symlink %r to %r" % (name, target))
os.symlink(target, name)
class Renamer(object):
"""Deals with renaming of files
"""
def __init__(self, filename):
self.filename = ... |
badbytes/pymeg | gui/gtk/data_editor.py | Python | gpl-3.0 | 30,723 | 0.01494 | #!/usr/bin/python2
#!/usr/bin/env python
#
# Copyright 2010 dan collins <danc@badbytes.net>
#
# 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 Lice... | cm
from matplotlib.figure import Figure
from matplotlib.lines import Line2D
#from meg import megcontour_gtk
from pdf2py import pdf, readwrite
from gui.gtk | import contour as contour_gtk
from gui.gtk import meg_assistant,event_process#,offset_correct
try:
import pygtk
pygtk.require("2.0")
except:
pass
try:
import gtk
import gtk.glade
except:
print("GTK Not Availible")
sys.exit(1)
class setup_gui:
def __init__(self):
self.builder = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.