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
dmacvicar/spacewalk
backend/server/rhnSQL/sql_types.py
Python
gpl-2.0
1,465
0
# # Copyright (c) 2008--2010 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...
. # # Red Hat trademarks are not licensed under GPLv2. No permission is # granted to use or replicate Red Hat trademarks that are incorporated # in this software or its documentation. # # # Database types we support for out variables # # Data types class DatabaseDataType:
type_name = None def __init__(self, value=None, size=None): self.size = size or 1 self.set_value(value) def get_value(self): return self.value def set_value(self, value): self.value = value def __str__(self): return self.type_name class NUMBER(DatabaseDa...
falbassini/googleads-dfa-reporting-samples
python/v2.2/target_ad_to_remarketing_list.py
Python
apache-2.0
2,651
0.00679
#!/usr/bin/python # # Copyright 2015 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 b...
se re-run the ' 'application to re-authorize') if
__name__ == '__main__': main(sys.argv)
5monkeys/blues
blues/redis.py
Python
mit
1,983
0.001513
""" Redis Blueprint =============== **Fabric environment:** .. code-block:: yaml blueprints: - blues.redis settings: redis: # bind: 0.0.0.0 # Set the bind address specifically (Default: 127.0.0.1) """ import re from fabric.decorators import task from fabric.utils import abort from ref...
etup(): """ Install and configure Redis """ install() configure() def install(): with sudo(): debian.apt_get('install', 'redis-server') def get_installed_version(): """ Get installed version as tuple. Parsed output format: Redis server
v=2.8.4 sha=00000000:0 malloc=jemalloc-3.4.1 bits=64 build=a... """ retval = run('redis-server --version') m = re.match('.+v=(?P<version>[0-9\.]+).+', retval.stdout) try: _v = m.group('version') v = tuple(map(int, str(_v).split('.'))) return v except IndexError: abort...
praekelt/panya-show
show/urls.py
Python
bsd-3-clause
804
0.007463
from django.conf.urls.defaults import patterns, url urlpatterns = patterns( 'show.views', url(r'^radioshow/entrylist/$', 'radioshow_entryitem_list', name='radioshow_entryitem_list'), url(r'^showc
ontributor/list/(?P<slug>[\w-]+)/$', 'showcontributor_content_list', name='showcontributor_content_list'), url(r'^showcontributor/appearance/(?P<slug>[\w-]+)/$', 'showcontributor_appearance_list', name='showcontributor_appearance_list'), url(r'^showcont
ributor/(?P<slug>[\w-]+)/$', 'showcontributor_detail', name='showcontributor_detail'), url(r'^showcontributor/content/(?P<slug>[\w-]+)/$', 'showcontributor_content_detail', name='showcontributor_content_detail'), url(r'^showcontributor/contact/(?P<slug>[\w-]+)/$', 'showcontributor_contact', name='showcontributo...
Sarthak30/Codeforces
soft_drinking.py
Python
gpl-2.0
109
0.027523
n, k, l, c, d
, p, nl, np = map(int,raw_input().split()) a = k*l x = a/nl y = c*d z = p/np print
min(x,y,z)/n
Marcdnd/cryptoescudo
contrib/spendfrom/spendfrom.py
Python
mit
10,054
0.005968
#!/usr/bin/env python # # Use the raw transactions API to spend bitcoins received on particular addresses, # and send any change back to that same address. # # Example usage: # spendfrom.py # Lists available funds # spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00 # # Assumes it will talk to a bitcoind or Bit...
], "Bitcoin") return os.path.expanduser("~/.bitcoin") def read_bitcoin_config(dbdir): """Read the bitcoin.conf file from dbdir, returns dictionary of settings""" from ConfigParser import SafeConfigParser class FakeSecHead(object): def __init__(self, f
p): self.fp = fp self.sechead = '[all]\n' def readline(self): if self.sechead: try: return self.sechead finally: self.sechead = None else: s = self.fp.readline() if s.find('#') != -1: ...
ozamiatin/oslo.messaging
oslo_messaging/_drivers/zmq_driver/client/publishers/dealer/zmq_dealer_publisher_direct.py
Python
apache-2.0
6,687
0.00015
# Copyright 2015-2016 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
.zmq_driver import zmq_address from oslo_messaging._drivers.zmq_driver import zmq_async from oslo_messaging._drivers.zmq_driver import zmq_names LOG = logging.getLogger(__name__) zmq = zmq_async.import_zmq() class DealerPublisherDirect(zmq_dealer_publisher_base.DealerPublisherBase): """DEALER-publisher using d...
services assumes the following: - All direct connections are dynamic - so they live per message, thus each message send executes the following: * Open a new socket * Connect to some host got from the RoutingTable * Send message(s) ...
InnovativeTravel/s3-keyring
tests/conftest.py
Python
mit
714
0
"""Global test fixtures.""" import uuid import pytest from s3keyring.s3 import S3Keyring from s3keyring.settings import config from keyring.errors import PasswordDeleteError
@pytest.fixture def keyring(scope="module"): config.boto_config.activate_profile("test") return S3Keyring() @pytest.yield_fixture def random_entry(keyring, scope="function"): service = str(uuid.uuid4()) user = str(uuid.uuid4())
pwd = str(uuid.uuid4()) yield (service, user, pwd) # Cleanup try: keyring.delete_password(service, user) except PasswordDeleteError as err: if 'not found' not in err.args[0]: # It's ok if the entry has been already deleted raise
georgetown-analytics/skidmarks
bin/cluster.py
Python
mit
2,943
0.016989
print(__doc__) from time import time import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn import metrics from sklearn.cluster import KMeans from sklearn.datasets import load_digits from sklearn.decomposition import PCA from sklearn.preprocessing import scale from sklearn.preprocessing i...
rs=n_clusters) cluster.fit_transform(patched) #assigned grouped labe
ls to the crime data labels = cluster.labels_ #copy dataframe (may be memory intensive but just for illustration) skid_data = crime_data.copy() #print pd.Series(classified_data) #print pd.Series(prediction_data) skid_data['Cluster Class'] = pd.Series(labels, index=skid_data.index) print skid_data.describe() print ski...
AllenDowney/MarriageNSFG
thinkstats2.py
Python
mit
75,264
0.000864
"""This file contains code for use with "Think Stats" and "Think Bayes", both by Allen B. Downey, available from greenteapress.com Copyright 2014 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """ from __future__ import print_function, division """This file contains class definitions for: H...
om generators. x: int seed """ random.seed(x) np.random.seed(x) def Odds(p): """Computes odds for a given probability. Examp
le: p=0.75 means 75 for and 25 against, or 3:1 odds in favor. Note: when p=1, the formula for odds divides by zero, which is normally undefined. But I think it is reasonable to define Odds(1) to be infinity, so that's what this function does. p: float 0-1 Returns: float odds """ if p == ...
GoogleCloudPlatform/gsutil
gslib/tests/test_notification.py
Python
apache-2.0
6,042
0.002648
# -*- coding: utf-8 -*- # Copyright 2013 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 require...
ion.') def test_stop_channel(self): """Tests stopping a notification channel on a bucket.""" bucket_uri = self.CreateBucket() stderr = self.RunGsUtil( ['notification', 'watchbucket', NOTIFICATION_URL, suri(bucket_uri)], return_stderr=True) channel_id = re.findall(r'channel
identifier: (?P<id>.*)', stderr) self.assertEqual(len(channel_id), 1) resource_id = re.findall(r'resource identifier: (?P<id>.*)', stderr) self.assertEqual(len(resource_id), 1) channel_id = channel_id[0] resource_id = resource_id[0] self.RunGsUtil(['notification', 'stopchannel', channel_id, r...
bdaroz/the-blue-alliance
controllers/datafeed_controller.py
Python
mit
31,351
0.002775
import logging import os import datetime import tba_config import time import json from google.appengine.api import taskqueue from google.appengine.ext import ndb from google.appengine.ext import webapp from google.appengine.ext.webapp import template from consts.event_type import EventType from consts.media_type imp...
uery(Event.official == True).filter(Event.year == int(when)).fetch(500, keys_only=True) events = ndb.get_multi(event_keys) for event in events: taskqueue.add( queue_name='datafeed', url='/tasks/get/fmsapi_awards/%s' % (event.key_name), met...
rite out if not in taskqueue path = os.path.join(os.path.dirname(__file__), '../templates/datafeeds/usfirst_awards_enqueue.html') self.response.out.write(template.render(path, template_values)) class FMSAPIAwardsGet(webapp.RequestHandler): """ Handles updating awards """ def ge...
CERNDocumentServer/cds-videos
cds/modules/records/bundles.py
Python
gpl-2.0
2,122
0
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016, 2017 CERN. # # Invenio 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...
_modules/invenio-files-js/dist/invenio-files-js.js", "node_modules/ngmodal/dist/ng-modal.js", "js/cds_records/main.js", "js/cds_records/user_actions_logger.js",
filters="jsmin", ), depends=("node_modules/cds/dist/*.js",), filters="jsmin", output="gen/cds.record.%(version)s.js", npm={ "angular": "~1.4.10", "angular-sanitize": "~1.4.10", "angular-loading-bar": "~0.9.0", "cds": "~0.2.0", "ng-dialog": "~0.6.0", ...
praekelt/molo
molo/core/management/commands/add_language_to_pages.py
Python
bsd-2-clause
702
0
from __future__ import absolute_import, unicode_literals from django.core.management.base import BaseCommand from molo.core.models import LanguageRelation from molo.core.models import Page class Command(BaseCommand): def handle(self, *args, **options): for relation in LanguageRelation.objects.all(): ...
page = Page.objects.get(pk=relation.page.pk).specific page.language = relation.language page.save() else: s
elf.stdout.write(self.style.NOTICE( 'Relation with pk "%s" is missing either page/language' % (relation.pk)))
onehao/opensource
pyml/inaction/ch03/decisiontree/trees.py
Python
apache-2.0
4,087
0.015659
''' @author: Michael Wan @since : 2014-11-08 ''' from math import log import operator def createDataSet(): dataSet = [[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']] labels = ['no surfacing','flippers'] #cha...
aSet, bestFeat, value),subLabels) return myTree
def classify(inputTree,featLabels,testVec): firstStr = inputTree.keys()[0] secondDict = inputTree[firstStr] featIndex = featLabels.index(firstStr) key = testVec[featIndex] valueOfFeat = secondDict[key] if isinstance(valueOfFeat, dict): classLabel = classify(value...
dstcontrols/osisoftpy
examples/mini_signal_example.py
Python
apache-2.0
5,723
0.007863
import random, inspect from sched import scheduler from time import time, sleep from datetime import datetime #################################################################################################### # Minimal implementation of the signaling library class Signal(object): def __init__(self, name): ...
ame, seamus, seamus_signal, seamus_signal.send(seamus))) ## Subscribing to signals def monitor_changes_in_effort(people): # For each person, we call the signal method. signal() will either return an existing signal for
# that person, or return a new signal for that person. - hence the singletome comment above. signals = [signal(person.name) for person in people] # list comprehension # signals = [functionToCall() for thing in someList] # signals = [] # for person in people: # s = signal(person.name) # ...
skomendera/PyMyTools
providers/terminal.py
Python
mit
2,039
0.00049
import os def get_terminal_columns(): terminal_rows, terminal_columns = os.popen('stty size', 'r').read().split() return int(terminal_columns) def get_terminal_rows(): terminal_rows, terminal_columns = os.popen('stty size', 'r').read().split() return int(terminal_rows) def get_header_l1(lines_li...
) if seconds > 86400: output.append('%s days' % round(seconds / 86400)) seconds %= 86400 if seconds > 36
00: output.append('%s hours' % round(seconds / 3600)) seconds %= 3600 if seconds > 60: output.append('%s minutes' % round(seconds / 60)) seconds %= 60 if seconds > 0: output.append('%s seconds' % seconds) return ' '.join(output) def format_documentation_list(l...
emanueldima/b2share
b2share/modules/deposit/utils.py
Python
gpl-2.0
823
0
"""Utilities for B2share deposit.""" from flask import request from werkzeug.local import LocalProxy from werkzeug.routing import PathConverter def file_id_to_key(value): """Convert file UUID to value if in request context.""" from invenio_fi
les_rest.models import ObjectVersion _, record = request.view_args['pid_value'].data if value in record.files: return value object_version = ObjectVersion.query.filter_by( bucket_id=record.files.bucket.id, file_id=value ).first() if object_version: return object_version.key...
UUID for key.""" def to_python(self, value): """Lazily convert value from UUID to key if need be.""" return LocalProxy(lambda: file_id_to_key(value))
coodoing/piconv
support_encodings.py
Python
apache-2.0
13,095
0.002596
#-*-coding=utf-8-*- class SupportEncodings(object): """ Given the support encoding of piconv """ supports = [] def __init__(self): self.supports = ['ASCII','UTF-8','UTF-16','UTF-32',\ 'BIG5','GBK','GB2312','GB18030','EUC-JP', 'SHIFT_JIS', 'ISO-2022-JP'\ 'WINDOWS-1252'] def get_support_enc
odings(self): return self.supports def get_all_coded_character_set(self): return [''] """ 437, 500, 500V1, 850, 851, 852, 855, 856, 857, 860, 861, 862, 863, 864, 865, 866, 866NAV, 869, 874, 904, 1026, 1046, 1047, 8859_1, 8859_2, 8859_3, 8859_4, 8859_5, 8859_6, 8859_7, 8859_8, 88
59_9, 10646-1:1993, 10646-1:1993/UCS4, ANSI_X3.4-1968, ANSI_X3.4-1986, ANSI_X3.4, ANSI_X3.110-1983, ANSI_X3.110, ARABIC, ARABIC7, ARMSCII-8, ASCII, ASMO-708, ASMO_449, BALTIC, BIG-5, BIG-FIVE, BIG5-HKSCS, BIG5, BIG5HKSCS, BIGFIVE, BRF, BS_4730, CA, CN-BIG5, CN-GB, CN, CP-AR, CP-GR, CP-HU, CP037, CP038, CP273, C...
fameyer/comatmor
src/comatmor/__init__.py
Python
gpl-2.0
96
0
# module in
cludes import elliptic import heat import IRT print "Loading comatmor version 0.0.1"
hyades/whatsapp-client
src/layers/receivers/receipt_receiver.py
Python
gpl-3.0
221
0
from layers.receivers.base_receiever import BaseRe
ceiver class ReceiptReceiver(BaseReceiver): def onReceipt(self, receiptEntity): ack = ReceiptReceiver.getAckEntity(receiptEnt
ity) self.toLower(ack)
agendaodonto/server
app/schedule/serializers/patient.py
Python
agpl-3.0
559
0.001789
from rest_framework.serializers import ModelSerializer from app
.schedule.models.patient import Patient from app.schedule.serializers.clinic import ClinicListSerializer from app.schedule.serializers.dental_plan import DentalPlanSerializer
class PatientSerializer(ModelSerializer): class Meta: model = Patient fields = ('id', 'name', 'last_name', 'sex', 'phone', 'clinic', 'created', 'modified', 'dental_plan') class PatientListSerializer(PatientSerializer): clinic = ClinicListSerializer() dental_plan = DentalPlanSerializer()...
Rcoko/flaskLearn
app/main/views.py
Python
mit
3,576
0.014646
# -- coding: utf-8 -- from flask import render_template, session, redirect, url_for, current_app, request from .. import db from ..models import Detail,Contents,Keywords,WXUrls from . import main from .forms import NameForm import wechatsogou import hashlib from .errors import * from ..API.reqweb import * @main.route...
session['name'] = form.name.data return redirect(url_for('.index')) return render_template('index.html', form=form, name=session.get('name'), known=session.get('known', False)) @main.route('/test/') def test(): content = Contents(name="tes...
len(ss) s1 = ss[0] a = 4 #todo1.save() return render_template('detail.html',detail = s1) @main.route('/content/',methods=['GET', 'POST']) def content(): keyword=request.args.get('key') vx_obj = wechatsogou.WechatSogouAPI() lists = [] sugg_keywords = [] md5_string = '' keyword...
bschug/neverending-story
markov.py
Python
mit
5,169
0.001161
import argparse from collections import defaultdict, Counter, deque import random import json import time from tqdm import tqdm import wikipedia class MarkovModel(object): def __init__(self): self.states = defaultdict(lambda: Counter()) self.totals = Counter() def add_sample(self, state, foll...
ma
in(parse_args())
pronexo-odoo/odoo-argentina
l10n_ar_account_check_debit_note/invoice.py
Python
agpl-3.0
31,158
0.008634
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012 OpenERP - Team de Localización Argentina. # https://launchpad.net/~openerp-l10n-ar-localization # # This program is free software: you can redistribute it and/or modify # it under the terms of t...
partner_bank_id=False, company_id=False): invoice_addr_id = False contact_addr_id = False partner_payment_term = False acc_id = False bank_id = False fiscal_position = False opt = [('uid', str(uid))] if partner_id: opt.insert(0, ('id', partne...
act'] invoice_addr_id = res['invoice'] p = self.pool.get('res.partner').browse(cr, uid, partner_id) if company_id: if not p.property_account_receivable or not p.property_account_payable: raise osv.except_osv(_('Error!'), ...
endlessm/chromium-browser
third_party/swiftshader/third_party/llvm-7.0/llvm/utils/llvm-build/llvmbuild/main.py
Python
bsd-3-clause
34,146
0.002577
from __future__ import absolute_import import filecmp import os import sys import llvmbuild.componentinfo as componentinfo from llvmbuild.util import fatal, note ### def cmake_quote_string(value): """ cmake_quote_string(value) -> str Return a quoted form of the given value that is suitable for use in C...
"component %r has invalid reference %r (via %r)" % ( ci.name, referent_name, relation)) # Visit the reference.
current_stack.append((relation,ci)) current_set.add(ci) visit_component_info(referent, current_stack, current_set) current_set.remove(ci) current_stack.pop() # Finally, add the component info to the ordered list. self.or...
hlmnrmr/liveblog
server/liveblog/themes/template/loaders.py
Python
agpl-3.0
3,378
0.001184
import os import logging from superdesk import get_resource_service from jinja2.loaders import FileSystemLoader, ModuleLoader, ChoiceLoader, DictLoader, PrefixLoader from liveblog.mongo_util import decode as mongodecode __all__ = ['ThemeTemplateLoader', 'CompiledThemeTemplateLoader'] logger = logging.getLogger('supe...
onary(theme) if parent_theme: parent = themes.find_one(req=None, name=parent_theme) self.addDictonary(parent) else: compiled = themes.get_theme_
compiled_templates_path(theme_name) self.loaders.append(ModuleLoader(compiled)) if parent_theme: parent_compiled = themes.get_theme_compiled_templates_path(parent_theme) self.loaders.append(ModuleLoader(parent_compiled)) # let's now add the parent theme p...
OCA/partner-contact
base_location/models/res_partner.py
Python
agpl-3.0
5,851
0.001196
# Copyright 2016 Nicolas Bessi, Camptocamp SA # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from lxml import etree from odoo import _, api, fields, models from odoo.exceptions import ValidationError class ResPartner(models.Model): _inherit = "res.par...
_compute_zip_id", readonly=False, store=True, ) city_id = fields.Many2one( index=True, # add index for performance compute="_compute_city_id", readonly=False, store=True, ) city = fields.Char(compute="_compute_city", readonly=False, store=True) zip = ...
state_id = fields.Many2one(compute="_compute_state_id", readonly=False, store=True) @api.depends("state_id", "country_id", "city_id", "zip") def _compute_zip_id(self): """Empty the zip auto-completion field if data mismatch when on UI.""" for record in self.filtered("zip_id"): fiel...
ZeroCater/Eyrie
interface/models.py
Python
mit
4,056
0.00074
from django.conf import settings from django.contrib.auth.models import User from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank from django.core.urlresolvers import reverse from django.db import models from github import UnknownObjectException from social.apps.django_app.default.models imp...
docs.append(document.filename) else: first_seg = doc_path.split('/', maxsplit=2)[1] if first_seg: folder_name = '{}/'.format(first_seg) if folder_name not in folders: folders.append(folder_name) ...
docs = sorted(docs) folders.extend(docs) return folders
deepmind/brave
brave/training/trainer.py
Python
apache-2.0
3,771
0.003447
# Copyright 2021 DeepMind Technologies Limited # # 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 agree...
dates(NamedTuple): params: hk.Params sta
te: hk.State opt_state: optax.OptState scalars: embedding_model.Scalars UpdateFn = Callable[ [chex.PRNGKey, datasets.MiniBatch, hk.Params, hk.State, optax.OptState], ModelUpdates] def build_update_fn(optimizer: optax.GradientTransformation, loss_fn: embedding_model.LossFn) -> UpdateF...
anirudhvenkats/clowdflows
workflows/management/commands/__init__.py
Python
gpl-3.0
23
0
_
_author__
= 'matjaz'
c3nav/c3nav
src/c3nav/site/migrations/0001_announcement.py
Python
apache-2.0
1,128
0.004433
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-12-07 22:51 from __future__ import unicode_literals import c3nav.mapdata.fields from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateMod...
dels.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True, verbose_name='created')), ('active_until', models.DateTimeField(null=True, verbose_name='active until')), ('active', models.Boolea...
_name='Message')), ], options={ 'verbose_name': 'Announcement', 'verbose_name_plural': 'Announcements', 'get_latest_by': 'created', 'default_related_name': 'announcements', }, ), ]
calpeyser/google-cloud-python
vision/google/cloud/vision_v1/types.py
Python
apache-2.0
1,284
0
# 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 ...
e 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. from
__future__ import absolute_import import sys from google.cloud.proto.vision.v1 import geometry_pb2 from google.cloud.proto.vision.v1 import image_annotator_pb2 from google.cloud.proto.vision.v1 import text_annotation_pb2 from google.cloud.proto.vision.v1 import web_detection_pb2 from google.gax.utils.messages import ...
phodal-archive/scrapy-elasticsearch-demo
dianping/dianping/spiders/rotateAgent.py
Python
mit
2,814
0.013859
#!/usr/local/bin/python # -*-coding:utf8-*- from scrapy.contrib.downloadermiddleware.useragent import UserAgentMiddleware import random class RotateUserAgentMiddleware(UserAgentMiddleware): def __init__(self, user_agent=''): self.user_agent = user_agent def process_request(self, request, spider): ...
# print '********user-agent:',ua # the default user_agent_list composes chrome,I E,firefox,Mozilla,opera,netscape #for more user agent strings,you can find it in http://www.useragentstring.com/pages/useragentstring.php user_agent_list = [ \ "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 ...
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6", \ "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6", \ "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrom...
agmscode/agms_python
agms/__init__.py
Python
mit
305
0
from __future__ import absolute_import f
rom agms.configuration import Configuration from agms.agms import Agms from agms.transaction import Transaction from agms.safe import SAFE from agms.report import Report from agms.recurring import Recurring from agms.hpp import HPP from agms.version import V
ersion
openqt/algorithms
projecteuler/pe303-multiples-with-small-digits.py
Python
gpl-3.0
418
0.014423
#!/u
sr/bin/env python # coding=utf-8 """303. Multiples with small digits https://projecteuler.net/problem=303 For a positive integer n, define f(n) as the least positive multiple of n that, written in base 10, uses only digits ≤ 2. Thus f(2)=2, f(3)=12, f(7)=21, f(42)=210, f(89)=1121222. Also, $\sum \limits_{n = 1}^{10...
)}{n}}$. """
mtils/ems
ems/support/bootstrappers/validation.py
Python
mit
1,933
0.002587
import json import os.path from ems.app import Bootstrapper, absolute_path from ems.inspection.util import classes from ems.validation.abstract import Validator, MessageProvider from ems.validation.registry import Registry from ems.validation.rule_validator import RuleValidator, SimpleMessageProvider from ems.validat...
g','de','validation.json') def bootstrap(self, app): self.app = app app.share(Registry, self.createRegistry) app.share(MessageProvider, self.createMessageProvider) app.share(PathNormalizer, self.createPathNormalizer) def createRegistry(self): regi
stry = Registry(self.app) self.addValidatorClasses(registry) return registry def createPathNormalizer(self): return AppPathNormalizer() def addValidatorClasses(self, registry): for module in self.validatorModules: for cls in self.findModuleValidatorClasses(module): ...
valeriocos/perceval
perceval/backends/core/twitter.py
Python
gpl-3.0
14,309
0.002238
# -*- coding: utf-8 -*- # # Copyright (C) 2015-2019 Bitergia # # 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 vers
ion. # # 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA. # # Authors: # Valerio Cosentino <valcos@bitergia.com...
Artemkaaas/indy-sdk
vcx/wrappers/python3/generate_docs.py
Python
apache-2.0
952
0.003151
import os import pydoc import sys class DocTree: def __init__(self, src, dest): self.basepath = os
.getcwd() sys.path.append(os.path.join(self.basepath, src)) self.src = src self.dest = dest self._make_dest(dest) self._make_docs(src) self._move_docs(dest) def _make_dest(self, dest): path = os.path.join(self.basepath, dest) if os.path.isdir(path): ...
ls for ' + src) pydoc.writedocs(src) print(os.listdir()) def _move_docs(self, dest): for f in os.listdir(): if f.endswith('.html'): _dest = os.path.join(dest, f) os.rename(f, _dest) def main(): dest = 'docs' src = 'vcx/api' src = os...
igor-toga/local-snat
neutron/tests/unit/agent/linux/test_iptables_firewall.py
Python
apache-2.0
86,232
0.000116
# Copyright 2012, Nachi Ueno, NTT MCL, 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 # # Unles...
irewallTestCase, self).setUp() cfg.CONF.register_opts(a_cfg.ROOT_HELPER_OPTS, 'AGENT') security_config.register_securitygroups_opts() cfg.CONF.set_override('comment_iptables_rules', False, 'AGENT') self.uti
ls_exec_p = mock.patch( 'neutron.agent.linux.utils.execute') self.utils_exec = self.utils_exec_p.start() self.iptables_cls_p = mock.patch( 'neutron.agent.linux.iptables_manager.IptablesManager') iptables_cls = self.iptables_cls_p.start() self.iptables_inst = mock....
libchaos/algorithm-python
bit/add_with_op.py
Python
mit
233
0.017167
def add_with
out_op(x, y): while y !=0: carry = x & y x = x ^ y y = carry << 1 print(x) def main(): x, y = map(int, input().split()) add_
without_op(x, y) if __name__ == "__main__": main()
NEMO-NOC/NEMOsphere
lego5.py
Python
gpl-2.0
14,256
0.012556
#!/usr/bin/env python from __future__ import print_function import os, platform from argparse import ArgumentParser import numpy as np import time import resource from mayavi import mlab from netCDF4 import Dataset from mpl_toolkits.basemap import Basemap from numba import jit @jit def add_triangles_from_square(x, ...
abs(yy01 - yy00) + abs(xx11 - xx10) + abs(yy11 - yy10) > ds_max: continue # x & y coordinates of f-points surrounding T-point i,j # 00 = SW, 10 = NW, 01 = SE, 11 = NE # do horizontal faces of T-box, zig-zag points SW, NW, SE, NE # insert x & y for 2-triangles (kth & k+1th)...
stant z dep00 = dep[j,i] add_triangles_from_square(z, dep00, dep00, dep00, dep00, k) # color depends on z if dep00 == 0.: add_triangles_from_square(t, t_land, t_land, t_land, t_land, k) else: add_triangles_from_square(t, dep00, dep00, dep00, dep00, k) ...
lookout/dd-agent
checks.d/mysql.py
Python
bsd-3-clause
62,670
0.002266
# stdlib import re import traceback from contextlib import closing, contextmanager from collections import defaultdict # 3p import pymysql try: import psutil PSUTIL_AVAILABLE = True except ImportError: PSUTIL_AVAILABLE = False # project from config import _is_affirmative from checks import AgentCheck GAU...
sql.myisam.key_buffer_size', GAUGE), 'Key_cache_utilization': ('mysql.performance.key_cache_utilization', GAUGE), 'max_connections': ('mysql.net.max_connections_available', GAUGE), 'query_cache_size': ('mysql.performance.qcache_size',
GAUGE), 'table_open_cache': ('mysql.performance.table_open_cache', GAUGE), 'thread_cache_size': ('mysql.performance.thread_cache_size', GAUGE) } INNODB_VARS = { # InnoDB metrics 'Innodb_data_reads': ('mysql.innodb.data_reads', RATE), 'Innodb_data_writes': ('mysql.innodb.data_writes', RATE), 'In...
quadrismegistus/prosodic
meters/strength_and_resolution.py
Python
gpl-3.0
10,457
0.005929
############################################ # [config.py] # CONFIGURATION SETTINGS FOR A PARTICULAR METER # # # Set the long-form name of this meter name = "*PEAK only" # # [Do not remove or uncomment the following line] Cs={} ############################################ ############################################ #...
on should not contain more than one syllable, # *unless* it is preceded by a disyllabic *weak* metrical po
sition: # [use to implement the metrical pattern described by Derek Attridge, # in The Rhythms of English Poetry (1982), and commented on by Bruce Hayes # in his review of the book in Language 60.1 (1984). # e.g. Shakespeare's "when.your|SWEET.IS|ue.your|SWEET.FORM|should|BEAR" # [this implementation is different in th...
MehmetNuri/ozgurlukicin
feedjack/fjlib.py
Python
gpl-3.0
9,326
0.006005
# -*- coding: utf-8 -*- """ feedjack Gustavo Picón fjlib.py """ from django.conf import settings from django.db import connection from django.core.paginator import Paginator, InvalidPage from django.http import Http404 from django.utils.encoding import smart_unicode from oi.feedjack import models from oi.feedjack im...
""" Returns the 1-based index of the last object on the given page, relative to total objects found (hits). """ page_number = self.validate_page_number(
page_number) if page_number == self.num_pages: return self.count return page_number * self.num_per_page # The old API called it "hits" instead of "count". hits = Paginator.count # The old API called it "pages" instead of "num_pages". pages = Paginator.num_pages def sitefe...
Kurpilyansky/street-agitation-telegram-bot
manage.py
Python
gpl-3.0
818
0.001222
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "street_agitation_bot.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ens...
s installed and " "available on your PYTHONPATH environment variable? Did you " "forget to
activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
ml6973/Course
tf-hands-on/slim/python/slim/nets/alexnet_test.py
Python
apache-2.0
5,839
0.008392
# Copyright 2016 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 applicable ...
et.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow.contrib.slim.nets import alexnet slim = tf.contrib.slim class AlexnetV2Test(tf.test.TestCase): def testBuild(self): batch_size = 5 height, width = 2...
session(): inputs = tf.random_uniform((batch_size, height, width, 3)) logits, _ = alexnet.alexnet_v2(inputs, num_classes) self.assertEquals(logits.op.name, 'alexnet_v2/fc8/squeezed') self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) def t...
tcstewar/finger_gnosis
pointer.py
Python
gpl-2.0
16,229
0.00875
import numpy as np import nengo import ctn_benchmark # define the inputs when doing number comparison task class NumberExperiment: def __init__(self, p): self.p = p self.pairs = [] self.order = [] rng = np.random.RandomState(seed=p.seed) for i in range(1, 10): fo...
e(self.exp.pointer_target) report_finger = nengo.Node(self.exp.report_finger) report_compare = nengo.Node(self.exp.report_compare) memory_clear = nengo.Node(self.exp.memory_clear) # create neural models for the
two input areas # (fingers and magnitude) area0 = nengo.Ensemble(p.N_input*p.pointer_count, p.pointer_count, radius=np.sqrt(p.pointer_count), label='area0') area1 = nengo.Ensemble(p.N_input, 1, label='area1') ...
ZeX2/TWTools
CustomDialogs.py
Python
gpl-3.0
3,155
0.005071
from PySide2 import QtGui, QtCore, QtWidgets from design import SidUi, DdUi from ServersData import ServersDownloadThread, servers import sys class SpeedInputDialog(QtWidgets.QDialog, SidUi): def __init__(self): QtWidgets.QDialog.__init__(self) self.setupUi() def get_data(self)...
rs_download_thread, QtCore.SIGNAL("update_button()"), self.update_button) self.connect(self.get_servers_download_thread, QtCore.SIGNAL("download_error(PyObject)"), self.download_error) self.get_servers_download_thread.start() def update_progress_text(self, text): self.progress_text.app...
ar(self, value): self.progress_bar.setValue(value) def update_button(self): self.horizontalLayout.removeWidget(self.cancelButton) self.cancelButton.deleteLater() self.cancelButton = None self.downloaded = True self.okButton = QtWidgets.QPushButton("Ok") ...
jsilhan/rpg
rpg/plugins/lang/c.py
Python
gpl-2.0
2,122
0
from rpg.plugin import Plugin from rpg.command import Command from rpg.utils import path_to_str from re import compile from subprocess import CalledProcessError import logging class CPlugin(Plugin): EXT_CPP = [r"cc", r"cxx", r"cpp", r"c\+\+", r"ii", r"ixx", r"ipp", r"i\+\+", r"hh", r"hxx", r"hpp",...
cc_makedep = Command("makedepend -w 1000 " + str(_f) + " -f- 2>/dev/null").execute() except CalledProcessError as e: logging.warn(str(e.cmd) + "\n" + str(e.output)) continue cc_included_files += [ s f...
and str(project_dir) not in s] spec.required_files.update(cc_included_files) spec.build_required_files.update(cc_included_files) MOCK_C_ERR = compile(r"fatal error\: ([^:]*\.[^:]*)\: " r"No such file or directory") def mock_recover(self, log, spec): ...
LRGH/amoco
amoco/arch/eBPF/formats.py
Python
gpl-2.0
1,781
0
# -*- coding: utf-8 -*- from .env import * from amoco.cas.expressions import regtype from amoco.arch.core import Formatter, Token def mnemo(i): mn = i.mnemonic.lower() return [(Token.Mnemonic, "{: <12}".format(mn))] def deref(opd): return "[%s+%d]" % (opd.a.base, opd.a.disp) def opers(i): s = [] ...
% (imm_ref)) return s def opers_adr2(i): s = opers(i) if i.address is None: s[-3] = (Token.Address, ".%+d" % i.opera
nds[-2]) s[-1] = (Token.Address, ".%+d" % i.operands[-1]) else: imm_ref1 = i.address + i.length * (i.operands[-2] + 1) imm_ref2 = i.address + i.length * (i.operands[-1] + 1) s[-3] = (Token.Address, "#%s" % (imm_ref1)) s[-1] = (Token.Address, "#%s" % (imm_ref2)) return s ...
ryokochang/Slab-GCS
bin/Release/Scripts/example6.py
Python
gpl-3.0
3,744
0.029129
# from http://diydrones.com/forum/topics/mission-planner-python-script?commentId=705844%3AComment%3A2035437&xg_source=msg_com_forum import socket import sys import math from math import sqrt import clr import time import re, string clr.AddReference("MissionPlanner.Utilities") import MissionPlanner #import * clr.AddRe...
n-privileged port RPORT = 4000 # Arbitrary non-privileged port REMOTE = '' # Datagram (udp) socket rsock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) print 'Sockets created' # Bind socket to local host and port try: rsock.bind((HOST,RPORT)) except socket.error, msg: #print 'Bind failed. Error ...
sys.stderr.write("[ERROR] %s\n" % msg[1]) rsock.close() sys.exit() print 'Receive Socket bind complete on ' + str(RPORT) print 'Starting Follow' Script.ChangeMode("Guided") # changes mode to "Guided" print 'Guided Mode' #keep talking with the Mission Planner server while 1: ...
itbabu/django-oscar
tests/functional/catalogue/review_tests.py
Python
bsd-3-clause
2,113
0
from oscar.test.testcases import WebTestCase from oscar.test.factories import create_product, UserFactory from oscar.core.compat import get_user_model from oscar.apps.catalogue.reviews.signals import review_added from oscar.test.contextmanagers import mock_signal_receiver class TestACustomer(WebTe
stCase): def setUp(self): self.product = create_product() def test_can_add_a_review_when_anonymous(self):
detail_page = self.app.get(self.product.get_absolute_url()) add_review_page = detail_page.click(linkid='write_review') form = add_review_page.forms['add_review_form'] form['title'] = 'This is great!' form['score'] = 5 form['body'] = 'Loving it, loving it, loving it' fo...
gustavovaliati/ci724-ppginfufpr-2016
exerc-3a/main.py
Python
gpl-3.0
930
0.022581
#!/usr/bin/python import cv2 import numpy as np import sys, getopt import matplotlib matplotlib.use('Agg') # Force matplotlib to not use any Xwindows backend. from matplotlib import pyplot as plt image_path = None def printHelp(): print 'main.py\n' \ ' -i <Image Path. Ex: /home/myImage.jpg > (Mandatory)\n' \...
("-i"): image_path = arg if image_path == None: p
rint "Input file missing" printHelp() sys.exit() img = cv2.imread(image_path) color = ('b','g','r') for i,col in enumerate(color): hist = cv2.calcHist([img],[i],None,[256],[0,256]) plt.plot(hist,color = col) plt.xlim([0,256]) plt.savefig("hist.png")
vuntz/glance
glance/cmd/cache_manage.py
Python
apache-2.0
16,590
0.000241
#!/usr/bin/env python # Copyright 2011 OpenStack Foundation # 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...
) pretty_table.add_column(19, label="Last Accessed (UTC)") pretty_table.add_column(19, label="Last Modified (UTC)") # 1 TB takes 13 characters to display: len(str(2**40)) ==
13 pretty_table.add_column(14, label="Size", just="r") pretty_table.add_column(10, label="Hits", just="r") print(pretty_table.make_header()) for image in images: last_modified = image['last_modified'] last_modified = timeutils.iso8601_from_timestamp(last_modified) last_access...
mete0r/gpl
mete0r_gpl/__init__.py
Python
agpl-3.0
810
0
# -*- coding: utf
-8 -*- # # mete0r.gpl : Manage GPL'ed source code files # Copyright (C) 2015 mete0r <mete0r@sarangbang.or.kr> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 ...
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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Pub...
freeitaly/Trading-System
vn.trader/ctaAlgo/strategyTickBreaker.py
Python
mit
8,133
0.00262
# encoding: UTF-8 import talib as ta import numpy as np from ctaBase import * from ctaTemplate import CtaTemplate import time ######################################################################## class TickBreaker(CtaTemplate): """跳空追击策略(MC版本转化)""" className = 'TickBreaker' author = u'融拓科技' # 策略...
会出现多个策略实例之间数据共享的情况,有可能导致潜在的策略逻辑错误风险, # 策略类中的这些可变对象属性可以选择不写,全都放在__init__下面,写主要是为了阅读 # 策略时方便(更多是
个编程习惯的选择) # 策略变量 self.tickHistory = [] # 缓存tick报价的数组 self.maxHistory = 7 # 最大缓存数量 self.forwardNo = EMPTY_INT # 正向tick数量 self.backwardNo = EMPTY_INT # 反向tick数量 self.reForwardNo = EMPTY_INT # 再次转向tick数量 self.oldPrice = 0 # 上一个ti...
nshafer/django-hashid-field
sandbox/sandbox/urls.py
Python
mit
1,076
0
"""sandbox URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topic
s/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL
to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a...
adfinis-sygroup/timed-backend
timed/subscription/serializers.py
Python
agpl-3.0
2,642
0.000379
from datetime import timedelta from django.db.models import Sum from django.utils.duration import duration_string from rest_framework_json_api.serializers import ( CharField, ModelSerializer, SerializerMethodField, ) from timed.projects.models import Project from timed.tracking.models import Report from ...
return duration_string(data["spent_time"] or timedelta()) included_serializers = { "billing_type": "timed.projects.serializers.BillingTypeSerializer", "cost_center": "timed.projects.serializers.CostCenterSerializer", "customer": "timed.projects.serializers.CustomerSerializer", "ord...
tlakshman26/cinder-https-changes
cinder/tests/unit/test_ibm_xiv_ds8k.py
Python
apache-2.0
30,480
0
# Copyright 2013 IBM Corp. # Copyright (c) 2013 OpenStack Foundation # 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...
raise self.exception.VolumeNotFound(volume_id=volume['id']) lun_id = volume['id'] self.volumes[volume['name']]['attached'] = connector return {'driver_volume_type': 'iscsi', 'data': {'target_discovered': True, 'target_discovered': True, ...
'target_lun': lun_id, 'volume_id': volume['id'], 'multipath': True, 'provider_location': "%s,1 %s %s" % ( self.xiv_ds8k_portal, self.xiv_ds8k_iqn, lun_id), }...
codervikash/algorithms
Python/Graphs/breath_first_traversal.py
Python
mit
2,188
0.002285
""" Pseudo code Breadth-First-Search(Graph, root): create empty set S create empty queue Q root.parent = NIL Q.enqueue(root) while Q is not empty: current = Q.dequeue() if current is the goal: return current for each node n that is adjacent to current: ...
t Graph def BFS(Graph, s):
graph = Graph.graph() if s not in graph: raise Exception("Edge %s not in graph" % s) q = deque([s]) visited = set([s]) while len(q) != 0: node = q.pop() for each in graph[node]: print visited if each not in visited: visited.add(each) ...
duke605/RunePy
commands/choices.py
Python
mit
957
0.003135
from util.arguments import Arguments from discord.ext import commands from shlex import split import random class Choices: def __init__(self, bot): self.bot = bot @commands.command(aliases=['choose'], description='Randomly picks a 1 of the given choices.') async def choices(self, *, msg): ...
_argument('choices', nargs='+', help='The choices to randomly pick from.') try: args = parser.parse_args(split(msg)) except SystemExit: await self.bot.say('```%s```' % parser.format_help()) return except Exception as e: await self.bot.say('```%s``...
args.choices[random.SystemRandom().randint(0, len(args.choices) - 1)] await self.bot.say('**%s** has randomly been selected.' % choice) def setup(bot): bot.add_cog(Choices(bot))
droberin/blackhouse
blackhouse/__init__.py
Python
mit
2,518
0.000397
import logging import socket from . import arcade logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) class Switch: remote_ip = None remote_port = 9999 state = None commands = {'info': '{"system":{"get_sysinfo":{}}}', 'on': u'{"system...
'{"time":{"get_time":{}}}', 'schedule': '{"schedule":{"get_rules":{}}}', 'countdown': '{"count_down":{"get_rules":{}}}', 'antitheft': '{"anti_theft":{"get_rules":{}}}', 'reboot': '{"system":{"reboot":{"delay":1}}}', 'reset': '{"system":{"re...
int(port) def activate(self): self.switch_requester(self.commands.get('on')) def deactivate(self): self.switch_requester(self.commands.get('off')) def info(self): self.switch_requester(self.commands.get('info')) def switch_requester(self, content=None): if content is ...
plinecom/pydpx_meta
pydpx_meta/low_header_big_endian.py
Python
mit
4,246
0
import ctypes class _DpxGenericHeaderBigEndian(ctypes.BigEndianStructure): _fields_ = [ ('Magic', ctypes.c_char * 4), ('ImageOffset', ctypes.c_uint32), ('Version', ctypes.c_char * 8), ('FileSize', ctypes.c_uint32), ('DittoKey', ctypes.c_uint32), ('GenericSize', ctyp...
32), ('Interlace', ctypes.c_byte), ('FieldNumber', ctypes.c_byte), ('VideoSignal', ctypes.c_byte), ('Padding', ctypes.c_byte), ('HorzSampleRate', ctypes.c_float), ('VertSampleRate', ctypes.c_float), ('FrameRate', ctypes.c_float),
('TimeOffset', ctypes.c_float), ('Gamma', ctypes.c_float), ('BlackLevel', ctypes.c_float), ('BlackGain', ctypes.c_float), ('Breakpoint', ctypes.c_float), ('WhiteLevel', ctypes.c_float), ('IntegrationTimes', ctypes.c_float), ('Reserved', ctypes.c_byte * 76) ] ...
tolomea/gatesym
gatesym/tests/blocks/test_latches.py
Python
mit
2,835
0
import random from gatesym import core, gates, test_utils from gatesym.blocks import latches def test_gated_d_latch(): network = core.Network() clock = gates.Switch(network) data = gates.Switch(network) latch = latches.gated_d_latch(data, clock) network.drain() assert not latch.read() da...
rite(True) network.drain() assert flop.read() clock.write(False) network.drain() assert not flop.read() def test_ms_d_flop_timing(): network = core.Network() clock = gates.Switch(network) data = gates.Switch(network) flop = latches.ms_d_flop
(data, clock) network.drain() assert not flop.read() # clock a 1 through data.write(True) network.drain() assert not flop.read() # data has no impact clock.write(True) network.drain() assert not flop.read() # clock high data in clock.write(False) data.write(False) netw...
google/vulncode-db
data/forms/__init__.py
Python
apache-2.0
4,727
0.001269
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
") def populate_obj(self, obj, name): if not hasattr(obj, name): setattr(obj, name, []) while len(
getattr(obj, name)) < len(self.entries): new_model = self.model() db.session.add(new_model) getattr(obj, name).append(new_model) while len(getattr(obj, name)) > len(self.entries): db.session.delete(getattr(obj, name).pop()) super().populate_obj(obj, name) ...
TNT-Samuel/Coding-Projects
File Sending/V1.0/output/receivefile.py
Python
gpl-3.0
5,213
0.005179
import socket,sys,os,hashlib,codecs,time # Import socket module #filecodec = 'cp037' filecodec = None buffersize = 1024 failed = False def filehash(filepath): openedFile = codecs.open(filepath,'rb',filecodec) # readFile = openedFile.read().encode() readFile = openedFile.read() openedFile.cl...
umode = False c.send("Start".encode()) exist = False gothash = False while not gothash:
cfhash = c.recv(buffersize).decode() c.send(cfhash.encode()) returndata = c.recv(buffersize).decode() if returndata == "y": gothash = True try: if cfhash == filehash(fname): exist = True except: pass if not exist: c.send("n".encode...
Arno-Nymous/pyload
module/plugins/hoster/YoutubeCom.py
Python
gpl-3.0
42,175
0.004268
# -*- coding: utf-8 -*- import operator import os import re import subprocess import time import urllib from xml.dom.minidom import parseString as parse_xml from module.network.CookieJar import CookieJar from module.network.HTTPRequest import HTTPRequest from ..internal.Hoster import Hoster from ..internal.misc impo...
[self.output_filename] p = subprocess.Popen( call, stdout=subprocess.PIPE, stderr=subprocess.PIPE) renice(p
.pid, self.priority) duration = self._find_duration(p) if duration: last_line = self._progress(p, duration) else: last_line = "" out, err = (_r.strip() if _r else "" for _r in p.communicate()) if err or p.returncode: self.error_message = last...
renxiaoyi/project_euler
problem_143.py
Python
unlicense
739
0.002706
import math # According to Law of cosines, p^2 + p*r + r^2 = c^2. # Let
c = r+k, => r = (p^2-k^2)/(2*k-p) and p > k > p/2 (k is even). # Suppose p <= q <= r. max_sum = 120000 d = {} # p => set(r) for p in range(1, max_sum/2+1): if p%10000 == 0: print p d[p] = set() mink = int(p/2)+1 maxk = int((math.sqrt(3)-1)*p) # so that r >= p for k in range(mink
, maxk+1): if (p**2-k**2)%(2*k-p) == 0: q = (p**2-k**2)/(2*k-p) d[p].add(q) ans = set() for p in d.keys(): for q in d[p]: if q in d and len(d[q]) > 0: for r in d[p].intersection(d[q]): if p + q + r > max_sum: continue ...
woddx/privacyidea
privacyidea/api/realm.py
Python
agpl-3.0
10,603
0.000283
# -*- coding: utf-8 -*- # # http://www.privacyidea.org # (c) cornelius kölbel, privacyidea.org # # 2014-12-08 Cornelius Kölbel, <cornelius@privacyidea.org> # Complete rewrite during flask migration # Try to provide REST API # # privacyIDEA is a fork of LinOTP. Some code is adapted from # the syste...
id": 1, "jsonrpc": "2.0", "result": { "status": true,
"value": { "realm1_with_resolver": { "default": true, "resolver": [ { "name": "reso1_with_realm", "type": "passwdresolver" } ] } } }, ...
babyliynfg/cross
tools/project-creator/Python2.6.6/Lib/distutils/tests/test_build_py.py
Python
mit
3,817
0.000786
"""Tests for distutils.command.build_py.""" import os import sys import StringIO import unittest from distutils.command.build_py import build_py from distutils.core import Distribution from distutils.errors import DistutilsFileError from distutils.tests import support class BuildPyTestCase(support.Te...
os.chdir(cwd) sys.stdout = old_stdout def test_dont_write_bytecode(self): # makes sure byte_compile is not used pkg_dir, dist = self.create_dist() cmd = build_py(dist) cmd.compile = 1 cmd.optimize = 1 old_dont_write_bytecode = sys.do...
sys.dont_write_bytecode = True try: cmd.byte_compile([]) finally: sys.dont_write_bytecode = old_dont_write_bytecode self.assertTrue('byte-compiling is disabled' in self.logs[0][1]) def test_suite(): return unittest.makeSuite(BuildPyTestCase) if __na...
stcioc/localdocindex
python/scrape_ps3.py
Python
mit
7,074
0.003675
# ------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Stefan # # Created: 11.07.2017 # Copyright: (c) Stefan 2017 # Licence: <your licence> # ------------------------------------------------------------------------...
= ScrapeProcessor.preparehtml(ocrfname, filetype) return sp.post_document(doctype, decisionid, annex, outstr, cssstr, link) if __name__ == '__main__': localsp = ScrapeProcessor("http://192.168.56.10", "stefan_cioc", "parola1234") loca
lsp.set_folders("X:/hot/S3I", "X:/hot/S3O") localsp.set_processmode(ScrapeProcessor.ProcessMode.FULL) extractdata(localsp)
garrettcap/Bulletproof-Backup
wx/tools/Editra/src/ed_statbar.py
Python
gpl-2.0
12,020
0.001165
############################################################################### # Name: ed_statbar.py # # Purpose: Custom statusbar with builtin progress indicator # # Author: Cody Precord <cprecord@editra.org> # ...
, 40, 40, 40, 155]) self._eolmenu.Append(ed_glob.ID_EOL_MAC, u"CR", _("Change line endings to %s") % u"CR", kind=wx.ITEM_CHECK) self._eolmenu.Append(ed_glob.ID_EOL_WIN, u"CRLF", _("Change line endings to %s") % u"CRLF...
self._eolmenu.Append(ed_glob.ID_EOL_UNIX, u"LF", _("Change line endings to %s") % u"LF", kind=wx.ITEM_CHECK) # Event Handlers self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self) self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)...
magfest/ubersystem
tests/uber/site_sections/test_summary.py
Python
agpl-3.0
3,732
0
from datetime import datetime, date import pytest from pytz import UTC from uber.config import c from uber.models import Attendee, Session from uber.site_sections import summary @pytest.fixture def birthdays(): dates = [ date(1964, 12, 30), date(1964, 12, 31), date(1964, 1, 1), d...
): monkeypatch.setattr(c, 'EPOCH', datetime(2017, 12, 31)) monkeypatch.setattr(c, 'ESCHATON', datetime(2018, 1, 1)) response = summary.Root().event_birthday_calendar() if isinstance(response, bytes): response = response.decode('utf-8') assert '"Born on December 31,...
(lines) == (2 + 1) # Extra line for the header
opennode/nodeconductor
waldur_core/structure/migrations/0040_make_is_active_nullable.py
Python
mit
634
0
#
-*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('structure', '0039_remove_permission_groups'), ] operations = [ migrations.AlterField( model_name='customerpermiss...
), migrations.AlterField( model_name='projectpermission', name='is_active', field=models.NullBooleanField(default=True, db_index=True), ), ]
alliedel/anomalyframework_python
anomalyframework/results.py
Python
mit
2,930
0.024232
import glob import matplotlib.pyplot as plt import numpy as np import os import pickle import scipy.signal import shutil import display_pyutils def apply_averaging_filter(x, filter_size=5): return np.convolve(x, np.ones(filter_size,) / float(filter_size), mode='valid') def apply_med
ian_filter(x, filter_size=5): return scipy.signal.medfilt(x, filter_size) def postprocess_signal(anomaly_ratings): signal = anomaly_ratings / (1 - anomaly_ratings) bottom_ninetyfive_percent = sorted(signal)[:int(np.floor(len(signal) * 0.95))] smoothed_signal = apply_averaging_filter(signal, 100) t...
shold def save_anomaly_plot(signal, pars): plt.figure(1); plt.clf() plot_anomaly_ratings(signal) title = 'video: {}\nlambda: {}\nmax_buffer_size:{}'.format( os.path.basename(pars.paths.files.infile_features), pars.algorithm.discriminability.lambd, pars.algorithm.discriminability.max_buffer...
afaheem88/tempest_neutron
tempest/services/image/v1/json/image_client.py
Python
apache-2.0
11,416
0
# Copyright 2013 IBM Corp. # 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 app...
headers = {} if name is not None: params['name'] = name if container_format is not None: params['container_format'] = container_format if properties is not None:
params['properties'] = properties headers.update(self._image_meta_to_headers(params)) if data is not None: return self._update_with_data(image_id, headers, data) url = 'v1/images/%s' % image_id resp, body = self.put(url, data, headers) self.expected_success(200...
akhambhati/Echobase
Echobase/Statistics/FDA/fda.py
Python
gpl-3.0
1,634
0
""" Functional Data Analysis Routines """ from __future__ import division import numpy as np def _curve_area(A, B): r1 = np.mean(A-B) r2 = np.mean(B-A) if r1 > r2: return r1 else: return r2 def curve_test(Y, cnd_1, cnd_2, n_pe
rm=1000): """ Assess whether two curves are statistically significant based on permutation test over conditions and replicates. Parameters ---------- Y: 2d array, shape: (time x var) Observations matrix for each variable over time. cnd_1: list, shape: (n
_reps_1) List of replicate indices in columns of Y for condition 1 cnd_2: list, shape: (n_reps_2) List of replicate indices in columns of Y for condition 2 n_perm: int Number of permutations to group Returns ------- p: int Two-tailed p-value """ n_reps_...
blakeboswell/valence
pyvalence/__init__.py
Python
bsd-3-clause
44
0
""" pyvalence """ __version__ = '0.0
.1.3'
theysconator/Scribbler
scribbler.py
Python
lgpl-3.0
2,173
0.02485
#!/usr/bin/python def conver
sionMap(): """ returns conversionmap """
return { 'a': [1, -2, -1], 'b': [1, 2, 1], 'c': [1, 2, -1], 'd': [1, -2, 1], 'e': [-1, 1, 1], 'f': [1, -2, 2], 'g': [-2, 1, 2], 'h': [-2, -1, 2], 'i': [-1, -1, 1], 'j': [2, 1, 2], 'k': [2, -1, 2], 'l': [-1, 1, 2], 'm': [-1, 2, 1], 'n': [-1, -2, 1], 'o': [-1,...
fopina/tgbotplug
tests/examples/test_guess.py
Python
mit
1,935
0.00155
from tgbot import plugintest from plugin_examples.guess import GuessPlugin class GuessPluginTest(plugintest.PluginTestCase): def setUp(self): self.plugin = GuessPlugin() self.bot = self.fake_bot('', plugins=[self.plugin]) def test_play(self): self.receive_message('/guess_start') ...
("I'm going to think of
a number between 0 and 9 and you have to guess it! What's your guess?") self.assertIsNotNone(self.plugin.read_data(1)) self.receive_message('/guess_stop') self.assertReplied('Ok :(') self.assertIsNone(self.plugin.read_data(1)) def test_stop_on_group(self): chat = { ...
beiko-lab/gengis
bin/Lib/site-packages/numpy/compat/__init__.py
Python
gpl-3.0
434
0
""" C
ompatibility module. This module contains duplicated code from Python itself or 3rd party extensions, which may be included for the following reasons: * compatibility * we may only need a small subset of the copied library/module """ import _inspect import py3k from _inspect import getargspec, formata...
.extend(_inspect.__all__) __all__.extend(py3k.__all__)
w3gh/ghost.py
plugins/join.py
Python
mit
716
0.023743
# -*- coding: utf-8 -*- import hook import bnetprotocol from misc import * from config import config #settings = config[__name__.split('.')[-1]] def message_received(bn, d): if d.event == bnetprotocol.EID_TALK: msg_list = str(d.message).split(' ', 1) try: command, payload = msg_list except Value
Error: command = msg_list[0] payload = '' if command == '.join' and len(payload) > 0: '''if str(d.message).split(' ')[0] == settings['trigger'] + 'join':''' bn.send_packet(bnetprotocol.SEND_SID_CHATCOMMAND('/join %s' % (payload))) def install(): hook.register('after-handle_sid_chateven
t', message_received) def uninstall(): hook.unregister('after-handle_sid_chatevent', message_received)
gi11es/thumbor
tests/filters/test_max_age.py
Python
mit
2,711
0.001107
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com thumbor@googlegroups.com from preggy import expect from tornado.testing import gen_test from...
import Importer class BaseMaxAgeFilterTestCase(TestCase): def get_fixture_path(self, name): return "./tests/fixtures/%s" % name def get_config(self): return Config.load(self.get_fixture_path("max_age_conf.py")) def get_importer(self): importer = Importer(self.config) impo...
async def test_max_age_filter_with_regular_image(self): response = await self.async_fetch("/unsafe/smart/image.jpg", method="GET") expect(response.code).to_equal(200) expect(response.headers["Cache-Control"]).to_equal("max-age=2,public") expect(response.headers).to_include("Expires") ...
jaor/python
bigml/predicates.py
Python
apache-2.0
2,025
0.000494
# -*- coding: utf-8 -*- # # Copyright 2014-2021 BigML # # 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 ...
list """ return " and ".join([predicate.to_rule(fields, label=label) for predicate in self.predicates if not isinstance(predicate, bool)]) def apply(self, input_data, fields): """ Applies the operators defined in each of the predica...
""" return all([predicate.apply(input_data, fields) for predicate in self.predicates if isinstance(predicate, Predicate)])
akatsoulas/mozillians
mozillians/users/views.py
Python
bsd-3-clause
9,979
0.001203
from functools import reduce from operator import or_ from django.db.models import Q from django.conf import settings from django.contrib.auth.models import User from django.http import JsonResponse from cities_light.models import City, Country, Region from dal import autocomplete from pytz import country_timezones ...
eturn all the users who have completed their profile registration. """ if not self.request.user.is_staff: return UserProfile.objects.none() qs = UserProfile.objects.complete() self.q_base_filter = (Q(ful
l_name__icontains=self.q) | Q(user__email__icontains=self.q) | Q(user__username__icontains=self.q)) if self.q: qs = qs.filter(self.q_base_filter) return qs class UsersAdminAutocomplete(autocomplete.Select2QuerySetView): """Ba...
ak0ska/rundeck-puppetdb-nodes
rundeck-puppetdb-nodes-plugin/contents/rundeck_puppetdb_nodes.py
Python
apache-2.0
5,881
0.006802
# Daniel Fernandez Rodriguez <danielfr@cern.ch> from argparse import ArgumentParser from collections import defaultdict from requests_kerberos import HTTPKerberosAuth import json import requests import subprocess import logging import sys class PuppetDBNodes(object): def __init__(self, args): for k, v ...
e output verbosity", action="store_true") parser.add_argument("-d", "--debug", help="increase output to debug messages", action="store_true")
parser.add_argument("--apiurl", help="PuppetDB API url (https://<SERVER>:<PORT>/<API VERSION>)", required=True) parser.add_argument("--hostgroup", help="Foreman hostgroup", required=True) parser.add_argument("--keytab", help="Keytab", required=True) parser.add_argument("--username", help="Username to...
ekaradon/demihi
core/admin.py
Python
mit
348
0.028736
from django.contrib import admin from core.models import Language # Register your models here. class LanguageA
dmin(admin.ModelAdmin): model = Language fieldsets = [ (''
, {'fields': ['name', 'locale']}) ] list_display = ['name', 'locale'] search_fields = ['name', 'locale'] ordering = ('name',) admin.site.register(Language, LanguageAdmin)
nkoech/csacompendium
csacompendium/research/api/experimentunit/experimentunitviews.py
Python
mit
2,054
0.003408
from csacompendium.research.models import ExperimentUnit from csacompendium.utils.pagination import APILimi
tOffsetPagination from csacompendium.utils.permissions import IsOwnerOrReadOnly from csacompendium.utils.viewsutils import DetailViewUpdateDelete, CreateAPIViewHook from rest_framework.filters import DjangoFilterBackend from rest_framework.generics import ListAPIView from rest_framework.permissions import IsAuthenticat...
it.experimentunitserializers import experiment_unit_serializers def experiment_unit_views(): """ Experiment unit views :return: All experiment unit views :rtype: Object """ experiment_unit_serializer = experiment_unit_serializers() class ExperimentUnitCreateAPIView(CreateAPIViewHook): ...
cypreess/PyrateDice
game_server/game_server/manage.py
Python
mit
254
0
#!/usr/bin/env python import os import sys if __name__ =
= "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "game_server.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv
)
Unofficial-Extend-Project-Mirror/openfoam-extend-Breeder-other-scripting-PyFoam
bin/pyFoamPVSnapshotMesa.py
Python
gpl-2.0
140
0.014286
#! /usr/bin/env python from PyFoam.Applications.ChangePython import changePython changePython("pv
python","PVSnapshot",options=["-
-mesa"])
punalpatel/st2
st2common/tests/unit/test_db_rule_enforcement.py
Python
apache-2.0
2,863
0
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th...
ieved = RuleEnforcement.get_by_id(saved.id) except StackStormDBObjectNotFoundError: retrieved = None self.asser
tIsNone(retrieved, 'managed to retrieve after delete.') @staticmethod def _create_save_rule_enforcement(): created = RuleEnforcementDB(trigger_instance_id=str(bson.ObjectId()), rule={'ref': 'foo_pack.foo_rule', 'uid': 'rule:f...
jsafrane/openlmi-storage
test/test_create_lv.py
Python
lgpl-2.1
12,008
0.002498
#!/usr/bin/python # -*- Coding:utf-8 -*- # # Copyright (C) 2012 Red Hat, Inc. All rights reserved. # # This library 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 Foundation; either # version 2.1 of the License, ...
library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# # Authors: Jan Safranek <jsafrane@redhat.com> from test_base import StorageTestBase, short_tests_only import unittest import pywbem MEGABYTE = 1024 * 1024 class TestCreateLV(StorageTestBase): """ Test CreateOrModifyLV method. """ VG_CLASS = "LMI_VGStoragePool" STYLE_GPT = 3 PARTITION_C...
MDAnalysis/RotamerConvolveMD
rotcon/library.py
Python
gpl-2.0
5,002
0.003798
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding: utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8 # # Convolve MTSS rotamers with MD trajectory. # Copyright (c) 2011-2017 Philip Fowler and AUTHORS # Published under the GNU Public Licence, version 2 (or higher) # # Includ...
rotamers = MDAnalysis.Universe(self.lib['topology'], self.lib['ensemble']) self.weights =
self.read_rotamer_weights(self.lib['populations']) if len(self.rotamers.trajectory) != len(self.weights): err_msg = "Discrepancy between number of rotamers ({0}) and weights ({1})".format( len(self.rotamers.trajectory), len(self.weights)) logger.critical(err_msg) ...
nilp0inter/cpe
cpe/cpeset2_2.py
Python
lgpl-3.0
3,512
0.000571
#! /usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of cpe package. This module of is an implementation of name matching algorithm in accordance with version 2.2 of CPE (Common Platform Enumeration) specification. Copyright (C) 2013 Alejandro Galindo García, Roberto Abdelkader Martínez Pérez This ...
PESet class CPESet2_2(CPESet): """ Represents a set of CPE Names. This class allows: - create set of CPE Names. - match a CPE element against a set of CPE Names. """ ############### # CONSTANTS # ############### #: Version of CPE set VERSION = "2.2" #############...
e: CPE Name to store in set :returns: None :exception: ValueError - invalid version of CPE Name TEST: >>> from .cpeset2_2 import CPESet2_2 >>> from .cpe2_2 import CPE2_2 >>> uri1 = 'cpe:/h:hp' >>> c1 = CPE2_2(uri1) >>> s = CPESet2_2() >>> s.appe...
seecr/meresco-components
meresco/components/http/pathrename.py
Python
gpl-2.0
1,768
0.003394
## begin license ## # # "Meresco Components" are components to build searchengines, repositories # and archives, based on "Meresco Core". # # Copyright (C) 2007-2009 SURF Foundation. http://www.surf.nl # Copyright (C) 2007 SURFnet. http://www.surfnet.nl # Copyright (C) 2007-2010
Seek You Too (CQ2) http://www.cq2.nl # Copyright (C) 2007-2009 Stichting Kennisnet Ict op school. http://www.kennisnetictopschool.nl # Copyright (C) 2012, 2017 Seecr (Seek You Too B.V.) http://seecr.nl # Copyright (C) 2017 SURF http://www.surf.nl # Copyright (C) 2017 Stichting Kennisnet http://www.kennisnet.nl # # This...
he 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. # # "Meresco Components" is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABIL...
littlecodersh/EasierLife
Plugins/ChatLikeCMD/ChatLikeCMD.py
Python
mit
7,974
0.007399
#coding=utf8 import thread, time, sys, os, platform try: import termios, tty termios.tcgetattr, termios.tcsetattr import threading OS = 'Linux' except (ImportError, AttributeError): try: import msvcrt OS = 'Windows' except ImportError: raise Exception('Mac i...
op() # linux special s
ys.stdout.write('\r') sys.stdout.flush() self.reprint_input() time.sleep(0.01) def fast_input_test(self): timer = threading.Timer(0.001, thread.interrupt_main) c = None try: timer.start() c = getch() except...
raycarnes/project
project_issue_baseuser/__openerp__.py
Python
agpl-3.0
1,661
0
# -*- coding: utf-8 -*- ############################################################################## # # Daniel Reis, 2013 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, eith...
ails. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Projects Issue extensions for user roles', 'version': '1.0',...
', 'description': """\ Also implements the Project user role extensions to the Project Issue documents. This module is automatically installed if the Issue Tracker is also installed. Please refer to the ``project_baseuser`` module for more details. """, 'author': "Daniel Reis,Odoo Community Association (OCA)",...
tommyip/zulip
zerver/management/commands/create_stream.py
Python
apache-2.0
919
0.002176
from argparse import ArgumentParser from typing import Any from zerver.lib.actions import create_stream_if_needed from zerver.lib.management import ZulipBaseCommand class Command(ZulipBaseCommand): help = """Create a stream, and subscribe all active users (excluding bots). This should be used for TESTING only, u...
# Should be ensured by parser stream_name = options['s
tream_name'] create_stream_if_needed(realm, stream_name)
anhstudios/swganh
data/scripts/templates/object/building/poi/shared_lok_nymshenchman_medium.py
Python
mit
454
0.046256
#### NOTICE: THIS FILE IS AUTOGENERATE
D #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from
swgpy.object import * def create(kernel): result = Building() result.template = "object/building/poi/shared_lok_nymshenchman_medium.iff" result.attribute_template_id = -1 result.stfName("poi_n","base_poi_building") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result