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
markdrago/caboose
src/test/files/file_matcher_glob_tests.py
Python
mit
1,146
0.002618
from nose.tools import * from unittest import TestCase import os from shutil import rmtree from tempfile import mkdtemp from fnmatch import fnmatch from files.file_matcher_glob import FileMatcherGlob class FileMatcherGlobTests(TestCase): def setUp(self): self.directory = mkdtemp('-caboose-file-matcher-gl...
t_of_globs(self): self.file_matcher = FileMatcherGlob(["*.one", "*.two"]) eq_(True, self.file_matcher.match("hello.one")) eq_(True, self.file_matcher.match("hello.
two")) eq_(False, self.file_matcher.match("hello.three"))
kytos/kytos
tests/unit/test_core/test_buffers.py
Python
mit
3,932
0
"""Test kytos.core.buffers module.""" import asyncio from unittest import TestCase from unittest.mock import MagicMock, patch from kytos.core.buffers import KytosBuffers, KytosEventBuffer # pylint: disable=protected-access class TestKytosEventBuffer(TestCase): """KytosEventBuffer tests.""" def setUp(self): ...
_q.put(event) qsize_2 = self.kytos_event_buffer.qsize() self.as
sertEqual(qsize_1, 0) self.assertEqual(qsize_2, 1) def test_empty(self): """Test empty method to empty and with one event in query.""" empty_1 = self.kytos_event_buffer.empty() event = self.create_event_mock() self.kytos_event_buffer._queue.sync_q.put(event) empty_...
lahwaacz/python-wikeddiff
WikEdDiff/__init__.py
Python
gpl-3.0
125
0
#! /usr/bin/env python3 from .config import * f
rom .diff import * from .HtmlFormatter import * from .AnsiFormatter
import *
marhoy/nrk-download
tests/test_utils.py
Python
gpl-3.0
721
0
import datetime import nrkdownload.utils def test_valid_filename(string=r":blah/bl:ah.ext"): filename = nrkdownload.utils.valid_filename(string) assert filename == "blahblah.ext" def te
st_parse_duration(string="PT3H12M41.6S"): # PT28M39S : 28m39s # PT3H12M41.6S : 3h12m41.6s duration = nrkdownload.utils.parse_duration(string) assert duration == datetime.timedelta(hours=3, minutes=12, seconds=41.6) duration = nrkdownload.utils.parse_duration("") assert duration == datetime.time...
) def test_classmethod(): c = nrkdownload.utils.ClassProperty() assert c
jevinw/rec_utilities
babel_util/parsers/aminer_test.py
Python
agpl-3.0
350
0.005714
#!/u
sr/bin/env python import unittest from aminer import AMinerParser class AMinerParserTest(unittest.TestCase)
: SINGLE_TEST_FILE = "./aminer_single.txt" def setUp(self): self.single_test = open(self.SINGLE_TEST_FILE, "r") def test_single_parse(self): p = AMinerParser() if __name__ == "__main__": unittest.main()
OriHoch/Open-Knesset
simple/parsers/parse_laws.py
Python
bsd-3-clause
21,686
0.003465
# encoding: utf-8 import datetime import logging import os import re import urllib import urllib2 from HTMLParser import HTMLParseError f
rom urlparse import urlparse from BeautifulSoup import BeautifulSoup, Comment, NavigableString from django.contrib.contenttypes.models import ContentType from django.core.files.base import ContentFile import parse_knesset_bill_pdf from knesset.utils import send_chat_notification from laws.models import Bill, Law, Gov...
_LAWS_URL from simple.government_bills.parse_government_bill_pdf import GovProposalParser from simple.parsers.utils import laws_parser_utils from simple.parsers.utils.laws_parser_utils import normalize_correction_title_dashes, clean_line logger = logging.getLogger("open-knesset.parse_laws") # don't parse laws from an...
mehmetkose/react-websocket
example/server.py
Python
mit
1,627
0.003688
#!/usr/bin/env python #-*- coding:utf-8 -*- import logging, os.path import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web import tornado.websocket import tornado.gen class Application(tornado.web.Application): def __init__(self): base_dir = os.path.dirname(__file__) ...
ocketHandler.listenners: WebSocketHandler.listenners.remove(self) @tornado.gen.engine def on_message(self, wsdata): for listenner in WebSocketHandler.listenners: listenner.write_message(wsdata) @tornado.gen.coroutine def main(): tornado.options.parse_command_line() htt...
88) logging.info("application running on http://localhost:8888") if __name__ == "__main__": tornado.ioloop.IOLoop.current().run_sync(main) tornado.ioloop.IOLoop.current().start()
jcarlson23/lammps
tools/moltemplate/examples/CG_membrane_examples/membrane_BranniganPRE2005/moltemplate_files/version_charmm_cutoff/calc_table.py
Python
gpl-2.0
2,403
0.012901
#!/usr/bin/env python # Calculate a table of pairwise energies and forces between "INT" atoms # in the lipid membrane model described in # Brannigan et al, Phys Rev E, 72, 011915 (2005) # The energy of this interaction U(r) = eps*(0.4*(sigma/r)^12 - 3.0*(sigma/r)^2) # I realized later this is not what we want becau...
nt a def S(r, rc1, rc2, derivative=False): """ Calculate the switching function S(r) which decays continuously between 1 and 0 in the range from rc1 to rc2 (rc2>rc1): S(r) = (rc2^2 - r^2)^2 * (rc2^2 + 2*r^2 - 3*rc1^2) / (rc2^2-rc1^2)^3 I'm using the same smoothing/switching cutoff function used...
pair style, rewritten in python.) """ assert(rc2>rc1) rsq = r*r rc1sq = rc1*rc1 rc2sq = rc2*rc2 denom_lj_inv = (1.0 / ((rc2sq-rc1sq)* (rc2sq-rc1sq)* (rc2sq-rc1sq))) if rsq > rc2sq: return 0.0 elif...
ptorrestr/clean_text
clean_text/tests/test_cleaner.py
Python
gpl-2.0
7,295
0.010981
# -*- coding: utf-8 -*- import unittest import logging from os.path import isfile from os import popen from os import remove from t2db_objects import objects from t2db_objects.utilities import formatHash from t2db_objects.parameters import generate_config_yaml from clean_text.cleaner import sentenceCleaner from cle...
field = 'status_clean' sentence_proc_list = {'removeUrl', 'removeUserMention'} token_proc_list = {'stemming', 'toLowerCase', 'removePunctuationAndNumbers', 'stopwording', 'removeSingleChar', 'removeDoubleChar'} functions.stopwords = load_stopwords('etc/stopwords_en.txt') proc = Processor(text_fie...
ip("avoid big files") def test_cleaner(self): rawParams = { 'input_file':'etc/example.tsv', 'output_file':'output.tmp', 'config_file':'etc/config.yaml', } params = objects.Configuration(param_fields, rawParams) config = generate_config_yaml(conf_fields, params.config_file) if isf...
flyapen/UgFlu
flumotion/worker/__init__.py
Python
gpl-2.0
962
0
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007 Fluendo, S.L. (www.fluendo.com). # All rights reserved. # This file may be distributed and/or modified under the terms of # the GNU General Public License version 2 as published by # the Free ...
. # This file is distributed without any warranty; without even the implied # warranty of merchantability or fitness for a particular purpose. # See "LICENSE.GPL" in the source distribution for more information. # Licensees having purchased or holding a valid Flumotion Advanced # Streaming Server lice
nse may use this file in accordance with the # Flumotion Advanced Streaming Server Commercial License Agreement. # See "LICENSE.Flumotion" in the source distribution for more information. # Headers in this file shall remain intact. """ code for workers executing jobs for the manager """ __version__ = "$Rev: 6125 $"
UITools/saleor
saleor/graphql/api.py
Python
bsd-3-clause
1,246
0
import graphene from .account.schema import AccountMutations, AccountQueries from .checkout.schema import CheckoutMutations, CheckoutQueries from .core.schema import CoreMutations from .discount.schema import DiscountMutations, DiscountQueries from .menu.schema import MenuMutations, MenuQueries from .order.schema impo...
Queries from .page.schema import PageMutations, PageQueries from .payment.schema import PaymentMutations, PaymentQueries from .product.schema import ProductMutations, ProductQueries from .sh
ipping.schema import ShippingMutations, ShippingQueries from .shop.schema import ShopMutations, ShopQueries from .translations.schema import TranslationQueries class Query(AccountQueries, CheckoutQueries, DiscountQueries, MenuQueries, OrderQueries, PageQueries, PaymentQueries, ProductQueries, ...
Canpio/Paddle
python/paddle/fluid/tests/book/high-level-api/recognize_digits/test_recognize_digits_mlp.py
Python
apache-2.0
3,760
0.000266
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
fluid.layers.fc(input=hidden, size=200, act='tanh') prediction = fluid.layers.fc(input=hidden, size=10, act='softmax') return prediction def train_program(): label = fluid.layers.data(name='label', shape=[1], dtype='int64') predict = inference_program() cost = fluid.layers.
cross_entropy(input=predict, label=label) avg_cost = fluid.layers.mean(cost) acc = fluid.layers.accuracy(input=predict, label=label) return [avg_cost, acc] def optimizer_func(): return fluid.optimizer.Adam(learning_rate=0.001) def train(use_cuda, train_program, params_dirname): place = fluid.CUD...
cysuncn/python
spark/crm/PROC_O_IBK_WSYH_ECUSRLOGINTYPE.py
Python
gpl-3.0
6,837
0.013234
#coding=UTF-8 from pyspark import SparkContext, SparkConf, SQLContext, Row, HiveContext from pyspark.sql.types import * from datetime import date, datetime, timedelta import sys, re, os st = datetime.now() conf = SparkConf().setAppName('PROC_O_IBK_WSYH_ECUSRLOGINTYPE').setMaster(sys.argv[2]) sc = SparkContext(conf = c...
nt(etl_date[4:6]), 1) + timedelta(-1)).strftime("%Y%m%d") #10位日期 V_DT10 = (date(int(etl_date[0:4]), int(etl_date[4:6]), int(etl_date[6:8]))).strftime("%Y-%m-%d") V_STEP = 0 O_CI_WSYH_ECUSRLOGINTYPE = sqlContext.read.parquet(hdfs+'/O_CI_WSYH_ECUSRLOGINTYPE/*') O_CI_WSYH_ECUSRLOGINTYPE.registerTempTable(
"O_CI_WSYH_ECUSRLOGINTYPE") #任务[12] 001-01:: V_STEP = V_STEP + 1 #先删除原表所有数据 ret = os.system("hdfs dfs -rm -r /"+dbname+"/F_CI_WSYH_ECUSRLOGINTYPE/*.parquet") #从昨天备表复制一份全量过来 ret = os.system("hdfs dfs -cp -f /"+dbname+"/F_CI_WSYH_ECUSRLOGINTYPE_BK/"+V_DT_LD+".parquet /"+dbname+"/F_CI_WSYH_ECUSRLOGINTYPE/"+V_DT+".parquet...
repotvsupertuga/tvsupertuga.repository
script.module.universalscrapers/lib/universalscrapers/executor.py
Python
gpl-2.0
842
0.001188
import concurrent.futures from itertools import islice import xbmc import threading
Executor = concurrent.futures.ThreadPoolExecutor def
execute(f, iterable, stop_flag=None, workers=10, timeout=30): with Executor(max_workers=workers) as executor: threading.Timer(timeout, stop_flag.set) for future in _batched_pool_runner(executor, workers, f, iterable, timeout): if xbmc.abortRequ...
vapkarian/soccer-analyzer
src/colors/v20/default.py
Python
mit
1,079
0
from src.settings import Colors def league_color(league: str) -> Colors: if league in [ ]: return Colors.GREEN if league in [ '1 CFL (Montenegro)', 'A Lyga (Lithuania)', 'Bikar (Iceland)', 'Coupe de la Ligue (France)', 'EURO Qualifiers (Europe)', 'F...
'Premier League (Wales)', 'Primera Division (Chile)', 'Proximus League (Belgium)', 'Serie A (Italy)', 'S-League (Singapore)', 'Slovensky Pohar (Slovakia)', 'Svenska Cupen (Sweden)', 'Swiss Cup (Switzerland)', 'Virsliga (Latvia)', 'Vyscha Liga (...
rvalsdeild (Iceland)', ]: return Colors.RED if league in [ ]: return Colors.YELLOW return Colors.EMPTY
adrn/gala
gala/potential/hamiltonian/tests/helpers.py
Python
mit
5,372
0.001862
# Third-party import astropy.units as u import numpy as np # Project from ....dynamics import PhaseSpacePosition, Orbit from ....units import galactic PSP = PhaseSpacePosition ORB = Orbit class _TestBase(object): use_half_ndim = False E_unit = u.erg/u.kg @classmethod def setup_class(cls): np...
t = np.zeros(np.array(arr).shape[1:]) + 0.1 self.obj.energy(arr, t=0.1) sel
f.obj.energy(arr, t=t) self.obj.energy(arr, t=0.1*self.obj.units['time']) def test_gradient(self): for arr, shp in zip(self.w0s, self.gradient_return_shapes): if self.E_unit.is_equivalent(u.one) and hasattr(arr, 'pos') and \ not arr.xyz.unit.is_equivalent(u.one):...
iktakahiro/sphinx_theme_pd
sphinx_theme_pd/__init__.py
Python
mit
136
0
import os
def get_html_theme_path(): theme_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) return theme_di
r
yonahbox/ardupilot
Tools/ardupilotwaf/chibios.py
Python
gpl-3.0
13,403
0.005596
#!/usr/bin/env python # encoding: utf-8 """ Waf tool for ChibiOS build """ from waflib import Errors, Logs, Task, Utils from waflib.TaskGen import after_method, before_method, feature import os import shutil import sys import re import pickle _dynamic_env_data = {} def _load_dynamic_env_data(bld): bldnode = bld...
.find_or_declare('bin/' + link_output.change_ext('.hex').name) hex_task = self.create_task('build_intel_hex', src=[bin_target, bootloader_bin], tgt=hex_target) hex_task.set_run_after(generate_bin_task) if self.env.DEFAULT_PARAMETERS
: default_params_task = self.create_task('set_default_parameters', src=link_output) default_params_task.set_run_after(self.link_task) generate_bin_task.set_run_after(default_params_task) if self.bld.options.upload: _upload_task = se...
hep7agon/city-feedback-hub
api/migrations/0016_service_code.py
Python
mit
640
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-04-19 10:32 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0015_auto_20160408_1355'), ] operations = [ migrations.AlterField( ...
model_name='feedback', name='service_code', field=models.CharField(max_length=120, null=True), ), migrations.AlterField( model_name='service', name='service_code', field=models.CharField(max
_length=120, unique=True), ), ]
miracle2k/stgit
stgit/commands/sync.py
Python
gpl-2.0
5,549
0.007929
__copyright__ = """ Copyright (C) 2006, Catalin Marinas <catalin.marinas@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be ...
ot sync_patches: raise CmdException, 'No common patches to be synchronised' # pop to the one before the first patch to be synchronised first_patch = sync_patches[0] if first_patch in applied: to_pop = applied[applied.index(first_patch) + 1:] if to_pop: pop_patches(crt_se...
[first_patch] else: to_pop = [] pushed = [] popped = to_pop + [p for p in patches if p in unapplied] for p in pushed + popped: if p in popped: # push this patch push_patches(crt_series, [p]) if p not in sync_patches: # nothing to synchroni...
zhenxuan00/mmdgm
mlp-mmdgm/gpulearn_z_x.py
Python
mit
50,776
0.015499
''' modified by Chongxuan Li (chongxuanli1991@gmail.com) ''' import sys sys.path.append('..') sys.path.append('../../data/') import os, numpy as np import scipy.io as sio import time import anglepy as ap import anglepy.paramgraphics as paramgraphics import anglepy.ndict as ndict import theano import theano.tensor as...
as pp import color def zca_dec(zca_mean, zca_winv, data): return zca_winv.dot(data) + zca_mean def labelToMat(y): label = np.unique(y) newy = np.zeros((len(y), len(label))) for i in range(len(y)): newy[i, y[i]] = 1 return newy.T def main(n_z, n_hidden, dataset, seed, comment, gfx=True): ...
x_mnist_96-(500, 500)' if os.environ.has_key('pretrain') and bool(int(os.environ['pretrain'])) == True: comment+='_pre-train' if os.environ.has_key('prior') and bool(int(os.environ['prior'])) == True: comment+='_prior' pre_dir+='_prior' if os.environ.has_key('cutoff'): comment+=('_'+str(int(os....
dimonaks/siman
siman/structure_functions.py
Python
gpl-2.0
8,328
0.018492
#!/usr/bin/env python3 """ Author: Kartamyshev A.I. (Darth Feiwante) """ def inherit_icalc_isotropic(new_structure = '', start_new_version = None, base_calculation = (None, None, None), database = None, min_mult = 1, max_mult = 1, num_points = 2, geo_folder = '', it_folder = '', override = False): """ This f...
+= 1 elif num_points_a == 1: for j in mult_list_c: inherit_icalc('c_a', new_structure, version, base_calculation, database, mult_a = 1, mult_c = j, geo_fo
lder=geo_folder, override=override) version += 1 def inherit_icalc_x_y(new_structure = '', start_new_version = None, base_calculation = (None, None, None), database = None, min_mult_a = 1, max_mult_a = 1, num_points_a = 2, min_mult_b = 1, max_mult_b = 1,num_points_b = 2,...
glove747/liberty-neutron
neutron/tests/unit/agent/linux/test_external_process.py
Python
apache-2.0
11,219
0
# Copyright 2012 New Dream Network, LLC (DreamHost) # # 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 a...
og_patch.start() self.spawn_patch = mock.patch("eventlet.spawn") self.eventlen
t_spawn = self.spawn_patch.start() # create a default process monitor self.create_child_process_monitor('respawn') def create_child_process_monitor(self, action): conf = mock.Mock() conf.AGENT.check_child_processes_action = action conf.AGENT.check_child_processes = True ...
upTee/upTee
uptee/accounts/forms.py
Python
bsd-3-clause
7,709
0.004281
from datetime import date import os from django.contrib.auth.models import User from django import forms from django.utils import timezone from fields import Html5CaptchaField from html5input import * from settings import AVAILABLE_TEMPLATES, TEMPLATE_DIRS from accounts.models import UserProfile class SettingsUserFor...
er = User.objects.filter(is_active=True, email=email) if not user: raise forms.ValidationError("No user with this email exists.") return email class RegisterForm(forms.Form): username = forms.RegexField(labe
l="Username", min_length=3, regex=r'^[\w.@+-]+$', error_messages={'invalid': 'Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters.'}, widget=forms.TextInput(attrs={'pattern': r'[\w.@+-]{3,30}', 'title': '30 characters or fewer. Letters, numbers and @/./+/-/_ characters', 'require...
makerbot/ReplicatorG
skein_engines/skeinforge-47/skeinforge_application/skeinforge_plugins/craft_plugins/home.py
Python
gpl-2.0
8,040
0.023383
""" This page is in the table of contents. Plugin to home the tool at beginning of each layer. The home manual page is at: http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Home ==Operation== The default 'Activate Home' checkbox is on. When it is on, the functions described below will work, when it is off, not...
the bevel gcode." splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) if len(splitLine) < 1: return firstWord = splitLine[0] if firstWord == 'G1': self.addHomeTravel(splitLine)
self.oldLocation = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine) elif firstWord == '(<layer>': self.layerCount.printProgressIncrement('home') if len(self.homeLines) > 0: self.shouldHome = True elif firstWord == 'M101': self.extruderActive = True elif firstWord == 'M103': self.ex...
egabancho/invenio
invenio/modules/jsonalchemy/testsuite/test_parser.py
Python
gpl-2.0
10,487
0.00143
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014, 2015 CERN. ## ## Invenio 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 opt...
n Field_parser.field_definitions('testsuite')) self.assertTrue('title' in Field_parser.field_definitions('testsuite'))
# Check work around for [n] and [0] self.assertTrue( Field_parser.field_definitions('testsuite')['doi']['pid']) # Check if derived and calulated are well parserd self.assertTrue('dummy' in Field_parser.field_definitions('testsuite')) self.assertEquals( Field_par...
shinglyu/servo
tests/wpt/harness/wptrunner/wptrunner.py
Python
mpl-2.0
9,731
0.00185
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import unicode_literals import json import os import sys import environment as env import products imp...
nexpected"] while repeat_count < repeat or repeat_until_unexpected: repeat_count += 1
if repeat_until_unexpected: logger.info("Repetition %i" % (repeat_count)) elif repeat > 1: logger.info("Repetition %i / %i" % (repeat_count, repeat)) unexpected_count = 0 logger.suite_start(test_loader.test_ids, run_info) ...
googleapis/google-resumable-media-python
google/resumable_media/_helpers.py
Python
apache-2.0
12,563
0.000637
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
s ) return status_code def calculate_retry_wait(base_wait, max_sleep, multiplier=2.0): """Calculate the amount of time to wait before a retry attempt. Wait time grows exponentially with the number of attempts, until ``max_sleep``. A random amount of jitter (between 0 and 1 seconds) i
s added to spread out retry attempts from different clients. Args: base_wait (float): The "base" wait time (i.e. without any jitter) that will be multiplied until it reaches the maximum sleep. max_sleep (float): Maximum value that a sleep time is allowed to be. multiplier (f...
tiancj/emesene
emesene/e3/xmpp/SleekXMPP/sleekxmpp/plugins/xep_0047/ibb.py
Python
gpl-3.0
5,190
0.000193
import uuid import logging import threading from sleekxmpp import Message, Iq from sleekxmpp.exceptions import XMPPError from sleekxmpp.xmlstream.handler import Callba
ck from sleekxmpp.xmlstream.matcher import StanzaPath from sleekxmpp.xmlstream import register_stanza_plugin from sleekxmpp.plugins import BasePlugin from sleekxmpp.plugins.xep_0047 import stanza, Open, Close, Data, IBBytestream log = logging.getLogger(__name__) class XEP_0047(BasePlugin): name = 'xep_0047' ...
stanza = stanza def plugin_init(self): self.streams = {} self.pending_streams = {3: 5} self.pending_close_streams = {} self._stream_lock = threading.Lock() self.max_block_size = self.config.get('max_block_size', 8192) self.window_size = self.config.get('window_...
msegado/edx-platform
common/test/acceptance/tests/lms/test_lms_dashboard.py
Python
agpl-3.0
5,727
0.002794
# -*- coding: utf-8 -*- """ End-to-end tests for the main LMS Dashboard (aka, Student Dashboard). """ import six from common.test.acceptance.fixtures.course import CourseFixture, XBlockFixtureDesc from common.test.acceptance.pages.common.auto_auth import AutoAuthPage from common.test.acceptance.pages.lms.dashboard im...
TODO: AC-934 'landmark-complementary-is-top-level', # TODO: AC-939 'region' # TODO: AC-932 ] }) course_listings = self.dashboard_page.get_courses() self.assertEqual(len(course_listings), 3) self.dashboard_page.a11y_audit.check_for_ac
cessibility_errors()
JarbasAI/JarbasAI
jarbas_skills/LILACS_core/concept.py
Python
gpl-3.0
25,737
0.002487
from jarbas_utils.skill_tools import LILACSstorageQuery from mycroft.util.log import getLogger __authors__ = ["jarbas", "heinzschmidt"] class ConceptNode(): ''' Node: name: type: "informational" <- all discussed nodes so far are informational Connections: synonims: [] <- is...
_off=None, type="info"): self.name = name self.type = type if data is None: data = {} self.data = data self.connections = {} if parent_concepts is not None: s
elf.connections.setdefault("parents", parent_concepts) else: self.connections.setdefault("parents", {}) if child_concepts is not None: self.connections.setdefault("childs", child_concepts) else: self.connections.setdefault("childs", {}) if synonims is ...
gamernetwork/gn-django
gn_django/fields.py
Python
mit
909
0.0011
from django.db import models from django.utils import timezone from pytz import common_timezones from .validators import YoutubeValidator class TimezoneField(models.CharField): """ A field for selecting a timezone from the common timezones list. """ def __init__(self, *args, **kwargs): common...
atic validation that given values are valid YouTube UR
Ls """ default_validators = [YoutubeValidator()]
musicpax/funcy
funcy/simple_funcs.py
Python
bsd-3-clause
1,941
0.002576
from functools import partial from .primitives import EMPTY __all__ = ['identity', 'constantly', 'caller', 'partial', 'rpartial', 'func_partial', 'curry', 'rcurry', 'autocurry', 'iffy'] def identity(x): return x def constantly(x): return lambda *a, **kw: x # an operator.m...
n is EMPTY: n = func.__code__.co_argcount if n <= 1: return func
elif n == 2: return lambda x: lambda y: func(x, y) else: return lambda x: curry(partial(func, x), n - 1) def rcurry(func, n=EMPTY): if n is EMPTY: n = func.__code__.co_argcount if n <= 1: return func elif n == 2: return lambda x: lambda y: func(y, x) els...
fusionbox/mezzanine
mezzanine/utils/models.py
Python
bsd-2-clause
8,880
0.000113
from __future__ import unicode_literals from functools import partial from future.utils import with_metaclass from django import VERSION from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db.models import Model, Field from django.db.models.signals import class_prepared...
tings
.ADMIN_THUMB_SIZE.split('x') thumb_url = thumbnail(thumb, x, y) return "<img src='%s%s'>" % (settings.MEDIA_URL, thumb_url) admin_thumb.allow_tags = True admin_thumb.short_description = "" class ModelMixinBase(type): """ Metaclass for ``ModelMixin`` which is used for injecting model ...
cpennington/edx-platform
common/lib/xmodule/xmodule/contentstore/content.py
Python
agpl-3.0
19,503
0.00323
import logging import os import re import uuid from io import BytesIO import six from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import AssetKey, CourseKey from opaque_keys.edx.locator import AssetLocator from PIL import Image from six.moves.urllib.parse import parse_qsl, quote_plus, urlencode, url...
path) return (asset_digest, asset_path) @staticmethod def add_version_to_asset_path(path, version): """ Adds a prefix to an asset path indicating the asset's version. """ # Don't version an already-versioned path. if StaticContent.is_versioned_asset_path(path):...
NED_ASSETS_PREFIX, structure_version, version, path) @staticmethod def get_asset_key_from_path(course_key, path): """ Parses a path, extracting an asset key or creating one. Args: course_key: key to the course which owns this asset path: the path to said content...
pyreaclib/pyreaclib
pynucastro/networks/rate_collection.py
Python
bsd-3-clause
34,049
0.002731
"""A collection of classes and methods to deal with collections of rates that together make up a network.""" # Common Imports import warnings import functools import math import os from operator import mul from collections import OrderedDict from ipywidgets import interact import numpy as np import matplotlib as mp...
= os.path.dirname(os.path.dirname(os.path.realpath(__file__))) def __init__(self, rate_files=None, libraries=None, rates=None, precedence=()): """ rate_files are the files that together define the network. This can be any iterable or single string. This can include Reaclib library...
ibrary object(s) in list 'libraries'. If rates is supplied, initialize a RateCollection using the Rate objects in the list 'rates'. Precedence should be sequence of rate labels (e.g. wc17) to be used to resolve name conflicts. If a nonempty sequence is provided, the rate collec...
carolFrohlich/nipype
nipype/pipeline/plugins/ipython.py
Python
bsd-3-clause
4,707
0.002337
# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Parallel workflow execution via IPython controller """ from __future__ import print_function, division, unicode_literals, absolute_import from future import standard_library stan...
if IPyversion >= '0.11': logger.debug("Clearing id: %d"
% taskid) self.taskclient.purge_results(self.taskmap[taskid]) del self.taskmap[taskid]
OCA/account-financial-tools
account_fiscal_position_vat_check/__manifest__.py
Python
agpl-3.0
637
0
# Copyright 2013-2020 Akretion France (https://akretion.com/) # @author: Alexis de Lattre <alexis.delattre@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Fiscal Position VAT Check", "version": "14.0.1.0.0", "category": "Invoices & Payments", "license": ...
: "Akretion,Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "depends": ["account", "base_vat"], "data": [ "views/account_fiscal_position
.xml", ], "installable": True, }
plazmer/pyrtsp
rtcp_datagram.py
Python
gpl-2.0
6,169
0.003242
# -*- coding: utf-8 -*- # RTCP Datagram Module from struct import unpack, pack debug = 0 # Receiver Reports included in Sender
Report class Report: SSRC = 0 FractionLost = 0 CumulativeNumberOfPacketsLostH = 0 CumulativeNumberOfPacketsLostL = 0 ExtendedHighestSequenceNumberReceived = 0 InterarrivalJitter = 0 LastSR = 0 DelaySinceLastSR = 0
# Source Description class SDES: SSRC = 0 CNAME = '' NAME = '' EMAIL = '' PHONE = '' LOC = '' TOOL = '' NOTE = '' PRIV = '' class RTCPDatagram(object): 'RTCP packet parser end generator' def __init__(self): self.Datagram = '' # SR specific self.SSRC...
googleads/googleads-shopping-samples
python/shopping/content/datafeeds/update.py
Python
apache-2.0
1,688
0.007109
#!/usr/bin/python # # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
erchantId=merchant_id, datafeedId=datafeed_id).execute() # Changing the scheduled fetch time to 7:00. datafeed['fetchSchedule']['hour'] = 7 request = service.datafeeds().update( merchantId=merchant_id, datafeedId=datafeed_id
, body=datafeed) result = request.execute() print('Datafeed with ID %s and fetchSchedule %s was updated.' % (result['id'], str(result['fetchSchedule']))) if __name__ == '__main__': main(sys.argv)
michalkurka/h2o-3
h2o-py/tests/testdir_algos/glm/pyunit_PUBDEV_7481_lambda_search_alpha_array_multinomial_cv.py
Python
apache-2.0
2,324
0.012909
import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.glm import H2OGeneralizedLinearEstimator as glm # Given alpha array and lambda_search=True, build two cross-validation models, one with validation dataset # and one without for multinomial. Since they use the metri...
a, x=myX,y=myY) cv_r_valid = glm.getGLMRegularizationPath(cv_model_valid) for l in range(len(cv_r['lambdas'])): print("comparing coefficients for submodel {0} with lambda {1}, alpha {2}".format(l, cv_r_valid["lambdas"][l], cv
_r_valid["alphas"][l])) pyunit_utils.assertEqualCoeffDicts(cv_r['coefficients'][l], cv_r_valid['coefficients'][l], tol=1e-6) pyunit_utils.assertEqualCoeffDicts(cv_r['coefficients_std'][l], cv_r_valid['coefficients_std'][l], tol=1e-6) if __name__ == "__main__": pyunit_utils.standalone_test(glm_alpha...
IOsipov/androguard
androguard/decompiler/dad/basic_blocks.py
Python
apache-2.0
10,681
0.000094
# This file is part of Androguard. # # Copyright (c) 2012 Geoffroy Gueguen <geoffroy.gueguen@gmail.com> # 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://...
def neg(self): self.cond.neg() def visit_cond(self, visitor): return self.cond.visit(visitor) def __str__(self): return '%d-SC(%s)' % (self.num, self.cond) class LoopBlock(CondBlock): def __init__(self, name, cond): super(LoopBlock, self).__init__(name, None) s...
th_ins(self): return self.cond.get_loc_with_ins() def visit(self, visitor): return visitor.visit_loop_node(self) def visit_cond(self, visitor): return self.cond.visit_cond(visitor) def update_attribute_with(self, n_map): super(LoopBlock, self).update_attribute_with(n_map) ...
zamattiac/SHARE
providers/com/dailyssrn/__init__.py
Python
apache-2.0
62
0
default
_app_config = 'providers.com.dailyssrn.apps.AppConf
ig'
manhhomienbienthuy/scikit-learn
examples/semi_supervised/plot_self_training_varying_threshold.py
Python
bsd-3-clause
4,008
0.000749
""" ============================================= Effect of varying threshold for self-training ============================================= This example illustrates the effect of a varying threshold on self-training. The `breast_cancer` dataset is loaded, and labels are deleted such that only 50 out of 569 samples h...
return_counts=True)[1][0] ) # The last iteration the classifier labeled a sample in amount_iterations[i, fold] = np.max(self_training_clf.labeled_iter_) y_pred = self_training_clf.predict(X_test) scores[i, fold] = accuracy_score(y_test_true, y_pred) ax1 = plt.subplot(211) ax1...
, color="b" ) ax1.set_ylabel("Accuracy", color="b") ax1.tick_params("y", colors="b") ax2 = ax1.twinx() ax2.errorbar( x_values, amount_labeled.mean(axis=1), yerr=amount_labeled.std(axis=1), capsize=2, color="g", ) ax2.set_ylim(bottom=0) ax2.set_ylabel("Amount of labeled samples", color="g") ax2.tick...
certeu/do-portal
tests/test_av.py
Python
bsd-3-clause
343
0
from flask import url_for from flask_sqlalchemy import BaseQuery def test_create_av_scan(client, monkeypatch, malware_sample): monkeypatch.setattr(Bas
eQuery, 'first_or_404', lambda x: True) rv = client.post(url_for('api.add_av_scan'),
json={'files': [malware_sample._asdict()]}) assert rv.status_code == 202
kmaglione/amo-validator
tests/test_js_operators.py
Python
bsd-3-clause
7,066
0.000849
from math import isnan from nose.tools import eq_ from js_helper import _do_real_test_raw, _do_test_raw, _do_test_scope, _get_var def test_assignment_with_pollution(): """ Access a bunch of identifiers, but do not write to them. Accessing undefined globals should not create scoped objects. """ a...
= typeof(Math.PI), n = typeof(0), o = typeof(1), p = typeof(-1), q = typeof(
'0'), r = typeof(Number()), s = typeof(Number(0)), t = typeof(new Number()), u = typeof(new Number(0)), v = typeof(new Number(1)), x = typeof(function() {}), y = typeof(Math.abs); """) eq_(_get_var(scope, 'a'), 'undefined') eq_(_get_var(scope, 'b'), 'o...
spulec/moto
tests/test_s3control/test_s3control_config_integration.py
Python
apache-2.0
11,847
0.001013
import boto3 import json import pytest import sure # noqa # pylint: disable=unused-import from boto3 import Session from botocore.client import ClientError from moto import settings, mock_s3control, mock_config # All tests for s3-control cannot be run under the server without a modification of the # hosts file on yo...
r r in result["ResourceIdentifiers"]: regions.remove(r.pop("SourceRegion")) asser
t r == { "ResourceType": "AWS::S3::AccountPublicAccessBlock", "SourceAccountId": ACCOUNT_ID, "ResourceId": ACCOUNT_ID, } # Just check that the len is the same -- this should be reasonable regions = {region for region in Session().get_available...
martinrusev/amonone
amon/apps/alerts/models/tests/alerts_model_test.py
Python
mit
13,755
0.012432
import unittest from nose.tools import eq_ from django.contrib.auth import get_user_model from amon.apps.alerts.models import AlertsModel from amon.apps.processes.models import process_model from amon.apps.plugins.models import plugin_model from amon.apps.servers.models import server_model from amon.apps.devices.mode...
rt['rule'], 'updated_test') def mute_test(self): self.collection.remove() self.collection.insert({"name" : "test", "key": "test_me"}) alert = s
elf.collection.find_one() alert_id = str(alert['_id']) self.model.mute(alert_id) result = self.collection.find_one() eq_(result["mute"], True) self.model.mute(alert_id) result = self.collection.find_one() eq_(result["mute"], False) def get_mute_state_tes...
nesdis/djongo
tests/django_tests/tests/v22/tests/auth_tests/models/with_integer_username.py
Python
agpl-3.0
681
0
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class IntegerUsernameUserManager(BaseUserManager): def create_user(self, username, password): user = self.mo
del(username=username) user.set_password(password) user.save(using=self._db) return user def get_by_natural_key(self, username): return self.get(username=username) class IntegerUsernameUser(AbstractBaseUser): username = models.IntegerField() password = models.CharFie
ld(max_length=255) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['username', 'password'] objects = IntegerUsernameUserManager()
robertnishihara/ray
python/ray/tests/test_gcs_fault_tolerance.py
Python
apache-2.0
3,783
0.000264
import sys import ray import pytest from ray.test_utils import ( generate_system_config_map, wait_for_condition, wait_for_pid_to_exit, ) @ray.remote class Increase: def method(self, x): return x + 2 @ray.remote def increase(x): return x + 1 @pytest.mark.parametrize( "ray_start_reg...
s_server()
ready, unready = ray.wait(ids, num_returns=100, timeout=240) print("Ready objects is {}.".format(ready)) print("Unready objects is {}.".format(unready)) assert len(unready) == 0 @pytest.mark.parametrize( "ray_start_cluster_head", [ generate_system_config_map( num_heartbeats_t...
crazy-canux/xplugin_nagios
plugin/plugins/sharepoint_2013/src/plugin/base.py
Python
gpl-2.0
3,450
0
# -*- coding: utf-8 -*- # Copyright (C) Canux CHENG <canuxcheng@gmail.com> # # 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 ...
elf._alerts['critical'].append(crit_result) self.have_criticals = True def add_warning_result(self, warn_result): """ Add a warning result. Used in longo
utput to show the result in a WARNING section. """ self._alerts['warning'].append(warn_result) self.have_warnings = True
EarthLifeConsortium/elc_api
swagger_server/test/test_taxonomy_controller.py
Python
apache-2.0
995
0.001005
# coding: utf-8 from __future__ import absolute_import from swagger_server.models.error_model import ErrorModel from swa
gger_server.models.taxonomy import Taxonomy from . import BaseT
estCase from six import BytesIO from flask import json class TestTaxonomyController(BaseTestCase): """ TaxonomyController integration test stubs """ def test_tax(self): """ Test case for tax Taxonomic information, or hierarchy """ query_string = [('taxon', 'taxon_exam...
vmendez/DIRAC
ResourceStatusSystem/Command/DowntimeCommand.py
Python
gpl-3.0
13,233
0.042167
''' DowntimeCommand module ''' import urllib2 from datetime import datetime, timedelta from operator import itemgetter from DIRAC import S_OK, S_ERROR from DIRAC.Core.LCG.GOCDBClient import GOCDBClient from DIRAC.Core.Utilities.Site...
alue' ] elementNames = [ elementName ] #WARNING: checking all the DT that are ongoing or starting in given <hours> from now try: results = self.gClient.getStatus( element, name = elementNames, startingInHours = hours ) except urllib2.URLError: try: #Let's
give it a second chance.. results = self.gClient.getStatus( element, name = elementNames, startingInHours = hours ) except urllib2.URLError, e: return S_ERROR( e ) if not results[ 'OK' ]: return results results = results[ 'Value' ] if results is None: return S_OK( None )...
ABASystems/pymyob
tests/test_managers.py
Python
bsd-3-clause
3,511
0.003987
from datetime import date, datetime from unittest import TestCase from myob.constants import DEFAULT_PAGE_SIZE from myob.credentials import PartnerCredentials from myob.managers import Manager class QueryParamTests(TestCase): def setUp(self): cred = PartnerCredentials( consumer_key='KeyToTheK...
, {'$filter': "(DisplayID gt '5-0000')"}) self.assertParamsEqual({'DateOccurred__lt': '2013-08-30T19:00:59.043'}, {'$filter': "(DateOccurred lt '2013-08-30T19:00:59.043')"}) self.assertParamsEqual({'Type': ('Customer', 'Supplier'), 'DisplayID__gt': '5-0000'}, {'$filter': "(Type eq 'Customer' or Type eq ...
lter': "(Type eq 'Customer' or Type eq 'Supplier') or DisplayID gt '5-0000'", 'DateOccurred__lt': '2013-08-30T19:00:59.043'}, {'$filter': "((Type eq 'Customer' or Type eq 'Supplier') or DisplayID gt '5-0000') and (DateOccurred lt '2013-08-30T19:00:59.043')"}) self.assertParamsEqual({'IsActive': True}, {'$filter...
chakki-works/elephant_sense
elephant_sense/evaluator.py
Python
apache-2.0
2,383
0.002098
import os import json import numpy as np from sklearn.externals import joblib from scripts.features.post import Post from scripts.features.post_feature import PostFeature import scripts.features.length_extractor as lext import scripts.features.charactor_extractor as cext import scripts.features.structure_extractor as s...
pf.add(sext.ImageCountExtracto
r()) pf.add(sext.ImageRatioExtractor(cleaned_rendered_body)) pf_d = pf.to_dict(drop_disused_feature=True) f_vector = [] for f in self.features: f_vector.append(pf_d[f]) f_vector = np.array(f_vector).reshape(1, -1) f_vector = self.scaler.transform...
equitania/myodoo-addons-v10
eq_stock/models/eq_report_stock.py
Python
agpl-3.0
3,096
0.002913
# -*- coding: utf-8 -*- ############################################################################## # # Odoo Addon, Open Source Management Solution # Copyright (C) 2014-now Equitania Software GmbH(<http://www.equitania.de>). # # This program is free software: you can redistribute it and/or modify # it un...
ge, 'Sale Price Report', currency_id) # # # @api.multi # def get_price
(self, value, currency_id, language): # """ # Formatierung eines Preises mit Berücksichtigung der Einstellung Dezimalstellen Sale Price Report # :param value: # :param currency_id: # :param language: # :return: # """ # return self.env["eq_report_helper"].g...
nathanhilbert/ulmo
test/usgs_eddn_test.py
Python
bsd-3-clause
13,809
0.004779
from datetime import datetime import pandas as pd from pandas.util.testing import assert_frame_equal import ulmo import ulmo.usgs.eddn.parsers as parsers import test_util fmt = '%y%j%H%M%S' message_test_sets = [ { 'dcp_address': 'C5149430', 'number_of_lines': 4, 'parser': 'twdb_stevens', ...
0 12:00:00', 'sense01', pd.np.nan, 67.81], ['2013-10-30 13:00:00', 'sense01', pd.np.nan, 67.73], ['2013-10-30 14:00:00', 'sense01', pd.np.nan, 66.15], ['2013-10-30 15
:00:00', 'sense01', 13.29, 67.84], ], }, { 'message_timestamp_utc': datetime(2013,10,30,15,28,18), 'dcp_message': '":OTT 703 60 #60 -231.47 -231.45 -231.44 -231.45 -231.47 -231.50 -231.51 -231.55 -231.56 -231.57 -231.55 -231.53 :6910704 60 #60 -261.85 -261.83 -261.81 -261.80 -261.81 -261...
zainag/RPi-Test-Projects
fan_control_daemon.py
Python
mit
2,129
0.034758
#!/usr/bin/env python # Fan control mod for Raspberry Pi import RPi.GPIO as GPIO, time, datetime, subprocess, os, logging from daemon import runner DEBUG = 1 GPIO.setmode(GPIO.BCM) # Respective ports on the GPIO header FAST = 18 SLOW = 25 # Default settings for fan control MAX_TEMP = 50 MIN_TEMP = 40 POLL_TIME =...
)s - %(levelname)s - %(message)s") handler = logging.FileHandler("/var/log/fandaemon/fandaemon.log") handler.setFormatter(formatter) logger.addHandler(handler) daemon_runner = runner.DaemonRunner(app) #This ensures that the logger file handle does not get closed during daemonization da
emon_runner.daemon_context.files_preserve=[handler.stream] daemon_runner.do_action()
jiaphuan/models
tutorials/image/cifar10/cifar10_train.py
Python
apache-2.0
4,491
0.004899
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ole.""") def train(): """Train CIFAR-10 for a number of steps.""" with tf.Graph().as_default(): global_step = tf.train.get_or_create_global_step() # Get images and labels for CIFAR-10. # Force input pipeline to CPU:0 to avoid operations sometimes ending up on # GPU and resulting in a slow down. ...
images, labels = cifar10.distorted_inputs() # Build a Graph that computes the logits predictions from the # inference model. logits = cifar10.inference(images) # Calculate loss. loss = cifar10.loss(logits, labels) # Build a Graph that trains the model with one batch of examples and # u...
ytanay/thinglang
tests/compiler/test_access_compilation.py
Python
mit
1,587
0.00189
from tests.compiler import compile_snippet, A_ID, LST_ID, SELF_ID, VAL1_ID, internal_call, A_INST, INNER_ID, \ CONTAINER_INNER_ID, STATIC_START from thinglang.compiler.opcodes import OpcodePushLocal, OpcodePushMember, OpcodePushStatic, OpcodePop, \ OpcodeDereference, OpcodeCallVirtual def test_direct_member_a...
OpcodePushMember(A_INST, 0) ] def test_nested_member_access(): assert compile_snippe
t('self.inner.inner.inner') == [ OpcodePushMember(SELF_ID, INNER_ID), OpcodeDereference(CONTAINER_INNER_ID), OpcodeDereference(CONTAINER_INNER_ID) ] def test_member_access_via_method_call(): assert compile_snippet('a_inst.me().a1') == [ OpcodePushLocal(A_INST), OpcodeCa...
avanc/mopidy-usbplaylist
mopidy_usbplaylist/__init__.py
Python
apache-2.0
668
0
from __future__ import unicode_literals import os from mopidy import config, ext __version__ = '0.0.1' class Extension(ext.Extension): dist_name = 'Mopidy-USBPlaylist' ext_name = 'usbplaylist' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__f...
ma(self): schema = super(Extension, self).get_config_
schema() schema['path'] = config.String() return schema def setup(self, registry): from .actor import USBPlaylistsBackend registry.add('backend', USBPlaylistsBackend)
pengutronix/aiohttp-json-rpc
tests/test_forms.py
Python
apache-2.0
530
0
import pytest import logging @pytest.mark.asyncio async def test_confirmation(rpc_cont
ext): # setup rpc async def test_method(request): a = await request.confirm('just say yes!', timeou
t=1) logging.debug('a = %s', a) return a rpc_context.rpc.add_methods(('', test_method)) # setup client async def confirm(request): return True client = await rpc_context.make_client() client.add_methods(('', confirm)) # run test assert await client.call('test_me...
gabrielf10/Soles-pythonanywhere
productos/migrations/0004_auto_20141119_0117.py
Python
bsd-3-clause
496
0.002016
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('productos', '0003_auto_20141118_2241'), ]
operations = [ migrations.AlterField( model_name='imagenes', name='url', field=models.ImageField(upload_to=b'img', null=True, verbose_name=b'Im\xc3\xa1g
en', blank=True), preserve_default=True, ), ]
codeforkaohsiung/CabuKcgCrawler
CabuKcgCrawler/pipelines.py
Python
mit
294
0
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html class CabukcgcrawlerPipeline(object): def process_item(self, item, spider):
retur
n item
kevinkahn/softconsole
utils/utilfuncs.py
Python
apache-2.0
3,291
0.033728
""" This file holds utility functions that have no dependencies on other console code. Avoids import loops """ import webcolors def wc(clr, factor=0.0, layercolor=(255, 255, 255)): lc = webcolors.name_to_rgb(layercolor.lower()) if isinstance(layercolor, str) else layercolor if isinstance(clr, str): try: v = we...
return False if isinstance(v, bool): return v try: return v.lower() in ('true', 'on', 'yes') except Exception as e: print("Error1: {}".format(v)) def BoolFalseWord(v): if v is None: return True if isinstance(v, bool): return not v try: return v.lower() in ('false', 'off', 'no') except Exception as e: pr...
eys for easier code if len(args) == 1: temp = d[args[0]] #temp = getattr(d,args[0]) if isinstance(temp, str) and temp.isdigit(): temp = int(temp) else: try: temp = float(temp) except (ValueError, TypeError): pass return temp else: return TreeDict(d[args[0]], args[1:]) #return TreeDict(g...
eachiaradia/IOGeopaparazzi
io_geopaparazzi_provider.py
Python
gpl-3.0
2,828
0.020156
# -*- coding: utf-8 -*- """ /*************************************************************************** IOGeopaparazzi A QGIS plugin A plugin to import/export geodata from/to geopaparazzi Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/ ------------------- begin :...
m(),ExportSpatialiteAlgorithm(),ExportTil
esAlgorithm()] self.alglist = [ImportGpapAlgorithm(),ExportSpatialiteAlgorithm(),ExportTilesAlgorithm()] def unload(self): """ Unloads the provider. Any tear-down steps required by the provider should be implemented here. """ pass def loadAlgorithms(self): """ Loads all algorithms belonging to this ...
mitzvotech/honorroll
app/utils.py
Python
mit
2,178
0.002296
import csv import sys from models import * from datetime import datetime import codecs import json # from models import Attorney, Organization from flask_mail import Message def load_attorneys_from_csv(filename): with codecs.open(filename, mode='rb', encoding='utf-8') as csvfile: attorneys = [row for row ...
e new record... if check_new_email(attorney[3]): a = Attorney.objects.get(email_address=attorney[3]) else: a = Attorney() a.first_name = attorney[0] a.middle_initial = attorney[1]
a.last_name = attorney[2] a.email_address = attorney[3] a.organization_name = Organization.objects( organization_name=attorney[4] ).upsert_one(organization_name=attorney[4]) \ .organization_name ...
hazmalware/sharephish
taxiigenerator.py
Python
gpl-3.0
3,968
0.024698
import pycurl import cStringIO import random import HTMLParser def generate_TAXII_header(xml, ssl=True): headers = { "Content-Type": "application/xml", "Content-Length": str(len(xml)), "User-Agent": "TAXII Client Application", "Accept": "application/xml", "X-TAXII-Accept": "urn:taxii...
coding="UTF-8" ?>""" boilerplate = """xmlns:xsi="http
://www.w3.org/2001/XMLSchema-instance" xmlns:taxii_11="http://taxii.mitre.org/messages/taxii_xml_binding-1.1" xsi:schemaLocation="http://taxii.mitre.org/messages/taxii_xml_binding-1.1 http://taxii.mitre.org/messages/taxii_xml_binding-1.1" """ message_id = str(random.randint(345271,9999999999)) xml_poll = xmls...
Ormod/Diamond
src/diamond/handler/archive.py
Python
mit
2,195
0
# coding=utf-8 """ Write the collected stats to a locally stored log file. Rotate the log file every night and remove after 7 days. """ from Handler import Handler import logging import logging.handlers class ArchiveHandler(Handler): """ Implements the Handler abstract class, archiving data to a log file ...
'log_file': 'Path to the l
ogfile', 'days': 'How many days to store', 'encoding': '', 'propagate': 'Pass handled metrics to configured root logger', }) return config def get_default_config(self): """ Return the default config for the handler """ config = su...
felix9064/python
Demo/pcc/mpl_squares.py
Python
mit
606
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 绘制简单的折线图 import matplotlib.pyplot as plt input_values = list(range(1, 6)) squares = [x *
x for x in input_values] # 根据传递的参数来绘制出有意义的图形 plt.plot(input_values, squares, linewidth=3) # 设置图表的标题及标题的字体大小 plt.titl
e("Square Numbers", fontsize=14) # 给坐标轴加上标签 plt.xlabel("Value", fontsize=14) plt.ylabel("Square of Value", fontsize=14) # 设置刻度标记的大小 plt.tick_params(axis='both', labelsize=14) # 打开查看器,并显示绘制的图形 plt.show()
yupasik/python_training
bdd/contact_scenarios.py
Python
apache-2.0
325
0
fro
m pytest_bdd import scenario from .contact_steps import * @scenario("contacts.feature", "Add new contact") def test_add_new_contact(): pass @scenario("contacts.feature", "Delete a contact") def test_delete_contact(): pass @scen
ario("contacts.feature", "Modify a contact") def test_modify_contact(): pass
harun-emektar/webfs
tests/Test_WebFSStat.py
Python
apache-2.0
655
0.015267
from webfs import WebFSStat import st
at def Test_Basic(): fields = ('st_mode', 'st_ino', 'st_dev', 'st_nlink', 'st_uid', 'st_gid', 'st_size', 'st_atime', 'st_mtime', 'st_ctime') st = WebFSStat() print st.__dict__.keys() for field in fields: assert field in st.__dict__.keys(), 'field(%s) is not in members' % field ...
t.st_mode == stat.S_IFREG | 0444 def Test_IsDir(): st = WebFSStat() assert st.isDir() st = WebFSStat(False) assert not st.isDir()
enthought/pikos
pikos/live/ui/cprofile_view.py
Python
bsd-3-clause
8,716
0.000459
from operator import attrgetter from traits.api import Any, Int, Bool, on_trait_change, Dict, Button, Str, \ HasTraits, cached_property, Property, Event, Either, Float, Instance from traitsui.api import View, Item, UItem, VGroup, HGroup, Spring, \ TabularEditor, HSplit, Group, ModelView from traitsui.tabular_a...
ctTool class TableItem(HasTraits): id = Int filename = Str line_number = Any function_name = Str callcount = Int per_call = Float total_time = Float cumulative_time = Float def __init__(self, id, filename, line_number, function_name, callcount, per_call, total_t...
nction_name, line_number=line_number, callcount=callcount, per_call=per_call, total_time=total_time, cumulative_time=cumulative_time, )) super(TableItem, self).__init__(**kwargs) class CProfileTabularAdapter(TabularAdapter): columns = ( ...
Justasic/StackSmash
StackSmash/urls.py
Python
bsd-2-clause
3,146
0.00445
from django.conf.urls import patterns, include, url from django.shortcuts import redirect, render_to_response from django.template.context import RequestContext # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() # Just redirect / to /blog for now until I can # co...
sslicense(request): slicense = """ Cop
yright (c) 2012-2013 Justin Crawford <Justasic@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, th...
drnextgis/QGIS
python/plugins/processing/algs/qgis/BarPlot.py
Python
gpl-2.0
3,271
0.000611
# -*- coding: utf-8 -*- """ *************************************************************************** BarPlot.py --------------------- Date : January 2013 Copyright : (C) 2013 by Victor Olaya Email : volayaf at gmail dot com ******************************...
self.name, self.i18n_name = self.trAlgorithm('Bar plot') self.group, self.i18n_group = self.trAlgorithm('Graphics') self.addParameter(ParameterTable(self.INPUT, self.tr('Input table'))) self.addParameter(ParameterTableField(self.NAME_FIELD,
self.tr('Category name field'), self.INPUT, ParameterTableField.DATA_TYPE_NUMBER)) self.addParameter(ParameterTableField(self.VALUE_FIELD, ...
zhyu/PasswdManager
util.py
Python
gpl-3.0
1,732
0.011547
# -*- coding:utf-8 -*- from Crypto.Cipher import AES from Crypto.Hash import MD5 import binascii import urllib2 import string, random # algorithm MODE = AES.MODE_CBC def __getKeyObject(key): obj = AES.new(md5Encoding(key), MODE) return obj def md5E
ncoding(msg): ''' get md5 encrypted text @param msg: the plain text message ''' m = MD5.new() m.update(msg) return m.hexdigest() def getRandomString(length, optionList=['number', 'lower', 'upper', 'punc']): charPool = {'number' : string.digits, 'lower' : string.lowercas...
ey(key): pool = pool + charPool.get(key) s = [random.choice(pool) for _ in xrange(length)] return ''.join(s) def encrypt(key, msg): ''' Encrypt message using given password @param key: the master password @param msg: the plain text to be encrypted ''' obj = __getKeyObject(ke...
jgphpc/linux
python/0.py
Python
gpl-2.0
888
0.029279
#!/usr/bin/env
python quit() for iii in range(0,6): try: print(iii,iii/(4-iii)) except ZeroDivisionError as e: #print("wrong: i={} {}".format(iii,e.message)) print("wrong: i={} {}".format(iii,"nooooooo")) #else: # print("OK") finally: print("continue...") def pickkey(myl...
t(reverse=True) ;print(listjg) quit() x=3 #def myfL(a,b): # return [] def myf (a,b,*other): print(type(other)) print(sum(other)) c=sum(other) #return (a+b+other) #res=myf(5,2,1) ;print(res) #res=myf(a=5,b=2,c=1) ;print(res) #res=myf(b=2,a=5,c=1) ;print(res) #res=myf(a=5) ;print(res) #no res=myf(a...
eharney/cinder
cinder/api/contrib/volume_image_metadata.py
Python
apache-2.0
6,636
0
# Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
the given volume. :param context: the request context :param resp_volume_list: the response volume list :param image_metas: The image metadata to append, if None is provided it will be retrieved from the database. An empty dict means there...
l_id_list.append(vol['id']) if image_metas is None: try: image_metas = self.volume_api.get_list_volumes_image_metadata( context, vol_id_list) except Exception as e: LOG.debug('Get image metadata error: %s', e) return ...
philippjfr/bokeh
bokeh/core/templates.py
Python
bsd-3-clause
1,358
0
''' Provide Jinja2 templates used by Bokeh to embed Bokeh models (e.g. plots, widgets, layouts) in various ways. .. bokeh-jinja:: bokeh.core.templates.AUTOLOAD_JS .. bokeh-jinja:: bokeh.core.templates.AUTOLOAD_NB_JS .. bokeh-jinja:: bokeh.core.templates.AUTOLOAD_TAG .. bokeh-jinja:: bokeh.core.templates.CSS_RESOURCES ...
URCES .. bokeh-jinja:: bokeh.core.templates.NOTEBOOK_LOAD .. bokeh-jinja:: bokeh.core.templates.PLOT_DIV .. bokeh-jinja:: bokeh.core.templates.SCRIPT_TAG ''' from __future__ import absolute_import import json from jinja2 import Environment, PackageLoader, Markup _env = Environment(loader=PackageLoader('bokeh.core',...
env.get_template("css_resources.html") SCRIPT_TAG = _env.get_template("script_tag.html") PLOT_DIV = _env.get_template("plot_div.html") DOC_JS = _env.get_template("doc_js.js") FILE = _env.get_template("file.html") NOTEBOOK_LOAD = _env.get_template("notebook_load.html") AUTOLOAD_JS = _env.get_template("autoload_js....
mbayon/TFG-MachineLearning
venv/lib/python3.6/site-packages/scipy/ndimage/filters.py
Python
mit
52,520
0.00019
# Copyright (C) 2003-2005 Peter J. Verveer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following d...
def correlate1d(input, weights, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a one-dimensional correlation along the given axis. The lines of the array along the given axis are correlated with the given weights. Parameters ---------- %(input)s wei...
sequence of numbers. %(axis)s %(output)s %(mode)s %(cval)s %(origin)s Examples -------- >>> from scipy.ndimage import correlate1d >>> correlate1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3]) array([ 8, 26, 8, 12, 7, 28, 36, 9]) """ input = numpy.asarray(input) if nu...
zgbjgg/jun
priv/jun_enc_dec.py
Python
mit
1,427
0.005606
#!/usr/bin/env python # -*- coding: utf-8 -*- import pandas as pd import numpy as np from erlport.erlterms import Atom, List from erlport.erlang import set_encoder, set_decoder def setup_dtype(): set_encoder(dtype_encoder) set_decoder(dtype_decoder) return Atom(b'ok') def dtype_encoder(value): if isi...
value elif isinstance(value, list): return [dtype_encoder(v) for v in value] elif isinstance(value, tuple): nvalue = () for v in value: nvalue = nvalue + (dtype_encoder(v),) return nvalue else: try: return value.encode('utf-8') except: ...
f dtype_decoder(value): try: if isinstance(value, List): return [dtype_decoder(v) for v in value] elif isinstance(value, tuple): nvalue = () for v in value: nvalue = nvalue + (dtype_decoder(v),) return nvalue elif isinstance(val...
FRBs/FRB
frb/tests/test_eazy.py
Python
bsd-3-clause
2,608
0.003067
# Module to run tests on surveys # Most of these are *not* done with Travis yet # TEST_UNICODE_LITERALS import pytest import os import shutil import numpy as np from astropy.table import Table from frb.galaxies.frbgalaxy import FRBHost from frb.galaxies import eazy as frbeazy from frb.frb import FRB from distutils...
['NIRI_J'] = 21.75 + 0.91 photom['NIRI_J_err'] = 0.2 # host190613A = FRBHost(photom['ra'], photom['dec'], FRB.by_name('FRB20121102'
)) host190613A.parse_photom(photom) host190613A.name = 'G_TEST' return host190613A @eazy_exec def test_eazy(host_obj): if os.path.isdir(data_path('eazy')): shutil.rmtree(data_path('eazy')) os.mkdir(data_path('eazy')) # Generate frbeazy.eazy_input_files(host_obj.photom, data_path('e...
MarieVdS/ComboCode
__init__.py
Python
gpl-3.0
42
0
# -*- coding:
utf-8 -*- __all__
= ["cc"]
any1m1c/ipc20161
lista4/ipc_lista4.01.py
Python
apache-2.0
675
0.040299
# #Programa Lista 4, questão 1; #Felipe Henrique Bastos Costa - 1615310032; # # # # lista = []#lista vazia; cont1 = 0#contador do indice; cont2 = 1#contador da posição do numero, se é o primeiro, segundo etc; v = 5#representaria o len da lista; while(cont1 < v): x = int(input("Informe o %dº numero inteiro para c...
ebe #o numero do usuario lista.append(x)#o numero informado para x e colocado de
ntro da lista; cont1+=1#Os contadores estao cont2+=1#sendo incrementados; print("A lista de informada foi:\n%s"%lista)
Tinkerforge/brickv
src/brickv/bindings/bricklet_linear_poti_v2.py
Python
gpl-2.0
14,625
0.004239
# -*- coding: utf-8 -*- ############################################################# # This file was automatically generated on 2022-01-18. # # # # Python Bindings Version 2.1.29
# # # # If you have a bugfix for this file and want to commit it, # # please fix the bug in the generator. You can find a link # # to the generators git repository on tinkerforge.com # ################
############################################# from collections import namedtuple try: from .ip_connection import Device, IPConnection, Error, create_char, create_char_list, create_string, create_chunk_data except (ValueError, ImportError): from ip_connection import Device, IPConnection, Error, create_char, cr...
lemarcudal/sha_thedivision
test/mysite/webapp/forms.py
Python
apache-2.0
1,935
0.03876
from django import forms from .models import Post from django.contrib.auth import ( authenticate, get_user_model, login, logout, ) class PostForm(forms.ModelForm): # Post Thread View class Meta: model = Post fields = ['title','image', 'user','country','guide'] widgets = { 'guide' : forms.Textarea(attrs = ...
rname = self.cleaned_data.get("username") password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("Incorrect password or User! Please try again.") if not user.check_password(password): ...
turn super(UserLoginForm, self).clean(*args, **kwargs) #-------------------------------- class UserRegisterForm(forms.ModelForm): email = forms.EmailField(label = 'Email Address') password = forms.CharField(widget = forms.PasswordInput) class Meta: model = User fields = [ 'username', 'email', 'password...
ilblackdragon/django-modeltranslation
modeltranslation/settings.py
Python
bsd-3-clause
1,569
0.003187
# -*- coding: utf-8 -*- import sys from warnings import warn from django.conf import settings from django.core.exceptions import ImproperlyConfigured if hasattr(settings, 'MODELTRANSLATION_TRANSLATION_REGISTRY'): TRANSLATION_REGISTRY =\ getattr(settings, 'MODELTRANSLATION_TRANSLATION_REGISTRY', None) elif ha...
"MODELTRANSLATION_TRANSLATION_REGISTRY " "setting yet.") AVAILABLE_LANGUAGES = [l[0] for l in se
ttings.LANGUAGES] DEFAULT_LANGUAGE = getattr(settings, 'MODELTRANSLATION_DEFAULT_LANGUAGE', None) if DEFAULT_LANGUAGE and DEFAULT_LANGUAGE not in AVAILABLE_LANGUAGES: raise ImproperlyConfigured('MODELTRANSLATION_DEFAULT_LANGUAGE not ' 'in LANGUAGES setting.') elif not DEFAULT_LANGUAGE...
0vercl0k/rp
src/third_party/beaengine/tests/0f3a25.py
Python
mit
2,835
0.001411
#!/usr/bin/python # -*- coding: utf-8 -*- # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This progra...
epr(), 'vpternlogd ymm28, ymm16, ymmword ptr [r8], 11h') # EVEX.512.66.0F3A.W0 25 /r ib # vpternlogd zmm1{k1}{z}, zmm2, zmm3/m512/m32bcst, imm8 myEVEX = EVEX('EVEX.512.66.0F3A.W0') Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDi...
.Opcode, 0x25) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogd') assert_equal(myDisasm.repr(), 'vpternlogd zmm28, zmm16, zmmword ptr [r8], 11h') # EVEX.256.66.0F3A.W1 25 /r ib # vpternlogq ymm1{k1}{z}, ymm2, ymm3/m256/m64bcst, imm8 myEVEX = EVEX('EVEX.256.66.0F3A...
siosio/intellij-community
python/testData/codeInsight/mlcompletion/isInConditionSimpleElif.py
Python
apache-2.0
78
0.051282
var1 = bool(input()) v
ar2 = bool(input()) if var1: print(var2) elif v
<caret>
lebabouin/CouchPotatoServer-develop
couchpotato/core/providers/trailer/vftrailers/youtube_dl/extractor/hark.py
Python
gpl-3.0
1,526
0.003932
# -*- coding: latin-1 -*- import re import json from .common import InfoExtractor from ..utils import determine_ext class HarkIE(InfoExtractor): _VALID_URL = r'https?://www\.hark\.com/clips/(.+?)-.+' _TEST = { u'url': u'http://www.hark.com/clips/mmbzyhkgny-obama-beyond-the-afghan-theater-we-only-targ...
trikes, detainees at Guantanamo Bay prison facility, and American citizens who are terrorists.'
, u'duration': 11, } } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group(1) json_url = "http://www.hark.com/clips/%s.json" %(video_id) info_json = self._download_webpage(json_url, video_id) info = json.loads(inf...
davehorton/drachtio-server
deps/boost_1_77_0/tools/build/test/conditionals2.py
Python
mit
960
0
#!/usr/bin/python # Copyright 2003 Vladimir Prus # Distributed under the Boost Software License, Version 1
.0. # (See accompanying file LICENSE.txt or https://www.bfgroup.xyz/b2/LICENSE.txt) # Regression test: it was possible that due to evaluation of conditional # requirements, two different values of non-free features were present in a # property set. import BoostBuild t = BoostBuild.Tester() t.write("a.cpp", "") t.w...
feature : false true : propagated ; rule maker ( targets * : sources * : properties * ) { if <the_feature>false in $(properties) && <the_feature>true in $(properties) { EXIT "Oops, two different values of non-free feature" ; } CMD on $(targets) = [ common.file-creation-command ] ; } ac...
geotagx/geotagx-pybossa-archive
test/test_authentication.py
Python
agpl-3.0
1,229
0
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa is free software: you can redis
tri
bute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PyBossa is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implie...
ClusterHQ/libcloud
libcloud/compute/drivers/hostvirtual.py
Python
apache-2.0
10,709
0.000093
# 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 use ...
, 'generated', False): node.extra['password'] = auth.pass
word return node def reboot_node(self, node): params = {'force': 0, 'mbpkgid': node.id} result = self.connection.request( API_ROOT + '/cloud/server/reboot', data=json.dumps(params), method='POST').object return bool(result) def destroy_node...
shanot/imp
modules/isd/test/test_mc_WeightMover.py
Python
gpl-3.0
1,309
0
#!/usr/bin/env python # imp general import IMP import IMP.core # our project from IMP.isd import Weight from IMP.isd import WeightMover # unit testing framework import IMP.test class TestWeightMover(IMP.test.TestCase): """tests weight setup""" def setUp(self): IMP.test.TestCase.setUp(self) ...
self.w = Weight.setup_particle(IMP.Particle(self.m)) self.w.set_weights_are_optimize
d(True) self.w.add_weight() self.w.add_weight() self.wm = WeightMover(self.w, 0.1) self.mc = IMP.core.MonteCarlo(self.m) self.mc.set_scoring_function([]) self.mc.set_return_best(False) self.mc.set_kt(1.0) self.mc.add_mover(self.wm) def test_run(self):...
datamade/la-metro-councilmatic
lametro/admin.py
Python
mit
116
0.008621
from django.contrib import admin # import your models # Register your models here. # admin.site.register(YourMode
l)
yinchunlong/abelkhan-1
juggle/gen/csharp/tools.py
Python
mit
394
0.007614
# 2016-7-1 # build by qianqians # tools def gentypetocsharp(typestr): if typestr == 'int': return 'Int
64' elif typestr == 'string': return 'String' elif typestr == 'array': return 'ArrayList' elif typestr == 'float': return 'Double' elif typestr == 'boo
l': return 'Boolean' elif typestr == 'table': return 'Hashtable'
ThiefMaster/indico
indico/modules/events/timetable/util.py
Python
mit
16,943
0.003305
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from collections import defaultdict from operator import attrgetter from flask import render_template, se...
lter( Event.category_chain_overlaps(categ_ids), ~Event.is_deleted, ((Event.timetable_entries.any(dates_overlap(TimetableEntry))) | (Event.query.exists().where( Event.happens_between(day_start, day_end) & (Event.id...
.order_by(Event.id, TimetableEntry.start_dt) .join(TimetableEntry, (TimetableEntry.event_id == Event.id) & (dates_overlap(TimetableEntry)), isouter=True)) def _query_blocks(event_ids, dates_overlap, detail_level='session'): options = [subqueryload('session').joined...
sebastic/NLExtract
bag/src/loggui.py
Python
gpl-3.0
2,159
0.003705
#------------------------------------------------------------------------------ # Naam: libLog.py # Omschrijving: Generieke functies voor logging binnen BAG Extract+ # Auteur: Matthijs van der De
ijl # Auteur: Just van den Broecke - porting naar NLExtract (2015) # # Versie: 1.3 # - foutafhandeling verbeterd # Datum: 16 december 2009 # # Versie: 1.2 # Datum: 24 november 2009 # # Ministerie van Volkshuisvesting, Ruimtelijke Ordening en Milieubeheer #------------------...
-------- import wx # Simple logscherm: tekst in tekstpanel class LogScherm: def __init__(self, text_ctrl): self.text_ctrl = text_ctrl def __call__(self, tekst): self.schrijf(tekst) def start(self): i = self.text_ctrl.GetNumberOfLines() self.text_ctrl.Clear() while...
ssdxiao/kimchi
src/kimchi/vnc.py
Python
lgpl-2.1
1,961
0.00051
#!/usr/bin/python # # Project Kimchi # # Copyright IBM, Corp. 2013 # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your opti
on) any later version. # # This library 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 PURPOS
E. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA import errno import os import sub...
zuntrax/schedule-ng
fahrplan/model/schedule.py
Python
gpl-3.0
3,835
0.001304
import logging from datetime import date as _date, timedelta from typing import Dict, List from fahrplan.exception import FahrplanError from fahrplan.xml import XmlWriter, XmlSerializable from .conference import Conference from .day import Day from .event import Event from .room import Room log = logging.getLogger(...
a room to the days given in day_filter, or all days. :param name: Name of the room to be added. :param day_filter
: List of day indices to create the room for. If empty, use all days. :return: None """ for day in self.days.values(): if not day_filter or day.index in day_filter: day.add_room(Room(name)) def add_event(self, day: int, room: str, event: Event): self.days...