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
kwss/keystone
keystone/common/wsgi_server.py
Python
apache-2.0
4,979
0.000803
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack LLC # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2010 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (...
self.cert_required = cert_required self.do_ssl = True def kill(self): if self.greenthread: self.greenthread.kill() def wait(self): """Wait until all servers have completed running.""" try: self.pool.waitall() except KeyboardInterrupt: ...
(self, application, socket): """Start a WSGI server in a new green thread.""" log = logging.getLogger('eventlet.wsgi.server') try: eventlet.wsgi.server(socket, application, custom_pool=self.pool, log=wsgi.WritableLogger(log)) except Exception:...
blowekamp/itkBinShrink
Documentation/utils/make_marschner_lobb.py
Python
apache-2.0
2,435
0.014374
#!/bin/env python import SimpleITK as sitk import numpy as np import math import time def marschner_lobb(size=40, alpha=0.25, f_M=6.0): img = sitk.PhysicalPointSource( sitk.sitkVectorFloat32, [size]*3, [-1]*3, [2.0/size]*3) imgx = sitk.Vecto
rIndexSelectionCast(img, 0) imgy = sitk.VectorIndexSelectionCast(img, 1) imgz = sitk.VectorIndexSelectionCast(img, 2) del img r = sitk.Sqrt(imgx**2 + imgy**2) del imgx, imgy pr = sitk.Cos((2.0*math.pi*f_M)*sitk.Cos((math.pi/2.0)*r))
return (1.0 - sitk.Sin((math.pi/2.0)*imgz) + alpha*(1.0+pr))/(2.0*(1.0+alpha)) ml = marschner_lobb(128) zslice = ml.GetSize()[-1]//2 print zslice ml = sitk.Normalize(ml) n = np.random.normal(0, scale=1.0, size=ml.GetSize()) img_noise = sitk.GetImageFromArray(n) img_noise.CopyInformation(ml) resample = sitk.Re...
starsirius/mongoengine
mongoengine/errors.py
Python
mit
3,834
0
from collections import defaultdict from mongoengine.python_support import txt_type __all__ = ('NotRegistered', 'InvalidDocumentError', 'LookUpError', 'DoesNotExist', 'MultipleObjectsReturned', 'InvalidQueryError', 'OperationError', 'NotUniqueError', 'FieldDoesNotExist', 'ValidationE...
within this document or list, or None if the error is for an individual field. """ errors = {} field_name = None _message = None def __init__(self, message="", **kwargs): self.errors = kwargs.get('errors', {}) self.field_name = kwargs.get(
'field_name') self.message = message def __str__(self): return txt_type(self.message) def __repr__(self): return '%s(%s,)' % (self.__class__.__name__, self.message) def __getattribute__(self, name): message = super(ValidationError, self).__getattribute__(name) if n...
ngardamala/the_trembling_info
articles/templatetags/links.py
Python
gpl-2.0
546
0.007326
from django import template from articles.models import Category, Article register = template.Library() # get list of all cate
gories @register.inclusion_tag('links_categories.html') def show_categories(): categories = Category.objects.all() return {'categories': categories} # get list of most popular stories @register.inclusion_tag('links_most_popular.html') def show_most_popular(): # get 7 most popular stories articles = Art...
rue).order_by('-views')[:7] return {'articles': articles}
team-vigir/vigir_footstep_planning_basics
vigir_footstep_planning_widgets/src/vigir_footstep_planning_widgets/pattern_generator_widget.py
Python
gpl-3.0
7,255
0.002343
#!/usr/bin
/env python import math import rospy import tf import std_msgs.msg from rqt_gui_py.plugin import Plugin from python_qt_binding.QtCore import Qt, Slot, QAbstractListModel from python_qt_binding.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout, QCheckB
ox, QLabel, QListWidget, QPushButton, QDoubleSpinBox, QFrame from vigir_footstep_planning_msgs.msg import PatternGeneratorParameters from vigir_footstep_planning_lib.parameter_set_widget import * from vigir_footstep_planning_lib.qt_helper import * from vigir_footstep_planning_lib.logging import * class PatternGenera...
mrquim/repository.mrquim
script.module.exodus/lib/resources/lib/sources/en/dizigold.py
Python
gpl-2.0
4,468
0.013429
# NEEDS FIXING # -*- coding: utf-8 -*- ''' Exodus Add-on 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. ...
[0]), re.sub('&#\d*;','', i[1])) for i in result] result = [(i[0], cleantitle.get(i[1])) for i in result] return result except: return def episode(self, url, imdb, tvdb, title, premiered, season, episode): if url == None: return url = '/%s/%01d-sezon/%...
MLCodes(url) url = url.encode('utf-8') return url def sources(self, url, hostDict, hostprDict): try: sources = [] if url == None: return sources base_url = urlparse.urljoin(self.base_link, url) result = client.request(base_url) ...
yongshengwang/hue
build/env/lib/python2.7/site-packages/nosetty-0.4-py2.7.egg/nosetty/test/nosepassthru.py
Python
apache-2.0
178
0.011236
"""a decoy python script that can be run like `python nosepassthru.py` to test using an executable chain""" if __name__ == '__main__': from nose.core import main main
()
joshbohde/scikit-learn
sklearn/decomposition/nmf.py
Python
bsd-3-clause
16,021
0.00025
""" Non-negative matrix factorization """ # Author: Vlad Niculae # Author: Chih-Jen Lin, National Taiwan University (original projected gradient # NMF implementation) # Author: Anthony Di Franco (original Python and NumPy port) # License: BSD from __future__ import division import warnings import numpy as np fro...
ormal random variates. Default: None eps: Truncate all values less then this in output to zero. random_state: numpy.RandomState | int, optional The generator used to fill in the zeros, when using variant='ar' Default: numpy.random Returns ------- (W, H): I...
in C. Boutsidis, E. Gallopoulos: SVD based initialization: A head start for nonnegative matrix factorization - Pattern Recognition, 2008 http://www.cs.rpi.edu/~boutsc/files/nndsvd.pdf """ if (X < 0).any(): raise ValueError("Negative values in data passed to initialization") if varia...
vbuell/python-javaobj
javaobj.py
Python
apache-2.0
31,597
0.003007
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribu...
== other.flags and self.fields_names == other.fields
_names and self.fields_types == other.fields_types and self.superclass == other.superclass) class JavaObject(object): def __init__(self): self.classdesc = None self.annotations = [] def get_class(self): return self.classdesc def __str__(self): ...
dimagi/commcare-hq
corehq/tabs/templatetags/menu_tags.py
Python
bsd-3-clause
4,847
0.000413
from corehq.apps.users.models import DomainMembershipError from django import template from django.template.loader import render_to_string from corehq.tabs.config import MENU_TABS from corehq.tabs.exceptions import TabClassError, TabClassErrorSummary from corehq.tabs.extension_points import uitab_classes from corehq.t...
end(uitab_classes()) for tab_class in tab_classes: try: tab = tab_class( request, domain=domain, couch_user=couch_user, project=project) except TabClassError as e: instantiation_errors.append(e) else: all_tabs.append(tab) ...
rrors: messages = ( '- {}: {}'.format(e.__class__.__name__, str(e)) for e in instantiation_errors ) summary_message = 'Summary of Tab Class Errors:\n{}'.format('\n'.join(messages)) raise TabClassErrorSummary(summary_message) else: return all_tabs cla...
scottdanesi/earthshaker-aftershock
procgame/fakepinproc.py
Python
gpl-3.0
7,383
0.033862
import time import pinproc import Queue from game import gameitems class FakePinPROC(object): """Stand-in class for :class:`pinproc.PinPROC`. Generates DMD events.""" last_dmd_event = 0 frames_per_second = 60 drivers = gameitems.AttrCollection() switch_events = [] switch_rules = [{'notifyHost':False, 'dri...
when to process an event def switch_get_states(self, *args): """ Method to provide current simulator switch states. """ return self._states def get_events(self): # Populate the events list from our fakepinproc DMD events, etc events = super(FakePinPROCPlayback, self).get_events() # Mark down the cu...
imulator_time() # Loop through all events that we should execute now while len(self._event_timestamps) > 0 and self._event_timestamps[0] <= current_time: evt = self._events[self._event_timestamps[0]] print "[%s] [%s] Firing switch %s" % (str(current_time),str(self._event_timestamps[0]), evt['swname']) # ...
FedeMPouzols/Savu
savu/data/data_structures/data_notes.py
Python
gpl-3.0
7,157
0.00014
# Copyright 2015 Diamond Light Source Ltd. # # 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 t...
* represents the set of indices specified by: >>> indices = range(start, stop[, step]) For more information see :func:`range` **start:stop:step:chunk (chunk > 1)** represents the set of indices specified by: >>> a = np.tile(np.a...
>>> indices = np.ravel(np.transpose(a + b)) Chunk indicates how many values to take around each value in ``range(start, stop, step)``. It is only available for slicing dimensions. .. warning:: If any indices are out of range (or negative) ...
herilalaina/scikit-learn
sklearn/metrics/pairwise.py
Python
bsd-3-clause
46,964
0.000043
# -*- coding: utf-8 -*- # Authors: Alexandre Gramfort <[email protected]> # Mathieu Blondel <[email protected]> # Robert Layton <[email protected]> # Andreas Mueller <[email protected]> # Philippe Gervais <[email protected]> # Lars Buitinck ...
not the most precise way of doing this computation, and the distance matrix returned by this function may not be exactly symmetric as required by, e.g., ``scipy.spatial.distance`` functions.
Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples_1, n_features) Y : {array-like, sparse matrix}, shape (n_samples_2, n_features) Y_norm_squared : array-like, shape (n_samples_2, ), optional Pre-computed dot-product...
RPGOne/Skynet
scikit-learn-0.18.1/examples/exercises/plot_cv_diabetes.py
Python
bsd-3-clause
2,861
0.002447
""" =============================================== Cross-validation on diabetes Dataset Exercise =============================================== A tutorial exercise which uses cross-validation with linear models. This exercise is used in the :ref:`cv_estimators_tut` part of the :ref:`model_selection_tut` section of ...
[:1
50] lasso = Lasso(random_state=0) alphas = np.logspace(-4, -0.5, 30) scores = list() scores_std = list() n_folds = 3 for alpha in alphas: lasso.alpha = alpha this_scores = cross_val_score(lasso, X, y, cv=n_folds, n_jobs=1) scores.append(np.mean(this_scores)) scores_std.append(np.std(this_scores)) s...
French77/osmc
package/mediacenter-addon-osmc/src/script.module.osmcsetting.services/resources/lib/osmcservices/__init__.py
Python
gpl-2.0
279
0
# -*- coding: utf-8 -*- """ Copyright (C) 2014-2020 OSMC (KodeKarnage) This f
ile is part of script.module.osmcsetting.services SPDX-License-Identifier: GPL-2.0-or-later See LICENSES/GPL-2.0-or-later for more information. """ __all__ = ['service
s_gui', 'osmc']
quora/qcore
qcore/enum.py
Python
apache-2.0
12,142
0.001235
# Copyright 2016 Quora, 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, so...
_all__ = ["Enum", "EnumType", "EnumValueGenerator", "Flags", "IntEnum"] import inspect import sys from . import helpers from . import inspection _no_default = helpers.MarkerObject("no_default @ enums") class EnumType(type): """Metaclass for all enum types.""" def __init__(cls, what, bases=None, dict=None)...
: return len(self._members) def __iter__(self): return iter(self._members) def __call__(self, value, default=_no_default): """Instantiating an Enum always produces an existing value or throws an exception.""" return self.parse(value, default=default) def process(self): ...
hpe-storage/python-lefthandclient
test/test_HPELeftHandClient_system.py
Python
apache-2.0
1,222
0
# (c) Copyright 2015 Hewlett Packard Enterprise Development LP # # 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...
): super(HPELeftHandClientSystemTestCase, self).tearDown() def test_1_get_api_versi
on(self): self.printHeader('get_api_version') version = self.cl.getApiVersion() self.assertTrue(version is not None) self.printFooter('get_api_version')
tschaume/ccsgp_get_started
ccsgp_get_started/examples/gp_ptspec.py
Python
mit
10,339
0.025728
import logging, argparse, os, sys, re import numpy as np from collections import OrderedDict from .utils import getWorkDirs, getEnergy4Key from ..ccsgp.ccsgp import make_panel, make_plot from ..ccsgp.utils import getOpts from ..ccsgp.config import default_colors from decimal import Decimal import uncertainties.umath as...
4} %g' % ( Decimal(yscale[energy])#.as_tuple().exponent ) ]) if data_type == 'data' else '' # use mass range in dict key to sort dpt_dict with increasing mass plot_key_order = dpt_dict.keys() plot_key_order.sort(key=lambda x: float(x.split(':')[1].split('-')[0])) # so
rt data_avpt by energy and apply x-shift for better visibility for k in data_avpt: data_avpt[k].sort(key=lambda x: x[0]) energies = [ dp[0] for dp in data_avpt[mee_keys[0]] ] energies.append(215.) # TODO: think of better upper limit linsp = {} for start,stop in zip(energies[:-1],energies[1:]): linsp[start...
tgquintela/TimeSeriesTools
TimeSeriesTools/Measures/information_theory_measures.py
Python
mit
9,838
0.001728
""" Information theory measures --------------------------- Collection of measures which uses the Information Theory. """ import numpy as np import scipy from ..utils.sliding_utils import sliding_embeded_transf from ..utils.fit_utils import general_multiscale_fit ##################################################...
me series between its frequency spectrum space. Parameters ---------- X : array_like, shape(N,) a 1-D real time series. bins : int number of bins in which we want to discretize the frequency spectrum space in order to compute the entropy. Returns ------- H_sp : floa...
ber of bins!!!!!!!!!!!!!!!! """ # Power spectral ps = np.abs(np.fft.fft(X))**2 # binning: psd, freq = np.histogram(ps, bins, normed=True) # Compute entropy (?) H_sp = - np.sum(psd * np.log2(psd+1e-16))/np.log2(psd.shape[0]) H_sp = float(H_sp) return H_sp ###########################...
bobsilverberg/oneanddone
oneanddone/users/tests/test_mixins.py
Python
mpl-2.0
2,289
0.000874
# 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/. from django.core.exceptions import PermissionDenied from mock import Mock, patch from nose.tools import eq_, raises fro...
""" request = Mock() request.user = UserFactory.create() with patch('one
anddone.users.mixins.redirect') as redirect: eq_(self.view.dispatch(request), redirect.return_value) redirect.assert_called_with('users.profile.create')
beeftornado/sentry
tests/sentry/api/test_paginator.py
Python
bsd-3-clause
23,706
0.001012
from __future__ import absolute_import from datetime import timedelta from django.utils import timezone from unittest import TestCase as SimpleTestCase from sentry.api.paginator import ( BadPaginationError, Paginator, DateTimePaginator, OffsetPaginator, SequencePaginator, GenericOffsetPaginato...
from sentry.utils.cursors import Cursor class PaginatorTest(TestCase): cls = Paginator def test_max_limit(self): self.create_u
ser("[email protected]") self.create_user("[email protected]") self.create_user("[email protected]") queryset = User.objects.all() paginator = self.cls(queryset, "id", max_limit=10) result = paginator.get_result(limit=2, cursor=None) assert len(result) == 2 paginator...
yerkesobservatory/seo
routines/ch.py
Python
gpl-3.0
48,676
0.000616
"""CALLHORIZONS - a Python interface to access JPL HORIZONS ephemerides and orbital elements. This module provides a convenient python interface to the JPL HORIZONS system by directly accessing and parsing the HORIZONS website. Ephemerides can be obtained through get_ephemerides, orbital elements through get_elements....
01) Einstein 2001 2001 AT1 2001 AT1 (1714) Sy 1714 1714 SY 1714 SY # Note the near-confusion with (1714) 2014 MU69 2014 MU69 2017 AA 2017 AA """ import re pat = ('^(([1-9][0-9]*( [A-Z]{1,2}([1-9][0-9]{0,...
return None else: if len(m[0][5]) > 0: return m[0][5] else: return m[0][0] def isorbit_record(self): """`True` if `targetname` appears to be a comet orbit record number. NAIF record numbers are 6 digits, begin with a '9' ...
devonjones/PSRD-Parser
src/psrd/spell_lists.py
Python
gpl-3.0
5,140
0.028599
import os import json import re from BeautifulSoup import BeautifulSoup from psrd.rules import write_rules from psrd.files import char_replace from psrd.universal import parse_universal, print_struct from psrd.sections import ability_pass, is_anonymous_section, has_subsections, entity_pass, quote_pass def core_structu...
comps = "" if soup.find('sup'): sup = soup.find('sup') comps = sup.renderContents() sup.replaceWith('') if comps.find(",") > -1: comps = [c.strip() for c in comps.split(",")] else: comps = list(comps) desc = ''.join(soup.findAll(text=True)) if desc.startswith(":"): desc = desc[1:].strip() spell ...
c.replace("&rdquo;", '"') desc = desc.replace("&ndash;", '-') spell['description'] = desc if len(comps) > 0: spell['material'] = comps if school: spell['school'] = school if descriptor: spell['descriptor'] = descriptor return spell def parse_spell_lists(filename, output, book): struct = parse_universal(...
HopeFOAM/HopeFOAM
ThirdParty-0.1/ParaView-5.0.1/VTK/Examples/Infovis/Python/tables4.py
Python
gpl-3.0
1,335
0.003745
#!/usr/bin/env python """ This file provides a more advanced example of vtkTable access and manipulation methods. """ from __future__ import print_function from vtk import * #------------------------------------------------------------------------------ # Script Entry Point (i.e., main() ) #--------------------------...
ce.SetHaveHeaders(True) csv_source.SetFileName("table_data.csv"
) csv_source.Update() csv_source.GetOutput().Dump(6) T = csv_source.GetOutput() # Print some information about the table print("Number of Columns =", T.GetNumberOfColumns()) print("Number of Rows =", T.GetNumberOfRows()) print("Get column 1, row 4 data: ", T.GetColumn(1).GetValue(4)) ...
NetApp/manila
manila/tests/db/test_api.py
Python
apache-2.0
2,190
0
# Copyright (c) Goutham Pacha Ravi. # 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 requir...
mock_method_call = self.mock_object(db_api, interface) # kwargs always specify defaults, ignore them in the signature. args = filter(
lambda x: x != 'kwargs', method.__code__.co_varnames) method(*args) self.assertTrue(mock_method_call.called)
Asurada2015/TFAPI_translation
framework_ops/Utility functions/tf_name_scope.py
Python
apache-2.0
401
0.005935
""" def name_scope(name, default_name=None, values=None): Wrapper for Graph.name_s
cope() using the default graph. 使用默认图包装“Graph.name_scope() See Graph.name_scope() for more detai
ls. Args: name: A name for the scope. Returns: A context manager that installs name as a new name scope in the default graph. 在默认图中安装名称作为一个新名称范围的内容管理器 """
tensorflow/examples
lite/examples/speech_commands/ml/export/convert_keras_to_quantized.py
Python
apache-2.0
6,406
0.004527
# Copyright 2019 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...
graph_def(), output_fld, f, as_text=True) print('saved the graph d
efinition in ascii format at: ', str(Path(output_fld) / f)) # convert variables to constants and save # In[ ]: if args.quantize: # graph_transforms will not be available for future versions. from tensorflow.compat.v1.tools.graph_transforms import TransformGraph # pylint: disable=g-import-not-at-top tr...
Retzudo/manufactorum
manage.py
Python
agpl-3.0
1,443
0
#!/usr/bin/env python3 import sys import pytest from flask.ext.script import Manager from manufactorum import app from manufactorum import users from getpass import getpass manager = Manager(app) @manager.option( '-h', '--host', dest='host', default='127.0.0.1'
) @manager.option( '-p', '--port', dest='port', default='5000' ) @manager.option( '--no-debug', dest='no_debug', action='store_true', help='Disable debugging mode' ) def run(host='127.0
.0.1', port=5000, no_debug=False): app.run(host=host, port=int(port), debug=(not no_debug)) @manager.command def add_admin(): username = input('Username: ') password = getpass('Password: ') password_repeat = getpass('Repeat: ') if password == password_repeat: try: users.add_us...
pykello/hdb
launch-hdb.py
Python
bsd-2-clause
2,162
0.000463
#!/usr/bin/env python import argparse import os import socket import sys import time from hdb import client from hdb import main import json from daemon import Daemon class HDBDaemon(Daemon): def run(self): main.main(self.args) def set_args(self, args): self.args = args def is_port_open(a...
int) parser.add_argument('rel_count_max', action='store', type=int) args = parser.parse_args() instance_count = args.instance_count node_count_max = args.node_count_max rel_count_max = args.rel_count_max port = 5430 ports = [] for i in range(instance_count): port = find_ope...
rr='/tmp/hdb.err', stdout='/tmp/hdb.out') daemon.set_args(['main.py', str(port), str(node_count_max), str(rel_count_max)]) daemon.start() else: sys.stdout.write("%d\n" % (port,)) sys.stdout.flush() ports.append(port) ...
tysonclugg/django
tests/generic_views/test_dates.py
Python
bsd-3-clause
35,527
0.003124
import datetime from django.core.exceptions import ImproperlyConfigured from django.test import TestCase, override_settings, skipUnlessDBFeature from django.test.utils import requires_tz_support from django.utils import timezone from .models import Artist, Author, Book, BookSigning, Page def _make_books(n, base_dat...
ts.all())) self.assertTemplateUsed(res, 'generic_views/book_archive.html') def test_archive_view_context_object_name(self): res
= self.client.get('/dates/books/context_object_name/') self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context['date_list']), list(Book.objects.dates('pubdate', 'year', 'DESC'))) self.assertEqual(list(res.context['thingies']), list(Book.objects.all())) self.assertNotIn(...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_05_01/aio/operations/_security_rules_operations.py
Python
mit
22,467
0.004896
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
security_group_name, 'str'), 'securityRuleName': se
lf._serialize.url("security_rule_name", security_rule_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_paramete...
Zlash65/erpnext
erpnext/patches/v11_0/set_default_email_template_in_hr.py
Python
gpl-3.0
297
0.023569
from __future__ import unicode_literals import frappe def execute(): hr_settings = frappe.get
_single("HR Settings") hr_settings.leave_approval_notification_tem
plate = "Leave Approval Notification" hr_settings.leave_status_notification_template = "Leave Status Notification" hr_settings.save()
MDA2014/django-xpand
django_project/django_project/urls.py
Python
mit
439
0.009112
fro
m django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'django_project.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', include('apps.home.urls', namespace='home', app_name='home')), url(r'^...
n/', include(admin.site.urls)), )
CallmeTorre/RicePanel
ricepanel/manage.py
Python
apache-2.0
252
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ricepanel.se
ttings") from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
keon/algorithms
algorithms/strings/__init__.py
Python
mit
1,248
0.000801
from .add_binary import * from .breaking_bad import * from .decode_string import * from .delete_reoccurring import * from .domain_extractor import * from .encode_decode import * from .group_anagrams import * from .int_to_roman import * from .is_palindrome import * from .is_rotated import * from .license_number import *...
.unique_morse import * from .judge_circle import * from .strong_password import * from .caesar_cipher import * fro
m .check_pangram import * from .contain_string import * from .count_binary_substring import * from .repeat_string import * from .text_justification import * from .min_distance import * from .longest_common_prefix import * from .rotate import * from .first_unique_char import * from .repeat_substring import * from .atbas...
hlzz/dotfiles
graphics/VTK-7.0.0/ThirdParty/Twisted/twisted/protocols/ident.py
Python
bsd-3-clause
7,930
0.002144
# -*- test-case-name: twisted.test.test_ident -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Ident protocol implementation. """ import struct from twisted.internet import defer from twisted.protocols import basic from twisted.python import log, failure _MIN_PORT = 1 _...
).addCallback(self._cbLookup, portOnServer, portOnClient ).addErrback
(self._ebLookup, portOnServer, portOnClient ) def _cbLookup(self, (sysName, userId), sport, cport): self.sendLine('%d, %d : USERID : %s : %s' % (sport, cport, sysName, userId)) def _ebLookup(self, failure, sport, cport): if failure.check(IdentError): self.send...
markgw/pimlico
src/python/pimlico/modules/spacy/__init__.py
Python
gpl-3.0
278
0.007194
"""spaCy Run spaCy tools and pipelines on
your datasets. Currently only includes tokenization, but this could be expanded to include many more of spaCy's tools. Or, if you want a different tool/pipeline, you could create your own module type following the same appr
oach. """
crakama/bc_7_twitment
keys.py
Python
mit
156
0.012821
Alchemy sentiment ana
lysis: fb12d2c55fff36e1e268584e261b6b010b37279f Africa Is Talking: 676dbd926bbb04fa69ce90ee81d3f5ffee2692aaf80eb5793bd70fe9
3e77dc2e
MichaelCoughlinAN/Odds-N-Ends
Python/test_server.py
Python
gpl-3.0
376
0.005319
#!/usr/bin/env python import socket TCP_IP = '' TCP_PORT = 5005 BUFFER_SIZE = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((TCP_IP, TCP_PORT)) s.listen(1) conn, addr = s.accept() print 'Starting' print 'Connection address:', addr while 1: data = conn.recv(BUFF
ER_SIZE) if not data: break print
"Frame received: " + data conn.close()
aebarber/ScriptToolbox
server-management/media-server/genoggrefs.py
Python
mit
1,117
0.005372
#!/usr/bin/env python import os import sys def createOggDir (artistDirectory): oggdir = os.path.join(artistDirectory, 'ogg') if os.path.isdir(oggdir): return True else: if os.path.exists(oggdir): return False else: print("creating directory" + oggdir) ...
for root, directories, filenames in os.walk(artistDirectory): for directory in directories: if directory == 'ogg': if createOggDir(artistDirectory): sourceDirectory = os.path.join(os.p
ath.abspath(root), directory) targetOggDirectory = os.path.join(artistDirectory, 'ogg') targetLinkName = os.path.basename(os.path.normpath(root)) targetLink = os.path.join(targetOggDirectory, targetLinkName) if not os.path.islink(targetLink...
herilalaina/scikit-learn
sklearn/metrics/cluster/supervised.py
Python
bsd-3-clause
31,399
0.000159
"""Utilities to evaluate the clustering performance of models. Functions named as *_score return a scalar value to maximize: the higher the better. """ # Authors: Olivier Grisel <[email protected]> # Wei LI <[email protected]> # Diego Molla <[email protected]> # Arnaud Fouchet ...
luster. # These are perfect matches hence return 1
.0. if (n_classes == n_clusters == 1 or n_classes == n_clusters == 0 or n_classes == n_clusters == n_samples): return 1.0 # Compute the ARI using the contingency data contingency = contingency_matrix(labels_true, labels_pred, sparse=True) sum_comb_c = sum(comb2(n_c) for ...
m8ttyB/socorro
webapp-django/crashstats/home/tests/test_views.py
Python
mpl-2.0
2,682
0
from nose.tools import eq_, ok_ from django.core.urlresolvers import reverse from django.conf import settings from crashstats.crashstats.tests.test_views import BaseTestViews class TestViews(BaseTestViews): def test_home(self): url = reverse('home:home', args=('WaterWolf',)) response = self.cli...
ts/WaterWolf' # some legacy URLs have this url += '/versions/' redirect_code = settings.PERMANENT_LEGACY_REDIRECTS and 301 or 302 destination = reverse('home:home', args=['WaterWolf']) response = self.client.get(url) eq_(response.status_code, redirect_code) inte...
eq_(response.status_code, redirect_code) ok_(destination in response['Location'], response['Location']) def test_home_400(self): url = reverse('home:home', args=('WaterWolf',)) response = self.client.get(url, {'days': 'xxx'}) eq_(response.status_code, 400) ok_('Enter a whol...
rado0x54/project-euler
python/problem0027.py
Python
mit
1,182
0.002538
#!/usr/bin/env python3 """Project Euler - Problem 27 Module""" def problem27(ab_limit): """Prob
lem 27 - Quadratic primes""" # upper limit nr_primes = 2 * ab_limit * ab_limit + ab_limit primes = [1] * (nr_primes - 2) result = 0 for x in range(2, nr_primes): if primes[x - 2] == 1: # x is Prime, eliminate x*y for y > 1 y = (x - 2) + x while y < nr_pri...
# Largest seq l_seq = 0 for a in range(-ab_limit + 1, ab_limit): for b in range(2, ab_limit): if primes[b - 2] == 0: continue # no prime # check formula seq = 1 x = 2 while True: v = (x**2) + (a * x) + b ...
leki75/ansible
lib/ansible/module_utils/asa.py
Python
gpl-3.0
5,158
0.003102
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete wo...
if line:
commands.add(line.strip().split()[0]) if 'all' in commands: return 'all' else: return 'full'
apmichaud/vitess-apm
py/vtdb/topology.py
Python
bsd-3-clause
6,219
0.011417
# Copyright 2013, 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. # Give a somewhat sane API to the topology, using zkocc as the backend. # # There are two main use cases for the topology: # 1. resolve a "db key" into a set of par...
isting <keyspace>.<shard>.<db_type> # - optionally, a list of all existing endpoints: # <keyspace>.<shard>.<db_type>.<instance_id> def read_topology(zkocc_client, read_fqdb_keys=True): fqdb_keys = [] db_keys = [] keyspace_list = zkocc_client.get_srv_keyspace_names('local') # validate step if len(keyspace_li...
.topo_empty_keyspace_list() raise Exception('zkocc returned empty keyspace list') for keyspace_name in keyspace_list: try: ks = keyspace.read_keyspace(zkocc_client, keyspace_name) __set_keyspace(ks) for shard_name in ks.shard_names: for db_type in ks.db_types: db_key_parts ...
offbye/PiBoat
pyboat/socket_client.py
Python
apache-2.0
525
0
#!/usr/bin/python # -*- encoding: UTF-8 -*- # BoatServer created on 15/8/21 下午3:15 # Copyright 2014 [email protected] """ """ __author
__
= ['"Xitao":<[email protected]>'] from socket import * host = '172.19.3.18' port = 9999 bufsize = 1024 addr = (host, port) client = socket() client.connect(addr) while True: data = raw_input() if not data or data == 'exit': break client.send('%s\r\n' % data) data = client.recv(bufsize) if n...
pgmpy/pgmpy
docs/conf.py
Python
mit
10,230
0.000587
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # pgmpy documentation build configuration file, created by # sphinx-quickstart on Tue Aug 30 18:17:42 2016. # # 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 # auto...
"analytics_id": "UA-177825880-1"} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. # "<project> v<release> documentation" by default. # html_title = 'pgmpy v0.1.2' # A shorter title for the navigation bar. Default is the...
ve to this directory) to place at the top # of the sidebar. # html_logo = "logo.png" # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custo...
Mango/mango-python
pymango/resources.py
Python
mit
4,129
0.000969
""" Mango Python Library Resources """ import pymango from .client import req from .error import InvalidApiKey class Resource(): """Mango Resource base class""" name = None def __init__(self): if not pymango.api_key: raise InvalidApiKey @classmethod def get_endpoint(cls): ...
t with a dictionary with the resource representation """ return req(pymango.api_key,
"get", cls.get_endpoint(), params=kwargs) class ResourceCreatable(Resource): @classmethod def create(cls, **kwargs): """ Create a Charge :param kwargs: Any optional argument accepted by the Charge resource :return: Dictionary with Charge representation """ retu...
AGMMGA/EM_scripts
EM_scripts/tests/Mass_rename_micrographs_argparse_tests.py
Python
gpl-2.0
12,315
0.009419
import glob import os from pprint import pprint import shlex import shutil import sys import tempfile import unittest from unittest.mock import patch # from context.EM_scripts import Micrograph_renamer as m from scripts_EM.Mass_rename_micrographs_argparse import Micrograph_renamer as m class test_rename_files(unitt...
lf.frame_suffix) with patch('sys.argv', testargs.split()): obj = m() frames, integrated = obj.find_mrc_files(obj.input_dir, obj.EPU_image_pattern, obj.frames_suffix)
obj.rename_files(frames, integrated) missing_frames = len(glob.glob(os.path.join(self.tempdir, 'missing_frames', '*.mrc'))) orphan_frames = len(glob.glob(os.path.join(self.tempdir, 'orphan_frames', '*.mrc'))) orphan_images = len(glob.glob(os.path.join(self.tempdir, 'orphan_integrated'...
nburn42/tensorflow
tensorflow/python/grappler/graph_placer.py
Python
apache-2.0
4,478
0.007816
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ensorflow.python.framework import ops as tf_ops from tensorflow.python.grappler import cluster as gcluster from tensorflow.python.grappler import hierarchical_controller from tensorflow.python.grappler import item as gitem from tensorflow.python.grappler import tf_optimizer from tensorflow.python.training import traini...
tagraph. Args: metagraph: the metagraph to place. cluster: an optional set of hardware resource to optimize the placement for. If none is specified, we'll optimize the placement for the hardware available on the local machine. allotted_time: the maximum amount to time in seconds to spend opti...
mornsun/javascratch
src/topcoder.py/LC_375_Guess_Number_Higher_or_Lower_II.py
Python
gpl-2.0
2,229
0.010777
#!/usr/bin/env python #coding=utf8 ''' We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I'll tell you whether the number I picked is higher or lower. However, when you guess a particular number x, and you guess w...
ni print i,i+k,'=',mini mini = min(f[1][n-1], f[0][n-2]) for x in xrange(1, n-1): mini = min(mini, max(f[0][x-1], f[x+1][n-1]) ) f[0][n-1] = mini return f[0][n-1] if __name__ == '__main__': solution = Solution() start_time = datetime.datetime.now()...
atetime.now() - start_time print 'elapsed:', elapsed.total_seconds()
jeremiahyan/odoo
addons/calendar/tests/test_event_recurrence.py
Python
gpl-3.0
30,782
0.001364
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.exceptions import UserError import pytz from datetime import datetime, date from dateutil.relativedelta import relativedelta from odoo.tests.common import TransactionCase class TestRecurrentEvents(Transactio...
, 27, 8, 0), datetime(2020, 2, 29, 18, 0)), ]) def test_monthly_count_by_date_31(self): self.event._apply_recurrence_values({ 'rrule_type': 'monthly', 'interval': 1, 'month_by': 'date', 'day': 31, 'end_type': 'count', 'count': ...
ids self.assertEqual(len(events), 3, "It should have 3 events in the recurrence") self.assertEventDates(events, [ (datetime(2019, 10, 31, 8, 0), datetime(2019, 11, 2, 18, 0)), # Missing 31th in November (datetime(2019, 12, 31, 8, 0), datetime(2020, 1, 2, 18, 0)), ...
doismellburning/django
tests/delete/tests.py
Python
bsd-3-clause
15,685
0.000638
from __future__ import unicode_literals from math import ceil from django.db import models, IntegrityError, connection from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE from django.test import TestCase, skipUnlessDBFeature, skipIfDBFeature from django.utils.six.moves import range from .models import...
T.objects.create(pk=2, s=s2) r.delete() self.assertEqual( pre_delete_order, [(T, 2), (T, 1), (S, 2), (S, 1), (R, 1)] ) self.assertEqual( post_delete_order, [(T, 1), (T, 2), (S, 1), (S, 2), (R, 1)] ) models.signals.post_delete.disconnect(log_post...
bwhmather/json-config-parser
jsonconfigparser/tests/__init__.py
Python
bsd-3-clause
6,075
0
import unittest import tempfile from jsonconfigparser import JSONConfigParser, NoSectionError, ParseError class JSONConfigTestCase(unittest.TestCase): def test_init(self): JSONConfigParser() def test_read_string(self): cf = JSONConfigParser() cf.read_string(( '[section]\...
cf.set('section', 'set', 'set-normally') self.assertTr
ue(cf.has_option('section', 'set'), msg="has option should return True if option is set \ normally") cf.set(cf.default_section, 'default', 'set-in-defaults') self.assertTrue(cf.has_option('section', 'default'), msg="has_option...
pedro2555/vatsim-status-proxy
setup.py
Python
gpl-2.0
995
0.021106
""" VATSIM Status Proxy. Copyright (C) 2017 - 2019 Pedro Rodrigues <[email protected]> VATSIM Status Proxy 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, version 2 of the License. VATSIM Status Pr...
re details. You should have received a copy of the GNU General Pu
blic License along with VATSIM Status Proxy. If not, see <http://www.gnu.org/licenses/>. """ from setuptools import setup, find_packages setup( name='VATSIM Status Proxy', version='1.0', description = 'VATSIM Status Proxy', author = 'Pedro Rodrigues', author_email = '[email protected]', packag...
theo-l/django
django/core/serializers/xml_serializer.py
Python
bsd-3-clause
16,785
0.00143
""" XML serializer. """ from xml.dom import pulldom from xml.sax import handler from xml.sax.expatreader import ExpatParser as _ExpatParser from django.apps import apps from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.core.serializers import base from django.db import...
attrs['pk'] = str(obj_pk) self.xml.startElement("object", attrs) def end_object(self, obj): """ Called after handling all fields for an object. """ self.indent(1) self.xml.endElement("object") def handle_field(self, obj, field): """ Handle e...
bject (except for ForeignKeys and ManyToManyFields). """ self.indent(2) self.xml.startElement('field', { 'name': field.name, 'type': field.get_internal_type(), }) # Get a "string version" of the object's data. if getattr(obj, field.name) i...
aymeric-spiga/planetoplot
bin/asciiplot.py
Python
gpl-2.0
1,508
0.031167
#! /usr/bin/env python import ppplot import numpy as np from optparse import OptionParser ### TBR by argparse # inputs and options parser = OptionParser() parser.usage = \ ''' asciiplot.py [options] text file(s) -- default is col2 for field and col1 for coord -- this can be set with -x and -y options (or use --swap...
ot.plot1d() # for all input files count = 0 for fff in args: # transfer options to plot object pl.transopt(opt,num=count) # load data var = np.transpose(np.loadtxt(fff,skiprows=opt.skiprows)) # get coord if len(var.shape) == 1: pl.f = var pl.x = None # important for chained plots elif opt.uniq...
t ppplot.show()
octavioturra/aritial
google_appengine/google/appengine/api/datastore.py
Python
apache-2.0
85,194
0.006526
#!/usr/bin/env python # # Copyright 2007 Google 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 o...
) rpc.wait() rpc.check_success() return response def CreateRPC(service='datastore_v3', deadline=None, callback=None, read_policy=STRONG_CONSISTENCY): """Create an rpc for use in configuring datastore calls. Args: deadline: float, deadline for calls in seconds. callback: callable, a ca...
ment: the returned rpc. read_policy: flag, set to EVENTUAL_CONSISTENCY to enable eventually consistent reads Returns: A datastore.DatastoreRPC instance. """ return DatastoreRPC(service, deadline, callback, read_policy) class DatastoreRPC(apiproxy_stub_map.UserRPC): """Specialized RPC for the da...
gniezen/n3pygments
swlexers/__init__.py
Python
bsd-2-clause
13,819
0.011578
# -*- coding: utf-8 -*- """ pygments.lexers.sw ~~~~~~~~~~~~~~~~~~~~~ Lexers for semantic web languages. :copyright: 2007 by Philip Cooper <[email protected]>. :license: BSD, see LICENSE for more details. Modified and extended by Gerrit Niezen. (LICENSE file described above is mis...
# | "@has" expression # | "
@is" expression "@of" # | expression include('whitespaces'), (r';', Punctuation), (r'(<=|=>|=|@?a(?=\s))', Operator, 'objectList'), (r'\.', Punctuation, '#pop'), (r'\]', Punctuation, '#pop'), (r'(?=\})', Text, '#pop'), ...
superzerg/TCD1304AP_teensy2pp
read_pixels.py
Python
gpl-3.0
2,341
0.032465
#!/usr/bin/python3 -i import serial # if you have not already done so from time import sleep import matplotlib.pyplot as plt import re import datetime import numpy import pickle class DataExtruder: def __init__(self,port='/dev/ttyACM0',baudrate=115200): self.pattern_pixels=re.compile(r'data=(?P<pixels>[\w ]*)...
re=plt.figure(figsize=[20,8]) self.figure.show() self.figure_axe=self.figure.gca() def acquire(self,plot=True): if self.ser is None: self.ser=serial.Serial(self.port, self.baudrate) else: print('serial connection alredy opened') print('starting acquisition, press Ctrl+C to stop.') ...
pixels_ascii=m.group('pixels'); i=0 npixel=0 while i+1<len(pixels_ascii): if pixels_ascii[i]==' ': if pixels_ascii[i+1]==' ': pixels_num.append(-1) i=i+2 else: print('ERROR reading pixel') ...
cpacia/python-libbitcoinclient
obelisk/__init__.py
Python
agpl-3.0
423
0.009456
from binary import * from bitcoin import * from client import * from models import * from transaction import * from zmqbase import MAX_UINT32 from twisted.internet import reactor def select_network(network):
import config if "test" in network.lower(): config.chain = config.testnet_chain else: config.chain = config.mainnet_chain def start(): reactor.run() def stop
(): reactor.stop()
kbrannan/PyHSPF
src/pyhspf/core/hspfplots.py
Python
bsd-3-clause
89,979
0.033619
# HSPF Model Plot Routines # # David J. Lampert, PhD, PE # # Last updated: 10/16/2013 # # Purpose: Lots of routines here to generate images for development of an HSPF # model. Descriptions below. # from matplotlib import pyplot, gridspec, path, patches, ticker, dates from calendar import isleap from scipy impor...
wateryear] return wateryear, watervalues def monthofyear(dates, values): """Returns the month of the water year average for the timeseries.""" if len(values) > 12: watervalues = [average([values[j] for j in range(i, len(values), 12)]) for i in range(12)] els
e: watervalues = values months = [d.month for d in dates] i = months.index(10) watervalues = (watervalues[i:] + watervalues[:i]) return watervalues def dayofyear_range(dates, values): """Returns the day of the water year average for the timeseries.""" year = dates[0].year while ...
ativelkov/murano-api
murano/api/v1/deployments.py
Python
apache-2.0
5,151
0
# Copyright (c) 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 # # Unless required by applicable law...
rn wsgi.Resource(Controller()) def set_dep_state(deployment, unit): num_errors = unit.query(models.Status).filter_by( level='error', deployment_id=deployment.id).count() num_warnings = unit.query(mo
dels.Status).filter_by( level='warning', deployment_id=deployment.id).count() if deployment.finished: if num_errors: deployment.state = 'completed_w_errors' elif num_warnings: deployment.state = 'completed_w_warnings' else: deployment.stat...
danieljwest/mycli
mycli/config.py
Python
bsd-3-clause
4,404
0.001135
import shutil from io import BytesIO, TextIOWrapper import logging import os from os.path import expanduser, exists import struct from configobj import ConfigObj from Crypto.Cipher import AES logger = logging.getLogger(__name__) def load_config(usr_cfg, def_cfg=None): cfg = ConfigObj() cfg.merge(ConfigObj(def...
logger.warning('Invalid pad found in login path file.') continue # Get rid of pad. plain = pplain[:-pad_len] plaintext.write(plain) if plaintext.tell() == 0: logger.error('No data successfully decrypted from login path file.') return None plaintext.seek(0) ...
return plaintext
CellulaProject/icc.cellula
src/icc/data/recoll/filters/rclxls.py
Python
lgpl-3.0
2,469
0.003645
#!/usr/bin/env python2 # Extractor for Excel files. # Mso-dumper is not compatible with Python3. We use sys.executable to # start the actual extractor, so we need to use python2 too. import rclexecm import rclexec1 import xlsxmltocsv import re import sy
s import os import xml.sax class XLSProcessData: def __init__(self, em, ishtml = False): self.em = em self.out = "" self.gotdata = 0 self.xmldata = "" self.ishtml = ishtml def takeLine(self, line):
if self.ishtml: self.out += line + "\n" return if not self.gotdata: self.out += '''<html><head>''' + \ '''<meta http-equiv="Content-Type" ''' + \ '''content="text/html;charset=UTF-8">''' + \ '''</h...
SabatierBoris/CecileWebSite
pyramidapp/forms/__init__.py
Python
gpl-2.0
53
0
# vim: set
fileencoding=utf-8 : """ Forms module """
ProjectSWGCore/NGECore2
scripts/mobiles/generic/static/tatooine/jano.py
Python
lgpl-3.0
1,147
0.026155
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobi...
mplate.setSocialGroup("township") mobileTemplate.setOptionsBitmask(Options.INVULNERABLE | Options.CONVERSABLE) templates = Vector() templates.add('object/mobile/shared_dressed_tatooine_opening_jano.iff') mobileTemplate.setTemp
lates(templates) weaponTemplates = Vector() weapontemplate = WeaponTemplate('object/weapon/melee/unarmed/shared_unarmed_default.iff', WeaponType.UNARMED, 1.0, 6, 'kinetic') weaponTemplates.add(weapontemplate) mobileTemplate.setWeaponTemplateVector(weaponTemplates) attacks = Vector() mobileTemplate.setDefault...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/connectivity_issue.py
Python
mit
2,121
0
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
de: 'Local', 'Inbound', 'Outbound' :vartype origin: str or
~azure.mgmt.network.v2017_11_01.models.Origin :ivar severity: The severity of the issue. Possible values include: 'Error', 'Warning' :vartype severity: str or ~azure.mgmt.network.v2017_11_01.models.Severity :ivar type: The type of issue. Possible values include: 'Unknown', 'AgentStopped', 'GuestFi...
GuiASousa/Estudos
Minicursopy/SomaBinária.py
Python
gpl-3.0
600
0.020067
def somaBin(bin1,bin2): resto = 0 for e in range(7, -1, -1): somado[e] = bin1[e] + bin2[e] + resto if somado[e] > 1: if somado[e] == 2: resto = 1 somado[e] -= 2 elif somado[e] == 3: res
to = 1 somado[e] -= 2 else: resto = 0 return somado bin1 = [] bin2 = [] somado = [0,0,0,0,0,0,0,0] for x in range(0,8): bin1.append(int(
input('Binário 1: '))) for d in range(0,8): bin2.append(int(input('Binário 2: '))) print(somaBin(bin1,bin2))
kevin-coder/tensorflow-fork
tensorflow/python/data/experimental/ops/random_ops.py
Python
apache-2.0
2,234
0.003133
# 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...
ed2 = random_seed.get_seed(seed) variant_tensor = gen_experimental_dataset_ops.experimental_random_dataset( seed=self._seed, seed2=self._seed2, **dataset_ops.flat_
structure(self)) super(RandomDatasetV2, self).__init__(variant_tensor) @property def _element_structure(self): return structure.TensorStructure(dtypes.int64, []) @tf_export(v1=["data.experimental.RandomDataset"]) class RandomDatasetV1(dataset_ops.DatasetV1Adapter): """A `Dataset` of pseudorandom values...
obi-two/Rebelion
data/scripts/templates/object/building/poi/shared_endor_ewok_medium4.py
Python
mit
449
0.046771
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Building() r
esult.template = "object/building/poi/shared_endor_ewok_medium4.iff" result.attribute_template_id = -1 result.stfName("poi_n","base_poi_building") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### ret
urn result
JoseALermaIII/python-tutorials
pythontutorials/books/AutomateTheBoringStuff/Ch05/P2_characterCount.py
Python
mit
496
0.006048
"""Character count This program
counts how often each character appears in a string. """ def main(): message = 'It was a bright cold day in April, and the clocks were striking thirteen.' """str: Message to count characters.""" count = {} """dict: Characters as keys and counts as values.""" for character in message: ...
n__': main()
aYukiSekiguchi/ACCESS-Chromium
native_client_sdk/src/build_tools/nacl_sdk_scons/nacl_utils_test.py
Python
bsd-3-clause
4,315
0.004403
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unit tests for nacl_utils.py.""" import fileinput import mox import nacl_utils import os import sys import unittest def TestM...
functions.""" def setUp(self): self.script_dir = os.path.abspath(os.path.dirname(__file__)) self.mock_factory = mox.Mox() self.InitializeResourceMocks() def InitializeResourceMocks(self): """Can be called multiple times if multiple functions need to be tested.""" self.fileinput_mock = self.moc...
f): output = nacl_utils.ToolchainPath('nacl_sdk_root') head, tail = os.path.split(output) base, toolchain = os.path.split(head) self.assertEqual('nacl_sdk_root', base) self.assertEqual('toolchain', toolchain) self.assertRaises(ValueError, nacl_utils.ToolchainPath, ...
Llamatech/sis-fibo
model/vos/operacion.py
Python
gpl-2.0
2,405
0.012895
#-*- coding:iso-8859-1 -*- """ Clase que modela la información de una cuenta en el sistema """ # NUMERO.valor.punto_atencion,cajero,cuenta,fecha class Operacion(object): def __init__(self, numero, tipo_operacion, cliente, valor, punto_atencion, cajero, cuenta, fecha): self.numero = numero sel...
lf.nombre_oficina = nombre_oficina
self.cajero = cajero self.nombre_emp = nombre_emp self.apellido_emp = apellido_emp self.cuenta = cuenta self.prestamo = prestamo self.fecha = fecha.strftime('%d/%m/%Y') def dict_repr(self): d = { 'numero':self.numero, 'fecha':self.fecha, ...
zcwaxsshjd/TimeGrinder
RunGrinder.py
Python
apache-2.0
1,020
0.009804
__author__ = 'minosniu' import sys import os import uuid import shutil path_root = 'D:\\S2_L_forward_
reaching' expt = 'FES_reaching' date = '20150929' analyst = 'zcwaxs' addr = 'mongodb://localhost:27017/' patient = 'CXM' side = 'left' movement = 'forwar
d_reaching' if __name__ == '__main__': path = path_root files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) if not f.startswith('.')] for f in files: fullname = os.path.abspath(os.path.join(path, f)) print('Processing "%s"' % (f)) u = str(uuid.uuid1()) ...
noahbenson/neuropythy
neuropythy/datasets/__init__.py
Python
agpl-3.0
779
0.008986
#################################################################################################### # neuropythy/datase
ts/__init__.py # Datasets for neuropythy. # by Noah C. Benson # mainly just to force these to load when datasets is loaded: from .benson_winawer_20
18 import (BensonWinawer2018Dataset) from .hcp import (HCPDataset, HCPRetinotopyDataset, HCPMetaDataset) from .visual_performance_fields import (VisualPerformanceFieldsDataset) from .hcp_lines import (HCPLinesDataset) # TODO: https://openneuro.org/crn/datasets/ds001499/snapsh...
InfluxGraph/influxgraph
influxgraph/classes/lock.py
Python
apache-2.0
756
0
import fcntl import logging logger = logging.getLogger('influxgraph.lock') class FileLock(object): __slots__ = ('handle', 'filename') def __init__(self, filename): self.filename = filename try: self.handle = open(self.filename, 'w') except (IOError, OSError): ...
aise def acquire(self): fcntl.flo
ck(self.handle, fcntl.LOCK_EX) def release(self): fcntl.flock(self.handle, fcntl.LOCK_UN) def __enter__(self): self.acquire() def __exit__(self, exc_type, exc_val, exc_tb): self.release() def __del__(self): self.handle.close()
baryon5/mercury
codecompetitions/migrations/0007_auto_20140805_2253.py
Python
gpl-2.0
1,067
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('codecompetitions', '0006_auto_20140805_2234'), ] operations = [ migrations.AddField( model_name='problem', ...
s.AddField(
model_name='problem', name='time_limit', field=models.PositiveIntegerField(default=5), preserve_default=True, ), ]
ronaldbradford/os-demo
coverage/coverageindex.py
Python
apache-2.0
8,840
0.000113
#!/usr/bin/env python # # 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, softwa...
for entry in new_links: if entry: try: entry.validate() except Exception as e: logging.warn(str(e)) if int(time.time()) - entry.created > PURGE_SECONDS: logging.debug("Purging old link " + e
ntry.url) new_links.remove(entry) continue logging.info('URL verified ' + entry.url) return def read_existing_links(self, filename=LINKS_JSON_FILE): """Read the existing links file to append new validated coverage links "...
eadgarchen/tensorflow
tensorflow/python/debug/cli/analyzer_cli.py
Python
apache-2.0
58,062
0.004254
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
from __future__ import print_function import argparse import copy import re from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.python.debug.cli import cli_config from tensorflow.python.debug.cli import cli_shared from tensorflow.python.debug.cli import command_parser from tensorflow.p...
m tensorflow.python.debug.cli import evaluator from tensorflow.python.debug.cli import ui_factory from tensorflow.python.debug.lib import debug_graphs from tensorflow.python.debug.lib import source_utils RL = debugger_cli_common.RichLine # String constants for the depth-dependent hanging indent at the beginning # of ...
jimmycallin/master-thesis
architectures/nn_discourse_parser/nets/util.py
Python
mit
11,972
0.005429
from collections import Counter import sys import numpy as np import scipy as sp from lexical_structure import WordEmbeddingDict import dense_feature_functions as df def _get_word2vec_ff(embedding_path, projection): word2vec = df.EmbeddingFeaturizer(embedding_path) if projection == 'mean_pool': return ...
[:, sorted_indices] for x in feature_matrices] class BrownDictionary(object): def __init__(self): self.word_to_brown_mapping = {} self.num_clusters = 0 brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c3200-freq1.txt' #brown_
cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c320-freq1.txt' #brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c100-freq1.txt' self._load_brown_clusters('resources/%s' % brown_cluster_file_name) def _load_brown_clusters(self, path): try: lexicon...
geggo/pyface
pyface/multi_toolbar_window.py
Python
bsd-3-clause
5,751
0.000522
#------------------------------------------------------------------------------ # Copyright (c) 2005, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions describe...
he tool bars for this window. """ if len(self._tool_bar_managers) > 0: # Create a top level sizer to handle to main layout and attach # it to the parent frame. self.main_sizer = sizer = wx.BoxSizer(wx.VERTICAL) parent.SetSizer(sizer) parent.SetAutoLay...
._tool_bar_managers: location = self._tool_bar_locations[tool_bar_manager] sizer = self._create_tool_bar(parent, sizer, tool_bar_manager, location) return sizer return None def _create_tool_bar(self, parent, sizer, ...
zerovip/link-link
game11_11/game11_11/urls.py
Python
apache-2.0
824
0.004854
"""game11_11 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$'
, views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r...
r'^admin/', admin.site.urls), url(r'^link_link/', include('link_link.urls')), ]
andrewyoung1991/supriya
supriya/tools/ugentools/LPZ2.py
Python
mit
2,895
0.002763
# -*- encoding: utf-8 -*- from supriya.tools.ugentools.Filter import Filter class LPZ2(Filter): r'''A two zero fixed lowpass filter. :: >>> source = ugentools.In.ar(bus=0) >>> lpz_2 = ugentools.LPZ2.ar( ... source=source, ... ) >>> lpz_2 LPZ2.ar() ...
synthdeftools calculation_rate = synthdeftools.CalculationRate.CONTROL ugen = cls._new_expanded( calculation_rate=calculation_rate, source=source, ) return ugen # def magResponse(): ... # def magResponse2(): ... # def magResponse5(): ... #...
:: >>> source = ugentools.In.ar(bus=0) >>> lpz_2 = ugentools.LPZ2.ar( ... source=source, ... ) >>> lpz_2.source OutputProxy( source=In( bus=0.0, calculation_rate=CalculationRate.AUDIO...
cloudify-cosmo/version-tool
version_control/tests/resources/cloudify-test2/input/cloudify-module/setup.py
Python
apache-2.0
1,244
0
######### # Copyright (c) 2013 GigaSpaces Technologies Ltd. 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 m
ay ob
tain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # * See the Licens...
WalissonRodrigo/SIMPLEMOOC
simplemooc/accounts/urls.py
Python
gpl-3.0
686
0.010204
from django.conf.urls import include, url from simplemooc.accounts.
views import * from django.contrib.auth.views import logout, login urlpatterns = [ url(r'^$', dashboard, name='dashboard'), url(r'^entrar/$', login, {'template_name': 'accounts/login.html'}, name='login'), url(r'^sair/$', logout, {'next_page': 'core:home'}, name='logout'), url(r'^nova-senha/$', passwor...
me='register'), url(r'^editar/$', edit, name='edit'), url(r'^editar-senha/$', edit_password, name='edit_password'), ]
lsjostro/pulp_win
test/upload_msi.py
Python
gpl-2.0
6,243
0.006728
#!/usr/bin/python import os import requests from requests.exceptions import HTTPError import hashlib import json from optparse import OptionParser from glob import glob from msilib import * CHUNK_SIZE = 1048576 # 1 Mb chunk size class MsiUploader(): def __init__(self, url, user, password): self.base_url ...
r.raise_for_status() return True def publish_repo(self, repo_id): repo_path = "/pulp/api/v2/repositories/%s/"
% repo_id publish_path = repo_path + "actions/publish/" distributor_data = { "id": "win_distributor", "override_config": {} } r = requests.post(self.base_url + publish_path, auth=self.basic_auth, verify=False, data=json.dumps(distributor_data)) r.raise_for...
CINPLA/expipe-dev
exana/exana/_version.py
Python
gpl-3.0
18,442
0
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains t...
return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: pr...
was %s" % stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and...
ahtn/keyplus
host-software/keyplus/keycodes/lang_map/English0.py
Python
mit
2,332
0.000433
# Copyright 2018 [email protected] # Licensed under the MIT license (http://opensource.org/licenses/MIT) from hid_keycodes import * lang = 'English' country = 'Canada' scancode_map = { KC_0: ('0', ')', ']', '', '', ''), KC_1: ('1', '!', '', '', '', ''), KC_2: ('2', '@', '', '', '', ''), KC_3: ('3', '#', ...
KC_5: ('5', '%', '', '', '', ''), KC_6: ('6', '?', '', '', '', ''), KC_7: ('7', '&', '{', '', '', ''), KC_8: ('8', '*', '}', '', '', ''), KC_9: ('9', '(', '[', '', '', ''), KC_A: ('a', 'A', '', '', '', ''), KC_B: ('b', 'B', '', '', '', ''), KC_C: ('c', 'C', '', '', '', ''), KC_D: ('d', ...
, ''), KC_H: ('h', 'H', '', '', '', ''), KC_I: ('i', 'I', '', '', '', ''), KC_J: ('j', 'J', '', '', '', ''), KC_K: ('k', 'K', '', '', '', ''), KC_L: ('l', 'L', '', '', '', ''), KC_M: ('m', 'M', '', '', '', ''), KC_N: ('n', 'N', '', '', '', ''), KC_O: ('o', 'O', '', '', '', ''), KC_P:...
10se1ucgo/cassiopeia
cassiopeia/datastores/merakianalyticscdn.py
Python
mit
1,352
0.002219
from typing import Type, TypeVar, MutableMapping, Any, Iterable from datapipelines import DataSource, PipelineContext, NotFoundError from ..dto.patch import PatchListDto from .common import HTTPClient, HTTPError try: import ujson as json except ImportError: import json json.decode = json.loads T = TypeV...
self._client = HTTPClient() else: self._client = http_client @DataSource.dispatch def get(self, type: Type[T], query: MutableMapping[str, Any], context: PipelineContext = None) -> T: pass @DataSource.dispatch def get_many(self, type: Type[T], query: MutableMappi...
@get.register(PatchListDto) def get_patch_list(self, query: MutableMapping[str, Any], context: PipelineContext = None) -> PatchListDto: url = "https://cdn.merakianalytics.com/riot/lol/resources/patches.json" try: body = self._client.get(url)[0] body = json.decode(body) ...
SJIT-Hackerspace/SJIT-CodingPortal
hackerspace/migrations/0010_auto_20160906_1442.py
Python
apache-2.0
2,386
0.001676
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-09-06 09:12 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hackerspace', '0009_verbal_subcategory'), ] operations = [ migrations.Remove...
ingquestion', name='TestCases', field=models.CharField(default='2', max_leng
th=200, verbose_name='Test Cases'), preserve_default=False, ), migrations.AddField( model_name='quiz', name='Answer', field=models.CharField(default='3', max_length=200), preserve_default=False, ), migrations.AddField( ...
Programmica/python-gtk3-tutorial
_examples/overlay.py
Python
cc0-1.0
798
0.002506
#!/usr/bin/env python import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk window = Gtk.Window() window.set_default_size(200, 200) window.connect("destroy", Gtk.main_quit) overlay = Gtk.Overlay() window.add(overlay) textview = Gtk.TextView() textview.set_wrap_mode(Gtk.WrapMode.WORD_CHAR) textbuf...
textbuffer.set_text("Welcome to the PyGObject Tutorial\n\nThis guide aims to provid
e an introduction to using Python and GTK+.\n\nIt includes many sample code files and exercises for building your knowledge of the language.", -1) overlay.add(textview) button = Gtk.Button(label="Overlayed Button") button.set_valign(Gtk.Align.CENTER) button.set_halign(Gtk.Align.CENTER) overlay.add_overlay(button) ove...
andela/troupon
troupon/cart/views.py
Python
mit
6,304
0.000159
import os from carton.cart import Cart from django.contrib import messages from django.shortcuts import render, redirect from django.template.response import TemplateResponse from django.views.generic import View from authentication.views import LoginRequiredMixin from deals.models import Deal from .models import Us...
he incoming get request object **kwargs: Any keyword arguments passed to the function Returns: A redirect to the deals homepage """ cart = Cart(request.session) cart.clear() return redirect('/') class RemoveItemView(LoginRe
quiredMixin, View): """ Remove item from cart. When triggered, removes a particular item from the cart session based on its id. Attributes: LoginRequiredMixin: Ensures the user is logged in View: Normal django view """ def post(self, request, **kwargs): """ ...
ArteliaTelemac/PostTelemac
PostTelemac/meshlayerparsers/libs_telemac/parsers/parserFortran.py
Python
gpl-3.0
59,062
0.002438
"""@author Sebastien E. Bourban and Noemie Durand """ """@note ... this work is based on a collaborative effort between .________. ,--. | | . ( ( |,-. / HR Wallingford EDF - L...
____/ Imports /__________________________________________________/ # # ~~> dependencies towards standard python import re import sys from copy import deepcopy from os import path, walk, remove, environ, sep # ~~> dependencies towards the root of pytel sys.path.append(path.join(path.dirname(sys.argv[0]), "..")) # cle...
other pytel/modules from utilstelemac.files import ( getTheseFiles, isNewer, addToList, addFileContent, getFileContent, putFileContent, diffTextFiles, ) from utilstelemac.progressbar import ProgressBar debug = False # _____ ______________________________________________ # ___...
colloquium/spacewalk
spacewalk/certs-tools/client_config_update.py
Python
gpl-2.0
6,500
0.003385
#!/usr/bin/python -u # # Copyright (c) 2008--2010 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You sho...
n %s CONFIG_FILENAME NEW_MAPPINGS [options] arguments: CONFIG_FILENAME config file to alter NEW_MAPPINGS file containing new settings that map onto the config file options: -h, --help show this help message and exit -
-usage show brief usage summary examples: python %s %s %s python %s %s %s """ % (sys.argv[0], sys.argv[0], RHN_REGISTER, DEFAULT_CLIENT_CONFIG_OVERRIDES, sys.argv[0], UP2DATE, DEFAULT_CLIENT_CONFIG_OVERRIDES) sys.exit(0) if len(sys.argv) != 3: msg = "ERROR: exactl...
ccxt/ccxt
examples/py/ftx-close-position-reduceOnly.py
Python
mit
1,037
0.000964
# -*- coding: utf-8 -*- import os import sys from pprint import pprint root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt # noqa: E402 print('CCXT Version:', ccxt.__version__) exchange = ccxt.
ftx({ 'enableRateLimit': True, 'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET', }) exchange.load_markets() # exchange.verbose = True # uncomment for debugging purposes if necessary symbol = 'BTC-PERP' # change for your symbol positions = exchange.fetch_positions() positions_by_symbol = exchange.index_by(positions, 'symbol') if symbol in positions_by_symbol: pos...
KoreaCloudObjectStorage/swift3
swift3/test/functional/test_object.py
Python
apache-2.0
27,679
0.000036
# Copyright (c) 2015 OpenStack Foundation # # 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 ...
.bucket = 'bucket' self.conn.make_request('PUT', self.bucket) def _assertObjectEtag(self, bucket, obj, etag): status, headers, _ =
self.conn.make_request('HEAD', bucket, obj) self.assertEquals(status, 200) # sanity self.assertCommonResponseHeaders(headers, etag) def test_object(self): obj = 'object' content = 'abc123' etag = md5(content).hexdigest() # PUT Object status, headers, body ...
0xdyu/RouteFlow-Exodus
pox/pox/lib/graph/nom.py
Python
apache-2.0
4,353
0.012176
# Copyright 2012 James McCauley # # This file is part of POX. # # POX 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. # # POX is distri...
pes is False: return self.find(is_a=t) else: return self.find(type=t) def raiseEvent (self, event, *args, **kw): """ Whenever we raise any event, we also raise an Update, so we extend the implementation in EventMixin. """ rv = EventMixin.raiseEvent(self, event, *args, **kw) if...
__name__, len(self))
shishengjia/OnlineCourses
extra_apps/xadmin/plugins/__init__.py
Python
apache-2.0
771
0.029831
PLUGINS = ( 'actions', 'filters', 'bookmark', 'export', 'layout', 'refresh', 'detai
ls', 'editabl
e', 'relate', 'chart', 'ajax', 'relfield', 'inline', 'topnav', 'portal', 'quickform', 'wizard', 'images', 'auth', 'multiselect', 'themes', 'aggregation', 'mobile', 'passwords', 'sitemenu', 'language', 'quickfilter', 'sortab...
cpennington/edx-platform
lms/djangoapps/bulk_email/views.py
Python
agpl-3.0
2,070
0.000483
""" Views to support bulk email functionalities like opt-out. """ import logging from six import text_type from django.contrib.auth.models import User from django.http import Http404 from bulk_email.models import Optout from courseware.courses import get_course_by_id from edxmako.shortcuts import render_to_respons...
try: username = UsernameCipher().decrypt(token) user = User.objects.get(username=username) course_key = CourseKey.from_string(course_id) course = get_course_by_id(course_key, depth=0) except UnicodeDecodeError: raise Http404("base64url") except UsernameDecryptionExcept...
ttp404("course") unsub_check = request.POST.get('unsubscribe', False) context = { 'course': course, 'unsubscribe': unsub_check } if request.method == 'GET': return render_to_response('bulk_email/confirm_unsubscribe.html', context) if request.method == 'POST' and unsub_chec...