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
ReactiveX/RxPY
docs/conf.py
Python
mit
5,837
0
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/stable/config # -- Path setup ------------------------------------------------------------...
fault.css" will overwrite the builtin "default.css". html_static_
path = ["_static"] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelin...
cedriclaunay/gaffer
python/GafferImageTest/FilterTest.py
Python
bsd-3-clause
2,759
0.022472
########################################################################## # # Copyright (c) 2013, Image Engine Design 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: # # * Redistrib...
SUCH DAMAGE. # ########################################################################## import unittest import IECore import Gaffer import GafferImage import os class FilterTest( unittest.TestCase ) : def testDefaultFilter( self ) : filters = GafferImage.Filter.filters() default = GafferImage.Filter.default...
def testFilterList( self ) : filters = GafferImage.Filter.filters() self.assertTrue( len(filters) == 9 ) self.assertTrue( "Box" in filters ) self.assertTrue( "BSpline" in filters ) self.assertTrue( "Bilinear" in filters ) self.assertTrue( "Hermite" in filters ) self.assertTrue( "Mitchell" in filters ) s...
cineuse/CNCGToolKit
cgtkLibs/cgtk_py/implant_method.py
Python
mit
238
0
# cod
ing=utf8 from types import MethodType def implant_method(obj, func, func_name): base_class = obj.__class__ event = MethodType(func, obj, base_class) setattr(obj, func_name, event) if __name__ == "__main__":
pass
uroslates/django-allauth
allauth/socialaccount/providers/oauth2/urls.py
Python
mit
483
0.00207
from django.conf.urls.defaults import patterns, url, include def default_urlpatterns(provider): urlpatterns = patterns(provider.package + '.views', url('^login/$', 'oauth2_login', name=provider.id + "_login"),
url('^login/done/$', 'oauth2_complete', name=provider.id + "_complete")) return patterns
('', url('^' + provider.id + '/', include(urlpatterns)))
fmenabe/python-unix
unix/linux/modules.py
Python
mit
862
0
class Modules(object): def __init__(self, host): self._host = host def list(self): status, stdout, stderr = self._host.execute('lsmod') if not status: raise LinuxError(stderr) return [line.split()[0] for line in stdout.splitlines()[1:]] def tree(self): p...
alue) for param, value in params.items()), force=force) def unload(self, module, force=False): return self._host.execute('modprobe', module, rem
ove=True, force=force) def options(self, module): pass
tomvand/paparazzi-gazebo
sw/supervision/python/processes.py
Python
gpl-2.0
8,578
0
# Paparazzi center utilities # # Copyright (C) 2016 ENAC, Florian BITARD (intern student) # # This file is part of paparazzi. # # paparazzi 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 ...
########################################################################### # [C
onstants] LOGGER = logging.getLogger("[PROCESSES]") AC_MAKEFILE_NAME = "Makefile.ac" CONF_FLAG_NAME = "AIRCRAFT" DEVICE_FLAG_NAME = "FLASH_MODE" DEFAULT_EXIT_CODE = 2 INTERRUPTED_EXIT_CODE = -1 SUCCESS_EXIT_CODE = 0 CLEAN = "clean" BUILD = "build" UPLOAD = "upload" PROGRAM = "program" TOOL = "tool" CLEAN_TARGET_KE...
gordonb3/domoticz
plugins/examples/HTTP.py
Python
gpl-3.0
8,304
0.00855
# Google Home page example # # Author: Dnpwwo, 2017 - 2018 # # Demonstrates HTTP/HTTPS connectivity. # After connection it performs a GET on www.google.com and receives a 302 (Page Moved) response # It then does a subsequent GET on the Location specified in the 302 response and receives a 200 response. # """ <pl...
"true" /> </options> </param> <param field="Mode6" label="Debug" width="150px"> <options> <option label="None" value="0" default="true" /> <option label="Python Only" value="2"/> <option label="Basic Debugging" value="62"/> ...
<option label="Connections+Python" value="18"/> <option label="Connections+Queue" value="144"/> <option label="All" value="-1"/> </options> </param> </params> </plugin> """ import Domoticz class BasePlugin: httpConn = None runAgain = 6 disconnectCoun...
marvinglenn/asnn-mda
asnn_reduce_spamrating.py
Python
gpl-2.0
7,003
0.016422
#!/usr/bin/env python ''' This file is part of the ASNN eMail Suite. ASNN-MDA is free software: you can redistribute it and/or modify it under the terms of the version 2 GNU General Public License as published by the Free Software Foundation. ASNN-MDA is distributed in the hope that it will be us...
: logfile.write(time.strftime('%Y-%m
-%d %H:%M:%S', time.gmtime()) + \ ' PID ' + str(os.getpid()) + ': IP addresses: ') if args.testrun: logfile.write('test run: ') if perreduct: logfile.write('percentage reduction of ' + str(perreduct * 100) + '%\n') if linreduct: logfile.write('linear reduction of ' + str...
Dawny33/Code
Hackerrank/Back2School/stockmax.py
Python
gpl-3.0
299
0.010033
T = int(input
()) for _ in range(T): T1 = int(input()) s = map(int, raw_input().split()) count = 0 if T1==len(s): for i in range(len(s)-1): if s[i+1]>s[i]: count = s[i]-s[i+1] if s[i+1]<=s[i]: count = 0 print count
Darthone/bug-free-octo-parakeet
technical-analysis/oneDayOHLC/sma_ema_vol_ohlc_rsi.py
Python
mit
6,893
0.025098
#!/usr/bin/env python import matplotlib # matplotlib.use('Agg') import time import datetime import numpy as np import matplotlib.pyplot as mplot import matplotlib.ticker as mticker import matplotlib.dates as mdates from matplotlib.finance import candlestick_ochl # custom matplotlib parameters matplotlib.rcParams.update...
'#386d13' negCol = '#8f2020' c = mplot.subplot2grid((6,4), (0,0), sharex=a, rowspan=1, colspan=4) rsi = rsiFunction(closePrice) c.plot(date[-SP:], rsi[-SP:], rsiCol, linewidth=1.5) c.axhline(70, color=negCol) c.axhline(30, color=posCol) c.fill_betwe
en(date[-SP:], rsi[-SP:], 70, where=(rsi[-SP:]>=70), facecolor=negCol, edgecolor=negCol) c.fill_between(date[-SP:], rsi[-SP:], 30, where=(rsi[-SP:]<=30), facecolor=posCol, edgecolor=posCol) # 70 --> red, overbought # 30 --> green, oversold c.text(0.015, 0.95, 'RSI (14)', va='top', transform=c.transAxes) c.tic...
noironetworks/group-based-policy
gbpservice/neutron/extensions/apic_reuse_bd.py
Python
apache-2.0
1,646
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 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. from neutron_lib.api import extensions from gbpservice._i18n import _ from gbpservice.n...
SgtFlame/pyzen-fabric
src/zen/fabric/batch_service_client.py
Python
mit
200
0.01
from zen.fabric.se
rvice_client import ServiceClient class BatchServiceClient
(ServiceClient): ''' Batch Service Client Service Client for batch / head-less processes ''' pass
teeheee/RobocupSoccerSimulator
debugger.py
Python
gpl-3.0
4,848
0.01382
import pygame from gameconfig import gc import numpy as np # This is an optional visualisation of the sensor values of an specific robot. # It can be disabled via the config.yml Gui->Debugger->False class Debugger: def __init__(self, display, robots): self._display = display self._robots = robot...
[int(topleft[0]+block["y"]),int(topleft[1]+block["x"])] if block["signature"] == 1: pygame.draw.circle(self._display, RED, point , int(10 * self.ppcm)) elif block["signature"] == 2: pygame.draw.rect(self._display, BLACK, [poi
nt[0]-5,point[1]-5,10,10]) elif block["signature"] == 3: pygame.draw.rect(self._display, BLACK,[point[0]-5,point[1]-5,10,10]) return # ROBOT pos = int((self.field_height+self.field_width/2) * self.ppcm), \ int(self.field_width/2* self.ppcm)...
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/google/appengine/api/mail_service_pb.py
Python
bsd-3-clause
25,492
0.020987
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
ef TryMerge(self, d): while d.avail() > 0: tt = d.getVarInt32() if tt == 10: self.set_filename(d.getPrefixedString()) continue if tt == 18: self.set_data(d.getPrefixedString()) continue if tt == 26: self.set_contentid(d.getPrefixedString()) con...
ProtocolBufferDecodeError d.skipData(tt) def __str__(self, prefix="", printElemNumber=0): res="" if self.has_filename_: res+=prefix+("FileName: %s\n" % self.DebugFormatString(self.filename_)) if self.has_data_: res+=prefix+("Data: %s\n" % self.DebugFormatString(self.data_)) if self.has_content...
Ranjandas/firewallmanager
clusters/views.py
Python
gpl-3.0
223
0.008969
from django.shortcuts import render # Create y
our views here. from django.http import HttpResponse from django
.views.generic import ListView, DetailView, CreateView class ClusterListView(ListView): model = Cluster
artsy/docker-images
redis-migrate/migrate.py
Python
mit
3,144
0.003499
#!/usr/bin/env python import os import argparse from urlparse import urlparse import redis from termcolor import cprint DEBUG = os.environ.get("DEBUG") DRY_RUN = os.environ.get("DRY_RUN") CLEAN_UP = os.environ.get("CLEAN_UP") if os.environ.get("REPLACE_DST_KEYS"): REPLACE_DST_KEYS = True else: REPLACE_DST_KE...
except (redis.exceptions.ResponseError, redis.exceptions.DataError): cprint("! Failed to restore key: %s"
% key, 'red') errors += 1 continue # Don't delete the key in src if it failed to restore - move on to the next iteration if CLEAN_UP: if DEBUG: cprint("Deleting source key: %s" % key, output_color) src.delete(key) if no...
ptphp/PyLib
src/dev/case/timethread.py
Python
apache-2.0
2,356
0.014856
# -*- coding:utf-8-*- from PyQt4.QtGui import * from PyQt4.QtCore import * from time import * import sys class Windows(QDialog): def __init__(self, parent=None): super(Windows, self).__init__(parent) self.startButton = QPushButton("Start") self.stopButton = QPushButton("Stop") ...
QFrame.Plain) topLayout = QHBoxLayout() topLayout.addWidget(self.startButton) topLayout.addWidget(self.stopButton) layout = QVBoxLayout() layout.addLayout(topLayout) layout.addWidget(self.statusLable) self.timer = Timer()
self.connect(self.startButton, SIGNAL("clicked()") , self.start) self.connect(self.stopButton, SIGNAL("clicked()") , self.stop) self.connect(self.timer, SIGNAL("updateTime()") , self.updateTime) self.setLayout(layout) ...
ar4s/django
tests/forms_tests/widget_tests/test_timeinput.py
Python
bsd-3-clause
1,641
0.002438
from datetime import time from django.forms import TimeInput from django.utils import translation from .base import WidgetTest class TimeInputTest(WidgetTest): widget = TimeInput() def test_render_none(self): self.check_html(self.widget, 'time', None, html='<input type="text" name="time">') de...
"time" value="12:51:00">' )) def test_string(self): """Initializing from a string value.""" self.check_html(self.widget, 'time', '13:12:11', html=( '<input type="text" name="time" value="13:12:11">' )) def test_format(self): """ Use 'format' to chang...
t, 'time', t, html='<input type="time" name="time" value="12:51">') @translation.override('de-at') def test_l10n(self): t = time(12, 51, 34, 482548) self.check_html(self.widget, 'time', t, html='<input type="text" name="time" value="12:51:34">')
shashank-sharma/mythical-learning
scrapper/apps.py
Python
mit
91
0
from django.apps import AppConfig
class ScrapperConfig(AppConfig): name = 'scrapper'
jasonwee/asus-rt-n14uhp-mrtg
src/lesson_runtime_features/os_strerror.py
Python
apache-2.0
208
0
import errno import os for num in [errno.ENOENT, errno.EINTR, errno.EBUSY]: nam
e = errno.errorcode[num] print('[{num:>2}] {name:<6}: {msg}'.format( name=name, num=num,
msg=os.strerror(num)))
jeremiah-c-leary/vhdl-style-guide
vsg/tests/process/test_rule_031.py
Python
gpl-3.0
1,200
0.004167
import os import unittest from vsg.rules import process from vsg import vhdlFile from vsg.tests import utils sTestDir = os.path.dirname(__file__) lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_031_test_input.vhd')) lExpected = [] lExpected.append('') utils.read_file(os.path.join(sTestDir,
'rule_031_test_input.fixed.vhd'), lExpected) class test_process_rule(unittest.TestCase): def setUp(self): self.oFile = vhdlFile.vhdlFile(lFile) self.assertIsNone(eError) def test_rule_031(self): oRule = process.rule_03
1() self.assertTrue(oRule) self.assertEqual(oRule.name, 'process') self.assertEqual(oRule.identifier, '031') lExpected = [11, 12, 13, 14, 32, 34, 35, 37, 38, 65, 88, 103, 104, 118] oRule.analyze(self.oFile) self.assertEqual(lExpected, utils.extract_violation_lines_from_...
taigaio/taiga-back
tests/integration/test_userstories.py
Python
agpl-3.0
71,594
0.003534
# -*- coding: utf-8 -*- # Copyright (C) 2014-present Taiga Agile LLC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later ver...
0 | user2 | None | None | tag3 | None | | # | 4 | status0 | user1 | user1 | None | tag1 tag2 tag3 | epic0 | None | # | 5 | status2 | user3 | user1 | None | tag3 | None | | # ...
| status0 | user1 | user2 | None | tag3 | None | | # | 8 | status3 | user3 | user2 | None | tag1 | epic2 | None | # | 9 | status1 | user2 | user3 | user1 | tag0 | None | ...
balazssimon/ml-playground
udemy/lazyprogrammer/ab-testing-python/chisquare_exercise.py
Python
apache-2.0
448
0
import numpy as np import pandas as pd from scipy import stats data = pd.read_csv("advertisement_clicks.csv") X1 = data[data['advertisement_id'] == 'A'] X2 = data[data['advertisement_id'] == 'B'] A0 = X1[X1['action'] == 0].shape[0]
A1 = X1[X1['action'] == 1].shape[0] B0 = X2[X2['action'] == 0].shape[0] B1 = X2[X2['action'] == 1].shape[0] T = [[A0, A1], [B0, B1]] chi2, p, dof, ex = stats.chi2_contingenc
y(T, correction=False)
ChuanleiGuo/AlgorithmsPlayground
LeetCodeSolutions/python/51_N-Queens.py
Python
mit
1,340
0.000746
class Solution(object): def solveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ def search(cur): if cur == n: add_answer() else: f
or i in range(n): ok = True rows[cur] = i for j in range(cur): if not is_valied(cur, j): ok = False break if ok: search(cur + 1) ...
pre_row + rows[pre_row] == cur_row + rows[cur_row]: return False else: return True def add_answer(): ans = [] for num in rows: res_str = "" for i in range(n): if i == num: ...
chirilo/remo
remo/dashboard/tests/test_forms.py
Python
bsd-3-clause
2,108
0
from django.contrib.auth.models import User from django.core import mail from django.test.client import RequestFactory from mock import ANY, patch from nose.tools import eq_, ok_ from test_utils import TestCase from remo.dashboard.forms import EmailRepsForm from remo.profiles.tests import FunctionalAreaFactory, UserF...
sFormsTest(TestCase): def setUp(self): self.functional_area = FunctionalAreaFactory.create() def test_form_tampered_functional_area(self): """Test form with tampered data in functional area field.""" data = {'subject': 'Test email subject', 'body': None, ...
ok_(not form.is_valid()) eq_(len(form.errors['functional_area']), 1) @patch('remo.dashboard.forms.messages.success') def test_send_mail(self, fake_messages): """Test EmailRepsForm email sending functionality.""" data = {'subject': 'Test email subject', 'body': 'Test ...
mwleeds/android-malware-analysis
parse_ssdeep.py
Python
gpl-3.0
3,067
0.006195
#!/usr/bin/python3 """ This script reads the CSV output from ssdeep in the malicious_apk and benign_apk folders and writes similarity scores for each sample and classifications to a JSON file for later analysis The output data format is as follows: {"features": ["similarity_limit_0", "similarity_limit_0.2", ...], "a...
y_limit_0.6', 'similarity_limit_0.8', 'similarity_limit_1.0'] root_dir = os.getcwd() for i, directory in enumerate(['benign_apk', 'malicious_apk']): os.chdir(directory) with open(directory.split('_')[0] + '_apk_ssdeep.csv') as hashes: for j, line in enumerate(hashes): ...
pp_malicious_map[app_name] = [1,0] if i else [0,1] all_hashes['malicious' if i else 'benign'].append((app_name, b64hash)) os.chdir(root_dir) all_apps = {} # mapping from each app to its similarity score and classification num_zero = {} num_each = {} for category in all_hashes: ...
kyleconroy/quivr
flickr.py
Python
mit
645
0.003101
import os import hashlib import requests import json FLICKR_BASE = "http://api.flickr.com/services/rest/" def api(method, **kwargs): kwargs.update({ "method": "flickr.{}".format(method), "format": "json",
"nojsoncallback": "1", "api_key": os.environ["FLICKR_KEY"], "auth_token": os.environ["FLICKR_AUTH_TOKEN"],
}) # Signature validation sig = ''.join([str(u[0]) + str(u[1]) for u in sorted(kwargs.items())]) kwargs["api_sig"] = hashlib.md5(os.environ["FLICKR_SECRET"] + sig).hexdigest() resp = requests.post(FLICKR_BASE, params=kwargs) return json.loads(resp.content)
bvernoux/micropython
tools/mpremote/mpremote/main.py
Python
mit
15,680
0.00102
""" MicroPython Remote - Interaction and automation tool for MicroPython MIT license; Copyright (c) 2019-2021 Damien P. George This program provides a set of utilities to interact with and automate a MicroPython device over a serial connection. Commands supported are: mpremote -- auto-det...
) else: # Optional argument with a default. value = exp_arg[1] pre.append(f"{exp_arg_name}={value}") args[0:0] = exp_sub last_arg_idx = len(exp_sub) if last_arg_idx < len(args) and "=" in args[last_arg_idx]: # Extra unknow...
Insert expansion with optional setting of arguments. if pre: args[0:0] = ["exec", ";".join(pre)] def do_connect(args): dev = args.pop(0) try: if dev == "list": # List attached devices. for p in sorted(serial.tools.list_ports.comports()): print( ...
tarikgwa/nfd
newfies/frontend/forms.py
Python
mpl-2.0
2,873
0.001044
# # Newfies-Dialer License # http://www.newfies-dialer.org # # 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/. # # Copyright (C) 2011-2014 Star2Billing S.L. # # The primar...
t('submit', 'Login'), HTML('<a class="btn btn-warning" href="/password_re
set/">%s?</a>' % _('Forgot password')), ), ) class DashboardForm(forms.Form): """Dashboard Form""" campaign = forms.ChoiceField(label=_('campaign'), required=False) search_type = forms.ChoiceField(label=_('type'), required=False, choices=list(SEARCH_TYPE), ...
TangXT/GreatCatMOOC
common/lib/xmodule/xmodule/modulestore/split_mongo/caching_descriptor_system.py
Python
agpl-3.0
6,524
0.003679
import sys import logging from xmodule.mako_module import MakoDescriptorSystem from xmodule.x_module import XModuleDescriptor from xmodule.modulestore.locator import BlockUsageLocator, LocalId from xmodule.error_module import ErrorDescriptor from xmodule.errortracker import exc_info_to_str from xblock.runtime import Db...
lock_id = LocalId() block_locator = BlockUsageLocator( version_guid=course_entry_override['structure']['_id'], block_id=block_id, package_id=course_entry_override.get('package_i
d'), branch=course_entry_override.get('branch') ) kvs = SplitMongoKVS( definition, json_data.get('fields', {}), json_data.get('_inherited_settings'), ) field_data = DbModel(kvs) try: module = self.construct_xblock_from...
poldracklab/niworkflows
niworkflows/tests/test_registration.py
Python
bsd-3-clause
7,017
0.001995
# -*- coding: utf-8 -*- """ Registration tests """ import os from shutil import copy import pytest from tempfile import TemporaryDirectory from nipype.pipeline import engine as pe from ..interfaces.reportlets.registration import ( FLIRTRPT, SpatialNormalizationRPT, ANTSRegistrationRPT, BBRegisterRPT, ...
moving_imag
e=moving, fixed_image=reference, from_file=pkgr.resource_filename( "niworkflows.data", "t1w-mni_registration_testing_000.json" ), ) _smoke_test_report(ants_rpt, "testANTSRegistrationRPT.svg")
eddiedb6/pdb
PDBConst.py
Python
mit
245
0
# Schema DB = "d
b" Name = "name" Tables = "tables" Table = "table" Columns = "columns" Column = "column" Attributes = "attributes" Initials = "initials" Initial = "initial" InitialValue = "initialvalu
e" Value = "value" PrimaryKey = "primarykey"
squirrelo/qiita
qiita_db/investigation.py
Python
bsd-3-clause
1,984
0
from __future__ import division """ Objects for dealing with Qiita studies This module provides the implementation of the Investigation class. Classes ------- - `Investigation` -- A Qiita investigation class """ # -
---------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # --------------------------------------------
--------------------------------- import qiita_db as qdb REQUIRED_KEYS = {"name", "description", "contact_person"} class Investigation(qdb.base.QiitaStatusObject): """ Study object to access to the Qiita Study information Attributes ---------- name: str name of the investigation des...
Lorquas/subscription-manager
src/subscription_manager/gui/messageWindow.py
Python
gpl-2.0
3,262
0.001839
from __future__ import print_function, division, absolute_import # # Copyright (c) 2010 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITN...
_modal(True) #this seems sp
urious, but without it, a ref to this obj gets "lost" ga_GObject.add_emission_hook(self, 'response', self.noop_hook) self.dialog.connect("response", self._on_response_event) def _on_response_event(self, dialog, response): rc = response in [ga_Gtk.ResponseType.OK, ga_Gtk.ResponseType.YES] ...
WilliamYi96/Machine-Learning
LeetCode/0033.py
Python
apache-2.0
1,334
0.001499
class Solution: def searchRot(self, nums): left = 0 right = len(nums) - 1 while left <= righ
t: mid = (left + right) >> 1 if mid == len(nums) - 1: return 0 # print(left, right, mid) if nums[mid] > nums[mid+1]
: return mid+1 elif nums[mid] < nums[mid+1]: if nums[left] < nums[mid]: left = mid + 1 elif nums[left] > nums[mid]: right = mid - 1 elif nums[left] == nums[mid]: left = mid + 1 ...
KBNode/CertNode
certnode/constants.py
Python
mit
273
0
API_NEW_REG = 'new-reg' API_NEW_AUTHZ = 'ne
w-authz' API_NEW_CERT = 'new-cert' LOCATION = 'Location' TOS = 'terms-of-service' REPLAY_NONCE = 'Replay-Nonce' CHALLENGE_METHO
D_HTTP_01 = 'http-01' CHALLENGE_METHOD_DNS_01 = 'dns-01' CHALLENGE_METHOD_TLS_SNI_01 = 'tls-sni-01'
nsanthony/super-fortnight
wwk/py/people/people_class.py
Python
apache-2.0
583
0.012007
#! /home/nsanthony/miniconda3/bin/python import inventory.inventory_class as inv import weapons.weapon_class as wp class people: """This is the people class with attributes:""" def name(): n = '' return n def healt
h(): hp = 0 return hp def descript(): d = 'Description of the person or creature' return d def equiped(): e = inv.inventory() e.weapon = wp.weapon() e.armor = 0 return e def bag(): b = {} return b def hostile(): h = ...
return h
azavea/blend
docs/conf.py
Python
mit
7,745
0.007489
# -*- coding: utf-8 -*- # # Blend documentation build configuration file, created by # sphinx-quickstart on Fri Feb 24 14:11:43 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All c...
documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags.
release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a s...
mazvv/travelcrm
travelcrm/forms/dismissals.py
Python
gpl-3.0
2,514
0
# -*-coding: utf-8 -*- import colander from . import ( SelectInteger, ResourceSchema, BaseForm, BaseSearchForm, BaseAssignForm, Date ) from ..resources.dismissals import DismissalsResource from ..models.dismissal import Dismissal from ..models.employee import Employee from ..models.note import...
eate_resource( get_auth_employee
(self.request) ) ) else: dismissal.resource.notes = [] dismissal.resource.tasks = [] dismissal.date = self._controls.get('date') dismissal.employee_id = self._controls.get('employee_id') for id in self._controls.get('note_id'): ...
ankush-me/SynthText
text_utils.py
Python
apache-2.0
23,512
0.01008
from __future__ import division import numpy as np import matplotlib.pyplot as plt import scipy.io as sio import os.path as osp import random, os import cv2 import cPickle as cp import scipy.si
gnal as ssig import scipy.stats as sstat import pygame, pygame.locals from pygame import freetype #import Image from PIL import Image import math from common import * def sample_weighted(p_dict): ps = p_dict.keys() return p_dict[np.random.choice(ps,p=ps)] def move_bb(bbs, t): """ Translate the boundi...
y """ return bbs + t[:,None,None] def crop_safe(arr, rect, bbs=[], pad=0): """ ARR : arr to crop RECT: (x,y,w,h) : area to crop to BBS : nx4 xywh format bounding-boxes PAD : percentage to pad Does safe cropping. Returns the cropped rectangle and the adjusted bounding-boxes """ ...
chewse/djangorestframework-dynamic-fields
test_dynamicfields.py
Python
mit
218
0.004587
# -*- coding: utf-8 -*- import uni
ttest import mock class DynamicFieldsMixinTestCase(unittest.TestCase): """Test functionality of the DynamicFieldsMixin class."""
def test_restrict_dynamic_fields(self):
leewujung/ooi_sonar
during_incubator/nmf_seq_20170228.py
Python
apache-2.0
6,547
0.017718
#!/usr/local/bin/python ''' NMF decomposition sequentially over multiple time chunks ''' import os, sys, glob, re import datetime import numpy as np from calendar import monthrange import h5py sys.path.insert(0,'/home/wu-jung/code_git/mi-instrument/') from concat_raw import get_num_days_pings, get_data_from_h5 from ...
r hr in every_ping] all
_idx = np.array(all_idx) # to allow numpy operation # Extract timing and Sv data notnanidx = np.int_(all_idx[~np.isnan(all_idx)]) data_times = np.empty(all_idx.shape) # initialize empty array data_times[~np.isnan(all_idx)] = f['data_time...
numerodix/killdupes
setup.py
Python
gpl-2.0
1,048
0
from setuptools import find_packages from setuptools import setup import killdupes setup( name='killdupes', version=killdupes.__version__, description='Kill duplicate files, finding partial files as well', author='Martin Matusiak', author_email='numerodix@gmail.com', url='https://github.com/n...
License :: OSI Approved :: GNU General Public License v2 (GPLv2)',
'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :...
Reagankm/KnockKnock
venv/lib/python3.4/site-packages/matplotlib/backends/windowing.py
Python
gpl-2.0
790
0.002532
""" MS Windows-specific helper for the TkAgg backend. With rcParams['tk.window_focus'] default of False, it is effectively disabled. It uses a tiny C++ extension module to access MS Win functions. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import ...
def SetForegroundWindow(hwnd): pass class FocusManager: def __init__(self): self._shellWindow = GetForegroundWindow() def __del__(self): SetForegroundWindow(self._shell
Window)
nephila/djangocms_twitter
djangocms_twitter/south_migrations/0004_rename_tables.py
Python
bsd-3-clause
4,301
0.007673
# -*- coding: utf-8 -*- from distutils.version import LooseVersion import cms 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): if LooseVersion(cms.__ver...
nged_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'depth': ('django.db.models.fields.PositiveIntegerField', [], {}), u'id': ('django.d...
CharField', [], {'max_length': '15', 'db_index': 'True'}), 'numchild': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}), 'path': ('djan...
janeen666/mi-instrument
mi/dataset/driver/adcps_jln/stc/adcps_jln_stc_recovered_driver.py
Python
bsd-2-clause
1,609
0.002486
#!/usr/local/bin/python2.7 ## # OOIPLACEHOLDER # # Copyright 2014 Raytheon Co. ## import os from mi.core.log import get_logger from mi.dataset.dataset_driver import DataSetDriver from mi.dataset.dataset_parser import DataSetDriverConfigKeys from mi.dataset.parser.adcps_jln_stc import AdcpsJlnStcParser, \ AdcpsJln...
) @version("0.0.5") def parse(unused, source_file_path, particle_data_handler): config = { DataSetDriverConfigKeys.PARTICLE_MODULE: 'mi.dataset.parser.adcps_jln_stc', DataSetDriverConfigKeys.PART
ICLE_CLASS: None, DataSetDriverConfigKeys.PARTICLE_CLASSES_DICT: { AdcpsJlnStcParticleClassKey.METADATA_PARTICLE_CLASS: AdcpsJlnStcMetadataRecoveredDataParticle, AdcpsJlnStcParticleClassKey.INSTRUMENT_PARTICLE_CLASS: AdcpsJlnStcInstrumentRecoveredDataParti...
tuxology/bcc
src/cc/frontends/p4/compiler/ebpfDeparser.py
Python
apache-2.0
6,681
0.000299
# Copyright (c) Barefoot Networks, Inc. # Licensed under the Apache License, Version 2.0 (the "License") from collections import defaultdict, OrderedDict from compilationException import CompilationException from p4_hlir.hlir import parse_call, p4_field, p4_parse_value_set, \ P4_DEFAULT, p4_parse_state, p4_table, ...
ng(hlir): # This function is copi
ed from the P4 behavioral model implementation header_graph = Graph() def walk_rec(hlir, parse_state, prev_hdr_node, tag_stacks_index): assert(isinstance(parse_state, p4_parse_state)) for call in parse_state.call_sequence: call_type = call[0] if call_type == parse_call.e...
rsnakamura/oldape
tests/testunits/testcommands/testifconfig/test_ifconfig_linux.py
Python
apache-2.0
1,971
0.008118
from StringIO import StringIO from mock import MagicMock from apetools.commands import ifconfig from apetools.commons import enumerations from apetools.connections.localconnection import OutputError def assert_equal(expected, actual): assert expected == actual, "Expected: {0} Actual: {1}".format(expected, actual) ...
9899 (392.9 MB) TX bytes:22980409 (22.9 MB)
Interrupt:18 ''' ifconfig_android = """ wlan0: ip 192.168.20.153 mask 255.255.255.0 flags [up broadcast running multicast] """ if __name__ == "__main__": import pudb; pudb.set_trace() testlinux() testandroid()
jefflyn/buddha
src/pci/chapter6/docclass.py
Python
artistic-2.0
5,785
0.038375
from pysqlite2 import dbapi2 as sqlite import re import math def getwords(doc): splitter=re.compile('\\W*') print doc # Split the words by non-alpha characters words=[s.lower() for s in splitter.split(doc) if len(s)>2 and len(s)<20] # Return the unique set of words only return dict([(w,1) for...
tiply all the probabilities together p=1 features=self.getfeatures(item) for f in features: p*=(self.weightedprob(f,cat,self.cprob)) # Take the natural log and multiply by -2 fscore=-2*math.log(p) # Use the inverse chi2 function to get a probability return self.invchi2(fscore,len(fea...
chi / 2.0 sum = term = math.exp(-m) for i in range(1, df//2): term *= m / i sum += term return min(sum, 1.0) def __init__(self,getfeatures): classifier.__init__(self,getfeatures) self.minimums={} def setminimum(self,cat,min): self.minimums[cat]=min def getminimum(self,c...
walteryang47/ovirt-engine
packaging/setup/plugins/ovirt-engine-common/ovirt-engine/db/connection.py
Python
apache-2.0
5,588
0
# # ovirt-engine-setup -- ovirt engine setup # Copyright (C) 2013-2015 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
ons.EngineDBEnv.PORT, None ) self.environment.setdefault( oenginecons.EngineDBEnv.SECURED, None ) self.environment.setdefault( oenginecons.EngineDBEnv.SECURED_HOST_VALIDATION, None ) self.environment.setdefault( ...
None ) self.environment.setdefault( oenginecons.EngineDBEnv.PASSWORD, None ) self.environment.setdefault( oenginecons.EngineDBEnv.DATABASE, None ) self.environment.setdefault( oenginecons.EngineDBEnv.DUMP...
Tan0/ironic
ironic/tests/drivers/ilo/test_inspect.py
Python
apache-2.0
19,077
0
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # 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 applicabl...
esult get_capabilities_mock.return_value = capabilities power_mock.return_value = states.POWER_OFF with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: task.driver.inspect.inspect_hardware(task) self.assertEqual(...
et_power_mock.assert_any_call(task, states.POWER_ON) get_essential_mock.assert_called_once_with(task.node, ilo_object_mock) get_capabilities_mock.assert_called_once_with(task.node, il...
kansanmuisti/datavaalit
web/utils/http.py
Python
agpl-3.0
1,709
0.00117
# -*- coding: utf-8 -*- import os import urllib2 import hashlib from urllib2 import HTTPError class HttpFetcher(object): cache_dir = None def set_cache_dir(self, dir): self.cache_dir = dir def _create_path_for_file(self, fname): dirname = os.path.dirname(fname) if not os.path.exis...
s.unlink(fname) def open_url(self, url, prefix, error_ok=False, return_url=False, force_load=False): final_url = None fname = None if self.cache_dir: fname = self.get_fname(url, prefix) if not fname or not os.access(fname, os.R_OK): opener = urllib2.build_ope...
if error_ok: return None raise s = f.read() final_url = f.geturl() if fname: self._create_path_for_file(fname) outf = open(fname, 'w') outf.write(s) outf.close() ...
littlejo/Libreosteo
libreosteoweb/migrations/0019_auto_20150420_1821.py
Python
gpl-3.0
460
0.002174
# -*- coding: utf-8 -*- from __future__ import unicode_
literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('libreosteoweb', '0018_auto_20150420_1232'), ] operations = [ migrations.AlterField( model_name='regulardoctor', name=
'phone', field=models.CharField(max_length=100, null=True, verbose_name='Phone', blank=True), ), ]
Alexsays/Kindle-Sync
KindleSearchDialog.py
Python
gpl-3.0
3,422
0.002046
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'KindleSearchDialog.ui' # # Created: Thu Apr 3 16:24:23 2014 # by: PyQt4 UI code generator 4.10.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 ex...
tf8("image_label")) self.text_label = QtGui.QLabel(Dialog) self.text_label.setGeometry(QtCore.QRect(11, 270, 261, 41)) font = QtGui.QFont() font.setFamily(_fromUtf8("Futura")) font.setPointSize(24) self.text_label.setFont(font) self.text_label.setAlignment(QtCore....
.QRect(0, 300, 21, 21)) self.pushButton.setText(_fromUtf8("")) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8("images/close-button.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton.setIcon(icon) self.pushButton.setIconSize(QtCore.QSize(21, 21)) sel...
MicrosoftGenomics/FaST-LMM
fastlmm/pyplink/__init__.py
Python
apache-2.0
49
0
from .snpset import * from
.snpreader import *
rwl/PyCIM
CIM14/IEC61970/Protection/SynchrocheckRelay.py
Python
mit
2,666
0.004501
# 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, includi
ng without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRA...
offlinehacker/flumotion
flumotion/component/encoders/vp8/wizard_gtk.py
Python
gpl-2.0
4,507
0.000666
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com). # All rights reserved. # This file may be distributed and/or modified under the terms of # the GNU General Public License version 2 as published by # the ...
to be set by view @type framerate: float """ componentType = 'vp8-encoder' def __init__(self): super(VP8VideoEncoder, self).__init__() self.has_quality = False self.has_bitrate = True self.framerate = 25.0 self.properties.keyframe_delta = 2.0 self.prope...
self.properties.quality = 16 def getProperties(self): properties = super(VP8VideoEncoder, self).getProperties() if self.has_bitrate: del properties.quality properties.bitrate *= 1000 elif self.has_quality: del properties.bitrate else: ...
tomasbelusky/gataca
src/resources/VcfCreator.py
Python
gpl-3.0
2,975
0.011104
#!/usr/bin/python2.7 # -*- encoding: utf-8 -*- __author__ = "Tomáš Beluský" __date__ = "09.03. 2013" import types class VcfCreator: """ Creator of VCF output """ def __init__(self, filename, output): """ Initialize variables """ self.__filename = filename self.__outputName = output s...
""" self.__output.write("##fileformat=VCFv4.1\n") for key, value in self.__headers: # write header self.__output.write("##%s=%s\n" % (key, value)) self.__output.write("##reference=%s\n" % self.__filename) for contig in self.__contigs: # write contigs self.__output.write("##contig=<%s>\n"...
##INFO=<ID=%s,Number=%s,Type=%s,Description=\"%s\">\n" % (iid, number, itype, description)) for aid, description in self.__alts: # write alt self.__output.write("##ALT=<ID=%s,Description=\"%s\">\n" % (aid, description)) self.__output.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n") def writeR...
siddhuwarrier/lockindicator-applet
src/typeutils/Exceptions.py
Python
gpl-3.0
2,038
0.008342
# Copyri
ght (c) 2010 Siddhu Warrier (http://siddhuwarrier.homelinux.org, # siddhuwarrier AT gmail DOT com). # # This file is part of the typeutils package. # The utils package is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Fo...
nse, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a...
dsweet04/rekall
rekall-core/rekall/plugins/linux/check_syscall.py
Python
gpl-2.0
6,461
0.000929
# Rekall Memory Forensics # Copyright (C) 2007-2013 Volatility Foundation # Copyright 2013 Google Inc. All Rights Reserved. # # This file is part of Rekall Memory Forensics. # # Rekall Memory Forensics is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License Version...
_table", table_size yield "sys_call_table", table_size def collect(self): """
This works by walking the system call table and verifies that each is a symbol in the kernel """ for table_name, table_size in self.Find_sys_call_tables(): # The syscall table is simply an array of pointers to functions. table = self.profile.get_constant_object( ...
dz0ny/vaultier
vaultier/libs/version/context.py
Python
bsd-3-clause
1,091
0
class Manager(object): _user = None _enabl
ed = True _user_required = True def set_user_required(self, user_required): self._user_required = user_required def get_user_required(self): return self._user_required def set_user(self, user): self._user = user def get_user(self): if self._user_required and (not ...
ion_context_manager' raise Exception(msg) return self._user def set_enabled(self, enabled): self._enabled = enabled def get_enabled(self): return self._enabled version_context_manager = Manager() class VersionContextAwareApiViewMixin(object): def initialize_request(...
JulyKikuAkita/PythonPrac
cs15211/ValidateStackSequences.py
Python
apache-2.0
2,782
0.001797
__source__ = 'https://leetcode.com/problems/validate-stack-sequences/' # Time: O(N) # Space: O(N) # # Description: Leetcode # 946. Validate Stack Sequences # # Given two sequences pushed and popped with distinct values, # return true if and only if this could have been the result of a sequence of push and pop operatio...
} # use array # 5ms 99.91% class Solution { public boolean validateStackSequences(int[] pushed, int[] popped) { int[] stack = new int[pushed.length]; int inde
x = 0, pIndex = 0; for (int i = 0; i < pushed.length; i++) { stack[index++] = pushed[i]; while (index != 0 && stack[index - 1] == popped[pIndex]) { index--; pIndex++; } } while (index != 0 && stack[index - 1] == popped[pIndex]...
nelsyeung/half-metals-analysis
lib/nmod.py
Python
mit
5,429
0.004237
""" Useful and shared functions """ import os import math import numpy as np from scipy.interpolate import interp1d def chunks(l, size): """ Return same size chunks in a list """ return [l[i:i+size] for i in range(0, len(l), size)] def findLine(filename, s): """ Return first encountered line from a file w...
""" Replace all the matching strings from a piece of text """ for i, j in reps.items(): text = text.replace(str(i), str(j)) return text def ntabulate(matrix): """ Return a nice tabulated string from a matrix """ s = [[str(e) for e in row] for row in matrix] lens = [len(max(col, key=len)) ...
ly formatted string from a float """ return '{val:.{prec}f}'.format(prec=prec, val=val) def nexit(): """ Standard exit program function """ print('Exiting program...') raise SystemExit def seconds2str(s): """ Return a nicely formatted time string from seconds """ seconds = str(int(s % 60)) ...
heromod/migrid
mig/wwwuser/pickle_file_sizes.py
Python
gpl-2.0
1,433
0.000698
#!/usr/bin/python # -*- coding: utf-8 -*- # # --- BEGIN_HEADER --- # # pickle_file_sizes - [insert a few words of module description on this
line] # Copyright (C) 2003-2009 The MiG Project lead by Brian Vinter # # This file is part of MiG. # # MiG is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # MiG is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY o...
hansonrobotics/chatbot
src/chatbot/server/config.py
Python
mit
1,300
0.002308
import os DEFAULT_CHARACTER_PATH = os.path.join( os.path.dirname(os.path.realpath
(__file__)), 'characters') CHARACT
ER_PATH = os.environ.get('HR_CHARACTER_PATH', DEFAULT_CHARACTER_PATH) RESET_SESSION_BY_HELLO = False SESSION_REMOVE_TIMEOUT = 3600 # Timeout seconds for a session to be removed CHATBOT_LOG_DIR = os.environ.get('CHATBOT_LOG_DIR') or os.path.expanduser('~/.hr/chatbot') SERVER_LOG_DIR = os.environ.get('SERVER_LOG_DIR') ...
ioram7/keystone-federado-pgid2013
build/sqlalchemy/test/aaa_profiling/test_memusage.py
Python
apache-2.0
19,051
0.004567
from test.lib.testing import eq_ from sqlalchemy.orm import mapper, relationship, create_session, \ clear_mappers, sessionmaker, class_mapper from sqlalchemy.orm.mapper import _mapper_registry from sqlalchemy.orm.session import _sessions import operator from test.lib import testing, engines from sqlalchemy import M...
import mysql, postgresql, sqlite from sqlalchemy import types eng = engines.testing_engine() for args in ( (types.Integer, ), (types.String, ), (types.PickleType, ), (types.Enum, 'a', 'b', 'c'), (sqlite.DATETIME, ), (postgr...
Interval, ), (postgresql.INTERVAL, ), (mysql.VARCHAR, ), ): @profile_memory def go(): type_ = args[0](*args[1:]) bp = type_._cached_bind_processor(eng.dialect) rp = type_._cached_result_processor(eng.dialect, 0) ...
MitchellChu/torndsession
torndsession/sessionhandler.py
Python
mit
964
0.003112
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright @ 2014 Mitchell Chu from __future__ import (absolute_import, division, print_function, with_statement) import tornado.web import torndsession.session class SessionBaseHandler(tornado.web.RequestHandler, torndsession.session.SessionM...
equest handler which is base on torndsession. Generally, user must persistent session object with manual operation when force_persistence is False. but when the handler is inherit from SessionBaseHandler, in your handler, you just need to add/update/delete session values, SessionBaseHandler will auto save it. ...
pass def on_finish(self): """ Overwrite tornado.web.RequestHandler on_finish. """ self.session.flush() # try to save session
cloudaice/simple-data
github/libs/client.py
Python
mit
3,814
0.001049
#-*-coding: utf-8-*- from tornado import gen from tornado.httpclient import AsyncHTTPClient, HTTPError, HTTPRequest from tornado.options import options from functools import wraps from tornado import escape import tornado.ioloop import base64 import time import datetime import json from math import exp AsyncHTTPClien...
(func.__name__, int(time.time()))) tornado.ioloop.IOLoop.instance().add_timeout( datetime.timedelta(milliseconds=delta), wrap_func) return wrap_func return wrap_loop class TornadoDataRequest(HTTPRequest): def __init__(self, url, **...
self.auth_password = options.password self.user_agent = "Tornado-data" @gen.coroutine def GetPage(url): client = AsyncHTTPClient() request = TornadoDataRequest(url, method='GET') try: response = yield client.fetch(request) except HTTPError, e: response = e raise gen....
HewlettPackard/oneview-ansible
test/test_oneview_sas_logical_interconnect_group_facts.py
Python
apache-2.0
2,046
0.000489
#!/usr/bin/python # -*- coding: utf-8 -*- ### # Copyright (2016-2019) Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # You may not use thi
s 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 KIN...
permissions and # limitations under the License. ### import pytest from hpe_test_utils import OneViewBaseFactsTest from oneview_module_loader import SasLogicalInterconnectGroupFactsModule ERROR_MSG = 'Fake message error' PARAMS_GET_ALL = dict( config='config.json', name=None ) PARAMS_GET_BY_NAME = dict( ...
UQ-UQx/edx-platform_lti
common/test/acceptance/tests/discussion/test_cohorts.py
Python
agpl-3.0
5,771
0.002599
""" Tests related to the cohorting feature. """ from uuid import uuid4 from .helpers import BaseDiscussionMixin from .helpers import CohortTestMixin from ..helpers import UniqueCourseTest from ...pages.lms.auto_auth import AutoAuthPage from ...fixtures.course import (CourseFixture, XBlockFixtureDesc) from ...pages.lm...
age.expand() def refresh_thread_page(self, thread_id): self.browser.refresh() self.show_thread(thread_id) @attr('shard_1') class CohortedInlineDiscussionTest(InlineDiscussionTest, CohortedDiscussionTestMixin): """ Tests for cohorted inline discussions. """ # Actual test method(s) ...
rtedDiscussionTestMixin): """ Tests for non-cohorted inline discussions. """ # Actual test method(s) defined in NonCohortedDiscussionTestMixin. pass
egineering-llc/egat
examples/config_example/test2.py
Python
mit
188
0.015957
from e
gat.testset import UnorderedTestSet class Test2(UnorderedTestSet): def testStep1(self): pass def testStep2(self): pass
def testStep3(self): pass
consbio/seedsource-core
seedsource_core/django/seedsource/tasks/write_tif.py
Python
bsd-3-clause
2,684
0.001863
import zipfile from stat import S_IRUSR, S_IRGRP, S_IWUSR import netCDF4 import numpy as np import os.path import rasterio import tempfile from django.conf import settings from io import BytesIO from django.template.loader import render_to_string from django.utils.translation import activate from ncdjango.geoprocessi...
ite_tif' inputs = [ StringParameter('service_id'), StringParameter('language_code', required=False) ] outputs = [StringParameter('filename')] def execute(self, service_id, language_code=None): if language_code is None: language_code = settings.LANGUAGE_CODE a...
ataset(os.path.join(SERVICE_DATA_ROOT, data_path), 'r') as nc: data = nc.variables[var.name][:].astype('uint8') height, width = data.shape ex = var.full_extent x_step = (ex.xmax - ex.xmin) / width y_step = (ex.ymax - ex.ymin) / height transform = Affine.from_gdal(ex....
matusvalo/python-easyldap
easyldap/tools.py
Python
bsd-3-clause
2,067
0.002903
from .libldap.structures import LDAPMod def is_iterable(obj): from collections import Iterable return not (isinstance(obj, str) or isinstance(obj, bytes)) and isinstance(obj, Iterable) def is_ascii(s): if isinstance(s, bytes): return all(c < 128 for c in s) else: return all(ord(c) < ...
if isinstance(s, str): return s.encode('utf8') elif isinstance(s, bytes): return bytes(s) else: try: return bytes(s) except: pass try: return str(s).encode('utf8') excep
t: pass raise ValueError('Cannot encode to bytes') def build_binary_ldapmod(battr_name, op, vals): if is_iterable(vals): mod = LDAPMod.create_binary(op | LDAPMod.LDAP_MOD_BVALUES, ldap_encode(battr_name), values=ma...
ducksboard/libsaas
doc/conf.py
Python
mit
8,086
0.007049
# -*- coding: utf-8 -*- # # libsaas documentation build configuration file, created by # sphinx-quickstart on Sun May 20 14:45:58 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All...
rcel
ink = False # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link>...
matham/kivy
kivy/tests/pyinstaller/simple_widget/project/widget.py
Python
mit
253
0.003953
from kivy.uix.widget import Widget class MyWidget(Widget):
def __init__(self, **kwargs): super(MyWidget, self).__init__
(**kwargs) def callback(*l): self.x = self.y self.fbind('y', callback) callback()
b1oki/time_clicker_automatization
main.py
Python
gpl-3.0
5,645
0.004076
# -*- coding: utf-8 -*- """Time Clickers Auto upgrade & Auto-Clicker Tool. It makes the increment game look like the idle game. Made by b1oki & hakonw """ import sys import time # dis_pylint: disable=locally-disabled, no-name-in-module, no-member from win32gui import GetWindowText, GetForegroundWindow, GetWindowRect i...
# sleeps for a short time if not in game to reduce stress on pc time.sleep(SLEEPS_DELAY_NOT_PLAY) return False rect = GetWindowRect(hwnd) # get the window posission width = rect[2] - rect[0] height = rect[3] - rect[1] # auto click window field, numbers is the % of pixels that needs ...
removed on the side x_min = rect[0] + 0.25 * width x_max = rect[2] - 0.25 * width y_min = rect[1] + 0.16 * height y_max = rect[3] - 0.05 * height pos_x, pos_y = win32api.GetCursorPos() # checks if the mouse is inside the field return x_max > pos_x > x_min and y_max > pos_y > y_min def mou...
mikron-ia/dice-roller
src/roller.py
Python
mit
260
0.023077
__author__ = "Mikron" __version__ = "0.0-dev" from roll import Roll dice = [ 6, 6, 20 ] if __name__ == "__main__": rolls = Roll(dice) roll
_results = rolls.get_rolls()
for roll in roll_results: print("Roll: "+str(roll)+"\n")
charles-g-young/Table2NetCDF
gov/noaa/gmd/table_2_netcdf/Util.py
Python
apache-2.0
428
0.011682
''' Utilities Created on Mar 3, 2017 @author: cyoung ''' cla
ss Util: # Get a class by fully qualified name. def getClass(self, kls): parts = kls.split('.') moduleName = ".".join(parts[:-1]) #print("mo
dule "+module) #print("attr "+parts[-1]) mod = __import__(moduleName, fromlist=[parts[-1]]) clazz = getattr(mod, parts[-1]) return clazz()
anhstudios/swganh
data/scripts/templates/object/draft_schematic/bio_engineer/creature/shared_creature_shear_mite.py
Python
mit
470
0.046809
#### NOTICE: T
HIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE T
HE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/bio_engineer/creature/shared_creature_shear_mite.iff" result.attribute_template_id = -1 result.stfName("string_id_table","") #### BEGIN MODIFICATIONS #### ###...
vmanoria/bluemix-hue-filebrowser
hue-3.8.1-bluemix/desktop/core/ext-py/guppy-0.1.10/guppy/heapy/Part.py
Python
gpl-2.0
19,486
0.052397
#._cv_part guppy.heapy.Part class Format(object): __slots__ = 'impl', 'mod' def __init__(self, impl): self.impl = impl self.mod = impl.mod def get_formatted_row(self, row): fr = self.get_stat_data(row) rows = [] rs = row.name.split('\n') subsequent_indent = len(fr)*' ' rows.extend(self.mod.wrap( ...
s = '' return 'Partition of a set of %d object%s. Total size = %d bytes.'%( impl.count, s, impl.size) def get_rowdata(self, row): return '%d %d %s'%(row.count, row.size, row.name) def get_stat_header(self): return ( ' Index Count % Size % Cumulative % ') def get_stat_data(self, row)...
('%.0f'%(row.size * 100.0/impl.size)), row.cumulsize, int('%.0f'%(row.cumulsize * 100.0/impl.size)), ) return fr def load_statrow(self, r): return self.load_statrow_csk(r) class IdFormat(Format): __slots__ = () def get_label(self): impl = self.impl if impl.count != 1: s = 's' else:...
Aloomaio/googleads-python-lib
examples/adwords/v201809/error_handling/handle_partial_failures.py
Python
apache-2.0
4,130
0.006295
#!/usr/bin/env python # # 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 requir...
lements[0] if (first_field_path_element and first_field_path_element['field'] == 'operations' and 'index' in first_field_path_element): operation_index = first_field_path_element['index'] adgroup_criterion = operations[operation_index]['operand'] print('Ad group criterion with a...
d ' 'a failure for the following reason: %s.' % (adgroup_criterion['adGroupId'], adgroup_criterion['criterion']['text'], error['errorString'])) else: print ('A failure has occurred for the following reasons: %s\n' % error['errorString']) if ...
drnextgis/QGIS
python/ext-libs/nose2/plugins/coverage.py
Python
gpl-2.0
2,893
0.000346
""" Use this plugin to activate coverage report. To install this plugin, you need to activate ``coverage-plugin`` with extra requirements : :: $ pip install nose2[coverage-plugin] Next, you can enable coverage reporting with : :: $ nose2 --with-coverage Or with this lines in ``unittest.cfg`` : :: ...
self.covController.start() def afterSummaryReport(self, event): """Only called if active so stop coverage and produce reports.""" if self.covController:
self.covController.finish() self.covController.summary(event.stream)
pedrospdc/pinger
setup.py
Python
mit
939
0.001065
#!/usr/bin/env python # -*- coding: utf-8 -*- import setuptools from setuptools import setup, find_packages if setuptools.__version__ < '0.7': raise RuntimeError("setuptools must be newer than 0.7") version = "0.1.3" setup( name="pinger", version=version, author="Pedro Palhares (pedrospdc)", aut...
Development Status :: 3 - Alpha", "Environment :: Console", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Lang
uage :: Python", ], install_requires=[ "requests>=2.4.3", "peewee>=2.4.0" ], scripts=["bin/pinger"], )
alfredodeza/pytest
src/_pytest/skipping.py
Python
mit
6,499
0.000308
""" support for skip/xfail functions and markers. """ from _pytest.config import hookimpl from _pytest.mark.evaluate import MarkEvaluator from _pytest.outcomes import fail from _pytest.outcomes import skip from _pytest.outcomes import xfail from _pytest.store import StoreKey skipped_by_mark_key = StoreKey[bool]() eva...
onally specify a reason for better reporting " "and run=False if you don't even want to execute the test function. " "If only specific exception(s) are expected, you can list them in " "raises, and if the test fails in other ways, it will be reported as " "a true failure. See https://doc...
are specified as pytest marks item._store[skipped_by_mark_key] = False eval_skipif = MarkEvaluator(item, "skipif") if eval_skipif.istrue(): item._store[skipped_by_mark_key] = True skip(eval_skipif.getexplanation()) for skip_info in item.iter_markers(name="skip"): item._store[ski...
arKtelix/plugin.program.1.search
resources/lib/infodialog.py
Python
gpl-2.0
6,445
0.045151
import sys, re import xbmc, xbmcgui import contextmenu __language__ = sys.modules[ "__main__" ].__language__ __cwd__ = sys.modules[ "__main__" ].__cwd__ CANCEL_DIALOG = ( 9, 10, 92, 216, 247, 257, 275, 61467, 61448, ) ACTION_SHOW_INFO = ( 11, ) class GUI( xbmcgui.WindowXMLDialog ): def __init__( self...
tVisible( False
) self.getControl( 120 ).setVisible( False ) self.getControl( 130 ).setVisible( False ) self.getControl( 140 ).setVisible( False ) self.getControl( 150 ).setVisible( False ) self.getControl( 160 ).setVisible( False ) self.getControl( 170 ).setVisible( False ) self...
choderalab/Ensembler2
MSMSeeder/__init__.py
Python
gpl-2.0
33
0
from MS
MSeed
er.attic import core
jazztpt/edx-platform
lms/djangoapps/discussion_api/tests/test_views.py
Python
agpl-3.0
34,440
0.001249
""" Tests for Discussion API views """ from datetime import datetime import json from urlparse import urlparse import ddt import httpretty import mock from pytz import UTC from django.core.urlresolvers import reverse from rest_framework.test import APIClient from discussion_api.tests.utils import ( CommentsServ...
eated_at": "2015-04-28T00:00:00Z", "updated_at": "2015-04
-28T11:11:11Z", "thread_type": "discussion", "title": "Test Title", "body": "Test body", "pinned": False, "closed": False, "abuse_flaggers": [], "votes": {"up_count": 4}, "comments_count": 5, "unread_comments_cou...
petroniocandido/pyFTS
pyFTS/partitioners/partitioner.py
Python
gpl-3.0
12,188
0.003774
from pyFTS.common import FuzzySet, Membership import numpy as np from scipy.spatial import KDTree import matplotlib.pylab as plt import logging class Partitioner(object): """ Universe of Discourse partitioner. Split data on several fuzzy sets """ def __init__(self, **kwargs): """ Univ...
.partitions) for ix in nearest: tmp = self[ix].membership(data) mv[ix] = tmp if tmp >= alpha_cut else 0. ix = np.ravel(np.argwhere(mv > 0.)) if ix.size == 0: mv[self.check_bounds(data)] = 1. if method == 'fuzzy' and mode == 'vector':
return mv elif method == 'fuzzy' and mode == 'sets': try: ix = np.ravel(np.argwhere(mv > 0.)) sets = [self.ordered_sets[i] for i in ix if i < self.partitions] return sets except Exception as ex: return None elif...
InstitutoPascal/campuswebpro
controllers/notas.py
Python
agpl-3.0
4,034
0.006696
# controlador de ejemplo para carga inicial / consulta de notas por alumno def index(): # armo un formulario para buscar alumno por su dni form = SQLFORM.factory( Field("dni", "integer"), ) if form.accepts(request.vars, session): # buscar el alumno q = db.alumnos.dni == form...
b.materias.materiaid>0 # HACER: filtrar por carrera/plan de estudio orden = db.materias.materiaid # HACER: mejorar el orden (por ej. curso) materias = db(q).select(orderby=orden) # obtengo las notas q = db.notas.alumnoid == alumnoid q &= db.notas.calificacionid == 5 # filtrar solo finales ...
[(nota.materiaid, nota.nota) for nota in notas]) # encabezado de la tabla: filas = [TR( TH("ID"), TH("Materia"), TH("Nota"), )] # recorro las materias armando la tabla for materia in materias: filas.extend([ TR( ...
andir/ganeti
lib/storage/gluster.py
Python
bsd-2-clause
14,117
0.005454
# # # Copyright (C) 2013 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: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and ...
"-t", "glusterfs", self._GetFUSEMountString(), self.mount_point] io.Makedirs(self.mount_point) self._run_cmd(" ".join(command), # Why set cwd? Because it's an area we control. If, # for some unfortunate reason, this folder exists...
%s/" % _GetFUSEMountString() # ...then the gluster parser gets confused and treats # _GetFUSEMountString() as your mount point and
tchellomello/home-assistant
homeassistant/components/roku/config_flow.py
Python
apache-2.0
4,682
0.000854
"""Config flow for Roku.""" import logging from typing import Any, Dict, Optional from urllib.parse import urlparse from rokuecp import Roku, RokuError import voluptuous as vol from homeassistant.components.ssdp import ( ATTR_SSDP_LOCATION, ATTR_UPNP_FRIENDLY_NAME, ATTR_UPNP_SERIAL, ) from homeassistant.c...
LL def __init__(self): """Set up the instance.""" self.discovery_info = {} @callback def _show_form(se
lf, errors: Optional[Dict] = None) -> Dict[str, Any]: """Show the form to the user.""" return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors or {}, ) async def async_step_import( self, user_input: Optional[Dict] = Non...
zacharyvoase/pathobject
src/pathobject.py
Python
unlicense
15,069
0.001128
# -*- coding: utf-8 -*- """pathobjec
t.py - A utility class for operating on pathnames.""" import codecs import fnmatch import glob import hashlib import os import shutil import sys import warnings __all__ = ["Path"] __version__ = "0.0.1" ## Some functional utilities to save code later on. def update_wrapper(wrapper, wra
pped): """Update a wrapper function to look like the wrapped function.""" for attr in ('__module__', '__name__', '__doc__'): value = getattr(wrapped, attr, None) if value: setattr(wrapper, attr, value) wrapper.__dict__.update(getattr(wrapped, '__dict__', {})) return wrapper ...
sfstpala/hello
hello/__main__.py
Python
gpl-3.0
1,225
0
# Copyright (c) 2014 Stefano Palazzo
<stefano.palazzo@gmail.com> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public Lic
ense as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See t...
jseabold/statsmodels
statsmodels/tsa/statespace/dynamic_factor_mq.py
Python
bsd-3-clause
186,145
0
# -*- coding: utf-8 -*- """ Dynamic factor model. Author: Chad Fulton License: BSD-3 """ from collections import OrderedDict from warnings import warn import numpy as np import pandas as pd from scipy.linalg import cho_factor, cho_solve, LinAlgError from statsmodels.tools.data import _is_using_pandas from statsmodel...
# Note that this is equivalent to factors_ix with ravel(order='F') o = self.state_offset return np.s_[o:o + self.k_factors * self._factor_orde
r] @property def factors_ar(self): """Factors and all lags used in the factor autoregression (p).""" o = self.state_offset return np.s_[o:o + self.k_factors * self.factor_order] @property def factors_L1(self): """Factors (first block / lag only).""" o = self.sta...
starwels/starwels
test/functional/feature_notifications.py
Python
mit
4,003
0.003747
#!/usr/bin/env python3 # Copyright (c) 2014-2019 The Starwels developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the -alertnotify, -blocknotify and -walletnotify options.""" import os from test_framework.test_frame...
self.sync_all()
with open(self.alert_filename, 'r', encoding='utf8') as f: alert_text2 = f.read() self.log.info("-alertnotify should not continue notifying for more unknown version blocks") assert_equal(alert_text, alert_text2) if __name__ == '__main__': NotificationsTest().main()
qisanstudio/qstudio-launch
src/studio/launch/commands/contrib.py
Python
mit
2,178
0.000459
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import print_function import os import codecs import shutil from termcolor import colored from jinja2 import Template from studio.launch import ROOT_PATH from jinja2 import Environment, FileSystemLoader JDIR = os.path.join(ROOT_PATH, 'ji...
real_fname = fname[:-7] if fname.endswith('.jinja2') else fname fpath = Template(os.path.join(relcurdir, real_fname)).render(**kwargs) if fname.endswith('.jinja2'):
text = JENV.get_template(os.path.join(reldir, fname)).render(**kwargs) writefp(fpath, text) else: shutil.copyfile(os.path.join(JDIR, reldir, fname), fpath) if __name__ == '__main__': build_struct...
odahoda/noisicaa
noisicaa/ui/graph/toolbox.py
Python
gpl-2.0
4,154
0.000722
#!/usr/bin/python3 # @begin:license # # Copyright (c) 2015-2019, Benjamin Niemann <pink@odahoda.de> # # 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 y...
ECT)) self.__select_tool_button = QtWidgets.QToolButton(self) self.__select_tool_button.setAutoRaise(True) self.__select_tool_button.setIconSize(icon_size) self.__select_tool_bu
tton.setDefaultAction(self.__select_tool_action) self.__insert_tool_action = QtWidgets.QAction("Insert tool", self) self.__insert_tool_action.setIcon(QtGui.QIcon( os.path.join(constants.DATA_DIR, 'icons', 'list-add.svg'))) self.__insert_tool_action.setCheckable(True) self.__...
matus-chochlik/various
atmost/presentation/tools/plot-link-actu-pred.py
Python
mit
3,063
0.001959
#!/usr/bin/python3 -B # coding=utf8 # ------------------------------------------------------------------------------ import os import sys import math import random import matplotlib.pyplot as plt import matplotlib.ticker as pltckr import matplotlib.lines as pltlns import numpy as np from statistics import mean from co...
bel("Actual - Predicted [GB]") avp.grid() act = spls[1] act.xaxis.set_major_locator(pltckr.NullLocator()) act.set_xlabel("Link targets") act.set_ylabel("Actual [
GB]") act.grid() avp.fill_between( x, y, e, where=(e <= y), interpolate=True, color="red", alpha=0.7 ) avp.fill_between( x, y, e, where=(y < e), interpolate=True, color="green", alpha=0.3 ) avp.plot(x, y, color="bla...
arkmaxim/grpc
test/distrib/python/distribtest.py
Python
bsd-3-clause
1,732
0
# Copyright 2016, 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 condi
tions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # cont...
ved from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. I...
porduna/appcomposer
alembic/versions/435d360d3398_add_position_and_category_in_each_.py
Python
bsd-2-clause
1,306
0.009188
"""Add position and category in each message, so as to order the XML Revision ID: 435d360d3398 Revises: 2a68ba66c32b Create Date: 2015-05-03 19:00:38.124617 """ # revision identifiers, used by Alembic. revision = '435d360d3398' down_revision = '2a68ba66c32b' from alembic import op import sqlalchemy as sa def upgr...
ust! ### op.add_column('ActiveTransla
tionMessages', sa.Column('category', sa.Unicode(length=255), nullable=True)) op.add_column('ActiveTranslationMessages', sa.Column('position', sa.Integer(), nullable=True)) op.create_index(u'ix_ActiveTranslationMessages_category', 'ActiveTranslationMessages', ['category'], unique=False) op.create_index(u'ix_...