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
jtakayama/makahiki-draft
makahiki/apps/managers/smartgrid_mgr/migrations/0001_initial.py
Python
mit
5,586
0.008772
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'GccSettings' db.create_table('smartgrid_mgr_gccsettings', ( ('id', self.gf('dj...
=orm['auth.User'])), ('check_pub_dates', self.gf('django.db.models.fields.BooleanField')(default=True)),
('check_event_dates', self.gf('django.db.models.fields.BooleanField')(default=True)), ('check_unlock_dates', self.gf('django.db.models.fields.BooleanField')(default=True)), ('check_unreachable', self.gf('django.db.models.fields.BooleanField')(default=True)), ('check_fals...
axonchisel/ax_metrics
py/axonchisel/metrics/foundation/chrono/dtmath.py
Python
mit
6,349
0.005198
""" Ax_Metrics - datetime math utilities ------------------------------------------------------------------------------ Author: Dan Kamins <dos at axonchisel dot net> Copyright (c) 2014 Dan Kamins, AxonChisel.net """ # ---------------------------------------------------------------------------- from datetime impor...
e=0, hour=0, day=1) def begin_week(dt, day0_sunday_ofs=0): """ Return datetime marking beginning of week containing dt. If day0_sunday_ofs specified, it is treated as day offset from Sunday indicating what first day of week is, e.g. 1=Monday, -1=Saturday. """ dt = begin...
day = dt.weekday() # (Mon=0, Sun=6) weekday = (weekday + 1) % 7 # (Sun=0, Sat=6) day0 = day0_sunday_ofs % 7 days_off = (weekday - day0) % 7 td = timedelta(days=-days_off) return dt + td def begin_day(dt): """Return datetime marking beginning of day containing dt.""" return dt.replace(micro...
laplacesdemon/django-social-friends-finder
social_friends_finder/tests.py
Python
bsd-3-clause
2,413
0.000414
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase from social_a
uth.models import UserSocialAuth from django.contrib.auth.models import User from social_friends_finder.models import SocialFriendList from django.test.client import Client class SocialFriendsManagerTest(TestCase): fixtures = ['users.json', 'social_auth.json'] def setUp(self): pass def test_fix...
users = User.objects.all() self.assertEqual(len(users), 2) social_users = UserSocialAuth.objects.all() self.assertEqual(len(social_users), 2) def test_fetch_friends_from_twitter(self): """tests that we can fetch friend ids""" usa = UserSocialAuth.objects.all()[0] ...
catalpainternational/MohingaV1
profiles/views.py
Python
agpl-3.0
15,410
0.00318
import json import datetime import urllib from django.utils.translation import ugettext_lazy as _ from django.views.generic import TemplateView, View from django.views.generic.edit import UpdateView, CreateView from django.shortcuts import get_object_or_404 from django.http import HttpResponse, Http404 from django.cor...
ims.with_drafts() if editor else aims.activity.aims.all() activities_by_role = activities.filter(activity_participating_organisation__organisation=organisation)\ .distinct() transaction_queryset = aims.transaction.o
bjects.filter(provider_organisation=organisation) try: first_statistics = transaction_queryset.order_by('transaction_date')[0].transaction_date.year except: first_statistics = datetime.datetime.now().year activity_statuses = aims.activity_status.objects.all() or...
the-zebulan/CodeWars
tests/kyu_8_tests/test_multiply.py
Python
mit
254
0
import unittest from katas.kyu_8.multiply import multiply
class MultiplyTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(multiply(3, 4), 12) def test_equals_2(self): self.assertEqual(multipl
y(10, 10), 100)
MidAtlanticPortal/marco-portal2
marco/portal/grid_pages/models.py
Python
isc
1,857
0.002154
from django.db import models from modelcluster.fields import ParentalKey from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel, \ MultiFieldPanel from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailcore.models import Orderable from wagtail.wagtailsearch import index from port...
, MediaItem from accounts.forms import SignUpForm # The abstract model for ocean story sections, complete with panels class GridPageSectionBase(MediaItem): title = models.Ch
arField(max_length=255, blank=True) body = RichTextField(blank=True) panels = [ FieldPanel('title'), MultiFieldPanel(MediaItem.panels, "media"), FieldPanel('body', classname="full"), ] index_fields = MediaItem.index_fields + ( 'title', 'body', ) class M...
Cinntax/home-assistant
homeassistant/components/demo/alarm_control_panel.py
Python
apache-2.0
2,364
0.000423
"""Demo platform that has two fake alarm control panels.""" import datetime from homeassistant.components.manual.alarm_control_panel import ManualAlarm from homeassistant.const import ( STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_CUSTOM_BYPASS, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_NIGHT, STATE_AL...
_ALARM_TRIGGERED, CONF_DELAY_TIME, CONF_PENDING_TIME, CONF_TRIGGER_TIME, ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Demo alarm control panel platform.""" async_add_entities( [ ManualAlarm( hass, ...
True, False, { STATE_ALARM_ARMED_AWAY: { CONF_DELAY_TIME: datetime.timedelta(seconds=0), CONF_PENDING_TIME: datetime.timedelta(seconds=5), CONF_TRIGGER_TIME: datetime.timedelta(seconds=10), ...
rohitranjan1991/home-assistant
homeassistant/components/abode/config_flow.py
Python
mit
5,964
0.000671
"""Config flow for the Abode Security System component.""" from __future__ import annotations from http import HTTPStatus from typing import Any, cast from abodepy import Abode from abodepy.exceptions import AbodeAuthenticationException, AbodeException from abodepy.helpers.errors import MFA_CODE_REQUIRED from request...
ASSWORD): str, } self.mfa_data_schema = { vol.Required(CONF_MFA): str, } self._cache: str | None = None self._mfa_code: str | None = None self._password: str | None = None self._polling: bool = False self._usernam
e: str | None = None async def _async_abode_login(self, step_id: str) -> FlowResult: """Handle login with Abode.""" self._cache = self.hass.config.path(DEFAULT_CACHEDB) errors = {} try: await self.hass.async_add_executor_job( Abode, self._username, self....
rahul003/mxnet
python/mxnet/module/base_module.py
Python
apache-2.0
47,156
0.003987
# 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...
candidates = [arg for arg in args if not arg.endswith('_weight') and not arg.endswith('_bias') and not arg.endswith('_gamma') and not arg.endswith('_beta')] msg = "\033[91mYou created Module with Module(..., %s_names=%...
uments(). " \ "Did you mean one of:\n\t%s\033[0m"%( typename, str(names), name, '\n\t'.join(candidates)) if throw: raise ValueError(msg) else: warnings.warn(msg) def _check_names_match(data_names, data_shapes, name, throw): """Check that inpu...
fedora-conary/rmake-2
rmake/db/logstore.py
Python
apache-2.0
2,060
0.003398
# # Copyright (c) SAS Institute 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 or agreed to in w...
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 conary.lib import sha1helper from conary.lib import util from conary.repository...
(object): def __init__(self, path): util.mkdirChain(path) self.store = DeletableDataStore(path) def getTrovePath(self, trove): return self.store.hashToPath(self.hashTrove(trove)) def hashTrove(self, trove): return sha1helper.sha1ToString( sha1helper.sha1Stri...
ramcn/demo3
venv/lib/python3.4/site-packages/compressor/test_settings.py
Python
mit
880
0
import os import django TEST_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'tests') COMPR
ESS_CACHE_BACKEND = 'locmem://' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } INSTALLED_APPS = [ 'compressor', 'coffin', 'jingo', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(TEST_DIR, 'static') TEMPLATE_DIRS = ( # Specif...
fic template without considering the others. os.path.join(TEST_DIR, 'test_templates'), ) if django.VERSION[:2] < (1, 6): TEST_RUNNER = 'discover_runner.DiscoverRunner' SECRET_KEY = "iufoj=mibkpdz*%bob952x(%49rqgv8gg45k36kjcg76&-y5=!" PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.UnsaltedMD5PasswordHa...
lugatuic/python-irobot-create
robot.py
Python
mit
622
0.045016
import serial class Robot: def __init__(self, port, baud_rate = 57600): self.port = port self.baud_rate = 57600 #Eventually this will be editable self.conn = serial.Serial(s
elf.port,
baudrate=self.baud_rate, timeout=0.5) #wrapper for serial send function def send(self, num): if self.conn: self.conn.send(bytes(num, encoding='Latin-1' )) else: raise Exception("No serial connection.") def sendAll(self, nums): for n in nums: self.send(n) #Wrapper for serial read function def read...
ShujiaHuang/AsmVar2
asmvar/check.py
Python
mit
518
0.001931
""" This module use for checking the enviroment parameters and checking the files: Fasta, bamfiles or vcf files, whether they could satisfy the requirement of AsmVar2.0 or not """ try: import pysam except ImportError:
raise Exception('"pysam" not available, try "pip install pysam"?') try: import vcf except ImportError: raise Exception('"vcf" not available, try "pip install PyVCF"?') try: import numpy except ImportError: raise Exception('"numpy" not
available, try "pip install numpy"?')
Tary/Python-Tool
imageDL/MyFrame.py
Python
mit
982
0.02444
# -*- coding: utf-8 -*- ########################################################################### ## Python code generated with wxFormBuilder (version Jun 5 2014) ## http://www.wxformbuilder.org/
## ## PLEASE DO "NOT" EDIT THIS FILE! ########################################################################### import wx import wx.xrc import wx.richtext from MainWindowLayout import MainWindowLayout as MWLayout ########################################################################### ## Class MainPa...
__init__(self, parent) self.m_LogRichText.Clear() #wx.Frame.__init__(self, parent) #self.panel = MWLayout(self) def onDownloadClicked( self, event ): val = self.m_dirPicker2.GetTextCtrlValue() self.m_LogRichText.WriteText(val + "\n") self.m_LogRichText.Refresh() event.Skip()
samhoo/askbot-realworld
askbot/migrations/0050_move_qa_revisions_to_postrevision.py
Python
gpl-3.0
30,419
0.00812
# encoding: utf-8 import datetime from django.db import models from south.db import db from south.v2 import DataMigration class Migration(DataMigration): def copy_revision(self, orm, source_revision): question = getattr(source_revision, 'question', None) answer = getattr(source_revision, 'answer...
els = { 'askbot.activity': { 'Meta': {'object_name': 'Activity', 'db_table': "u'activity'"}, 'active_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'
}), 'activity_type': ('django.db.models.fields.SmallIntegerField', [], {}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_auditte...
jbergantine/pyeeg
pyeeg/approximate_entropy.py
Python
gpl-3.0
2,931
0.000682
import numpy from .embedded_sequence import embed_seq def ap_entropy(X, M, R): """Computer approximate entropy (ApEN) of series X, specified by M and R. Suppose given time series is X = [x(1), x(2), ... , x(N)]. We first build embedding matrix Em, of dimension (N-M+1)-by-M, such that the i-th row of ...
# Probability that random M-sequences are in range Cm = InRange.mean(axis=0) # M+1-sequences in range if M-sequences are in range & last values are close Dp = numpy.abs( numpy.tile(X[M:], (N - M, 1)) - numpy.tile(X[M:], (N - M, 1)).T ) Cmp = numpy.logical_and(Dp <= R, InRange[:-1, :-...
_En
bhavanaananda/DataStage
src/SubmitDatasetHandler/tests/TestGetDatasetMetadataHandler.py
Python
mit
2,943
0.013252
# $Id: TestAll.py 1047 2009-01-15 14:48:58Z graham $ # # Unit testing for WebBrick library functions (Functions.py) # See http://pyunit.sourceforge.net/pyunit.html # import sys, unittest, logging, zipfile, re, StringIO, os, logging, cgi from os.path import normpath, abspath from rdflib import URIRef sys.path.append(".....
Logger.debug("Output String from output stream: " + outputStr.getvalue()) # Check retrieving metadata metadata = json.load(outputStr) Logger.debug("Metadata Length = "+ repr(len(metadata))) self.assertEquals(len(metadata), 4, "Expected 4 pairs of field-values to be returned...
"component" return suite of unit and component tests "all" return suite of unit, component and integration tests "pending" return suite of pending tests name a single named test to be run """ testdict = { "unit": [ #"testUnits" ...
happz/ducky
tests/hdt.py
Python
mit
2,496
0.032853
import ducky.config import ducky.boot import ducky.mm from hypothesis import given from hypothesis.strategies import integers from ctypes import sizeof from . import common_run_machine, LOGGER from functools import partial def setup_machine(cpus, cores, memory): machine_config = ducky.config.MachineConfig() mach...
ducky.mm.MINIMAL_SIZE * ducky.mm.PAGE_SIZE, max_value = 0xFFFFFF00)) def test_sanity(cpus, cores, memory): memory &= ducky.mm.PAGE_MASK LOGGER.debug('TEST: cpus=%d, cores=%d, memory=0x%08X', cpus, cores, memory) M = setup_machine(cpus, cores, memory) assert M.nr_cpus == cpus assert M.nr_cores == cores S...
capture_state() memory_node = S.get_child('machine').get_child('memory') hdt_page = ducky.boot.DEFAULT_HDT_ADDRESS // ducky.mm.PAGE_SIZE hdt_page = [pg_node for pg_node in memory_node.get_page_states() if pg_node.index == hdt_page][0] def __base_assert(size, page, offset, value): for i, byte_offset, byte...
ministryofjustice/cla_public
cla_public/apps/base/extensions.py
Python
mit
602
0.001661
from flask import current_app, url_for from cla_public.apps.base import base from cla_public.apps.base.utils import check_categories @base.app_template_global() def asset(filename, min_ext="min"
): if not current_app.config["DEBUG"]: amended = filename.split(".") amended.insert(-1, min_ext) filename = ".".join(amended) return url_for("static", filename=filename) @base.app_template_global() def is_quick_exit_
enabled(session): categories_list = ["n43n3", "n18", "n19", "n88", "n86", "n97", "n149", "n62"] return check_categories(session, categories_list)
fabianvaccaro/pygums
pythonLibs/pymorph-0.96/pymorph/compat.py
Python
gpl-2.0
20,493
0.018348
import warnings warnings.warn('pymorph.compat should be replaced with pymorph', DeprecationWarning) from notimplemented import * from mmorph import * from text import * # old abbreviations: clohole=close_holes ero=erode cero=cerode dil=dilate cdil=cdilate sedil=sedilate add4dil=add4dilate uint8=to_uint8 uint16=to_ui...
fbi
n=binary([0, 1]) f1=to_uint8([1, 2, 3]) f2=to_uint8([2, 2, 3]) f3=to_uint8([2, 3, 4]) mmis(fbin,'binary') mmis(f1,'gray') mmis(f1,'==',f2) mmis(f1,'<',f3) mmis(f1,'<=',f2) mmis(f1,'<=',f2,'<=',f3) """ fro...
holmes-app/holmes-alf
holmesalf/wrapper.py
Python
mit
1,536
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of holmesalf. # https://github.com/holmes-app/holmes-alf # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT-license # Copyright (c) 2014 Pablo Aguiar scorphus@gmail.com from holmesalf import BaseAuthNZWrapper from alf.client i...
T_SECRET') ) return self._sync_client @property def async_client(self): """Asynchronous OAuth 2.0 Bearer client""" if not self._async_client: self._async_client = AlfAsyncClient( token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'), ...
ent_id=self.config.get('OAUTH_CLIENT_ID'), client_secret=self.config.get('OAUTH_CLIENT_SECRET') ) return self._async_client
jcollado/pic2map
tests/test_db.py
Python
mit
9,374
0
# -*- coding: utf-8 -*- """Test database functionality.""" import os import shutil import sqlite3 import tempfile import unittest from contextlib import closing from datetime import datetime from dateutil.tz import tzutc from mock import patch from sqlalchemy.exc import NoSuchTableError from sqlalchemy.types import...
ile.name)) as connection: with closing(connection.cursor()) as cursor: cursor.execute( 'CREATE TABLE messages (id INTEGER, message TEXT)') database = Database(db_file.name) table = database['messages'] schema = {column.name...
schema, {'id': INTEGER, 'message': TEXT}) def test_get_unknown_table_metadata(self): """NoSuchTableError raised when table name is not found.""" with tempfile.NamedTemporaryFile() as db_file: with closing(sqlite3.connect(db_file.name)) as connection: ...
prateekchandan/ldap-oauth2
user_resource/serializers.py
Python
gpl-3.0
1,772
0
from rest_framework import serializers from .models import Program, ContactNumber, SecondaryEmail, InstituteAddress from django.contrib.auth.models import User import copy from .oauth import default_fields, user_fields class ProgramSerializer(serializers.ModelSerializer): class Meta: model = Program ...
user'] class SecondaryEm
ailSerializer(serializers.ModelSerializer): class Meta: model = SecondaryEmail exclude = ['user'] class ContactNumberSerializer(serializers.ModelSerializer): class Meta: model = ContactNumber exclude = ['user'] class InstituteAddressSerializer(serializers.ModelSerializer): ...
zstackio/zstack-woodpecker
integrationtest/vm/mini/paths/path73.py
Python
apache-2.0
2,644
0.020045
import zstackwoodpecker.test_state as ts_header import os TestAction = ts_header.TestAction def path(): return dict(initial_formation="template5", path_list=[ [TestAction.create_mini_vm, 'vm1', ], [TestAction.destroy_vm, 'vm1'], [TestA
ction.recover_vm, 'vm1'], [TestAction.start_vm, 'vm1'], [TestAction.create_vm_backup, 'vm1', 'vm1-backup1'], [TestAction.stop_vm, 'vm1'], [TestAction.create_mini_vm, 'vm2', 'flag=thin'], [TestAction.resize_volume, 'vm2', 5*1024*1024], [TestAction.create_volume, 'volume1', 'flag=scsi'], [TestAction.attach_...
, 'root', 'http://172.20.1.28/mirror/diskimages/centos_vdbench.qcow2'], [TestAction.start_vm, 'vm1'], [TestAction.create_volume_backup, 'volume1', 'volume1-backup2'], [TestAction.stop_vm, 'vm1'], [TestAction.use_volume_backup, 'volume1-backup2'], [TestAction.delete_image, 'image1'], [TestAction.recover_imag...
WilliamKinaan/ScrapyDynamicItems
DynamicItemsScrapy/DynamicItemsScrapy/settings.py
Python
apache-2.0
3,084
0.010052
# -*- coding: utf-8 -*- # Scrapy settings for DynamicItemsScrapy project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.or...
ddleware': 543, #} # Enable or disable downlo
ader middlewares # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'DynamicItemsScrapy.middlewares.MyCustomDownloaderMiddleware': 543, #} # Enable or disable extensions # See http://scrapy.readthedocs.org/en/latest/topics/extensions.html #EXTENSIONS = { # ...
rnirmal/savanna
savanna/utils/openstack/keypairs.py
Python
apache-2.0
933
0
# Copyright (c) 2013 Mirantis 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 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 novaclient import base from novaclient.v1_1 import keypairs class SavannaKeypairManager...
Boussadia/weboob
weboob/tools/browser2/cookies.py
Python
agpl-3.0
2,534
0.000789
# -*- coding: utf-8 -*- # Copyright(C) 2014 Laurent Bachelier # # This file is part of weboob. # # weboob 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 o...
d=True, ignore_expires=True) def _cookies_from_attrs_set(self, attrs_set, request): for tup in self._normalized_cookie_tuples(attrs_set): cookie = self._cookie_from_cookie_tuple(tup, request) if cookie: yield cookie def make_cookies(self, respons
e, request): """Return sequence of Cookie objects extracted from response object.""" # get cookie-attributes for RFC 2965 and Netscape protocols headers = response.info() rfc2965_hdrs = headers.getheaders("Set-Cookie2") ns_hdrs = headers.getheaders("Set-Cookie") rfc2965 ...
Pegase745/sublime-flowtype
flowtype/listeners/builtintypes.py
Python
mit
41,312
0.002711
""" Flow's list of built-in types available in 0.44.0 (Apr 13, 2017). Related to https://flow.org/en/docs/types/ and http://www.saltycrane.com/blog/2016/06/flow-type-cheat-sheet/ """ def print_type_format(trigger, content=None, description=None): """Format output for autocompletion for a given trigger te...
on="Flow core type"), print_type_format("Set", "Set<${1}>", "Flow core type"), print_type_format("String", description="Flow core type"), print_type_format("Symbol", description="Flow co
re type"), print_type_format("SyntaxError", description="Flow core type"), print_type_format("TypeError", description="Flow core type"), print_type_format("Uint16Array", description="Flow core type"), print_type_format("Uint32Array", description="Flow core type"), print_type_format("Uint8Array", des...
ningchi/scikit-learn
sklearn/decomposition/tests/test_nmf.py
Python
bsd-3-clause
6,123
0
import numpy as np from scipy import linalg from sklearn.decomposition import nmf from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_false from sklearn.utils.testing import raises from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_gr...
sform returns close values # (transform uses scipy.optimize.nnls for now) A = np.abs(random_state.rand
n(6, 5)) m = nmf.ProjectedGradientNMF(n_components=5, init='nndsvd', random_state=0) transf = m.fit_transform(A) assert_true(np.allclose(transf, m.transform(A), atol=1e-2, rtol=0)) def test_n_components_greater_n_features(): # Smoke test for the case of more components than features. A = np.abs(ra...
mjm159/sunpy
sunpy/net/helioviewer.py
Python
bsd-2-clause
9,598
0.00646
""" This module provides a wrapper around the Helioviewer API. """ from __future__ import absolute_import #pylint: disable=E1101,F0401,W0231 __author__ = ["Keith Hughitt"] __email__ = "keith.hughitt@nasa.gov" import os import urllib import urllib2 import json import sunpy from sunpy.time import parse_time from sunp...
ss HelioviewerClient: """Helioviewer.org Client""" def __init__(self, url="http://helioviewer.org/api/"): self._api = url def get_data_sources(self, **kwargs): """Returns a structured list of datasources available at Heliovie
wer.org""" params = {"action": "getDataSources"} params.update(kwargs) return self._get_json(params) def get_closest_image(self, date, **kwargs): """Finds the closest image available for the specified source and date. For more information on what ty...
Slezhuk/ansible
lib/ansible/modules/network/nxos/nxos_vpc_interface.py
Python
gpl-3.0
11,899
0.001093
#!/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 distribut...
== portchannel: pc = port_ch vpc = str(existing_vpc) config['portchannel'] = pc config['peer-link'] = peer_link config['vpc'] = vpc return
config def get_commands_to_config_vpc_interface(portchannel, delta, config_value, existing): commands = [] if delta.get('peer-link') is False and existing.get('peer-link') is True: command = 'no vpc peer-link' commands.append('no vpc peer-link') commands.insert(0, 'interface port-chan...
Sbalbp/DIRAC
ResourceStatusSystem/Utilities/Utils.py
Python
gpl-3.0
3,106
0.043142
# $HeadURL: $ ''' :mod: Utils Module that collects utility functions. ''' import fnmatch from DIRAC import gConfig, S_OK from DIRAC.Core.Utilities import List from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations __...
h = '' ): ''' Gives the configuration rooted at path in a Python dict. The result is a Python dictionary that reflects the structure of the configuration file. ''' opHelper = Operations() def getCSTreeAsDict( treePath ): ''' Function to recursively iterate over a CS tree ''' ...
' ]: opts = opts[ 'Value' ] for optKey, optValue in opts.items(): if optValue.find( ',' ) > -1: optValue = List.fromChar( optValue ) else: optValue = [ optValue ] csTreeDict[ optKey ] = optValue secs = opHelper.getSections( treePath ) ...
mdbloice/CLSM-classification
TrainNetwork.py
Python
mit
7,030
0.006686
# Keras code for confocal laser scanner microscopy skin lesion classification. # M.D. Bloice, # Inst. for Medical Informatics, # Medical University Graz. # <marcus.bloice@medunigraz.at> # Portions of code from the Keras GitHub repository. # https://github.com/fchollet/keras ''' Train a Convolutional Neural Networ...
iments. np.random.seed(376483) batch_size = 128
# Size of image batch during training nb_classes = 2 # How many classes of objects do we have nb_epoch = 20 # Adjust until stabilising img_rows, img_cols = 64, 64 # Input image dimensions nb_filters = 32 # Number of convolutional filters to use nb_pool = 2 ...
MartinHjelmare/home-assistant
tests/components/light/common.py
Python
apache-2.0
3,341
0
"""Collection of helper methods. All containing methods are legacy helpers that should not be used by new components. Instead call the service directly. """ from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_BRIGHTNESS_PCT, ATTR_COLOR_NAME, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_FLASH, ATTR_HS_COLO...
sistant.loader import bind_hass @bind_hass def turn_on(hass, entity_id=None, t
ransition=None, brightness=None, brightness_pct=None, rgb_color=None, xy_color=None, hs_color=None, color_temp=None, kelvin=None, white_value=None, profile=None, flash=None, effect=None, color_name=None): """Turn all or specified light on.""" hass.add_job( async_turn_...
tkaitchuck/nupic
examples/opf/experiments/multistep/hotgym_best_tp_5step/description.py
Python
gpl-3.0
3,192
0.008772
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have purchased from # Numenta, Inc. a separate commercial license for this software code, the # following terms and conditions apply: # # This pro...
'type': 'DateEncoder'},
'timestamp_weekend': None}, 'verbosity': 0}, 'spParams': { }, 'tpParams': { 'activationThreshold': 13, 'minThreshold': 9, 'verbosity': 0}}} mod = importBaseDescription('../hotg...
hubert667/AIR
src/scripts/queryRanker.py
Python
gpl-3.0
3,450
0.014783
import sys, random, ast try: import include, copy, pickle except: pass import retrieval_system, environment, evaluation import query as queryClass from queryRankers import * class QueryRanker(): def __init__(self, path_train_dataset, path_test_dataset, feature_count_dataset, min_freq_count, iterations, ...
highQuery.get_qid(),l) BestRanker.addEval(highQuery.get_qid(),e) #save the dictionary to a file ('bestRanker.p') paths=self.path_train.sp
lit('/') name=paths[1] #pickle.dump(BestRanker, open( "QueryData/"+name+".data", "wb" ) ) pickle.dump(BestRanker, open( "QueryData/"+self.dataset+str(self.iterationCount)+".data", "wb" ) ) test = pickle.load( open( "QueryData/"+self.dataset+str(self.iterationCount)+".data", "rb" ) ) ...
VoltBit/ellida
code_archive/ellida_engine_old.py
Python
mit
10,607
0.003111
#!/usr/bin/python3 """ Engine used for processing test plans. """ from __future__ import print_function import os import sys import shutil import subprocess import socket import signal from time import sleep from threading import Thread from multiprocessing import Process import zmq sys.path.append('/home/smith/Drop...
-tapdevs <uid> <gid> <num> <native-sysroot-basedir> 2. add
INHERIT += "testimage" in local.conf 3. add TEST_SUITES = test_list in local.conf 4. copy tests in meta/lib/oeqa/runtime 5. call bitbake core-image-minimal -c testimage """ conf_path = "/home/smith/projects/poky/build/conf/local.conf" imagetest_script_path = "imagetest_sc...
joshbohde/megaminer-framework
server/networking/Filter.py
Python
agpl-3.0
5,766
0.004336
""" Copyright (C) 2008 by Steven Wallace snwallace@gmail.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later vers...
not in self.algorithms: self.error("UNKNOWN COMPRESSION ALGORITHM " + data) self.writeIn(self.algorithms[algorithm].decompress(data[1:])) def _writeOut(self,
data): if not self.initialized: Filter._writeOut(self, data) else: algorithm = 'n' newData = data for i in self.otherAlgorithms: if i in self.algorithms: tmpData = self.algorithms[i].compress(data, 9) ...
aldebaran/qibuild
python/qisys/sh.py
Python
bsd-3-clause
22,082
0.000815
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved. # Use of this source code is governed by a BSD-style license (see the COPYING file). """ Common filesystem operations """ from __future__ import absolute_import from __future__ import unicode_literals from __...
installed.append(rel_path) return installed def install(src, dest, filter_fun=None, quiet=False):
""" Install a directory or a file to a destination. If filter_fun is not None, then the file will only be installed if filter_fun(relative/path/to/file) returns True. If ``dest`` does not exist, it will be created first. When installing files, if the destination already exists, it will be remo...
asedunov/intellij-community
python/testData/completion/heavyStarPropagation/lib/_pkg1/_pkg1_0/_pkg1_0_1/_pkg1_0_1_0/_pkg1_0_1_0_0/_mod1_0_1_0_0_4.py
Python
apache-2.0
128
0.007813
name1_0_1_0_0_4_0 = None nam
e1_0_1_0_0_4_1 = None name1_0_1_0_0_4_2 = None name1_0_1_0_0_4_3 = None name1_0_1_0_0_4_4 = None
spacetelescope/asv
asv/commands/continuous.py
Python
bsd-3-clause
7,132
0.001542
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) import os import six import argparse from . import Command from .run import Run from .compare import Compare from ..rep...
color_print("") if worsened: color_print("SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY.", 'red') color_prin
t("PERFORMANCE DECREASED.", 'red') elif improved: color_print("SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY.", 'green') color_print("PERFORMANCE INCREASED.", 'green') else: color_print("BENCHMARKS NOT SIGNIFICANTLY CHANGED.", 'green') return worsened
goyal-sidd/BLT
website/migrations/0001_initial.py
Python
agpl-3.0
588
0.003401
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-27 21:54
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Greeting', fields=[ ('id', models.AutoField(auto_cr...
('when', models.DateTimeField(auto_now_add=True, verbose_name=b'date created')), ], ), ]
ForAP/Advanc3d-Pr0graming
Kivy-Resources/kivy-book-examples-master/Chapter_02_code/06-project/comiccreator.py
Python
gpl-2.0
494
0.01417
import kivy kivy.require('1.7.0') from kivy.app import App from kivy.lang import Builder from kivy.uix.anchorlayout import AnchorLayout Builder.load_file('toolbox.kv') Builder.load_file('drawingspace.kv') Builder.load_file('comi
cwidgets.kv') Builder.load_file('generaloptions.kv') Builder.load_file('statusbar.kv') class ComicCreator(AnchorLayout): pass class ComicCreatorApp(App): def build(self): return ComicCreator() if __name__=="__main__": ComicCreatorApp()
.run()
mkhuthir/learnPython
Book_pythonlearn_com/05_functions/lyrics.py
Python
mit
192
0.015625
def print_lyrics(): print("I'm a lumberjack, and
I'm okay.")
print('I sleep all night and I work all day.') def repeat_lyrics(): print_lyrics() print_lyrics() repeat_lyrics()
zepto/biblesearch.web
sword_search.old/sword_verses.py
Python
gpl-3.0
32,753
0.000611
#!/usr/bin/env python # vim: sw=4:ts=4:sts=4:fdm=indent:fdl=0: # -*- coding: UTF8 -*- # # A sword KJV indexed search module. # Copyright (C) 2012-2013 Josiah Gordon <josiahg@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as publ...
odule) dbm_name = '%s/%s.dbm' % (path, module) with IndexDbm(dbm_name, 'nf') as dbm_file: for key in key_iter: dbm_file[key] = lookup.get_raw_text(key) return dbm_name def make_daily_dbm(path: str=INDEX_PATH) -> str: """ Saves the daily devotional to a dbm file. """ fro...
date_iter = ((start + timedelta(i)).strftime('%m.%d') for i in range(365)) return mod_to_dbm('Daily', date_iter, path) def make_strongs_dbm(path: str=INDEX_PATH) -> str: """ Saves the StrongsReal modules as dbms. """ keys = IndexDict('KJV')['_strongs_'] greek_keys = (i[1:] for i in keys if i.sta...
florensacc/snn4hrl
envs/mujoco/gather/ant_gather_env.py
Python
mit
189
0.005291
from
rllab.envs.mujoco.gather.gather_env import GatherEnv from sandbox.snn4hrl.envs.mujoco.ant_env import AntEnv class AntGatherEnv(GatherEnv):
MODEL_CLASS = AntEnv ORI_IND = 3
annarev/tensorflow
tensorflow/python/keras/distribute/collective_all_reduce_strategy_test.py
Python
apache-2.0
3,234
0.006184
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a co
py 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 perm...
ethankennerly/hotel-vs-gozilla
lifeanddeath.fla.stage.py
Python
mit
433,306
0.010124
# file:///C|/project/lifeanddeath/lifeanddeath.fla.stage.py # max_depth = 9 { 'currentLabel': 'setup', 'cursor_mc': { 'currentLabel': 'none', 'act_mc': { 'currentLabel': 'none', }, # act_mc 'extra_stone_mc': { 'currentLabel': '_0', }, #...
'enter_btn': { }, # enter_btn 'recommend_mc': {
'currentLabel': 'none', }, # recommend_mc 'attract_mc': { 'currentLabel': 'none', }, # attract_mc 'score_txt': {'text': ''}, 'info_txt': {'text': ' '}, }, # none_mc '_txt': {'text': '_txt: ____-____1 ___-____2 ___-_...
fnp/koed-quiz
koedquiz/wsgi.py
Python
agpl-3.0
495
0.00202
import os import os.path import sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Add apps and lib directories to PYTHONPATH sys.path = [ ROOT, os.path.join(ROOT, 'apps'), ] + sys.path os.environ.setdefa
ult("D
JANGO_SETTINGS_MODULE", "koedquiz.settings") # This application object is used by the development server # as well as any WSGI server configured to use this file. from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
eayunstack/fuel-web
nailgun/nailgun/test/unit/test_primary_roles_assignment.py
Python
apache-2.0
6,992
0
# Copyright 2013 Mirantis, 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 or agreed to in writing, software # distributed under the License is distribut
ed 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. import abc from contextlib import contextmanager import six from nailgun import consts from nailgun import...
siemens/django-dingos-authoring
dingos_authoring/south_migrations/0007_auto__add_field_authoreddata_yielded.py
Python
gpl-2.0
17,052
0.007448
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'AuthoredData.yielded' db.add_column(u'dingos_authoring_authoreddata', 'yielded', ...
'}), 'latest': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'latest_of'", 'unique': 'True', 'null': 'True', 'to': u"orm['dingos.InfoObject']"}), 'namespace': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['dingos.IdentifierNameSpace']"}), '...
ct_name': 'IdentifierNameSpace'}, 'description': ('django.db.models.fields.T
omritoptix/django-ltg-skeleton
ltg_backend_app/wsgi.py
Python
mit
1,452
0.000689
""" WSGI config for nerdeez_server_app project. This module contains the WSGI ap
plication used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` co
mmands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware he...
transientlunatic/acreroad_1420
docs/conf.py
Python
bsd-3-clause
9,093
0.005282
#!/usr/bin/env python # -*- coding: utf-8 -*- # # acreroad_1420 documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # 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...
See the documentation for # a list of builtin themes. #html
_theme = 'default' html_theme = 'bootstrap' html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() # Theme options are theme-specific and customize the look and feel of a # theme further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} html_theme_options = {...
SanPen/GridCal
src/research/qt_related/pyside_enums.py
Python
lgpl-3.0
963
0
from PySide2.QtWidgets import * from PySide2 import QtCore from enum import Enum class SomeEnum(Enum): A = 'A' B = 'B' C = 'C' class EnumModel(QtCore.QA
bstractListModel): def __init__(self, list_of_enums): """ Enumeration model :param list_of_enums: list of enumeration values to show """ QtCore.QAbstractListModel.__init__(self) self.items = list_of_enums def rowCount(self, parent=QtCore.QModelIndex()): ...
index, role=QtCore.Qt.DisplayRole): if index.isValid() is True: if role == QtCore.Qt.DisplayRole: return self.items[index.row()].value[0] return None if __name__ == '__main__': import sys model = EnumModel([SomeEnum.A, SomeEnum.A, SomeEnum.B, SomeEnum.C]) app ...
barseghyanartur/django-slim
example/example/foo/urls.py
Python
gpl-2.0
243
0.016461
from django.conf.urls import * urlpatterns = patterns('foo.views', # Listing URL url(r'^$', view='browse', name='foo.browse'), # Detail URL url(r'^(?P<slug>(?!overview\-)[\w\-\_\.\,]+)/$', vi
ew='detail', name='foo.detail'),
)
eduherraiz/foowill
app/views.py
Python
mit
10,083
0.010909
#-*- coding: UTF-8 -*- from django.http import HttpResponseRedirect from django.contrib.auth import logout as auth_logout from django.contrib.auth.decorators import login_required from django.template import RequestContext from django.shortcuts import render_to_response, redirect from django.contrib.messages.api impo...
rm': TweetForm(), 'user': user, 'from_email' : from_email, 'infomail' : infomail, 'sended' : sended, } return render_to_response('contact.html', ctx, RequestContext(request)) def home(request): """Home view, displays login mechanism""" if request.user.is...
in have to configure the app -> redirecting if not user.configured: return HttpResponseRedirect('/config/') # Redirect after POST else: user = () ctx = { 'tweetform': TweetForm(), 'user': user, } return render_to_response('home.html', ctx, RequestContext(reques...
heromod/migrid
mig/cgi-bin/cleanexe.py
Python
gpl-2.0
1,104
0.002717
#!/usr/bin/python # -*- coding: utf-8 -*- # # --- BEGIN_HEADER --- # # cleanexe - [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 ...
ished 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 or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Pub...
nklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # -- END_HEADER --- # import cgi import cgitb cgitb.enable() from shared.functionality.cleanexe import main from shared.cgiscriptstub import run_cgi_script run_cgi_script(main)
liorvh/pythonpentest
nmap_scannner.py
Python
bsd-3-clause
2,228
0.013489
#!/usr/bin/env python ''' Author: Christopher Duffy Date: February 2015 Name: nmap_scanner.py Purpose: To scan a network Copyright (c) 2015, Christopher Duffy All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are...
EVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABIL
ITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import sys try: import nmap except: sys.exit("[!] Install the nmap library: pip install python-nmap") # Argument Validator if len(sys.argv) != 3: sys...
mortbauer/webapp
application/__init__.py
Python
mit
444
0.002252
import os from flask import Flask from flask.ext
.sqlalchemy import SQLAlchemy from flask.ext.bcrypt import Bcrypt from flask_sockets import Sockets app = Flask(__name__, static_folder="../static/dist", template_folder="../static") if os.environ.get('PRODUCTION'): app.config.from_object('config.ProductionConfig') else: app.config.from_obj
ect('config.TestingConfig') db = SQLAlchemy(app) bcrypt = Bcrypt(app) sockets = Sockets(app)
schae234/Camoco
camoco/cli/commands/list.py
Python
mit
878
0.004556
import camoco as co from camoco.Tools import * def list_com
mand(args): if args.type != None and args.name != None: if args.terms: if args.type == "GWAS": gwas = co.GWAS(args.name)
print("\n".join([x.id for x in gwas.iter_terms()])) elif args.type == "GOnt": gont = co.GOnt(args.name) print("\n".join([x.id for x in gont.iter_terms()])) if args.names: print(" ".join(available_datasets(args.type, args.name).Name)) else: ...
ingenioustechie/zamboni
mkt/stats/tasks.py
Python
bsd-3-clause
6,127
0
import json import logging import datetime from celery import task import mkt from mkt.constants.regions import REGIONS_CHOICES_SLUG from mkt.monolith.models import MonolithRecord from mkt.site.decorators import use_master from mkt.ratings.models import Review from mkt.webapps.models import AddonUser, Webapp from mkt...
lude(addonexcludedregion__region
=region.id) .count), 'dimensions': {'region': region_slug, 'premium_type': pt_name}, }) stats.update({'apps_added_by_package_type': package_counts}) stats.update({'apps_added_by_premium_type': premium_counts}) # Add vario...
MSeifert04/astropy
conftest.py
Python
bsd-3-clause
1,526
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst # This file is the main file used when running tests with pytest directly, # in particular if running e.g. ``pytest docs/``. from importlib.util import find_spec import os import pkg_resources import tempfile try: from pytest_astropy_header.display ...
_resources.iter_entry_points('pytest11'): entry_points.append(entry_point.name) if "asdf_schema_tester" not in entry_points: pytest_
plugins += ['asdf.tests.schema_tester'] PYTEST_HEADER_MODULES['Asdf'] = 'asdf' # Make sure we use temporary directories for the config and cache # so that the tests are insensitive to local configuration. os.environ['XDG_CONFIG_HOME'] = tempfile.mkdtemp('astropy_config') os.environ['XDG_CACHE_HOME'] = tempfil...
MarcoVogt/basil
examples/mio_sram_test/tests/test_Sim.py
Python
bsd-3-clause
6,711
0.000894
# ------------------------------------------------------------ # Copyright (c) All rights reserved # SiLab, Institute of Physics, University of Bonn # ------------------------------------------------------------ # import unittest import os import yaml import numpy as np from basil.dut import Dut from basil.utils.sim...
self.chip['CONTROL'].write() self.chip['CONTROL']['COUNTER_EN'] =
0 self.chip['CONTROL'].write() self.chip['CONTROL'].write() self.chip['CONTROL'].write() ret = np.hstack((ret, self.chip['FIFO'].get_data())) x = np.arange(245 * 4, dtype=np.uint8) x.dtype = np.uint32 self.assertEqual(ret.tolist(), x.tolist()) def test_fu...
wubr2000/googleads-python-lib
examples/dfp/v201505/custom_targeting_service/get_custom_targeting_values_by_statement.py
Python
apache-2.0
2,184
0.008242
#!/usr/bin/python # # Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
d. # See the License for the specific language governing permissions and # limitations under the License. """This example gets custom targeting values for the given predefined custom targeting key. To create custom targeting values, run create_custom_targeting_keys_and_values.py. To determine which custom targeting k...
GETING_KEY_ID_HERE' def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201505') values = [{ 'key': 'keyId', 'value': { 'xsi_type': 'NumberValue', 'value': key_id } }] query...
NewpTone/hotzenplotz
hotzenplotz/worker/driver/cron.py
Python
apache-2.0
6,103
0.002949
import os import datetime from jinja2 import Environment,PackageLoader,TemplateNotFound from hotzenplotz.openstack.common import cfg from hotzenplotz.openstack.common import log as logging from hotzenplotz.openstack.common import utils from hotzenplotz.common import exception from hotzenplotz.api import validator L...
if line.startswith('\t'): value.append(line) elif line.startswith('listen'): return i, value
return line_total - 1, value
willtownes/ped_parser
tests/test_individual.py
Python
mit
2,845
0.008439
#!/usr/bin/env python # encoding: utf-8 """ test_indivdual.py Test the individual class. Created by Måns Magnusson on 2013-03-07. Copyright (c) 2013 __MyCompanyName__. All rights reserved. """ import sys import os from ped_parser import individual class TestIndividual(object): """Test class for testing how the...
y='1', mother='0', father='0', sex=2,
phenotype=1 ) self.random_individual = individual.Individual(ind='0') def test_daughter(self): """Test if the information about the daughter comes out correctly.""" assert self.daughter.affected assert se...
arangodb/arangodb
3rdParty/V8/gyp/generator/dump_dependency_json.py
Python
apache-2.0
3,418
0.011118
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import print_function import os import gyp import gyp.common import gyp.msvs_emulation import json generator_supports_multiple_toolsets = True g...
arget_list, target_dicts, _, params): # Map of target -> list of targets it depends on. edges = {} # Queue of targets to visit. targets_to_visit = target_list[:] while len(targets_to_visit) > 0: target = targets_to_visit.pop()
if target in edges: continue edges[target] = [] for dep in target_dicts[target].get('dependencies', []): edges[target].append(dep) targets_to_visit.append(dep) try: filepath = params['generator_flags']['output_dir'] except KeyError: filepath = '.' filename = os.path.join(f...
worldbank/cv4ag
modules/overlay.py
Python
mit
12,673
0.055709
#!usr/bin/python ''' Overlay classes and satellite data ''' import os,csv,json import utils.gdal_rasterize as gdal_rasterize from PIL import Image from functools import partial from multiprocessing import Pool from utils.coordinate_converter import CoordConvert from utils.getImageCoordinates import imageCoordinates fro...
th+"/"+featureDataFolder+"/f
_"+str(i)+".json" try: os.remove(outFile) except OSError: pass gdal_rasterize.rasterize( \ featureFile, outFile, ts=size, # set resolution out_format='PNG', init=0, te=te, burn_values=[i]) # set image limits in te #make 0s transparent to prepare for merge img = Image.open(outFile) img = i...
ovnicraft/openerp-restaurant
sale/report/__init__.py
Python
agpl-3.0
1,065
0
# -*- 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 GNU...
###################################################################### import sal
e_report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
thombashi/pytablereader
pytablereader/csv/formatter.py
Python
mit
1,206
0
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ import typepy from tabledata import TableData from pytablereader import DataError from ..formatter import TableFormatter class CsvTableFormatter(TableFormatter): def to_table_data(self): if typepy.is_empty_sequence(self._loader.hea...
ce_data[1:] else: headers = self._l
oader.headers data_matrix = self._source_data if not data_matrix: raise DataError("data row must be greater or equal than one") self._loader.inc_table_count() yield TableData( self._loader.make_table_name(), headers, data_matrix, ...
BurtBiel/autorest
AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/auto_rest_report_service_for_azure.py
Python
mit
5,023
0.001593
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Cor
poration. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes m
ay cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.service_client import ServiceClient from msrest import Serializer, Deserializer from msrestazure import AzureConfiguration from .version import VERSION fro...
GunnerJnr/_CodeInstitute
Stream-3/Full-Stack-Development/21.Django REST Framework/4.User-Authentication/django_todo/django_todo/urls.py
Python
mit
869
0
"""django_todo URL Configuration The `urlp
atterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views
1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django....
ethanperez/t4k-rms
links/urls.py
Python
mit
340
0.029412
from django.conf.urls import patte
rns, url from links import views urlpatterns = patt
erns('links.views', url(r'^link/settings/$', views.settings, name = 'settings'), url(r'^link/donate/(?P<url>[\d\w.]+)$', views.kintera_redirect, name = 'donate'), url(r'^link/rider/(?P<url>[\d\w.]+)$', views.t4k_redirect, name = 'profile'), )
aricchen/openHR
openerp/addons/mail/mail_thread.py
Python
agpl-3.0
73,103
0.004405
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2009-today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms o...
de_header(message, header, separator=' '): return separator.join(map(decode, filter(None, message.get_all(header, [])))) class mail_thread(osv.AbstractModel): ''' mail_thread model is meant to be inherited by any model that needs to act as a discussion topic on which me
ssages can be attached. Public methods are prefixed with ``message_`` in order to avoid name collisions with methods of the models that will inherit from this class. ``mail.thread`` defines fields used to handle and display the communication history. ``mail.thread`` also manages followe...
aaijazi/vitess
examples/local/client.py
Python
bsd-3-clause
1,843
0.010852
#!/usr/bin/env python """Sample Vitess client in Python. This is a sample for using the Python Vitess client with an unsharded keyspace. Before running this, start up a local example cluster as described in the README.md file. Then run client.sh, which sets up PYTHONPATH before running client.py: vitess/examples/lo...
print 'Inserting into master...'
cursor = conn.cursor( tablet_type='master', keyspace='test_keyspace', keyranges=UNSHARDED, writable=True) cursor.begin() cursor.execute( 'INSERT INTO test_table (msg) VALUES (:msg)', {'msg': 'V is for speed'}) cursor.commit() # Read it back from the master. print 'Reading from mast...
CodeVITap/ProjectEuler
python/014-1.py
Python
gpl-3.0
395
0.04557
def collatzSequence(n): length = 0 while n != 1: if n % 2 == 0: n //= 2 else: n = 3 * n + 1 length += 1 return length + 1 max_length = 0 max_number = 0 for i in range(1000000, 0, -1): if i % 100000 == 0: print("Crossed {}".format(i/100000)) result = collatzSequence(i) if result > max_length: ...
_length = res
ult max_number = i print(max_length) print(max_number)
nicememory/pie
pyglet/contrib/model/examples/tree_test.py
Python
apache-2.0
2,094
0.00191
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: gl_tree_test.py 114 2006-10-22 09:46:11Z r1chardj0n3s $' import math import random from pyglet.window import * from pyglet.window import mouse from pyglet import clock from ctypes import * from pyglet.window.event import * # from py...
gluPerspective(60., 1., 1., 100.) glMatrixMode(GL_MODELVIEW) glClearColor(1, 1, 1, 1) class Tree(object): def __init__(self, n=2, r=False): self.tree = tree_list(n, r) self.x = self.y = 0 self.rx = self.ry = 0 self.zpos = -10 self.lmb = False self.rmb = F...
uttons & mouse.RIGHT: self.x += dx self.y += dy def on_mouse_scroll(self, x, y, dx, dy): self.zpos = max(-10, self.zpos + dy) def draw(self): glPushMatrix() glLoadIdentity() glTranslatef(self.x/10., -self.y/10., self.zpos) glRotatef(self.ry, 1., ...
jwvhewitt/dmeternal
old_game/narrator/encounters.py
Python
gpl-2.0
6,062
0.028373
from .plots import Plot,PlotError from .. import context from .. import items from .. import maps from .. import waypoints from .. import monsters from .. import dialogue from .. import services from .. import teams from .. import characters import random from .. import randmaps from .. import stats from .. import spel...
"""Requires the SCENE to exist.""" return ( pstate.elements.get("LOCAL
E") and context.MAP_DUNGEON in pstate.elements["LOCALE"].desctags ) def custom_init( self, nart ): scene = self.elements.get("LOCALE") mygen = nart.get_map_generator( scene ) room = mygen.DEFAULT_ROOM() room.contents.append( teams.Team(default_reaction=-999, rank=self...
clarko1/Cramd
appengine/standard/ndb/modeling/keyproperty_models.py
Python
apache-2.0
2,072
0
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2
.0 # # Unless required by applicable law or agreed to in writing, software # distributed und
er 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. """Models for representing a contact with multiple phone numbers. This module provides m...
arielalmendral/ert
python/python/ert/ecl/ecl_grid.py
Python
gpl-3.0
50,865
0.025558
# Copyright (C) 2011 Statoil ASA, Norway. # # The file 'ecl_grid.py' is part of ERT - Ensemble based Reservoir Tool. # # ERT is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of ...
int*)") _get_xyz3 = EclPrototype("void ecl_grid_get_xyz3( ecl_grid , int , int , int , double* , double* , double*)") _get_xyz1 = EclPrototype("void ecl_grid_get_xyz1( ecl_grid , int , double* , double* , double*)") _get_cell_corner_xyz1
= EclPrototype("void ecl_grid_get_cell_corner_xyz1( ecl_grid , int , int , double* , double* , double*)") _get_corner_xyz = EclPrototype("void ecl_grid_get_corner_xyz( ecl_grid , int , int , int, double* , double* , double*)") _get_xyz1A = EclPrototype("void ecl_grid_get_xyz1A( ...
todorez/crops
tests/unit/test_basic.py
Python
gpl-2.0
397
0.002519
''' Crawl the running Docker site and verify all links give a 200 OK ''' import unittest import subprocess # Placeholder for future python based
codi/TURFF class BasicTests(unittest.TestCase): ''' Base class for testin
g ''' def setUp(self): ''' Define some unique data for validation ''' pass def tearDown(self): ''' Destroy unique data ''' pass
openslack/openslack-crawler
crawler/schedulers/rabbitmq/queue.py
Python
apache-2.0
1,960
0
from scrapy.utils.reqser import request_to_dict, request_from_dict try: import cPickle as pickle except ImportError: import pickle class Base(object): """Per-spider queue/stack base class""" def __init__(self, server, spider, key, exchange=None): """Initialize per-spider RabbitMQ queue. ...
r instance key -- key for this queue (e.g. "%(spider)s:queue") """ self.server = server self.spider = spider self.key = key % {'spider': spider.name} def _encode_request(self, request): """Encode a request object""" return pickle.dumps(request_to_dict(req...
s(encoded_request), self.spider) def __len__(self): """Return the length of the queue""" raise NotImplementedError def push(self, request): """Push a request""" raise NotImplementedError def pop(self, timeout=0): """Pop a request""" raise NotImplementedErro...
kaw3ut/cs3240-labdemo
anothaone.py
Python
mit
76
0.013158
__author
__ = 'Kirsten White' if __name__ == "__main__": print("bless
up")
scott-trinkle/DIC
main.py
Python
mit
1,049
0.003813
from dic.experiment import Experiment from dic.plots import generate_plots '''This script ge
nerates data for a given experiment condition and plots it in a single figure. Plotting options are: polar: Plots in polar coordinates if true, otherwise Cartesian. areaplot: Plots the "error area" (\gamma*\sigma_gamma*\sigma_theta) if true, otherwise, creates 4x4 variable-specific plots show: Displays the ...
ue, otherwise does not. Used when saving.''' experiment = Experiment(lens=40, weak_grad=False, lamda=546, approaches=['A: 2x2', 'A: 2x3', 'B: 2x3', 'B: 2x4'], k=1e2, fromZero=True, ...
perlygatekeeper/glowing-robot
Project_Euler/14_longest_Collatz_sequence/print_Collatz_sequence.py
Python
artistic-2.0
534
0.009363
#!/opt/local/bin/python
# Python program to find largest common multiple import sys import math import timeit import time def collatz_sequence(start): next =
start print(next, end="") while next != 1: if next & 1 == 1: print(" is odd so (3n+1) ->") next = 3 * next + 1 else: print(" is even so (n/2) ->") next = int(next / 2) print(next, end="") print("") start = 99 if len(sys.argv) == 2: ...
tartley/toml
test_sys/test_happy_day.py
Python
bsd-3-clause
2,067
0.019836
import datetime import textwrap import unittest import toml # TODO steal the hard tests from toml-ply class HappyDayTest(unittest.TestCase): def test_convert_example_test(self): example = textwrap.dedent('''\ # This is a TOML document. Boom. title = "TOML Example" ...
01, 8002 ] connection_max = 5000 enabled = true [servers] # You can indent as you plea
se. [servers.alpha] ip = "10.0.0.1" dc = "eqdc10" # Tabs or spaces. TOML don't care. \t[servers.beta] \tip = "10.0.0.2" \tdc = "eqdc10" [clients] # Line breaks are OK when inside arrays ...
lbartoletti/QGIS
python/plugins/processing/algs/qgis/FindProjection.py
Python
gpl-2.0
6,167
0.002432
# -*- coding: utf-8 -*- """ *************************************************************************** FindProjection.py ----------------- Date : February 2017 Copyright : (C) 2017 by Nyall Dawson Email : nyall dot dawson at gmail dot com *****************...
gException(self.invalidSinkError(parameters, self.OUTPUT)) # make intersection tests nice and fast engine = QgsGeometry.createGeometryEngine(target_geom.constGet()) engine.prepareGeometry() layer_bounds = QgsGeometry.fromRect(source.sourceExtent()) crses_to_check = QgsCoordina...
al = 100.0 / len(crses_to_check) found_results = 0 transform_context = QgsCoordinateTransformContext() for current, srs_id in enumerate(crses_to_check): if feedback.isCanceled(): break candidate_crs = QgsCoordinateReferenceSystem.fromSrsId(srs_id) ...
nicolasgallardo/TECHLAV_T1-6
bebop_ws/devel/lib/python2.7/dist-packages/bebop_msgs/msg/_CommonAudioStateAudioStreamingRunning.py
Python
gpl-2.0
6,495
0.017244
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from bebop_msgs/CommonAudioStateAudioStreamingRunning.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import std_msgs.msg class CommonAudioStateAudioStreamingRunning(genp...
= self buff.write(_struct_3I.pack(_x.header
.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) _x = self.header.frame_id length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) if python3: buff.write(struct.pack('<I%sB'%length, length, *_x)) else: buff.write(struc...
GeorgeGkas/Data_Structures_and_Algorithms_in_Python
Chapter1/C-1/15.py
Python
mit
210
0
def unique_elems(data):
found_numbers = {} for number in data: if number not in found_numbers: foun
d_numbers[number] = number else: return False return True
griffinqiu/airflow
airflow/www/utils.py
Python
apache-2.0
6,553
0.002594
from future import standard_library standard_library.install_aliases() from builtins import str from builtins import object from cgi import escape from io import BytesIO as IO import functools import gzip import dateutil.parser as dateparser import json import os from flask import after_this_request, request, Response ...
''' <div id="{el_id}" style="height:100px;">{contents}</div> <textarea id="{el_id}_ace" name="{form_name}" style="display:none;visibility:hidden;"> </textarea> '''.format( el_id=kwargs.get('id', field.id), contents=escape(text_type(field._...
.HTMLString(html)
logicmonitor/k8s-argus
scripts/ds/ds_gen_watcher.py
Python
mpl-2.0
14,233
0.002319
import xml.etree.ElementTree as eT filehandler = open("argus_watcher_tmpl.xml", "r") raw_data = eT.parse(filehandler) data_root = raw_data.getroot() filehandler.close() tree = eT.ElementTree(data_root) datapoints = tree.find(".//entry/datapoints") events = ['add', 'update', 'delete'] latency_events = ['delete'] qua...
ile) eT.SubElement(graph, "dataType").text = str(7) eT.SubElement(graph, "type").text = str(2) eT.SubElement(graph, "postprocessormethod").text = "regex" eT.SubElement(graph, "postprocessorparam").text = "event=\"" + event + "\",resource=\"##WILDVALUE##\",quantile=\...
eT.SubElement(graph, "usevalue").text = "body" eT.SubElement(graph, "alertexpr") eT.SubElement(graph, "alertmissing").text = str(1) eT.SubElement(graph, "alertsubject") eT.SubElement(graph, "alertbody") eT.SubElement(graph, "enableanomalyalertsuppression") eT.SubEle...
ajbouh/tfi
src/tfi/driver/tf/asset.py
Python
mit
470
0.004255
import os import os.path def asset_paths_from(saved_model_dir): asset_paths = {} asset_path_basedir = os.path.join(saved_model_dir, 'assets.extra') for root, dirs, files in os.walk(asset_path_basedir): root = os.path.abspath(root) for filename in files: filepath = os.path.join(r...
path.relpath(filepath,
asset_path_basedir) asset_paths[relpath] = filepath return asset_paths
APIG2014/raspberryPiCam
raspberry_pi_cam/run_camera_server.py
Python
gpl-3.0
1,274
0.006279
#!/usr/bin/env python """ starts the daemon to gi
ve remote acces to the raspery pi ressources. Usage: run_camera_server.py [--port=<port>] [--IP=<IP>] [--allow_webcam] [--allow_picam] Options: -h --help show this screen. --port=<port> port used to connect [default: 8000]. --IP=<IP> IP used by the daemon. default, will...
age of the wecam [default: False]. --allow_picam allow the usage of the picam [default: False]. """ from docopt import docopt from raspberry_pi_cam.remotecamera.remotecameraserver import run_server from raspberry_pi_cam.remotecamera.utils import get_my_ip def main(): arguments = docopt(__doc__) ...
kwagyeman/openmv
scripts/examples/Arduino/Nano-33-BLE-Sense/01-Sensors/apds9960/ambient.py
Python
mit
374
0
from time import sleep_ms from machine import Pin, I2C from apds9960.const import * from apds9960 import uAPDS9960 as APDS9960 bus = I2C(1, sda=Pin(13), scl=Pin(14)) apds = APDS9960(bus) print("Light Sensor Test") print("=================") apds.enableLightSensor() wh
ile True: sleep_ms(250) val = apds.readAmbientLight() print("A
mbientLight={}".format(val))
sgallagher/reviewboard
reviewboard/webapi/resources/default_reviewer.py
Python
mit
13,364
0
from __future__ import unicode_literals from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.utils import six from djblets.util.decorators import augment_method_from from djblets.webapi.decorators import (webapi_login_required, ...
ult_reviewer' model = DefaultReviewer fields = { 'id': { 'type': int, 'description': 'The numeric ID of the default reviewer.', }, 'name': { 'type': six.text_type, 'description': 'The d
escriptive name of the entry.', }, 'file_regex': { 'type': six.text_type, 'description': 'The regular expression that is used to match ' 'files uploaded in a diff.', }, 'repositories': { 'type': six.text_type, 'de...
pybuilder/pybuilder
setup.py
Python
apache-2.0
1,895
0.001055
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of PyBuilder # # Copyright 2011-2020 PyBuilder Team # # 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 # # h...
path.basename(src_file) target_file_name = os.path.join(script_dir, file_name) if os.path.exists(target_file_name): if os.path.isdir(target_file_name): shutil.rmtree(target_file_name) else:
os.remove(target_file_name) shutil.move(src_file, script_dir) setup_args = sys.argv[1:] subprocess.check_call([sys.executable, "setup.py"] + setup_args, cwd=script_dir) except subprocess.CalledProcessError as e: exit_code = e.returncode sys.exit(exit_code)
sonald/Red-Flag-Linux-Installer
examples/installer/libs/run.py
Python
gpl-3.0
4,093
0.006108
#!/usr/bin/env python2 import os import sys import dbus from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * from webpage import WebPage class Installer(QObject): @pyqtSlot() def closeInstaller(self): sys.exit(0) @pyqtSlot(str) def reboot(self,msg): msg ...
er', 'org.gnome.SessionManager'] for arg in args: if arg in bus.list_names() and arg.find('kde') < 0: desktop_os = 'gnome' if desktop_os == 'kde': proxy = bus.get_object('org.kde.ksmserver', '/KSMServer') if msg == "reboot" or msg == "shutdown": ...
os.system(msg_tag[msg]['shell']) else: proxy = bus.get_object('org.gnome.SessionManager','/org/gnome/SessionManager') if msg == "reboot" or msg == "shutdown": try: proxy.Shutdown(timeout=30) except Exception, e: ...
adam-rabinowitz/ngs_analysis
scripts/GTF/ensembl_gene2biotype_gtf.py
Python
gpl-2.0
1,352
0.005917
'''ensembl_name_gtf.py Usage: ensembl_name_gtf.py <gtffile> <outfile> ''' # Import required modules import collections import re from general_python import docopt # Extract arguments args = docopt.docopt(__doc__, version='1.0') # Create regular expressions eRE = re.compile('gene_id\s+"(.*?)";') bRE = re.comp...
E, data).group(1) geneDict[ensembl].add(biotype) # Create output file counter = [0, 0, 0] with open(args['<outfile>'], 'w') as outFile:
for ensembl, biotype in geneDict.items(): counter[0] += 1 biotype = filter(None, biotype) if biotype: if len(biotype) > 1: counter[1] += 1 for bio in biotype: outFile.write('%s\t%s\n' %(ensembl, bio)) else: counter[2]...
aikramer2/spaCy
spacy/tests/lang/fr/test_exceptions.py
Python
mit
2,317
0.001737
# coding: utf-8 from __future__ import unicode_literals import pytest from .... import util @pytest.fixture(scope='module') def fr_tokenizer(): return util.get_lang_class('fr').Defaults.create_tokenizer() @pytest.mark.parametrize('text', ["aujourd'hui", "Aujourd'hui", "prud'hommes", ...
er_handles_title(fr_tokenizer): text = "N'est-ce pas génial?" tokens = fr_tokenizer(text) assert len(tokens) == 6 assert tokens[0].text == "N'" assert tokens[0].lemma_ == "ne" assert tokens[1].text == "est" assert tokens[1].lemma_ == "être" assert tokens[2].text == "-ce" assert token...
al?" tokens = fr_tokenizer(text) assert len(tokens) == 6 assert tokens[0].text == "Est" assert tokens[0].lemma_ == "être" def test_tokenizer_handles_title_2(fr_tokenizer): text = "Qu'est-ce que tu fais?" tokens = fr_tokenizer(text) assert len(tokens) == 7 assert tokens[0].text == "Qu'" ...
crabmanX/m4baker
src/aboutDialog.py
Python
gpl-2.0
1,275
0.003922
# -*- coding: utf-8 -*- # # M4Baker # Copyright (C) 2010 Kilian Lackhove # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later versio...
ort QDialog from PyQt4.QtCore import pyqtSignature from Ui_aboutDialog import Ui_aboutDialog from baseclasses import version class aboutDialog(QDialog, Ui_aboutDialog): """ Class documentation goes here. """ def __init__(self, parent = None): """ Con
structor """ QDialog.__init__(self, parent) self.setupUi(self) self.versionLabel.setText('Version: '+version)