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
cuspaceflight/tawhiri
docs/conf.py
Python
gpl-3.0
9,512
0.006098
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Tawhiri documentation build configuration file, created by # sphinx-quickstart on Thu Apr 10 23:05:18 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 # au...
it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # ext...
your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The enc...
lichengshuang/createvhost
others/webvirtmgr/addServer.py
Python
apache-2.0
1,380
0.013043
#!/usr/bin/python #-*-encoding:utf-8-*- #author: asher #date: 20160429 on train D909 # this scripts useed for add server ip to webvirtmgr # if not , each server must add by website,it's too slow, and very not interesting. # use this , it's make you feel very happy import sqlite3 try: conn = sqlite3.connect('../...
cur.execute('''insert into servers_compute (name,hostname,login,password,type) values('%s','%s','%s','%s','%d')''' % (jifang1,newip,login,password,1)) ips1 = int(ips1) ips1 += 1 conn.commit() else: break finally: allservers = cur.execute("select id,name,hostname,logi...
t i conn.close()
Chibin/gpdb
src/test/tinc/tincrepo/mpp/lib/gpSystem.py
Python
apache-2.0
4,502
0.004887
#!/usr/bin/env python # Line too long - pylint: disable=C0301 # Invalid name - pylint: disable=C0103 """ Copyright (c) 2004-Present Pivotal Software, Inc. This program and the accompanying materials are made available under the terms of the under the Apache License, Version 2.0 (the "License"); you may not use this ...
n: %s\n os major version: %s' % (self.host, self.architecture, self.os, self.os_version, self.os_major_version) def __getOsVersion(self, releasefile=None)
: """ @summary: Internal function to get the OS full release version (e.g. 5.5.) and major release version (e.g. 5) @return: list (full_version, major_version), e.g. (5.5, 5) """ if self.os == 'OSX': full_version = platform.mac_ver()[0] major_vers...
Tom-Trumper/selenium
py/selenium/__init__.py
Python
apache-2.0
812
0
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See th
e NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC 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, WIT...
teampheenix/StarCraft-Casting-Tool
scctool/settings/history.py
Python
gpl-3.0
4,381
0
"""Provide history manager for SCCTool.""" import json import logging import scctool.settings.translation from scctool.settings import getJsonFile, idx2race, race2idx module_logger = logging.getLogger(__name__) _ = scctool.settings.translation.gettext class HistoryManager: """History manager for SCCTool.""" ...
.strip() race = "Random" for item in self.__player_history: if item.get('player', '').lower() == player: race = item.get('race', 'Random') break return race def getLogo(self, team): """Look up the logo of a team in history.""" team...
', '0') break return logo
domidimi/ddt
test/test_functional.py
Python
mit
6,480
0.000154
import os import json import six from ddt import ddt, data, file_data, is_hash_randomized from nose.tools import assert_equal, assert_is_not_none, assert_raises @ddt class Dummy(object): """ Dummy class to test the data decorator on """ @data(1, 2, 3, 4) def test_something(self, value): ...
ddt_mytest = ddt(Mytest) assert_is_not_none(getattr(ddt_mytest, 'test_hello_1_
data1')) assert_is_not_none(getattr(ddt_mytest, 'test_hello_2_2')) def test_ddt_data_unicode(): """ Test that unicode strings are converted to function names correctly """ def hello(): pass # We test unicode support separately for python 2 and 3 if six.PY2: @ddt ...
huyphan/pyyawhois
test/record/parser/test_response_whois_domainregistry_ie_property_contacts_multiple.py
Python
mit
1,945
0.004627
# This file is autogenerated. Do not edit it manually. # If you want change the content of this file, edit # # spec/fixtures/responses/whois.domainregistry.ie/property_contacts_multiple # # and regenerate the tests with the following script # # $ scripts/generate_tests.py # from nose.tools import * from dateutil....
name, "John Moylan") def test_technical_contacts(self): eq_(self.record.technical_contacts.__class__.__name__, 'list') eq_(len(self.record.technical_contacts), 1) eq_(self.record.technical_contacts[0].__class__.__name__, 'Contact') eq_(self.record.tec
hnical_contacts[0].type, yawhois.record.Contact.TYPE_TECHNICAL) eq_(self.record.technical_contacts[0].id, "JM474-IEDR") eq_(self.record.technical_contacts[0].name, "John Moylan")
wgrose/leanto
google/appengine/ext/admin/__init__.py
Python
apache-2.0
31,441
0.010114
#!/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...
e_path': base_path + MemcachePageHandler.PATH, } values.update(template_values) directory = os.path.dirname(__file__) path = os.path.join(directory, os.path.join('templates', template_name)) self.response.out.write(template.render(path, values, debug=_DEBUG)) def base_path(self): """Returns t...
. Combine with the constant paths specified by the classes to construct URLs. """ path = self.__class__.PATH return self.request.path[:-len(path)] def filter_url(self, args): """Filters the current URL to only have the given list of arguments. For example, if your URL is /search?q=foo&num=10...
vanaf/mirrormanager-rfremix
server/mirrormanager/rfremix.py
Python
gpl-2.0
1,543
0.022035
from mirrormanager.model import Product, Category, Arch, Directory product = Product(name='RFRemix') categories = {'RFRemix Linux':('releases/RFRemix','rsync://mirror.yandex.ru/fedor
a/russianfedora'), 'RFRemix Repo Fixes':('russianfedora/fixes/fed
ora', 'rsync://mirror.yandex.ru/fedora/russianfedora'), 'RFRemix Repo Free':('russianfedora/free/fedora', 'rsync://mirror.yandex.ru/fedora/russianfedora'), 'RFRemix Repo Nonfree':('russianfedora/nonfree/fedora', 'rsync://mirror.yandex.ru/fedora/russianfedora'), 'RFRemix Build':('b...
tensorflow/tensorflow
tensorflow/python/distribute/multi_worker_util_test.py
Python
apache-2.0
9,133
0.004051
# 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...
cluster_spec = {} with self.assertRaisesRegex( ValueError, "`task_type` 'worker' not found in cluster_spec."): multi_worker_util.worker_count(cluster_spec, task_type="worker") def testCountPs(self): cluster_spec = { "chief": ["127.0.0.1:1234"], "ps": ["127.0.0.1:1926
", "127.0.0.1:3141"] } # A "ps" job shouldn't call this method. with self.assertRaisesRegex(ValueError, "Unexpected `task_type` 'ps'"): multi_worker_util.worker_count(cluster_spec, task_type="ps") class IdInClusterTest(test.TestCase): def testChiefId(self): cluster_spec = { "chief": [...
EndPointCorp/lg_ros_nodes
lg_twister/scripts/mux_twists.py
Python
apache-2.0
2,793
0
#!/usr/bin/env python3 from functools import partial import math from threading import Lock import rospy from geometry_msgs.msg import Twist from lg_common.helpers import run_with_influx_exception_handler NODE_NAME = 'mux_twists' DEFAULT_TICK_RATE = 65.0 DEFAULT_AXIS_LIMIT = math.sqrt(2) / 2 DEFAULT_AGE_LIMIT = 1.0...
result.angular.z += twist.angular.z clamp_twist(result, -self.axis_limit, self.axis_limit) self.twist_pub.publish(result) def main(): rospy.init_node(NODE_NAME) tick_rate = float(rospy.get_param('~tick_rate', DEFAULT_TICK_RATE)) sources = [ s.strip() for s in rospy.get_para...
LT_AGE_LIMIT)) twist_pub = rospy.Publisher('/lg_twister/twist', Twist, queue_size=10) muxer = TwistMuxer(twist_pub, axis_limit, age_limit) for source in sources: handler = partial(muxer.handle_twist, source) rospy.Subscriber(source, Twist, handler) rospy.Timer(rospy.Duration(1.0 / ti...
Azure/azure-sdk-for-python
sdk/applicationinsights/azure-mgmt-applicationinsights/azure/mgmt/applicationinsights/v2018_05_01_preview/operations/_proactive_detection_configurations_operations.py
Python
mit
15,441
0.004598
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
urations of an Application Insights component. :param resour
ce_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param resource_name: The name of the Application Insights component resource. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the dir...
hbiyik/tribler
src/tribler-gui/tribler_gui/tests/fake_tribler_api/models/torrent.py
Python
lgpl-3.0
2,618
0.001528
import time from binascii import unhexlify from random import choice, randint, uniform from tribler_core.modules.metadata_store.serialization import REGULAR_TORRENT from tribler_core.utilities.unicode import hexlify from tribler_gui.tests.fake_tribler_api.constants import COMMITTED from tribler_gui.tests.fake_tribler...
"size": self.length, "category": self.category, "relevance_score": self.relevance_score, "num_seeders": self.num_seeders, "num_leechers": self.num_leechers, "last_tracker_check": self.last_tracker_check, "type": REGULAR_TORRENT, } ...
result["trackers"] = self.trackers return result @staticmethod def random(): infohash = unhexlify(get_random_hex_string(40)) name = get_random_filename() categories = ['document', 'audio', 'video', 'xxx'] torrent = Torrent(infohash, name, randint(1024, 1024 * 3000), ...
Ecotrust/COMPASS
mp/visualize/forms.py
Python
apache-2.0
197
0.005076
from madrona.features.forms import FeatureForm from django import forms from visualize.models import *
class BookmarkForm(FeatureForm): class Meta(Fe
atureForm.Meta): model = Bookmark
OmnesRes/pan_cancer
paper/cox_regression/BLCA/patient_info.py
Python
mit
7,247
0.024424
## A script for extracting info about the patients used in the analysis ## Load necessary modules from rpy2 import robjects as ro import numpy as np import os ro.r('library(survival)') ##This call will only work if you are running python from the command line. ##If you are not running from the command line manually...
me(os.path.abspath(__file__)))) ## Read the follow up data ## It was found that the v4.0 file co
ntained more recent follow up data than v2.0, but the files contained nonredundant patients. ## So both files are loaded with the v4.0 getting preference. ## A patient can be listed multiple times in the file. The most recent listing (furthest down in the file), contains the most recent ## follow up data. This code...
ddico/odoo
addons/account_edi_facturx/models/account_edi_format.py
Python
agpl-3.0
12,584
0.004371
# -*- coding: utf-8 -*- from odoo import api, models, fields, tools, _ from odoo.tools import DEFAULT_SERVER_DATE_FORMAT, float_repr from odoo.tests.common import Form from odoo.exceptions import UserError from datetime import datetime from lxml import etree from PyPDF2 import PdfFileReader import io import logging...
t. template_values = { 'record': invoice, 'format_date': format_date, 'format_monetary': form
at_monetary, } xml_content = b"<?xml version='1.0' encoding='UTF-8'?>" xml_content += self.env.ref('account_edi_facturx.account_invoice_facturx_export')._render(template_values) xml_name = '%s_facturx.xml' % (invoice.name.replace('/', '_')) return {'name': xml_name, ...
wangjiezhe/FetchNovels
novel/sources/myshuge.py
Python
gpl-3.0
1,042
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from pyquery import PyQuery from novel import serial, utils, config BASE_URL = 'http://www.myshuge.com/read/{}/' class Myshuge(serial.SerialNovel): def __init__(self, tid): super().__init__(utils.base_to_url(BASE_URL, tid), '#content', ...
lf.encoding = config.GB def get_intro(self): intro = self.doc('meta').filter( lambda i, e: PyQuery(e).attr('property') == 'og:description' ).attr('content') intro = self.refine(intro) return intro def get_title_and_author(self): name = self.doc('meta').filte...
).attr('content') author = self.doc('meta').filter( lambda i, e: PyQuery(e).attr('property') == 'og:novel:author' ).attr('content') return name, author
xbmc/atv2
xbmc/lib/libPython/Python/Lib/tempfile.py
Python
gpl-2.0
14,377
0.002295
"""Temporary files. This module provides generic, low- and high-level interfaces for creating temporary files and directories. The interfaces listed as "safe" just below can be used without fear of race conditions. Those listed as "unsafe" cannot, and are provided for backward compatibility only. This module also pr...
= _os.lstat elif hasattr(_os, "stat"): _stat = _os.stat else: # Fallback. All we need is something that raises os.error if the # file doesn't exist. def _stat(fn): try: f = open(fn) except IOError: raise _os.error f.close() def _exists(fn): try: ...
_stat(fn) except _os.error: return False else: return True class _RandomNameSequence: """An instance of _RandomNameSequence generates an endless sequence of unpredictable strings which can safely be incorporated into file names. Each string is six characters long. Multiple t...
justanr/py3traits
src/pytraits/core/binders.py
Python
apache-2.0
6,145
0
#!/usr/bin/python -tt # -*- coding: utf-8 -*- ''' Copyright 2014-2015 Teppo Perä 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 Un...
ng permissions and limitations under the License. ''' def bind_method_to_class(clazz, method, name=None): """ Binds a single method into class. This can be very useful in situation, where your trait properties are dynamic, and you first need to construct your trait in some fashion and after th...
to some class (You don't have always full control to creation process). @param clazz: Class to be extended @param method: Method that is added as a trait into class @param name: New name for the method. When omitted, original is used. >>> class MyClass(object): ... def __init__(self):...
sjl/d
d/base.py
Python
mit
6,812
0.003083
import sys, os, shutil import markdown from pyquery import PyQuery as pq j = os.path.join md = markdown.Markdown(extensions=['toc', 'codehilite']) up = lambda p: j(*os.path.split(p)[:-1]) dirname = lambda p: os.path.basename(os.path.abspath(p)) extensions = ['md', 'mdown', 'markdown'] INDEX_PRE = u'''\ <!DOCTYPE htm...
d> <meta charset="utf-8" /> <title>{title_tag}</title> <link rel="stylesheet" href="../_dmedia/tango.css"/> <link rel="stylesheet/less" type="text/css" href="../_dmedia/style.less"> <script src="../_dmedia/less.js" type="text/javascript"> </script> </head> <body c...
<header><h1><a href="..">{project_title}</a></h1></header> <div class="markdown"> ''' POST = u''' </div> <footer>{footer}</footer> </div> </body> </html> ''' def _read(f): return f.read().decode('utf-8') def _write(f, content): return f.write(content...
Erikun/elogy
elogy/patch.py
Python
gpl-3.0
4,904
0.00306
#!/usr/bin/env python # coding=utf-8 # License: Public domain (CC0) # Isaac Turner 2016/12/05 # Port to Python 3 and cleanup by Johan Forsberg from __future__ import print_function import difflib import re _no_eol = "\ No newline at end of file" _hdr_pat = re.compile("^@@ -(\d+),?(\d+)? \+(\d+),?(\d+)? @@$") def ...
raise Exception("Bad patch -- bad line num [line " + str(i) + "]") t += ''.join(s[sl:l]) sl = l i += 1 while i < len(p) and p[i][0] != '@': if i + 1 < len(p) and p[i + 1][0] == '\\':
line = p[i][:-1] i += 2 else: line = p[i] i += 1 if len(line) > 0: if line[0] == sign or line[0] == ' ': t += line[1:] sl += (line[0] != sign) t += ''.join(s[sl:]) return...
deepmind/enn
enn/experiments/neurips_2021/distillation/train_lib.py
Python
apache-2.0
5,289
0.009265
# python3 # pylint: disable=g-bad-file-header # Copyright 2021 DeepMind Technologies Limited. 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...
et_out = enn_base.OutputWithPrior(net_out) net_out: enn_base.OutputWithPrior = net_out net_out.extra.update(transformed.apply(params, x)) return net_out def init(key: enn_base.RngKey, x: enn_base.Array, z: enn_base.Index) -> hk.Pa
rams: base_params = enn.init(key, x, z) distill_params = transformed.init(key, x) return _merge_params([base_params, distill_params]) indexer = DistillationIndexer(enn.indexer) super().__init__(apply, init, indexer) @dataclasses.dataclass class DistillRegressionLoss(enn_base.LossFn): """...
FireballDWF/cloud-custodian
c7n/output.py
Python
apache-2.0
13,380
0.000299
# Copyright 2015-2017 Capital One Services, 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 ...
ault') class NullStats(object): """Execution statistics/metrics collection. Encompasses concrete implementations over system stats (memory, cpu, cache size) and api calls. The api supports stack nested snapshots, with delta consumption to support tracing metadata annotation across nested subsegmen...
= ctx self.config = config or {} def push_snapshot(self): """Take a snapshot of the system stats and append to the stack.""" def pop_snapshot(self): """Remove a snapshot from the snack and return a delta of the current stats to it. """ return {} def get_metadata(s...
JWilson0/dt211-cloud-repo
Euler/sovle1.py
Python
mit
120
0.016667
sum
= 0 for i in range(1000): if(i % 3 == 0 or i % 5 == 0): totalSum+=i print(i) print(totalSum)
mitchsmith/qd_screener
questionnaire/admin.py
Python
mit
7,839
0.007782
from django.contrib import admin from django.forms import ModelChoiceField, ModelForm, Textarea from questionnaire.models import * from django.core.exceptions import ValidationError from django.forms.models import BaseInlineFormSet from questionnaire import admin_helper ############################################### ...
trip()) + len(related_content_text.strip())) > 0 both_fields_have_text = (len(related_content_link.strip()) * len(related_content_text.strip())) > 0 i
f at_least_one_field_has_text and not both_fields_have_text: raise ValidationError('Both related_content_link and related_content_text need to be either set or empty') class QuestionInline(admin.TabularInline): model = Question formset = QuestionFormSet ordering = ('-created_on',) def f...
pouyana/teireader
webui/applications/admin/models/access.py
Python
mit
5,924
0.000675
import base64 import os import time from gluon import portalocker from gluon.admin import apath from gluon.fileutils import read_file # ########################################################### # ## make sure administrator is on localhost or https # ########################################################### http_h...
p_host, ) is_gae = True else: is_gae = False if request.env.http_
x_forwarded_for or request.is_https: session.secure() elif not request.is_local and not DEMO_MODE: raise HTTP(200, T('Admin is disabled because insecure channel')) try: _config = {} port = int(request.env.server_port or 0) restricted( read_file(apath('../parameters_%i.py' % port, request)),...
hos7ein/firewalld
src/firewall/core/io/service.py
Python
gpl-2.0
11,872
0.00598
# -*- coding: utf-8 -*- # # Copyright (C) 2011-2016 Red Hat, Inc. # # Authors: # Thomas Woerner <twoerner@redhat.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the Li...
if x in self.item.destination:
log.warning("Destination address for '%s' already set, ignoring", x) else: self.item.destination[x] = attrs[x] elif name == "module": module = attrs["name"] if module.startswith("nf_conntrack_"): ...
ucsd-ccbb/jupyter-genomics
src/microbiome/exec_fastqc.py
Python
mit
3,451
0.002028
""" Module to call fastqc in pipeline""" import os import subprocess import argparse import logging __author__ = "YiDing Fang" __maintainer__ = "YiDing Fang" __email__ = "yif017@eng.ucsd.edu" __status__ = "prototype" def form_fastqc_cmd_list(fastqc_fp, fastq_fp, outdir): """Generate
argument list to be given as input to the fastqc function call. Args: fastqc_fp(str): the string representing path to fastqc program fastq_fp(str): the string representing path to the fastq file to be eval
uated outdir(str): the string representing the path to the output directory Return value: call_args(list): the list of call_args representing the options for the fastqc subprocess call Raises: ValueError is raised when either the fastqc path or the fastqc input files are empty """ ...
seanballais/SAElections
SAElections/voting/admin.py
Python
mit
1,715
0.005831
from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.admin import UserAdmin from django.contrib import admin from django import forms class VoterCreationForm(UserCreationForm): section = forms.CharField() def save(self, com...
ame', 'is_active', 'is_staff', 'is_superuser') class VoterChangeForm(UserChangeForm): section = forms.CharField() def save(self, commit=True): user = super(VoterChangeForm, self).save(commit=False) user.section = self.cleaned_data['section'] if commit: user.save() r...
: form = VoterChangeForm add_form = VoterCreationForm list_filter = UserAdmin.list_filter + ('section',) fieldsets = ( (None, {'fields': ('username', 'password')}), (('Personal info'), {'fields': ('first_name', 'last_name', 'section')}), (('Permissions'), {'fields': ('is_active'...
renebentes/Python4Zumbis
Materiais/Ultima Semana/euler 02.py
Python
mit
285
0.042105
def fib(): a, b = 1, 1 while True: yield b a, b = b, a + b def pares(seq): for n in seq: if n % 2 == 0: yield n def menores_4M(seq): for n in seq: if n > 4000000: break yield n
print (sum(pares(menores_4M(fib()))))
lnls-sirius/dev-packages
siriuspy/siriuspy/injctrl/__init__.py
Python
gpl-3.0
36
0
"""Injection
control subpackag
e."""
NickDaly/GemRB-FixConfig-Branch
gemrb/GUIScripts/GUIClasses.py
Python
gpl-2.0
6,912
0.011719
#-*-python-*- #GemRB - Infinity Engine Emulator #Copyright (C) 2009 The GemRB Project # #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 lat...
el(GControl): __metaclass__ = metaControl methods = { 'SetTextColor': _GemRB.Label_SetTextColor, 'SetUseRGB': _GemRB.Label_SetUseRGB } class GTextArea(GControl): __metaclass__ = metaControl methods = { 'Rewind': _GemRB.TextAr
ea_Rewind, 'SetHistory': _GemRB.TextArea_SetHistory, 'Append': _GemRB.TextArea_Append, 'Clear': _GemRB.TextArea_Clear, 'Scroll': _GemRB.TextArea_Scroll, 'SetFlags': _GemRB.Control_TextArea_SetFlags, 'GetCharSounds': _GemRB.TextArea_GetCharSounds, 'GetCharacters': _GemRB.TextArea_GetCharacter...
sdgathman/pymilter
testsample.py
Python
gpl-2.0
5,060
0.014427
import unittest import Milter import sample import template import mime import zipfile from Milter.test import TestBase from Milter.testctx import TestCtx class TestMilter(TestBase,sample.sampleMilter): def __init__(self): TestBase.__init__(self) sample.sampleMilter.__init__(self) class BMSMilterTestCase(un...
bodyreplaced,"Message body not replaced") fp = milter._body with open("test/virus3.tstout","wb") as f: f.write(fp.getvalue()) #self.assertTrue(fp.getvalue() == open("test/virus3.out","r").read()) with self.zf.open("virus6") as fp: rc = milter.
feedFile(fp) self.assertTrue(rc == Milter.ACCEPT) self.assertTrue(milter._bodyreplaced,"Message body not replaced") self.assertTrue(milter._headerschanged,"Message headers not adjusted") fp = milter._body with open("test/virus6.tstout","wb") as f: f.write(fp.getvalue()) milter.close() d...
DocDir/docdir
plans/migrations/0002_auto_20150722_0003.py
Python
bsd-3-clause
3,284
0.003959
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('plans', '0001_initial'), ] operations = [ migrations.CreateModel( name='DataSource',
fields=[ ('id', models.AutoField(auto
_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200, verbose_name='organization name')), ('source_type', models.CharField(max_length=1, choices=[('C', 'Crawled'), ('V', 'Official Release csv'), ('P', 'Official Release pdf')])), ...
grlee77/nipype
nipype/interfaces/afni/tests/test_auto_To3D.py
Python
bsd-3-clause
1,337
0.023186
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from nipype.testing import assert_equal from nipype.interfaces.afni.preprocess import To3D def test_To3D_inputs(): input_map = dict(args=dict(argstr='%s', ), assumemosaic=dict(argstr='-assume_dicom_mosaic', ), datatype=dict(argstr='-datum %s', ...
), terminal_output=dict(nohash=True, ), ) inputs = To3D.input_spec() for key, metadata in input_map.items(): for metakey, value in metadata.items(): yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_To3D_outputs(): output_map = dict(out_file=dic...
outputs = To3D.output_spec() for key, metadata in output_map.items(): for metakey, value in metadata.items(): yield assert_equal, getattr(outputs.traits()[key], metakey), value
setokinto/slack-shogi
app/shogi.py
Python
mit
4,557
0.002766
import re import functools from slackbot.bot import respond_to from app.modules.shogi_input import ShogiInput, UserDifferentException, KomaCannotMoveException from app.modules.shogi_output import ShogiOutput from app.slack_utils.user import User from app.helper import channel_info, should_exist_shogi @respond_to('...
ogi def matta(channel, message): try: ShogiInput.matta(channel.channel_id, channel.own_id)
message.send("mattaed") except UserDifferentException: message.reply("You cannot matta because *it's not your turn*") except KomaCannotMoveException: message.reply("You cannot matta because koma not moved") finally: board = ShogiInput.get_shogi_board(channel.channel_id) ...
j-po/django-brambling
brambling/management/commands/update_tokens.py
Python
bsd-3-clause
931
0
from optparse import make_option from django.core.management.base import BaseCommand, CommandError from brambling.utils.payment import dwolla_update_tokens class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option( '--days', action='store', des...
ndError("Days must be an integer value.") self.stdout.write("Updating dwolla tokens...") self.stdout.flu
sh() count, test_count = dwolla_update_tokens(days) self.stdout.write("Test tokens updated: {}".format(count)) self.stdout.write("Live tokens updated: {}".format(test_count)) self.stdout.flush()
kcompher/pygraphistry
graphistry/plotter.py
Python
bsd-3-clause
18,526
0.002375
from __future__ import print_function from __future__ import absolute_import from builtins import str from builtins import range from builtins import object import random import string import copy import types import pandas from . import pygraphistry from . import util class Plotter(object): """Graph plotting cl...
self._nodes = None self._source = None self._destination = None self._node = None self._edge_title = None self._edge_label = None self._edge_color = None self._edge_weight = None self._point_title = None self._point_label = None self._poi...
elf._point_size = None # Settings self._height = 500 self._url_params = {'info': 'true'} def __repr__(self): bnds = ['edges', 'nodes', 'source', 'destination', 'node', 'edge_title', 'edge_label', 'edge_color', 'edge_weight', 'point_title', 'point_labe...
VPAC/patchman
patchman/domains/models.py
Python
gpl-3.0
813
0
# Copyright 2012 VPAC, http://www.vpac.org # # This file is part of Patchman. # # Patchman 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 only. # # Patchman is distributed in the hope that it will b...
ique=True) def __unicode__(self): return
self.name
nd1/women_in_tech_summit_DC2017
api/seeclickfix_api.py
Python
mit
2,074
0.000964
''' Pull one page of 100 results fro
m seeclickfix using the global PARAMS value if the parameters are not supplied. If there are more than 100 results, make another pull passing paramters that include the next page to be pulled. Nicole Donnelly 30May2016, updated 21Oct2016 ''' import requests import json def get_seeclickfix(page=1, pulled=0, search_p...
'district-of-columbia', 'after': '2016-10-01', 'per_page': 100}): # base_url for usajobs api to build the request url base_url = 'https://seeclickfix.com/api/v2/issues' # send a get request with the url, parameters, and header myResponse = requests.get(url=base_url, params=sea...
kristerw/spirv-tools
spirv_tools/ext_inst/glsl_std_450.py
Python
mit
11,873
0.033521
"""Instruction descriptions for the "SPIR-V Extended Instructions for GLSL" version 1.00, revision 2. """ INST_FORMAT = { 1 : { 'name' : 'Round', 'operands' : ['Id'], 'has_side_effects' : False, 'is_commutative' : False },
2 : { 'name' : 'RoundEven', 'operands' : ['Id'], 'has_side_effects' : False, 'is_commutative' : False }, 3 : { 'name' : 'Trunc', 'operands' : ['Id'], 'has_side_effects' : False, 'is_commutative' : False }, 4 : { 'name': 'FAbs',...
'operands' : ['Id'], 'has_side_effects' : False, 'is_commutative' : False }, 6 : { 'name' : 'FSign', 'operands' : ['Id'], 'has_side_effects' : False, 'is_commutative' : False }, 7 : { 'name' : 'SSign', 'operands' : ['Id'], '...
anthgur/servo
tests/wpt/web-platform-tests/tools/third_party/pytest/_pytest/runner.py
Python
mpl-2.0
16,098
0.000186
""" basic collect and runtest protocol implementations """ from __future__ import absolute_import, division, print_function import bdb import os import sys from time import time import py from _pytest._code.code import TerminalRepr, ExceptionInfo from _pytest.outcomes import skip, Skipped, TEST_OUTCOME # # pytest pl...
durations (N=0 for all)."), def pytest_terminal_summary(terminalreporter): durations = terminalreporter.config.option.durations if durations is None: return tr = terminalreporter dlist = [] for replist in tr.stats.values(): for rep in replist: if hasattr(rep, 'duration'...
uration) dlist.reverse() if not durations: tr.write_sep("=", "slowest test durations") else: tr.write_sep("=", "slowest %s test durations" % durations) dlist = dlist[:durations] for rep in dlist: nodeid = rep.nodeid.replace("::()::", "::") tr.write_line("%02.2fs ...
h-mayorquin/camp_india_2016
tutorials/LTPinnetworks2/Step2aCorr_Gilson_etal_2012.py
Python
mit
8,226
0.016168
#!/usr/bin/env python ''' Based on: Gilson, Matthieu, Tomoki Fukai, and Anthony N. Burkitt. Spectral Analysis of Input Spike Trains by Spike-Timing-Dependent Plasticity. PLoS Comput Biol 8, no. 7 (July 5, 2012): e1002584. doi:10.1371/journal.pcbi.1002584. Author: Aditya Gilra, Jun 2016. (with inputs from Matthieu Gils...
# synaptic epsp tauB eqs
_neurons=''' dA/dt=-A/tauA : 1 dB/dt=-B/tauB : 1 rho_out = (A-B)/(tauA-tauB) : Hz ''' # ########################################### # Network parameters: numbers # ########################################### Npools = 4 # Number of correlated pools Ninp = 500 # Number of neurons per pool nu0...
buddyzhangrenze/i2c
python/project/buddy/statusbar.py
Python
gpl-2.0
403
0.012407
#!/usr/bin/python # statusbar.py import sys from P
yQt4 import QtGui class MainWindow(QtGui.QMainWindow): def __init__(self, parent = None): QtGui.QMainWindow.__init__(self) self.resize(250, 150) self.setWindowTitle('statusbar') self.statusBar().showMessage('Ready') app = QtGui.QApplication(sys.argv) main
= MainWindow() main.show() sys.exit(app.exec_())
karan259/GrovePi
Software/Python/grove_electricity_sensor.py
Python
mit
2,530
0.003162
#!/usr/bin/env python # # GrovePi Example for using the Grove Electricity Sensor (http://www.seeedstudio.com/wiki/Gro
ve_-_Electricity_Sensor) # # The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi # # Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/
c/grovepi # ''' ## License The MIT License (MIT) GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi. Copyright (C) 2015 Dexter Industries Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation fil...
laurent-george/weboob
weboob/browser/filters/__init__.py
Python
agpl-3.0
729
0
# -*- c
oding: utf-8 -*- # Copyright(C) 2014 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any...
HANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with weboob. If not, see <http://www.gnu.org/licenses/>.
PoseidonAW/Py_RPG
playerdata.py
Python
apache-2.0
4,639
0.004311
__author__ = 'Poseidon' # Import the AW SDK Information from ctypes import * aw = CDLL("aw") AWEVENT = CFUNCTYPE(None) AWCALLBACK = CFUNCTYPE(None) import sqlite3 import genericMessaging db = sqlite3.connect('awrpg.db') cursor = db.cursor() from random import randint session_dict = {} def player_check(player_s...
= 0 location_x = 0 location_y = 0 cursor.execute('''SELECT name, health, mana, race FROM players WH
ERE name = ?''', (player_name,)) results = cursor.fetchone() if results is not None: aw.aw_hud_destroy(player_session, hud_id) health = results[1] mana = results[2] race = results[3] genericMessaging.py_hud_generic(player_session, "Health: {}, Mana: {}, Race: {}".format(h...
wwwslinger/airflow
airflow/operators/mysql_operator.py
Python
apache-2.0
1,063
0
import logging from airflow.hooks import MySqlHook from airflow.models import BaseOperator from airflow.utils import apply_defaults class MySqlOperator(BaseOperator): """ Executes sql code in a specific MySQL database :param mysql_conn_id: reference to a specific mysql database :type mysql_conn_id: ...
logging.info('Executing: ' + str(self.sql)) hook = MySqlHook(mysql_conn
_id=self.mysql_conn_id) hook.run(self.sql)
osgcc/ryzom
nel/tools/build_gamedata/processes/displace/1_export.py
Python
agpl-3.0
1,885
0.007958
#!/usr/bin/python # # \file 1_export.py # \brief Export displace # \date 2009-03-10-21-45-GMT # \author Jan Boon (Kaetemi) # Python port of game data build pipeline. # Export displace # # NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/> # Copyright (C) 2010 Winch Gate Property Limited # # This program is ...
ram 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # alo...
rogram. If not, see <http://www.gnu.org/licenses/>. # import time, sys, os, shutil, subprocess, distutils.dir_util sys.path.append("../../configuration") if os.path.isfile("log.log"): os.remove("log.log") log = open("log.log", "w") from scripts import * from buildsite import * from process import * from tools impo...
jyr/japos
goods/forms.py
Python
gpl-2.0
1,027
0.027264
from django import forms from japos.goods.models import Product, Group class ProductForm(forms.ModelForm): sku = forms.CharField(widget = forms.TextInput(attrs={'class': 'text-input small-input'})) barcode = forms.CharField(widget = forms.TextInput(attrs={'class': 'text-in
put small-input'})) name = forms.CharField(widget = forms.TextInput(attrs={'class': 'text-input small-input'})) description = forms.CharField(widget = forms.Textarea(attrs={'class': 'textarea', 'rows': '5', 'cols': '50'})) stock = forms.IntegerField(widget = forms.TextInput(attrs={'class': 'text-input small...
s.TextInput(attrs={'class': 'text-input small-input'})) class Meta: model = Product class GroupForm(forms.ModelForm): sku = forms.CharField(widget = forms.TextInput(attrs={'class': 'text-input small-input'})) name = forms.CharField(widget = forms.TextInput(attrs={'class': 'text-input small-input'}...
TTSpaxxy/SpaghettiPy
src/mangle.py
Python
gpl-2.0
7,428
0.011443
# # Copyright (C) 2014 Aaron Cohen # # This file is part of SpaghettiPy. ...
- 2].plaintext #End if else: block.declaration = "GLOBAL SCOPE" #End else while True: if statements[currentStatement],kind == "Begin Code Block": block.children.append(findBlocks(statements, currentStatement + 1, currentLevel + 1)) block.children[-1].parent...
lock statements.append(Statement("BREAK", "Break at statement " + str(currentStatement), statements[currentStatement].line)) currentStatement = block.children[-1].end + 1 #End if elif statements[currentStatement].kind == "End Code Block" or currentStatement == len(statements): ...
arcturusannamalai/open-tamil
examples/savaal.py
Python
mit
325
0.01278
# -*- coding: utf-8 -*- # (C
) 2015 Muthiah Annamalai # # This file is part of 'open-tamil' package tests import tamil import solthiruthi from solthiruthi.dictionary import * TVU_dict,_ = DictionaryBuilder.create(TamilVU) word = 'சவால்’' q=list(tamil.wordutils.combinagr
ams(word,TVU_dict)) print(('|'.join(q)))
AutorestCI/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2016_12_01/models/effective_network_security_group.py
Python
mit
1,777
0.002251
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
ction of effective security rules. :type effective_security_rules: list[~azure.mgmt.network.v2016_12_01.models.EffectiveNetworkSecurityRule] """ _attribute_map = { 'network_security_group': {'key': 'networkSecurityGroup', 'type': 'SubResource'}, 'association': {'key': 'association', 't...
ssociation'}, 'effective_security_rules': {'key': 'effectiveSecurityRules', 'type': '[EffectiveNetworkSecurityRule]'}, } def __init__(self, network_security_group=None, association=None, effective_security_rules=None): super(EffectiveNetworkSecurityGroup, self).__init__() self.network_s...
cspang1/4534-08
src/supervisory/test_protocol/test_serial_com.py
Python
gpl-3.0
1,683
0.005348
import serial import sys import time import matplotlib.pyplot as plt import numpy def update_line(h1, x, y): h1.set_xdata(numpy.append(h1.get_xdata(), x)) h1.set_ydata(numpy.append(h1.get_ydata(), y)) plt.draw() ''' __author__ = 'tjd08a' ''' port = None for arg in sys.argv: port = arg ser = serial....
nter = 0 seconds = 0 # h1, = plt.plot([], []) # Reboot sequence below ser.write('$$$') time.sleep(1) ser.write('reboot\r') time.sleep(3) start = None stop = None initial = True #plt.show(h1) while 1: #ser.write("hello world") bytesWaiting = ser.inWaiting() if bytesWaiting: # print bytesWaiting ...
r") readNum = True if initial: start = time.time() initial = False else: end = time.time() # print "Received %i" % val if (end - start >= 1): seconds += 1 print "%d: Total ...
myselfHimanshu/Udacity-DataML
Intro-To-Data-Science/Lesson3/PS3_6.py
Python
gpl-2.0
743
0.005384
import numpy as np import scipy import matplotlib.pyplot as plt def plot_residuals(turnstile_weather, predictions): ''' Using the same methods that we used to plot a histogram of entries per hour for our data, why don't you make a
histogram of the residuals (that is, the difference be
tween the original hourly entry data and the predicted values). Try different binwidths for your histogram. Based on this residual histogram, do you have any insight into how our model performed? Reading a bit on this webpage might be useful: http://www.itl.nist.gov/div898/handbook/pri/section2/pri24...
bhipple/brobot
currency.py
Python
gpl-3.0
336
0
#
Lookup Bitcoin value from exchanges from exchanges.bitfinex import Bitfinex import re def bitcoinValue(msg): val = Bitfinex().get_current_price() formattedVal = "$" + "{:,.2f}".format(val) if re.search(r"(?i)moon", msg): return "To the moon! " + formattedVal else: return "Bitcoin: " ...
l
hofmannedv/training-python
usecases/patterns-in-strings/pattern.py
Python
gpl-2.0
1,056
0.012311
# ----------------------------------------------------------- # find n
umber patterns in strings #o # (C
) 2016 Frank Hofmann, Berlin, Germany # Released under GNU Public License (GPL) # email frank.hofmann@efho.de # ----------------------------------------------------------- # # use the regex module import re text1 = "this is contract 14556-658, London, postcode SE30AF" text2 = "computer 2345-56, value EUR 255.18" text...
paulmcquad/Python
10-Tuples/Tuple_indices.py
Python
gpl-3.0
111
0.045045
t1 = ("apple",
"banana", "cherry", "durian", "orange") i = 0 while i < len( t1 ): print( t1[i] ) i
+= 1
pmghalvorsen/gramps_branch
gramps/gen/test/user_test.py
Python
gpl-2.0
1,410
0.002837
# -*- coding: utf-8 -*- # # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2013 Vassilii Khachaturov <vassilii@tarunz.org> # # 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; eith...
along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """ Unittest for user.py """ from __future__ import print_function import unittest from .. import user class TestUser(object): TITLE = "Testing prompt" MSG = "Choice...
user.User() def test_returns_False(self): assert not self.user.prompt( TestUser.TITLE, TestUser.MSG, TestUser.ACCEPT, TestUser.REJECT) if __name__ == "__main__": unittest.main()
obi-two/Rebelion
data/scripts/templates/object/mobile/shared_dressed_spice_collective_sentry_twk_male_01.py
Python
mit
469
0.046908
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICAT
IONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "objec
t/mobile/shared_dressed_spice_collective_sentry_twk_male_01.iff" result.attribute_template_id = 9 result.stfName("npc_name","twilek_base_male") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
gammalib/gammalib
inst/cta/test/test_CTA.py
Python
gpl-3.0
25,438
0.007155
# ========================================================================== # This module performs unit tests for the GammaLib CTA module. # # Copyright (C) 2012-2021 Juergen Knoedlseder # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as p...
' minimum energy') self.test_value(aeff(+2.20001, 0.0), 0.0, 1.0e-6, 'Test that effective area is zero for energy above' ' maximum energy') self.test_value(aeff(0.0, -0.00001), 0.0, 1.0e-6, 'Test that effective area is ...
st that effective area is zero for offset angle' ' above maximum offset angle') # Test GCTAAeffPerfTable file constructor filename = self._caldb + '/cta_dummy_irf.dat' aeff = gammalib.GCTAAeffPerfTable(filename) # Test Aeff values self.test_value(aef...
ltiao/networkx
networkx/algorithms/link_analysis/hits_alg.py
Python
bsd-3-clause
9,424
0.009975
"""Hubs and authorities analysis of graph structure. """ # Copyright (C) 2008-2012 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. # NetworkX:http://networkx.github.io/ import networkx as nx from networkx....
: interger, optional Maximum number of iterations in power method. tol : float, optional Error tolerance used to check convergence in power method iteration. nstart : dictionary, optional Starting value of each node for power method iteration. normalized : bool (default=True) No...
ies) : two-tuple of dictionaries Two dictionaries keyed by node containing the hub and authority values. Examples -------- >>> G=nx.path_graph(4) >>> h,a=nx.hits(G) Notes ----- This implementation uses SciPy sparse matrices. The eigenvector calculation is done by the pow...
AMLab-Amsterdam/lie_learn
lie_learn/groups/SO3_tests.py
Python
mit
3,912
0.00409
import numpy as np from lie_learn.groups.SO3 import * def test_change_parameterization(): def is_equal(R1, R2, p): if p == 'Q': # Quaternions are only defined up to a sign, so check each row, what sign we need for i in range(R1.shape[0]): if not (np.allclose(R1[i,...
qual(R1_p1_from_R1_p2, R1_p1, p1), ( p1 + ' to ' + p2 + ' | R1_p1: ' + str(R1_p1) + ' | R1_p2: ' + str(R1_p2) + ' | R1_p1_from_R1_p2: ' + str(R1_p1_from_R1_p2)) assert is_equal(R2_p1_from_R2_p2, R2_p1, p1), ( p1 + ' to ' + p2 + ' | R2_p1: ' + str(R2_p1) + ' | ...
(R2_p2) + ' | R2_p1_from_R2_p2: ' + str(R2_p1_from_R2_p2)) assert is_equal(R_p1_from_R_p2, R_p1, p1), ( p1 + ' to ' + p2 + ' | R_p1: ' + str(R_p1) + ' | R_p2: ' + str(R_p2) + ' | R_p1_from_R_p2: ' + str(R_p1_from_R_p2)) assert is_equal(R1_p2_from_R...
mk-pmb/heidisql-ubuntu-util
cfg.unpack.py
Python
gpl-2.0
3,798
0.001316
#!/usr/bin/python # -*- coding: UTF-8, tab-width: 4 -*- # Python Coding Style: http://docs.python.org/tutorial/con
trolflow.html#intermezzo-coding-style # Command Line Arguments Parser: http://docs.python.org/library/argparse.html from __future__ import division from sys import
argv, stdout, stderr from codecs import open as cfopen def main(invocation, *cli_args): HEIDI_CHARSET = 'UTF-8' INI_CHARSET = 'UTF-8-sig' if len(cli_args) < 1: raise ValueError('not enough parameters. required: ConfigFileName') cfg_fn = cli_args[0] cfg_realms = { 'app': {}, ...
softappeal/yass
py3/tutorial/generated/contract/__init__.py
Python
bsd-3-clause
2,223
0
from enum import Enum from typing import List, Any, cast import yass from tutorial.base_types_external import Integer # shows how to use contract internal base types class ExpirationHandler(yass.BaseTypeHandler): def readBase(self, reader: yass.Reader) -> 'Expiration': return Expiration( rea...
onlyNeededForTests2: bytes = cast(bytes, None) self.onlyNeededForTests3: Exception = cast(Exception, None) class Node: def __init__(self) -> None: self.id: float = cast(float, None) self.links: List[Node] = cast(List[Node], None)
self.next: Node = cast(Node, None) class EchoService: def echo(self, value: Any) -> Any: raise NotImplementedError() class PriceEngine: def subscribe(self, instrumentIds: List[Integer]) -> None: raise NotImplementedError() class PriceListener: def newPrices(self, prices: List[P...
Userperson321/DigitalGold
share/qt/clean_mac_info_plist.py
Python
mit
903
0.016611
#!/usr/bin/env python # Jonas Schnelli, 2013 # make sure the Digitalgold-Qt.app contains the right plist (including the right version) # fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267) from string import Template from datetime import date bitcoinDir = "./"; ...
ace(" ", "").split("="); if lineArr[0].startswith("VERSION"): version = lineArr[1].replace("\n", ""); fIn = open(inFile, "r") fileContent = fIn.read() s = Template(fileContent) newFileContent = s.substitute(VERSION=version,YEAR=date.today().y
ear) fOut = open(outFile, "w"); fOut.write(newFileContent); print "Info.plist fresh created"
openstack/ironic-lib
ironic_lib/disk_utils.py
Python
apache-2.0
30,540
0.000065
# Copyright 2014 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
number of primary partitions and logical partitions. :
raise: ValueError if the device does not have a valid MBR partition table. """ # -d do not update the kernel table # -s print a summary of the partition table output, err = utils.execute('partprobe', '-d', '-s', device, run_as_root=True, use_standard_locale=Tr...
AsherBond/MondocosmOS
grass_trunk/lib/python/array.py
Python
agpl-3.0
3,001
0.070976
"""!@package grass.script.array @brief GRASS Python scripting module (rasters with numpy) Functions to use GRASS rasters with NumPy. Usage: @code from grass.script import array as garray ... @endcode (C) 2010-2011 by Glynn Clements and the GRASS Development Team This program is free software under the GNU General ...
@param mapname name for raster map @param title title for raster map @param null null value @param overwrite True for overwritting existing raster maps @return 0 on success @return non-zero code on failure """ kind = self.dtype.kind size = self.dtype.itemsize...
elif size == 8: flags = 'd' else: raise ValueError(_('Invalid FP size <%d>') % size) size = None elif kind in 'biu': if size not in [1,2,4]: raise ValueError(_('Invalid integer size <%d>') % size) flags = None else: raise ValueError(_('Invalid kind <%s>') % kind) reg = gra...
DESHRAJ/fjord
vendor/packages/nose/unit_tests/test_core.py
Python
bsd-3-clause
2,069
0.002417
import os import sys import unittest from cStringIO import StringIO from optparse import OptionParser import nose.core from nose.config import Config from nose.tools import set_trace from mock import Bucket, MockOptParser class NullLoader: def loadTestsFromNames(self, names): return unittest.TestSuite() ...
tdout conf = Config(stream=s) # set_trace() print "About to run" res = nose.core.run( testLoader=NullLoader(), argv=['test_run'], env={}, config=conf) print "Done running" stdout_after = sys.stdout self.assertEqual(stdout, stdout_after) class Undefine...
estProgram.usage() assert usage_txt.startswith('nose collects tests automatically'), ( "Unexpected usage: '%s...'" % usage_txt[0:50].replace("\n", '\n')) def test_from_zip(self): requested_data = [] # simulates importing nose from a zip archive # with a zipimport.zi...
eonpatapon/rally
rally/plugins/openstack/types.py
Python
apache-2.0
5,962
0
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
limitations # under the License. from rally.common.plugin import plugin from rally import exceptions from rally.task import types @plugin.configure(name="nova_flavor") class Flavor(types.ResourceType): @classmethod
def transform(cls, clients, resource_config): """Transform the resource config to id. :param clients: openstack admin client handles :param resource_config: scenario config with `id`, `name` or `regex` :returns: id matching resource """ resource_id = resource_config.ge...
bcl/pykickstart
tests/commands/monitor.py
Python
gpl-2.0
2,924
0.002394
# # James Laska <jlaska@redhat.com> # # Copyright 2009 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, modify, # copy, or redistribute it subject to the terms and conditions of the GNU # General Public License v.2. This program is distributed in the hope that it # will be useful...
self.assert_parse("monitor", "") self.assert_parse("monitor --hsync=HSYNC", "monitor --hsync=HSYNC\n")
self.assert_parse("monitor --vsync=VSYNC", "monitor --vsync=VSYNC\n") self.assert_parse("monitor --monitor=MONITOR", "monitor --monitor=\"MONITOR\"\n") self.assert_parse("monitor --hsync=HSYNC --monitor=MONITOR", "monitor --hsync=HSYNC --monitor=\"MONITOR\"\n") ...
SpyDeX/BeepMiBot
bot/event_handler.py
Python
mit
3,806
0.011823
import json import logging import re logger = logging.getLogger(__name__) csRegStr4Hash = '\B(?P<Type>[\@\#\$\%\&])(?P<Text>\S+)' def FindHashes(srcStr, RegStr): #\B(?P<Type>[\@\#\$\%\&])(?P<Text>\S+) regex = r'' +RegStr matches = re.finditer(regex, srcStr, re.IGNORECASE | re.UNICODE) # plain = [] for matc...
turn {"cmd":"sms", 'hashes': None} return None; class RtmEventHandler(object): def __init__(self, slack_clients, msg_writer): self.clients = slack_clients self.msg_writer = msg_writer self.log = {}; def handle(self, event):
if 'type' in event: self._handle_by_type(event['type'], event) def _handle_by_type(self, event_type, event): # See https://api.slack.com/rtm for a full list of events if event_type == 'error': # error self.msg_writer.write_error(event['channel'], js...
OpenNingia/l5r-character-manager-3
l5r/dialogs/managedatapack.py
Python
gpl-3.0
5,427
0.000369
# -*- coding: utf-8 -*- # Copyright (C) 2014-2022 Daniele Simonetti # # 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. # ...
oregroundRole: if index.row() % 2: return self.settings.ui.table_row_color_alt_fg return self.settings.ui.table_row_color_fg elif role == QtCore.Qt.BackgroundRole: if index.row() % 2: return self.settings.ui.table_row_color_alt_bg r...
ngs.ui.table_row_size elif role == QtCore.Qt.UserRole: return item elif role == QtCore.Qt.CheckStateRole: return self.__checkstate_role(item, index.column()) return None def setData(self, index, value, role): if not index.isValid(): return False ...
alxgu/ansible-modules-extras
system/firewalld.py
Python
gpl-3.0
20,455
0.006698
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Adam Miller (maxamillion@fedoraproject.org) # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
pdate(fw_settings) def remove_source(zone, source): fw_zone = fw.config().getZoneByName(zone) fw_settings = fw_zone.getSettings() fw_settings.removeSource(source) fw_zone.update(fw_settings) #################### # interface handling # def get_interface(zone, interface): fw_zo
ne = fw.config().getZoneByName(zone) fw_settings = fw_zone.getSettings() if interface in fw_settings.getInterfaces(): return True else: return False def add_interface(zone, interface): fw_zone = fw.config().getZoneByName(zone) fw_settings = fw_zone.getSettings() fw_settings.addIn...
Battleroid/yanker
yanker/yanker.py
Python
mit
2,508
0.000797
""" Yanker Usage: yanker [--threads=<tnum>] """ __version__ = '1.0.1' import Queue import threading import youtube_dl as ydl import pyperclip as clip import time from docopt import docopt class ErrLogger(object): def debug(self, msg): pas
s def warning(self, msg): pass def error(self, msg): print msg class Worker(threading.Thread): def __init__(self, tasks): threading.Thread.__init__(self) self.tasks = tasks self.daemon = True se
lf.start() def run(self): while True: vid = self.tasks.get() vid.download() self.tasks.task_done() class Video: def progress(self, s): if s['status'] == 'finished': print 'Finished {}'.format(s['filename']) def __init__(self, url, opts={}):...
snapcore/snapcraft
tools/collect_ppa_autopkgtests_results.py
Python
gpl-3.0
2,694
0.001485
#!/usr/bin/env python3 # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2017 Canonical Ltd # # This program is free softwar
e: 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 hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR ...
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/>. import argparse import os import subprocess import tempfile ACTIVE_DISTROS = ("xenial", "artful", "bionic") def main(): parser = argparse...
dunkhong/grr
grr/core/grr_response_core/lib/type_info_test.py
Python
apache-2.0
5,306
0.002271
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2012 Google Inc. All Rights Reserved. """Tests for grr.lib.type_info.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from absl import app from grr_response_core.lib import type_info from grr...
_info.TypeValueError, a.Validate, 2) self.assertRaises(type_info.TypeValueError, a.Validate, "ab") self.assertRaises(type_info.TypeValueError, a.Validate, [1, 2]) # None values are left as is. self.assertEqual(None, a.Validate(None)) # Check that validation raises when unknown attributes are passe...
htype="TSK")) self.assertIsInstance(v, rdf_paths.PathSpec) self.assertEqual(v.path, "blah") self.assertEqual(v.pathtype, "TSK") def testTypeDescriptorSet(self): type_infos = [ type_info.String(name="output", default="analysis/{p}/{u}-{t}"), type_info.String( description="...
kongsally/Deep-Learning-for-Automated-Discourse
FirstChatbot/seq2seq_model.py
Python
mit
14,119
0.003966
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
============================================= """Sequence-to-sequence model with an attention mechanism.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import random import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin ...
ce-to-sequence model with attention and for multiple buckets. This class implements a multi-layer recurrent neural network as encoder, and an attention-based decoder. This is the same as the model described in this paper: http://arxiv.org/abs/1412.7449 - please look there for details, or into the seq2seq libra...
django-bmf/django-bmf
djangobmf/core/module.py
Python
bsd-3-clause
17,355
0.00023
#!/usr/bin/python # ex:set fileencoding=utf-8: from __future__ import unicode_literals from django.conf.urls import patterns from django.conf.urls import url from django.contrib.admin.sites import AlreadyRegistered from django.contrib.contenttypes.models import ContentType from django.core.exceptions import Improperl...
es many functions used in the whole framework. """ open_relation = None workflow_class = None workflow_field_name = "state" detail_view = ModuleDetail def __init__(self, bmfconfig): # validation if not hasattr(self, 'model'): raise ImproperlyConfigur
ed( 'No model defined in %s.' % self.__class__ ) self.bmfconfig = bmfconfig self._class_reports = {} self._object_reports = {} self._relations = [] self.signals_setup() self.validate_workflow() # auto add document relationship ...
Lajnold/adventofcode2015
day12.py
Python
mit
1,136
0.001761
#!/usr/bin/env p
ython3 import json with open("day12-input.txt") as f: day12_input = f.read() day12_input_json = json.loads(day12_input) def is_int(token): return isinstance(token, int) def is_list(token): return isinstance(token, list) def is_dict(token): return isinstance(token, dict) def part1(): def ...
sum(crawl(el) for el in x) elif is_dict(x): return sum(crawl(el) for el in x.values()) else: return 0 input_sum = crawl(day12_input_json) print("Sum of numbers: {}".format(input_sum)) def part2(): def has_forbidden_value(x): return "red" in x.values() ...
zentralopensource/zentral
tests/utils/http_server.py
Python
apache-2.0
1,158
0
import http.server import sys class ServerHandler(http.server.BaseHTTPRequestHandler): def _process_request(self): self.log_message("<<<HEADERS") self.log_message(self.headers.as_string().strip()) self.log_message("HEADERS>>>") self.log_message("<<<BODY") try: c...
int(self.headers['Content-Length']) except TypeError: self.log_message("ERROR: missing Content-Length") else: self.log_message(self.rfile.read(content_length).decode("utf-8")) self.log_message("BODY>>>") self.send_response(200) self.send_header('Content-T...
utf-8")) def do_GET(self): self._process_request() def do_POST(self): self._process_request() if __name__ == "__main__": try: port = int(sys.argv[1]) except Exception: port = 8000 server_address = ('', port) print("Starting server:", server_address) httpd ...
mikesun/xen-cow-checkpointing
tools/python/xen/xend/XendBootloader.py
Python
gpl-2.0
5,656
0.006188
# # XendBootloader.py - Framework to run a boot loader for picking the kernel # # Copyright 2005-2006 Red Hat, Inc. # Jeremy Katz <katzj@redhat.com> # # This software may be freely redistributed under the terms of the GNU # general public license. # # You should have received a copy of the GNU General Public License # ...
log.error(msg) raise VmError,
msg pin = sxp.Parser() pin.input(ret) pin.input_eof() blcfg = pin.val return blcfg def bootloader_tidy(dom): if hasattr(dom, "bootloader_pid") and dom.bootloader_pid is not None: pid = dom.bootloader_pid dom.bootloader_pid = None os.kill(pid, signal.SIGKILL)
subkar/rasmodel
src/simulate_chen_2009.py
Python
mit
755
0
from REM.chen_2009 import model from pysb.integrate import Solver from pysb.bng import generate_equations import numpy as np import matplotlib.pyplot as plt import sympy # Replicate matlab simulation # Implement "fixed" species (they are never consumed). generate_equations(model) for i in (5, 6, 7): model.odes[i]...
(solver.yobs, 'pERK', 'g'),
(solver.yobs, 'pAKT', 'r')]): plt.subplot(3, 1, i + 1) plt.plot(tspan, arr[obs], c=color, label=obs) plt.show()
wandb/client
wandb/vendor/watchdog/observers/inotify.py
Python
mit
8,528
0.001993
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com> # Copyright 2012 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 # # ...
ete or (event.is_moved_from and not full_events): cls = DirDeletedEvent if event.is_directory else FileDeletedEvent self.queue_event(cls(src_path)) self.queue_event(DirModifiedEvent(
os.path.dirname(src_path))) elif event.is_moved_from and full_events: cls = DirMovedEvent if event.is_directory else FileMovedEvent self.queue_event(cls(src_path, None)) self.queue_event(DirModifiedEvent(os.path.dirname(src_path))) elif event.is_cr...
derkling/trappy
tests/test_sched.py
Python
apache-2.0
5,299
0.002076
# Copyright 2015-2015 ARM Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
self.assertEquals(dfr["capacity"].iloc[0], 430)
self.assertEquals(dfr["rt_capacity"].iloc[0], 1024) class TestSchedCpuFrequency(BaseTestSched): def test_get_dataframe(self): """Test that CpuFrequency creates a proper data_frame""" dfr = trappy.Run().sched_cpu_frequency.data_frame self.assertTrue(len(dfr) == 1) self.assertEqu...
ics/doc8643
app/__init__.py
Python
mit
930
0.009677
from flask import Flask, render_template from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.mail import Mail from flask.ext.assets import Environment #from flask.ext.adm
in import Admin #from flask_debugtoolbar import DebugToolbarExtension app = Flask(__name__) app.config.from_object('config') # SelectiveHTMLCompress {% strip %} ... {% endstrip %} app.jinja_env.add_extension('app.helpers.jinja2htmlcompress.
HTMLCompress') assets = Environment(app) #js = Bundle("js/vendor/jquery-1.9.1.min.js", "js/vendor/bootstrap.min.js", # "js/vendor/jquery.masonry.min.js", "js/vendor/jquery.infinitescroll.min.js", # filters='jsmin', output='gen/packed.js') #assets.register('js_all', js) db = SQLAlchemy(app) #admi...
wathen/PhD
MHD/FEniCS/FieldSplit/NSpicard.py
Python
mit
8,721
0.014104
#!/usr/bin/env python import petsc4py import sys petsc4py.init(sys.argv) from petsc4py import PETSc # from MatrixOperations import * from dolfin import * import numpy as np import matplotlib.pylab as plt import os import scipy.io from PyTrilinos import Epetra, EpetraExt, AztecOO, ML, Amesos from scipy2Trilinos import ...
:Vdim}) # scipy.io.savem
at('DoF.mat', {'DoF':DoF}) # plt.loglog(NN,errL2u) # plt.title('Error plot for CG2 elements - Velocity L2 convergence = %f' % np.log2(np.average((errL2u[0:m-2]/errL2u[1:m-1])))) # plt.xlabel('N') # plt.ylabel('L2 error') # plt.figure() # plt.loglog(NN,errL2p) # plt.title('Error plot for CG1 elements - Pressure L2 c...
EvilMcJerkface/crate
devs/tools/create_certs.py
Python
apache-2.0
4,616
0.002166
#!/usr/bin/env python3 """Script to generate a keystore with node and client certificates. Requires keystore and openssl to be available in $PATH """ import os import argparse from os.path import join, splitext, basename from subprocess import run def int_or(val, default): if val: return int(val) r...
= join(out_dir, 'keystore.jks') keystore_p12 = join(out_dir, 'keystore.p12') import_into_keystores(certs_and_keys, 'node', keystore_pw, ca_crt, keystore, keystore_p12) # the CA certificate should also be in the keystore for the # node to be able to verify the client certificate run(['keytool', '-imp...
and_keys = generate_for(ca_key, ca_crt, out_dir, 'client', 1) keystore_client = join(out_dir, 'keystore_client.jks') keystore_client_p12 = join(out_dir, 'keystore_client.p12') import_into_keystores(certs_and_keys, 'client', keystore_pw, ca_crt, keystore_client, keystore_client_p12) def main(): parser ...
ruippeixotog/beets
beetsplug/duplicates.py
Python
mit
13,370
0.000374
# This file is part of beets. # Copyright 2015, Pedro Silva. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, mod...
help='report duplicates based on' ' arbitrary command') self._c
ommand.parser.add_option('-d', '--delete', dest='delete', action='store_true', help='delete items from library and ' 'disk') self._command.parser.add_option('-F', '--full', dest='full', ...
t-mertz/slurmCompanion
django-web/sshcomm/migrations/0003_auto_20170118_1901.py
Python
mit
697
0.001435
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-18 18:01 from __future__ import unicode_literals from django.db import migrations, models import django.forms.widgets class Migration(migrations.Migration): dependencies = [
('sshcomm', '0002_auto_20170118_1702'), ] operations = [ migrations.AlterField( model_name='userdata', name='user_name', field=models.CharField(max_length=128), ), migrations.AlterField( model_name='userdata', name='use
r_password', field=models.CharField(max_length=128, verbose_name=django.forms.widgets.PasswordInput), ), ]
apache/qpid-dispatch
tests/system_tests_core_endpoint.py
Python
apache-2.0
9,396
0.005747
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache Licens
e, 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...
mosbasik/dotatreasures
create_treasures_json.py
Python
mit
794
0.002519
#!/usr/bin/py
thon import json f = file('treasures.json', 'r') try: foo = json.load(f) json_contents = foo except ValueError: json_contents = dict() f.close() print 'Type \'q\' to [q]uit' while True: name = raw_input('Treasure Name: ') if name == 'q': break print 'Type \'n\' to stop entering heroe...
== 'n' or hero == 'q': break else: bundle_rating = raw_input('Item set rating [1-3]: ') set_contents[hero] = bundle_rating json_contents[name] = set_contents if hero == 'q': break f = open('treasures.json', 'w') json.dump(json_contents, f, indent=4) f.close(...
quuxlabs/goodiff-core
includes/GooDiffProvider.py
Python
agpl-3.0
307
0.006515
from GooDiffService import GooDiffService class GooDiffProvider: def __init__(self, name, services=None):
self.name = name self.services = services
or [] def debug(self): print "Provider name:", self.name for service in self.services: service.debug()
DROPCitizenShip/e-cidadania
tests/unit_tests/helpers/test_cache.py
Python
gpl-3.0
2,101
0.007139
# -*- coding: utf-8 -*- # # Copyright (c) 2010-2012 Cidadania S. Coop. Galega # # This file is part of e-cidadania. # # e-cidadania 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. # # e-cidadania 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 e-cidadania. If not, see <http://www.gnu.org/licenses/>. from django.core.cache import cache from core.spaces.models import Space from src.helpers import cache as cache_helper from...
chubbymaggie/cle
cle/backends/blob.py
Python
bsd-2-clause
2,119
0.006607
from ..backends import Backend from ..errors import CLEError import logging import os l = logging.getLogger("cle.blob") __all__ = ('Blob',) class Blob(Backend): """ Representation of a binary blob, i.e. an executable in an unknown file format. """ def __init__(self, path, custom_arch=None, custom_of...
ne: string = self.binary_stream.read() else: string = self.binary_stream.read(size) self.memory.add_backer(0, string) self._max_addr = len(string) def function_name(se
lf, addr): #pylint: disable=unused-argument,no-self-use """ Blobs don't support function names. """ return None def contains_addr(self, addr): return addr in self.memory def in_which_segment(self, addr): #pylint: disable=unused-argument,no-self-use """ B...
BlaXpirit/steam-notifier
app/cookies.py
Python
gpl-3.0
1,650
0.006061
# Copyright (C) 2014-2015 Oleh Prypin <blaxpirit@gmail.com> # # This file is part of Steam Notifier. # # Steam Notifier 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 # (...
ult = QNetworkCookieJar.setCookiesFromUrl(self, cookies, url) self.save_to_file(self.filename) return result def save_to_file(self, filename): with open(filename, 'wb') as f: for cookie in self.allCookies():
f.write(cookie.toRawForm().data()) f.write(b'\n\n')
magnusmorton/pycket
pycket/values_struct.py
Python
mit
45,589
0.002479
import itertools from pycket import config from pycket import values from pycket import vector as values_vector from pycket.arity import Arity from pycket.base import SingleResultMixin, UnhashableType from pycket.cont import continuation, label from pycket.error import SchemeException from pycket.prims.expose import d...
d returns an instance of W_StructType only.
It does not support properties. """ if inspector is PREFAB: prefab_key = W_PrefabKey.from_raw_params(name, init_field_cnt,\ auto_field_cnt, auto_v, immutables, super_type) if prefab_key in W_StructType.unbound_prefab_types: return W_StructType...
Teknologforeningen/tf_arsfest
tf_arsfest/forms.py
Python
mit
366
0.016393
from django.forms import ModelForm, RadioSelect from models import Registration, Guest class RegistrationForm(ModelForm): class Meta:
model = Registration exclude = ('guest', 'avec', 'event', 'reference_number', 'sum') class GuestForm(ModelForm): class Meta: model = Guest exclude = ('event')
Daerdemandt/Learning-bioinformatics
LEXF/Solution.py
Python
apache-2.0
366
0.032787
#!/usr/bin/env python3 def get_strin
gs(alphabet, length): if length == 0: yield '' else: for ch in alphabet: for st in get_strings(alphabet, length - 1): yield ch + st def main(): alphabet = "T A G C".split() length = 2 with open("Output.txt", "w") as output_file: for st in get_strings(alphabet, length): print(st, file=output_file) ...
()
ostrokach/bioconda-recipes
recipes/pgdspider/PGDSpider2-cli.py
Python
mit
3,267
0.000918
#!/usr/bin/env python # # Wrapper script for Java Conda packages that ensures that the java runtime # is invoked with the right options. Adapted from the bash script (http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in/246128#246128). # # Program Parameters # import os import s...
f the form: (memory_options, prop_options, passthrough_options) """ mem_opts = [] prop_opts = [] pass_args = [] exec_dir =
None for arg in argv: if arg.startswith('-D'): prop_opts.append(arg) elif arg.startswith('-XX'): prop_opts.append(arg) elif arg.startswith('-Xm'): mem_opts.append(arg) elif arg.startswith('--exec_dir='): exec_dir = arg.split('=')[1].st...