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
dalgr/svtplay-dl
lib/svtplay_dl/subtitle/__init__.py
Python
mit
10,611
0.002639
import xml.etree.ElementTree as ET import json import re from svtplay_dl.log import log from svtplay_dl.utils import is_py2, is_py3, decode_html_entities, HTTP from svtplay_dl.utils.io import StringIO from svtplay_dl.output import output from requests import __build__ as re
quests_version import platform class subtitle(object): def __init__(self, options, subtype, url, subfix = None): self.url = url self.subtitle = None self.options = options self.subtype = subtype self.http = HTTP(options) self.su
bfix = subfix self.bom = False def download(self): subdata = self.http.request("get", self.url, cookies=self.options.cookies) if not subdata or (subdata.status_code != 200): log.warning("Can't download subtitle file") return data = None if "mtgx" in ...
AnshulYADAV007/Lean
Algorithm.Python/FractionalQuantityRegressionAlgorithm.py
Python
apache-2.0
3,139
0.008288
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # 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 Lice...
ry> ### Regression algorithm for fractional forex pair ### </summary> ### <meta name="tag" content="using data" /> ### <meta name="tag" content="trading and orders" /> ### <meta name="tag" content="regression test" /> class FractionalQuantityRegressionAlgorithm(QCAlgorithm): def Initialize(self): self.Set...
.GDAX, AccountType.Cash) self.SetTimeZone(DateTimeZone.Utc) security = self.AddSecurity(SecurityType.Crypto, "BTCUSD", Resolution.Daily, Market.GDAX, False, 3.3, True) ### The default buying power model for the Crypto security type is now CashBuyingPowerModel. ### Since this test algo...
richlewis42/scikit-chem
skchem/test/test_core/test_base.py
Python
bsd-3-clause
2,637
0.000758
#! /usr/bin/env python # # Copyright (C) 2016 Rich Lewis <rl403@cam.ac.uk> # License: 3-clause BSD import pytest import numpy as np from ...core import Mol, Atom @pytest.fixture def m(): return Mol.from_smiles('CC') @pytest.fixture def mk(m): m.props['test'] = 'value' return m @pytest.fixture def ma(m...
def test
_clear(mk): mk.props.clear() assert len(mk.props) == 0 def test_clear2(mkl): mkl.props.clear() assert len(mkl.props) == 0 def test_delete(mkl): del mkl.props['test'] assert len(mkl.props) == 2 def test_int_prop(m): m.props['test'] = 1 assert m.props['test'] == 1 def test_float_pr...
kuke/models
fluid/PaddleCV/metric_learning/losses/npairsloss.py
Python
apache-2.0
2,981
0.016437
from __future__ import absolute_import from __future__ import division from __future__ import print_function import paddle.fluid as fluid from utility import get_gpu_num class NpairsLoss(): def __init__(self, train_batch_size = 160, samples_each_class=2, reg_l...
luid.layers.softmax(input=similarity_matrix, use_cudnn=False) xentloss = fluid.layers.cross_entropy(input=out, label=label_remapped, soft_label=True)
xentloss = fluid.layers.mean(x=xentloss) reg = fluid.layers.reduce_mean(fluid.layers.reduce_sum(fluid.layers.square(input), dim=1)) l2loss = 0.5 * reg_lambda * reg return xentloss + l2loss
pystockhub/pykiwoom
setup.py
Python
mit
401
0.069825
from
setuptools import setup setup( name = 'pykiwoom', version = '0.0.2', description = 'python module for Kiwoom Open API+', url = 'https://github.com/pystockhub/pykiwoom', author = 'brayden.jo', author_email = 'pystock@outlook.com', license ...
aleju/keras
keras/utils/plotting_utils.py
Python
mit
11,976
0.000084
from __future__ import absolute_import from __future__ import print_function import matplotlib.pyplot as plt import numpy as np from six.moves import range class PlotGenerator(object): """Class to plot training and validation loss and accuracy. Usually not used directly, but instead together with callbacks.P...
tage is relative to the current epoch.
E.g. if epoch is 100 and this value is 0.2, then the regression will be calculated for 20 values in the future. poly_backward_perc: Similar to poly_forward_perc. Percentage of the data basis to use in order to calculate the regression. E.g. if...
enesates/GA_8Queens
GA_8Queens.py
Python
gpl-3.0
6,582
0.010787
''' Solution for Eight Queens Problem Using the Genetic Algorithms 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 la...
success = self.mutation(second_chrom, next_generation)
return success def mutation(self, chromosome, next_generation): for i in range(0,8): if random.random() < self.prob_mutation: chromosome.queens[i] = random.randint(0, 7) chromosome.fitness = self.calc_fitness(chromosome.queens) ...
GNOME/orca
src/orca/orca_gui_prefs.py
Python
lgpl-2.1
142,434
0.001425
# Orca # # Copyright 2005-2009 Sun Microsystems Inc. # # 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 option) any later version. # # This...
GObject.TYPE_STRING, # Handler name GObject.TYPE_STRING, # Human Readable Description GObject.TYPE_STRING, # Modifier mask 1 GObject.TYPE_STRING, # Used Modifiers 1 GObject.TYPE_STRING, # Modifier key name 1 GObject.TYPE_STRING, # Click count 1...
GObject.TYPE_STRING, # Text of the Key Binding Shown 1 GObject.TYPE_BOOLEAN, # Key Modified by User GObject.TYPE_BOOLEAN) # Row with fields editable or not self.planeCellRendererText = Gtk.CellRendererText() self.cellRendererText = Gtk.CellRendererText() self.cellRend...
hzlf/openbroadcast
website/__filer/server/urls.py
Python
gpl-3.0
449
0.008909
#-*- coding: utf-8 -*- from django.conf.urls.defaults import patterns, url from filer import settings as filer
_settings urlpatterns = patterns('filer.server.views', url(r'^' + filer_settings.FILER_PRIVATEMEDIA_STORAGE.base_url.lstrip('/') + r'(?P<path>.*)/$', 'serve_protected_file',), url(r'^' + filer_settings.FILER_PRIVATEMEDIA_THUMBNAIL_STORAGE.base_url.lstrip('/') + r'(?P<path>.*)$', 'serve_protect...
thumbnail',), )
edisonlz/fruit
web_project/base/site-packages/django/forms/forms.py
Python
apache-2.0
23,724
0.003204
""" Form classes """ from __future__ import absolute_import, unicode_literals import copy import warnings from django.core.exceptions import ValidationError from django.forms.fields import Field, FileField from django.forms.util import flatatt, ErrorDict, ErrorList from django.forms.widgets import Media, media_prope...
ld, name) @property def errors(self): "Returns an ErrorDict for the data provided for the form" if self._
errors is None: self.full_clean() return self._errors def is_valid(self): """ Returns True if the form has no errors. Otherwise, False. If errors are being ignored, returns False. """ return self.is_bound and not bool(self.errors) def add_prefix(self...
lukeiwanski/tensorflow
tensorflow/python/keras/estimator/__init__.py
Python
apache-2.0
1,873
0.004271
# 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
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. # ======================================...
import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.util.tf_export import tf_export # Keras has undeclared dependency on tensorflow/estimator:estimator_py. # As long as you depend //third_party/py/tensorflow:tensorflow target # everything will work as n...
ride90/Booktype
lib/booki/editor/management/commands/confdel.py
Python
agpl-3.0
1,610
0.002484
# This file is part of Booktype. # Copyright (c) 2012 Aleksandar Erkalovic <aleksandar.erkalovic@sourcefabric.org> # # Booktype 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 Li...
If not, see <http://www.gnu.org/licenses/>. from django.core.management.base import BaseCommand, Co
mmandError from django.conf import settings from booktype.utils import config class Command(BaseCommand): help = "Delete configuration variable." requires_model_validation = False def add_arguments(self, parser): parser.add_argument("<key>", nargs=1, type=str) def handle(self, *args, **opti...
obi-two/Rebelion
data/scripts/templates/object/building/poi/shared_tatooine_spicefiend_medium2.py
Python
mit
458
0.045852
#### NOTICE: THIS FILE IS AUTOGENERATED ###
# MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Buildin
g() result.template = "object/building/poi/shared_tatooine_spicefiend_medium2.iff" result.attribute_template_id = -1 result.stfName("poi_n","base_poi_building") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
kartikgupta0909/build-mozharness
configs/unittests/win_unittest.py
Python
mpl-2.0
7,351
0.002721
import os import sys # OS Specifics ABS_WORK_DIR = os.path.join(os.getcwd(), "build") BINARY_PATH = os.path.join(ABS_WORK_DIR, "firefox", "firefox.exe") INSTALLER_PATH = os.path.join(ABS_WORK_DIR, "installer.zip") XPCSHELL_NAME = 'xpcshell.exe' EXE_SUFFIX = '.exe' DISABLE_SCREEN_SAVER = False ADJUST_MOUSE_AND_SCREEN =...
te=devtools"], "mochitest-devtools-chrome-1": ["--browser-chrome", "--subsuite=devtools", "--chunk-by-dir=5", "
--total-chunks=3", "--this-chunk=1"], "mochitest-devtools-chrome-2": ["--browser-chrome", "--subsuite=devtools", "--chunk-by-dir=5", "--total-chunks=3", "--this-chunk=2"], "mochitest-devtools-chrome-3": ["--browser-chrome", "--subsuite=devtools", "--chunk-by-dir=5", "--total-chunks=3", "--this-chunk=3"]...
mzoellerGit/openstack
scripts/launchpad/common.py
Python
mit
1,002
0.003992
#!/usr/bin/env python # # Common client code # # Copyright 2016 Markus Zoeller import os from launchpadlib.launchpad import Launchpad def get_project_client(project_name): cachedir = os.path.expanduser("~/.launchpadlib/cache/") if not os.path.exists(cachedir): os.makedirs(cachedir, 0o700) launchp...
on.split('\n')[1:]) class BugReport(object): def __init__(self, link, title, a
ge): self.link = link self.title = title.encode('ascii', 'replace') self.age = age def __str__(self): data = {'link': self.link, 'title': self.title, 'age': self.age} return "{link} ({title}) - ({age} days)".format(**data) def __cmp__(self, other): return cmp(se...
nagaozen/my-os-customizations
home/nagaozen/gedit-plugins-2.30.1/usr/local/share/gedit-2/plugins/commander/modules/goto.py
Python
gpl-3.0
1,028
0.025292
"""Goto specific places in the document""" import os import commander.commands as commands import commander.commands.completion import commander.commands.result import commander.commands.exceptions __commander_module__ = True def __default__(view, line, column=1): """Goto line number""" buf = view.get_buffer() i...
: linnum = int(line) - 1 column = int(column) - 1 except ValueError: raise comma
nder.commands.exceptions.Execute('Please specify a valid line number') linnum = min(max(0, linnum), buf.get_line_count() - 1) citer = buf.get_iter_at_line(linnum) column = min(max(0, column), citer.get_chars_in_line() - 1) citer = buf.get_iter_at_line(linnum) citer.forward_chars(column) buf.place_cursor(citer...
Duoxilian/home-assistant
tests/components/test_ffmpeg.py
Python
mit
8,114
0.000123
"""The tests for Home Assistant ffmpeg.""" import asyncio from unittest.mock import patch, MagicMock import homeassistant.components.ffmpeg as ffmpeg from homeassistant.bootstrap import setup_component from homeassistant.util.async import ( run_callback_threadsafe, run_coroutine_threadsafe) from tests.common impo...
assert run_coroutine_threadsafe( manager.async_run_test("blabalblabla"), self.hass.loop).result() assert mock_test.called assert mock_test.call_count == 1 assert len(manager._cache) == 1 assert manager.
_cache['blabalblabla'] @patch('haffmpeg.Test.run_test', return_value=mock_coro(False)) def test_setup_component_test_run_test_test_fail(self, mock_test): """Setup ffmpeg component test run_test.""" with assert_setup_component(2): setup_component(self.hass, ffmpeg.DOMAIN, ...
N-Parsons/exercism-python
exercises/isogram/isogram_test.py
Python
mit
1,889
0
import unittest from isogram import is_isogram # Tests adapted from `problem-specifications//canonical-data.json` @ v1.7.0 class IsogramTest(unittest.TestCase): def test_empty_string(self): self.assertIs(is_isogram(""), True) def test_isogram_with_only_lower_case_characters(self): self.ass...
lf): self.assertIs(is_isogram("six-year-old"), True) def test_made_up_name_that_is_an_isogram(self): self.assertIs(is_isogram("Emily Jung Schwartzkopf"), True) def test_duplicated_character_in_the_middle(self): self.assertIs(is_isogram("accentor"), False) def test_same_first_and_l
ast_characters(self): self.assertIs(is_isogram("angola"), False) # Additional tests for this track def test_isogram_with_duplicated_letter_and_nonletter_character(self): self.assertIs(is_isogram("Aleph Bot Chap"), False) if __name__ == '__main__': unittest.main()
hypermindr/barbante
barbante/api/tests/test_generate_product_templates_tfidf_api.py
Python
mit
603
0.001658
""" Tests barbante.api.generate_product_templates_tfidf. """ import json import nose.tools import barbante.api.generate_product_templates_tfidf as script import barbante.utils.logging as
barbante_logging import barbante.tests as tests log = barbante_logging.get_logger(__name__) def test_script(): """ Tests a call to script barbante.api.generate_product_templates_tfidf. """ result = script.main(
[tests.TEST_ENV]) log.debug(result) result_json = json.dumps(result) nose.tools.ok_(result_json) # a well-formed json is enough if __name__ == '__main__': test_script()
krzysztofwos/BitcoinUnlimited
qa/rpc-tests/merkle_blocks.py
Python
mit
4,042
0.004453
#!/usr/bin/env python3 # Copyright (c) 2014-2015 The Bitcoin Core developers # Copyright (c) 2015-2017 The Bitcoin Unlimited developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test merkleblock fetch/validation # from ...
ework): def setup_chain(self): print("Initializing test directory "+self.options.tmpdir) initialize_chain_clean(self.options.tmpdir, 4) def setup_network(self): self.nodes = [] # Nodes 0/1 are "wallet" nodes self.nodes.append(start_node(0, self.options.tmpdir, ["-debug"...
self.nodes.append(start_node(3, self.options.tmpdir, ["-debug", "-txindex"])) connect_nodes(self.nodes[0], 1) connect_nodes(self.nodes[0], 2) connect_nodes(self.nodes[0], 3) self.is_network_split = False self.sync_all() def run_test(self): print("Mining blo...
gurpinars/hash-generator
generator.py
Python
gpl-3.0
971
0.013388
import hashlib class Generator(object): """ >>> generator = Generator() >>> generator.md5('string'
) Class including hash genarating methods. """ def __init__(self,ui): self.ui = ui def md5(self,text): self.hash = hashlib.md5(text).hexdigest() self.ui.textEdit.setText(self.hash) def sha(self,text): self.hash = hashlib.sha1(text).hexdigest() ...
f.hash = hashlib.sha224(text).hexdigest() self.ui.textEdit.setText(self.hash) def sha256(self,text): self.hash = hashlib.sha256(text).hexdigest() self.ui.textEdit.setText(self.hash) def sha384(self,text): self.hash = hashlib.sha384(text).hexdigest() self.ui.textEdit.set...
onlytiancai/warning-agent
src/senders/mail.py
Python
mit
2,060
0.008342
# -*- coding: utf-8 -*- import logging import smtplib from email.mime.text import MIMEText from datetime import datetime last_hour = datetime.now().strftime('%H') last_hour_send_count = 0 class Sender(object): 'Sender插件类,必须使用Sender作为类名' def __init__(self, options): '插件初
始化方法,options是插件配置数据' self.options = options def send(self, title, content, level=0, cate='default', host='default', appname='default'): try: global last_hour, last_hour_send_count this_hour = datetime.now().strftime('%H') logging.info('begin sender.mail send:%s',...
_max_send > 10: # 防止无节操报警 one_hour_max_send = 10 if this_hour == last_hour and last_hour_send_count >= one_hour_max_send: logging.info('sender.mail not send one_hour_max_send :%s %s', title, last_hour_send_count) return # 设置最后一次报警的小时 i...
plotly/python-api
packages/python/plotly/plotly/validators/scattermapbox/_lonsrc.py
Python
mit
441
0.002268
import _plotly_utils.basevalidators class
LonsrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(self, plotly_name="lonsrc", parent_name="scattermapbox", **kwargs): super(LonsrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs )
diegopettengill/multiuserblog
handlers/logout.py
Python
mit
168
0
from app import Handl
er from handlers.auth import Auth class LogoutHandler(Handler): def get(self): Auth.logout(self.response) self.red
irect("/")
googlearchive/simian
src/simian/mac/admin/summary.py
Python
apache-2.0
10,096
0.008023
#!/usr/bin/env python # # Copyright 2018 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 require...
_PROTECTION = False def get(self):
"""Summary get handler.""" report_type = self.request.get('filter-type') report_filter = self.request.get('filter') self_report_username = auth.DoUserAuthWithSelfReportFallback() if self_report_username: report_type = 'owner' report_filter = self_report_username if report_type and ...
wronk/mne-python
examples/decoding/plot_decoding_xdawn_eeg.py
Python
bsd-3-clause
3,406
0
""" ============================= XDAWN Decoding From EEG data ============================= ERP decoding with Xdawn. For each event type, a set of spatial Xdawn filters are trained and applied on the signal. Channels are concatenated and rescaled to create features vectors that will be fed into a Logistic Regression...
3 event_id = dict(aud_l=1, aud_r=2, vis_l=3, vis_r=4) # Se
tup for reading the raw data raw = io.read_raw_fif(raw_fname, preload=True) raw.filter(1, 20, method='iir') events = read_events(event_fname) picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude='bads') epochs = Epochs(raw, events, event_id, tmin, tmax, proj=False, ...
klahnakoski/ActiveData-ETL
activedata_etl/transforms/fx_test_to_normalized.py
Python
mpl-2.0
2,201
0.004543
# encoding: utf-8 # # 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 thi
s file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Contact: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import division from __future__ import unicode_literals from activedata_etl import key2etl, etl2key from mo_dots import Data, wrap, set_default, Null from mo_logs import machine
_metadata, strings from mo_times import Date from activedata_etl.transforms.unittest_logs_to_sink import accumulate_logs DEBUG = False DEBUG_SHOW_LINE = True DEBUG_SHOW_NO_LOG = False PARSE_TRY = True SINGLE_URL = None def process(source_key, source, destination, resources, please_stop=None): test_results = acc...
cantora/mozz
mozz/location.py
Python
gpl-3.0
2,939
0.038108
import struct import mozz.util class Base(object): def size(self): raise Exception("not implemented") def value(self, host): ''' return value at location in native endian format ''' raise Exce
ption("not implemented") def set(self, host, data): raise Exception("not im
plemented") class Register(Base): def __init__(self, name, size): ''' specify size in bits ''' self._name = name self._size = size # in bits def name(self): return self._name def size(self): return self._size def __str__(self): return self._name def value(self, host): v = host.inferior().reg...
maxis1314/pyutils
crawler/bayes_fenci.py
Python
apache-2.0
1,170
0.017949
#encoding=utf-8 import sys from numpy import * from tools.MysqlBase import * import jieba from os import listdir,mkdir,path,makedirs import hashlib import base64 import pickle import re reload(sys) sys.setdefaultencoding( "utf-8" ) db = MysqlBase('python') list_of_all_the_lines = db.query('select * from blog wher...
e64.b64encode(tags[0]) dirname = hashlib.md5(tags[0]).hexdigest() mapfile[dirname]=tags[0] if not path.exists(u'originSample/'+dirname): makedirs(u'originSample/'+dirname) wfil
e_object = open('originSample/'+dirname+'/'+str(record[0])+'.txt', 'w') wfile_object.write(line) wfile_object.close() with open('md5_catname', 'w') as f: # open file with write-mode picklestring = pickle.dump(mapfile, f) # serialize and save object
davidcasterton/PyMarchMadness
docs/conf.py
Python
gpl-3.0
8,832
0.005435
# -*- coding: utf-8 -*- # # PyMarchMadness documentation build configuration file, created by # sphinx-quickstart on Thu Mar 6 16:41:14 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file...
2, ratio='compress') inheritance_node_attrs = dict(shape='ellipse', fontsize=12, height=0.75, color='dodgerblue1', style='filled') # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '....
cument. master_doc = 'index' # General information about the project. project = u'PyMarchMadness' copyright = u'2014, David Casterton' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The s...
mrooney/wxbanker
wxbanker/bankobjects/transactionlist.py
Python
gpl-3.0
1,282
0.00078
#!/usr/bin/env python # # https://launchpad.net/wxbanker # transactionlist.py: Copyright 2007-2010 Mike Rooney <mrooney@ubuntu.com> # # This fi
le is part of wxBanker. # # wxBanker 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. # # wxBanker is distributed in the ...
GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with wxBanker. If not, see <http://www.gnu.org/licenses/>. class TransactionList(list): def __init__(self, items=None): # list does not understand items=None apparently. ...
Lysxia/dissemin
backend/testoai.py
Python
agpl-3.0
8,574
0.003965
# -*- encoding: utf-8 -*- # Dissemin: open access policy enforcement tool # Copyright (C) 2014 Antonin Delpeuch # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License # as published by the Free Software Foundation; either version 2 # of th...
rprint()) def test_create_already_existing(self): """ Creation of a paper from an OAI record, when the exact same OAI record already exists. """ # TODO we could repeat this for various papers oai_id ='ftccsdartic:oai:hal.archives-ouvertes.fr:hal-00830421' ...
# Create it again! new_paper = self.create(oai_id, 'base_dc') # It's the same thing! self.assertEqual(new_paper, hal_paper) self.assertSetEqual(set(new_paper.oairecords), set(hal_paper.oairecords)) self.assertListEqual(new_paper.bare_author_names(), ...
compufreakjosh/add-delete-routing
python/models.py
Python
mit
964
0.005187
import flask.ext.restless import flask.ext.sqlalchemy import datetime app = flask.Flask(__name__) app.config['DEBUG'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = flask.ext.sqlalchemy.SQLAlchemy(app) c
lass User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=False) email = db.Column(db.String(120), unique=False) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<...
ser %r>' % self.username # db.create_all() # admin = User('admin', 'admin@example.com') # guest = User('guest', 'guest@example.com') # db.session.add(admin) # db.session.add(guest) # db.session.commit() manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db) manager.create_api(User, ...
mesonbuild/meson
docs/refman/loaderpickle.py
Python
apache-2.0
629
0.00159
# SPDX-License-Identifer
: Apache-2.0 # Copyright 2021 The Meson development team from pathlib import Path import pickle from .loaderbase import LoaderBase from .model import ReferenceManual
class LoaderPickle(LoaderBase): def __init__(self, in_file: Path) -> None: super().__init__() self.in_file = in_file def load_impl(self) -> ReferenceManual: res = pickle.loads(self.in_file.read_bytes()) assert isinstance(res, ReferenceManual) return res # Assume tha...
geomapping/raspi-python
Schleifenwechsel.py
Python
mit
643
0.009331
from sense_hat import SenseHat import pygame from pygame.locals import * from time import sleep py
game.init() pygame.display.set_mode((1,1)) sense = SenseHat() loop = True i = 0 while i < 25: i += 1 while loop == True: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_DOWN: loop = False pr
int("1") sleep(1) while loop == False: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_UP: loop = True print("2") sleep(1)
eduardoftoliveira/qt_scripts
scripts/draw_PES.py
Python
gpl-3.0
3,836
0.007821
#!/usr/bin/env python import matplotlib as mpl from matplotlib import pyplot as plt import argparse def add_adiabatic_map_to_axis(axis, style, energies, color): """ add single set of energies to plot """ # Energy horizontal decks x = style['START'] for energy in energies: axis.plot([x, x+styl...
olors args.colors += 'k' * missing_colors return args def makelabels(N): """ Make automatic labels: TS1, INT1, TS2, etc..""" labels = ['R']
n_ts = N / 2 n_i = (N - 2) / 2 n_i = n_i * (n_i > 0) # becomes zero if negative for i in range(n_ts + n_i): if i % 2: labels.append('INT%d' % (i/2+1)) else: labels.append('TS%d' % (i/2+1)) if N % 2 and N >= 3: labels.append('P') return labels ...
kyper-data/python-highcharts
examples/highmaps/map-drilldown.py
Python
mit
5,831
0.00686
# -*- coding: utf-8 -*- """ Highmaps Demos Drilldown: http://www.highcharts.com/maps/demo/map-drilldown """ from highcharts import Highmap from highcharts.highmaps.highmap_helper import jsonp_loader, js_map_loader, geojson_handler """ Drilldown is a techique to present data in different detail level. This example i...
.point.name); fail = setTimeout(function () {
chart.hideLoading(); }, 1000); } }, 3000); chart.showLoading('<i class="icon-spinner icon-s...
jobovy/galpy
galpy/df/kingdf.py
Python
bsd-3-clause
6,898
0.018556
# Class that represents a King DF import numpy from scipy import special, integrate, interpolate from ..util import conversion from .df import df from .sphericaldf import isotropicsphericaldf _FOURPI= 4.*numpy.pi _TWOOVERSQRTPI= 2./numpy.sqrt(numpy.pi) class kingdf(isotropicsphericaldf): """Class that represents ...
cale*self._scalefree_kdf._cumul_mass/self.M, self._radius_scale*self._scalefree_kdf._r, k=3) # Setup velocity DF interpolator for velocity sampling here self._rmin_sampling= 0. self._v_vesc_pvr_interpolator= self._make_pvr_interpolator(\ ...
ns(r/self._radius_scale)\ *self._density_scale def fE(self,E): out= numpy.zeros(numpy.atleast_1d(E).shape) varE= self._potInf-E if numpy.sum(varE > 0.) > 0: out[varE > 0.]= (numpy.exp(varE[varE > 0.]/self._sigma2)-1.)\ *(2.*numpy.pi*self._sigma2)**-1....
jdowns/play2048
game.py
Python
mit
2,669
0.005995
def double(val): if val is None: return None return val * 2 def merge(tiles): if tiles[0] == tiles[1]: tiles[0], tiles[1] = double(tiles[0]), None if tiles[1] == tiles[2]: tiles[1], tiles[2] = double(tiles[1]), None if tiles[2] == tiles[3]: tiles[2], tiles[3] = doubl...
[None, None, None, None], [None, None, None, No
ne]] else: self.board = board def move_left(self): row_1 = merge(self.board[0]) row_2 = merge(self.board[1]) row_3 = merge(self.board[2]) row_4 = merge(self.board[3]) return [row_1, row_2, row_3, row_4] def move_right(self): row_1 = merge...
tahsmith/pycmake
cmake/arguments/argument.py
Python
mit
1,893
0.001585
__author__ = 'tahsmith' from operator import add import os from cmake.context import Context from functo
ols import reduce class VariableReference(object): def __init__(self, tokens): self.name = tokens[0] def evaluate(self, ctx): """ Perform any nested interpola
tions and give the value of the variable, or None. :type ctx: Context """ return ctx.variable_lookup(self.name.evaluate(ctx)) class EnvironmentVariableReference(object): def __init__(self, tokens): self.name = tokens def evaluate(self, ctx): """ Perform any nes...
showell/zulip
zerver/lib/onboarding.py
Python
apache-2.0
7,591
0.003425
from typing import Any, Dict, List, MutableMapping from django.conf import settings from django.db.models import Count from django.utils.translation import ugettext as _ from zerver.lib.actions import ( create_users, do_add_reaction, do_send_messages, internal_prep_stream_message_by_name, internal...
n" "\n" + _("Feel free to continue using this space to practice your new messaging " "skills. Or, try clicking on some of the stream names to your left!") ) internal_send_private_message( message['realm'], welcome_bot, message['message'].sender, content)...
ages(realm: Realm) -> None: welcome_bot = get_system_bot(settings.WELCOME_BOT) # Make sure each stream created in the realm creation process has at least one message below # Order corresponds to the ordering of the streams on the left sidebar, to make the initial Home # view slightly less overwhelming ...
xen0n/gingerprawn
gingerprawn/api/update/updlist.py
Python
gpl-3.0
840
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # gingerprawn / api.update / update list manager # # Copyright (C) 2011 Wang Xuerui <idontknw.wang@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 ...
=utf
-8
JFriel/honours_project
venv/lib/python2.7/site-packages/numpy/distutils/command/config.py
Python
gpl-3.0
17,986
0.002168
# Added Fortran compiler support to config. Currently useful only for # try_compile call. try_run works but is untested for most of Fortran # compilers (they must define linker_exe first). # Pearu Peterson from __future__ import division, absolute_import, print_function import os, signal import warnings import sys fr...
if fileexists: continue # make g77-compiled static libs available to MSVC fileexists = False for libdir in l
ibrary_dirs: libfile = os.path.join(libdir, 'lib%s.a' % (libname)) if os.path.isfile(libfile): # copy libname.a file to name.lib so that MSVC linker # can find it libfile2 = os.path.join(libdir, '%s.lib' % (l...
OCA/l10n-brazil
l10n_br_fiscal/models/cest.py
Python
agpl-3.0
2,047
0.000489
# Copyright (C) 2013 Renato Lima - Akretion <renato.lima@akretion.com.br> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import api, fields, models from ..constants.fiscal import CEST_SEGMENT from ..tools import misc class Cest(models.Model): _name = "l10n_br_fiscal.cest" _inher...
nv.context.get("do_not_write") if "ncms" in values.keys() and not do_not_write: self.with_context(do_not_write=True).action_search_ncms() return write_super def action_search_ncms(self): ncm = self.env["l10n_br_fiscal.ncm"] for r in self: if r.ncms: ...
= misc.domain_field_codes(field_codes=r.ncms) r.ncm_ids = ncm.search(domain)
dawran6/zulip
puppet/zulip/files/postgresql/pg_backup_and_purge.py
Python
apache-2.0
1,945
0.001542
#!/usr/bin/env python from __future__ import print_function import sys import glob import subprocess import sys import logging import dateutil.parser import pytz from datetime import datetime, timedelta if False: from typing import Dict, List logging.basicConfig(format="%(asctime)s %(levelname)s: %(message)s") l...
logger.error("Could not invoke %s\nstdout: %s\nstderror: %s" % (args[0], stdout, stderr)) sys.exit(1) return stdout # Only run if we're the master if run(['psql', '-t', '-c', 'se
lect pg_is_in_recovery()']).strip() != 'f': sys.exit(0) pg_data_paths = glob.glob('/var/lib/postgresql/*/main') if len(pg_data_paths) != 1: print("Postgres installation is not unique: %s" % (pg_data_paths,)) sys.exit(1) pg_data_path = pg_data_paths[0] run(['env-wal-e', 'backup-push', pg_data_path]) now = ...
scraperwiki/spreadsheet-download-tool
pyexcelerate/Worksheet.py
Python
bsd-2-clause
4,340
0.031106
from . import Range from . import Style from . import Format from .DataTypes import DataTypes from . import six from datetime import datetime from safe_xml import replace_invalid_xml_chars class Worksheet(object): def __init__(self, name, workbook, data=None): self._columns = 0 # cache this for speed self._name =...
styles[x]: self.set_cell_style(x, y, Style.Style()) return self._styles[x][y] def set_cell_style(self, x, y, value): if x not in self._styles: self._styles[x] = {} self._styles[x][y] = value self._parent.add_style(value) if not self.get_cell_value(x, y): self.set_cell_value(x, y, '') def get_row_...
yles[row] def set_row_style(self, row, value): self._row_styles[row] = value self._parent.add_style(value) @property def workbook(self): return self._parent def __get_cell_data(self, cell, x, y, style): if cell not in self._cell_cache: type = DataTypes.get_type(cell) if type == DataTypes.NUMBER: ...
samhutchins/tools
video_production/stitch-timelapse.py
Python
mit
2,855
0.003853
#!/usr/bin/env python3.6 import os, argparse, subprocess, tempfile, shutil, exifread, re from datetime import datetime def main(): parser = argparse.ArgumentParser() parser.add_argument("project") args = parser.parse_args() home = os.path.join(os.path.expanduser("~"), "Videos", "Mine", "WIP") des...
missing__(self, key): value = self[key] = Timelapse() return value class ExifError(Exception): def __init__(self, value): self.value
= value def __str__(self): return repr(self.value) if __name__ == "__main__": main()
Erethon/synnefo
snf-astakos-app/astakos/im/functions.py
Python
gpl-3.0
40,441
0.000074
# Copyright (C) 2010-2014 GRNET S.A. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed i...
project_notif import astakos.im.messages as astakos_messages logger = logging.getLogger(__n
ame__) class ProjectError(Exception): pass class ProjectNotFound(ProjectError): pass class ProjectForbidden(ProjectError): pass class ProjectBadRequest(ProjectError): pass class ProjectConflict(ProjectError): pass AUTO_ACCEPT_POLICY = 1 MODERATED_POLICY = 2 CLOSED_POLICY = 3 POLICIES = [...
mbuciora/eWallet
eWallet_app/serializers.py
Python
mit
989
0
from rest_framework import serializers from .models import User from .models import Group from .models import UserGroup from .models import ChangeDetail from .models import GroupChange from .models import UserChange class UserSerializer(serializers.ModelSerializer): cla
ss Meta: model = User fields = '__all__' # ZMIANA class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = '__all__' class UserGroupSerializer(serializers.ModelSerializer): class Meta: model = UserGroup fields = '__all__' ...
alizer): class Meta: model = GroupChange fields = '__all__' class UserChangeSerializer(serializers.ModelSerializer): class Meta: model = UserChange fields = '__all__'
agadiraju/519finalproject
svm/test_poly_svm.py
Python
mit
1,515
0.042244
print(__doc__) import numpy as np from sklearn import metrics from sklearn import datasets from sklearn.svm import SVC from sklearn.svm import SVR from sklearn.svm import LinearSVC from sklearn.metrics import accuracy_score from datetime import datetime from import_train import rmsle from import_train import import_tr...
= y_casual[nTrain:] y_regis_test = y_regis[nTrain:] y_total_test = y_total[nTrain:] #linear #param_grid = {'C': [1, 5, 10, 100],} #clf = GridSearchCV(SVC(kernel='linear'
), param_grid,n_jobs=-1) #clf = SVC(kernel='poly') #clf.fit(Xtrain,ytrain) #pred = clf.predict(Xtest) #print "best estimator = ",clf.best_estimator_ #print "RMSE poly = ", rmsle(ytest, pred) #new stuff clf_regis = SVR(kernel='poly') clf_regis.fit(Xtrain,y_regis_train) pred_regis = clf_regis.predict(Xtest) ...
christianurich/DynaMind-ToolBox
DynaMind-Performance-Assessment/3rdparty/CD3Waterbalance/Modelcreator/Demandmodelsetup.py
Python
gpl-2.0
2,545
0.010216
# -*- coding: utf-8 -*- """ Created on Thu Dec 11 15:47:44 2014 @author: Acer """ class Demandmodelsetup: def __init__(self, numberofDemand_Models, starting_value_i, **Demand_Modelattributes ): self.numberofDemand_Models = numberofDemand_Models self.Demand_Modelattributelist = [] s...
int((str(numberofDemand_Models)+' Demand_Models have been created!')) return def Setandwrite_attributes(self,numberofDemand_Models, starting_value_i, attributevector): for i in range(numberofDemand_Models+starting_value_i)[starting_value_i:]: self.Demand_Modelattributelist
[i-starting_value_i][str('Demand_Model_'+str(i))]["Commercial_Vector"] = attributevector[i-starting_value_i][1] self.Demand_Modelattributelist[i-starting_value_i][str('Demand_Model_'+str(i))]["Residential_Vector"] = attributevector[i-starting_value_i][0] self.Demand_Modelattributelist[i-starting...
ambikeshwar1991/gnuradio-3.7.4
grc/python/FlowGraph.py
Python
gpl-3.0
9,529
0.006297
""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion 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 l...
ace namespace_hash: a unique hash for the namespace Returns: the resultant object """ if not code: raise Exception, 'Cannot evaluate empty statement.' my_hash = hash(code) ^ namespace_hash #cache if does not exist if not self._eval_cache.has_key(m...
_signaturev(self, direction): """ Get a list of io signatures for this flow graph. Args: direction: a string of 'in' or 'out' Returns: a list of dicts with: type, label, vlen, size """ sorted_pads = { 'in': self.get_pad_sources(), ...
evz/demo
map_demo/california/urls.py
Python
mit
445
0.004494
from django.conf.urls.defaults import * from california.views import * urlpatterns = patterns('', url(r'^counties/$', counties, name='counties'), url(r'^places/$', places, name='places'), url(r'^complex-county/$', complex_county, name='complex-county'), url(r'^tiles-county/$', tiles_county, name='tile...
h, name='map-search'), url(r'^census/$', map_search, name='map-search'), )
naibaf7/PyGreentea
examples/VD2D3D/mknet_vd2d3d.py
Python
bsd-2-clause
1,991
0.045203
from __future__ import print_function import sys, os, math import numpy as np from numpy import float32, int32, uint8, dtype # Load PyGreentea # Relative path to where PyGreentea resides pygt_path = '../..' sys.path.append(pygt_path) import pygreentea.pygreentea as pygt import caffe from caffe import layers as L from...
ng=[4,84,84], fmap_inc_rule = lambda x: fmaps_vd2d3d.pop(0), fmap_bridge_rule = lambda x: 100, fmap_dec_rule = lambda x: 0, ip_depth = 1, hybrid_dimension
s = [0], dropout = 0.0) net.out = L.Convolution(net.sknet, kernel_size=[1,1,1], num_output=2, weight_filler=dict(type='msra'), bias_filler=dict(type='constant')) net.prob = L.Softmax(net.out, ntop=1, in_place=False, include=[dict(phase=1)]) net.loss = L.SoftmaxWithLoss(net.out, net.label, ntop=0, ...
pybae/etc
Project Euler/1-9/python/problem7.py
Python
mit
175
0.005714
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys s
ys.path.append('/Users/pybae/etc/Project Euler/') import general array = general.prime(200000)
print array[10000]
tztztztztz/robot
response/no_answer.py
Python
mit
198
0
# encodin
g=utf-8 from courtesy import courtesy_reply from log_decorator import error_logging @error_logging('na') def response(com, answer, **kwargs): return courtesy_reply(('na',), **kwar
gs)
YelpArchive/pushmanager
pushmanager/ui_methods.py
Python
apache-2.0
1,099
0.00091
def authorized_to_manage_request(_, request, current_user, pushmaster=False): if pushmaster or \ request['user'] == current_user or \
(request['watchers'] and current_user in request['watchers'].split(',
')): return True return False def sort_pickmes(_, requests, tags_order): """Sort pickmes based on tags_order Args: - - request handler object requests - a list of requests tags_order - order to sort requests Return: sorted requests list """ def compare_request...
hyl0327/esoe_oop_judge
web/judge/migrations/0010_auto_20160306_1216.py
Python
mit
446
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-03-06 12:16 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('judge', '0009_auto_20160306_0945'), ] operations = [ migrations.RenameField( ...
bmission', old_name='detail_message', new_name='detail_messages', ), ]
gabofer82/taller_programacion_2017
Documentación/SOURCE/Programa/main.py
Python
mit
1,181
0.000847
# -*- coding: utf-8 -*- import sys, time from PySide import QtGui, QtCore from presentacion.form_abm_paciente import FormPacienteABM if __name__ == "__main__": app = QtGui.QApplication(sys.argv) # Create and display the splash screen splash_pix = QtGui.QPixmap('splash.
png') splash = QtGui.QSplashScreen(splash_pix, QtCore.Qt.WindowStaysOnTopHint) splash.setWindowFlags( QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint) splash.setEnabled(False) # splash = QSplashScreen(splash_pix) # adding progress bar progressBar = QtGui.QProgressBar(spla...
ss = "QProgressBar::chunk { background: yellow; }" progressBar.setStyleSheet(css) # splash.setMask(splash_pix.mask()) splash.show() for i in range(1, 11): progressBar.setValue(i) t = time.time() while time.time() < t + 0.1: app.processEvents() # Simulate someth...
diagonalwalnut/Experience
adl_lrs/urls.py
Python
apache-2.0
1,002
0.006986
from django.conf import settings from django.conf.urls import patterns, include, url from django.views.generic import RedirectView # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', RedirectView.as_view(url='/xAPI/')), ...
n/', include(admin.site.urls)), ) urlpatterns += patterns('', url(r'^accounts/login/$
', 'django.contrib.auth.views.login', name="login"), url(r'^accounts/logout/$', 'lrs.views.logout_view', name="logout"), ) if settings.DEBUG: urlpatterns += patterns('', url(r'^media/attachment_payloads/(?P<path>.*)$', 'lrs.views.admin_attachments'), )
jaraco/calendra
calendra/tests/test_america.py
Python
mit
20,047
0.0001
from datetime import date from . import GenericCalendarTest from ..america import ( Argentina, Barbados, Chile, Colombia, Mexico, Panama, Paraguay ) class ArgentinaTest(GenericCalendarTest): cal_class = Argentina def test_holidays_2018(self): holidays = self.cal.holidays_set(2018) # 1. Añ...
= holidays[date(2020, 12, 8)] self.assertE
qual(label, "Día de la Inmaculada Concepción de María") class ChileTest(GenericCalendarTest): cal_class = Chile def test_holidays_2013(self): holidays = self.cal.holidays_set(2013) self.assertIn(date(2013, 1, 1), holidays) self.assertIn(date(2013, 3, 29), holidays) self.assert...
wikimedia/pywikibot-core
pywikibot/families/wikitech_family.py
Python
mit
405
0
"
""Family module for Wikitech.""" # # (C) Pywikibot team, 2005-2020 # # Distributed under the terms of the MIT license. # from pywikibot import family # The Wikitech family class Family(family.WikimediaOrgFamily): """Family class for Wikitech.""" name = 'wikitech' code = 'en' def protocol(self, code...
n the protocol for this family.""" return 'https'
QuinnSong/JPG-Tools
src/shear.py
Python
gpl-3.0
1,179
0.024597
from PIL import Image from math import tan, radians, sin, cos def Shear(
im, x_angle = 45, y_angle = 45, bkcolor = (255,255,255,255)): im = im.convert("RGBA") pixels = im.load() w, h = im.size top_angle = 90 - y_angle + x_angle # calculate x factors in (ax + by + c) a = 1 b = tan(radians(x_angle)) c = - h * tan(r
adians(x_angle)) x_factor = sin(radians(y_angle))/(cos(radians(x_angle)) * sin(radians(top_angle))) # calculate y factors in (dx + ey + f) d = - x_factor e = 1 - tan(radians(x_angle)) * x_factor f = h * tan(radians(x_angle))* x_factor size = (int((w * e - c * e + b * f)/ (a * e - b * d))...
colaftc/webtool
top/api/rest/ShopGetRequest.py
Python
mit
303
0.033003
''' Created by auto_sdk on 2015.03.18 ''' from top.api.b
ase import RestApi class ShopGetRequest(RestApi): def __init__(self,domain='gw.api.taobao.com',port=80): RestApi.__init__(self,domain, port) self.fields
= None self.nick = None def getapiname(self): return 'taobao.shop.get'
ekiwi/tinyos-1.x
contrib/handhelds/hwtest/telosb/Accel/multiaccel.py
Python
bsd-3-clause
12,716
0.014313
#!/usr/bin/python # # Copyright (c) 2004,2005 Hewlett-Packard Company # All rights reserved # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # * Redistributions of source code must retain the above copyright # ...
height = r.height
xscale = float(r.width) / (len(data) - 1) yscale = float(r.height) / 4096 count = len(data) for i in range(0,count-1): widget.window.draw_line(gc, int(xscale * i), height - int(yscale * data[i]), int(xscale * (i+1)), height - int(yscal...
formiano/enigma2
lib/python/Plugins/SystemPlugins/SoftwareManager/BackupRestore.py
Python
gpl-2.0
27,174
0.032126
from Screens.Screen import Screen from Screens.MessageBox import MessageBox from Screens.Console import Console from Screens.Standby import TryQuitMainloop from Components.ActionMap import ActionMap, NumberActionMap from Components.Pixmap import Pixmap from Tools.LoadPixmap import LoadPixmap from Components.Label impor...
Text(default = '/media/hdd/', visible_width = 50, fixed_size = False) config.plugins.configurationbackup.backupdirs_default = NoSave(ConfigLocations(default=[eEnv.resolve('${sysconfdir}/enigma2/'), '/etc/CCcam.cfg', '/usr/keys', '/etc/tuxbox/config/', '/etc/auto.network', '/etc/
machine-id', '/etc/openvpn/', '/etc/dropbear/', '/etc/default/dropbear', '/home/root/', '/etc/samba/', '/etc/fstab', '/etc/inadyn.conf', '/etc/network/interfaces', '/etc/wpa_supplicant.conf', '/etc/wpa_supplicant.ath0.conf', '/etc/opkg/secret-feed.conf', '/etc/wpa_supplicant.wlan0.conf', '/etc/resolv.conf',...
UOSHUB/BackEnd
API/views/details.py
Python
gpl-3.0
877
0
from rest_framework.response import Response from rest_framework.views import APIView from .common import login_required from Requests import myudc # Student's details requests handler class Student(APIView): """ This only returns student's basic info right now, but in the future it will have all layout d...
red("myudc") def get(request): # Return student's basic info as o
f now return Response( # Get & scrape student's basic info from MyUDC myudc.scrape.student_details( myudc.get.summarized_schedule( # Send MyUDC cookies request.session["myudc"] ) ) )
GutenkunstLab/SloppyCell
test/test_crossReferences.py
Python
bsd-3-clause
4,044
0.006924
import unittest import os import copy import scipy import SloppyCell.Utility as Utility from SloppyCell.ReactionNetworks import * import SloppyCell.daskr from SloppyCell.daskr import daeint # Load the fast reaction example from the SBML semantic test suite. # To avoid extra dependencies on libsbml, we use verions bu...
copy() net._makeCrossReferences() self.integration_tests(net) def test_manual_without_makeCrossReferences(self): """ Test that after setting _manualCrossReferenc
es_flag to True the \ compilation will fail if makeCrossReferences is NOT called """ net = algebraic_net_manual.copy() self.assertRaises(AttributeError, Dynamics.integrate, net, tlist_algebraic_net) def test_manual_without_makeCrossReferences_2(self): """ Test that after setting _manualCro...
henkelis/sonospy
web2py/applications/sonospy/languages/hu.py
Python
gpl-3.0
4,428
0.022358
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '%Y-%m-%d': '%Y.%m.%d.', '%Y-%m-%d %H:%M:%S': '%Y.%m.%d. %H:%M:%S', '%s...
record inserted': '\xc3\xbaj bejegyz\xc3\xa9s felv\xc3\xa9ve', 'next 100 rows': 'k\xc3\xb6vetkez\xc5\x91 100 sor', 'or import from csv file': 'vagy bet\xc3\xb6lt\xc3\xa9s csv f\xc3\xa1jlb\xc3\xb3l', 'previous 100 rows': 'el\xc5\x91z\xc5\x91 100 sor', 'record': 'bejegyz\xc3\xa9s', 'record does not exist': 'bejegyz\xc3\...
v\xc3\xa1lasztott', 'state': '\xc3\xa1llapot', 'table': 't\xc3\xa1bla', 'unable to parse csv file': 'nem lehet a csv f\xc3\xa1jlt beolvasni', }
sl2017/campos
campos_participant_access/models/__init__.py
Python
agpl-3.0
102
0
from .
import campos_event_participant from . import campos_clc_stat from . import e
vent_registration
bradrowesf/AnkiDeckMaker
tests/notetranslator_tests.py
Python
gpl-3.0
1,526
0.038008
from nose.tools import * from DeckMaker.notetranslator import NoteTranslator def setup(): print "SETUP!" def teardown(): print "TEAR DOWN!" def test_basic(): t = NoteTranslator() assert_equal(t.GetMidiCodeForHumans("E5"),64) assert_equal(t.GetMidiCodeForHumans("C1"),12) assert_equal(t.GetM...
CodeForHumans("Gb7"),90) assert_equal(t.GetMidiCodeForHumans("D#2"),27) pass def test_hex(): t = NoteTranslator() assert_equal(t.GetHexString(t.GetMidiCodeForHumans("E5")),"40") assert_equal(t.GetHexString(t.GetMidiCodeForHumans("C1")),"c") assert_equal(t.GetHexString(t.GetMidiCodeForHumans("Ab6")),"50"...
"1b") pass def test_GetTriadCodes(): t = NoteTranslator() assert_equal(t.GetTriadCodes( t.GetMidiCodeForHumans("C4"), "minor", 3),[48, 53, 56]) assert_equal(t.GetTriadCodes( t.GetMidiCodeForHumans("Ab2"), "major", 2),[32, 40, 35]) assert_equal(t.GetTriadCodes( t.GetMidiCodeForHumans("G#6"), "minor", 1),[80...
mctenthij/hortiradar
hortiradar/database/tasks_workers.py
Python
apache-2.0
2,675
0.001498
import os from configparser import ConfigParser from time import time from typing import Sequence from redis import StrictRedis import ujson as json from hortiradar.database import app, get_frog, get_keywords, insert_tweet, insert_lemma if os.environ.get("ROLE") == "worker": keywords = get_keywords() keywor...
if (time() - keywords_sync_time) > 60 * 60: keywords = get_keywords() keywords_sync_time = time() # First check if retweets are already processed in the cache if retweet_id_str: key = "t:%s" % retweet_id_str rt = redis.get(key) if rt: kw, groups, tokens ...
is.expire(key, rt_cache_time) return frog = get_frog() # tokens contains a list of dictionaries with frog's analysis per token # each dict has the keys "index", "lemma", "pos", "posprob" and "text" # where "text" is the original text tokens = frog.process(text) kw = [] groups = ...
haizawa/odenos
src/test/python/org/o3project/odenos/core/component/network/topology/test_port.py
Python
apache-2.0
4,161
0.00024
# -*- coding:utf-8 -*- # Copyright 2015 NEC Corporation. # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License...
ress or implied. # # See the License for the specific language governing permissions and # # limitations under the License.
# import unittest from org.o3project.odenos.core.component.network.topology.port import Port class PortTest(unittest.TestCase): def setUp(self): self.target = Port('Port', '1', 'PortId', 'NodeId', 'OutLink', 'InLink', {'Key': 'Val'}) ...
devtronics/Gitme
monty.py
Python
agpl-3.0
405
0.017284
cast = ['Cleese', 'Palin', 'Jones', 'Idle'] movies = ['The Holy Grail', 1975, 'Terry Jones & Terry Gilliam', 91, ['Graham Chapman', ['Michael Palin',
'John Cleese', 'Terry Gilliam', 'Eric Idle', 'Terry Jones']]] fav_movies = ['The Holy Grail', 'The Life of Brian'] def print_lol(the_list): for each_item in the_list: if isinstance(each_item, list): print_lol(each_item) else: print(eac
h_item)
XiaJieCom/change
stu103151/days20/project/bbs/models.py
Python
lgpl-2.1
2,809
0.016088
from django.db import models from django.contrib.auth.models import User from django.core.exceptions
import ValidationError import datetime # Create your models here. class Article(models.Model): title = models.CharField(max_length=255) brief = models.CharField(null=True,blank=True,max_length=255) category = models.ForeignKey("Category
") content = models.TextField(u"文章内容") author = models.ForeignKey("UserProfile") pub_date = models.DateTimeField(blank=True,null=True) last_modify = models.DateTimeField(auto_now=True) priority = models.IntegerField(u"优先级",default=1000) head_img = models.ImageField(u"文章标题图片",upload_to="uploads")...
tgquintela/pythonUtils
pythonUtils/NeighsManager/neighs_info.py
Python
mit
99,145
0.000988
""" neighs information ------------------ Auxiliar class in order to manage the information of the neighbourhood returned by the retrievers. Due to the complexity of the structure it is convenient to put altogether in a single class and manage in a centralized way all the different interactions with neighs_info in the...
ighbours number is set as None. Returns ------- sh0: int the number of elements we want to get their neighbourhood. sh1: int the number of neighs they have it is constant. sh2: int the number of perturbations applied. """ if n...
(self.iss) step = self.idxs.step sh1 = (self.idxs.stop + step - 1 - self.idxs.start)/step sh1 = 0 if self.ks is None else len(self.ks) elif type(self.idxs) == np.ndarray: sh0 = 0 if self.idxs is None else len(self.idxs) sh1 = 0 if self.idxs is None els...
tswast/google-cloud-python
grafeas/synth.py
Python
apache-2.0
13,298
0.00173
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
google\.api_core\.client_options\.ClientOptions\]\): Client options used to set user options on the client\. API Endpoint should be set through client_options\. \"\"\"""", " \"\"\"" ) s.replace( "grafeas/**/grafeas_client.py", r"""if channel: warn...
'`transport` instead\.', PendingDeprecationWarning, stacklevel=2\) api_endpoint = self\.SERVICE_ADDRESS if client_options: if type\(client_options\) == dict: client_options = google\.api_core\.client_options\.from_dict\(client...
teoreteetik/api-snippets
client/capability-token-2way/capability-token.5.x.py
Python
mit
763
0
from flask import Flask, Response, request from twilio.util import TwilioCapability app = Flask(__name__) @app.route('/token', methods=['GET']) def get_capability_token(): """Respond to incoming requests.""" # Find these values at twilio.com/console account_sid =
'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' capability = TwilioCapability(account_sid, auth_token) # Twilio Application Sid application_sid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' capability.allow_client_outgoing(application_sid) capability.allow_client_incoming(request....
e() return Response(token, mimetype='application/jwt') if __name__ == "__main__": app.run(debug=True)
alexhersh/calico
calico/felix/masq.py
Python
apache-2.0
4,208
0.000951
# Copyright (c) Metaswitch Networks 2015. All rights reserved. import logging from calico.felix.actor import Actor, actor_message from calico.felix.futils import IPV4, IPV6 from calico.felix.ipsets import Ipset, FELIX_PFX _log = logging.getLogger(__name__) ALL_POOLS_SET_NAME = FELIX_PFX + "all-ipam-pools" MASQ_POOL...
as dirty, looking for masq-enabled pools") masq_enabled_cidrs = set() all_cidrs = set() for pool in self.pools_by_id.itervalues(): all_cidrs.add(pool["cidr"]) if pool.get("masquerade", False):
masq_enabled_cidrs.add(pool["cidr"]) if masq_enabled_cidrs: _log.info("There are masquerade-enabled pools present. " "Updating.") self._all_pools_ipset.replace_members(all_cidrs) self._masq_pools_ipset.replace_members(masq_enab...
Mitchkoens/sympy
sympy/functions/elementary/tests/test_hyperbolic.py
Python
bsd-3-clause
22,379
0.001519
from sympy import symbols, Symbol, sinh, nan, oo, zoo, pi, asinh, acosh, log, sqrt, \ coth, I, cot, E, tanh, tan, cosh, cos, S, sin, Rational, atanh, acoth, \ Integer, O, exp, sech, sec, csch from sympy.utilities.pytest import raises def test_sinh(): x, y = symbols('x,y') k = Symbol('k', integer=Tru...
h(-pi) == -sinh(pi) assert sinh(2**1024 * E) == sinh(2**1024 * E) assert sinh(-2**1024 * E) == -sinh(2**1024 * E) assert sinh(pi*I) == 0 assert sinh(-pi*I) == 0 assert sinh(2*pi*I) == 0 assert sinh(-2*pi*I) == 0 assert sinh(-3*10**73*pi*I) == 0 assert sinh
(7*10**103*pi*I) == 0 assert sinh(pi*I/2) == I assert sinh(-pi*I/2) == -I assert sinh(5*pi*I/2) == I assert sinh(7*pi*I/2) == -I assert sinh(pi*I/3) == S.Half*sqrt(3)*I assert sinh(-2*pi*I/3) == -S.Half*sqrt(3)*I assert sinh(pi*I/4) == S.Half*sqrt(2)*I assert sinh(-pi*I/4) == -S.Half*...
ChromiumWebApps/chromium
remoting/webapp/build-html.py
Python
bsd-3-clause
2,936
0.012262
#!/usr/bin/env python # Copyright
2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Builds the complete main.html file from the basic components. """ from HTMLParser import HTMLParser import os import re import sys def error(msg): print 'Error:...
class HtmlChecker(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.ids = set() def handle_starttag(self, tag, attrs): for (name, value) in attrs: if name == 'id': if value in self.ids: error('Duplicate id: %s' % value) self.ids.add(value) class Generat...
landlab/landlab
landlab/grid/nodestatus.py
Python
mit
457
0
#! /usr/bin/env
python from enum import IntEnum, unique @unique class NodeStatus(IntEnum): """Define the boundary-type codes""" #: Indicate a node is *core*. CORE = 0 #: Indicate a boundary node is has a fixed values. FIXED_VALUE = 1 #: Indicate a boundary node is has a fixed gradient. FIXED_GRADIENT = ...
s closed CLOSED = 4
ashapochka/saapy
tests/test_workspace.py
Python
apache-2.0
393
0
# coding=utf-
8 import pytest from pathlib import Path @pytest.mark.integration def test_work_directory(): path = Path('.').resolve() print() print('work dir:', path) def test_data_directory(data_directory): print() print('data_directory:', data_directory) def test_neo4j_test_ws_dir(neo4j_test_ws_dir): ...
:', neo4j_test_ws_dir)
KWARC/mwetoolkit
bin/libs/base/tpclass.py
Python
gpl-3.0
2,892
0.007607
#!/usr/bin/python # -*- coding:UTF-8 -*- ################################################################################ # # Copyright 2010-2014 Carlos Ramisch, Vitor De Araujo, Silvio Ricardo Cordeiro, # Sandra Castellanos # # tpclass.py is part of mwetoolkit # # mwetoolkit is free software: you can redistribute it ...
conform to the `MetaTPClass` defined in the `Meta` header of the XML file, e.g. if the meta-TP class allows three base "{c1,c2,c3}", the value should equal one of these three values. If you use multi-class evaluation, please be sure that the machine learning algorithm that you are goin...
################################################# def __init__( self, name, value ): r"""(See Feature.__init__).""" super(TPClass, self).__init__(name, value, xml_class="tpclass") ################################################################################ if __name__ == "__main__" : ...
hagleitn/Openstack-Devstack2
devstack/cfg.py
Python
apache-2.0
6,505
0.001537
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (C) 2012 Yahoo! 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.or...
ig provided value [%s]" % (extracted_val)) return extracted_val def add_header(fn, contents): lines = list() lines.append('# Adjusted source file %s' % (fn.strip())) lines.append("# On %s" % (date.rcf8222date())) lines.append("# By user %s, grou
p %s" % (sh.getuser(), sh.getgroupname())) lines.append("# Comments may have been removed (TODO: darn python config writer)") # TODO Maybe use https://code.google.com/p/iniparse/ which seems to preserve comments! lines.append("") if contents: lines.append(contents) return utils.joinlinesep(*...
williamFalcon/pytorch-lightning
pl_examples/test_examples.py
Python
apache-2.0
1,486
0.000673
# Copyright The PyTorch Lightning 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
ytest.mark.parametrize("cli_args", [ARGS_GPU]) def test_examples_mnist_dali(tmpdir, cli_args): from pl_examples.basic_exa
mples.dali_image_classifier import cli_main # update the temp dir cli_args = cli_args % {"tmpdir": tmpdir} with mock.patch("argparse._sys.argv", ["any.py"] + cli_args.strip().split()): cli_main()
CameronLonsdale/jam
compiler/lekvar/__init__.py
Python
mit
2,659
0.01053
import logging from contextlib import contextmanager from ..errors import CompilerError from .state import State from .core import Context, Object, BoundObject, SoftScope, Scope, Type from .module import Module from .closure import Closure, ClosedLink, ClosedTarget from .function import Function, FunctionType, Functi...
ging.getLogger(), opt_level = 0): module = _verify(source, frontend, logger) logger.info("Generating Code") return backend.emit(module, logger, opt_level) def run(source, frontend, backend, logger =
logging.getLogger(), opt_level = 0): module = _verify(source, frontend, logger) logger.info("Running") return backend.run(module) def verify(module:Module, logger = logging.getLogger()): # Set up the initial state before verifying State.init(logger.getChild("lekvar")) State.logger.info(modul...
janusnic/honcho
honcho/test/unit/export/test_upstart.py
Python
mit
4,088
0
import collections from mock import MagicMock from mock import call from mock import patch from honcho.test.helpers import TestCase from honcho.export.upstart import Export FakeProcess = collections.namedtuple('FakeProcess', 'name') FIX_1PROC = [FakeProcess('web.1')] FIX_NPROC = [FakeProcess('web.1'), ...
sertIn(('elephant-worker.conf', self.process_master.render.return_value), out)
expected = [call({'app': 'elephant', 'group_name': 'elephant-web'}), call({'app': 'elephant', 'group_name': 'elephant-worker'})] self.assertEqual(expected, self.process_master.render.call_args_list) def test_render_multiple_processe...
MLnick/spark
python/pyspark/worker.py
Python
apache-2.0
8,012
0.001248
# # Licensed to the Apache Software Foundation (ASF) under one or more # contr
ibutor 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 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 Li...
sullivanmatt/splunk-sdk-python
examples/github_forks/github_forks.py
Python
apache-2.0
6,663
0.003902
#!/usr/bin/env python # # Copyright 2013 Splunk, 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 ...
s defined by its configuration, and tries to run them with the argument --scheme. Splunkd expects the modular inputs to print a description of the input in XML on stdout. The modular input framework takes care of all the details of formatting XML and printing it. The user need only ...
urn a new Scheme object. :return: scheme, a Scheme object """ # Splunk will display "Github Repository Forks" to users for this input scheme = Scheme("Github Repository Forks") scheme.description = "Streams events giving the number of forks of a GitHub repository." # If...
maybedy/MLDLStudy
week1/JY/activation.py
Python
mit
540
0
import numpy
as np def identity_function(x): return x def leaky_relu(x): return np.max(0.1 * x, x) def relu(x): return np.max(0, x) def sigmoid(x): return 1 / (1 + np.exp(-x)) def tanh(x): return np.tanh(x) def step_function(x): return np.array(x > 0, dtype=np.int) def softmax(x): if x.ndim...
(x) / np.sum(np.exp(x))
Diviyan-Kalainathan/causal-humans
DimensionalityReduction/data_reader.py
Python
mit
2,112
0.005208
#DEPRECATED import csv import numpy # Load var info researched_var='le' researched_index=0 result=numpy.zeros((31112,1)) count=0 with open('output/prepared_data.csv', 'rb') as datafile: datareader = csv.reader(datafile, delimiter=';', quotechar='"')
num_row = 0 header=next(datareader) for i in [i for i, x in enumerate(header) if x == researched_var]: researched_index=i print('Found! ') print(researched_index) for row in datareade
r: if row[researched_index]!='0': print(row[researched_index]) '''for row in datareader: if int(row[researched_index])==1: result[count]=1 elif int(row[researched_index+1])==1: result[count]=2 elif int(row[researched_index + 2]) == 1: ...
pywren/pywren
pywren/wrenhandler.py
Python
apache-2.0
17,657
0.003568
# # Copyright 2018 PyWren 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
ContentLength'] except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == "404": return None else: raise e def key_exists(s3client, bucket, key): return get_key_size(s3client, bucket
, key) is not None def free_disk_space(dirname): """ Returns the number of free bytes on the mount point containing DIRNAME """ if os.name == 'nt': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), ...
lukeshingles/artistools
artistools/nltepops/plotnltepops.py
Python
mit
24,895
0.003896
#!/usr/bin/env python3 """Artistools - NLTE population related functions.""" import argparse import math import multiprocessing import os # import re # import sys # from functools import lru_cache # from functools import partial from pathlib import Path # from itertools import chain import matplotlib.pyplot as plt imp...
imestep[s] for s in ['nne', 'Te', 'TR', 'W']] # comparison to Chianti file elsym = at.elsymbols[atomic_number] elsymlower = elsym.lower() if Path('data', f'{elsymlower}_{ion_stage}-levelmap.txt').exists(): # ax.set_ylim(bottom=2e-3) # ax.set_ylim(top=4) levelmapfile = Path('data'...
for line in levelmapfile: row = line.split() levelnumofconfigterm[(row[0], row[1])] = int(row[2]) - 1 # ax.set_ylim(bottom=5e-4) for depfilepath in sorted(Path('data').rglob(f'chianti_{elsym}_{ion_stage}_*.txt')): with depfilepath.open('r') as depfile: ...
frouty/odoogoeen
openerp/osv/orm.py
Python
agpl-3.0
272,006
0.004511
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
odifiers`` node attribute and set it on the provided node. Alters its first argument in-place. :par
am node: ``field`` node from an OpenERP view :type node: lxml.etree._Element :param dict field: field descriptor corresponding to the provided node :param dict context: execution context used to evaluate node attributes :param bool in_tree_view: triggers the ``tree_invisible`` code ...
Alberto-Beralix/Beralix
i386-squashfs-root/usr/share/pyshared/duplicity/backends/rsyncbackend.py
Python
gpl-3.0
6,517
0.004603
# -*-
Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright 2002 Ben Escoto <ben@emerose.org> # Copyright 2007 Kenneth Loafman <kenneth@loafman.com> # # This file is part of duplicity. # # Duplicity is free
software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation; either version 2 of the License, or (at your # option) any later version. # # Duplicity is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; wi...
tylermumford/euler
14/python/main.py
Python
mit
752
0.005319
#!/usr/bin/env python3 if __name__ == '__main__': from collatz
import collatz import argparse desc = 'Find the number with the longest Collatz sequence under a given ceiling.' parser = argparse.ArgumentParser(description=desc) parser.add_argument('ceiling', type=int, default=13, nargs='
?') args = parser.parse_args() ceiling = args.ceiling results = {} for x in range(ceiling - 1, 1, -2): results[collatz(x)] = x longest = max(iter(results)) answer = results[longest] print("Longest: C{0} for {1}".format(longest, answer)) print_all = False if print_all: ...
lino-framework/book
lino_book/projects/auto_create/models.py
Python
bsd-2-clause
267
0.003745
from lino.api import dd class Tag(dd.Model):
name = dd.CharField(max_length=100) def __str__(self): return self.name @dd.receiver(dd.auto_create) def my_auto_create_handler(sender, **kw): print("My ha
ndler was called with {}".format(sender))
PepperPD/edx-pepper-platform
common/djangoapps/tests.py
Python
agpl-3.0
2,072
0.004826
''' Created on Jun 6, 2013 @author: dmitchell ''' from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory from student.tests.factories import AdminFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase import xmodule_modifiers import datetime from pytz import UTC from xmodule...
has_score = False # don't trip trying to retrieve db data late_problem = ItemFactory.create( parent_location=section.location, display_name='problem hist 2', category='problem')
late_problem.start = datetime.datetime.now(UTC) + datetime.timedelta(days=32) late_problem.has_score = False problem_module = factories.get_test_xmodule_for_descriptor(problem) problem_module.get_html = xmodule_modifiers.add_histogram(lambda:'', problem_module, instructor) self.ass...
pmghalvorsen/gramps_branch
gramps/gen/filters/rules/citation/_citationprivate.py
Python
gpl-2.0
1,680
0.005357
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2002-2006 Donald N. Allingham # Copyright (C) 2011
Tim G L Lyons # # 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 version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILI...