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
petrjasek/superdesk-core
superdesk/etree.py
Python
agpl-3.0
5,846
0.002053
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2017 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from lxml im...
elements in <head> and <body> # <script> can be used in embed, and the parser will move them to <head> # so we need both <head> and <body> for elt in root: div.extend(elt) root = div else: raise ValueError("invalid content: {}".format(content)...
.tag in BLOCK_ELEMENTS: elem.tail = (elem.tail or "") + "\n" # prepend \n to the tail elif elem.tag in ("br",): elem.tail = "\n" + (elem.tail or "") if space_on_elements: for elem in root.iterfind(".//"): elem.tail = (elem.tail or "") + spa...
SasView/sasview
src/sas/qtgui/Perspectives/Fitting/UnitTesting/FittingUtilitiesTest.py
Python
bsd-3-clause
11,524
0.003818
import sys import unittest from unittest.mock import MagicMock from PyQt5 import QtGui, QtCore from sas.qtgui.Plotting.PlotterData import Data1D from sas.qtgui.Plotting.PlotterData import Data2D from UnitTesting.TestUtils import WarningTestNotImplemented from sasmodels import generate from sasmodels import modelinf...
kernel_module = generate.load_kernel_module(model_name) multishell_parameters = modelinfo.ma
ke_parameter_table(getattr(kernel_module, 'parameters', [])) params = FittingUtilities.getIterParams(multishell_parameters) # returns a non-empty list self.assertNotEqual(params, []) self.assertIn('sld', str(params)) self.assertIn('thickness', str(params)) def testGetMultip...
szepeviktor/debian-server-tools
mail/mx-check/hubspot-free-email-domains.py
Python
mit
772
0.002591
#!/usr/bin/env python3 # # List HubSpot's free email domains. from urllib.request import urlopen # pip3 install --user beautifulsoup4 # https://www.crummy.com/sof
tware/BeautifulSoup/bs4/doc/#strings-and-stripped-strings from bs4 import BeautifulSoup URL = "https://knowledge.hubspot.com/articles/kcs_article/forms/what-domains-are-blocked-when-using-the-forms-email-domains-to-block-feature" page = urlopen(URL) html = page.read() soup = BeautifulSoup(html, "html.parser") # Ope...
ml.parser") # Original CSS selector: "#post-body span > p:not(1)" ps = soup.select("#post-body span > p") # Skip first paragraph for p in ps[1:]: for domain in p.stripped_strings: print(domain)
larrybradley/astropy-helpers
astropy_helpers/version_helpers.py
Python
bsd-3-clause
9,639
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Utilities for generating the version string for Astropy (or an affiliated package) and the version.py module, which contains version info for the package. Within the generated astropy.version module, the `major`, `minor`, and `bugfix` variables hold ...
f this fails for any reason an empty string is returned. """ loader = pkgutil.get_loader(git_helpers) source = loader.get_source(git_helpers.__name__) or '' source_lines = source.splitlines() if not source_lines: log.warn('Cannot get source code for astropy_helpers.git_helpers; ' ...
f line.startswith('# BEGIN'): break git_helpers_py = '\n'.join(source_lines[idx + 1:]) if PY3: verstr = version else: # In Python 2 don't pass in a unicode string; otherwise verstr will # be represented with u'' syntax which breaks on Python 3.x with x # < 3. Th...
tapomayukh/projects_in_python
classification/Classification_with_CRF/old_crfsuite_package/old code/feature_conversion.py
Python
mit
5,099
0.016278
#!/usr/bin/env python import numpy as np # Create features for tagging a sequence. def create_features(f, g, history): tempf = [] tempa = [] tempm = [] for line in f: if line != '\n': idstr = line.split()[3] if line == '\n': templen = np.size(tempf,0) ...
write('f' +str([i-history]) + '=f') if (i-history) < 0:
g.write('n' + str(abs(i-history)) + ':' + tempf[i+j] + ' ') else: g.write(str(i-history) + ':' + tempf[i+j] + ' ') for i in range(2*history): if (i+j) < templen: ...
mohierf/mod-webui
module/plugins/eltdetail/eltdetail.py
Python
agpl-3.0
2,612
0.001149
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2009-2012: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # Gregory Starck, g.starck@gmail.com # Hartmut Goebel, h.goebel@goebel-consult.de # # This file is part of Shinken. # # Shinken is free software: you can redis...
amgr.get_service(host_name, service, user) or app.redirect404() # Set servicegroups level ... app.datamgr.set_servicegroups_level(user) # Get graph data. By default, show last 4 hours now = int(time.time()) graphstart = int(app
.request.GET.get('graphstart', str(now - 4 * 3600))) graphend = int(app.request.GET.get('graphend', str(now))) return { 'elt': s, 'graphstart': graphstart, 'graphend': graphend, 'configintervallength': app.datamgr.get_configuration_parameter('interval_length') } pages = { show...
e-koch/VLA_Lband
14B-088/HI/turbulence/M33_turbstats.py
Python
mit
5,008
0.001198
''' Run a variety of turbulent statistics on the full M33 cube. This will use a TON of memory. Recommend running on a cluster. File structure setup to work on cedar in scratch space. Saves the outputs for later use ''' from spectral_c
ube import SpectralCube from astropy.io import fits from os.path import join as osjoin import astropy.units as u fr
om astropy import log import sys from turbustat.statistics import (PowerSpectrum, VCA, VCS, PCA, SCF, StatMoments, DeltaVariance) ncore = int(sys.argv[-1]) run_pspec = False run_delvar = False run_moments = False run_vca = False run_vcs = True run_pca = True run_scf = True scratch...
akulakov/mangotrac
proj_issues/issues/migrations/0008_auto__del_field_report_url__add_field_report_columns__add_field_report.py
Python
mit
11,960
0.007023
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Report.url' db.delete_column(u'issues_report', 'url') ...
}, u'issues.issue': { 'Meta': {'object_name': 'Issue'}, 'cc': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'closed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'component': ('djang...
s.related.ForeignKey', [], {'blank': 'True', 'related_name': "'issues'", 'null': 'True', 'to': u"orm['issues.Component']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'blank'...
storyandstructure/django-nomnom
setup.py
Python
mit
1,453
0.002065
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) VERSION = __import__('nomnom').get_version() CLASSIFIERS = [ 'Development Status :: 3 - Alpha', 'Enviro...
ent :: Libraries :: Application Frameworks', ] # get install_requires from requirements.txt text = open('requirements.txt', 'r') REQUIREMENTS = text.readlines() i = 0 while i < len(REQUIREMENTS): REQUIREMENTS[i] = REQUIREMENTS[i].replace('\n', '') i += 1 setup( author="Kevin Harvey", author_email="kev...
go admin site.', long_description='', license='MIT', keywords='django, import, admin', url='https://github.com/storyandstructure/django-nomnom/', platforms=['OS Independent'], classifiers=CLASSIFIERS, install_requires=REQUIREMENTS, packages=find_packages(), include_package_data=True,...
guaix-ucm/numina
numina/array/tests/test_bpm.py
Python
gpl-3.0
1,012
0.007905
import numpy f
rom numina.array.bpm import process_bpm_median def test_process_bpm(): data = numpy.zeros((10, 10), dtype='float32') + 3.0 mask = numpy.z
eros((10, 10), dtype='int32') mask[3,3] = 1 result1 = process_bpm_median(data, mask) assert result1[3,3] == 3.0 result2, subs2 = process_bpm_median(data, mask, subs=True) assert result2[3,3] == 3.0 assert subs2.min() == 1 def test_process_bpm_large_hole(): data = numpy.zeros((100, 100...
Reagankm/KnockKnock
venv/lib/python3.4/site-packages/nltk/sem/evaluate.py
Python
gpl-2.0
25,345
0.004222
# Natural Language Toolkit: Models for first-order languages with lambda # # Copyright (C) 2001-2015 NLTK Project # Author: Ewan Klein <ewan@inf.ed.ac.uk>, # URL: <http://nltk.sourceforge.net> # For license information, see LICENSE.TXT #TODO: #- fix tracing #- fix iterator-based approach to existentials """ T...
(\([^)]+\)) # tuple-expression \s*""", re.VERBOSE) def _read_valuation_line(s): """ Read a line in a valuation file. Lines are expected to be of the form:: noosa
=> n girl => {g1, g2} chase => {(b1, g1), (b2, g1), (g1, d1), (g2, d2)} :param s: input line :type s: str :return: a pair (symbol, value) :rtype: tuple """ pieces = _VAL_SPLIT_RE.split(s) symbol = pieces[0] value = pieces[1] # check whether the value is meant to be a se...
dkamotsky/program-y
src/test/config/file/test_factory.py
Python
mit
1,628
0.0043
import unittest from programy.config.file.factory import ConfigurationFactory from programy.config.client.client import ClientConfiguration class ConfigurationFactoryTests(unittest.TestCase): def test_guess_format_from_filenam
e(self): config_format = ConfigurationFactory.guess_format_from_filename("file.yaml") self.assertEqual(config_format, "yaml") config_format = ConfigurationFactory.guess_format_from_filename("file.json") self.assertEqual(config_format, "json") confi
g_format = ConfigurationFactory.guess_format_from_filename("file.xml") self.assertEqual(config_format, "xml") def test_guess_format_no_extension(self): with self.assertRaises(Exception): ConfigurationFactory.guess_format_from_filename("file_yaml") def test_get_config_by_name(self):...
micjerry/groupservice
handlers/acceptmember.py
Python
apache-2.0
2,851
0.004911
import tornado.web import tornado.gen import json import io import logging import motor from bson.objectid import ObjectId import mickey.userfetcher from mickey.basehandler import BaseHandler class AcceptMemberHandler(BaseHandler): @tornado.web.asynchronous @tornado.gen.coroutine def post(self): ...
}) if append_result: self.set_status(200) publish.
publish_multi(add_members, notify) else: self.set_status(500) logging.error("add user failed %s" % groupid) return self.finish()
erik/sketches
projects/700c/web/views/api.py
Python
agpl-3.0
54
0
import flask mod = flask.
Blueprint('api', __name__)
cornell-cup/cs-minibot
minibot/hardware/communication/UDP.py
Python
apache-2.0
1,145
0.012227
# UDP code taken from < https://pymotw.com/2/socket/udp.html > import socket, time, fcntl, struct def udpBeacon(): # Create a UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADD...
r_address = (spliced_subnet, 5001) message = 'Hello, I am a minibot!' # Send message and resend every 9 seconds whi
le True: try: # Send data print('sending broadcast: "%s"' % message) sent = sock.sendto(bytes(message, 'utf8'), server_address) except Exception as err: print(err) time.sleep(9) def getIP(ifname): """ Returns the IP of the device """ s =...
KoffeinFlummi/AGM
.devfiles/stringtablediag.py
Python
gpl-2.0
3,247
0.018479
#!/usr/bin/env python3 import os import sys from xml.dom import minidom # STRINGTABLE DIAG TOOL # Author: KoffeinFlummi # --------------------- # Checks for missing translations and all that jazz. def get_all_languages(projectpath): """ Checks what languages exist in the repo. """ languages = [] for module i...
nt("\n\n### MARKDOWN ###") print("\nTotal number of keys: %i\n" % (keysum)) print("| Language | Missing Entries | Relevant Modules | % done |") print("|----------|----------------:|------------------|--------|") for i, language in enumerate(languages): if localizedsum[i] == keysum: print("| {} | 0 ...
( language, keysum - localizedsum[i], ", ".join(missing[i]), round(100 * localizedsum[i] / keysum))) if __name__ == "__main__": main()
licongyu95/learning_python
core_python_programming/cap2/two.py
Python
unlicense
180
0.05
#!/usr/bin/env python #encoding=utf-8 from onefile import * def two():
print "at two\n", def second(): print "at second\n", if __name__ == '__main__': two() #one() #first
()
YaguangZhang/EarsMeasurementCampaignCode
Trials/lib/Trial6_pySerial_Mod.py
Python
mit
857
0.012835
import serial port = "COM5" baud = 19200 try: ser = serial.Serial(port, baud, timeout=1) ser.isOpen() # try to open port, if possible print message and proceed with 'while True:' print ("port is opened!") except IOError: # if port is already opened, close it and open it again and print message ...
ser.close() exit() else
: ser.write(cmd.encode('ascii')) # out = ser.read() # print('Receiving...'+out) if __name__ == "__main__": main()
moto-timo/robotframework
src/robot/utils/__init__.py
Python
apache-2.0
3,555
0.000281
# Copyright 2008-2015 Nokia Solutions and Networks # # 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 l...
secs_to_timestr, timestamp_to_secs, timestr_to_secs, parse_time) from .robottypes import (is_bytes, is_dict_like, is_falsy, is_integer, is_list_like, is_number, is_string
, is_truthy, is_unicode, long, type_name, unicode, StringIO) from .setter import setter, SetterAwareType from .sortable import Sortable from .text import (cut_long_message, format_assign_message, pad_console_length, get_console_length, split_tags_from_doc, ...
hydroshare/hydroshare
hs_tracking/management/commands/tracking_popular.py
Python
bsd-3-clause
1,309
0.001528
""" Check tracking functions for proper output. """ from django.core.management.base import BaseCommand from hs_tracking.models import Variable class Command(BaseCommand): help = "check on tracking" def add_arguments(self, parser): parser.add_argument('--days', type=int, dest='days', default=31, ...
umber of resources to return') def handle(self, *args, **options): days = options['days'] n_resources = options['n_resources'] popular = Variable.popular_resources(days=days, n_resources=n_resources) for v in popular: print("users={} short_id={}" .form...
.format(v.created.strftime("%Y-%m-%d %H:%M:%S"), v.last_updated.strftime("%Y-%m-%d %H:%M:%S"))) print(" published={} public={} discoverable={} first author={}" .format(v.published, v.public, v.discoverabl...
aberdah/Stockvider
stockvider/stockviderApp/dbManager.py
Python
mit
33,602
0.01157
# -*- coding: utf-8 -*- import threading import logging import unittest import gc from stockviderApp.utils import retryLogger from stockviderApp.sourceDA.symbols.referenceSymbolsDA import ReferenceSymbolsDA from stockviderApp.localDA.symbols.dbReferenceSymbolsDA import DbReferenceSymbolsDA from stockviderApp.sourc...
s Quandl") self.logger.info("Début de l'update des symbols de référence") # Upate les symbols de référence for exchange in self.exchangeTuple: self.logger.info("Référence - ajout des symbols de " + str(exchange)) self._updateReferenceSymbols(exchange, self.inst...
rence") # Nettoie les doublons dans les symbols de ref entre Nyse et Nasdaq self._cleanDuplicatedReferenceSymbols() self.logger.info("Fin du nettoyage des symbols de référence") self.logger.info("Début du mapping des symbols de référence") # Mappe les symbols de référe...
finklabs/aws-deploy
botodeploy/tool.py
Python
mit
3,485
0.000287
#!/usr/bin/env python import os import sys import inspect from functools import update_wrapper import getpass import copy import click import signals from .config_reader import read_config from .utils import version, dict_merge from .defaults import DEFAULT_CONFIG # add fixture feature to pocoo-click def _make_comm...
er(), callback=new_func, params=params, **attrs) # patch in the custom command maker click.decorators._make_command = _make_command def _get_env(): """Read ENV environment variable. """ env = os.getenv('ENV', '') if env: env = env.lower() return env def _get_context(): ...
click_xtc = click.get_current_context() context = { 'tool': click_xtc.parent.info_name, 'command': click_xtc.info_name, 'version': version(), 'user': getpass.getuser() } env = _get_env() if env: context['env'] = env return context def lifecycle(): """T...
YangTe1/site_at_will
site_at_will/zhihu/urls.py
Python
gpl-3.0
470
0.010638
from django.conf.
urls import url from . import views urlpatterns = [ url(r'psycholagny/', views.psycholagny_zhihu_user, name="psycholagny_zhihu_user"), ur
l(r'followed_zhihu_user/add/', views.add_followed_zhihu_user, name="add_followed_zhihu_user"), url(r'ajax_hidden_zhihu_user/', views.ajax_hidden_zhihu_user, name="ajax_hidden_zhihu_user"), url(r'ajax_select_many_zhihu_user/', views.ajax_select_many_zhihu_user, name="ajax_select_many_zhihu_user"), ]
dramatis/dramatis
lib/dramatis/actor/interface.py
Python
mit
4,979
0.011448
from __future__ import absolute_import from __future__ import with_statement import time from logging import warning import dramatis class Interface(object): """provides actors with control over their runtime dynamics A dramatis.Actor.Interface object provides actors that have mixed in dramatis.Actor ac...
e( sleeper ). continuation( { "continuation": "rpc",
"nonblocking": True } ) ).nap( t ) self._actor.actor_send( [ "actor_yield" ], { "continuation": "rpc", "nonblocking": True } ) return None def become(self, behavior): """The actor behavior is changed to the pr...
FabriceSalvaire/PyOpenGLng
examples/high-level-api-demo/ShaderProgramesV3.py
Python
gpl-3.0
3,221
0.009935
#################################################################################################### # # PyOpenGLng - An OpenGL Python Wrapper with a High Level API. # Copyright (C) 2014 Fabrice Salvaire # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Pu...
he Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU
General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # #################################################################################################### ###############################...
plotly/plotly.py
packages/python/plotly/plotly/validators/bar/_uirevision.py
Python
mit
398
0
import _plotly_utils.basevalidators class UirevisionValidator(
_plotly_utils.basevalidators.AnyValidator): def __init__(self, plotly_name="uirevision", parent_name="bar", **kwargs): super(UirevisionValid
ator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), **kwargs )
diblaze/TDP002
Old Exams/201510/Uppgift3.py
Python
mit
1,026
0
#! /usr/env/bin python3 def scrape_rates(filename): dict_rate = {} with open(filename) as f: for line in f.readlines(): line = line.split(
"\t") line[1] = line[1].replace("\n", "") line[1] = line[1].replace(",", ".") dict_rate[line[0]] = line[1] return dict_rate def convert_to_sek(string,
dict_rate): string = string.split(" ") if len(string) == 2: currency_multiply = dict_rate[string[0]] value = string[1] return float(currency_multiply) * float(value) else: return float(string[0]) if __name__ == "__main__": dict_rate = scrape_rates("exchange_rates.txt...
Zarthus/Reconcile
modules/topic.py
Python
mit
2,286
0.001312
""" The MIT License (MIT) Copyright (c) 2014 - 2015 Jos "Zarthus" Ahrens and contributors 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 rig...
stribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, s
ubject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS...
xczh/ccoin
modules/__init__.py
Python
apache-2.0
185
0.021622
#!/usr/bin/env python #coding:utf-8 """ Purpose: ccoin Modules Package Author: xczh <christopher.winnie2012@gmail.com> Copyright (c) 2015 xczh. All r
ights reserved. ""
"
dymkowsk/mantid
Framework/PythonInterface/test/python/plugins/algorithms/VesuvioThicknessTest.py
Python
gpl-3.0
3,285
0.005479
from __future__ import (absolute_import, division, print_function) import unittest import platform import num
py as np from mantid.simpleapi import VesuvioThickness from mantid.api import ITableWorkspace class VesuvioThicknessTest(unittest.TestCase): #----------------------------------Algorithm tests---------------------------------------- def test_basic_input(self): # Original test values
from fortran routines masses = [1.0079, 27.0, 91.0] amplitudes = [0.9301589, 2.9496644e-02, 4.0345035e-02] trans_guess = 0.831 thickness = 5.0 number_density = 1.0 dens_table, trans_table = VesuvioThickness(Masses=masses, ...
jelly/calibre
src/calibre/ebooks/lrf/html/table.py
Python
gpl-3.0
13,980
0.001788
__license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' import math, sys, re from calibre.ebooks.lrf.fonts import get_font from calibre.ebooks.lrf.pylrs.pylrs import TextBlock, Text, CR, Span, \ CharButton, Plot, Paragraph, \ ...
l((float(self.conv.profile.dpi)/72.)*(pts/10.)) def minimum_width(self): return max([self.minimum_tb_width(tb) for tb in self.text_blocks]) def minimum_tb_wi
dth(self, tb): ts = tb.textStyle.attrs default_font = get_font(ts['fontfacename'], self.pts_to_pixels(ts['fontsize'])) parindent = self.pts_to_pixels(ts['parindent']) mwidth = 0 for token, attrs in tokens(tb): font = default_font if isinstance(token, int):...
sigmapi-gammaiota/sigmapi-web
sigmapiweb/apps/PubSite/views.py
Python
mit
4,610
0.000651
""" Views for PubSite app. """ from django.conf import settings from django.contrib.auth.views import ( PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView, ) from django.shortcuts import render import requests import logging logger = logging.getLogger(__name__...
dResetCompleteView): template_name
= "password_reset/password_reset_complete.html"
jzcxer/0Math
python/dictionary/Merriam_Webster_api.py
Python
gpl-3.0
987
0.020263
from lxml import etree import requests import re #coding utf-8 def getResource(word): r = requests.get("http://www.dictionaryapi.com/api/v1/references/learners/xml/"+word+"?key=508b6e11-3920-41fe-a57a-d379deacf188") return r.text[39:] def isWord(entry,word): g=re.compile(entry) return re.fullmatch(word...
en.tag=="def": for x in children: if x.tag=="dt": if x.text is not None: meanings.append(x.text[1:]) return meanings # main loop def getDefintion(word): root = etree.XML(getResou
rce(word), etree.XMLParser(remove_blank_text=True)) meaning_list=[] for entry in root: if isWord(entry.attrib["id"],word): meaning_list.append(parse_entry(entry)) return meaning_list
MSeifert04/astropy
astropy/units/format/generic.py
Python
bsd-3-clause
18,514
0.000162
# Licensed under a 3-clause BSD style license - see LICENSE.rst # This module includes files automatically generated from ply (these end in # _lextab.py and _parsetab.py). To generate these files, remove them from this # folder, then build astropy and run the tests in-place: # # python setup.py build_ext --inplace #...
parts.append(f'({unit_list})') return ' '.join(parts) elif isinstance(unit, core.NamedUnit): return cls._get_unit_name(unit) class Generic(Base): """ A "generic" format. The syntax of the format is based directly on the FITS standard, but instead of only supporting the ...
""" _show_scale = True _tokens = ( 'DOUBLE_STAR', 'STAR', 'PERIOD', 'SOLIDUS', 'CARET', 'OPEN_PAREN', 'CLOSE_PAREN', 'FUNCNAME', 'UNIT', 'SIGN', 'UINT', 'UFLOAT' ) @classproperty(lazy=True) def _all...
nettitude/PoshC2
poshc2/client/command_handlers/SharpHandler.py
Python
bsd-3-clause
21,566
0.002782
import base64, re, traceback, os, string, subprocess from prompt_toolkit import PromptSession from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.styles import Style from poshc2.client.Alias import cs_alias, cs_replace from poshc2.Colours im...
(user, command, randomuri) return elif command.startswith("m
igrate"): do_migrate(user, command, randomuri) return elif command == "kill-implant" or command == "exit": do_kill_implant(user, command, randomuri) return elif command == "sharpsocks": do_sharpsocks(user, command, randomuri) return elif (command.startswith("s...
anpe9592/projectEuler
11-20/problem12.py
Python
mit
273
0.007326
#
problem12.py import math x = 0 z = 0 n = 1 i = True while i != False: z = n * (n + 1) / 2 x = 2 y = int(math.sqrt(z)) for k in range(2, y): if z % k == 0: x += 2 if x == 500: i = False n += 1 print(
z)
caspervg/pylex
src/pylex/user.py
Python
mit
1,830
0
import requests from .route import Route class UserRoute(Route): def me(self): """ Return the currently authenticated user :rtype: dict """ return self._get_json('user') def user(self, id): """ Return the user with given id :rtype: dict ...
'email': email, 'fullname': full_name }) r.raise_for_status() else: raise Exception('None of th
e arguments may be "None"') def activate(self, key): """ Activates a new registree on the LEX with given activation key :rtype: None """ url = self._base + 'user/activate' r = requests.get(url, params={ 'activation_key': key }) r.raise_for...
zach-morris/plugin.program.iarl
resources/lib/historydat_parser.py
Python
gpl-2.0
6,720
0.001637
from __future__ import print_function import sys import re import string #TODO: # * fail if an unexpected state occurs _verbose = False _echo_file = False class Game: regex = re.compile(r'(.+)\s+\(c\)\s+([0-9]+)\s+(.+)') def __init__(self, systems, romnames): self.systems = systems self....
tateInfo.STATE_BIO) state_info.game = game elif state_info.state is StateInfo.STATE_BIO: if parsed is not None: if parsed[0] is self.TOKEN_END:
state_info = StateInfo(StateInfo.STATE_END) else: state_info.game._add_to_bio(line) else: raise Exception('Unexpected parse state') if _verbose: if len(self._unknown_systems) > 0: print("Found unknown game syste...
chipaca/snapcraft
tests/unit/store/test_store_client.py
Python
gpl-3.0
63,982
0.000797
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright 2016-2021 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the ...
mVhdAowMDE5dmlkIHRlc3QgdmVyaWZpYWNpb24KMDAxN2NsIGxvY2FsaG9zdDozNTM1MQowMDBmc2lnbmF0dXJlIAo", file=config_fd, ) print( "unbound_discharge=MDAwZWxvY2F0aW9uIAowMDEwaWRlbnRpZmllciAKMDAwZnNpZ25hdHVyZSAK", file=config_fd, ) config...
self.client.login(config_fd=config_fd) self.assertThat( self.client.auth_client._conf.get("macaroon"), Equals( "MDAwZWxvY2F0aW9uIAowMDEwaWRlbnRpZmllciAKMDAxNGNpZCB0ZXN0IGNhdmVhdAowMDE5dmlkIHRlc3QgdmVyaWZpYWNpb24KMDAxN2NsIGxvY2FsaG9zdDozNTM1MQowMDBmc2lnbmF0dXJ...
marvinpinto/charlesbot
tests/slack/test_slack_base_object_children.py
Python
mit
1,314
0
import unittest from charlesbot.slack.slack_channel_joined import SlackChannelJoined from charlesbot.slack.slack_channel_left import SlackChannelLeft from charlesbot.slack.slack_group_joined import SlackGroupJoined from charlesbot.slack.slack_group_left import SlackGroupLeft from charlesbot.slack.slack_message import S...
atible(object_dict)) def test_slack_channel_left_compatibility(self): sc = SlackChannelLeft() object_dict = {"type": "channel_left"} self.assertTrue(sc.is_compatible(object_dict)) def test_slack_group_joined_compatibility(
self): sc = SlackGroupJoined() object_dict = {"type": "group_joined"} self.assertTrue(sc.is_compatible(object_dict)) def test_slack_group_left_compatibility(self): sc = SlackGroupLeft() object_dict = {"type": "group_left"} self.assertTrue(sc.is_compatible(object_dict...
obi-two/Rebelion
data/scripts/templates/object/draft_schematic/space/armor/shared_mass_reduction_kit_mk4.py
Python
mit
463
0.047516
#### 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 = Intangible() result.template = "object/draft_schematic/space/armor/shared_mass_reduction_kit_mk4.iff" result.attribute_template_id = -1 result.stfName("string_id_table","") #### BEGIN MODIFICATIONS...
ND MODIFICATIONS #### return result
pombredanne/django-avocado
avocado/store/tests/models.py
Python
bsd-3-clause
4,138
0.000483
from django.test import TestCase from django.core.cache import cache as mcache from django.contrib.auth.models import User from django.core.urlresolvers import reverse from avocado.store.models import Scope, Perspective, Report __all__ = ('ScopeTestCase', 'PerspectiveTestCase', 'ReportTestCase') class ScopeTestCase(...
Up(self): mcache.clear() self.user = User.objects.get(id=1) self.client.login(username='foo', password='foo') self.request = Object() self.request.user = self.user self.request.session = self.client.session self.report = Report() self.report.scope = Sco...
.report.perspective = Perspective() def test_resolve_caching(self): session = self.request.session self.report.resolve(self.request, 'html') cache = session[Report.REPORT_CACHE_KEY] ts1 = cache['timestamp'] self.report.resolve(self.request, 'html') ts2 = cache['tim...
primecloud-controller-org/pcc-cli
src/pcc/api/instance/stop_all_instance.py
Python
apache-2.0
327
0.006116
# -*- co
ding: utf-8 -*- def command(): return "stop-all-instance" def init_argument(parser): parser.add_argument("--farm-no", required=True) def execute(requester, args): farm_no = args.farm_no parameters = {} parameters["FarmNo"] = farm_no return requester.execute("/StopAllInstan
ce", parameters)
nsalomonis/AltAnalyze
import_scripts/filterFASTA.py
Python
apache-2.0
619
0.017771
from Bio import SeqIO import sys, string fasta_file = "/Users/saljh8/GitHub
/altanalyze/AltDatabase/EnsMart72/Hs/SequenceData/Homo_sapiens.GRCh37.72.cdna.all.fa" # Input fasta file result_file = "/Users/saljh8/GitHub/altanalyze/AltDatabase/EnsMart72/Hs/SequenceData/Homo_sapiens.GRCh37.72.cdna.all.filtered.fa" # Output fasta file fasta_sequences = SeqIO.parse(open(fasta_file),'fast...
SeqIO.write([seq], f, "fasta") except: continue
shagabutdinov/sublime-method
method.py
Python
mit
6,962
0.020684
import sublime import sublime_plugin import re from xml.dom import minidom try: from Expression import expression except ImportError as error: sublime.error_message("Dependency import failed; please read readme for " + "Method plugin for installation instructions; to disable this " + "message remove this pl...
if filename == None: if null: filename = language + '-method-call-null.sublime-snippet' else: filename = language + '-method-call.sublime-snippet' return _get_snippet_body(filename) def get_method_snippet(langua
ge, filename = None): if filename == None: filename = language + '-method.sublime-snippet' return _get_snippet_body(filename) def _get_snippet_body(filename): snippets = sublime.find_resources(filename) if len(snippets) == 0: raise Exception('Snippet "' + filename + '" not found') snippet = sublime...
eiriniar/CellCnn
cellCnn/utils.py
Python
gpl-3.0
12,947
0.00363
""" Copyright 2016-2017 ETH Zurich, Eirini Arvaniti and Manfred Claassen. This module contains utility functions. """ import os import errno from collections import Counter import numpy as np import pandas as pd import copy from cellCnn.downsample import random_subsample, kmeans_subsample, outlier_subsample from ce...
lters from the 3 best if np.sort(accuracies)[-3] < accur_thres: accur_thres = np.sort(accuracies)[-3] # combine filters from multiple models for i, params in param_dict.items(): if accuracies[i] >= accur_thres: W_tot = keras_param_vector(params) accum.append(W_tot) ...
stack(accum) # perform hierarchical clustering on cosine distances Z = linkage(w_strong[:, :nmark+1], 'average', metric='cosine') clusters = fcluster(Z, dendrogram_cutoff, criterion='distance') - 1 c = Counter(clusters) cons = [] for key, val in c.items(): if val > 1: member...
lukasmarshall/embedded-network-model
tariffs.py
Python
mit
22,618
0.014015
import numpy as np import pandas as pd import datetime class Tariffs : def __init__(self, scheme_name, retail_tariff_data_path, duos_data_path, tuos_data_path, nuos_data_path, ui_tariff_data_path): self.scheme_name = scheme_name self.retail_tariff_data_path = retail_tariff_data_path self.du...
ar_cap_1'] # If below or equal to the threshold, return the relevant solar rate in $/kWh. if solar_capacity <= solar_capacity_threshold: retail_solar_tariff = self.retail_tariff_data.loc[retail_tariff_type,'solar_tariff_1'] # Else return the rate for systems above the threshold. ...
lar_tariff def get_fixed_tariff(self, fixed_period_minutes, retail_tariff_type): """Fixed tariff component from retail tariff data. Returns fixed value expressed per fixed period minutes (input).""" fixed_tariff = self.retail_tariff_data.loc[retail_tariff_type,'daily_charge'] * (float(fixed_period_...
yuginboy/from_GULP_to_FEFF
feff/libs/determine_numbers_of_target_atoms.py
Python
gpl-3.0
2,071
0.005311
''' * Created by Zhenia Syryanyy (Yevgen Syryanyy) * e-mail: yuginboy@gmail.com * License: this code is under GPL license * Last modified: 2017-10-24 ''' import re import os class TargetAtom(): def __init__(self): self.path_to_cfg_file = '' self.atom_type = 'Mn' self.number_of_target_atoms =...
lf.number_o
f_target_atoms is None: self.read_cfg_file() if self.number_of_target_atoms is not None: return int(self.number_of_target_atoms) else: return int(self.number_of_target_atoms) def print_info(self): txt = '==========================================...
Chilledheart/chromium
tools/telemetry/telemetry/value/skip_unittest.py
Python
bsd-3-clause
1,626
0.004305
# 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. import os import unittest from telemetry import story from telemetry import page as page_module from telemetry import value from telemetry.value import skip class TestBase(unittest.TestCase): def setUp(self): story_set = story.StorySet(base_dir=os.path.dirname(__file__)) story_...
tp://www.bar.com/', story_set, story_set.base_dir)) self.story_set = story_set @property def pages(self): return self.story_set.stories class ValueTest(TestBase): def testBuildbotAndRepresentativeValue(self): v = skip.SkipValue(self.pages[0], 'page skipped for testing reason') self.assertIsNone(...
rtucker/sycamore
Sycamore/i18n/it.py
Python
gpl-2.0
19,046
0.026672
# -*- coding: iso-8859-1 -*- # Text translations for Italiano (it). # Automatically generated - DO NOT EDIT, edit it.po instead! meta = { 'language': 'Italiano', 'maintainer': 'gian paolo ciceri <gp.ciceri@acm.org>', 'encoding': 'iso-8859-1', 'direction': 'ltr', } text = { '''(last edited %(time)s by %(editor)s...
tamp)s da parte di %(owner)s, o perlomeno ne ha richiesto un\'anteprima a quell\'ora.<br> <strong class="highlight">Dovresti <em>evitare di modificare</em> questa pagina per almeno altri %(mins_valid)d m
inuti per non incorrere in probabili conflitti.</strong><br> Premi il pulsante "Annulla" per lasciare l\'editor.''', '''<unknown>''': '''<informazione non disponibile>''', '''Info''': '''Informazioni''', '''Edit''': '''Modifica''', '''UnSubscribe''': '''Annulla sottoscrizione''', '''Subscribe''': '''Sottoscrivi''', '''...
dilworm/pytest
redisinfo/redisclient.py
Python
gpl-2.0
5,692
0.008784
#-*-coding=utf8-*- import asyncore, socket, time import redisproto as rp import threading import traceback import Queue,logging logger = logging.getLogger("cf") CONN_TIMEOUT = 15 class RedisClient(asyncore.dispatcher): redis_reply = ''# redis reply, bulk strings recv_size = 0 wflag = False rflag = False # pre...
connected def is_connecting(self): return self.connecting def handle_close(self): print "{0}: handle close {1}:{2}".format(time.time(), self.host, self.port) #traceback.print_stack() self.set_reada
ble(False) self.set_writable(False) self.close() # remove old socket from asyncore pollable channel # add new socket to poolable channel self.create_socket(socket.AF_INET, socket.SOCK_STREAM) ''' --------------- Test ----------------- r = RedisClient('127.0.0.1', 52021) r.asyn_info() c...
etherkit/OpenBeacon2
macos/venv/lib/python3.8/site-packages/_pyinstaller_hooks_contrib/hooks/stdhooks/hook-gadfly.py
Python
gpl-3.0
458
0
# ------------------------------------------------------------------ # Copyright (c) 2020 PyInstaller
Development Team. # # This file is distributed under the terms of the GNU General Public # License (version 2.0 or later). # # The full license is available in LICENSE.GPL.txt, distributed with # this software. # # SPDX-License-Identifier
: GPL-2.0-or-later # ------------------------------------------------------------------ hiddenimports = ["sql_mar"]
adviti/melange
thirdparty/google_appengine/google/storage/speckle/python/api/rdbms.py
Python
apache-2.0
22,582
0.00806
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
k(statement, args) response = self._conn.MakeRequest('Exec', request) result = response.result if result.HasField('sql_exception'): raise DatabaseError('%d: %s' % (result.sql_exception.code, result.sql_exception.message)) self._rows = collections.deque() ...
label, column.type, column.display_size, None, column.precision, column.scale, column.nullable)) else: self._description = None if result.rows.tuples: assert self._description, 'Column descriptions do not exist.' column_names = [col[0] for col in self._description] self._ro...
yangleo/cloud-github
openstack_dashboard/enabled/_9001_developer.py
Python
apache-2.0
948
0
# Copyright 2015 Cisco Systems, 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 wr...
xpress or implied. # See the License for the specific language governing permissions and # limitations under the License. from django.conf import settings DASHBOARD = 'developer' ADD_ANGULAR_MODULES = [ 'horizon.dashboard.developer' ] ADD_INSTALLED_APPS = [ 'openstack_dashboard.contrib.developer' ] ADD_SCS...
LED = True if getattr(settings, 'DEBUG', False): DISABLED = False
brianwc/juriscraper
opinions/united_states/state/calctapp_2nd.py
Python
bsd-2-clause
472
0.002119
# Scraper for California's Second District Court of Appeal # CourtID: calctapp_2nd # Court Short Name: Cal. Ct. App. fr
om juriscraper.opinions.united_states.state import cal class Site(cal.Site):
def __init__(self): super(Site, self).__init__() self.url = 'http://www.courtinfo.ca.gov/cgi-bin/opinions-blank.cgi?Courts=B' self.court_id = self.__module__ def _get_divisions(self): return ['2nd App. Dist.'] * len(self.case_names)
xin3liang/platform_external_chromium_org_third_party_WebKit
Tools/Scripts/webkitpy/common/checkout/baselineoptimizer.py
Python
bsd-3-clause
17,896
0.003856
# Copyright (C) 2011, Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the...
or directory in directories: path = self._join_directory(directory, baseline_name) if self._filesystem.exists(path): results_by_directory[directory] = self._filesystem.sha1
(path) return results_by_directory def _results_by_port_name(self, results_by_directory, baseline_name): results_by_port_name = {} for port_name in self._port_names: for directory in self._relative_baseline_search_paths(port_name, baseline_name): if directory in ...
dimtruck/magnum
magnum/common/pythonk8sclient/swagger_client/models/v1_service_status.py
Python
apache-2.0
2,814
0
# coding: utf-8 """ Copyright 2015 SmartBear Software 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...
st): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[att
r] = value.to_dict() else: result[attr] = value return result def to_str(self): """ Return model properties str """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return se...
googleapis/python-appengine-admin
samples/generated_samples/appengine_v1_generated_services_get_service_sync.py
Python
apache-2.0
1,416
0.000706
# -*- coding: utf-8 -*- # Copyright 2022 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...
in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-appengine-admin # [START appengine_v1_generated_Services_GetService_sync] from google.cloud import appengine_admin_v1 def sample_get_service(): # Create a client client...
onse = client.get_service(request=request) # Handle the response print(response) # [END appengine_v1_generated_Services_GetService_sync]
ruchee/vimrc
vimfiles/bundle/vim-python/submodules/pylama/pylama/config.py
Python
mit
8,032
0
"""Parse arguments from command line and configuration files.""" import fnmatch import os import sys import re import logging from argparse import ArgumentParser from . import __version__ from .libs.inirama import Namespace from .lint.extensions import LINTERS #: A default checkers DEFAULT_LINTERS = 'pycodestyle', '...
choices=['pep8', 'pycodestyle', 'pylint', 'parsable'], help="Choose errors format (pycodestyle, pylint, parsable).") PARSER.add_argument( "--select", "-s", default=_Default(''), type=split_csp_str, help="Select errors and warnings. (comma-separated list)") PARSER.add_argument( "--sort", default=_Defa...
help="Sort result by error types. Ex. E,W,D") PARSER.add_argument( "--linters", "-l", default=_Default(','.join(DEFAULT_LINTERS)), type=parse_linters, help=( "Select linters. (comma-separated). Choices are %s." % ','.join(s for s in LINTERS) )) PARSER.add_argument( "--ignore", "-i", ...
dayaftereh/scripts
python/tcu/lib/config.py
Python
apache-2.0
3,690
0.002168
import os import json import logging _DEFAULT_CONFIG_DIR = "config" _DEFAULT_CONFIG_NAME = "config.json" _DEFAULT_LOG_CONFIG_NAME = "default_log.json" ###################################################################################################### def load(path): json_content = _load_json(path) loggin...
default_value=None): self._valid_content() path = map(lambda x: x.strip(), key.split('.')) value = self._find(self._content, path) if value is None: return default_value return value ################################################################################...
nt(self, key): value = self.get(key) return int(value) def as_int_default(self, key, default_value=None): value = self.get_default(key, default_value) return int(value) def as_float(self, key): value = self.get(key) return float(value) def as_float_default(...
llby/tasks-for-notebook
tasks_for_notebook/tasks_for_notebook.py
Python
mit
3,217
0.020827
import os import json import pandas import numpy from IPython.display import HTML from datetime import datetime import pandas_highcharts.core title_name = 'Tasks' file_name = 'tasks.csv' css_dt_name = '//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css' js_dt_name = '//cdn.datatables.net/1.10.12/js/jquery.data...
ime("%Y/%m/%d %H:%M:%S") }], columns = ['name', 'content', 'status', 'created_at', 'updated_at'
]) data = data.append(df, ignore_index=True) save_task(data) def render_task(data): js = ''' <link rel='stylesheet' type='text/css' href='%s'> <script> require.config({ paths: { dataTables: '%s' } }); require(['dataTables'], function(){ $('.dataframe').D...
wchan/tensorflow
tensorflow/contrib/learn/python/learn/ops/dnn_ops.py
Python
apache-2.0
2,001
0
"""TensorFlow ops for deep neural networks.""" # Copyright 2015-present The Scikit Flow 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.apac...
e, will add a dropout layer with given probability. Returns: A tensor which would be a deep neural network. """ with vs.variable_scope('dnn'): for i, n_units in enumerate(hidden_units): with vs.variable_scope('layer%d' % i): tensor_in = rnn_cell....
tensor_in = activation(tensor_in) if dropout is not None: tensor_in = dropout_ops.dropout(tensor_in, prob=(1.0 - dropout)) return tensor_in
ff94315/hiwifi-openwrt-HC5661-HC5761
staging_dir/host/lib64/scons-2.1.0/SCons/Script/SConscript.py
Python
gpl-2.0
24,428
0.002702
"""SCons.Script.SConscript This module defines the Python API provided to SConscript and SConstruct files. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software an...
raise SCons.Errors.UserError("Return of non-existent variable '%s'"%x) if len(retval) == 1: call_stack[-1].retval = retval[0] else: call_stack[-1].retval = tuple(retval) stop = kw.get('stop', True) if stop: raise SConscriptReturn st
ack_bottom = '% Stack boTTom %' # hard to define a variable w/this name :) def _SConscript(fs, *files, **kw): top = fs.Top sd = fs.SConstruct_dir.rdir() exports = kw.get('exports', []) # evaluate each SConscript file results = [] for fn in files: call_stack.append(Frame(fs, exports, fn...
ardi69/pyload-0.4.10
pyload/plugin/crypter/FiletramCom.py
Python
gpl-3.0
843
0.017794
# -*- coding: utf-8 -*- from pyload.plugin.internal.SimpleCrypter import SimpleCrypter class FiletramCom(SimpleCrypter): __name = "FiletramCom" __type = "crypter" __version = "0.03" __pattern = r'http://(?:www\.)?filetram\.com/[^/]+/.+' __config = [("use_premium" , "bool", "Use prem...
"bool", "Save package to subfolder" , True), ("subfolder_per_pack", "bool", "Create a subfolder for each package", True)] __description = """Filetram.com decrypter plugin""" __license = "GPLv3" __authors = [("igel", "igelkun@myopera.com"), ("sticke...
K_PATTERN = r'\s+(http://.+)' NAME_PATTERN = r'<title>(?P<N>.+?) - Free Download'
hhjiang/mcores
setup.py
Python
mit
436
0
from distutils.core import setup, Extension import numpy from Cython.Distutils import build_ext setup( name='MCores', vers
ion='1.0', cmdclass={'build_ext': build_ext}, ext_modules=[Extension("MCores", sources=["kernelModesCluster.pyx"], language="c++", include_dirs=[numpy.get_include()])], author='Heinrich Jiang', autho
r_email='heinrich.jiang@gmail.com' )
jamslevy/gsoc
app/django/core/mail.py
Python
apache-2.0
14,299
0.001818
""" Tools for sending email. """ import mimetypes import os import smtplib import socket import time import random from email import Charset, Encoders from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.Header import Header from email.Utils i...
F-8 messages so that we avoid unwanted attention from # some spam filters. Charset.add_charset('utf-8', Charset.SHORTEST, Charset.QP, 'utf-8') # Default MIME type to use on attachments (if it is not explicitly give
n # and cannot be guessed). DEFAULT_ATTACHMENT_MIME_TYPE = 'application/octet-stream' # Cache the hostname, but do it lazily: socket.getfqdn() can take a couple of # seconds, which slows down the restart of the server. class CachedDnsName(object): def __str__(self): return self.get_fqdn() def get_fqdn...
PowerDNS/exabgp
lib/exabgp/reactor/network/connection.py
Python
bsd-3-clause
7,221
0.041961
# encoding: utf-8 """ network.py Created by Thomas Mangin on 2009-09-06. Copyright (c) 2009-2013 Exa Networks. All rights reserved. """ import time import random import socket import select from struct import unpack from exabgp.configuration.environment import environment from exabgp.util.od import od from exabgp.u...
' % (self.local,self.peer)),od,read)) yield data return yield '' except socket.timeout,e: self.close() self.logger.wire("%s %s peer is too slow" % (self.name(),self.peer)) raise TooSlowError('Timeout while reading data from the network
(%s)' % errstr(e)) except socket.error,e: if e.args[0] in error.block: message = "%s %s blocking io problem mid-way through reading a message %s, trying to complete" % (self.name(),self.peer,errstr(e)) if message != reported: reported = message self.logger.wire(message,'debug') yield ...
luotao1/Paddle
python/paddle/fluid/tests/unittests/tokenizer/__init__.py
Python
apache-2.0
613
0.004894
# Copyright (c) 2021 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 ap...
KIND, either express or
implied. # See the License for the specific language governing permissions and # limitations under the License.
gryzz/uCall
utils/asterisk-connector/ami2stomp.py
Python
gpl-3.0
3,524
0.004824
#!/usr/bin/env python # vim: set expandtab shiftwidth=4: # http://www.voip-info.org/wiki/view/asterisk+manager+events import asterisk.manager import sys,os,time import simplejson as json from stompy.simple import Client import ConfigParser from sqlobject import * from handlers.command_handler_factory import CommandHan...
manager.ManagerAuthException, reason: # print "Error logging in to the manager: %s" % reason #except asterisk.manager.ManagerException, re
ason: # print "Error: %s" % reason #except: # sys.exit() #finally: manager.close()
luizfelippesr/galmag
galmag/analysis/visualization.py
Python
gpl-3.0
8,599
0.021282
import matplotlib.pyplot as plt import numpy as np """ Contains functions to facilitate simple ploting tasks """ def std_setup(): """ Adjusts matplotlib default settings""" from cycler import cycler plt.rc('image', cmap='viridis') plt.rc('xtick', labelsize=14) plt.rc('ytick', labelsize=14) plt...
r',['#1f78b4','#a6cee3','#33a02c','#b2df8a', '#e31a1c','#fb9a99','#ff7f00','#fdbf6f', '#6a3d9a','#cab2d6']) plt.rcParams['lines.linewidth'] = 1.65 def plot_r_z_uniform(B,skipr=3,skipz=5, quiver=True, contour=True, quiv...
: """ Plots a r-z slice of the field. Assumes B is created using a cylindrical grid - for a more sophisticated/flexible plotting script which does not rely on the grid structure check the plot_slice. The plot consists of: 1) a coloured contourplot of :math:`B_\phi` 2) quivers showing th...
jtopjian/st2
st2actions/tests/unit/test_notifier.py
Python
apache-2.0
4,699
0.003405
# Licensed to the StackStorm, Inc ('StackStorm') 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 th...
tifier import Notifier from st2common.constants.triggers import INTERNAL_TRIGGER_TYPES from st2common.models.db.liveaction import LiveActionDB from st2common.models.db.notification import NotificationSchema from st2common.models.db.notification import NotificationSubSchema from st2common.persistence.action import Actio...
NTERNAL_TRIGGER_TYPES['action'][1] MOCK_EXECUTION_ID = '287r8383t5BDSVBNVDNBVD' class NotifierTestCase(unittest2.TestCase): class MockDispatcher(object): def __init__(self, tester): self.tester = tester self.notify_trigger = ResourceReference.to_string_reference( p...
cscanlin/munger-builder
munger_builder/forms.py
Python
mit
269
0.003717
from django.contrib.auth.models import Use
r from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django import forms class UserRegistrationForm(UserCreationForm): class Meta: model = User fields = ('username', 'ema
il',)
mhugent/Quantum-GIS
tests/src/python/test_qgscomposershapes.py
Python
gpl-2.0
3,326
0.00391
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsComposerShape. .. note:: 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. """ ...
es_ellipse', self.mComposition) myTestResult, myMessage = checker.testComposition() assert myTestResult == True, myMessage def testTriangle(self): """Test triangle composer shape""" self.mComposerShape.setShapeType(QgsComposerShape.Triangle) checker = QgsCompositionChecke...
essage def testRoundedRectangle(self): """Test rounded rectangle composer shape""" self.mComposerShape.setShapeType(QgsComposerShape.Rectangle) self.mComposerShape.setCornerRadius(30) checker = QgsCompositionChecker('composershapes_roundedrect', self.mComposition) myTestRe...
takeshineshiro/heat
heat/scaling/rolling_update.py
Python
apache-2.0
1,960
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
new size of the group and the number of members that may receive the new definition (by a c
ombination of creating new members and updating existing ones). Inputs are the target size for the group, the current size of the group, the number of members that already have the latest definition, the batch size, and the minimum number of members to keep in service during a rolling update. "...
xbed/Mixly_Arduino
mixly_arduino/mpBuild/common/esptool.py-script.py
Python
apache-2.0
442
0
#!c:\users\fredqian\appdata\local\programs\python
\python36-32\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'esptool==2.3.1','console_scripts','esptool.py' __requires__ = 'esptool==2.3.1' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( loa...
=2.3.1', 'console_scripts', 'esptool.py')() )
harveyr/thunderbox
app/lintblame/git.py
Python
mit
2,301
0
import subprocess import re import os from app import util BLAME_NAME_REX = re.compile(r'\(([\w\s]+)\d{4}') def git_path(path): """Returns the top-level git path.""" dir_ = path if os.path.isfile(path): dir_ = os.path.split(path)[0] proc = subprocess.Popen( ['git', 'rev-parse', '--sh...
rr = proc.communicate() if err: return None return out.strip() def git_branch_files(path): path = util.path_dir(path) if not path: raise Exception("Bad path: {}".format(path)) top_dir = git_path(path) proc = subprocess.Popen( ["git", "diff", "--name-only"], st...
out = proc.communicate()[0] all_files = set(out.splitlines()) branch = git_branch(path) if branch != 'master': proc = subprocess.Popen( ["git", "diff", "--name-only", "master..HEAD"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=path ...
mavarick/spider-python
webspider/settings/default_params.py
Python
gpl-2.0
1,332
0.012763
""" global params """ # url database default_url_db = {"host": "127.0.0.1", "port": 3306, "username": "root", "password": "", "database": "liuxf", "charset": "utf8", "tablename": "url"} # proxy database default_proxy_db = {"host": ...
00 # default queue size DEFAULT_QUEUE_TIMEOUT = 0.0001 # default queue timeout # Links pattern RE_PATTERN_URL = [ (r'href\s*=\s*(\'|\")(.+?)(\1)', 2), # represent the 2nd brackets, # in use ,should be result[1] ] # log config file relative pa...
or openning one url URL_OPEN_TIMEOUT = 5 # monitor relative params # Monitor Info Queue length, which decides exit time when program exits MONITOR_QUEUE_LEN = 5 # result Queue Max size RESULT_QUEUE_MAX_SIZE = 100 # get or put timeout for queue QUEUE_TIMEOUT = 0.001
dmazzella/uble
micropython-lib/collections/__init__.py
Python
mit
401
0
try: from collections import namedtuple, OrderedDict, deque, defaultdict except ImportError: try: from ucollec
tions import namedtuple, OrderedDict, deque except ImportError: from ucollections import namedtuple, OrderedDict if "deque" not in globals(): from .deque import deque if "d
efaultdict" not in globals(): from .defaultdict import defaultdict
LordDamionDevil/Lony
lib/discord/ext/commands/context.py
Python
gpl-3.0
4,638
0.001509
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2015-2016 Rapptz Permission is hereby granted, free of
charge, to any person obtain
ing a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished ...
start-jsk/jsk_apc
demos/instance_occlsegm/instance_occlsegm_lib/contrib/instance_occlsegm/models/fcn/fcn16s_resnet_occlusion.py
Python
bsd-3-clause
3,904
0
import chainer import chainer.functions as F import chainer.links as L from chainer_mask_rcnn.models.mask_rcnn_resnet import _copy_persistent_chain from chainer_mask_rcnn.models.resnet_extractor import _convert_bn_to_affine from ..resnet import BuildingBlock from ..resnet import ResNet101Extractor from ..resnet impor...
return score, score_oc def predict(self, imgs): lbls = [] masks_oc = [] for img in imgs: with chainer.no_backprop_mode(), \ chainer.using_config('train', False): x = self.xp.asarray(img[None]) score, score_oc = self.__...
score_oc) lbl = chainer.cuda.to_cpu(lbl.array[0]) mask_oc = chainer.cuda.to_cpu(prob_oc.array[0] > 0.5) lbls.append(lbl) masks_oc.append(mask_oc) return lbls, masks_oc class OcclusionSegmentationTrainChain(chainer.Chain): def __init__(self, predictor, train...
shakamunyi/neutron-vrrp
neutron/tests/unit/services/metering/drivers/__init__.py
Python
apache-2.0
665
0
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com> # # Author: Sylvain Afchain <sylvain.afchain@enovance.com> # # 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.apach...
or impli
ed. See the # License for the specific language governing permissions and limitations # under the License.
fengkaicnic/traffic
traffic/utils.py
Python
apache-2.0
44,222
0.000565
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may #...
(subprocess): %s'), ' '.join(cmd)) _PIPE = subprocess.PIPE # pylint: disable=E1101 obj = subprocess.Popen(cmd, stdin=_PIPE,
stdout=_PIPE, stderr=_PIPE, close_fds=True, preexec_fn=_subprocess_setup, shell=shell) result = None if process_input is not N...
zasdfgbnm/qutip
qutip/entropy.py
Python
bsd-3-clause
10,172
0.000098
# This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted pr
ovided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the fo...
g disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names # of its contributors may be used to endorse or promote products derived # from this software without specific prior written permi...
ScreamingUdder/mantid
scripts/HFIR_4Circle_Reduction/detector2dview.py
Python
gpl-3.0
14,100
0.002199
#pylint: disable=W0403,R0902,R0903,R0904,W0212 from __future__ import (absolute_import, division, print_function) from HFIR_4Circle_Reduction import mpl2dgraphicsview from PyQt4 import QtCore import numpy as np import os class Detector2DView(mpl2dgraphicsview.Mpl2dGraphicsView): """ Customized 2D detector vie...
0 or axis-1 :return: """ def save_to_file(base_file_name, axis, array1d, start_index): """ save the result (1D data
) to an ASCII file :param base_file_name: :param axis: :param array1d: :param start_index: :return: """ file_name = '{0}_axis_{1}.dat'.format(base_file_name, axis) wbuf = '' vec_x = np.arange(len(array1d)) + sta...
minhphung171093/GreenERP
openerp/addons/base/res/res_config.py
Python
gpl-3.0
31,737
0.003624
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from operator import attrgetter import re import openerp from openerp import SUPERUSER_ID from openerp.osv import osv, fields from openerp.tools import ustr from openerp.tools.translate import _ from opene...
ons import UserError _logger = logging.getLogger(__name__) class res_config_module_installation_mixin(object): def _install_modules(self, cr, uid, modules, context): """Install the requested modules. return the next action to execute modules is a list of tuples (m
od_name, browse_record | None) """ ir_module = self.pool.get('ir.module.module') to_install_ids = [] to_install_missing_names = [] for name, module in modules: if not module: to_install_missing_names.append(name) elif module.state == 'unin...
pjuu/pjuu
pjuu/auth/backend.py
Python
agpl-3.0
14,374
0
# -*- coding: utf8 -*- """Simple auth functions with access to the databases for use in the views. :license: AGPL v3, see LICENSE for more details :copyright: 2014-2021 Joe Doherty """ # Stdlib imports from datetime import datetime import re # 3rd party imports from flask import session from pymongo.errors import D...
ost', 'posts', 'privacy', 'privacy_policy', 'privacypolicy', 'profile', 'project', 'p
rojects', 'pub', 'public', 'random', 'recover', 'register', 'registration', 'report', 'reset', 'root', 'rss', 'script', 'scripts', 'search', 'secure', 'security', 'send', 'service', 'setting', 'settings', 'setup', 'signin', 'signup', 'singout', 'site', 'sitemap', 'sites', 'ssh', 'stage', 'staging', ...
alby128/syncplay
buildPy2exe.py
Python
apache-2.0
31,233
0.002964
#!/usr/bin/env python3 #coding:utf8 # *** TROUBLESHOOTING *** # 1) If you get the error "ImportError: No module named zope.interface" then add an empty __init__.py file to the PYTHONDIR/Lib/site-packages/zope directory # 2) It is expected that you will have NSIS 3 NSIS from http://nsis.sourceforge.net installed. imp...
zybkiego uruchamiania" LangString ^UninstConfig $${LANG_POLISH} "Usun plik konfiguracyjny." LangString ^SyncplayLanguage $${LANG_RUSSIAN} "ru" LangString ^Associate $${LANG_RUSSIAN} "Ассоциировать Syncplay с видеофайлами" LangString ^Shortcut $${LANG_RUSSIAN} "Создать ярлыки:" LangString ^StartMenu $${LANG_R...
го запуска" LangString ^AutomaticUpdates $${LANG_RUSSIAN} "Проверять обновления автоматически"; TODO: Confirm Russian translation ("Check for updates automatically") LangString ^UninstConfig $${LANG_RUSSIAN} "Удалить файл настроек." LangString ^SyncplayLanguage $${LANG_GERMAN} "de" LangString ^Associate $${LAN...
jnez71/demos
methods/dynpro_queens.py
Python
mit
2,894
0.00311
#!/usr/bin/env python3 """ The 8-Queens Problem as dynamic programming. https://en.wikipedia.org/wiki/Eight_queens_puzzle """ class QueenSolver: def __init__(self, numqueens, boardsize): # Cast and validate self.numqueens = int(numqueens) self.boardsize = int(boardsize) assert self...
ame space? if len(state) != time: return True # Are queens threatening each other? rows, cols, ldiags, rdiags = zip(*((q[0], q[1], q[1]-q[0], self.boardsize-(q[0]+q[1])-1) for q in state))
for i in range(0, len(state)): for j in range(i+1, len(state)): if (rows[i] == rows[j]) or (cols[i] == cols[j]) or (ldiags[i] == ldiags[j]) or (rdiags[i] == rdiags[j]): return True return False def _reward(self, state, action): # Sa...
rallured/PyXFocus
examples/arcus/uvYaw.py
Python
mit
3,901
0.026916
import numpy as np import matplotlib.pyplot as plt import pdb import traces.sources as sources import traces.transformations as tran import traces.surfaces as surf #Set up incident beam trace and determine sensitivity to beam #impact location. #Trace nominal geometry (function of incidence angle) and #record location...
ating = np.zeros(6) impact = np.zeros(6) #Initialize output vectors xr = np.zeros(np.size(alignvector)) yr = np.copy(xr) xd = np.copy(xr) yd = np.copy(xr) #Perform raytraces in loop for a in alignvector: #Adjust misalignments if obj is 'beam': impa
ct[dof] = a else: grating[dof] = a #Perform trace and set appropriate output elements i = a==alignvector x,y = alignTrace(inc,impact,grating,order=0) xr[i] = x yr[i] = y x,y = alignTrace(inc,impact,grating,order=1) xd[i] = x yd[i] = y ...
CQT-Alex/GSN-heatmap
gomsurveyplot.py
Python
gpl-3.0
10,155
0.015854
''' gomsurveyplot.py: This program creates the sky heatmap plot from the GomSpace survey data. input: A CSV file containing the sky survey data generated by the survey program provided by GomSpace. output: A heatmap plot of the input data. ...
TNESS FOR A PARTICULAR PURPOSE. Please refer to the GNU Public License for more details. You should ha
ve received a copy of the GNU Public License along with this source code; if not, see: <https://www.gnu.org/licenses/gpl.html> ''' import os import sys import inspect import csv import re import numpy as np import bisect import math from scipy.interpolate import griddata import matplotlib.pyplot as plt import ...
ckolumbus/mikidown
setup.py
Python
mit
2,051
0.009751
from distutils import log from distutils.core import setup from distutils.command.build import build from distutils.command.install_scripts import install_scripts import glob import sys from mikidown.config import __version__ class miki_build(build): def run(self): # Check the python version try: ...
('share/mikidown', ['Changelog.md']), ('share/mikidown/css', glob.glob("mikidown/css/*")), ('share/icons/hicolor/scalable/apps', ['mikidown/icons/mikidown.svg']), ('share/applications', ['mikidown.desktop']) ], requires=['PyQt', 'mark...
'build': miki_build, 'install_scripts': miki_install_scripts }, classifiers=[ "Topic :: Text Editors :: Documentation", "Development Status :: 3 - Alpha", "Environment :: X11 Applications", "License :: OSI Approved :: MIT License", "Programming Language ...
EmreAtes/spack
lib/spack/spack/test/svn_fetch.py
Python
lgpl-2.1
3,319
0
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
.path.isfile(file_path) os.unlink(file_path) assert not os.path.isfile(file_path) untracked_file = 'foobarbaz' touch(untracked_file) assert o
s.path.isfile(untracked_file) pkg.do_restage() assert not os.path.isfile(untracked_file) assert os.path.isdir(pkg.stage.source_path) assert os.path.isfile(file_path) assert h() == t.revision
django-fluent/django-fluent-contents
fluent_contents/plugins/formdesignerlink/migrations/0001_initial.py
Python
apache-2.0
1,286
0.000778
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("form_designer", "__first__"), ("fluent_contents", "0001_initial")] operations = [ migrations.CreateModel( name="FormDesignerLink", fields=[ ( ...
n", ), ), ], options={ "db_table": "contentitem_formdesignerlink_formdesignerlink", "verbose_name": "
Form link", "verbose_name_plural": "Form links", }, bases=("fluent_contents.contentitem",), ) ]
HugoMMRabson/fonsa
src/test/old/backend/svrtools/crypto/__init__.py
Python
gpl-3.0
2,949
0.00373
''' test.backend.svrtools.crypto.__init__ ''' import unittest from my.backend im
port Backend # from my.backend.crypto import is_this_the_correct_dollhouse_password from my.globals.exceptions import WrongDollhousePasswordError from my.miscellany import random_alphanum_string class Test_is_this_the_correct_dollhouse_password(unittest.TestCase): ''' Test the supplied password. If it's the r...
to try to decrypt the key and check to see if the password is the right onw. If we are using ECRYPTFS, this function is not used because ECRYPTFS (in our usage) does not use an external keyfile but uses a password instead. Outputs: True/Fal...
pallets/click
examples/aliases/aliases.py
Python
bsd-3-clause
4,061
0.000492
import configparser import os import click class Config: """The config in this example only holds aliases.""" def __init__(self): self.path = os.getcwd() self.aliases = {} def add_alias(self, alias, cmd): self.aliases.update({alias: cmd}) def read_config(self, filename): ...
name): parser = configparser.RawConfigParser() parser.add_section("aliases") for key, value in self.aliases.items(): parser.set("aliases", key, value) with open(filename, "wb") as file: parser.write(file) pass_config = click.make_pass_decorator(
Config, ensure=True) class AliasedGroup(click.Group): """This subclass of a group supports looking up aliases in a config file and with a bit of magic. """ def get_command(self, ctx, cmd_name): # Step one: bulitin commands as normal rv = click.Group.get_command(self, ctx, cmd_name) ...
miyazaki-tm/aoj
Volume0/0030.py
Python
mit
334
0
"""
Sum of Integers """ import itertools if __name__ == '__main__': while True: n, s = map(int, raw_input().split()) if n == 0 and s == 0: break result = 0 for a in itertools.combinations(xrange(10), n): if sum(a) == s: result += 1 prin
t result
shymonk/django-datatable
example/app/views.py
Python
mit
2,085
0.00048
#!/usr/bin/env python # coding: utf-8 from django.shortcuts import render from table.views import FeedDataView from app.tables import ( ModelTable, AjaxTable, AjaxSourceTable, CalendarColumnTable, SequenceColumnTable, LinkColumnTable, CheckboxColumnTable, ButtonsExtensionTable ) def base(request): ...
ndex.html", {'people': table}) def link_column(request): table = LinkColumnTable() return render(request, "index.html", {'people': table}) def checkbox_column(request): table = CheckboxColumnTable() return render(request, "index.html", {'people': table}) def buttons_extension(request): table =...
ml", {'people': table}) def user_profile(request, uid): from app.models import Person from django.http import HttpResponse from django.shortcuts import get_object_or_404 person = get_object_or_404(Person, pk=uid) return HttpResponse("User %s" % person.name) class MyDataView(FeedDataView): to...
jocelynj/weboob
weboob/backends/aum/pages/base.py
Python
gpl-3.0
4,096
0.002442
# -*- coding: utf-8 -*- # Copyright(C) 2008-2010 Romain Bignon # # 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, version 3 of the License. # # This program is distributed in the hope that it w...
table') for tag in l: if tag.getAttribute('width') == '220': # <table><tbody(implicit)><tr><td> child = tag.childNodes[0].childNodes[0].childNodes[3] return int(child.childNodes[0].childNodes[1].data.replace(' ', '').strip()) self.logger.error...
l = self.document.getElementsByTagName('span') for tag in l: if tag.getAttribute('id') == elementName: child = tag.childNodes[0] if not hasattr(child, 'data'): if child.tagName != u'blink': self.logger.warning("Warn...
kaidokert/cookiecutter-django
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/taskapp/celery.py
Python
bsd-3-clause
1,017
0.012783
{% if cookiecutter.use_celery == "y" %} from __future__ import absolute_import import os from celery import Celery from django.apps import AppConfig from django.conf import settings if not settings.configured: # set the default Django settings module for the 'celery' program. os.environ.setdefault("DJANGO_SETT...
# Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True) @app.task(bind=True) def de
bug_task(self): print('Request: {0!r}'.format(self.request)) {% else %} # Use this as a starting point for your project with celery. # If you are not using celery, you can remove this app {% endif %}
forkbong/qutebrowser
qutebrowser/misc/sql.py
Python
gpl-3.0
16,139
0.000806
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2016-2021 Ryan Roden-Corrent (rcorre) <ryan@rcorre.net> # # This file is part of qutebrowser. # # qutebrowser 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...
alled?') database.setDatabaseName(db_path) if not database.open(): error = database.lastError() msg = "Failed to open sqlite database at {}: {}".format(db_path, error.text()) raise_sqlite_error(msg, error) global _db_us...
sion').run().value() _db_user_version = UserVersion.from_int(version_int) if _db_user_version.major > _USER_VERSION.major: raise KnownError( "Database is too new for this qutebrowser version (database version " f"{_db_user_version}, but {_USER_VERSION.major}.x is supported)") ...