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
voitureblanche/projet-secret
work/Python-toolchain/3D/build_cosine_tables.py
Python
mit
1,178
0.043294
import os import string import codecs import ast import math from vector3 import Vector3 filename_out = "../../
Assets/cosine_table" table_size = 512 fixed_point_precision = 512 def dumpCosine(_cosine_func, display_name, f): f.write('const int ' + display_name + '[] =' + '\n') f.write('{' + '\n') # _str_out = '\t' for angle in range(0,table_size): _cos = int(_cosine_func(angle * math.pi / (table_size / 2.0)...
_out = str(_cos) + ',' f.write(_str_out + '\n') # if angle%10 == 9: # f.write(_str_out + '\n') # _str_out = '\t' f.write('};' + '\n') def main(): ## Creates the header f = codecs.open(filename_out + '.h', 'w') f.write('#define COSINE_TABLE_LEN ' + str(table_size) + '\n') f.write('\n') ...
genodeftest/exaile
xlgui/preferences/plugin.py
Python
gpl-2.0
11,178
0.000716
# Copyright (C) 2008-2010 Adam Olsen # # 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, or (at your option) # any later version. # # This program is distributed in the hope that...
m xl.nls import gettext as _, ngettext import logging logger = logging.getLogger(__name__) name = _('Plugins') ui = xdg.get_data_path('ui', 'preferences', 'plugin.ui') class PluginManager(object): """ Gui to manage plugins """ def __
init__(self, preferences, builder): """ Initializes the manager """ self.preferences = preferences builder.connect_signals(self) self.plugins = main.exaile().plugins self.message = dialogs.MessageBar( parent=builder.get_object('preferences_pane'),...
peragro/peragro-at
src/damn_at/analyzers/image/analyzerimage.py
Python
bsd-3-clause
3,097
0.000323
""" Generic Image analyzer. """ # Standard import os import logging import subprocess # Damn from damn_at import ( mimetypes, MetaDataType, MetaDataValue, FileId, FileDescription, AssetDescription, AssetId ) from damn_at.pluginmanager import IAnalyzer from damn_at.analyzer import AnalyzerEx...
string_value=value )
file_descr.assets.append(asset_descr) return file_descr
nguyenkims/projecteuler-python
src/p102.py
Python
mit
1,087
0.103036
limit = 10 ** 4 def isOK(a1,a2,a3,m): '''test if m is in the same plan as a3 vis-a-vis to a1a2''' x1, y1= float(a1[0]), float(a1[1]) x2,y2= float(a2[0]), float(a2[1]) x3,y3=float(a3[0]), float(a3[1]) x,y=float(m[0
]), float(m[1]) t = (x-x1) * (y2-y1) - (y-y1) * (x2-x1) k = (x3-x1) * (y2-y1) - (y3-y1) * (x2-x1) if t*k > 0: return True return False def isInterior(a1,a2,a3,m) : '''test if m is in the triangle
formed by a,b,c ''' if isOK(a1,a2,a3,m) and isOK(a2,a3,a1,m) and isOK(a3,a1,a2,m): return True def test(): a1 =(-340,495) a2= (-153,-910) a3 = (835,-947) X= (-175,41) Y= (-421,-714) Z = (574,-645) m = (0,0) print isInterior(a1,a2,a3,m), isInterior(X,Y,Z,m) print intersection(X,m,Y,Z) # test() def main(...
jamesandreou/hackerrank-solutions
warmup/hr_time_conversion.py
Python
mit
298
0.026846
# hackerrank - Algo
rithms: Time Conversion # Written by James Andreou, University of Waterloo S = raw_input() TYPE = S[len(S)-2] if S[:2] == "12": if TYPE == "A": print "00" + S[2:-2] else: print S[:-2] elif TYPE == "P": HOUR = int(S[:2]) + 12 print str(HOUR) + S[2:-2] else: print
S[:-2]
Castronova/EMIT
api_old/ODM2/Sensors/services/__init__.py
Python
gpl-2.0
319
0.00627
__author__ = 'Stephanie' from ODMconnection import dbconnection from
readSensors import readSensors from up
dateSensors import updateSensors from createSensors import createSensors from deleteSensors import deleteSensors __all__ = [ 'readSensors', 'updateSensors', 'createSensors', 'deleteSensors', ]
garinh/cs
docs/support/docutils/writers/latex2e.py
Python
lgpl-2.1
75,964
0.00387
""" :Author: Engelbert Gruber :Contact: grubert@users.sourceforge.net :Revision: $Revision: 21817 $ :Date: $Date: 2005-07-21 13:39:57 -0700 (Thu, 21 Jul 2005) $ :Copyright: This module has been placed in the public domain. LaTeX2e document tree Writer. """ __docformat__ = 'reStructuredText' # code contributions from...
'superscript', 'metavar': '<format>', 'overrides': 'trim_footnote_reference_space'}), ('Use LaTeX citations. ' 'Default: no, uses figures which might get mixed with images.',
['--use-latex-citations'], {'default': 0, 'action': 'store_true', 'validator': frontend.validate_boolean}), ('Format for block quote attributions: one of "dash" (em-dash ' 'prefix), "parentheses"/"parens", or "none". Default is "dash".', ['--attribution'], ...
ingve/IncludeOS
test/fs/integration/ide_write/test.py
Python
apache-2.0
663
0.007541
#! /usr/bin/env python import sys import os import subprocess includeos_src = os.environ.get('INCLUDEOS_SRC', os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))).split('/test')[0]) sys.path.insert(0,includeos_src) from vmrunner import vmrunner #
Get an auto-created VM from the vmrunner vm = vmrunner.vms[0] def cleanup(): # Call the cleanup script - let python do the printing to get it synced print subprocess.check_output(["./fat32_disk.sh", "clean"]) # Setup
disk subprocess.call(["./fat32_disk.sh"], shell=True) # Clean up on exit vm.on_exit(cleanup) # Boot the VM vm.cmake().boot(30).clean()
gustavofonseca/penne-core
frontdesk/templatetags/frontdesk.py
Python
bsd-2-clause
1,931
0.002071
from django import template from django.template.defaultfilters import stringfilter register = template.Library() STATUS_COLORS = { 'default': 'blue', 'queued': 'blue', 'undetermined': 'blue', 'infected': 'red', 'uninfect
ed': 'green', 'deposited': 'blue', 'rejected': 'red', 'accepted': 'green', 'valid': 'green', 'invalid': 'red', 'undefined': 'blue' } BOX_COLORS = { 'blue': 'primary', 'red': 'danger', 'green': 'success', 'grey': 'default' } @register
.filter @stringfilter def status_color(status): """ This method will return grey for a unkown status. """ return STATUS_COLORS.get(status, 'grey') @register.filter def box_color(status): """ This method will return grey for a unkown status. """ return BOX_COLORS.get(STATUS_COLORS.get...
matus-stehlik/glowing-batman
events/migrations/0002_auto__add_unique_campuserinvitation_camp_user.py
Python
mit
10,021
0.007983
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding unique constraint on 'CampUserInvitation', fields ['camp', 'user'] db.create_unique(u'events_campus...
ype': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [
], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),...
aronsky/home-assistant
homeassistant/components/rfxtrx/helpers.py
Python
apache-2.0
715
0
"""Provides helpers for R
FXtrx.""" from RFXtrx import get_device from homeassistant.core import callback from homeassistant.helpers import device_registry as dr from homeassistant.helpers.typing import HomeAssistantType @callback def async_get_device_object(hass: HomeAssistantType, device_id): """Get a device for the given device regi...
et(device_id) if registry_device is None: raise ValueError(f"Device {device_id} not found") device_tuple = list(list(registry_device.identifiers)[0]) return get_device( int(device_tuple[1], 16), int(device_tuple[2], 16), device_tuple[3] )
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_07_01/operations/_application_security_groups_operations.py
Python
mit
24,325
0.005015
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
ingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-impo
rt,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class ApplicationSecurityGroupsOperations(object): """ApplicationSecurityGroupsO...
dichen001/Go4Jobs
JoeXu/42. Trapping rain water.py
Python
gpl-3.0
616
0.027597
class Solution(object): def trap(self, height): """ :t
ype height: List[int] :rtype: int """ l=len(height) maxheight=[0 for i in range(l)] leftmax=0 rightmax=0 res=0 for i in range(l): if height[i]>leftmax: leftmax=height[i] maxheight[i]=leftmax for i in...
)-height[i] return res
chubbymaggie/miasm
miasm2/analysis/expression_range.py
Python
gpl-2.0
2,613
0.000383
"""Naive range analysis fo
r expression""" from miasm2.analysis.modul
arintervals import ModularIntervals _op_range_handler = { "+": lambda x, y: x + y, "&": lambda x, y: x & y, "|": lambda x, y: x | y, "^": lambda x, y: x ^ y, "*": lambda x, y: x * y, ">>": lambda x, y: x >> y, "a>>": lambda x, y: x.arithmetic_shift_right(y), "<<": lambda x, y: x << y, ...
CVML/winpython
winpython/py3compat.py
Python
mit
6,585
0.003949
# -*- coding: utf-8 -*- # # Copyright © 2012-2013 Pierre Raybaut # Licensed under the terms of the MIT License # (see spyderlib/__init__.py for details) """ spyderlib.py3compat ------------------- Transitional module providing compatibility functions intended to help migrating from Python 2 to Python 3. ...
========================================================== def get_meth_func(obj): """Return method f
unction object""" if PY2: # Python 2 return obj.im_func else: # Python 3 return obj.__func__ def get_meth_class_inst(obj): """Return method class instance""" if PY2: # Python 2 return obj.im_self else: # Python 3 return ...
b3c/VTK-5.8
Wrapping/Python/vtk/__helper.py
Python
bsd-3-clause
981
0.008155
""" This provides some useful code used by other modules. This is not to be used by the end user which is why it is hidden. """ import string, sys class LinkError(Exception): pass def refine_import_err(mod_name, extension_name, exc): """ Checks to see if the ImportError was because the library itself was...
that is to be imported by the module having mod_name. - exc : The exception raised when the module called mod_name was imported. To see example usage look at __init__.py. """ try: del sys.modules['vtk.%s'%mod_name]
except KeyError: pass if string.find(str(exc), extension_name) == -1: raise LinkError, str(exc)
laborautonomo/youtube-dl
youtube_dl/utils.py
Python
unlicense
42,818
0.002382
#!/usr/bin/env python # -*- coding: utf-8 -*- import calendar import contextlib import ctypes import datetime import email.utils import errno import getpass import gzip import itertools import io import json import locale import math import os import pipes import platform import re import ssl import socket import stru...
# Flush the final pct_sequence string += pct_sequence.decode(
encoding, errors) return string def _parse_qsl(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace'): qs, _coerce_result = qs, unicode pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')] r = [] for name_value in pairs...
Alexis-benoist/CaTeX
tests/test_core.py
Python
apache-2.0
1,434
0.001395
# -*- coding: utf-8 -*- from click import open_file
def read_file(path): with open_file(path, 'r', encoding='utf8') as f: return ''.join(f.readlines()) def test_import(): from catex import LaTeX def test_import_(): import catex def test_latex_simple(): from catex import LaTeX f1 = LaTeX.from_file("tests/data/latex1.tex") f1.merge(f1...
"tests/data/latex2.tex") expected_result = read_file("tests/data/merge1_2.tex") assert rv.__repr__() == expected_result def test_merge_packeges(): from catex.core import merge_packages pkg1 = [ ['th', ['mou', 'moi', 'mumu=tutu']], ['blo', []], ['bli', ['tut']], ['bli',...
codeforamerica/mdc-feedback
feedback/surveys/views.py
Python
mit
1,698
0.002356
# -*- coding: utf-8 -*- # DO NOT DELETE import StringIO import csv import datetime today = datetime.date.today() from flask import ( Blueprint, make_response ) from flask.ext.login import login_required from sqlalchemy import desc from feedback.surveys.models import Survey blueprint = Blueprint( 'sur...
bmitted', 'method', 'language', 'route', 'rating', 'role', 'get_done', 'purpose', 'best', 'worst', 'improvement', 'follow_up', 'contact', 'more_comments']) survey_models = Survey.query.order_by(desc(Survey.date_...
survey_model.lang, survey_model.route_en, survey_model.rating, survey_model.role_en, survey_model.get_done, survey_model.purpose_en, survey_model.best_en, survey_model.worst_en, survey_model.improvement, ...
ytaben/cyphesis
rulesets/mason/world/tasks/Logging.py
Python
gpl-2.0
4,546
0.009899
#This file is distributed under the terms of the GNU General Public license. #Copyright (C) 2005 Al Riddoch (See the file COPYING for details). from atlas import * from physics import * from physics import Quaternion from physics import Vector3D import math from random import * import server class Logging(server.T...
# from character to tree, and vertically upward vector
axis = distance_to(self.character.location, self.target().location).cross(Vector3D(0,0,1)) # the axis must be a unit vector try: axis = axis.unit_vector() except ZeroDivisionError: ...
lixiangning888/whole_project
modules/signatures_orignal/rat_spynet.py
Python
lgpl-3.0
1,986
0.006546
# Copyright (C) 2014 @threatlead # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in th...
m lib.cuckoo.common.abstracts import Signature class SpynetRat(Signature): name = "rat_spynet" description = "Creates known SpyNet mutexes and/or registry changes." severity = 3 catego
ries = ["rat"] families = ["spynet"] authors = ["threatlead", "nex"] references = [ "https://malwr.com/analysis/ZDQ1NjBhNWIzNTdkNDRhNjhkZTFmZTBkYTU2YjMwNzg/", "https://malwr.com/analysis/MjkxYmE2YzczNzcwNGJiZjljNDcwMzA2ZDkyNDU2Y2M/", "https://malwr.com/analysis/N2E3NWRiNDMyYjIwNGE0NT...
michealcarrerweb/LHVent_app
operation_finance/migrations/0021_auto_20170712_0222.py
Python
mit
519
0.001927
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-07-12 02:22 from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('operation_finance', '0020_auto_20170711_1429'), ] operations = [ ...
=models.DateField(default=datetime.date
time(2017, 8, 6, 2, 22, 37, 974278)), ), ]
alexgibson/bedrock
bedrock/firefox/redirects.py
Python
mpl-2.0
32,590
0.005247
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. from bedrock.redirects.util import no_redirect, platform_redirector, redirect def firefox_mobile_faq(request, *args, ...
irefox.nightly.firstrun"), # bug 840814 redirect( r"^projects/firefox" r"(?P<version>/(?:\d+\.\d+\.?(?:\d+)?\.?(?:\d+)?(?:[a|b]?)(?:\d*)(?:pre)?(?:\d)?))" r"(?P<page>/(?:firstrun|whatsnew))" r"(?P<res
t>/.*)?$", "/firefox{version}{page}{rest}", ), # bug 877165 redirect(r"^firefox/connect", "mozorg.home"), # bug 657049, 1238851 redirect(r"^firefox/accountmanager/?$", "https://developer.mozilla.org/Persona"), # Bug 1009247, 1101220, 1299947, 1314603, 1328409 redirect(r"^(firefox/)?b...
vendelin8/serverApplet
plugin/__init__.py
Python
gpl-2.0
1,584
0.004422
# -*- coding: utf-8 -*- # # Plugins' module file for serverApplet. # Copyright (C) 2015 Gergely Bódi # # 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 ...
n account with that plugin 'testLogin', # tests an account after creating it 'startCron', # does cron job functionality for the given login 'nextCron', # returns the time for the next cron job running time for the given login ...
modulename): '''Returns additional plugin functions for the plugin as a dict: {"system tray menu label": "plugin function name"}''' return __import__('plugin.{}'.format(modulename), fromlist=['actions']).actions
oomlout/oomlout-OOMP
old/OOMPpart_CAPC_0603_X_PF100_V50.py
Python
cc0-1.0
245
0
import OOMP newPart = OOMP.oompItem(8826) newPart.addTag("oompType", "CAPC") newPart.addTag("oompSize", "0603") newPart.addTag("oompColor", "X") newPart.
add
Tag("oompDesc", "PF100") newPart.addTag("oompIndex", "V50") OOMP.parts.append(newPart)
home-assistant/home-assistant
homeassistant/components/hue/v1/sensor_base.py
Python
apache-2.0
7,575
0.001056
"""Support for the Philips Hue sensors as a platform.""" from __future__ import annotations from datetime import timedelta import logging from typing import Any from aiohue import AiohueException, Unauthorized from aiohue.v1.sensors import TYPE_ZLL_PRESENCE import async_timeout from homeassistant.components.sensor i...
d_listener(self.async_update_items) ) await self.coordinator.async_refresh() @callback def async_upda
te_items(self): """Update sensors from the bridge.""" api = self.bridge.api.sensors if len(self._component_add_entities) < len(self._enabled_platforms): return to_add = {} primary_sensor_devices = {} current = self.current # Physical Hue motion sens...
ticosax/django-rest-framework
tests/test_fields.py
Python
bsd-2-clause
38,463
0.00117
from decimal import Decimal from django.utils import timezone from rest_framework import serializers import rest_framework import datetime import django import pytest import uuid # Tests for field keyword arguments and core functionality. # --------------------------------------------------------- class TestEmpty: ...
s set, then omitted values get the default input. """ field = serializers.IntegerField(default=123) outp
ut = field.run_validation() assert output is 123 class TestSource: def test_source(self): class ExampleSerializer(serializers.Serializer): example_field = serializers.CharField(source='other') serializer = ExampleSerializer(data={'example_field': 'abc'}) assert serializ...
brad/swftools
spec/gradients.py
Python
gpl-2.0
3,650
0.019452
from sys import * from pdflib_py import * p = PDF_new() PDF_open_file(p, "gradients.pdf") PDF_set_parameter(p, "usercoordinates", "true") PDF_set_value(p, "compress", 0) PDF_set_info(p, "Author", "pdflib") PDF_set_info(p, "Creator", "pdflib_py") PDF_set_info(p, "Title", "gradients") width = 1024 height = 800 PDF_...
ding = PDF_shading(p, type, 0+x,0+y, 320+x,320+y, 1.0, 1.0, 1.0, 1.0, params) #axial|radial pattern = PDF_shading_pattern(p,shading,"") PDF_setcolor(p, "fill", "pattern", pattern,0,0,0) PDF_moveto(p, x,y) P
DF_curveto(p, x+80, y+80, x+80, y+240, x, y+320) PDF_curveto(p, x+80, y+240, x+240, y+240, x+320, y+320) PDF_curveto(p, x+240, y+240, x+240, y+80, x+320, y) PDF_curveto(p, x+240, y+80, x+80, y+80, x, y) PDF_fill(p) PDF_moveto(p, x,y) PDF_curveto(p, x+80, y+80, x+80, y+240, x, y+320) PDF_curveto(p, x+80, y+240, x+240, y...
obnam-mirror/obnam
obnamlib/app.py
Python
gpl-3.0
11,277
0
# Copyright (C) 2009-2017 Lars Wirzenius # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distribu...
for pattern in self.settings['trace']: tracing.trace_add_pattern(pattern) self.hooks.call('config-loade
d') cliapp.Application.process_args(self, args) self.hooks.call('shutdown') except paramiko.SSHException as e: logging.critical( 'Caught SSHExcpetion: %s', str(e), exc_info=True) raise ObnamSSHError(msg=str(e)) e...
garncarz/dns-server
dns/migrations/0003_redirection.py
Python
gpl-2.0
640
0.001563
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-01-10 22:43 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dns', '0002_auto_20151228_0134'), ] operations = [ migrations.Cr
eateModel( name='Redirection', fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abbr', models.CharField(max_length=100, unique=True)), ('target', models.URLField()), ], ), ]
JKlesmith/Bioinformatics
ProcessMSA.py
Python
bsd-3-clause
4,782
0.015056
#!/usr/bin/python #Copyright (c) 2016, Justin R. Klesmith #All rights reserved. from __future__ import division from math import log, sqrt, pow import argparse, os, random #Set the author information __author__ = "Justin R. Klesmith" __copyright__ = "Copyright 2016, Justin R. Klesmith" __credits__ = ["Justin R. Kles...
lose() #Make a DSSP lookup string Wildtype = MSATable[">ENTER YOUR WILD-TYPE SEQUENCE HEADER NAME HERE found in the MSA or CDHIT Cluster"] MSAWTLen = len(Wi
ldtype) #CorrectedDSSP = "" #DSSPCount = 1 #print Wildtype #DSSP = "" #for j in xrange(1,int(args.length)): #Mutations[j] = False #DSSP = DSSP + Mutations[j].rstrip("\n\r") #print DSSP #for j in xrange(0,MSAWTLen): # if Wildtype[j] == "-": # CorrectedDSSP = CorrectedDSSP + "-" # else: # ...
pchickey/paparazzi-linux-release
sw/tools/calibration/calib.py
Python
gpl-2.0
3,989
0.018802
# # My first attempt at python # calibrate accelerometer # import re import scipy from scipy import optimize from scipy import linalg from pylab import * # # parse the log # def read_log(ac_id, filename, sensor): f = open(filename, 'r') pattern = re.compile("(\S+) "+ac_id+" IMU_"+sensor+"_RAW (\S+) (\S+) (\S+...
[5]*2**res)+"\" integer=\"16\"/>" filename = 'log_accel_booz2_a2' ac_id = "151" if 1: sensor = "ACCEL" sensor_ref = 9.81 sensor_res = 10 noise_window = 20; noise_threshold = 40; else: sensor = "MAG" sensor_ref = 1. sensor_res = 11 noise_window = 10; noise_threshold = 1000; ...
nd "+str(len(measurements))+" records" flt_meas, flt_idx = filter_meas(measurements, noise_window, noise_threshold) print "remaining "+str(len(flt_meas))+" after low pass" p0 = get_min_max_guess(flt_meas, sensor_ref) cp0, np0 = scale_measurements(flt_meas, p0) print "initial guess : "+str(np0.mean())+" "+str(np0.std(...
ttn-be/ttnmapper
config.py
Python
mit
1,297
0.010023
from network import WLAN ##############################
################################################# # Settings for WLAN STA mode ############################################################################### WLAN_MODE = 'off' #WLAN_SSID = '' #WLAN_AUTH = (
WLAN.WPA2,'') ############################################################################### # LoRaWAN Configuration ############################################################################### # May be either 'otaa', 'abp', or 'off' LORA_MODE = 'otaa' # Settings for mode 'otaa' LORA_OTAA_EUI = '70B3...
chubbymaggie/reverse
plasma/lib/__init__.py
Python
gpl-3.0
12,594
0.005717
#!/usr/bin/env python3 # # PLASMA : Generate an indented asm code (pseudo-C) with colored syntax. # Copyright (C) 2015 Joel # # 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 ...
t 30, maximum of chars to display for strings or bytes array.') parser.add_argument('-x', '--entry', metavar='SYMBOLNAME|0xXXXXX|EP', help='Pseudo-decompilation, default is main. EP stands for entry point.') parser.add_argument('--vim', action='store_true', help='Generate...
dd_argument('--sections', action='store_true', help='Print all sections') parser.add_argument('--dump', action='store_true', help='Dump asm without decompilation') parser.add_argument('-l', '--lines', type=int, default=30, metavar='N', help='Max lines used...
vgrem/Office365-REST-Python-Client
office365/outlook/calendar/calendar_permission.py
Python
mit
1,204
0.005814
from office365.entity import Entity from office365.outlook.calendar.email_address import EmailAddress class CalendarPermission(Entity): """ The permissions of a user with whom the calendar has been shared or delegated in an Outlook client. Get, update, and delete of calendar permissions is supported on b...
nly the calendar owner. Getting the calendar permissions of a calendar on behalf of a sharee or delegate returns an empty calendar permissions collection. Once a sharee or delegate has been set up for a calendar, you can update only the role property to change the permissions of a sharee or delegate. ...
the allowedRoles, emailAddress, isInsideOrganization, or isRemovable property. To change these properties, you should delete the corresponding calendarPermission object and create another sharee or delegate in an Outlook client. """ @property def email_address(self): """ Represents...
pepeportela/edx-platform
common/lib/xmodule/xmodule/word_cloud_module.py
Python
agpl-3.0
8,926
0.001232
"""Word cloud is ungraded xblock used by students to generate and view word cloud. On the client side we show: If student does not yet answered - `num_inputs` numbers of text inputs. If student have answered - words he entered and cloud. """ import json import logging from pkg_resources import resource_string from x...
umber of occurences :param dict_obj: all words :type dict_obj: dict :param amount: number of words to be in top dict :type amount: int :rtype: dict """ return dict( s
orted( dict_obj.items(), key=lambda x: x[1], reverse=True )[:amount] ) def handle_ajax(self, dispatch, data): """Ajax handler. Args: dispatch: string request slug data: dict request get parameters ...
anurag03/integration_tests
cfme/base/credential.py
Python
gpl-2.0
7,024
0.000712
# -*- coding: utf-8 -*- from copy import deepcopy from cfme.utils import conf from cfme.utils.pretty import Pretty from cfme.utils.update import Updateable class FromConfigMixin(object): @staticmethod def rename_properties(creds): """ helper function to make properties have same names in crede...
if key1 in creds: creds[key2] = creds[key1] del creds[key1] return creds @classmethod def from_config(cls, key): """ helper function which allows to construct credential object from credentials.eyaml Args: key: credential k...
ns: credential object """ creds = cls.rename_properties(conf.credentials[key]) return cls(**creds) @classmethod def from_plaintext(cls, creds): """ helper function which allows to construct credential class from plaintext dict Args: creds: dict ...
mozilla/make.mozilla.org
make_mozilla/pages/models.py
Python
bsd-3-clause
5,208
0.003072
from django.conf import settings from django.core.files.storage import FileSystemStorage from django.core.urlresolvers import reverse from django.db import models from django.utils.html import strip_tags from django.utils.safestring import mark_safe from django.core.exceptions import ValidationError from make_mozilla....
r = models.TextField(blank=True, null=True) quotes = models.ManyToManyField('Quote', blank=True, null=True) class Meta: verbose_name = 'section' ordering = ['id'] def __unicode__(self): return mark_safe(self.title) @property def nav_title(self): if self.subnav_titl...
class Quote(models.Model): quote = models.CharField(max_length=1000) source = models.ForeignKey('QuoteSource', blank=True, null=True) url = models.URLField(blank=True, null=True, verbose_name='URL') show_source_image = models.BooleanField(default=False, help_text='Show the source\'s image next to thi...
Azure/azure-sdk-for-python
sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_diagnostic_settings_operations.py
Python
mit
12,838
0.004674
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parame...
response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) raise HttpResponseError(re...
uclouvain/osis_louvain
assessments/tests/functionals/test_score_encoding.py
Python
agpl-3.0
57,982
0.004933
import datetime import functools import os import random import shutil import tempfile import time from urllib import request import faker import magic import pendulum from django.conf import settings from django.contrib.auth.models import Group, Permission from django.contrib.staticfiles.testing import StaticLiveServ...
mport PersonFactory from base.tests.factories.program_manager import ProgramManagerFactory from base.tests.factories.session_exam_calendar import \ SessionExamCalendarFactory from base.tests.factories.session_examen import SessionExamFactory from base.tests.factories.student import StudentFactory from base.tests.fa...
: def create_user(self): return UserFactory() def create_super_user(self): return SuperUserFactory() def add_group(self, user, *group_names): for name in group_names: group, created = Group.objects.get_or_create(name=name) group.user_set.add(user) def a...
nextml/NEXT
apps/PoolBasedTripletMDS/algs/ValidationSampling/utilsMDS.py
Python
apache-2.0
14,387
0.018002
""" utilsMDS.py author: Kevin Jamieson (kevin.g.jamieson@gmail.com) edited: 1/18/15 This module has methods that assist with non-metric multidimensional scaling. If you're trying to COMPUTE an embedding, you might simply call: X,emp_loss = computeEmbedding(n,d,S) You may also consider getLoss to check how well...
se) Usage: q,score = getRandomQuery(X) """ n,d = X.shape while True: i = randint
(n) j = randint(n) k = randint(n) if i != j and j != k and k != i: break q = [i, j, k] score = getTripletScore(X,q) return q,score def getTripletScore(X,q): """ Given X,q=[i,j,k] returns score = ||x_j - x_k||^2 - ||x_i - x_k||^2 If score > 0 then the triplet ...
lia2790/grasp_learning
python/simple_batch_splitter.py
Python
bsd-3-clause
913
0.004381
#!/usr/bin/env python from mvbb.box_db import MVBBLoader import multiprocessing, subprocess from multiprocessing import Pool import sys from plugins import soft_hand def grasp_boxes(filename): subprocess.call(['python', './grasp_boxes_batch.py', filename]) if __name__ == '__main__': try: import os.p...
name = 'box_db' if not os.path.isfile(filename+'.csv'): print "Error: file", filename, "doesn't exist" exit() try: n_dofs = int(sys.argv[2]) n_l = int(sys.argv[3]) except: n_dofs = soft_hand.numJoints n_l = len(soft_hand.links_to_check) # for SoftHand ...
s, n_l) filenames = box_db.split_db() p = Pool(multiprocessing.cpu_count()) p.map(grasp_boxes, filenames) box_db.join_results(filenames)
klim-iv/phantomjs-qt5
src/webkit/Tools/Scripts/webkitpy/layout_tests/models/test_results_unittest.py
Python
bsd-3-clause
2,300
0
# Copyright (C) 2010 Google 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 copyright # notice, this list of conditions and the ...
CH DAMAGE. import unittest2 as
unittest from webkitpy.layout_tests.models.test_results import TestResult class TestResultsTest(unittest.TestCase): def test_defaults(self): result = TestResult("foo") self.assertEqual(result.test_name, 'foo') self.assertEqual(result.failures, []) self.assertEqual(result.test_run...
abitofalchemy/hrg_nets
karate_chop.py
Python
gpl-3.0
4,865
0.019527
import random import math import collections import tree_decomposition as td import create_production_rules as pr import graph_sampler as gs import stochastic_growth import probabilistic_growth import net_metrics import matplotlib.pyplot as plt import product import networkx as nx import numpy as np import snap #G =...
Complete" exit() Gergm = [] Gergmgl = [] for run in range(1, 3): f = open('../demo_graphs/ergm_sim/enron/data '+str(run)+' .csv', 'r') E=nx.Graph() header = 0 for line in f: line=line.rstrip() if header == 0: header+=1 continue c
= line.split("\t") if(len(c) is not 3): continue E.add_edge(int(c[1]),int(c[2])) if int(c[1]) > num_nodes or int(c[2]) > num_nodes: continue Gergm.append(E) print "G ergm iteration " + str(run) + " of 20" Gergmgl.append(gs.subgraphs_cnt(E,50)) k = int(math.floor(math.log...
Bolt64/proxy_switcher
proxy_autoconfig.py
Python
mit
3,103
0.010957
#!/usr/bin/env python ## Some necessary imports from __future__ import print_function from commands import getoutput from time import sleep from os.path import expanduser import os import re from datetime import datetime import process_lock as pl ### ## Configuration options script_location = os.path.dirname(os.pa...
want to run to turn on proxy proxy_unset_script = "bash {0}/proxy_u
nset.sh".format(script_location) # The script to turn off proxy checking_interval = 2 # The checking frequency in seconds. default_log_file = expanduser("~/.proxy_log") # Where the logging will happen. ssid_matcher=re.compile("ESSID:\"[\w]*\"") # A regular expression to match to the output of iwconfig. ssid_slice=slic...
smorante/continuous-goal-directed-actions
simulated-CGDA/generalization/generalization_old_test2.py
Python
mit
7,027
0.021346
from __future__ import division import itertools from sklearn import mixture, metrics from sklearn.cluster import DBSCAN from scipy import linalg from scipy.spatial import distance import pylab as pl import matplotlib as mpl from scipy.interpolate import Rbf, InterpolatedUnivariateSpline import csv import numpy as np...
#ell.set_clip_box(splot.bbox) #ell.set_alpha(.6) #splot.add_artist(ell) #pl.xticks(()) #pl.yticks(()) #pl.title('GMM-BIC. Components: ' + str(len(clf.means_)), size=20) ## saving centers sortedPoints = sorted(clf.means_, key=lambda point: point[0]) np.savetxt("generali...
ime=min(meansX) #maximTime=max(meansX) #print minimTime, maximTime #xi = np.linspace(minimTime, maximTime, 10*len(meansX)) #testrbf = Rbf(meansX, meansY, function='gaussian') #yi = testrbf(xi) #pl.subplot(4, 1, 4) #pl.plot(xi, yi, 'g') #pl.scatter(means...
mintuhouse/shotfactory
shotfactory04/gui/linux/navigator.py
Python
gpl-3.0
2,507
0
# browsershots.org - Test your web design in different browsers # Copyright (C) 2007 Johann C. Rocholl <johann@browsershots.org> # # Browsershots 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 Fou
ndation; either version 3 of the License, or # (at your option) any later version. # # Browsershots 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 det...
nctions for X11. """ __revision__ = "$Rev: 2749 $" __date__ = "$Date: 2008-04-08 20:43:21 +0530 (Tue, 08 Apr 2008) $" __author__ = "$Author: hawk $" import os from shotfactory04.gui import linux as base class Gui(base.Gui): """ Special functions for Netscape Navigator. """ def reset_browser(self):...
nico202/pyUniSR
setup.py
Python
gpl-2.0
919
0.020675
import os from setuptools import setup # Utility function to read the README file. # Used
for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "pyUniSR", version = "0.0.7", a...
erity Vita-Salute San Raffaele, Milano)"), license = "GPLv2", keywords = "unisr class milano university raffaele", url = "https://github.com/nico202/pyUniSR", packages=['UniSR'], classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :...
utisam/gfly
gfly/__init__.py
Python
gpl-3.0
4,933
0.036084
#-*- coding:utf-8 -*- import string from gi.repository import GObject, Gedit, Gtk, Pango from settings import errorGenerator, jump_to_error_key, notification ui_str = """<ui> <menubar name="MenuBar"> <menu name="EditMenu" action="Edit"> <placeholder name="EditOps_6"> <menuitem name="gfly" action="gfly"/> ...
tConnectedTab = window.connect("active_tab_chan
ged", self.__tab_changed) #connect document signal if not self.currentConnectedDoc is None: window.disconnect(self.currentConnectedDoc) self.currentConnectedDoc = None doc.connect("saved", self.__doc_saved) #connect view signal tab.get_view().connect_after("move-cursor", self.__move_cursor) #create ta...
acasadoquijada/Telegram-bot-stuff
Stuff/new_users_saver.py
Python
gpl-2.0
825
0.008485
###
############################################################################# # new_users_saver funciton ################################################################################ def newusers(m): dict_updater() un = m.from_user.username if un not in DBDIC: uid = m.from_user.id DBDIC[...
uid = m.new_chat_participant.id DBDIC[un] = [uid,0] dict_saver() ################################################################################ # "newusers" saves new users in the dictionary # (see dict_updater_saver.py for "dict_updater()" and "dict_saver()") #####################################...
stefanpeidli/GoNet
Filters.py
Python
mit
15,577
0.004365
""" @author: Stefan Peidli License: MIT Tags: Neural Network """ import numpy as np from Board import Board n = 9 # Testboards def gen_test_board(method=0): if method == 0: b = np.zeros((n, n)) b[0, 2] = 1 b[1, 3] = 1 b[3, 3] = 1 b[2, 3] = -1 b[0, 1] = -1 ...
if color == board[row-1, col]:
[group, libs] = give_group_at_position(board, row-1, col) val += - libs neighbours += 1 checked.extend(group) if not(row == n-1): if color == board[row+1, col]: [group, libs
kirienko/unseries
unseries.py
Python
gpl-3.0
9,529
0.002205
# encoding: utf8 from sympy import Add from uncertainties import __version_info__ as uncert_version from uncertainties import ufloat, ufloat_fromstr from uncertainties.core import Variable, AffineScalarFunc if uncert_version < (3, 0): raise Warning("Your version of uncertanties is not supported. Try\n" ...
def __rdiv__(self, other): return other * self.__invert__() def __pow__(self, power, modulo=None): if isinstance(power, int) and power > 1: return reduce(lambda x, y: x * y, [self] * power) elif isinstance(power, int)
and power == 1: return self elif isinstance(power, int) and power == 0: if self.analytic: return Series(self.n, {0: 1}, self.name, analytic=self.analytic) else: return Series(self.n, {0: ufloat(1, 0)}, self.name, analytic=self.analytic) ...
Tydus/deluge
deluge/core/eventmanager.py
Python
gpl-3.0
3,162
0.001265
# # eventmanager.py # # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> # # Deluge 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 Software # Foundation; either version 3 of the License, or (at your option) # any later ...
nt if event.name in self.handlers: for handler in self.handlers[event.name
]: #log.debug("Running handler %s for event %s with args: %s", event.name, handler, event.args) try: handler(*event.args) except Exception, e: log.error("Event handler %s failed in %s with exception %s", event.name, handler, e) ...
Bideau/SmartForrest
RaspberryPi/dataBase/mysql/CreateMysqlTable.py
Python
mit
6,863
0.006994
#!/usr/bin/python # -*- coding: utf-8 -* """ The MIT License (MIT) Copyright (c) 2015 Christophe Aubert 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 limit...
NULL,"\ "c_password VARCHAR (50) NOT NULL ,"\ "c_adminKey BOOLEAN DEFAULT
NULL,"\ "PRIMARY KEY(c_id)"\ ")ENGINE=InnoDB;" self.sqlCommand.append(connection) stationAccess = "CREATE TABLE stationAccess ( "\ "staa_id INT (11) Auto_increment NOT NULL,"\ ...
vim-scripts/TeX-9
ftplugin/tex_nine/tex_nine_utils.py
Python
gpl-3.0
3,875
0.005935
# -*- coding: utf-8 -*- #************************************************************************ # # TeX-9 library: Python module # # 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 Softw...
(2) envs[m.groups()] = i if ('begin', e) in envs and ('end', e) in envs and envs[('end', e)] < envs[('begin', e)]: # Eliminate nested environments del envs[('begin', e)] del envs[('end', e)] elif ('end', e) not i...
environment = e break if not end: envs = {} for i, line in enumerate(tail): m = pat.match(line) if m: envs[m.groups()] = i e = m.group(2) if ('begin', e) in envs and ('end', e) in envs: ...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-3.3.0/Lib/test/test_htmlparser.py
Python
mit
30,373
0.001152
"""Tests for HTMLParser.py.""" import html.parser import pprint import unittest from test import support class EventCollector(html.parser.HTMLParser): def __init__(self, *args, **kw): self.events = [] self.append = self.events.append html.parser.HTMLParser.__init__(self, *args, **kw) ...
.fail("received events did not match expected events\n" "Expected:\n" + pprint.pformat(expected_events) + "\nReceived:\n" + pprint.pformat(events)) def _run_check_extra(self, source, events): self._run_check(source, events, EventCollectorExtra()) def _parse_...
self.assertRaises(html.parser.HTMLParseError, parse) class HTMLParserStrictTestCase(TestCaseBase): def get_collector(self): with support.check_warnings(("", DeprecationWarning), quite=False): return EventCollector(strict=True) def test_processing_instruction_only(self): self....
dnxbjyj/python-basic
gui/wxpython/wxPython-demo-4.0.1/demo/PopupMenu.py
Python
mit
4,928
0.004261
#!/usr/bin/env python import wx import images #---------------------------------------------------------------------- text = """\ Right-click on any bare area of this panel (or Ctrl-click on Macs if you don't have a multi-button mouse) to show a popup menu. Then look at the code for this sample. Notice how the Po...
se to the object of interest # for clarity. if not hasattr(self, "popupID1"): self.popupID1 = wx.NewId() self.popupID2 = wx.NewId() self.popupID3 = wx.NewId() self.popupID4 = wx.NewId() self.popupID5 = wx.NewId() self.popupID6 = wx....
= wx.NewId() self.popupID9 = wx.NewId() self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1) self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2) self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3) self.Bind(wx.EVT_MENU, self.OnPopupFour, id...
TheWardoctor/Wardoctors-repo
script.module.fantastic/lib/resources/lib/sources/en/sceper.py
Python
apache-2.0
6,854
0.018675
# -*- coding: utf-8 -*- ''' fantastic Add-on This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This pro...
() y = re.findall('[\.|\(|\[|\s](\d{4}|S\d*E\d*|S\d*)[\.|\)|\]|\s]', name)[-1].upper() if not y == hdlr: raise Exception() fmt = re.sub('(.+)(\.|\(|\[|\s)(\d{4}|S\d*E\d*|S\d*)(\.|\)|\]|\s)', '', name.upper()) fmt = re.split('\.|\(|\)|\[|...
dub')) for i in fmt): raise Exception() if any(i in ['extras'] for i in fmt): raise Exception() if '1080p' in fmt: quality = '1080p' elif '720p' in fmt: quality = 'HD' else: quality = 'SD' if any(i in ['dvdscr', 'r5', '...
stxnext/intranet-open
src/intranet3/intranet3/views/times/tickets.py
Python
mit
4,991
0.004809
from __future__ import with_statement from pyramid.view import view_config from pyramid.renderers import render from intranet3.utils.views import BaseView from intranet3.models import ( User, TimeEntry, Tracker, Project, Client, DBSession, ) from intranet3.forms.times import ProjectsTimeForm, ...
ew_time_report') class Report(TimesReportMixin, BaseView): def dispatch(self): clie
nt = self.request.user.get_client() form = ProjectsTimeForm(self.request.GET, client=client) if not self.request.GET or not form.validate(): return dict(form=form) start_date, end_date = form.date_range.data projects = form.projects.data if not projects: ...
geomf/omf-fork
omf/hdfs.py
Python
gpl-2.0
7,235
0.003179
# Open Modeling Framework (OMF) Software for simulating power systems behavior # Copyright (c) 2015, Intel Corporation. # # This program is free software; you can redistribute it and/or modify it # under the terms and conditions of the GNU General Public License, # version 2, as published by the Free Software Foundatio...
status = self.hdfs.get_file_status(Hdfs.HOME_DIR + path) return status def get_file_modification_time(self, path): return self.hdfs.get_file_status(Hdfs.HOME_DIR + path).modificationTime / 1000 def exists(self, path): return self.hdfs.exists(Hdfs.HOME_DIR + path) def open...
.open(Hdfs.HOME_DIR + path) print "Opening file: " + path + ". Type is: " + str(type(f)) return f def save(self, path, content): try: self.hdfs.create(Hdfs.HOME_DIR + path, content) except pyhdfs.HdfsFileAlreadyExistsException: self.hdfs.delete(Hdfs.HOME_DIR ...
linfanangel/Trality
cart/cartapp/permission.py
Python
gpl-3.0
268
0.003731
from rest_framework import permissions class IsReadOnly(permissions.BasePermission): def has_object_permissi
on(self, request, view, obj):
if request.method in permissions.SAFE_METHODS: return True return obj.owner == self.request.user
PrairieLearn/PrairieLearn
exampleCourse/questions/workshop/Lesson1_example3_v3/server.py
Python
agpl-3.0
1,005
0.01393
import random def generate(data): ask = ['equivalent resistance $R_T$', 'current from the power supply $I_T$'] which = random.choice([0,1]) data['para
ms']['ask'] = ask[which] label = ["$R_T$", "$I_T$"] data['params']['lab'] = label[which] unit = ["$\\Omega$", "
A"] data['params']['unit'] = unit[which] Vt = random.randint(100,200) data['params']['Vt'] = Vt R1 = random.choice(list(range(20,180,10))) data['params']['R1'] = R1 R2 = random.choice(list(range(20,180,20))) data['params']['R2'] = R2 R3 = random.choice(list(range(20,100,5))) data...
zqfan/leetcode
algorithms/437. Path Sum III/solution.py
Python
gpl-3.0
748
0
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: int ...
rn (root
.val == sum) + left + right
jumpserver/jumpserver
apps/tickets/serializers/ticket/meta/ticket_type/login_asset_confirm.py
Python
gpl-3.0
591
0.003431
from rest_framework import serializers from django.utils.translation import ugettext_lazy as _ __all__ = [ 'ApplySerializer', 'LoginAssetConfirmSerializer', ] class ApplySerializer(serializers.Serializer): # 申请信息 apply_login_user = serializers.Char
Field(required=True, label=_('Login user')) apply_login_asset = serializers.CharField(required=True, label=_('Login asset')) apply_login_system_use
r = serializers.CharField( required=True, max_length=64, label=_('Login system user') ) class LoginAssetConfirmSerializer(ApplySerializer): pass
celebdor/kuryr-libnetwork
kuryr_libnetwork/schemata/request_pool.py
Python
apache-2.0
2,102
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 # distributed under t...
pace.', u'type': u'string', u'example': u'foo', }, u'Pool': { u'description': u'A range of IP Addresses represented in ' u'CIDR format address/mask.', u'$ref': u'#/definitions/commons/definitions/cidr' }, u'SubPo...
': u'#/definitions/commons/definitions/cidr' }, u'Options': { u'type': [u'object', u'null'], u'description': u'Options', u'example': {}, }, u'V6': { u'description': u'If set to "True", requesting IPv6 pool and ' ...
inventree/InvenTree
InvenTree/order/migrations/0042_auto_20210310_1619.py
Python
mit
972
0.002058
# Generated by Django 3.0.7 on 2021-03-10 05:19 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('users', '0005_owner_model'), ('order', '0041_auto_20210114_1728'), ] operations = [ migrations.AddF...
s.ForeignKey(blank=True, help_text='User or group responsible for this order', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='users.O
wner', verbose_name='Responsible'), ), ]
suutari-ai/shoop
shuup/addons/admin_module/views/reload.py
Python
agpl-3.0
3,004
0.001664
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals import time from django ...
=_("Reload Method"), initial=self.reload_methods[0].identifier, widget=forms.RadioSelect ) def get_selected_reload_method(self): return first(rm for rm in self.reload_methods if rm.identifier == self.cleaned_data["reload_method"]) def finalize_installation_for_enabled_ap
ps(): out = StringIO() enabled_addons = get_enabled_addons(settings.SHUUP_ENABLED_ADDONS_FILE) new_apps = [app for app in enabled_addons if app not in settings.INSTALLED_APPS] if new_apps: out.write("Enabling new addons: %s" % new_apps) settings.INSTALLED_APPS += type(settings.INSTALLED_...
erickdom/restAndroid
transactions/migrations/0002_transaction_response.py
Python
apache-2.0
436
0.002294
# -*- coding: utf-8 -*-
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('transactions', '0001_initial'), ]
operations = [ migrations.AddField( model_name='transaction', name='response', field=models.CharField(default=b'', max_length=4, null=True, blank=True), ), ]
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.7/Lib/doctest.py
Python
mit
101,750
0.001179
# Module doctest. # Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org). # Major enhancements and refactoring by: # Jim Fulton # Edward Loper # Provided as-is; use at your own risk; no warranty; no promises; enjoy! r"""Module doctest -- a framework for running examples in docstrings. In...
ring containing a traceback message for the given exc_info tuple (a
s returned by sys.exc_info()). """ # Get a traceback mess
phw/weblate
weblate/formats/tests/test_convert.py
Python
gpl-3.0
4,423
0.000452
# # Copyright © 2012 - 2021 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lice...
onvert import ( HTMLFormat, IDMLFormat, OpenDocumentFormat, PlainTextFormat, WindowsRCFormat, ) from weblate.formats.helpers import BytesIOMode from weblate.formats.tests.test_formats import AutoFormatTest from weblate.trans.tests.utils import get_test_file IDML_FILE = get_test_file("en.idml") HTML...
et_test_file("cs.odt") TEST_RC = get_test_file("cs-CZ.rc") TEST_TXT = get_test_file("cs.txt") class ConvertFormatTest(AutoFormatTest): NEW_UNIT_MATCH = None EXPECTED_FLAGS = "" def parse_file(self, filename): return self.FORMAT(filename, template_store=self.FORMAT(filename)) class HTMLFormatTes...
trombastic/PyScada
pyscada/modbus/migrations/0004_auto_20160115_0920.py
Python
gpl-3.0
454
0
# -*- coding: utf-8 -*- fro
m __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pyscada', '0010_auto_20160115_0918'), ('modbus', '0003_auto_20160115_0918'), ] operations = [ migrations.RenameField( model_name='m...
), ]
savoirfairelinux/secure-odoo
action_access_control_list/models/ir_rule.py
Python
lgpl-3.0
486
0
# -*- coding: utf-8 -*- # © 2017 Savoir-faire Linux # License LGPL-3.
0 or later (http://www.gnu.org/licenses/gpl). from odoo import api, models class IrRule(models.Model): _inherit = 'ir.rule' @api.model def _compute_domain(self, model_name, mode="read"): if getattr(self.env, '_bypass_access', False): if self.env._bypass_exception != model_name: ...
mode=mode)
acevest/acecode
learn/python/mul.py
Python
gpl-2.0
462
0.008658
#!/usr/bin/env python # -*- coding: utf-8 -*- # -------------------------------------------
----------------------------- # File Name: mul.py # Author: Zhao Yanbai # Thu Oct 1 15:10:27 2015 # Description: none # ------------------
------------------------------------------------------ for j in range(1, 10) : for i in range(1, 10) : if i>j : continue print "{0}*{1}={2:<2d}\t".format(i, j, i*j), print ""
kernsuite-debian/lofar
SAS/DataManagement/ResourceTool/resourcetool.py
Python
gpl-3.0
24,976
0.006006
#!/usr/bin/env python3 # Copyright (C) 2017 # ASTRON (Netherlands Institute for Radio Astronomy) # P.O.Box 2, 7990 AA Dwingeloo, The Netherlands # # This file is part of the LOFAR software suite. # The LOFAR software suite is free software: you can redistribute it # and/or modify it under the terms of the GNU General P...
ce_type_id) # Get associated tasks for their end times. Update claims for tasks that ended. task_ids = list(set({claim['task_id'] for claim i
n claims}))
iaddict/mercurial.rb
vendor/mercurial/contrib/debugshell.py
Python
mit
533
0.003752
# debugshell extension """a python shell with repo, changelog & manifest objects""" import mercurial import code def debugshell(ui, repo, **opts): objects = { 'mercurial': me
rcurial, 'repo': repo, 'cl': repo.changelog, 'mf': repo.manifest, } bannermsg = "loaded repo : %s\n" \ "using source: %s" % (repo.root,
mercurial.__path__[0]) code.interact(bannermsg, local=objects) cmdtable = { "debugshell|dbsh": (debugshell, []) }
csmengwan/autorest
AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/setup.py
Python
mit
1,158
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 may cause incorrect behavior and will be lost if the code is # regenerated. # --------------------
------------------------------------------------------ # coding: utf-8 from setuptools import setup, find_packages NAME = "autorestparametergroupingtestservice" VERSION = "1.0.0" # To install the library, run the following # # python setup.py install # # prerequisite: setuptools # http://pypi.python.org/pypi/setupto...
andersk/zulip
zerver/migrations/0192_customprofilefieldvalue_rendered_value.py
Python
apache-2.0
418
0
# Generated by Django 1.11.16 on 2018-11-14 12:15 from django.db import migrations, models class Migration(migrations.Migration): d
ependencies = [ ("zerver", "0191_realm_seat_limit"), ] operations = [ migrations.AddField( model_name="customprofilefiel
dvalue", name="rendered_value", field=models.TextField(default=None, null=True), ), ]
Valka7a/python-playground
sqlite3/tutorials/module-in-python.py
Python
mit
756
0.001323
""" To use the SQLite3 module we need to add an import statement to our python script: _____
___________________________________________________________________________ >>> import sqlite3 ________________________________________________________________________________ We can check sqlite version: ________________________________________________________________________________ >>> sqlite3.verison '2.6.0' >>> sq...
____ The sqlite.version is the version of the pysqlite (2.6.0), which is the binding of the Python language to the SQLite database. The sqlite3.sqlite_version gives us the version of the SQLite database library. In our case it is 3.7.17.
DonBeo/statsmodels
statsmodels/duration/tests/test_phreg.py
Python
bsd-3-clause
11,981
0.003506
import os import numpy as np from statsmodels.duration.hazard_regression import PHReg from numpy.testing import (assert_allclose, assert_equal) import pandas as pd # TODO: Include some corner cases: data sets with empty strata, strata # with no events, entry times after censoring times,...
exog[:, 1:] mod2 = PHReg(time, exog, status, offset=offset) rslt2 = mod2.fit() assert_allclose(rslt2.params,
rslt1.params[1:]) def test_post_estimation(self): # All regression tests np.random.seed(34234) time = 50 * np.random.uniform(size=200) status = np.random.randint(0, 2, 200).astype(np.float64) exog = np.random.normal(size=(200,4)) mod = PHReg(time, exog, status) ...
waynegm/OpendTect-Plugins
bin/python/wmpy/Skeletons/ex_multi_trace_single_attribute_input_single_output.py
Python
gpl-3.0
2,619
0.030546
# External Attribute Skeleton # # Input: Multi-trace, single attribute # Output: Single attribute # import sys,os import numpy as np # # Import the module with the I/O scaffolding of the External Attribute # sys.path.insert(0, os.path.join(sys.path[0], '..')) import extattrib as xa # # The attribute parameters - keep ...
er_xline = xa.SI['nrcrl'] centre_trace_x = xa.SI['nrinl']//2 centre_trace_y = xa.SI['nrcrl']//2 nyquist = 1.0/(2.0*xa.SI['zstep']) par0 = xa.params['Par_0']['Value'] zw = xa.params['ZSampMargin']['Value'][1] - xa.params['ZSampMargin']['Value'
][0] + 1 select = xa.params['Select']['Selection'] # # This is the trace processing loop # while True: xa.doInput() # # After doInput the TraceInfo, xa.TI, array contains information specific to this trace segment - keep what you need # number_of_samples = xa.TI['nrsamp'] start_time = xa.TI['z0'] current_inli...
Universal-Model-Converter/UMC3.0a
scripts/SSBM.py
Python
mit
25,037
0.037385
from data.COMMON import * #essentials Header( 0.001, #Script Version (for updates) ('Melee',['dat']), #model activation ('Melee',['dat']), #anim activation ['RVL_IMG'])#revolution']) #included libs #gist number: 2757147 #for the work I've done to get this far, this should really ...
#yet to be seen (returning white) count=bu16(label=' -- Facepoint Count') while count>0: tmtx = MTX44() #transformations V,N,C,U='','',['',''],['','','','','','','',''] for attr in Attributes: I,L=CPT(attr[1]); length += L...
(attr[7]+(I*attr[6]))+32, IS3D) switch(attr[0]) if case( 0): tmtx = weights_list[bu8()/3];length+=1; LABEL(' -- Weight Index/value') #vert/nor_mtx elif case( 1): bu8()/3; length+=1 #uv[0]_mtx (value not used yet) elif case( 2): bu8()/3;...
tidepool-org/dfaker
dfaker/cbg.py
Python
bsd-2-clause
2,185
0.008696
import statsmodels.api as sm from . import common_fields from . import make_gaps from . import tools from .device_event import make_alarm_event def apply_loess(solution, num_days, gaps): """Solves the blood glucose equation over specified period of days and applies a loess smoothing regression to the da...
gluc -- a list of glucose values at each timestep timesteps -- a list of epoch times zonename -- name of timezone in effect """ cbg_data = [] for value, timestamp in zip(gluc, timesteps): cbg_reading = {} cbg_reading = common_fields.add_common_fields('cbg', cbg_readi...
ng["annotation"] = [{"code": "bg/out-of-range", "threshold": 400, "value": "high"}] cbg_reading["value"] = tools.convert_to_mmol(401) elif value < 40: cbg_reading["annotation"] = [{"code": "bg/out-of-range", "threshold": 40, "value": "low"}] cbg_reading["value"] = tools.conve...
spatialdev/onadata
onadata/apps/logger/migrations/0048_auto__add_project__add_unique_project_name_organization__add_projectxf.py
Python
bsd-2-clause
16,039
0.007419
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Project' db.create_table(u'logger_project', ( ...
s.files.FileField', [], {'max_length': '100'}), 'mimetype': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '50', 'blank': 'True'}) }, 'logger.instance': { 'Meta': {'object_name': 'Instance'}, 'date_created': ('django.db.models.fields.DateTim...
to_now_add': 'True', 'blank': 'True'}), 'date_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'deleted_at': ('django.db.models.fields.DateTimeField', [], {'default': 'None', 'null': 'True'}), 'geom': ('django.contrib.gis.db.models.fiel...
deepchem/deepchem-gui
gui/app.py
Python
gpl-3.0
8,020
0.001995
import os from flask import Flask, url_for, request, render_template, jsonify, send_file from werkzeug.utils import secure_filename import deepchem as dc import subprocess from shutil import copyfile import csv import rdkit from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem import Draw STATIC_DIR = ...
data[i].append(url_for('static', filename='data/' + smiles_2_fn)) except Exception as e: print(e) data[i].append("Invalid") data[i].append("Invalid") data[i].append("Invalid") pass return data def dock(protein_fns, ligand_fns): ...
(protein_fns))] for i in range(len(protein_fns)): for j in range(len(ligand_fns)): protein_fn = protein_fns[i] ligand_fn = ligand_fns[j] print("Docking: %s to %s" % (ligand_fn, protein_fn)) docker = dc.dock.VinaGridDNNDocker( exhaustiveness=...
rhyolight/nupic.son
app/soc/logic/program.py
Python
apache-2.0
944
0.002119
# Copyright 2013 the Melange 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 applicable law or agreed to in wr...
ermissions and # limitations under the License. """Logic for programs.""" from soc.models import program as program_model def getSponsorKey(program): """Returns key which represents Sponsor of the specified program. Args: pr
ogram: program entity Returns: db.Key instance of the sponsor for the specified program """ return program_model.Program.sponsor.get_value_for_datastore(program)
Kegbot/kegbot-server
pykeg/web/setup_wizard/views.py
Python
gpl-2.0
6,069
0.00033
from functools import wraps import logging import traceback from django.conf import settings from django.core import management from django.contrib import messages from django.contrib.auth import authenticate from django.http import Http404 from django.shortcuts import redirect from django.shortcuts import render from ...
e elif "disable_users" in request.POST: response = redirect("setup_site_settings") response.set_cookie("kb_setup_enable_users", "False") return response else: messages.error(request, "Unknown response.") return render(request, "setup_wizard/accounts.h...
@setup_view @never_cache def site_settings(request): context = {} if request.method == "POST": site = models.KegbotSite.get() form = MiniSiteSettingsForm(request.POST, instance=site) if form.is_valid(): form.save() messages.success(request, "Settings saved!") ...
TMiguelT/csvschema
csv_schema/__init__.py
Python
mit
103
0
# -*- coding: utf-8 -*- """Module that he
lps in checking the correctnes
s of CSV file structure."""
CalthorpeAnalytics/urbanfootprint
footprint/client/configuration/default/layer_style/default_layer_style.py
Python
gpl-3.0
793
0.001261
# UrbanFootprint v1.5 # Copyright (C) 2017 Calthorpe Analytics # # This file is part of UrbanFootprint version 1.5 # # UrbanFootprint is distributed under the terms of the GNU General # Public License version 3, as published by the Free Software Foundation. This # code is distributed WITHOUT ANY WARRANTY, without impl...
ty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License v3 for more details; see <http://www.gnu.org/licenses/>. from fo
otprint.main.models.presentation.layer_style import LayerStyle __author__ = 'calthorpe_analytics' class DefaultLayerStyle(LayerStyle): """ The default LayerStyle for newly created Layers that don't match any more specific LayerStyle subclasses """ model_class = object
GoogleCloudPlatform/repo-automation-playground
xunit-autolabeler-v2/ast_parser/core/__init__.py
Python
apache-2.0
783
0
# Copyright 2020 Google LLC. # # Licensed under the Apache License, Ver
sion 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 # 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. # Add the parent 'ast...
guanxin0206/dice_crawler
dice_spider_2/spider/html_outputer.py
Python
bsd-2-clause
1,497
0.008059
#!/usr/bin/env python -t # -*- coding: UTF-8 -*- import codecs import urllib class HtmlOutputer(object): def __init__(self): self.datas = [] def collect_data(self,data): if data is None: return self.datas.append(data) de
f output_html(self): fout = open('output.html','w') """ for data in self.datas: print data['url'].encode("utf-8"), type(data['url'].encode("utf-8")) print urllib.unquote(data['url'].encode("utf-8")) ,type(urllib.unquote(data['url'].encode("utf-8"))) #print ur...
e(data['summary']) """ fout.write("<html>") fout.write("<head>") fout.write("<meta charset='UTF-8'>") fout.write("</head>") fout.write("<body>") fout.write("<table>") # 默认编码ascii for data in self.datas: fout.w...
jessamynsmith/twitterbot
tests/messages/test_base.py
Python
mit
989
0.003033
import unittest from twitter_bot import messages class TestBaseMessageProvider(unittest.TestCase): def test_extract_hashtags_empty_mention(self): provider = messages.BaseMessageProvider() hashtags = provider._extract_hashtags({}) self.assertEqual([], hashtags) def test_extract_has...
provider.create({}, 20) self.fail("Should not be able to call create() on abstract parent class")
except NotImplementedError as e: error = 'Child class must implement create(self, mention, max_message_length)' self.assertEqual(error, '{0}'.format(e))
gngrwzrd/gity
python/add.py
Python
gpl-3.0
1,341
0.028337
# Copyright Aaron Smith 2009 # # This file is part of Gity. # # Gity 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. # # Gity is dis...
mport * try: import sys,re,os,subprocess except Exception, e: sys.stderr.write(str(e)) exit(84) command="" try: from _argv import * if not checkfiles(options): raise Exception("Gity Error: The add command requires files! They weren't set.") gitcommand="add" command="%s %s %s %s"%(options.git,gitcommand,"--ignore...
s.files)) rcode,stout,sterr=run_command(command) rcode_for_git_exit(rcode,sterr) exit(0) except Exception, e: sys.stderr.write("The add command threw this error: " + str(e)) sys.stderr.write("\ncommand: %s\n" % command) log_gity_version(options.gityversion) log_gitv(options.git) exit(84)
dichen001/Go4Jobs
JackChen/Google/484. Find Permutation.py
Python
gpl-3.0
1,750
0.003429
""" By now, you are given a secret signature consisting of character 'D' and 'I'. 'D' represents a decreasing relationship between two numbers, 'I' represents an increasing relationship between two numbers. And our secret signature was constructed by a special integer array, which contains uniquely all the different nu...
ignature "I", where the number 1 and 2 construct an increasing relationship. Example 2: Input: "DI" Output: [2,1,3] Explanation: Both [2,1,3] and [3,1,2] can construct the secret signature "DI", but since we want to find the one with the smallest lexicographical permutation, you need to output [2,1,3] Note: The input ...
n(object): def findPermutation(self, s): """ :type s: str :rtype: List[int] """ i, n = 0, len(s) ans = range(1, n + 2) while i < n: j = i while j < n and s[j] == "D": j += 1 ans[i:j+1] = ans[i:j+1][::-1] ...
7digital/troposphere
examples/Lambda.py
Python
bsd-2-clause
5,154
0
from troposphere.constants import NUMBER from troposphere import FindInMap, GetAtt, Join, Output from troposphere import Parameter, Ref, Template from troposphere.awslambda import Function, Code, MEMORY_VALUES from troposphere.cloudformation import CustomResource from troposphere.ec2 import Instance from troposphere.ec...
iam import Role, Policy t = Template() t.add_version("2010-09-09") ExistingVPC = t.add_parameter(Parameter( "ExistingVPC", Type="AWS::EC2::VPC::Id", Description=( "The VPC ID that includes the security groups in the "
"ExistingSecurityGroups parameter." ), )) InstanceType = t.add_parameter(Parameter( "InstanceType", Default="t2.micro", Type="String", AllowedValues=["t2.micro", "m1.small"], )) ExistingSecurityGroups = t.add_parameter(Parameter( "ExistingSecurityGroups", Type="List<AWS::EC2::Security...
neilhan/tensorflow
tensorflow/contrib/factorization/python/ops/gmm.py
Python
apache-2.0
7,521
0.002792
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
terator. batch_size: s
ize to use for batching up x for querying the model. Returns: Array with same number of rows as x, containing cluster ids. """ return np.array([ prediction[GMM.ASSIGNMENTS] for prediction in super(GMM, self).predict(x=x, batch_size=batch_size, as_iterable=True)]) def score(self, x,...
aikramer2/spaCy
spacy/tests/lang/en/test_prefix_suffix_infix.py
Python
mit
4,124
0.000242
# coding: utf-8 """Test that tokenizer prefixes, suffixes and infixes are handled correctly.""" from __future__ import unicode_literals import pytest @pytest.mark.parametrize('text', ["(can)"]) def test_tokenizer_splits_no_special(en_tokenizer, text): tokens = en_tokenizer(text) assert len(tokens) == 3 @...
_uneven_wrap_interact(en_tokenizer, text): tokens = en_tokenizer(text) assert len(tokens) == 4 @pytest.mark.parametrize('text', ["best-known"]) def test_tokenizer_splits_hyphens(en_tokenizer, text): tokens = en_tokenizer(text) assert len(tokens) == 3 @pytest.mar
k.parametrize('text', ["0.1-13.5", "0.0-0.1", "103.27-300"]) def test_tokenizer_splits_numeric_range(en_tokenizer, text): tokens = en_tokenizer(text) assert len(tokens) == 3 @pytest.mark.parametrize('text', ["best.Known", "Hello.World"]) def test_tokenizer_splits_period_infix(en_tokenizer, text): tokens =...
SciTools/iris
lib/iris/__init__.py
Python
lgpl-3.0
14,621
0
# Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """ A package for handling multi-dimensional data and associated metadata. .. note :: The Iris documentation has further ...
applied to th
e Future object. On exit from the `with` statement, the previous state is restored. For example:: with iris.FUTURE.context(example_future_flag=False): # ... code that expects some past behaviour .. note:: iris.FUTURE.example_future_flag does not exist a...
endlessm/chromium-browser
third_party/depot_tools/recipes/recipe_modules/git/examples/full.py
Python
bsd-3-clause
5,942
0.009424
# Copyright 2013 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. DEPS = [ 'recipe_engine/buildbucket', 'recipe_engine/context', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', 'recip...
h_tags to fetch all tags from the remote api.git.fetch_tags(api.properties.get('remote_name')) # If you need to run more arbitrary git commands,
you can use api.git itself, # which behaves like api.step(), but automatically sets the name of the step. with api.context(cwd=api.path['checkout']): api.git('status') api.git('status', name='git status can_fail_build', can_fail_build=True) api.git('status', name='git status cannot_fail_build', ...
CYBAI/servo
python/mach/setup.py
Python
mpl-2.0
1,204
0
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import absolute_import try: from setuptoo
ls import setup except ImportError: from distutils.core import setup VERSION = '1.0.0' README = open('README.rst').read() setup( name='mach', description='Generic command line command dispatching framework.', long_description=README, license='MPL 2.0', author='Gregory
Szorc', author_email='gregory.szorc@gmail.com', url='https://developer.mozilla.org/en-US/docs/Developer_Guide/mach', packages=['mach', 'mach.mixin'], version=VERSION, classifiers=[ 'Environment :: Console', 'Development Status :: 5 - Production/Stable', 'License :: OSI Approv...
rodriguesrl/reddit-clone-udemy
accounts/urls.py
Python
mit
366
0.002732
from django.contrib.auth import views as auth_views from django.conf.urls import url from . import views app_name = "accounts" urlpatterns = [ url(r'^login/$', auth_views.login, {'template_name': 'accounts/signin.html'}, name='signin'), url(r'^signup/', views.SignUpView.as_view(),
name="signup"), url(r'^logout/', auth_views.logout, name="logout"), ]