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
matthiask/django-chet
chet/south_migrations/0001_initial.py
Python
bsd-3-clause
4,095
0.008547
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Album' db.create_table(u'chet_album', ( (u'id...
('title', self.gf('django.db.models.fields.CharField')(max_length=200, blank=True)), ('is_dark', self.gf(
'django.db.models.fields.BooleanField')(default=False)), )) db.send_create_signal(u'chet', ['Photo']) def backwards(self, orm): # Deleting model 'Album' db.delete_table(u'chet_album') # Deleting model 'Photo' db.delete_table(u'chet_photo') models = { ...
Xperia-Nicki/android_platform_sony_nicki
external/webkit/LayoutTests/http/tests/websocket/tests/hybi/close-on-unload_wsh.py
Python
apache-2.0
2,370
0
# Copyright 2009, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from mod_pywebsocket import msgutil # we don't use set() here, because python on mac tiger doesn't support it. connections = {} def web_socket_do_extra_handshake(r
equest): pass # Always accept. def web_socket_transfer_data(request): global connections connections[request] = True socketName = None try: socketName = msgutil.receive_message(request) # notify to client that socketName is received by server. msgutil.send_message(request,...
zhangjunli177/sahara
sahara/main.py
Python
apache-2.0
6,825
0
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
description = (ex.description if isinstance(ex, werkzeug_exceptions.HTTPException) else str(ex)) return api_utils.render({'error': status_code, 'error_message': description}, status=status_code) ...
and not CONF.log_exchange: LOG.debug('Logging of request/response exchange could be enabled using' ' flag --log-exchange') # Create a CORS wrapper, and attach sahara-specific defaults that must be # included in all CORS responses. app.wsgi_app = cors_middleware.CORS(app.wsgi_app,...
pikeszfish/Leetcode.py
leetcode.py/CompareVersionNumbers.py
Python
mit
791
0.001264
class Solution: # @param version1, a string # @param version2, a string # @return an integer def compareVersion(self, version1, version2): v1 = version1.split('.') v2 = version2.spli
t('.') for i in range(0, min(len(v1), len(v2))): if int(v1[i]) > int(v2[i]): return 1 if int(v1[i]) < int(v2[i]): return -1 if len(v1) == len(v2): return 0 elif len(v1) > len(v2): for i in range(len(v2), len...
or i in range(len(v1), len(v2)): if int(v2[i]) != 0: return -1 return 0
jhuapl-boss/boss-manage
cloud_formation/configs/migrations/api/00010002_dns_update.py
Python
apache-2.0
1,140
0.003509
# Copyright 2019 The Johns Hopkins University Applied Physics Laboratory # # 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 ...
update(bosslet_config): # With version 2 the DNS records are now part of the CloudFormation template, so # remove the existing DNS record so the update can happen console.warning("Removing existing Api public DNS entry, so CloudFormation can manage the DNS record") aws.route53_delete_records(bosslet_con...
bosslet_config.EXTERNAL_DOMAIN, bosslet_config.names.public_dns('api'))
aetel/3D-printer
prusa_i3/Firmware/Marlin-2.0.x/buildroot/share/PlatformIO/scripts/STM32F1_create_variant.py
Python
gpl-2.0
1,009
0.003964
import os,shutil from SCons.Script import DefaultEnvironment from platformio import util def copytree(src, dst, symlinks=False, ignore=None):
for item in os.listdir(src):
s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): shutil.copytree(s, d, symlinks, ignore) else: shutil.copy2(s, d) env = DefaultEnvironment() platform = env.PioPlatform() board = env.BoardConfig() FRAMEWORK_DIR = platform.get_package_di...
lmorchard/badger
libs/activitystreams/atom.py
Python
bsd-3-clause
8,938
0.004363
from activitystreams import Activity, Object, MediaLink, ActionLink, Link import re import datetime import time class AtomActivity(Activity): pass # This is a weird enum-like thing. class ObjectParseMode(object): def __init__(self, reprstring): self.reprstring = reprstring def __repr__(self...
HOR parsing mode looks in atom:name instead of atom:title if mode == ObjectParseMode.ATOM_AUTHOR: name_tag_name = ATOM_NAME name = None name_elem = object_elem.find(name_tag_name) if name_elem is not None
: name = name_elem.text url = None image = None for link_elem in object_elem.findall(ATOM_LINK): type = link_elem.get("type") rel = link_elem.get("rel") if rel is None or rel == "alternate": if type is None or type == "text/html": url = link_elem....
ojii/ircbotframework
ircbotframework/app.py
Python
bsd-3-clause
719
0.005563
# -*- coding: utf-8 -*- from flask import request class View(object): def __init__(self, core): self.core = core def __call__(self, *args, **kwargs): method = request.method.lower() handler = getattr(self, method, None) if callable(handler): return handler(reque...
_(self, core): self.core = core def
get_urls(self): """ Returns a list of tuples: (route, View) """ return [] def get_plugins(self): """ Returns a list of plugin classes """ return []
YzPaul3/h2o-3
h2o-py/tests/testdir_algos/gbm/pyunit_bernoulli_synthetic_data_GBM_medium.py
Python
apache-2.0
3,234
0.009895
from builtins import range import sys, os sys.path.insert(1, os.path.join("..","..","..")) import h2o from tests import pyunit_utils from h2o import H2OFrame import numpy as np import numpy.random import scipy.stats from sklearn import ensemble from sklearn.metrics import roc_auc_score from h2o.estimators.gbm import H2...
)) train_h2o["C1"] = train_h2o["C1"].asfactor() test_h2o["C1"] = test_h2o["C1"].asfactor() gbm_h2o = H2OGradientBoostingEsti
mator(distribution=distribution, ntrees=ntrees, min_rows=min_rows, max_depth=max_depth, learn_rate=learn_rate, ...
GabrielNicolasAvellaneda/dd-agent
checks.d/supervisord.py
Python
bsd-3-clause
6,841
0.000877
# stdlib from collections import defaultdict import itertools import re import socket import time import xmlrpclib # 3p import supervisor.xmlrpc # project from checks import AgentCheck DEFAULT_HOST = 'localhost' DEFAULT_PORT = '9001' DEFAULT_SOCKET_IP = 'http://127.0.0.1' DD_STATUS = { 'STOPPED': AgentCheck.CRI...
'%s:%s' % (PROCESS_TAG, proc_name)] # Report Service Check status = DD_STATUS[proc['statename']] msg = self._build_message(proc) count_by_status[status] += 1 self.service_check(PROCESS_SERVICE_CHECK, status, tags=tags, me...
ptime = self._extract_uptime(proc) self.gauge('supervisord.process.uptime', uptime, tags=tags) # Report counts by status tags = ['%s:%s' % (SERVER_TAG, server_name)] for status in PROCESS_STATUS: self.gauge('supervisord.process.count', count_by_status[status], ...
philipdexter/rain
rain/module.py
Python
mit
12,253
0.014037
from . import ast as A from . import runtime from . import scope as S from . import static from . import token as K from . import types as T from contextlib import contextmanager from llvmlite import binding from llvmlite import ir from os.path import isdir, isfile from os.path import join import os.path import re nam...
.string_token)): key = key.value return normalize_name(key) def __init__(self, file=None, name=None): S.Scope.__init__(self) if name: self.qname = self.mname = name els
e: self.file = file self.qname, self.mname = find_name(self.file) self.llvm = ir.Module(name=self.qname) self.llvm.triple = binding.get_default_triple() self.imports = set() self.links = set() self.libs = set() self.runtime = runtime.Runtime(self) self.static = static.Static(se...
mattduan/proof
mapper/DatabaseMap.py
Python
bsd-3-clause
3,615
0.008852
""" DatabaseMap is used to model a database. """ __version__= '$Revision: 3194 $'[11:-2] __author__ = "Duan Guoqiang (mattgduan@gmail.com)" import string import proof.pk.IDMethod as IDMethod import proof.pk.generator.IDBroker as IDBroker import proof.mapper.TableMap as TableMap class DatabaseMap: def __init__...
f addTable(self, table): """ Add a new TableMap to the database. @param map The Name/TableMap representation. """ if not isinstance( table, TableMap.TableMap ): table = TableMap.TableMap( table, self ) self.__tables[table.getName()] = table def setI...
ot isinstance( idTable, TableMap.TableMap ): idTable = TableMap.TableMap( idTable, self ) self.__idTable = idTable self.addTable(idTable) idBroker = IDBroker.IDBroker(idTable) self.addIdGenerator(IDMethod.ID_BROKER, idBroker) def addIdGenerator(self, idType, idGen): ...
vecnet/om
website/tests/test_views.py
Python
mpl-2.0
874
0
# -*- coding: utf-8 -*- # # This file is part of the VecNet OpenMalaria Portal. # For copyright and licensing information about this package, see the # NOTI
CE.txt and LICENSE.txt files in its top-level directory; they are # available at https://github.com/vecnet/om # # This Source Code Form is subject to the terms of the Mozilla Public # License (MPL), version 2.0. If a copy of the MPL was not distributed # with this file, You can obt
ain one at http://mozilla.org/MPL/2.0/. from django.test.testcases import TestCase from django.urls.base import reverse class Http500Test(TestCase): def test(self): url = reverse("test_http_code_500") self.assertRaises(RuntimeError, self.client.get, url) class IndexViewTest(TestCase): def te...
missionpinball/mpf-mc
mpfmc/tests/test_Animation.py
Python
mit
18,424
0.000326
from mpfmc.tests.MpfMcTestCase import MpfMcTestCase class TestAnimation(MpfMcTestCase): def get_machine_path(self): return 'tests/machine_files/animation' def get_config_file(self): return 'test_animation.yaml' def test_animation_config_processing(self): # The animation sections ...
(s3w0['entrance3'][0]['named_animation'], 'fade_in') self.assertEqual(s3w0[
'entrance3'][1]['named_animation'], 'multi') # slide def, 2 events, list of named animations s4w0 = self.mc.slides['slide4']['widgets'][0]['animations'] self.assertIs(type(s4w0['entrance4']), list) self.assertEqual(len(s4w0['entrance4']), 2) self.assertIs(type(s4w0['entrance4'][...
stackforge/python-senlinclient
senlinclient/tests/unit/v1/test_cluster_policy.py
Python
apache-2.0
4,136
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 unde...
k.Mock( return_value=fake_resp) def test_cluster_policy_update(self): arglist = ['--policy', 'my_policy', '--enabled', 'true', 'my_cluster'] parsed_args = self.check_parser(self.
cmd, arglist, []) self.cmd.take_action(parsed_args) self.mock_client.update_cluster_policy.assert_called_with( 'my_cluster', 'my_policy', enabled=True)
SanaMobile/sana.mds
src/mds/api/v1/v2compatlib.py
Python
bsd-3-clause
14,907
0.012075
""" Utilities for transforming from the 1.x to other versions. :Authors: Sana dev team :Version: 1.1 """ import logging from uuid import UUID import re import cjson as _json import shutil, os from django.contrib.auth.models import User, UserManager from django.views.generic import RedirectView #from django.views.gen...
Got complex concept: node: %s, answer: %s" % (node,answer)) if not answer or answer == "": continue answer, _, additional = answer.partition(',') # Begin Complex obs loop while True: value_t
ext = "complex data" try: obs = v2.Observation.objects.get( uuid=uuid) obs.encounter=encounter obs.node=node obs.concept=concept obs.value_text=value_text obs...
esdalmaijer/PyOpenGaze
example/example_pygaze.py
Python
gpl-3.0
561
0.008913
from pygaze.display import Display from pygaze.screen import
Screen from pygaze.eyetracker import EyeTracker import pygaze.libtime as timer disp = Display() scr = Screen() scr.draw_text("Preparing experiment...", fontsize=20) disp.fill(scr) disp.show() tracker = EyeTracker(disp) tracker.calibrate() tracker.start_recording() t0 = timer.get_time() while timer.get_time() - t0 <...
.sample() scr.clear() scr.draw_fixation(fixtype='dot', pos=gazepos) disp.fill(scr) disp.show() tracker.stop_recording() tracker.close() disp.close()
obi-two/Rebelion
data/scripts/templates/object/tangible/ship/components/reactor/shared_rct_sfs_imperial_4.py
Python
mit
482
0.045643
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE
DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/ship/components/reactor/shared_rct_sfs_imperial_4.iff" result.attribute_template_id = 8 result.stfName("space/space_item","rct_sfs_imperial_4_n") #### BEGIN MODI
FICATIONS #### #### END MODIFICATIONS #### return result
Geoion/TorCMS
torlite/handlers/reply_handler.py
Python
mit
3,236
0.003399
# -*- coding:utf-8 -*- ''' Author: Bu Kun E-mail: bukun@osgeo.cn CopyRight: http://www.yunsuan.org ''' import tornado.web import tornado.escape import json from torlite.core import tools from torlite.core.base_handler import BaseHandler from torlite.model.mwiki import MWiki from torlite.model.mcatalog import MCatalog ...
guments(key) # # post_data['user_id'] = self.userinfo.uid # # cur_coun
t = self.mreply2user.insert_data(self.userinfo.uid, id_reply) # if cur_count: # self.mreply.update_vote(id_reply, cur_count) # # out_dic = {'zan_count': cur_count} # return json.dump(out_dic) @tornado.web.authenticated def zan(self, id_reply): post_data = {} ...
VHAINNOVATIONS/DmD
scrubber/MIST_2_0_4/src/MAT/lib/mat/python/MAT/Utilities.py
Python
apache-2.0
719
0.009736
# Copyright
(C) 2011 The MITRE Corporation. See the toplevel # file LICENSE for license terms. # I just have no place for this. import socket import MAT def findPort(startingAt): while True: v = socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect_ex(('127.0.0.1', startingAt)) if
v == 0: startingAt += 1 else: return startingAt def portTaken(portNum): return socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect_ex(('127.0.0.1', portNum)) == 0 def configurationPortTaken(configName): return portTaken(int(MAT.Config.MATConfig[configName])) def conf...
phil-mansfield/gotetra
render/scripts/plot_caustic_3d.py
Python
mit
637
0.00157
import numpy as np import sys import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D if len(sys.argv) != 2: print "Correct usage: $ %s caustic_file" % sys.argv[1] exit(1) fig = plt.figure() ax = fig.add_subplot(111, projection="3d") rows = np.loadtxt(sys.argv[1]) rs = np.array(zip(*cols)[-1...
ax.scatter([term_x], [term_y]
, [term_z], c="r") plt.show()
northern-bites/nao-man
noggin/players/pData.py
Python
gpl-3.0
1,354
0.004431
import os from . import SoccerFSA from . import DataStates class SoccerPlayer(SoccerFSA.SoccerFSA): def __init__(self, brain): SoccerFSA.SoccerFSA.__init__(self,brain) self.addStates(DataStates) self.setName('pData') self.postDistance = 50 self.lastDistance = 0 # Sp...
name = "/home/root/postDistData" + str(self.postDistance) + ".csv" # need to remove it if it exists already and make way # for new data if self.lastDistance != self.postDistance and \ os.path.exists(filename): self.lastDistance = self.postDistance os.remo...
csv.write("dist,bearing\n") else : csv = open(filename,'a+') for obj in self.objects: if obj.dist !=0.0 and abs(obj.dist - self.postDistance) < 100: csv.write(str(obj.dist) + "," + str(obj.bearing) + '\n') print obj.dist, obj.bearing csv....
simleo/openmicroscopy
components/tools/OmeroPy/test/unit/test_model.py
Python
gpl-2.0
12,180
0.000493
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Simple unit test which makes various calls on the code generated model. Copyright 2007-2014 Glencoe Software, Inc. All rights reserved. Use is subject to license terms supplied in LICENSE.txt """ import pytest import omero import omero.clients from omero...
assert img.isLoaded() assert img.getDetails() # details are auto instantiated assert not img.getName() # no other single-valued field is img.unload() assert not img.isLoaded() pytest.raises(omero.UnloadedEntityException, img.getDetails) def testUnloadField(self): ...
assert img.getDetails() img.unloadDetails() assert not img.getDetails() def testSequences(self): img = ImageI() assert img.sizeOfAnnotationLinks() >= 0 img.linkAnnotation(None) img.unload() try: assert not img.sizeOfAnnotationLinks() >= 0 ...
13pi/HipstaChat
api/decorators.py
Python
gpl-2.0
684
0.002924
from datetime import datetime from api.utils import api_response def auth_required(fn): def wrapped(self, reque
st, *args, **kwargs): if not request.user.is_authenticated(): return api_response({"error": "not authenticated"}, status=401) request.user.last_action=datetime.now().replace(tzinfo=None) request.user.save() return fn(self, request, *args, **kwargs) return wrapped def p...
turn fn(self, request, *args, **kwargs) return wrapped
cs-au-dk/Artemis
WebKit/Tools/Scripts/webkitpy/tool/commands/upload.py
Python
gpl-3.0
22,709
0.003479
#!/usr/bin/env python # Copyright (c) 2009, 2010 Google Inc. All rights reserved. # Copyright (c) 2009 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of sour...
+" % patch.reviewer().full_name) else: what_was_cleared.append("review+") return join_with_separators(what_was_cleared) def execute(self, options, args, tool): committers = Com
mitterList() for bug_id in tool.bugs.queries.fetch_bug_ids_from_pending_commit_list(): bug = self._tool.bugs.fetch_bug(bug_id) patches = bug.patches(include_obsolete=True) for patch in patches: flags_to_clear = self._flags_to_clear_on_patch(patch) ...
wgoulet/CTPyClient
fetchroots.py
Python
apache-2.0
1,184
0.017736
import os import base64 from requests import Session, Request from OpenSSL import crypto url = 'http://ct.googleapis.com/aviator/ct/v1/get-roots' s = Session() r = Request('GET', url) prepped = r.prepare() r = s.send(prepped) if r.status_code == 200: roots = r.json() # RFC 6962 defines the cert...
_certificate(crypto.FILETYPE_ASN1,base64.b64decode(k)) subject = certobj.get_subject() print 'CN={},OU={},O={},L={},S={},C={}'.format(subject.commonName, subject.organizationalUnitName, subj...
ct.localityName, subject.stateOrProvinceName, subject.countryName) except: print subject.get_components()
googlearchive/titan
titan/common/lib/google/apputils/datelib.py
Python
apache-2.0
15,413
0.007591
#!/usr/bin/env python # Copyright 2002 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...
oMicroseconds(time.time())) def GetSecondsSinceEpoch(time_tuple): """Convert time_tuple (in UTC) to seconds (also in UTC). Args: time_tuple: tuple with at least 6 items. Returns: seconds. """ return calendar.timegm(time_tuple[:6] + (0, 0, 0)) def GetTimeMicros(time_tuple): """Get a time in micr...
ince the epoch represented by the input tuple. """ return int(SecondsToMicroseconds(GetSecondsSinceEpoch(time_tuple))) def DatetimeToUTCMicros(date): """Converts a datetime object to microseconds since the epoch in UTC. Args: date: A datetime to convert. Returns: The number of microseconds since th...
lgastako/loglint
example.py
Python
mit
413
0
#!/usr/bin/env python import logging import optparse from zillion.utils
import cmdline logger = logging.getLogger(__name__) def main(): parser = optparse.OptionParser() options, args = parser.parse_args() logger.debug("foo") logger.debug("foo", 1) logger.debug("foo: %s", 1) logger.debug("foo: %s %s",
2, 3, 4) logger.debug("foo: %s %s", 5) cmdline.entry_point(__name__, main)
whitesource/python-plugin
agent/api/model/Coordinates.py
Python
apache-2.0
559
0.003578
class Coordinates: """ WhiteSource model for
artifact's coordinates. """ def __init__(self, group_id, artifact_id, version_id): self.groupId = group_id self.artifactId = artifact_id self.versionId = version_id def create_project_coordinates(distribution): """ Creates a 'Coordinates' instance for the user package""" dist_nam...
dinates(group_id=None, artifact_id=dist_name, version_id=dist_version) return coordinates
sasha-gitg/python-aiplatform
google/cloud/aiplatform_v1/services/migration_service/async_client.py
Python
apache-2.0
17,064
0.001641
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "Lic
ense"); # 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 WA...
nd # limitations under the License. # from collections import OrderedDict import functools import re from typing import Dict, Sequence, Tuple, Type, Union import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore from google.api_core import exceptions as core_exceptions # type: ignor...
hubinary/flasky
app/main/errors.py
Python
mit
255
0.003922
from flask import render_t
emplate from . import main @main.app_errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @main.app_errorhandler(500) def internal_server_error(e): return render_template('500.ht
ml'), 500
fnl/libfnl
src/fnl/stat/textclass.py
Python
agpl-3.0
15,148
0.001783
""" .. py:module:: fnl.stat.textclass :synopsis: Tools for developing a text classifier. .. moduleauthor:: Florian Leitner <florian.leitner@gmail.com> .. License: GNU Affero GPL v3 (http://www.gnu.org/licenses/agpl.html) """ from collections import defaultdict, namedtuple, Counter from itertools import chain from ...
[1:])) d.update(tokens) return d class Data: """ The data object is a container for all data relevant to the classifiers. """ # FIXME: this class is coder's hell...
def __init__(self, *files, columns=None, ngrams=2, decap=False, patterns=None, mask=None): """ Create a new data object with the following attributes: * instances - list of raw text instances * labels - array of instance labels in same order as raw text * featu...
chrta/canfestival-3-ct
objdictgen/commondialogs.py
Python
lgpl-2.1
69,421
0.008398
#!/usr/bin/env python # -*- coding: utf-
8 -*- #This file is part of CanFestival, a library implementing CanOpen Stack. # #Copyright (C): Edouard TISSERANT, Francis DUPIN and Laurent BESSARD # #See COPYING file for copyrights details. # #This library is free software; you can redistribute it and/or #modify it under the terms of the GNU Lesser General Public...
License, or (at your option) any later version. # #This library is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU #Lesser General Public License for more details. # #You should have recei...
shengshuyang/StanfordCNNClass
assignment1/cs231n/classifiers/softmax.py
Python
gpl-3.0
3,970
0.019395
import numpy as np from random import shuffle def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X:...
ftmax loss and its gradient using no explicit loops. # # Store the loss in loss and the gradient in dW. If you are not careful # # here, it is easy to run into numeric instability. Don't forget the # # regularization! # ######################...
is for broadcasting p = np.exp(scores) / np.sum(np.exp(scores), axis = 1)[:,np.newaxis] loss = -np.sum(np.log(p[range(num_train),y])) # Always think of the problem with the variable scores in mind, so dLoss/dW # should be dLoss/dscores (nonlinear scalar to matrix derivative) times dscores/dW # (simply X sinc...
MartinHjelmare/home-assistant
homeassistant/components/automation/sun.py
Python
apache-2.0
1,227
0
"""Offer sun based automation rules.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.core import callback from homeassistant.const import ( CONF_EVENT, CONF_OFFSET, CONF_PLATFORM, SUN_EVENT_SUNRISE) from homeassistant.helpers.event import async_track_sunrise, async_tra...
if event == SUN_EVENT_SUNRISE: return async_track_sunrise(
hass, call_action, offset) return async_track_sunset(hass, call_action, offset)
dhermyt/WONS
analysis/textclassification/SklearnClassifierFactory.py
Python
bsd-2-clause
2,285
0.001751
from nltk import NaiveBayesClassifier, SklearnClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.linear_model import PassiveAggressiveClassifier from sklearn.linear_model import Perceptron from sklearn.linear_model import RidgeClassifier from ...
rt LinearSVC from sklearn.svm import NuSVC from sklearn.svm import SVC from analysis.textclassification.NltkClassifierWrapper import NltkClassifierWrapper from analysis.textclassification.SklearnClassifierWrapper import SklearnClassifierWrapper class SklearnClassifierFactory(object): @staticmethod def Sklear...
eturn SklearnClassifierWrapper(MultinomialNB) @staticmethod def SklearnBernoulliNB(): return SklearnClassifierWrapper(BernoulliNB) @staticmethod def SklearnLogisticRegression(): return SklearnClassifierWrapper(LogisticRegression) @staticmethod def SklearnSGDClassifier(): ...
cboelsen/tastytopping
tastytopping/field.py
Python
lgpl-3.0
6,454
0.001085
# -*- coding: utf-8 -*- """ .. module: field :platform: Unix, Windows :synopsis: Separates field_type-dependent functionality into Field classes. .. moduleauthor:: Christian Boelsen <christian.boelsen@hds.com> """ __all__ = ('create_field', ) from datetime import datetime from .exceptions import ( In...
return details['resource_uri'].split('/')[-3] except TypeError: return details.split('/')[-3] def stream(self): return self._value.uri() def filter(self, field): related_field = self.value().filter
_field() filtered_field = self.value()._schema().append_to_filter(field, related_field) return filtered_field, getattr(self.value(), related_field) class ResourceListField(Field): """Wrap a list of Resources in a to_many relationship.""" def __init__(self, values, factory): value = [R...
SudarshanGp/R_Test
test.py
Python
mit
1,088
0.05239
import csv import json csvfile = open('su15.csv', 'r') jsonfile = open('output.json', 'w') output = {'name' : 'Summer 2015', 'children': []} gender = {'children' : []} i = 0 a = {'test' : []} for row in csv.DictReader(csvfile): a['test'].append({'name' : 'Male', 'size' : row['Male'] }) a['test'].append({'name' : '...
ow['Female'] }) gender['children'].append( { 'name' : row['Courses'], 'children' : a['test'] }) a = {'test' : []} output['children'].append( { 'name' : 'Gender', 'children' : gender['children'] }) csvfile.close() print "success 1" csvfile = open('su15_2.csv', 'r') instate = {'children' : []} a = {'test' ...
}) a['test'].append({'name' : 'Outstate', 'size' : row['Non-Illinois'] }) instate['children'].append( { 'name' : row['Courses'], 'children' : a['test'] }) a = {'test' : []} output['children'].append( { 'name' : 'Instate', 'children' : instate['children'] }) json.dump(output, jsonfile) jsonfile.close...
cursoweb/python-archivos
Merlo-Joaquin/wordcount.py
Python
mit
2,864
0.007749
#!/usr/bin/python -tt # -*- coding: utf-8 -*- # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ """Wordcount exercise Google's Python class La función main() d...
las letras -- no se preocupen por eso). Guardar todas las palabras en minúsculas, así 'The' y 'the' cuentan como la misma palabra. 2. para la bandera --topcount, implementar una función print_top(nombre_archivo) que es similar a print_words() pero imprime sólo las 20 palabras más comunes ordenadas para que aparezca ...
construyas todo el programa de una vez. Llega hasta un hito intermedio e imprime tu estructura de datos y luego sys.exit(0). Cuando eso funcione, intenta con el siguiente hito. Opcional: defina una función de ayuda para evitar duplicar código dentro de print_words() y print_top(). """ import sys # +++tu código aq...
silverfield/pythonsessions
s13_python_day/__init__.py
Python
mit
23
0
__au
tho
r__ = 'ferrard'
esilgard/caisis_query_and_de_identify
sweeper.py
Python
apache-2.0
2,097
0.012399
''' author@esilgard April 2016 "sweep" through output directory files searching for potential PHI and print out warning statements ''' import os, re # general directory for output files file_dir = 'H:\DataExtracts\OncoscapeLungHoughton-4229\Output' ## common names or potential phi (assume first line is a ...
sep + 'PHI_Keywords.txt', 'r').readlines()[1:]]) print 'sweeping output files for potential PHI: mrns, path numbers, ',\ len(first_names), 'first names, ', len(last_names), 'last names, ',\ len(potential_phi_keywords), 'PHI indicator keywords' for path, directory, files in os.walk(file_dir): for ...
path.sep + f, 'r').read() alpha_words = set(re.split('[\W]', text)) ## PHI patterns mrn = re.search('[UH][0-9]{7}', text) pathnum = re.search('[A-B][\-][\-\d]{2,11}', text) if mrn: print 'WARNING. Potential MRN found in ' + path + f + ' at ' + str(mrn.start()...
negrinho/deep_architect
examples/contrib/kubernetes/master.py
Python
mit
9,581
0.000417
import argparse import time import subprocess import logging from deep_architect import search_logging as sl from deep_architect import utils as ut from deep_architect.contrib.communicators.mongo_communicator import MongoCommunicator from search_space_factory import name_to_search_space_factory_fn from searcher impor...
warning', 'error'], default='info') parser.add_argument('--repetition', default=0) options = parser.parse_args() numeric_level = getattr(log
ging, options.log.upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % options.log) logging.getLogger().setLevel(numeric_level) configs = ut.read_jsonfile(options.config_file) config = configs[options.config_name] config['bucket'] = options.bucke...
proofchains/python-proofmarshal
proofmarshal/serialize.py
Python
gpl-3.0
14,738
0.003393
# Copyright (C) 2015 Peter Todd <pete@petertodd.org> # # This file is part of python-proofmarshal. # # It is subject to the license terms in the LICENSE file found in the top-level # directory of this distribution. # # No part of python-proofmarshal, including this file, may be copied, modified, # propagated, or distri...
ger in the range min < i < max Struct - Zero or more of the above, (de)serialized in a fixed order to form a structure. Serialization contexts ====================== We would like to be
able to serialize/deserialize Hashing ======= Cryptographic hashing of serializable objects is performed by re-using the serialization machinery. For efficiency reasons objects with serialized representations that are less than the length of a hash return a so-called "hash" that is simply the serialized object itse...
emencia/emencia_paste_djangocms_3
emencia_paste_djangocms_3/django_buildout/project/accounts/urls.py
Python
mit
2,293
0.004361
""" URLconf for registration and activation, using django-registration's default mods backend. If the default behavior of these views is acceptable to you, simply use a line like this in your root URLconf to set up the default URLs for registration:: (r'^accounts/', include('project.registration.urls')), This wi...
mplete/$', TemplateView.as_view(template_name='registration/activation_complete.html'), name='registration_activation_complete'), # Activation keys get matched by \w+ instead of the more specific # [a-fA-F0-9]{40} because a bad activation key should still get to the view; # that way it can r...
name='registration_activate'), url(r'^register/$', RegistrationView.as_view(), name='registration_register'), url(r'^register/complete/$', TemplateView.as_view(template_name='registration/registration_complete.html'), name='registration_complete'), url(r'^register/closed...
matrix-org/synapse
synapse/replication/http/__init__.py
Python
apache-2.0
1,864
0
# Copyright 2018 New Vector Ltd # # 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 writin...
# We enable extracting jaeger contexts here as these are internal APIs. super().__init__(hs, canonical_json=False, extract_context=True) self.register_servlets(hs) def register_servlets(self, hs: "HomeServer") -> None: send_event.register_servlets(hs, self) federation.regis...
streams.register_servlets(hs, self) account_data.register_servlets(hs, self) push.register_servlets(hs, self) # The following can't currently be instantiated on workers. if hs.config.worker.worker_app is None: login.register_servlets(hs, self) register.register_s...
hovo1990/deviser
generator/tests/test_cpp_code/run_cpp_tests.py
Python
lgpl-2.1
17,841
0.000224
#!/usr/bin/env python import os import sys sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../') sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../../') from code_files import CppFiles, ExtensionFiles, ValidationFiles from parseXML import ParseXML from tests import test_functions ###...
are_code_impl(class_name) print('') return fail def run_ext_test(name, class_name, test_case, test): filename = test_functions.set_up_test(name, class_name, test_case) if test == 0: generate_extension_he
ader(filename) elif test == 1: generate_types_header(filename) else: generate_fwd_header(filename) fail = compare_ext_headers(class_name) if test == 0: fail += compare_ext_impl(class_name) print('') return fail def run_plug_test(name, class_name, test_case, num): fi...
danielhers/ucca
uccaapp/upload_streussel_passages.py
Python
gpl-3.0
3,363
0.003271
#!/usr/bin/env python3 import sys import argparse from ucca.convert import from_text, to_json from uccaapp.api import ServerAccessor desc = """Upload a passage from a streussel format file""" class StreusselPassageUploader(ServerAccessor): def __init__(self, user_id, source_id, project_id, **kwargs): s...
else: passage_text = passage_text + " " + line passage_out = self.create_passage(text=passage_text.strip(), external_id=external_id, type="PUBLIC", source=self.source) task_in = dict(type="TOKENIZATION", stat...
michkot/benchexec
benchexec/tools/predatorhp.py
Python
apache-2.0
3,054
0.002292
""" BenchExec is a framework for reliable benchmarking. This file is part of BenchExec. Copyright (C) 2007-2015 Dirk Beyer 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 ...
plicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WI
THOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import benchexec.util as util import benchexec.tools.template import benchexec.result as result import subprocess import os import sys class To...
DailyActie/Surrogate-Model
01-codes/scipy-master/benchmarks/benchmarks/go_benchmark_functions/go_funcs_N.py
Python
mit
4,191
0.000716
# -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import from numpy import cos, sqrt, sin, abs from .go_benchmark import Benchmark class NeedleEye(Benchmark): r""" NeedleEye objective function. This class defines the Needle-Eye [1]_ global optimization problem. This is a...
Functions. Munich Personal RePEc Archive, 2006, 1005 TODO Line 368 TODO WARNING, minimum value is estimated from running many optimisations and choosing the best. """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip
([-10.0] * self.N, [10.0] * self.N)) self.global_optimum = [[-9.94114736324, -9.99997128772]] self.fglob = -0.199409030092 def fun(self, x, *args): self.nfev += 1 return ((abs(sin(sqrt(abs(x[0] ** 2 + x[1]))))) ** 0.5 + 0.01 * (x[0] + x[1])) # Newfunction 3 from G...
dwysocki/trivial
doc/stats/plot.py
Python
gpl-3.0
2,722
0.005878
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np def separate_windows(arr): ret = dict() for k, v in zip(*arr): if k in ret: ret[k].append(v) else: ret[k] = [v] return ret def load_file(filename, *args, **kwargs): data = np.genfromtxt(...
def plot_multi(filenames, output, window, title, xlabel="Trial", ylabel="Throughput (kbps)", *args, **kwargs): all_windows = {fname.split('.')[0] : load_file(fname) for fname in filenames} stop_wait = {trial : all_windows[trial][1] for trial in...
for trial in all_windows} trials = sorted(optimal.keys()) N = len(trials) x_offsets = np.arange(N) fig, ax = plt.subplots() ax.boxplot(list(optimal.get(k) for k in trials)) plt.setp(ax.boxplot(list(stop_wait.get(k) for k in trials)...
ashishbaghudana/mthesis-ashish
resources/tees/Utils/InteractionXML/CopyParse.py
Python
mit
4,989
0.008419
try: import xml.etree.cElementTree as ET except ImportError: import cElementTree as ET import Utils.ElementTreeUtils as ETUtils import sys import CorpusElements from optparse import OptionParser def copyParse(input, source, output, parse, tokenization): print >> sys.stderr, "Loading input file", input ...
ment.find("parses") if targetParsesElement == None: targetParsesElement = ET.Element("parses") targetAnalysesElement.append(targetParsesElement) # Check whether parse already exists targetParseElements = targetParsesElement.findall("parse") newParse = None ...
f it doesn't if newParse == None and sourceSentence.parseElement != None: targetParsesElement.append(sourceSentence.parseElement) parsesCopied[0] += 1 # Create tokenizations element (if needed) targetTokenizationsElement = targetAnalysesElement.find("tokenization...
HewlettPackard/ratekeeper-neutron-ml2-plugin
patches/nova/ratekeeper_monkey_patch.py
Python
apache-2.0
2,041
0.00196
# (c) Copyright 2015 Hewlett Packard Enterprise Development LP # # 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 appli...
if fn.func_name == '_populate_neutron_extension_values': LOG.debug("RK: wrapping function call: %s" % fn.func_name) foo, context, instance, pci_request_id, port_req_body = args flavor = instance.get_flavor() extra_specs = flavor.get('extra_specs', {}) ...
int(extra_specs.get(rk_const.RK_MIN_RATE, 0)) max_rate = int(extra_specs.get(rk_const.RK_MAX_RATE, 0)) port_req_body['port'][rk_const.RK_MIN_RATE] = min_rate port_req_body['port'][rk_const.RK_MAX_RATE] = max_rate ret = fn(*args, **kwarg) LOG.debug("RK: Extend...
firasbenmakhlouf/JobLookup
metadata/admin.py
Python
mit
169
0
from django.contrib import admin from metadata.models impo
rt * # Register your models here. admin.site.register(TanitJobsCategory) admin.site.register
(KeeJobsCategory)
pulsar-chem/Pulsar-Core
lib/systems/l-arginine.py
Python
bsd-3-clause
1,416
0.000706
import pulsar as psr def load_ref_system(): """ Returns l-arginine as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" N 0.8592 -2.9103 -0.8578 C 1.3352 -1.5376 -1.1529 C 2.8596...
0.4139 C -2.9738 2.2808 1.4124 N -3.4837 3.3356 0.8530 H -3.9046 4.0108 1.4410 N -2.8404 2.0695 2.8280 H -2.7215 1.1094 3.0676 H -3.5979 2.4725 3.3357 H -0.1386 -2.9250 ...
562 -1.2864 -2.1768 H 4.3768 -1.2078 -2.2540 """)
Egomania/SOME-IP_Generator
src/attacks/sendErrorOnError.py
Python
agpl-3.0
1,693
0.005316
""" Answers with an Error message to a previous Error message. """ import copy import random from src import Msg from src import SomeIPPacket from src.attacks import Attacker
Helper def sendErrorOnError(a, msgOrig): """ Attack Specific Function. """ sender = msgOrig.receiver receiver = msgOrig.sender timestamp = None message = {} message['service'] = msgOrig.message['service'
] message['method'] = msgOrig.message['method'] message['client'] = msgOrig.message['client'] message['session'] = msgOrig.message['session'] message['proto'] = SomeIPPacket.VERSION message['iface'] = SomeIPPacket.INTERFACE message['type'] = SomeIPPacket.messageTypes['ERROR'] errors = ['E_N...
tgquintela/pyDataProcesser
pyDataProcesser/DataManagement.py
Python
mit
16,526
0.001029
# -*- coding: utf-8 -*- import pandas as pd from datetime import datetime import numpy as np from DataDictObject import DataDictObject from TablonReader import TablonReader from TablonEncoder import TablonEncoder from TablonLoader import TablonLoaderDB class DataManagementObject: """This is the cla...
.loader] self.pipelineselection = ['parser', 'preexploratory', 'encoder', 'loader', 'exploratory'] # The processes that could generat
e an input to this system self.inputters = ['parser', 'downloader'] # The processes that generate a tablon self.tabloners = ['encoder'] + self.inputters # The other parematers self.typeoutput = '' # tablon, formattablon,analyticaltablon, others self.defaultpipe...
hyperized/ansible
lib/ansible/modules/network/eos/eos_vrf.py
Python
gpl-3.0
10,723
0.001585
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # # This file is part of Ansible by Red Hat # # 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 Li...
face %s' % i) commands.append('vrf forwarding %s' % w['name']) else: if w['rd'] is not None and w['rd'] != obj_in_have['rd']: commands.append('vrf definition %s' % w['name']) commands.append('rd %s' % w['rd']) i...
if not obj_in_have['interfaces']: for i in w['interfaces']: commands.append('interface %s' % i) commands.append('vrf forwarding %s' % w['name']) elif set(w['interfaces']) != obj_in_have['interfaces']: ...
Blazemeter/taurus
examples/molotov/blazedemo.py
Python
apache-2.0
169
0
import molotov @molotov.scenario(100) async def Molotov_test(session): async with
session.get('https://blazedemo.com/') as resp: assert
resp.status == 200
benjello/liam2
liam2/entities.py
Python
gpl-3.0
33,581
0.000566
# encoding: utf-8 from __future__ import print_function import collections import sys import warnings # import bcolz import numpy as np import tables import config from data import (merge_arrays, get_fields, ColumnArray, index_table, build_period_array) from expr import (Variable, Var...
in count_occurrences(fields.names) if num > 1] if dupli
cate_names: raise Exception("duplicate fields in entity '%s': %s" % (self.name, ', '.join(duplicate_names))) fnames = set(fields.names) if 'id' not in fnames: fields.insert(0, Field('id', int)) if 'period' not in fnames: fi...
cursoweb/ejemplo-django
manage.py
Python
mit
248
0
#!/usr/bin/en
v python import os import sys i
f __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "curso.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
portante/sosreport
sos/plugins/ipsec.py
Python
gpl-2.0
1,514
0.009908
## Copyright (C) 2007 Sadique Puthen <sputhenp@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 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 FITNE...
re details. ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin class IPSec(Plugin): """ipsec relat...
KayaBaber/Computational-Physics
Assignment_3_chaos_and_pendulums/Phys440_Assignment03_Prob2.py
Python
mit
2,476
0.023021
''' Kaya Baber Physics 440 - Computational Physics Assignment 3 Problem 2 ''' from scipy.integrate import odeint import numpy as np import matplotlib.pyplot as plt import math def f(thetas, t, b, gamma, omega): #pendulum driven-damped function theta=thetas[0] thetaDot=thetas[1] thetaDouble=-b*thetaDot ...
rray(sol[:,0][210*steps:])+math.pi)%(2*math.pi))-math.pi #plot phase space plot plt.pl
ot(thetaLog, sol[:, 1][210*steps:], 'g.', label='theta-Dot(theta)') plt.xlabel('theta') plt.ylabel('theta-Dot') plt.title('Phase Space Plot') plt.grid() plt.gca().set_aspect('equal', adjustable='box') plt.savefig('plots/gamma'+str(gamma)+'_thetaDot_theta.png',bbox_inches='tight') #plt.savefi...
OldPanda/B551
hw4/simpleGreedy.py
Python
gpl-2.0
907
0.083793
import gamePlay from copy import deepcopy def value(board): value = 0 for row in board: for elem in row: if elem == "W": value = value + 1 elif elem == "B": value = value - 1 return value def betterThan(val1, val2, color, reversed): if color == "W": retVal = val1 > val2 els...
olor, (i,j)): moves.append((i,j)) if len(moves) == 0: return "pass" best = None for move in moves
: newBoard = deepcopy(board) gamePlay.doMove(newBoard,color,move) moveVal = value(newBoard) if best == None or betterThan(moveVal, best, color, reversed): bestMove = move best = moveVal return bestMove
elena/django
django/utils/deprecation.py
Python
bsd-3-clause
4,818
0.000623
import asyncio import inspect import warnings from asgiref.sync import sync_to_async class RemovedInDjango41Warning(DeprecationWarning): pass class RemovedInDjango50Warning(PendingDeprecationWarning): pass RemovedInNextVersionWarning = RemovedInDjango41Warning class warn_about_renamed_method: def _...
_method)) return new_class class DeprecationInstanceCheck(type): def __instancecheck__(self, instance):
warnings.warn( "`%s` is deprecated, use `%s` instead." % (self.__name__, self.alternative), self.deprecation_warning, 2 ) return super().__instancecheck__(instance) class MiddlewareMixin: sync_capable = True async_capable = True def __init__(self, get_resp...
chrys87/fenrir
src/fenrirscreenreader/commands/commands/review_curr_line.py
Python
lgpl-3.0
1,171
0.01281
#!/bin/python # -*- coding: utf-8 -*- # Fenr
ir TTY screen reader # By Chrys, Storm Dragon, and contributers. from fenrirscreenreader.core import debug from fenrirscreenreader.utils import line_utils class command(): def __init__(self): pass def initialize(self, environment): self.env = environment def shutdown(self): ...
self.env['runtime']['cursorManager'].enterReviewModeCurrTextCursor() self.env['screen']['newCursorReview']['x'], self.env['screen']['newCursorReview']['y'], currLine = \ line_utils.getCurrentLine(self.env['screen']['newCursorReview']['x'], self.env['screen']['newCursorReview']['y'], self.env['scre...
mathemage/h2o-3
py/h2o_test_utils.py
Python
apache-2.0
31,016
0.005771
import sys, os, time, json, datetime, errno, stat, getpass, requests, pprint if sys.version_info[0] < 3: import urlparse else: import urllib.parse as urlparse import h2o debug_rest = False verbosity = 0 # 0, 1, 2, 3 pp = pprint.PrettyPrinter(indent=4) # pretty printer for debugging def setVerbosity(level): glob...
art in key.split('/'): part = part[keypart] k = keypart
# print 'for keypart: ', keypart, ' part: ', repr(part) result[part] = entry # print 'result: ', repr(result) return result def validate_builder(algo, builder): ''' Validate that a model builder seems to have a well-formed parameters list. ''' assert 'parameters' in builder, "FAIL: Fai...
maxive/erp
addons/im_livechat/__manifest__.py
Python
agpl-3.0
1,269
0.000788
# -*- coding: utf-8 -*- { 'name' : 'Live Chat', 'version': '1.0', 'sequence': 170, 'summary': 'Live Chat with Visitors/Customers', 'category': 'Website', 'complexity': 'easy', 'website': 'https://www.odoo.com/page/live-chat', 'description': """ Live Chat Support =================...
low to drop instant messaging widgets on any web page that will communicate with the current server and dispatch visitors request amongst several live chat operators. Help your customers with this chat, and analyse their feedback. """, 'data': [ "security/im_livechat_channel_security.xml", ...
l", "views/im_livechat_channel_templates.xml", "views/res_users_views.xml", "report/im_livechat_report_channel_views.xml", "report/im_livechat_report_operator_views.xml" ], 'demo': [ "data/im_livechat_channel_demo.xml", 'data/mail_shortcode_demo.xml', ], '...
madgik/exareme
Exareme-Docker/src/mip-algorithms/tests/integration_tests/test_exareme_integration_logistic_regression.py
Python
mit
894
0.001119
import json import numpy as np import pytest import requests from mipframework.testutils import get_test_params from tests import vm_url from tests.algorithm_tests.test_logistic_regression import expected_file headers = {"Content-type": "application/json", "Accept": "text/plain"} url = vm_url + "LOGISTIC_REGRESSION" ...
100)) ) def test_logistic_regression_algorithm_exareme(test_input, expected): result = requests.post(url, data=json.dumps(test_input), headers=headers) result = json.loads(result.text) result = result["result"][0]["data"] assert are_collinear(result["Coefficients"], expected["coeff"]) def are_collin...
Canpio/Paddle
python/paddle/fluid/tests/unittests/test_array_read_write_op.py
Python
apache-2.0
3,404
0
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
ent is 1 and the neural network are all linear # with mean_op. # the input gradient should also be 1 self.assertAlmostEqual(1.0, g_out_sum, delta=0.
1) if __name__ == '__main__': unittest.main()
mahabs/nitro
nssrc/com/citrix/netscaler/nitro/resource/config/ns/nspbr_args.py
Python
apache-2.0
1,045
0.025837
# # 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...
w or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # class nspbr_args : """ Pr...
s additional arguments required for fetching the nspbr resource. """ def __init__(self) : self._detail = False @property def detail(self) : """To get a detailed view. """ try : return self._detail except Exception as e: raise e @detail.setter def detail(self, detail) : """To get a detailed vie...
lopopolo/hyperbola
hyperbola/frontpage/views.py
Python
mit
284
0.003521
from d
jango.shortcuts import render from .m
odels import Blurb, Schedule def index(request): blurbs = Blurb.objects.filter(display=True) schedule = Schedule.objects.filter(display=True) return render(request, "frontpage.html", {"blurbs": blurbs, "schedule": schedule})
lootr/netzob
netzob/test/src/test_netzob/test_Common/suite_Type.py
Python
gpl-3.0
2,410
0.012469
#!/usr/bin/python
# -*- coding: utf-8 -*- #+---------------------------------------------------------------------------+ #| 01001110 01100101 01110100 01111010 01101111 01100010 | #|
| #| Netzob : Inferring communication protocols | #+---------------------------------------------------------------------------+ #| Copyright (C) 2011-2017 Georges Bossert and Frédéric Guihéry | #| This program is free software: you can redistribute...
shakamunyi/tensorflow
tensorflow/python/framework/ops.py
Python
apache-2.0
181,558
0.006059
# 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...
`name` property") except AttributeError: raise TypeError("Type %s does not define a `name` property") try: if not isinstance(tens
or_type.dtype, property): raise TypeError("Type %s does not define a `dtype` property") except AttributeError: raise TypeError("Type %s does not define a `dtype` property") # We expect this list to be small, so choose quadratic complexity # for registration, so that we have a tuple that can be used for ...
kelseyoo14/Wander
venv_2_7/lib/python2.7/site-packages/IPython/qt.py
Python
artistic-2.0
744
0
""" Shim to maintain backwards compatibility with old IPython.qt imports. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import sys from warnings import warn from IPython.uti
ls.shimmodule import ShimModule, ShimWarning warn("The `IPython.qt` package has been deprecated. " "You should import from qtconsole instead.", ShimWarning) # Unco
nditionally insert the shim into sys.modules so that further import calls # trigger the custom attribute access above _console = sys.modules['IPython.qt.console'] = ShimModule( src='IPython.qt.console', mirror='qtconsole') _qt = ShimModule(src='IPython.qt', mirror='qtconsole') _qt.console = _console sys.modules[...
hallover/alloy-database
code/timeErrorPlot.py
Python
mit
3,797
0.008428
import os as os import zipfile as Z from os.path import isfile, join from getpass import getuser from matplotlib import pyplot as plt zipfiles = [] kptList = [] name = [] inputzips = [] netID = getuser() zippath = "/fslhome/" + netID + "/vasp/alloydatabase/alloyzips/" newpath = "/fslhome/" + netID + "/vasp/alloyd...
r_alldata[i][2]) # print(error_alldata[i][0][0]) kpts = 3 * h + 4 # print(kpts) eTOTEN.append(a) #ikpts.append(irrk) del totalCPUtime[0] del eTOTEN[0] #del ikpts[0] print(totalCPUtime) print(eTOTEN) graphpath = "/fslhome/" ...
: # print(etoten[0][i]) # print(totalCPUtime[i]) for j in range(len(freeEnergy[i])) plt.plot(eTOTEN[i][j], totalCPUtime[i]) plt.loglog() plt.xlabel("Error") plt.ylabel("CPU Usage Time") plt.title(name + "Time-Error Efficiency") plt.savefig(graphpath + name + '_kpts.p...
agile-geoscience/welly
tests/test_quality.py
Python
apache-2.0
2,002
0
# -*- coding: utf 8 -*- """ Define a suite a tests for the canstrat functions. """ from welly import Well import welly.quality as q tests = { 'Each': [ q.no_flat, q.no_monotonic, q.no_gaps, ], 'Gamma': [ q.all_positive, q.all_below(450), q.check_units(['API',...
ions in class Curve """ w = Well.from_las('tests/assets/P-129_out.LAS') c = w.get_curve(mnemonic='CALI') tests_curve = c.quality(tests=tests) assert isinstance(tests_curve, dict)
assert len(tests_curve) == 3 tests_curve_qflag = c.qflag(tests=tests, alias=alias) assert isinstance(tests_curve_qflag, dict) assert len(tests_curve_qflag) == 3 tests_curve_qflags = c.qflags(tests=tests, alias=alias) assert isinstance(tests_curve_qflags, dict) assert len(tests_curve_qflags) ==...
hyunchel/webargs
tests/test_bottleparser.py
Python
mit
4,813
0.004363
# -*- coding: utf-8 -*- import pytest from bottle import Bottle, debug, request, response from webtest import TestApp from webargs import ValidationError, fields from webargs.bottleparser import BottleParser hello_args = { 'name': fields.Str(missing='World', validate=lambda n: len(n) >= 3), } hello_multiple = { ...
myvalue): return {'myvalue': myvalue} assert testapp.p
ost('/foo/', {'myvalue': 23}).json == {'myvalue': 23} def test_use_kwargs_with_url_params(app, testapp): @app.route('/foo/<name>') @parser.use_kwargs({'myvalue': fields.Int()}) def foo(myvalue, name): return {'myvalue': myvalue} assert testapp.get('/foo/Fred?myvalue=42').json == {'myvalue': 42}...
innovimax/vxquery
vxquery-benchmark/src/main/resources/util/diff_xml_files.py
Python
apache-2.0
3,401
0.006469
#!/usr/bin/env python # # 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 "Lic...
ot 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
ble 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 License for the specific language governing permissions and # limitations under the License. import getopt, glob, os, sys d...
andersk/zulip
zerver/webhooks/freshdesk/tests.py
Python
apache-2.0
4,844
0.001034
from unittest.mock import MagicMock, patch from zerver.lib.test_classes import WebhookTestCase class FreshdeskHookTests(WebhookTestCase): STREAM_NAME = "freshdesk" URL_TEMPLATE = "/api/v1/external/freshdesk?stream={stream}" WEBHOOK_DIR_NAME = "freshdesk" def test_ticket_creation(self) -> None: ...
self.assert_json_success(result) def note_change(self, fixture: str, note_type: str) -
> None: """ Messages are generated when a note gets added to a ticket through Freshdesk's "Observer" service. """ expected_topic = "#11: Test ticket subject" expected_message = """ Requester Bob <requester-bob@example.com> added a {} note to \ [ticket #11](http://test1234...
tomka/CATMAID
django/lib/custom_testrunner.py
Python
gpl-3.0
635
0.00315
# -*- coding: utf-8 -*- from django.conf import settings from django.test.runner import DiscoverRunner from pipeline.conf import s
ettings as pipeline_settings class TestSuiteRunner(DiscoverRunner): def __init__(self, *args, **kwargs): settings.TESTING_ENVIRONMENT = True super(TestSuiteRunner, self).__init__(*args, **kwargs) def setup_test_environment(self, **kwargs): '''Override STATICFILES_STORAGE and pipeline ...
EBUG.''' super().setup_test_environment(**kwargs) settings.STATICFILES_STORAGE = 'pipeline.storage.NonPackagingPipelineStorage' pipeline_settings.DEBUG = True
brata-hsdc/brata.station
bin/pibrellaMidi.py
Python
apache-2.0
1,422
0.006329
from mido import MidiFile from time import sleep import pibrella """ fade test pibrella.light.red.fade(0,100,10) sleep(11) pibrella.light.red.fade(100,0,10) sleep(11) """ """ start pibrella.buzzer.note(-9) sleep(.9) pibrella.buzzer.off() sleep(0.1) pibrella.buzzer.note(-9) sleep(0.9) pibrella.buzzer.off() sleep(0.1) ...
te(0) sleep(1.25) pibrella.buzzer.note(-7) sleep(2) pibrellay.buzzer.off() """ """ Mike notes for success likely bond theme and need a calibration mode push button yellow goes on then as turn the light can change untl the light changes press red button again to go back to operational state """ """ it knows it is a c...
d') for i, track in enumerate(mid.tracks): print('Track ') print(track.name) if track.name == '': for message in track: if message.type == 'note_on': # print('Turn on ') note = message.note - 69 print(note) pibrella.buzzer.note(note) d...
hughdbrown/sed
sed/engine/sed_util.py
Python
mit
3,112
0.000321
#!/usr/bin/env python from itertools import count import doctest def delete_range(lines, r=None): """ >>> a = list(range(10)) >>> delete_range(a, (1, 3)) [0, 4, 5, 6, 7, 8, 9] """ r = r or (0, len(lines)) return rep
lace_range(lines, [], (r[0], r[1] + 1)) def insert_range(lines, new_lines, line_no): """ >>> a = list(range(10)) >>> b = list(range(11, 13)) >>> insert_range(a, 3, b) [0, 1, 2, 11, 12, 3, 4, 5, 6, 7, 8, 9] >>> insert_range(a, 0, b) [11, 12, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9] >>> insert_range(a, 9, b) [0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 9] """ return replace_range(lines, new_lines, (line_no, line_no)) def append_range(lines, new_lines, line_no): """ >>> a = list(range(10)) >>> b = list(range(11, 13)) >>> append_range(a, 3, b) [0, 1...
chngchinboon/intercomstats
scripts/tagclassifer_keras.py
Python
mit
9,514
0.018604
# -*- coding: utf-8 -*- """ Created on Wed Jan 25 13:50:30 2017 @author: Owner """ from __future__ import print_function import os import numpy as np np.random.seed(1337) import matplotlib.pyplot as plt import pandas as pd from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence ...
ndex) labels_index[name] = label_id for fname in sorted(os.listdir(path)): if fname.isdigit(): fpath = os.path.join(path, fname) if sys.version_info < (3,): f = open(fpath)
else: f = open(fpath, encoding='latin-1') texts.append(f.read()) f.close() labels.append(label_id) ''' print('Found %s texts.' % len(texts)) # finally, vectorize the text samples into a 2D integer tensor tokenizer = Tokenizer(nb_words=MA...
jmcnamara/XlsxWriter
xlsxwriter/test/utility/test_xl_cell_to_rowcol_abs.py
Python
bsd-2-clause
1,642
0
######################################################
######################### # # Tests for XlsxWriter. # # SPDX-License-Identifier: BSD-2-Clause # Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org # import unittest from ...utility import xl_cell_to_rowcol_abs class TestUtility(unittest.TestCase): """ Test xl_cell_to_rowcol_abs() utility function. ...
xl_cell_to_rowcol_abs(self): """Test xl_cell_to_rowcol_abs()""" tests = [ # row, col, A1 string (0, 0, 'A1'), (0, 1, 'B1'), (0, 2, 'C1'), (0, 9, 'J1'), (1, 0, 'A2'), (2, 0, 'A3'), (9, 0, 'A10'), ...
sshnaidm/openstack-sqe
tools/cloud/domain.py
Python
apache-2.0
3,609
0.003325
import os import yaml from network import Network from storage import Storage from cloudtools import conn, make_network_name from config import TEMPLATE_PATH with open(os.path.join(TEMPLATE_PATH, "network.yaml")) as f: netconf = yaml.load(f) with open(os.path.join(TEMPLATE_PATH, "vm.yaml")) as f: vmconf = yam...
if not net_params[net]["nat"]: self.pool[self.box][index]["internal_interface"] = "eth" + str(key) return xml def storage(self, index): return Storage.disks[self.names[index]] def define(self): return [vmconf[self.box]["xml"].format( name=self.names[num], ...
['params']["ram"]*1024*1024, cpu=self.conf['params']["cpu"], network=self.network(num), disk=self.storage(num), ) for num in xrange(self.conf['params']['count'])] def start(self): vm_xmls = self.define() for vm_xml in vm_xmls: vm = conn.define...
AlbertWeichselbraun/davify
src/davify/keyring.py
Python
gpl-3.0
1,784
0
#!/usr/bin/env python ''' Handles access to the WebDAV's server creditentials. ''' from collections import namedtuple import secretstorage APPLICATION_NAME = "davify" Fi
leStorage = namedtuple('FileStorage', 'username password protocol server port path') def get_secret_storage(): bus = secretstorage.dbus_init() return secretstorage.get_default_collection(bus) def store_password(username, pwd, protocol, server, port, path): ''' stores the giv...
N_NAME, 'username': username, 'server': server, 'protocol': protocol, 'port': str(port), 'path': path} description = f'davify WebDAV password for <{protocol}://{username}@' \ '{server}:{port}/{path}>' secret_storage.create_item(d...
sohail-aspose/Aspose_Words_Cloud
SDKs/Aspose.Words_Cloud_SDK_for_Python/asposewordscloud/models/DrawingObjectResponse.py
Python
mit
822
0.013382
#!/usr/bin/env python cl
ass DrawingObjectResponse(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.""" def __init__(self): """ Attributes: swaggerTypes (dict): The key is attribute name and the value is attribute type. attribu...
n. """ self.swaggerTypes = { 'DrawingObject': 'DrawingObject', 'Code': 'str', 'Status': 'str' } self.attributeMap = { 'DrawingObject': 'DrawingObject','Code': 'Code','Status': 'Status'} self.DrawingObject = None # DrawingO...
zmap/ztag
ztag/log.py
Python
apache-2.0
1,994
0
from datetime import datetime class Logger(object): FATAL = 0 ERROR = 1 WARN = 2 INFO = 3 DEBUG = 4 TRACE = 5 def __init__(self, f, log_level=3): level = int(log_level) if level < 0 or level > Logger.TRACE: raise Exception("Invalid Log Level %d" % level) ...
000") def fatal(self, msg): t = self.make_time() out = "%s [ERROR] %s: %s\n" % (t, "ztag", msg) self.f.write(out) self.f.flush() raise Exception("Fatal!")
def error(self, msg): if self.level < Logger.ERROR: return t = self.make_time() out = "%s [ERROR] %s: %s\n" % (t, "ztag", msg) self.f.write(out) self.f.flush() def warn(self, msg): if self.level < Logger.WARN: return t = self.make_time...
neurosnap/Flask-User
flask_user/settings.py
Python
bsd-2-clause
10,164
0.01525
""" This file handles default application config settings for Flask-User. :copyright: (c) 2013 by Ling Thio :author: Ling Thio (ling.thio@gmail.com) :license: Simplified BSD License, see LICENSE.txt for more details.""" def set_default_settings(user_manager, app_config): """ Set default app.config set...
= sd('USER_EMAIL_ACTION_URL', '/user/email/<id>/<action>/') um.forgot_password_url = sd('USER_FORGOT_PASSWORD_URL', '/user/forgot-password/') um.login_url = sd('USER_LOGIN_URL', '/user/sign-in/') um.logout_url = sd('USER_LOG
OUT_URL', '/user/sign-out/') um.manage_emails_url = sd('USER_MANAGE_EMAILS_URL', '/user/manage-emails/') um.register_url = sd('USER_REGISTER_URL', '/user/register/') um.resend_confirm_email_url = sd('USER_RESEND_CONFIRM_EMAIL_URL', '/user/resend...
iPatso/PyGameProjs
PyGames/CS254_platform/CS254_platform/src/menu.py
Python
apache-2.0
2,114
0.005203
import CONST from CONST import * clock = pygame.time.Clock() class Menu(): def __init__(self): self.bg_image = pygame.image.load(os.path.join("data","title1.png")).convert_alpha() self.subLogo = textFont("Initial Fantasy: Glitch", BLACK, 36, "Coalition.ttf") self.selection = 0; sel...
.get_
rect(x=screen.get_width()/2 + 65) BACK_pos = BACK.get_rect(x=screen.get_width()/2 + 65) screen.blit(TOGGLE_MUSIC, (TOGGLE_MUSIC_pos[0], 265)) screen.blit(TOGGLE_SOUNDFX, (TOGGKE_SOUNDFX_pos[0], 280)) screen.blit(BACK, (BACK_pos[0], 300))
v-iam/azure-sdk-for-python
azure-mgmt-web/azure/mgmt/web/models/app_service_certificate_resource.py
Python
mit
2,874
0.001392
# 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 cause incorrect behavior and will be lost if the code is # r
egenerated. # -------------------------------------------------------------------------- from .resource import Resource class AppServiceCertificateResource(Resource): """Key Vault container ARM resource for a certificate that is purchased through Azure. Variables are only populated by the server, and wi...
joshsomma/rice_python_1
memory.py
Python
apache-2.0
1,375
0.015273
# implementation of card game - Memory import simplegui import random #globals frame_size = [800,100] l1 = range(1,9) + range(1,9) random.shuffle(l1) #exposed = [False for l in range(len(l1))] exposed = [True, False, True, False, True, False, True, False, True, False, True, False, True, False, True, False] # helper...
if not exposed[i]: canvas.draw_polygon([sq_tr,sq_tl,sq_br,sq_bl], 2, 'Orange', 'Green') sq_tr[0] += 50 sq_tl[0] += 50 sq_
br[0] += 50 sq_bl[0] += 50 # create frame and add a button and labels frame = simplegui.create_frame("Memory", frame_size[0], frame_size[1]) frame.add_button("Reset", new_game) label = frame.add_label("Turns = 0") # register event handlers frame.set_mouseclick_handler(mouseclick) frame.set_draw_handler(draw) ...
Alex-Chizhov/python_training
home_work_6/test/test_del_group.py
Python
apache-2.0
201
0.034826
de
f test_delite_group(app): app.session.login( username="admin", password="secret") app.group.delete_first_group() app.session.logout() if __name__ == '__main__': pytest.main('tes
t_del_group.py')
xiao0720/leetcode
binary_search.py
Python
mit
415
0.019277
def bs(data, target, low, high): if low > high: return False else: mid = (low + high)//2 if target == data[mid]: return True elif target < data[mid]: return bs(data, target, low, mid - 1) else: return bs(data, target, mid + 1, high) if...
1))
zapcoop/vertex
vertex_api/vertex/settings/dev.py
Python
agpl-3.0
714
0.001401
from .base import * # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ip5ezdgcr92+p@(o4g$kc5lzw&$-rjqf7d9-h)16(!z&(lzils' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True DEBUG_TOOLBAR_PATCH_SETTINGS = False INTERNAL_IPS = ('127.0.0.1', '::1',) ALLOWED_H...
ddleware',] + MIDDLEWARE DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'vertex',
'USER': 'vertex', 'PASSWORD': '1a2e233f53edaf690', 'HOST': '127.0.0.1', }, }
bytebit-ch/uguubot
plugins/choose.py
Python
gpl-3.0
632
0.017405
import re import random from util import hook # @hook.regex(r'^uguubot(.*)') @hook.command(
'decide') @hook.command def choose(inp): "choose <choice1>, [choice2], [choice3], [choice4], ... -- " \ "Randomly picks one of the given choices." try: inp = inp.group(1) except: inp = inp replacewords = {'should','could','?', ' i ',' you '} for word in replacewords
: inp = inp.replace(word,'') if ':' in inp: inp = inp.split(':')[1] c = inp.split(', ') if len(c) == 1: c = inp.split(' or ') if len(c) == 1: c = ['Yes','No'] return random.choice(c).strip()
XDatum/prodsys-pa-model
p2pamodel/providers/deftclient.py
Python
apache-2.0
4,707
0
# # Author: # - Dmitry Golubkov, <dmitry.v.golubkov@cern.ch>, 2016-2018 # # Updates by: # - Mikhail Titov, <mikhail.titov@cern.ch>, 2018 # import json try: import requests import urllib except ImportError: pass API_VERSION = 'v1' class DEFTClient(object): API_BASE_PATH = '/api/{0}'.format(API_VERS...
H) self.headers = { 'Content-Type': 'application/json', 'Authorization': 'ApiKey {0}:{1}'.format(auth_user, auth_key)} self.verify_ssl_cert =
verify_ssl_cert def _get_action_list(self): action_cls = 'actions' response = requests.get(url='{0}/{1}/'.format( self.api_url, action_cls), headers=self.headers, ...
BorgERP/borg-erp-6of3
verticals/medical61/web_doc_oemedical/__init__.py
Python
agpl-3.0
25
0.08
#k
gb import contr
ollers
ibara1454/pyss
pyss/util/analysis.py
Python
mit
443
0.002257
#!/usr/bin/env python # -*- coding: utf-8 -*- impo
rt numpy as np import numpy.linalg def norm_along_column(a, ord=2): norm = lambda x: np.linalg.norm(x, ord=ord) return np.apply_a
long_axis(norm, 0, a) def eig_residul(a, b, x, v, rel=True): av = a @ v bv = b @ v rs = norm_along_column(av - x * bv) if rel: return rs / (norm_along_column(av) + np.abs(x) * norm_along_column(bv)) else: return rs
0x0mar/memex-explorer
source/apps/crawl_space/settings.py
Python
bsd-2-clause
1,268
0.003155
"""Crawl settings.""" import os, sys """ Inserts path to project root into sys.path of of crawl_supervisor. Splits the directory path to this settings file, and c
uts off the path up to the root of the project d
irectory, allowing crawl_supervisor to import modules from other apps. """ sys.path.insert(1, '/'.join(os.path.dirname(__file__).split('/')[:-2])) """ Ensures that the settings module used by crawl_supervisor is the one used by the rest of the apps in the project. """ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "m...