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 |
|---|---|---|---|---|---|---|---|---|
alope107/nbgrader | nbgrader/preprocessors/computechecksums.py | Python | bsd-3-clause | 771 | 0.002594 | from nbgrader import utils
from nbgrader.preprocessors import NbGraderPreprocessor
class ComputeChecksums(NbGraderPreprocessor):
"""A preprocessor to compute checksums of grade cells."""
def preprocess_cell(self, cell, resources, cell_in | dex):
# compute checksums of grade cell and solution cells
if utils.is_grade(cell) or utils.is_solution(cell) or utils.is_locked(cell):
checksum = | utils.compute_checksum(cell)
cell.metadata.nbgrader['checksum'] = checksum
if utils.is_grade(cell) or utils.is_solution(cell):
self.log.debug(
"Checksum for '%s' is %s",
cell.metadata.nbgrader['grade_id'],
checksum)
... |
capoe/espressopp.soap | src/analysis/Test.py | Python | gpl-3.0 | 1,624 | 0.012315 | # Copyright (C) 2012,2013
# Max Planck Institute for Polymer Research
# Copyright (C) 2008,2009,2010,2011
# Max-Planck-Institute for Polymer Research & Fraunhofer SCAI
#
# This file is part of ESPResSo++.
#
# ESPResSo++ is free software: you can redistribute it and/or modify
# it under the terms of t... | mport *
from _espressopp import analysis_Test
class TestLocal(AnalysisBaseLocal, analysis_Test):
def __init__(self, system):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
cxxinit(self, analysis_Test, system)
if pmi.isController :
class T... | :
__metaclass__ = pmi.Proxy
pmiproxydefs = dict(
cls = 'espressopp.analysis.TestLocal'
)
|
nextgis-extra/tests | lib_gdal/ogr/ogr_sxf.py | Python | gpl-2.0 | 2,553 | 0.005875 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# $Id: ogr_sxf.py 26513 2013-10-02 11:59:50Z bishop $
#
# Project: GDAL/OGR Test Suite
# Purpose: Test OGR SXF driver functionality.
# Author: Dmitry Baryshnikov <polimax@mail.ru>
#
########... | () + ' data/100_test.sxf')
if ret.find('INFO') == -1 or ret.find('ERROR') != -1:
print(ret)
return 'fail'
return 'success'
###############################################################################
#
def ogr_sxf_cleanup():
if gdaltest.sxf_ds is None:
return 'skip'
gd | altest.sxf_ds = None
return 'success'
gdaltest_list = [
ogr_sxf_1,
ogr_sxf_2,
ogr_sxf_cleanup ]
if __name__ == '__main__':
gdaltest.setup_run( 'ogr_sxf' )
gdaltest.run_tests( gdaltest_list )
gdaltest.summarize()
|
ct-23/home-assistant | tests/components/cover/test_template.py | Python | apache-2.0 | 26,113 | 0 | """The tests the cover command line platform."""
import logging
import unittest
from homeassistant.core import callback
from homeassistant import setup
import homeassistant.components.cover as cover
from homeassistant.const import STATE_OPEN, STATE_CLOSED
from tests.common import (
get_test_home_assistant, asser... | block_till_done()
state = self.hass.states.get('cover.test_template_cover')
assert state.state == STATE_OPEN
state = self.hass.states.set('cover.test_state', STATE_CLOSED)
self.hass.block_till_done()
state = self.hass.states.get('cover.test_template_cover')
assert stat... | ):
"""Test the value_template attribute."""
with assert_setup_component(1, 'cover'):
assert setup.setup_component(self.hass, 'cover', {
'cover': {
'platform': 'template',
'covers': {
'test_template_cover': {
... |
Small-Star/PDV3 | app/views.py | Python | gpl-3.0 | 5,584 | 0.008059 | from flask import render_template
from app import app, db
from app.models import Mood, QS_Params, Lifts
import pandas as pd
import graph_mood, graph_diet, graph_body, graph_weightlifting, graph_meditation, analysis
@app.route("/")
@app.route("/index")
def index():
title = "Index"
return render_template("index... | dur, div_avg_slp_q=div_avg_slp_q, div_days_b | c=div_days_bc, div_avg_wt=div_avg_wt, div_avg_bf=div_avg_bf, plot_blood_div=plot_blood_div, plot_rhr_div=plot_rhr_div, plot_osq_div=plot_osq_div, plot_body_comp_div=plot_body_comp_div, plot_sleep_div=plot_sleep_div, ma_slider_div=ma_slider_div, title="BODY")
@app.route("/diet")
def diet():
q = QS_Params.query.filt... |
veveykocute/Spl | splc.py | Python | unlicense | 19,239 | 0.007745 | import sys
import math
"""A Shakespeare Compiler written in Python, splc.py
This is a compiler that implements the majority of the Shakespeare programming language
invented by Kalle Hasselstrom and Jon Aslund, I take no credit for inventing the language.
This software is free to edit or use, and though I doubt anyone ... | man_string.upper()
strindex = 0
roman_sum = 0
while strindex < len(roman_string) - 1:
| if(roman_values[roman_string[strindex]] < roman_values[roman_string[strindex+1]]):
roman_sum -= roman_values[roman_string[strindex]]
else:
roman_sum += roman_values[roman_string[strindex]]
strindex += 1
return roman_sum + roman_values[roman_string[strindex]]
def isNumber... |
opencord/xos | lib/xos-api/xosapi/chameleon_client/protos/schema_pb2_grpc.py | Python | apache-2.0 | 2,079 | 0.00481 | #!/usr/bin/env python
# Copyright 2017 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | RANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
from __fu | ture__ import absolute_import
import grpc
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
from . import schema_pb2 as schema__pb2
class SchemaServiceStub(object):
"""Schema services
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
""... |
os-cloud-storage/openstack-workload-disaster-recovery | dragon/db/sqlalchemy/migration.py | Python | apache-2.0 | 3,810 | 0.00105 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... |
engine = migrate_util.construct_engine(url, **kw)
try:
kw['engine'] = engine
return f(*a, **kw)
finally:
if isinstance(engine, migrate_util.Engine) and engine is not url:
| migrate_util.log.debug('Disposing SQLAlchemy engine %s', engine)
engine.dispose()
# TODO(jkoelker) When migrate 0.7.3 is released and nova depends
# on that version or higher, this can be removed
MIN_PKG_VERSION = dist_version.StrictVersion('0.7.3')
if (not hasattr(migrate, '__version_... |
nyergler/nested-formset | setup.py | Python | bsd-3-clause | 1,386 | 0.001443 | from setuptools import setup, find_packages
import sys, os
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
NEWS = open(os.path.join(here, 'NEWS.txt')).read()
version = '0.1.4'
setup(name='django-nested-formset',
description='Nest Django formsets for mu... | r/nested-formset',
license='BSD',
packages=find_packages('src'),
package_dir={'': 'src'},
incl | ude_package_data=True,
zip_safe=False,
install_requires=[
'Django<2.0',
],
tests_require=[
'rebar',
],
test_suite='nested_formset.tests.run_tests',
)
|
the-zebulan/CodeWars | katas/beta/multiply_list_by_integer_with_restrictions.py | Python | mit | 86 | 0.011628 | fro | m operator import mul
def multiply(n, l):
return map(lambda a: mul(a, n), | l)
|
cybergarage/round-py | round/test.py | Python | bsd-3-clause | 1,569 | 0.006373 | #################################################################
#
# Round for Python
#
# Copyright (C) Satoshi Konno 2016
#
# This is licensed under BSD-style license, see file COPYING.
#
##################################################################
from __future__ import absolute_import
from .server import Se... | # return TestProcessServer()
return TestDebugServer()
class TestNode(Node):
def __init__(self):
Node.__init__(self)
self.server = TestServer.Create()
self.server.start()
self.start()
def start(self):
if | not self.server.start():
return False
node = self.server.nodes[0]
if not node.is_alive:
return False
self.set_node(node)
return True
def stop(self):
self.server.stop()
return True
def __del__(self):
self.stop() |
UKN-DBVIS/SciBib | app/backend/db_controller/helper.py | Python | apache-2.0 | 2,777 | 0.002521 | # Copyright (C) 2020 University of Konstanz - Data Analysis and Visualization Group
# This file is part of SciBib <https://github.com/dbvis-ukon/SciBib>.
#
# SciBib 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 Fo... | eturn: if the user is authorized
@rtype: bool
"""
# check if the current user is the editor of the publication
is_editor = db.session.query(
db.session().query(Users_publication)\
.filter( | Users_publication.user_id == curr_user.get_id() and Users_publication.publication_id == pub_id).exists()
).scalar()
db.session.close()
return is_editor or curr_user.has_role('admin')
def _createCiteName(authors, year, title):
"""
Create a name for a bibtex citation:
* concat the first two le... |
Poofjunior/dxf2gcode | gui/messagebox.py | Python | gpl-3.0 | 2,949 | 0.001018 | # -*- coding: utf-8 -*-
############################################################################
#
# Copyright (C) 2011-2014
# Christian Kohlöffel
#
# This file is part of DXF2GCODE.
#
# DXF2GCODE is free software: you can redistribute it and/or modify
# it under the terms of the GNU General P... | class initialized
previously.
"""
super(MessageBox, self).__init__()
self.setOpenExternalLinks(True)
self.append(self.tr("You are using DXF2GCODE"))
self.append(self.tr("Version %s (%s)") % (c.VERSION, c.DATE))
self.append(self.tr("For more information a... | ng_to_translate):
"""
Translate a string using the QCoreApplication translation framework
@param: string_to_translate: a unicode string
@return: the translated unicode string if it was possible to translate
"""
return text_type(QtCore.QCoreApplication.translate('Mes... |
jhamman/xarray | xarray/tests/test_formatting.py | Python | apache-2.0 | 12,536 | 0.000718 | import sys
from textwrap import dedent
imp | ort numpy as np
import pandas as pd
import xarray as xr
from xarray.core import formatting
from . import raises_regex
class TestFormatting:
def test_get_indexer_at_least_n_items(self):
cases = [
((20,), (slice(10),), (slice(-10, None),)),
( | (3, 20), (0, slice(10)), (-1, slice(-10, None))),
((2, 10), (0, slice(10)), (-1, slice(-10, None))),
((2, 5), (slice(2), slice(None)), (slice(-2, None), slice(None))),
((1, 2, 5), (0, slice(2), slice(None)), (-1, slice(-2, None), slice(None))),
((2, 3, 5), (0, slice(2), s... |
inventree/InvenTree | InvenTree/InvenTree/serializers.py | Python | mit | 18,182 | 0.00132 | """
Serializers used in various InvenTree apps
"""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import tablib
from decimal import Decimal
from collections import OrderedDict
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ... | on_field_errors' (DRF style)
if '__all__' in data:
data['non_field_errors'] = data['__all__']
del data['__all__']
raise ValidationError(data)
return data
class ReferenceIndexingSerializerMixin():
"""
This serializer mixin ensures the the refere... | IntegerField.MAX_BIGINT:
raise serializers.ValidationError('reference is to to big')
return value
class InvenTreeAttachmentSerializerField(serializers.FileField):
"""
Override the DRF native FileField serializer,
to remove the leading server path.
For example, the FileField might ... |
samastur/django-filer | filer/fields/file.py | Python | bsd-3-clause | 5,482 | 0.002189 | #-*- coding: utf-8 -*-
import inspect
from django import forms
from django.conf import settings as globalsettings
from django.contrib.admin.widgets import ForeignKeyRawIdWidget
from django.contrib.admin.sites import site
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import revers... | = self.widget(rel, site)
else: # Django <= 1.3
widget_instance = self.widget(rel)
forms.Field.__init__(self, widget=widget_instance, *args, **kwargs)
def widget_attrs(self, widget):
widget.required = self.required
return {}
class FilerFileField(models.ForeignKey):
... | **kwargs):
# we call ForeignKey.__init__ with the Image model as parameter...
# a FilerImageFiled can only be a ForeignKey to a Image
return super(FilerFileField, self).__init__(
self.default_model_class, **kwargs)
def formfield(self, **kwargs):
# This is a fairly stand... |
maplesond/msa2qubo | gurobi.py | Python | gpl-3.0 | 1,975 | 0.028354 | #!/usr/bin/env python3
import bvc
from gurobipy import *
import numpy as np
__author__ = "Dan Mapleson, Luis Yanes, Katie Barr, Sophie Kirkwood and Tim Stitt"
__copyright__ = "Copyright 2016, Quantum MSA"
__credits__ = ["Dan Mapleson", "Luis Yanes", "Katie Barr",
"Sophie Kirkwood", "Tim Stitt"]
_... | R)
x_k += L_k
for k in range(data.N()):
L_k = data.lenK(k)
for j in range(L_k):
G_kj = G_k + j
vars[G_kj] = m.addVar(name="G_" + str(k) + "," + str(j), vtype=GRB.INTEGER)
G_k += L_k
# Integrate new variables
m.update()
data.createBVMatrix(intmode=True)
data.printIntegerCoefficients()
# Set obj... | range(data.get_NbIV()):
for j in range(data.get_NbIV()):
if data.qim(i,j) != 0:
obj += data.qim(i,j) * vars[i] * vars[j]
if data.lil(i) != 0:
obj += data.lil(i) * vars[i]
obj = data.l0() * (obj)
print("Integer Objective Function:")
print(obj)
print()
m.setObjective(obj)
for i in range(data.get_N... |
tiagochiavericosta/edx-platform | lms/djangoapps/open_ended_grading/views.py | Python | agpl-3.0 | 15,748 | 0.002794 | import logging
from django.views.decorators.cache import cache_control
from edxmako.shortcuts import render_to_response
from django.core.urlresolvers import reverse
from courseware.courses import get_course_with_access
from courseware.access import has_access
from courseware.tabs import EnrolledTab
from xmodule.ope... |
# Reverse the base course url.
base_course_url = reve | rse('courses')
found_module = False
problem_url = ""
# Get the peer grading modules currently in the course. Explicitly specify the course id to avoid issues with different runs.
items = modulestore().get_items(course.id, qualifiers={'category': 'peergrading'})
# See if any of the modules are cent... |
lianliuwei/gyp | pylib/gyp/generator/xcode.py | Python | bsd-3-clause | 53,816 | 0.006875 | # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import filecmp
import gyp.common
import gyp.xcodeproj_file
import errno
import os
import sys
import posixpath
import re
import shutil
import subprocess
import temp... | are the same BUILT_PRODUCTS_DIR.
_shared_intermediate_var = 'SHARED_INTERMEDIATE_DIR'
_library_search_paths_var = 'LIBRARY_SEARCH_PATHS'
generator_default_variables = {
'EXECUTABLE_PREFIX': '',
'EXECUTABLE_SUFFIX': '',
'STATIC_LIB_PREFIX': 'lib',
'SHARED_LIB_PREFIX': 'lib',
'STATIC_LIB_SUFFIX': '.a',
'SHA... | EDIATE_DIR is a place for targets to build up intermediate products.
# It is specific to each build environment. It is only guaranteed to exist
# and be constant within the context of a project, corresponding to a single
# input file. Some build environments may allow their intermediate directory
# to be shar... |
justyns/home-assistant | homeassistant/components/sensor/time_date.py | Python | mit | 2,911 | 0 | """
Support for showing the date and the time.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.time_date/
| """
import logging
import homeassistant.util.dt as dt_util
from homeassistant.helpers.entity import Entity
_LOGGER = logging.getLogger(__name__)
OPTION_TYPES = {
'time': 'Time',
'date': 'Date',
'date_time': 'Date & Time',
'time_date': 'Time & Date',
'beat': 'Time (beat)',
't | ime_utc': 'Time (UTC)',
}
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Time and Date sensor."""
if hass.config.time_zone is None:
_LOGGER.error("Timezone is not set in Home Assistant config")
return False
dev = []
for variable in config['display_opt... |
nputikhin/simple-ant-hrm | SimpleHRMServer/sensorserver.py | Python | mit | 2,312 | 0.003893 | import socket
import time
class SensorTCPServer:
'''
Server for Galileo with connected ANT HRM
'''
def startServer(self, serverAddr, handler):
'''
Open a new socket and bind it to serverAddr
'''
self.handler = handler
self.socket = socket.socket()
self.s... | break
self._onLoopShutdown()
def shutdown(self):
'''
Set shutdown request for loop to stop execution on next iteration
'''
self._shutdown_requ | est = True
def _onLoopShutdown(self):
'''
Shutdown connection and close socket
'''
if self.hasConnection:
self.connection.shutdown(socket.SHUT_RDWR)
self.connection.close()
self.hasConnection = False
self.rfile = None
self.sock... |
anirudhr/neural | adaline.py | Python | gpl-2.0 | 4,068 | 0.014749 | #!/usr/bin/python2
import math, sys, time
def drange(start, stop, step): #Generator for step <1, from http://stackoverflow.com/questions/477486/python-decimal-range-step-value
r = start
while r < stop:
yield r
r += step
class adaline:
def __init__(self, w_vec):#, bias): #absorbed
... | isTraining = True) # yy = yin
w_change = list()
bias_change = -2*rate*(yin - tt)
for i in range(len(self.w_vec)):
w_change.append(bias_change*s_vec[i])
if verbose_flag:
print "yy: ", yy
#print "bi... | int "w_change: ", w_change
#self.bias = self.bias + bias_change #absorbed
for ii,wc in enumerate(self.w_vec):
self.w_vec[ii] = wc + w_change[ii]
#if math.fabs(bias_change) < 0.1: #absorbed
insigFlag = True #time to ... |
darknightghost/AntiPkgLoss | ui/screen.py | Python | gpl-3.0 | 2,542 | 0.04341 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright 2016,暗夜幽灵 <darknightghost.cn@gmail.com>
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 y... | *
scr = screen.screen()
scr.screen_main(menu)
The menu is a list in the format of
[[type,text,value],
[type,text,value],
[type,text,value],
...
[type,text,value]]
Current support types:
Type Value Description
"lable" None Static text
"submenu" menu Sub Menu Ente... | t2,text3...],selected-index] Show a list and select one
'''
def __init__(self):
locale.setlocale(locale.LC_ALL, '')
self.stdscr = None
self.width = 0
self.height = 0
def screen_main(self,menu_list,title):
success = True
try:
#Begin GUI
self.stdscr = curses.initscr()
self.height = self.stdscr.... |
jacksonicson/paper.IS2015 | times/Times/src/service/times_service.py | Python | mit | 4,006 | 0.008737 | from thrift.protocol import TBinaryProtocol, TCompactProtocol
from thrift.server import TServer
from thrift.transport import TSocket, TTransport
from times import TimeService, ttypes
import os
import re
import StringIO
################################
## Configuration ##
DATA_DIR = os.path.abspath('../../... | ult
def _create(self, name, frequency):
ts = ttypes.TimeSeries()
| ts.name = name
ts.frequency = frequency
ts.elements = []
self.__write(ts, self.__filename(name))
def _append(self, name, elements):
ts = self._read_decode(self.__filename(name))
if ts is None:
print 'ERROR: TS not found %s' % (name)
... |
pitunti/alfaPitunti | plugin.video.alfa/servers/kbagi.py | Python | gpl-3.0 | 1,896 | 0.00211 | # -*- coding: utf-8 -*-
from core import httptools
from core import jsontools
from core import scrapertools
from platformcode import logger
def test_video_exists(page_url):
logger.info("(page_url='%s')" % page_url)
if "kbagi.com" in page_url:
from channels import kbagi
logueado, error_message... | mium=False, user="", password="", video_password=""):
logger.info("(page_url='%s')" % page_url)
| video_urls = []
data = httptools.downloadpage(page_url).data
host = "http://kbagi.com"
host_string = "kbagi"
if "diskokosmiko.mx" in page_url:
host = "http://diskokosmiko.mx"
host_string = "diskokosmiko"
url = scrapertools.find_single_match(data, '<form action="([^"]+)" class="downl... |
BuzzFeedNews/bikeshares | bikeshares/programs/nyc.py | Python | mit | 1,861 | 0.01021 | import bikeshares
import pandas as pd
import numpy as np
def convert_rider_gender(x):
if x == 0: return np.nan
if x == 1: return "M"
if x == 2: return "F"
raise Exception("Unrecognized gender variable: {0}".format(x))
def convert_rider_type(x):
if x == "Subscriber": return "member"
if x == "Cu... | "start station id", "end station id",
"bikeid", "usertype", "gender", "birth year" ],
parse_dates=["starttime", "stoptime"])
mapped = pd.DataFrame({
"start_time": parsed["starttime"],
"start_station": parsed["start station id"],
... | duration": parsed["tripduration"],
"bike_id": parsed["bikeid"],
"rider_type": parsed["usertype"].apply(convert_rider_type),
"rider_gender": parsed["gender"].apply(convert_rider_gender),
"rider_birthyear": parsed["birth year"]
})
return mapped
def par... |
JulianSchuette/android-instrumentation | injector/injector/apk.py | Python | apache-2.0 | 726 | 0.006887 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2012, The Honeynet Project. All rights reserved.
# Author: Kun Yang <kelwya@gmail.com>
#
# APKIL is free software: you can redistribute it and/or modify it under
# the terms of version 3 of the GNU Lesser General Public License as
# published by the Free Soft... | URPOSE. 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 APKIL. If not, see <http://www.gnu.org/l | icenses/>.
|
vineethguna/heroku-buildpack-libsandbox | vendor/pygal-0.13.0/pygal/config.py | Python | mit | 8,580 | 0.000816 | # -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012 Kozea
#
# 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 3 of... | fill = Key(
False, bool, "Look", "Fill areas under lines")
show_legend = Key(
True, bool, "Look", "Set to false to remove legend")
legend_at_bottom = Key(
False, bool, "Look", "Set to true to position legend at bottom")
legend_box_size = Key(
12, int, "Look", "Size of ... | bel",
"X labels, must have same len than data.",
"Leave it to None to disable x labels display.",
str)
y_labels = Key(
None, list, "Label",
"You can specify explicit y labels",
"Must be a list of numbers", float)
x_label_rotation = Key(
0, int, "Label", ... |
sirodoht/ting | API/chat/tests.py | Python | mit | 24,874 | 0.000804 | import time
import json
import datetime
import urllib
from django.test import TestCase, Client
from django.core.urlresolvers import reverse
from django_dynamic_fixture import G
from django.utils.dateformat import format
from .utils import datetime_to_timestamp, timestamp_to_datetime
from .models import Message, Chann... | tetime(timestamp),
datetime_sent=timestamp_to_datetime(timestamp + 10),
username='vitsalis',
typing=True,
channel=self.channel
| )
message2 = Message.objects.create(
text='Message2',
datetime_start=timestamp_to_datet |
vbursztyn/SegundoVoto | application/persistence.py | Python | agpl-3.0 | 1,800 | 0.035 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from urlparse import urlparse
import os
import pymongo
import json
class MongoPersistence():
def __init__(self, collection):
self.collectionName = collection
MONGO_URI = os.environ.get('MONGOLAB_URI')
if MONGO_URI:
self.client = pymongo.MongoClient(MONG... | ]
| def getInterface(self):
collection = self.db[self.collectionName]
results = list()
for result in collection.find():
results.append(result)
return results
def getResult(self, pType, pId, year, subject, position):
collection = self.db[self.collectionName]
results = dict()
for result in collection.... |
varunarya10/rally | tests/unit/benchmark/scenarios/quotas/test_utils.py | Python | apache-2.0 | 4,630 | 0 | # Copyright 2014: Kylin Cloud
# 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 ... | eturn_value=quotas)
fake_clients = fakes.FakeClients()
fake_clients._nova = fake_nova
scenario = utils.QuotasScenario(admin_clients=fake_clients)
scenario._generate_quota_values = mock.MagicMock(return_value=quotas)
mock_quota = mock.Mock(return_value=quotas)
result = s... | quota_update_fn=mock_quota)
self.assertEqual(quotas, result)
self._test_atomic_action_timer(scenario.atomic_actions(),
"quotas.update_quotas")
def test__generate_quota_values_nova(self):
max_quota = 1024
scenario = u... |
bram85/topydo | test/facilities.py | Python | gpl-3.0 | 1,802 | 0 | # Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topydo.org>
#
# This program is free software: you can redistribute it and/or modify
# it under | the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or... | A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from topydo.lib.printers.PrettyPrinter import PrettyPrinter
from topydo.lib.Todo import Todo
from t... |
OAButton/tricorder | plugins/python/metaheaders.py | Python | bsd-3-clause | 2,791 | 0.039412 | #!/usr/bin/env python2.6
import lxml.html, re, HTMLParser
class InvalidArguments(Exception):
pass
class MetaHeaders:
def __init__(self, url=None, page=None,name='name',content='content', unescape_entities=False):
if page:
self.root = lxml.html.document_fromstring(page)
elif url:
self.root = lxml.html.pa... | taheaders = MetaHeaders(url=url)
for (k,v) in metaheaders.meta.items():
print "%s = %s" % (k,v)
print "===============\nRepeat with manual fetch"
from urllib2 import urlopen
page = urlopen(url).read()
metaheaders = | MetaHeaders(page=page)
for (k,v) in metaheaders.meta.items():
print "%s = %s" % (k,v)
if __name__ == '__main__':
test()
|
yuanlisky/linlp | linlp/algorithm/viterbiMat/prob_start_organization.py | Python | apache-2.0 | 282 | 0.056738 | prob_start = {
'P': -3.14e+100,
'B': -3.14e+100,
'M': -3.14e+100,
'S': 0.0,
'X | ': -3.14e+100,
'L': -3.14e+100,
'F': -3.14e+100,
| 'W': -3.14e+100,
'D': -3.14e+100,
'G': -3.14e+100,
'K': -3.14e+100,
'I': -3.14e+100,
'A': -3.14e+100,
'Z': -3.14e+100,
'J': -3.14e+100,
'C': -3.14e+100,
}
|
cloudbase/neutron | neutron/agent/windows/utils.py | Python | apache-2.0 | 3,141 | 0 | # Copyright 2015 Cloudbase Solutions.
# 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 requ... | heck_exit_code:
raise RuntimeError(m)
finally:
# NOTE(termie): this appears to be necessary to let the | subprocess
# call clean something up in between calls, without
# it two execute calls in a row hangs the second one
greenthread.sleep(0)
return (_stdout, _stderr) if return_stderr else _stdout
|
UITools/saleor | saleor/product/migrations/0080_auto_20181214_0440.py | Python | bsd-3-clause | 616 | 0 | # Generated by Django 2.1.3 on 2018-12-14 10:40
from django.db import migrations, models
clas | s Migration(migrations.Migration):
|
dependencies = [
('product', '0079_default_tax_rate_instead_of_empty_field'),
]
operations = [
migrations.AddField(
model_name='category',
name='background_image_alt',
field=models.CharField(blank=True, max_length=128),
),
migrations.AddF... |
shiquanwang/numba | numba/tests/test_filter2d.py | Python | bsd-2-clause | 1,782 | 0.005612 | #! /usr/bin/env python
# ______________________________________________________________________
'''test_filter2d
Test the filter2d() example from the PyCon'12 slide deck.
'''
# ______________________________________________________________________
import numpy
from numba import *
from numba.decorators import jit
im... | stFilter2d(unittest.TestCase):
def test_vectorized_filter2d(self):
ufilter2d = jit(argtypes=[double[:,:], double[:,:]],
restype=double[:,:])(filter2d)
image = numpy.random.random(( | 50, 50))
filt = numpy.random.random((5, 5))
filt /= filt.sum()
plain_old_result = filter2d(image, filt)
hot_new_result = ufilter2d(image, filt)
self.assertTrue((abs(plain_old_result - hot_new_result) < 1e-9).all())
# ______________________________________________________________... |
vbkaisetsu/clopure | clopure/exceptions.py | Python | mit | 273 | 0 | c | lass ClopureSyntaxError(Exception):
def __init__(self, *args, pos=0, **kwargs):
super().__init__(*args, **kwargs)
self.pos = pos
class ClopureRuntimeError(Exception):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
| |
LethusTI/supportcenter | vendor/django/tests/regressiontests/admin_inlines/admin.py | Python | gpl-3.0 | 2,914 | 0.001716 | from django.contrib import admin
from django import forms
from models import *
site = admin.AdminSite(name="admin")
class BookInline(admin.TabularInline):
model = Author.books.through
class AuthorAdmin(admin.ModelAdmin):
inlines = [BookInline]
class InnerInline(admin.StackedInline):
model = Inner
... | s.ModelForm):
def clean(self):
cleaned_data = self.cleaned_data
title1 = cleaned_data.get("title1")
title2 = cleaned_data.get("title2")
if title1 != title2:
raise forms.ValidationError("The two titles must be the same")
return cleaned_data
class TitleInline(adm... | kedInline(admin.StackedInline):
model = Inner4Stacked
class Inner4TabularInline(admin.TabularInline):
model = Inner4Tabular
class Holder4Admin(admin.ModelAdmin):
inlines = [Inner4StackedInline, Inner4TabularInline]
class InlineWeakness(admin.TabularInline):
model = ShoppingWeakness
extra = 1
... |
paul30001/pikapy1 | pikapy/ptcexceptions.py | Python | gpl-3.0 | 658 | 0 | __all__ = [
'PTCException',
'PTCInvalidStatusCodeException',
'PTCInvalidNameException',
'PTCInvalidEmailException',
'PTCInvalidPasswordException',
]
class PTCException(Exception):
| """Base exception for all PTC Account exceptions"""
pass
class PTCInvalidStatusCodeException(Exception):
"""Base exception for all PTC Account exceptions"""
pass
class PTCInvalidNameException(PTCException):
"""Username already in use"""
pass
class PTCInvalidEmailException(PTCException):
""... | invalid or already in use"""
pass
class PTCInvalidPasswordException(PTCException):
"""Password invalid"""
pass
|
QiJune/Paddle | python/paddle/fluid/tests/unittests/dist_transformer.py | Python | apache-2.0 | 63,417 | 0.000347 | # Copyright (c) 2018 PaddlePaddle 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 app... | iler.details import program_to_code
const_para_attr = fluid.ParamAttr(initializer=fluid.initializer.Constant(0.001))
const_bias_attr = const_para_a | ttr
# Fix seed for test
fluid.default_startup_program().random_seed = 1
fluid.default_main_program().random_seed = 1
#from transformer_config import ModelHyperParams, TrainTaskConfig, merge_cfg_from_list
class TrainTaskConfig(object):
# only support GPU currently
use_gpu = True
# the epoch number to trai... |
bingshuika/hearthbreaker-new | hearthbreaker/cards/weapons/__init__.py | Python | mit | 594 | 0 | from hearthbreaker.cards.weapons.hunter import (
EaglehornBow,
GladiatorsLongbow,
| Glaivezooka,
)
from hearthbreaker.cards.weapons.paladin import (
LightsJustice,
SwordOfJustice,
TruesilverChampion,
Coghammer,
)
from hearthbreaker.cards.weapons.rogue import (
AssassinsBlade,
PerditionsBlade,
CogmastersWrench,
)
from hearthbreaker.cards.weapons.shaman import (
Doomh... | Warmaul,
)
|
efiring/numpy-work | numpy/core/numerictypes.py | Python | bsd-3-clause | 20,785 | 0.003464 | """numerictypes: Define the numeric type objects
This module is designed so 'from numerictypes import *' is safe.
Exported symbols include:
Dictionary with all registered number types (including aliases):
typeDict
Type objects (not all will be available, depends on platform):
see variable sctypes for w... | 5] + _ascii_lower + _all_chars[65+26:])
UPPER_TABLE="".join(_all_chars[:97] + _ascii_upper + _all_chars[97+26:])
#import string
# assert (string.maketrans(string.ascii_uppercase, string.ascii_lowercase) == \
# LOWER_TABLE)
# assert (string.maketrnas(string_ascii_lowerca | se, string.ascii_uppercase) == \
# UPPER_TABLE)
#LOWER_TABLE = string.maketrans(string.ascii_uppercase, string.ascii_lowercase)
#UPPER_TABLE = string.maketrans(string.ascii_lowercase, string.ascii_uppercase)
def english_lower(s):
""" Apply English case rules to convert ASCII strings to all lower case.
... |
lingcheng99/LeetCode | AddBinary.py | Python | mit | 327 | 0.015291 | """
Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
"""
clas | s Solution(object):
def addBina | ry(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a,base=2)+int(b,base=2))[2:]
|
ToonTownInfiniteRepo/ToontownInfinite | toontown/building/DistributedBuildingMgrAI.py | Python | mit | 9,120 | 0.001535 | from direct.directnotify.DirectNotifyGlobal import *
from otp.ai.AIBaseGlobal import *
from toontown.building import DistributedBuildingAI
from toontown.building import GagshopBuildingAI
from toontown.building import HQBuildingAI
from toontown.building import KartShopBuildingAI
from toontown.building import PetshopBuil... | ks, gagshopBlocks, petshopBlocks, kartshopBlocks,
| animBldgBlocks) = self.getDNABlockLists()
for blockNumber in blocks:
self.newBuilding(blockNumber, backup=backups.get(blockNumber, None))
for blockNumber in animBldgBlocks:
self.newAnimBuilding(blockNumber, backup=backups.get(blockNumber, None))
for blockNumber in hqBl... |
AlessandroSpallina/JASM | testclient/sockets.py | Python | gpl-3.0 | 578 | 0.025952 | import socket
class Socket:
def __init__(self,ipaddr="127.0.0.1",p | ort=9734):
self.ipaddr=ipaddr
self.port=port
self.sck=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.sck.connect((ipaddr,port))
def send(self,data):
defdata="Data-Size: {}\n\n{}".format(len(data),data)
return sel | f.sck.sendall(bytes(defdata.encode('utf-8')))
def recv(self,bufsize=1024):
return self.sck.recv(bufsize).decode("utf-8","replace")
def close(self):
self.sck.close()
if __name__ == '__main__':
exit(1)
|
dipen30/boxapi | box/error.py | Python | mit | 982 | 0.026477 | # box
# Copyright 2013-2014 Dipen Patel
# See LICENSE for details.
STATUSCODES = {
200 : "success",
201 : "created",
202 : "accepted",
204 : "no_content",
302 : "redirect",
304 : " | not_modified",
400 : "bad_request",
401 : "unauthorized",
40 | 3 : "forbidden",
404 : "not_found",
405 : "method_not_allowed",
409 : "conflict",
412 : "precondition_failed",
429 : "too_many_requests",
500 : "internal_server_error",
507 : "insufficient_storage"
}
ERRORCODES = (204,... |
annahs/atmos_research | AL_size_distrs.py | Python | mit | 14,993 | 0.048689 | import sys
import os
import numpy as np
from pprint import pprint
from datetime import datetime
from datetime import timedelta
import mysql.connector
import math
import matplotlib.pyplot as plt
import matplotlib.colors
from matplotlib import dates
import calendar
from scipy.optimize import curve_fit
start = datetime(... | ] = [bin,(bin+bin_incr),0,0]
return new_dict
def calcuate_VED(bbhg_incand_pk_amp,bblg_incand_pk_amp, instr_id):
VED = np.nan
if instr_id == '58':
#HG
bbhg_mass_uncorr = 0.29069 + 1.49267E-4*bbhg_incand_pk_amp + 5.02184E-10*bbhg_incand_pk_amp*bbhg_incand_pk_amp
bbhg_mass_corr = bbhg_mass_uncorr/0.7 #AD c... | d_pk_amp*bblg_incand_pk_amp
bblg_mass_corr = bblg_mass_uncorr/0.7 #AD correction factor is 0.7 +- 0.05
if min_rBC_mass <= bbhg_mass_corr < 12.8:
VED = (((bbhg_mass_corr/(10**15*1.8))*6/math.pi)**(1/3.0))*10**7
elif 12.8 <= bblg_mass_corr < max_rBC_mass:
VED = (((bblg_mass_corr/(10**15*1.8))*6/math.pi)**(... |
ruchee/vimrc | vimfiles/bundle/vim-python/submodules/snowball_py/snowballstemmer/dutch_stemmer.py | Python | mit | 23,184 | 0.002459 | # self file was generated automatically by the Snowball to Python interpreter
from .basestemmer import BaseStemmer
from .among import Among
class DutchStemmer(BaseStemmer):
'''
self class was automatically generated by a Snowball to Python interpreter
It implements the stemming algorithm defined by a sno... | elif among_var == 5:
# (, line 53
# <-, line 53
if not self.slice_from(u"u"):
return False
elif among_va | r == 6:
# (, line 54
# next, line 54
if self.cursor >= self.limit:
raise lab2()
self.cursor += 1
raise lab1()
except lab2: pass
... |
endlessm/chromium-browser | third_party/catapult/dashboard/dashboard/services/crrev_service_test.py | Python | bsd-3-clause | 1,606 | 0.000623 | # Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import json
import unittest
import mock
from ... | es import crrev_service
@mock.patch('dashboard.services.request.Request')
class CrrevServiceTest(unittest.TestCase):
def testGetNumbering(self, mock_request):
params = {
'number': '498032',
'numbering_identifier': 'refs/heads/master',
'numbering_type': 'COMMIT_POSITION',
'projec | t': 'chromium',
'repo': 'chromium/src'
}
return_value = {
'git_sha': '4c9925b198332f5fbb82b3edb672ed55071f87dd',
'repo': 'chromium/src',
'numbering_type': 'COMMIT_POSITION',
'number': '498032',
'project': 'chromium',
'numbering_identifier': 'refs/heads/mas... |
Bihaqo/exp-machines | src/TTRegression.py | Python | mit | 13,433 | 0.001266 | from sklearn.linear_model.base import BaseEstimator, LinearClassifierMixin
import sklearn
import numpy as np
from copy import deepcopy
from utils import roc_auc_score_reversed
import tt
import logging
class TTRegression(BaseEstimator, LinearClassifierMixin):
"""This class alows to optimize functions of the foll... | , w> / 2\n'
'while sgd solver assumes regularization in terms of the cores elements:\n'
'\treg * <w.core, w.core> / 2\n')
if self.persuit_init and self.coef0 is not None:
if self.logger.disp():
print('WARNING: persuit_init parameter is not compati... | viding initial values.')
# TODO: deal with sparse data.
# Copy the dataset, since preprocessing changes user's data, which is messy.
X = deepcopy(X_)
y = deepcopy(y_)
X, y, self.info = self.preprocess(X, y)
if val_X_ is not None and val_y_ is not None:
val_X ... |
ChenglongChen/Kaggle_HomeDepot | Code/Chenglong/feature_base.py | Python | mit | 8,989 | 0.007342 | # -*- coding: utf-8 -*-
"""
@author: Chenglong Chen <c.chenglong@gmail.com>
@brief: base class for feature generation
"""
import os
import sys
import numpy as np
import config
from config import TRAIN_SIZE
from utils import np_utils, pkl_utils
# Since we have many features that measure the correlation/similarity/... | ance_Ngram
# 2. CompressionDistance_Ngram
# 3. Word2Vec_CosineSim
# 4. WordNet_Path_Similarity, WordNet_Lch_Similarity, WordNet_Wup_Similarity
# which are very time consuming to compute the inner list
self.double_aggregation = True
def _check_aggregation_... | gation_mode):
valid_aggregation_modes = ["", "size", "mean", "std", "max", "min", "median"]
if isinstance(aggregation_mode, str):
assert aggregation_mode.lower() in valid_aggregation_modes, "Wrong aggregation_mode: %s"%aggregation_mode
aggregation_mode = [aggregation_mode.lower()... |
cloudify-cosmo/cloudify-azure-plugin | examples/aks_service/scripts/store_kube_token.py | Python | apache-2.0 | 259 | 0 | impo | rt base64
from cloudify.state import ctx_parameters as inputs
from cloudify.manager import get_rest_client
client = get_rest_client()
client.secrets.cre | ate(
'kubernetes_token',
base64.b64decode(inputs['kube_token']),
update_if_exists=True)
|
christiano/pyArango | pyArango/index.py | Python | apache-2.0 | 1,257 | 0.043755 | import json
from theExceptions import (CreationError, DeletionError, UpdateError)
class Index(object) :
def __init__(self, collection, infos = None, creationData = None) :
"""An index on a collection's fields. Indexes have a .infos dictionnary that stores all the infos about | the index"""
self.collection = collection
self.connection = self.collection.database.connection
self.indexesURL = "%s/index" % self.collection.database.URL
self.infos = None
if infos :
self.infos = infos
elif creationData :
self._create(creationData)
if self.infos :
self.URL = "%s/%s" % (... |
def _create(self, postData) :
"""Creates an index of any type according to postData"""
if self.infos is None :
r = self.connection.session.post(self.indexesURL, params = {"collection" : self.collection.name}, data = json.dumps(postData))
data = r.json()
if (r.status_code >= 400) or data['error'] :
r... |
airbnb/streamalert | streamalert_cli/terraform/alert_processor.py | Python | apache-2.0 | 2,636 | 0.002276 | """
Copyright 2017-present Airbnb, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, sof... | name is needed for the IAM permissions
func.split(':')[0] for func in list(config['outputs'].get('aws-lambda', {}).values())
],
'output_s3_buckets': list(config['outputs'].get('aws-s3', {}).values()),
'output_sns_topics': list(config['outputs'].get('aws-sns', {}).values()),
... | da'] = generate_lambda(
'{}_streamalert_{}'.format(config['global']['account']['prefix'], ALERT_PROCESSOR_NAME),
'streamalert.alert_processor.main.handler',
config['lambda']['alert_processor_config'],
config,
environment={
'ALERTS_TABLE': '{}_streamalert_alerts'.forma... |
brandonmburroughs/food2vec | src/food2vec.py | Python | mit | 9,886 | 0.012341 | """Train a multi-class classification problem.
Use the embedding for each ingredient in a recipe to predict the rest
of the ingredients in the recipe.
Debug the model with a held-out validation set.
"""
import tensorflow as tf
import collections
import nomen
import numpy as np
layers = tf.contrib.layers
cfg = nomen... | depth=vocabulary_size, on_v | alue=1, off_value=0, axis=1)
print(train_indicators)
train_indicators = tf.to_float(tf.reduce_sum(train_indicators, -1))
valid_dataset = tf.constant(valid_examples, dtype=tf.int32)
# Ops and variables pinned to the CPU because of missing GPU implementation
with tf.device('/cpu:0'):
# Look up e... |
City-of-Helsinki/smbackend | services/models/__init__.py | Python | agpl-3.0 | 696 | 0 | from .accessibility_variable import AccessibilityVariable
from .department import Department
from .keyword import Keyword
from .notification import Announcement, ErrorMessage
from .service import Service, UnitServ | iceDetails
from .service_mapping import ServiceMapping
from .service_node import ServiceNode
from .unit import Unit
from .unit_accessibility_property import UnitAccessibilityProperty
from .unit_accessibility | _shortcomings import UnitAccessibilityShortcomings
from .unit_alias import UnitAlias
from .unit_connection import UnitConnection
from .unit_count import ServiceNodeUnitCount, ServiceUnitCount
from .unit_entrance import UnitEntrance
from .unit_identifier import UnitIdentifier
|
DerThorsten/nifty | src/python/examples/graph/plot_undirected_grid_graph_watersheds.py | Python | mit | 3,725 | 0.013423 | """
Edge/Node Weighted Watersheds
====================================
Compare edge weighted watersheds
and node weighted on a grid graph.
"""
####################################
# sphinx_gallery_thumbnail_number = 5
from __future__ import print_function
import nifty.graph
import skimage.data
import skimage.segmen... | (sum weights)')
f.add_subplot(2,2, 2)
b_img = skimage.segmentation.mark_boundaries(img/255,
oversegEdgeWeightedB.astype('uint32'), mode='inner', color=(0.1,0.1,0.2))
pylab.imshow(b_img)
pylab.title('Edge Weighted Watershed (interpixel weights)')
f.add_subplot(2,2, 3)
b_img = | skimage.segmentation.mark_boundaries(img/255,
oversegNodeWeighted.astype('uint32'), mode='inner', color=(0.1,0.1,0.2))
pylab.imshow(b_img)
pylab.title('Node Weighted Watershed')
pylab.show() |
CORE-GATECH-GROUP/serpent-tools | docs/magicPlotDoc.py | Python | mit | 646 | 0 | """
Write out magic strings to magicPlotDocDecorator
"""
from os.path import join
from sys import version_info
import serpentTools
pyVersion = '{}.{}.{}'.format(*version_info[:3])
magicStrings = serpentTools.plot.PLOT_MAGIC_STRINGS
magicOpts = [
'#. ``{key}``: {value}'.format(key=key, value=magicStrings[key] | )
for key in sorted(magicStrings.keys())]
targetFile = join('develop', 'magicPlotOpts.rst')
print("Making magic plot conversion options | with \n python: {}"
"\n serpentTools: {}".format(pyVersion, serpentTools.__version__))
with open(targetFile, 'w') as target:
target.write('\n'.join(magicOpts))
print(' done')
|
sharkdata/sharkdata | sharkdata_core/string_utils.py | Python | mit | 3,194 | 0.001252 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Copyright (c) 2013-present SMHI, Swedish Meteorological and Hydrological Institute
# License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit).
from fnmatch import fnmatch
def extract_pattern_values(
string_to_parse,
pattern_strings,
pat... | stop_pos = len(string_to_parse)
else:
next_part = file_name_parts[index + 1]
stop_pos = string_to_parse.find(next_part, start_pos + 1)
value_string = string_to_parse[start_pos:stop_pos]
identifier_values[part] = value_string
c... | art_pos:].startswith(part):
return None
checked_part += part
return identifier_values
def does_pattern_match(
string_to_parse,
pattern_string,
keys,
pattern_var_start_sign="<",
pattern_var_stop_sign=">",
):
match_string = pattern_string
for key in keys:
... |
alerta/python-alerta | tests/integration/test_groups.py | Python | mit | 937 | 0.001067 | import unittest
from alertaclient.api import Client
class AlertTestCase(unittest.TestCase):
def setUp(self):
self.client = Client(e | ndpoint='http://api:8080', key='demo-key')
def test | _group(self):
group = self.client.create_group(name='myGroup', text='test group')
group_id = group.id
self.assertEqual(group.name, 'myGroup')
self.assertEqual(group.text, 'test group')
group = self.client.update_group(group_id, name='newGroup', text='updated group text')
... |
freesmartphone/framework | framework/cxutil/ip.py | Python | gpl-2.0 | 2,408 | 0.039452 | """
Misc utils for IPv4 management
"""
# Copyright (c) 2008 Peter V. Saveliev
#
# This file is part of Connexion project.
#
# Connexion 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... | .")
st.reverse()
mask = 32
c = [32]
for i in st:
mask -= 8
if i == "0":
c.append(mask)
return c | [-1]
def get_mask(st):
"""
Return int mask for IP
"""
st = st.split("/")
if len(st) > 1:
mask = st[1]
if mask.find(".") > 0:
mask = dqn_to_int(mask)
else:
mask = msk[int(mask)]
else:
mask = msk[mask_unknown(st[0])]
return mask
def ip_range(st):
"""
Return IP list for a network
"""
mask = get... |
toobaz/pandas | setup.py | Python | bsd-3-clause | 28,584 | 0.000455 | #!/usr/bin/env python
"""
Parts of this file were taken from the pyzmq project
(https://github.com/zeromq/pyzmq) which have been permitted for use under the
BSD license. Parts are from lxml (https://github.com/lxml/lxml)
"""
import os
from os.path import join as pjoin
import pkg_resources
import platform
from distut... | label-based **slicing**, **fancy indexing**, and **subsetting**
of large data sets
- Intuitive **merging** and **joining** data sets
- Flexible **reshaping** and pivoting of data sets
- **Hierarchical** labeling of axes (possible to have multiple la | bels per
tick)
- Robust IO tools for loading data from **flat files** (CSV and delimited),
Excel files, databases, and saving / loading data from the ultrafast **HDF5
format**
- **Time series**-specific functionality: date range generation and frequency
conversion, moving window statistics, moving w... |
Dronolab/antenna-tracking | Sensors/imuAbstract.py | Python | mit | 1,320 | 0.00303 | import os
import sys
import RTIMU
import schedule
import GeneralSettings
from Utility.abstract_process import processAbstract
import time
class imuHandler(processAbstract):
#SETTINGS_FILE = GeneralSettings.IMU_SETTINGS_FILE
def __init__(self, antenna_data):
processAbstract.__init__(self)
self... | elf.SETTINGS_FILE)
self.imu = RTIMU.RTIMU(s)
if (not self.imu.IMUInit()):
print("IMU Init Failed", self.SETTINGS_FILE)
sys.exit(1)
else:
print("IMU Init Succeeded")
self.ready = True
# initialising fusion parameters
self.imu.setSl... |
self.imu.setGyroEnable(True)
self.imu.setAccelEnable(True)
self.imu.setCompassEnable(True)
self.poll_interval = self.imu.IMUGetPollInterval()
while self.kill_pill.empty():
self.job()
time.sleep(10 / 1000)
|
abalakh/robottelo | tests/foreman/ui/test_login.py | Python | gpl-3.0 | 1,168 | 0 | # -*- encoding: utf-8 -*-
"""Test class for Login UI"""
from ddt import ddt
from robottelo.decorators import data
from robottelo.helpers import gen_string
from robottelo.test import UITestCase
@ddt
class Login(UITestCase):
"""Implements the login tests rom UI"""
def test_successful_login(self):
"""@... | @Assert: Successfully logged in as an admin user
"""
self.login.login(self.katello_user, self.katello_passwd)
self.assertTrue(self.login.is_logged())
@data(
{u'login': 'admin', u'pass': ''},
{u'login': '', u'pass': 'mypassword'},
{u'login': '', u'pass': | ''},
{u'login': gen_string('alpha', 300), u'pass': ''},
{u'login': gen_string('alpha', 300),
u'pass': gen_string('alpha', 300)},
)
def test_failed_login(self, test_data):
"""@Test: Login into application using invalid credentials
@Feature: Login - Negative
@Ass... |
TheManaWorld-Ger/server-data | tools/showvars.py | Python | gpl-2.0 | 2,535 | 0.035108 | #!/usr/bin/python
# must be started in the npc dir
import os
import re
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
help="show the occur | rences of that var")
parser.add_option("-f", "--file", dest="fname", default="",
help="inspect that file", metavar="FILE")
parser.add_option("-l", "--localvariables", dest="localvars", action="store_true", default=False,
help="show local variables as well")
(options, args) = parse... | e comments
line = l.split(r"//")[0]
sp = line.split()
# no set command?
if not "set" in sp:
continue
# ignore those lines printing messages
if 'mes "' in line:
continue
#ignore anything before the "set" command:
sp = sp[sp.index("set")+1:]
line = "".join(sp)
endpos = line.find(",")
#che... |
rrahn/gdf_tools | include/seqan/apps/tree_recon/tests/run_tests.py | Python | gpl-3.0 | 3,621 | 0.001657 | #!/usr/bin/env python
"""Execute the tests for the tree_recomb program.
The golden test outputs are generated by the script generate_outputs.sh.
You have to give the root paths to the source and the binaries as arguments to
the program. These are the paths to the directory that contains the 'projects'
directory.
Us... | t
# was generated in generate_outputs.sh.
conf_list = []
for i in [1, 2, 3]:
conf = app_tests.TestConf(
program=path_to_program,
args= | ['-m', ph.inFile('example%d.dist' % i),
'-o', ph.outFile('example%d.dot' % i)],
to_diff=[(ph.inFile('example%d.dot' % i),
ph.outFile('example%d.dot' % i))])
conf_list.append(conf)
for i in [1, 2, 3]:
for b in ['nj', 'min', 'max', 'avg', 'wavg']:
... |
ealogar/curso-python | advanced/fib_fac.py | Python | apache-2.0 | 1,159 | 0.004314 | #-*- coding: utf-8 -*-
def factorial(n):
"""Return the factorial of n"""
if n < 2:
return 1
return n * factorial(n - 1)
def fibonacci(n):
"""Return the nth fibonacci number"""
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
def fib_fac(x=30, y=900 | ):
fib = fibonacci(x)
fac = factorial(y)
print "fibonacci({}):".format(x), fib
print "factorial({}):".format(y), fac
if __name__ == "__main__":
def opc1():
fruits = tuple(str(i) for i in xrange(100))
out = ''
for fruit in fruits:
out += fruit +':'
return... | (i) for i in xrange(100))
out = format_str % fruits
return out
def opc3():
format_str = '{}:' * 100
fruits = tuple(str(i) for i in xrange(100))
out = format_str.format(*fruits)
return out
def opc4():
fruits = tuple(str(i) for i in xrange(100))
... |
CoinAge-DAO/solari | qa/rpc-tests/keypool.py | Python | mit | 4,289 | 0.006528 | #!/usr/bin/env python2
# Copyright (c) 2014 The Bitcoin Core Developers
// Copyright (c) 2015 Solarminx
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Exercise the wallet keypool, and interaction with wallet encryption/locking
... | g [options]")
parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true",
help="Leave solarids and test.* datadir on exit or error")
parser.add_option("--srcdir", dest="srcdir", default="../../src",
help="Source directory containing solarid/... | mpfile.mkdtemp(prefix="test"),
help="Root directory for datadirs")
(options, args) = parser.parse_args()
os.environ['PATH'] = options.srcdir+":"+os.environ['PATH']
check_json_precision()
success = False
nodes = []
try:
print("Initializing test directory "+options... |
justinh5/CipherBox | Arithmetic/__init__.py | Python | mit | 202 | 0 | from Ar | ithmetic.Numbers.NumberArith import Arithmetic
from Arithmetic.Numbers.Modulo import Modulus
from Arithmetic.Numbers.Primality.Primality import Prime
__all__ = ["Arithmetic", "Modulu | s", "Prime"]
|
antoinecarme/sklearn2sql_heroku | tests/classification/FourClass_10/ws_FourClass_10_XGBClassifier_db2_code_gen.py | Python | bsd-3-clause | 138 | 0.014493 | f | rom sklearn2sql_heroku.tests.classification import generic as class_ | gen
class_gen.test_model("XGBClassifier" , "FourClass_10" , "db2")
|
ToonTownInfiniteRepo/ToontownInfinite | toontown/coghq/DistributedBattleFactory.py | Python | mit | 2,002 | 0.001998 | from pandac.PandaModules import *
from direct.interval.IntervalGlobal import *
from toontown.battle.BattleBase import *
from toontown.coghq import DistributedLevelBattle
from direct.directnotify import DirectNotifyGlobal
from toontown.toon import TTEmote
from otp.avatar import Emote
from toontown.battle import SuitBatt... | d('PlayMovie')
playMovieState.addTransition('FactoryReward')
def enterFactoryReward(self, ts):
self.notify.info('enterFactoryReward()')
self.disableCollision()
self.delayDeleteMembers()
if self.hasLocalToon():
NametagGlobals.setMasterArrowsOn(0)
if se... | e:
messenger.send('localToonConfrontedForeman')
self.movie.playReward(ts, self.uniqueName('building-reward'), self.__handleFactoryRewardDone)
def __handleFactoryRewardDone(self):
self.notify.info('Factory reward done')
if self.hasLocalToon():
self.d_rewardDone(ba... |
nonemaw/MATRIX_01 | COMP9041/ass1/examples/0/ls.py | Python | gpl-2.0 | 82 | 0 | #!/usr/bin/python2.7 -u
import subprocess
subprocess.c | all(['ls', '/dev/nu | ll'])
|
apple/coremltools | coremltools/converters/mil/mil/var.py | Python | bsd-3-clause | 8,592 | 0.000815 | # Copyright (c) 2020, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from coremltools.converters.mil.mil import types
from coremltools.converters.mil.mil.types import bui... | t), and all Vars must have `sym_type`.
Example Usage:
from coremltools.converters.mil.mil | import (
Builder as mb,
Function,
types
)
func_inputs = {"a": mb.placeholder(shape=(1,2)),
"b": mb.placeholder(shape=(1,2)) }
with Function(func_inputs) as ssa_func:
a, b = ssa_func.inputs["a"], ssa_func.inputs["b"]
res = mb.add(x=a, y=b) # res is... |
ets-labs/python-dependency-injector | tests/unit/providers/traversal/test_method_caller_py3.py | Python | bsd-3-clause | 1,790 | 0 | """MethodCaller provider traversal tests."""
from dependency_injector import providers
def test_traverse():
provider1 = providers.Provider()
provided = provider1.provided
method = provided.method
provider = method.call()
all_providers = list(provider.traverse())
assert len(all_providers) ==... | rs
assert method in all_providers
def test_traverse_kwargs | ():
provider1 = providers.Provider()
provided = provider1.provided
method = provided.method
provider2 = providers.Provider()
provider = method.call(foo="foo", bar=provider2)
all_providers = list(provider.traverse())
assert len(all_providers) == 4
assert provider1 in all_providers
a... |
thomasdouenne/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/examples/transports/regress/regress_determinants_ticpe.py | Python | agpl-3.0 | 4,104 | 0.009024 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 09:47:41 2015
@author: thomas.douenne
"""
from __future__ import division
import statsmodels.formula.api as smf
from openfisca_france_indirect_taxation.examples.utils_example import simulate_df_calee_by_grosposte
if __name__ == '__main__':
import logging
lo... | data_for_reg['part_diesel'] = data_for_reg['depenses_diesel'] / data_for_reg['rev_disp_loyerimput']
data_for_reg['part_essence'] = data_for_reg['depenses_essence'] / data_for_reg['rev_disp_loyerimput']
data_for_reg['rural'] = 0
data_for_reg['petite_vi | lles'] = 0
data_for_reg['villes_moyennes'] = 0
data_for_reg['grandes_villes'] = 0
data_for_reg['agglo_paris'] = 0
data_for_reg.loc[data_for_reg['strate'] == 0, 'rural'] = 1
data_for_reg.loc[data_for_reg['strate'] == 1, 'petite_villes'] = 1
data_for_reg.loc[data_for_reg['strate'] == 2, 'villes_m... |
pybursa/homeworks | e_tverdokhleboff/hw6/hw6_starter.py | Python | gpl-2.0 | 540 | 0.002304 | #!/usr/bin/env python
# | -*- coding: utf-8 -*-
u"""
Основной скрипт запуска ДЗ.
Данный скрипт призван запускать на выполнение домашнее задание #6.
"""
__author__ = "Elena Sharovar"
__date__ = "2014-11-23"
from hw6_solution1 import modifier
def runner():
u"""Запускает выполнение всех задач"""
print "Modifying file..."
modifi... | a.csv")
print "Modified successfully!"
if __name__ == '__main__':
runner()
|
Groovy-Dragon/tcRIP | ST_pTuple.py | Python | mit | 2,015 | 0.016377 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 4 10:56:51 2017
@author: lewismoffat
This script is focused on statistics, it calculates the most common pTuples
without clipping and with clipping
"""
#==============================================================================
# Module Imports
#=================... | ===========
# Get the data
#==============================================================================
# are we doing the full set
singlePatient=False
# which patient to get data from
patient=['Complete']
chain = "beta"
if singlePatient:
print('Patient: '+patient[0])
delim = ["naiv | e",chain]+patient #other delimiters
else:
print('Patient: All')
delim = ["naive",chain] #other delimiters
seqs, vj = dp.loadAllPatients(delim) # these gets all the sequences and vj values
#==============================================================================
# Clipping the data
#==================... |
xkmato/tracpro | tracpro/polls/migrations/0012_response_status.py | Python | bsd-3-clause | 825 | 0.001212 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def populate_status(apps, schema_editor):
Response = apps.get_model("p | olls", "Response")
for response in Response.objects.all():
response.status = 'C' if response.is_complete else 'E'
response.save(update_fields=('status',))
class Migration(migrations.Migration):
dependencies = [
('polls', '0011_issue_regions'),
]
operations = [
migrati... | tus',
field=models.CharField(default='C', help_text='Current status of this response', max_length=1, verbose_name='Status', choices=[('E', 'Empty'), ('P', 'Partial'), ('C', 'Complete')]),
preserve_default=False,
),
]
|
NaturalSolutions/NsPortal | Back/ns_portal/utils/utils.py | Python | mit | 380 | 0 | from pyramid.security import (
_get_authentication_po | licy
)
def my | _get_authentication_policy(request):
# CRITICAL
# _get_authentication_policy(request)
# this method will return the instanciate singleton object that handle
# policy in pyramid app
# the policy object store keys from conf for generate token
return _get_authentication_policy(request)
|
googleapis/python-translate | samples/snippets/hybrid_glossaries/hybrid_tutorial_test.py | Python | apache-2.0 | 3,065 | 0.000326 | # 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, ... | text_to_speech(text, outfile)
# Assert audio file generated
assert os.path.isfile(outfile)
out, err = capsys.r | eadouterr()
# Assert success message printed
assert "Audio content written to file " + outfile in out
# Delete test file
os.remove(outfile)
|
qingpingguo/git-repo | subcmds/list.py | Python | apache-2.0 | 2,535 | 0.007101 | #
# Copyright (C) 2011 The Android Open Source Project
#
# 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... | ', action='store_true',
help="Display the full work tree path instead of the relative path")
def Execute(self, opt, args):
"""List all projects and the associated directories.
This may be possible to do with 'repo forall', but repo newbi | es have
trouble figuring that out. The idea here is that it should be more
discoverable.
Args:
opt: The options.
args: Positional args. Can be a list of projects to list, or empty.
"""
if not opt.regex:
projects = self.GetProjects(args)
else:
projects = self.FindProjec... |
iamweilee/pylearn | builtin-callable-example-1.py | Python | mit | 767 | 0.018253 | '''
callable º¯Êý, ¿ÉÒÔ¼ì²éÒ»¸ö¶ÔÏóÊÇ·ñÊǿɵ÷ÓõÄ(ÎÞÂÛÊÇÖ±½Óµ÷ÓûòÊÇͨ | ¹ý apply ).
¶ÔÓÚº¯Êý, ·½·¨, lambda º¯Ê½, Àà, ÒÔ¼°ÊµÏÖÁË __call__ ·½·¨µÄÀàʵÀý, Ëü¶¼·µ»Ø True.
'''
def dump(function):
if callable(function):
print function, "is callable"
else:
print function, "is *not* callable"
class A:
def method(self | , value):
return value
class B(A):
def __call__(self, value):
return value
a = A()
b = B()
dump(0) # simple objects
dump("string")
dump(callable)
dump(dump) # function
dump(A) # classes
dump(B)
dump(B.method)
dump(a) # instances
dump(b)
dump(b.method)
'''
×¢ÒâÀà¶ÔÏó (A ºÍ B) ¶¼Êǿɵ÷ÓõÄ... |
plotly/python-api | packages/python/plotly/plotly/validators/splom/marker/line/_widthsrc.py | Python | mit | 465 | 0 | import _plotly_utils.basevalidators
class WidthsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="widthsrc", parent_name="splom.marker.line", **kwargs
):
super(WidthsrcValidator, self).__init__(
plotly_name=plotly_name,
paren | t_name=parent_name,
edit_type=kwargs.pop("edit_type", "no | ne"),
role=kwargs.pop("role", "info"),
**kwargs
)
|
PyCQA/pylint | tests/functional/a/await_outside_async.py | Python | gpl-2.0 | 579 | 0.006908 | # pylint: disable=missing-docstring,unused-variable
import asyncio
async def nested():
return 42
async def main():
nested()
print(await nested()) # This is | okay
def not_async():
print(await nested()) # [await-outside-async]
async def func(i):
return i**2
async def okay_function():
var = [await func(i) for i in range(5)] # This should be okay
# Test nested functions
async def func2():
def inner_func():
await asyncio.sleep | (1) # [await-outside-async]
def outer_func():
async def inner_func():
await asyncio.sleep(1)
|
subhacom/moose-core | tests/python/test_vec.py | Python | gpl-3.0 | 92 | 0 | import moose
foo = moose.Pool('/foo1 | ', 500)
bar = moose.vec('/foo1')
assert len(bar) == | 500
|
sametmax/Django--an-app-at-a-time | ignore_this_directory/django/http/multipartparser.py | Python | mit | 24,849 | 0.001207 | """
Multi-part parsing for file uploads.
Exposes one class, ``MultiPartParser``, which feeds chunks of uploaded data to
file upload handlers for processing.
"""
import base64
import binascii
import cgi
from urllib.parse import unquote
from django.conf import settings
from django.core.exceptions import (
RequestDa... | oundary):
if old_field_name:
# We run this at the beginning of the next loop
# since we cannot be sure a file is complete until
# we hit the next boundary/part of the multipart content.
self.handle_file_complete(old_field_na... | old_field_name = None
try:
disposition = meta_data['content-disposition'][1]
field_name = disposition['name'].strip()
except (KeyError, IndexError, AttributeError):
continue
transfer_encoding = meta... |
brady-vitrano/full-stack-django-kit | fabfile/docs.py | Python | mit | 877 | 0.002281 | from fabric.api import task, local, run
from fabric.context_managers import lcd
import settings
@task(default=True)
def build():
"""
(Default) Build Sphinx HTML documentation
"""
with lcd('docs'):
local('make html')
@task()
def deplo | y():
"""
Upload docs to server
"""
build()
destination = '/usr/share/nginx/localhost/mysite/docs/build/html'
if settings.environment == 'vagrant':
local(" | rsync -avz --rsync-path='sudo rsync' -e 'ssh -p 2222 -i .vagrant/machines/web/virtualbox/private_key -o StrictHostKeyChecking=no' docs/build/html/ %s@%s:%s " % ('vagrant', 'localhost', destination))
elif settings.environment == 'ci':
local("rsync -avz --rsync-path='sudo rsync' -e 'ssh -p 2222 -i /var/go/id_... |
benhoff/reddit_helper | reddit_helper/github.py | Python | gpl-3.0 | 1,071 | 0.002801 | import requests
import datetime
def get_most_recent_commits(github_name, hours_to_go_back=8):
url = 'https://api.github.com/users/{}/events'.format(github_name)
r = requests.get(url)
events = r.json()
push_events = []
for event in events:
if event['type'] == u'PushEvent':
push_... | break
| else:
latest_commit = push_event['payload']['commits'][0]
most_recent_commits[repo_name] = latest_commit
return most_recent_commits
|
nyarasha/firemix | patterns/radial_gradient.py | Python | gpl-3.0 | 7,317 | 0.003553 | # This file is part of Firemix.
#
# Copyright 2013-2016 Jonathan Evans <jon@craftyjon.com>
#
# Firemix 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... | is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# ME | RCHANTABILITY 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 Firemix. If not, see <http://www.gnu.org/licenses/>.
import colorsys
import random
import math
import numpy as np
import ast
fr... |
igoroya/igor-oya-solutions-cracking-coding-interview | crackingcointsolutions/chapter2/exerciseeight.py | Python | mit | 2,720 | 0.003309 | '''
Created on 23 Aug 2017
Loop detection: Given a circular linked list, implement an algorithm
that returns the beginning of the loop
DEFINITION
Circular linked list: A (corrupt) linked list in which a node's next pointer points
to another as to make a loop in the linked list.
EXAMPLE:
Input A -> B -> C -> D -> E -... | f is_circular(my_list):
my_set = set()
node = my_list.head_node
count = 0
while node.next_node is not None:
if (node.cargo, node.next_node.cargo) in my_set:
# indication that may be same, make that "node"
# is referenced before by runnign again
if is_node_in... | y_list, count):
return True, node
my_set.add((node.cargo, node.next_node.cargo))
node = node.next_node
count += 1
return False, None
def is_node_in_list_num_nodes(my_node, my_list, n):
'''
Find is a node is in a list's first N nodes
'''
count = 0
node = m... |
ega1979/ros_book_programs | hello_world.py | Python | bsd-2-clause | 86 | 0 | i | mport rospy
rospy.init_node('hello_world')
rospy.loginfo('Hello World')
rospy.spin() | |
hylom/grrreader | backend/feedfetcher.py | Python | gpl-2.0 | 889 | 0.00225 | #!/usr/bin/python
"feed fetcher"
from db import MySQLDatabase
from fetcher import FeedFetcher
def main():
| db = MySQLDatabase()
fetcher = FeedFetcher()
feeds = db.get_feeds(offset=0, limit=10)
read_count = 10
while len(feeds) > 0:
for feed in feeds:
| fid = feed[0]
url = feed[1]
title = feed[2]
print "fetching #{0}: {1}".format(fid, url)
entries = fetcher.fetch(url)
for entry in entries:
entry.feed_id = fid
try:
print "insert {0}".format(entry.u... |
bongo-project/bongo | src/apps/storetool/bongo/storetool/CalendarCommands.py | Python | gpl-2.0 | 14,791 | 0.003786 | import bongo.external.simplejson as simplejson
import bongo.external.vobject as vobject
import logging
import os
import re
import time
import random
import md5
import email
from email.MIMEText import MIMEText
from email.MIMEMessage import MIMEMessage
from email.MIMEMultipart import MIMEMultipart
from email.Message imp... | md <name> [address, ...]")
def Run(self, options, args):
if len(args) < 1 :
self.print_usage()
self.exit()
doc = "\"/calendars/%s\"" % (args[0])
addresses = args[1:]
store = StoreClient(options.user, options.store)
try:
acl = CalendarAC... | ead)
store.SetACL(doc, acl.GetACL())
finally:
store.Quit()
class CalendarUnpublishCommand(Command):
log = logging.getLogger("Bongo.StoreTool")
def __init__(self):
Command.__init__(self, "calendar-u |
rcarneva/rcarneva.github.io | publishconf.py | Python | mit | 533 | 0.005629 | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ i | mport unicode_literals
# This file is only used if you use `make publish` or
# explicitly specify it as your config file.
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'http://rcarneva.github.io'
RELATIVE_URLS = False
FEED_ALL_ATOM = 'feeds/all.atom.xml'
CATEGORY_FEED_ATOM = 'f... | items are often useful when publishing
#DISQUS_SITENAME = ""
#GOOGLE_ANALYTICS = ""
|
slint/zenodo | zenodo/modules/records/httpretty_mock.py | Python | gpl-2.0 | 2,498 | 0.0004 |
# -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2018 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later ... | import HTTPretty as OriginalHTTPretty
try:
from requests.packages.urllib3.contrib.pyopenssl import \
inject_into_urllib3, extract_from_urllib3
pyopenssl_override = True
except:
pyopenssl_override = False
class MyHTTPretty(OriginalHTTPretty):
"""
HTTPretty mock.
| pyopenssl monkey-patches the default ssl_wrap_socket() function in the
'requests' library, but this can stop the HTTPretty socket monkey-patching
from working for HTTPS requests.
Our version extends the base HTTPretty enable() and disable()
implementations to undo and redo the pyopenssl monkey-patch... |
390910131/Misago | misago/markup/bbcode/blocks.py | Python | gpl-2.0 | 223 | 0 | im | port re
from markdown.blockprocessors import HRProcessor
class BBCodeHRProcessor(HRProcessor):
RE = r'^\[hr\]*'
# Detect hr on any line of a block.
SEARCH_RE = re.compile(RE, re.MULTILINE | | re.IGNORECASE)
|
ianmiell/OLD-shutitdist | bison/bison.py | Python | gpl-2.0 | 1,256 | 0.041401 | """ShutIt module. See http://shutit.tk/
"""
from shutit_module import ShutItModule
class bison(ShutItModule):
def is_installed(self, shutit):
return shutit.file_exists('/root/shutit_build/module_record/' + self.module_id + '/built')
def build(self, shutit):
shutit.send('mkdir -p /tmp/build/bison')
shutit.... | 8844782.0039,
descri | ption='Bison compilation',
maintainer='ian.miell@gmail.com',
depends=['shutit.tk.sd.pkg_config.pkg_config']
)
|
luxus/home-assistant | homeassistant/components/light/rfxtrx.py | Python | mit | 6,729 | 0 | """
Support for RFXtrx lights.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.rfxtrx/
"""
import logging
import homeassistant.components.rfxtrx as rfxtrx
from homeassistant.components.light import ATTR_BRIGHTNESS, Light
from homeassistant.componen... | ".join("{0:02x}".format(x) for x in event.data)
entity_name = "%s : %s" % (device_id, pkt_id)
datas = {ATTR_STATE: False, ATTR_FIREEVENT: False}
signal_repetitions = config.get('signal_repetitions',
SIGNAL_REPETITIONS)
new_light... | S[device_id] = new_light
add_devices_callback([new_light])
# Check if entity exists or previously added automatically
if device_id in rfxtrx.RFX_DEVICES:
_LOGGER.debug(
"EntityID: %s light_update. Command: %s",
device_id,
event.val... |
poldracklab/mriqc | mriqc/classifier/sklearn/__init__.py | Python | bsd-3-clause | 1,178 | 0 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright 2021 The NiPreps Developers <nipreps@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may... | ut
from mriqc.classifier.sklearn.cv_nested import ModelAndGridSearchCV
from mriqc.classifier.sklearn.p | arameters import ModelParameterGrid
__all__ = [
"ModelParameterGrid",
"ModelAndGridSearchCV",
"RobustLeavePGroupsOut",
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.