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
pprett/scikit-learn
sklearn/feature_selection/from_model.py
Python
bsd-3-clause
6,968
0
# Authors: Gilles Louppe, Mathieu Blondel, Maheshakya Wijewardena # License: BSD 3 clause import numpy as np from .base import SelectorMixin from ..base import BaseEstimator, clone from ..externals import six from ..exceptions import NotFittedError from ..utils.fixes import norm def _get_feature_importances(estima...
t_params : Other estimator specific parameters Returns ------- self : object Returns self. """ if self.prefit:
raise NotFittedError( "Since 'prefit=True', call transform directly") if not hasattr(self, "estimator_"): self.estimator_ = clone(self.estimator) self.estimator_.partial_fit(X, y, **fit_params) return self
JulyKikuAkita/PythonPrac
cs15211/RangeModule.py
Python
apache-2.0
7,564
0.003966
__source__ = 'https://leetcode.com/problems/rang
e-module/' # Time: O(logK) to O(K) # Space: O(A+R), the space used by ranges. # # Description: Leetco
de # 715. Range Module # # A Range Module is a module that tracks ranges of numbers. # Your task is to design and implement the following interfaces in an efficient manner. # # addRange(int left, int right) Adds the half-open interval [left, right), # tracking every real number in that interval. # Adding an interval th...
mluo613/osf.io
addons/s3/routes.py
Python
apache-2.0
1,947
0
from framework.routing import Rule, json_renderer from addons.s3 import views api_routes = { 'rules': [ Rule( [ '/settings/s3/accounts/', ], 'post', views.s3_add_user_account, json_renderer, ), Rule( [...
pid>/s3/s
ettings/', '/project/<pid>/node/<nid>/s3/settings/', ], 'get', views.s3_get_config, json_renderer, ), Rule( [ '/project/<pid>/s3/user-auth/', '/project/<pid>/node/<nid>/s3/user-auth/', ...
endlessm/chromium-browser
tools/android/asan/third_party/with_asan.py
Python
bsd-3-clause
3,894
0.012327
#!/usr/bin/env vpython # Copyright 2019 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. import argparse import contextlib import logging import os import subprocess import sys _SRC_ROOT = os.path.abspath( os.path.joi...
e=None, long_list=True): logging.error(' %s: %s', entry[0].GetDeviceSerial(), ' '.join(entry[1:])) raise @contextlib.contextmanager def Asan(args): env = os.environ.copy() env['ADB'] = args.adb try: with _Log...
device = device_utils.DeviceUtils.HealthyDevices( device_arg=args.device)[0] disable_verity = device.build_version_sdk >= version_codes.MARSHMALLOW if disable_verity: device.EnableRoot() # TODO(crbug.com/790202): Stop logging output after diagnosing # issues on android-asan...
hgsoft/hgsoft-addons
custom_account_payment_v11/__manifest__.py
Python
gpl-3.0
1,867
0.008043
# -*- coding: utf-8 -*- ############################################################################### # # # Copyright (C) 2018 HGSOFT - www.hgsoft.com.br # # ...
istributed in the hope that it will be useful, # #but WITHOUT ANY WARRANTY; without e
ven the implied warranty of # #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # #GNU General Public License for more details. # # # #You should have received a copy of ...
niwinz/Green-Mine
src/greenmine/core/utils/slug.py
Python
bsd-3-clause
1,106
0.001808
# -*- coding: utf-8 -*- from django.utils import baseconv from django.template.defaultfilters import
slugify import time def slugify_uniquely(value, model, slugfield="slu
g"): """ Returns a slug on a name which is unique within a model's table """ suffix = 0 potential = base = slugify(value) if len(potential) == 0: potential = 'null' while True: if suffix: potential = "-".join([base, str(suffix)]) if not model.objects.filt...
timfreund/PhotoFUSE
setup.py
Python
mit
588
0.003401
# -*- coding: utf-8 -*- from setuptools import setup, find_packages
setup( name='PhotoFUSE', version='1.0', description="PhotoFUSE: Show photos based on ratings and tags", author='Tim Freund', author_email='tim@freunds.net', license = 'MIT License', url='http://github.com/timfreund/photofuse', install_requires=[ 'fusepy', # PIL ...
tofuse.cli:ls photofuse = photofuse.cli:photofuse """, )
anushbmx/kitsune
kitsune/forums/models.py
Python
bsd-3-clause
13,732
0.000073
import datetime import time from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.db.models import Q from django.db.models.signals import pre_save from django.contrib.contenttypes.fields import GenericRelation from django.contrib.auth.models import User from tidings.models imp...
elf): query = {'last': self.last_post_id} page = self.last_page if page > 1: query['page'] = page url = reverse('forums.posts', args=[self.forum.slug, self.id]) return urlparams(url, hash='post-%s' % self.last_post_id,
**query) def save(self, *args, **kwargs): super(Thread, self).save(*args, **kwargs) old_forum = getattr(self, '_old_forum', None) new_forum = self.forum if old_forum and old_forum != new_forum: old_forum.update_last_post(exclude_thread=self) old_forum.save() ...
mattvonrocketstein/smash
smashlib/ipy3x/utils/tests/test_io.py
Python
mit
6,837
0.000878
# encoding: utf-8 """Tests for io.py""" #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #------...
setattr(sys, channel, trap) tee = Tee(chan, channel=channel) print(text, end='', file=chan) setattr(sys, channel, std_ori) trap_val = trap.getvalue() nt.assert_equal(chan.getvalue(), text) if check == 'close': tee.close() else: del tee ...
: """Test that io.stdin/out/err exist at startup""" for name in ('stdin', 'stdout', 'stderr'): cmd = doctest_refactor_print( "from IPython.utils import io;print io.%s.__class__" % name) p = Popen([sys.executable, '-c', cmd], stdout=PIPE) p.wait() cla...
chaehni/scion-coord
python/local_gen.py
Python
apache-2.0
6,540
0.002141
# Copyright 2017 ETH Zurich # # 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...
ice_type, instance_name, instance_path) generate_zk_config(tp, new_ia, local_gen_path
, simple_conf_mode=True) generate_sciond_config(TopoID(args.joining_ia), as_obj, tp, local_gen_path) # We don't initiate the prometheous service for user ASes. # generate_prom_config(ia, tp, gen_path) def generate_certificate(joining_ia, core_ia, core_sign_priv_key_file, core_cert_file, trc_file): """...
foxtrot94/EchelonPlanner
src/app/admin.py
Python
mit
296
0.003378
# Register your mod
els here. from app.subsystem.usermanagement.professor import * from app.subsystem.usermanagement.programdirector import * from app.subsystem.usermanagement.student import * # admin.sit
e.register(Professor) # admin.site.register(ProgramDirector) # admin.site.register(Student)
msullivan/advent-of-code
2017/17b.py
Python
mit
358
0.00838
#!/usr/bin/env
python3 import sys def main(args): #cnt = 2017 cnt = 50000000 n = 3 n = 345 size = 0 buf = [0] pos = 0 at_1 = None for i in range(cnt): pos = (pos + n) % (i+1) if pos == 0: at_1 = i+1 pos += 1 print(at_1) if __name__ == '__main
__': sys.exit(main(sys.argv))
uw-it-aca/grading-standard-lti
grading_standard/models.py
Python
apache-2.0
3,569
0
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from django.db import models from django.core.exceptions import ValidationError import json class GradingStandardManager(models.Manager): def find_by_login(self, login_id, id=None, name=None): kwargs = {'created_by': l...
_CHOICES: if scale == choice[0]: return scale raise ValidationError('Invalid scale: {}'.format(scale)) @staticmethod def valid_grading_scheme(scheme): if type(scheme) is list and len(scheme): return scheme raise ValidationError('Scheme is ...
ef valid_course_id(sis_course_id): if sis_course_id is not None: sis_course_id = sis_course_id.strip() if len(sis_course_id): return sis_course_id raise ValidationError('Course SIS ID is required') class GradingStandardCourse(models.Model): """ Represents a ...
jumpstarter-io/cinder
cinder/volume/drivers/coraid.py
Python
apache-2.0
21,417
0
# Copyright 2012 Alyseo. # 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 appli...
groups_map[group_name] = group_info['groupId'] return groups_map def _set_effective_group(self, groups_map, group): """Set effective group. Use groups_map returned from _login method. """ try: group_id = groups_map[group] except KeyError: ...
ly = self._rest_client.rpc('admin', url_params, 'Group') if reply['state'] != 'adminSucceed': raise exception.CoraidESMBadCredentials() self._logined = True def _ensure_session(self): if not self._logined: groups_map = self._login() self._set_effective_g...
jfcherng/sublime-TypeShort
functions.py
Python
mit
401
0
import re def snake_to_camel(snake, upper_first=False): # title-cased words words = [word.title() for word in snak
e.split('_')] if words and not upper_first: words[0] = words[0].lower() return ''.join(words) def camel_to_snake(camel): # first upper-cased camel cam
el = camel[0].upper() + camel[1:] return '_'.join(re.findall(r'[A-Z][^A-Z]*', camel)).lower()
cpennington/edx-platform
common/djangoapps/entitlements/models.py
Python
agpl-3.0
21,559
0.004267
"""Entitlement Models""" import logging import uuid as uuid_tools from datetime import timedelta from django.conf import settings from django.contrib.sites.models import Site from django.db import IntegrityError, models, transaction from django.utils.encoding import python_2_unicode_compatible from django.utils.time...
Model): """ Represents a Student's Entitlement to a Course Run for a given Course. .. no_pii: """ user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) uuid = models.UUIDField(d
efault=uuid_tools.uuid4, editable=False, unique=True) course_uuid = models.UUIDField(help_text=u'UUID for the Course, not the Course Run') expired_at = models.DateTimeField( null=True, help_text=u'The date that an entitlement expired, if NULL the entitlement has not expired.', blank=True...
jamesblunt/kaggle-galaxies
predict_augmented_npy_8433n_maxout2048_pysex.py
Python
bsd-3-clause
9,590
0.005214
""" Load an analysis file and redo the predictions on the validation set / test set, this time with augmented data and averaging. Store them as numpy files. """ import numpy as np # import pandas as pd import theano import theano.tensor as T import layers import cc_layers import custom import load_data import realtime...
np.ceil(chunk_length / float(BATCH_SIZE))) # make predictions, don't forget to cute off the zeros at the end predictions_chunk_list = [] for b in xrange(num_batches_chunk): if b % 1000 == 0: print " batch %d/%d" % (b + 1, num_batches_chunk) predictions ...
redictions_chunk[:chunk_length] # cut off zeros / padding print " compute average over transforms" predictions_chunk_avg = predictions_chunk.reshape(-1, len(augmentation_transforms), 37).mean(1) predictions_list.append(predictions_chunk_avg) time_since_start = time.time() - start_tim...
rsalmaso/django-allauth
allauth/decorators.py
Python
mit
683
0.001464
from functools import wraps from allauth import ratelimit def rate_limit(*, action, **rl_kwargs): from allauth.account import app_settings rate = app_settings.RATE_LIMITS.get(action) if rate: rate = ratelimit.parse(rate) rl_kwargs.setdefault("duration", rate.duration) rl_kwargs.s...
if not resp: resp = function(request, *args, **k
wargs) return resp return wrap return decorator
ivesbai/server
generator/sources/python/KalturaClient/tests/utils.py
Python
agpl-3.0
2,114
0.014664
import os, sys, inspect import unittest import ConfigParser from KalturaClient import KalturaClient, KalturaConfiguration from KalturaClient.Base import KalturaObjectFactory, KalturaEnumsFactory from KalturaClient.Base import IKalturaLogger from KalturaClient.Plugins.Core import KalturaSessionType from KalturaClient....
ry as to avoid thrashing kaltura with logins... def setUp(self): #(client session is enough when we do operations in a users scope) self.config = GetConfig() self.client = KalturaClient(self.config) self.ks = self.client.generateSession(ADMIN_SECRET, USER_NAME, ...
elf.client.setKs(self.ks) def tearDown(self): #do cleanup first, probably relies on self.client self.doCleanups() del(self.ks) del(self.client) del(self.config)
NifTK/NiftyNet
niftynet/engine/handler_console.py
Python
apache-2.0
1,161
0
# -*- coding: utf-8 -*- """ This module implements a console output writer. """ import tensorflow as tf from niftynet.engine.application_variables import CONSOLE from niftynet.engine.signal import ITER_STARTED, ITER_FINISHED class ConsoleLogger(object): """ This class handles iteration events to print outpu...
rs(self, _sender, **msg): """ Printing iteration message with ``tf.lo
gging`` interface. :param _sender: :param msg: an iteration message instance :return: """ tf.logging.info(msg['iter_msg'].to_console_string())
MarioVilas/secondlife-experiments
SimProxy/extract_xml.py
Python
gpl-2.0
1,050
0.018095
import os import types from sllib.LLSD import LLSD try: os.make
dirs('./httpcap') except: pass data = open('httpcap.txt','r').read() c = 0 btag = '<llsd>' etag = '</llsd>' ##mbtag = '<key>message</key><string>' ##metag = '</string>' b = data.find(btag) mnames = {} while b >= 0: e = data.find(etag, b) + len(etag) xml = data[b:e] ## bm = xml.rfind(mbt...
m >= 0 and em >= bm: ## bm = bm + len(mbtag) ## m = xml[bm:em] ## mnames[m] = None ## else: ## m = 'Unknown' ll = LLSD.fromstring(xml) m = 'DATA' if type(ll) == types.DictType and ll.has_key('events'): ## print ll for msg in ll['events']: ...
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/telepathy/_generated/Channel_Type_Room_List.py
Python
gpl-3.0
76
0.013158
../../
../../../share/pyshared/telepathy/_generated/Channel_Type_Room
_List.py
s20121035/rk3288_android5.1_repo
external/chromium_org/chrome/common/extensions/docs/server2/fake_fetchers.py
Python
gpl-3.0
6,215
0.00901
# 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. # These are fake fetchers that are used for testing and the preview server. # They return canned responses for URLs. appengine_wrappers.py uses the fake ...
ConfigureFakeFetchers(): '''Configu
re the fake fetcher paths relative to the docs directory. ''' appengine_wrappers.ConfigureFakeUrlFetch({ url_constants.OMAHA_HISTORY: _FakeOmahaHistory(), url_constants.OMAHA_PROXY_URL: _FakeOmahaProxy(), '%s/.*' % url_constants.SVN_URL: _FakeSubversionServer(), '%s/.*' % url_constants.VIEWVC_URL: _...
pddg/qkouserver
qkoubot/my_exception.py
Python
mit
136
0
class NoResultScr
aped(Exception): pass class NotCompleteParse(Exception): pass class CouldNotAuthorize(Exception)
: pass
h4ck3rm1k3/pywikibot-core
scripts/catall.py
Python
mit
4,132
0.000242
#!/usr/bin/python # -*- coding: utf-8 -*- """ This script shows the categories on each page and lets you change them. For each page in the target wiki: * If the page contains no categories, you can specify a list of categories to add to the page. * If the page already contains one or more categories, you can specify...
pywikibot.bot import QuitKeyboardInterrupt def choosecats(pagetext): """Coose categories.""" chosen = [] done = False length = 1000 # TODO: → input_choice pywikibot.output("""Give the new categories, one per line. Empty line: if the first, don't change. Otherwise: Ready. -: I made a mistake, l...
l categories and add no new. q: quit.""") while not done: choice = pywikibot.input(u"?") if choice == "": done = True elif choice == "-": chosen = choosecats(pagetext) done = True elif choice == "?": from pywikibot import editor as edit...
FibercorpLabs/FibercorpDevops
vmware/vcenter/AddDisk2VM.py
Python
gpl-3.0
4,831
0.005589
#AddDisk2VM.py from VMWConfigFile import * from pyVim import connect from pyVim.connect import SmartConnect, Disconnect from pyVmomi import vim, vmodl import atexit import os import sys import ssl import requests import argparse import time import getpass # Disabling urllib3 ssl warnings requests.packages.urllib3.dis...
disk(vm, si, disk_size, disk_type): spec = vim.vm.ConfigSpec() # get all disks on a VM, set unit_number to the next available for dev in vm.config.hardware.device: if hasattr(dev.backing, 'fileName'):
unit_number = int(dev.unitNumber) + 1 # unit_number 7 reserved for scsi controller if unit_number == 7: unit_number += 1 if unit_number >= 16: print "ERROR: we don't support this many disks" return ...
cloudera/hue
desktop/core/ext-py/Babel-2.5.1/tests/conftest.py
Python
apache-2.0
396
0
impo
rt os import pytest @pytest.fixture def os_environ(monkeypatch): mock_environ = dict(os.environ) monkeypatch.setattr(os, 'environ', mock_environ) return mock_environ def pytest_generate_tests(metafunc): if hasattr(metafunc.function, "all_locales"): from babel.localedata import locale_identif...
.parametrize("locale", list(locale_identifiers()))
Y--/root
documentation/doxygen/converttonotebook.py
Python
lgpl-2.1
35,405
0.006157
#!/usr/bin/env python # Author: Pau Miquel i Mir <pau.miquel.mir@cern.ch> <pmm1g15@soton.ac.uk>> # Date: July, 2016 # # DISCLAIMER: This script is a prototype and a work in progress. Indeed, it is possible that # it may not work for certain tutorials, and that it, or the tutorial, might need to be # tweaked slightly to...
o to be converted is imported as a string. # A series of modifications are made to this string, for instance delimiting where markdown and # code cells begin and end. Then, this string is converted into ipynb format using a function # in the nbconvert package. Finally, the notebook is executed and output. # # For conve...
It extracts the decription and # author information from the header and then removes it. It also converts any comment at the # beginning of a line into a Markdown cell. # # For C++ files the process is slightly more complex. The script separates the functions from the # main code. The main function is identified as it ...
yamstudio/Codeforces
100/148A - Insomnia cure.py
Python
gpl-3.0
146
0.013699
x =
[] d = 0 for _ in range(4): x.append(int(raw_input())) for i in range(input()): if any(((i + 1) % j == 0) for j in x): d +=
1 print d
swwendel/ZipUploadPublishWebmapShare
ZipUploadPublishWebMapShare.py
Python
apache-2.0
3,872
0.012655
''' Title: ZipUploadPublishWebMapShare.py Author: Stephanie Wendel Date: 4/18/2014 Updated: 10/15/2015 Description: NOTE: This script uses the request module to make http requests. The script should be able to access this module in order for it to work correctly. If it is not installed, one place it can be d...
,"opacity":1, 'title': filename}],"baseMap": {'baseMapLayers':[{'id':"World_Imagery_1068",'opacity':1,'visibility':'true','url':'http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer'}],'title':'Imagery'},'version':'1.9.1'}) webmap_params = {'title': webmap_name, 'type':'Web Map', 'text':te
xt, 'f': 'json','token': token} webmap_response = requests.post(webmap_url, params=webmap_params) print json.loads(webmap_response.text) webmap_id = json.loads(webmap_response.text)['id'] # Share the web map with the organziation share_webmap_url = "http://www.arcgis.com/sharing/rest/content/users/{0}/items/{1}/share"...
knoppo/pi3bar
pi3bar/plugins/disk.py
Python
mit
3,744
0.00187
import os from pi3bar.plugins.base import Plugin from pi3bar.utils import humanize_size_bytes class Disk(Plugin): """ :class:`pi3bar.app.Pi3Bar` plugin to disk usage. Available format replacements (``*_p`` = percentage): * ``%(size)s`` E.g. '100GB' * ``%(free)s`` E.g. '70GB' * ``%(free_p)f``...
e) :param critical_usage: :class:`int` - Critical breakpoint (default: 95) :param critical_color: :class:`str` - Critical color (default: None) :param critical_background: :class:`str` - Critical background color (default: '#ff0000') Examples: .. code-block:: python # root Disk('/...
format (escape '%' with '%') Disk('/', full_format='%(usage)s / %(size)s', short_format='%(free_p)f%%') # adjust warning/critical switches Disk('/mnt', warning_usage=80, critical_usage=90) """ def __init__(self, mount_path, **kwargs): self.instance = mount_path self.mou...
mF2C/COMPSs
compss/programming_model/bindings/python/src/pycompss/worker/piper/commons/__init__.py
Python
apache-2.0
670
0
#!/usr/bin/python # # Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es) # # 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 ...
cable 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 License for the specific language governing permissions and # limitations under the License. # # -*- coding: utf-8 -*-
colour-science/colour
colour/temperature/tests/test_hernandez1999.py
Python
bsd-3-clause
4,583
0.000218
"""Defines the unit tests for the :mod:`colour.temperature.hernandez1999` module.""" import numpy as np import unittest from itertools import permutations from colour.temperature import xy_to_CCT_Hernandez1999, CCT_to_xy_Hernandez1999 from colour.utilities import ignore_numpy_errors __author__ = "Colour Developers" ...
sional_CCT_to_xy_Hernandez1999(self): """ Test :func:`colour.temperature.hernandez1999.CCT_to_xy_Hernandez1999` definition n-dimensional arrays support. """ CCT = 6500.74204318 xy = CCT_to_xy_Hernandez1999(CCT)
CCT = np.tile(CCT, 6) xy = np.tile(xy, (6, 1)) np.testing.assert_almost_equal( CCT_to_xy_Hernandez1999(CCT), xy, decimal=7 ) CCT = np.reshape(CCT, (2, 3)) xy = np.reshape(xy, (2, 3, 2)) np.testing.assert_almost_equal( CCT_to_xy_Hernandez...
ngageoint/geoq
geoq/agents/admin.py
Python
mit
710
0.008451
# -*- coding: utf-8 -*- # This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and # is subject to t
he Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012) from reversion.admin import VersionAdmin from django.contrib.gis import admin from .models import Feedback,Topic @admin.register(Feedback) class FeedbackAdmin(VersionAdmin, admin.ModelAdmi
n): model = Feedback list_display = ['name', 'email', 'topic', 'message'] save_as = True ordering = ['topic'] @admin.register(Topic) class TopicAdmin(VersionAdmin, admin.ModelAdmin): model = Topic list_display = ['name'] save_as = True ordering = ['name']
andrewsmedina/django-admin2
djadmin2/tests/test_auth_admin.py
Python
bsd-3-clause
2,211
0
from django import forms from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase from django.test.client import RequestFactory from djadmin2.site import djadmin2_site from ..admin2 import UserAdmin2 class UserAdminTest(TestCase): def setUp(self): ...
.factory.get( reverse('admin2:auth_user_update', args=(self.user.pk,))) request.user = self.user model_admin = UserAdmin2(User, djadmin2_site) view = model_admin.update_view.view.as_view( **model_admin.get_update_kwargs()) response = view(request, pk=self.user.pk)...
ext_data['form'] self.assertTrue( isinstance(form.fields['username'].widget, forms.TextInput)) self.assertTrue( isinstance(form.fields['date_joined'].widget, forms.DateTimeInput))
peret/visualize-bovw
datamanagers/ClefManager.py
Python
gpl-2.0
3,399
0.00912
from DataManager import DataManager, NoSuchCategoryException import string class CLEFManager(DataManager): def __init__(self, *args, **kwargs): super(CLEFManager, self).__init__(*args, **kwargs) self.PATHS = { "BASE" : "/home/peter/thesis/data_ImageCLEF", "KEYPOINTS" : "/ho...
mage_names(self.PATHS["TEST_CATEGORIES"]) return img_names def _get_image_names(self, file_list): with open(file_list, "r") as f: return [line.split()[0].strip() for line in f] # Overwr
ite parent method to make category optional def build_sample_matrix(self, dataset, category = None): # TODO: Cache results? return super(CLEFManager, self).build_sample_matrix(dataset, category) def _build_sample_matrix(self, dataset, category = None, files = None): if not files...
google/llvm-propeller
lldb/source/Interpreter/embedded_interpreter.py
Python
apache-2.0
4,415
0.001586
import sys if sys.version_info[0] < 3: import __builtin__ as builtins else: import builtins import code import lldb import traceback try: import readline import rlcompleter except ImportError: have_readline = False except AttributeError: # This exception gets hit by the rlcompleter when Linux ...
exit') # When running one line, we might place the string to run in this string # in case it would be hard to correctly escape a string's contents g_run_on
e_line_str = None def get_terminal_size(fd): try: import fcntl import termios import struct hw = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) except: hw = (0, 0) return hw def readfunc_stdio(prompt): sys.stdout.write(prompt) sys.stdout....
neizod/coding-analysis
framework/github/extract/compatibility.py
Python
mit
4,835
0
import os import json import logging from framework._utils import FunctionHook class GitHubExtractCompatibility(FunctionHook): ''' test compatibility over language versions. ''' @staticmethod def handle_python(directory): ''' returns number of Python files in a repository that is syntactic ...
k. ''' from subprocess import getoutput finder = 'find {} -name "{}" | wc -l' return (int(getoutput(('python2 -m compileall {} 2> /dev/null | ' 'grep "File" | wc -l').format(directory))), int(getoutput(('python3 -m compileall {} 2> /dev/null | ' ...
, '*.py')))) @staticmethod def handle_php(directory): ''' returns number of PHP files in a repository that is syntactic compatible in PHP 5.3~5.6. this method use standard PHP program (`php -l`), selection between PHP versions is done by phpbrew. ''' from subprocess impo...
mindw/grin
examples/grinpython.py
Python
bsd-3-clause
4,086
0.002203
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ Transform Python code by omitting strings, comments, and/or code. """ from six.moves import StringIO import os import shlex import string import sys import tokenize import grin __version__ = '1.2' class Transformer(object): """ Transform Python files to remove...
self.comments = comments # Keep strings. self.strings = strings
table = [' '] * 256 for s in string.whitespace: table[ord(s)] = s # A table for the translate() function that replaces all non-whitespace # characters with spaces. self.space_table = ''.join(table) def keep_token(self, kind): """ Return True if we should...
psusloparov/sneeze
pocket_change/pocket_change/__init__.py
Python
apache-2.0
2,161
0.009255
#### DB SETUP #### from pocket_change.database import SQLAlchemyWrapperProxy sqlalchemy_db = SQLAlchemyWrapperProxy() from sneeze.database.models import add_models as sneeze_models from pocket.database import add_models as pocket_models model_adders = [sneeze_models, pocket_models] #### APP CONFIG #### from flask ...
False) and app.config.get('JIRA_RSA_KEY_FILE', False)): app.config['KAICHU_ENABLED'] = True model_adders.append(kaichu_models) else: app.config['KAICHU_ENABLED'] = False #### DB INIT #### sqlalchemy_db.make(app, *model_adders) #### AUTH #### from pocket_change.auth import login_manager login_manager...
rom pocket_change.rest import api from pocket_change.rest.components import load as load_rest_components load_rest_components(app) app.register_blueprint(api, url_prefix='/rest') #### GUI #### from pocket_change.ui import load as load_ui, core as core_ui load_ui(app) app.register_blueprint(core_ui) if app.config['KAI...
y-sira/atcoder
abc005/a.py
Python
mit
48
0
x, y = map(int, input().split()) print(y // x)
ATNF/askapsdp
Tests/SelavySourcefindingService/clients/coast.py
Python
gpl-2.0
2,777
0.006122
#!/usr/bin/env python import sys import os import hashlib import uuid from ftplib import FTP def usage(progname): print "Usage:" print progname + " upload <filename.fits>" print "or" print progname + " submit <filename.job>" print "or" print progname + " download <jobid>" sys.exit(1) def ...
ion file (indicates completion of the first upload) sendfile("/dev/null", remotename + ".md5") print "Upload completed. File ID: " + remotename def submit(filename): f=open(filename,'
r') lines=f.read().split('\n') f.close() if(len([elem for elem in lines if (len(elem.split())==3 and elem[0]!='#' and elem.split()[0]=='Selavy.email')])==0): print "Error: No valid email address provided. Not submitting job." sys.exit(1) print "Submitting job " + filename + "..." jo...
Synerty/vortexpy
vortex/PayloadPriority.py
Python
mit
213
0
""" * Created by Synerty Pty Ltd * * This software is open source, the MIT licens
e applies
. * * Website : http://www.synerty.com * Support : support@synerty.com """ RPC_PRIORITY = 10 DEFAULT_PRIORITY = 100
PaulEG/Various-Projects
Sudu.py
Python
artistic-2.0
347
0.011527
MARV 2 21 7710 36 0 70 MARV 5 01 x 0 0 0 MARV 5 02 7710 66 420 40 MARV 5 14 5710 33 315 70 MARV 5 67 7710 66 500 70 MARV 6 09 + 0 5 x 20 MARV 6 16 + 310 0 0 0 MARV 6 46 + 0 66 660 70 MARV 6 49 + x 66 0 70 MARV 6 82a 7710 66 x x MARV 6 82b 0 0 x 70 MARV 7 27 x x 600 0 MARV 7 63 x 7 70 x MARV 9 01
x x 0 MARV 9 06 x 0 0 0 MARV 9 12
7710 66 660 70
ruleant/buildtime-trend
get_read_key.py
Python
gpl-3.0
1,578
0.000634
#!/usr/bin/env python # vim: set expandtab sw=4 ts=4: ''' Generate a read key for Keen.io API Usage : get_read_key.py [project_name] When argument project_name is used, the read key will be generated to access this project. If no argument is given, the default project name will be used. Copyright (C) 2014 Dieter Adr...
distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, se...
m buildtimetrend.settings import Settings import sys def get_read_key(): ''' Generate a read key for the project and print that key ''' settings = Settings() settings.load_config_file("config.yml") # get project name from argument if len(sys.argv) > 1: settings.set_project_name(sy...
Lekanich/intellij-community
python/testData/console/indent10.after.py
Python
apache-2.0
363
0.00551
x = '''Multiline starts; next line with indent; next line with indent; multiline ends''' x = '''Multiline sta
rts;
first second third fourth fifth multiline ends''' x = '''Multiline starts; #line #line multiline ends'''
jborlik/AdventOfCode2015
day24.py
Python
mit
1,524
0.015748
# -*- coding: utf-8 -*- import itertools def evaluateGroup(packages, grouping): firstcount = 0 qe = 1 weight = [0,0] for i in range(len(packages)): weight[ grouping[i] ] = weight[ grouping[i] ] + packages[i] if (grouping[i] == 0): firstcount = firstcount + 1 qe...
repeat=len(packages)): coun
t = count + 1 (isequal, firstcount, qe) = evaluateGroup(packages,group) if (isequal): print("{}. Equal weights. firstcount={}, qe={}".format(count,firstcount,qe)) if (firstcount <= bestfirstcount): bestfirstcount=firstcount if (qe < bestqe): ...
bq/horus
src/horus/gui/workbench/calibration/main.py
Python
gpl-2.0
9,466
0.004543
# -*- coding: utf-8 -*- # This file is part of the Horus Project __author__ = 'Jesús Arroyo Torrens <jesus.arroyo@bq.com>' __copyright__ = 'Copyright (C) 2014-2016 Mundo Reader S.L.' __license__ = 'GNU General Public License v2 http://www.gnu.org/licenses/gpl2.html' from horus.util import profile from horus.gui.engi...
_capture.set_mode_pattern() pattern_mode = image_capture.pattern_mode pattern_mode.set_brightness(profile.settings['brightness_pattern_calibration']) pattern_mode.set_contrast(profile
.settings['contrast_pattern_calibration']) pattern_mode.set_saturation(profile.settings['saturation_pattern_calibration']) pattern_mode.set_exposure(profile.settings['exposure_pattern_calibration']) laser_mode = image_capture.laser_mode laser_mode.brightness = profile.settings['brightnes...
ad-m/taravel
taravel/orders/migrations/0001_initial.py
Python
mit
1,251
0.003997
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-08 23:49 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial =
True dependencies = [ ('trips', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Order', fields=[ ('id', models
.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True, verbose_name='Creation date')), ('paid', models.DateField(blank=True, null=True, verbose_name='Date of payment')), ('trip', models.For...
kantel/processingpy
sketches/modes/PythonMode/examples/Topics/Simulate/MultipleParticleSystems/particle_system.py
Python
mit
1,129
0.000886
# A list is used to manage the list of Particles. from particle import Particle from crazy_particle import CrazyParticle class ParticleSystem(object): def __init__(self, num, v): self.particles = [] # Initialize the list. self.origin = v.get() # Store the origin point. for i in range(n...
# Cycle through the list backwards, because we are deleting while # iterating.
for i in reversed(range(len(self.particles))): p = self.particles[i] p.run() if p.isDead(): del self.particles[i] def addParticle(self): p = None # Add either a Particle or CrazyParticle to the system. if int(random(0, 2)) == 0: ...
anhstudios/swganh
data/scripts/templates/object/tangible/loot/loot_schematic/shared_spear_rack_schematic.py
Python
mit
479
0.045929
#### 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 = Tangible() result.template = "object/tangible/loot/loot_schematic/shared_spear_rack_schematic.iff" result.attribute_template_id = -1 result.stfName("craft_item_ingredient...
BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
mikeshultz/whatthediff
whatthediff/forms.py
Python
gpl-2.0
818
0.013447
from django import forms from django.contrib.auth.forms import UserCreationForm from .models import WhatTheUser class RegistrationForm(UserCreationForm): #first_name = forms.CharField() #last_name = forms.CharField
() #email = forms.EmailField() #password1 = forms.CharField() #password2 = forms.CharField() class Meta: model = WhatTh
eUser fields = ['email', 'first_name', 'last_name', ] #fields = [first_name, last_name, email, password1, password2] """def clean(self): cleaned_data = super(RegistrationtForm, self).clean() if cleaned_data.get('password1') is None \ or cleaned_data.get('password1') == ...
mwkang/zeppelin
flink/src/main/resources/python/zeppelin_pyflink.py
Python
apache-2.0
2,045
0.004401
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
or the specific language governing permissions and # limitat
ions under the License. # from pyflink.common import * from pyflink.dataset import * from pyflink.datastream import * from pyflink.table import * from pyflink.table.catalog import * from pyflink.table.descriptors import * from pyflink.table.window import * import pyflink from py4j.java_gateway import java_import in...
iLoop2/ResInsight
ThirdParty/Ert/devel/python/python/ert/job_queue/job_queue_manager.py
Python
gpl-3.0
2,799
0.01965
# Copyright (C) 2014 Statoil ASA, Norway. # # The file 'job_queue_manager.py' is part of ERT - Ensemble based Reservoir Tool. # # ERT 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 vers...
turn JobQueueManager.cNamespace().is_running( self ) def free(self): JobQueueManager.cNamespace().free(self) def jobComplete(self , job_index): return JobQueueManager.cNamespace().job_complete( self , job_index ) #########################################################...
tType("job_queue_manager", JobQueueManager) JobQueueManager.cNamespace().alloc = cwrapper.prototype("c_void_p job_queue_manager_alloc( job_queue) ") JobQueueManager.cNamespace().free = cwrapper.prototype("void job_queue_manager_free( job_queue_manager )") JobQueueManager.cNamespace().start_que...
edx/edx-analytics-dashboard
analytics_dashboard/learner_analytics_api/v0/views.py
Python
agpl-3.0
6,267
0.002074
from requests.exceptions import ConnectTimeout from rest_framework.exceptions import PermissionDenied from rest_framework.generics import RetrieveAPIView from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from .clients import LearnerAPIClient from .permissions import Ha...
o define the developer message returned with 404s.') @property def not_found_error_code(self): raise NotImplementedError('Override this attribute to define the error_code string returned with 404s.') def handle_exception(self, exc): if isinstance(exc, PermissionDenied): return ...
return super().handle_exception(exc) class LearnerDetailView(NotFoundLearnerApiViewMixin, BaseLearnerApiView): """ Forwards requests to the Learner Analytics API's Learner Detail endpoint. """ not_found_error_code = 'no_learner_for_course' @property def not_found_developer_message(self): ...
Kronuz/pyXapiand
xapiand/server/base.py
Python
gpl-2.0
11,482
0.001742
from __future__ import unicode_literals, absolute_import, print_function import time import logging import weakref import threading from hashlib import md5 from functools import wraps from gevent import socket from gevent.server import StreamServer from gevent.threadpool import ThreadPool from ..utils import format_...
: pass class DeadException(Exception): def __init__(self, command): self.command = command class AliveCommand(object):
""" Raises DeadException if the object's cmd_id id is not the same as it was when the object was created. """ cmds_duration = 0 cmds_start = 0 cmds_count = 0 def __init__(self, parent, cmd, origin): parent.cmd_id = getattr(parent, 'cmd_id', 0) + 1 self.parent = parent ...
ministryofjustice/cla_backend
cla_backend/apps/core/routers.py
Python
mit
1,336
0
from rest_framework
.routers import DefaultRouter, Route class SingletonRouter(DefaultRouter): """ Use this router instead of the DRF DefaultRouter if you have only one resource accessible from an endpoint. This gives you the following urls: * prefix/ GET: returns 404 or the object POST: creates th...
ect PATCH: updates the object partially DELETE: deletes the object * prefix/<method>/ used for @action and @link methods (NOTE: not tested yet) """ routes = [ # List route. Route( url=r"^{prefix}{trailing_slash}$", mapping={ ...
andybond13/fontina
fontina.py
Python
gpl-2.0
7,414
0.054222
#!/usr/bin/python import csv import datetime import os import copy class Trip: dols = [] dists = [] gals = [] octs = [] eths = [] drivers = [] tires = [] miles = 0 gallons = 0 actualGals = 0 days = 0 octane = 0 snowtires =
0 make = 0 model = 0 year = 0 engineIV = 0 enginecyl = 0 engineL = 0 ethanol = 0 driver = 0 avgMileage = 0 beginDate = 0 hybrid = 0 def write(self): out = [self.miles,self.gallons,self.actualGals,self.dollars,self.days,sel
f.octane,self.snowtires,self.make,self.model,self.year,self.engineIV,self.enginecyl,self.engineL,self.ethanol,self.driver,self.avgMileage,self.beginDate,self.hybrid] return out def clear(self): self.dols[:] = [] self.dists[:] = [] self.gals[:] = [] self.octs[:] = [] self.eths[:] = [] self.drivers[:] = ...
hubenjm/Project-Euler
problem18.py
Python
mit
992
0.044355
datafile1 = "./problem18data.t
xt" datafile2 = "./problem67data.txt" def getdata(filename): l = [
] with open(filename, 'r') as f: for line in f: row = [int(s.strip()) for s in line.split(" ")] l.append(row) return l def read_data_test(): l = getdata(datafile) print l def longest_path(filename): l = getdata(filename) m = len(l) longest = l[0] longest_next = [] for j in xrange(1,m): #j corresp...
jaraco/paramiko
paramiko/common.py
Python
lgpl-2.1
8,105
0
# Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com> # # This file is part of paramiko. # # Paramiko is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (a...
AILURE) cMSG_CHANNEL_WINDOW_ADJUST = byte_chr(MSG_CHANNEL_WINDOW_ADJUST) cMSG_CHANNEL_DATA = byte_chr(MSG_CHANNEL_DATA)
cMSG_CHANNEL_EXTENDED_DATA = byte_chr(MSG_CHANNEL_EXTENDED_DATA) cMSG_CHANNEL_EOF = byte_chr(MSG_CHANNEL_EOF) cMSG_CHANNEL_CLOSE = byte_chr(MSG_CHANNEL_CLOSE) cMSG_CHANNEL_REQUEST = byte_chr(MSG_CHANNEL_REQUEST) cMSG_CHANNEL_SUCCESS = byte_chr(MSG_CHANNEL_SUCCESS) cMSG_CHANNEL_FAILURE = byte_chr(MSG_CHANNEL_FAILURE) #...
jantman/biweeklybudget
biweeklybudget/alembic/versions/08b6358a04bf_txnreconcile_allow_txn_id_to_be_null.py
Python
agpl-3.0
765
0
"""TxnReconcile allow txn_id to be null Revision ID: 08b6358a04bf Revises: 04e61490804b Create Date:
2018-03-07 19:48:06.050926 """ from alembic import op from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '08b6358a04bf' down_revision = '04e61490804b' branch_labels = None depends_on = None def upgrade(): op.alter_column( 'txn_reconciles', 'txn_id',
existing_type=mysql.INTEGER(display_width=11), nullable=True ) def downgrade(): conn = op.get_bind() conn.execute("SET FOREIGN_KEY_CHECKS=0") op.alter_column( 'txn_reconciles', 'txn_id', existing_type=mysql.INTEGER(display_width=11), nullable=False ) con...
christiangalsterer/httpbeat
vendor/github.com/elastic/beats/metricbeat/tests/system/test_reload.py
Python
apache-2.0
2,260
0.000885
import re import sys import unittest import metricbeat import os import time # Further tests: # * Mix full config modules with reloading modules # * Load empty file # * Add remove module # * enabled / disable module # * multiple files # * Test empty file class Test(metricbeat.BaseTest): @unittest.skipUnless(re....
w line is updated self.wait_until( lambda: self.log_contains("Starting 1 runner"), max_timeout=10) self.wait_until(lambda: self.output_lines() > 0) # Remove config again os.remove(config_path) # Wait until offset for new line is updated self.wai...
s() time.sleep(1) # Make sure no new lines were added since stopping assert lines == self.output_lines() proc.check_kill_and_wait()
saeedhadi/rt-thread
bsp/x86/rtconfig.py
Python
gpl-2.0
1,647
0.009715
import os # toolchains options ARCH='ia32' CPU='' CROSS_TOOL='gcc' if os.getenv('RTT_CC'): CROSS_TOOL = os.getenv('RTT_CC') # cross_tool provides the cross compiler # EXEC_PATH is the compiler execute path, for example, CodeSourcery, if CROSS_TOOL == 'gcc': PLATFORM = 'gcc' EXEC_PATH = 'E:/Prog...
=======ERROR=====================
=======' print 'Not support iar yet!' print '=================================================' exit(0) if os.getenv('RTT_EXEC_PATH'): EXEC_PATH = os.getenv('RTT_EXEC_PATH') BUILD = 'debug' if PLATFORM == 'gcc': # toolchains PREFIX = 'i686-elf-' CC = PREFIX + 'gcc' AS = PRE...
sdague/home-assistant
tests/components/bond/test_cover.py
Python
apache-2.0
4,207
0.000713
"""Tests for the Bond cover device.""" from datetime import tim
edelta from bond_api import Action, DeviceType from homeassistant import core from homeassistant.components.cover import DOMAIN as COVER_DOMAIN from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_CLOSE_COVER, SERVICE_OPEN_COVER, SERVICE_STOP_COVER, ) from homeassistant.helpers.entity_registry im...
ction, patch_bond_device_state, setup_platform, ) from tests.common import async_fire_time_changed def shades(name: str): """Create motorized shades with given name.""" return {"name": name, "type": DeviceType.MOTORIZED_SHADES} async def test_entity_registry(hass: core.HomeAssistant): """Tests ...
SUSE/azure-sdk-for-python
azure-mgmt-resource/azure/mgmt/resource/resources/v2016_02_01/models/resources_move_info.py
Python
mit
1,105
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 Gene
rator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class ResourcesMoveInfo(Model): """Parameters of move resources. :param resources: The ids of the r...
get_resource_group: The target resource group. :type target_resource_group: str """ _attribute_map = { 'resources': {'key': 'resources', 'type': '[str]'}, 'target_resource_group': {'key': 'targetResourceGroup', 'type': 'str'}, } def __init__(self, resources=None, target_resource_gr...
markgw/jazzparser
bin/analysis/findsong.py
Python
gpl-3.0
10,264
0.006333
#!/usr/bin/env ../jazzshell """ Perform song identification by loading up a corpus of harmonic analyses and comparing parse results to all of them, according to some distance metric. """ """ ============================== License ======================================== Copyright (C) 2008, 2010-12 University of Edin...
arch results to print for each query (parse result). Default: 5. Use -1 to print dista
nces from all songs in the corpus") parser.add_option("-g", "--gold-only", dest="gold_only", action="store_true", help="skip results that have no gold standard sequence associated with them (we can't tell which is the right answer for these)") parser.add_option("--mc", "--metric-computation", dest="metric_compu...
parpg/parpg
parpg/dialogueprocessor.py
Python
gpl-3.0
15,770
0.003044
# This file is part of PARPG. # # PARPG 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. # # PARPG is distributed in the hop...
e interface'.format(dialogue) self._dialogue = dialogue return locals()
dialogue = property(**dialogue()) def dialogue_section_stack(): def fget(self): return self._dialogue_section_stack def fset(self, new_value): assert isinstance(new_value, Sequence) and not \ isinstance(new_value, basestring), \ ...
mitsuhiko/python-unio
unio.py
Python
bsd-3-clause
15,682
0
import io import os import sys import codecs import contextlib # We do not trust traditional unixes about having reliable file systems. # In that case we know better than what the env says and declare this to # be utf-8 always. has_likely_buggy_unicode_filesystem = \ sys.platform.startswith('linux') or 'bsd' in s...
_is_binary_reader(buf, True): return buf def _stream_is_misconfigured(stream): """A stream is misconfigured if it's encoding is ASCII.""" return is_ascii_encoding(getattr(stream, 'encoding', None)) def _wrap_stream_for_text(stream, encoding, errors): if errors is None: ...
= get_std_stream_encoding() return _NonClosingTextIOWrapper(_FixupStream(stream), encoding, errors) def _is_compatible_text_stream(stream, encoding, errors): stream_encoding = getattr(stream, 'encoding', None) stream_errors = getattr(stream, 'errors', None)
ICTU/quality-time
components/collector/src/source_collectors/gitlab/source_version.py
Python
apache-2.0
700
0.001429
"""GitLab source version collector.""" from packaging.version import Version from base_collectors import SourceVersionCollector from collecto
r_utilities.type import Response, URL from .base import GitLabBase class GitLabSourceVersion(GitLabBase, SourceVersionCollector): """Collector class to measure the version of a GitLab instance.""" async def _api_url(self) -> URL: """Override to return the version API URL.""" return URL
(f"{await super()._api_url()}/api/v4/version") async def _parse_source_response_version(self, response: Response) -> Version: """Override to return the GitLab version.""" return Version((await response.json())["version"])
knuu/competitive-programming
atcoder/corp/aising2019_a.py
Python
mit
84
0
N = int(input()) H = int(inp
ut()) W = int(input()) print((N -
H + 1) * (N - W + 1))
ranea/ccepy
setup.py
Python
mit
4,235
0.000236
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspat...
tall_requires" vs pip's # requirements files see: # https://packaging.python.org/en/latest/requirements.html # install_requires=['peppercorn'], # List run-time dependencies here. These will be installed by pip when # your project is installed. For an analysis of "install_requires" vs pip's # r...
nstall_requires=['peppercorn'], # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] extras_require={ 'dev': ['sphinx'], 'test': ['hypothesis'], }, # ...
nielsbuwen/ilastik
ilastik/shell/gui/splashScreen.py
Python
gpl-3.0
1,515
0.006601
###############
################################################################ # ilastik: interactive learning and segmentation toolkit # # Copyright (C)
2011-2014, the ilastik developers # <team@ilastik.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 2 # of the License, or (at your option) any...
leonidas141/HIT-ML-2016-report
load.py
Python
mpl-2.0
1,459
0.028787
# -*- coding: utf-8 -*- """ Created on Sun Jan 8 14:45:26 2017 @author: leonidas """ import numpy as np import operator def classify(inputPoint,dataSet,labels,k): dataSetSize = dataSet.shape[0] diffMat = np.tile(inputPoint,(dataSetSize,1))-dataSet sqDiffMat = pow(diffMat,2) sqDistances = sqDi...
ename) for i in range(32): temp = data.readline() for j in range(32): try: vect.append(int(temp[j])) except(ValueError): print temp[j],'error',ValueError return vect def loa
d_train_data(): train_lables = [] size = 100 train_data = np.zeros((size*10,1024)) for i in range(10): for j in range(size): train_lables.append(i) train_data[i*100+j,:] = mat_to_vect('train/%s/%s.txt' %( i,j )) return train_lables,train_data def ...
ehouarn-perret/EhouarnPerret.Python.Kattis
Trivial/Different Distances.py
Python
mit
179
0.039106
impo
rt math while True: s = input() if s != "0": x1, y1, x2, y2, p = map(fl
oat, s.split()) r = (abs(x1 - x2) ** p + abs(y1 - y2) ** p) ** (1 / p) print(r) else: break
SINTEF-Infosec/Incident-Information-Sharing-Tool
incidents/migrations/0024_incidentnotificationstatus.py
Python
apache-2.0
624
0.001603
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('incidents', '0023_alert_link'), ] operations = [ migrations.CreateModel( name='IncidentNotificationStatus', ...
('notified', models.BooleanField(default=False)),
('incident', models.ForeignKey(to='incidents.Incident')), ], ), ]
shojikai/python-google-api-clients
test/test_bigquery_dataset.py
Python
apache-2.0
3,541
0.003389
import os import sys import unittest from pprint import pprint sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + '/../') from google_api_clients.bigquery import BigQuery from google_api_clients.bigquery.errors import ParameterError class BigQueryTest(unittest.TestCase): def setUp(self): se...
e_expiration_ms=3600000, description='Description', friendly_name='Friendly Name', location='EU') self.assertTrue(bool(res)) print('info dataset') res = self.bq.info_dataset(self.dataset_id, project_id=self.project_id) self.assertEqual(1, len(res['access'])) self.ass...
s'])) self.assertEqual('Description', res['description']) self.assertEqual('Friendly Name', res['friendlyName']) self.assertEqual('EU', res['location']) pprint(res) print('show datasets') res = self.bq.show_datasets(project_id=self.project_id, all=True, max_results=10) ...
appfluence/prioritymatrix-python
pmatrix/user.py
Python
apache-2.0
3,046
0.005253
import json import demjson from datetime import datetime, timedelta class User(object): account_manager = "" date_joined = None email = "" first_name = "" id = None last_login = None last_name = "" paying_single = False paying_team = False resource_uri = "" teammate = False...
file: " + self.user_profile) print("Date joined: " + str(datetime.fromtimestamp(float(self.date_joined)))) print("Last login: " + str(datetime.fromtimestamp(float(self.last_login)))) if (self.teammate):
print("Is teammate") else: print("Is not teammate")
foxdog-studios/pyddp
ddp/pubsub/pod_message_filter.py
Python
apache-2.0
1,493
0.00067
# -*- coding: utf-8 -*- # Copyright 2014 Foxdog Studios # # 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 l...
ected __all__ = ['PodMessageFilter'] class PodMessageFilter(Subscriber): def __init__(self, board, pod_message_filter): super(PodMessageFilter, self).__init__(board, { PodReceived: self._on_received}) self._board = board self._pod_message_filter = pod_message_filter d...
pod): if self._accept(pod): topic = PodAccepted + self._get_type(pod) else: topic = PodRejected self._board.publish(topic, pod) def _accept(self, pod): return self._pod_message_filter.accept(pod) def _get_type(self, pod): return self._pod_messag...
justin-l/alltest
thread.py
Python
apache-2.0
440
0.015909
#!/usr/bin/env python #coding = utf-8 import threading lk = threading.Lock() g_counter = 0 def count(n): global g_counter for i in xrange(n): lk.acq
uire() g_counter += 1 lk.release() print g_counter return g_cou
nter t1 = threading.Thread(target=count,args=(10000000,)) t2 = threading.Thread(target=count,args=(10000000,)) t1.start() t2.start() print t1.join() print t2.join() print "final",g_counter
oesteban/niworkflows
niworkflows/interfaces/bids.py
Python
bsd-3-clause
35,326
0.001698
# 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...
workflows", "data/nipreps.json")).read_text()) BIDS_DERIV_ENTITIES = frozenset({e["name"] for e in _pybids_spec["entities"]}) BIDS_DERIV_PATTERNS = tuple(_pybids_spec["default_path_patterns"]) STANDARD_SPACES = _get_template_list() LOGGER = logging.getLogger("nipype.interface") def _none(): return None # Autom...
"int16"), ("probseg", "float32"), ("boldref", "source"), ), ) class _BIDSBaseInputSpec(BaseInterfaceInputSpec): bids_dir = traits.Either( (None, Directory(exists=True)), usedefault=True, desc="optional bids directory" ) bids_validate = traits.Bool(True, usedefault=True, desc="...
newvem/pytz
pytz/zoneinfo/Asia/Rangoon.py
Python
mit
564
0.069149
'''tzinfo timezone information for Asia/Rangoon.'''
from pytz.tzinfo import DstTzInfo from pytz.tzinfo import memorized_datetime as d from pytz.tzinfo import memorized_ttinfo as i class Rangoon(DstTzInfo): '''Asia/Rangoon timezone definition. See datetime.tzinfo for details''' zone = 'Asia/Rangoon'
_utc_transition_times = [ d(1,1,1,0,0,0), d(1919,12,31,17,35,24), d(1942,4,30,17,30,0), d(1945,5,2,15,0,0), ] _transition_info = [ i(23100,0,'RMT'), i(23400,0,'BURT'), i(32400,0,'JST'), i(23400,0,'MMT'), ] Rangoon = Rangoon()
dtkelch/Tagger
tweepy/tweepy/models.py
Python
mit
12,645
0.001503
# Tweepy # Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. from tweepy.error import TweepError from tweepy.utils import parse_datetime, parse_html_value, parse_a_href class ResultSet(list): """A list like object that holds results from a Twitter API query.""" def __init__(self, max_id=None, s...
(cls, api, json): dm = cls(api) for k, v in json.items(): if k == 'sender' or k == 'recipient': setattr(dm, k, User.parse(api, v)) elif k == 'created_at': setattr(dm, k, parse_datetime(v)) else: setattr(dm, k, v) ...
: relationship = json['relationship'] # parse source source = cls(api) for k, v in relationship['source'].items(): setattr(source, k, v) # parse target target = cls(api) for k, v in relationship['target'].items(): setattr(target, k, v) ...
Kryz/sentry
tests/sentry/web/frontend/test_auth_organization_login.py
Python
bsd-3-clause
6,946
0
from __future__ import absolute_import from django.core.urlresolvers import reverse from sentry.models import AuthIdentity, AuthProvider, OrganizationMember from sentry.testutils import AuthProviderTestCase # TODO(dcramer): this is an integration test class OrganizationAuthSettingsTest(AuthProviderTestCase): de...
assert resp.status_code == 200 assert self.provider.TEMPLATE in resp.content path = reverse('sentry-auth-sso') resp = self.client.post(path, {'email': 'foo@example.com'}) self.assertTemplateUsed(resp, 'sentry/auth-confirm-identity.html') assert resp.status_code == 200 ...
tatus_code == 302 auth_identity = AuthIdentity.objects.get( auth_provider=auth_provider, ) user = auth_identity.user assert user.email == 'foo@example.com' member = OrganizationMember.objects.get( organization=organization, user=user, ...
ee-in/python-api
plotly/tests/test_core/test_graph_objs/test_get_data.py
Python
mit
6,703
0
from __future__ import absolute_import from unittest import TestCase from plotly.graph_objs import (Data, Figure, Layout, Line, Margin, Marker, Scatter, XAxis, YAxis) class TestGetData(TestCase): fig = None def setUp(self): super(TestGetData, self).setUp() se...
'name': 'North America', 'text': ['United States', 'Canada'], 'x'
: [52698, 43117], 'y': [53, 31] }, { 'name': 'Europe', 'text': ['Germany', 'Britain', 'France', 'Spain', 'Italy', 'Czech Rep.', 'Greece', 'Poland'], 'x': [39317, 37236, 35650, 30066, 29570, 27159, 23557, 210...
johngian/mozillians
mozillians/common/utils.py
Python
bsd-3-clause
3,547
0.000282
import sys from django.conf import settings import requests import waffle from nameparser import HumanName def absolutify(url): """Takes a URL and prepends the SITE_URL""" site_url = getattr(settings, 'SITE_URL', False) # If we don't define it explicitly if not site_url: protocol = settings...
roups(idp), 'tags': [] if delete else profile.get_cis_tags(), # Derived fields 'firstName': human_name.first, 'lastName': human_name.last, # Hardcoded fields 'preferredLanguage': 'en_US', 'phoneNumbers': [], 'nicknames': [...
'SSHFingerprints': [], 'PGPFingerprints': [], 'authoritativeGroups': [] } results.append(data) return results
f0x11/Merak
spider/__init__.py
Python
mit
68
0
#!/usr/b
in/env python3 # -*- coding: utf-8
-*- __author__ = 'f0x11'
mypaint/mypaint
gui/meta.py
Python
gpl-2.0
10,067
0.002598
# -*- coding: utf-8 -*- # This file is part of MyPaint. # Copyright (C) 2007-2015 by Martin Renold <martinxyz@gmx.ch> # Copyright (C) 2015-2016 by the MyPaint Development Team # # 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 ...
r line, optionally with an email # TRANSLATORS: address within angle brackets "<email@somewhere.com>", and # TRANSLATORS: optionally with a year or year range indicating when the # TRANSLATORS: contributions were made, e.g: 2005 or 2010-2012 etc. u"translator-credits", ) ## About dialog for the app d...
on_string(): """Get a string describing the versions of important libs. >>> type(get_libs_version_string()) == str True """ versions = [ ("Python", "{major}.{minor}.{micro}".format( major = sys.version_info.major, minor = sys.version_info.minor, micro = ...
google-research/language
language/mentionmemory/utils/test_utils.py
Python
apache-2.0
4,490
0.008241
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 by ...
n_size mention_start_positions.sort() mention_end_positions = mention_start_positions + mention_size - 1 dense_span_starts = np.zeros(shape=max_length, dtype=np.int64) dense_span_starts[mention_start_positions] = 1 dense_span_ends = np.zeros(shape=max_length, dtype=np.int64) dense_span_ends[mention_end_po...
mention_end_positions[idx] + 1) for idx in linked_mention_indices ] if n_linked_mentions > 0: dense_linked_mention_positions = np.concatenate( linked_mention_position_slices) else: dense_linked_mention_positions = np.arange(0) linked_mention_ids = np.random.randint( low=1, high=ent...
gnodar01/basic-blog
util/jinjaenv.py
Python
apache-2.0
325
0
import os import jinja2 tem
plate_dir = os.path.join(os.path.dirname(__file__), '../views') jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=True) def rende
r_str(template, **params): t = jinja_env.get_template(template) return t.render(params)
MAPC/cedac
map/models.py
Python
bsd-3-clause
1,599
0.001876
from django.db import models from django.utils.translation import ugettext as _ class Category(models.Model): title = models.CharField(max_length=50) slug = models.SlugField() order = models.IntegerField(default=1) class Meta: verbose_name = _('Category') verbose_name_plural = _('Cat...
png', 'image/png'), ('image/jpeg', 'image/jpeg'), ) title = models.CharField(max_length=100) category = models.ForeignKey(Category) visible = models.BooleanField() category_order = models.IntegerField(default=1) map_order = models.IntegerFie
ld(default=1) wms_server = models.ForeignKey(WMSServer) wms_layers = models.CharField(max_length=100) wms_styles = models.CharField(max_length=100, null=True, blank=True) wms_format = models.CharField(max_length=10, choices=WMS_FORMAT_OPTIONS, default='image/png') wms_transparent = models.BooleanFi...
mcclurmc/juju
juju/providers/ec2/securitygroup.py
Python
agpl-3.0
7,289
0.000274
from twisted.internet.defer import Deferred, inlineCallbacks, returnValue from txaws.ec2.exception import EC2Error from juju.errors import ProviderInteractionError from juju.lib.twistutils import gather_results from .utils import log def _get_juju_security_group(provider): """Get EC2 security group name for env...
oup, e)) returnValue(False)
miguelgrinberg/heat
heat/engine/resources/openstack/neutron/net.py
Python
apache-2.0
7,583
0
# # 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 # ...
t support class Net(neutron.NeutronResource): PROPERTIES = ( NAME, VALUE_SPECS, ADMIN_STATE_UP, TENANT_ID, SHARED, DHCP_AGENT_IDS, PORT_SECURITY_ENABLED, ) = ( 'name', 'value_specs', 'admin_state_up', 'tenant_id', 'shared',
'dhcp_agent_ids', 'port_security_enabled', ) ATTRIBUTES = ( STATUS, NAME_ATTR, SUBNETS, ADMIN_STATE_UP_ATTR, TENANT_ID_ATTR, PORT_SECURITY_ENABLED_ATTR, MTU_ATTR, ) = ( "status", "name", "subnets", "admin_state_up", "tenant_id", "port_security_enabled", "mtu", ) ...
benkonrath/transip-api
tests/service_tests/test_webhosting.py
Python
mit
4,475
0.001341
import unittest from transip.client import MODE_RO, MODE_RW from transip.service.objects import MailBox, MailForward, WebHost from transip.service.webhosting import WebhostingService try: from unittest.mock import Mock, patch except ImportError: from mock import patch, Mock class TestWebhostingService(unitt...
result='mock', parameters=('info@example.com', 'mock'), mode=MODE_RW ) def test_get_available_upgrades(self): self._gen
eric_test( soap_method='getAvailableUpgrades', method='get_available_upgrades', result='mock', parameters=('example.com',), mode=MODE_RO ) def test_set_mailbox_password(self): self._generic_test( soap_method='setMailBoxPassword...
egens/toolkit-for-ynab
lib/kango-framework-latest/kango/settings.py
Python
mit
416
0.004808
import os import json VERSION = '1.7.9' BUILD = 'e39b6ff2fcc8' PACKAGE_ID = 'dev' KEYWORDS = { "product": "kango", "ie.engine": "KangoEngine", "ie.bho": "KangoBHO" } try: with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'se
ttings.json'), 'r') as f: settings = json.load(f) KEYWORDS.update(settings.get('keywords', {})) except IO
Error: pass
lithiumtech/skybase.io
skybase/skytask/pack/submit.py
Python
apache-2.0
11,301
0.005309
import os import logging import tarfile import shutil import ConfigParser import tempfile from skybase import config as sky_cfg from skybase.skytask import SkyTask from skybase import skytask from skybase.actions import pack as pack_actions from skybase.skytask import pack from skybase.actions import sky_boto as sky_b...
self.result.status = sky_cfg.API_STATUS_FAIL return self.result else: self.result.output += "Cannot locate aws credentials, please confirm they are set in " + aws_creds_file \ + "\n" self.result.status = sky_cfg.API_STATUS_FA...
_dir, artiball) depot_bucket_name = os.path.expanduser(self.runner_cfg.data['package_depot_S3_bucket']) # Hardcoding default to True for pack group command, revisit later self.args['apply'] = True if self.args['apply']: self.logger.write('Uploading package to S3 bucket ' + d...
krishna11888/ai
third_party/gensim/gensim/models/hdpmodel.py
Python
gpl-2.0
23,000
0.002174
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2012 Jonathan Esterhazy <jonathan.esterhazy at gmail.com> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html # # HDP inference code is adapted from the onlinehdp.py script by # Chong Wang (chongw at cs.princeton.edu). # http://www.c...
logsticks = np.zeros(n) Elogsticks[0: n - 1] = ElogW Elogsticks[1:] = Elogsticks[1:] + np.cumsum(Elog1_W) return Elogsticks def lda_e_step(doc_word_ids, doc_word_counts, alpha, beta, max_iter=100): gamma = np.ones(len(alpha)) expElogtheta = np.exp(dirichlet_expectation(gamma)) betad
= beta[:, doc_word_ids] phinorm = np.dot(expElogtheta, betad) + 1e-100 counts = np.array(doc_word_counts) for _ in xrange(max_iter): lastgamma = gamma gamma = alpha + expElogtheta * np.dot(counts / phinorm, betad.T) Elogtheta = dirichlet_expectation(gamma) expElogtheta = np...
AsgerPetersen/QGIS
python/plugins/processing/algs/lidar/lastools/blast2dem.py
Python
gpl-2.0
3,426
0.001168
# -*- coding: utf-8 -*- """ *************************************************************************** blast2dem.py --------------------- Date : September 2013 Copyright : (C) 2013 by Martin Isenburg Email : martin near rapidlasso point com ***************...
ands.append("-use_tile_bb") self.addParametersRasterOutputCommands(commands) self.addParame
tersAdditionalCommands(commands) LAStoolsUtils.runLAStools(commands, progress)
Clarify/clarify_python_2
setup.py
Python
mit
1,348
0.000742
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst...
thor_email='murphy@clarify.io', url='https://github.com/Clarify/clarify_python_2', pa
ckages=[ 'clarify_python_2', ], package_dir={'clarify_python_2': 'clarify_python_2'}, include_package_data=True, install_requires=[ ], license="MIT", zip_safe=False, keywords='clarify_python_2 clarify', classifiers=[ 'Development Status :: 5 - Product...
jl4ge/cs3240-labdemo
names.py
Python
mit
67
0
N
AMES = ["Agatha", "Be
rnard", "Lucy", "Russle", "April", "Sammy"]
JungInkyo/Qualcomm_sensor
pa10a/btserver/bthandler.py
Python
gpl-2.0
2,423
0.002889
import asyncore import logging import re from bterror import BTError logger = logging.getLogger(__name__) class BTClientHandler(asyncore.dispatcher_with_send): """BT handler for client-side socket""" def __init__(self, socket, server): asyncore.dispatcher_with_send.__init__(self, socket) sel...
ing_status' variable to False # - history start_time end_time # Stop sending real time data, and quer
y the history data from the database. Getting history data might # take some time so we should use a different thread to handle this request if re.match('stop', command) is not None: self.sending_status['real-time'] = False pass if re.match('start', command) is not...