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
eduNEXT/edx-platform
openedx/core/djangoapps/session_inactivity_timeout/middleware.py
Python
agpl-3.0
2,044
0.003425
""" Middleware to auto-expire inactive sessions after N seconds, which is configurable in settings. To enable this feature, set in a settings.py: SESSION_INACTIVITY_TIMEOUT_IN_SECS = 300 This was taken from StackOverflow (http://stackoverflow.com/questions/14830669/how-to-expire-django-session-in-5minutes) """ f...
me user made a request to server, which is stored in session data last_touch = request.session.get(LAST_TOUCH_KEYNAME) # have we stored a 'last visited' in session? NOTE: first time access after login # this ke
y will not be present in the session data if last_touch: # compute the delta since last time user came to the server time_since_last_activity = utc_now - last_touch # did we exceed the timeout limit? if time_since_last_activity > timedelta(sec...
jarped/QGIS
python/plugins/db_manager/dlg_sql_window.py
Python
gpl-2.0
12,633
0.001662
# -*- coding: utf-8 -*- """ /*************************************************************************** Name : DB Manager Description : Database manager plugin for QGIS Date : May 23, 2011 copyright : (C) 2011 by Giuseppe Sucameli email : brush.tyler@...
lts) self.btnExecute.clicked.connect(self.executeSql) self.btnClear.clicked.connect(self.clearSql) self.presetStore.clicked.connect(self.storePreset) self.presetDelete.clicked.connect(self
.deletePreset) self.presetCombo.activated[str].connect(self.loadPreset) self.presetCombo.activated[str].connect(self.presetName.setText) self.updatePresetsCombobox() # hide the load query as layer if feature is not supported self._loadAsLayerAvailable = self.db.connector.hasCus...
ity/pants
src/python/pants/engine/legacy/graph.py
Python
apache-2.0
11,698
0.008036
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import logging from ...
.structs import BundleAdaptor, BundlesField, SourcesField, TargetAdaptor from pants.engine.nodes import Return, SelectNode, State, Throw from pants.engine.selectors import Select, SelectDependencies, SelectProjection from pants
.source.wrapped_globs import EagerFilesetWithSpec from pants.util.dirutil import fast_relpath from pants.util.objects import datatype logger = logging.getLogger(__name__) class LegacyBuildGraph(BuildGraph): """A directed acyclic graph of Targets and dependencies. Not necessarily connected. This implementation ...
130s/bloom
bloom/config.py
Python
bsd-3-clause
12,185
0.001067
# Software License Agreement (BSD License) # # Copyright (c) 2013, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above...
f, key, value): if key == 'default' and self.values: if value not in self.values: error( "Invalid input '{0}' for '{1}', acceptable values: {2}."
.format(value, self.name, self.values), exit=True ) object.__setattr__(self, key, value) def __str__(self): msg = fmt('@_' + sanitize(self.name) + ':@|') if self.spec is not None: for key, val in self.spec.iteritems(): ...
Tuxemon/Tuxemon
tuxemon/event/actions/print.py
Python
gpl-3.0
1,942
0
# # Tuxemon # Copyright (c) 2014-2017 William Edwards <[email protected]>, # Benjamin Bean <[email protected]> # # This file is part of Tuxemon # # 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 #...
: variable: Optional[str] @final class PrintAction(EventAction[PrintActionParameters]): """ Print the current value of a game variable to the console. If no variable is specified, print out values of all game variables. Script usage: ..
code-block:: print print <variable> Script parameters: variable: Optional, prints out the value of this variable. """ name = "print" param_class = PrintActionParameters def start(self) -> None: player = self.session.player variable = self...
borg-project/borg
borg/regression.py
Python
mit
4,929
0.005478
"""@author: Bryan Silverthorn <[email protected]>""" import numpy import sklearn.svm import sklearn.pipeline import sklearn.linear_model import sklearn.decomposition import sklearn.kernel_approximation import borg logger = borg.get_logger(__name__, default_level = "INFO") class MultiClassifier(object): def __in...
t) def predict(self, tasks, features): """Predict RTD probabilities.""" features = numpy.asarray(features) (P,) = self._model.log_weights.shape (N, _) = self._masks.shape (M, F) = features.shape predictions = self._regression.predict_log_proba(features) we...
weights[:, self._masks[n]] += predictions[:, n, None] weights = numpy.exp(weights) weights += 1e-64 weights /= numpy.sum(weights, axis = -1)[..., None] return weights @property def classifier(self): (_, classifier) = self._regression.steps[-1] return c...
Branlala/docker-sickbeardfr
sickbeard/lib/requests/packages/chardet2/escprober.py
Python
mit
3,094
0.003878
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is mozill
a.org code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C
) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the Li...
lucidbard/NewsBlur
apps/profile/migrations/0005_view_settings_to_preferences.py
Python
mit
4,350
0.007816
# encoding: utf-8 import datetime from south.db import db from south.v2 import DataMigration from django.db import models from django.contrib.auth.models import User class Migration(DataMigration): def forwards(self, orm): users = User.objects.all() for user in users: user.profile.pref...
0'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'profile.profile': {
'Meta': {'object_name': 'Profile'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_seen_ip': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'last_seen_on': ('django.db.models.fields.DateTimeField'...
benelot/bullet-gym
pybulletgym/envs/gym_manipulators.py
Python
mit
10,183
0.03005
from pybulletgym.envs.scene_abstract import SingleRobotEmptyScene from gym_mujoco_xml_env import PybulletMujocoXmlEnv import gym, gym.spaces, gym.utils, gym.utils.seeding import numpy as np import os, sys class PybulletReacher(PybulletMujocoXmlEnv): def __init__(self): PybulletMujocoXmlEnv.__init__(self, 'reacher....
(self): PybulletMujocoXmlEnv.__init__(self, 'pusher.xml', 'body0', action_dim=7, obs_dim=5) def create_single_player_scene(self): return SingleRobotEmptyScene(gravity=9.81, timestep=0.0020, frame_skip=5) def robot_specific_r
eset(self): self.fingertip = self.parts["fingertip"] # qpos = self.init_qpos self.goal_pos = np.asarray([0, 0]) while True: self.cylinder_pos = np.concatenate([ self.np_random.uniform(low=-0.3, high=0, size=1), self.np_random.uniform(low=-0.2, high=0.2, size=1)]) if np.linalg.norm(self.cylinder_...
msabramo/requests
requests/models.py
Python
isc
27,078
0.001883
# -*- coding: utf-8 -*- """ requests.models ~~~~~~~~~~~~~~~ This module contains the primary objects that power Requests. """ import os from datetime import datetime from .hooks import dispatch_hook, HOOKS from .structures import CaseInsensitiveDict from .status_codes import codes from .auth import HTTPBasicAuth, ...
unctionality of Requests. Recommended interface is with the Requests functions. """ def __init__(self, url=None, headers=dict(), files=Non
e, method=None, data=dict(), params=dict(), auth=None, cookies=None, timeout=None, redirect=False, allow_redirects=False, proxies=None, hooks=None, config=None, prefetch=False, _poolmanager=None, verify=None,...
mlskit/astromlskit
REGRESSION/linear.py
Python
gpl-3.0
2,059
0.000971
from numpy import * import matplotlib.pyplot as plt def file2matrix(filename): data_file = open(filename) data_lines = data_file.readlines() number_of_lines = len(data_lines) data_matrix = zeros((number_of_lines, 1)) for line_index in range(number_of_lines): line = data_lines[line_index]...
_cycles = 1500 alpha = 0.07 weights = ones((n, 1)) theta = ones((n, 1)) for cycle_index in range(max_cycles): for j in range(n): theta[j] = weights[j] - alpha / m * partial_derivative_of_h(weights, x_matrix, y_matrix, j) weights = [weight for weight in theta] return the...
or[i] * x_matrix[i, j] return sum(error) def hypothesis(weights, x_matrix): return x_matrix * weights def plot_best_fit(weights, x_matrix, y_matrix): fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(x_matrix[:], y_matrix[:]) plt.xlabel('Age') plt.ylabel('Height') x = arange(0....
brainstorm/bcbio-nextgen
scripts/bcbio_fastq_umi_prep.py
Python
mit
4,259
0.004226
#!/usr/bin/env python """Convert 3 fastq inputs (read 1, read 2, UMI) into paired inputs with UMIs in read names Usage: bcbio_fastq_umi_prep.py single <out basename> <read 1 fastq> <read 2 fastq> <umi fastq> or: bcbio_fastq_umi_prep.py autopair [<list> <of> <fastq> <files>] Creates two fastq files with embedded U...
out1_fq = out_base + "_R1.fq.gz" out2_fq = out_base + "_R2.fq.gz" transform_json_file = out_base + "-transform.json" with open(transform_json_file, "w") as out_handle: out_handle.write(transform_json) with utils.open_gzipsafe(read1_fq) as in_handle: ex_name = in_handle.readline().split...
cmd = ("umis fastqtransform {fastq_tags_arg} " "--fastq1out >(pbgzip -n {cores} -c > {out1_fq}) " "--fastq2out >(pbgzip -n {cores} -c > {out2_fq}) " "{transform_json_file} {read1_fq} " "{read2_fq} {umi_fq}") do.run(cmd.format(**locals()), "Add UMIs to paired fastq files...
meskio/keymanager
src/leap/keymanager/_version.py
Python
gpl-3.0
8,362
0.000598
IN_LONG_VERSION_PY = True # 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 (build by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter f...
t_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: variables["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line)
if mo: variables["full"] = mo.group(1) f.close() except EnvironmentError: pass return variables def versions_from_expanded_variables(variables, tag_prefix, verbose=False): refnames = variables["refnames"].strip() if refnames.startswith("$Format"): ...
vyrus/wubi
src/bittorrent/CurrentRateMeasure.py
Python
gpl-2.0
1,016
0.004921
# Written by Bram Cohen # see LICENSE.txt for license information from time import time class Measure: def __init__(self, max_rate_period, fudge = 1): self.max_rate_period = max_rate_period self.ratesince = time() - fudge self.last = self.ratesince self.rate = 0.0 self.tota...
esince < t - self.max_rate_period: self.ratesince = t - self.max_rate_period def
get_rate(self): self.update_rate(0) return self.rate def get_rate_noupdate(self): return self.rate def time_until_rate(self, newrate): if self.rate <= newrate: return 0 t = time() - self.ratesince return ((self.rate * t) / newrate) - t def get_t...
OnShift/page_object
features/steps/label_steps.py
Python
apache-2.0
288
0
@when(u'I get t
he text from the label') def step_impl(context): context.expected_text = context.page.label_id() @when(u'I search for the label by "{how}"') def step_impl(context, how): method = 'label_{0}'.format(how) co
ntext.expected_text = getattr(context.page, method)()
gophronesis/smlib
smlib/keras_vectorizer.py
Python
apache-2.0
2,229
0.005832
import sys import numpy as np from normalization import tokenize from helpers import ahash class KerasVectorizer(): ''' Convert list of documents to numpy array for input into Keras model ''' def __init__(self, n_features=100000, maxlen=None, maxper=100, hash_function=ahash): self.maxlen = ...
['this is a test', 'this is a another test']) ktv = KerasTokenVectorizer(maxlen=2) ktv.fit_transform(['this is a test', 'this is a another test']) kcv = KerasCharacterVectorizer() kcv.fit_transform(['something', 'else'
]) '''
sixohsix/xychan
tests/test_user.py
Python
gpl-3.0
315
0.003175
from test_basics import setUp, app def test_visit_login(): r = app.get('/mod/login') assert "<form na
me=\"login\"" in r def test_login(): r = app.get('/mod/login') r.form['username'] = 'admin' r.form['password'] = 'adminadmin1' r = r.form.submit() assert "You are now logged
in" in r
shobhitmishra/CodingProblems
epi_judge_python/insert_operators_in_string.py
Python
mit
426
0
from typing import List from test_framework import generic_test def expressio
n_synthesis(digits: List[int], target: int) -> bool: # TODO - you fill in here. return True if __name__
== '__main__': exit( generic_test.generic_test_main('insert_operators_in_string.py', 'insert_operators_in_string.tsv', expression_synthesis))
HERA-Team/pyuvdata
pyuvdata/uvdata/tests/test_mir.py
Python
bsd-2-clause
19,246
0.001871
# -*- mode: python; coding: utf-8 -*- # Copyright (c) 2020 Radio Astronomy Software Group # Licensed under the 2-clause BSD License """Tests for Mir class. Performs a series of test for the Mir class, which inherits from UVData. Note that there is a separate test module for the MirParser class (mir_parser.py), which ...
reorderings just make sure that data from the two formats are lined up # correctly. sma_mir.reorder_freqs(spw_order="number") ms_uv.reorder_blts() # MS doesn't have the concept of an "instrument" name like FITS does, and instead # de
faults to the telescope name. Make sure that checks out here. assert sma_mir.instrument == "SWARM" assert ms_uv.instrument == "SMA" sma_mir.instrument = ms_uv.instrument # Quick check for history here assert ms_uv.history != sma_mir.history ms_uv.history = sma_mir.history # Only MS has ext...
itsjeyd/edx-platform
openedx/core/djangoapps/coursegraph/utils.py
Python
agpl-3.0
1,464
0
""" Helpers for the CourseGraph app """ from django.core.cache import cache from django.utils import timezone class TimeRecordingCacheBase(object): """ A base class for caching the current time for some key. """ # cache_prefix should be defined in children classes cache_prefix = None _cache = ...
urn: a cache key """ return self.cache_prefix + unicode(course_key) def get(self, course_key): """ Gets the time value associated with the CourseKey. :param course_key: a CourseKey object. :return: the time the key was last set. """ return self._cache...
def set(self, course_key): """ Sets the current time for a CourseKey key. :param course_key: a CourseKey object. """ return self._cache.set(self._key(course_key), timezone.now()) class CourseLastPublishedCache(TimeRecordingCacheBase): """ Used to record the last t...
chichilalescu/bfps
tests/test_field_class.py
Python
gpl-3.0
6,948
0.012666
import numpy as np import h5py import matplotlib.pyplot as plt import pyfftw import bfps import bfps.tools import os from bfps._fluid_base import _fluid_particle_base class TestField(_fluid_particle_base): def __init__( self, name = 'TestField-v' + bfps.__version__, work_dir =...
ta)) #err1 = np.max(np.abs(f['scal
/real/0'].value/(n**3) - rdata)) / np.mean(np.abs(rdata)) #err2 = np.max(np.abs(f['scal_tmp/complex/0'].value/(n**3) - cdata)) / np.mean(np.abs(cdata)) #print(err0, err1, err2) #assert(err0 < 1e-5) #assert(err1 < 1e-5) #assert(err2 < 1e-4) ## compare fig = plt.figure(figsize=(18, 6)) a =...
OCA/multi-company
account_invoice_consolidated/models/res_partner.py
Python
agpl-3.0
698
0.001433
# Copyright (C) 2019 Open Source Integrators # Copyright (C) 2019 Serpent Consulting Services Pvt. Ltd. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class ResPartner(models.Model): _inherit = "res.partner" def view_consolidated_invoice(self): self.ensure_on...
[("partner_id", "=", self.id)] )
action = self.env.ref( "account_invoice_consolidated." "account_invoice_consolidated_action" ) action = action.read()[0] action["domain"] = [("id", "in", cons_invoices_rec.ids)] return action
MaximNevrov/neutron
neutron/cmd/sanity/checks.py
Python
apache-2.0
13,900
0.000144
# Copyright (c) 2014 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
priority=1, proto='arp', dl_vlan=42, nw_dst='%s' % ip, actions=actions) def arp_header_match_supported(): return ofctl_arg_supported(cmd='add-flow', ...
pdorrell/aptrow
aptrow_server.py
Python
gpl-3.0
1,772
0.011851
""" Copyright 2009 Philip Dorrell http://www.1729.com/ (email: http://www.1729.com/email.html) This file is part of Aptrow ("Advance Programming Technology Read-Only Webification": http://www.1729.com/aptrow/) Aptrow is free software: you can redistribute it and/or modify it under the terms of the GNU General...
IP access) # SECURITY NOTE: This demo application gives r
ead-only access to all files and directories # on the local filesystem which can be accessed by the user running the application. So beware. # # (Also, this application may create temporary files which it does not delete, which are copies # of the contents of 'file-like' objects which are not themselves files.) ...
lmazuel/azure-sdk-for-python
azure-mgmt-containerregistry/tests/test_mgmt_containerregistry_2017_03_01.py
Python
mit
4,129
0.002665
# 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. #---------------------------------------------------------------------...
AULT_SKU_NAME) self.assertEqual(registry.sku.tier, SkuTier.basic.value) self.assertEqual(registry.provisioning_state.value, ProvisioningState.succeeded.value) self.assertEqual(registry.admin_user_enabled, False) registries = list(self.client.registries.list_by_resource_group(resour
ce_group.name)) self.assertEqual(len(registries), 1) # Update the registry with new tags and enable admin user registry = self.client.registries.update( resource_group_name=resource_group.name, registry_name=registry_name, registry_update_parameters=RegistryU...
eduNEXT/edx-platform
openedx/core/djangoapps/coursegraph/management/commands/tests/test_dump_to_neo4j.py
Python
agpl-3.0
20,829
0.00221
""" Tests for the dump_to_neo4j management command. """ from datetime import datetime from unittest import mock import ddt from django.core.management import call_command from edx_toggles.toggles.testutils import override_waffle_switch from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from...
s.chapter, category='sequential') cls.vertical = ItemFactory.create(parent=cls.sequential, category='vertical', display_name='subject') cls.html = ItemFactory.create(parent=cls.vertical, category='html') cls.problem = ItemFa
ctory.create(parent=cls.vertical, category='problem') cls.video = ItemFactory.create(parent=cls.vertical, category='video', display_name='subject') cls.video2 = ItemFactory.create(parent=cls.vertical, category='video') cls.course2 = CourseFactory.create() cls.course_strings = [str(cls....
akavlie/SMSr
sms/tw_send.py
Python
bsd-3-clause
1,031
0.007759
from sms import app import twilio def twilio_send(phone_number, message): """Sends an SMS via the Twilio service. """ data = {'From': app.config['CALLER_ID'], 'To': phone_number, 'Body': message} account = twilio.Account(app.config['ACCOUNT_SID'], ap...
(app.config['API_VERSION'], app.config['ACCOUNT_SID']), 'POST', data) return tw_response def twilio_update(sid): """Updat
e status for a given SMS. """ account = twilio.Account(app.config['ACCOUNT_SID'], app.config['ACCOUNT_TOKEN']) tw_response = account.request('/%s/Accounts/%s/SMS/Messages/%s.json' % (app.config['API_VERSION'], a...
eesatfan/openpli-enigma2
lib/python/Screens/EpgSelection.py
Python
gpl-2.0
15,315
0.030167
from Screen import Screen from Components.config import config, ConfigClock from Components.Button import Button from Components.Pixmap import Pixmap from Components.Label import Label from Components.EpgList import EPGList, EPG_TYPE_SINGLE, EPG_TYPE_SIMILAR, EPG_TYPE_MULTI from Components.ActionMap import ActionMap fr...
self["key_blue"] = Button(pgettext("button label, 'next screen'", "Next")) self["now_button"] = Pixmap() self["next_button"] = Pixmap() self["more_button"] = Pixmap(
) self["now_button_sel"] = Pixmap() self["next_button_sel"] = Pixmap() self["more_button_sel"] = Pixmap() self["now_text"] = Label() self["next_text"] = Label() self["more_text"] = Label() self["date"] = Label() self.services = service self.zapFunc = zapFunc self["key_green"] = Button(_("A...
chennan47/osf.io
api_tests/nodes/views/test_node_detail.py
Python
apache-2.0
75,427
0.000849
# -*- coding: utf-8 -*- import mock import pytest from urlparse import urlparse from api.base.settings.defaults import API_BASE from framework.auth.core import Auth from osf.models import NodeLog from osf.models.licenses import NodeLicense from osf.utils.sanitize import strip_html from osf.utils import permissions fr...
ype == 'application/vnd.api+json' assert res.json['data']['attributes']['title'] == project_private.title assert res.json['data']['attributes']['description'] == project_private.description assert res.json['data']['attributes']['category'] == project_private.category assert_items_equal( ...
get(url_private, expect_errors=True) assert res.status_code == 401 assert 'detail' in res.json['errors'][0] # test_return_private_project_details_logged_in_non_contributor res = app.get(url_private, auth=user_two.auth, expect_errors=True) assert res.status_code == 403 asse...
lukas-hetzenecker/home-assistant
tests/components/plaato/__init__.py
Python
apache-2.0
40
0
"""Te
sts for the Plaato integration."
""
google-research/google-research
snerg/train.py
Python
apache-2.0
11,308
0.006986
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compli
ance 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 # 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. # Lint as: python3 """Training script for Nerf.""" import functools import gc import time from absl import app from absl import flags import flax from flax.metrics import tensorboard from flax.training ...
viranch/exodus
resources/lib/sources_de/streamkiste.py
Python
gpl-3.0
5,119
0.009768
# -*- coding: utf-8 -*- ''' Exodus Add-on Copyright (C) 2016 Viper2k4 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...
fmt] if '1080p' in fmt: quality = '1080p' elif '720p' in fmt: quality = 'HD' else: quality = 'SD' if any(i in ['dvdscr', 'r5', 'r6'] for i
in fmt): quality = 'SCR' elif any(i in ['camrip', 'tsrip', 'hdcam', 'hdts', 'dvdcam', 'dvdts', 'cam', 'telesync', 'ts'] for i in fmt): quality = 'CAM' info = [] if '3d' in fmt or any(i.endswith('3d') for i in fmt): info.append('3D') if any(i in ['hevc',...
jawilson/home-assistant
homeassistant/components/ubus/device_tracker.py
Python
apache-2.0
5,843
0.000513
"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CON...
self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) s...
le = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return resu...
wisfern/vnpy
beta/api/korbit/korbit-python-master/korbit/private_api.py
Python
mit
6,359
0.003931
# -*- coding: utf-8 -*- import time from public_api import PublicAPI class PrivateAPI(PublicAPI): def __init__(self, client_id, secret, production=True, version="v1", timeout=20): try: super(self.__class__, self).__init__(production, version, timeout) except TypeError: Publ...
_amount, 'nonce': self.nonce } #return self.request_post("user/orders/buy", headers=self.header
s, data=payload) return self.request_post("user/orders/buy", headers=self.headers, data=payload) def market_bid_order(self, fiat_amount, currency_pair="btc_krw"): return self.bid_order('market', fiat_amount=fiat_amount, currency_pair=currency_pair) def limit_bid_order(self, coin_amount, price,...
youdar/work
work/FAB/cross/fab_elbow_angle.py
Python
mit
5,657
0.012374
from __future__ import division from scitbx.linalg import eigensystem from scitbx.array_family import flex from libtbx.utils import null_out from math import acos,pi from iotbx import pdb import iotbx.pdb class fab_elbow_angle(object): def __init__(self, pdb_hierarchy, chain_ID_light='...
riable domain is from residue 1 to limit. Constant domain form limit+1 to end. - Method of calculating angle is based on Stanfield, et al., JMB 2006 ''' # create selection strings for the heavy/light var/const part of cha
ins self.select_str( chain_ID_H=chain_ID_heavy, limit_H=limit_heavy, chain_ID_L=chain_ID_light, limit_L=limit_light) # get the hirarchy for and divide using selection strings self.pdb_hierarchy = pdb_hierarchy self.get_pdb_chains() # Get heavy to light reference vector before...
BenThelen/python-refprop
python2.7/rptest.py
Python
bsd-3-clause
21,437
0.004851
#------------------------------------------------------------------------------- #Name: rptest #Purpose: test module for refprop and multiRP # #Author: Thelen, B.J. # [email protected] #-------------------------------------------------------------------------------...
'\n' print u'virc' print rp.virc(prop[u't'], x), u'\n' #function not supported in Windows if platform.system() == u'Linux': print u'vird' print rp.vird(prop[u't'], x), u'\n' print u'virba' print rp.virba(prop[u't'], x), u'\n' print u'vi...
pk' print rp.cvcpk(1, prop[u't'], D), u'\n' print u'dbdt' print rp.dbdt(prop[u't'], x), u'\n' print u'dpddk' print rp.dpddk(1, prop[u't'], D), u'\n' print u'dpdtk' print rp.dpdtk(2, prop[u't'], D), u'\n' D = 55 t = 373 prop = rp.press(...
pri22296/yaydoc
modules/scripts/config/validation.py
Python
gpl-3.0
626
0.011182
import re import mimetypes def
validate_markdown_flavour(value): return value in ('markdown', 'markdown_strict', 'markdown_phpextra', 'markdown_github', 'markdown_mmd', 'commonmark') def validate_mimetype_image(value): # Empty string is also valid if not value: return True mimetype = mimetypes.guess_ty...
else: return mimetype.startswith('image') def validate_subproject(value): regex = '(http|https)://(www.|)github.com/([\w\d\.]+)/([\w\d\.]+)(.git|)' return re.match(regex, value['url']) != None
Sorsly/subtle
google-cloud-sdk/lib/googlecloudsdk/command_lib/compute/managed_instance_groups/update_instances_utils.py
Python
mit
5,956
0.00638
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
tr: string containing fixed or percent value. messages: module containing message classes. Returns: FixedOrPercent message object. """ if fixed_or_percent_str is None: return None fixed = _ParseFixed(fixed_or_percent_str) if fixed is not None: return messages.FixedOrPercent(fixed=fixed) pe...
_ParsePercent(fixed_or_percent_str) if percent is not None: if percent > 100: raise exceptions.InvalidArgumentException( flag_name, 'percentage cannot be higher than 100%.') return messages.FixedOrPercent(percent=percent) raise exceptions.InvalidArgumentException( flag_name, flag...
ezequielpereira/Time-Line
timelinelib/xml/parser.py
Python
gpl-3.0
9,465
0.000106
# Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Rickard Lindberg, Roger Lindberg # # This file is part of Timeline. # # Timeline 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 th...
er # Occurrence rules for tags SINGLE = 1 OPTIONAL = 2 ANY = 3 class ValidationError(Exception): """Raised when parsed xml document doe
s not follow the schema.""" pass class Tag(object): """ Represents a tag in an xml document. Used to define structure of an xml document and define parser functions for individual parts of an xml document. Parser functions are called when the end tag has been read. See SaxHandler class ...
gustavemichel/IEEEXtreme10-Technomancers
P23 - P is NP/PisNP.py
Python
gpl-3.0
555
0.005405
import sys input_data = sys.stdin.readlines() static = input_dat
a.pop(0).rstrip().split() teams = int(static[0]) pizza = int(static[1]) nopizza= int(static[2]) input_data.pop(0) pizza_scores = input_data[0:pizza] input_data = input_data[pizza:] pizza_scores = [-1 if x.rstrip() == '?' else int(x.rstrip()) for x in pizza_scores] input_data.pop(0) nopizza_scores = input_data[0:nop...
1 if x.rstrip() == '?' else int(x.rstrip()) for x in nopizza_scores] print pizza_scores print nopizza_scores
SickGear/SickGear
sickbeard/providers/torrentday.py
Python
gpl-3.0
7,671
0.00352
# coding=utf-8 # # This file is part of SickGear. # # SickGear 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. # # SickGear is distribu...
return super(TorrentDayProvider, self)._authorised( logged_in=(lambda y='': all( ['RSS URL' in y, self.has_all_cookies()] + [(self.session.cookies.get(c, doma
in='') or 'sg!no!pw') in self.digest for c in ('uid', 'pass')])), failed_msg=(lambda y=None: u'Invalid cookie details for %s. Check settings')) @staticmethod def _has_signature(data=None): return generic.TorrentProvider._has_signature(data) or \ (data and re....
twitter/pants
tests/python/pants_test/backend/jvm/tasks/test_checkstyle.py
Python
apache-2.0
5,076
0.005122
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import os from textwrap import dedent from pants.backend.jvm.targets.java_library import...
1.1//EN" "http://www.puppycrawl.com/dtds/suppressions_1_1.dtd"> <suppressions> {suppresses_xml} </suppressions> """.format(suppresses_xml='\n'.join(suppresses_xml)))) def _create_target(self, name, test_java_source): rel_dir = os.path.join('src/java', name) ...
=os.path.join(rel_dir, '{name}.java'.format(name=name)), contents=test_java_source) return self.make_target(Address(spec_path=rel_dir, target_name=name).spec, JavaLibrary, sources=['{}.java'.format(name)]) # # Test section # @ens...
xxn59/weat
order.py
Python
mit
1,603
0.011853
# -*- coding: ut
f-8 -*- import time from flask import Flask,g,request,make_response import hashlib import xml.etree.ElementTree as ET app = Flask(__name__) app.debug=True @app.route('/',methods=['GET','POST']) def wechat_auth(): if request.method == 'GET': token='weatorg' data = request.args signature = dat...
tamp = data.get('timestamp','') nonce = data.get('nonce','') # echostr = data.get('echostr','') echostr = data.get('echostr') print 'ech0str:',echostr s = [timestamp,nonce,token] s.sort() s = ''.join(s) if (hashlib.sha1(s).hexdigest() == signature): ...
chubbymaggie/simuvex
simuvex/procedures/libc___so___6/__stack_chk_fail.py
Python
bsd-2-clause
258
0.007752
im
port simuvex ###################################### # __stack_chk_fail ###################################### class __stack_chk_fail(simuvex.SimProcedure): NO_RET = True def run(self, exit_code): #pylint:di
sable=unused-argument return
kleientertainment/ds_mod_tools
pkg/win32/Python27/Lib/site-packages/clint/textui/__init__.py
Python
mit
181
0
# -*- coding:
utf-8 -*- """ clint.textui
~~~~~~~~~~~~ This module provides the text output helper system. """ from . import colored from . import progress from .core import *
zofuthan/edx-platform
openedx/core/djangoapps/course_groups/cohorts.py
Python
agpl-3.0
16,159
0.002166
""" This file contains the logic for cohorts, as exposed internally to the forums, and to the cohort admin views. """ import logging import random from django.db import transaction from django.db.models.signals import post_save, m2m_changed from django.dispatch import receiver from django.http import Http404 from dja...
def is_course_cohorted(course_key): """ Give
n a course key, return a boolean for whether or not the course is cohorted. Raises: Http404 if the course doesn't exist. """ return get_course_cohort_settings(course_key).is_cohorted def get_cohort_id(user, course_key, use_cached=False): """ Given a course key and a user, return the id...
kislyuk/aegea
aegea/top.py
Python
apache-2.0
1,383
0.007231
import os, sys from datetime import datetime from typing import List import boto3 import botocore.exceptions from . import register_parser from .util import ThreadPoolExecutor from .util.printing import format_table, page_output def get_stats_for_region(region): try: session = boto3.Session(region_name=r...
instances, num_amis, num_vpcs, num_enis, num_volumes] def top(args): table = [] # type: List[List] columns = ["Region", "Instances", "AMIs", "VPCs", "Network interfaces", "EBS volumes"] executor = ThreadPoolExecutor() table = list(executo
r.map(get_stats_for_region, boto3.Session().get_available_regions("ec2"))) page_output(format_table(table, column_names=columns, max_col_width=args.max_col_width)) parser = register_parser(top, help='Show an overview of AWS resources per region')
ARISE-Initiative/robosuite
robosuite/wrappers/domain_randomization_wrapper.py
Python
mit
9,076
0.002093
""" This file implements a wrapper for facilitating domain randomization over robosuite environments. """ import numpy as np from robosuite.utils.mjmod import CameraModder, DynamicsModder, LightingModder, TextureModder from robosuite.wrappers import Wrapper DEFAULT_COLOR_ARGS = { "geom_names": None, # all geoms ...
OrderedDict: Environment observation space after reset occurs """
# undo all randomizations self.restore_default_domain() # normal env reset ret = super().reset() # save the original env parameters self.save_default_domain() # reset counter for doing domain randomization at a particular frequency self.step_counter = 0 ...
krux/graphite-web
webapp/graphite/events/urls.py
Python
apache-2.0
832
0
"""Copyright 2008 Orbitz WorldWide 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, softw...
?P<event_id>\d+)/$', views.detail, name='events_detail'), url('^$', views.view_events, name='events
'), ]
tangrams/data2image
example/lut.py
Python
mit
817
0.058752
#!/usr/bin/env python from PIL import Image import sys sys.path.insert(0, r'../python/') import encode lut = [[0.8487,0.84751182,0.84479598,0.840213,0.83359314,0.8257851,0.814752,0.80006949,0.78216192,0.76060494,0.73658673,0.7086645,0.67777182,0.64475739,0.60987582,0.57134484,0.52729731,0.48562614,0.45167814],[
0,0.0838426,0.1676852,0.2515278,0.3353704,0.419213,0.5030556,0.5868982,0.67182264,0.75336633,0.83518048,0.91537187,0.99339958,1.06872269,1.14066505,1.20841528,1.27035062,1.31998003,1.3523]] print len(lut[0]),len(lut) img = Image.new('RGBA', (len(lut[0]), len(lut)), (0,0,0,0)) pixels = img.load() for y in range(len(l...
r') img.save(open('lut.png', 'w'))
meisamhe/GPLshared
Programming/MPI — AMath 483 583, Spring 2013 1.0 documentation_files/rotate_array_permutation.py
Python
gpl-3.0
569
0
import fractions # @include def rotate_array(rotate_amount, A): def apply_cyclic_permutation(rotate_amount, offset):
temp = A[offset] for i in range(1, cycle_length): idx = (offset + i * rotate_amount) % len(A) A[idx], temp = temp, A[idx] A[offset] = temp rotate_amount %= len(A) if rotate_amount == 0: return num_cycles = fractions.gcd(len(A), rotate
_amount) cycle_length = len(A) // num_cycles for c in range(num_cycles): apply_cyclic_permutation(rotate_amount, c) # @exclude
dropbox/changes
tests/changes/api/test_snapshot_index.py
Python
apache-2.0
2,245
0.000445
from changes.config import db from changes.models.project import ProjectOption from changes.models.snapshot import SnapshotStatus from changes.testutils import APITestCase class SnapshotListTest(APITestCase): def test_simple(self): project_1 = self.create_project() build_1 = self.create_build(proj...
assert data[0]['images'][0]['id'] == image_2.id.hex assert data[0]['images'][1]['id'] == image_3.id.hex assert data[1]['id'] == snapshot_1.id.hex assert not data[1]['isActive'] assert len(data[1]['images']) == 1 assert data[1]['images'][0]['id'] == image_1.id.hex pat...
ts/?state=valid' resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert len(data) == 1 assert data[0]['id'] == snapshot_1.id.hex path = '/api/0/snapshots/?state=invalid' resp = self.client.get(path) assert resp....
evernym/zeno
plenum/test/monitoring/test_monitor_attributes.py
Python
apache-2.0
201
0
def testHasMasterPrimary(txnPoolNodeSet): maste
rPrimaryCount = 0 for node
in txnPoolNodeSet: masterPrimaryCount += int(node.monitor.hasMasterPrimary) assert masterPrimaryCount == 1
Tankypon/ubuntu-make
umake/network/download_center.py
Python
gpl-3.0
9,909
0.002321
# -*- coding: utf-8 -*- # Copyright (C) 2014 Canonical # # Authors: # Didier Roche # # 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; version 3. # # This program is distributed in the hope that ...
is set to False. close() will clean it from memory, error=string detailing the error which occurred (path and content would be empty), f
d=temporary file descriptor. close() will delete it from disk, final_url=the final url, which may be different from the start if there were redirects, cookies=a dictionary of cookies after the request ) } """ self._do...
mixman/djangodev
django/contrib/auth/tests/forms.py
Python
bsd-3-clause
10,655
0.002065
from __future__ import with_statement import os from django.core import mail from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, PasswordChangeForm, SetPasswordForm, UserChangeForm, PasswordResetForm from django.test import TestCase class UserCreati...
his account is inactive.']) def test_success(self): # The success case data = { 'username': 'testclient', 'password': 'password',
} form = AuthenticationForm(None, data) self.assertTrue(form.is_valid()) self.assertEqual(form.non_field_errors(), []) class SetPasswordFormTest(TestCase): fixtures = ['authtestdata.json'] def test_password_verification(self): # The two new passwords do not match....
batiste/django-page-cms
pages/tests/test_functional.py
Python
bsd-3-clause
35,775
0.001621
# -*- coding: utf-8 -*- """Django page CMS functionnal tests suite module.""" from pages.models import Page, Content, PageAlias from pages.tests.testcase import TestCase import django from django.conf import settings from django.urls import reverse from pages.utils import get_now from pages.phttp import get_request_mo...
'slug'] = 'test-page-2' page_data['template'] = 'pages/examples/index.html' response = c.post(add_url, page_data) self.assertRedirects(response, changelist_url) response = c.get(self.get_page_url('t
est-page-2')) self.assertEqual(response.status_code, 200) def test_edit_page(self): """Test that a page can edited via the admin.""" c = self.get_admin_client() page_data = self.get_new_page_data() response = c.post(reverse('admin:pages_page_add'), page_data) self.as...
mhogg/cKDTree-bench
ckdtreebench/spatial_PR4890/__init__.py
Python
bsd-3-clause
146
0
from __f
uture__ import absolute_import __all__ = ['cKDTree'] from . import ckdtree cKDTree = ckdtree.cKDTree cKDTreeNode = ckdtree.cKDTree
Node
viswimmer1/PythonGenerator
data/python_files/32695181/__init__.py
Python
gpl-2.0
387
0.046512
import column_chooser import constants import library_manager import list_manager import main_window import media import movie_tagger import prefs_manager import prefs_window import tag_manager __all__ = ['column_chooser', 'cons
tants', 'library_manager', 'list
_manager', 'main_window', 'media', 'movie_tagger', 'prefs_manager', 'prefs_window', 'tag_manager']
alexphelps/django-drip
drip/models.py
Python
mit
6,448
0.003567
from datetime import datetime, timedelta import random from django.db import models from django.core.exceptions import ValidationError from django.conf import settings from django.utils.functional import cached_property from drip.utils import get_user_model # just using this to parse, but totally insane package nami...
gth=150, null=True, blank=Tru
e, help_text="Set a name for a custom from email.") subject_template = models.TextField(null=True, blank=True) body_html_template = models.TextField(null=True, blank=True, help_text='You will have settings and user in the context.') message_class = models.CharField(max_length=120, blank=True...
scrapinghub/keystone
keystone/auth/plugins/external.py
Python
apache-2.0
6,469
0
# Copyright 2013 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 in...
t, self).__init__() class ExternalDomain(Domain): """Deprecated. Please use keystone.auth.external.Domain instead.""" @versionutils.deprecated( as_of=versionutils.deprecated.ICEHOUSE, in_favor_of='keystone.auth.external.Domain', remove_in=+1) def __init__(self): super(Exte...
plugin exists to provide compatibility for the unintended behavior described here: https://bugs.launchpad.net/keystone/+bug/1253484 """ @versionutils.deprecated( as_of=versionutils.deprecated.ICEHOUSE, in_favor_of='keystone.auth.external.DefaultDomain', remove_in=+1) def __init...
tensorflow/graphics
tensorflow_graphics/geometry/representation/mesh/tests/mesh_test_utils.py
Python
apache-2.0
1,686
0.004745
# Copyright 2020 The TensorFlow 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
array faces: A [4, 3] int array """ vertices = np.array( ((0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0.5, 0.5, 0)), dtype=np.float32) faces = np.array( ((0, 1, 4), (1, 3, 4), (3, 2, 4), (2, 0, 4)), dtype=np.in
t32) return vertices, faces
dmsurti/mayavi
mayavi/components/actor2d.py
Python
bsd-3-clause
5,263
0.00038
"""A simple actor component. """ # Author: Prabhu Ramachandran <[email protected]> # Copyright (c) 2005, Enthought, Inc. # License: BSD Style. # Enthought library imports. from traits.api import Instance from traitsui.api import View, Group, Item, InstanceEditor from tvtk.api import tvtk # Local imports. from ma...
################################################## def _setup_handlers(self, old, new): if old is not None: old.on_trait_change(self.render, remove=True) new.on_trait_change(self.render) def _mapper_changed(self, old, new): # Setup the handlers. self._setup_handlers(...
self.configure_connection(new, self.inputs[0]) # Setup the actor's mapper. actor = self.actor if actor is not None: actor.mapper = new self.render() def _actor_changed(self, old, new): # Setup the handlers. self._setup_handlers(old, new) ...
ActiveState/code
recipes/Python/444766_cherrypy_RESTResource/recipe-444766.py
Python
mit
6,312
0.003169
""" REST Resource cherrypy controller mixin to make it easy to build REST applications. handles nested resources and method-based dispatching. here's a rough sample of what a controller would look like using this: cherrypy.root = MainController() cherrypy.root.user = UserController() class PostController(RESTResou...
sume that default has already # traversed down the tree to the right location and this is # being called for a raw resource method = cherrypy.request.method if self.REST_map.has_key(method): m = getattr(self
,self.REST_map[method]) if m and getattr(m, "expose_resource"): return m(resource,**params) else: if self.REST_defaults.has_key(method): m = getattr(self,self.REST_defaults[method]) if m and getattr(m, "expose_resource"): ...
glenn-edgar/local_controller_3
__backup__/py_cf_py3/chain_flow.py
Python
mit
11,716
0.004097
import datetime import time from .opcodes_py3 import Opcodes class CF_Base_Interpreter(): def __init__(self): self.chains = [] self.chain_map = {} self.event_queue = [] self.current_chain = None self.opcodes = Opcodes() self.valid_return_codes = {} self.v...
hain_to_list(chain) for i in chain: assert isinstance(i, str), "chain name is not a string" k = self.find_chain_object(i) k["link_index"] = 0 links = k["links"] for m in links: m["active_flag"] = True m["init_flag"] = Tr...
k = self.find_chain_object(i) k["suspend"] = False k["active"] = True def suspend_chain_code(self, chain): chain = self.chain_to_list(chain) for i in chain: assert isinstance(i, str), "chain name is not a string" k = self.find_chain_object(i) ...
douglasbagnall/sonograms
server.py
Python
mit
8,302
0.00265
#!/usr/bin/python import random, re import anydbm import os, sys from flask import Flask, render_templat
e, request, make_response app = Flask(__name__) IGNORED = 'ignored' INTERESTING = 'interesting' PENDING_FILES = set() WAV_DIR = 'static/wav' IGNORED_WAV_DIRS = ('doc-kiwi', 'doc-morepork', 'rfpt-15m', 'doc-minutes', 'doc-interesting', 'd...
) #WAV_DIR = 'static/wav-test' CALLS_FOUND = 0 FILES_PROCESSED = 0 FILES_IGNORED = 0 FILES_INTERESTING = 0 UNCONFIRMED_TIMES = {} REQUESTED_FILES = set() DEFAULT_DBM_FILE = 'calls.dbm' def gen_times_from_file(fn): f = open(fn) for line in f: line = line.strip() if ' ' in line: ...
alissonbf/blog-teste
blog/urls.py
Python
gpl-2.0
989
0.005097
# -*- coding: utf-8 -*- """ ------ Urls ------ Arquivo de configuração das urls da aplicação blog Autores: * Alisson Barbosa Ferreira <[email protected]> Data: ============== ================== Criação Atualização ============== ================== 29/11/2014 29/11/2014 ============== =====...
', 'post', name='post'), url(r'^api-all-posts', 'all_posts', name='all_posts'), url(r'^api-get-post/(?P<pk>[0-9]+)/$', 'get_post', name='get_post'), url(r'^api-auth', 'api_auth', name='api_auth'), url(r'^api-token', 'api_token', name='api_token'), url(r'^api-login', 'api_login', name='api_login'), ...
, 'enviar_email', name='enviar_email'), url(r'^autorelacionamento/$', 'autorelacionamento', name='autorelacionamento'), )
kynikos/outspline
src/outspline/interfaces/wxgui/rootw.py
Python
gpl-3.0
17,506
0.0008
# Outspline - A highly modular and extensible outliner. # Copyright (C) 2011 Dario Giovannetti <dev@dariogiovannetti
.net> # # This file is part of Outspline. # # Outspline 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. # # Ou
tspline is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ou...
birocorneliu/conference
lib/models.py
Python
apache-2.0
4,402
0.00159
#!/usr/bin/env python import httplib import endpoints from protorpc import messages, message_types class ConflictException(endpoints.ServiceException): """ConflictException -- exception mapped to HTTP 409 response""" http_status = httplib.CONFLICT class ProfileMiniForm(messages.Message): """ProfileMini...
ssage): """ProfileForm -- Profile outbound form message""" displayName = messages.StringField(1) mainEmail = messages.StringField(2) teeShirtSize = messages.EnumField('TeeShirtSize', 3) conferenceKeysToAttend = messages.StringField(4, repeated=True) sessionKeysWishlist = messages.StringField(5, ...
""" NOT_SPECIFIED = 1 XS_M = 2 XS_W = 3 S_M = 4 S_W = 5 M_M = 6 M_W = 7 L_M = 8 L_W = 9 XL_M = 10 XL_W = 11 XXL_M = 12 XXL_W = 13 XXXL_M = 14 XXXL_W = 15 class BooleanMessage(messages.Message): """BooleanMessage-- outbound Boolean value message""" da...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2016_09_01/models/effective_route.py
Python
mit
2,684
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 ...
ay', 'Default' :type source: str or ~azure.mgmt.network.
v2016_09_01.models.EffectiveRouteSource :param state: The value of effective route. Possible values are: 'Active' and 'Invalid'. Possible values include: 'Active', 'Invalid' :type state: str or ~azure.mgmt.network.v2016_09_01.models.EffectiveRouteState :param address_prefix: The address prefixes o...
pombredanne/readthedocs.org
readthedocs/core/signals.py
Python
mit
1,987
0.00151
"""Signal handling for core app.""" from __future__ import absolute_import import logging from corsheaders import signals from django.dispatch import Signal from django.db.models import Q from future.backports.urllib.parse import urlparse from readthedocs.projects.models import Project, Domain log = logging.getLo...
= ['/api/v2/footer_html', '/api/v2/search', '/api/v2/docsearch'] webhook_github = Signal(providing_args=['project', 'data', 'event']) webhook_gitlab = Signal(providing_args=['project', 'data', 'event']) webhook_bitbucket = Signal(providing_args=['project', 'data', 'even
t']) def decide_if_cors(sender, request, **kwargs): # pylint: disable=unused-argument """ Decide whether a request should be given CORS access. This checks that: * The URL is whitelisted against our CORS-allowed domains * The Domain exists in our database, and belongs to the project being querie...
rwl/PyCIM
CIM15/IEC61970/Informative/InfGMLSupport/GmlTopologyStyle.py
Python
mit
3,427
0.002334
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
le topology properties, thus multiple topology style descriptors can be specified within one feature style.The style for one topology property. Similarly to the Geometry style, a feature can have multiple topology properties, thus multiple topology style descriptors can
be specified within one feature style. """ def __init__(self, GmlLableStyle=None, GmlFeatureStyle=None, *args, **kw_args): """Initialises a new 'GmlTopologyStyle' instance. @param GmlLableStyle: @param GmlFeatureStyle: """ self._GmlLableStyle = None self.GmlLabl...
baloan/mt-krpc
krpc/lko.py
Python
mit
899
0.003337
#!/usr/bin/env python3 # -*- coding: cp1252 -*- # created on May 21, 2014 by baloan """ Launch to orbit (with atmosphere) """ from threading import Thread import krpc from toolkit import ksp from toolkit import launch from toolkit import system from toolkit import warp from vessels import surveyor, ...
("Surveyor 1") warp.warpday() # setup st
aging try: staging = STAGING_DICT[SC.active_vessel.name] except KeyError: staging = stock.default stage = Thread(target=staging, args=["Staging", ]) # launch to orbit stage.start() launch.ltoa() system.tts() if __name__ == "__main__": main()
arvinddoraiswamy/blahblah
cryptopals/Set2/c11.py
Python
mit
625
0.0144
import sys import os #Adding directory to the path where Python searches for modules cmd_folder = os.path.dirname('/home/arvind/Documents/Me/My_Projects/Git/Crypto/modules/') sys.path.insert(0, cmd_folder) #Importing common crypto module import block if __name__ == "__main__": plaintext= 'aaaaaaaaaaaaaaaaaaaaaaaa...
aaa
aaaaaaaaaa' is_aes_mode_ecb= block.encryption_oracle(plaintext) if is_aes_mode_ecb == 1: print "String ",plaintext, "is AES encrypted with ECB mode" else: print "String ",plaintext, "is AES encrypted with CBC mode"
hzlf/openbroadcast
website/apps/alibrary/management/commands/import_folder.py
Python
gpl-3.0
8,608
0.014292
#-*- coding: utf-8 -*- from django.core.files import File as DjangoFile from django.core.management.base import BaseCommand, NoArgsCommand from optparse import make_option import os import sys import re from django.template.defaultfilters import slugify from alibrary.models import Artist, Release, Media, Label from ...
v[1] releases = [] artists = [] tracks = [] #pattern = "^/[A-Za-z0-9.]/*$" pattern = re.compile('^/(?P<artist>[a-zA-Z0-9 ]+)/(?P<release>[a-zA-Z0-9 ]+)/(?P<tracknumber>[\d]+)[ ]* - [ ]*(?P<track>[
a-zA-Z0-9 -_]+)\.[a-zA-Z]+.*') pattern = re.compile('^/(?P<artist>[a-zA-Z0-9 ]+)/(?P<release>[a-zA-Z0-9 ]+)/(?P<tracknumber>[ab]?\d+?)[ | - ](?P<track>[Ça-zA-Z0-9 -_]+)\.[a-zA-Z]+.*') '^/(?P<release>[a-zA-Z0-9 ]+)/(?P<tracknumber>[ab]?\d+?)[ | -](?P<artist>[a-zA-Z0-9 ]+) - (?P<track>[Ç...
dwaithe/FCS_point_correlator
focuspoint/correlation_gui.py
Python
gpl-2.0
51,790
0.014501
import struct import numpy as np #import scipy.weave as weave import matplotlib.pyplot as plt from matplotlib.patches import Rectangle import sys, csv, os from PyQt5 import QtGui, QtCore, QtWidgets #import matplotlib #matplotlib.use('Agg') from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanva...
[i % len(self.par_obj.colors)], alpha=0.5,picker=True)) self.win_obj.canvas5.draw()
def redraw(self): for i in range(0,self.scrollBox.rect.__len__()): self.scrollBox.rect[i].remove() self.scrollBox.rect =[] for i in range(0,self.scrollBox.x0.__len__()): self.scrollBox.rect.append(plt.axvspan(self.scro...
tensorflow/datasets
tensorflow_datasets/audio/gtzan_music_speech/gtzan_music_speech_test.py
Python
apache-2.0
1,030
0.003883
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets 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 appl...
THOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """GTZAN Music Speech dataset.""" from tensorflow_datasets import testing from tensorflow_datasets.audio.gtzan_music_speech import gtzan_music_s...
ZANMusicSpeech SPLITS = { "train": 1, # Number of fake train examples } DL_EXTRACT_RESULT = {"music_speech": ""} if __name__ == "__main__": testing.test_main()
openstreams/wflow
Scripts/wflow_flood_lib.py
Python
gpl-3.0
28,442
0.001864
# -*- coding: utf-8 -*- """ Created on Wed Jul 08 16:12:29 2015 @author: winsemi $Id: wflow_flood_lib.py $ $Date: 2016-04-07 12:05:38 +0200 (Thu, 7 Apr 2016) $ $Author: winsemi $ $Revision: $ $HeadURL: $ $Keywords: $ """ import sys import os import configparser import logging import logging.handlers import numpy ...
er.addHandler(ch) logger.addHandler(console) logger.debug("File logging to " + logfilename)
return logger, ch except IOError: print("ERROR: Failed to initialize logger with logfile: " + logfilename) sys.exit(1) def closeLogger(logger, ch): logger.removeHandler(ch) ch.flush() ch.close() return logger, ch def close_with_error(logger, ch, msg): logger.error(msg) l...
vileopratama/vitech
src/openerp/tests/common.py
Python
mit
15,778
0.001521
# -*- coding: utf-8 -*- """ The module :mod:`openerp.tests.common` provides unittest test cases and a few helpers and classes to write tests. """ import errno import glob import importlib import json import logging import os import select import subprocess import threading import time import itertools import unittest ...
api.Environment(cls.cr, cls.uid, {}) @classmethod def tearDownClass(cls): # rollback and close the cursor, and reset the environments cls.registry.clear_caches() cls.env.reset() cls.cr.rollback() cls.cr.close() savepoint_seq = itertools.count() class SavepointCase(Sin...
Case` in that all test methods are run in a single transaction *but* each test case is run inside a rollbacked savepoint (sub-transaction). Useful for test cases containing fast tests but with significant database setup common to all cases (complex in-db test data): :meth:`~.setUpClass` can be used...
jiivan/genoomy
genoome/genoome/wsgi.py
Python
mit
1,563
0.00064
""" WSGI config for genoome project. This module contains the WSGI application used by Django's development server and any produc
tion WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Djang...
an application of another framework. """ import os from os.path import abspath, dirname from sys import path SITE_ROOT = dirname(dirname(abspath(__file__))) path.append(SITE_ROOT) # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. ...
wainersm/buildbot
master/buildbot/data/builders.py
Python
gpl-2.0
4,882
0.000615
# This file is part of Buildbot. Buildbot 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. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
od def updateBuilderInfo(self, builderid, description, tags): return self.master.db.builders.updateBuilderInfo(builderid, description, tags) @base.updateMethod @defer.inlineCallbacks def updateBuilderList(self, masterid, builderNames): # get the "current" list of builders for this maste...
we know what # changes to make. Race conditions here aren't a great worry, as this # is the only master inserting or deleting these records. builders = yield self.master.db.builders.getBuilders(masterid=masterid) # figure out what to remove and remove it builderNames_set = set(...
cawka/packaging-PyNDN
examples/ndnChat/chat.py
Python
bsd-3-clause
2,131
0.030502
# # Copyright (c) 2011, Regents of the University of California # BSD license, See the COPYING file for more information # Written by: Derek Kulinski <[email protected]> # import curses, curses.wrapper, curses.textpad, threading, time, sys from ChatNet import ChatNet, ChatServer class ChatGUI(object): def __init__(se...
atServer(self.prefix) thread = threading.Thread(target=server.lis
ten) thread.start() while True: text = self.textbox.edit() self.input_sc.erase() if text == "": continue #self.write(text) server.send_message(text) def curses_code(self, stdscr): self.stdscr = stdscr self.window_setup() curses.doupdate() chatnet = ChatNet(self.prefix, self.callback) ...
jawilson/home-assistant
tests/components/climate/test_device_condition.py
Python
apache-2.0
10,053
0.001492
"""The tests for Climate device conditions.""" import pytest import voluptuous_serialize import homeassistant.components.automation as automation from homeassistant.components.climate import DOMAIN, const, device_condition from homeassistant.helpers import config_validation as cv, device_registry from homeassistant.se...
s += [ { "condition": "device", "domain": DOMAIN, "type":
condition, "device_id": device_entry.id, "entity_id": f"{DOMAIN}.test_5678", } for condition in expected_condition_types ] conditions = await async_get_device_automations(hass, "condition", device_entry.id) assert_lists_same(conditions, expected_conditions) async d...
josch149/pyjs-seminar
website/code/scalign.py
Python
gpl-2.0
4,124
0.008734
# author : Johann-Mattis List # email : [email protected] # created : 2015-07-11 11:27 # modified : 2015-07-11 11:27 """ Carry out Sound-Class Based Alignment Analyses. """ __author__="Johann-Mattis List" __date__="2015-07-11" import json def segment2class(segment, converter): """ Convert a s...
M[i][j] = match elif gapA <= gapB: M[i][j] = gapA T[i][j] = 1 # don't forget the traceback else: M[i][j] = gapB T[i][j] = 2 # don't forget the traceback # get the edit distance ED = M[i][j] # start the traceback...
while i > 0 or j > 0: if T[i][j] == 0: almA += [seqA[i-1]] almB += [seqB[j-1]] i -= 1 j -= 1 elif T[i][j] == 1: almA += [seqA[i-1]] almB += ["-"] i -= 1 else: almA += ["-"] almB += [...
joostvdg/jenkins-job-builder
tests/general/test_general.py
Python
apache-2.0
1,118
0
# Joint copyright: # - Copyright 2012,2013 Wikimedia Foundation # - Copyright 2012,2013 Antoine "hashar" Musso # - Copyright 2013 Arnaud Fabre # # 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 ...
D, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os from testscenarios.testcase import TestWithScenarios from testtools import TestCase from jenkins_jobs.modules import general from tests.base import BaseTestCase from tests.ba...
xtures_path = os.path.join(os.path.dirname(__file__), 'fixtures') scenarios = get_scenarios(fixtures_path) klass = general.General
fishilico/shared
python/clang_cfi_typeid.py
Python
mit
16,141
0.002416
#!/usr/bin/env python3 """Compute the CallSiteTypeId of some function types for clang CFI (Control Flow Integrity). When calling a function indirectly, clang could introduce a call to a function which checks the type of the called function: void __cfi_check(uint64 CallSiteTypeId, void *TargetAddr, void *DiagData)...
("_ZTSy", 0x1639a2a5e21b1916, "unsigned long long"), ("_ZTSz", 0xfd
5f5dc16053a2a4, "..."), # Two letters, with type modifiers. There are also possible three-letter combinations ("_ZTSra", 0x88f6d4d6eab1df2e, "signed char restrict"), ("_ZTSrb", 0xad687ff06e782ded, "bool restrict"), ("_ZTSrc", 0xdba4d1ceedf018fb, "char restrict"), ("_ZTSrd", 0x0430abdad346705c, "dou...
NaturalEcon/RDb
NatEcon/urls.py
Python
gpl-3.0
433
0.004619
from django.conf.urls import patterns, include, url from RDb import views from django.contrib i
mport admin from django.conf import settings from django.conf.urls.static import static admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'views.index', name='index'), url(r'^RDb/', include('RDb.urls')), url(r'^admin/', include(admin.site.urls)), ) + static(settings.STATIC_URL, document_root=sett...
OT)
weigj/django-multidb
tests/regressiontests/model_fields/tests.py
Python
bsd-3-clause
1,604
0
""" >>> from django.db.models.fields import * >>> try: ... from decimal import Decimal ... except ImportError: ... from django.utils._decimal import Decimal # DecimalField >>> f = DecimalField(max_digits=4, decimal_places=2) >>> f.to_python(3) == Decimal("3") True >>> f.to_python("3.14") == Decimal("3.14") ...
. f.get_db_prep_lookup('exact', val) [False] [False] [False] >>> f = NullBooleanField() >>> for val in (True, '1', 1): ... f.get_db_prep_lookup('exact', val) [True] [True] [True] >>> for val in (False, '0', 0): ... f.get_db_prep_lookup('exact', val) [False] [False] [False] >>> f.get_db_prep_lookup('exact',...
ne) [None] """
Gehn/JustAChatBot
sleekxmpp/plugins/xep_0079/amp.py
Python
mit
2,578
0.001552
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2013 Nathanael C. Fritz, Lance J.T. Stout This file is part of SleekXMPP. See the file LICENSE for copying permissio """ import logging from sleekxmpp.stanza import Message, Error, StreamFeatures from sleekxmpp.xmlstream import register_stanza_plugi...
StanzaPath('message/error/failed_rules'), StanzaPath('message/amp') ]), self._handle_amp_response)) if not self.xmpp.is_component:
self.xmpp.register_feature('amp', self._handle_amp_feature, restart=False, order=9000) register_stanza_plugin(StreamFeatures, stanza.AMPFeature) def plugin_end(self): self.xmpp.remove_handler('AMP Response') def _handle_amp_re...
ashwinm76/alienfx
alienfx/core/controller_m15x.py
Python
gpl-3.0
4,057
0.003451
# # controller_m15x.py # # Copyright (C) 2013-2014 Ashwin Menon <[email protected]> # Copyright (C) 2015-2018 Track Master Steve <[email protected]> # # Alienfx is free software. # # You may redistribute it and/or modify it under the terms of the # GNU General Public License, as published by the Free Soft...
self.STATE_AC_SLEEP: self.AC_SLEEP, self.STATE_AC_CHARGED: self.AC_CHARGED, self.STATE_AC_CHARGING: self.AC_CHARGING, self.STATE_BATTERY_SLEEP: self.BATTERY_SLEEP, self.STATE_BATTERY_ON: self.BATTERY_ON, self.STATE_BATTERY_CRITICAL: self.BATTERY_CRIT...
x())
kmcginn/advent-of-code
2016/day04/security.py
Python
mit
922
0.003254
from collections import defaultdict from operator import itemgetter import re def isRealRoom(name, checksum): if len(checksum) != 5: raise Exception totals = defaultdict(int) for c in name: if c != '-': totals[c] += 1 pairs = zip(totals.keys(), totals.values()) alphaPair...
if(isRealRoom(room, checksum)): sectorSum += sector print
(sectorSum) if __name__ == "__main__": main()
jeanmask/opps
opps/core/management/commands/exportcontainerbox.py
Python
mit
546
0
from django.core.management.base import BaseCommand from django.core import serializers from opps.boxes.models import QuerySet fro
m opps.channels.models import Channel from opps.containers.models import ContainerBox class Command(BaseCommand): def handle(self, *args, **options): models = [Channel, ContainerBox, QuerySet] for m in models: data = serializers.serialize("json", m.objects.all()) out = ope...
out.write(data) out.close()
factorlibre/odoo-addons-cpo
purchase_compute_order_product_filter_season/models/computed_purchase_order.py
Python
agpl-3.0
696
0
# -*- coding: utf-8 -*- # © 2016 FactorLibre - Hugo Santos <hug
[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import api, fields, models class ComputedPurchaseOrder(models.Model): _inherit = 'computed.purchase.order' product_season = fi
elds.Many2one('product.season', 'Product Season') @api.multi def _active_product_stock_product_domain(self, psi_ids): product_domain = super(ComputedPurchaseOrder, self).\ _active_product_stock_product_domain(psi_ids) if self.product_season: product_domain.append(('seaso...
eufarn7sp/egads-eufar
egads/thirdparty/nappy/nc_interface/na_to_nc.py
Python
bsd-3-clause
3,191
0.008461
# Copyright (C) 2004 CCLRC & NERC( Natural Environment Research Council ). # This software may be distributed under the terms of the # Q Public License, version 1.0 or later. http://ndg.nerc.ac.uk/public_docs/QPublic_license.txt """ na_to_nc.py =========== Contains the NAToNC class for converting a NASA...
=time_units, time_warning=time_warning, rename_variables=rename_variables) def writeNCFile(self, file_name, mode="w"): """ Writes the NASA Ames content that has been converted into CDMS objects to a NetCDF file of name 'file_name'. Note that mode can be set to appe...
output file object fout = cdms.open(file_name, mode=mode) # Write main variables for var in self.cdms_variables: fout.write(var) # Write aux variables for avar in self.cdms_aux_variables: fout.write(avar) # Write global attributes ...
sekikn/ambari
ambari-common/src/main/python/ambari_ws4py/streaming.py
Python
apache-2.0
13,075
0.002141
# -*- coding: utf-8 -*- import struct from struct import unpack from ambari_ws4py.utf8validator import Utf8Validator from ambari_ws4py.messaging import TextMessage, BinaryMessage, CloseControlMessage,\ PingControlMessage, PongControlMessage from ambari_ws4py.framing import Frame, OPCODE_CONTINUATION, OPCODE_TEXT,...
y yields for more bytes whenever it requires them. The stream owner is responsible to provide the stream with those bytes until a frame can be interpreted. .. code-block:: python :linenos: >>> s = Stream() >>> s.parser.send(BYTES) >>> s.has_m...
_BYTES) >>> s.has_messages True >>> s.message <TextMessage ... > Set ``always_mask`` to mask all frames built. Set ``expect_masking`` to indicate masking will be checked on all parsed frames. """ self.message = None """ ...
dafrito/trac-mirror
trac/ticket/tests/report.py
Python
bsd-3-clause
4,474
0.001342
# -*- coding: utf-8 -*- # # Copyright (C) 2006-2013 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consi...
"$VAR, $PARAM, $MISSING", {'VAR': 'value'}) self.assertEqual("%s, %s, %s", sql) self.assertEqual(['value', '', ''], values) self.assertEqual(['PARAM', 'MISSING'], missing_args) def test_csv_escape(self): buf = StringIO() def start_response(status, headers): ...
iron, start_response) cols = ['TEST_COL', 'TEST_ZERO'] rows = [('value, needs escaped', 0)] try: self.report_module._send_csv(req, cols, rows) except RequestDone: pass self.assertEqual('\xef\xbb\xbfTEST_COL,TEST_ZERO\r\n"value, needs escaped",0\r\n', ...
jmcarpenter2/swifter
swifter/swifter_tests.py
Python
mit
31,276
0.000831
import sys import importlib import unittest import subprocess import time import logging import warnings from psutil import cpu_count import numpy as np import numpy.testing as npt import pandas as pd import swifter from tqdm.auto import tqdm LOG = logging.getLogger(__name__) LOG.setLevel(logging.INFO) ch = logging...
0, 10)}, index=pd.date_range("2019-01-1", "2020-01-1", periods=10), ).swifter.rolling("1d"), pd.DataFrame( {"x": np.arange(0, 10)}, index=pd.date_range("2019-01-1", "2020-01-1", periods=10), ).swifter.resample("3T"),
]: before = swifter_df._dask_threshold swifter_df.set_dask_threshold(expected) actual = swifter_df._dask_threshold self.assertEqual(actual, expected) self.assertNotEqual(before, actual) def test_set_dask_scheduler(self): LOG.info("test_set_dask_s...
mozilla/zamboni
mkt/tags/utils.py
Python
bsd-3-clause
2,555
0
from django import forms from django.utils.translation import ugettext as _, ungettext as ngettext import mkt from mkt.access import acl from mkt.site.utils import slugify from mkt.tags.models import Tag def clean_tags(request, tags, max_tags=None): """ Blocked tags are not allowed. Restricted tags can ...
s.ValidationError(msg) restricted = (Tag.objects.values_list('tag_text', flat=True) .filter(tag_text__in=target, restricted=True)) if restricted and not can_edit_restricted_tags(request): # L10n: {0} is a single tag or a
comma-separated list of tags. msg = ngettext(u'"{0}" is a reserved tag and cannot be used.', u'"{0}" are reserved tags and cannot be used.', len(restricted)).format('", "'.join(restricted)) raise forms.ValidationError(msg) else: # Admin's restric...
teeple/pns_server
work/install/Python-2.7.4/Lib/test/test_set.py
Python
gpl-2.0
62,916
0.004466
import unittest from test import test_support import gc import weakref import operator import copy import pickle from random import randrange, shuffle import sys import collections class PassThru(Exception): pass def check_pass_thru(): raise PassThru yield 1 class BadCmp: def __hash__(self): ...
ertRaises(PassThru, self.s.symmetric_difference, check_pass_thru()) self.assertRaises(TypeError, self.s.symmetric_difference, [[]]) for C in set, frozenset, dict.fromkeys, str, unicode, list, tuple: self.assertEqu
al(self.thetype('abcba').symmetric_difference(C('cdc')), set('abd')) self.assertEqual(self.thetype('abcba').symmetric_difference(C('efgfe')), set('abcefg')) self.assertEqual(self.thetype('abcba').symmetric_difference(C('ccb')), set('a')) self.assertEqual(self.thetype('abcba').symmetr...
rmmh/skybot
plugins/weather.py
Python
unlicense
4,026
0.000497
"""Weather, thanks to darksky and google geocoding.""" from __future__ import unicode_literals from util import hook, http GEOCODING_URL = "https://maps.googleapis.com/maps/api/geocode/json" DARKSKY_URL = "https://api.darksky.net/forecast/" def geocode_location(api_key, loc): """Get a geocoded location from goo...
sed_json def get_weather_data(api_key, lat, long): """Get weather data from darksky.""" query = "{key}/{lat},{long}".format(key=api_key, lat=lat, long=long) u
rl = DARKSKY_URL + query try: parsed_json = http.get_json(url) except IOError: return None return parsed_json def f_to_c(temp_f): """Convert F to C.""" return (temp_f - 32) * 5 / 9 def mph_to_kph(mph): """Convert mph to kph.""" return mph * 1.609 @hook.api_key("google"...
Chuban/moose
python/chigger/tests/chigger/test_chigger.py
Python
lgpl-2.1
2,346
0.003836
#!/usr/bin/env python #pylint: disable=missing-docstring ################################################################# # DO NOT MODIFY THIS HEADER # # MOOSE - Multiphysics Object Oriented Simulation Environment # # #...
tIn('aux_elem', out) self.assertIn('func_pp', out) def testImg2Mov(self): """ Test 'img2mov' command. """ pattern = os.path.join('..', 'fi
eld_data', 'gold', 'plot_current_*.png') out = self.execute('img2mov', pattern, '-o', 'output.mov', '--dry-run', '-j', '4', '--duration', '30') gold = 'ffmpeg -pattern_type glob -framerate 0 -i ../field_data/gold/plot_current_*.png ' \ '-c:v mpeg2video -b:v 10M -pix_fmt yuv420p -q:v 1 -th...