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 |
|---|---|---|---|---|---|---|---|---|
DayGitH/Python-Challenges | DailyProgrammer/DP20150713A.py | Python | mit | 1,597 | 0.005009 | """
[2015-07-13] Challenge #223 [Easy] Garland words
https://www.reddit.com/r/dailyprogrammer/comments/3d4fwj/20150713_challenge_223_easy_garland_words/
# Description
A [_garland word_](http://blog.vivekhaldar.com/post/89763722591/garland-words) is one that starts and ends with the
same N letters in the same order, f... | and` that, given a lowercase word, returns the degree of the word if it's
a garland word, and 0 otherwise.
# Examples
garland("programmer") -> 0
garland("ceramic") -> 1
ga | rland("onion") -> 2
garland("alfalfa") -> 4
# Optional challenges
1. Given a garland word, print out the chain using that word, as with "onion" above. You can make it as long or short
as you like, even infinite.
1. Find the largest degree of any garland word in the [enable1 English word
list](https://code.google.co... |
priyankarani/trytond-shipping-dhl-de | tests/test_shipment.py | Python | bsd-3-clause | 29,744 | 0.000067 | # -*- coding: utf-8 -*-
"""
test_shipment
Test dhl de Integration
"""
from decimal import Decimal
from time import time
from datetime import datetime
from dateutil.relativedelta import relativedelta
import sys
import os
import unittest
import trytond.tests.test_tryton
from trytond.tests.test_tryton import PO... | n['DHL_DE_USERNAME']
self.password = os.environ['DHL_DE_PASSWORD']
def _create_coa_minimal(self, company):
"""Create a minimal chart of accounts
"""
AccountTemplate = POOL.get('account.account.template')
Account = POOL.get('account.account')
| account_create_chart = POOL.get(
'account.create_chart', type="wizard"
)
account_template, = AccountTemplate.search(
[('parent', '=', None)]
)
session_id, _, _ = account_create_chart.create()
create_chart = account_create_chart(session_id)
cr... |
cloudera/hue | desktop/core/ext-py3/requests-2.27.1/requests/help.py | Python | apache-2.0 | 3,920 | 0 | """Module containing bug report helper(s)."""
from __future__ import print_function
import json
import platform
import sys
import ssl
import idna
import urllib3
from . import __version__ as requests_version
try:
import charset_normalizer
except ImportError:
charset_normalizer = None
chardet = None
try:
... | rset_normalizer:
charset_n | ormalizer_info = {'version': charset_normalizer.__version__}
if chardet:
chardet_info = {'version': chardet.__version__}
pyopenssl_info = {
'version': None,
'openssl_version': '',
}
if OpenSSL:
pyopenssl_info = {
'version': OpenSSL.__version__,
'o... |
RannyeriDev/Solfege | solfege/fpeditor.py | Python | gpl-3.0 | 34,999 | 0.002972 | # vim: set fileencoding=utf-8 :
# GNU Solfege - free ear training software
# Copyright (C) 2009, 2011 Tom Cato Amundsen
#
# 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... | uld have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
import logging
import os
import StringIO
import subprocess
from gi.repository import Gtk
from solfege.esel import SearchView
if __name__ == '__ma... | mport i18n
i18n.setup(".", "C")
import solfege.statistics
solfege.db = solfege.statistics.DB()
import solfege
from solfege import cfg
from solfege import filesystem
from solfege import gu
from solfege import frontpage as pd
from solfege import lessonfile
from solfege import osutils
class LessonFilePreview... |
lifeinoppo/littlefishlet-scode | RES/REF/python_sourcecode/ipython-master/docs/source/conf.py | Python | gpl-2.0 | 8,853 | 0.003615 | # -*- coding: utf-8 -*-
#
# IPython documentation build configuration file.
# NOTE: This file has been edited manually from the auto-generated one from
# sphinx. Do NOT delete and re-generate. If any changes from sphinx are
# needed, generate a scratch one and merge by hand any new fields needed.
#
# This file is e... | compile(open('../../IPython/core/release.py').read(), '../../IPython/core/release.py', 'exec'),iprelease)
# General configuration
# --------- | ------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'matplotlib.sphinxext.mathmpl',
'matplotlib.sphinxext.only_directives',
'matplotlib.sphinxext.plot_directive',
'sphinx.ext.autodo... |
JoelBender/bacpypes | samples/RecurringWriteProperty.py | Python | mit | 4,423 | 0.000452 | #!/usr/bin/env python
"""
This application demonstrates writing a series of values at a regular interval.
$ python RecurringWriteProperty.py 1.2.3.4 analogValue:1 \
presentValue 1.2 3.4 5.6
"""
import sys
from bacpypes.debugging import bacpypes_debugging, ModuleLogger
from bacpypes.consolelogging import... | airieDog(RecurringTask):
"""
An instance of this class pops up out of the ground every once in a
while and write out the next value.
"""
def __init__(self, interval):
| if _debug:
PrairieDog._debug("__init__ %r", interval)
RecurringTask.__init__(self, interval)
# install it
self.install_task()
def process_task(self):
if _debug:
PrairieDog._debug("process_task")
global args, this_application
if _debug... |
jeremiah-c-leary/vhdl-style-guide | vsg/rules/number_of_lines_between_tokens.py | Python | gpl-3.0 | 1,091 | 0.00275 |
from vsg.rule_group import length
from vsg import violation
class number_of_lines_between_tokens(length.Rule):
'''
Checks the number of lines between tokens do not exceed a specified number
Parameters
----------
name : string
The group the r | ule belongs to.
identifier : string
unique identifier. Usually in the form of 00N.
'''
def __init__(self, name, identifier, oLeftToken, oRightToken, iLines):
length.Rule.__init__(self, name=name, identifier=identifier)
self.length = iLines
self.oLeftToken = oLeftToken
... | self.oRightToken = oRightToken
def _get_tokens_of_interest(self, oFile):
return oFile.get_line_count_between_tokens(self.oLeftToken, self.oRightToken)
def _analyze(self, lToi):
for oToi in lToi:
if oToi.get_token_value() > self.length:
sSolution = 'Reduce process t... |
yenliangl/bitcoin | test/functional/feature_help.py | Python | mit | 2,481 | 0.000806 | #!/usr/bin/env python3
# Copyright (c) 2018-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Verify that starting bitcoin with -h works as expected."""
from test_framework.test_framework import B... | s = None
self.nodes[0].rpc_connected = False
self.nodes[0].rpc = None
return out, err
def run_test(self):
self.log.info("Start bitcoin with -h for help text" | )
self.nodes[0].start(extra_args=['-h'])
# Node should exit immediately and output help to stdout.
output, _ = self.get_node_output(ret_code_expected=0)
assert b'Options' in output
self.log.info(f"Help text received: {output[0:60]} (...)")
self.log.info("Start bitcoin wi... |
PavlovVitaly/python__homework_ITMO | task_04_01.py | Python | gpl-3.0 | 722 | 0 | n = int(input()) |
p = int(input())
with open('data.txt') as input_file:
content = str(input_file.read())
content = list(content.split(' '))
content = list(map(int, content))
content_of_out_file_1 = list(filter(lambda x: (x % n) == 0, content))
content_of_out_file_1 = list(map(str, content_of_out_file_1))
content_of_out_file_1 = ' ... | ile_2 = list(map(lambda x: x ** p, content))
content_of_out_file_2 = list(map(str, content_of_out_file_2))
content_of_out_file_2 = ' '.join(content_of_out_file_2)
with open('out-2.txt', 'w') as out_file_2:
out_file_2.write(content_of_out_file_2)
|
doctoryes/project_euler | prob9.py | Python | mit | 983 | 0.020346 |
#
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a^2 + b^2 = c^2
#
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
#
# There exists exactly one Pythagorean triplet for which | a + b + c = 1000.
# Find the product abc.
for x in range(1, 1000):
for y in range(2, 1000):
if x > y:
# Increase y until greater than x.
continue
for z in range(3, 1000):
if y > z:
# Increase z until greater than y.
continue
elif x + y + z != 1... | if lval == z_sq:
print "%5d^2 + %5d^2 = %5d^2" % (x, y, z)
if x + y + z == 1000:
print "ANSWER!!!! Product abc = ", x*y*z
exit()
elif lval < z_sq:
# No point in increasing z anymore.
break
|
commtrack/commtrack-core | apps/transformers/zip.py | Python | bsd-3-clause | 3,024 | 0.007606 | import os, tempfile, zipfile, tarfile, logging
from django.core.servers.basehttp import FileWrapper
from django.http import HttpResponse
def get_zipfile(file_list):
"""
Create a ZIP file on disk and transmit it in chunks of 8KB,
without loading the whole file into memory.
"""
... | os.path.basename(file))
else:
logging.warn("zipfile could not | find %s" % file)
archive.close()
wrapper = FileWrapper(temp)
response = HttpResponse(wrapper, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=commcarehq.zip'
response['Content-Length'] = temp.tell()
# this seek is required for 'response' to work
temp.... |
cklein/wtforms | tests/locale_babel.py | Python | bsd-3-clause | 2,927 | 0.000342 | from __future__ import unicode_literals
import babel
from decimal import Decimal, ROUND_UP
from unittest import TestCase
from wtforms import Form
from wtforms.fields import DecimalField
from wtforms.utils import unset_value
from tests.common import DummyPostData
class TestLocaleDecimal(TestCase):
class F(Form):
... | test_typeerror(self):
def build(**kw):
form = self.F()
DecimalField(
use_locale=True,
_form=form,
_name='a', |
_translations=form.meta.get_translations(form),
**kw
)
self.assertRaises(TypeError, build, places=2)
self.assertRaises(TypeError, build, rounding=ROUND_UP)
def test_formatting(self):
val = Decimal('123456.789')
neg = Decimal('-5.2')
... |
jolyonb/edx-platform | lms/djangoapps/verify_student/models.py | Python | agpl-3.0 | 40,982 | 0.001611 | # -*- coding: utf-8 -*-
"""
Models for Student Identity Verification
This is where we put any models relating to establishing the real-life identity
of a student over a period of time. Right now, the only models are the abstract
`PhotoVerification`, and its one concrete implementation
`SoftwareSecurePhotoVerification`... | che import cache
from django.core.files.base import ContentFile
from django.urls import reverse
from django.db import models
f | rom django.dispatch import receiver
from django.utils.functional import cached_property
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy
from model_utils import Choices
from model_utils.models import StatusModel, TimeStampedModel
from opaque_keys.edx.django.models import CourseKe... |
willyrv/microSDcheck | microSDcheck.py | Python | mit | 3,837 | 0.005734 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 26 23:44:04 2015
@author: willy
"""
import random
import hashlib
import argparse
import shutil, os, time
def write_a_file(destination, character, size=1):
"""
Create random file with specifyed size (in GBytes)
and copy them to "destina... | ination, 'w') as f:
f.write('{}\n'.format(line1))
number_of_characters = (1024**3)*size -10
characters_to_write = character * number_of_characters
f.write(characters_to_write)
print('File {} copied on disk. Computing md5 hash value ...'.format(destination))
md5_value = md5sum(des... | 6*128
with open(filename, 'rb') as f:
for block in iter(lambda: f.read(blocksize), b''):
hash.update(block)
return hash.hexdigest()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Check a microSD memory')
parser.add_argument("microSDpath")
parse... |
parksandwildlife/observations | manage.py | Python | apache-2.0 | 297 | 0.003367 | #!/usr/bin/env python
import os
import sys
import confy
confy.read_environment_file()
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "incredibus | .settings")
from django.core.management import execute_from_command_line
exec | ute_from_command_line(sys.argv)
|
UbiCastTeam/gst-gtklaunch-1.0 | main.py | Python | lgpl-2.1 | 941 | 0.003188 | #!/usr/ | bin/env python3
# -*- coding: utf-8 -*-
# * This Program is free software; you can redistribute it and/or
# * modify it under the terms of the GNU Lesser General Public
# * License as published by the Free Software Foundation; either
# * version 2.1 of the License, or (at your option) any later version.
# *
# * Libav ... | WARRANTY; without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# * Lesser General Public License for more details.
# *
# * You should have received a copy of the GNU Lesser General Public
# * License along with Libav; if not, write to the Free Software
# * Foundati... |
r-kitaev/lucid-python-werkzeug | tests/test_exceptions.py | Python | bsd-3-clause | 2,680 | 0 | # -*- coding: utf-8 -*-
"""
werkzeug.exceptiosn test
~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD license.
"""
from nose.tools import assert_raises
from werkzeug import exceptions
from werkzeug.exceptions import Aborter, abort
from wer... | 5)
assert_raises(exceptions.InternalServerError, abort, 500)
assert_raises(exceptions.NotImplemented, abort, 501)
assert_raises(exceptions.BadGateway, abort, 502)
assert_raises(exceptions.ServiceUnavailable, abort, 503)
| myabort = Aborter({1: exceptions.NotFound})
assert_raises(LookupError, myabort, 404)
assert_raises(exceptions.NotFound, myabort, 1)
myabort = Aborter(extra={1: exceptions.NotFound})
assert_raises(exceptions.NotFound, myabort, 404)
assert_raises(exceptions.NotFound, myabort, 1)
def test_exceptio... |
rschnapka/odoo | addons/account_asset/account_asset.py | Python | agpl-3.0 | 29,456 | 0.008759 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the G... | ', required=True,
help="Choose the method to use to compute the dates and number of depreciation lines.\n"\
" * Number of Depreciations: Fix the number of depreciation lines and the time between 2 depreciations.\n" \
... | e the depreciations won't go beyond."),
'method_end': fields.date('Ending date'),
'prorata':fields.boolean('Prorata Temporis', help='Indicates that the first depreciation entry for this asset have to be done from the purchase date instead of the first January'),
'open_asset': fields.boolean('Ski... |
e-koch/VLA_Lband | 16B/pipeline4.7.1_custom/EVLA_pipe_testgains.py | Python | mit | 8,921 | 0.01872 | ######################################################################
#
# Copyright (C) 2013
# Associated Universities, Inc. Washington DC, USA,
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Library General Public License as published by
# the Free Software Fo... | for gain calibrations"
print ""
refantspw=''
refantfield=calibrator_field_select_string
# NB: would use ms_active below instead of calibrators.ms when selection
# to exclude flagged data is implemented
findrefant=RefAntHeuristics(vis='calibrators.ms',field=refantfield,geometry=True,flag | ging=True)
RefAntOutput=findrefant.calculate()
refAnt=str(RefAntOutput[0])+','+str(RefAntOutput[1])+','+str(RefAntOutput[2])+','+str(RefAntOutput[3])
logprint ("The pipeline will use antenna(s) "+refAnt+" as the reference", logfileout='logs/testgains.log')
logprint ("Doing test gain calibration", logfileout='logs/tes... |
Genesis30/GeDRA | ds.py | Python | gpl-2.0 | 6,580 | 0.040578 | #!/usr/bin/python
#############################
# Function "calculateRisk"
# Given "data", calls the required function to compute the risk state of the
# system, and returns it.
#############################
def calculateRisk(data):
risk = computeRiskState(data[0], data[1], data[2], data[3], data[4], data[5], data[... | element]+1
# AK : alert amount of an alert thread (not only attack strength but also attack confidence).
# Calculate AK
a | lert_number = alert_num_dict[affected_element]
AK = alert_number * 3.0 + float(affected_element_relevance) + float(attack_rating)
# CK0 : updated alert confidence [0,1] ; probability that an abnormal activity is a true attack.
# Calculate CK0
if alert_number == 0:
CK0 = 0.3
elif alert_number >=2:
CK0 = 0.7
... |
ds-hwang/deeplearning_udacity | tensorflow_examples/word2vec.py | Python | mit | 14,317 | 0.004051 | # coding: utf-8
# The goal of this assignment is to train a Word2Vec skip-gram model over [Text8](http://mattmahoney.net/dc/textdata) data.
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
import collections
import math
import numpy as np
import os
import ra... | lename):
filename, _ = urlretr | ieve(url + filename, filename)
statinfo = os.stat(filename)
if statinfo.st_size == expected_bytes:
print('Found and verified %s' % filename)
else:
print(statinfo.st_size)
raise Exception(
'Failed to verify ' + filename + '. Can you get to it with... |
IDragonfire/modular-client | src/fa/replayserver.py | Python | gpl-3.0 | 8,647 | 0.011218 | #-------------------------------------------------------------------------------
# Copyright (c) 2012 Gael Honorez.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the GNU Public License v3.0
# which accompanies this distribution, and is available at
# htt... | rest = datas.indexOf("\x00") + 1
self.__logger.info("Stripping prefix '" + str(datas.left(rest)) + "' from replay.")
self.replayData.append(datas.right(datas.size() - rest))
else:
self.replayData.append(datas)
else:
... |
# Relay to faforever.com
if self.relaySocket.isOpen():
self.relaySocket.write(datas)
def done(self):
self.__logger.info("closing replay file")
self.parent.removeRecorder(self)
@QtCore.pyqtSlot()
def inputDisconnected(self):
... |
sparkslabs/kamaelia_ | Sketches/AB/Bookmarks-Dev/App/Bookmarks.py | Python | apache-2.0 | 7,466 | 0.023306 | #! /usr/bin/python
'''
Bookmarks.py - Main Executable
- Identifies current BBC programmes and generates keywords based on them.
- Collects Twitter streaming API data based on generated keywords.
- Analyses the collected data to identify frequent words, hence allowing the web interface to generate bookmarks.
'''
### D... | self", "inbox") : ("LINKRESOLVE", "inbox"),
("LINKRESOLVE", "outbox") : ("self", "outbox"),
("LINKRESOLVE", "urlrequests") : ("LINKREQUESTER", "inbox"),
| ("LINKREQUESTER", "outbox") : ("LINKRESOLVE", "responses")}).activate()
system = Graphline(CURRENTPROG = WhatsOn(proxy),
REQUESTER = Requester("all",dbuser,dbpass), # Can set this for specific channels to limit Twitter requests whilst doing dev
FIR... |
fifengine/fifengine | engine/python/fife/extensions/fife_compat.py | Python | lgpl-2.1 | 2,742 | 0.016411 | # -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2019 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
#... | umableKeys():
class CompatKeyFilter(fife.IKeyFilter):
def __init__(self, keys):
fife.IKeyFilter.__init__(self)
self.keys = keys
def isFiltered(self, event):
return event.getKey().getValue() in self.keys
def _setNonCon | sumableKeys(self,keys):
deprecated(2636, "Write an IKeyFilter instead of using EventManager.setNonConsumableKeys.\n" +
"You probably don't need it anyway")
self.compat_keyfilter = CompatKeyFilter(keys)
self.compat_keyfilter.__disown__()
self.setKeyFilter(self.compat_keyfilter)
def _getNonConsumableKeys(s... |
huggingface/transformers | src/transformers/models/realm/tokenization_realm_fast.py | Python | apache-2.0 | 14,317 | 0.003772 | # coding=utf-8
# Copyright 2022 The REALM authors and The HuggingFace Inc. team.
#
# 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 ... | pad_token="[PAD]",
cls_token="[CLS]",
mask_token="[MASK]",
tokenize_chinese_chars=True,
strip_accents=None,
**kwargs
):
super().__init__(
vocab_file,
tokenizer_file=tokenizer_file,
do_lower_case=do_lower_case,
unk_token=... | oken,
tokenize_chinese_chars=tokenize_chinese_chars,
strip_accents=strip_accents,
**kwargs,
)
normalizer_state = |
tvlive/tv-crawler | tvChannelLoader.py | Python | apache-2.0 | 5,139 | 0.003308 | #!/usr/bin/env python
import urllib2
from bs4 import BeautifulSoup
from parsingLibrary import loadHtmlTags, parseChannel, remove_duplicate_elements
from pymongo import MongoClient
from mongoConfiguration import load_mongo_configuration
mongo_address | , mongo_port = load_mongo_configuration()
client = MongoClient(mongo_address, mongo_port)
db = client['freeview']
channelCollection = db['tvChannel']
channelCollection.drop()
channelCategoryCollection = db['tvChannelCategory']
channelCategoryCollection.drop()
channelProviderCollection = db['tvChannelProvider']
channel... | ib2.urlopen(url_channels).read())
channels = a.findAll("div", {"class": "channel_name"})
list_channels = []
for channel in channels:
list_channels.append(channel.text)
return list_channels
def add_type_to_channel(channels_classified, channels_by_type, key, value):
for channel in channels_b... |
yalcinozhabes/pythonJDFTx | ElectronicMinimize.py | Python | gpl-2.0 | 9,552 | 0.00157 | #!/usr/bin/python3
# Author: Yalcin Ozhabes
# email: yalcinozhabes@gmail.com
import copy
import time
import numpy as np
from mpi4py import MPI
from ase.calculators.calculator import Calculator, all_changes
from ase import Atoms
from ase.units import Bohr, Hartree
from JDFTxCalcCPU import JDFTxCalcCPU
try:
from J... | species_order = []
for atom | in atoms:
try:
symbols[atom.symbol] += 1
except KeyError:
species_order.append(atom.symbol)
symbols[atom.symbol] = 0
i = 0
for sp in species_order:
number_of_sp = symbols[sp] + 1
symbols[sp] = i
... |
tardate/LittleCodingKata | python/random_mac_generation/random_mac.py | Python | mit | 558 | 0 | #! /usr/bin/env python
"""
Generate random MAC address
Inspired | by http://www.linux-kvm.com/sites/default/files/macgen.py
"""
from sys import argv
import random
DEFAULT_OUI = '00-16-3e' # Xens | ource, Inc.
def random_mac(oui=None):
"""returns a random MAC address, with optional +oui+ override"""
mac_parts = [oui or DEFAULT_OUI]
for limit in [0x7f, 0xff, 0xff]:
mac_parts.append("%02x" % random.randint(0x00, limit))
return '-'.join(mac_parts)
if __name__ == '__main__':
print rand... |
thunderhoser/GewitterGefahr | gewittergefahr/scripts/train_many_cnns_2d3d_myrorss.py | Python | mit | 14,391 | 0.000208 | """Trains many CNNs with 2-D and 3-D MYRORSS images.
The 2-D images contain azimuthal shear, and the 3-D images contain reflectivity.
"""
import os
import pickle
import argparse
import traceback
from multiprocessing import Pool, Manager
import numpy
from gewittergefahr.gg_utils import time_conversion
from gewittergef... | )
noise_standard_deviation = argument_dict[dl_helper.NOISE_STDEV_ARG_NAME]
num_noisings = argument_dict[dl_helper.NUM_NOISINGS_ARG_NAME]
flip_in_x = bool(argument_dict[dl_helper.FLIP_X_ARG_NAME])
flip_in_y = bool(argument_dict[dl_helper.FLIP_Y_ARG_NAME])
top_training_dir_name = argument_dict[dl... | dl_helper.FIRST_TRAINING_TIME_ARG_NAME]
last_training_time_string = argument_dict[
dl_helper.LAST_TRAINING_TIME_ARG_NAME]
num_examples_per_train_batch = argument_dict[
dl_helper.NUM_EX_PER_TRAIN_ARG_NAME]
top_validation_dir_name = argument_dict[
dl_helper.VALIDATION_DIR_ARG_NAME]
... |
Royal-Society-of-New-Zealand/NZ-ORCID-Hub | orcid_api_v3/models/education_summary_v30.py | Python | mit | 13,754 | 0.000073 | # coding: utf-8
"""
ORCID Member
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: Latest
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import si... | title': 'role-title',
'start_date': 'start-date',
'end_date': 'end-date',
'organization': 'organization',
'url': | 'url',
'external_ids': 'external-ids',
'display_index': 'display-index',
'visibility': 'visibility',
'path': 'path'
}
def __init__(self, created_date=None, last_modified_date=None, source=None, put_code=None, department_name=None, role_title=None, start_date=None, end_date=None,... |
ZombieNinjaPirate/kvmbuild | KVM/generate/ifobj.py | Python | lgpl-3.0 | 7,981 | 0.022052 | """These functions can be called to manage and generate various objects that are associated with
network interfaces. """
"""
Copyright (c) 2014, Are Hansen
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following co... | om.randint(0x00, 0xff),
random.randint(0x0 | 0, 0xff) ]
# Belkin International: 94:44:52
mac17 = [ 0x94, 0x44, 0x52,
random.randint(0x00, 0x7f),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff) ]
# Oracle Corporation: 00:14:4f
mac18 = [ 0x00, 0x14, 0x4f,
random.randint(0x00, 0x7f),
... |
Intel-bigdata/swift | test/unit/common/middleware/test_acl.py | Python | apache-2.0 | 6,539 | 0.000765 | # Copyright (c) 2010-2011 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/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | f.assert_(not acl.referrer_allowed('http://thief.example.com',
['*', '-thief.example.com']))
self.assert_(acl.referrer_allowed('http://www.example.com',
['.other.com', 'www.example.com']))
self.assert_(acl.referrer_allowed('http://www.example.com',
['-.example.com', '... | quest uri, a mode not
# currently supported.
self.assert_(not acl.referrer_allowed('www.example.com',
['.example.com']))
self.assert_(not acl.referrer_allowed('../index.html',
['.example.com']))
s... |
deepmind/detcon | utils/augmentations.py | Python | apache-2.0 | 10,529 | 0.006743 | # 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... | x.random.split(rng, 4)
out = images
if presets['random_flip']:
out = random_flip(out, flip_rng)
| if presets['color_transform']['apply_prob'] > 0:
out = color_transform(out, color_rng, **presets['color_transform'])
if presets['gaussian_blur']['apply_prob'] > 0:
out = gaussian_blur(out, blur_rng, **presets['gaussian_blur'])
if presets['solarize']['apply_prob'] > 0:
out = solarize(out, so... |
Havate/havate-openstack | proto-build/gui/horizon/Horizon_GUI/openstack_dashboard/dashboards/project/vpn/urls.py | Python | apache-2.0 | 1,933 | 0.000517 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013, 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
#
#... | nection$',
views.AddIPSecSiteConnectionView.as_view(),
name='addipsecsiteconnection'),
url(r'^addvpnservice$',
views.AddVPNServiceView.as_view(), name='addvpnservice'),
url(r'^ikepolicy/(?P<ikepolicy_id>[^/]+)/$',
views.IKEPolicyDetailsView.as_view(), name='ikep | olicydetails'),
url(r'^ipsecpolicy/(?P<ipsecpolicy_id>[^/]+)/$',
views.IPSecPolicyDetailsView.as_view(), name='ipsecpolicydetails'),
url(r'^vpnservice/(?P<vpnservice_id>[^/]+)/$',
views.VPNServiceDetailsView.as_view(), name='vpnservicedetails'),
url(r'^ipsecsiteconnection/(?P<ipsecsiteconnec... |
RealTimeWeb/wikisite | MoinMoin/web/utils.py | Python | apache-2.0 | 10,269 | 0.002532 | # -*- coding: iso-8859-1 -*-
"""
MoinMoin - Utility functions for the web-layer
@copyright: 2003-2008 MoinMoin:ThomasWaldmann,
2008-2008 MoinMoin:FlorianKrupicka
@license: GNU GPL, see COPYING for details.
"""
import time
from werkzeug import abort, redirect, cookie_date, Response
from Mo... | tely ban this user
@param action: specify the action explicitly (default: requ | est.action)
@param username: give username (for action == 'auth-name')
"""
limits = request.cfg.surge_action_limits
if not limits:
return False
remote_addr = request.remote_addr or ''
if remote_addr.startswith('127.'):
return False
validuser = request.user.valid
current... |
Erotemic/local | depricated/speech/Examples/_foxitreader.py | Python | gpl-3.0 | 2,827 | 0.005664 | #
# This file is a command-module for Dragonfly.
# (c) Copyright 2008 by Christo Butcher
# Licensed under the LGPL, see <http://www.gnu.org/licenses/>
#
"""
Command-module for **Foxit Reader** PDF viewer
============================================================================
This module offers commands to contr... | ---------------------------------------
# Set up this module's configuration.
config = Config("Foxit reader control")
config.lang = Section("Language section")
config.lang.new_win = Item("new (window | win)")
#config.generate_config_file()
config.load()... | mandRule(MappingRule):
mapping = {
"zoom in [<n>]": Key("c-equals:%(n)d"),
"zoom out [<n>]": Key("c-hyphen:%(n)d"),
"zoom [one] hundred": Key("c-1"),
"zoom [whole | full] page": Key("c-2"),
"zoom [page] widt... |
ecologylab/BigSemanticsService | Scripts/utils/crawl.py | Python | apache-2.0 | 3,552 | 0.020552 | #!python
import sys
import io
import re
import urllib
import urllib2
import urlparse
import lxml.etree
def get_outlinks(url):
'''
url: the url to the page to crawl
'''
result = []
if url is None:
return result
html = None
resp = None
try:
url = url.strip()
resp = url... | if url not in visited and crawl_test(url):
outlinks = get_outlinks(url)
visited.add(url)
urls.extend(outlinks)
if handle_test(url) and url not in handled:
handle_url | (url, p + 1, max_to_handle)
handled.append(url)
p += 1
i += 1
return handled
def call_semantics_service(url, i, max_to_handle):
service_pattern = "http://ecology-service.cse.tamu.edu/BigSemanticsService/metadata.xml?url={0}"
qurl = urllib.quote(url)
surl = service_pattern.format(qurl)
... |
lenoch/tagsetbench | makefile.py | Python | mit | 5,682 | 0 | from tagsetbench import ShellPath
class Makefile:
def __init__(self, path=None, recipes=None):
self.path = path # TODO: všechny budou ve working_dir, stačí 'name'
# TODO: self.declarations? (pomocí slovníku, aby na ně šlo odkazovat)
# split_corpora=' \\\n\t'.join(self.split_corpora)... | n, ShellPath):
return str(token)
elif hasattr( | token, 'path'):
return token.path.name # str(token.path)?
elif isinstance(token, str):
return token
else:
raise ValueError(token)
|
androportal/f-droid-fdroidserver | setup.py | Python | agpl-3.0 | 443 | 0.009029 | #!/usr/bin/python
from distutils.core import setup
setup(name='FDroidServer',
version='0.1',
descriptio | n='F-Droid Server Tools',
author='The F-Droid Project',
author_email='admin@f-droid.org',
url='http://f-droid.org',
packages=['fdroidserver'],
scripts=['fdroid'],
data_files = [('', ['COPYING', 'config.sample.py']),
('docs', ['docs/*.texi'])
| ]
)
|
mugurrus/eve | examples/security/sha1-hmac.py | Python | bsd-3-clause | 1,400 | 0 | # -*- coding: utf-8 -*-
"""
Auth-SHA1/HMAC
~~~~~~~~~~~~~~
Securing an Eve-powered API with Basic Authentication (RFC2617).
This script assumes that user accounts are stored in a MongoDB collection
('accounts'), and that passwords are stored as SHA1 | /HMAC hashes. All API
resources/methods will be secured unless they are made explicitly public
(by fiddling with some settings you can open one or mor | e resources and/or
methods to public access -see docs).
Since we are using werkzeug we don't need any extra import (werkzeug being
one of Flask/Eve prerequisites).
Checkout Eve at https://github.com/nicolaiarocci/eve
This snippet by Nicola Iarocci can be used freely for anything you like.
Con... |
antoinecarme/pyaf | tests/model_control/detailed/transf_Integration/model_control_one_enabled_Integration_MovingMedian_Seasonal_MonthOfYear_LSTM.py | Python | bsd-3-clause | 169 | 0.047337 | import | tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Integration'] , ['MovingMedian'] , ['Seasonal_MonthOfYear'] , ['LSTM'] ) | ; |
civet-software/CIVET-Django | djcivet_site/djciv_data/migrations/0001_initial.py | Python | mit | 1,089 | 0.002755 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Choice',
fields=[
('id', models.AutoField(verbo... | y=True)),
('choice_text', models.CharField(max_length=200)),
('votes', models.IntegerField(default=0)),
],
),
migrations.CreateModel(
name='Question',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, ... | =True, primary_key=True)),
('question_text', models.CharField(max_length=200)),
('pub_date', models.DateTimeField(verbose_name=b'date published')),
],
),
migrations.AddField(
model_name='choice',
name='question',
field=model... |
mooniak/hindkit | hindkit/AFDKOPython/generate_designspace.py | Python | mit | 1,566 | 0.019157 | #! AFDKOPython
import sys, pickle, os
from mutatorMath.ufo.document import DesignSpaceDocumentWriter
def main():
family = pickle.load(sys.stdin)
generate_designspace(family, 'font.designspace')
def generate_designspace(family, path):
def normalize_path(path):
return os.path.join(family['working_... | copyInfo = True if i == 0 else False,
# muteInfo = False,
# muteKerning = False,
# mutedGlyphNames = None,
)
for style in family['styles']:
doc.startInstance(
name = 'instance-' + style['name'],
location = {'weight': style['interpol... | fileName = normalize_path(style['path']),
postScriptFontName = style['output_full_name_postscript'],
# styleMapFamilyName = None,
# styleMapStyleName = None,
)
doc.writeInfo()
if family['has_kerning']:
doc.writeKerning()
doc.endInstanc... |
teonlamont/mne-python | mne/io/bti/tests/test_bti.py | Python | bsd-3-clause | 12,138 | 0 | from __future__ import print_function
# Authors: Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import os
import os.path as op
from functools import reduce, partial
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_all... | raw = _test_raw_reader(
read_raw_bti, pdf_fname=pdf_fnames[0],
config_fname=config_fnames[0], head_shape_fname=hs_fnames[0])
y, t = raw[:]
t0, t1 = 0.25 * t[-1], 0.75 * t[-1]
mask = (t0 <= t) * (t <= t1)
raw_ = raw.copy().crop(t | 0, t1)
y_, _ = raw_[:]
assert (y_.shape[1] == mask.sum())
assert (y_.shape[0] == y.shape[0])
def test_transforms():
"""Test transformations."""
bti_trans = (0.0, 0.02, 0.11)
bti_dev_t = Transform('ctf_meg', 'meg', _get_bti_dev_t(0.0, bti_trans))
for pdf, config, hs, in zip(pdf_fnames, conf... |
brain0/archweb | releng/migrations/0003_release_populate_last_modified.py | Python | gpl-2.0 | 494 | 0.006073 | # -*- coding: utf-8 -*-
f | rom __future__ import unicode_literals
from django.db import models, migrations
def forwards(apps, schema_editor):
Release = apps.get_model('releng', 'Release')
Release.objects.update(last_modified=models.F('created'))
def backwards(apps, schema_editor):
pass
class Migration(migrations.Migration):
... | ('releng', '0002_release_last_modified'),
]
operations = [
migrations.RunPython(forwards, backwards)
]
|
makinacorpus/ionyweb | ionyweb/page/admin.py | Python | bsd-3-clause | 158 | 0 | # -*- | coding: utf-8 -*-
from django.contrib import admin
from ionyweb.page.models import Page, Layout
| admin.site.register(Page)
admin.site.register(Layout)
|
Curahelper/Cura | plugins/UltimakerMachineActions/UM2UpgradeSelection.py | Python | agpl-3.0 | 3,052 | 0.006881 | # Copyright (c) 2017 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Settings.ContainerRegistry import Con | tainerRegistry
from UM.Settings.InstanceContainer import InstanceContainer
from cura.MachineAction import MachineAction
from PyQt5.QtCore import pyqtSlot, pyqtSignal, pyqtProperty
from UM.i18n import i18nCatalog
from UM.Application import Application
from UM.Util import parseBool
catalog = i | 18nCatalog("cura")
import UM.Settings.InstanceContainer
## The Ultimaker 2 can have a few revisions & upgrades.
class UM2UpgradeSelection(MachineAction):
def __init__(self):
super().__init__("UM2UpgradeSelection", catalog.i18nc("@action", "Select upgrades"))
self._qml_url = "UM2UpgradeSelectionM... |
alfredoavanzosc/odoo-addons | stock_orderpoint_filter/models/__init__.py | Python | agpl-3.0 | 164 | 0 | # -*- coding: u | tf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from . import procurement_orde | r
|
BurtBiel/azure-cli | src/command_modules/azure-cli-resource/azure/cli/command_modules/resource/tests/test_api_check.py | Python | mit | 2,871 | 0.007315 | #---------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#---------------------------------------------------------------------... | client = MagicMock()
provider = MagicMock()
provider.resource_types = [
self._get_mock_resource_type('skip', ['2000-01-01-preview', '2000-01-01']),
self._get_mock_resource_type('test', ['2016-01-01-preview', '2016-01-01']),
self._get_mock_resource_type('foo/bar', ... | rs.get.return_value = provider
return client
def _get_mock_resource_type(self, name, api_versions): #pylint: disable=no-self-use
rt = MagicMock()
rt.resource_type = name
rt.api_versions = api_versions
return rt
if __name__ == '__main__':
unittest.main()
|
PatteWi/pythonwetter | executables/mailsend.py | Python | mit | 513 | 0.003899 | fr | om boto.ses import SESConnection
import os
def sendmail(name, comment):
source = "patte.wilhelm@googlemail.com"
subject = "Kommentar eingegangen"
body = 'Es wurde ein neues Wetter bewertet. Von: ' + name + ': ' + comment
to_addresses = ["patte.wilhelm@googlemail.com"]
connection = SESConnection(aw... | connection.send_email(source, subject, body, to_addresses) |
lefteye/superroutingchioce | model.py | Python | gpl-2.0 | 2,888 | 0.026518 | # -*- coding:UTF-8 -*-
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding
from keras.layers import LSTM,Flatten
import numpy as np
import loadpkl
(X_train, y_train),(X_test, y_test) = loadpkl.load_data()
#print "hello"
X_train = np.array(X_train)... | _train = y_train
#Y_test = y_test
#model = Sequential()
#model.add(Dense(200, input_dim = 30))
#model.add(Activation('tanh'))
#model.add(Dense(100))
#model.add(Activation('sigmoid'))
#model.add(Dense( | 50))
#model.add(Activation('tanh'))
#model.add(Dense(30))
#model.add(Activation('tanh'))
#model.add(Dense(20))
#model.add(Activation('tanh'))
#model.add(Dense(6))
#model.add(Activation('softmax'))
#model.compile(optimizer = 'rmsprop', loss = 'mse', metrics=['accuracy'])
#model.fit(X_train, Y_train, batch_size=10, nb_ep... |
JohnGriffiths/nipype | nipype/algorithms/tests/test_auto_CalculateNormalizedMoments.py | Python | bsd-3-clause | 858 | 0.009324 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.algorithms.misc import CalculateNormalizedMoments
def test_CalculateNormalizedMoments_inputs():
input_map = dict(moment=dict(mandatory=True,
),
timeseries_file=dict(mandatory=True,
),
)
inp... | alizedMoments.output_spec()
for key, metadata in output_map.items():
for met | akey, value in metadata.items():
yield assert_equal, getattr(outputs.traits()[key], metakey), value
|
honzajavorek/tipi | tipi/langs/base.py | Python | mit | 2,966 | 0 | # -*- coding: utf-8 -*- #
from __future__ import unicode_literals
"""
Basic typography rules
Most regular expressions inspired by
`texytypo.py <https://gist.github.com/msgre/3805872>`, which is Python port
of typography rules from `Texy! <https://github.com/dg/texy/>`_ project.
"""
import re
__all__ = ('base_repl... | # nbsp space between number (optionally followed by dot) and word, symbol,
# punctation, currency symbol
(
re.compile(
(r'(?<= |\.|,|-|\+|\x16|\()([\x17-\x1F]*\d+\.?[\x17-\x1F]*)\s+'
r'(?=[\x17-\x1F]*[%{0}\u00B0-\u00be\u2020-\u214f])').format(ch),
re.M | re.U
... | -\x1F]*)\s+'
r'(?=[\x17-\x1F]*[%{0}\u00B0-\u00be\u2020-\u214f])').format(ch),
re.M | re.U
),
'\\1\u00a0'
),
)
|
dramatis/dramatis | setup.py | Python | mit | 633 | 0.006319 | from distutils.core import setup
s | etup( name='dramatis',
version='0.1.1',
author='Steven Parkes',
author_email='smparkes@smparkes.net',
url='http://dramatis.mischance.net',
description="an actor library for ruby and python",
package_dir = {'':'lib'},
packages=[
'dramatis',
'... | 'dramatis.runtime.actor',
'dramatis.runtime.continuation',
],
)
|
webus/libthumbor | tests/testproj/settings.py | Python | mit | 2,850 | 0.002105 | # Django settings for testproj project.
import logging
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASE_SUPPORTS_TRANSACTIONS = True
DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
... | .urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
)
logging.basicConfig(level=logging.DEBUG)
THUMBOR | _SECURITY_KEY = 'my-security-key'
THUMBOR_SERVER = 'http://localhost:8888/'
|
plotly/plotly.py | packages/python/plotly/plotly/validators/treemap/marker/colorbar/_showticklabels.py | Python | mit | 477 | 0 | import _plotly_utils.basevalidators
class ShowticklabelsValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self,
plotly_name="showticklabels",
parent_name="treemap.m | arker.colorbar",
**kwargs
):
super(ShowticklabelsValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
| edit_type=kwargs.pop("edit_type", "colorbars"),
**kwargs
)
|
Parbhat/cookiecutter-django-foundation | hooks/post_gen_project.py | Python | bsd-3-clause | 10,586 | 0.000756 | """
NOTE:
the below code is to be maintained Python 2.x-compatible
as the whole Cookiecutter Django project initialization
can potentially be run in Python 2.x environment
(at least so we presume in `pre_gen_project.py`).
TODO: ? restrict Cookiecutter Django project initialization to Python 3.x environ... | s not None:
random_string = formatted.format(random_string)
value = random_string
with open(file_path, "r+") as f:
file_contents = f.read().replace(flag, value)
f.seek(0)
f.write(file_contents)
f.truncate()
return value
def set_dj | ango_secret_key(file_path):
django_secret_key = set_flag(
file_path,
"!!!SET DJANGO_SECRET_KEY!!!",
length=64,
using_digits=True,
using_ascii_letters=True,
)
return django_secret_key
def set_django_admin_url(file_path):
django_admin_url = set_flag(
file_... |
spennihana/h2o-3 | h2o-py/h2o/backend/cluster.py | Python | apache-2.0 | 11,458 | 0.003927 | # -*- encoding: utf-8 -*-
"""Information about the backend H2O cluster."""
from __future__ import division, print_function, absolute_import, unicode_literals
import sys
import time
import h2o
from h2o.exceptions import H2OConnectionError, H2OServerError
from h2o.display import H2ODisplay
from h2o.utils.compatibility ... | isk
open_fds: Open File Descripters
swap_mem: Size of data on node's disk
tcps_active: Open TCP connections
num_cpus: Number of cpus
cpus_allowed: CPU's allowed
gflops: Linpack GFlops
fjthrds: F/J Thread count, by priority
mem_bw: Memory bandwith
f... | num_keys: Number of local keys
ip_port: IP address and port in the form a.b.c.d:e
last_ping: Time (in msec) of last ping
rpcs_active: Active Remote Procedure Calls
max_mem: Maximum memory size for node
healthy: (now-last_ping)<HeartbeatThread.TIMEOUT
sys_load: System... |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/tensorflow/contrib/opt/python/training/drop_stale_gradient_optimizer.py | Python | bsd-2-clause | 4,333 | 0.003462 | # 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... | gradients. Must be one of the Optimizer classes.
staleness: The maximum staleness allowed for the optimizer.
use_locking: If `True` use locks for clip update operations.
name: Optional name prefix for the operations created when applying
gradients. Defaults to "DropStaleGradient... | name)
self._opt = opt
self._staleness = staleness
def compute_gradients(self, loss, *args, **kwargs):
# Record current global step for worker.
with ops.colocate_with(loss):
self._local_step = training_util.get_global_step() + 0
with ops.control_dependencies([self._local_step]):
loss... |
kalikaneko/leap_mail | src/leap/mail/imap/fields.py | Python | gpl-3.0 | 4,610 | 0.000217 | # -*- coding: utf-8 -*-
# fields.py
# Copyright (C) 2013 LEAP
#
# 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... | cent and seen index`, but the semantic is not too
# correct since the recent flag is volatile.
TYPE_MBOX_RECT_SEEN_IDX = 'by-type-and-mbox-and-recent-and-seen'
KTYPE = TYPE_KEY
MBOX_VAL = TYP | E_MBOX_VAL
CHASH_VAL = CONTENT_HASH_KEY
PHASH_VAL = PAYLOAD_HASH_KEY
INDEXES = {
# generic
TYPE_IDX: [KTYPE],
TYPE_MBOX_IDX: [KTYPE, MBOX_VAL],
TYPE_MBOX_UID_IDX: [KTYPE, MBOX_VAL, UID_KEY],
# mailboxes
TYPE_SUBS_IDX: [KTYPE, 'bool(subscribed)'],
# ... |
timedata-org/expressy | expressy/ast_handlers/expressions.py | Python | mit | 1,421 | 0 | from . operators import operators
def Expr(node): # A container for an expression.
return (lambda x: x), [node.value]
def BinOp(node): # a + b
| return operators(node.op), [node.left, node.right]
def BoolOp(node): # a and b and c
return operators(node.op), node.values
def UnaryOp(node): # -a, not a, +a, ~a
return operators(node.op), [node.operand]
def Compare(node): # a < b < c > d
ops = [operators(o) for o in node.ops]
def compare(l... | not op(left, value):
return False
left = value
return True
return compare, [node.left] + node.comparators
def Call(node): # f(a, *b, **c)
if not node.keywords:
def call(caller, *args):
return caller(*args)
return call, [node.func] + node.args... |
tintoy/seqlog | setup.py | Python | mit | 1,510 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'python_dateutil>=2.5.3',
'requests>=2.10.0',
'PyYAML>=3.11',
]
... | etup(
name='seqlog',
version='0.3.21a1',
description="SeqLog enables logging from Python to Seq.",
lon | g_description=readme + '\n\n' + history,
author="Adam Friedman",
author_email='tintoy@tintoy.io',
url='https://github.com/tintoy/seqlog',
packages=[
'seqlog',
],
package_dir={'seqlog':
'seqlog'},
include_package_data=True,
install_requires=requirements,
licen... |
adngdb/socorro | socorro/processor/processor_2015.py | Python | mpl-2.0 | 11,998 | 0.000083 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""this file defines the method of converting a raw crash into a processed
crash. In this latest version, all transform... | ash, raw_dumps, processed_crash):
"""Take a raw_crash and its associated raw_dumps and return a
processed_crash.
"""
# processor_meta_data will be us | ed to ferry "inside information" to
# transformation rules. Sometimes rules need a bit more extra
# information about the transformation process itself.
processor_meta_data = DotDict()
processor_meta_data.processor_notes = [
self.config.processor_name,
self.__cla... |
HydrelioxGitHub/home-assistant | homeassistant/components/scene/__init__.py | Python | apache-2.0 | 3,292 | 0 | """Allow users to set and activate scenes."""
import asyncio
import importlib
import logging
import voluptuous as vol
from homeassistant.const import (
ATTR_ENTITY_ID, CONF_PLATFORM, SERVICE_TURN_ON)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassi... |
vol.Schema({
vol.Required(CONF_PLATFORM): str
}, extra=vol.ALLOW_EXTRA),
_platform_valida | tor
), extra=vol.ALLOW_EXTRA)
SCENE_SERVICE_SCHEMA = vol.Schema({
vol.Required(ATTR_ENTITY_ID): cv.entity_ids,
})
async def async_setup(hass, config):
"""Set up the scenes."""
logger = logging.getLogger(__name__)
component = hass.data[DOMAIN] = EntityComponent(logger, DOMAIN, hass)
await com... |
Jorge-Rodriguez/ansible | lib/ansible/modules/network/netvisor/pn_port_config.py | Python | gpl-3.0 | 12,238 | 0.000735 | #!/usr/bin/python
# Copyright: (c) 2018, Pluribus Networks
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['... | e, type='str'),
state=dict(required=True, type='str',
| choices=['update']),
pn_intf=dict(required=False, type='str'),
pn_crc_check_enable=dict(required=False, type='bool'),
pn_dscp_map=dict(required=False, type='str'),
pn_autoneg=dict(required=False, type='bool'),
pn_speed=dict(required=False, type='str',
... |
UMONS-GFA/ardas | docs/source/conf.py | Python | gpl-3.0 | 5,513 | 0.00127 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# ardas documentation build configuration file, created by |
# sphinx-quickstart on Mon Mar 20 08:42:32 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values | are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentatio... |
urashima9616/Leetcode_Python | Leet415_AddStrings.py | Python | gpl-3.0 | 975 | 0.024615 | def addStrings(s1, s2):
"""
type s1, s2: String
rtype string
"""
digit2num = {"0":0, "1":1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9}
pt1, pt2 = len(s1)-1, len(s2)-1
carry = 0
res = []
while pt1 >= 0 and pt2 >= 0:
digit_sum = digit2num[s1[pt1]] + digit2num[s2[pt... |
carry = digit_sum/10
res.append(str(digit_sum%10))
pt2 -=1
else:
while pt1 >=0 | :
digit_sum = digit2num[s1[pt1]] + carry
carry = digit_sum/10
res.append(str(digit_sum%10))
pt1 -=1
if carry != 0:
res.append(str(carry))
return "".join(reversed(res))
print addStrings("9919", "12312")
|
borisroman/vdsm | lib/yajsonrpc/stompreactor.py | Python | gpl-2.0 | 19,115 | 0 | # Copyright (C) 2014 Saggi Mizrahi, Red Hat Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY... | cy, 1000)
# The server can send a heart-beat every cy ms and doesn't want
# to receive any heart-beat from the client.
resp.headers[stomp.Headers.HEARTEBEAT] = "%d,0" % (cy,)
di | spatcher.setHeartBeat(cy)
self.queue_frame(resp)
self._reactor.wakeup()
def _cmd_subscribe(self, dispatcher, frame):
self.log.info("Subscribe command received")
destination = frame.headers.get("destination", None)
sub_id = frame.headers.get("id", None)
if not desti... |
alvason/probability-insighter | code/mutation_drift.py | Python | gpl-2.0 | 7,287 | 0.008508 | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
%matplotlib inline
# packages
import numpy as np
import itertools
import matplotlib.pyplot as plt
import matplotlib as mpl
import argparse
# global variables
pop_size = 50
seq_length = 100
alphabet = ['A', 'T', 'G', 'C']
mutation_rate = 0.0001 # per ge... | fspring_counts()
for (haplotype, count) in zip(pop.keys(), counts):
if (count > 0):
pop[haplotype] = count
else:
del pop[haplotype]
# simulate
def time_step():
mutation_step()
offspring_step()
def simulate():
clone_pop = dict(pop)
history.append(clone_po... |
# plot diversity
def get_distance(seq_a, seq_b):
diffs = 0
length = len(seq_a)
assert len(seq_a) == len(seq_b)
for chr_a, chr_b in zip(seq_a, seq_b):
if chr_a != chr_b:
diffs += 1
return diffs / float(length)
def get_diversity(population):
haplotypes = population.keys()
... |
zyantific/IDASkins | plugins/idaskins/objectinspector.py | Python | mit | 2,576 | 0 | from __future__ import absolute_import, division, print_function
import os
from idaskins import UI_DIR
from PyQt5 import uic
from PyQt5.Qt import qApp
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QCursor, QFont, QKeySequence
from PyQt5.QtWidgets import QShortcut, QWidget
Ui_ObjectInspector, ObjectInspectorBas... | InspectionResults.setText((
"Type: {}\n"
"Name: {}\n"
"Number of children: {}\n"
"QSS: {}"
).format(
widget.metaObject().className(),
widget.objectName() or '<none>',
len(widget.children()),
... | .connect(
self.on_selected_widget_destroyed
)
else:
self._ui.teInspectionResults.setText('<no object under cursor>')
def on_selected_widget_destroyed(self, obj):
self._selected_widget = None
|
rlr/fjord | fjord/feedback/views.py | Python | bsd-3-clause | 17,044 | 0 | import json
from functools import wraps
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.utils import translation
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.views.decorators.http import... | thankyou'):
suggestions = get_suggestions(feedback, request)
return render(request, 'feedbac | k/thanks.html', {
'product': product,
'feedback': feedback,
'suggestions': suggestions
})
def requires_firefox(func):
"""Redirects to "download firefox" page if not Firefox.
If it isn't a Firefox browser, then we don't want to deal with it.
This is a temporary solution. See b... |
antoinecarme/pyaf | tests/bench/web_traffic_jobs/en.wikipedia.org/test_web_traffic_en.wikipedia.org_pyaf_hierarchical_top_down.py | Python | bsd-3-clause | 447 | 0.002237 | impor | t pyaf.Bench.web_traffic.Forecaster as fo
PROJECTS = ['en.wikipedia.org']
data_dir = 'data/web-traffic-time-series-forecasting'
lForecaster = fo.cProjectForecaster()
lForecaster.mDataDirectory = data_dir
lForecaster.mBackendName = 'pyaf_hierarchical_top_down'
lForecaster.mKeysFileName = 'key_1.csv.zip'
last_date = ... | on)
|
mehdidc/py-earth | examples/return_sympy.py | Python | bsd-3-clause | 760 | 0.005263 | """
=====================================================
Exporting a fitted Earth models as a sympy expression
=============== | ======================================
A simple example returning a sympy expression describing the fit of a sine function computed by Earth.
"""
import numpy
fro | m pyearth import Earth
from pyearth import export
# Create some fake data
numpy.random.seed(2)
m = 1000
n = 10
X = 10 * numpy.random.uniform(size=(m, n)) - 40
y = 100 * \
(numpy.sin((X[:, 6])) - 4.0) + \
10 * numpy.random.normal(size=m)
# Fit an Earth model
model = Earth(max_degree=2, minspan_alpha=.5, verbos... |
sparkslabs/kamaelia_ | Sketches/MPS/BugReports/FixTests/Kamaelia/Kamaelia/Apps/IRCLogger/Support.py | Python | apache-2.0 | 7,622 | 0.010102 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License... | time()
def cannedResponse():
return [
"Hi, I'm a bot. I've been put here to answer faq's and log the channel.",
"I've not really been configured yet, so I won't do much here yet :-)",
]
def cannedYesTheyreAround():
return [
"Hi, I'm a bot. I've been put here to answer faq's and log the cha... | really been configured yet, so I won't do much here yet :-)",
]
def respondToQueries(self, msg):
"""Takes a BasicLogger as its first argument. If this function recognizes
"msg" as a command, then it sends back the appropriate response to IRC
"""
replyLines = ""
tag = 'PRIVMSG'
if m... |
mattclay/ansible | test/units/playbook/test_conditional.py | Python | gpl-3.0 | 9,810 | 0.002039 | from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat import unittest
from units.mock.loader import DictDataLoader
from mock import MagicMock
from ansible.template import Templar
from ansible import errors
from ansible.playbook import conditional
class TestCondit... | ret = self._eval_con(when, variables)
self.assertTrue(ret)
def test_dict_defined_multiple_values_is_defined(self):
variables = | {'dict_value': 1,
'some_defined_dict': {'key1': 'value1',
'key2': '{{ dict_value }}'}}
when = [u"some_defined_dict.key1 is defined",
u"some_defined_dict.key2 is not undefined"]
ret = self._eval_con(when, variables)
... |
wechatpy/wechatpy | tests/test_constants.py | Python | mit | 527 | 0 | # -*- coding: utf-8 -*-
import unittest
from wechatpy.constants import WeChatErrorCode
class WeChatErrorCodeTestCase(unittest.TestCase):
"""ensure python compatibility"""
def test_error_code(self):
self.assertEqual(-1000, WeChatErrorCode.SYSTEM_ERROR.value)
self.assertEqual(42001, WeChatErro... | self.assertEqual(WeC | hatErrorCode.SYSTEM_BUSY, WeChatErrorCode(-1))
|
execunix/vinos | xsrc/external/mit/MesaLib/dist/src/gallium/auxiliary/indices/u_indices_gen.py | Python | apache-2.0 | 10,366 | 0.014663 | #!/usr/bin/env python
copyright = '''
/*
* Copyright 2009 VMware, Inc.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without li... | opies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* VMWARE AND | /OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
'''
GENERATE, UBYTE, USHORT, UINT = 'generate', 'ubyte', 'ushort', 'uint'
FIRS... |
Daksh/tuxmath | activity.py | Python | gpl-2.0 | 6,945 | 0.010369 | # -*- coding: UTF-8 -*-
# Copyright 2007-2008 One Laptop Per Child
# Copyright 2007 Gerard J. Cerchio <www.circlesoft.com>
# Copyright 2008 Andrés Ambrois <andresambrois@gmail.com>
# Copyright 2010 Marcos Orfila <www.marcosorfila.com>
#
# This program is free software; you can redistribute it and/or modify
# it under t... | TH/bin/tuxmath --homedir $TUX_HOMEDIR --fullscreen"
if (self.checkbtn_sound.get_active()):
script_text += " --nosound "
"""
if (self.checkbtn_negatives.get_active()):
script_text += " --allownegatives | "
"""
f = open(script_path, 'w')
f.write(script_text)
f.close()
os.chmod(script_path, 0755)
def _button_play_clicked_cb(self, widget):
self.create_script(os.getenv("TUXMATH_SCRIPT"))
sys.exit(0)
def _button_exit_clicked_cb(self, widget):
sys.exit(0)... |
lscube/feng | contrib/feng_destroyer.py | Python | lgpl-2.1 | 2,136 | 0.044944 | #!/usr/bin/python
import os, sys, signal, random
from datetime import datetime, timedelta
VLC_POOL_SIZE = 10 #number of vlc client to keep open
SPAWN_TIMER = 5 #number of seconds between vlc spawn
MAX_VLC_LIFE_TIME = 60 #max life time in seconds of a vlc client
VLC_COMMAND = '/usr/bin/vlc'
class Vlc(object):
def __i... | to_remove.append(vlc)
if len(to_remove) and random.random() > 0.95:
for vlc in vlc_pool:
if not vlc in to_remove:
print 'Stopping multiple vlcs', vlc.spawn_time
vlc.stop()
to_remove.append(vlc)
for vlc in to_remove:
vlc_pool.remove(vlc)
if __ | name__ == '__main__':
if len(sys.argv) != 2:
print '%s requires an rtsp url to request' % sys.argv[0]
else:
main(sys.argv[1])
|
gleitz/automaticdj | pyechonest/playlist.py | Python | mit | 20,190 | 0.008618 | #!/usr/bin/env python
# encoding: utf-8
"""
Copyright (c) 2010 The Echo Nest. All rights reserved.
Created by Tyler Williams on 2010-04-25.
The Playlist module loosely covers http://developer.echonest.com/docs/v4/playlist.html
Refer to the official api documentation if you are unsure about something.
"""
import util... | iarity=None, \
artist_max_hotttnesss=None, artist_min_hotttnesss=None, song_max_hotttnesss=None, song_min_hotttnesss=None, \
min_longitude=None, max_longitude=None, min_latitude=No | ne, max_latitude=None, \
mode=None, key=None, buckets=[], sort=None, limit=False, dmca=False, audio=False, chain_xspf=False, \
seed_catalog=None, steer=None, source_catalog=None, steer_description=None):
"""
Args:
Kwargs:
type (str): a... |
Partysun/corona_lua.snippets | converter/convert.py | Python | mit | 1,847 | 0.016243 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, getopt
import codecs
import json
def load_data(filename):
"""Load Atom Snippets data from json
:filename: Atom Snippets json file
:returns: json atom data
"""
snippets_file = open(filename)
# data = snippets_file.read().decode('utf-8')
a... | (trigger)s "%(description)s"\n'
% {
'trigger': (atom_snippet['displayText']).replace(" ", ""),
'description': (atom_snippet['description']).replace("\" | ", "\'")
} +
'%s\n' % atom_snippet['snippet'] +
'endsnippet')
return snippet
def convert_snippets(atom_snippets_file, new_filename):
"""Convert atom snippets
from file to UltiSnippets
:atom_snippets_file: a file path of atom snippets
:new_filename: new Ulti... |
DanielNeugebauer/adhocracy | src/adhocracy/model/instance_filter.py | Python | agpl-3.0 | 531 | 0 | from beaker.util import T | hreadLocal
thread_instance = ThreadLocal()
def setup_thread(instance):
global thread_instance
thread_instance.put(instance)
def teardown_thread():
'''
A counterpart for setup_thread(), probly only |
useful in test_code
'''
global thread_instance
try:
thread_instance.remove()
except AttributeError:
# no value saved
pass
def has_instance():
return thread_instance.get() is not None
def get_instance():
return thread_instance.get()
|
openpolis/open_municipio | open_municipio/people/admin.py | Python | agpl-3.0 | 10,689 | 0.005613 | from django.contrib import | admin
from django.utils.translation import ugettext_lazy as _
from django.utils.datetime_safe import date
from django.db.models import Q
from open_municipio.people.models import *
from open_municipio.votations.admin import VotationsInline
from open_municipio.acts.model | s import Speech
from open_municipio.widgets import SortWidget
from sorl.thumbnail.admin import AdminImageMixin
from django.contrib.admin.util import unquote
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.utils.functional import update_wrapper
from django.utils.... |
rene-dev/stmbl | tools/create_config.py | Python | gpl-3.0 | 784 | 0.002551 | #!/usr/bin/env python
import re
import sys
import os
config = []
for infile in sys.argv[2:]:
with open(infile) as f:
config.append((os.path.splitext(os.path.basename(infile))[0], f.read()))
code = open(sys.argv[1], 'w')
code.write("//generated by " + sys.argv[0] + " DO NOT EDIT\n\n")
code.write("#includ... | .write(".name = \"" + file_name + "\",\n")
code.write(".config = \"\\\n")
for line in content.splitli | nes():
code.write(line + "\\n\\\n")
code.write("\"\n},\n\n")
code.write("};\n")
code.close()
|
danjac/ownblock | ownblock/ownblock/apps/buildings/permissions.py | Python | mit | 284 | 0 | from rest_framework.permissions import BasePermission
class IsBuilding(BasePermissio | n):
"""Checks if a current building (preselected by middleware)
has been assigned for this user"""
def has_permission(self, request, view):
return request.build | ing is not None
|
MAndelkovic/pybinding | tests/utils/fuzzy_equal.py | Python | bsd-2-clause | 5,216 | 0.001725 | import math
from functools import singledispatch, update_wrapper
import numpy as np
from scipy.sparse import csr_matrix, coo_matrix
import pybinding as pb
def _assertdispatch(func):
"""Adapted `@singledispatch` for custom assertions
* Works with methods instead of functions
* Keeps track of the data st... | d on 3 of 5 values: 60%
E actual: [1, 2, 9]
E expected: [5, 4, 6]
E indices: [1, 3, 4]
"""
actual, expected = map(np.asanyarray, (ac | tual, expected))
if actual.shape != expected.shape:
raise AssertionError("\n".join([
"\nFailed on shape mismatch",
"actual: {}".format(actual.shape),
"expected: {}".format(expected.shape),
]))
isclose = np.isclose(actual, expected, rtol, atol)
if np.all... |
joachimmetz/plaso | tests/preprocessors/test_lib.py | Python | apache-2.0 | 5,825 | 0.002232 | # -*- coding: utf-8 -*-
"""Preprocessing related functions and classes for testing."""
from artifacts import reader as artifacts_reader
from artifacts import registry as artifacts_registry
from dfvfs.helpers import fake_file_system_builder
from dfvfs.helpers import file_system_searcher
from dfvfs.lib import definition... | mediator = mediator.PreprocessMediator(
session, storage_writer, test_knowledge_base)
searcher = registry_searcher.WinRegistrySearcher(win_registry)
plugin.Collect(test_mediator, artifact_definition, searcher)
return test_mediator
def _RunPreprocessorPluginOnWindowsRegistryValueSoftware(
... | writer.
plugin (ArtifactPreprocessorPlugin): preprocessor plugin.
Return:
PreprocessMediator: preprocess mediator.
"""
file_system_builder = fake_file_system_builder.FakeFileSystemBuilder()
test_file_path = self._GetTestFilePath(['SOFTWARE'])
file_system_builder.AddFileReadData(
... |
adamfeuer/ArtOfGratitude_app | gratitude/migrations/0005_auto__add_action.py | Python | mit | 7,091 | 0.00832 | # -*- 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 'Action'
db.create_table('gratitude_action', (
('id', self.gf('django.db.models.f... | 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups' | : ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'... |
openearth/delft3d-gt-server | delft3dworker/management/commands/containersync_sceneupdate.py | Python | gpl-3.0 | 4,813 | 0.000208 | import logging
from time import sleep
from celery.result import AsyncResult
from django.core.management import BaseCommand
from delft3dcontainermanager.tasks import do_docker_remove, get_docker_ps
from delft3dworker.models import Container, Scene
"""
Synchronization command that's called periodically.
- Run docker p... | set = set(Container.objects.exclude(task_uuid__exact=None))
for container in celery_set:
container.update_task_result()
def _get_latest_docker_status(self):
"""
Synchronise local Django Container models with remote Docker containers
"""
ps = get_docker_ps.apply... | ng too long
checked = 0
while not ps.successful():
sleep(1)
# if things take too long, revoke the task and return
checked += 1
if checked >= 30:
ps.revoke()
return False
# task is succesful, so we're getting the re... |
lampwins/netbox | netbox/virtualization/api/views.py | Python | apache-2.0 | 3,151 | 0.001587 | from django.db.models import Count
from dcim.models import Device, Interface
from extras.api.views import CustomFieldModelViewSet
from utilities.api import FieldChoicesViewSet, ModelViewSet
from utilities.utils import get_subquery
from virtualization import filters
from virtualization.models import Cluster, ClusterGro... | machines
#
class VirtualMachineViewSet(CustomFieldModelViewSet):
queryset = VirtualMachine.objects.select_related(
'cluster__site', 'role', 'tenant', 'platform', 'primary_ip4', 'primary_ip6'
).prefetch_related('tags')
filterset_class = filters.VirtualMachineFilter
def get_serializer_class(sel... | stedVirtualMachineSerializer
If the `exclude` query param includes `config_context` as a value, return the VirtualMachineSerializer
Else, return the VirtualMachineWithConfigContextSerializer
"""
request = self.get_serializer_context()['request']
if request.query_params.get('br... |
tshadley/examples | word_language_model_bptt_hsm/generate.py | Python | bsd-3-clause | 2,597 | 0.000385 | ###############################################################################
# Language Modeling on Penn Tree Bank
#
# This file generates new sentences sampled from the language model
#
###############################################################################
import argparse
import torch
from torch.autograd... | ype=str, default='./model.pt',
help='model checkpoint to use')
parser.add_argument('--outf', type=str, default='generated.txt',
help='output file for generated text')
parser.add_argument('--words', type=int, default='1000',
help='number of wo | rds to generate')
parser.add_argument('--seed', type=int, default=1111,
help='random seed')
parser.add_argument('--cuda', action='store_true',
help='use CUDA')
parser.add_argument('--temperature', type=float, default=1.0,
help='temperature - higher will increa... |
timothyb0912/pylogit | src/pylogit/conditional_logit.py | Python | bsd-3-clause | 17,093 | 0 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 25 07:19:49 2016
@name: MultiNomial Logit
@author: Timothy Brathwaite
@summary: Contains functions necessary for estimating multinomial logit
models (with the help of the "base_multinomial_cm.py" file).
Differs from version one since it w... | general_gradient = cc. | calc_gradient
general_calc_probabilities = cc.calc_probabilities
general_hessian = cc.calc_hessian
def split_param_vec(beta,
rows_to_alts=None,
design=None,
return_all_types=False,
*args, **kwargs):
"""
Parameters
----------
... |
the-zebulan/CodeWars | tests/kyu_8_tests/test_a_needle_in_the_haystack.py | Python | mit | 897 | 0 | import unittest
from katas.kyu_8.a_needle_in_the_haystack import find_needle
class FindNeedleTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(find_needle([
| '3', '123124234', None, 'needle', 'world', 'hay', 2, '3',
True, False
]), 'found the needle at position 3')
def test_equals_2(self):
self.assertEqual(find_needle([
'283497238987234', 'a dog', 'a cat', 'some random junk',
'a piece of hay', 'needle', 'so... | 1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 5, 4, 3, 4, 5, 6, 67, 5, 5, 3,
3, 4, 2, 34, 234, 23, 4, 234, 324, 324, 'needle', 1, 2, 3, 4,
5, 5, 6, 5, 4, 32, 3, 45, 54
]), 'found the needle at position 30')
|
plaid/plaid-python | plaid/model/link_token_get_metadata_response.py | Python | mit | 8,788 | 0.000455 | """
The Plaid API
The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from plaid.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal... | ata
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when... | eserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through s... |
idaholab/civet | ci/ajax/tests/test_views.py | Python | apache-2.0 | 14,812 | 0.000743 | # -*- coding: utf-8 -*-
# Copyright 2016 Battelle Energy Alliance, 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 ... | self.assertEqual(response.status_code, 200)
json_data = response.json()
self.assertIn(result.output, json_data["contents"])
result.job.recipe.private = True
result.job.recipe.save()
# recipe is private and not signed in, shouldn't see it
response = self.client.g... | te, not a collaborator
response = self.client.get(url, data)
self.assertEqual(response.status_code, 403)
mock_is_collaborator.return_value = True
# recipe is private, but a collaborator
response = self.client.get(url, data)
self.assertEqual(response.status_code, 200)
... |
heldergg/labs | labs_django/manage.py | Python | gpl-3.0 | 254 | 0 | # | !/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "labs_django.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) | |
ddico/odoo | addons/event_sale/models/sale_order.py | Python | agpl-3.0 | 7,205 | 0.003747 | # -*- coding: utf-8 -*-
from odoo import api, fields, models, _
class SaleOrder(models.Model):
_inherit = "sale.order"
attendee_count = fields.Integer('Attendee Count', compute='_compute_attendee_count')
def write(self, vals):
""" Synchronize partner from SO to registrations. This is done notab... | None
@api.onchange('product_uom', 'product_uom_qty')
def product_uom | _change(self):
if not self.event_ticket_id:
super(SaleOrderLine, self).product_uom_change()
@api.onchange('event_ticket_id')
def _onchange_event_ticket_id(self):
# we call this to force update the default name
self.product_id_change()
def get_sale_order_line_multiline_d... |
FlorianNaumann/BA_ePuck_Graph_Formations | communication.py | Python | gpl-2.0 | 680 | 0.022059 | """
Graph ePuck framework:
communication.py
You can put Bluetooth or WLAN communication in here
that sets | up a connection and sends/receives mission goals
"""
# standard imports
import numpy as np
import platform
# project related imports
if platform.machine() == 'armv7l':
from ePuck import *
else:
fr | om fakebot import *
from constants import *
def get_new_msg():
return None
def get_desired_leader():
"""
decides the leader of the formation
idea: can be divided into "server setting" and "election by the swarm",
perhaps switching between these modes or depending on connection to server -> increasing stabili... |
JarbasAI/jarbas-core | mycroft/skills/intent_service.py | Python | gpl-3.0 | 14,724 | 0.001426 | # Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core 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 versio... | l_response", {
"skill_id": id, "intent_name": intent}))
return id
self.emitter.emit(Message("intent_to_skill_response", {
"skill_id": 0, "intent_name": intent}))
re | turn 0
def handle_conversation_response(self, message):
# id = message.data["skill_id"]
# no need to crosscheck id because waiting before new request is made
# no other skill will make this request is safe assumption
result = message.data["result"]
self.result = result
... |
openai/universe | universe/vncdriver/libvnc_session.py | Python | mit | 4,042 | 0.001484 | import logging
import os
from twisted.internet import defer, endpoints
from universe import error, utils
from universe.twisty import reactor
from universe.vncdriver import screen, vnc_client
PYGAME_INSTALLED = None
def load_pygame():
global PYGAME_INSTALLED, pygame
if PYGAME_INSTALLED is not None:
re... | rformance.txt
is decent.
"""
load_pygame()
import libvncdriver
if encoding is None:
encoding = os.environ.get('LIBVNC_ENCODING', 'tight')
if compress_level is None:
compress_level = int(os.environ.get('LIBVNC_COMPRESS_LEVEL', '0'))
if fin... | _quality_level is None:
fine_quality_level = int(os.environ.get('LIBVNC_FINE_QUALITY_LEVEL', '100'))
if subsample_level is None:
subsample_level = int(os.environ.get('LIBVNC_SUBSAMPLE_LEVEL', '0'))
if not hasattr(libvncdriver, 'VNCSession'):
raise error.Error('''
*=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.