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
pydawan/protetores_bucais
protetores_bucais/apps/destaques/migrations/0001_initial.py
Python
mit
843
0.004745
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Destaque', fields=[ ('id', models.AutoField(ver...
True, primary_key=True)), ('titulo', models.CharField(max_length=100, verbose_name=b'T\xc3\xadtulo')), ('descricao', models.TextField(verbose_name=b'Descri\xc3\xa7\xc3\xa3o', blank=True)), ('imagem', models.ImageField(upload_to=b'imagens/destaques', blank=True)), ...
]
krafczyk/spack
var/spack/repos/builtin/packages/gtkmm/package.py
Python
lgpl-2.1
2,394
0.000835
############################################################################## # 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, [email protected], All rights reserved. # LLNL-CODE-64...
version('2.19.6', 'fb140e82e583620defe0d70bfe7eefd7') version('2.19.4', '60006a23306487938dfe0e4b17e3fa46') version('2.19.2', 'dc208575a24e8d5265af2fd59c08f3d8') version('2.17.11', '2326ff83439aac83721ed4694acf14e5') version('2.17.1', '19358644e5e620ad738658be2cb6d739') versi
on('2.16.0', 'de178c2a6f23eda0b6a8bfb0219e2e1c') version('2.4.11', 'a339958bc4ab7f74201b312bd3562d46') depends_on('glibmm') depends_on('atk') depends_on('gtkplus') depends_on('pangomm') depends_on('cairomm') def url_for_version(self, version): """Handle glib's version-based custom ...
teoreteetik/api-snippets
monitor/events/list-get-example-sourceipaddress-filter/list-get-example-sourceipaddress-filter.6.x.py
Python
mit
552
0
# Download the
Python helper library from twilio.com/docs/python/install from datetime import datetime import pytz from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACCOUNT_SID" auth_token = "your_auth_token" client = Client(account
_sid, auth_token) events = client.monitor.events.list( source_ip_address="104.14.155.29", start_date=datetime(2015, 4, 25, tzinfo=pytz.UTC), end_date=datetime(2015, 4, 25, 23, 59, 59, tzinfo=pytz.UTC) ) for e in events: print(e.description)
Taapat/enigma2-openpli-vuplus
lib/python/Plugins/SystemPlugins/AnimationSetup/plugin.py
Python
gpl-2.0
9,065
0.030667
from Screens.Screen import Screen from Screens.MessageBox import MessageBox from Components.ActionMap import ActionMap from Components.ConfigList import ConfigListScreen from Components.MenuList import MenuList from Components.Sources.StaticText import StaticText from Components.config import config, ConfigNumber, Conf...
= StaticText(_("Default")) self.makeConfigList() self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.setTitle(_('Animation Setup')) def keyGreen(self): co
nfig.misc.window_animation_speed.save() setAnimation_speed(int(config.misc.window_animation_speed.value)) setAnimation_speed(int(config.misc.window_animation_speed.value)) config.misc.listbox_animation_default.save() setAnimation_current_listbox(int(config.misc.listbox_animation_default.value)) self.close() ...
sfu-fas/coursys
ra/migrations/0017_add_processor_field.py
Python
gpl-3.0
636
0.001572
# Generated by Django 2.2.15 on 2021-10-07 12:02 import django.core.files.storage from django.db import migrations, models import django.db.models.deletion import ra.models class Migration(migrations.Migration): dependencies = [ ('coredata', '0025_update_choices'), ('ra', '0016_
add_drafts'), ] operations = [ migrations.AddField( model_name='rarequest', name='processor', field=models.ForeignKey(default=None, editable=False, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='rarequest_processo
r', to='coredata.Person'), ), ]
jakobharlan/avango
avango-display/python/avango/display/setups/AutoStereoDisplay.py
Python
lgpl-3.0
2,055
0.000973
# -*- Mode:Python -*- ########################################################################## # # # This file is part of AVANGO. # # ...
####################### import avango.display class AutoStereoDisplay(avango.display.Display): def __init__(self, inspector
, options): super(AutoStereoDisplay, self).__init__("AutoStereoDisplay", inspector) window = self.make_window(0, 0, 1200, 1600, 0.33, 0.43, True) window.Name.value = "" self.add_window(window, avango.osg.make_trans_mat(0, 1.7, -0.7), 0) user = avango.display.nodes.User() ...
willingc/vms
vms/volunteer/views.py
Python
gpl-2.0
7,224
0.004291
import os from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.core.servers.basehttp import FileWrapper from django.core.urlresolvers import reverse from django.http import Http404, HttpResponse, HttpResponseRedirect ...
.models import Volunteer from volunteer.services import * from volunteer.validation import validate_file from django.views.generic import View from django.core.urlresolvers import reverse_lazy @login_required def download_resume(request, volunteer_id):
user = request.user if int(user.volunteer.id) == int(volunteer_id): if request.method == 'POST': basename = get_volunteer_resume_file_url(volunteer_id) if basename: filename = settings.MEDIA_ROOT + basename wrapper = FileWrapper(file(filename))...
akvo/akvo-rsr
akvo/iati/exports/elements/current_situation.py
Python
agpl-3.0
877
0.003421
# -*- coding: utf-8 -*- # Akvo RSR is covered by the GNU Affero General Public License. # See more details in the license.txt file located at the root folder of the Akvo RSR module. # For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >. from lxml import etree def current_s...
ement with type "1" and akvo type "9"
. :param project: Project object :return: A list of Etree elements """ if project.current_status: element = etree.Element("description") element.attrib['type'] = '1' element.attrib['{http://akvo.org/iati-activities}type'] = '9' narrative_element = etree.SubElement(eleme...
apyrgio/ganeti
test/py/cmdlib/backup_unittest.py
Python
bsd-2-clause
7,522
0.003722
#!/usr/bin/python # # Copyright (C) 2013 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: # # 1. Redistributions of source code must retain the above copyright notice, # this list of...
[objects.ImportExportStatus(
exit_status=0 )]) self.rpc.call_impexp_status.side_effect = ImpExpStatus def ImpExpCleanup(node_uuid, name): return self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(node_uuid) self.rpc.call_impexp_cleanup.side_effect = ImpE...
nlamirault/python-freeboxclient
freeboxclient/simple.py
Python
apache-2.0
1,473
0
# # Copyright 2013 Nicolas Lamirault <[email protected]>. # # 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 ...
action(self, parsed_args): conf = config.load_configuration() if conf: self.app.stdout.write("Configuration
:\n%s" % conf) else: self.app.stdout.write("Configuration file %s doesn't exists.\n" % config)
naturalness/unnaturalcode
unnaturalcode/mutators.py
Python
agpl-3.0
7,294
0.010008
from copy import copy from random import randint class Mutators(object): def deleteRandom(self, vFile): """Delete a random token from a file.""" ls = copy(vFile.scrubbed) idx = randint(1, len(ls)-2) after = ls[idx+1] token = ls.pop(idx) if token.type == 'ENDMARKER'...
) line = len(linesbefore) lineChar = len(linesbefore[-1]) c = s[charPos:charPos+1] if (punct.match(c)): break new = s[:charPos] + s[charPos+1:] vFile.mutatedLexemes = vFile.lm(new) vFile.mutatedLocation = pythonLexeme.fromTuple((token.OP, c, (l...
ineChar), (line, lineChar))) return None def colonRandom(self, vFile): s = copy(vFile.original) while True: charPos = randint(1, len(s)-1) linesbefore = s[:charPos].splitlines(True) line = len(linesbefore) lineChar = len(linesbefore[-1]) c =...
googlefonts/diffbrowsers
bin/test_gf_autohint.py
Python
apache-2.0
2,225
0.004494
""" If a family has been hinted with ttfautohint. The x-height must remain the same as before. Users do notice changes: https://github.com/google/fonts/issues/644 https://github.com/google/fonts/issues/528 """ from __future__ import print_function, division, absolute_import, unicode_literals import argparse import os ...
) args = parser.parse_args() auth = load_browserstack_credentials() browsers_to_test = test_browsers['all_browsers'] fonts_before = 'from-googlefonts' if args.from_googlefonts \ else args.fonts_before diffbrowsers = DiffBrowsers(dst_dir=args.output_dir, browsers=browsers_to_t...
0 secs. Giving Browserstack api a rest") time.sleep(10) diffbrowsers.update_browsers(test_browsers['osx_browser']) diffbrowsers.diff_view('glyphs-modified', gen_gifs=True) report = cli_reporter(diffbrowsers.stats) report_path = os.path.join(args.output_dir, 'report.txt') with open(report_path,...
checkr/fdep
tests/fixtures/serve/app.py
Python
mit
36
0
def
classify(text): return T
rue
chopmann/warehouse
tasks/__init__.py
Python
apache-2.0
603
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 # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the Lice...
from . import pip ns = invoke.Collection(pip)
KennethPierce/pylearnk
pylearn2/space/__init__.py
Python
bsd-3-clause
85,589
0.000093
""" Classes that define how vector spaces are formatted Most of our models can be viewed as linearly transforming one vector space to another. These classes define how the vector spaces should be represented as theano/numpy variables. For example, the VectorSpace class just represents a vector space with a vector, an...
eric) def _dense_to_sparse(batch): """ Casts dense batches to sparse batches (non-composite). Supports both symbolic and numeric variables. """ if isinstance(batch, tuple): raise TypeError("Composite batches not supported.") assert not isinstance(batch, list) if is_symbolic_batc...
assert isinstance(batch, theano.tensor.TensorVariable) return theano.sparse.csr_from_dense(batch) else: assert isinstance(batch, np.ndarray), "type of batch: %s" % type(batch) return scipy.sparse.csr_matrix(batch) def _reshape(arg, shape): """ Reshapes a tensor. Supports bot...
vdmtools/vdmtools
test/powertest/tcrun.py
Python
gpl-3.0
14,259
0.019216
import gentestcases, cmdline, util, setup, report, convert, resfile import os, re, locale true, false = 1,0 #-------------------------------------------------------------------------------- # Execute type checker test environment. # lang - language to use (SL, PP, RT) # type - type of test (either spec or impl) # retu...
eport.Progress(3, "Running " + name) ok = RunImplTestCase(name, lang, posdef) if util.CleanFile(ok): bn = util.ExtractName(name) util.DeleteFiles([bn+".vdm"]) name = gentestcases.NextTestCase() total = total +1 util.MoveProfile() #-----------------------------------------------------...
------------------ # Prepare a single test case for specification test run. # name - the full name of the .vdm file to test # lang - the language to use (SL, PP) # posdef - variant to run (pos,def) # return - a boolean which indicates whether the preparation went ok. #---------------------------------------------------...
Triv90/SwiftUml
swift/proxy/controllers/obj.py
Python
apache-2.0
50,946
0.000059
# Copyright (c) 2010-2012 OpenStack, LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
'%(path)s etag: %(r_etag)s != %(s_etag)s or ' 'size: %(r_size)s != %(s_size)s') % {'path': path, 'r_e
tag': resp.etag, 's_etag': self.segment_dict['hash'], 'r_size': resp.content_length, 's_size': self.segment_dict['bytes']}) self.segment_iter = resp.app_iter # See NOTE: swift_conn at top of file about this. s...
artwr/airflow
airflow/hooks/base_hook.py
Python
apache-2.0
3,203
0
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
n = cls._get_connection_from_env(conn_id) if conn: conns = [conn] else: conns = cls._get_connections_from_db(conn_id) return conns @classmethod def get_connection(cls, conn_id): conn = random.choice(cls.get_connections(conn_id)) if conn.host: ...
log log.info("Using connection to: %s", conn.debug_info()) return conn @classmethod def get_hook(cls, conn_id): connection = cls.get_connection(conn_id) return connection.get_hook() def get_conn(self): raise NotImplementedError() def get_records(self, sql):...
TNG/svnfiltereddump
functional_tests/command_line_feature_tests.py
Python
gpl-3.0
13,483
0.013053
import unittest from subprocess import call from functional_test_environment import TestEnvironment class ComandLineFeatureTests(unittest.TestCase): def setUp(self): self.env = TestEnvironment() def tearDown(self): self.env.destroy() def check_log_of_file_in_rev(self, name, rev, e...
self.env.get_log_of_file_in_rev(name, rev) if error is None: self.assertEquals(parsed_log, exected_log) else: self.fail( "Failed to get log of file %s in revision %d with error:\n%s" % ( nam
e, rev, error ) ) def test_basic_call(self): env = self.env # Revision 1 env.mkdir('a') env.add_file('a/bla', 'xxx') env.propset('a/bla', 'some_prop', 'prop_value') env.mkdir('b') env.add_file('b/blub', 'yyy') env.commit('c1') # Re...
medialab/ANTA2
anta/readers/unfccc_reader.py
Python
lgpl-3.0
4,367
0.003664
#!/usr/bin/python # -*- coding: utf-8 -*- # coding=utf-8 import csv import logging import os from anta.util import config from anta.annotators import pattern_annotator from anta.annotators import tika_annotator from anta.storage.solr_client import SOLRInterface def read(): data_dir = config.config["data_dir"] ...
ar/unfccc_adaptation_metadatas.csv" unfccc_files_path = data_dir + "/UNFCCC Documents/unfccc_adaptation_1991-2012.tar/pdfs" read_collection(unfccc_csv_path, unfccc
_files_path) # 2003-2012 unfccc_csv_path = data_dir + "/UNFCCC Documents/unfccc_adaptation_2003-2012.tar/unfccc_adaptation_metadatas.csv" unfccc_files_path = data_dir + "/UNFCCC Documents/unfccc_adaptation_2003-2012.tar/pdfs" read_collection(unfccc_csv_path, unfccc_files_path) def read_collection(csv...
khandavally/devstack
EPAQA/vf_allocation.py
Python
apache-2.0
4,020
0.012687
from nova.db.sqlalchemy import api as model_api from nova.db.sqlalchemy.models import PciDevice, Instance, ComputeNode import collections #, VFAllocation session = model_api.get_session() WORK_LOAD = ["cp","cr"] def execute_vf_allocation(req_vf,los,req_work,bus_list, *args,**kwargs): """This method is ...
tmp_add_store = ("") REQ_VF = req_work RESET_COUNT = 0 for k in range(req_vf): if REQ_VF == "cp-cr" and ( req_vf / 2 != RESET_COUNT ): req_work = 'cp' RESET_COUNT = RESET_COUNT + 1 elif REQ_VF == "cp-cr" and ( req_vf / 2 <= RESET_COUNT ): ...
os} # Filter the Bus slot having vfs less than los value for selected workload if req_work == 'cp': final_list = sorted(filter_data, key=lambda x: (filter_data[x][0]['cp'], filter_data[x][0]['cr'])) # sort the filtered dict based on cp cr count else: final_list = sorted(filte...
domino14/Webolith
djAerolith/wordwalls/apps.py
Python
gpl-3.0
96
0
fro
m django.ap
ps import AppConfig class WordwallsAppConfig(AppConfig): name = 'wordwalls'
livef1/Livef1-web
src/comment.py
Python
gpl-2.0
3,104
0.02674
# # livef1 # # f1comment.py - classes to store the live F1 comments # # Copyright (c) 2014 Marc Bertens <[email protected]> # # 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; eit...
sep = "" #endif output = "<tr valign='top'><td>%s</td><td>%s</td><td>%s</td></tr>" % ( elem.clock, sep, elem.text ) + output return """<div class="%s"><table>%s</table></div>""" % ( div_tag_name, output ) def append( se...
clock: secs = new.timestamp % 60 mins = new.timestamp // 60 hours = 0 if ( mins > 60 ): hours = mins // 60 mins = mins % 60 # endif # add time stamp new.clock = "%02i:%02i" % ( hours, mins ) self...
cropr/bjk2017
cd_subscription/migrations/0006_cdsubscription_badgemimetype.py
Python
apache-2.0
478
0.002092
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migratio
ns.Migration): dependencies = [ ('cd_subscription', '0005_auto_20161125_1908'), ] operations = [ migrations.AddField( model_name='cdsubscription', name='badgemimetype', field=models.CharField(default='', max_length=20, blank=True, ve
rbose_name='Badge mimetype'), ), ]
chrsrds/scikit-learn
sklearn/tree/tests/test_tree.py
Python
bsd-3-clause
68,270
0.000059
""" Testing for the tree module (sklearn.tree). """ import copy import pickle from functools import partial from itertools import product import struct import pytest import numpy as np from scipy.sparse import csc_matrix from scipy.sparse import csr_matrix from scipy.sparse import coo_matrix from sklearn.random_proje...
1, -1, 1, 0, 0, -2, 3, 0, 1, 0, ], [2, 0, 1, 2, 3, -1, 10, 2, 0, -1, 1, 2, 2, 0, ], [1, 1, 0, 2, 2, -1, 1, 2, 0, -5, 1, 2, 3, 0, ], [3, 1, 0, 3, 0, -4, 10, 0, 1, -5, 3, 0, 3, 1, ], [2.11, 8, -6, -0.5, 0, 1, 0, 0, -3.2, 6, 0.5, 0, -3, 1, ], [2.11, 8, -6, -0.5, 0, 1, 0, 0, -3.2, 6, 1.5, 1, -1, -1, ], ...
[2, 1, 1, 1, 2, -1, 10, 2, 0, -1, 0, 2, 1, 1, ], [1, 1, 0, 0, 1, -3, 1, 2, 0, -5, 1, 2, 1, 1, ], [3, 1, 0, 1, 0, -4, 1, 0, 1, -2, 0, 0, 1, 0, ]]) y_small = [1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0] y_small_reg = [1.0, 2.1, 1.2, 0.05, 10, 2.4, 3.1, 1.01, 0.01, 2.98, 3.1, 1...
gentnerlab/pyoperant
pyoperant/local_zog.py
Python
bsd-3-clause
7,782
0.006682
from pyoperant import hwio, components, panels, utils from pyoperant.interfaces import comedi_, pyaudio_ from pyoperant import InterfaceError import time _ZOG_MAP = { 1: ('/dev/comedi0', 2, 0, 2, 8), # box_id:(subdevice,in_dev,in_chan,out_dev,out_chan) 2: ('/dev/comedi0', 2, 4, 2, 16), 3: ('/dev/comedi0', ...
}, ) ) for out_chan in [ii+_ZOG_MAP[self.id][4] for ii in range(8)]: self.outputs.append(hwio.BooleanOutput(interface=self.interfaces['comedi'], ...
}, ) ) self.speaker = hwio.AudioOutput(interface=self.interfaces['pyaudio']) # assemble inputs into components self.left = components.PeckPort(IR=self.inpu...
skobz/Python
Find_Duplicates.py
Python
mit
651
0.019969
# Name: Pre-Logic Script C
ode # Created: April, 27, 2015 # Author: Sven Koberwitz # Purpose: Find the number of occurrences of a value in a Field using Field Calculator. ## Pre-Logic Script Code import arcpy uniqueList = {} ## Set the name of the feature class here fc = "feature_class" rows = arcpy.SearchCursor(fc) for row in rows: ## Se...
getValue("field_name") if value not in uniqueList: uniqueList[value] = 1 else: uniqueList[value] = uniqueList[value] + 1 def duplicates(inValue): return uniqueList[inValue] ## Use this as the calculation formula duplicates(!field_name!)
leoc/home-assistant
homeassistant/components/conversation.py
Python
mit
2,231
0
""" Support for functionality to have conversations with Home Assistant. For more details about this component, please refer to the documentation at https://home-assistant.io/components/conversation/ """ import logging import re import warnings import voluptuous as vol from homeassistant import core from homeassista...
MAIN, SERVICE_TURN_ON, { ATTR_ENTITY_ID: entity_ids,
}, blocking=True) elif command == 'off': hass.services.call(core.DOMAIN, SERVICE_TURN_OFF, { ATTR_ENTITY_ID: entity_ids, }, blocking=True) else: logger.error('Got unsupported command %s from text %s', command, text) has...
CompPhysics/ComputationalPhysics2
doc/LectureNotes/_build/jupyter_execute/logisticregression.py
Python
cc0-1.0
22,266
0.008758
#!/usr/bin/env python # coding: utf-8 # # Logistic Regression # # ## Introduction # # In linear regression our main interest was centered on learning the # coefficients of a functional fit (say a polynomial) in order to be # able to predict the response of a continuous variable on some unseen # data. The fit to the ...
unction of age may serve as an illustration. In the code here we read and plot whether a person has had CHD (output = 1) or not (output = 0). This ouput is plotted the person's against age. Clearly, the figure shows that attempting to make a standard linear regression fit may not be very meaningful. # In[1]: get_ip...
umpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression, Ridge, Lasso from sklearn.model_selection import train_test_split from sklearn.utils import resample from sklearn.metrics import mean_squared_error from IPython.display import display from pylab import plt,...
archifix/settings
sublime/Packages/backrefs/tools/unipropgen.py
Python
mit
44,164
0.001404
""" Generate a Unicode prop table for Python narrow and wide builds. Narrow builds will stop at `0xffff`. """ from __future__ import unicode_literals import sys import struct import unicodedata import codecs import os import re __version__ = '4.2.0' UNIVERSION = unicodedata.unidata_version UNIVERSION_INFO = tuple([i...
GROUP_ESCAPES: # Escape characters that are (or will be in the future) problematic c = "\\x%02x\\x%02x" % (0x5c, value) elif value <= 0xFF: c = "\\x%02x" % value elif value <= 0xFFFF: c = "\\u%04x" % value else: c = "\\U%08x" % value return c def format_name(tex...
) def binaryformat(value): """Convert a binary value.""" if value in GROUP_ESCAPES: # Escape characters that are (or will be in the future) problematic c = "\\x%02x\\x%02x" % (0x5c, value) else: c = "\\x%02x" % value return c def create_span(unirange, binary=False): """C...
wT-/SpelunkyWadUtility
restore_original.py
Python
unlicense
843
0.033215
#!/usr/bin/env python """ Created on Aug 12, 2013 @author: wT @version: 1.2 """ from __future__ import print_function import sys sys.dont_writ
e_bytecode = True # It's just clutter for this small scripts import shutil import traceback from unpack import get_wad_path, get_wix_path if __name__ == '__main__': try: input = raw_input # Python 2 <-> 3 fix except NameError: pass try: yesno = input(r"Overwrite both (potentially modified) .wad and .wix fil...
lower() if yesno == "y" or yesno == "yes": try: shutil.move(get_wad_path() + ".orig", get_wad_path()) shutil.move(get_wix_path() + ".orig", get_wix_path()) except: print("No .orig files to restore") else: print("Done") else: print("Not restoring") except SystemExit as e: print(e) exc...
bobbybabra/codeGuild
zombieHS.py
Python
bsd-2-clause
5,598
0.009646
import random class Character: def __init__(self): self.name = "" self.life = 20 self.health = random.choice(0, life) self.zombie_life = 10 self.zombie_health = random.choice(0, zombie_life) def attack(self, zombie): self.hit = self.health - self.zombie_health ...
flee': Player.flee, 'attack': Player.attack, } hero = Player() hero.name = raw_input("What is your character's name? ") print "(type help to get a list of actions)\n" print """When %s leaves homeroom, they a strange stench in the air m
aybe we are dissecting a frog in biology today...""" % hero.name while (p.health > 0): line = raw_input("> ") args = line.split() if len(args) > 0: commandFound = False for c in Commands.keys(): if args[0] == c[:len(args[0])]: Commands[c](p) ...
sgmap/openfisca-france
openfisca_france/scenarios.py
Python
agpl-3.0
2,063
0.00921
# -*- coding: utf-8 -*- import logging log = logging.getLogger(__name__) def init_single_entity(scenario, axes = None, enfants = None, famille = None, foyer_fiscal = None, menage = None, parent1 = None, parent2 = None, period = None): if enfants is None: enfants = [] assert parent1 is not None ...
famille_nth.setdefault('enfants', []).append(id) foyer_fiscal_nth.setdefault('personnes_a_charge', []).append(id) menage_nth.setdefault('enfants', []).append(id) count_so_far += len(group) familles["f{}".format(nth)] = famille_nth foyers_fiscaux["ff{}".for...
["m{}".format(nth)] = menage_nth test_data = { 'period': period, 'familles': familles, 'foyers_fiscaux': foyers_fiscaux, 'menages': menages, 'individus': individus } if axes: test_data['axes'] = axes scenario.init_from_dict(test_data) return scena...
deonwu/PyTEL
src/pytel/ast/_build_tables.py
Python
gpl-2.0
762
0.011811
#----------------------------------------------------------------- # pycparser: _build_tables.py # # A dummy for generating the lexing/parsing tables and and # compiling them into .pyc for faster execution in optimized mode. # Also generates AST code from th
e _c_ast.yaml configuration file. # # Copyright (C) 2008, Eli Bendersky # License: LGPL #----------------------------------------------------------------- # Generate c_ast.py # from _ast_gen import ASTCodeGenerator ast_gen = ASTCodeGenerator('_c_ast.yaml') ast_gen.generate(open
('c_ast.py', 'w')) import c_parser # Generates the tables # c_parser.CParser( lex_optimize=True, yacc_debug=False, yacc_optimize=True) # Load to compile into .pyc # import lextab import yacctab import c_ast
Trust-Code/trust-addons
trust_task_time_control/models/__init__.py
Python
agpl-3.0
1,625
0
# -*- encoding: utf-8 -*- ############################################################################### #
# # Copyright (C) 2015 Trustcode - www.trustcode.com.br # # Danimar Ribeiro <[email protected]> # # # # This program is free software: you can redistribute it...
# # it under the terms of the GNU Affero General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # ...
huyphan/pyyawhois
test/record/parser/test_response_whois_nic_af_status_registered.py
Python
mit
2,584
0.002322
# This file is autogenerated. Do not edit it manually. # If you want change the content of this file, edit # # spec/fixtures/responses/whois.nic.af/status_registered # # and regenerate the tests with the following script # # $ scripts/generate_tests.py # from nose.tools import * from dateutil.parser import parse ...
eq_(self.record.nameservers[1].__class__.__name__, 'Nameserver') eq_(self.record.nam
eservers[1].name, "ns2.google.com") eq_(self.record.nameservers[2].__class__.__name__, 'Nameserver') eq_(self.record.nameservers[2].name, "ns3.google.com") eq_(self.record.nameservers[3].__class__.__name__, 'Nameserver') eq_(self.record.nameservers[3].name, "ns4.google.com") def tes...
fbkarsdorp/mbmp
mbmp/datatypes.py
Python
gpl-3.0
2,861
0.003146
## Python implementation of MBMA (Van den Bosch & Daelemans 1999) ## Copyright (C) 2011 Folgert Karsdorp ## Author: Folgert Karsdorp <[email protected]> ## URL: <http://github.com/fbkarsdorp/mbmp> ## For licence information, see LICENCE.TXT class Morpheme(object): """ A data class representing a m...
def __repr__(self): return 'Morpheme(token=%s, lemma=%s, pos=%s)' % ( self.token, self.lemma, self.pos) def __str__(self): return self.pprint() def __eq__(self, other): if not isinstance(other, Morpheme): return False return (self.token == othe...
elf, mrepr='tokens-and-lemmas'): """ Return a string representation of the morpheme. Args: - mrepr: Choose a morpheme representation: - tokens = token representation - lemmas = lemma representation - tokens-and-lemmas =...
stackingfunctions/practicepython
src/02-even_odd.py
Python
mit
415
0.004819
number = int(input("Give me a number and I will tellyou if i
t is even or odd. Your number: ")) divisor = int(input("What divisor would you like to check? ")) if number % 2 == 0: print("%d is EVEN" % number) else: print("%d is ODD" % number) if number % 4 == 0: print("%d is evenly divisible by 4." % number) if number % divisor == 0: print("%d is evenly divisib...
% (number, divisor))
adaschevici/firebase-demo
python-back/api/firebase/firebase.py
Python
mit
1,373
0.00437
import pyrebase import random try: import constants config = { "apiKey": constants.API_KEY, "authDomain": constants.AUTH_DOMAIN, "databaseURL": constants.DB_URL, "projectId": constants.PROJECT_ID, "storageBucket": constants.STORAGE_BUCKET, "messagingSenderId": c...
user's idToken to the push method results = db.child("users").child(user_id).set(data, user['idToken']) def firebase_update_claps(user_id): global user if not user.get('idToken'): user = auth.sign_in_with_email_and_password(constants.USER_EMAIL, constants.USER_PASSWORD) db = firebase.database(...
d(user_id).get(user['idToken']).val()['claps'] db.child("users").child(user_id).update({"claps": claps + 1}, user['idToken'])
anhstudios/swganh
data/scripts/templates/object/tangible/furniture/all/shared_frn_all_throwpillow_med_s02.py
Python
mit
465
0.047312
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### P
LEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): re
sult = Tangible() result.template = "object/tangible/furniture/all/shared_frn_all_throwpillow_med_s02.iff" result.attribute_template_id = 6 result.stfName("frn_n","frn_throwpillow") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
hzlf/openbroadcast.ch
app/rating/api/views.py
Python
gpl-3.0
1,458
0.002058
# -*- coding: utf-8 -*- import logging from django.conf import settings from channels.layers import get_channel_layer from asgiref.sync import async_to_sync from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.permissions import IsAuthenticatedOrReadOnly fr...
te_votes, update_remote_vote API_BASE_URL = getattr(settings, 'API_BASE_URL', None) API_BASE_AUTH = getattr(settings, 'API_BASE_AUTH', None) log = logging.getLogger(__name__) channel_layer = get_channel_layer() @api_view(['GET', 'POST']) @authentication_classes((Session
Authentication,)) @permission_classes((IsAuthenticatedOrReadOnly,)) def vote_detail(request, obj_ct, obj_pk): if request.method == 'POST': value = request.data.get('value') user_remote_id = request.user.remote_id votes, status_code = update_remote_vote(obj_ct, obj_pk, value, user_remote_id)...
khillion/ToolDog
tooldog/analyse/code_collector.py
Python
mit
2,950
0.002712
#!/usr/bin/env python3 import logging import os import urllib.parse import urllib.request import tarfile from tooldog import TMP_DIR from .utils import * LOGGER = logging.getLogger(__name__) class CodeCollector(object): """ Class to download source code from a https://bio.tools entry """ ZIP_NAME ...
oin(TMP_DIR, self.TAR_NAME) write_to_file(zip_pa
th, data, 'wb') LOGGER.info('Making tar...') self._make_tar(zip_path, tar_path) return tar_path except: LOGGER.warn('Something went wrong with the following Github repository: {}'.format(zip_url)) def _get_from_source_code(self, url): """ Ge...
factorlibre/l10n-spain
l10n_es_partner/gen_src/__init__.py
Python
agpl-3.0
95
0
# License AG
PL-3.0 or
later (https://www.gnu.org/licenses/agpl). from . import gen_data_banks
ramusus/django-oauth-tokens
oauth_tokens/migrations/0006_auto__chg_field_accesstoken_access_token.py
Python
bsd-3-clause
4,058
0.007886
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'AccessToken.access_token' db.alter_column(u'oauth_tokens_accesstoken', 'access_token', se...
{ 'Meta': {'ordering': "('-granted',)", 'object_name': 'AccessToken'}, 'access_token': ('django.db.models.fields.CharFiel
d', [], {'max_length': '500'}), 'expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'granted': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key...
VioletRed/script.module.urlresolver
lib/urlresolver/plugins/vidbull.py
Python
gpl-2.0
2,788
0.003945
''' Vidbull urlresolver plugin Copyright (C) 2013 Vinnydude This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 o
f 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...
ww.gnu.org/licenses/>. ''' import re import urllib2 import urllib from t0mm0.common.net import Net from urlresolver.plugnplay.interfaces import UrlResolver from urlresolver.plugnplay.interfaces import PluginSettings from urlresolver.plugnplay import Plugin from urlresolver import common USER_AGENT = 'Mozilla/5.0 (Lin...
scottbarstow/iris-python
iris_sdk/models/maps/roles_list.py
Python
mit
119
0.016807
#!/usr/bin/env python from iris_sdk.mod
els.maps.base_map import BaseMap class RolesListMap(BaseMap):
role = None
rouzazari/fuzzyflask
app/main/datatools.py
Python
mit
388
0
from
fuzzywuzzy import process def dictionary_match(item, dictionary, allow_low_match=False, low_match_threshold=90): if item in dictionary: return item, 100 matched_item, score = process.extractOne(item, dictionary) if score < low_match_threshold and not allow_low_match: r...
ore
googleinterns/schemaorg-generator
protogenerator/tests/test_utils.py
Python
apache-2.0
9,030
0.001329
# Copyright 2020 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 # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, sof...
either express or implied. # See the License for the specific language governing permissions and # limitations unde
r the License. import utils.utils as utils import rdflib def test_to_snake_case(): """Test utils.to_snake_case function. Procedure: - Create input and expected output for the following cases. * Pascal Case. * Pascal Case with multiple upper case characters at the start. ...
pcmagic/stokes_flow
ecoli_in_pipe/ecoliInPipe_singletail.py
Python
mit
4,799
0.003334
# coding=utf-8 # 1. generate velocity and force nodes of sphere using MATLAB, # 2. for each force node, get b, solve surrounding velocity boundary condition (pipe and cover, named boundary velocity) using formula from Liron's paper, save .mat file # 3. read .mat file, for each boundary velocity, solve associated bounda...
' raise ValueError(err_msg) ecoli_comp = sf.ForceFreeComposite(center=ecoli_comp0.get_center(), name='ecoli_0') ecoli_comp.add_obj(ecoli_comp0.get_obj_list()[0], rel_U=ecoli_comp0.get_rel_U_list()[0]) ecoli_comp.add_obj(ecoli_comp0.get_obj_list()[1], rel_U=ecoli_comp0.get_rel_U_list(...
e', 1e-4) problem = sf.StokesletsInPipeforcefreeIterateProblem(**problem_kwargs) problem.set_prepare(forcepipe) problem.add_obj(ecoli_comp) if problem_kwargs['pickProblem']: problem.pickmyself(fileHandle, ifcheck=True) problem.set_iterate_comp(ecoli_comp) prob...
jasonzou/MyPapers
bibserver/search.py
Python
mit
19,340
0.012048
""" search.py """ from flask import Flask, request, redirect, abort, make_response from flask import render_template, flash import bibserver.dao from bibserver import auth import json, httplib from bibserver.config import config import bibserver.util as util import logging from logging.handlers import RotatingFileHand...
cord.get(res._hits[0]['_id']) found = 1 else: found = 2 if not found: abort(404) elif found == 1: collection = bibserver.dao.Collection.get_by_owner_coll(rec.data['owner'],rec.data['collection']) if request.method == 'DELETE': ...
ec: if not auth.collection.update(self.current_user, collection): abort(401) rec.delete() abort(404) else: abort(404) elif request.method == 'POST': if rec: ...
vd4mmind/MACS
MACS2/OptValidator.py
Python
bsd-3-clause
26,830
0.010175
# Time-stamp: <2015-05-19 13:42:30 Tao Liu> """Module Description Copyright (c) 2010,2011 Tao Liu <[email protected]> This code is free software; you can re
distribute it and/or modify it under the terms of the BSD License (see the file
COPYING included with the distribution). @status: experimental @version: $Revision$ @author: Tao Liu @contact: [email protected] """ # ------------------------------------ # python modules # ------------------------------------ import sys import os import re import logging from argparse import ArgumentError...
ftrautsch/testEvolution
resultprocessor/coveragemodels.py
Python
apache-2.0
1,211
0.002477
from mongoengine import Document, StringField, DateTimeField, ListField, DateTimeField, IntField, BooleanField, \ ObjectIdFi
eld, FloatField class Covelement(Document): instructionsCov = IntField() instructionsMis = IntField() branchesCo
v = IntField() branchesMis = IntField() lineCov = IntField() lineMis = IntField() complexityCov = IntField() complexityMis = IntField() methodCov = IntField() methodMis = IntField() class Covproject(Covelement): classCov = IntField() classMis = IntField() class Covpackage(Covelem...
lgarren/spack
var/spack/repos/builtin/packages/r-annotationdbi/package.py
Python
lgpl-2.1
2,016
0.000992
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-64...
lass RAnnotationdbi(RPackage): """Provides user interface and database connection code for annotation data packages using SQLite data storage.""" homepage = "https://www.bioconductor.org/packages/AnnotationDbi/" url = "https://git.bioconductor.org/packages/Annotati
onDbi" list_url = homepage version('1.38.2', git='https://git.bioconductor.org/packages/AnnotationDbi', commit='67d46facba8c15fa5f0eb47c4e39b53dbdc67c36') depends_on('[email protected]:3.4.9', when='@1.38.2') depends_on('r-biocgenerics', type=('build', 'run')) depends_on('r-biobase', type=('build', 'run')) ...
CityOfNewYork/NYCOpenRecords
app/upload/constants/upload_status.py
Python
apache-2.0
80
0
PROCESSING = "processing" SCANNING = "scanning"
READY = "ready" ERROR = "e
rror"
mlperf/training_results_v0.7
Google/benchmarks/transformer/implementations/transformer-research-TF-tpu-v4-16/lingvo/tasks/mt/model.py
Python
apache-2.0
16,381
0.006105
# Lint as: python2, python3 # 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 # ...
put_batch, encoder_outputs, decoder_outs) def _ProcessBeamSearchDecodeOut(self, input_batch, encoder_outputs, decoder_outs): self.r1_shape = decoder_outs[0] self.r2_shape = decoder_outs[1] self.r3_shape = decoder_outs[2] ...
hyps = decoder_outs[3] prev_hyps = decoder_outs[4] done_hyps = decoder_outs[5] scores = decoder_outs[6] atten_probs = decoder_outs[7] eos_scores = decoder_outs[8] eos_atten_probs = decoder_outs[9] source_seq_lengths = decoder_outs[10] tlen = tf.cast( tf.round(tf.reduce_sum...
peterhinch/micropython-async
v3/as_drivers/as_GPS/as_rwGPS.py
Python
mit
4,383
0.003194
# as_rwGPS.py Asynchronous device driver for GPS devices using a UART. # Supports a limited subset of the PMTK command packets employed by the # widely used MTK3329/MTK3339 chip. # Sentence parsing based on MicropyGPS by Michael Calvin McCoy # https://github.com/inmcm/micropyGPS # Copyright (c) 2018 Peter Hinch # Rele...
sentence = bytearray('$PMTK251,{:d}*00\r\n'.format(value)) await self._send(sentence) async def update_interval(self, ms=1000): if ms < 100 or ms > 10000: raise ValueError('Invalid update interval {:d}ms.'.format(ms)) sentence = bytearray('$PMTK220,{:d}*00\r\n'.format(...
e for timing driver async def enable(self, *, gll=0, rmc=1, vtg=1, gga=1, gsa=1, gsv=5, chan=0): fstr = '$PMTK314,{:d},{:d},{:d},{:d},{:d},{:d},0,0,0,0,0,0,0,0,0,0,0,0,{:d}*00\r\n' sentence = bytearray(fstr.format(gll, rmc, vtg, gga, gsa, gsv, chan)) await self._send(sentence) async de...
chbrandt/zyxw
eada/io/ascii.py
Python
gpl-2.0
9,744
0.018986
"""Module to read/write ascii catalog files (CSV and DS9)""" ##@package catalogs ##@file ascii_data """ The following functions are meant to help in reading and writing text CSV catalogs as well as DS9 region files. Main structure used is dictionaries do deal with catalog data in a proper way. """ import sys import ...
=%s\n" % (x[i],y[i],size[i],color[i])); elif marker[i] == 'box': output.write("box(%s,%s,%s,%s,0) # color=%s\n" % (x[i],y[i],size[i],size[i],color[i])); output.close(); return # ---
def read_ds9cat(regionfile): """ Function to read ds9 region file Only regions marked with a 'circle' or 'box' are read. 'color' used for region marks (circle/box) are given as output together with 'x','y','dx','dy' as list in a dictionary. The key 'image' in the output (<dict>) gives the file...
joaander/hoomd-blue
hoomd/jit/__init__.py
Python
bsd-3-clause
703
0.007112
# Copyright (c) 2009-2021 The Regents of the University of Michigan # This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. """ JIT The JIT module provides *experimental* support to to JIT (just in time) compile C++ code and call it during the simulation. Compiled C++ code will execute...
s **unstable**. When upgrading from version 2.x to 2.y (y > x), existing job scripts may need to be updated. **Maintainer:** Joshua A. Anderson, University of Michigan .. versionadded:: 2.3 """
from hoomd.hpmc import _hpmc from hoomd.jit import patch from hoomd.jit import external
valkyriesavage/makers-marks
openscad.py
Python
mit
20,842
0.016937
import os, subprocess from component import Component from config import OPENSCAD, OPENSCAD_OLD, CHECK_INTERSECT_SCRIPT, SUB_COMPONENT_SCRIPT, \ PART_SCRIPT, BOSS_CHECK_COMPS_SCRIPT, BOSS_PUT_SCRIPT, SHELL_SCRIPT, DEFORM_SHELL_SCRIPT, \ MINKOWSKI_TOP, MINKOWSKI_BOT, BUTTON_CAP_SCRIPT, SCRATCH ''' We will give ...
% { 'shelled_bb':placeBoundingBoxSCAD(components, geom='bbshell'), 'solid_obj_body':full_body } #subtracts solid body from hollow bounding box if script == CHECK_INTERSECT_SCRIPT and object_body == '': text += ''' intersection() { %(comp_0)s %(comp_1)s } ''' % { 'comp_0':placeCompOpenSCAD(com...
text += ''' intersection() { %(comp_0)s import("%(obj)s"); } ''' % { 'comp_0':placeCompOpenSCAD(components[0], geom='clearance'), 'obj':object_body, } if script == SUB_COMPONENT_SCRIPT: comps_sub = '' comps_add = '' for component in components: if component['type'] == Component.par...
MatthewShao/mitmproxy
pathod/language/base.py
Python
mit
13,851
0.000433
import operator import os import abc import functools import pyparsing as pp from mitmproxy.utils import strutils from mitmproxy.utils import human import typing # noqa from . import generators from . import exceptions class Settings: def __init__( self, is_client=False, staticdir=None, ...
e = v_naked_literal.copy() return e.setParseAction(lambda x: cls(*x)) def spec(self): return strutils.bytes_to_escaped_str(self.val, escape_single_quotes=True) class TokValueGenerate(Token):
def __init__(self, usize, unit, datatype): if not unit: unit = "b" self.usize, self.unit, self.datatype = usize, unit, datatype def bytes(self): return self.usize * human.SIZE_UNITS[self.unit] def get_generator(self, settings_): return generators.RandomGenerator(sel...
IKeiran/FPT-Sinyakov
test/test_contact_compare.py
Python
apache-2.0
993
0.005035
__author__ = 'Keiran' from model.contact
import Contact im
port pytest def test_contact_compare(app, orm): with pytest.allure.step('Given a sorted contact list from DB'): contacts_from_db = orm.get_contact_list() sorted_contacts_from_db = list(sorted(contacts_from_db, key=Contact.id_or_max)) with pytest.allure.step('Given a sorted contact list from ho...
ferventdesert/Hawk-Projects
安居客/安居客.py
Python
apache-2.0
2,402
0.081843
# coding=utf-8 #下面的代码是接口函数,无关 def get(ar,index): l=len(ar); if index<0: return ar[l+index]; else: return ar[index]; def find(ar,filt
er): for r in ar: if filter(r): return r; return None; def execute(ar,filter,action): for r in ar: if filter(r): action(r); unabled=[户型图存储方案,户型图存储,安居客户型列表,安居客评价,安居客楼盘详情,相册存储方案,安居客相册]; for e in unabled: e.etls[0].Enabled=False 页数范围控制=find(安居客核心流程.etls,lambda x:x.TypeName=='数量范围选择'
) #下面是可能需要修改的配置: ################################################### 重试次数='3' ##要跳过的页数,注意是翻页的数量 页数范围控制.Skip=0 ##要获取的页数,可以设置的非常大,这样就一直会到末尾 页数范围控制.Take=20000000 debug=False #是否要进行增量抓取? #注意:系统会在数据库里查询是否已有数据,因此可能会造成在调试时,没有任何数据显示(所有的数据都在数据库里了) #如果无所谓重复,或为了调试观察,则 not_repeat=True def work2(x): x.Enabled=not_repeat...
MKTCloud/MKTCloud
openstack_dashboard/dashboards/support/support/views.py
Python
apache-2.0
497
0.006036
import log
ging from django.utils.translation import ugettext_lazy as _ from horizon import tables from openstack_dashboard.dashboards.support.support import tables as project_tables from horizon import views class IndexView(tables.DataTableView): # A very simple class-based view... table_class = project_tables.SupportT...
resource = [] return resource
jamesmarva/myria
jsonQueries/case_conversion/generate_convert_zsh.py
Python
bsd-3-clause
761
0.00657
#!/usr/bin/env python def fix(word): ret = "" flag = False for c in word: if c == '_': flag = True continue if flag: c = c.upper() flag = False
ret += c return ret words = [line.strip() for line in open('keywords.txt', 'r') if len(line.strip())] fixed = [fix(word) for word in words] sed_dblqt_expr = [r"s#\"{}\"#\"{}\"#g".format(w,f) for w, f in zip(words, fixed)] sed_sglqt_expr = [r"s#'{}'#'{}'#g".format(w,f) for w, f in zip(words, fixed)] front = ...
lqt_expr) end = """\" $file echo $file done""" print "%s%s%s" % (front, middle, end)
tremblerz/breach-detection-system
dashboard/bds/admin.py
Python
gpl-3.0
206
0.004854
from
django.contrib import admin from bds.models import Packet from bds.models import CT,admins # Register your mode
ls here. admin.site.register(Packet) admin.site.register(CT) admin.site.register(admins)
badlogicmanpreet/nupic
tests/unit/nupic/encoders/random_distributed_scalar_test.py
Python
agpl-3.0
19,742
0.004306
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
stributedScalarEncoder(name="encoder", resolution=1.0, w=23, n=500, offset=0.0) e0 = encoder.encode(-0.1) self.a
ssertEqual(e0.sum(), 23, "Number of on bits is incorrect") self.assertEqual(e0.size, 500, "Width of the vector is incorrect") self.assertEqual(encoder.getBucketIndices(0.0)[0], encoder._maxBuckets / 2, "Offset doesn't correspond to middle bucket") self.assertEqual(len(encoder.bucketMap)...
rackerlabs/django-DefectDojo
dojo/management/commands/system_settings.py
Python
bsd-3-clause
1,040
0
from django.core.management.base import BaseCommand from dojo.models import Sys
tem_Settings class Command(BaseCommand): help = 'Updates product grade calculation' def handle(self, *args, **options): code = """def grade_product(crit, high, med, low): health=100 if crit > 0: health = 40 health = health - ((crit - 1) * 5) ...
if health == 100: health = 60 health = health - ((high - 1) * 3) if med > 0: if health == 100: health = 80 health = health - ((med - 1) * 2) if low > 0: if health == 100: ...
gg0/libming-debian
test/Text/test02.py
Python
lgpl-2.1
451
0.035477
#!/usr/bin/python from ming import * import sys mediadir = sys.argv[1]+'/../Media' m
= SWFMovie(); font = SWFFont(mediadir + "/font01.fdb") text = SWFText(2); text.setFont(font); text.setHeight(20); text.setColor(0x00, 0x00, 0x00, 0xff); text.addString("abc"); font2 =
SWFFont(mediadir + "/test.ttf") text.setFont(font2); text.setHeight(40); text.setColor(0xff, 0x00, 0x00, 0xff); text.addString("def"); m.add(text); m.save("test02.swf");
coxmediagroup/googleads-python-lib
examples/dfp/v201411/label_service/create_labels.py
Python
apache-2.0
1,668
0.008393
#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
f main(client): # Initialize appropriate service. label_service = client.GetServic
e('LabelService', version='v201411') # Create label objects. labels = [] for _ in xrange(5): label = { 'name': 'Label #%s' % uuid.uuid4(), 'isActive': 'true', 'types': ['COMPETITIVE_EXCLUSION'] } labels.append(label) # Add Labels. labels = label_service.createLabels(label...
agconti/KaggleAux
kaggleaux/__init__.py
Python
apache-2.0
188
0
import dataframe import modeling import ploting import s
coring import utils __all__ = ['dataframe', 'modeling', 'ploting',
'scoring', 'utils']
hamsterbacke23/wagtail
wagtail/contrib/modeladmin/views.py
Python
bsd-3-clause
35,740
0.000084
from __future__ import absolute_import, unicode_literals import operator import sys from collections import OrderedDict from functools import reduce from django import forms from django.contrib.admin import FieldListFilter, widgets from django.contrib.admin.exceptions import DisallowedModelAdminLookup from django.con...
eryset(request or self.request) class ModelFormView(WMABaseView, FormView): def get_edit_handler_class(self): if hasattr(self.model, 'edit_handler'): edit_handler = self.model.edit_handler else: panels = extract_panel_definitions_from_model_class(self.model)
edit_handler = ObjectList(panels) return edit_handler.bind_to_model(self.model) def get_form_class(self): return self.get_edit_handler_class().get_form_class(self.model) def get_success_url(self): return self.index_url def get_instance(self): return getattr(self,...
Castronova/EMIT
api_old/ODM2/LabAnalyses/services/createLabAnalyses.py
Python
gpl-2.0
223
0.022422
__au
thor__ = 'Stephanie' import sys import os from ... import serv
iceBase from ..model import * # from ODMconnection import SessionFactory class createLabAnalyses (serviceBase): def test(self): return None
dchucks/coursera-python-course
capstone/accidents-analysis/AccidentsJsonImporter.py
Python
gpl-3.0
2,735
0.004022
import json import sqlite3 import os from os import listdir conn = sqlite3.connect('accidentsdb.sqlite') cur = conn.cursor() # Do some setup cur.executescript(''' DRO
P TABLE IF EXISTS AccidentsData; CREATE TABLE AccidentsData ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, State TEXT, Year INTEGER, Accidents INTEGER, Education TEXT ); ''') filedir = os.path.join(os.path.dirname(__file__), "dataset//accidents-vs-e
ducation//2009-2015") filelist = listdir(filedir) print("Found following files in specified folder ", filedir, ":", filelist) totrows = 0 for fname in filelist: print("Now inserting data from:", fname) if len(fname) > 1: education = fname.split(".")[0] # print("education", education) ...
Seanmcn/poker
tests/test_hand.py
Python
mit
5,035
0.000993
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import, division, print_function import pickle import pytest from poker import Hand, Combo, Rank def test_first_and_second_are_instances_of_Rank(): assert isinstance(Hand('22').first, Rank) assert Hand('22').first == Rank('2') asse...
, Combo('7s6d'), Combo('7s6h') ) def test_s
uited_hand_to_combos(): assert Hand('76s').to_combos() == (Combo('7c6c'), Combo('7d6d'), Combo('7h6h'), Combo('7s6s')) def test_pickable(): assert pickle.loads(pickle.dumps(Hand('Ako'))) == Hand('AKo')
wsqhubapp/learning_log
learning_logs/migrations/0002_entry.py
Python
apache-2.0
869
0.002301
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-06-06 16:11 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('learning_logs', '0001_initial'), ] operations = [ ...
_name='ID')), ('text', models.TextField()), ('date_added', models.DateTimeField(auto_now_add=True)), ('topic', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='learning_logs.Topic')), ], options={
'verbose_name_plural': 'entries', }, ), ]
Stargrazer82301/CAAPR
CAAPR/CAAPR_AstroMagic/PTS/pts/core/tools/special.py
Python
mit
24,211
0.003552
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** ##...
compatibility from __future__ import absolute_import, division, print_function # Import standard modules import numpy as np # Import the relevant PTS classes and modules from ...magic.core.frame import Frame from ..basics.remote import Remote, connected_remotes from . import time from . import filesystem as fs from ....
... :param image: :param kernel: :param host_id: """ # Check whether we are already connected to the specified remote host if host_id in connected_remotes and connected_remotes[host_id] is not None: remote = connected_remotes[host_id] else: # Debugging log.debug("L...
vensder/itmo_python
my_circle_class.py
Python
gpl-3.0
458
0.050218
#my_circle_class.py class Circle: def __init__(self, x, y, r): self.x = x self.y = y self.r = r def are
a(self): return 3.14 * self.get_radius() * self.get_radius() @property def r(self): return self._r @r.setter def r(self, radius): if r < 0: raise ValueError('Radius sho
uld be positive') self._r = r circle = Circle(0, 0, 1) print(circle.area()) circle.set_radius(3) print(circle.area()) circle.r = -10 print(circle.r)
kevinlee12/oppia
core/tests/build_sources/extensions/base.py
Python
apache-2.0
10,783
0.000185
# coding: utf-8 # # Copyright 2014 The Oppia 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 requi...
should be displayed -- either within the # conversation ('inline'), or as a separate object ('supplemental'). In the # latter case, the interaction instance is reused if two adjacent states # have the same interaction id. display_mode = '' # Whether this interaction should be consid
ered terminal, i.e. it ends # the exploration. Defaults to False. is_terminal = False # Whether the interaction has only one possible answer. is_linear = False # Whether this interaction supports machine learning classification. # TODO(chiangs): remove once classifier_services is generalized. ...
suyashphadtare/vestasi-erp-1
erpnext/erpnext/accounts/report/gross_profit/gross_profit.py
Python
agpl-3.0
4,692
0.032396
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import flt from erpnext.stock.utils import get_buying_amount, get_sales_bom_buying_amount def execute(filters=None):...
" order by item_code desc, warehouse desc, posting_date desc, posting_time desc, name desc" res = frappe.db.sql(query, filters, as_dict=True) out = {} for r in res: if (r.item_code, r.warehouse) not in out: out[(r.item_code, r.warehouse)] = [] out[(r.item_code, r.warehouse)].append(r) return out de...
m `tabPacked Item` where docstatus=1""", as_dict=True): item_sales_bom.setdefault(d.parenttype, frappe._dict()).setdefault(d.parent, frappe._dict()).setdefault(d.parent_item, []).append(d) return item_sales_bom def get_source_data(filters): conditions = "" if filters.get("company"): conditions += " and com...
siddharth96/windows-tweaker
WindowsTweaker/Search/stemmer.py
Python
gpl-3.0
3,563
0.001403
#!/usr/bin/env python """ Script Usage: Write to a file with indentation: python %(scriptName)s --input <input-file> --output englishTermAndUiElementMap.json --indent=4 Write to a file without any indentation: python %(scriptName)s --input <input-file> --output englishTermAndUiElementMap.json Write to stdout with in...
ython %(scriptName)s --input <input-file-path> """ import argparse import json import Stemmer from collections import defaultdict from stemming import porter2 EN = "en" DE = "de" RU = "ru" FR = "fr" UI_ELEMENT_NAME = 0 MAIN_NAV_ITEM
= 1 SUB_TAB_CONTROL = 2 SUB_TAB = 3 def stemmer_meth(lang): if lang == EN: print 'Returning eng stem' return porter2.stem if lang == DE: print 'Returning german stem' return Stemmer.Stemmer('german').stemWord if lang == RU: print 'Returning russian stem' re...
tiankangkan/paper_plane
king_spider/music_web_spider/__init__.py
Python
gpl-3.0
269
0
import os import sys def current_file_directory(): return os.p
ath.dirname(os.path.realpath(__file__)) BASE_DIR = os.path.dirname(os.path.dirname(current_file_directory())) sys.path.append(BASE_DIR) os.envi
ron['DJANGO_SETTINGS_MODULE'] = 'paper_plane.settings'
pyphrb/myweb
app/plugin/nmap/libnmap/diff.py
Python
apache-2.0
2,896
0
# -*- coding: utf-8 -*- class DictDiffer(object): """ Calculate the difference between two dictionaries as: (1) items added (2) items removed (3) keys same in both but changed values (4) keys same in both and unchanged values """ def __init__(self, current_dict, pas...
the get_dict() method of the objects you which to compare (i.e: libnmap.objects.NmapHost, NmapService,...). """ def __init__(self, nmap_obj1, nmap_obj2): """ Constructor of NmapDiff: - Checks if the two objects are of the same class - Checks if the objects ar...
_ or nmap_obj1.id != nmap_obj2.id): raise NmapDiffException("Comparing objects with non-matching id") self.object1 = nmap_obj1.get_dict() self.object2 = nmap_obj2.get_dict() DictDiffer.__init__(self, self.object1, self.object2) def __repr__(self): return ("a...
benfinke/ns_python
nssrc/com/citrix/netscaler/nitro/resource/config/lb/lbmonbindings.py
Python
apache-2.0
6,759
0.035804
# # Copyright (c) 2008-2015 Citrix 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 l...
rt options from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception from nssrc.com.citrix.netscaler.nitro.util.nitro_
util import nitro_util class lbmonbindings(base_resource) : """ Configuration for monitro bindings resource. """ def __init__(self) : self._monitorname = "" self._type = "" self._state = "" self.___count = 0 @property def monitorname(self) : ur"""The name of the monitor.<br/>Minimum length = 1. """ ...
SickGear/SickGear
lib/hachoir_py3/parser/image/jpeg.py
Python
gpl-3.0
26,067
0.001113
""" JPEG picture parser. Information: - APP14 documents http://partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf http://java.sun.com/j2se/1.5.0/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html#color - APP12: http://search.cpan.org/~exiftool/Image-ExifTool/lib/Image/ExifTool/TagNames....
, 355, 338, 326, 318, 311, 305, 300, 297, 293, 291, 288, 286, 284, 283, 281, 280, 279, 278, 277, 273, 262, 251, 243, 233, 225, 218, 211, 205, 198, 193, 186, 181, 177, 172, 168, 164, 158, 156, 152, 148, 145, 142, 139, 136, 133, 131, 129, 126, 123, 120, 118, 115, 113, 110, 107, 105, 102, 100, 97, ...
76, 74, 70, 68, 66, 63, 61, 57, 55, 52, 50, 48, 44, 42, 39, 37, 34, 31, 29, 26, 24, 21, 18, 16, 13, 11, 8, 6, 3, 2, 0) QUALITY_SUM_GRAY = ( 16320, 16315, 15946, 15277, 14655, 14073, 13623, 13230, 12859, 12560, 12240, 11861, 11456, 11081, 10714, 10360, 10027, 9679, 9368, 9056, 8680, 8331, 79...
Orangestar12/cacobot
main.py
Python
gpl-3.0
6,389
0.006261
# per-module import for actioninja # standard imports import sys # for tracebaks in on_error. import json # to load the config file. import traceback # also used to print tracebacks. I'm a lazy ass. import asyncio # because we're using the async branch of discord.py. from random import choice # for choosing game ids ...
hannel.name ) ) if sys.exc_info()[0].__name
__ == 'Forbidden': await client.send_message( args[1].channel, 'You told me to do something that requires permissions I currently do not have. Ask an administrator to give me a proper role or something!') elif sys.exc_info()[0].__name__...
davelab6/pyfontaine
fontaine/charsets/noto_glyphs/notosanscuneiform_regular.py
Python
gpl-3.0
42,569
0.023186
# -*- coding: utf-8 -*- class Charset(object): common_name = 'NotoSansCuneiform-Regular' native_name = '' def glyphs(self): glyphs = [] glyphs.append(0x0173) #glyph00371 glyphs.append(0x030A) #glyph00778 glyphs.append(0x030B) #glyph00779 glyphs.append(0x02EB) #...
glyphs.append(0x032C) #glyph00812 glyphs.append(0x032B) #glyph00811 glyphs.append(0x032A) #glyph00810 glyphs.append(0x0331) #glyph00817 glyphs.append(0x0330) #glyph00816 glyphs.append(0x032F) #glyph00815 glyphs.append(0x032E) #glyph00814 glyphs.append...
C) #glyph00956 glyphs.append(0x03BD) #glyph00957 glyphs.append(0x03BA) #glyph00954 glyphs.append(0x021C) #glyph00540 glyphs.append(0x02BF) #glyph00703 glyphs.append(0x037C) #glyph00892 glyphs.append(0x0206) #glyph00518 glyphs.append(0x0207) #glyph00519 ...
maxamillion/atomic-reactor
tests/plugins/test_tag_from_config.py
Python
bsd-3-clause
5,924
0.000169
""" Copyright (c) 2016 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import unicode_literals from flexmock import flexmock import pytest import os.path from atomic_reactor.build import BuildRe...
s not None: input_tags = { 'unique': unique_tags, 'primary': primary_tags } else: input_tags = None runner = PostBuildPluginsRunner( docker_tasker, workflow, [{'name': TagFromConfigPlugin.key, 'args': {'tag_suffixes': input_tags}}...
results = runner.run() plugin_result = results[TagFromConfigPlugin.key] assert plugin_result == expected else: with pytest.raises(PluginFailedException): runner.run()
rainslytherin/ansible
lib/ansible/inventory/script.py
Python
gpl-3.0
9,853
0.008769
# -*- coding: utf-8 -*- # (c) 2012-2014, Michael DeHaan <[email protected]> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, ...
e using external inventory scripts. 当inventory文件为可执行的脚本时的处理逻辑。 ''' def __init__(self, filename=C.DEFAULT_HOST_LIST):
# Support inventory scripts that are not prefixed with some # path information but happen to be in the current working # directory when '.' is not in PATH. self.filename = os.path.abspath(filename) # 获取文件的绝对路径 cmd = [ self.filename, "--list" ] # 可执行的inventory脚本需要支持--list参数 tr...
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/third_party/pycoverage/setup.py
Python
mit
6,151
0.007804
# setup.py for coverage.py """Code coverage measurement for Python Coverage.py measures code coverage, typically during test execution. It uses the code analysis tools and tracing hooks provided in the Python standard library to determine which lines are executable, and which have been executed. Coverage.py runs on ...
hor_email = '[email protected]', description = doclines[0
], long_description = '\n'.join(doclines[2:]), keywords = 'code coverage testing', license = 'BSD', classifiers = classifier_list, url = __url__, ) # A replacement for the build_ext command which raises a single exception # if the build fails, so we can fallback nicely. ext_errors = ( erro...
ram8647/gcb-mobilecsp
modules/help_urls/topics.py
Python
apache-2.0
6,586
0.000607
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
ata_removal:removal_policy', '/create-a-course/course-settings.html' '#removal-policy'), ('help:documentation', '/index.html'), ('help:forum', _LegacyUrl( 'https://groups.google.com/for
um/?fromgroups#!categories/' 'course-builder-forum/general-troubleshooting')), ('help:videos', _LegacyUrl( 'https://www.youtube.com/playlist?list=PLFB_aGY5EfxeltJfJZwkjqDLAW' 'dMfSpES')), ('labels:tracks', '/create-a-course/organize-elements/tracks.html'), ('math:math:input_type...
shaunduncan/helga-oneliner
helga_oneliner.py
Python
mit
8,137
0.002116
# -*- coding: utf8 -*- import random import re from helga.plugins import match def imgur(image): """ Returns an imgur link with a given hash """ return 'http://i.imgur.com/{0}.gif'.format(image) RESPONSES = { # Direct text responses r'(gross|disgusting|eww)': (imgur('XEEI0Rn'),), # Dumb an...
), # Shocked cat is shocked imgur('wdA2Z'), # Monsters Inc watching Boo in compactor imgur('nj3yp'), # Spock is shocked i
mgur('AGnOQ'), # PeeWee is shocked imgur('wkY1FUI'), # Shocked looks around imgur('AXuUYIj')), # Simpsons jaw drop r'(bloody mary|vodka)': imgur('W9SS4iJ'), # Archer: Bloody Mary, blessed are you among cocktails r'popcorn': (imgur('00IJgSZ'), # Thriller...
SydneyUniLibrary/auto-holds
sierra/migrations/0001_initial.py
Python
gpl-3.0
1,534
0.000652
# Copyright 2016 Susan Bennett, David Mitchell, Jim Nicholls # # This file is part of AutoHolds. # # A
utoHolds is free software: you can redistribute it and/or mo
dify # 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. # # AutoHolds is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHA...
Ultimaker/Cura
plugins/VersionUpgrade/VersionUpgrade40to41/__init__.py
Python
lgpl-3.0
2,370
0.004641
# Copyright (c) 2018 Ultimaker B.V. # Cura is released under the terms of the LGPLv3 or higher. from typing import Any, Dict, TYPE_CHECKING from . import VersionUpgrade40to41 if TYPE_CHECKING: from UM.Application import Application upgrade = VersionUpgrade40to41.VersionUpgrade40to41() def getMetaData() -> Dict...
ty", 4000006): ("quality", 4000007, upgrade.upgradeInstanceContainer), ("user", 4000006): ("user", 4000007, upgrade.upgradeInstanceContainer), }, "sources": { "preferences": { "get_version": upgrade.getCfgVersion, ...
CfgVersion, "location": {"./machine_instances"} }, "extruder_train": { "get_version": upgrade.getCfgVersion, "location": {"./extruders"} }, "definition_changes": { "get_version": upgrade.getCfgVersion, ...
theKono/mobile-push
setup.py
Python
apache-2.0
1,163
0
#!/usr/bin/env python # standard library imports from os.path import exists # third party related imports from setuptools import setup, find_packages # local library imports from mobile_push import __version__ def read_from_file(filename): if exists(filename): with open(filename) as f: ret...
author='Yu Liang', author_email='[email protected]', # If you had mobile_push.tests, you would also include that in this list packages=find_packages(), # Any executable scripts, typically in 'bin'. E.g 'bin/do-something.py' scripts=[], # REQUIRED: Your project's URL url='https://gith...
com/theKono/mobile-push', # Put your license here. See LICENSE.txt for more information license=read_from_file('LICENSE'), # Put a nice one-liner description here description='A mobile-push microservice (APNS, GCM)', long_description=read_from_file('README.md'), # Any requirements here, e.g. "Dj...
jakobzhao/wbcrawler3
sentiment_by_tencent.py
Python
mit
378
0
# !/usr/bin/pytho
n # -*- coding: utf-8 -*- # # Created on Nov 19, 2015 # @author: Bo Zhao # @email: [email protected] # @website: http://yenching.org # @organization: Harvard Kennedy School import sys from wbcrawler.sentiment import tencent_sentiment reload(sys) sys.setdefaultencoding('utf-8') tencent_sentimen...
calhost', 27017)
okuta/chainer
tests/chainer_tests/training_tests/triggers_tests/test_once_trigger.py
Python
mit
6,615
0
from __future__ import division import numpy as np import random import tempfile import unittest from chainer import serializers from chainer import testing from chainer.testing import condition from chainer import training @testing.parameterize( # basic { 'iter_per_epoch': 5, 'call_on_resume': Fals...
stop_trigger=None, iter_per_epoch=self.iter_per_epoch) with tempfile.NamedTemporaryFile(delete=False) as f: trigger = trainin
g.triggers.OnceTrigger(self.call_on_resume) for expected, finished in zip(self.resumed_expected[:self.resume], self.resumed_finished[:self.resume]): trainer.updater.update() self.assertEqual(trigger.finished, finished) ...
ldm5180/hammerhead
data-manager/client/bdmplot2/bdmplot2_callback.py
Python
lgpl-2.1
7,139
0.013727
# Copyright (c) 2008-2010, Regents of the University of Colorado. # This work was supported by NASA contracts NNJ05HE10G, NNC06CB40C, and # NNC07CB47C. # This library is free software. You can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Softwa...
et_node_get_hab(node); value_str = bionet_value_to_str(value); #"%s.%s.%s:%s = %s %s %s @ %s" #print(bionet_resource_get_name(resource) + " = " + bionet_resource_data_type_to_string(bionet_resource_get_data_type(resource)) + " " + bionet_resource_flavor_to_string(bionet_resource_get_flavor(resource...
ionet_resource_get_name(resource) dp = (timeval_to_int(bionet_datapoint_get_timestamp(datapoint)), value_str) for session_id, session in sessions.iteritems(): found = False for r in session['resource']: if (bionet_resource_name_matches(resource_name, r)): for name in ...
facebookexperimental/eden
eden/scm/edenscm/mercurial/hgweb/request.py
Python
gpl-2.0
5,622
0.000534
# Portions Copyright (c) Meta Platforms, Inc. and affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. # hgweb/request.py - An http request from either CGI or the standalone server. # # Copyright 21 May 2005 - (c) 2005 Jake Edge <[email protected]...
te(self, thing): if thing: try: self.server_write(thing) except socket.error as inst: if inst.errno != errno.ECONNRESET: raise def writelines(self, lines): for line in lines: self.write(line) def flush(self...
atibility with old CGI scripts. A plain hgweb() or hgwebdir() can and should now be used as a WSGI application.""" application = app_maker() def run_wsgi(env, respond): return application(env, respond) return run_wsgi
pidydx/grr
grr/lib/email_alerts.py
Python
apache-2.0
5,328
0.006381
#!/usr/bin/env python """A simple wrapper to send email alerts.""" from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import logging import re import smtplib import socket from grr.lib import config_lib from grr.lib im...
lf, data): p = re.compile(r"<.*?>") return p.sub("", data) def AddEmailDomain(self, address): suffix = config_lib.CONFIG["Logging.domain"] if isinstance(address, rdf_standard.DomainEmailAddress): address = str(address) if suffix and "@" not in address: return address + "@%s" % suffix ...
"Splits a string of comma-separated emails, appending default domain.""" result = [] # Process email addresses, and build up a list. if isinstance(address_list, rdf_standard.DomainEmailAddress): address_list = [str(address_list)] elif isinstance(address_list, basestring): address_list = [add...
cschenck/blender_sim
fluid_sim_deps/blender-2.69/2.69/scripts/addons/add_mesh_BoltFactory/presets/M5.py
Python
gpl-3.0
795
0.003774
props.bf_Shank_Dia = 5.0 #props.bf_Pitch = 0.8 # Coarse props.bf_Pitch = 0.5 # Fine props.bf_Crest_Percent = 10 props.bf_Root_Percent = 10 props.bf_Major_Dia = 5.0 props.bf_Minor_Dia = props.bf_Major_Dia - (1.082532 * pro
ps.bf_Pitch) props.bf_Hex_Head_Flat_Distance = 8.0 props.bf_Hex_Head_Height = 3.5 props.bf_Cap_Head_Dia = 8.5 props.bf_Cap_Head_Height = 5.0 props.bf_CounterSink_Head_Dia = 10.4 props.bf_Allen_Bit_Flat_Distance = 4.0 props.bf_Allen_Bit_Depth = 2.5 props.bf_Pan_Head_Dia = 9.5 props.bf_Dome_Head_Dia = 9.5 props.b
f_Philips_Bit_Dia = props.bf_Pan_Head_Dia * (1.82 / 5.6) #props.bf_Phillips_Bit_Depth = Get_Phillips_Bit_Height(props.bf_Philips_Bit_Dia) props.bf_Hex_Nut_Height = 4.0 props.bf_Hex_Nut_Flat_Distance = 8.0 props.bf_Thread_Length = 10 props.bf_Shank_Length = 0.0